Add files using upload-large-folder tool
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- backend/node_modules/effect/src/Arbitrary.tsAdded+1101
- backend/node_modules/effect/src/BigInt.tsAdded+1139
- backend/node_modules/effect/src/Boolean.tsAdded+560
- backend/node_modules/effect/src/Cache.tsAdded+281
- backend/node_modules/effect/src/Cause.tsAdded+2049
- backend/node_modules/effect/src/Channel.tsAdded
- backend/node_modules/effect/src/ChildExecutorDecision.tsAdded+158
- backend/node_modules/effect/src/Chunk.tsAdded+2350
- backend/node_modules/effect/src/Clock.tsAdded+111
- backend/node_modules/effect/src/Config.tsAdded+743
- backend/node_modules/effect/src/ConfigError.tsAdded+286
- backend/node_modules/effect/src/ConfigProviderPathPatch.tsAdded+132
- backend/node_modules/effect/src/Context.tsAdded+867
- backend/node_modules/effect/src/Cron.tsAdded+848
- backend/node_modules/effect/src/DefaultServices.tsAdded+34
- backend/node_modules/effect/src/Deferred.tsAdded+471
- backend/node_modules/effect/src/Differ.tsAdded+512
- backend/node_modules/effect/src/Duration.tsAdded+1140
- backend/node_modules/effect/src/Effectable.tsAdded+107
- backend/node_modules/effect/src/Encoding.tsAdded+195
- backend/node_modules/effect/src/Equal.tsAdded+101
- backend/node_modules/effect/src/ExecutionPlan.tsAdded+308
- backend/node_modules/effect/src/ExecutionStrategy.tsAdded+138
- backend/node_modules/effect/src/FiberHandle.tsAdded+582
- backend/node_modules/effect/src/FiberId.tsAdded+219
- backend/node_modules/effect/src/FiberMap.tsAdded+779
- backend/node_modules/effect/src/FiberRef.tsAdded+511
- backend/node_modules/effect/src/Graph.tsAdded
- backend/node_modules/effect/src/Hash.tsAdded+203
- backend/node_modules/effect/src/HashRing.tsAdded+387
- backend/node_modules/effect/src/HashSet.tsAdded+2346
- backend/node_modules/effect/src/KeyedPool.tsAdded+201
- backend/node_modules/effect/src/Layer.tsAdded+1723
- backend/node_modules/effect/src/List.tsAdded+1469
- backend/node_modules/effect/src/LogLevel.tsAdded+387
- backend/node_modules/effect/src/Logger.tsAdded+863
- backend/node_modules/effect/src/Mailbox.tsAdded+298
- backend/node_modules/effect/src/ManagedRuntime.tsAdded+180
- backend/node_modules/effect/src/MergeDecision.tsAdded+103
- backend/node_modules/effect/src/MergeState.tsAdded+180
- backend/node_modules/effect/src/MergeStrategy.tsAdded+124
- backend/node_modules/effect/src/Metric.tsAdded+1165
- backend/node_modules/effect/src/MetricKeyType.tsAdded+262
- backend/node_modules/effect/src/MetricPair.tsAdded+71
- backend/node_modules/effect/src/MetricPolling.tsAdded+182
- backend/node_modules/effect/src/MetricState.tsAdded+273
- backend/node_modules/effect/src/Micro.tsAdded
- backend/node_modules/effect/src/ModuleVersion.tsAdded+18
- backend/node_modules/effect/src/MutableHashMap.tsAdded+518
- backend/node_modules/effect/src/NonEmptyIterable.tsAdded+32
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101/** * @since 3.10.0 */
import * as Arr from "./Array.js"import * as FastCheck from "./FastCheck.js"import { globalValue } from "./GlobalValue.js"import * as errors_ from "./internal/schema/errors.js"import * as schemaId_ from "./internal/schema/schemaId.js"import * as util_ from "./internal/schema/util.js"import * as Option from "./Option.js"import * as Predicate from "./Predicate.js"import type * as Schema from "./Schema.js"import * as SchemaAST from "./SchemaAST.js"import type * as Types from "./Types.js"
/** * @category model * @since 3.10.0 */export interface LazyArbitrary<A> { (fc: typeof FastCheck): FastCheck.Arbitrary<A>}
/** * @category annotations * @since 3.10.0 */export interface ArbitraryGenerationContext { readonly maxDepth: number readonly depthIdentifier?: string readonly constraints?: StringConstraints | NumberConstraints | BigIntConstraints | DateConstraints | ArrayConstraints}
/** * @category annotations * @since 3.10.0 */export type ArbitraryAnnotation<A, TypeParameters extends ReadonlyArray<any> = readonly []> = ( ...arbitraries: [ ...{ readonly [K in keyof TypeParameters]: LazyArbitrary<TypeParameters[K]> }, ctx: ArbitraryGenerationContext ]) => LazyArbitrary<A>
/** * Returns a LazyArbitrary for the `A` type of the provided schema. * * @category arbitrary * @since 3.10.0 */export const makeLazy = <A, I, R>(schema: Schema.Schema<A, I, R>): LazyArbitrary<A> => { const description = getDescription(schema.ast, []) return go(description, { maxDepth: 2 })}
/** * Returns a fast-check Arbitrary for the `A` type of the provided schema. * * @category arbitrary * @since 3.10.0 */export const make = <A, I, R>(schema: Schema.Schema<A, I, R>): FastCheck.Arbitrary<A> => makeLazy(schema)(FastCheck)
interface StringConstraints { readonly _tag: "StringConstraints" readonly constraints: FastCheck.StringSharedConstraints readonly pattern?: string}
/** @internal */export const makeStringConstraints = (options: { readonly minLength?: number | undefined readonly maxLength?: number | undefined readonly pattern?: string | undefined}): StringConstraints => { const out: Types.Mutable<StringConstraints> = { _tag: "StringConstraints", constraints: {} } if (Predicate.isNumber(options.minLength)) { out.constraints.minLength = options.minLength } if (Predicate.isNumber(options.maxLength)) { out.constraints.maxLength = options.maxLength } if (Predicate.isString(options.pattern)) { out.pattern = options.pattern } return out}
interface NumberConstraints { readonly _tag: "NumberConstraints" readonly constraints: FastCheck.FloatConstraints readonly isInteger: boolean}
/** @internal */export const makeNumberConstraints = (options: { readonly isInteger?: boolean | undefined readonly min?: unknown readonly minExcluded?: boolean | undefined readonly max?: unknown readonly maxExcluded?: boolean | undefined readonly noNaN?: boolean | undefined readonly noDefaultInfinity?: boolean | undefined}): NumberConstraints => { const out: Types.Mutable<NumberConstraints> = { _tag: "NumberConstraints", constraints: {}, isInteger: options.isInteger ?? false } if (Predicate.isNumber(options.min)) { out.constraints.min = Math.fround(options.min) } if (Predicate.isBoolean(options.minExcluded)) { out.constraints.minExcluded = options.minExcluded } if (Predicate.isNumber(options.max)) { out.constraints.max = Math.fround(options.max) } if (Predicate.isBoolean(options.maxExcluded)) { out.constraints.maxExcluded = options.maxExcluded } if (Predicate.isBoolean(options.noNaN)) { out.constraints.noNaN = options.noNaN } if (Predicate.isBoolean(options.noDefaultInfinity)) { out.constraints.noDefaultInfinity = options.noDefaultInfinity } return out}
interface BigIntConstraints { readonly _tag: "BigIntConstraints" readonly constraints: FastCheck.BigIntConstraints}
/** @internal */export const makeBigIntConstraints = (options: { readonly min?: bigint | undefined readonly max?: bigint | undefined}): BigIntConstraints => { const out: Types.Mutable<BigIntConstraints> = { _tag: "BigIntConstraints", constraints: {} } if (Predicate.isBigInt(options.min)) { out.constraints.min = options.min } if (Predicate.isBigInt(options.max)) { out.constraints.max = options.max } return out}
interface ArrayConstraints { readonly _tag: "ArrayConstraints" readonly constraints: FastCheck.ArrayConstraints}
/** @internal */export const makeArrayConstraints = (options: { readonly minLength?: unknown readonly maxLength?: unknown}): ArrayConstraints => { const out: Types.Mutable<ArrayConstraints> = { _tag: "ArrayConstraints", constraints: {} } if (Predicate.isNumber(options.minLength)) { out.constraints.minLength = options.minLength } if (Predicate.isNumber(options.maxLength)) { out.constraints.maxLength = options.maxLength } return out}
interface DateConstraints { readonly _tag: "DateConstraints" readonly constraints: FastCheck.DateConstraints}
/** @internal */export const makeDateConstraints = (options: { readonly min?: Date | undefined readonly max?: Date | undefined readonly noInvalidDate?: boolean | undefined}): DateConstraints => { const out: Types.Mutable<DateConstraints> = { _tag: "DateConstraints", constraints: {} } if (Predicate.isDate(options.min)) { out.constraints.min = options.min } if (Predicate.isDate(options.max)) { out.constraints.max = options.max } if (Predicate.isBoolean(options.noInvalidDate)) { out.constraints.noInvalidDate = options.noInvalidDate } return out}
type Refinements = ReadonlyArray<SchemaAST.Refinement>
interface Base { readonly path: ReadonlyArray<PropertyKey> readonly refinements: Refinements readonly annotations: ReadonlyArray<ArbitraryAnnotation<any, any>>}
interface StringKeyword extends Base { readonly _tag: "StringKeyword" readonly constraints: ReadonlyArray<StringConstraints>}
interface NumberKeyword extends Base { readonly _tag: "NumberKeyword" readonly constraints: ReadonlyArray<NumberConstraints>}
interface BigIntKeyword extends Base { readonly _tag: "BigIntKeyword" readonly constraints: ReadonlyArray<BigIntConstraints>}
interface DateFromSelf extends Base { readonly _tag: "DateFromSelf" readonly constraints: ReadonlyArray<DateConstraints>}
interface Declaration extends Base { readonly _tag: "Declaration" readonly typeParameters: ReadonlyArray<Description> readonly ast: SchemaAST.AST}
interface TupleType extends Base { readonly _tag: "TupleType" readonly constraints: ReadonlyArray<ArrayConstraints> readonly elements: ReadonlyArray<{ readonly isOptional: boolean readonly description: Description }> readonly rest: ReadonlyArray<Description>}
interface TypeLiteral extends Base { readonly _tag: "TypeLiteral" readonly propertySignatures: ReadonlyArray<{ readonly isOptional: boolean readonly name: PropertyKey readonly value: Description }> readonly indexSignatures: ReadonlyArray<{ readonly parameter: Description readonly value: Description }>}
interface Union extends Base { readonly _tag: "Union" readonly members: ReadonlyArray<Description>}
interface Suspend extends Base { readonly _tag: "Suspend" readonly id: string readonly ast: SchemaAST.AST readonly description: () => Description}
interface Ref extends Base { readonly _tag: "Ref" readonly id: string readonly ast: SchemaAST.AST}
interface NeverKeyword extends Base { readonly _tag: "NeverKeyword" readonly ast: SchemaAST.AST}
interface Keyword extends Base { readonly _tag: "Keyword" readonly value: | "UndefinedKeyword" | "VoidKeyword" | "UnknownKeyword" | "AnyKeyword" | "BooleanKeyword" | "SymbolKeyword" | "ObjectKeyword"}
interface Literal extends Base { readonly _tag: "Literal" readonly literal: SchemaAST.LiteralValue}
interface UniqueSymbol extends Base { readonly _tag: "UniqueSymbol" readonly symbol: symbol}
interface Enums extends Base { readonly _tag: "Enums" readonly enums: ReadonlyArray<readonly [string, string | number]> readonly ast: SchemaAST.AST}
interface TemplateLiteral extends Base { readonly _tag: "TemplateLiteral" readonly head: string readonly spans: ReadonlyArray<{ readonly description: Description readonly literal: string }>}
type Description = | Declaration | NeverKeyword | Keyword | Literal | UniqueSymbol | Enums | TemplateLiteral | StringKeyword | NumberKeyword | BigIntKeyword | DateFromSelf | TupleType | TypeLiteral | Union | Suspend | Ref
const getArbitraryAnnotation = SchemaAST.getAnnotation<ArbitraryAnnotation<any, any>>(SchemaAST.ArbitraryAnnotationId)
const getASTConstraints = (ast: SchemaAST.AST) => { const TypeAnnotationId = ast.annotations[SchemaAST.SchemaIdAnnotationId] if (Predicate.isPropertyKey(TypeAnnotationId)) { const out = ast.annotations[TypeAnnotationId] if (Predicate.isReadonlyRecord(out)) { return out } }}
const idMemoMap = globalValue( Symbol.for("effect/Arbitrary/IdMemoMap"), () => new Map<SchemaAST.AST, string>())
let counter = 0
function wrapGetDescription( f: (ast: SchemaAST.AST, description: Description) => Description, g: (ast: SchemaAST.AST, path: ReadonlyArray<PropertyKey>) => Description): (ast: SchemaAST.AST, path: ReadonlyArray<PropertyKey>) => Description { return (ast, path) => f(ast, g(ast, path))}
function parseMeta(ast: SchemaAST.AST): [SchemaAST.SchemaIdAnnotation | undefined, Record<string | symbol, unknown>] { const jsonSchema = SchemaAST.getJSONSchemaAnnotation(ast).pipe( Option.filter(Predicate.isReadonlyRecord), Option.getOrUndefined ) const schemaId = Option.getOrElse(SchemaAST.getSchemaIdAnnotation(ast), () => undefined) const schemaParams = Option.fromNullable(schemaId).pipe( Option.map((id) => ast.annotations[id]), Option.filter(Predicate.isReadonlyRecord), Option.getOrUndefined ) return [schemaId, { ...schemaParams, ...jsonSchema }]}
/** @internal */export const getDescription = wrapGetDescription( (ast, description) => { const annotation = getArbitraryAnnotation(ast) if (Option.isSome(annotation)) { return { ...description, annotations: [...description.annotations, annotation.value] } } return description }, (ast, path) => { const [schemaId, meta] = parseMeta(ast) switch (ast._tag) { case "Refinement": { const from = getDescription(ast.from, path) switch (from._tag) { case "StringKeyword": return { ...from, constraints: [...from.constraints, makeStringConstraints(meta)], refinements: [...from.refinements, ast] } case "NumberKeyword": { const c = schemaId === schemaId_.NonNaNSchemaId ? makeNumberConstraints({ noNaN: true }) : schemaId === schemaId_.FiniteSchemaId || schemaId === schemaId_.JsonNumberSchemaId ? makeNumberConstraints({ noDefaultInfinity: true, noNaN: true }) : makeNumberConstraints({ isInteger: "type" in meta && meta.type === "integer", noNaN: undefined, noDefaultInfinity: undefined, min: meta.exclusiveMinimum ?? meta.minimum, minExcluded: "exclusiveMinimum" in meta ? true : undefined, max: meta.exclusiveMaximum ?? meta.maximum, maxExcluded: "exclusiveMaximum" in meta ? true : undefined }) return { ...from, constraints: [...from.constraints, c], refinements: [...from.refinements, ast] } } case "BigIntKeyword": { const c = getASTConstraints(ast) return { ...from, constraints: c !== undefined ? [...from.constraints, makeBigIntConstraints(c)] : from.constraints, refinements: [...from.refinements, ast] } } case "TupleType": return { ...from, constraints: [ ...from.constraints, makeArrayConstraints({ minLength: meta.minItems, maxLength: meta.maxItems }) ], refinements: [...from.refinements, ast] } case "DateFromSelf": return { ...from, constraints: [...from.constraints, makeDateConstraints(meta)], refinements: [...from.refinements, ast] } default: return { ...from, refinements: [...from.refinements, ast] } } } case "Declaration": { if (schemaId === schemaId_.DateFromSelfSchemaId) { return { _tag: "DateFromSelf", constraints: [makeDateConstraints(meta)], path, refinements: [], annotations: [] } } return { _tag: "Declaration", typeParameters: ast.typeParameters.map((ast) => getDescription(ast, path)), path, refinements: [], annotations: [], ast } } case "Literal": { return { _tag: "Literal", literal: ast.literal, path, refinements: [], annotations: [] } } case "UniqueSymbol": { return { _tag: "UniqueSymbol", symbol: ast.symbol, path, refinements: [], annotations: [] } } case "Enums": { return { _tag: "Enums", enums: ast.enums, path, refinements: [], annotations: [], ast } } case "TemplateLiteral": { return { _tag: "TemplateLiteral", head: ast.head, spans: ast.spans.map((span) => ({ description: getDescription(span.type, path), literal: span.literal })), path, refinements: [], annotations: [] } } case "StringKeyword": return { _tag: "StringKeyword", constraints: [], path, refinements: [], annotations: [] } case "NumberKeyword": return { _tag: "NumberKeyword", constraints: [], path, refinements: [], annotations: [] } case "BigIntKeyword": return { _tag: "BigIntKeyword", constraints: [], path, refinements: [], annotations: [] } case "TupleType": return { _tag: "TupleType", constraints: [], elements: ast.elements.map((element, i) => ({ isOptional: element.isOptional, description: getDescription(element.type, [...path, i]) })), rest: ast.rest.map((element, i) => getDescription(element.type, [...path, i])), path, refinements: [], annotations: [] } case "TypeLiteral": return { _tag: "TypeLiteral", propertySignatures: ast.propertySignatures.map((ps) => ({ isOptional: ps.isOptional, name: ps.name, value: getDescription(ps.type, [...path, ps.name]) })), indexSignatures: ast.indexSignatures.map((is) => ({ parameter: getDescription(is.parameter, path), value: getDescription(is.type, path) })), path, refinements: [], annotations: [] } case "Union": return { _tag: "Union", members: ast.types.map((member, i) => getDescription(member, [...path, i])), path, refinements: [], annotations: [] } case "Suspend": { const memoId = idMemoMap.get(ast) if (memoId !== undefined) { return { _tag: "Ref", id: memoId, ast, path, refinements: [], annotations: [] } } counter++ const id = `__id-${counter}__` idMemoMap.set(ast, id) return { _tag: "Suspend", id, ast, description: () => getDescription(ast.f(), path), path, refinements: [], annotations: [] } } case "Transformation": return getDescription(ast.to, path) case "NeverKeyword": return { _tag: "NeverKeyword", path, refinements: [], annotations: [], ast } default: { return { _tag: "Keyword", value: ast._tag, path, refinements: [], annotations: [] } } } })
function getMax(n1: Date | undefined, n2: Date | undefined): Date | undefinedfunction getMax(n1: bigint | undefined, n2: bigint | undefined): bigint | undefinedfunction getMax(n1: number | undefined, n2: number | undefined): number | undefinedfunction getMax( n1: bigint | number | Date | undefined, n2: bigint | number | Date | undefined): bigint | number | Date | undefined { return n1 === undefined ? n2 : n2 === undefined ? n1 : n1 <= n2 ? n2 : n1}
function getMin(n1: Date | undefined, n2: Date | undefined): Date | undefinedfunction getMin(n1: bigint | undefined, n2: bigint | undefined): bigint | undefinedfunction getMin(n1: number | undefined, n2: number | undefined): number | undefinedfunction getMin( n1: bigint | number | Date | undefined, n2: bigint | number | Date | undefined): bigint | number | Date | undefined { return n1 === undefined ? n2 : n2 === undefined ? n1 : n1 <= n2 ? n1 : n2}
const getOr = (a: boolean | undefined, b: boolean | undefined): boolean | undefined => { return a === undefined ? b : b === undefined ? a : a || b}
function mergePattern(pattern1: string | undefined, pattern2: string | undefined): string | undefined { if (pattern1 === undefined) { return pattern2 } if (pattern2 === undefined) { return pattern1 } return `(?:${pattern1})|(?:${pattern2})`}
function mergeStringConstraints(c1: StringConstraints, c2: StringConstraints): StringConstraints { return makeStringConstraints({ minLength: getMax(c1.constraints.minLength, c2.constraints.minLength), maxLength: getMin(c1.constraints.maxLength, c2.constraints.maxLength), pattern: mergePattern(c1.pattern, c2.pattern) })}
function buildStringConstraints(description: StringKeyword): StringConstraints | undefined { return description.constraints.length === 0 ? undefined : description.constraints.reduce(mergeStringConstraints)}
function mergeNumberConstraints(c1: NumberConstraints, c2: NumberConstraints): NumberConstraints { return makeNumberConstraints({ isInteger: c1.isInteger || c2.isInteger, min: getMax(c1.constraints.min, c2.constraints.min), minExcluded: getOr(c1.constraints.minExcluded, c2.constraints.minExcluded), max: getMin(c1.constraints.max, c2.constraints.max), maxExcluded: getOr(c1.constraints.maxExcluded, c2.constraints.maxExcluded), noNaN: getOr(c1.constraints.noNaN, c2.constraints.noNaN), noDefaultInfinity: getOr(c1.constraints.noDefaultInfinity, c2.constraints.noDefaultInfinity) })}
function buildNumberConstraints(description: NumberKeyword): NumberConstraints | undefined { return description.constraints.length === 0 ? undefined : description.constraints.reduce(mergeNumberConstraints)}
function mergeBigIntConstraints(c1: BigIntConstraints, c2: BigIntConstraints): BigIntConstraints { return makeBigIntConstraints({ min: getMax(c1.constraints.min, c2.constraints.min), max: getMin(c1.constraints.max, c2.constraints.max) })}
function buildBigIntConstraints(description: BigIntKeyword): BigIntConstraints | undefined { return description.constraints.length === 0 ? undefined : description.constraints.reduce(mergeBigIntConstraints)}
function mergeDateConstraints(c1: DateConstraints, c2: DateConstraints): DateConstraints { return makeDateConstraints({ min: getMax(c1.constraints.min, c2.constraints.min), max: getMin(c1.constraints.max, c2.constraints.max), noInvalidDate: getOr(c1.constraints.noInvalidDate, c2.constraints.noInvalidDate) })}
function buildDateConstraints(description: DateFromSelf): DateConstraints | undefined { return description.constraints.length === 0 ? undefined : description.constraints.reduce(mergeDateConstraints)}
const constArrayConstraints = makeArrayConstraints({})
function mergeArrayConstraints(c1: ArrayConstraints, c2: ArrayConstraints): ArrayConstraints { return makeArrayConstraints({ minLength: getMax(c1.constraints.minLength, c2.constraints.minLength), maxLength: getMin(c1.constraints.maxLength, c2.constraints.maxLength) })}
function buildArrayConstraints(description: TupleType): ArrayConstraints | undefined { return description.constraints.length === 0 ? undefined : description.constraints.reduce(mergeArrayConstraints)}
const arbitraryMemoMap = globalValue( Symbol.for("effect/Arbitrary/arbitraryMemoMap"), () => new WeakMap<SchemaAST.AST, LazyArbitrary<any>>())
function applyFilters(filters: ReadonlyArray<Predicate.Predicate<any>>, arb: LazyArbitrary<any>): LazyArbitrary<any> { return (fc) => filters.reduce((arb, filter) => arb.filter(filter), arb(fc))}
function absurd(message: string): LazyArbitrary<any> { return () => { throw new Error(message) }}
function getContextConstraints(description: Description): ArbitraryGenerationContext["constraints"] { switch (description._tag) { case "StringKeyword": return buildStringConstraints(description) case "NumberKeyword": return buildNumberConstraints(description) case "BigIntKeyword": return buildBigIntConstraints(description) case "DateFromSelf": return buildDateConstraints(description) case "TupleType": return buildArrayConstraints(description) }}
function wrapGo( f: (description: Description, ctx: ArbitraryGenerationContext, lazyArb: LazyArbitrary<any>) => LazyArbitrary<any>, g: (description: Description, ctx: ArbitraryGenerationContext) => LazyArbitrary<any>): (description: Description, ctx: ArbitraryGenerationContext) => LazyArbitrary<any> { return (description, ctx) => f(description, ctx, g(description, ctx))}
const go = wrapGo( (description, ctx, lazyArb) => { const annotation: ArbitraryAnnotation<any, any> | undefined = description.annotations[description.annotations.length - 1]
// error handling if (annotation === undefined) { switch (description._tag) { case "Declaration": case "NeverKeyword": throw new Error(errors_.getArbitraryMissingAnnotationErrorMessage(description.path, description.ast)) case "Enums": if (description.enums.length === 0) { throw new Error(errors_.getArbitraryEmptyEnumErrorMessage(description.path)) } } }
const filters = description.refinements.map((ast) => (a: any) => Option.isNone(ast.filter(a, SchemaAST.defaultParseOption, ast)) ) if (annotation === undefined) { return applyFilters(filters, lazyArb) }
const constraints = getContextConstraints(description) if (constraints !== undefined) { ctx = { ...ctx, constraints } }
if (description._tag === "Declaration") { return applyFilters(filters, annotation(...description.typeParameters.map((p) => go(p, ctx)), ctx)) } if (description.refinements.length > 0) { // TODO(4.0): remove the `lazyArb` parameter return applyFilters(filters, annotation(lazyArb, ctx)) } return annotation(ctx) }, (description, ctx) => { switch (description._tag) { case "DateFromSelf": { const constraints = buildDateConstraints(description) return (fc) => fc.date(constraints?.constraints) } case "Declaration": case "NeverKeyword": return absurd(`BUG: cannot generate an arbitrary for ${description._tag}`) case "Literal": return (fc) => fc.constant(description.literal) case "UniqueSymbol": return (fc) => fc.constant(description.symbol) case "Keyword": { switch (description.value) { case "UndefinedKeyword": return (fc) => fc.constant(undefined) case "VoidKeyword": case "UnknownKeyword": case "AnyKeyword": return (fc) => fc.anything() case "BooleanKeyword": return (fc) => fc.boolean() case "SymbolKeyword": return (fc) => fc.string().map((s) => Symbol.for(s)) case "ObjectKeyword": return (fc) => fc.oneof(fc.object(), fc.array(fc.anything())) } } case "Enums": return (fc) => fc.oneof(...description.enums.map(([_, value]) => fc.constant(value))) case "TemplateLiteral": { return (fc) => { const string = fc.string({ maxLength: 5 }) const number = fc.float({ noDefaultInfinity: true, noNaN: true })
const getTemplateLiteralArb = (description: TemplateLiteral) => { const components: Array<FastCheck.Arbitrary<string | number>> = description.head !== "" ? [fc.constant(description.head)] : []
const getTemplateLiteralSpanTypeArb = ( description: Description ): FastCheck.Arbitrary<string | number> => { switch (description._tag) { case "StringKeyword": return string case "NumberKeyword": return number case "Literal": return fc.constant(String(description.literal)) case "Union": return fc.oneof(...description.members.map(getTemplateLiteralSpanTypeArb)) case "TemplateLiteral": return getTemplateLiteralArb(description) default: return fc.constant("") } }
description.spans.forEach((span) => { components.push(getTemplateLiteralSpanTypeArb(span.description)) if (span.literal !== "") { components.push(fc.constant(span.literal)) } })
return fc.tuple(...components).map((spans) => spans.join("")) }
return getTemplateLiteralArb(description) } } case "StringKeyword": { const constraints = buildStringConstraints(description) const pattern = constraints?.pattern return pattern !== undefined ? (fc) => fc.stringMatching(new RegExp(pattern)) : (fc) => fc.string(constraints?.constraints) } case "NumberKeyword": { const constraints = buildNumberConstraints(description) return constraints?.isInteger ? (fc) => fc.integer(constraints.constraints) : (fc) => fc.float(constraints?.constraints) } case "BigIntKeyword": { const constraints = buildBigIntConstraints(description) return (fc) => fc.bigInt(constraints?.constraints ?? {}) } case "TupleType": { const elements: Array<LazyArbitrary<any>> = [] let hasOptionals = false for (const element of description.elements) { elements.push(go(element.description, ctx)) if (element.isOptional) { hasOptionals = true } } const rest = description.rest.map((d) => go(d, ctx)) return (fc) => { // --------------------------------------------- // handle elements // --------------------------------------------- let output = fc.tuple(...elements.map((arb) => arb(fc))) if (hasOptionals) { const indexes = fc.tuple( ...description.elements.map((element) => element.isOptional ? fc.boolean() : fc.constant(true)) ) output = output.chain((tuple) => indexes.map((booleans) => { for (const [i, b] of booleans.reverse().entries()) { if (!b) { tuple.splice(booleans.length - i, 1) } } return tuple }) ) }
// --------------------------------------------- // handle rest element // --------------------------------------------- if (Arr.isNonEmptyReadonlyArray(rest)) { const constraints = buildArrayConstraints(description) ?? constArrayConstraints const [head, ...tail] = rest const item = head(fc) output = output.chain((as) => { const len = as.length // We must adjust the constraints for the rest element // because the elements might have generated some values const restArrayConstraints = subtractElementsLength(constraints.constraints, len) if (restArrayConstraints.maxLength === 0) { return fc.constant(as) } /*
`getSuspendedArray` is used to generate less values in the context of a recursive schema. Without it, the following schema would generate an big amount of values possibly leading to a stack overflow:
```ts type A = ReadonlyArray<A | null>
const schema = S.Array( S.NullOr(S.suspend((): S.Schema<A> => schema)) ) ```
*/ const arr = ctx.depthIdentifier !== undefined ? getSuspendedArray(fc, ctx.depthIdentifier, ctx.maxDepth, item, restArrayConstraints) : fc.array(item, restArrayConstraints) if (len === 0) { return arr } return arr.map((rest) => [...as, ...rest]) }) // --------------------------------------------- // handle post rest elements // --------------------------------------------- for (let j = 0; j < tail.length; j++) { output = output.chain((as) => tail[j](fc).map((a) => [...as, a])) } }
return output } } case "TypeLiteral": { const propertySignatures: Array<LazyArbitrary<any>> = [] const requiredKeys: Array<PropertyKey> = [] for (const ps of description.propertySignatures) { if (!ps.isOptional) { requiredKeys.push(ps.name) } propertySignatures.push(go(ps.value, ctx)) } const indexSignatures = description.indexSignatures.map((is) => [go(is.parameter, ctx), go(is.value, ctx)] as const ) return (fc) => { const pps: any = {} for (let i = 0; i < propertySignatures.length; i++) { const ps = description.propertySignatures[i] pps[ps.name] = propertySignatures[i](fc) } let output = fc.record<any, any>(pps, { requiredKeys }) // --------------------------------------------- // handle index signatures // --------------------------------------------- for (let i = 0; i < indexSignatures.length; i++) { const key = indexSignatures[i][0](fc) const value = indexSignatures[i][1](fc) output = output.chain((o) => { const item = fc.tuple(key, value) /*
`getSuspendedArray` is used to generate less key/value pairs in the context of a recursive schema. Without it, the following schema would generate an big amount of values possibly leading to a stack overflow:
```ts type A = { [_: string]: A }
const schema = S.Record({ key: S.String, value: S.suspend((): S.Schema<A> => schema) }) ```
*/ const arr = ctx.depthIdentifier !== undefined ? getSuspendedArray(fc, ctx.depthIdentifier, ctx.maxDepth, item, { maxLength: 2 }) : fc.array(item) return arr.map((tuples) => ({ ...Object.fromEntries(tuples), ...o })) }) }
return output } } case "Union": { const members = description.members.map((member) => go(member, ctx)) return (fc) => fc.oneof(...members.map((arb) => arb(fc))) } case "Suspend": { const memo = arbitraryMemoMap.get(description.ast) if (memo) { return memo } if (ctx.depthIdentifier === undefined) { ctx = { ...ctx, depthIdentifier: description.id } } const get = util_.memoizeThunk(() => { return go(description.description(), ctx) }) const out: LazyArbitrary<any> = (fc) => fc.constant(null).chain(() => get()(fc)) arbitraryMemoMap.set(description.ast, out) return out } case "Ref": { const memo = arbitraryMemoMap.get(description.ast) if (memo) { return memo } throw new Error(`BUG: Ref ${JSON.stringify(description.id)} not found`) } } })
function subtractElementsLength( constraints: FastCheck.ArrayConstraints, len: number): FastCheck.ArrayConstraints { if (len === 0 || (constraints.minLength === undefined && constraints.maxLength === undefined)) { return constraints } const out = { ...constraints } if (out.minLength !== undefined) { out.minLength = Math.max(out.minLength - len, 0) } if (out.maxLength !== undefined) { out.maxLength = Math.max(out.maxLength - len, 0) } return out}
const getSuspendedArray = ( fc: typeof FastCheck, depthIdentifier: string, maxDepth: number, item: FastCheck.Arbitrary<any>, constraints: FastCheck.ArrayConstraints) => { // In the context of a recursive schema, we don't want a `maxLength` greater than 2. // The only exception is when `minLength` is also set, in which case we set // `maxLength` to the minimum value, which is `minLength`. const maxLengthLimit = Math.max(2, constraints.minLength ?? 0) if (constraints.maxLength !== undefined && constraints.maxLength > maxLengthLimit) { constraints = { ...constraints, maxLength: maxLengthLimit } } return fc.oneof( { maxDepth, depthIdentifier }, fc.constant([]), fc.array(item, constraints) )}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139/** * This module provides utility functions and type class instances for working with the `bigint` type in TypeScript. * It includes functions for basic arithmetic operations, as well as type class instances for * `Equivalence` and `Order`. * * @module BigInt * @since 2.0.0 * @see {@link module:BigDecimal} for more similar operations on `BigDecimal` types * @see {@link module:Number} for more similar operations on `number` types */
import * as equivalence from "./Equivalence.js"import { dual } from "./Function.js"import * as Option from "./Option.js"import * as order from "./Order.js"import type { Ordering } from "./Ordering.js"import * as predicate from "./Predicate.js"
const bigint0 = BigInt(0)const bigint1 = BigInt(1)const bigint2 = BigInt(2)
/** * Tests if a value is a `bigint`. * * @example * ```ts * import * as assert from "node:assert" * import { isBigInt } from "effect/BigInt" * * assert.deepStrictEqual(isBigInt(1n), true) * assert.deepStrictEqual(isBigInt(1), false) * ``` * * @category guards * @since 2.0.0 */export const isBigInt: (u: unknown) => u is bigint = predicate.isBigInt
/** * Provides an addition operation on `bigint`s. * * @example * ```ts * import * as assert from "node:assert" * import { sum } from "effect/BigInt" * * assert.deepStrictEqual(sum(2n, 3n), 5n) * ``` * * @category math * @since 2.0.0 */export const sum: { /** * Provides an addition operation on `bigint`s. * * @example * ```ts * import * as assert from "node:assert" * import { sum } from "effect/BigInt" * * assert.deepStrictEqual(sum(2n, 3n), 5n) * ``` * * @category math * @since 2.0.0 */ (that: bigint): (self: bigint) => bigint /** * Provides an addition operation on `bigint`s. * * @example * ```ts * import * as assert from "node:assert" * import { sum } from "effect/BigInt" * * assert.deepStrictEqual(sum(2n, 3n), 5n) * ``` * * @category math * @since 2.0.0 */ (self: bigint, that: bigint): bigint} = dual(2, (self: bigint, that: bigint): bigint => self + that)
/** * Provides a multiplication operation on `bigint`s. * * @example * ```ts * import * as assert from "node:assert" * import { multiply } from "effect/BigInt" * * assert.deepStrictEqual(multiply(2n, 3n), 6n) * ``` * * @category math * @since 2.0.0 */export const multiply: { /** * Provides a multiplication operation on `bigint`s. * * @example * ```ts * import * as assert from "node:assert" * import { multiply } from "effect/BigInt" * * assert.deepStrictEqual(multiply(2n, 3n), 6n) * ``` * * @category math * @since 2.0.0 */ (that: bigint): (self: bigint) => bigint /** * Provides a multiplication operation on `bigint`s. * * @example * ```ts * import * as assert from "node:assert" * import { multiply } from "effect/BigInt" * * assert.deepStrictEqual(multiply(2n, 3n), 6n) * ``` * * @category math * @since 2.0.0 */ (self: bigint, that: bigint): bigint} = dual(2, (self: bigint, that: bigint): bigint => self * that)
/** * Provides a subtraction operation on `bigint`s. * * @example * ```ts * import * as assert from "node:assert" * import { subtract } from "effect/BigInt" * * assert.deepStrictEqual(subtract(2n, 3n), -1n) * ``` * * @category math * @since 2.0.0 */export const subtract: { /** * Provides a subtraction operation on `bigint`s. * * @example * ```ts * import * as assert from "node:assert" * import { subtract } from "effect/BigInt" * * assert.deepStrictEqual(subtract(2n, 3n), -1n) * ``` * * @category math * @since 2.0.0 */ (that: bigint): (self: bigint) => bigint /** * Provides a subtraction operation on `bigint`s. * * @example * ```ts * import * as assert from "node:assert" * import { subtract } from "effect/BigInt" * * assert.deepStrictEqual(subtract(2n, 3n), -1n) * ``` * * @category math * @since 2.0.0 */ (self: bigint, that: bigint): bigint} = dual(2, (self: bigint, that: bigint): bigint => self - that)
/** * Provides a division operation on `bigint`s. * * If the dividend is not a multiple of the divisor the result will be a `bigint` value * which represents the integer division rounded down to the nearest integer. * * Returns `None` if the divisor is `0n`. * * @example * ```ts * import * as assert from "node:assert" * import { BigInt, Option } from "effect" * * assert.deepStrictEqual(BigInt.divide(6n, 3n), Option.some(2n)) * assert.deepStrictEqual(BigInt.divide(6n, 0n), Option.none()) * ``` * * @category math * @since 2.0.0 */export const divide: { /** * Provides a division operation on `bigint`s. * * If the dividend is not a multiple of the divisor the result will be a `bigint` value * which represents the integer division rounded down to the nearest integer. * * Returns `None` if the divisor is `0n`. * * @example * ```ts * import * as assert from "node:assert" * import { BigInt, Option } from "effect" * * assert.deepStrictEqual(BigInt.divide(6n, 3n), Option.some(2n)) * assert.deepStrictEqual(BigInt.divide(6n, 0n), Option.none()) * ``` * * @category math * @since 2.0.0 */ (that: bigint): (self: bigint) => Option.Option<bigint> /** * Provides a division operation on `bigint`s. * * If the dividend is not a multiple of the divisor the result will be a `bigint` value * which represents the integer division rounded down to the nearest integer. * * Returns `None` if the divisor is `0n`. * * @example * ```ts * import * as assert from "node:assert" * import { BigInt, Option } from "effect" * * assert.deepStrictEqual(BigInt.divide(6n, 3n), Option.some(2n)) * assert.deepStrictEqual(BigInt.divide(6n, 0n), Option.none()) * ``` * * @category math * @since 2.0.0 */ (self: bigint, that: bigint): Option.Option<bigint>} = dual( 2, (self: bigint, that: bigint): Option.Option<bigint> => that === bigint0 ? Option.none() : Option.some(self / that))
/** * Provides a division operation on `bigint`s. * * If the dividend is not a multiple of the divisor the result will be a `bigint` value * which represents the integer division rounded down to the nearest integer. * * Throws a `RangeError` if the divisor is `0n`. * * @example * ```ts * import * as assert from "node:assert" * import { unsafeDivide } from "effect/BigInt" * * assert.deepStrictEqual(unsafeDivide(6n, 3n), 2n) * assert.deepStrictEqual(unsafeDivide(6n, 4n), 1n) * ``` * * @category math * @since 2.0.0 */export const unsafeDivide: { /** * Provides a division operation on `bigint`s. * * If the dividend is not a multiple of the divisor the result will be a `bigint` value * which represents the integer division rounded down to the nearest integer. * * Throws a `RangeError` if the divisor is `0n`. * * @example * ```ts * import * as assert from "node:assert" * import { unsafeDivide } from "effect/BigInt" * * assert.deepStrictEqual(unsafeDivide(6n, 3n), 2n) * assert.deepStrictEqual(unsafeDivide(6n, 4n), 1n) * ``` * * @category math * @since 2.0.0 */ (that: bigint): (self: bigint) => bigint /** * Provides a division operation on `bigint`s. * * If the dividend is not a multiple of the divisor the result will be a `bigint` value * which represents the integer division rounded down to the nearest integer. * * Throws a `RangeError` if the divisor is `0n`. * * @example * ```ts * import * as assert from "node:assert" * import { unsafeDivide } from "effect/BigInt" * * assert.deepStrictEqual(unsafeDivide(6n, 3n), 2n) * assert.deepStrictEqual(unsafeDivide(6n, 4n), 1n) * ``` * * @category math * @since 2.0.0 */ (self: bigint, that: bigint): bigint} = dual(2, (self: bigint, that: bigint): bigint => self / that)
/** * Returns the result of adding `1n` to a given number. * * @example * ```ts * import * as assert from "node:assert" * import { increment } from "effect/BigInt" * * assert.deepStrictEqual(increment(2n), 3n) * ``` * * @category math * @since 2.0.0 */export const increment = (n: bigint): bigint => n + bigint1
/** * Decrements a number by `1n`. * * @example * ```ts * import * as assert from "node:assert" * import { decrement } from "effect/BigInt" * * assert.deepStrictEqual(decrement(3n), 2n) * ``` * * @category math * @since 2.0.0 */export const decrement = (n: bigint): bigint => n - bigint1
/** * @category instances * @since 2.0.0 */export const Equivalence: equivalence.Equivalence<bigint> = equivalence.bigint
/** * @category instances * @since 2.0.0 */export const Order: order.Order<bigint> = order.bigint
/** * Returns `true` if the first argument is less than the second, otherwise `false`. * * @example * ```ts * import * as assert from "node:assert" * import { lessThan } from "effect/BigInt" * * assert.deepStrictEqual(lessThan(2n, 3n), true) * assert.deepStrictEqual(lessThan(3n, 3n), false) * assert.deepStrictEqual(lessThan(4n, 3n), false) * ``` * * @category predicates * @since 2.0.0 */export const lessThan: { /** * Returns `true` if the first argument is less than the second, otherwise `false`. * * @example * ```ts * import * as assert from "node:assert" * import { lessThan } from "effect/BigInt" * * assert.deepStrictEqual(lessThan(2n, 3n), true) * assert.deepStrictEqual(lessThan(3n, 3n), false) * assert.deepStrictEqual(lessThan(4n, 3n), false) * ``` * * @category predicates * @since 2.0.0 */ (that: bigint): (self: bigint) => boolean /** * Returns `true` if the first argument is less than the second, otherwise `false`. * * @example * ```ts * import * as assert from "node:assert" * import { lessThan } from "effect/BigInt" * * assert.deepStrictEqual(lessThan(2n, 3n), true) * assert.deepStrictEqual(lessThan(3n, 3n), false) * assert.deepStrictEqual(lessThan(4n, 3n), false) * ``` * * @category predicates * @since 2.0.0 */ (self: bigint, that: bigint): boolean} = order.lessThan(Order)
/** * Returns a function that checks if a given `bigint` is less than or equal to the provided one. * * @example * ```ts * import * as assert from "node:assert" * import { lessThanOrEqualTo } from "effect/BigInt" * * assert.deepStrictEqual(lessThanOrEqualTo(2n, 3n), true) * assert.deepStrictEqual(lessThanOrEqualTo(3n, 3n), true) * assert.deepStrictEqual(lessThanOrEqualTo(4n, 3n), false) * ``` * * @category predicates * @since 2.0.0 */export const lessThanOrEqualTo: { /** * Returns a function that checks if a given `bigint` is less than or equal to the provided one. * * @example * ```ts * import * as assert from "node:assert" * import { lessThanOrEqualTo } from "effect/BigInt" * * assert.deepStrictEqual(lessThanOrEqualTo(2n, 3n), true) * assert.deepStrictEqual(lessThanOrEqualTo(3n, 3n), true) * assert.deepStrictEqual(lessThanOrEqualTo(4n, 3n), false) * ``` * * @category predicates * @since 2.0.0 */ (that: bigint): (self: bigint) => boolean /** * Returns a function that checks if a given `bigint` is less than or equal to the provided one. * * @example * ```ts * import * as assert from "node:assert" * import { lessThanOrEqualTo } from "effect/BigInt" * * assert.deepStrictEqual(lessThanOrEqualTo(2n, 3n), true) * assert.deepStrictEqual(lessThanOrEqualTo(3n, 3n), true) * assert.deepStrictEqual(lessThanOrEqualTo(4n, 3n), false) * ``` * * @category predicates * @since 2.0.0 */ (self: bigint, that: bigint): boolean} = order.lessThanOrEqualTo(Order)
/** * Returns `true` if the first argument is greater than the second, otherwise `false`. * * @example * ```ts * import * as assert from "node:assert" * import { greaterThan } from "effect/BigInt" * * assert.deepStrictEqual(greaterThan(2n, 3n), false) * assert.deepStrictEqual(greaterThan(3n, 3n), false) * assert.deepStrictEqual(greaterThan(4n, 3n), true) * ``` * * @category predicates * @since 2.0.0 */export const greaterThan: { /** * Returns `true` if the first argument is greater than the second, otherwise `false`. * * @example * ```ts * import * as assert from "node:assert" * import { greaterThan } from "effect/BigInt" * * assert.deepStrictEqual(greaterThan(2n, 3n), false) * assert.deepStrictEqual(greaterThan(3n, 3n), false) * assert.deepStrictEqual(greaterThan(4n, 3n), true) * ``` * * @category predicates * @since 2.0.0 */ (that: bigint): (self: bigint) => boolean /** * Returns `true` if the first argument is greater than the second, otherwise `false`. * * @example * ```ts * import * as assert from "node:assert" * import { greaterThan } from "effect/BigInt" * * assert.deepStrictEqual(greaterThan(2n, 3n), false) * assert.deepStrictEqual(greaterThan(3n, 3n), false) * assert.deepStrictEqual(greaterThan(4n, 3n), true) * ``` * * @category predicates * @since 2.0.0 */ (self: bigint, that: bigint): boolean} = order.greaterThan(Order)
/** * Returns a function that checks if a given `bigint` is greater than or equal to the provided one. * * @example * ```ts * import * as assert from "node:assert" * import { greaterThanOrEqualTo } from "effect/BigInt" * * assert.deepStrictEqual(greaterThanOrEqualTo(2n, 3n), false) * assert.deepStrictEqual(greaterThanOrEqualTo(3n, 3n), true) * assert.deepStrictEqual(greaterThanOrEqualTo(4n, 3n), true) * ``` * * @category predicates * @since 2.0.0 */export const greaterThanOrEqualTo: { /** * Returns a function that checks if a given `bigint` is greater than or equal to the provided one. * * @example * ```ts * import * as assert from "node:assert" * import { greaterThanOrEqualTo } from "effect/BigInt" * * assert.deepStrictEqual(greaterThanOrEqualTo(2n, 3n), false) * assert.deepStrictEqual(greaterThanOrEqualTo(3n, 3n), true) * assert.deepStrictEqual(greaterThanOrEqualTo(4n, 3n), true) * ``` * * @category predicates * @since 2.0.0 */ (that: bigint): (self: bigint) => boolean /** * Returns a function that checks if a given `bigint` is greater than or equal to the provided one. * * @example * ```ts * import * as assert from "node:assert" * import { greaterThanOrEqualTo } from "effect/BigInt" * * assert.deepStrictEqual(greaterThanOrEqualTo(2n, 3n), false) * assert.deepStrictEqual(greaterThanOrEqualTo(3n, 3n), true) * assert.deepStrictEqual(greaterThanOrEqualTo(4n, 3n), true) * ``` * * @category predicates * @since 2.0.0 */ (self: bigint, that: bigint): boolean} = order.greaterThanOrEqualTo(Order)
/** * Checks if a `bigint` is between a `minimum` and `maximum` value (inclusive). * * @example * ```ts * import * as assert from "node:assert" * import { BigInt } from "effect" * * const between = BigInt.between({ minimum: 0n, maximum: 5n }) * * assert.deepStrictEqual(between(3n), true) * assert.deepStrictEqual(between(-1n), false) * assert.deepStrictEqual(between(6n), false) * ``` * * @category predicates * @since 2.0.0 */export const between: { /** * Checks if a `bigint` is between a `minimum` and `maximum` value (inclusive). * * @example * ```ts * import * as assert from "node:assert" * import { BigInt } from "effect" * * const between = BigInt.between({ minimum: 0n, maximum: 5n }) * * assert.deepStrictEqual(between(3n), true) * assert.deepStrictEqual(between(-1n), false) * assert.deepStrictEqual(between(6n), false) * ``` * * @category predicates * @since 2.0.0 */ ( options: { minimum: bigint maximum: bigint } ): (self: bigint) => boolean /** * Checks if a `bigint` is between a `minimum` and `maximum` value (inclusive). * * @example * ```ts * import * as assert from "node:assert" * import { BigInt } from "effect" * * const between = BigInt.between({ minimum: 0n, maximum: 5n }) * * assert.deepStrictEqual(between(3n), true) * assert.deepStrictEqual(between(-1n), false) * assert.deepStrictEqual(between(6n), false) * ``` * * @category predicates * @since 2.0.0 */ ( self: bigint, options: { minimum: bigint maximum: bigint } ): boolean} = order.between(Order)
/** * Restricts the given `bigint` to be within the range specified by the `minimum` and `maximum` values. * * - If the `bigint` is less than the `minimum` value, the function returns the `minimum` value. * - If the `bigint` is greater than the `maximum` value, the function returns the `maximum` value. * - Otherwise, it returns the original `bigint`. * * @example * ```ts * import * as assert from "node:assert" * import { BigInt } from "effect" * * const clamp = BigInt.clamp({ minimum: 1n, maximum: 5n }) * * assert.equal(clamp(3n), 3n) * assert.equal(clamp(0n), 1n) * assert.equal(clamp(6n), 5n) * ``` * * @since 2.0.0 */export const clamp: { /** * Restricts the given `bigint` to be within the range specified by the `minimum` and `maximum` values. * * - If the `bigint` is less than the `minimum` value, the function returns the `minimum` value. * - If the `bigint` is greater than the `maximum` value, the function returns the `maximum` value. * - Otherwise, it returns the original `bigint`. * * @example * ```ts * import * as assert from "node:assert" * import { BigInt } from "effect" * * const clamp = BigInt.clamp({ minimum: 1n, maximum: 5n }) * * assert.equal(clamp(3n), 3n) * assert.equal(clamp(0n), 1n) * assert.equal(clamp(6n), 5n) * ``` * * @since 2.0.0 */ ( options: { minimum: bigint maximum: bigint } ): (self: bigint) => bigint /** * Restricts the given `bigint` to be within the range specified by the `minimum` and `maximum` values. * * - If the `bigint` is less than the `minimum` value, the function returns the `minimum` value. * - If the `bigint` is greater than the `maximum` value, the function returns the `maximum` value. * - Otherwise, it returns the original `bigint`. * * @example * ```ts * import * as assert from "node:assert" * import { BigInt } from "effect" * * const clamp = BigInt.clamp({ minimum: 1n, maximum: 5n }) * * assert.equal(clamp(3n), 3n) * assert.equal(clamp(0n), 1n) * assert.equal(clamp(6n), 5n) * ``` * * @since 2.0.0 */ ( self: bigint, options: { minimum: bigint maximum: bigint } ): bigint} = order.clamp(Order)
/** * Returns the minimum between two `bigint`s. * * @example * ```ts * import * as assert from "node:assert" * import { min } from "effect/BigInt" * * assert.deepStrictEqual(min(2n, 3n), 2n) * ``` * * @since 2.0.0 */export const min: { /** * Returns the minimum between two `bigint`s. * * @example * ```ts * import * as assert from "node:assert" * import { min } from "effect/BigInt" * * assert.deepStrictEqual(min(2n, 3n), 2n) * ``` * * @since 2.0.0 */ (that: bigint): (self: bigint) => bigint /** * Returns the minimum between two `bigint`s. * * @example * ```ts * import * as assert from "node:assert" * import { min } from "effect/BigInt" * * assert.deepStrictEqual(min(2n, 3n), 2n) * ``` * * @since 2.0.0 */ (self: bigint, that: bigint): bigint} = order.min(Order)
/** * Returns the maximum between two `bigint`s. * * @example * ```ts * import * as assert from "node:assert" * import { max } from "effect/BigInt" * * assert.deepStrictEqual(max(2n, 3n), 3n) * ``` * * @since 2.0.0 */export const max: { /** * Returns the maximum between two `bigint`s. * * @example * ```ts * import * as assert from "node:assert" * import { max } from "effect/BigInt" * * assert.deepStrictEqual(max(2n, 3n), 3n) * ``` * * @since 2.0.0 */ (that: bigint): (self: bigint) => bigint /** * Returns the maximum between two `bigint`s. * * @example * ```ts * import * as assert from "node:assert" * import { max } from "effect/BigInt" * * assert.deepStrictEqual(max(2n, 3n), 3n) * ``` * * @since 2.0.0 */ (self: bigint, that: bigint): bigint} = order.max(Order)
/** * Determines the sign of a given `bigint`. * * @example * ```ts * import * as assert from "node:assert" * import { sign } from "effect/BigInt" * * assert.deepStrictEqual(sign(-5n), -1) * assert.deepStrictEqual(sign(0n), 0) * assert.deepStrictEqual(sign(5n), 1) * ``` * * @category math * @since 2.0.0 */export const sign = (n: bigint): Ordering => Order(n, bigint0)
/** * Determines the absolute value of a given `bigint`. * * @example * ```ts * import * as assert from "node:assert" * import { abs } from "effect/BigInt" * * assert.deepStrictEqual(abs(-5n), 5n) * assert.deepStrictEqual(abs(0n), 0n) * assert.deepStrictEqual(abs(5n), 5n) * ``` * * @category math * @since 2.0.0 */export const abs = (n: bigint): bigint => (n < bigint0 ? -n : n)
/** * Determines the greatest common divisor of two `bigint`s. * * @example * ```ts * import * as assert from "node:assert" * import { gcd } from "effect/BigInt" * * assert.deepStrictEqual(gcd(2n, 3n), 1n) * assert.deepStrictEqual(gcd(2n, 4n), 2n) * assert.deepStrictEqual(gcd(16n, 24n), 8n) * ``` * * @category math * @since 2.0.0 */export const gcd: { /** * Determines the greatest common divisor of two `bigint`s. * * @example * ```ts * import * as assert from "node:assert" * import { gcd } from "effect/BigInt" * * assert.deepStrictEqual(gcd(2n, 3n), 1n) * assert.deepStrictEqual(gcd(2n, 4n), 2n) * assert.deepStrictEqual(gcd(16n, 24n), 8n) * ``` * * @category math * @since 2.0.0 */ (that: bigint): (self: bigint) => bigint /** * Determines the greatest common divisor of two `bigint`s. * * @example * ```ts * import * as assert from "node:assert" * import { gcd } from "effect/BigInt" * * assert.deepStrictEqual(gcd(2n, 3n), 1n) * assert.deepStrictEqual(gcd(2n, 4n), 2n) * assert.deepStrictEqual(gcd(16n, 24n), 8n) * ``` * * @category math * @since 2.0.0 */ (self: bigint, that: bigint): bigint} = dual(2, (self: bigint, that: bigint): bigint => { while (that !== bigint0) { const t = that that = self % that self = t } return self})
/** * Determines the least common multiple of two `bigint`s. * * @example * ```ts * import * as assert from "node:assert" * import { lcm } from "effect/BigInt" * * assert.deepStrictEqual(lcm(2n, 3n), 6n) * assert.deepStrictEqual(lcm(2n, 4n), 4n) * assert.deepStrictEqual(lcm(16n, 24n), 48n) * ``` * * @category math * @since 2.0.0 */export const lcm: { /** * Determines the least common multiple of two `bigint`s. * * @example * ```ts * import * as assert from "node:assert" * import { lcm } from "effect/BigInt" * * assert.deepStrictEqual(lcm(2n, 3n), 6n) * assert.deepStrictEqual(lcm(2n, 4n), 4n) * assert.deepStrictEqual(lcm(16n, 24n), 48n) * ``` * * @category math * @since 2.0.0 */ (that: bigint): (self: bigint) => bigint /** * Determines the least common multiple of two `bigint`s. * * @example * ```ts * import * as assert from "node:assert" * import { lcm } from "effect/BigInt" * * assert.deepStrictEqual(lcm(2n, 3n), 6n) * assert.deepStrictEqual(lcm(2n, 4n), 4n) * assert.deepStrictEqual(lcm(16n, 24n), 48n) * ``` * * @category math * @since 2.0.0 */ (self: bigint, that: bigint): bigint} = dual(2, (self: bigint, that: bigint): bigint => (self * that) / gcd(self, that))
/** * Determines the square root of a given `bigint` unsafely. Throws if the given `bigint` is negative. * * @example * ```ts * import * as assert from "node:assert" * import { unsafeSqrt } from "effect/BigInt" * * assert.deepStrictEqual(unsafeSqrt(4n), 2n) * assert.deepStrictEqual(unsafeSqrt(9n), 3n) * assert.deepStrictEqual(unsafeSqrt(16n), 4n) * ``` * * @category math * @since 2.0.0 */export const unsafeSqrt = (n: bigint): bigint => { if (n < bigint0) { throw new RangeError("Cannot take the square root of a negative number") } if (n < bigint2) { return n } let x = n / bigint2 while (x * x > n) { x = ((n / x) + x) / bigint2 } return x}
/** * Determines the square root of a given `bigint` safely. Returns `none` if the given `bigint` is negative. * * @example * ```ts * import * as assert from "node:assert" * import { BigInt, Option } from "effect" * * assert.deepStrictEqual(BigInt.sqrt(4n), Option.some(2n)) * assert.deepStrictEqual(BigInt.sqrt(9n), Option.some(3n)) * assert.deepStrictEqual(BigInt.sqrt(16n), Option.some(4n)) * assert.deepStrictEqual(BigInt.sqrt(-1n), Option.none()) * ``` * * @category math * @since 2.0.0 */export const sqrt = (n: bigint): Option.Option<bigint> => greaterThanOrEqualTo(n, bigint0) ? Option.some(unsafeSqrt(n)) : Option.none<bigint>()
/** * Takes an `Iterable` of `bigint`s and returns their sum as a single `bigint * * @example * ```ts * import * as assert from "node:assert" * import { sumAll } from "effect/BigInt" * * assert.deepStrictEqual(sumAll([2n, 3n, 4n]), 9n) * ``` * * @category math * @since 2.0.0 */export const sumAll = (collection: Iterable<bigint>): bigint => { let out = bigint0 for (const n of collection) { out += n } return out}
/** * Takes an `Iterable` of `bigint`s and returns their multiplication as a single `number`. * * @example * ```ts * import * as assert from "node:assert" * import { multiplyAll } from "effect/BigInt" * * assert.deepStrictEqual(multiplyAll([2n, 3n, 4n]), 24n) * ``` * * @category math * @since 2.0.0 */export const multiplyAll = (collection: Iterable<bigint>): bigint => { let out = bigint1 for (const n of collection) { if (n === bigint0) { return bigint0 } out *= n } return out}
/** * Takes a `bigint` and returns an `Option` of `number`. * * If the `bigint` is outside the safe integer range for JavaScript (`Number.MAX_SAFE_INTEGER` * and `Number.MIN_SAFE_INTEGER`), it returns `Option.none()`. Otherwise, it converts the `bigint` * to a number and returns `Option.some(number)`. * * @example * ```ts * import * as assert from "node:assert" * import { BigInt as BI, Option } from "effect" * * assert.deepStrictEqual(BI.toNumber(BigInt(42)), Option.some(42)) * assert.deepStrictEqual(BI.toNumber(BigInt(Number.MAX_SAFE_INTEGER) + BigInt(1)), Option.none()) * assert.deepStrictEqual(BI.toNumber(BigInt(Number.MIN_SAFE_INTEGER) - BigInt(1)), Option.none()) * ``` * * @category conversions * @since 2.0.0 */export const toNumber = (b: bigint): Option.Option<number> => { if (b > BigInt(Number.MAX_SAFE_INTEGER) || b < BigInt(Number.MIN_SAFE_INTEGER)) { return Option.none() } return Option.some(Number(b))}
/** * Takes a string and returns an `Option` of `bigint`. * * If the string is empty or contains characters that cannot be converted into a `bigint`, * it returns `Option.none()`, otherwise, it returns `Option.some(bigint)`. * * @example * ```ts * import * as assert from "node:assert" * import { BigInt as BI, Option } from "effect" * * assert.deepStrictEqual(BI.fromString("42"), Option.some(BigInt(42))) * assert.deepStrictEqual(BI.fromString(" "), Option.none()) * assert.deepStrictEqual(BI.fromString("a"), Option.none()) * ``` * * @category conversions * @since 2.4.12 */export const fromString = (s: string): Option.Option<bigint> => { try { return s.trim() === "" ? Option.none() : Option.some(BigInt(s)) } catch { return Option.none() }}
/** * Takes a number and returns an `Option` of `bigint`. * * If the number is outside the safe integer range for JavaScript (`Number.MAX_SAFE_INTEGER` * and `Number.MIN_SAFE_INTEGER`), it returns `Option.none()`. Otherwise, it attempts to * convert the number to a `bigint` and returns `Option.some(bigint)`. * * @example * ```ts * import * as assert from "node:assert" * import { BigInt as BI, Option } from "effect" * * assert.deepStrictEqual(BI.fromNumber(42), Option.some(BigInt(42))) * assert.deepStrictEqual(BI.fromNumber(Number.MAX_SAFE_INTEGER + 1), Option.none()) * assert.deepStrictEqual(BI.fromNumber(Number.MIN_SAFE_INTEGER - 1), Option.none()) * ``` * * @category conversions * @since 2.4.12 */export const fromNumber = (n: number): Option.Option<bigint> => { if (n > Number.MAX_SAFE_INTEGER || n < Number.MIN_SAFE_INTEGER) { return Option.none() }
try { return Option.some(BigInt(n)) } catch { return Option.none() }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560/** * This module provides utility functions and type class instances for working with the `boolean` type in TypeScript. * It includes functions for basic boolean operations, as well as type class instances for * `Equivalence` and `Order`. * * @since 2.0.0 */import * as equivalence from "./Equivalence.js"import type { LazyArg } from "./Function.js"import { dual } from "./Function.js"import * as order from "./Order.js"import * as predicate from "./Predicate.js"
/** * Tests if a value is a `boolean`. * * @example * ```ts * import * as assert from "node:assert" * import { isBoolean } from "effect/Boolean" * * assert.deepStrictEqual(isBoolean(true), true) * assert.deepStrictEqual(isBoolean("true"), false) * ``` * * @category guards * @since 2.0.0 */export const isBoolean: (input: unknown) => input is boolean = predicate.isBoolean
/** * This function returns the result of either of the given functions depending on the value of the boolean parameter. * It is useful when you have to run one of two functions depending on the boolean value. * * @example * ```ts * import * as assert from "node:assert" * import { Boolean } from "effect" * * assert.deepStrictEqual(Boolean.match(true, { onFalse: () => "It's false!", onTrue: () => "It's true!" }), "It's true!") * ``` * * @category pattern matching * @since 2.0.0 */export const match: { /** * This function returns the result of either of the given functions depending on the value of the boolean parameter. * It is useful when you have to run one of two functions depending on the boolean value. * * @example * ```ts * import * as assert from "node:assert" * import { Boolean } from "effect" * * assert.deepStrictEqual(Boolean.match(true, { onFalse: () => "It's false!", onTrue: () => "It's true!" }), "It's true!") * ``` * * @category pattern matching * @since 2.0.0 */ <A, B = A>( options: { readonly onFalse: LazyArg<A> readonly onTrue: LazyArg<B> } ): (value: boolean) => A | B /** * This function returns the result of either of the given functions depending on the value of the boolean parameter. * It is useful when you have to run one of two functions depending on the boolean value. * * @example * ```ts * import * as assert from "node:assert" * import { Boolean } from "effect" * * assert.deepStrictEqual(Boolean.match(true, { onFalse: () => "It's false!", onTrue: () => "It's true!" }), "It's true!") * ``` * * @category pattern matching * @since 2.0.0 */ <A, B>( value: boolean, options: { readonly onFalse: LazyArg<A> readonly onTrue: LazyArg<B> } ): A | B} = dual(2, <A, B>(value: boolean, options: { readonly onFalse: LazyArg<A> readonly onTrue: LazyArg<B>}): A | B => value ? options.onTrue() : options.onFalse())
/** * @category instances * @since 2.0.0 */export const Equivalence: equivalence.Equivalence<boolean> = equivalence.boolean
/** * @category instances * @since 2.0.0 */export const Order: order.Order<boolean> = order.boolean
/** * Negates the given boolean: `!self` * * @example * ```ts * import * as assert from "node:assert" * import { not } from "effect/Boolean" * * assert.deepStrictEqual(not(true), false) * assert.deepStrictEqual(not(false), true) * ``` * * @category combinators * @since 2.0.0 */export const not = (self: boolean): boolean => !self
/** * Combines two boolean using AND: `self && that`. * * @example * ```ts * import * as assert from "node:assert" * import { and } from "effect/Boolean" * * assert.deepStrictEqual(and(true, true), true) * assert.deepStrictEqual(and(true, false), false) * assert.deepStrictEqual(and(false, true), false) * assert.deepStrictEqual(and(false, false), false) * ``` * * @category combinators * @since 2.0.0 */export const and: { /** * Combines two boolean using AND: `self && that`. * * @example * ```ts * import * as assert from "node:assert" * import { and } from "effect/Boolean" * * assert.deepStrictEqual(and(true, true), true) * assert.deepStrictEqual(and(true, false), false) * assert.deepStrictEqual(and(false, true), false) * assert.deepStrictEqual(and(false, false), false) * ``` * * @category combinators * @since 2.0.0 */ (that: boolean): (self: boolean) => boolean /** * Combines two boolean using AND: `self && that`. * * @example * ```ts * import * as assert from "node:assert" * import { and } from "effect/Boolean" * * assert.deepStrictEqual(and(true, true), true) * assert.deepStrictEqual(and(true, false), false) * assert.deepStrictEqual(and(false, true), false) * assert.deepStrictEqual(and(false, false), false) * ``` * * @category combinators * @since 2.0.0 */ (self: boolean, that: boolean): boolean} = dual(2, (self: boolean, that: boolean): boolean => self && that)
/** * Combines two boolean using NAND: `!(self && that)`. * * @example * ```ts * import * as assert from "node:assert" * import { nand } from "effect/Boolean" * * assert.deepStrictEqual(nand(true, true), false) * assert.deepStrictEqual(nand(true, false), true) * assert.deepStrictEqual(nand(false, true), true) * assert.deepStrictEqual(nand(false, false), true) * ``` * * @category combinators * @since 2.0.0 */export const nand: { /** * Combines two boolean using NAND: `!(self && that)`. * * @example * ```ts * import * as assert from "node:assert" * import { nand } from "effect/Boolean" * * assert.deepStrictEqual(nand(true, true), false) * assert.deepStrictEqual(nand(true, false), true) * assert.deepStrictEqual(nand(false, true), true) * assert.deepStrictEqual(nand(false, false), true) * ``` * * @category combinators * @since 2.0.0 */ (that: boolean): (self: boolean) => boolean /** * Combines two boolean using NAND: `!(self && that)`. * * @example * ```ts * import * as assert from "node:assert" * import { nand } from "effect/Boolean" * * assert.deepStrictEqual(nand(true, true), false) * assert.deepStrictEqual(nand(true, false), true) * assert.deepStrictEqual(nand(false, true), true) * assert.deepStrictEqual(nand(false, false), true) * ``` * * @category combinators * @since 2.0.0 */ (self: boolean, that: boolean): boolean} = dual(2, (self: boolean, that: boolean): boolean => !(self && that))
/** * Combines two boolean using OR: `self || that`. * * @example * ```ts * import * as assert from "node:assert" * import { or } from "effect/Boolean" * * assert.deepStrictEqual(or(true, true), true) * assert.deepStrictEqual(or(true, false), true) * assert.deepStrictEqual(or(false, true), true) * assert.deepStrictEqual(or(false, false), false) * ``` * * @category combinators * @since 2.0.0 */export const or: { /** * Combines two boolean using OR: `self || that`. * * @example * ```ts * import * as assert from "node:assert" * import { or } from "effect/Boolean" * * assert.deepStrictEqual(or(true, true), true) * assert.deepStrictEqual(or(true, false), true) * assert.deepStrictEqual(or(false, true), true) * assert.deepStrictEqual(or(false, false), false) * ``` * * @category combinators * @since 2.0.0 */ (that: boolean): (self: boolean) => boolean /** * Combines two boolean using OR: `self || that`. * * @example * ```ts * import * as assert from "node:assert" * import { or } from "effect/Boolean" * * assert.deepStrictEqual(or(true, true), true) * assert.deepStrictEqual(or(true, false), true) * assert.deepStrictEqual(or(false, true), true) * assert.deepStrictEqual(or(false, false), false) * ``` * * @category combinators * @since 2.0.0 */ (self: boolean, that: boolean): boolean} = dual(2, (self: boolean, that: boolean): boolean => self || that)
/** * Combines two booleans using NOR: `!(self || that)`. * * @example * ```ts * import * as assert from "node:assert" * import { nor } from "effect/Boolean" * * assert.deepStrictEqual(nor(true, true), false) * assert.deepStrictEqual(nor(true, false), false) * assert.deepStrictEqual(nor(false, true), false) * assert.deepStrictEqual(nor(false, false), true) * ``` * * @category combinators * @since 2.0.0 */export const nor: { /** * Combines two booleans using NOR: `!(self || that)`. * * @example * ```ts * import * as assert from "node:assert" * import { nor } from "effect/Boolean" * * assert.deepStrictEqual(nor(true, true), false) * assert.deepStrictEqual(nor(true, false), false) * assert.deepStrictEqual(nor(false, true), false) * assert.deepStrictEqual(nor(false, false), true) * ``` * * @category combinators * @since 2.0.0 */ (that: boolean): (self: boolean) => boolean /** * Combines two booleans using NOR: `!(self || that)`. * * @example * ```ts * import * as assert from "node:assert" * import { nor } from "effect/Boolean" * * assert.deepStrictEqual(nor(true, true), false) * assert.deepStrictEqual(nor(true, false), false) * assert.deepStrictEqual(nor(false, true), false) * assert.deepStrictEqual(nor(false, false), true) * ``` * * @category combinators * @since 2.0.0 */ (self: boolean, that: boolean): boolean} = dual(2, (self: boolean, that: boolean): boolean => !(self || that))
/** * Combines two booleans using XOR: `(!self && that) || (self && !that)`. * * @example * ```ts * import * as assert from "node:assert" * import { xor } from "effect/Boolean" * * assert.deepStrictEqual(xor(true, true), false) * assert.deepStrictEqual(xor(true, false), true) * assert.deepStrictEqual(xor(false, true), true) * assert.deepStrictEqual(xor(false, false), false) * ``` * * @category combinators * @since 2.0.0 */export const xor: { /** * Combines two booleans using XOR: `(!self && that) || (self && !that)`. * * @example * ```ts * import * as assert from "node:assert" * import { xor } from "effect/Boolean" * * assert.deepStrictEqual(xor(true, true), false) * assert.deepStrictEqual(xor(true, false), true) * assert.deepStrictEqual(xor(false, true), true) * assert.deepStrictEqual(xor(false, false), false) * ``` * * @category combinators * @since 2.0.0 */ (that: boolean): (self: boolean) => boolean /** * Combines two booleans using XOR: `(!self && that) || (self && !that)`. * * @example * ```ts * import * as assert from "node:assert" * import { xor } from "effect/Boolean" * * assert.deepStrictEqual(xor(true, true), false) * assert.deepStrictEqual(xor(true, false), true) * assert.deepStrictEqual(xor(false, true), true) * assert.deepStrictEqual(xor(false, false), false) * ``` * * @category combinators * @since 2.0.0 */ (self: boolean, that: boolean): boolean} = dual(2, (self: boolean, that: boolean): boolean => (!self && that) || (self && !that))
/** * Combines two booleans using EQV (aka XNOR): `!xor(self, that)`. * * @example * ```ts * import * as assert from "node:assert" * import { eqv } from "effect/Boolean" * * assert.deepStrictEqual(eqv(true, true), true) * assert.deepStrictEqual(eqv(true, false), false) * assert.deepStrictEqual(eqv(false, true), false) * assert.deepStrictEqual(eqv(false, false), true) * ``` * * @category combinators * @since 2.0.0 */export const eqv: { /** * Combines two booleans using EQV (aka XNOR): `!xor(self, that)`. * * @example * ```ts * import * as assert from "node:assert" * import { eqv } from "effect/Boolean" * * assert.deepStrictEqual(eqv(true, true), true) * assert.deepStrictEqual(eqv(true, false), false) * assert.deepStrictEqual(eqv(false, true), false) * assert.deepStrictEqual(eqv(false, false), true) * ``` * * @category combinators * @since 2.0.0 */ (that: boolean): (self: boolean) => boolean /** * Combines two booleans using EQV (aka XNOR): `!xor(self, that)`. * * @example * ```ts * import * as assert from "node:assert" * import { eqv } from "effect/Boolean" * * assert.deepStrictEqual(eqv(true, true), true) * assert.deepStrictEqual(eqv(true, false), false) * assert.deepStrictEqual(eqv(false, true), false) * assert.deepStrictEqual(eqv(false, false), true) * ``` * * @category combinators * @since 2.0.0 */ (self: boolean, that: boolean): boolean} = dual(2, (self: boolean, that: boolean): boolean => !xor(self, that))
/** * Combines two booleans using an implication: `(!self || that)`. * * @example * ```ts * import * as assert from "node:assert" * import { implies } from "effect/Boolean" * * assert.deepStrictEqual(implies(true, true), true) * assert.deepStrictEqual(implies(true, false), false) * assert.deepStrictEqual(implies(false, true), true) * assert.deepStrictEqual(implies(false, false), true) * ``` * * @category combinators * @since 2.0.0 */export const implies: { /** * Combines two booleans using an implication: `(!self || that)`. * * @example * ```ts * import * as assert from "node:assert" * import { implies } from "effect/Boolean" * * assert.deepStrictEqual(implies(true, true), true) * assert.deepStrictEqual(implies(true, false), false) * assert.deepStrictEqual(implies(false, true), true) * assert.deepStrictEqual(implies(false, false), true) * ``` * * @category combinators * @since 2.0.0 */ (that: boolean): (self: boolean) => boolean /** * Combines two booleans using an implication: `(!self || that)`. * * @example * ```ts * import * as assert from "node:assert" * import { implies } from "effect/Boolean" * * assert.deepStrictEqual(implies(true, true), true) * assert.deepStrictEqual(implies(true, false), false) * assert.deepStrictEqual(implies(false, true), true) * assert.deepStrictEqual(implies(false, false), true) * ``` * * @category combinators * @since 2.0.0 */ (self: boolean, that: boolean): boolean} = dual(2, (self, that) => self ? that : true)
/** * This utility function is used to check if all the elements in a collection of boolean values are `true`. * * @example * ```ts * import * as assert from "node:assert" * import { every } from "effect/Boolean" * * assert.deepStrictEqual(every([true, true, true]), true) * assert.deepStrictEqual(every([true, false, true]), false) * ``` * * @since 2.0.0 */export const every = (collection: Iterable<boolean>): boolean => { for (const b of collection) { if (!b) { return false } } return true}
/** * This utility function is used to check if at least one of the elements in a collection of boolean values is `true`. * * @example * ```ts * import * as assert from "node:assert" * import { some } from "effect/Boolean" * * assert.deepStrictEqual(some([true, false, true]), true) * assert.deepStrictEqual(some([false, false, false]), false) * ``` * * @since 2.0.0 */export const some = (collection: Iterable<boolean>): boolean => { for (const b of collection) { if (b) { return true } } return false}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281/** * @since 2.0.0 */import type * as Duration from "./Duration.js"import type * as Effect from "./Effect.js"import type { Either } from "./Either.js"import type * as Exit from "./Exit.js"import * as internal from "./internal/cache.js"import type * as Option from "./Option.js"import type * as Predicate from "./Predicate.js"import type * as Types from "./Types.js"
/** * @since 2.0.0 * @category symbols */export const CacheTypeId: unique symbol = internal.CacheTypeId
/** * @since 2.0.0 * @category symbols */export type CacheTypeId = typeof CacheTypeId
/** * @since 3.6.4 * @category symbols */export const ConsumerCacheTypeId: unique symbol = internal.ConsumerCacheTypeId
/** * @since 3.6.4 * @category symbols */export type ConsumerCacheTypeId = typeof ConsumerCacheTypeId
/** * A `Cache` is defined in terms of a lookup function that, given a key of * type `Key`, can either fail with an error of type `Error` or succeed with a * value of type `Value`. Getting a value from the cache will either return * the previous result of the lookup function if it is available or else * compute a new result with the lookup function, put it in the cache, and * return it. * * A cache also has a specified capacity and time to live. When the cache is * at capacity the least recently accessed values in the cache will be * removed to make room for new values. Getting a value with a life older than * the specified time to live will result in a new value being computed with * the lookup function and returned when available. * * The cache is safe for concurrent access. If multiple fibers attempt to get * the same key the lookup function will only be computed once and the result * will be returned to all fibers. * * @since 2.0.0 * @category models */export interface Cache<in out Key, in out Value, out Error = never> extends ConsumerCache<Key, Value, Error>, Cache.Variance<Key, Value, Error>{ /** * Retrieves the value associated with the specified key if it exists. * Otherwise computes the value with the lookup function, puts it in the * cache, and returns it. */ get(key: Key): Effect.Effect<Value, Error>
/** * Retrieves the value associated with the specified key if it exists as a left. * Otherwise computes the value with the lookup function, puts it in the * cache, and returns it as a right. */ getEither(key: Key): Effect.Effect<Either<Value, Value>, Error>
/** * Computes the value associated with the specified key, with the lookup * function, and puts it in the cache. The difference between this and * `get` method is that `refresh` triggers (re)computation of the value * without invalidating it in the cache, so any request to the associated * key can still be served while the value is being re-computed/retrieved * by the lookup function. Additionally, `refresh` always triggers the * lookup function, disregarding the last `Error`. */ refresh(key: Key): Effect.Effect<void, Error>
/** * Associates the specified value with the specified key in the cache. */ set(key: Key, value: Value): Effect.Effect<void>}
/** * A ConsumerCache models a portion of a cache which is safe to share without allowing to create new values or access existing ones. * * It can be used safely to give over control for request management without leaking writer side details. * * @since 2.0.0 * @category models */export interface ConsumerCache<in out Key, out Value, out Error = never> extends Cache.ConsumerVariance<Key, Value, Error>{ /** * Retrieves the value associated with the specified key if it exists. * Otherwise returns `Option.none`. */ getOption(key: Key): Effect.Effect<Option.Option<Value>, Error>
/** * Retrieves the value associated with the specified key if it exists and the * lookup function has completed. Otherwise returns `Option.none`. */ getOptionComplete(key: Key): Effect.Effect<Option.Option<Value>>
/** * Returns statistics for this cache. */ readonly cacheStats: Effect.Effect<CacheStats>
/** * Returns whether a value associated with the specified key exists in the * cache. */ contains(key: Key): Effect.Effect<boolean>
/** * Returns statistics for the specified entry. */ entryStats(key: Key): Effect.Effect<Option.Option<EntryStats>>
/** * Invalidates the value associated with the specified key. */ invalidate(key: Key): Effect.Effect<void>
/** * Invalidates the value associated with the specified key if the predicate holds. */ invalidateWhen(key: Key, predicate: Predicate.Predicate<Value>): Effect.Effect<void>
/** * Invalidates all values in the cache. */ readonly invalidateAll: Effect.Effect<void>
/** * Returns the approximate number of values in the cache. */ readonly size: Effect.Effect<number>
/** * Returns an approximation of the values in the cache. */ readonly keys: Effect.Effect<Array<Key>>
/** * Returns an approximation of the values in the cache. */ readonly values: Effect.Effect<Array<Value>>
/** * Returns an approximation of the values in the cache. */ readonly entries: Effect.Effect<Array<[Key, Value]>>}
/** * @since 2.0.0 */export declare namespace Cache { /** * @since 2.0.0 * @category models */ export interface Variance<in out Key, in out Value, out Error> { readonly [CacheTypeId]: { readonly _Key: Types.Invariant<Key> readonly _Error: Types.Covariant<Error> readonly _Value: Types.Invariant<Value> } } /** * @since 3.6.4 * @category models */ export interface ConsumerVariance<in out Key, out Value, out Error> { readonly [ConsumerCacheTypeId]: { readonly _Key: Types.Invariant<Key> readonly _Error: Types.Covariant<Error> readonly _Value: Types.Covariant<Value> } }}
/** * Constructs a new cache with the specified capacity, time to live, and * lookup function. * * @since 2.0.0 * @category constructors */export const make: <Key, Value, Error = never, Environment = never>( options: { readonly capacity: number readonly timeToLive: Duration.DurationInput readonly lookup: Lookup<Key, Value, Error, Environment> }) => Effect.Effect<Cache<Key, Value, Error>, never, Environment> = internal.make
/** * Constructs a new cache with the specified capacity, time to live, and * lookup function, where the time to live can depend on the `Exit` value * returned by the lookup function. * * @since 2.0.0 * @category constructors */export const makeWith: <Key, Value, Error = never, Environment = never>( options: { readonly capacity: number readonly lookup: Lookup<Key, Value, Error, Environment> readonly timeToLive: (exit: Exit.Exit<Value, Error>) => Duration.DurationInput }) => Effect.Effect<Cache<Key, Value, Error>, never, Environment> = internal.makeWith
/** * `CacheStats` represents a snapshot of statistics for the cache as of a * point in time. * * @since 2.0.0 * @category models */export interface CacheStats { readonly hits: number readonly misses: number readonly size: number}
/** * Constructs a new `CacheStats` from the specified values. * * @since 2.0.0 * @category constructors */export const makeCacheStats: ( options: { readonly hits: number readonly misses: number readonly size: number }) => CacheStats = internal.makeCacheStats
/** * Represents a snapshot of statistics for an entry in the cache. * * @since 2.0.0 * @category models */export interface EntryStats { readonly loadedMillis: number}
/** * Constructs a new `EntryStats` from the specified values. * * @since 2.0.0 * @category constructors */export const makeEntryStats: (loadedMillis: number) => EntryStats = internal.makeEntryStats
/** * A `Lookup` represents a lookup function that, given a key of type `Key`, can * return an effect that will either produce a value of type `Value` or fail * with an error of type `Error` using an environment of type `Environment`. * * @since 2.0.0 * @category models */export type Lookup<Key, Value, Error = never, Environment = never> = ( key: Key) => Effect.Effect<Value, Error, Environment>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049/** * The `Effect<A, E, R>` type is polymorphic in values of type `E` and we can * work with any error type that we want. However, there is a lot of information * that is not inside an arbitrary `E` value. So as a result, an `Effect` needs * somewhere to store things like unexpected errors or defects, stack and * execution traces, causes of fiber interruptions, and so forth. * * Effect-TS is very strict about preserving the full information related to a * failure. It captures all type of errors into the `Cause` data type. `Effect` * uses the `Cause<E>` data type to store the full story of failure. So its * error model is lossless. It doesn't throw information related to the failure * result. So we can figure out exactly what happened during the operation of * our effects. * * It is important to note that `Cause` is an underlying data type representing * errors occuring within an `Effect` workflow. Thus, we don't usually deal with * `Cause`s directly. Even though it is not a data type that we deal with very * often, the `Cause` of a failing `Effect` workflow can be accessed at any * time, which gives us total access to all parallel and sequential errors in * occurring within our codebase. * * @since 2.0.0 */import type * as Channel from "./Channel.js"import type * as Chunk from "./Chunk.js"import type * as Effect from "./Effect.js"import type * as Either from "./Either.js"import type * as Equal from "./Equal.js"import type * as FiberId from "./FiberId.js"import type * as HashSet from "./HashSet.js"import type { Inspectable } from "./Inspectable.js"import * as internal from "./internal/cause.js"import * as core from "./internal/core.js"import type * as Option from "./Option.js"import type { Pipeable } from "./Pipeable.js"import type { Predicate, Refinement } from "./Predicate.js"import type * as Sink from "./Sink.js"import type * as Stream from "./Stream.js"import type { Span } from "./Tracer.js"import type { Covariant, NoInfer } from "./Types.js"
/** * A unique symbol identifying the `Cause` type. * * **Details** * * This provides a symbol that helps identify instances of the `Cause` data * type. This can be used for advanced operations such as refining types or * building internal utilities that check whether an unknown value is a `Cause`. * * @see {@link isCause} Check if a value is a `Cause` * * @since 2.0.0 * @category Symbols */export const CauseTypeId: unique symbol = internal.CauseTypeId
/** * @since 2.0.0 * @category Symbols */export type CauseTypeId = typeof CauseTypeId
/** * A unique symbol identifying the `RuntimeException` type. * * **Details** * * This provides a symbol that identifies a `RuntimeException`. This is * typically used internally by the library to recognize checked exceptions that * occur during runtime. * * @see {@link RuntimeException} Create or work with a `RuntimeException` * * @since 2.0.0 * @category Symbols */export const RuntimeExceptionTypeId: unique symbol = core.RuntimeExceptionTypeId
/** * @since 2.0.0 * @category Symbols */export type RuntimeExceptionTypeId = typeof RuntimeExceptionTypeId
/** * A unique symbol identifying the `InterruptedException` type. * * **Details** * * This provides a symbol that identifies an `InterruptedException`. This is * typically used internally to recognize when a fiber has been interrupted, * helping the framework handle interruption logic correctly. * * @see {@link InterruptedException} Create or work with an `InterruptedException` * * @since 2.0.0 * @category Symbols */export const InterruptedExceptionTypeId: unique symbol = core.InterruptedExceptionTypeId
/** * @since 2.0.0 * @category Symbols */export type InterruptedExceptionTypeId = typeof InterruptedExceptionTypeId
/** * A unique symbol identifying the `IllegalArgumentException` type. * * **Details** * * This provides a symbol that identifies an `IllegalArgumentException`. This is * often used in scenarios where invalid arguments are supplied to methods that * expect specific input. * * @see {@link IllegalArgumentException} Create or work with an `IllegalArgumentException` * * @since 2.0.0 * @category Symbols */export const IllegalArgumentExceptionTypeId: unique symbol = core.IllegalArgumentExceptionTypeId
/** * @since 2.0.0 * @category Symbols */export type IllegalArgumentExceptionTypeId = typeof IllegalArgumentExceptionTypeId
/** * A unique symbol identifying the `NoSuchElementException` type. * * **Details** * * This provides a symbol that identifies a `NoSuchElementException`. It helps * differentiate cases where a required element is missing within a data * structure. * * @see {@link NoSuchElementException} Create or work with a `NoSuchElementException` * * @since 2.0.0 * @category Symbols */export const NoSuchElementExceptionTypeId: unique symbol = core.NoSuchElementExceptionTypeId
/** * @since 2.0.0 * @category Symbols */export type NoSuchElementExceptionTypeId = typeof NoSuchElementExceptionTypeId
/** * A unique symbol identifying the `InvalidPubSubCapacityException` type. * * **Details** * * This provides a symbol that identifies an `InvalidPubSubCapacityException`. * It indicates an error related to an invalid capacity passed to a `PubSub` * structure. * * @see {@link InvalidPubSubCapacityException} Create or work with an `InvalidPubSubCapacityException` * * @since 2.0.0 * @category Symbols */export const InvalidPubSubCapacityExceptionTypeId: unique symbol = core.InvalidPubSubCapacityExceptionTypeId
/** * @since 2.0.0 * @category Symbols */export type InvalidPubSubCapacityExceptionTypeId = typeof InvalidPubSubCapacityExceptionTypeId
/** * A unique symbol identifying the `ExceededCapacityException` type. * * **Details** * * This provides a symbol that identifies an `ExceededCapacityException`. It * denotes situations where a resource has exceeded its configured capacity * limit. * * @see {@link ExceededCapacityException} Create or work with an `ExceededCapacityException` * * @since 3.5.0 * @category Symbols */export const ExceededCapacityExceptionTypeId: unique symbol = core.ExceededCapacityExceptionTypeId
/** * @since 3.5.0 * @category Symbols */export type ExceededCapacityExceptionTypeId = typeof ExceededCapacityExceptionTypeId
/** * A unique symbol identifying the `TimeoutException` type. * * **Details** * * This provides a symbol that identifies a `TimeoutException`. It helps the * framework recognize errors related to operations that fail to complete within * a given timeframe. * * @see {@link TimeoutException} Create or work with a `TimeoutException` * * @since 2.0.0 * @category Symbols */export const TimeoutExceptionTypeId: unique symbol = core.TimeoutExceptionTypeId
/** * @since 2.0.0 * @category Symbols */export type TimeoutExceptionTypeId = typeof TimeoutExceptionTypeId
/** * A unique symbol identifying the `UnknownException` type. * * **Details** * * This provides a symbol that identifies an `UnknownException`. It is typically * used for generic or unexpected errors that do not fit other specific * exception categories. * * @see {@link UnknownException} Create or work with an `UnknownException` * * @since 2.0.0 * @category Symbols */export const UnknownExceptionTypeId: unique symbol = core.UnknownExceptionTypeId
/** * @since 2.0.0 * @category Symbols */export type UnknownExceptionTypeId = typeof UnknownExceptionTypeId
/** * Represents the full history of a failure within an `Effect`. * * **Details** * * This type is a data structure that captures all information about why and how * an effect has failed, including parallel errors, sequential errors, defects, * and interruptions. It enables a "lossless" error model: no error-related * information is discarded, which helps in debugging and understanding the root * cause of failures. * * @since 2.0.0 * @category Models */export type Cause<E> = | Empty | Fail<E> | Die | Interrupt | Sequential<E> | Parallel<E>
/** * @since 2.0.0 */export declare namespace Cause { /** * This interface is used internally to manage the type variance of `Cause`. * * @since 2.0.0 * @category Models */ export interface Variance<out E> { readonly [CauseTypeId]: { readonly _E: Covariant<E> } }}
/** * Describes methods for reducing a `Cause<E>` into a value of type `Z` with * access to contextual information. * * **Details** * * This interface is meant for advanced transformations of `Cause`. By * implementing each method, you can define how different parts of the `Cause` * structure (like `Fail`, `Die`, or `Interrupt`) should be transformed into a * final type `Z`. The `context` parameter carries additional data needed during * this reduction. * * @see {@link reduceWithContext} Apply a `CauseReducer` to transform a `Cause` * * @since 2.0.0 * @category Models */export interface CauseReducer<in C, in E, in out Z> { emptyCase(context: C): Z failCase(context: C, error: E): Z dieCase(context: C, defect: unknown): Z interruptCase(context: C, fiberId: FiberId.FiberId): Z sequentialCase(context: C, left: Z, right: Z): Z parallelCase(context: C, left: Z, right: Z): Z}
/** * Represents an error object that can be yielded in `Effect.gen`. * * @since 2.0.0 * @category Models */export interface YieldableError extends Pipeable, Inspectable, Error { readonly [Effect.EffectTypeId]: Effect.Effect.VarianceStruct<never, this, never> readonly [Stream.StreamTypeId]: Stream.Stream.VarianceStruct<never, this, never> readonly [Sink.SinkTypeId]: Sink.Sink.VarianceStruct<never, unknown, never, this, never> readonly [Channel.ChannelTypeId]: Channel.Channel.VarianceStruct<never, unknown, this, unknown, never, unknown, never> [Symbol.iterator](): Effect.EffectGenerator<Effect.Effect<never, this, never>>}
/** * Creates an error that occurs at runtime, extendable for other exception * types. * * @since 2.0.0 * @category Errors */export const YieldableError: new(message?: string | undefined) => YieldableError = core.YieldableError
/** * An error representing a runtime error. * * **Details** * * This interface is used for errors that occur at runtime but are still * considered recoverable or typed. * * @since 2.0.0 * @category Models */export interface RuntimeException extends YieldableError { readonly _tag: "RuntimeException" readonly [RuntimeExceptionTypeId]: RuntimeExceptionTypeId}
/** * An error representing fiber interruption. * * **Details** * * This interface represents errors that occur when a fiber is forcefully * interrupted. Interruption can happen for various reasons, including * cancellations or system directives to halt operations. Code that deals with * concurrency might need to catch or handle these to ensure proper cleanup. * * @since 2.0.0 * @category Models */export interface InterruptedException extends YieldableError { readonly _tag: "InterruptedException" readonly [InterruptedExceptionTypeId]: InterruptedExceptionTypeId}
/** * An error representing an invalid argument passed to a method. * * **Details** * * This interface is used for signaling that a function or method received an * argument that does not meet its preconditions. * * @since 2.0.0 * @category Models */export interface IllegalArgumentException extends YieldableError { readonly _tag: "IllegalArgumentException" readonly [IllegalArgumentExceptionTypeId]: IllegalArgumentExceptionTypeId}
/** * An error that occurs when an expected element is missing. * * **Details** * * This interface indicates scenarios like looking up an item in a collection * or searching for data that should be present but isn't. It helps your code * signal a more specific issue rather than a general error. * * @since 2.0.0 * @category Models */export interface NoSuchElementException extends YieldableError { readonly _tag: "NoSuchElementException" readonly [NoSuchElementExceptionTypeId]: NoSuchElementExceptionTypeId}
/** * An error indicating invalid capacity for a `PubSub`. * * @since 2.0.0 * @category Models */export interface InvalidPubSubCapacityException extends YieldableError { readonly _tag: "InvalidPubSubCapacityException" readonly [InvalidPubSubCapacityExceptionTypeId]: InvalidPubSubCapacityExceptionTypeId}
/** * An error that occurs when resource capacity is exceeded. * * @since 3.5.0 * @category Models */export interface ExceededCapacityException extends YieldableError { readonly _tag: "ExceededCapacityException" readonly [ExceededCapacityExceptionTypeId]: ExceededCapacityExceptionTypeId}
/** * An error representing a computation that timed out. * * @since 2.0.0 * @category Models */export interface TimeoutException extends YieldableError { readonly _tag: "TimeoutException" readonly [TimeoutExceptionTypeId]: TimeoutExceptionTypeId}
/** * A checked exception for handling unknown or unexpected errors. * * **Details** * * This interface captures errors that don't fall under known categories. It is * especially helpful for wrapping low-level or third-party library errors that * might provide little or no context, such as from a rejected promise. * * @since 2.0.0 * @category Models */export interface UnknownException extends YieldableError { readonly _tag: "UnknownException" readonly [UnknownExceptionTypeId]: UnknownExceptionTypeId readonly error: unknown}
/** * Represents a lack of errors within a `Cause`. * * @see {@link empty} Construct a new `Empty` cause * @see {@link isEmptyType} Check if a `Cause` is an `Empty` type * * @since 2.0.0 * @category Models */export interface Empty extends Cause.Variance<never>, Equal.Equal, Pipeable, Inspectable { readonly _tag: "Empty"}
/** * Represents an expected error within a `Cause`. * * **Details** * * This interface models a `Cause` that carries an expected or known error of * type `E`. For example, if you validate user input and find it invalid, you * might store that error within a `Fail`. * * @see {@link fail} Construct a `Fail` cause * @see {@link isFailType} Check if a `Cause` is a `Fail` * * @since 2.0.0 * @category Models */export interface Fail<out E> extends Cause.Variance<E>, Equal.Equal, Pipeable, Inspectable { readonly _tag: "Fail" readonly error: E}
/** * Represents an unexpected defect within a `Cause`. * * **Details** * * This interface models a `Cause` for errors that are typically unrecoverable or * unanticipated—like runtime exceptions or bugs. When code "dies," it indicates a * severe failure that wasn't accounted for. * * @see {@link die} Construct a `Die` cause * @see {@link isDieType} Check if a `Cause` is a `Die` * * @since 2.0.0 * @category Models */export interface Die extends Cause.Variance<never>, Equal.Equal, Pipeable, Inspectable { readonly _tag: "Die" readonly defect: unknown}
/** * Represents fiber interruption within a `Cause`. * * **Details** * * This interface models a scenario where an effect was halted by an external * signal, carrying a `FiberId` that identifies which fiber was interrupted. * Interruption is a normal part of concurrency, used for cancellation or * resource cleanup. * * @see {@link interrupt} Construct an `Interrupt` cause * @see {@link isInterruptType} Check if a `Cause` is an `Interrupt` * * @since 2.0.0 * @category Models */export interface Interrupt extends Cause.Variance<never>, Equal.Equal, Pipeable, Inspectable { readonly _tag: "Interrupt" readonly fiberId: FiberId.FiberId}
/** * Represents parallel composition of two `Cause`s. * * **Details** * * This interface captures failures that happen simultaneously. In scenarios * with concurrency, more than one operation can fail in parallel. Instead of * losing information, this structure stores both errors together. * * @see {@link parallel} Combine two `Cause`s in parallel * @see {@link isParallelType} Check if a `Cause` is a `Parallel` * * @since 2.0.0 * @category Models */export interface Parallel<out E> extends Cause.Variance<E>, Equal.Equal, Pipeable, Inspectable { readonly _tag: "Parallel" readonly left: Cause<E> readonly right: Cause<E>}
/** * Represents sequential composition of two `Cause`s. * * **Details** * * This interface models the scenario where one error follows another in * sequence, such as when a main effect fails and then a finalizer also fails. * It ensures both errors are retained in the final `Cause`. * * @see {@link sequential} Combine two `Cause`s sequentially * @see {@link isSequentialType} Check if a `Cause` is a `Sequential` * * @since 2.0.0 * @category Models */export interface Sequential<out E> extends Cause.Variance<E>, Equal.Equal, Pipeable, Inspectable { readonly _tag: "Sequential" readonly left: Cause<E> readonly right: Cause<E>}
/** * Creates an `Empty` cause. * * **Details** * * This function returns a cause that signifies "no error." It's commonly used * to represent an absence of failure conditions. * * @see {@link isEmpty} Check if a `Cause` is empty * * @since 2.0.0 * @category Constructors */export const empty: Cause<never> = internal.empty
/** * Creates a `Fail` cause from an expected error. * * **Details** * * This function constructs a `Cause` carrying an error of type `E`. It's used * when you want to represent a known or anticipated failure in your effectful * computations. * * @see {@link isFailure} Check if a `Cause` contains a failure * * @since 2.0.0 * @category Constructors */export const fail: <E>(error: E) => Cause<E> = internal.fail
/** * Creates a `Die` cause from an unexpected error. * * **Details** * * This function wraps an unhandled or unknown defect (like a runtime crash) * into a `Cause`. It's useful for capturing unforeseen issues in a structured * way. * * @see {@link isDie} Check if a `Cause` contains a defect * * @since 2.0.0 * @category Constructors */export const die: (defect: unknown) => Cause<never> = internal.die
/** * Creates an `Interrupt` cause from a `FiberId`. * * **Details** * * This function represents a fiber that has been interrupted. It stores the * identifier of the interrupted fiber, enabling precise tracking of concurrent * cancellations. * * @see {@link isInterrupted} Check if a `Cause` contains an interruption * * @since 2.0.0 * @category Constructors */export const interrupt: (fiberId: FiberId.FiberId) => Cause<never> = internal.interrupt
/** * Combines two `Cause`s in parallel. * * **Details** * * This function merges two errors that occurred simultaneously. Instead of * discarding one error, both are retained, allowing for richer error reporting * and debugging. * * @see {@link isParallelType} Check if a `Cause` is a `Parallel` * * @since 2.0.0 * @category Constructors */export const parallel: <E, E2>(left: Cause<E>, right: Cause<E2>) => Cause<E | E2> = internal.parallel
/** * Combines two `Cause`s sequentially. * * **Details** * * This function merges two errors that occurred in sequence, such as a main * error followed by a finalization error. It preserves both errors for complete * failure information. * * @see {@link isSequentialType} Check if a `Cause` is a `Sequential` * * @since 2.0.0 * @category Constructors */export const sequential: <E, E2>(left: Cause<E>, right: Cause<E2>) => Cause<E | E2> = internal.sequential
/** * Checks if a value is a `Cause`. * * @since 2.0.0 * @category Guards */export const isCause: (u: unknown) => u is Cause<unknown> = internal.isCause
/** * Checks if a `Cause` is an `Empty` type. * * @see {@link empty} Create a new `Empty` cause * * @since 2.0.0 * @category Guards */export const isEmptyType: <E>(self: Cause<E>) => self is Empty = internal.isEmptyType
/** * Checks if a `Cause` is a `Fail` type. * * @see {@link fail} Create a new `Fail` cause * * @since 2.0.0 * @category Guards */export const isFailType: <E>(self: Cause<E>) => self is Fail<E> = internal.isFailType
/** * Checks if a `Cause` is a `Die` type. * * @see {@link die} Create a new `Die` cause * * @since 2.0.0 * @category Guards */export const isDieType: <E>(self: Cause<E>) => self is Die = internal.isDieType
/** * Checks if a `Cause` is an `Interrupt` type. * * @see {@link interrupt} Create an `Interrupt` cause * * @since 2.0.0 * @category Guards */export const isInterruptType: <E>(self: Cause<E>) => self is Interrupt = internal.isInterruptType
/** * Checks if a `Cause` is a `Sequential` type. * * @see {@link sequential} Combine two `Cause`s sequentially * * @since 2.0.0 * @category Guards */export const isSequentialType: <E>(self: Cause<E>) => self is Sequential<E> = internal.isSequentialType
/** * Checks if a `Cause` is a `Parallel` type. * * @see {@link parallel} Combine two `Cause`s in parallel * * @since 2.0.0 * @category Guards */export const isParallelType: <E>(self: Cause<E>) => self is Parallel<E> = internal.isParallelType
/** * Calculates the size of a `Cause`. * * **Details** * * This function returns the total number of `Cause` nodes in the semiring * structure, reflecting how many individual error elements are recorded. * * @since 2.0.0 * @category Getters */export const size: <E>(self: Cause<E>) => number = internal.size
/** * Checks if a `Cause` is entirely empty. * * **Details** * * This function returns `true` if the `Cause` contains no errors, defects, or * interruptions. It's helpful for verifying if a computation truly had no * failures. * * @since 2.0.0 * @category Getters */export const isEmpty: <E>(self: Cause<E>) => boolean = internal.isEmpty
/** * Checks if a `Cause` contains a failure. * * **Details** * * This function returns `true` if the `Cause` includes any `Fail` error. It's * commonly used to confirm whether a workflow encountered an anticipated error * versus just defects or interruptions. * * @since 2.0.0 * @category Getters */export const isFailure: <E>(self: Cause<E>) => boolean = internal.isFailure
/** * Checks if a `Cause` contains a defect. * * **Details** * * This function returns `true` if the `Cause` includes any unexpected or * unhandled errors (`Die`). It's useful for differentiating known failures from * unexpected ones. * * @since 2.0.0 * @category Getters */export const isDie: <E>(self: Cause<E>) => boolean = internal.isDie
/** * Checks if a `Cause` contains an interruption. * * **Details** * * This function returns `true` if the `Cause` includes any fiber interruptions. * * @since 2.0.0 * @category Getters */export const isInterrupted: <E>(self: Cause<E>) => boolean = internal.isInterrupted
/** * Checks if a `Cause` contains only interruptions. * * **Details** * * This function returns `true` if the `Cause` has been interrupted but does not * contain any other failures, such as `Fail` or `Die`. It's helpful for * verifying purely "cancellation" scenarios. * * @since 2.0.0 * @category Getters */export const isInterruptedOnly: <E>(self: Cause<E>) => boolean = internal.isInterruptedOnly
/** * Extracts all recoverable errors of type `E` from a `Cause`. * * **Details** * * This function returns a chunk of errors, providing a list of all `Fail` * values found in the cause. It's useful for collecting all known failures for * logging or combined error handling. * * @since 2.0.0 * @category Getters */export const failures: <E>(self: Cause<E>) => Chunk.Chunk<E> = internal.failures
/** * Extracts all unrecoverable defects from a `Cause`. * * **Details** * * This function returns a chunk of values representing unexpected errors * (`Die`). It's handy for capturing or logging unanticipated failures that * might need special handling, such as bug reports. * * @since 2.0.0 * @category Getters */export const defects: <E>(self: Cause<E>) => Chunk.Chunk<unknown> = internal.defects
/** * Collects all `FiberId`s responsible for interrupting a fiber. * * **Details** * * This function returns a set of IDs indicating which fibers caused * interruptions within this `Cause`. It's useful for debugging concurrency * issues or tracing cancellations. * * @since 2.0.0 * @category Getters */export const interruptors: <E>(self: Cause<E>) => HashSet.HashSet<FiberId.FiberId> = internal.interruptors
/** * Retrieves the first `Fail` error in a `Cause`, if present. * * **Details** * * This function returns an `Option` containing the first recoverable error * (`E`) from the cause. It's often used to quickly check if there's a primary * error to handle or display. * * @since 2.0.0 * @category Getters */export const failureOption: <E>(self: Cause<E>) => Option.Option<E> = internal.failureOption
/** * Splits a `Cause` into either its first `Fail` error or the rest of the cause * (which might only contain `Die` or `Interrupt`). * * **Details** * * This function either returns the checked error (`E`) or the remaining * `Cause<never>` with defects/interruptions. It helps you decide if there's a * recoverable path or if only unhandled issues remain. * * @since 2.0.0 * @category Getters */export const failureOrCause: <E>(self: Cause<E>) => Either.Either<Cause<never>, E> = internal.failureOrCause
/** * Strips out failures with an error of `None` from a `Cause<Option<E>>`. * * **Details** * * This function turns a `Cause<Option<E>>` into an `Option<Cause<E>>`. If the * cause only contains failures of `None`, it becomes `None`; otherwise, it * returns a `Cause` of the remaining errors. It's helpful when working with * optional errors and filtering out certain error paths. * * @since 2.0.0 * @category Getters */export const flipCauseOption: <E>(self: Cause<Option.Option<E>>) => Option.Option<Cause<E>> = internal.flipCauseOption
/** * Retrieves the first `Die` defect in a `Cause`, if present. * * **Details** * * This function returns an `Option` containing the first unexpected failure * (`Die`) discovered. It's helpful for diagnosing the primary defect in a chain * of errors. * * @since 2.0.0 * @category Getters */export const dieOption: <E>(self: Cause<E>) => Option.Option<unknown> = internal.dieOption
/** * Retrieves the first `Interrupt` in a `Cause`, if present. * * **Details** * * This function returns an `Option` with the first fiber interruption * discovered. This is particularly useful for concurrency analysis or debugging * cancellations. * * @since 2.0.0 * @category Getters */export const interruptOption: <E>(self: Cause<E>) => Option.Option<FiberId.FiberId> = internal.interruptOption
/** * Removes all `Fail` and `Interrupt` nodes, keeping only defects (`Die`) in a * `Cause`. * * **Details** * * This function strips a cause of recoverable errors and interruptions, leaving * only unexpected failures. If no defects remain, it returns `None`. It's * valuable for focusing only on unanticipated problems when both known errors * and defects could occur. * * @since 2.0.0 * @category Getters */export const keepDefects: <E>(self: Cause<E>) => Option.Option<Cause<never>> = internal.keepDefects
// TODO(4.0): remove? what's the point of this API?/** * Linearizes a `Cause` into a set of parallel causes, each containing a * sequential chain of failures. * * **Details** * * This function reorganizes the cause structure so that you can analyze each * parallel branch separately, even if they have multiple sequential errors. * * @since 2.0.0 * @category Getters */export const linearize: <E>(self: Cause<E>) => HashSet.HashSet<Cause<E>> = internal.linearize
/** * Removes `Fail` and `Interrupt` nodes from a `Cause`, keeping only defects * (`Die`). * * **Details** * * This function is similar to `keepDefects` but returns a `Cause<never>` * directly, which can still store `Die` or finalizer-related defects. It's * helpful for analyzing only the irrecoverable portion of the error. * * @since 2.0.0 * @category Getters */export const stripFailures: <E>(self: Cause<E>) => Cause<never> = internal.stripFailures
/** * Removes matching defects from a `Cause` using a partial function, returning * the remainder. * * **Details** * * This function applies a user-defined extraction function to each defect * (`Die`). If the function matches the defect, that defect is removed. If all * defects match, the result is `None`. Otherwise, you get a `Cause` with the * unmatched defects. * * @since 2.0.0 * @category Getters */export const stripSomeDefects: { /** * Removes matching defects from a `Cause` using a partial function, returning * the remainder. * * **Details** * * This function applies a user-defined extraction function to each defect * (`Die`). If the function matches the defect, that defect is removed. If all * defects match, the result is `None`. Otherwise, you get a `Cause` with the * unmatched defects. * * @since 2.0.0 * @category Getters */ (pf: (defect: unknown) => Option.Option<unknown>): <E>(self: Cause<E>) => Option.Option<Cause<E>> /** * Removes matching defects from a `Cause` using a partial function, returning * the remainder. * * **Details** * * This function applies a user-defined extraction function to each defect * (`Die`). If the function matches the defect, that defect is removed. If all * defects match, the result is `None`. Otherwise, you get a `Cause` with the * unmatched defects. * * @since 2.0.0 * @category Getters */ <E>(self: Cause<E>, pf: (defect: unknown) => Option.Option<unknown>): Option.Option<Cause<E>>} = internal.stripSomeDefects
/** * Replaces any errors in a `Cause` with a provided constant error. * * **Details** * * This function transforms all `Fail` errors into the specified error value, * preserving the structure of the `Cause`. It's useful when you no longer need * the original error details but still want to keep the cause shape. * * @see {@link map} Apply a custom transformation to `Fail` errors * * @since 2.0.0 * @category Mapping */export const as: { /** * Replaces any errors in a `Cause` with a provided constant error. * * **Details** * * This function transforms all `Fail` errors into the specified error value, * preserving the structure of the `Cause`. It's useful when you no longer need * the original error details but still want to keep the cause shape. * * @see {@link map} Apply a custom transformation to `Fail` errors * * @since 2.0.0 * @category Mapping */ <E2>(error: E2): <E>(self: Cause<E>) => Cause<E2> /** * Replaces any errors in a `Cause` with a provided constant error. * * **Details** * * This function transforms all `Fail` errors into the specified error value, * preserving the structure of the `Cause`. It's useful when you no longer need * the original error details but still want to keep the cause shape. * * @see {@link map} Apply a custom transformation to `Fail` errors * * @since 2.0.0 * @category Mapping */ <E, E2>(self: Cause<E>, error: E2): Cause<E2>} = internal.as
/** * Transforms the errors in a `Cause` using a user-provided function. * * **Details** * * This function applies `f` to each `Fail` error while leaving defects (`Die`) * and interruptions untouched. It's useful for changing or simplifying error * types in your effectful workflows. * * @see {@link as} Replace errors with a single constant * * @since 2.0.0 * @category Mapping */export const map: { /** * Transforms the errors in a `Cause` using a user-provided function. * * **Details** * * This function applies `f` to each `Fail` error while leaving defects (`Die`) * and interruptions untouched. It's useful for changing or simplifying error * types in your effectful workflows. * * @see {@link as} Replace errors with a single constant * * @since 2.0.0 * @category Mapping */ <E, E2>(f: (e: E) => E2): (self: Cause<E>) => Cause<E2> /** * Transforms the errors in a `Cause` using a user-provided function. * * **Details** * * This function applies `f` to each `Fail` error while leaving defects (`Die`) * and interruptions untouched. It's useful for changing or simplifying error * types in your effectful workflows. * * @see {@link as} Replace errors with a single constant * * @since 2.0.0 * @category Mapping */ <E, E2>(self: Cause<E>, f: (e: E) => E2): Cause<E2>} = internal.map
/** * Transforms errors in a `Cause` into new causes. * * **Details** * * This function applies a function `f` to each `Fail` error, converting it into * a new `Cause`. This is especially powerful for merging or restructuring error * types while preserving or combining cause information. * * @see {@link map} Apply a simpler transformation to errors * * @since 2.0.0 * @category Sequencing */export const flatMap: { /** * Transforms errors in a `Cause` into new causes. * * **Details** * * This function applies a function `f` to each `Fail` error, converting it into * a new `Cause`. This is especially powerful for merging or restructuring error * types while preserving or combining cause information. * * @see {@link map} Apply a simpler transformation to errors * * @since 2.0.0 * @category Sequencing */ <E, E2>(f: (e: E) => Cause<E2>): (self: Cause<E>) => Cause<E2> /** * Transforms errors in a `Cause` into new causes. * * **Details** * * This function applies a function `f` to each `Fail` error, converting it into * a new `Cause`. This is especially powerful for merging or restructuring error * types while preserving or combining cause information. * * @see {@link map} Apply a simpler transformation to errors * * @since 2.0.0 * @category Sequencing */ <E, E2>(self: Cause<E>, f: (e: E) => Cause<E2>): Cause<E2>} = internal.flatMap
/** * Sequences two `Cause`s. The second `Cause` can be dependent on the result of * the first `Cause`. * * @since 2.0.0 * @category Sequencing */export const andThen: { /** * Sequences two `Cause`s. The second `Cause` can be dependent on the result of * the first `Cause`. * * @since 2.0.0 * @category Sequencing */ <E, E2>(f: (e: E) => Cause<E2>): (self: Cause<E>) => Cause<E2> /** * Sequences two `Cause`s. The second `Cause` can be dependent on the result of * the first `Cause`. * * @since 2.0.0 * @category Sequencing */ <E2>(f: Cause<E2>): <E>(self: Cause<E>) => Cause<E2> /** * Sequences two `Cause`s. The second `Cause` can be dependent on the result of * the first `Cause`. * * @since 2.0.0 * @category Sequencing */ <E, E2>(self: Cause<E>, f: (e: E) => Cause<E2>): Cause<E2> /** * Sequences two `Cause`s. The second `Cause` can be dependent on the result of * the first `Cause`. * * @since 2.0.0 * @category Sequencing */ <E, E2>(self: Cause<E>, f: Cause<E2>): Cause<E2>} = internal.andThen
/** * Flattens a nested `Cause` structure. * * **Details** * * This function takes a `Cause<Cause<E>>` and merges the layers into a single * `Cause<E>`. It's useful for eliminating additional nesting created by * repeated transformations or compositions. * * @see {@link flatMap} Compose nested causes * * @since 2.0.0 * @category Sequencing */export const flatten: <E>(self: Cause<Cause<E>>) => Cause<E> = internal.flatten
/** * Checks if the current `Cause` contains or is equal to another `Cause`. * * **Details** * * This function returns `true` if `that` cause is part of or the same as * the current `Cause`. It's useful when you need to check for specific * error patterns or deduplicate repeated failures. * * @since 2.0.0 * @category Elements */export const contains: { /** * Checks if the current `Cause` contains or is equal to another `Cause`. * * **Details** * * This function returns `true` if `that` cause is part of or the same as * the current `Cause`. It's useful when you need to check for specific * error patterns or deduplicate repeated failures. * * @since 2.0.0 * @category Elements */ <E2>(that: Cause<E2>): <E>(self: Cause<E>) => boolean /** * Checks if the current `Cause` contains or is equal to another `Cause`. * * **Details** * * This function returns `true` if `that` cause is part of or the same as * the current `Cause`. It's useful when you need to check for specific * error patterns or deduplicate repeated failures. * * @since 2.0.0 * @category Elements */ <E, E2>(self: Cause<E>, that: Cause<E2>): boolean} = internal.contains
/** * Extracts the most "important" defect from a `Cause`. * * **Details** * * This function reduces a `Cause` to a single, prioritized defect. It evaluates * the `Cause` in the following order of priority: * * 1. If the `Cause` contains a failure (e.g., from `Effect.fail`), it returns * the raw error value. * 2. If there is no failure, it looks for the first defect (e.g., from * `Effect.die`). * 3. If neither of the above is present, and the `Cause` stems from an * interruption, it creates and returns an `InterruptedException`. * * This function ensures you can always extract a meaningful representation of * the primary issue from a potentially complex `Cause` structure. * * **When to Use** * * Use this function when you need to extract the most relevant error or defect * from a `Cause`, especially in scenarios where multiple errors or defects may * be present. It's particularly useful for simplifying error reporting or * logging. * * @see {@link squashWith} Allows transforming failures into defects when squashing. * * @since 2.0.0 * @category Destructors */export const squash: <E>(self: Cause<E>) => unknown = core.causeSquash
/** * Extracts the most "important" defect from a `Cause`, transforming failures * into defects using a provided function. * * **Details** * * This function reduces a `Cause` to a single, prioritized defect, while * allowing you to transform recoverable failures into defects through a custom * function. It processes the `Cause` in the following order: * * 1. If the `Cause` contains a failure (e.g., from `Effect.fail`), it applies * the provided function `f` to the error to transform it into a defect. * 2. If there is no failure, it looks for the first defect (e.g., from * `Effect.die`) and returns it. * 3. If neither is present and the `Cause` stems from an interruption, it * returns an `InterruptedException`. * * This function is particularly useful when you need custom handling or * transformation of errors while processing a `Cause`. * * @see {@link squash} Extracts the most "important" defect without transforming failures. * * @since 2.0.0 * @category Destructors */export const squashWith: { /** * Extracts the most "important" defect from a `Cause`, transforming failures * into defects using a provided function. * * **Details** * * This function reduces a `Cause` to a single, prioritized defect, while * allowing you to transform recoverable failures into defects through a custom * function. It processes the `Cause` in the following order: * * 1. If the `Cause` contains a failure (e.g., from `Effect.fail`), it applies * the provided function `f` to the error to transform it into a defect. * 2. If there is no failure, it looks for the first defect (e.g., from * `Effect.die`) and returns it. * 3. If neither is present and the `Cause` stems from an interruption, it * returns an `InterruptedException`. * * This function is particularly useful when you need custom handling or * transformation of errors while processing a `Cause`. * * @see {@link squash} Extracts the most "important" defect without transforming failures. * * @since 2.0.0 * @category Destructors */ <E>(f: (error: E) => unknown): (self: Cause<E>) => unknown /** * Extracts the most "important" defect from a `Cause`, transforming failures * into defects using a provided function. * * **Details** * * This function reduces a `Cause` to a single, prioritized defect, while * allowing you to transform recoverable failures into defects through a custom * function. It processes the `Cause` in the following order: * * 1. If the `Cause` contains a failure (e.g., from `Effect.fail`), it applies * the provided function `f` to the error to transform it into a defect. * 2. If there is no failure, it looks for the first defect (e.g., from * `Effect.die`) and returns it. * 3. If neither is present and the `Cause` stems from an interruption, it * returns an `InterruptedException`. * * This function is particularly useful when you need custom handling or * transformation of errors while processing a `Cause`. * * @see {@link squash} Extracts the most "important" defect without transforming failures. * * @since 2.0.0 * @category Destructors */ <E>(self: Cause<E>, f: (error: E) => unknown): unknown} = core.causeSquashWith
/** * Searches a `Cause` using a partial function to extract information. * * **Details** * * This function allows you to search through a `Cause` using a custom partial * function. The partial function is applied to the `Cause`, and if it matches, * the result is returned wrapped in a `Some`. If no match is found, the result * is `None`. * * This is particularly useful when you are only interested in specific types of * errors, defects, or interruption causes within a potentially complex `Cause` * structure. By leveraging a partial function, you can focus on extracting only * the relevant information you care about. * * The partial function should return an `Option` indicating whether it matched * and the value it extracted. * * @since 2.0.0 * @category Elements */export const find: { /** * Searches a `Cause` using a partial function to extract information. * * **Details** * * This function allows you to search through a `Cause` using a custom partial * function. The partial function is applied to the `Cause`, and if it matches, * the result is returned wrapped in a `Some`. If no match is found, the result * is `None`. * * This is particularly useful when you are only interested in specific types of * errors, defects, or interruption causes within a potentially complex `Cause` * structure. By leveraging a partial function, you can focus on extracting only * the relevant information you care about. * * The partial function should return an `Option` indicating whether it matched * and the value it extracted. * * @since 2.0.0 * @category Elements */ <E, Z>(pf: (cause: Cause<E>) => Option.Option<Z>): (self: Cause<E>) => Option.Option<Z> /** * Searches a `Cause` using a partial function to extract information. * * **Details** * * This function allows you to search through a `Cause` using a custom partial * function. The partial function is applied to the `Cause`, and if it matches, * the result is returned wrapped in a `Some`. If no match is found, the result * is `None`. * * This is particularly useful when you are only interested in specific types of * errors, defects, or interruption causes within a potentially complex `Cause` * structure. By leveraging a partial function, you can focus on extracting only * the relevant information you care about. * * The partial function should return an `Option` indicating whether it matched * and the value it extracted. * * @since 2.0.0 * @category Elements */ <E, Z>(self: Cause<E>, pf: (cause: Cause<E>) => Option.Option<Z>): Option.Option<Z>} = internal.find
/** * Preserves parts of a `Cause` that match a given predicate. * * **Details** * * This function allows you to retain only the parts of a `Cause` structure that * match a specified predicate or refinement. Any parts of the `Cause` that do * not match the provided condition are excluded from the result. * * You can use this function in two ways: * - With a `Predicate`: A function that evaluates whether a `Cause` should be * retained based on its value. * - With a `Refinement`: A more specific predicate that can refine the type of * the `Cause`. * * This is useful when you need to extract specific types of errors, defects, or * interruptions from a `Cause` while discarding unrelated parts. * * @since 2.0.0 * @category Filtering */export const filter: { /** * Preserves parts of a `Cause` that match a given predicate. * * **Details** * * This function allows you to retain only the parts of a `Cause` structure that * match a specified predicate or refinement. Any parts of the `Cause` that do * not match the provided condition are excluded from the result. * * You can use this function in two ways: * - With a `Predicate`: A function that evaluates whether a `Cause` should be * retained based on its value. * - With a `Refinement`: A more specific predicate that can refine the type of * the `Cause`. * * This is useful when you need to extract specific types of errors, defects, or * interruptions from a `Cause` while discarding unrelated parts. * * @since 2.0.0 * @category Filtering */ <E, EB extends E>(refinement: Refinement<Cause<NoInfer<E>>, Cause<EB>>): (self: Cause<E>) => Cause<EB> /** * Preserves parts of a `Cause` that match a given predicate. * * **Details** * * This function allows you to retain only the parts of a `Cause` structure that * match a specified predicate or refinement. Any parts of the `Cause` that do * not match the provided condition are excluded from the result. * * You can use this function in two ways: * - With a `Predicate`: A function that evaluates whether a `Cause` should be * retained based on its value. * - With a `Refinement`: A more specific predicate that can refine the type of * the `Cause`. * * This is useful when you need to extract specific types of errors, defects, or * interruptions from a `Cause` while discarding unrelated parts. * * @since 2.0.0 * @category Filtering */ <E>(predicate: Predicate<Cause<NoInfer<E>>>): (self: Cause<E>) => Cause<E> /** * Preserves parts of a `Cause` that match a given predicate. * * **Details** * * This function allows you to retain only the parts of a `Cause` structure that * match a specified predicate or refinement. Any parts of the `Cause` that do * not match the provided condition are excluded from the result. * * You can use this function in two ways: * - With a `Predicate`: A function that evaluates whether a `Cause` should be * retained based on its value. * - With a `Refinement`: A more specific predicate that can refine the type of * the `Cause`. * * This is useful when you need to extract specific types of errors, defects, or * interruptions from a `Cause` while discarding unrelated parts. * * @since 2.0.0 * @category Filtering */ <E, EB extends E>(self: Cause<E>, refinement: Refinement<Cause<E>, Cause<EB>>): Cause<EB> /** * Preserves parts of a `Cause` that match a given predicate. * * **Details** * * This function allows you to retain only the parts of a `Cause` structure that * match a specified predicate or refinement. Any parts of the `Cause` that do * not match the provided condition are excluded from the result. * * You can use this function in two ways: * - With a `Predicate`: A function that evaluates whether a `Cause` should be * retained based on its value. * - With a `Refinement`: A more specific predicate that can refine the type of * the `Cause`. * * This is useful when you need to extract specific types of errors, defects, or * interruptions from a `Cause` while discarding unrelated parts. * * @since 2.0.0 * @category Filtering */ <E>(self: Cause<E>, predicate: Predicate<Cause<E>>): Cause<E>} = internal.filter
/** * Transforms a `Cause` into a single value using custom handlers for each * possible case. * * **Details** * * This function processes a `Cause` by applying a set of custom handlers to * each possible type of cause: `Empty`, `Fail`, `Die`, `Interrupt`, * `Sequential`, and `Parallel`. The result of this function is a single value * of type `Z`. This function allows you to define exactly how to handle each * part of a `Cause`, whether it's a failure, defect, interruption, or a * combination of these. * * The options parameter provides handlers for: * - `onEmpty`: Handles the case where the cause is `Empty`, meaning no errors * occurred. * - `onFail`: Processes a failure with an error of type `E`. * - `onDie`: Processes a defect (unexpected error). * - `onInterrupt`: Handles a fiber interruption, providing the `FiberId` of the * interruption. * - `onSequential`: Combines two sequential causes into a single value of type * `Z`. * - `onParallel`: Combines two parallel causes into a single value of type `Z`. * * @since 2.0.0 * @category Matching */export const match: { /** * Transforms a `Cause` into a single value using custom handlers for each * possible case. * * **Details** * * This function processes a `Cause` by applying a set of custom handlers to * each possible type of cause: `Empty`, `Fail`, `Die`, `Interrupt`, * `Sequential`, and `Parallel`. The result of this function is a single value * of type `Z`. This function allows you to define exactly how to handle each * part of a `Cause`, whether it's a failure, defect, interruption, or a * combination of these. * * The options parameter provides handlers for: * - `onEmpty`: Handles the case where the cause is `Empty`, meaning no errors * occurred. * - `onFail`: Processes a failure with an error of type `E`. * - `onDie`: Processes a defect (unexpected error). * - `onInterrupt`: Handles a fiber interruption, providing the `FiberId` of the * interruption. * - `onSequential`: Combines two sequential causes into a single value of type * `Z`. * - `onParallel`: Combines two parallel causes into a single value of type `Z`. * * @since 2.0.0 * @category Matching */ <Z, E>( options: { readonly onEmpty: Z readonly onFail: (error: E) => Z readonly onDie: (defect: unknown) => Z readonly onInterrupt: (fiberId: FiberId.FiberId) => Z readonly onSequential: (left: Z, right: Z) => Z readonly onParallel: (left: Z, right: Z) => Z } ): (self: Cause<E>) => Z /** * Transforms a `Cause` into a single value using custom handlers for each * possible case. * * **Details** * * This function processes a `Cause` by applying a set of custom handlers to * each possible type of cause: `Empty`, `Fail`, `Die`, `Interrupt`, * `Sequential`, and `Parallel`. The result of this function is a single value * of type `Z`. This function allows you to define exactly how to handle each * part of a `Cause`, whether it's a failure, defect, interruption, or a * combination of these. * * The options parameter provides handlers for: * - `onEmpty`: Handles the case where the cause is `Empty`, meaning no errors * occurred. * - `onFail`: Processes a failure with an error of type `E`. * - `onDie`: Processes a defect (unexpected error). * - `onInterrupt`: Handles a fiber interruption, providing the `FiberId` of the * interruption. * - `onSequential`: Combines two sequential causes into a single value of type * `Z`. * - `onParallel`: Combines two parallel causes into a single value of type `Z`. * * @since 2.0.0 * @category Matching */ <Z, E>( self: Cause<E>, options: { readonly onEmpty: Z readonly onFail: (error: E) => Z readonly onDie: (defect: unknown) => Z readonly onInterrupt: (fiberId: FiberId.FiberId) => Z readonly onSequential: (left: Z, right: Z) => Z readonly onParallel: (left: Z, right: Z) => Z } ): Z} = internal.match
/** * Combines all parts of a `Cause` into a single value by starting with an * initial value. * * **Details** * * This function processes a `Cause` by starting with an initial value (`zero`) * and applying a custom function (`pf`) to combine all elements of the `Cause` * into a single result of type `Z`. The custom function determines how each * part of the `Cause` contributes to the final result. The function can return * an `Option` to either continue combining values or skip specific parts of the * `Cause`. * * This function is useful for tasks such as: * - Aggregating error messages from a `Cause` into a single string. * - Summarizing the structure of a `Cause` into a simplified result. * - Filtering or processing only specific parts of a `Cause`. * * The reduction proceeds in a top-down manner, visiting all nodes in the * `Cause` structure. This gives you complete control over how each part of the * `Cause` contributes to the final result. * * @since 2.0.0 * @category Reducing */export const reduce: { /** * Combines all parts of a `Cause` into a single value by starting with an * initial value. * * **Details** * * This function processes a `Cause` by starting with an initial value (`zero`) * and applying a custom function (`pf`) to combine all elements of the `Cause` * into a single result of type `Z`. The custom function determines how each * part of the `Cause` contributes to the final result. The function can return * an `Option` to either continue combining values or skip specific parts of the * `Cause`. * * This function is useful for tasks such as: * - Aggregating error messages from a `Cause` into a single string. * - Summarizing the structure of a `Cause` into a simplified result. * - Filtering or processing only specific parts of a `Cause`. * * The reduction proceeds in a top-down manner, visiting all nodes in the * `Cause` structure. This gives you complete control over how each part of the * `Cause` contributes to the final result. * * @since 2.0.0 * @category Reducing */ <Z, E>(zero: Z, pf: (accumulator: Z, cause: Cause<E>) => Option.Option<Z>): (self: Cause<E>) => Z /** * Combines all parts of a `Cause` into a single value by starting with an * initial value. * * **Details** * * This function processes a `Cause` by starting with an initial value (`zero`) * and applying a custom function (`pf`) to combine all elements of the `Cause` * into a single result of type `Z`. The custom function determines how each * part of the `Cause` contributes to the final result. The function can return * an `Option` to either continue combining values or skip specific parts of the * `Cause`. * * This function is useful for tasks such as: * - Aggregating error messages from a `Cause` into a single string. * - Summarizing the structure of a `Cause` into a simplified result. * - Filtering or processing only specific parts of a `Cause`. * * The reduction proceeds in a top-down manner, visiting all nodes in the * `Cause` structure. This gives you complete control over how each part of the * `Cause` contributes to the final result. * * @since 2.0.0 * @category Reducing */ <Z, E>( self: Cause<E>, zero: Z, pf: (accumulator: Z, cause: Cause<E>) => Option.Option<Z> ): Z} = internal.reduce
/** * Combines all parts of a `Cause` into a single value using a custom reducer * and a context. * * **Details** * * This function allows you to reduce a `Cause` into a single value of type `Z` * using a custom `CauseReducer`. A `CauseReducer` provides methods to handle * specific parts of the `Cause`, such as failures, defects, or interruptions. * Additionally, this function provides access to a `context` value, which can * be used to carry information or maintain state during the reduction process. * * This is particularly useful when the reduction process needs additional * context or configuration, such as: * - Aggregating error details with dynamic formatting. * - Collecting logs or statistics about the `Cause`. * - Performing stateful transformations based on the `context`. * * @see {@link reduce} To reduce a `Cause` without additional context. * * @since 2.0.0 * @category Reducing */export const reduceWithContext: { /** * Combines all parts of a `Cause` into a single value using a custom reducer * and a context. * * **Details** * * This function allows you to reduce a `Cause` into a single value of type `Z` * using a custom `CauseReducer`. A `CauseReducer` provides methods to handle * specific parts of the `Cause`, such as failures, defects, or interruptions. * Additionally, this function provides access to a `context` value, which can * be used to carry information or maintain state during the reduction process. * * This is particularly useful when the reduction process needs additional * context or configuration, such as: * - Aggregating error details with dynamic formatting. * - Collecting logs or statistics about the `Cause`. * - Performing stateful transformations based on the `context`. * * @see {@link reduce} To reduce a `Cause` without additional context. * * @since 2.0.0 * @category Reducing */ <C, E, Z>(context: C, reducer: CauseReducer<C, E, Z>): (self: Cause<E>) => Z /** * Combines all parts of a `Cause` into a single value using a custom reducer * and a context. * * **Details** * * This function allows you to reduce a `Cause` into a single value of type `Z` * using a custom `CauseReducer`. A `CauseReducer` provides methods to handle * specific parts of the `Cause`, such as failures, defects, or interruptions. * Additionally, this function provides access to a `context` value, which can * be used to carry information or maintain state during the reduction process. * * This is particularly useful when the reduction process needs additional * context or configuration, such as: * - Aggregating error details with dynamic formatting. * - Collecting logs or statistics about the `Cause`. * - Performing stateful transformations based on the `context`. * * @see {@link reduce} To reduce a `Cause` without additional context. * * @since 2.0.0 * @category Reducing */ <C, E, Z>(self: Cause<E>, context: C, reducer: CauseReducer<C, E, Z>): Z} = internal.reduceWithContext
/** * Creates an error that indicates a `Fiber` was interrupted. * * **Details** * * This function constructs an `InterruptedException` recognized by the Effect * runtime. It is usually thrown or returned when a fiber's execution is * interrupted by external events or by another fiber. This is particularly * helpful in concurrent programs where fibers may halt each other before * completion. * * @since 2.0.0 * @category Errors */export const InterruptedException: new(message?: string | undefined) => InterruptedException = core.InterruptedException
/** * Checks if a given unknown value is an `InterruptedException`. * * @since 2.0.0 * @category Guards */export const isInterruptedException: (u: unknown) => u is InterruptedException = core.isInterruptedException
/** * Creates an error indicating an invalid method argument. * * **Details** * * This function constructs an `IllegalArgumentException`. It is typically * thrown or returned when an operation receives improper inputs, such as * out-of-range values or invalid object states. * * @since 2.0.0 * @category Errors */export const IllegalArgumentException: new(message?: string | undefined) => IllegalArgumentException = core.IllegalArgumentException
/** * Checks if a given unknown value is an `IllegalArgumentException`. * * @since 2.0.0 * @category Guards */export const isIllegalArgumentException: (u: unknown) => u is IllegalArgumentException = core.isIllegalArgumentException
/** * Creates an error indicating a missing element. * * **Details** * * This function constructs a `NoSuchElementException`. It helps you clearly * communicate that a required element is unavailable. * * @since 2.0.0 * @category Errors */export const NoSuchElementException: new(message?: string | undefined) => NoSuchElementException = core.NoSuchElementException
/** * Checks if a given unknown value is a `NoSuchElementException`. * * @since 2.0.0 * @category Guards */export const isNoSuchElementException: (u: unknown) => u is NoSuchElementException = core.isNoSuchElementException
/** * Creates an error for general runtime errors. * * **Details** * * This function constructs a `RuntimeException`, for errors that occur at * runtime but are not specifically typed or categorized as interruptions, * missing elements, or invalid arguments. It helps unify a wide range of * unexpected conditions under a single, recognizable error type. * * @since 2.0.0 * @category Errors */export const RuntimeException: new(message?: string | undefined) => RuntimeException = core.RuntimeException
/** * Checks if a given unknown value is a `RuntimeException`. * * @since 2.0.0 * @category Guards */export const isRuntimeException: (u: unknown) => u is RuntimeException = core.isRuntimeException
/** * Creates an error for operations that exceed their expected time. * * **Details** * * This function constructs a `TimeoutException`. It is typically used to signal * that an operation or fiber did not complete within a designated time limit, * allowing you to handle slow or hanging processes. * * @since 2.0.0 * @category Errors */export const TimeoutException: new(message?: string | undefined) => TimeoutException = core.TimeoutException
/** * Checks if a given unknown value is a `TimeoutException`. * * @since 3.15.0 * @category Guards */export const isTimeoutException: (u: unknown) => u is TimeoutException = core.isTimeoutException
/** * Creates an instance of `UnknownException`, an error object used to handle * unknown errors such as those from rejected promises. * * **Details** * * This function constructs an `UnknownException` with flexible behavior for * managing the error message and cause. * * The required `error` argument is passed as the `cause` to the global `Error` * constructor, ensuring that the original cause is preserved in the error chain * for debugging purposes. This ensures that the origin stack trace is * preserved. * * The `error` argument is always stored in the `error` property of the * `UnknownException` instance for reference, regardless of its type. * * Additionally, if you provide a `message` argument, it is used as the error * message. If no `message` is provided, the error message defaults to `"An * unknown error occurred"`. * * **When to Use** * * Use this function when you need to handle unexpected or unknown errors in * your application, particularly when the source of the error might not provide * a clear message. This is useful for wrapping generic errors thrown from * promises or external APIs. * * @since 2.0.0 * @category Errors */export const UnknownException: new(error: unknown, message?: string | undefined) => UnknownException = core.UnknownException
/** * Checks if a given unknown value is an `UnknownException`. * * @since 2.0.0 * @category Guards */export const isUnknownException: (u: unknown) => u is UnknownException = core.isUnknownException
/** * Creates an error indicating resource capacity has been exceeded. * * **Details** * * This function constructs an `ExceededCapacityException`, signifying that an * operation or resource usage surpassed established limits. This can be * essential for concurrency or resource management situations, ensuring your * application doesn't go beyond acceptable thresholds. * * @since 3.5.0 * @category Errors */export const ExceededCapacityException: new(message?: string | undefined) => ExceededCapacityException = core.ExceededCapacityException
/** * Checks if a given unknown value is an `ExceededCapacityException`. * * @since 3.5.0 * @category Guards */export const isExceededCapacityException: (u: unknown) => u is ExceededCapacityException = core.isExceededCapacityException
/** * Converts a `Cause` into a human-readable string. * * **Details** * * This function pretty-prints the entire `Cause`, including any failures, * defects, and interruptions. It can be especially helpful for logging, * debugging, or displaying structured errors to users. * * You can optionally pass `options` to configure how the error cause is * rendered. By default, it includes essential details of all errors in the * `Cause`. * * @see {@link prettyErrors} Get a list of `PrettyError` objects instead of a single string. * * @since 2.0.0 * @category Formatting */export const pretty: <E>(cause: Cause<E>, options?: { readonly renderErrorCause?: boolean | undefined}) => string = internal.pretty
/** * A shape for prettified errors, optionally including a source span. * * @since 3.2.0 * @category Models */export interface PrettyError extends Error { readonly span: Span | undefined}
/** * Returns a list of prettified errors (`PrettyError`) from a `Cause`. * * **Details** * * This function inspects the entire `Cause` and produces an array of * `PrettyError` objects. Each object may include additional metadata, such as a * `Span`, to provide deeper insights into where and how the error occurred. * * @since 3.2.0 * @category Formatting */export const prettyErrors: <E>(cause: Cause<E>) => Array<PrettyError> = internal.prettyErrors
/** * Retrieves the original, unproxied error instance from an error object. * * **Details** * * This function returns the underlying error object without any * library-specific wrapping or proxying that might occur during error handling. * This can be essential if you need direct access to the error's native * properties, such as stack traces or custom data fields, for detailed * debugging or integration with external systems. * * @since 2.0.0 * @category Errors */export const originalError: <E>(obj: E) => E = core.originalInstance123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158/** * @since 2.0.0 */import * as internal from "./internal/channel/childExecutorDecision.js"
/** * @since 2.0.0 * @category symbols */export const ChildExecutorDecisionTypeId: unique symbol = internal.ChildExecutorDecisionTypeId
/** * @since 2.0.0 * @category symbols */export type ChildExecutorDecisionTypeId = typeof ChildExecutorDecisionTypeId
/** * @since 2.0.0 * @category models */export type ChildExecutorDecision = Continue | Close | Yield
/** * @since 2.0.0 */export declare namespace ChildExecutorDecision { /** * @since 2.0.0 * @category models */ export interface Proto { readonly [ChildExecutorDecisionTypeId]: ChildExecutorDecisionTypeId }}
/** * Continue executing the current substream * * @since 2.0.0 * @category models */export interface Continue extends ChildExecutorDecision.Proto { readonly _tag: "Continue"}
/** * Close the current substream with a given value and pass execution to the * next substream * * @since 2.0.0 * @category models */export interface Close extends ChildExecutorDecision.Proto { readonly _tag: "Close" readonly value: unknown}
/** * Pass execution to the next substream. This either pulls a new element * from upstream, or yields to an already created active substream. * * @since 2.0.0 * @category models */export interface Yield extends ChildExecutorDecision.Proto { readonly _tag: "Yield"}
/** * @since 2.0.0 * @category constructors */export const Continue: (_: void) => ChildExecutorDecision = internal.Continue
/** * @since 2.0.0 * @category constructors */export const Close: (value: unknown) => ChildExecutorDecision = internal.Close
/** * @since 2.0.0 * @category constructors */export const Yield: (_: void) => ChildExecutorDecision = internal.Yield
/** * Returns `true` if the specified value is a `ChildExecutorDecision`, `false` * otherwise. * * @since 2.0.0 * @category refinements */export const isChildExecutorDecision: (u: unknown) => u is ChildExecutorDecision = internal.isChildExecutorDecision
/** * Returns `true` if the specified `ChildExecutorDecision` is a `Continue`, * `false` otherwise. * * @since 2.0.0 * @category refinements */export const isContinue: (self: ChildExecutorDecision) => self is Continue = internal.isContinue
/** * Returns `true` if the specified `ChildExecutorDecision` is a `Close`, `false` * otherwise. * * @since 2.0.0 * @category refinements */export const isClose: (self: ChildExecutorDecision) => self is Close = internal.isClose
/** * Returns `true` if the specified `ChildExecutorDecision` is a `Yield`, `false` * otherwise. * * @since 2.0.0 * @category refinements */export const isYield: (self: ChildExecutorDecision) => self is Yield = internal.isYield
/** * Folds over a `ChildExecutorDecision` to produce a value of type `A`. * * @since 2.0.0 * @category folding */export const match: { /** * Folds over a `ChildExecutorDecision` to produce a value of type `A`. * * @since 2.0.0 * @category folding */ <A>( options: { readonly onContinue: () => A readonly onClose: (value: unknown) => A readonly onYield: () => A } ): (self: ChildExecutorDecision) => A /** * Folds over a `ChildExecutorDecision` to produce a value of type `A`. * * @since 2.0.0 * @category folding */ <A>( self: ChildExecutorDecision, options: { readonly onContinue: () => A readonly onClose: (value: unknown) => A readonly onYield: () => A } ): A} = internal.match1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350/** * @since 2.0.0 */import * as RA from "./Array.js"import type { NonEmptyReadonlyArray } from "./Array.js"import type { Either } from "./Either.js"import * as Equal from "./Equal.js"import * as Equivalence from "./Equivalence.js"import { dual, identity, pipe } from "./Function.js"import * as Hash from "./Hash.js"import type { TypeLambda } from "./HKT.js"import { format, type Inspectable, NodeInspectSymbol, toJSON } from "./Inspectable.js"import type { NonEmptyIterable } from "./NonEmptyIterable.js"import type { Option } from "./Option.js"import * as O from "./Option.js"import * as Order from "./Order.js"import type { Pipeable } from "./Pipeable.js"import { pipeArguments } from "./Pipeable.js"import { hasProperty, type Predicate, type Refinement } from "./Predicate.js"import type { Covariant, NoInfer } from "./Types.js"
const TypeId: unique symbol = Symbol.for("effect/Chunk") as TypeId
/** * @category symbol * @since 2.0.0 */export type TypeId = typeof TypeId
/** * @category models * @since 2.0.0 */export interface Chunk<out A> extends Iterable<A>, Equal.Equal, Pipeable, Inspectable { readonly [TypeId]: { readonly _A: Covariant<A> } readonly length: number /** @internal */ right: Chunk<A> /** @internal */ left: Chunk<A> /** @internal */ backing: Backing<A> /** @internal */ depth: number}
/** * @category model * @since 2.0.0 */export interface NonEmptyChunk<out A> extends Chunk<A>, NonEmptyIterable<A> {}
/** * @category type lambdas * @since 2.0.0 */export interface ChunkTypeLambda extends TypeLambda { readonly type: Chunk<this["Target"]>}
type Backing<A> = | IArray<A> | IConcat<A> | ISingleton<A> | IEmpty | ISlice<A>
interface IArray<A> { readonly _tag: "IArray" readonly array: ReadonlyArray<A>}
interface IConcat<A> { readonly _tag: "IConcat" readonly left: Chunk<A> readonly right: Chunk<A>}
interface ISingleton<A> { readonly _tag: "ISingleton" readonly a: A}
interface IEmpty { readonly _tag: "IEmpty"}
interface ISlice<A> { readonly _tag: "ISlice" readonly chunk: Chunk<A> readonly offset: number readonly length: number}
function copy<A>( src: ReadonlyArray<A>, srcPos: number, dest: Array<A>, destPos: number, len: number) { for (let i = srcPos; i < Math.min(src.length, srcPos + len); i++) { dest[destPos + i - srcPos] = src[i]! } return dest}
const emptyArray: ReadonlyArray<never> = []
/** * Compares the two chunks of equal length using the specified function * * @category equivalence * @since 2.0.0 */export const getEquivalence = <A>(isEquivalent: Equivalence.Equivalence<A>): Equivalence.Equivalence<Chunk<A>> => Equivalence.make((self, that) => self.length === that.length && toReadonlyArray(self).every((value, i) => isEquivalent(value, unsafeGet(that, i))) )
const _equivalence = getEquivalence(Equal.equals)
const ChunkProto: Omit<Chunk<unknown>, "backing" | "depth" | "left" | "length" | "right"> = { [TypeId]: { _A: (_: never) => _ }, toString<A>(this: Chunk<A>) { return format(this.toJSON()) }, toJSON<A>(this: Chunk<A>) { return { _id: "Chunk", values: toReadonlyArray(this).map(toJSON) } }, [NodeInspectSymbol]<A>(this: Chunk<A>) { return this.toJSON() }, [Equal.symbol]<A>(this: Chunk<A>, that: unknown): boolean { return isChunk(that) && _equivalence(this, that) }, [Hash.symbol]<A>(this: Chunk<A>): number { return Hash.cached(this, Hash.array(toReadonlyArray(this))) }, [Symbol.iterator]<A>(this: Chunk<A>): Iterator<A> { switch (this.backing._tag) { case "IArray": { return this.backing.array[Symbol.iterator]() } case "IEmpty": { return emptyArray[Symbol.iterator]() } default: { return toReadonlyArray(this)[Symbol.iterator]() } } }, pipe<A>(this: Chunk<A>) { return pipeArguments(this, arguments) }}
const makeChunk = <A>(backing: Backing<A>): Chunk<A> => { const chunk = Object.create(ChunkProto) chunk.backing = backing switch (backing._tag) { case "IEmpty": { chunk.length = 0 chunk.depth = 0 chunk.left = chunk chunk.right = chunk break } case "IConcat": { chunk.length = backing.left.length + backing.right.length chunk.depth = 1 + Math.max(backing.left.depth, backing.right.depth) chunk.left = backing.left chunk.right = backing.right break } case "IArray": { chunk.length = backing.array.length chunk.depth = 0 chunk.left = _empty chunk.right = _empty break } case "ISingleton": { chunk.length = 1 chunk.depth = 0 chunk.left = _empty chunk.right = _empty break } case "ISlice": { chunk.length = backing.length chunk.depth = backing.chunk.depth + 1 chunk.left = _empty chunk.right = _empty break } } return chunk}
/** * Checks if `u` is a `Chunk<unknown>` * * @category constructors * @since 2.0.0 */export const isChunk: { /** * Checks if `u` is a `Chunk<unknown>` * * @category constructors * @since 2.0.0 */ <A>(u: Iterable<A>): u is Chunk<A> /** * Checks if `u` is a `Chunk<unknown>` * * @category constructors * @since 2.0.0 */ (u: unknown): u is Chunk<unknown>} = (u: unknown): u is Chunk<unknown> => hasProperty(u, TypeId)
const _empty = makeChunk<never>({ _tag: "IEmpty" })
/** * @category constructors * @since 2.0.0 */export const empty: <A = never>() => Chunk<A> = () => _empty
/** * Builds a `NonEmptyChunk` from an non-empty collection of elements. * * @category constructors * @since 2.0.0 */export const make = <As extends readonly [any, ...ReadonlyArray<any>]>(...as: As): NonEmptyChunk<As[number]> => unsafeFromNonEmptyArray(as)
/** * Builds a `NonEmptyChunk` from a single element. * * @category constructors * @since 2.0.0 */export const of = <A>(a: A): NonEmptyChunk<A> => makeChunk({ _tag: "ISingleton", a }) as any
/** * Creates a new `Chunk` from an iterable collection of values. * * @category constructors * @since 2.0.0 */export const fromIterable = <A>(self: Iterable<A>): Chunk<A> => isChunk(self) ? self : unsafeFromArray(RA.fromIterable(self))
const copyToArray = <A>(self: Chunk<A>, array: Array<any>, initial: number): void => { switch (self.backing._tag) { case "IArray": { copy(self.backing.array, 0, array, initial, self.length) break } case "IConcat": { copyToArray(self.left, array, initial) copyToArray(self.right, array, initial + self.left.length) break } case "ISingleton": { array[initial] = self.backing.a break } case "ISlice": { let i = 0 let j = initial while (i < self.length) { array[j] = unsafeGet(self, i) i += 1 j += 1 } break } }}
const toArray_ = <A>(self: Chunk<A>): Array<A> => toReadonlyArray(self).slice()
/** * Converts a `Chunk` into an `Array`. If the provided `Chunk` is non-empty * (`NonEmptyChunk`), the function will return a `NonEmptyArray`, ensuring the * non-empty property is preserved. * * @category conversions * @since 2.0.0 */export const toArray: <S extends Chunk<any>>( self: S) => S extends NonEmptyChunk<any> ? RA.NonEmptyArray<Chunk.Infer<S>> : Array<Chunk.Infer<S>> = toArray_ as any
const toReadonlyArray_ = <A>(self: Chunk<A>): ReadonlyArray<A> => { switch (self.backing._tag) { case "IEmpty": { return emptyArray } case "IArray": { return self.backing.array } default: { const arr = new Array<A>(self.length) copyToArray(self, arr, 0) self.backing = { _tag: "IArray", array: arr } self.left = _empty self.right = _empty self.depth = 0 return arr } }}
/** * Converts a `Chunk` into a `ReadonlyArray`. If the provided `Chunk` is * non-empty (`NonEmptyChunk`), the function will return a * `NonEmptyReadonlyArray`, ensuring the non-empty property is preserved. * * @category conversions * @since 2.0.0 */export const toReadonlyArray: <S extends Chunk<any>>( self: S) => S extends NonEmptyChunk<any> ? RA.NonEmptyReadonlyArray<Chunk.Infer<S>> : ReadonlyArray<Chunk.Infer<S>> = toReadonlyArray_ as any
const reverseChunk = <A>(self: Chunk<A>): Chunk<A> => { switch (self.backing._tag) { case "IEmpty": case "ISingleton": return self case "IArray": { return makeChunk({ _tag: "IArray", array: RA.reverse(self.backing.array) }) } case "IConcat": { return makeChunk({ _tag: "IConcat", left: reverse(self.backing.right), right: reverse(self.backing.left) }) } case "ISlice": return unsafeFromArray(RA.reverse(toReadonlyArray(self))) }}
/** * Reverses the order of elements in a `Chunk`. * Importantly, if the input chunk is a `NonEmptyChunk`, the reversed chunk will also be a `NonEmptyChunk`. * * **Example** * * ```ts * import { Chunk } from "effect" * * const chunk = Chunk.make(1, 2, 3) * const result = Chunk.reverse(chunk) * * console.log(result) * // { _id: 'Chunk', values: [ 3, 2, 1 ] } * ``` * * @since 2.0.0 * @category elements */export const reverse: <S extends Chunk<any>>(self: S) => Chunk.With<S, Chunk.Infer<S>> = reverseChunk as any
/** * This function provides a safe way to read a value at a particular index from a `Chunk`. * * @category elements * @since 2.0.0 */export const get: { /** * This function provides a safe way to read a value at a particular index from a `Chunk`. * * @category elements * @since 2.0.0 */ (index: number): <A>(self: Chunk<A>) => Option<A> /** * This function provides a safe way to read a value at a particular index from a `Chunk`. * * @category elements * @since 2.0.0 */ <A>(self: Chunk<A>, index: number): Option<A>} = dual( 2, <A>(self: Chunk<A>, index: number): Option<A> => index < 0 || index >= self.length ? O.none() : O.some(unsafeGet(self, index)))
/** * Wraps an array into a chunk without copying, unsafe on mutable arrays * * @since 2.0.0 * @category unsafe */export const unsafeFromArray = <A>(self: ReadonlyArray<A>): Chunk<A> => self.length === 0 ? empty() : self.length === 1 ? of(self[0]) : makeChunk({ _tag: "IArray", array: self })
/** * Wraps an array into a chunk without copying, unsafe on mutable arrays * * @since 2.0.0 * @category unsafe */export const unsafeFromNonEmptyArray = <A>(self: NonEmptyReadonlyArray<A>): NonEmptyChunk<A> => unsafeFromArray(self) as any
/** * Gets an element unsafely, will throw on out of bounds * * @since 2.0.0 * @category unsafe */export const unsafeGet: { /** * Gets an element unsafely, will throw on out of bounds * * @since 2.0.0 * @category unsafe */ (index: number): <A>(self: Chunk<A>) => A /** * Gets an element unsafely, will throw on out of bounds * * @since 2.0.0 * @category unsafe */ <A>(self: Chunk<A>, index: number): A} = dual(2, <A>(self: Chunk<A>, index: number): A => { switch (self.backing._tag) { case "IEmpty": { throw new Error(`Index out of bounds`) } case "ISingleton": { if (index !== 0) { throw new Error(`Index out of bounds`) } return self.backing.a } case "IArray": { if (index >= self.length || index < 0) { throw new Error(`Index out of bounds`) } return self.backing.array[index]! } case "IConcat": { return index < self.left.length ? unsafeGet(self.left, index) : unsafeGet(self.right, index - self.left.length) } case "ISlice": { return unsafeGet(self.backing.chunk, index + self.backing.offset) } }})
/** * Appends the specified element to the end of the `Chunk`. * * @category concatenating * @since 2.0.0 */export const append: { /** * Appends the specified element to the end of the `Chunk`. * * @category concatenating * @since 2.0.0 */ <A2>(a: A2): <A>(self: Chunk<A>) => NonEmptyChunk<A2 | A> /** * Appends the specified element to the end of the `Chunk`. * * @category concatenating * @since 2.0.0 */ <A, A2>(self: Chunk<A>, a: A2): NonEmptyChunk<A | A2>} = dual(2, <A, A2>(self: Chunk<A>, a: A2): NonEmptyChunk<A | A2> => appendAll(self, of(a)))
/** * Prepend an element to the front of a `Chunk`, creating a new `NonEmptyChunk`. * * @category concatenating * @since 2.0.0 */export const prepend: { /** * Prepend an element to the front of a `Chunk`, creating a new `NonEmptyChunk`. * * @category concatenating * @since 2.0.0 */ <B>(elem: B): <A>(self: Chunk<A>) => NonEmptyChunk<B | A> /** * Prepend an element to the front of a `Chunk`, creating a new `NonEmptyChunk`. * * @category concatenating * @since 2.0.0 */ <A, B>(self: Chunk<A>, elem: B): NonEmptyChunk<A | B>} = dual(2, <A, B>(self: Chunk<A>, elem: B): NonEmptyChunk<A | B> => appendAll(of(elem), self))
/** * Takes the first up to `n` elements from the chunk * * @since 2.0.0 */export const take: { /** * Takes the first up to `n` elements from the chunk * * @since 2.0.0 */ (n: number): <A>(self: Chunk<A>) => Chunk<A> /** * Takes the first up to `n` elements from the chunk * * @since 2.0.0 */ <A>(self: Chunk<A>, n: number): Chunk<A>} = dual(2, <A>(self: Chunk<A>, n: number): Chunk<A> => { if (n <= 0) { return _empty } else if (n >= self.length) { return self } else { switch (self.backing._tag) { case "ISlice": { return makeChunk({ _tag: "ISlice", chunk: self.backing.chunk, length: n, offset: self.backing.offset }) } case "IConcat": { if (n > self.left.length) { return makeChunk({ _tag: "IConcat", left: self.left, right: take(self.right, n - self.left.length) }) }
return take(self.left, n) } default: { return makeChunk({ _tag: "ISlice", chunk: self, offset: 0, length: n }) } } }})
/** * Drops the first up to `n` elements from the chunk * * @since 2.0.0 */export const drop: { /** * Drops the first up to `n` elements from the chunk * * @since 2.0.0 */ (n: number): <A>(self: Chunk<A>) => Chunk<A> /** * Drops the first up to `n` elements from the chunk * * @since 2.0.0 */ <A>(self: Chunk<A>, n: number): Chunk<A>} = dual(2, <A>(self: Chunk<A>, n: number): Chunk<A> => { if (n <= 0) { return self } else if (n >= self.length) { return _empty } else { switch (self.backing._tag) { case "ISlice": { return makeChunk({ _tag: "ISlice", chunk: self.backing.chunk, offset: self.backing.offset + n, length: self.backing.length - n }) } case "IConcat": { if (n > self.left.length) { return drop(self.right, n - self.left.length) } return makeChunk({ _tag: "IConcat", left: drop(self.left, n), right: self.right }) } default: { return makeChunk({ _tag: "ISlice", chunk: self, offset: n, length: self.length - n }) } } }})
/** * Drops the last `n` elements. * * @since 2.0.0 */export const dropRight: { /** * Drops the last `n` elements. * * @since 2.0.0 */ (n: number): <A>(self: Chunk<A>) => Chunk<A> /** * Drops the last `n` elements. * * @since 2.0.0 */ <A>(self: Chunk<A>, n: number): Chunk<A>} = dual(2, <A>(self: Chunk<A>, n: number): Chunk<A> => take(self, Math.max(0, self.length - n)))
/** * Drops all elements so long as the predicate returns true. * * @since 2.0.0 */export const dropWhile: { /** * Drops all elements so long as the predicate returns true. * * @since 2.0.0 */ <A>(predicate: Predicate<NoInfer<A>>): (self: Chunk<A>) => Chunk<A> /** * Drops all elements so long as the predicate returns true. * * @since 2.0.0 */ <A>(self: Chunk<A>, predicate: Predicate<A>): Chunk<A>} = dual(2, <A>(self: Chunk<A>, predicate: Predicate<A>): Chunk<A> => { const arr = toReadonlyArray(self) const len = arr.length let i = 0 while (i < len && predicate(arr[i]!)) { i++ } return drop(self, i)})
/** * Prepends the specified prefix chunk to the beginning of the specified chunk. * If either chunk is non-empty, the result is also a non-empty chunk. * * **Example** * * ```ts * import { Chunk } from "effect" * * const result = Chunk.make(1, 2).pipe(Chunk.prependAll(Chunk.make("a", "b")), Chunk.toArray) * * console.log(result) * // [ "a", "b", 1, 2 ] * ``` * * @category concatenating * @since 2.0.0 */export const prependAll: { /** * Prepends the specified prefix chunk to the beginning of the specified chunk. * If either chunk is non-empty, the result is also a non-empty chunk. * * **Example** * * ```ts * import { Chunk } from "effect" * * const result = Chunk.make(1, 2).pipe(Chunk.prependAll(Chunk.make("a", "b")), Chunk.toArray) * * console.log(result) * // [ "a", "b", 1, 2 ] * ``` * * @category concatenating * @since 2.0.0 */ <S extends Chunk<any>, T extends Chunk<any>>(that: T): (self: S) => Chunk.OrNonEmpty<S, T, Chunk.Infer<S> | Chunk.Infer<T>> /** * Prepends the specified prefix chunk to the beginning of the specified chunk. * If either chunk is non-empty, the result is also a non-empty chunk. * * **Example** * * ```ts * import { Chunk } from "effect" * * const result = Chunk.make(1, 2).pipe(Chunk.prependAll(Chunk.make("a", "b")), Chunk.toArray) * * console.log(result) * // [ "a", "b", 1, 2 ] * ``` * * @category concatenating * @since 2.0.0 */ <A, B>(self: Chunk<A>, that: NonEmptyChunk<B>): NonEmptyChunk<A | B> /** * Prepends the specified prefix chunk to the beginning of the specified chunk. * If either chunk is non-empty, the result is also a non-empty chunk. * * **Example** * * ```ts * import { Chunk } from "effect" * * const result = Chunk.make(1, 2).pipe(Chunk.prependAll(Chunk.make("a", "b")), Chunk.toArray) * * console.log(result) * // [ "a", "b", 1, 2 ] * ``` * * @category concatenating * @since 2.0.0 */ <A, B>(self: NonEmptyChunk<A>, that: Chunk<B>): NonEmptyChunk<A | B> /** * Prepends the specified prefix chunk to the beginning of the specified chunk. * If either chunk is non-empty, the result is also a non-empty chunk. * * **Example** * * ```ts * import { Chunk } from "effect" * * const result = Chunk.make(1, 2).pipe(Chunk.prependAll(Chunk.make("a", "b")), Chunk.toArray) * * console.log(result) * // [ "a", "b", 1, 2 ] * ``` * * @category concatenating * @since 2.0.0 */ <A, B>(self: Chunk<A>, that: Chunk<B>): Chunk<A | B>} = dual(2, <A, B>(self: NonEmptyChunk<A>, that: Chunk<B>): Chunk<A | B> => appendAll(that, self))
/** * Concatenates two chunks, combining their elements. * If either chunk is non-empty, the result is also a non-empty chunk. * * **Example** * * ```ts * import { Chunk } from "effect" * * const result = Chunk.make(1, 2).pipe(Chunk.appendAll(Chunk.make("a", "b")), Chunk.toArray) * * console.log(result) * // [ 1, 2, "a", "b" ] * ``` * * @category concatenating * @since 2.0.0 */export const appendAll: { /** * Concatenates two chunks, combining their elements. * If either chunk is non-empty, the result is also a non-empty chunk. * * **Example** * * ```ts * import { Chunk } from "effect" * * const result = Chunk.make(1, 2).pipe(Chunk.appendAll(Chunk.make("a", "b")), Chunk.toArray) * * console.log(result) * // [ 1, 2, "a", "b" ] * ``` * * @category concatenating * @since 2.0.0 */ <S extends Chunk<any>, T extends Chunk<any>>(that: T): (self: S) => Chunk.OrNonEmpty<S, T, Chunk.Infer<S> | Chunk.Infer<T>> /** * Concatenates two chunks, combining their elements. * If either chunk is non-empty, the result is also a non-empty chunk. * * **Example** * * ```ts * import { Chunk } from "effect" * * const result = Chunk.make(1, 2).pipe(Chunk.appendAll(Chunk.make("a", "b")), Chunk.toArray) * * console.log(result) * // [ 1, 2, "a", "b" ] * ``` * * @category concatenating * @since 2.0.0 */ <A, B>(self: Chunk<A>, that: NonEmptyChunk<B>): NonEmptyChunk<A | B> /** * Concatenates two chunks, combining their elements. * If either chunk is non-empty, the result is also a non-empty chunk. * * **Example** * * ```ts * import { Chunk } from "effect" * * const result = Chunk.make(1, 2).pipe(Chunk.appendAll(Chunk.make("a", "b")), Chunk.toArray) * * console.log(result) * // [ 1, 2, "a", "b" ] * ``` * * @category concatenating * @since 2.0.0 */ <A, B>(self: NonEmptyChunk<A>, that: Chunk<B>): NonEmptyChunk<A | B> /** * Concatenates two chunks, combining their elements. * If either chunk is non-empty, the result is also a non-empty chunk. * * **Example** * * ```ts * import { Chunk } from "effect" * * const result = Chunk.make(1, 2).pipe(Chunk.appendAll(Chunk.make("a", "b")), Chunk.toArray) * * console.log(result) * // [ 1, 2, "a", "b" ] * ``` * * @category concatenating * @since 2.0.0 */ <A, B>(self: Chunk<A>, that: Chunk<B>): Chunk<A | B>} = dual(2, <A, B>(self: Chunk<A>, that: Chunk<B>): Chunk<A | B> => { if (self.backing._tag === "IEmpty") { return that } if (that.backing._tag === "IEmpty") { return self } const diff = that.depth - self.depth if (Math.abs(diff) <= 1) { return makeChunk</** * Concatenates two chunks, combining their elements. * If either chunk is non-empty, the result is also a non-empty chunk. * * **Example** * * ```ts * import { Chunk } from "effect" * * const result = Chunk.make(1, 2).pipe(Chunk.appendAll(Chunk.make("a", "b")), Chunk.toArray) * * console.log(result) * // [ 1, 2, "a", "b" ] * ``` * * @category concatenating * @since 2.0.0 */ A | B>({ _tag: "IConcat", left: self, right: that }); } else if (diff < -1) { if (self.left.depth >= self.right.depth) { const nr = appendAll(self.right, that) return makeChunk({ _tag: "IConcat", left: self.left, right: nr }) } else { const nrr = appendAll(self.right.right, that) if (nrr.depth === self.depth - 3) { const nr = makeChunk({ _tag: "IConcat", left: self.right.left, right: nrr }) return makeChunk({ _tag: "IConcat", left: self.left, right: nr }) } else { const nl = makeChunk({ _tag: "IConcat", left: self.left, right: self.right.left }) return makeChunk({ _tag: "IConcat", left: nl, right: nrr }) } } } else { if (that.right.depth >= that.left.depth) { const nl = appendAll(self, that.left) return makeChunk({ _tag: "IConcat", left: nl, right: that.right }) } else { const nll = appendAll(self, that.left.left) if (nll.depth === that.depth - 3) { const nl = makeChunk({ _tag: "IConcat", left: nll, right: that.left.right }) return makeChunk({ _tag: "IConcat", left: nl, right: that.right }) } else { const nr = makeChunk({ _tag: "IConcat", left: that.left.right, right: that.right }) return makeChunk({ _tag: "IConcat", left: nll, right: nr }) } } }})
/** * Returns a filtered and mapped subset of the elements. * * @since 2.0.0 * @category filtering */export const filterMap: { /** * Returns a filtered and mapped subset of the elements. * * @since 2.0.0 * @category filtering */ <A, B>(f: (a: A, i: number) => Option<B>): (self: Chunk<A>) => Chunk<B> /** * Returns a filtered and mapped subset of the elements. * * @since 2.0.0 * @category filtering */ <A, B>(self: Chunk<A>, f: (a: A, i: number) => Option<B>): Chunk<B>} = dual( 2, <A, B>(self: Chunk<A>, f: (a: A, i: number) => Option<B>): Chunk<B> => unsafeFromArray(RA.filterMap(self, f)))
/** * Returns a filtered and mapped subset of the elements. * * @since 2.0.0 * @category filtering */export const filter: { /** * Returns a filtered and mapped subset of the elements. * * @since 2.0.0 * @category filtering */ <A, B extends A>(refinement: Refinement<NoInfer<A>, B>): (self: Chunk<A>) => Chunk<B> /** * Returns a filtered and mapped subset of the elements. * * @since 2.0.0 * @category filtering */ <A>(predicate: Predicate<NoInfer<A>>): (self: Chunk<A>) => Chunk<A> /** * Returns a filtered and mapped subset of the elements. * * @since 2.0.0 * @category filtering */ <A, B extends A>(self: Chunk<A>, refinement: Refinement<A, B>): Chunk<B> /** * Returns a filtered and mapped subset of the elements. * * @since 2.0.0 * @category filtering */ <A>(self: Chunk<A>, predicate: Predicate<A>): Chunk<A>} = dual( 2, <A>(self: Chunk<A>, predicate: Predicate<A>): Chunk<A> => unsafeFromArray(RA.filter(self, predicate)))
/** * Transforms all elements of the chunk for as long as the specified function returns some value * * @since 2.0.0 * @category filtering */export const filterMapWhile: { /** * Transforms all elements of the chunk for as long as the specified function returns some value * * @since 2.0.0 * @category filtering */ <A, B>(f: (a: A) => Option<B>): (self: Chunk<A>) => Chunk<B> /** * Transforms all elements of the chunk for as long as the specified function returns some value * * @since 2.0.0 * @category filtering */ <A, B>(self: Chunk<A>, f: (a: A) => Option<B>): Chunk<B>} = dual(2, <A, B>(self: Chunk<A>, f: (a: A) => Option<B>) => unsafeFromArray(RA.filterMapWhile(self, f)))
/** * Filter out optional values * * @since 2.0.0 * @category filtering */export const compact = <A>(self: Chunk<Option<A>>): Chunk<A> => filterMap(self, identity)
/** * Applies a function to each element in a chunk and returns a new chunk containing the concatenated mapped elements. * * @since 2.0.0 * @category sequencing */export const flatMap: { /** * Applies a function to each element in a chunk and returns a new chunk containing the concatenated mapped elements. * * @since 2.0.0 * @category sequencing */ <S extends Chunk<any>, T extends Chunk<any>>(f: (a: Chunk.Infer<S>, i: number) => T): (self: S) => Chunk.AndNonEmpty<S, T, Chunk.Infer<T>> /** * Applies a function to each element in a chunk and returns a new chunk containing the concatenated mapped elements. * * @since 2.0.0 * @category sequencing */ <A, B>(self: NonEmptyChunk<A>, f: (a: A, i: number) => NonEmptyChunk<B>): NonEmptyChunk<B> /** * Applies a function to each element in a chunk and returns a new chunk containing the concatenated mapped elements. * * @since 2.0.0 * @category sequencing */ <A, B>(self: Chunk<A>, f: (a: A, i: number) => Chunk<B>): Chunk<B>} = dual(2, <A, B>(self: Chunk<A>, f: (a: A, i: number) => Chunk<B>) => { if (self.backing._tag === "ISingleton") { return f(self.backing.a, 0) } let out: Chunk<B> = _empty let i = 0 for (const k of self) { out = appendAll(out, f(k, i++)) } return out})
/** * Iterates over each element of a `Chunk` and applies a function to it. * * **Details** * * This function processes every element of the given `Chunk`, calling the * provided function `f` on each element. It does not return a new value; * instead, it is primarily used for side effects, such as logging or * accumulating data in an external variable. * * @since 2.0.0 * @category combinators */export const forEach: { /** * Iterates over each element of a `Chunk` and applies a function to it. * * **Details** * * This function processes every element of the given `Chunk`, calling the * provided function `f` on each element. It does not return a new value; * instead, it is primarily used for side effects, such as logging or * accumulating data in an external variable. * * @since 2.0.0 * @category combinators */ <A, B>(f: (a: A, index: number) => B): (self: Chunk<A>) => void /** * Iterates over each element of a `Chunk` and applies a function to it. * * **Details** * * This function processes every element of the given `Chunk`, calling the * provided function `f` on each element. It does not return a new value; * instead, it is primarily used for side effects, such as logging or * accumulating data in an external variable. * * @since 2.0.0 * @category combinators */ <A, B>(self: Chunk<A>, f: (a: A, index: number) => B): void} = dual(2, <A, B>(self: Chunk<A>, f: (a: A) => B): void => toReadonlyArray(self).forEach(f))
/** * Flattens a chunk of chunks into a single chunk by concatenating all chunks. * * @since 2.0.0 * @category sequencing */export const flatten: <S extends Chunk<Chunk<any>>>(self: S) => Chunk.Flatten<S> = flatMap(identity) as any
/** * Groups elements in chunks of up to `n` elements. * * @since 2.0.0 * @category elements */export const chunksOf: { /** * Groups elements in chunks of up to `n` elements. * * @since 2.0.0 * @category elements */ (n: number): <A>(self: Chunk<A>) => Chunk<Chunk<A>> /** * Groups elements in chunks of up to `n` elements. * * @since 2.0.0 * @category elements */ <A>(self: Chunk<A>, n: number): Chunk<Chunk<A>>} = dual(2, <A>(self: Chunk<A>, n: number) => { const gr: Array<Chunk<A>> = [] let current: Array<A> = [] toReadonlyArray(self).forEach((a) => { current.push(a) if (current.length >= n) { gr.push(unsafeFromArray(current)) current = [] } }) if (current.length > 0) { gr.push(unsafeFromArray(current)) } return unsafeFromArray(gr)})
/** * Creates a Chunk of unique values that are included in all given Chunks. * * The order and references of result values are determined by the Chunk. * * @since 2.0.0 * @category elements */export const intersection: { /** * Creates a Chunk of unique values that are included in all given Chunks. * * The order and references of result values are determined by the Chunk. * * @since 2.0.0 * @category elements */ <A>(that: Chunk<A>): <B>(self: Chunk<B>) => Chunk<A & B> /** * Creates a Chunk of unique values that are included in all given Chunks. * * The order and references of result values are determined by the Chunk. * * @since 2.0.0 * @category elements */ <A, B>(self: Chunk<A>, that: Chunk<B>): Chunk<A & B>} = dual( 2, <A, B>(self: Chunk<A>, that: Chunk<B>): Chunk<A & B> => unsafeFromArray(RA.intersection(toReadonlyArray(self), toReadonlyArray(that))))
/** * Determines if the chunk is empty. * * @since 2.0.0 * @category elements */export const isEmpty = <A>(self: Chunk<A>): boolean => self.length === 0
/** * Determines if the chunk is not empty. * * @since 2.0.0 * @category elements */export const isNonEmpty = <A>(self: Chunk<A>): self is NonEmptyChunk<A> => self.length > 0
/** * Returns the first element of this chunk if it exists. * * @since 2.0.0 * @category elements */export const head: <A>(self: Chunk<A>) => Option<A> = get(0)
/** * Returns the first element of this chunk. * * It will throw an error if the chunk is empty. * * @since 2.0.0 * @category unsafe */export const unsafeHead = <A>(self: Chunk<A>): A => unsafeGet(self, 0)
/** * Returns the first element of this non empty chunk. * * @since 2.0.0 * @category elements */export const headNonEmpty: <A>(self: NonEmptyChunk<A>) => A = unsafeHead
/** * Returns the last element of this chunk if it exists. * * @since 2.0.0 * @category elements */export const last = <A>(self: Chunk<A>): Option<A> => get(self, self.length - 1)
/** * Returns the last element of this chunk. * * It will throw an error if the chunk is empty. * * @since 2.0.0 * @category unsafe */export const unsafeLast = <A>(self: Chunk<A>): A => unsafeGet(self, self.length - 1)
/** * Returns the last element of this non empty chunk. * * @since 3.4.0 * @category elements */export const lastNonEmpty: <A>(self: NonEmptyChunk<A>) => A = unsafeLast
/** * @since 2.0.0 */export declare namespace Chunk { /** * @since 2.0.0 */ export type Infer<S extends Chunk<any>> = S extends Chunk<infer A> ? A : never
/** * @since 2.0.0 */ export type With<S extends Chunk<any>, A> = S extends NonEmptyChunk<any> ? NonEmptyChunk<A> : Chunk<A>
/** * @since 2.0.0 */ export type OrNonEmpty<S extends Chunk<any>, T extends Chunk<any>, A> = S extends NonEmptyChunk<any> ? NonEmptyChunk<A> : T extends NonEmptyChunk<any> ? NonEmptyChunk<A> : Chunk<A>
/** * @since 2.0.0 */ export type AndNonEmpty<S extends Chunk<any>, T extends Chunk<any>, A> = S extends NonEmptyChunk<any> ? T extends NonEmptyChunk<any> ? NonEmptyChunk<A> : Chunk<A> : Chunk<A>
/** * @since 2.0.0 */ export type Flatten<T extends Chunk<Chunk<any>>> = T extends NonEmptyChunk<NonEmptyChunk<infer A>> ? NonEmptyChunk<A> : T extends Chunk<Chunk<infer A>> ? Chunk<A> : never}
/** * Transforms the elements of a chunk using the specified mapping function. * If the input chunk is non-empty, the resulting chunk will also be non-empty. * * **Example** * * ```ts * import { Chunk } from "effect" * * const result = Chunk.map(Chunk.make(1, 2), (n) => n + 1) * * console.log(result) * // { _id: 'Chunk', values: [ 2, 3 ] } * ``` * * @since 2.0.0 * @category mapping */export const map: { /** * Transforms the elements of a chunk using the specified mapping function. * If the input chunk is non-empty, the resulting chunk will also be non-empty. * * **Example** * * ```ts * import { Chunk } from "effect" * * const result = Chunk.map(Chunk.make(1, 2), (n) => n + 1) * * console.log(result) * // { _id: 'Chunk', values: [ 2, 3 ] } * ``` * * @since 2.0.0 * @category mapping */ <S extends Chunk<any>, B>(f: (a: Chunk.Infer<S>, i: number) => B): (self: S) => Chunk.With<S, B> /** * Transforms the elements of a chunk using the specified mapping function. * If the input chunk is non-empty, the resulting chunk will also be non-empty. * * **Example** * * ```ts * import { Chunk } from "effect" * * const result = Chunk.map(Chunk.make(1, 2), (n) => n + 1) * * console.log(result) * // { _id: 'Chunk', values: [ 2, 3 ] } * ``` * * @since 2.0.0 * @category mapping */ <A, B>(self: NonEmptyChunk<A>, f: (a: A, i: number) => B): NonEmptyChunk<B> /** * Transforms the elements of a chunk using the specified mapping function. * If the input chunk is non-empty, the resulting chunk will also be non-empty. * * **Example** * * ```ts * import { Chunk } from "effect" * * const result = Chunk.map(Chunk.make(1, 2), (n) => n + 1) * * console.log(result) * // { _id: 'Chunk', values: [ 2, 3 ] } * ``` * * @since 2.0.0 * @category mapping */ <A, B>(self: Chunk<A>, f: (a: A, i: number) => B): Chunk<B>} = dual(2, <A, B>(self: Chunk<A>, f: (a: A, i: number) => B): Chunk<B> => self.backing._tag === "ISingleton" ? of(f(self.backing.a, 0)) : unsafeFromArray(pipe(toReadonlyArray(self), RA.map((a, i) => f(a, i)))))
/** * Statefully maps over the chunk, producing new elements of type `B`. * * @since 2.0.0 * @category folding */export const mapAccum: { /** * Statefully maps over the chunk, producing new elements of type `B`. * * @since 2.0.0 * @category folding */ <S, A, B>(s: S, f: (s: S, a: A) => readonly [S, B]): (self: Chunk<A>) => [S, Chunk<B>] /** * Statefully maps over the chunk, producing new elements of type `B`. * * @since 2.0.0 * @category folding */ <S, A, B>(self: Chunk<A>, s: S, f: (s: S, a: A) => readonly [S, B]): [S, Chunk<B>]} = dual(3, <S, A, B>(self: Chunk<A>, s: S, f: (s: S, a: A) => readonly [S, B]): [S, Chunk<B>] => { const [s1, as] = RA.mapAccum(self, s, f) return [s1, unsafeFromArray(as)]})
/** * Separate elements based on a predicate that also exposes the index of the element. * * @category filtering * @since 2.0.0 */export const partition: { /** * Separate elements based on a predicate that also exposes the index of the element. * * @category filtering * @since 2.0.0 */ <A, B extends A>(refinement: (a: NoInfer<A>, i: number) => a is B): (self: Chunk<A>) => [excluded: Chunk<Exclude<A, B>>, satisfying: Chunk<B>] /** * Separate elements based on a predicate that also exposes the index of the element. * * @category filtering * @since 2.0.0 */ <A>(predicate: (a: NoInfer<A>, i: number) => boolean): (self: Chunk<A>) => [excluded: Chunk<A>, satisfying: Chunk<A>] /** * Separate elements based on a predicate that also exposes the index of the element. * * @category filtering * @since 2.0.0 */ <A, B extends A>(self: Chunk<A>, refinement: (a: A, i: number) => a is B): [excluded: Chunk<Exclude<A, B>>, satisfying: Chunk<B>] /** * Separate elements based on a predicate that also exposes the index of the element. * * @category filtering * @since 2.0.0 */ <A>(self: Chunk<A>, predicate: (a: A, i: number) => boolean): [excluded: Chunk<A>, satisfying: Chunk<A>]} = dual( 2, <A>(self: Chunk<A>, predicate: (a: A, i: number) => boolean): [excluded: Chunk<A>, satisfying: Chunk<A>] => pipe( RA.partition(toReadonlyArray(self), predicate), ([l, r]) => [unsafeFromArray(l), unsafeFromArray(r)] ))
/** * Partitions the elements of this chunk into two chunks using f. * * @category filtering * @since 2.0.0 */export const partitionMap: { /** * Partitions the elements of this chunk into two chunks using f. * * @category filtering * @since 2.0.0 */ <A, B, C>(f: (a: A) => Either<C, B>): (self: Chunk<A>) => [left: Chunk<B>, right: Chunk<C>] /** * Partitions the elements of this chunk into two chunks using f. * * @category filtering * @since 2.0.0 */ <A, B, C>(self: Chunk<A>, f: (a: A) => Either<C, B>): [left: Chunk<B>, right: Chunk<C>]} = dual(2, <A, B, C>(self: Chunk<A>, f: (a: A) => Either<C, B>): [left: Chunk<B>, right: Chunk<C>] => pipe( RA.partitionMap(toReadonlyArray(self), f), ([l, r]) => [unsafeFromArray(l), unsafeFromArray(r)] ))
/** * Partitions the elements of this chunk into two chunks. * * @category filtering * @since 2.0.0 */export const separate = <A, B>(self: Chunk<Either<B, A>>): [Chunk<A>, Chunk<B>] => pipe( RA.separate(toReadonlyArray(self)), ([l, r]) => [unsafeFromArray(l), unsafeFromArray(r)] )
/** * Retireves the size of the chunk * * @since 2.0.0 * @category elements */export const size = <A>(self: Chunk<A>): number => self.length
/** * Sort the elements of a Chunk in increasing order, creating a new Chunk. * * @since 2.0.0 * @category sorting */export const sort: { /** * Sort the elements of a Chunk in increasing order, creating a new Chunk. * * @since 2.0.0 * @category sorting */ <B>(O: Order.Order<B>): <A extends B>(self: Chunk<A>) => Chunk<A> /** * Sort the elements of a Chunk in increasing order, creating a new Chunk. * * @since 2.0.0 * @category sorting */ <A extends B, B>(self: Chunk<A>, O: Order.Order<B>): Chunk<A>} = dual( 2, <A extends B, B>(self: Chunk<A>, O: Order.Order<B>): Chunk<A> => unsafeFromArray(RA.sort(toReadonlyArray(self), O)))
/** * @since 2.0.0 * @category sorting */export const sortWith: { /** * @since 2.0.0 * @category sorting */ <A, B>(f: (a: A) => B, order: Order.Order<B>): (self: Chunk<A>) => Chunk<A> /** * @since 2.0.0 * @category sorting */ <A, B>(self: Chunk<A>, f: (a: A) => B, order: Order.Order<B>): Chunk<A>} = dual( 3, <A, B>(self: Chunk<A>, f: (a: A) => B, order: Order.Order<B>): Chunk<A> => sort(self, Order.mapInput(order, f)))
/** * Returns two splits of this chunk at the specified index. * * @since 2.0.0 * @category splitting */export const splitAt: { /** * Returns two splits of this chunk at the specified index. * * @since 2.0.0 * @category splitting */ (n: number): <A>(self: Chunk<A>) => [beforeIndex: Chunk<A>, fromIndex: Chunk<A>] /** * Returns two splits of this chunk at the specified index. * * @since 2.0.0 * @category splitting */ <A>(self: Chunk<A>, n: number): [beforeIndex: Chunk<A>, fromIndex: Chunk<A>]} = dual(2, <A>(self: Chunk<A>, n: number): [Chunk<A>, Chunk<A>] => [take(self, n), drop(self, n)])
/** * Splits a `NonEmptyChunk` into two segments, with the first segment containing a maximum of `n` elements. * The value of `n` must be `>= 1`. * * @category splitting * @since 2.0.0 */export const splitNonEmptyAt: { /** * Splits a `NonEmptyChunk` into two segments, with the first segment containing a maximum of `n` elements. * The value of `n` must be `>= 1`. * * @category splitting * @since 2.0.0 */ (n: number): <A>(self: NonEmptyChunk<A>) => [beforeIndex: NonEmptyChunk<A>, fromIndex: Chunk<A>] /** * Splits a `NonEmptyChunk` into two segments, with the first segment containing a maximum of `n` elements. * The value of `n` must be `>= 1`. * * @category splitting * @since 2.0.0 */ <A>(self: NonEmptyChunk<A>, n: number): [beforeIndex: NonEmptyChunk<A>, fromIndex: Chunk<A>]} = dual(2, <A>(self: NonEmptyChunk<A>, n: number): [Chunk<A>, Chunk<A>] => { const _n = Math.max(1, Math.floor(n)) return _n >= self.length ? [self, empty()] : [take(self, _n), drop(self, _n)]})
/** * Splits this chunk into `n` equally sized chunks. * * @since 2.0.0 * @category splitting */export const split: { /** * Splits this chunk into `n` equally sized chunks. * * @since 2.0.0 * @category splitting */ (n: number): <A>(self: Chunk<A>) => Chunk<Chunk<A>> /** * Splits this chunk into `n` equally sized chunks. * * @since 2.0.0 * @category splitting */ <A>(self: Chunk<A>, n: number): Chunk<Chunk<A>>} = dual(2, <A>(self: Chunk<A>, n: number) => chunksOf(self, Math.ceil(self.length / Math.floor(n))))
/** * Splits this chunk on the first element that matches this predicate. * Returns a tuple containing two chunks: the first one is before the match, and the second one is from the match onward. * * @category splitting * @since 2.0.0 */export const splitWhere: { /** * Splits this chunk on the first element that matches this predicate. * Returns a tuple containing two chunks: the first one is before the match, and the second one is from the match onward. * * @category splitting * @since 2.0.0 */ <A>(predicate: Predicate<NoInfer<A>>): (self: Chunk<A>) => [beforeMatch: Chunk<A>, fromMatch: Chunk<A>] /** * Splits this chunk on the first element that matches this predicate. * Returns a tuple containing two chunks: the first one is before the match, and the second one is from the match onward. * * @category splitting * @since 2.0.0 */ <A>(self: Chunk<A>, predicate: Predicate<A>): [beforeMatch: Chunk<A>, fromMatch: Chunk<A>]} = dual(2, <A>(self: Chunk<A>, predicate: Predicate<A>): [beforeMatch: Chunk<A>, fromMatch: Chunk<A>] => { let i = 0 for (const a of toReadonlyArray(self)) { if (predicate(a)) { break } else { i++ } } return splitAt(self, i)})
/** * Returns every elements after the first. * * @since 2.0.0 * @category elements */export const tail = <A>(self: Chunk<A>): Option<Chunk<A>> => self.length > 0 ? O.some(drop(self, 1)) : O.none()
/** * Returns every elements after the first. * * @since 2.0.0 * @category elements */export const tailNonEmpty = <A>(self: NonEmptyChunk<A>): Chunk<A> => drop(self, 1)
/** * Takes the last `n` elements. * * @since 2.0.0 * @category elements */export const takeRight: { /** * Takes the last `n` elements. * * @since 2.0.0 * @category elements */ (n: number): <A>(self: Chunk<A>) => Chunk<A> /** * Takes the last `n` elements. * * @since 2.0.0 * @category elements */ <A>(self: Chunk<A>, n: number): Chunk<A>} = dual(2, <A>(self: Chunk<A>, n: number): Chunk<A> => drop(self, self.length - n))
/** * Takes all elements so long as the predicate returns true. * * @since 2.0.0 * @category elements */export const takeWhile: { /** * Takes all elements so long as the predicate returns true. * * @since 2.0.0 * @category elements */ <A, B extends A>(refinement: Refinement<NoInfer<A>, B>): (self: Chunk<A>) => Chunk<B> /** * Takes all elements so long as the predicate returns true. * * @since 2.0.0 * @category elements */ <A>(predicate: Predicate<NoInfer<A>>): (self: Chunk<A>) => Chunk<A> /** * Takes all elements so long as the predicate returns true. * * @since 2.0.0 * @category elements */ <A, B extends A>(self: Chunk<A>, refinement: Refinement<A, B>): Chunk<B> /** * Takes all elements so long as the predicate returns true. * * @since 2.0.0 * @category elements */ <A>(self: Chunk<A>, predicate: Predicate<A>): Chunk<A>} = dual(2, <A>(self: Chunk<A>, predicate: Predicate<A>): Chunk<A> => { const out: Array<A> = [] for (const a of toReadonlyArray(self)) { if (predicate(a)) { out.push(a) } else { break } } return unsafeFromArray(out)})
/** * Creates a Chunks of unique values, in order, from all given Chunks. * * @since 2.0.0 * @category elements */export const union: { /** * Creates a Chunks of unique values, in order, from all given Chunks. * * @since 2.0.0 * @category elements */ <A>(that: Chunk<A>): <B>(self: Chunk<B>) => Chunk<A | B> /** * Creates a Chunks of unique values, in order, from all given Chunks. * * @since 2.0.0 * @category elements */ <A, B>(self: Chunk<A>, that: Chunk<B>): Chunk<A | B>} = dual( 2, <A, B>(self: Chunk<A>, that: Chunk<B>) => unsafeFromArray(RA.union(toReadonlyArray(self), toReadonlyArray(that))))
/** * Remove duplicates from an array, keeping the first occurrence of an element. * * @since 2.0.0 * @category elements */export const dedupe = <A>(self: Chunk<A>): Chunk<A> => unsafeFromArray(RA.dedupe(toReadonlyArray(self)))
/** * Deduplicates adjacent elements that are identical. * * @since 2.0.0 * @category filtering */export const dedupeAdjacent = <A>(self: Chunk<A>): Chunk<A> => unsafeFromArray(RA.dedupeAdjacent(self))
/** * Takes a `Chunk` of pairs and return two corresponding `Chunk`s. * * Note: The function is reverse of `zip`. * * @since 2.0.0 * @category elements */export const unzip = <A, B>(self: Chunk<readonly [A, B]>): [Chunk<A>, Chunk<B>] => { const [left, right] = RA.unzip(self) return [unsafeFromArray(left), unsafeFromArray(right)]}
/** * Zips this chunk pointwise with the specified chunk using the specified combiner. * * @since 2.0.0 * @category zipping */export const zipWith: { /** * Zips this chunk pointwise with the specified chunk using the specified combiner. * * @since 2.0.0 * @category zipping */ <A, B, C>(that: Chunk<B>, f: (a: A, b: B) => C): (self: Chunk<A>) => Chunk<C> /** * Zips this chunk pointwise with the specified chunk using the specified combiner. * * @since 2.0.0 * @category zipping */ <A, B, C>(self: Chunk<A>, that: Chunk<B>, f: (a: A, b: B) => C): Chunk<C>} = dual( 3, <A, B, C>(self: Chunk<A>, that: Chunk<B>, f: (a: A, b: B) => C): Chunk<C> => unsafeFromArray(RA.zipWith(self, that, f)))
/** * Zips this chunk pointwise with the specified chunk. * * @since 2.0.0 * @category zipping */export const zip: { /** * Zips this chunk pointwise with the specified chunk. * * @since 2.0.0 * @category zipping */ <B>(that: Chunk<B>): <A>(self: Chunk<A>) => Chunk<[A, B]> /** * Zips this chunk pointwise with the specified chunk. * * @since 2.0.0 * @category zipping */ <A, B>(self: Chunk<A>, that: Chunk<B>): Chunk<[A, B]>} = dual( 2, <A, B>(self: Chunk<A>, that: Chunk<B>): Chunk<[A, B]> => zipWith(self, that, (a, b) => [a, b]))
/** * Delete the element at the specified index, creating a new `Chunk`. * * @since 2.0.0 */export const remove: { /** * Delete the element at the specified index, creating a new `Chunk`. * * @since 2.0.0 */ (i: number): <A>(self: Chunk<A>) => Chunk<A> /** * Delete the element at the specified index, creating a new `Chunk`. * * @since 2.0.0 */ <A>(self: Chunk<A>, i: number): Chunk<A>} = dual( 2, <A>(self: Chunk<A>, i: number): Chunk<A> => { if (i < 0 || i >= self.length) return self return unsafeFromArray(RA.remove(toReadonlyArray(self), i)) })
/** * @since 3.16.0 */export const removeOption: { /** * @since 3.16.0 */ (i: number): <A>(self: Chunk<A>) => Option<Chunk<A>> /** * @since 3.16.0 */ <A>(self: Chunk<A>, i: number): Option<Chunk<A>>} = dual( 2, <A>(self: Chunk<A>, i: number): Option<Chunk<A>> => { if (i < 0 || i >= self.length) return O.none() return O.some(unsafeFromArray(RA.remove(toReadonlyArray(self), i))) })
/** * @since 2.0.0 */export const modifyOption: { /** * @since 2.0.0 */ <A, B>(i: number, f: (a: A) => B): (self: Chunk<A>) => Option<Chunk<A | B>> /** * @since 2.0.0 */ <A, B>(self: Chunk<A>, i: number, f: (a: A) => B): Option<Chunk<A | B>>} = dual( 3, <A, B>(self: Chunk<A>, i: number, f: (a: A) => B): Option<Chunk<A | B>> => { if (i < 0 || i >= self.length) return O.none() return O.some(unsafeFromArray(RA.modify(toReadonlyArray(self), i, f))) })
/** * Apply a function to the element at the specified index, creating a new `Chunk`, * or returning the input if the index is out of bounds. * * @since 2.0.0 */export const modify: { /** * Apply a function to the element at the specified index, creating a new `Chunk`, * or returning the input if the index is out of bounds. * * @since 2.0.0 */ <A, B>(i: number, f: (a: A) => B): (self: Chunk<A>) => Chunk<A | B> /** * Apply a function to the element at the specified index, creating a new `Chunk`, * or returning the input if the index is out of bounds. * * @since 2.0.0 */ <A, B>(self: Chunk<A>, i: number, f: (a: A) => B): Chunk<A | B>} = dual( 3, <A, B>(self: Chunk<A>, i: number, f: (a: A) => B): Chunk<A | B> => O.getOrElse(modifyOption(self, i, f), () => self))
/** * Change the element at the specified index, creating a new `Chunk`, * or returning the input if the index is out of bounds. * * @since 2.0.0 */export const replace: { /** * Change the element at the specified index, creating a new `Chunk`, * or returning the input if the index is out of bounds. * * @since 2.0.0 */ <B>(i: number, b: B): <A>(self: Chunk<A>) => Chunk<B | A> /** * Change the element at the specified index, creating a new `Chunk`, * or returning the input if the index is out of bounds. * * @since 2.0.0 */ <A, B>(self: Chunk<A>, i: number, b: B): Chunk<B | A>} = dual(3, <A, B>(self: Chunk<A>, i: number, b: B): Chunk<B | A> => modify(self, i, () => b))
/** * @since 2.0.0 */export const replaceOption: { /** * @since 2.0.0 */ <B>(i: number, b: B): <A>(self: Chunk<A>) => Option<Chunk<B | A>> /** * @since 2.0.0 */ <A, B>(self: Chunk<A>, i: number, b: B): Option<Chunk<B | A>>} = dual(3, <A, B>(self: Chunk<A>, i: number, b: B): Option<Chunk<B | A>> => modifyOption(self, i, () => b))
/** * Return a Chunk of length n with element i initialized with f(i). * * **Note**. `n` is normalized to an integer >= 1. * * @category constructors * @since 2.0.0 */export const makeBy: { /** * Return a Chunk of length n with element i initialized with f(i). * * **Note**. `n` is normalized to an integer >= 1. * * @category constructors * @since 2.0.0 */ <A>(f: (i: number) => A): (n: number) => NonEmptyChunk<A> /** * Return a Chunk of length n with element i initialized with f(i). * * **Note**. `n` is normalized to an integer >= 1. * * @category constructors * @since 2.0.0 */ <A>(n: number, f: (i: number) => A): NonEmptyChunk<A>} = dual(2, (n, f) => fromIterable(RA.makeBy(n, f)))
/** * Create a non empty `Chunk` containing a range of integers, including both endpoints. * * @category constructors * @since 2.0.0 */export const range = (start: number, end: number): NonEmptyChunk<number> => start <= end ? makeBy(end - start + 1, (i) => start + i) : of(start)
// -------------------------------------------------------------------------------------// re-exports from ReadonlyArray// -------------------------------------------------------------------------------------
/** * Returns a function that checks if a `Chunk` contains a given value using the default `Equivalence`. * * @category elements * @since 2.0.0 */export const contains: { // ------------------------------------------------------------------------------------- // re-exports from ReadonlyArray // -------------------------------------------------------------------------------------
/** * Returns a function that checks if a `Chunk` contains a given value using the default `Equivalence`. * * @category elements * @since 2.0.0 */ <A>(a: A): (self: Chunk<A>) => boolean // ------------------------------------------------------------------------------------- // re-exports from ReadonlyArray // -------------------------------------------------------------------------------------
/** * Returns a function that checks if a `Chunk` contains a given value using the default `Equivalence`. * * @category elements * @since 2.0.0 */ <A>(self: Chunk<A>, a: A): boolean} = RA.contains
/** * Returns a function that checks if a `Chunk` contains a given value using a provided `isEquivalent` function. * * @category elements * @since 2.0.0 */export const containsWith: <A>( isEquivalent: (self: A, that: A) => boolean) => { (a: A): (self: Chunk<A>) => boolean (self: Chunk<A>, a: A): boolean} = RA.containsWith
/** * Returns the first element that satisfies the specified * predicate, or `None` if no such element exists. * * @category elements * @since 2.0.0 */export const findFirst: { /** * Returns the first element that satisfies the specified * predicate, or `None` if no such element exists. * * @category elements * @since 2.0.0 */ <A, B extends A>(refinement: Refinement<NoInfer<A>, B>): (self: Chunk<A>) => Option<B> /** * Returns the first element that satisfies the specified * predicate, or `None` if no such element exists. * * @category elements * @since 2.0.0 */ <A>(predicate: Predicate<NoInfer<A>>): (self: Chunk<A>) => Option<A> /** * Returns the first element that satisfies the specified * predicate, or `None` if no such element exists. * * @category elements * @since 2.0.0 */ <A, B extends A>(self: Chunk<A>, refinement: Refinement<A, B>): Option<B> /** * Returns the first element that satisfies the specified * predicate, or `None` if no such element exists. * * @category elements * @since 2.0.0 */ <A>(self: Chunk<A>, predicate: Predicate<A>): Option<A>} = RA.findFirst
/** * Return the first index for which a predicate holds. * * @category elements * @since 2.0.0 */export const findFirstIndex: { /** * Return the first index for which a predicate holds. * * @category elements * @since 2.0.0 */ <A>(predicate: Predicate<A>): (self: Chunk<A>) => Option<number> /** * Return the first index for which a predicate holds. * * @category elements * @since 2.0.0 */ <A>(self: Chunk<A>, predicate: Predicate<A>): Option<number>} = RA.findFirstIndex
/** * Find the last element for which a predicate holds. * * @category elements * @since 2.0.0 */export const findLast: { /** * Find the last element for which a predicate holds. * * @category elements * @since 2.0.0 */ <A, B extends A>(refinement: Refinement<NoInfer<A>, B>): (self: Chunk<A>) => Option<B> /** * Find the last element for which a predicate holds. * * @category elements * @since 2.0.0 */ <A>(predicate: Predicate<NoInfer<A>>): (self: Chunk<A>) => Option<A> /** * Find the last element for which a predicate holds. * * @category elements * @since 2.0.0 */ <A, B extends A>(self: Chunk<A>, refinement: Refinement<A, B>): Option<B> /** * Find the last element for which a predicate holds. * * @category elements * @since 2.0.0 */ <A>(self: Chunk<A>, predicate: Predicate<A>): Option<A>} = RA.findLast
/** * Return the last index for which a predicate holds. * * @category elements * @since 2.0.0 */export const findLastIndex: { /** * Return the last index for which a predicate holds. * * @category elements * @since 2.0.0 */ <A>(predicate: Predicate<A>): (self: Chunk<A>) => Option<number> /** * Return the last index for which a predicate holds. * * @category elements * @since 2.0.0 */ <A>(self: Chunk<A>, predicate: Predicate<A>): Option<number>} = RA.findLastIndex
/** * Check if a predicate holds true for every `Chunk` element. * * @category elements * @since 2.0.0 */export const every: { /** * Check if a predicate holds true for every `Chunk` element. * * @category elements * @since 2.0.0 */ <A, B extends A>(refinement: Refinement<NoInfer<A>, B>): (self: Chunk<A>) => self is Chunk<B> /** * Check if a predicate holds true for every `Chunk` element. * * @category elements * @since 2.0.0 */ <A>(predicate: Predicate<A>): (self: Chunk<A>) => boolean /** * Check if a predicate holds true for every `Chunk` element. * * @category elements * @since 2.0.0 */ <A, B extends A>(self: Chunk<A>, refinement: Refinement<A, B>): self is Chunk<B> /** * Check if a predicate holds true for every `Chunk` element. * * @category elements * @since 2.0.0 */ <A>(self: Chunk<A>, predicate: Predicate<A>): boolean} = dual( 2, <A, B extends A>(self: Chunk<A>, refinement: Refinement<A, B>): self is Chunk<B> => RA.fromIterable(self).every(refinement))
/** * Check if a predicate holds true for some `Chunk` element. * * @category elements * @since 2.0.0 */export const some: { /** * Check if a predicate holds true for some `Chunk` element. * * @category elements * @since 2.0.0 */ <A>(predicate: Predicate<NoInfer<A>>): (self: Chunk<A>) => self is NonEmptyChunk<A> /** * Check if a predicate holds true for some `Chunk` element. * * @category elements * @since 2.0.0 */ <A>(self: Chunk<A>, predicate: Predicate<A>): self is NonEmptyChunk<A>} = dual( 2, <A>(self: Chunk<A>, predicate: Predicate<A>): self is NonEmptyChunk<A> => RA.fromIterable(self).some(predicate))
/** * Joins the elements together with "sep" in the middle. * * @category folding * @since 2.0.0 */export const join: { /** * Joins the elements together with "sep" in the middle. * * @category folding * @since 2.0.0 */ (sep: string): (self: Chunk<string>) => string /** * Joins the elements together with "sep" in the middle. * * @category folding * @since 2.0.0 */ (self: Chunk<string>, sep: string): string} = RA.join
/** * @category folding * @since 2.0.0 */export const reduce: { /** * @category folding * @since 2.0.0 */ <B, A>(b: B, f: (b: B, a: A, i: number) => B): (self: Chunk<A>) => B /** * @category folding * @since 2.0.0 */ <A, B>(self: Chunk<A>, b: B, f: (b: B, a: A, i: number) => B): B} = RA.reduce
/** * @category folding * @since 2.0.0 */export const reduceRight: { /** * @category folding * @since 2.0.0 */ <B, A>(b: B, f: (b: B, a: A, i: number) => B): (self: Chunk<A>) => B /** * @category folding * @since 2.0.0 */ <A, B>(self: Chunk<A>, b: B, f: (b: B, a: A, i: number) => B): B} = RA.reduceRight
/** * Creates a `Chunk` of values not included in the other given `Chunk` using the provided `isEquivalent` function. * The order and references of result values are determined by the first `Chunk`. * * @since 3.2.0 */export const differenceWith = <A>(isEquivalent: (self: A, that: A) => boolean): { (that: Chunk<A>): (self: Chunk<A>) => Chunk<A> (self: Chunk<A>, that: Chunk<A>): Chunk<A>} => { return dual( 2, (self: Chunk<A>, that: Chunk<A>): Chunk<A> => unsafeFromArray(RA.differenceWith(isEquivalent)(that, self)) )}
/** * Creates a `Chunk` of values not included in the other given `Chunk`. * The order and references of result values are determined by the first `Chunk`. * * @since 3.2.0 */export const difference: { /** * Creates a `Chunk` of values not included in the other given `Chunk`. * The order and references of result values are determined by the first `Chunk`. * * @since 3.2.0 */ <A>(that: Chunk<A>): (self: Chunk<A>) => Chunk<A> /** * Creates a `Chunk` of values not included in the other given `Chunk`. * The order and references of result values are determined by the first `Chunk`. * * @since 3.2.0 */ <A>(self: Chunk<A>, that: Chunk<A>): Chunk<A>} = dual( 2, <A>(self: Chunk<A>, that: Chunk<A>): Chunk<A> => unsafeFromArray(RA.difference(that, self)))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111/** * @since 2.0.0 */import type * as Context from "./Context.js"import type * as Duration from "./Duration.js"import type * as Effect from "./Effect.js"import * as internal from "./internal/clock.js"import * as defaultServices from "./internal/defaultServices.js"
/** * @since 2.0.0 * @category symbols */export const ClockTypeId: unique symbol = internal.ClockTypeId
/** * @since 2.0.0 * @category symbols */export type ClockTypeId = typeof ClockTypeId
/** * Represents a time-based clock which provides functionality related to time * and scheduling. * * @since 2.0.0 * @category models */export interface Clock { readonly [ClockTypeId]: ClockTypeId /** * Unsafely returns the current time in milliseconds. */ unsafeCurrentTimeMillis(): number /** * Returns the current time in milliseconds. */ readonly currentTimeMillis: Effect.Effect<number> /** * Unsafely returns the current time in nanoseconds. */ unsafeCurrentTimeNanos(): bigint /** * Returns the current time in nanoseconds. */ readonly currentTimeNanos: Effect.Effect<bigint> /** * Asynchronously sleeps for the specified duration. */ sleep(duration: Duration.Duration): Effect.Effect<void>}
/** * @since 2.0.0 * @category models */export type CancelToken = () => boolean
/** * @since 2.0.0 * @category models */export type Task = () => void
/** * @since 2.0.0 * @category models */export interface ClockScheduler { /** * Unsafely schedules the specified task for the specified duration. */ unsafeSchedule(task: Task, duration: Duration.Duration): CancelToken}
/** * @since 2.0.0 * @category constructors */export const make: (_: void) => Clock = internal.make
/** * @since 2.0.0 * @category constructors */export const sleep: (duration: Duration.DurationInput) => Effect.Effect<void> = defaultServices.sleep
/** * @since 2.0.0 * @category constructors */export const currentTimeMillis: Effect.Effect<number> = defaultServices.currentTimeMillis
/** * @since 2.0.0 * @category constructors */export const currentTimeNanos: Effect.Effect<bigint> = defaultServices.currentTimeNanos
/** * @since 2.0.0 * @category constructors */export const clockWith: <A, E, R>(f: (clock: Clock) => Effect.Effect<A, E, R>) => Effect.Effect<A, E, R> = defaultServices.clockWith
/** * @since 2.0.0 * @category context */export const Clock: Context.Tag<Clock, Clock> = internal.clockTag123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743/** * @since 2.0.0 */import type * as Brand from "./Brand.js"import type * as Chunk from "./Chunk.js"import type * as ConfigError from "./ConfigError.js"import type * as Duration from "./Duration.js"import type * as Effect from "./Effect.js"import type * as Either from "./Either.js"import type { LazyArg } from "./Function.js"import type * as HashMap from "./HashMap.js"import type * as HashSet from "./HashSet.js"import * as internal from "./internal/config.js"import type * as LogLevel from "./LogLevel.js"import type * as Option from "./Option.js"import type { Predicate, Refinement } from "./Predicate.js"import type * as Redacted from "./Redacted.js"import type * as Secret from "./Secret.js"import type * as Types from "./Types.js"
/** * @since 2.0.0 * @category symbols */export const ConfigTypeId: unique symbol = internal.ConfigTypeId
/** * @since 2.0.0 * @category symbols */export type ConfigTypeId = typeof ConfigTypeId
/** * A `Config` describes the structure of some configuration data. * * @since 2.0.0 * @category models */export interface Config<out A> extends Config.Variance<A>, Effect.Effect<A, ConfigError.ConfigError> {}
/** * @since 2.0.0 */export declare namespace Config { /** * @since 2.0.0 * @category models */ export interface Variance<out A> { readonly [ConfigTypeId]: { readonly _A: Types.Covariant<A> } }
/** * @since 2.5.0 * @category models */ export type Success<T extends Config<any>> = [T] extends [Config<infer _A>] ? _A : never
/** * @since 2.0.0 * @category models */ export interface Primitive<out A> extends Config<A> { readonly description: string parse(text: string): Either.Either<A, ConfigError.ConfigError> }
/** * Wraps a nested structure, converting all primitives to a `Config`. * * `Config.Wrap<{ key: string }>` becomes `{ key: Config<string> }` * * To create the resulting config, use the `unwrap` constructor. * * @since 2.0.0 * @category models */ export type Wrap<A> = [NonNullable<A>] extends [infer T] ? [IsPlainObject<T>] extends [true] ? | { readonly [K in keyof A]: Wrap<A[K]> } | Config<A> : Config<A> : Config<A>
type IsPlainObject<A> = [A] extends [Record<string, any>] ? [keyof A] extends [never] ? false : [keyof A] extends [string] ? true : false : false}
/** * @since 2.0.0 * @category models */export type LiteralValue = string | number | boolean | null | bigint
/** * Constructs a config from a tuple / struct / arguments of configs. * * @since 2.0.0 * @category constructors */export const all: <const Arg extends Iterable<Config<any>> | Record<string, Config<any>>>( arg: Arg) => Config< [Arg] extends [ReadonlyArray<Config<any>>] ? { -readonly [K in keyof Arg]: [Arg[K]] extends [Config<infer A>] ? A : never } : [Arg] extends [Iterable<Config<infer A>>] ? Array<A> : [Arg] extends [Record<string, Config<any>>] ? { -readonly [K in keyof Arg]: [Arg[K]] extends [Config<infer A>] ? A : never } : never> = internal.all
/** * Constructs a config for an array of values. * * @since 2.0.0 * @category constructors */export const array: <A>(config: Config<A>, name?: string) => Config<Array<A>> = internal.array
/** * Constructs a config for a boolean value. * * @since 2.0.0 * @category constructors */export const boolean: (name?: string) => Config<boolean> = internal.boolean
/** * Constructs a config for a network port [1, 65535]. * * @since 3.16.0 * @category constructors */export const port: (name?: string) => Config<number> = internal.port
/** * Constructs a config for an URL value. * * @since 3.11.0 * @category constructors */export const url: (name?: string) => Config<URL> = internal.url
/** * Constructs a config for a sequence of values. * * @since 2.0.0 * @category constructors */export const chunk: <A>(config: Config<A>, name?: string) => Config<Chunk.Chunk<A>> = internal.chunk
/** * Constructs a config for a date value. * * @since 2.0.0 * @category constructors */export const date: (name?: string) => Config<Date> = internal.date
/** * Constructs a config that fails with the specified message. * * @since 2.0.0 * @category constructors */export const fail: (message: string) => Config<never> = internal.fail
/** * Constructs a config for a float value. * * @since 2.0.0 * @category constructors */export const number: (name?: string) => Config<number> = internal.number
/** * Constructs a config for a integer value. * * @since 2.0.0 * @category constructors */export const integer: (name?: string) => Config<number> = internal.integer
/** * Constructs a config for a literal value. * * **Example** * * ```ts * import { Config } from "effect" * * const config = Config.literal("http", "https")("PROTOCOL") * ``` * * @since 2.0.0 * @category constructors */export const literal: <Literals extends ReadonlyArray<LiteralValue>>(...literals: Literals) => ( name?: string) => Config<Literals[number]> = internal.literal
/** * Constructs a config for a `LogLevel` value. * * @since 2.0.0 * @category constructors */export const logLevel: (name?: string) => Config<LogLevel.LogLevel> = internal.logLevel
/** * Constructs a config for a duration value. * * @since 2.5.0 * @category constructors */export const duration: (name?: string) => Config<Duration.Duration> = internal.duration
/** * This function returns `true` if the specified value is an `Config` value, * `false` otherwise. * * This function can be useful for checking the type of a value before * attempting to operate on it as an `Config` value. For example, you could * use `isConfig` to check the type of a value before using it as an * argument to a function that expects an `Config` value. * * @since 2.0.0 * @category refinements */export const isConfig: (u: unknown) => u is Config<unknown> = internal.isConfig
/** * Returns a config whose structure is the same as this one, but which produces * a different value, constructed using the specified function. * * @since 2.0.0 * @category mapping */export const map: { /** * Returns a config whose structure is the same as this one, but which produces * a different value, constructed using the specified function. * * @since 2.0.0 * @category mapping */ <A, B>(f: (a: A) => B): (self: Config<A>) => Config<B> /** * Returns a config whose structure is the same as this one, but which produces * a different value, constructed using the specified function. * * @since 2.0.0 * @category mapping */ <A, B>(self: Config<A>, f: (a: A) => B): Config<B>} = internal.map
/** * Returns a config whose structure is the same as this one, but which may * produce a different value, constructed using the specified function, which * may throw exceptions that will be translated into validation errors. * * @since 2.0.0 * @category utils */export const mapAttempt: { /** * Returns a config whose structure is the same as this one, but which may * produce a different value, constructed using the specified function, which * may throw exceptions that will be translated into validation errors. * * @since 2.0.0 * @category utils */ <A, B>(f: (a: A) => B): (self: Config<A>) => Config<B> /** * Returns a config whose structure is the same as this one, but which may * produce a different value, constructed using the specified function, which * may throw exceptions that will be translated into validation errors. * * @since 2.0.0 * @category utils */ <A, B>(self: Config<A>, f: (a: A) => B): Config<B>} = internal.mapAttempt
/** * Returns a new config whose structure is the samea as this one, but which * may produce a different value, constructed using the specified fallible * function. * * @since 2.0.0 * @category utils */export const mapOrFail: { /** * Returns a new config whose structure is the samea as this one, but which * may produce a different value, constructed using the specified fallible * function. * * @since 2.0.0 * @category utils */ <A, B>(f: (a: A) => Either.Either<B, ConfigError.ConfigError>): (self: Config<A>) => Config<B> /** * Returns a new config whose structure is the samea as this one, but which * may produce a different value, constructed using the specified fallible * function. * * @since 2.0.0 * @category utils */ <A, B>(self: Config<A>, f: (a: A) => Either.Either<B, ConfigError.ConfigError>): Config<B>} = internal.mapOrFail
/** * Returns a config that has this configuration nested as a property of the * specified name. * * @since 2.0.0 * @category utils */export const nested: { /** * Returns a config that has this configuration nested as a property of the * specified name. * * @since 2.0.0 * @category utils */ (name: string): <A>(self: Config<A>) => Config<A> /** * Returns a config that has this configuration nested as a property of the * specified name. * * @since 2.0.0 * @category utils */ <A>(self: Config<A>, name: string): Config<A>} = internal.nested
/** * Returns a config whose structure is preferentially described by this * config, but which falls back to the specified config if there is an issue * reading from this config. * * @since 2.0.0 * @category utils */export const orElse: { /** * Returns a config whose structure is preferentially described by this * config, but which falls back to the specified config if there is an issue * reading from this config. * * @since 2.0.0 * @category utils */ <A2>(that: LazyArg<Config<A2>>): <A>(self: Config<A>) => Config<A2 | A> /** * Returns a config whose structure is preferentially described by this * config, but which falls back to the specified config if there is an issue * reading from this config. * * @since 2.0.0 * @category utils */ <A, A2>(self: Config<A>, that: LazyArg<Config<A2>>): Config<A | A2>} = internal.orElse
/** * Returns configuration which reads from this configuration, but which falls * back to the specified configuration if reading from this configuration * fails with an error satisfying the specified predicate. * * @since 2.0.0 * @category utils */export const orElseIf: { /** * Returns configuration which reads from this configuration, but which falls * back to the specified configuration if reading from this configuration * fails with an error satisfying the specified predicate. * * @since 2.0.0 * @category utils */ <A2>( options: { readonly if: Predicate<ConfigError.ConfigError> readonly orElse: LazyArg<Config<A2>> } ): <A>(self: Config<A>) => Config<A | A2> /** * Returns configuration which reads from this configuration, but which falls * back to the specified configuration if reading from this configuration * fails with an error satisfying the specified predicate. * * @since 2.0.0 * @category utils */ <A, A2>( self: Config<A>, options: { readonly if: Predicate<ConfigError.ConfigError> readonly orElse: LazyArg<Config<A2>> } ): Config<A | A2>} = internal.orElseIf
/** * Returns an optional version of this config, which will be `None` if the * data is missing from configuration, and `Some` otherwise. * * @since 2.0.0 * @category utils */export const option: <A>(self: Config<A>) => Config<Option.Option<A>> = internal.option
/** * Constructs a new primitive config. * * @since 2.0.0 * @category constructors */export const primitive: <A>( description: string, parse: (text: string) => Either.Either<A, ConfigError.ConfigError>) => Config<A> = internal.primitive
/** * Returns a config that describes a sequence of values, each of which has the * structure of this config. * * @since 2.0.0 * @category utils */export const repeat: <A>(self: Config<A>) => Config<Array<A>> = internal.repeat
/** * Constructs a config for a secret value. * * @since 2.0.0 * @category constructors * @deprecated */export const secret: (name?: string) => Config<Secret.Secret> = internal.secret
/** * Constructs a config for a redacted value. * * @since 2.0.0 * @category constructors */export const redacted: { /** * Constructs a config for a redacted value. * * @since 2.0.0 * @category constructors */ (name?: string): Config<Redacted.Redacted> /** * Constructs a config for a redacted value. * * @since 2.0.0 * @category constructors */ <A>(config: Config<A>): Config<Redacted.Redacted<A>>} = internal.redacted
/** * Constructs a config for a branded value. * * @since 3.16.0 * @category constructors */export const branded: { /** * Constructs a config for a branded value. * * @since 3.16.0 * @category constructors */ <A, B extends Brand.Branded<A, any>>(constructor: Brand.Brand.Constructor<B>): (config: Config<A>) => Config<B> /** * Constructs a config for a branded value. * * @since 3.16.0 * @category constructors */ <B extends Brand.Branded<string, any>>(name: string | undefined, constructor: Brand.Brand.Constructor<B>): Config<B> /** * Constructs a config for a branded value. * * @since 3.16.0 * @category constructors */ <A, B extends Brand.Branded<A, any>>(config: Config<A>, constructor: Brand.Brand.Constructor<B>): Config<B>} = internal.branded
/** * Constructs a config for a sequence of values. * * @since 2.0.0 * @category constructors */export const hashSet: <A>(config: Config<A>, name?: string) => Config<HashSet.HashSet<A>> = internal.hashSet
/** * Constructs a config for a string value. * * @since 2.0.0 * @category constructors */export const string: (name?: string) => Config<string> = internal.string
/** * Constructs a config for a non-empty string value. * * @since 3.7.0 * @category constructors */export const nonEmptyString: (name?: string) => Config<string> = internal.nonEmptyString
/** * Constructs a config which contains the specified value. * * @since 2.0.0 * @category constructors */export const succeed: <A>(value: A) => Config<A> = internal.succeed
/** * Lazily constructs a config. * * @since 2.0.0 * @category constructors */export const suspend: <A>(config: LazyArg<Config<A>>) => Config<A> = internal.suspend
/** * Constructs a config which contains the specified lazy value. * * @since 2.0.0 * @category constructors */export const sync: <A>(value: LazyArg<A>) => Config<A> = internal.sync
/** * Constructs a config for a sequence of values. * * @since 2.0.0 * @category constructors */export const hashMap: <A>(config: Config<A>, name?: string) => Config<HashMap.HashMap<string, A>> = internal.hashMap
/** * Constructs a config from some configuration wrapped with the `Wrap<A>` utility type. * * For example: * * ``` * import { Config, unwrap } from "./Config" * * interface Options { key: string } * * const makeConfig = (config: Config.Wrap<Options>): Config<Options> => unwrap(config) * ``` * * @since 2.0.0 * @category constructors */export const unwrap: <A>(wrapped: Config.Wrap<A>) => Config<A> = internal.unwrap
/** * Returns a config that describes the same structure as this one, but which * performs validation during loading. * * @since 2.0.0 * @category utils */export const validate: { /** * Returns a config that describes the same structure as this one, but which * performs validation during loading. * * @since 2.0.0 * @category utils */ <A, B extends A>( options: { readonly message: string readonly validation: Refinement<A, B> } ): (self: Config<A>) => Config<B> /** * Returns a config that describes the same structure as this one, but which * performs validation during loading. * * @since 2.0.0 * @category utils */ <A>( options: { readonly message: string readonly validation: Predicate<A> } ): (self: Config<A>) => Config<A> /** * Returns a config that describes the same structure as this one, but which * performs validation during loading. * * @since 2.0.0 * @category utils */ <A, B extends A>( self: Config<A>, options: { readonly message: string readonly validation: Refinement<A, B> } ): Config<B> /** * Returns a config that describes the same structure as this one, but which * performs validation during loading. * * @since 2.0.0 * @category utils */ <A>( self: Config<A>, options: { readonly message: string readonly validation: Predicate<A> } ): Config<A>} = internal.validate
/** * Returns a config that describes the same structure as this one, but has the * specified default value in case the information cannot be found. * * @since 2.0.0 * @category utils */export const withDefault: { /** * Returns a config that describes the same structure as this one, but has the * specified default value in case the information cannot be found. * * @since 2.0.0 * @category utils */ <const A2>(def: A2): <A>(self: Config<A>) => Config<A2 | A> /** * Returns a config that describes the same structure as this one, but has the * specified default value in case the information cannot be found. * * @since 2.0.0 * @category utils */ <A, const A2>(self: Config<A>, def: A2): Config<A | A2>} = internal.withDefault
/** * Adds a description to this configuration, which is intended for humans. * * @since 2.0.0 * @category utils */export const withDescription: { /** * Adds a description to this configuration, which is intended for humans. * * @since 2.0.0 * @category utils */ (description: string): <A>(self: Config<A>) => Config<A> /** * Adds a description to this configuration, which is intended for humans. * * @since 2.0.0 * @category utils */ <A>(self: Config<A>, description: string): Config<A>} = internal.withDescription
/** * Returns a config that is the composition of this config and the specified * config. * * @since 2.0.0 * @category zipping */export const zip: { /** * Returns a config that is the composition of this config and the specified * config. * * @since 2.0.0 * @category zipping */ <B>(that: Config<B>): <A>(self: Config<A>) => Config<[A, B]> /** * Returns a config that is the composition of this config and the specified * config. * * @since 2.0.0 * @category zipping */ <A, B>(self: Config<A>, that: Config<B>): Config<[A, B]>} = internal.zip
/** * Returns a config that is the composes this config and the specified config * using the provided function. * * @since 2.0.0 * @category zipping */export const zipWith: { /** * Returns a config that is the composes this config and the specified config * using the provided function. * * @since 2.0.0 * @category zipping */ <B, A, C>(that: Config<B>, f: (a: A, b: B) => C): (self: Config<A>) => Config<C> /** * Returns a config that is the composes this config and the specified config * using the provided function. * * @since 2.0.0 * @category zipping */ <A, B, C>(self: Config<A>, that: Config<B>, f: (a: A, b: B) => C): Config<C>} = internal.zipWith123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286/** * @since 2.0.0 */import type * as Cause from "./Cause.js"import * as internal from "./internal/configError.js"
/** * @since 2.0.0 * @category symbols */export const ConfigErrorTypeId: unique symbol = internal.ConfigErrorTypeId
/** * @since 2.0.0 * @category symbols */export type ConfigErrorTypeId = typeof ConfigErrorTypeId
/** * The possible ways that loading configuration data may fail. * * @since 2.0.0 * @category models */export type ConfigError = | And | Or | InvalidData | MissingData | SourceUnavailable | Unsupported
/** * @since 2.0.0 */export declare namespace ConfigError { /** * @since 2.0.0 * @category models */ export interface Proto { readonly _tag: "ConfigError" readonly [ConfigErrorTypeId]: ConfigErrorTypeId }
/** * @since 2.0.0 * @category models */ export type Reducer<C, Z> = ConfigErrorReducer<C, Z>}
/** * @since 2.0.0 * @category models */export interface ConfigErrorReducer<in C, in out Z> { andCase(context: C, left: Z, right: Z): Z orCase(context: C, left: Z, right: Z): Z invalidDataCase(context: C, path: Array<string>, message: string): Z missingDataCase(context: C, path: Array<string>, message: string): Z sourceUnavailableCase( context: C, path: Array<string>, message: string, cause: Cause.Cause<unknown> ): Z unsupportedCase(context: C, path: Array<string>, message: string): Z}
/** * @since 2.0.0 * @category models */export interface And extends ConfigError.Proto { readonly _op: "And" readonly left: ConfigError readonly right: ConfigError readonly message: string}
/** * @since 2.0.0 * @category models */export interface Or extends ConfigError.Proto { readonly _op: "Or" readonly left: ConfigError readonly right: ConfigError readonly message: string}
/** * @since 2.0.0 * @category models */export interface InvalidData extends ConfigError.Proto { readonly _op: "InvalidData" readonly path: Array<string> readonly message: string}
/** * @since 2.0.0 * @category models */export interface MissingData extends ConfigError.Proto { readonly _op: "MissingData" readonly path: Array<string> readonly message: string}
/** * @since 2.0.0 * @category models */export interface SourceUnavailable extends ConfigError.Proto { readonly _op: "SourceUnavailable" readonly path: Array<string> readonly message: string readonly cause: Cause.Cause<unknown>}
/** * @since 2.0.0 * @category models */export interface Unsupported extends ConfigError.Proto { readonly _op: "Unsupported" readonly path: Array<string> readonly message: string}
/** * @since 2.0.0 * @category models */export interface Options { readonly pathDelim: string}
/** * @since 2.0.0 * @category constructors */export const And: (self: ConfigError, that: ConfigError) => ConfigError = internal.And
/** * @since 2.0.0 * @category constructors */export const Or: (self: ConfigError, that: ConfigError) => ConfigError = internal.Or
/** * @since 2.0.0 * @category constructors */export const MissingData: (path: Array<string>, message: string, options?: Options) => ConfigError = internal.MissingData
/** * @since 2.0.0 * @category constructors */export const InvalidData: (path: Array<string>, message: string, options?: Options) => ConfigError = internal.InvalidData
/** * @since 2.0.0 * @category constructors */export const SourceUnavailable: ( path: Array<string>, message: string, cause: Cause.Cause<unknown>, options?: Options) => ConfigError = internal.SourceUnavailable
/** * @since 2.0.0 * @category constructors */export const Unsupported: (path: Array<string>, message: string, options?: Options) => ConfigError = internal.Unsupported
/** * Returns `true` if the specified value is a `ConfigError`, `false` otherwise. * * @since 2.0.0 * @category refinements */export const isConfigError: (u: unknown) => u is ConfigError = internal.isConfigError
/** * Returns `true` if the specified `ConfigError` is an `And`, `false` otherwise. * * @since 2.0.0 * @category refinements */export const isAnd: (self: ConfigError) => self is And = internal.isAnd
/** * Returns `true` if the specified `ConfigError` is an `Or`, `false` otherwise. * * @since 2.0.0 * @category refinements */export const isOr: (self: ConfigError) => self is Or = internal.isOr
/** * Returns `true` if the specified `ConfigError` is an `InvalidData`, `false` * otherwise. * * @since 2.0.0 * @category refinements */export const isInvalidData: (self: ConfigError) => self is InvalidData = internal.isInvalidData
/** * Returns `true` if the specified `ConfigError` is an `MissingData`, `false` * otherwise. * * @since 2.0.0 * @category refinements */export const isMissingData: (self: ConfigError) => self is MissingData = internal.isMissingData
/** * Returns `true` if the specified `ConfigError` contains only `MissingData` errors, `false` otherwise. * * @since 2.0.0 * @categer getters */export const isMissingDataOnly: (self: ConfigError) => boolean = internal.isMissingDataOnly
/** * Returns `true` if the specified `ConfigError` is a `SourceUnavailable`, * `false` otherwise. * * @since 2.0.0 * @category refinements */export const isSourceUnavailable: (self: ConfigError) => self is SourceUnavailable = internal.isSourceUnavailable
/** * Returns `true` if the specified `ConfigError` is an `Unsupported`, `false` * otherwise. * * @since 2.0.0 * @category refinements */export const isUnsupported: (self: ConfigError) => self is Unsupported = internal.isUnsupported
/** * @since 2.0.0 * @category utils */export const prefixed: { /** * @since 2.0.0 * @category utils */ (prefix: Array<string>): (self: ConfigError) => ConfigError /** * @since 2.0.0 * @category utils */ (self: ConfigError, prefix: Array<string>): ConfigError} = internal.prefixed
/** * @since 2.0.0 * @category folding */export const reduceWithContext: { /** * @since 2.0.0 * @category folding */ <C, Z>(context: C, reducer: ConfigErrorReducer<C, Z>): (self: ConfigError) => Z /** * @since 2.0.0 * @category folding */ <C, Z>(self: ConfigError, context: C, reducer: ConfigErrorReducer<C, Z>): Z} = internal.reduceWithContext123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132/** * @since 2.0.0 */import * as internal from "./internal/configProvider/pathPatch.js"
/** * Represents a description of how to modify the path to a configuration * value. * * @since 2.0.0 * @category models */export type PathPatch = Empty | AndThen | MapName | Nested | Unnested
/** * @since 2.0.0 * @category models */export interface Empty { readonly _tag: "Empty"}
/** * @since 2.0.0 * @category models */export interface AndThen { readonly _tag: "AndThen" readonly first: PathPatch readonly second: PathPatch}
/** * @since 2.0.0 * @category models */export interface MapName { readonly _tag: "MapName" f(string: string): string}
/** * @since 2.0.0 * @category models */export interface Nested { readonly _tag: "Nested" readonly name: string}
/** * @since 2.0.0 * @category models */export interface Unnested { readonly _tag: "Unnested" readonly name: string}
/** * @since 2.0.0 * @category constructors */export const empty: PathPatch = internal.empty
/** * @since 2.0.0 * @category constructors */export const andThen: { /** * @since 2.0.0 * @category constructors */ (that: PathPatch): (self: PathPatch) => PathPatch /** * @since 2.0.0 * @category constructors */ (self: PathPatch, that: PathPatch): PathPatch} = internal.andThen
/** * @since 2.0.0 * @category constructors */export const mapName: { /** * @since 2.0.0 * @category constructors */ (f: (string: string) => string): (self: PathPatch) => PathPatch /** * @since 2.0.0 * @category constructors */ (self: PathPatch, f: (string: string) => string): PathPatch} = internal.mapName
/** * @since 2.0.0 * @category constructors */export const nested: { /** * @since 2.0.0 * @category constructors */ (name: string): (self: PathPatch) => PathPatch /** * @since 2.0.0 * @category constructors */ (self: PathPatch, name: string): PathPatch} = internal.nested
/** * @since 2.0.0 * @category constructors */export const unnested: { /** * @since 2.0.0 * @category constructors */ (name: string): (self: PathPatch) => PathPatch /** * @since 2.0.0 * @category constructors */ (self: PathPatch, name: string): PathPatch} = internal.unnested123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867/** * This module provides a data structure called `Context` that can be used for dependency injection in effectful * programs. It is essentially a table mapping `Tag`s to their implementations (called `Service`s), and can be used to * manage dependencies in a type-safe way. The `Context` data structure is essentially a way of providing access to a set * of related services that can be passed around as a single unit. This module provides functions to create, modify, and * query the contents of a `Context`, as well as a number of utility types for working with tags and services. * * @since 2.0.0 */import type * as Effect from "./Effect.js"import type { Equal } from "./Equal.js"import type { LazyArg } from "./Function.js"import type { Inspectable } from "./Inspectable.js"import * as internal from "./internal/context.js"import type { Option } from "./Option.js"import type { Pipeable } from "./Pipeable.js"import type * as Types from "./Types.js"import type * as Unify from "./Unify.js"
/** * @since 2.0.0 * @category symbol */export const TagTypeId: unique symbol = internal.TagTypeId
/** * @since 2.0.0 * @category symbol */export type TagTypeId = typeof TagTypeId
/** * @since 3.5.9 * @category models */export interface Tag<in out Id, in out Value> extends Pipeable, Inspectable, ReadonlyTag<Id, Value> { readonly _op: "Tag" readonly Service: Value readonly Identifier: Id readonly [TagTypeId]: { readonly _Service: Types.Invariant<Value> readonly _Identifier: Types.Invariant<Id> } of(self: Value): Value context(self: Value): Context<Id> readonly stack?: string | undefined readonly key: string [Unify.typeSymbol]?: unknown [Unify.unifySymbol]?: TagUnify<this> [Unify.ignoreSymbol]?: TagUnifyIgnore}
/** * @since 3.5.9 * @category models */export interface ReadonlyTag<in out Id, out Value> extends Pipeable, Inspectable, Effect.Effect<Value, never, Id> { readonly _op: "Tag" readonly Service: Value readonly Identifier: Id readonly [TagTypeId]: { readonly _Service: Types.Covariant<Value> readonly _Identifier: Types.Invariant<Id> } readonly stack?: string | undefined readonly key: string}
/** * @since 3.11.0 * @category symbol */export const ReferenceTypeId: unique symbol = internal.ReferenceTypeId
/** * @since 3.11.0 * @category symbol */export type ReferenceTypeId = typeof ReferenceTypeId
/** * @since 3.11.0 * @category models */export interface Reference<in out Id, in out Value> extends Pipeable, Inspectable { readonly [ReferenceTypeId]: ReferenceTypeId readonly defaultValue: () => Value
readonly _op: "Tag" readonly Service: Value readonly Identifier: Id readonly [TagTypeId]: { readonly _Service: Types.Invariant<Value> readonly _Identifier: Types.Invariant<Id> } of(self: Value): Value context(self: Value): Context<Id> readonly stack?: string | undefined readonly key: string [Unify.typeSymbol]?: unknown [Unify.unifySymbol]?: TagUnify<this> [Unify.ignoreSymbol]?: TagUnifyIgnore}
/** * @since 2.0.0 * @category models */export interface TagClassShape<Id, Shape> { readonly [TagTypeId]: TagTypeId readonly Type: Shape readonly Id: Id}
// TODO(4.0): move key narrowing to the Tag interface/** * @since 2.0.0 * @category models */export interface TagClass<Self, Id extends string, Type> extends Tag<Self, Type> { new(_: never): TagClassShape<Id, Type> readonly key: Id}
// TODO(4.0): move key narrowing to the Reference interface/** * @since 3.11.0 * @category models */export interface ReferenceClass<Self, Id extends string, Type> extends Reference<Self, Type> { new(_: never): TagClassShape<Id, Type> readonly key: Id}
/** * @category models * @since 2.0.0 */export interface TagUnify<A extends { [Unify.typeSymbol]?: any }> { Tag?: () => Extract<A[Unify.typeSymbol], Tag<any, any>>}
/** * @category models * @since 2.0.0 */export interface TagUnifyIgnore {}
/** * @since 2.0.0 */export declare namespace Tag { /** * @since 2.0.0 */ export type Service<T extends Tag<any, any> | TagClassShape<any, any>> = T extends Tag<any, any> ? T["Service"] : T extends TagClassShape<any, infer A> ? A : never /** * @since 2.0.0 */ export type Identifier<T extends Tag<any, any> | TagClassShape<any, any>> = T extends Tag<any, any> ? T["Identifier"] : T extends TagClassShape<any, any> ? T : never}
/** * Creates a new `Tag` instance with an optional key parameter. * * @example * ```ts * import * as assert from "node:assert" * import { Context } from "effect" * * assert.strictEqual(Context.GenericTag("PORT").key === Context.GenericTag("PORT").key, true) * ``` * * @since 2.0.0 * @category constructors */export const GenericTag: <Identifier, Service = Identifier>(key: string) => Tag<Identifier, Service> = internal.makeGenericTag
const TypeId: unique symbol = internal.TypeId as TypeId
/** * @since 2.0.0 * @category symbol */export type TypeId = typeof TypeId
/** * @since 2.0.0 * @category models */export type ValidTagsById<R> = R extends infer S ? Tag<S, any> : never
/** * @since 2.0.0 * @category models */export interface Context<in Services> extends Equal, Pipeable, Inspectable { readonly [TypeId]: { readonly _Services: Types.Contravariant<Services> } readonly unsafeMap: Map<string, any>}
/** * @since 2.0.0 * @category constructors */export const unsafeMake: <Services>(unsafeMap: Map<string, any>) => Context<Services> = internal.makeContext
/** * Checks if the provided argument is a `Context`. * * @example * ```ts * import * as assert from "node:assert" * import { Context } from "effect" * * assert.strictEqual(Context.isContext(Context.empty()), true) * ``` * * @since 2.0.0 * @category guards */export const isContext: (input: unknown) => input is Context<never> = internal.isContext
/** * Checks if the provided argument is a `Tag`. * * @example * ```ts * import * as assert from "node:assert" * import { Context } from "effect" * * assert.strictEqual(Context.isTag(Context.GenericTag("Tag")), true) * ``` * * @since 2.0.0 * @category guards */export const isTag: (input: unknown) => input is Tag<any, any> = internal.isTag
/** * Checks if the provided argument is a `Reference`. * * @since 3.11.0 * @category guards * @experimental */export const isReference: (u: unknown) => u is Reference<any, any> = internal.isReference
/** * Returns an empty `Context`. * * @example * ```ts * import * as assert from "node:assert" * import { Context } from "effect" * * assert.strictEqual(Context.isContext(Context.empty()), true) * ``` * * @since 2.0.0 * @category constructors */export const empty: () => Context<never> = internal.empty
/** * Creates a new `Context` with a single service associated to the tag. * * @example * ```ts * import * as assert from "node:assert" * import { Context } from "effect" * * const Port = Context.GenericTag<{ PORT: number }>("Port") * * const Services = Context.make(Port, { PORT: 8080 }) * * assert.deepStrictEqual(Context.get(Services, Port), { PORT: 8080 }) * ``` * * @since 2.0.0 * @category constructors */export const make: <I, S>(tag: Tag<I, S>, service: Types.NoInfer<S>) => Context<I> = internal.make
/** * Adds a service to a given `Context`. * * @example * ```ts * import * as assert from "node:assert" * import { Context, pipe } from "effect" * * const Port = Context.GenericTag<{ PORT: number }>("Port") * const Timeout = Context.GenericTag<{ TIMEOUT: number }>("Timeout") * * const someContext = Context.make(Port, { PORT: 8080 }) * * const Services = pipe( * someContext, * Context.add(Timeout, { TIMEOUT: 5000 }) * ) * * assert.deepStrictEqual(Context.get(Services, Port), { PORT: 8080 }) * assert.deepStrictEqual(Context.get(Services, Timeout), { TIMEOUT: 5000 }) * ``` * * @since 2.0.0 */export const add: { /** * Adds a service to a given `Context`. * * @example * ```ts * import * as assert from "node:assert" * import { Context, pipe } from "effect" * * const Port = Context.GenericTag<{ PORT: number }>("Port") * const Timeout = Context.GenericTag<{ TIMEOUT: number }>("Timeout") * * const someContext = Context.make(Port, { PORT: 8080 }) * * const Services = pipe( * someContext, * Context.add(Timeout, { TIMEOUT: 5000 }) * ) * * assert.deepStrictEqual(Context.get(Services, Port), { PORT: 8080 }) * assert.deepStrictEqual(Context.get(Services, Timeout), { TIMEOUT: 5000 }) * ``` * * @since 2.0.0 */ <I, S>(tag: Tag<I, S>, service: Types.NoInfer<S>): <Services>(self: Context<Services>) => Context<Services | I> /** * Adds a service to a given `Context`. * * @example * ```ts * import * as assert from "node:assert" * import { Context, pipe } from "effect" * * const Port = Context.GenericTag<{ PORT: number }>("Port") * const Timeout = Context.GenericTag<{ TIMEOUT: number }>("Timeout") * * const someContext = Context.make(Port, { PORT: 8080 }) * * const Services = pipe( * someContext, * Context.add(Timeout, { TIMEOUT: 5000 }) * ) * * assert.deepStrictEqual(Context.get(Services, Port), { PORT: 8080 }) * assert.deepStrictEqual(Context.get(Services, Timeout), { TIMEOUT: 5000 }) * ``` * * @since 2.0.0 */ <Services, I, S>(self: Context<Services>, tag: Tag<I, S>, service: Types.NoInfer<S>): Context<Services | I>} = internal.add
/** * Get a service from the context that corresponds to the given tag. * * @example * ```ts * import * as assert from "node:assert" * import { pipe, Context } from "effect" * * const Port = Context.GenericTag<{ PORT: number }>("Port") * const Timeout = Context.GenericTag<{ TIMEOUT: number }>("Timeout") * * const Services = pipe( * Context.make(Port, { PORT: 8080 }), * Context.add(Timeout, { TIMEOUT: 5000 }) * ) * * assert.deepStrictEqual(Context.get(Services, Timeout), { TIMEOUT: 5000 }) * ``` * * @since 2.0.0 * @category getters */export const get: { /** * Get a service from the context that corresponds to the given tag. * * @example * ```ts * import * as assert from "node:assert" * import { pipe, Context } from "effect" * * const Port = Context.GenericTag<{ PORT: number }>("Port") * const Timeout = Context.GenericTag<{ TIMEOUT: number }>("Timeout") * * const Services = pipe( * Context.make(Port, { PORT: 8080 }), * Context.add(Timeout, { TIMEOUT: 5000 }) * ) * * assert.deepStrictEqual(Context.get(Services, Timeout), { TIMEOUT: 5000 }) * ``` * * @since 2.0.0 * @category getters */ <I, S>(tag: Reference<I, S>): <Services>(self: Context<Services>) => S /** * Get a service from the context that corresponds to the given tag. * * @example * ```ts * import * as assert from "node:assert" * import { pipe, Context } from "effect" * * const Port = Context.GenericTag<{ PORT: number }>("Port") * const Timeout = Context.GenericTag<{ TIMEOUT: number }>("Timeout") * * const Services = pipe( * Context.make(Port, { PORT: 8080 }), * Context.add(Timeout, { TIMEOUT: 5000 }) * ) * * assert.deepStrictEqual(Context.get(Services, Timeout), { TIMEOUT: 5000 }) * ``` * * @since 2.0.0 * @category getters */ <Services, I extends Services, S>(tag: Tag<I, S>): (self: Context<Services>) => S /** * Get a service from the context that corresponds to the given tag. * * @example * ```ts * import * as assert from "node:assert" * import { pipe, Context } from "effect" * * const Port = Context.GenericTag<{ PORT: number }>("Port") * const Timeout = Context.GenericTag<{ TIMEOUT: number }>("Timeout") * * const Services = pipe( * Context.make(Port, { PORT: 8080 }), * Context.add(Timeout, { TIMEOUT: 5000 }) * ) * * assert.deepStrictEqual(Context.get(Services, Timeout), { TIMEOUT: 5000 }) * ``` * * @since 2.0.0 * @category getters */ <Services, I, S>(self: Context<Services>, tag: Reference<I, S>): S /** * Get a service from the context that corresponds to the given tag. * * @example * ```ts * import * as assert from "node:assert" * import { pipe, Context } from "effect" * * const Port = Context.GenericTag<{ PORT: number }>("Port") * const Timeout = Context.GenericTag<{ TIMEOUT: number }>("Timeout") * * const Services = pipe( * Context.make(Port, { PORT: 8080 }), * Context.add(Timeout, { TIMEOUT: 5000 }) * ) * * assert.deepStrictEqual(Context.get(Services, Timeout), { TIMEOUT: 5000 }) * ``` * * @since 2.0.0 * @category getters */ <Services, I extends Services, S>(self: Context<Services>, tag: Tag<I, S>): S} = internal.get
/** * Get a service from the context that corresponds to the given tag, or * use the fallback value. * * @since 3.7.0 * @category getters */export const getOrElse: { /** * Get a service from the context that corresponds to the given tag, or * use the fallback value. * * @since 3.7.0 * @category getters */ <S, I, B>(tag: Tag<I, S>, orElse: LazyArg<B>): <Services>(self: Context<Services>) => S | B /** * Get a service from the context that corresponds to the given tag, or * use the fallback value. * * @since 3.7.0 * @category getters */ <Services, S, I, B>(self: Context<Services>, tag: Tag<I, S>, orElse: LazyArg<B>): S | B} = internal.getOrElse
/** * Get a service from the context that corresponds to the given tag. * This function is unsafe because if the tag is not present in the context, a runtime error will be thrown. * * For a safer version see {@link getOption}. * * @example * ```ts * import * as assert from "node:assert" * import { Context } from "effect" * * const Port = Context.GenericTag<{ PORT: number }>("Port") * const Timeout = Context.GenericTag<{ TIMEOUT: number }>("Timeout") * * const Services = Context.make(Port, { PORT: 8080 }) * * assert.deepStrictEqual(Context.unsafeGet(Services, Port), { PORT: 8080 }) * assert.throws(() => Context.unsafeGet(Services, Timeout)) * ``` * * @since 2.0.0 * @category unsafe */export const unsafeGet: { /** * Get a service from the context that corresponds to the given tag. * This function is unsafe because if the tag is not present in the context, a runtime error will be thrown. * * For a safer version see {@link getOption}. * * @example * ```ts * import * as assert from "node:assert" * import { Context } from "effect" * * const Port = Context.GenericTag<{ PORT: number }>("Port") * const Timeout = Context.GenericTag<{ TIMEOUT: number }>("Timeout") * * const Services = Context.make(Port, { PORT: 8080 }) * * assert.deepStrictEqual(Context.unsafeGet(Services, Port), { PORT: 8080 }) * assert.throws(() => Context.unsafeGet(Services, Timeout)) * ``` * * @since 2.0.0 * @category unsafe */ <S, I>(tag: Tag<I, S>): <Services>(self: Context<Services>) => S /** * Get a service from the context that corresponds to the given tag. * This function is unsafe because if the tag is not present in the context, a runtime error will be thrown. * * For a safer version see {@link getOption}. * * @example * ```ts * import * as assert from "node:assert" * import { Context } from "effect" * * const Port = Context.GenericTag<{ PORT: number }>("Port") * const Timeout = Context.GenericTag<{ TIMEOUT: number }>("Timeout") * * const Services = Context.make(Port, { PORT: 8080 }) * * assert.deepStrictEqual(Context.unsafeGet(Services, Port), { PORT: 8080 }) * assert.throws(() => Context.unsafeGet(Services, Timeout)) * ``` * * @since 2.0.0 * @category unsafe */ <Services, S, I>(self: Context<Services>, tag: Tag<I, S>): S} = internal.unsafeGet
/** * Get the value associated with the specified tag from the context wrapped in an `Option` object. If the tag is not * found, the `Option` object will be `None`. * * @example * ```ts * import * as assert from "node:assert" * import { Context, Option } from "effect" * * const Port = Context.GenericTag<{ PORT: number }>("Port") * const Timeout = Context.GenericTag<{ TIMEOUT: number }>("Timeout") * * const Services = Context.make(Port, { PORT: 8080 }) * * assert.deepStrictEqual(Context.getOption(Services, Port), Option.some({ PORT: 8080 })) * assert.deepStrictEqual(Context.getOption(Services, Timeout), Option.none()) * ``` * * @since 2.0.0 * @category getters */export const getOption: { /** * Get the value associated with the specified tag from the context wrapped in an `Option` object. If the tag is not * found, the `Option` object will be `None`. * * @example * ```ts * import * as assert from "node:assert" * import { Context, Option } from "effect" * * const Port = Context.GenericTag<{ PORT: number }>("Port") * const Timeout = Context.GenericTag<{ TIMEOUT: number }>("Timeout") * * const Services = Context.make(Port, { PORT: 8080 }) * * assert.deepStrictEqual(Context.getOption(Services, Port), Option.some({ PORT: 8080 })) * assert.deepStrictEqual(Context.getOption(Services, Timeout), Option.none()) * ``` * * @since 2.0.0 * @category getters */ <S, I>(tag: Tag<I, S>): <Services>(self: Context<Services>) => Option<S> /** * Get the value associated with the specified tag from the context wrapped in an `Option` object. If the tag is not * found, the `Option` object will be `None`. * * @example * ```ts * import * as assert from "node:assert" * import { Context, Option } from "effect" * * const Port = Context.GenericTag<{ PORT: number }>("Port") * const Timeout = Context.GenericTag<{ TIMEOUT: number }>("Timeout") * * const Services = Context.make(Port, { PORT: 8080 }) * * assert.deepStrictEqual(Context.getOption(Services, Port), Option.some({ PORT: 8080 })) * assert.deepStrictEqual(Context.getOption(Services, Timeout), Option.none()) * ``` * * @since 2.0.0 * @category getters */ <Services, S, I>(self: Context<Services>, tag: Tag<I, S>): Option<S>} = internal.getOption
/** * Merges two `Context`s, returning a new `Context` containing the services of both. * * @example * ```ts * import * as assert from "node:assert" * import { Context } from "effect" * * const Port = Context.GenericTag<{ PORT: number }>("Port") * const Timeout = Context.GenericTag<{ TIMEOUT: number }>("Timeout") * * const firstContext = Context.make(Port, { PORT: 8080 }) * const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) * * const Services = Context.merge(firstContext, secondContext) * * assert.deepStrictEqual(Context.get(Services, Port), { PORT: 8080 }) * assert.deepStrictEqual(Context.get(Services, Timeout), { TIMEOUT: 5000 }) * ``` * * @since 2.0.0 */export const merge: { /** * Merges two `Context`s, returning a new `Context` containing the services of both. * * @example * ```ts * import * as assert from "node:assert" * import { Context } from "effect" * * const Port = Context.GenericTag<{ PORT: number }>("Port") * const Timeout = Context.GenericTag<{ TIMEOUT: number }>("Timeout") * * const firstContext = Context.make(Port, { PORT: 8080 }) * const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) * * const Services = Context.merge(firstContext, secondContext) * * assert.deepStrictEqual(Context.get(Services, Port), { PORT: 8080 }) * assert.deepStrictEqual(Context.get(Services, Timeout), { TIMEOUT: 5000 }) * ``` * * @since 2.0.0 */ <R1>(that: Context<R1>): <Services>(self: Context<Services>) => Context<R1 | Services> /** * Merges two `Context`s, returning a new `Context` containing the services of both. * * @example * ```ts * import * as assert from "node:assert" * import { Context } from "effect" * * const Port = Context.GenericTag<{ PORT: number }>("Port") * const Timeout = Context.GenericTag<{ TIMEOUT: number }>("Timeout") * * const firstContext = Context.make(Port, { PORT: 8080 }) * const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) * * const Services = Context.merge(firstContext, secondContext) * * assert.deepStrictEqual(Context.get(Services, Port), { PORT: 8080 }) * assert.deepStrictEqual(Context.get(Services, Timeout), { TIMEOUT: 5000 }) * ``` * * @since 2.0.0 */ <Services, R1>(self: Context<Services>, that: Context<R1>): Context<Services | R1>} = internal.merge
/** * Merges any number of `Context`s, returning a new `Context` containing the services of all. * * @example * ```ts * import * as assert from "node:assert" * import { Context } from "effect" * * const Port = Context.GenericTag<{ PORT: number }>("Port") * const Timeout = Context.GenericTag<{ TIMEOUT: number }>("Timeout") * const Host = Context.GenericTag<{ HOST: string }>("Host") * * const firstContext = Context.make(Port, { PORT: 8080 }) * const secondContext = Context.make(Timeout, { TIMEOUT: 5000 }) * const thirdContext = Context.make(Host, { HOST: "localhost" }) * * const Services = Context.mergeAll(firstContext, secondContext, thirdContext) * * assert.deepStrictEqual(Context.get(Services, Port), { PORT: 8080 }) * assert.deepStrictEqual(Context.get(Services, Timeout), { TIMEOUT: 5000 }) * assert.deepStrictEqual(Context.get(Services, Host), { HOST: "localhost" }) * ``` * * @since 3.12.0 */export const mergeAll: <T extends Array<unknown>>( ...ctxs: [...{ [K in keyof T]: Context<T[K]> }]) => Context<T[number]> = internal.mergeAll
/** * Returns a new `Context` that contains only the specified services. * * @example * ```ts * import * as assert from "node:assert" * import { pipe, Context, Option } from "effect" * * const Port = Context.GenericTag<{ PORT: number }>("Port") * const Timeout = Context.GenericTag<{ TIMEOUT: number }>("Timeout") * * const someContext = pipe( * Context.make(Port, { PORT: 8080 }), * Context.add(Timeout, { TIMEOUT: 5000 }) * ) * * const Services = pipe(someContext, Context.pick(Port)) * * assert.deepStrictEqual(Context.getOption(Services, Port), Option.some({ PORT: 8080 })) * assert.deepStrictEqual(Context.getOption(Services, Timeout), Option.none()) * ``` * * @since 2.0.0 */export const pick: <Tags extends ReadonlyArray<Tag<any, any>>>( ...tags: Tags) => <Services>(self: Context<Services>) => Context<Services & Tag.Identifier<Tags[number]>> = internal.pick
/** * @since 2.0.0 */export const omit: <Tags extends ReadonlyArray<Tag<any, any>>>( ...tags: Tags) => <Services>(self: Context<Services>) => Context<Exclude<Services, Tag.Identifier<Tags[number]>>> = internal.omit
/** * @example * ```ts * import * as assert from "node:assert" * import { Context, Layer } from "effect" * * class MyTag extends Context.Tag("MyTag")< * MyTag, * { readonly myNum: number } * >() { * static Live = Layer.succeed(this, { myNum: 108 }) * } * ``` * * @since 2.0.0 * @category constructors */export const Tag: <const Id extends string>(id: Id) => <Self, Shape>() => TagClass<Self, Id, Shape> = internal.Tag
/** * Creates a context tag with a default value. * * **Details** * * `Context.Reference` allows you to create a tag that can hold a value. You can * provide a default value for the service, which will automatically be used * when the context is accessed, or override it with a custom implementation * when needed. * * **Example** (Declaring a Tag with a default value) * * ```ts * import * as assert from "node:assert" * import { Context, Effect } from "effect" * * class SpecialNumber extends Context.Reference<SpecialNumber>()( * "SpecialNumber", * { defaultValue: () => 2048 } * ) {} * * // ┌─── Effect<void, never, never> * // ▼ * const program = Effect.gen(function* () { * const specialNumber = yield* SpecialNumber * console.log(`The special number is ${specialNumber}`) * }) * * // No need to provide the SpecialNumber implementation * Effect.runPromise(program) * // Output: The special number is 2048 * ``` * * **Example** (Overriding the default value) * * ```ts * import { Context, Effect } from "effect" * * class SpecialNumber extends Context.Reference<SpecialNumber>()( * "SpecialNumber", * { defaultValue: () => 2048 } * ) {} * * const program = Effect.gen(function* () { * const specialNumber = yield* SpecialNumber * console.log(`The special number is ${specialNumber}`) * }) * * Effect.runPromise(program.pipe(Effect.provideService(SpecialNumber, -1))) * // Output: The special number is -1 * ``` * * @since 3.11.0 * @category constructors * @experimental */export const Reference: <Self>() => <const Id extends string, Service>( id: Id, options: { readonly defaultValue: () => Service }) => ReferenceClass<Self, Id, Service> = internal.Reference123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848/** * @since 2.0.0 */import * as Arr from "./Array.js"import * as Data from "./Data.js"import type * as DateTime from "./DateTime.js"import * as Either from "./Either.js"import * as Equal from "./Equal.js"import * as equivalence from "./Equivalence.js"import { constVoid, dual, identity, pipe } from "./Function.js"import * as Hash from "./Hash.js"import { format, type Inspectable, NodeInspectSymbol } from "./Inspectable.js"import * as dateTime from "./internal/dateTime.js"import * as N from "./Number.js"import * as Option from "./Option.js"import { type Pipeable, pipeArguments } from "./Pipeable.js"import { hasProperty } from "./Predicate.js"import * as String from "./String.js"import type { Mutable } from "./Types.js"
/** * @since 2.0.0 * @category symbols */export const TypeId: unique symbol = Symbol.for("effect/Cron")
/** * @since 2.0.0 * @category symbol */export type TypeId = typeof TypeId
/** * @since 2.0.0 * @category models */export interface Cron extends Pipeable, Equal.Equal, Inspectable { readonly [TypeId]: TypeId readonly tz: Option.Option<DateTime.TimeZone> readonly seconds: ReadonlySet<number> readonly minutes: ReadonlySet<number> readonly hours: ReadonlySet<number> readonly days: ReadonlySet<number> readonly months: ReadonlySet<number> readonly weekdays: ReadonlySet<number> /** @internal */ readonly first: { readonly second: number readonly minute: number readonly hour: number readonly day: number readonly month: number readonly weekday: number } /** @internal */ readonly last: { readonly second: number readonly minute: number readonly hour: number readonly day: number readonly month: number readonly weekday: number } /** @internal */ readonly next: { readonly second: ReadonlyArray<number | undefined> readonly minute: ReadonlyArray<number | undefined> readonly hour: ReadonlyArray<number | undefined> readonly day: ReadonlyArray<number | undefined> readonly month: ReadonlyArray<number | undefined> readonly weekday: ReadonlyArray<number | undefined> } /** @internal */ readonly prev: { readonly second: ReadonlyArray<number | undefined> readonly minute: ReadonlyArray<number | undefined> readonly hour: ReadonlyArray<number | undefined> readonly day: ReadonlyArray<number | undefined> readonly month: ReadonlyArray<number | undefined> readonly weekday: ReadonlyArray<number | undefined> }}
const CronProto = { [TypeId]: TypeId, [Equal.symbol](this: Cron, that: unknown) { return isCron(that) && equals(this, that) }, [Hash.symbol](this: Cron): number { return pipe( Hash.hash(this.tz), Hash.combine(Hash.array(Arr.fromIterable(this.seconds))), Hash.combine(Hash.array(Arr.fromIterable(this.minutes))), Hash.combine(Hash.array(Arr.fromIterable(this.hours))), Hash.combine(Hash.array(Arr.fromIterable(this.days))), Hash.combine(Hash.array(Arr.fromIterable(this.months))), Hash.combine(Hash.array(Arr.fromIterable(this.weekdays))), Hash.cached(this) ) }, toString(this: Cron) { return format(this.toJSON()) }, toJSON(this: Cron) { return { _id: "Cron", tz: this.tz, seconds: Arr.fromIterable(this.seconds), minutes: Arr.fromIterable(this.minutes), hours: Arr.fromIterable(this.hours), days: Arr.fromIterable(this.days), months: Arr.fromIterable(this.months), weekdays: Arr.fromIterable(this.weekdays) } }, [NodeInspectSymbol](this: Cron) { return this.toJSON() }, pipe() { return pipeArguments(this, arguments) }}
/** * Checks if a given value is a `Cron` instance. * * @since 2.0.0 * @category guards */export const isCron = (u: unknown): u is Cron => hasProperty(u, TypeId)
/** * Creates a `Cron` instance. * * @since 2.0.0 * @category constructors */export const make = (values: { readonly seconds?: Iterable<number> | undefined readonly minutes: Iterable<number> readonly hours: Iterable<number> readonly days: Iterable<number> readonly months: Iterable<number> readonly weekdays: Iterable<number> readonly tz?: DateTime.TimeZone | undefined}): Cron => { const o: Mutable<Cron> = Object.create(CronProto) o.seconds = new Set(Arr.sort(values.seconds ?? [0], N.Order)) o.minutes = new Set(Arr.sort(values.minutes, N.Order)) o.hours = new Set(Arr.sort(values.hours, N.Order)) o.days = new Set(Arr.sort(values.days, N.Order)) o.months = new Set(Arr.sort(values.months, N.Order)) o.weekdays = new Set(Arr.sort(values.weekdays, N.Order)) o.tz = Option.fromNullable(values.tz)
const seconds = Array.from(o.seconds) const minutes = Array.from(o.minutes) const hours = Array.from(o.hours) const days = Array.from(o.days) const months = Array.from(o.months) const weekdays = Array.from(o.weekdays)
o.first = { second: seconds[0] ?? 0, minute: minutes[0] ?? 0, hour: hours[0] ?? 0, day: days[0] ?? 1, month: (months[0] ?? 1) - 1, weekday: weekdays[0] ?? 0 }
o.last = { second: seconds[seconds.length - 1] ?? 59, minute: minutes[minutes.length - 1] ?? 59, hour: hours[hours.length - 1] ?? 23, day: days[days.length - 1] ?? 31, month: (months[months.length - 1] ?? 12) - 1, weekday: weekdays[weekdays.length - 1] ?? 6 }
o.next = { second: lookupTable(seconds, 60, "next"), minute: lookupTable(minutes, 60, "next"), hour: lookupTable(hours, 24, "next"), day: lookupTable(days, 32, "next"), month: lookupTable(months, 13, "next"), weekday: lookupTable(weekdays, 7, "next") }
o.prev = { second: lookupTable(seconds, 60, "prev"), minute: lookupTable(minutes, 60, "prev"), hour: lookupTable(hours, 24, "prev"), day: lookupTable(days, 32, "prev"), month: lookupTable(months, 13, "prev"), weekday: lookupTable(weekdays, 7, "prev") }
return o}
const lookupTable = ( values: ReadonlyArray<number>, size: number, dir: "next" | "prev"): Array<number | undefined> => { const result = new Array(size).fill(undefined) if (values.length === 0) { return result }
let current: number | undefined = undefined
if (dir === "next") { let index = values.length - 1 for (let i = size - 1; i >= 0; i--) { while (index >= 0 && values[index] >= i) { current = values[index--] } result[i] = current } } else { let index = 0 for (let i = 0; i < size; i++) { while (index < values.length && values[index] <= i) { current = values[index++] } result[i] = current } }
return result}
/** * @since 2.0.0 * @category symbol */export const ParseErrorTypeId: unique symbol = Symbol.for("effect/Cron/errors/ParseError")
/** * @since 2.0.0 * @category symbols */export type ParseErrorTypeId = typeof ParseErrorTypeId
/** * Represents a checked exception which occurs when decoding fails. * * @since 2.0.0 * @category models */export class ParseError extends Data.TaggedError("CronParseError")<{ readonly message: string readonly input?: string}> { /** * @since 2.0.0 */ readonly [ParseErrorTypeId] = ParseErrorTypeId}
/** * Returns `true` if the specified value is an `ParseError`, `false` otherwise. * * @since 2.0.0 * @category guards */export const isParseError = (u: unknown): u is ParseError => hasProperty(u, ParseErrorTypeId)
/** * Parses a cron expression into a `Cron` instance. * * @example * ```ts * import * as assert from "node:assert" * import { Cron, Either } from "effect" * * // At 04:00 on every day-of-month from 8 through 14. * assert.deepStrictEqual(Cron.parse("0 0 4 8-14 * *"), Either.right(Cron.make({ * seconds: [0], * minutes: [0], * hours: [4], * days: [8, 9, 10, 11, 12, 13, 14], * months: [], * weekdays: [] * }))) * ``` * * @since 2.0.0 * @category constructors */export const parse = (cron: string, tz?: DateTime.TimeZone | string): Either.Either<Cron, ParseError> => { const segments = cron.split(" ").filter(String.isNonEmpty) if (segments.length !== 5 && segments.length !== 6) { return Either.left( new ParseError({ message: `Invalid number of segments in cron expression`, input: cron }) ) }
if (segments.length === 5) { segments.unshift("0") }
const [seconds, minutes, hours, days, months, weekdays] = segments const zone = tz === undefined || dateTime.isTimeZone(tz) ? Either.right(tz) : Either.fromOption(dateTime.zoneFromString(tz), () => new ParseError({ message: `Invalid time zone in cron expression`, input: tz }))
return Either.all({ tz: zone, seconds: parseSegment(seconds, secondOptions), minutes: parseSegment(minutes, minuteOptions), hours: parseSegment(hours, hourOptions), days: parseSegment(days, dayOptions), months: parseSegment(months, monthOptions), weekdays: parseSegment(weekdays, weekdayOptions) }).pipe(Either.map(make))}
/** * Parses a cron expression into a `Cron` instance. * * **Details** * * This function takes a cron expression as a string and attempts to parse it * into a `Cron` instance. If the expression is valid, the resulting `Cron` * instance will represent the schedule defined by the cron expression. * * If the expression is invalid, the function throws a `ParseError`. * * You can optionally provide a time zone (`tz`) to interpret the cron * expression in a specific time zone. If no time zone is provided, the cron * expression will use the default time zone. * * @example * ```ts * import { Cron } from "effect" * * // At 04:00 on every day-of-month from 8 through 14. * console.log(Cron.unsafeParse("0 4 8-14 * *")) * // Output: * // { * // _id: 'Cron', * // tz: { _id: 'Option', _tag: 'None' }, * // seconds: [ 0 ], * // minutes: [ 0 ], * // hours: [ 4 ], * // days: [ * // 8, 9, 10, 11, * // 12, 13, 14 * // ], * // months: [], * // weekdays: [] * // } * ``` * * @since 2.0.0 * @category constructors */export const unsafeParse = (cron: string, tz?: DateTime.TimeZone | string): Cron => Either.getOrThrowWith(parse(cron, tz), identity)
/** * Checks if a given `Date` falls within an active `Cron` time window. * * @example * ```ts * import * as assert from "node:assert" * import { Cron, Either } from "effect" * * const cron = Either.getOrThrow(Cron.parse("0 4 8-14 * *")) * assert.deepStrictEqual(Cron.match(cron, new Date("2021-01-08 04:00:00")), true) * assert.deepStrictEqual(Cron.match(cron, new Date("2021-01-08 05:00:00")), false) * ``` * * @throws `IllegalArgumentException` if the given `DateTime.Input` is invalid. * * @since 2.0.0 */export const match = (cron: Cron, date: DateTime.DateTime.Input): boolean => { const parts = dateTime.unsafeMakeZoned(date, { timeZone: Option.getOrUndefined(cron.tz) }).pipe(dateTime.toParts)
if (cron.seconds.size !== 0 && !cron.seconds.has(parts.seconds)) { return false }
if (cron.minutes.size !== 0 && !cron.minutes.has(parts.minutes)) { return false }
if (cron.hours.size !== 0 && !cron.hours.has(parts.hours)) { return false }
if (cron.months.size !== 0 && !cron.months.has(parts.month)) { return false }
if (cron.days.size === 0 && cron.weekdays.size === 0) { return true }
if (cron.weekdays.size === 0) { return cron.days.has(parts.day) }
if (cron.days.size === 0) { return cron.weekdays.has(parts.weekDay) }
return cron.days.has(parts.day) || cron.weekdays.has(parts.weekDay)}
const daysInMonth = (date: Date): number => new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 0)).getUTCDate()
/** * Returns the next run `Date` for the given `Cron` instance. * * Uses the current time as a starting point if no value is provided for `startFrom`. * * @example * ```ts * import * as assert from "node:assert" * import { Cron, Either } from "effect" * * const after = new Date("2021-01-01 00:00:00") * const cron = Either.getOrThrow(Cron.parse("0 4 8-14 * *")) * assert.deepStrictEqual(Cron.next(cron, after), new Date("2021-01-08 04:00:00")) * ``` * * @throws `IllegalArgumentException` if the given `DateTime.Input` is invalid. * @throws `Error` if the next run date cannot be found within 10,000 iterations. * * @since 2.0.0 */export const next = (cron: Cron, startFrom?: DateTime.DateTime.Input): Date => { return stepCron(cron, startFrom, "next")}
/** * Returns the previous run `Date` for the given `Cron` instance. * * Uses the current time as a starting point if no value is provided for `startFrom`. * * @example * ```ts * import * as assert from "node:assert" * import { Cron, Either } from "effect" * * const before = new Date("2021-01-15 00:00:00") * const cron = Either.getOrThrow(Cron.parse("0 4 8-14 * *")) * assert.deepStrictEqual(Cron.prev(cron, before), new Date("2021-01-14 04:00:00")) * ``` * * @throws `IllegalArgumentException` if the given `DateTime.Input` is invalid. * @throws `Error` if the previous run date cannot be found within 10,000 iterations. * * @since 3.20.0 */export const prev = (cron: Cron, startFrom?: DateTime.DateTime.Input): Date => { return stepCron(cron, startFrom, "prev")}
/** @internal */const stepCron = (cron: Cron, startFrom: DateTime.DateTime.Input | undefined, direction: "next" | "prev"): Date => { const tz = Option.getOrUndefined(cron.tz) const zoned = dateTime.unsafeMakeZoned(startFrom ?? new Date(), { timeZone: tz })
const prev = direction === "prev" const tick = prev ? -1 : 1 const table = cron[direction] const boundary = prev ? cron.last : cron.first
const needsStep = prev ? (next: number, current: number) => next < current : (next: number, current: number) => next > current
const utc = tz !== undefined && dateTime.isTimeZoneNamed(tz) && tz.id === "UTC" const adjustDst = utc ? constVoid : (current: Date) => { const adjusted = dateTime.unsafeMakeZoned(current, { timeZone: zoned.zone, adjustForTimeZone: true, disambiguation: prev ? "later" : undefined }).pipe(dateTime.toDate)
const drift = current.getTime() - adjusted.getTime() if (prev ? drift !== 0 : drift > 0) { current.setTime(adjusted.getTime()) } }
const result = dateTime.mutate(zoned, (current) => { current.setUTCSeconds(current.getUTCSeconds() + tick, 0)
for (let i = 0; i < 10_000; i++) { if (cron.seconds.size !== 0) { const currentSecond = current.getUTCSeconds() const nextSecond = table.second[currentSecond] if (nextSecond === undefined) { current.setUTCMinutes(current.getUTCMinutes() + tick, boundary.second) adjustDst(current) continue } if (needsStep(nextSecond, currentSecond)) { current.setUTCSeconds(nextSecond) adjustDst(current) continue } }
if (cron.minutes.size !== 0) { const currentMinute = current.getUTCMinutes() const nextMinute = table.minute[currentMinute] if (nextMinute === undefined) { current.setUTCHours(current.getUTCHours() + tick, boundary.minute, boundary.second) adjustDst(current) continue } if (needsStep(nextMinute, currentMinute)) { current.setUTCMinutes(nextMinute, boundary.second) adjustDst(current) continue } }
if (cron.hours.size !== 0) { const currentHour = current.getUTCHours() const nextHour = table.hour[currentHour] if (nextHour === undefined) { current.setUTCDate(current.getUTCDate() + tick) current.setUTCHours(boundary.hour, boundary.minute, boundary.second) adjustDst(current) continue } if (needsStep(nextHour, currentHour)) { current.setUTCHours(nextHour, boundary.minute, boundary.second) adjustDst(current) continue } }
if (cron.weekdays.size !== 0 || cron.days.size !== 0) { let a: number = prev ? -Infinity : Infinity let b: number = prev ? -Infinity : Infinity
if (cron.weekdays.size !== 0) { const currentWeekday = current.getUTCDay() const nextWeekday = table.weekday[currentWeekday] if (nextWeekday === undefined) { a = prev ? currentWeekday - 7 + boundary.weekday : 7 - currentWeekday + boundary.weekday } else { a = nextWeekday - currentWeekday } }
// Only check day-of-month if weekday constraint not already satisfied (they're OR'd) if (cron.days.size !== 0 && a !== 0) { const currentDay = current.getUTCDate() const nextDay = table.day[currentDay] if (nextDay === undefined) { if (prev) { // When wrapping to previous month, calculate days back: // Current day offset + gap from end of prev month to target day // Example: June 3 → May 20 with boundary.day=20: -(3 + (31 - 20)) = -14 const prevMonthDays = daysInMonth( new Date(Date.UTC(current.getUTCFullYear(), current.getUTCMonth(), 0)) ) b = -(currentDay + (prevMonthDays - boundary.day)) } else { b = daysInMonth(current) - currentDay + boundary.day } } else { b = nextDay - currentDay } }
const addDays = prev ? Math.max(a, b) : Math.min(a, b) if (addDays !== 0) { current.setUTCDate(current.getUTCDate() + addDays) current.setUTCHours(boundary.hour, boundary.minute, boundary.second) adjustDst(current) continue } }
if (cron.months.size !== 0) { const currentMonth = current.getUTCMonth() + 1 const nextMonth = table.month[currentMonth] const clampBoundaryDay = (targetMonthIndex: number): number => { if (cron.days.size !== 0) { return boundary.day } const maxDayInMonth = daysInMonth(new Date(Date.UTC(current.getUTCFullYear(), targetMonthIndex, 1))) return Math.min(boundary.day, maxDayInMonth) } if (nextMonth === undefined) { current.setUTCFullYear(current.getUTCFullYear() + tick) current.setUTCMonth(boundary.month, clampBoundaryDay(boundary.month)) current.setUTCHours(boundary.hour, boundary.minute, boundary.second) adjustDst(current) continue } if (needsStep(nextMonth, currentMonth)) { const targetMonthIndex = nextMonth - 1 current.setUTCMonth(targetMonthIndex, clampBoundaryDay(targetMonthIndex)) current.setUTCHours(boundary.hour, boundary.minute, boundary.second) adjustDst(current) continue } }
return }
throw new Error("Unable to find next cron date") })
return dateTime.toDateUtc(result)}
/** * Returns an `IterableIterator` which yields the sequence of `Date`s that match the `Cron` instance. * * @since 2.0.0 */export const sequence = function*(cron: Cron, startFrom?: DateTime.DateTime.Input): IterableIterator<Date> { while (true) { yield startFrom = next(cron, startFrom) }}
/** * Returns an `IterableIterator` which yields the sequence of `Date`s that match the `Cron` instance, * in reverse direction. * * @since 3.20.0 */export const sequenceReverse = function*(cron: Cron, startFrom?: DateTime.DateTime.Input): IterableIterator<Date> { while (true) { yield startFrom = prev(cron, startFrom) }}
/** * @category instances * @since 2.0.0 */export const Equivalence: equivalence.Equivalence<Cron> = equivalence.make((self, that) => restrictionsEquals(self.seconds, that.seconds) && restrictionsEquals(self.minutes, that.minutes) && restrictionsEquals(self.hours, that.hours) && restrictionsEquals(self.days, that.days) && restrictionsEquals(self.months, that.months) && restrictionsEquals(self.weekdays, that.weekdays))
const restrictionsArrayEquals = equivalence.array(equivalence.number)const restrictionsEquals = (self: ReadonlySet<number>, that: ReadonlySet<number>): boolean => restrictionsArrayEquals(Arr.fromIterable(self), Arr.fromIterable(that))
/** * Checks if two `Cron`s are equal. * * @since 2.0.0 * @category predicates */export const equals: { /** * Checks if two `Cron`s are equal. * * @since 2.0.0 * @category predicates */ (that: Cron): (self: Cron) => boolean /** * Checks if two `Cron`s are equal. * * @since 2.0.0 * @category predicates */ (self: Cron, that: Cron): boolean} = dual(2, (self: Cron, that: Cron): boolean => Equivalence(self, that))
interface SegmentOptions { min: number max: number aliases?: Record<string, number> | undefined}
const secondOptions: SegmentOptions = { min: 0, max: 59}
const minuteOptions: SegmentOptions = { min: 0, max: 59}
const hourOptions: SegmentOptions = { min: 0, max: 23}
const dayOptions: SegmentOptions = { min: 1, max: 31}
const monthOptions: SegmentOptions = { min: 1, max: 12, aliases: { jan: 1, feb: 2, mar: 3, apr: 4, may: 5, jun: 6, jul: 7, aug: 8, sep: 9, oct: 10, nov: 11, dec: 12 }}
const weekdayOptions: SegmentOptions = { min: 0, max: 6, aliases: { sun: 0, mon: 1, tue: 2, wed: 3, thu: 4, fri: 5, sat: 6 }}
const parseSegment = ( input: string, options: SegmentOptions): Either.Either<ReadonlySet<number>, ParseError> => { const capacity = options.max - options.min + 1 const values = new Set<number>() const fields = input.split(",")
for (const field of fields) { const [raw, step] = splitStep(field) if (raw === "*" && step === undefined) { return Either.right(new Set()) }
if (step !== undefined) { if (!Number.isInteger(step)) { return Either.left(new ParseError({ message: `Expected step value to be a positive integer`, input })) } if (step < 1) { return Either.left(new ParseError({ message: `Expected step value to be greater than 0`, input })) } if (step > options.max) { return Either.left(new ParseError({ message: `Expected step value to be less than ${options.max}`, input })) } }
if (raw === "*") { for (let i = options.min; i <= options.max; i += step ?? 1) { values.add(i) } } else { const [left, right] = splitRange(raw, options.aliases) if (!Number.isInteger(left)) { return Either.left(new ParseError({ message: `Expected a positive integer`, input })) } if (left < options.min || left > options.max) { return Either.left( new ParseError({ message: `Expected a value between ${options.min} and ${options.max}`, input }) ) }
if (right === undefined) { values.add(left) } else { if (!Number.isInteger(right)) { return Either.left(new ParseError({ message: `Expected a positive integer`, input })) } if (right < options.min || right > options.max) { return Either.left( new ParseError({ message: `Expected a value between ${options.min} and ${options.max}`, input }) ) } if (left > right) { return Either.left(new ParseError({ message: `Invalid value range`, input })) }
for (let i = left; i <= right; i += step ?? 1) { values.add(i) } } }
if (values.size >= capacity) { return Either.right(new Set()) } }
return Either.right(values)}
const splitStep = (input: string): [string, number | undefined] => { const seperator = input.indexOf("/") if (seperator !== -1) { return [input.slice(0, seperator), Number(input.slice(seperator + 1))] }
return [input, undefined]}
const splitRange = (input: string, aliases?: Record<string, number>): [number, number | undefined] => { const seperator = input.indexOf("-") if (seperator !== -1) { return [aliasOrValue(input.slice(0, seperator), aliases), aliasOrValue(input.slice(seperator + 1), aliases)] }
return [aliasOrValue(input, aliases), undefined]}
function aliasOrValue(field: string, aliases?: Record<string, number>): number { return aliases?.[field.toLocaleLowerCase()] ?? Number(field)}12345678910111213141516171819202122232425262728293031323334/** * @since 2.0.0 */import type * as Clock from "./Clock.js"import type * as ConfigProvider from "./ConfigProvider.js"import type * as Console from "./Console.js"import type * as Context from "./Context.js"import type * as FiberRef from "./FiberRef.js"import * as internal from "./internal/defaultServices.js"import type * as Random from "./Random.js"import type * as Tracer from "./Tracer.js"
/** * @since 2.0.0 * @category models */export type DefaultServices = | Clock.Clock | Console.Console | Random.Random | ConfigProvider.ConfigProvider | Tracer.Tracer
/** * @since 2.0.0 * @category constructors */export const liveServices: Context.Context<DefaultServices> = internal.liveServices
/** * @since 2.0.0 * @category fiberRefs */export const currentServices: FiberRef.FiberRef<Context.Context<DefaultServices>> = internal.currentServices123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471/** * @since 2.0.0 */import type * as Cause from "./Cause.js"import type * as Effect from "./Effect.js"import type * as Exit from "./Exit.js"import type * as FiberId from "./FiberId.js"import type { LazyArg } from "./Function.js"import * as core from "./internal/core.js"import * as internal from "./internal/deferred.js"import type * as MutableRef from "./MutableRef.js"import type * as Option from "./Option.js"import type * as Types from "./Types.js"import type * as Unify from "./Unify.js"
/** * @since 2.0.0 * @category symbols */export const DeferredTypeId: unique symbol = internal.DeferredTypeId
/** * @since 2.0.0 * @category symbols */export type DeferredTypeId = typeof DeferredTypeId
/** * A `Deferred` represents an asynchronous variable that can be set exactly * once, with the ability for an arbitrary number of fibers to suspend (by * calling `Deferred.await`) and automatically resume when the variable is set. * * `Deferred` can be used for building primitive actions whose completions * require the coordinated action of multiple fibers, and for building * higher-level concurrent or asynchronous structures. * * @since 2.0.0 * @category models */export interface Deferred<in out A, in out E = never> extends Effect.Effect<A, E>, Deferred.Variance<A, E> { /** @internal */ readonly state: MutableRef.MutableRef<internal.State<A, E>> /** @internal */ readonly blockingOn: FiberId.FiberId readonly [Unify.typeSymbol]?: unknown readonly [Unify.unifySymbol]?: DeferredUnify<this> readonly [Unify.ignoreSymbol]?: DeferredUnifyIgnore}
/** * @category models * @since 3.8.0 */export interface DeferredUnify<A extends { [Unify.typeSymbol]?: any }> extends Effect.EffectUnify<A> { Deferred?: () => Extract<A[Unify.typeSymbol], Deferred<any, any>>}
/** * @category models * @since 3.8.0 */export interface DeferredUnifyIgnore extends Effect.EffectUnifyIgnore { Effect?: true}
/** * @since 2.0.0 */export declare namespace Deferred { /** * @since 2.0.0 * @category models */ export interface Variance<in out A, in out E> { readonly [DeferredTypeId]: { readonly _A: Types.Invariant<A> readonly _E: Types.Invariant<E> } }}
/** * Creates a new `Deferred`. * * @since 2.0.0 * @category constructors */export const make: <A, E = never>() => Effect.Effect<Deferred<A, E>> = core.deferredMake
/** * Creates a new `Deferred` from the specified `FiberId`. * * @since 2.0.0 * @category constructors */export const makeAs: <A, E = never>(fiberId: FiberId.FiberId) => Effect.Effect<Deferred<A, E>> = core.deferredMakeAs
const _await: <A, E>(self: Deferred<A, E>) => Effect.Effect<A, E> = core.deferredAwait
export { /** * Retrieves the value of the `Deferred`, suspending the fiber running the * workflow until the result is available. * * @since 2.0.0 * @category getters */ _await as await}
/** * Completes the deferred with the result of the specified effect. If the * deferred has already been completed, the method will produce false. * * Note that `Deferred.completeWith` will be much faster, so consider using * that if you do not need to memoize the result of the specified effect. * * @since 2.0.0 * @category utils */export const complete: { /** * Completes the deferred with the result of the specified effect. If the * deferred has already been completed, the method will produce false. * * Note that `Deferred.completeWith` will be much faster, so consider using * that if you do not need to memoize the result of the specified effect. * * @since 2.0.0 * @category utils */ <A, E>(effect: Effect.Effect<A, E>): (self: Deferred<A, E>) => Effect.Effect<boolean> /** * Completes the deferred with the result of the specified effect. If the * deferred has already been completed, the method will produce false. * * Note that `Deferred.completeWith` will be much faster, so consider using * that if you do not need to memoize the result of the specified effect. * * @since 2.0.0 * @category utils */ <A, E>(self: Deferred<A, E>, effect: Effect.Effect<A, E>): Effect.Effect<boolean>} = core.deferredComplete
/** * Completes the deferred with the result of the specified effect. If the * deferred has already been completed, the method will produce false. * * @since 2.0.0 * @category utils */export const completeWith: { /** * Completes the deferred with the result of the specified effect. If the * deferred has already been completed, the method will produce false. * * @since 2.0.0 * @category utils */ <A, E>(effect: Effect.Effect<A, E>): (self: Deferred<A, E>) => Effect.Effect<boolean> /** * Completes the deferred with the result of the specified effect. If the * deferred has already been completed, the method will produce false. * * @since 2.0.0 * @category utils */ <A, E>(self: Deferred<A, E>, effect: Effect.Effect<A, E>): Effect.Effect<boolean>} = core.deferredCompleteWith
/** * Exits the `Deferred` with the specified `Exit` value, which will be * propagated to all fibers waiting on the value of the `Deferred`. * * @since 2.0.0 * @category utils */export const done: { /** * Exits the `Deferred` with the specified `Exit` value, which will be * propagated to all fibers waiting on the value of the `Deferred`. * * @since 2.0.0 * @category utils */ <A, E>(exit: Exit.Exit<A, E>): (self: Deferred<A, E>) => Effect.Effect<boolean> /** * Exits the `Deferred` with the specified `Exit` value, which will be * propagated to all fibers waiting on the value of the `Deferred`. * * @since 2.0.0 * @category utils */ <A, E>(self: Deferred<A, E>, exit: Exit.Exit<A, E>): Effect.Effect<boolean>} = core.deferredDone
/** * Fails the `Deferred` with the specified error, which will be propagated to * all fibers waiting on the value of the `Deferred`. * * @since 2.0.0 * @category utils */export const fail: { /** * Fails the `Deferred` with the specified error, which will be propagated to * all fibers waiting on the value of the `Deferred`. * * @since 2.0.0 * @category utils */ <E>(error: E): <A>(self: Deferred<A, E>) => Effect.Effect<boolean> /** * Fails the `Deferred` with the specified error, which will be propagated to * all fibers waiting on the value of the `Deferred`. * * @since 2.0.0 * @category utils */ <A, E>(self: Deferred<A, E>, error: E): Effect.Effect<boolean>} = core.deferredFail
/** * Fails the `Deferred` with the specified error, which will be propagated to * all fibers waiting on the value of the `Deferred`. * * @since 2.0.0 * @category utils */export const failSync: { /** * Fails the `Deferred` with the specified error, which will be propagated to * all fibers waiting on the value of the `Deferred`. * * @since 2.0.0 * @category utils */ <E>(evaluate: LazyArg<E>): <A>(self: Deferred<A, E>) => Effect.Effect<boolean> /** * Fails the `Deferred` with the specified error, which will be propagated to * all fibers waiting on the value of the `Deferred`. * * @since 2.0.0 * @category utils */ <A, E>(self: Deferred<A, E>, evaluate: LazyArg<E>): Effect.Effect<boolean>} = core.deferredFailSync
/** * Fails the `Deferred` with the specified `Cause`, which will be propagated to * all fibers waiting on the value of the `Deferred`. * * @since 2.0.0 * @category utils */export const failCause: { /** * Fails the `Deferred` with the specified `Cause`, which will be propagated to * all fibers waiting on the value of the `Deferred`. * * @since 2.0.0 * @category utils */ <E>(cause: Cause.Cause<E>): <A>(self: Deferred<A, E>) => Effect.Effect<boolean> /** * Fails the `Deferred` with the specified `Cause`, which will be propagated to * all fibers waiting on the value of the `Deferred`. * * @since 2.0.0 * @category utils */ <A, E>(self: Deferred<A, E>, cause: Cause.Cause<E>): Effect.Effect<boolean>} = core.deferredFailCause
/** * Fails the `Deferred` with the specified `Cause`, which will be propagated to * all fibers waiting on the value of the `Deferred`. * * @since 2.0.0 * @category utils */export const failCauseSync: { /** * Fails the `Deferred` with the specified `Cause`, which will be propagated to * all fibers waiting on the value of the `Deferred`. * * @since 2.0.0 * @category utils */ <E>(evaluate: LazyArg<Cause.Cause<E>>): <A>(self: Deferred<A, E>) => Effect.Effect<boolean> /** * Fails the `Deferred` with the specified `Cause`, which will be propagated to * all fibers waiting on the value of the `Deferred`. * * @since 2.0.0 * @category utils */ <A, E>(self: Deferred<A, E>, evaluate: LazyArg<Cause.Cause<E>>): Effect.Effect<boolean>} = core.deferredFailCauseSync
/** * Kills the `Deferred` with the specified defect, which will be propagated to * all fibers waiting on the value of the `Deferred`. * * @since 2.0.0 * @category utils */export const die: { /** * Kills the `Deferred` with the specified defect, which will be propagated to * all fibers waiting on the value of the `Deferred`. * * @since 2.0.0 * @category utils */ (defect: unknown): <A, E>(self: Deferred<A, E>) => Effect.Effect<boolean> /** * Kills the `Deferred` with the specified defect, which will be propagated to * all fibers waiting on the value of the `Deferred`. * * @since 2.0.0 * @category utils */ <A, E>(self: Deferred<A, E>, defect: unknown): Effect.Effect<boolean>} = core.deferredDie
/** * Kills the `Deferred` with the specified defect, which will be propagated to * all fibers waiting on the value of the `Deferred`. * * @since 2.0.0 * @category utils */export const dieSync: { /** * Kills the `Deferred` with the specified defect, which will be propagated to * all fibers waiting on the value of the `Deferred`. * * @since 2.0.0 * @category utils */ (evaluate: LazyArg<unknown>): <A, E>(self: Deferred<A, E>) => Effect.Effect<boolean> /** * Kills the `Deferred` with the specified defect, which will be propagated to * all fibers waiting on the value of the `Deferred`. * * @since 2.0.0 * @category utils */ <A, E>(self: Deferred<A, E>, evaluate: LazyArg<unknown>): Effect.Effect<boolean>} = core.deferredDieSync
/** * Completes the `Deferred` with interruption. This will interrupt all fibers * waiting on the value of the `Deferred` with the `FiberId` of the fiber * calling this method. * * @since 2.0.0 * @category utils */export const interrupt: <A, E>(self: Deferred<A, E>) => Effect.Effect<boolean> = core.deferredInterrupt
/** * Completes the `Deferred` with interruption. This will interrupt all fibers * waiting on the value of the `Deferred` with the specified `FiberId`. * * @since 2.0.0 * @category utils */export const interruptWith: { /** * Completes the `Deferred` with interruption. This will interrupt all fibers * waiting on the value of the `Deferred` with the specified `FiberId`. * * @since 2.0.0 * @category utils */ (fiberId: FiberId.FiberId): <A, E>(self: Deferred<A, E>) => Effect.Effect<boolean> /** * Completes the `Deferred` with interruption. This will interrupt all fibers * waiting on the value of the `Deferred` with the specified `FiberId`. * * @since 2.0.0 * @category utils */ <A, E>(self: Deferred<A, E>, fiberId: FiberId.FiberId): Effect.Effect<boolean>} = core.deferredInterruptWith
/** * Returns `true` if this `Deferred` has already been completed with a value or * an error, `false` otherwise. * * @since 2.0.0 * @category getters */export const isDone: <A, E>(self: Deferred<A, E>) => Effect.Effect<boolean> = core.deferredIsDone
/** * Returns a `Some<Effect<A, E, R>>` from the `Deferred` if this `Deferred` has * already been completed, `None` otherwise. * * @since 2.0.0 * @category getters */export const poll: <A, E>( self: Deferred<A, E>) => Effect.Effect<Option.Option<Effect.Effect<A, E>>> = core.deferredPoll
/** * Completes the `Deferred` with the specified value. * * @since 2.0.0 * @category utils */export const succeed: { /** * Completes the `Deferred` with the specified value. * * @since 2.0.0 * @category utils */ <A>(value: A): <E>(self: Deferred<A, E>) => Effect.Effect<boolean> /** * Completes the `Deferred` with the specified value. * * @since 2.0.0 * @category utils */ <A, E>(self: Deferred<A, E>, value: A): Effect.Effect<boolean>} = core.deferredSucceed
/** * Completes the `Deferred` with the specified lazily evaluated value. * * @since 2.0.0 * @category utils */export const sync: { /** * Completes the `Deferred` with the specified lazily evaluated value. * * @since 2.0.0 * @category utils */ <A>(evaluate: LazyArg<A>): <E>(self: Deferred<A, E>) => Effect.Effect<boolean> /** * Completes the `Deferred` with the specified lazily evaluated value. * * @since 2.0.0 * @category utils */ <A, E>(self: Deferred<A, E>, evaluate: LazyArg<A>): Effect.Effect<boolean>} = core.deferredSync
/** * Unsafely creates a new `Deferred` from the specified `FiberId`. * * @since 2.0.0 * @category unsafe */export const unsafeMake: <A, E = never>(fiberId: FiberId.FiberId) => Deferred<A, E> = core.deferredUnsafeMake
/** * Unsafely exits the `Deferred` with the specified `Exit` value, which will be * propagated to all fibers waiting on the value of the `Deferred`. * * @since 2.0.0 * @category unsafe */export const unsafeDone: <A, E>(self: Deferred<A, E>, effect: Effect.Effect<A, E>) => void = core.deferredUnsafeDone123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512/** * @since 2.0.0 */import type { Chunk } from "./Chunk.js"import type { Context } from "./Context.js"import type { Either } from "./Either.js"import type { Equal } from "./Equal.js"import * as Dual from "./Function.js"import type { HashMap } from "./HashMap.js"import type { HashSet } from "./HashSet.js"import * as internal from "./internal/differ.js"import * as ChunkPatch from "./internal/differ/chunkPatch.js"import * as ContextPatch from "./internal/differ/contextPatch.js"import * as HashMapPatch from "./internal/differ/hashMapPatch.js"import * as HashSetPatch from "./internal/differ/hashSetPatch.js"import * as OrPatch from "./internal/differ/orPatch.js"import * as ReadonlyArrayPatch from "./internal/differ/readonlyArrayPatch.js"import type { Pipeable } from "./Pipeable.js"import type * as Types from "./Types.js"
/** * @since 2.0.0 * @category symbol */export const TypeId: unique symbol = internal.DifferTypeId as TypeId
/** * @since 2.0.0 * @category symbol */export type TypeId = typeof TypeId
/** * A `Differ<Value, Patch>` knows how to compare an old value and new value of * type `Value` to produce a patch of type `Patch` that describes the * differences between those values. A `Differ` also knows how to apply a patch * to an old value to produce a new value that represents the old value updated * with the changes described by the patch. * * A `Differ` can be used to construct a `FiberRef` supporting compositional * updates using the `FiberRef.makePatch` constructor. * * The `Differ` companion object contains constructors for `Differ` values for * common data types such as `Chunk`, `HashMap`, and `HashSet``. In addition, * `Differ`values can be transformed using the `transform` operator and combined * using the `orElseEither` and `zip` operators. This allows creating `Differ` * values for arbitrarily complex data types compositionally. * * @since 2.0.0 * @category models */export interface Differ<in out Value, in out Patch> extends Pipeable { readonly [TypeId]: { readonly _V: Types.Invariant<Value> readonly _P: Types.Invariant<Patch> } readonly empty: Patch diff(oldValue: Value, newValue: Value): Patch combine(first: Patch, second: Patch): Patch patch(patch: Patch, oldValue: Value): Value}
const ChunkPatchTypeId: unique symbol = ChunkPatch.ChunkPatchTypeId as Differ.Chunk.TypeIdconst ContextPatchTypeId: unique symbol = ContextPatch.ContextPatchTypeId as Differ.Context.TypeIdconst HashMapPatchTypeId: unique symbol = HashMapPatch.HashMapPatchTypeId as Differ.HashMap.TypeIdconst HashSetPatchTypeId: unique symbol = HashSetPatch.HashSetPatchTypeId as Differ.HashSet.TypeIdconst OrPatchTypeId: unique symbol = OrPatch.OrPatchTypeId as Differ.Or.TypeIdconst ReadonlyArrayPatchTypeId: unique symbol = ReadonlyArrayPatch .ReadonlyArrayPatchTypeId as Differ.ReadonlyArray.TypeId
/** * @since 2.0.0 */export declare namespace Differ { /** * @since 2.0.0 */ export namespace Context { /** * @since 2.0.0 * @category symbol */ export type TypeId = typeof ContextPatchTypeId /** * A `Patch<Input, Output>` describes an update that transforms a `Env<Input>` * to a `Env<Output>` as a data structure. This allows combining updates to * different services in the environment in a compositional way. * * @since 2.0.0 * @category models */ export interface Patch<in Input, out Output> extends Equal { readonly [ContextPatchTypeId]: { readonly _Input: Types.Contravariant<Input> readonly _Output: Types.Covariant<Output> } } }
/** * @since 2.0.0 */ export namespace Chunk { /** * @since 2.0.0 * @category symbol */ export type TypeId = typeof ChunkPatchTypeId /** * A patch which describes updates to a chunk of values. * * @since 2.0.0 * @category models */ export interface Patch<in out Value, in out Patch> extends Equal { readonly [ChunkPatchTypeId]: { readonly _Value: Types.Invariant<Value> readonly _Patch: Types.Invariant<Patch> } } }
/** * @since 2.0.0 */ export namespace HashMap { /** * @since 2.0.0 * @category symbol */ export type TypeId = typeof HashMapPatchTypeId /** * A patch which describes updates to a map of keys and values. * * @since 2.0.0 * @category models */ export interface Patch<in out Key, in out Value, in out Patch> extends Equal { readonly [HashMapPatchTypeId]: { readonly _Key: Types.Invariant<Key> readonly _Value: Types.Invariant<Value> readonly _Patch: Types.Invariant<Patch> } } }
/** * @since 2.0.0 */ export namespace HashSet { /** * @since 2.0.0 * @category symbol */ export type TypeId = typeof HashSetPatchTypeId /** * A patch which describes updates to a set of values. * * @since 2.0.0 * @category models */ export interface Patch<in out Value> extends Equal { readonly [HashSetPatchTypeId]: { readonly _Value: Types.Invariant<Value> } } }
/** * @since 2.0.0 */ export namespace Or { /** * @since 2.0.0 * @category symbol */ export type TypeId = typeof OrPatchTypeId /** * A patch which describes updates to either one value or another. * * @since 2.0.0 * @category models */ export interface Patch<in out Value, in out Value2, in out Patch, in out Patch2> extends Equal { readonly [OrPatchTypeId]: { readonly _Value: Types.Invariant<Value> readonly _Value2: Types.Invariant<Value2> readonly _Patch: Types.Invariant<Patch> readonly _Patch2: Types.Invariant<Patch2> } } }
/** * @since 2.0.0 */ export namespace ReadonlyArray { /** * @since 2.0.0 * @category symbol */ export type TypeId = typeof ReadonlyArrayPatchTypeId /** * A patch which describes updates to a ReadonlyArray of values. * * @since 2.0.0 * @category models */ export interface Patch<in out Value, in out Patch> extends Equal { readonly [ReadonlyArrayPatchTypeId]: { readonly _Value: Types.Invariant<Value> readonly _Patch: Types.Invariant<Patch> } } }}
/** * An empty patch that describes no changes. * * @since 2.0.0 * @category patch */export const empty: <Value, Patch>(self: Differ<Value, Patch>) => Patch = ( self) => self.empty
/** * @since 2.0.0 * @category patch */export const diff: { /** * @since 2.0.0 * @category patch */ <Value>(oldValue: Value, newValue: Value): <Patch>( self: Differ<Value, Patch> ) => Patch /** * @since 2.0.0 * @category patch */ <Value, Patch>(self: Differ<Value, Patch>, oldValue: Value, newValue: Value): Patch} = Dual.dual( 3, <Value, Patch>( self: Differ<Value, Patch>, oldValue: Value, newValue: Value ): Patch => self.diff(oldValue, newValue))
/** * Combines two patches to produce a new patch that describes the updates of * the first patch and then the updates of the second patch. The combine * operation should be associative. In addition, if the combine operation is * commutative then joining multiple fibers concurrently will result in * deterministic `FiberRef` values. * * @since 2.0.0 * @category patch */export const combine: { /** * Combines two patches to produce a new patch that describes the updates of * the first patch and then the updates of the second patch. The combine * operation should be associative. In addition, if the combine operation is * commutative then joining multiple fibers concurrently will result in * deterministic `FiberRef` values. * * @since 2.0.0 * @category patch */ <Patch>(first: Patch, second: Patch): <Value>( self: Differ<Value, Patch> ) => Patch /** * Combines two patches to produce a new patch that describes the updates of * the first patch and then the updates of the second patch. The combine * operation should be associative. In addition, if the combine operation is * commutative then joining multiple fibers concurrently will result in * deterministic `FiberRef` values. * * @since 2.0.0 * @category patch */ <Value, Patch>(self: Differ<Value, Patch>, first: Patch, second: Patch): Patch} = Dual.dual( 3, <Value, Patch>( self: Differ<Value, Patch>, first: Patch, second: Patch ): Patch => self.combine(first, second))
/** * Applies a patch to an old value to produce a new value that is equal to the * old value with the updates described by the patch. * * @since 2.0.0 * @category patch */export const patch: { /** * Applies a patch to an old value to produce a new value that is equal to the * old value with the updates described by the patch. * * @since 2.0.0 * @category patch */ <Patch, Value>(patch: Patch, oldValue: Value): ( self: Differ<Value, Patch> ) => Value /** * Applies a patch to an old value to produce a new value that is equal to the * old value with the updates described by the patch. * * @since 2.0.0 * @category patch */ <Patch, Value>(self: Differ<Value, Patch>, patch: Patch, oldValue: Value): Value} = Dual.dual( 3, <Patch, Value>( self: Differ<Value, Patch>, patch: Patch, oldValue: Value ): Value => self.patch(patch, oldValue))
/** * Constructs a new `Differ`. * * @since 2.0.0 * @category constructors */export const make: <Value, Patch>(params: { readonly empty: Patch readonly diff: (oldValue: Value, newValue: Value) => Patch readonly combine: (first: Patch, second: Patch) => Patch readonly patch: (patch: Patch, oldValue: Value) => Value}) => Differ<Value, Patch> = internal.make
/** * Constructs a differ that knows how to diff `Env` values. * * @since 2.0.0 * @category constructors */export const environment: <A>() => Differ< Context<A>, Differ.Context.Patch<A, A>> = internal.environment
/** * Constructs a differ that knows how to diff a `Chunk` of values given a * differ that knows how to diff the values. * * @since 2.0.0 * @category constructors */export const chunk: <Value, Patch>( differ: Differ<Value, Patch>) => Differ<Chunk<Value>, Differ.Chunk.Patch<Value, Patch>> = internal.chunk
/** * Constructs a differ that knows how to diff a `HashMap` of keys and values given * a differ that knows how to diff the values. * * @since 2.0.0 * @category constructors */export const hashMap: <Key, Value, Patch>( differ: Differ<Value, Patch>) => Differ<HashMap<Key, Value>, Differ.HashMap.Patch<Key, Value, Patch>> = internal.hashMap
/** * Constructs a differ that knows how to diff a `HashSet` of values. * * @since 2.0.0 * @category constructors */export const hashSet: <Value>() => Differ< HashSet<Value>, Differ.HashSet.Patch<Value>> = internal.hashSet
/** * Combines this differ and the specified differ to produce a differ that * knows how to diff the sum of their values. * * @since 2.0.0 */export const orElseEither: { /** * Combines this differ and the specified differ to produce a differ that * knows how to diff the sum of their values. * * @since 2.0.0 */ <Value2, Patch2>(that: Differ<Value2, Patch2>): <Value, Patch>( self: Differ<Value, Patch> ) => Differ< Either<Value2, Value>, Differ.Or.Patch<Value, Value2, Patch, Patch2> > /** * Combines this differ and the specified differ to produce a differ that * knows how to diff the sum of their values. * * @since 2.0.0 */ <Value, Patch, Value2, Patch2>(self: Differ<Value, Patch>, that: Differ<Value2, Patch2>): Differ< Either<Value2, Value>, Differ.Or.Patch<Value, Value2, Patch, Patch2> >} = internal.orElseEither
/** * Constructs a differ that knows how to diff a `ReadonlyArray` of values. * * @since 2.0.0 * @category constructors */export const readonlyArray: <Value, Patch>( differ: Differ<Value, Patch>) => Differ<ReadonlyArray<Value>, Differ.ReadonlyArray.Patch<Value, Patch>> = internal.readonlyArray
/** * Transforms the type of values that this differ knows how to differ using * the specified functions that map the new and old value types to each other. * * @since 2.0.0 */export const transform: { /** * Transforms the type of values that this differ knows how to differ using * the specified functions that map the new and old value types to each other. * * @since 2.0.0 */ <Value, Value2>( options: { readonly toNew: (value: Value) => Value2 readonly toOld: (value: Value2) => Value } ): <Patch>(self: Differ<Value, Patch>) => Differ<Value2, Patch> /** * Transforms the type of values that this differ knows how to differ using * the specified functions that map the new and old value types to each other. * * @since 2.0.0 */ <Value, Patch, Value2>( self: Differ<Value, Patch>, options: { readonly toNew: (value: Value) => Value2 readonly toOld: (value: Value2) => Value } ): Differ<Value2, Patch>} = internal.transform
/** * Constructs a differ that just diffs two values by returning a function that * sets the value to the new value. This differ does not support combining * multiple updates to the value compositionally and should only be used when * there is no compositional way to update them. * * @since 2.0.0 */export const update: <A>() => Differ<A, (a: A) => A> = internal.update
/** * A variant of `update` that allows specifying the function that will be used * to combine old values with new values. * * @since 2.0.0 */export const updateWith: <A>(f: (x: A, y: A) => A) => Differ<A, (a: A) => A> = internal.updateWith
/** * Combines this differ and the specified differ to produce a new differ that * knows how to diff the product of their values. * * @since 2.0.0 */export const zip: { /** * Combines this differ and the specified differ to produce a new differ that * knows how to diff the product of their values. * * @since 2.0.0 */ <Value2, Patch2>(that: Differ<Value2, Patch2>): <Value, Patch>( self: Differ<Value, Patch> ) => Differ< readonly [Value, Value2], // readonly because invariant readonly [Patch, Patch2] // readonly because invariant > /** * Combines this differ and the specified differ to produce a new differ that * knows how to diff the product of their values. * * @since 2.0.0 */ <Value, Patch, Value2, Patch2>(self: Differ<Value, Patch>, that: Differ<Value2, Patch2>): Differ< readonly [Value, Value2], // readonly because invariant readonly [Patch, Patch2] // readonly because invariant >} = internal.zip123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140/** * @since 2.0.0 */import * as Equal from "./Equal.js"import type * as equivalence from "./Equivalence.js"import { dual } from "./Function.js"import * as Hash from "./Hash.js"import type { Inspectable } from "./Inspectable.js"import { NodeInspectSymbol } from "./Inspectable.js"import * as Option from "./Option.js"import * as order from "./Order.js"import type { Pipeable } from "./Pipeable.js"import { pipeArguments } from "./Pipeable.js"import { hasProperty, isBigInt, isNumber, isString } from "./Predicate.js"
const TypeId: unique symbol = Symbol.for("effect/Duration")
const bigint0 = BigInt(0)const bigint24 = BigInt(24)const bigint60 = BigInt(60)const bigint1e3 = BigInt(1_000)const bigint1e6 = BigInt(1_000_000)const bigint1e9 = BigInt(1_000_000_000)
/** * @since 2.0.0 * @category symbol */export type TypeId = typeof TypeId
/** * @since 2.0.0 * @category models */export interface Duration extends Equal.Equal, Pipeable, Inspectable { readonly [TypeId]: TypeId readonly value: DurationValue}/** * @since 2.0.0 * @category models */export type DurationValue = | { readonly _tag: "Millis" readonly millis: number } | { readonly _tag: "Nanos" readonly nanos: bigint } | { readonly _tag: "Infinity" }
/** * @since 2.0.0 * @category models */export type Unit = | "nano" | "nanos" | "micro" | "micros" | "milli" | "millis" | "second" | "seconds" | "minute" | "minutes" | "hour" | "hours" | "day" | "days" | "week" | "weeks"
/** * @since 2.0.0 * @category models */export type DurationInput = | Duration | number // millis | bigint // nanos | readonly [seconds: number, nanos: number] | `${number} ${Unit}`
const DURATION_REGEX = /^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/
/** * @since 2.0.0 */export const decode = (input: DurationInput): Duration => { if (isDuration(input)) { return input } else if (isNumber(input)) { return millis(input) } else if (isBigInt(input)) { return nanos(input) } else if (Array.isArray(input) && input.length === 2 && input.every(isNumber)) { if (input[0] === -Infinity || input[1] === -Infinity || Number.isNaN(input[0]) || Number.isNaN(input[1])) { return zero }
if (input[0] === Infinity || input[1] === Infinity) { return infinity }
return nanos(BigInt(Math.round(input[0] * 1_000_000_000)) + BigInt(Math.round(input[1]))) } else if (isString(input)) { const match = DURATION_REGEX.exec(input) if (match) { const [_, valueStr, unit] = match const value = Number(valueStr) switch (unit) { case "nano": case "nanos": return nanos(BigInt(valueStr)) case "micro": case "micros": return micros(BigInt(valueStr)) case "milli": case "millis": return millis(value) case "second": case "seconds": return seconds(value) case "minute": case "minutes": return minutes(value) case "hour": case "hours": return hours(value) case "day": case "days": return days(value) case "week": case "weeks": return weeks(value) } } } throw new Error("Invalid DurationInput")}
/** * @since 2.5.0 */export const decodeUnknown: (u: unknown) => Option.Option<Duration> = Option.liftThrowable(decode) as any
const zeroValue: DurationValue = { _tag: "Millis", millis: 0 }const infinityValue: DurationValue = { _tag: "Infinity" }
const DurationProto: Omit<Duration, "value"> = { [TypeId]: TypeId, [Hash.symbol](this: Duration) { return Hash.cached(this, Hash.structure(this.value)) }, [Equal.symbol](this: Duration, that: unknown): boolean { return isDuration(that) && equals(this, that) }, toString(this: Duration) { return `Duration(${format(this)})` }, toJSON(this: Duration) { switch (this.value._tag) { case "Millis": return { _id: "Duration", _tag: "Millis", millis: this.value.millis } case "Nanos": return { _id: "Duration", _tag: "Nanos", hrtime: toHrTime(this) } case "Infinity": return { _id: "Duration", _tag: "Infinity" } } }, [NodeInspectSymbol]() { return this.toJSON() }, pipe() { return pipeArguments(this, arguments) }} as const
const make = (input: number | bigint): Duration => { const duration = Object.create(DurationProto) if (isNumber(input)) { if (isNaN(input) || input <= 0) { duration.value = zeroValue } else if (!Number.isFinite(input)) { duration.value = infinityValue } else if (!Number.isInteger(input)) { duration.value = { _tag: "Nanos", nanos: BigInt(Math.round(input * 1_000_000)) } } else { duration.value = { _tag: "Millis", millis: input } } } else if (input <= bigint0) { duration.value = zeroValue } else { duration.value = { _tag: "Nanos", nanos: input } } return duration}
/** * @since 2.0.0 * @category guards */export const isDuration = (u: unknown): u is Duration => hasProperty(u, TypeId)
/** * @since 2.0.0 * @category guards */export const isFinite = (self: Duration): boolean => self.value._tag !== "Infinity"
/** * @since 3.5.0 * @category guards */export const isZero = (self: Duration): boolean => { switch (self.value._tag) { case "Millis": { return self.value.millis === 0 } case "Nanos": { return self.value.nanos === bigint0 } case "Infinity": { return false } }}
/** * @since 2.0.0 * @category constructors */export const zero: Duration = make(0)
/** * @since 2.0.0 * @category constructors */export const infinity: Duration = make(Infinity)
/** * @since 2.0.0 * @category constructors */export const nanos = (nanos: bigint): Duration => make(nanos)
/** * @since 2.0.0 * @category constructors */export const micros = (micros: bigint): Duration => make(micros * bigint1e3)
/** * @since 2.0.0 * @category constructors */export const millis = (millis: number): Duration => make(millis)
/** * @since 2.0.0 * @category constructors */export const seconds = (seconds: number): Duration => make(seconds * 1000)
/** * @since 2.0.0 * @category constructors */export const minutes = (minutes: number): Duration => make(minutes * 60_000)
/** * @since 2.0.0 * @category constructors */export const hours = (hours: number): Duration => make(hours * 3_600_000)
/** * @since 2.0.0 * @category constructors */export const days = (days: number): Duration => make(days * 86_400_000)
/** * @since 2.0.0 * @category constructors */export const weeks = (weeks: number): Duration => make(weeks * 604_800_000)
/** * @since 2.0.0 * @category getters */export const toMillis = (self: DurationInput): number => match(self, { onMillis: (millis) => millis, onNanos: (nanos) => Number(nanos) / 1_000_000 })
/** * @since 2.0.0 * @category getters */export const toSeconds = (self: DurationInput): number => match(self, { onMillis: (millis) => millis / 1_000, onNanos: (nanos) => Number(nanos) / 1_000_000_000 })
/** * @since 3.8.0 * @category getters */export const toMinutes = (self: DurationInput): number => match(self, { onMillis: (millis) => millis / 60_000, onNanos: (nanos) => Number(nanos) / 60_000_000_000 })
/** * @since 3.8.0 * @category getters */export const toHours = (self: DurationInput): number => match(self, { onMillis: (millis) => millis / 3_600_000, onNanos: (nanos) => Number(nanos) / 3_600_000_000_000 })
/** * @since 3.8.0 * @category getters */export const toDays = (self: DurationInput): number => match(self, { onMillis: (millis) => millis / 86_400_000, onNanos: (nanos) => Number(nanos) / 86_400_000_000_000 })
/** * @since 3.8.0 * @category getters */export const toWeeks = (self: DurationInput): number => match(self, { onMillis: (millis) => millis / 604_800_000, onNanos: (nanos) => Number(nanos) / 604_800_000_000_000 })
/** * Get the duration in nanoseconds as a bigint. * * If the duration is infinite, returns `Option.none()` * * @since 2.0.0 * @category getters */export const toNanos = (self: DurationInput): Option.Option<bigint> => { const _self = decode(self) switch (_self.value._tag) { case "Infinity": return Option.none() case "Nanos": return Option.some(_self.value.nanos) case "Millis": return Option.some(BigInt(Math.round(_self.value.millis * 1_000_000))) }}
/** * Get the duration in nanoseconds as a bigint. * * If the duration is infinite, it throws an error. * * @since 2.0.0 * @category getters */export const unsafeToNanos = (self: DurationInput): bigint => { const _self = decode(self) switch (_self.value._tag) { case "Infinity": throw new Error("Cannot convert infinite duration to nanos") case "Nanos": return _self.value.nanos case "Millis": return BigInt(Math.round(_self.value.millis * 1_000_000)) }}
/** * @since 2.0.0 * @category getters */export const toHrTime = (self: DurationInput): [seconds: number, nanos: number] => { const _self = decode(self) switch (_self.value._tag) { case "Infinity": return [Infinity, 0] case "Nanos": return [ Number(_self.value.nanos / bigint1e9), Number(_self.value.nanos % bigint1e9) ] case "Millis": return [ Math.floor(_self.value.millis / 1000), Math.round((_self.value.millis % 1000) * 1_000_000) ] }}
/** * @since 2.0.0 * @category pattern matching */export const match: { /** * @since 2.0.0 * @category pattern matching */ <A, B>( options: { readonly onMillis: (millis: number) => A readonly onNanos: (nanos: bigint) => B } ): (self: DurationInput) => A | B /** * @since 2.0.0 * @category pattern matching */ <A, B>( self: DurationInput, options: { readonly onMillis: (millis: number) => A readonly onNanos: (nanos: bigint) => B } ): A | B} = dual(2, <A, B>( self: DurationInput, options: { readonly onMillis: (millis: number) => A readonly onNanos: (nanos: bigint) => B }): A | B => { const _self = decode(self) switch (_self.value._tag) { case "Nanos": return options.onNanos(_self.value.nanos) case "Infinity": return options.onMillis(Infinity) case "Millis": return options.onMillis(_self.value.millis) }})
/** * @since 2.0.0 * @category pattern matching */export const matchWith: { /** * @since 2.0.0 * @category pattern matching */ <A, B>( that: DurationInput, options: { readonly onMillis: (self: number, that: number) => A readonly onNanos: (self: bigint, that: bigint) => B } ): (self: DurationInput) => A | B /** * @since 2.0.0 * @category pattern matching */ <A, B>( self: DurationInput, that: DurationInput, options: { readonly onMillis: (self: number, that: number) => A readonly onNanos: (self: bigint, that: bigint) => B } ): A | B} = dual(3, <A, B>( self: DurationInput, that: DurationInput, options: { readonly onMillis: (self: number, that: number) => A readonly onNanos: (self: bigint, that: bigint) => B }): A | B => { const _self = decode(self) const _that = decode(that) if (_self.value._tag === "Infinity" || _that.value._tag === "Infinity") { return options.onMillis( toMillis(_self), toMillis(_that) ) } else if (_self.value._tag === "Nanos" || _that.value._tag === "Nanos") { const selfNanos = _self.value._tag === "Nanos" ? _self.value.nanos : BigInt(Math.round(_self.value.millis * 1_000_000)) const thatNanos = _that.value._tag === "Nanos" ? _that.value.nanos : BigInt(Math.round(_that.value.millis * 1_000_000)) return options.onNanos(selfNanos, thatNanos) }
return options.onMillis( _self.value.millis, _that.value.millis )})
/** * @category instances * @since 2.0.0 */export const Order: order.Order<Duration> = order.make((self, that) => matchWith(self, that, { onMillis: (self, that) => (self < that ? -1 : self > that ? 1 : 0), onNanos: (self, that) => (self < that ? -1 : self > that ? 1 : 0) }))
/** * Checks if a `Duration` is between a `minimum` and `maximum` value. * * @category predicates * @since 2.0.0 */export const between: { /** * Checks if a `Duration` is between a `minimum` and `maximum` value. * * @category predicates * @since 2.0.0 */ ( options: { minimum: DurationInput maximum: DurationInput } ): (self: DurationInput) => boolean /** * Checks if a `Duration` is between a `minimum` and `maximum` value. * * @category predicates * @since 2.0.0 */ ( self: DurationInput, options: { minimum: DurationInput maximum: DurationInput } ): boolean} = order.between(order.mapInput(Order, decode))
/** * @category instances * @since 2.0.0 */export const Equivalence: equivalence.Equivalence<Duration> = (self, that) => matchWith(self, that, { onMillis: (self, that) => self === that, onNanos: (self, that) => self === that })
const _min = order.min(Order)
/** * @since 2.0.0 */export const min: { /** * @since 2.0.0 */ (that: DurationInput): (self: DurationInput) => Duration /** * @since 2.0.0 */ (self: DurationInput, that: DurationInput): Duration} = dual(2, (self: DurationInput, that: DurationInput): Duration => _min(decode(self), decode(that)))
const _max = order.max(Order)
/** * @since 2.0.0 * @category order */export const max: { /** * @since 2.0.0 * @category order */ (that: DurationInput): (self: DurationInput) => Duration /** * @since 2.0.0 * @category order */ (self: DurationInput, that: DurationInput): Duration} = dual(2, (self: DurationInput, that: DurationInput): Duration => _max(decode(self), decode(that)))
const _clamp = order.clamp(Order)
/** * @since 2.0.0 * @category order */export const clamp: { /** * @since 2.0.0 * @category order */ ( options: { minimum: DurationInput maximum: DurationInput } ): (self: DurationInput) => Duration /** * @since 2.0.0 * @category order */ ( self: DurationInput, options: { minimum: DurationInput maximum: DurationInput } ): Duration} = dual( 2, (self: DurationInput, options: { minimum: DurationInput maximum: DurationInput }): Duration => _clamp(decode(self), { minimum: decode(options.minimum), maximum: decode(options.maximum) }))
/** * @since 2.4.19 * @category math */export const divide: { /** * @since 2.4.19 * @category math */ (by: number): (self: DurationInput) => Option.Option<Duration> /** * @since 2.4.19 * @category math */ (self: DurationInput, by: number): Option.Option<Duration>} = dual( 2, (self: DurationInput, by: number): Option.Option<Duration> => match(self, { onMillis: (millis) => { if (by === 0 || isNaN(by) || !Number.isFinite(by)) { return Option.none() } return Option.some(make(millis / by)) }, onNanos: (nanos) => { if (isNaN(by) || by <= 0 || !Number.isFinite(by)) { return Option.none() } try { return Option.some(make(nanos / BigInt(by))) } catch { return Option.none() } } }))
/** * @since 2.4.19 * @category math */export const unsafeDivide: { /** * @since 2.4.19 * @category math */ (by: number): (self: DurationInput) => Duration /** * @since 2.4.19 * @category math */ (self: DurationInput, by: number): Duration} = dual( 2, (self: DurationInput, by: number): Duration => match(self, { onMillis: (millis) => make(millis / by), onNanos: (nanos) => { if (isNaN(by) || by < 0 || Object.is(by, -0)) { return zero } else if (Object.is(by, 0) || !Number.isFinite(by)) { return infinity } return make(nanos / BigInt(by)) } }))
/** * @since 2.0.0 * @category math */export const times: { /** * @since 2.0.0 * @category math */ (times: number): (self: DurationInput) => Duration /** * @since 2.0.0 * @category math */ (self: DurationInput, times: number): Duration} = dual( 2, (self: DurationInput, times: number): Duration => match(self, { onMillis: (millis) => make(millis * times), onNanos: (nanos) => make(nanos * BigInt(times)) }))
/** * @since 2.0.0 * @category math */export const subtract: { /** * @since 2.0.0 * @category math */ (that: DurationInput): (self: DurationInput) => Duration /** * @since 2.0.0 * @category math */ (self: DurationInput, that: DurationInput): Duration} = dual( 2, (self: DurationInput, that: DurationInput): Duration => matchWith(self, that, { onMillis: (self, that) => make(self - that), onNanos: (self, that) => make(self - that) }))
/** * @since 2.0.0 * @category math */export const sum: { /** * @since 2.0.0 * @category math */ (that: DurationInput): (self: DurationInput) => Duration /** * @since 2.0.0 * @category math */ (self: DurationInput, that: DurationInput): Duration} = dual( 2, (self: DurationInput, that: DurationInput): Duration => matchWith(self, that, { onMillis: (self, that) => make(self + that), onNanos: (self, that) => make(self + that) }))
/** * @since 2.0.0 * @category predicates */export const lessThan: { /** * @since 2.0.0 * @category predicates */ (that: DurationInput): (self: DurationInput) => boolean /** * @since 2.0.0 * @category predicates */ (self: DurationInput, that: DurationInput): boolean} = dual( 2, (self: DurationInput, that: DurationInput): boolean => matchWith(self, that, { onMillis: (self, that) => self < that, onNanos: (self, that) => self < that }))
/** * @since 2.0.0 * @category predicates */export const lessThanOrEqualTo: { /** * @since 2.0.0 * @category predicates */ (that: DurationInput): (self: DurationInput) => boolean /** * @since 2.0.0 * @category predicates */ (self: DurationInput, that: DurationInput): boolean} = dual( 2, (self: DurationInput, that: DurationInput): boolean => matchWith(self, that, { onMillis: (self, that) => self <= that, onNanos: (self, that) => self <= that }))
/** * @since 2.0.0 * @category predicates */export const greaterThan: { /** * @since 2.0.0 * @category predicates */ (that: DurationInput): (self: DurationInput) => boolean /** * @since 2.0.0 * @category predicates */ (self: DurationInput, that: DurationInput): boolean} = dual( 2, (self: DurationInput, that: DurationInput): boolean => matchWith(self, that, { onMillis: (self, that) => self > that, onNanos: (self, that) => self > that }))
/** * @since 2.0.0 * @category predicates */export const greaterThanOrEqualTo: { /** * @since 2.0.0 * @category predicates */ (that: DurationInput): (self: DurationInput) => boolean /** * @since 2.0.0 * @category predicates */ (self: DurationInput, that: DurationInput): boolean} = dual( 2, (self: DurationInput, that: DurationInput): boolean => matchWith(self, that, { onMillis: (self, that) => self >= that, onNanos: (self, that) => self >= that }))
/** * @since 2.0.0 * @category predicates */export const equals: { /** * @since 2.0.0 * @category predicates */ (that: DurationInput): (self: DurationInput) => boolean /** * @since 2.0.0 * @category predicates */ (self: DurationInput, that: DurationInput): boolean} = dual(2, (self: DurationInput, that: DurationInput): boolean => Equivalence(decode(self), decode(that)))
/** * Converts a `Duration` to its parts. * * @since 3.8.0 * @category conversions */export const parts = (self: DurationInput): { days: number hours: number minutes: number seconds: number millis: number nanos: number} => { const duration = decode(self) if (duration.value._tag === "Infinity") { return { days: Infinity, hours: Infinity, minutes: Infinity, seconds: Infinity, millis: Infinity, nanos: Infinity } }
const nanos = unsafeToNanos(duration) const ms = nanos / bigint1e6 const sec = ms / bigint1e3 const min = sec / bigint60 const hr = min / bigint60 const days = hr / bigint24
return { days: Number(days), hours: Number(hr % bigint24), minutes: Number(min % bigint60), seconds: Number(sec % bigint60), millis: Number(ms % bigint1e3), nanos: Number(nanos % bigint1e6) }}
/** * Converts a `Duration` to a human readable string. * * @since 2.0.0 * @category conversions * @example * ```ts * import { Duration } from "effect" * * Duration.format(Duration.millis(1000)) // "1s" * Duration.format(Duration.millis(1001)) // "1s 1ms" * ``` */export const format = (self: DurationInput): string => { const duration = decode(self) if (duration.value._tag === "Infinity") { return "Infinity" } if (isZero(duration)) { return "0" }
const fragments = parts(duration) const pieces = [] if (fragments.days !== 0) { pieces.push(`${fragments.days}d`) }
if (fragments.hours !== 0) { pieces.push(`${fragments.hours}h`) }
if (fragments.minutes !== 0) { pieces.push(`${fragments.minutes}m`) }
if (fragments.seconds !== 0) { pieces.push(`${fragments.seconds}s`) }
if (fragments.millis !== 0) { pieces.push(`${fragments.millis}ms`) }
if (fragments.nanos !== 0) { pieces.push(`${fragments.nanos}ns`) }
return pieces.join(" ")}
/** * Formats a Duration into an ISO8601 duration string. * * Months are assumed to be 30 days and years are assumed to be 365 days. * * Milliseconds and nanoseconds are expressed as fractional seconds. * * @example * ```ts * import { Duration } from "effect" * * Duration.unsafeFormatIso(Duration.days(1)) // => "P1D" * Duration.unsafeFormatIso(Duration.minutes(90)) // => "PT1H30M" * Duration.unsafeFormatIso(Duration.millis(1500)) // => "PT1.5S" * ``` * * @throws `RangeError` If the duration is not finite. * * @since 3.13.0 * @category conversions */export const unsafeFormatIso = (self: DurationInput): string => { const duration = decode(self) if (!isFinite(duration)) { throw new RangeError("Cannot format infinite duration") }
const fragments = [] const { days, hours, millis, minutes, nanos, seconds } = parts(duration)
let rest = days if (rest >= 365) { const years = Math.floor(rest / 365) rest %= 365 fragments.push(`${years}Y`) }
if (rest >= 30) { const months = Math.floor(rest / 30) rest %= 30 fragments.push(`${months}M`) }
if (rest >= 7) { const weeks = Math.floor(rest / 7) rest %= 7 fragments.push(`${weeks}W`) }
if (rest > 0) { fragments.push(`${rest}D`) }
if (hours !== 0 || minutes !== 0 || seconds !== 0 || millis !== 0 || nanos !== 0) { fragments.push("T")
if (hours !== 0) { fragments.push(`${hours}H`) }
if (minutes !== 0) { fragments.push(`${minutes}M`) }
if (seconds !== 0 || millis !== 0 || nanos !== 0) { const total = BigInt(seconds) * bigint1e9 + BigInt(millis) * bigint1e6 + BigInt(nanos) const str = (Number(total) / 1e9).toFixed(9).replace(/\.?0+$/, "") fragments.push(`${str}S`) } }
return `P${fragments.join("") || "T0S"}`}
/** * Formats a Duration into an ISO8601 duration string. * * Months are assumed to be 30 days and years are assumed to be 365 days. * * Returns `Option.none()` if the duration is infinite. * * @example * ```ts * import { Duration, Option } from "effect" * * Duration.formatIso(Duration.days(1)) // => Option.some("P1D") * Duration.formatIso(Duration.minutes(90)) // => Option.some("PT1H30M") * Duration.formatIso(Duration.millis(1500)) // => Option.some("PT1.5S") * Duration.formatIso(Duration.infinity) // => Option.none() * ``` * * @since 3.13.0 * @category conversions */export const formatIso = (self: DurationInput): Option.Option<string> => { const duration = decode(self) return isFinite(duration) ? Option.some(unsafeFormatIso(duration)) : Option.none()}
/** * Parses an ISO8601 duration string into a `Duration`. * * Months are assumed to be 30 days and years are assumed to be 365 days. * * @example * ```ts * import { Duration, Option } from "effect" * * Duration.fromIso("P1D") // => Option.some(Duration.days(1)) * Duration.fromIso("PT1H") // => Option.some(Duration.hours(1)) * Duration.fromIso("PT1M") // => Option.some(Duration.minutes(1)) * Duration.fromIso("PT1.5S") // => Option.some(Duration.seconds(1.5)) * ``` * * @since 3.13.0 * @category conversions */export const fromIso = (iso: string): Option.Option<Duration> => { const result = DURATION_ISO_REGEX.exec(iso) if (result == null) { return Option.none() }
const [years, months, weeks, days, hours, mins, secs] = result.slice(1, 8).map((_) => _ ? Number(_) : 0) const value = years * 365 * 24 * 60 * 60 + months * 30 * 24 * 60 * 60 + weeks * 7 * 24 * 60 * 60 + days * 24 * 60 * 60 + hours * 60 * 60 + mins * 60 + secs
return Option.some(seconds(value))}
const DURATION_ISO_REGEX = /^P(?!$)(?:(\d+)Y)?(?:(\d+)M)?(?:(\d+)W)?(?:(\d+)D)?(?:T(?!$)(?:(\d+)H)?(?:(\d+)M)?(?:(\d+(?:\.\d+)?)S)?)?$/123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107/** * @since 2.0.0 */import type * as Channel from "./Channel.js"import type * as Effect from "./Effect.js"import * as internal from "./internal/effectable.js"import type * as Sink from "./Sink.js"import type * as Stream from "./Stream.js"
/** * @since 2.0.0 * @category type ids */export const EffectTypeId: Effect.EffectTypeId = internal.EffectTypeId
/** * @since 2.0.0 * @category type ids */export type EffectTypeId = Effect.EffectTypeId
/** * @since 2.0.0 * @category type ids */export const StreamTypeId: Stream.StreamTypeId = internal.StreamTypeId
/** * @since 2.0.0 * @category type ids */export type StreamTypeId = Stream.StreamTypeId
/** * @since 2.0.0 * @category type ids */export const SinkTypeId: Sink.SinkTypeId = internal.SinkTypeId
/** * @since 2.0.0 * @category type ids */export type SinkTypeId = Sink.SinkTypeId
/** * @since 2.0.0 * @category type ids */export const ChannelTypeId: Channel.ChannelTypeId = internal.ChannelTypeId
/** * @since 2.0.0 * @category type ids */export type ChannelTypeId = Channel.ChannelTypeId
/** * @since 2.0.0 * @category models */export interface CommitPrimitive { new<A, E = never, R = never>(): Effect.Effect<A, E, R>}
/** * @since 2.0.0 * @category prototypes */export const EffectPrototype: Effect.Effect<never> = internal.EffectPrototype
/** * @since 2.0.0 * @category prototypes */export const CommitPrototype: Effect.Effect<never> = internal.CommitPrototype
/** * @since 2.0.0 * @category prototypes */export const StructuralCommitPrototype: Effect.Effect<never> = internal.StructuralCommitPrototype
const Base: CommitPrimitive = internal.Baseconst StructuralBase: CommitPrimitive = internal.StructuralBase
/** * @since 2.0.0 * @category constructors */export abstract class Class<A, E = never, R = never> extends Base<A, E, R> { /** * @since 2.0.0 */ abstract commit(): Effect.Effect<A, E, R>}
/** * @since 2.0.0 * @category constructors */export abstract class StructuralClass<A, E = never, R = never> extends StructuralBase<A, E, R> { /** * @since 2.0.0 */ abstract commit(): Effect.Effect<A, E, R>}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195/** * This module provides encoding & decoding functionality for: * * - base64 (RFC4648) * - base64 (URL) * - hex * * @since 2.0.0 */import * as Either from "./Either.js"import * as Base64 from "./internal/encoding/base64.js"import * as Base64Url from "./internal/encoding/base64Url.js"import * as Common from "./internal/encoding/common.js"import * as Hex from "./internal/encoding/hex.js"
/** * Encodes the given value into a base64 (RFC4648) `string`. * * @category encoding * @since 2.0.0 */export const encodeBase64: (input: Uint8Array | string) => string = (input) => typeof input === "string" ? Base64.encode(Common.encoder.encode(input)) : Base64.encode(input)
/** * Decodes a base64 (RFC4648) encoded `string` into a `Uint8Array`. * * @category decoding * @since 2.0.0 */export const decodeBase64 = (str: string): Either.Either<Uint8Array, DecodeException> => Base64.decode(str)
/** * Decodes a base64 (RFC4648) encoded `string` into a UTF-8 `string`. * * @category decoding * @since 2.0.0 */export const decodeBase64String = (str: string) => Either.map(decodeBase64(str), (_) => Common.decoder.decode(_))
/** * Encodes the given value into a base64 (URL) `string`. * * @category encoding * @since 2.0.0 */export const encodeBase64Url: (input: Uint8Array | string) => string = (input) => typeof input === "string" ? Base64Url.encode(Common.encoder.encode(input)) : Base64Url.encode(input)
/** * Decodes a base64 (URL) encoded `string` into a `Uint8Array`. * * @category decoding * @since 2.0.0 */export const decodeBase64Url = (str: string): Either.Either<Uint8Array, DecodeException> => Base64Url.decode(str)
/** * Decodes a base64 (URL) encoded `string` into a UTF-8 `string`. * * @category decoding * @since 2.0.0 */export const decodeBase64UrlString = (str: string) => Either.map(decodeBase64Url(str), (_) => Common.decoder.decode(_))
/** * Encodes the given value into a hex `string`. * * @category encoding * @since 2.0.0 */export const encodeHex: (input: Uint8Array | string) => string = (input) => typeof input === "string" ? Hex.encode(Common.encoder.encode(input)) : Hex.encode(input)
/** * Decodes a hex encoded `string` into a `Uint8Array`. * * @category decoding * @since 2.0.0 */export const decodeHex = (str: string): Either.Either<Uint8Array, DecodeException> => Hex.decode(str)
/** * Decodes a hex encoded `string` into a UTF-8 `string`. * * @category decoding * @since 2.0.0 */export const decodeHexString = (str: string) => Either.map(decodeHex(str), (_) => Common.decoder.decode(_))
/** * Encodes a UTF-8 `string` into a URI component `string`. * * @category encoding * @since 3.12.0 */export const encodeUriComponent = (str: string): Either.Either<string, EncodeException> => Either.try({ try: () => encodeURIComponent(str), catch: (e) => EncodeException(str, e instanceof Error ? e.message : "Invalid input") })
/** * Decodes a URI component `string` into a UTF-8 `string`. * * @category decoding * @since 3.12.0 */export const decodeUriComponent = (str: string): Either.Either<string, DecodeException> => Either.try({ try: () => decodeURIComponent(str), catch: (e) => DecodeException(str, e instanceof Error ? e.message : "Invalid input") })
/** * @since 2.0.0 * @category symbols */export const DecodeExceptionTypeId: unique symbol = Common.DecodeExceptionTypeId
/** * @since 2.0.0 * @category symbols */export type DecodeExceptionTypeId = typeof DecodeExceptionTypeId
/** * Represents a checked exception which occurs when decoding fails. * * @since 2.0.0 * @category models */export interface DecodeException { readonly _tag: "DecodeException" readonly [DecodeExceptionTypeId]: DecodeExceptionTypeId readonly input: string readonly message?: string}
/** * Creates a checked exception which occurs when decoding fails. * * @since 2.0.0 * @category errors */export const DecodeException: (input: string, message?: string) => DecodeException = Common.DecodeException
/** * Returns `true` if the specified value is an `DecodeException`, `false` otherwise. * * @since 2.0.0 * @category refinements */export const isDecodeException: (u: unknown) => u is DecodeException = Common.isDecodeException
/** * @since 3.12.0 * @category symbols */export const EncodeExceptionTypeId: unique symbol = Common.EncodeExceptionTypeId
/** * @since 3.12.0 * @category symbols */export type EncodeExceptionTypeId = typeof EncodeExceptionTypeId
/** * Represents a checked exception which occurs when encoding fails. * * @since 3.12.0 * @category models */export interface EncodeException { readonly _tag: "EncodeException" readonly [EncodeExceptionTypeId]: EncodeExceptionTypeId readonly input: string readonly message?: string}
/** * Creates a checked exception which occurs when encoding fails. * * @since 3.12.0 * @category errors */export const EncodeException: (input: string, message?: string) => EncodeException = Common.EncodeException
/** * Returns `true` if the specified value is an `EncodeException`, `false` otherwise. * * @since 3.12.0 * @category refinements */export const isEncodeException: (u: unknown) => u is EncodeException = Common.isEncodeException123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101/** * @since 2.0.0 */import type { Equivalence } from "./Equivalence.js"import * as Hash from "./Hash.js"import { hasProperty } from "./Predicate.js"import { structuralRegionState } from "./Utils.js"
/** * @since 2.0.0 * @category symbols */export const symbol: unique symbol = Symbol.for("effect/Equal")
/** * @since 2.0.0 * @category models */export interface Equal extends Hash.Hash { [symbol](that: Equal): boolean}
/** * @since 2.0.0 * @category equality */export function equals<B>(that: B): <A>(self: A) => booleanexport function equals<A, B>(self: A, that: B): booleanexport function equals(): any { if (arguments.length === 1) { return (self: unknown) => compareBoth(self, arguments[0]) } return compareBoth(arguments[0], arguments[1])}
function compareBoth(self: unknown, that: unknown): boolean { if (self === that) { return true } const selfType = typeof self if (selfType !== typeof that) { return false } if (selfType === "object" || selfType === "function") { if (self !== null && that !== null) { if (isEqual(self) && isEqual(that)) { if (Hash.hash(self) === Hash.hash(that) && self[symbol](that)) { return true } else { return structuralRegionState.enabled && structuralRegionState.tester ? structuralRegionState.tester(self, that) : false } } else if (self instanceof Date && that instanceof Date) { const t1 = self.getTime() const t2 = that.getTime() return t1 === t2 || (Number.isNaN(t1) && Number.isNaN(t2)) } else if (self instanceof URL && that instanceof URL) { return self.href === that.href } } if (structuralRegionState.enabled) { if (self === null || that === null) { return false } if (Array.isArray(self) && Array.isArray(that)) { return self.length === that.length && self.every((v, i) => compareBoth(v, that[i])) } if (Object.getPrototypeOf(self) === Object.prototype && Object.getPrototypeOf(that) === Object.prototype) { const keysSelf = Object.keys(self as any) const keysThat = Object.keys(that as any) if (keysSelf.length === keysThat.length) { for (const key of keysSelf) { // @ts-expect-error if (!(key in that && compareBoth(self[key], that[key]))) { return structuralRegionState.tester ? structuralRegionState.tester(self, that) : false } } return true } } return structuralRegionState.tester ? structuralRegionState.tester(self, that) : false } }
return structuralRegionState.enabled && structuralRegionState.tester ? structuralRegionState.tester(self, that) : false}
/** * @since 2.0.0 * @category guards */export const isEqual = (u: unknown): u is Equal => hasProperty(u, symbol)
/** * @since 2.0.0 * @category instances */export const equivalence: <A>() => Equivalence<A> = () => equals123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308/** * @since 3.16.0 * @experimental */import type { NonEmptyReadonlyArray } from "./Array.js"import type * as Context from "./Context.js"import * as Effect from "./Effect.js"import * as internal from "./internal/executionPlan.js"import * as Layer from "./Layer.js"import type { Pipeable } from "./Pipeable.js"import { pipeArguments } from "./Pipeable.js"import type * as Schedule from "./Schedule.js"
/** * @since 3.16.0 * @category Symbols * @experimental */export const TypeId: unique symbol = internal.TypeId
/** * @since 3.16.0 * @category Symbols * @experimental */export type TypeId = typeof TypeId
/** * @since 3.16.0 * @category Guards * @experimental */export const isExecutionPlan: (u: unknown) => u is ExecutionPlan<any> = internal.isExecutionPlan
/** * A `ExecutionPlan` can be used with `Effect.withExecutionPlan` or `Stream.withExecutionPlan`, allowing you to provide different resources for each step of execution until the effect succeeds or the plan is exhausted. * * ```ts * import type { LanguageModel } from "@effect/ai" * import type { Layer } from "effect" * import { Effect, ExecutionPlan, Schedule } from "effect" * * declare const layerBad: Layer.Layer<LanguageModel.LanguageModel> * declare const layerGood: Layer.Layer<LanguageModel.LanguageModel> * * const ThePlan = ExecutionPlan.make( * { * // First try with the bad layer 2 times with a 3 second delay between attempts * provide: layerBad, * attempts: 2, * schedule: Schedule.spaced(3000) * }, * // Then try with the bad layer 3 times with a 1 second delay between attempts * { * provide: layerBad, * attempts: 3, * schedule: Schedule.spaced(1000) * }, * // Finally try with the good layer. * // * // If `attempts` is omitted, the plan will only attempt once, unless a schedule is provided. * { * provide: layerGood * } * ) * * declare const effect: Effect.Effect< * void, * never, * LanguageModel.LanguageModel * > * const withPlan: Effect.Effect<void> = Effect.withExecutionPlan(effect, ThePlan) * ``` * * @since 3.16.0 * @category Models * @experimental */export interface ExecutionPlan< Types extends { provides: any input: any error: any requirements: any }> extends Pipeable { readonly [TypeId]: TypeId readonly steps: NonEmptyReadonlyArray<{ readonly provide: | Context.Context<Types["provides"]> | Layer.Layer<Types["provides"], Types["error"], Types["requirements"]> readonly attempts?: number | undefined readonly while?: | ((input: Types["input"]) => Effect.Effect<boolean, Types["error"], Types["requirements"]>) | undefined readonly schedule?: Schedule.Schedule<any, Types["input"], Types["requirements"]> | undefined }>
/** * Returns an equivalent `ExecutionPlan` with the requirements satisfied, * using the current context. */ readonly withRequirements: Effect.Effect< ExecutionPlan<{ provides: Types["provides"] input: Types["input"] error: Types["error"] requirements: never }>, never, Types["requirements"] >}
/** * @since 3.16.0 * @experimental */export type TypesBase = { provides: any input: any error: any requirements: any}
/** * Create an `ExecutionPlan`, which can be used with `Effect.withExecutionPlan` or `Stream.withExecutionPlan`, allowing you to provide different resources for each step of execution until the effect succeeds or the plan is exhausted. * * ```ts * import type { LanguageModel } from "@effect/ai" * import type { Layer } from "effect" * import { Effect, ExecutionPlan, Schedule } from "effect" * * declare const layerBad: Layer.Layer<LanguageModel.LanguageModel> * declare const layerGood: Layer.Layer<LanguageModel.LanguageModel> * * const ThePlan = ExecutionPlan.make( * { * // First try with the bad layer 2 times with a 3 second delay between attempts * provide: layerBad, * attempts: 2, * schedule: Schedule.spaced(3000) * }, * // Then try with the bad layer 3 times with a 1 second delay between attempts * { * provide: layerBad, * attempts: 3, * schedule: Schedule.spaced(1000) * }, * // Finally try with the good layer. * // * // If `attempts` is omitted, the plan will only attempt once, unless a schedule is provided. * { * provide: layerGood * } * ) * * declare const effect: Effect.Effect< * void, * never, * LanguageModel.LanguageModel * > * const withPlan: Effect.Effect<void> = Effect.withExecutionPlan(effect, ThePlan) * ``` * * @since 3.16.0 * @category Constructors * @experimental */export const make = <const Steps extends NonEmptyReadonlyArray<make.Step>>( ...steps: Steps & { [K in keyof Steps]: make.Step }): ExecutionPlan<{ provides: make.StepProvides<Steps> input: make.StepInput<Steps> error: | (Steps[number]["provide"] extends Context.Context<infer _P> | Layer.Layer<infer _P, infer E, infer _R> ? E : never) | (Steps[number]["while"] extends (input: infer _I) => Effect.Effect<infer _A, infer _E, infer _R> ? _E : never) requirements: | (Steps[number]["provide"] extends Layer.Layer<infer _A, infer _E, infer R> ? R : never) | (Steps[number]["while"] extends (input: infer _I) => Effect.Effect<infer _A, infer _E, infer R> ? R : never) | (Steps[number]["schedule"] extends Schedule.Schedule<infer _O, infer _I, infer R> ? R : never)}> => makeProto(steps.map((options, i) => { if (options.attempts && options.attempts < 1) { throw new Error(`ExecutionPlan.make: step[${i}].attempts must be greater than 0`) } return { schedule: options.schedule, attempts: options.attempts, while: options.while ? (input: any) => Effect.suspend(() => { const result = options.while!(input) return typeof result === "boolean" ? Effect.succeed(result) : result }) : undefined, provide: options.provide } }) as any)
/** * @since 3.16.0 * @experimental */export declare namespace make { /** * @since 3.16.0 * @experimental */ export type Step = { readonly provide: Context.Context<any> | Context.Context<never> | Layer.Layer.Any readonly attempts?: number | undefined readonly while?: ((input: any) => boolean | Effect.Effect<boolean, any, any>) | undefined readonly schedule?: Schedule.Schedule<any, any, any> | undefined }
/** * @since 3.16.1 * @experimental */ export type StepProvides<Steps extends ReadonlyArray<any>, Out = unknown> = Steps extends readonly [infer Step, ...infer Rest] ? StepProvides< Rest, & Out & ( (Step extends { readonly provide: Context.Context<infer P> | Layer.Layer<infer P, infer _E, infer _R> } ? P : unknown) ) > : Out
/** * @since 3.16.1 * @experimental */ export type PlanProvides<Plans extends ReadonlyArray<any>, Out = unknown> = Plans extends readonly [infer Plan, ...infer Rest] ? PlanProvides<Rest, Out & (Plan extends ExecutionPlan<infer T> ? T["provides"] : unknown)> : Out
/** * @since 3.16.0 * @experimental */ export type StepInput<Steps extends ReadonlyArray<any>, Out = unknown> = Steps extends readonly [infer Step, ...infer Rest] ? StepInput< Rest, & Out & ( & (Step extends { readonly while: (input: infer I) => infer _ } ? I : unknown) & (Step extends { readonly schedule: Schedule.Schedule<infer _O, infer I, infer _R> } ? I : unknown) ) > : Out
/** * @since 3.16.0 * @experimental */ export type PlanInput<Plans extends ReadonlyArray<any>, Out = unknown> = Plans extends readonly [infer Plan, ...infer Rest] ? PlanInput<Rest, Out & (Plan extends ExecutionPlan<infer T> ? T["input"] : unknown)> : Out}
const Proto: Omit<ExecutionPlan<any>, "steps"> = { [TypeId]: TypeId, get withRequirements() { const self = this as any as ExecutionPlan<any> return Effect.contextWith((context: Context.Context<any>) => makeProto(self.steps.map((step) => ({ ...step, provide: Layer.isLayer(step.provide) ? Layer.provide(step.provide, Layer.succeedContext(context)) : step.provide })) as any) ) }, pipe() { return pipeArguments(this, arguments) }}
const makeProto = <Provides, In, PlanE, PlanR>( steps: ExecutionPlan<{ provides: Provides input: In error: PlanE requirements: PlanR }>["steps"]) => { const self = Object.create(Proto) self.steps = steps return self}
/** * @since 3.16.0 * @category Combining * @experimental */export const merge = <const Plans extends NonEmptyReadonlyArray<ExecutionPlan<any>>>( ...plans: Plans): ExecutionPlan<{ provides: make.PlanProvides<Plans> input: make.PlanInput<Plans> error: Plans[number] extends ExecutionPlan<infer T> ? T["error"] : never requirements: Plans[number] extends ExecutionPlan<infer T> ? T["requirements"] : never}> => makeProto(plans.flatMap((plan) => plan.steps) as any)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138/** * @since 2.0.0 */import type { LazyArg } from "./Function.js"import * as internal from "./internal/executionStrategy.js"
/** * Describes a strategy for evaluating multiple effects, potentially in * parallel. * * There are 3 possible execution strategies: `Sequential`, `Parallel`, * `ParallelN`. * * @since 2.0.0 * @category models */export type ExecutionStrategy = Sequential | Parallel | ParallelN
/** * Execute effects sequentially. * * @since 2.0.0 * @category models */export interface Sequential { readonly _tag: "Sequential"}
/** * Execute effects in parallel. * * @since 2.0.0 * @category models */export interface Parallel { readonly _tag: "Parallel"}
/** * Execute effects in parallel, up to the specified number of concurrent fibers. * * @since 2.0.0 * @category models */export interface ParallelN { readonly _tag: "ParallelN" readonly parallelism: number}
/** * Execute effects sequentially. * * @since 2.0.0 * @category constructors */export const sequential: ExecutionStrategy = internal.sequential
/** * Execute effects in parallel. * * @since 2.0.0 * @category constructors */export const parallel: ExecutionStrategy = internal.parallel
/** * Execute effects in parallel, up to the specified number of concurrent fibers. * * @since 2.0.0 * @category constructors */export const parallelN: (parallelism: number) => ExecutionStrategy = internal.parallelN
/** * Returns `true` if the specified `ExecutionStrategy` is an instance of * `Sequential`, `false` otherwise. * * @since 2.0.0 * @category refinements */export const isSequential: (self: ExecutionStrategy) => self is Sequential = internal.isSequential
/** * Returns `true` if the specified `ExecutionStrategy` is an instance of * `Sequential`, `false` otherwise. * * @since 2.0.0 * @category refinements */export const isParallel: (self: ExecutionStrategy) => self is Parallel = internal.isParallel
/** * Returns `true` if the specified `ExecutionStrategy` is an instance of * `Sequential`, `false` otherwise. * * @since 2.0.0 * @category refinements */export const isParallelN: (self: ExecutionStrategy) => self is ParallelN = internal.isParallelN
/** * Folds over the specified `ExecutionStrategy` using the provided case * functions. * * @since 2.0.0 * @category folding */export const match: { /** * Folds over the specified `ExecutionStrategy` using the provided case * functions. * * @since 2.0.0 * @category folding */ <A>( options: { readonly onSequential: LazyArg<A> readonly onParallel: LazyArg<A> readonly onParallelN: (n: number) => A } ): (self: ExecutionStrategy) => A /** * Folds over the specified `ExecutionStrategy` using the provided case * functions. * * @since 2.0.0 * @category folding */ <A>( self: ExecutionStrategy, options: { readonly onSequential: LazyArg<A> readonly onParallel: LazyArg<A> readonly onParallelN: (n: number) => A } ): A} = internal.match123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582/** * @since 2.0.0 */import type { NoSuchElementException } from "./Cause.js"import * as Cause from "./Cause.js"import * as Deferred from "./Deferred.js"import * as Effect from "./Effect.js"import * as Exit from "./Exit.js"import * as Fiber from "./Fiber.js"import * as FiberId from "./FiberId.js"import { constFalse, dual } from "./Function.js"import * as HashSet from "./HashSet.js"import * as Inspectable from "./Inspectable.js"import * as Option from "./Option.js"import { type Pipeable, pipeArguments } from "./Pipeable.js"import * as Predicate from "./Predicate.js"import * as Runtime from "./Runtime.js"import type * as Scope from "./Scope.js"
/** * @since 2.0.0 * @categories type ids */export const TypeId: unique symbol = Symbol.for("effect/FiberHandle")
/** * @since 2.0.0 * @categories type ids */export type TypeId = typeof TypeId
/** * @since 2.0.0 * @categories models */export interface FiberHandle<out A = unknown, out E = unknown> extends Pipeable, Inspectable.Inspectable { readonly [TypeId]: TypeId readonly deferred: Deferred.Deferred<void, unknown> /** @internal */ state: { readonly _tag: "Open" fiber: Fiber.RuntimeFiber<A, E> | undefined } | { readonly _tag: "Closed" }}
/** * @since 2.0.0 * @categories refinements */export const isFiberHandle = (u: unknown): u is FiberHandle => Predicate.hasProperty(u, TypeId)
const Proto = { [TypeId]: TypeId, toString(this: FiberHandle) { return Inspectable.format(this.toJSON()) }, toJSON(this: FiberHandle) { return { _id: "FiberHandle", state: this.state } }, [Inspectable.NodeInspectSymbol](this: FiberHandle) { return this.toJSON() }, pipe() { return pipeArguments(this, arguments) }}
const unsafeMake = <A = unknown, E = unknown>( deferred: Deferred.Deferred<void, E>): FiberHandle<A, E> => { const self = Object.create(Proto) self.state = { _tag: "Open", fiber: undefined } self.deferred = deferred return self}
/** * A FiberHandle can be used to store a single fiber. * When the associated Scope is closed, the contained fiber will be interrupted. * * You can add a fiber to the handle using `FiberHandle.run`, and the fiber will * be automatically removed from the FiberHandle when it completes. * * @example * ```ts * import { Effect, FiberHandle } from "effect" * * Effect.gen(function*() { * const handle = yield* FiberHandle.make() * * // run some effects * yield* FiberHandle.run(handle, Effect.never) * // this will interrupt the previous fiber * yield* FiberHandle.run(handle, Effect.never) * * yield* Effect.sleep(1000) * }).pipe( * Effect.scoped // The fiber will be interrupted when the scope is closed * ) * ``` * * @since 2.0.0 * @categories constructors */export const make = <A = unknown, E = unknown>(): Effect.Effect<FiberHandle<A, E>, never, Scope.Scope> => Effect.acquireRelease( Effect.map(Deferred.make<void, E>(), (deferred) => unsafeMake<A, E>(deferred)), (handle) => Effect.withFiberRuntime((parent) => { const state = handle.state if (state._tag === "Closed") return Effect.void handle.state = { _tag: "Closed" } return state.fiber ? Effect.intoDeferred( Effect.asVoid(Fiber.interruptAs(state.fiber, FiberId.combine(parent.id(), internalFiberId))), handle.deferred ) : Deferred.done(handle.deferred, Exit.void) }) )
/** * Create an Effect run function that is backed by a FiberHandle. * * @since 2.0.0 * @categories constructors */export const makeRuntime = <R, E = unknown, A = unknown>(): Effect.Effect< <XE extends E, XA extends A>( effect: Effect.Effect<XA, XE, R>, options?: | Runtime.RunForkOptions & { readonly onlyIfMissing?: boolean | undefined } | undefined ) => Fiber.RuntimeFiber<XA, XE>, never, Scope.Scope | R> => Effect.flatMap( make<A, E>(), (self) => runtime(self)<R>() )
/** * Create an Effect run function that is backed by a FiberHandle. * * @since 3.13.0 * @categories constructors */export const makeRuntimePromise = <R = never, A = unknown, E = unknown>(): Effect.Effect< <XE extends E, XA extends A>( effect: Effect.Effect<XA, XE, R>, options?: Runtime.RunForkOptions | undefined ) => Promise<XA>, never, Scope.Scope | R> => Effect.flatMap( make<A, E>(), (self) => runtimePromise(self)<R>() )
const internalFiberIdId = -1const internalFiberId = FiberId.make(internalFiberIdId, 0)const isInternalInterruption = Cause.reduceWithContext(undefined, { emptyCase: constFalse, failCase: constFalse, dieCase: constFalse, interruptCase: (_, fiberId) => HashSet.has(FiberId.ids(fiberId), internalFiberIdId), sequentialCase: (_, left, right) => left || right, parallelCase: (_, left, right) => left || right})
/** * Set the fiber in a FiberHandle. When the fiber completes, it will be removed from the FiberHandle. * If a fiber is already running, it will be interrupted unless `options.onlyIfMissing` is set. * * @since 2.0.0 * @categories combinators */export const unsafeSet: { /** * Set the fiber in a FiberHandle. When the fiber completes, it will be removed from the FiberHandle. * If a fiber is already running, it will be interrupted unless `options.onlyIfMissing` is set. * * @since 2.0.0 * @categories combinators */ <A, E, XE extends E, XA extends A>( fiber: Fiber.RuntimeFiber<XA, XE>, options?: { readonly interruptAs?: FiberId.FiberId | undefined readonly onlyIfMissing?: boolean | undefined readonly propagateInterruption?: boolean | undefined } ): (self: FiberHandle<A, E>) => void /** * Set the fiber in a FiberHandle. When the fiber completes, it will be removed from the FiberHandle. * If a fiber is already running, it will be interrupted unless `options.onlyIfMissing` is set. * * @since 2.0.0 * @categories combinators */ <A, E, XE extends E, XA extends A>( self: FiberHandle<A, E>, fiber: Fiber.RuntimeFiber<XA, XE>, options?: { readonly interruptAs?: FiberId.FiberId | undefined readonly onlyIfMissing?: boolean | undefined readonly propagateInterruption?: boolean | undefined } ): void} = dual((args) => isFiberHandle(args[0]), <A, E, XE extends E, XA extends A>( self: FiberHandle<A, E>, fiber: Fiber.RuntimeFiber<XA, XE>, options?: { readonly interruptAs?: FiberId.FiberId | undefined readonly onlyIfMissing?: boolean | undefined readonly propagateInterruption?: boolean | undefined }): void => { if (self.state._tag === "Closed") { fiber.unsafeInterruptAsFork(FiberId.combine(options?.interruptAs ?? FiberId.none, internalFiberId)) return } else if (self.state.fiber !== undefined) { if (options?.onlyIfMissing === true) { fiber.unsafeInterruptAsFork(FiberId.combine(options?.interruptAs ?? FiberId.none, internalFiberId)) return } else if (self.state.fiber === fiber) { return } self.state.fiber.unsafeInterruptAsFork(FiberId.combine(options?.interruptAs ?? FiberId.none, internalFiberId)) self.state.fiber = undefined }
self.state.fiber = fiber fiber.addObserver((exit) => { if (self.state._tag === "Open" && fiber === self.state.fiber) { self.state.fiber = undefined } if ( Exit.isFailure(exit) && ( options?.propagateInterruption === true ? !isInternalInterruption(exit.cause) : !Cause.isInterruptedOnly(exit.cause) ) ) { Deferred.unsafeDone(self.deferred, exit as any) } })})
/** * Set the fiber in the FiberHandle. When the fiber completes, it will be removed from the FiberHandle. * If a fiber already exists in the FiberHandle, it will be interrupted unless `options.onlyIfMissing` is set. * * @since 2.0.0 * @categories combinators */export const set: { /** * Set the fiber in the FiberHandle. When the fiber completes, it will be removed from the FiberHandle. * If a fiber already exists in the FiberHandle, it will be interrupted unless `options.onlyIfMissing` is set. * * @since 2.0.0 * @categories combinators */ <A, E, XE extends E, XA extends A>( fiber: Fiber.RuntimeFiber<XA, XE>, options?: { readonly onlyIfMissing?: boolean readonly propagateInterruption?: boolean | undefined } ): (self: FiberHandle<A, E>) => Effect.Effect<void> /** * Set the fiber in the FiberHandle. When the fiber completes, it will be removed from the FiberHandle. * If a fiber already exists in the FiberHandle, it will be interrupted unless `options.onlyIfMissing` is set. * * @since 2.0.0 * @categories combinators */ <A, E, XE extends E, XA extends A>( self: FiberHandle<A, E>, fiber: Fiber.RuntimeFiber<XA, XE>, options?: { readonly onlyIfMissing?: boolean readonly propagateInterruption?: boolean | undefined } ): Effect.Effect<void>} = dual((args) => isFiberHandle(args[0]), <A, E, XE extends E, XA extends A>( self: FiberHandle<A, E>, fiber: Fiber.RuntimeFiber<XA, XE>, options?: { readonly onlyIfMissing?: boolean readonly propagateInterruption?: boolean | undefined }): Effect.Effect<void> => Effect.fiberIdWith( (fiberId) => Effect.sync(() => unsafeSet(self, fiber, { interruptAs: fiberId, onlyIfMissing: options?.onlyIfMissing, propagateInterruption: options?.propagateInterruption }) ) ))
/** * Retrieve the fiber from the FiberHandle. * * @since 2.0.0 * @categories combinators */export const unsafeGet = <A, E>(self: FiberHandle<A, E>): Option.Option<Fiber.RuntimeFiber<A, E>> => self.state._tag === "Closed" ? Option.none() : Option.fromNullable(self.state.fiber)
/** * Retrieve the fiber from the FiberHandle. * * @since 2.0.0 * @categories combinators */export const get = <A, E>(self: FiberHandle<A, E>): Effect.Effect<Fiber.RuntimeFiber<A, E>, NoSuchElementException> => Effect.suspend(() => unsafeGet(self))
/** * @since 2.0.0 * @categories combinators */export const clear = <A, E>(self: FiberHandle<A, E>): Effect.Effect<void> => Effect.uninterruptibleMask((restore) => Effect.withFiberRuntime((fiber) => { if (self.state._tag === "Closed" || self.state.fiber === undefined) { return Effect.void } return Effect.zipRight( restore(Fiber.interruptAs(self.state.fiber, FiberId.combine(fiber.id(), internalFiberId))), Effect.sync(() => { if (self.state._tag === "Open") { self.state.fiber = undefined } }) ) }) )
const constInterruptedFiber = (function() { let fiber: Fiber.RuntimeFiber<never, never> | undefined = undefined return () => { if (fiber === undefined) { fiber = Effect.runFork(Effect.interrupt) } return fiber }})()
/** * Run an Effect and add the forked fiber to the FiberHandle. * When the fiber completes, it will be removed from the FiberHandle. * * @since 2.0.0 * @categories combinators */export const run: { /** * Run an Effect and add the forked fiber to the FiberHandle. * When the fiber completes, it will be removed from the FiberHandle. * * @since 2.0.0 * @categories combinators */ <A, E>( self: FiberHandle<A, E>, options?: { readonly onlyIfMissing?: boolean readonly propagateInterruption?: boolean | undefined } ): <R, XE extends E, XA extends A>( effect: Effect.Effect<XA, XE, R> ) => Effect.Effect<Fiber.RuntimeFiber<XA, XE>, never, R> /** * Run an Effect and add the forked fiber to the FiberHandle. * When the fiber completes, it will be removed from the FiberHandle. * * @since 2.0.0 * @categories combinators */ <A, E, R, XE extends E, XA extends A>( self: FiberHandle<A, E>, effect: Effect.Effect<XA, XE, R>, options?: { readonly onlyIfMissing?: boolean readonly propagateInterruption?: boolean | undefined } ): Effect.Effect<Fiber.RuntimeFiber<XA, XE>, never, R>} = function() { const self = arguments[0] as FiberHandle if (Effect.isEffect(arguments[1])) { return runImpl(self, arguments[1], arguments[2]) as any } const options = arguments[1] return (effect: Effect.Effect<unknown, unknown, any>) => runImpl(self, effect, options)}
const runImpl = <A, E, R, XE extends E, XA extends A>( self: FiberHandle<A, E>, effect: Effect.Effect<XA, XE, R>, options?: { readonly onlyIfMissing?: boolean readonly propagateInterruption?: boolean | undefined }): Effect.Effect<Fiber.RuntimeFiber<XA, XE>, never, R> => Effect.withFiberRuntime((parent) => { if (self.state._tag === "Closed") { return Effect.interrupt } else if (self.state.fiber !== undefined && options?.onlyIfMissing === true) { return Effect.sync(constInterruptedFiber) } const runtime = Runtime.make<R>({ context: parent.currentContext as any, fiberRefs: parent.getFiberRefs(), runtimeFlags: Runtime.defaultRuntime.runtimeFlags }) const fiber = Runtime.runFork(runtime)(effect) unsafeSet(self, fiber, { ...options, interruptAs: parent.id() }) return Effect.succeed(fiber) })
/** * Capture a Runtime and use it to fork Effect's, adding the forked fibers to the FiberHandle. * * @example * ```ts * import { Context, Effect, FiberHandle } from "effect" * * interface Users { * readonly _: unique symbol * } * const Users = Context.GenericTag<Users, { * getAll: Effect.Effect<Array<unknown>> * }>("Users") * * Effect.gen(function*() { * const handle = yield* FiberHandle.make() * const run = yield* FiberHandle.runtime(handle)<Users>() * * // run an effect and set the fiber in the handle * run(Effect.andThen(Users, _ => _.getAll)) * * // this will interrupt the previous fiber * run(Effect.andThen(Users, _ => _.getAll)) * }).pipe( * Effect.scoped // The fiber will be interrupted when the scope is closed * ) * ``` * * @since 2.0.0 * @categories combinators */export const runtime: <A, E>( self: FiberHandle<A, E>) => <R = never>() => Effect.Effect< <XE extends E, XA extends A>( effect: Effect.Effect<XA, XE, R>, options?: | Runtime.RunForkOptions & { readonly onlyIfMissing?: boolean | undefined readonly propagateInterruption?: boolean | undefined } | undefined ) => Fiber.RuntimeFiber<XA, XE>, never, R> = <A, E>(self: FiberHandle<A, E>) => <R>() => Effect.map( Effect.runtime<R>(), (runtime) => { const runFork = Runtime.runFork(runtime) return <XE extends E, XA extends A>( effect: Effect.Effect<XA, XE, R>, options?: | Runtime.RunForkOptions & { readonly onlyIfMissing?: boolean | undefined readonly propagateInterruption?: boolean | undefined } | undefined ) => { if (self.state._tag === "Closed") { return constInterruptedFiber() } else if (self.state.fiber !== undefined && options?.onlyIfMissing === true) { return constInterruptedFiber() } const fiber = runFork(effect, options) unsafeSet(self, fiber, options) return fiber } } )
/** * Capture a Runtime and use it to fork Effect's, adding the forked fibers to the FiberHandle. * * The returned run function will return Promise's that will resolve when the * fiber completes. * * @since 3.13.0 * @categories combinators */export const runtimePromise = <A, E>(self: FiberHandle<A, E>): <R = never>() => Effect.Effect< <XE extends E, XA extends A>( effect: Effect.Effect<XA, XE, R>, options?: | Runtime.RunForkOptions & { readonly propagateInterruption?: boolean | undefined } | undefined ) => Promise<XA>, never, R> =><R>() => Effect.map( runtime(self)<R>(), (runFork) => <XE extends E, XA extends A>( effect: Effect.Effect<XA, XE, R>, options?: | Runtime.RunForkOptions & { readonly propagateInterruption?: boolean | undefined } | undefined ): Promise<XA> => new Promise((resolve, reject) => runFork(effect, options).addObserver((exit) => { if (Exit.isSuccess(exit)) { resolve(exit.value) } else { reject(Cause.squash(exit.cause)) } }) ) )
/** * If any of the Fiber's in the handle terminate with a failure, * the returned Effect will terminate with the first failure that occurred. * * @since 2.0.0 * @categories combinators * @example * ```ts * import { Effect, FiberHandle } from "effect"; * * Effect.gen(function* (_) { * const handle = yield* _(FiberHandle.make()); * yield* _(FiberHandle.set(handle, Effect.runFork(Effect.fail("error")))); * * // parent fiber will fail with "error" * yield* _(FiberHandle.join(handle)); * }); * ``` */export const join = <A, E>(self: FiberHandle<A, E>): Effect.Effect<void, E> => Deferred.await(self.deferred as Deferred.Deferred<void, E>)
/** * Wait for the fiber in the FiberHandle to complete. * * @since 3.13.0 * @categories combinators */export const awaitEmpty = <A, E>(self: FiberHandle<A, E>): Effect.Effect<void, E> => Effect.suspend(() => { if (self.state._tag === "Closed" || self.state.fiber === undefined) { return Effect.void } return Fiber.await(self.state.fiber) })123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219/** * @since 2.0.0 */import type * as Equal from "./Equal.js"import type * as HashSet from "./HashSet.js"import type { Inspectable } from "./Inspectable.js"import * as internal from "./internal/fiberId.js"import type * as Option from "./Option.js"
/** * @since 2.0.0 * @category symbols */export const FiberIdTypeId: unique symbol = internal.FiberIdTypeId
/** * @since 2.0.0 * @category symbols */export type FiberIdTypeId = typeof FiberIdTypeId
/** * @since 2.0.0 * @category models */export type Single = None | Runtime
/** * @since 2.0.0 * @category models */export type FiberId = Single | Composite
/** * @since 2.0.0 * @category models */export interface None extends Equal.Equal, Inspectable { readonly [FiberIdTypeId]: FiberIdTypeId readonly _tag: "None" readonly id: -1 readonly startTimeMillis: -1}
/** * @since 2.0.0 * @category models */export interface Runtime extends Equal.Equal, Inspectable { readonly [FiberIdTypeId]: FiberIdTypeId readonly _tag: "Runtime" readonly id: number readonly startTimeMillis: number}
/** * @since 2.0.0 * @category models */export interface Composite extends Equal.Equal, Inspectable { readonly [FiberIdTypeId]: FiberIdTypeId readonly _tag: "Composite" readonly left: FiberId readonly right: FiberId}
/** * @since 2.0.0 * @category constructors */export const none: None = internal.none
/** * @since 2.0.0 * @category constructors */export const runtime: (id: number, startTimeMillis: number) => Runtime = internal.runtime
/** * @since 2.0.0 * @category constructors */export const composite: (left: FiberId, right: FiberId) => Composite = internal.composite
/** * Returns `true` if the specified unknown value is a `FiberId`, `false` * otherwise. * * @since 2.0.0 * @category refinements */export const isFiberId: (self: unknown) => self is FiberId = internal.isFiberId
/** * Returns `true` if the `FiberId` is a `None`, `false` otherwise. * * @since 2.0.0 * @category refinements */export const isNone: (self: FiberId) => self is None = internal.isNone
/** * Returns `true` if the `FiberId` is a `Runtime`, `false` otherwise. * * @since 2.0.0 * @category refinements */export const isRuntime: (self: FiberId) => self is Runtime = internal.isRuntime
/** * Returns `true` if the `FiberId` is a `Composite`, `false` otherwise. * * @since 2.0.0 * @category refinements */export const isComposite: (self: FiberId) => self is Composite = internal.isComposite
/** * Combine two `FiberId`s. * * @since 2.0.0 * @category constructors */export const combine: { /** * Combine two `FiberId`s. * * @since 2.0.0 * @category constructors */ (that: FiberId): (self: FiberId) => FiberId /** * Combine two `FiberId`s. * * @since 2.0.0 * @category constructors */ (self: FiberId, that: FiberId): FiberId} = internal.combine
/** * Combines a set of `FiberId`s into a single `FiberId`. * * @since 2.0.0 * @category constructors */export const combineAll: (fiberIds: HashSet.HashSet<FiberId>) => FiberId = internal.combineAll
/** * Returns this `FiberId` if it is not `None`, otherwise returns that `FiberId`. * * @since 2.0.0 * @category utils */export const getOrElse: { /** * Returns this `FiberId` if it is not `None`, otherwise returns that `FiberId`. * * @since 2.0.0 * @category utils */ (that: FiberId): (self: FiberId) => FiberId /** * Returns this `FiberId` if it is not `None`, otherwise returns that `FiberId`. * * @since 2.0.0 * @category utils */ (self: FiberId, that: FiberId): FiberId} = internal.getOrElse
/** * Get the set of identifiers for this `FiberId`. * * @since 2.0.0 * @category destructors */export const ids: (self: FiberId) => HashSet.HashSet<number> = internal.ids
/** * Creates a new `FiberId`. * * @since 2.0.0 * @category constructors */export const make: (id: number, startTimeSeconds: number) => FiberId = internal.make
/** * Creates a string representing the name of the current thread of execution * represented by the specified `FiberId`. * * @since 2.0.0 * @category destructors */export const threadName: (self: FiberId) => string = internal.threadName
/** * Convert a `FiberId` into an `Option<FiberId>`. * * @since 2.0.0 * @category destructors */export const toOption: (self: FiberId) => Option.Option<FiberId> = internal.toOption
/** * Convert a `FiberId` into a `HashSet<FiberId>`. * * @since 2.0.0 * @category destructors */export const toSet: (self: FiberId) => HashSet.HashSet<Runtime> = internal.toSet
/** * Unsafely creates a new `FiberId`. * * @since 2.0.0 * @category unsafe */export const unsafeMake: (_: void) => Runtime = internal.unsafeMake123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779/** * @since 2.0.0 */import type { NoSuchElementException } from "./Cause.js"import * as Cause from "./Cause.js"import * as Deferred from "./Deferred.js"import * as Effect from "./Effect.js"import * as Exit from "./Exit.js"import * as Fiber from "./Fiber.js"import * as FiberId from "./FiberId.js"import { constFalse, constVoid, dual } from "./Function.js"import * as HashSet from "./HashSet.js"import * as Inspectable from "./Inspectable.js"import * as Iterable from "./Iterable.js"import * as MutableHashMap from "./MutableHashMap.js"import * as Option from "./Option.js"import { type Pipeable, pipeArguments } from "./Pipeable.js"import * as Predicate from "./Predicate.js"import * as Runtime from "./Runtime.js"import type * as Scope from "./Scope.js"
/** * @since 2.0.0 * @categories type ids */export const TypeId: unique symbol = Symbol.for("effect/FiberMap")
/** * @since 2.0.0 * @categories type ids */export type TypeId = typeof TypeId
/** * @since 2.0.0 * @categories models */export interface FiberMap<in out K, out A = unknown, out E = unknown> extends Pipeable, Inspectable.Inspectable, Iterable<[K, Fiber.RuntimeFiber<A, E>]>{ readonly [TypeId]: TypeId readonly deferred: Deferred.Deferred<void, unknown> /** @internal */ state: { readonly _tag: "Open" readonly backing: MutableHashMap.MutableHashMap<K, Fiber.RuntimeFiber<A, E>> } | { readonly _tag: "Closed" }}
/** * @since 2.0.0 * @categories refinements */export const isFiberMap = (u: unknown): u is FiberMap<unknown> => Predicate.hasProperty(u, TypeId)
const Proto = { [TypeId]: TypeId, [Symbol.iterator](this: FiberMap<unknown>) { if (this.state._tag === "Closed") { return Iterable.empty() } return this.state.backing[Symbol.iterator]() }, toString(this: FiberMap<unknown>) { return Inspectable.format(this.toJSON()) }, toJSON(this: FiberMap<unknown>) { return { _id: "FiberMap", state: this.state } }, [Inspectable.NodeInspectSymbol](this: FiberMap<unknown>) { return this.toJSON() }, pipe() { return pipeArguments(this, arguments) }}
const unsafeMake = <K, A = unknown, E = unknown>( backing: MutableHashMap.MutableHashMap<K, Fiber.RuntimeFiber<A, E>>, deferred: Deferred.Deferred<void, E>): FiberMap<K, A, E> => { const self = Object.create(Proto) self.state = { _tag: "Open", backing } self.deferred = deferred return self}
/** * A FiberMap can be used to store a collection of fibers, indexed by some key. * When the associated Scope is closed, all fibers in the map will be interrupted. * * You can add fibers to the map using `FiberMap.set` or `FiberMap.run`, and the fibers will * be automatically removed from the FiberMap when they complete. * * @example * ```ts * import { Effect, FiberMap } from "effect" * * Effect.gen(function*() { * const map = yield* FiberMap.make<string>() * * // run some effects and add the fibers to the map * yield* FiberMap.run(map, "fiber a", Effect.never) * yield* FiberMap.run(map, "fiber b", Effect.never) * * yield* Effect.sleep(1000) * }).pipe( * Effect.scoped // The fibers will be interrupted when the scope is closed * ) * ``` * * @since 2.0.0 * @categories constructors */export const make = <K, A = unknown, E = unknown>(): Effect.Effect<FiberMap<K, A, E>, never, Scope.Scope> => Effect.acquireRelease( Effect.map(Deferred.make<void, E>(), (deferred) => unsafeMake<K, A, E>( MutableHashMap.empty(), deferred )), (map) => Effect.withFiberRuntime((parent) => { const state = map.state if (state._tag === "Closed") return Effect.void map.state = { _tag: "Closed" } return Fiber.interruptAllAs( Iterable.map(state.backing, ([, fiber]) => fiber), FiberId.combine(parent.id(), internalFiberId) ).pipe( Effect.intoDeferred(map.deferred) ) }) )
/** * Create an Effect run function that is backed by a FiberMap. * * @since 2.0.0 * @categories constructors */export const makeRuntime = <R, K, E = unknown, A = unknown>(): Effect.Effect< <XE extends E, XA extends A>( key: K, effect: Effect.Effect<XA, XE, R>, options?: | Runtime.RunForkOptions & { readonly onlyIfMissing?: boolean | undefined } | undefined ) => Fiber.RuntimeFiber<XA, XE>, never, Scope.Scope | R> => Effect.flatMap( make<K, A, E>(), (self) => runtime(self)<R>() )
/** * Create an Effect run function that is backed by a FiberMap. * * @since 3.13.0 * @categories constructors */export const makeRuntimePromise = <R, K, A = unknown, E = unknown>(): Effect.Effect< <XE extends E, XA extends A>( key: K, effect: Effect.Effect<XA, XE, R>, options?: | Runtime.RunForkOptions & { readonly onlyIfMissing?: boolean | undefined } | undefined ) => Promise<XA>, never, Scope.Scope | R> => Effect.flatMap( make<K, A, E>(), (self) => runtimePromise(self)<R>() )
const internalFiberIdId = -1const internalFiberId = FiberId.make(internalFiberIdId, 0)const isInternalInterruption = Cause.reduceWithContext(undefined, { emptyCase: constFalse, failCase: constFalse, dieCase: constFalse, interruptCase: (_, fiberId) => HashSet.has(FiberId.ids(fiberId), internalFiberIdId), sequentialCase: (_, left, right) => left || right, parallelCase: (_, left, right) => left || right})
/** * Add a fiber to the FiberMap. When the fiber completes, it will be removed from the FiberMap. * If the key already exists in the FiberMap, the previous fiber will be interrupted. * * @since 2.0.0 * @categories combinators */export const unsafeSet: { /** * Add a fiber to the FiberMap. When the fiber completes, it will be removed from the FiberMap. * If the key already exists in the FiberMap, the previous fiber will be interrupted. * * @since 2.0.0 * @categories combinators */ <K, A, E, XE extends E, XA extends A>( key: K, fiber: Fiber.RuntimeFiber<XA, XE>, options?: { readonly interruptAs?: FiberId.FiberId | undefined readonly onlyIfMissing?: boolean | undefined readonly propagateInterruption?: boolean | undefined } | undefined ): (self: FiberMap<K, A, E>) => void /** * Add a fiber to the FiberMap. When the fiber completes, it will be removed from the FiberMap. * If the key already exists in the FiberMap, the previous fiber will be interrupted. * * @since 2.0.0 * @categories combinators */ <K, A, E, XE extends E, XA extends A>( self: FiberMap<K, A, E>, key: K, fiber: Fiber.RuntimeFiber<XA, XE>, options?: { readonly interruptAs?: FiberId.FiberId | undefined readonly onlyIfMissing?: boolean | undefined readonly propagateInterruption?: boolean | undefined } | undefined ): void} = dual((args) => isFiberMap(args[0]), <K, A, E, XE extends E, XA extends A>( self: FiberMap<K, A, E>, key: K, fiber: Fiber.RuntimeFiber<XA, XE>, options?: { readonly interruptAs?: FiberId.FiberId | undefined readonly onlyIfMissing?: boolean | undefined readonly propagateInterruption?: boolean | undefined } | undefined): void => { if (self.state._tag === "Closed") { fiber.unsafeInterruptAsFork(FiberId.combine(options?.interruptAs ?? FiberId.none, internalFiberId)) return }
const previous = MutableHashMap.get(self.state.backing, key) if (previous._tag === "Some") { if (options?.onlyIfMissing === true) { fiber.unsafeInterruptAsFork(FiberId.combine(options?.interruptAs ?? FiberId.none, internalFiberId)) return } else if (previous.value === fiber) { return } previous.value.unsafeInterruptAsFork(FiberId.combine(options?.interruptAs ?? FiberId.none, internalFiberId)) }
MutableHashMap.set(self.state.backing, key, fiber) fiber.addObserver((exit) => { if (self.state._tag === "Closed") { return } const current = MutableHashMap.get(self.state.backing, key) if (Option.isSome(current) && fiber === current.value) { MutableHashMap.remove(self.state.backing, key) } if ( Exit.isFailure(exit) && ( options?.propagateInterruption === true ? !isInternalInterruption(exit.cause) : !Cause.isInterruptedOnly(exit.cause) ) ) { Deferred.unsafeDone(self.deferred, exit as any) } })})
/** * Add a fiber to the FiberMap. When the fiber completes, it will be removed from the FiberMap. * If the key already exists in the FiberMap, the previous fiber will be interrupted. * * @since 2.0.0 * @categories combinators */export const set: { /** * Add a fiber to the FiberMap. When the fiber completes, it will be removed from the FiberMap. * If the key already exists in the FiberMap, the previous fiber will be interrupted. * * @since 2.0.0 * @categories combinators */ <K, A, E, XE extends E, XA extends A>( key: K, fiber: Fiber.RuntimeFiber<XA, XE>, options?: { readonly onlyIfMissing?: boolean | undefined readonly propagateInterruption?: boolean | undefined } | undefined ): (self: FiberMap<K, A, E>) => Effect.Effect<void> /** * Add a fiber to the FiberMap. When the fiber completes, it will be removed from the FiberMap. * If the key already exists in the FiberMap, the previous fiber will be interrupted. * * @since 2.0.0 * @categories combinators */ <K, A, E, XE extends E, XA extends A>( self: FiberMap<K, A, E>, key: K, fiber: Fiber.RuntimeFiber<XA, XE>, options?: { readonly onlyIfMissing?: boolean | undefined readonly propagateInterruption?: boolean | undefined } | undefined ): Effect.Effect<void>} = dual((args) => isFiberMap(args[0]), <K, A, E, XE extends E, XA extends A>( self: FiberMap<K, A, E>, key: K, fiber: Fiber.RuntimeFiber<XA, XE>, options?: { readonly onlyIfMissing?: boolean | undefined readonly propagateInterruption?: boolean | undefined } | undefined): Effect.Effect<void> => Effect.fiberIdWith( (fiberId) => Effect.sync(() => unsafeSet(self, key, fiber, { ...options, interruptAs: fiberId }) ) ))
/** * Retrieve a fiber from the FiberMap. * * @since 2.0.0 * @categories combinators */export const unsafeGet: { /** * Retrieve a fiber from the FiberMap. * * @since 2.0.0 * @categories combinators */ <K>(key: K): <A, E>(self: FiberMap<K, A, E>) => Option.Option<Fiber.RuntimeFiber<A, E>> /** * Retrieve a fiber from the FiberMap. * * @since 2.0.0 * @categories combinators */ <K, A, E>(self: FiberMap<K, A, E>, key: K): Option.Option<Fiber.RuntimeFiber<A, E>>} = dual< /** * Retrieve a fiber from the FiberMap. * * @since 2.0.0 * @categories combinators */ <K>(key: K) => <A, E>(self: FiberMap<K, A, E>) => Option.Option<Fiber.RuntimeFiber<A, E>>, /** * Retrieve a fiber from the FiberMap. * * @since 2.0.0 * @categories combinators */ <K, A, E>(self: FiberMap<K, A, E>, key: K) => Option.Option<Fiber.RuntimeFiber<A, E>>>(2, (self, key) => self.state._tag === "Closed" ? Option.none() : MutableHashMap.get(self.state.backing, key))
/** * Retrieve a fiber from the FiberMap. * * @since 2.0.0 * @categories combinators */export const get: { /** * Retrieve a fiber from the FiberMap. * * @since 2.0.0 * @categories combinators */ <K>(key: K): <A, E>(self: FiberMap<K, A, E>) => Effect.Effect<Fiber.RuntimeFiber<A, E>, NoSuchElementException> /** * Retrieve a fiber from the FiberMap. * * @since 2.0.0 * @categories combinators */ <K, A, E>(self: FiberMap<K, A, E>, key: K): Effect.Effect<Fiber.RuntimeFiber<A, E>, NoSuchElementException>} = dual< /** * Retrieve a fiber from the FiberMap. * * @since 2.0.0 * @categories combinators */ <K>(key: K) => <A, E>(self: FiberMap<K, A, E>) => Effect.Effect<Fiber.RuntimeFiber<A, E>, NoSuchElementException>, /** * Retrieve a fiber from the FiberMap. * * @since 2.0.0 * @categories combinators */ <K, A, E>(self: FiberMap<K, A, E>, key: K) => Effect.Effect<Fiber.RuntimeFiber<A, E>, NoSuchElementException>>(2, (self, key) => Effect.suspend(() => unsafeGet(self, key)))
/** * Check if a key exists in the FiberMap. * * @since 2.0.0 * @categories combinators */export const unsafeHas: { /** * Check if a key exists in the FiberMap. * * @since 2.0.0 * @categories combinators */ <K>(key: K): <A, E>(self: FiberMap<K, A, E>) => boolean /** * Check if a key exists in the FiberMap. * * @since 2.0.0 * @categories combinators */ <K, A, E>(self: FiberMap<K, A, E>, key: K): boolean} = dual( 2, <K, A, E>(self: FiberMap<K, A, E>, key: K): boolean => self.state._tag === "Closed" ? false : MutableHashMap.has(self.state.backing, key))
/** * Check if a key exists in the FiberMap. * * @since 2.0.0 * @categories combinators */export const has: { /** * Check if a key exists in the FiberMap. * * @since 2.0.0 * @categories combinators */ <K>(key: K): <A, E>(self: FiberMap<K, A, E>) => Effect.Effect<boolean> /** * Check if a key exists in the FiberMap. * * @since 2.0.0 * @categories combinators */ <K, A, E>(self: FiberMap<K, A, E>, key: K): Effect.Effect<boolean>} = dual( 2, <K, A, E>(self: FiberMap<K, A, E>, key: K): Effect.Effect<boolean> => Effect.sync(() => unsafeHas(self, key)))
/** * Remove a fiber from the FiberMap, interrupting it if it exists. * * @since 2.0.0 * @categories combinators */export const remove: { /** * Remove a fiber from the FiberMap, interrupting it if it exists. * * @since 2.0.0 * @categories combinators */ <K>(key: K): <A, E>(self: FiberMap<K, A, E>) => Effect.Effect<void> /** * Remove a fiber from the FiberMap, interrupting it if it exists. * * @since 2.0.0 * @categories combinators */ <K, A, E>(self: FiberMap<K, A, E>, key: K): Effect.Effect<void>} = dual< /** * Remove a fiber from the FiberMap, interrupting it if it exists. * * @since 2.0.0 * @categories combinators */ <K>(key: K) => <A, E>(self: FiberMap<K, A, E>) => Effect.Effect<void>, /** * Remove a fiber from the FiberMap, interrupting it if it exists. * * @since 2.0.0 * @categories combinators */ <K, A, E>(self: FiberMap<K, A, E>, key: K) => Effect.Effect<void>>(2, (self, key) => Effect.withFiberRuntime((removeFiber) => { if (self.state._tag === "Closed") { return Effect.void } const fiber = MutableHashMap.get(self.state.backing, key) if (fiber._tag === "None") { return Effect.void } // will be removed by the observer return Fiber.interruptAs(fiber.value, FiberId.combine(removeFiber.id(), internalFiberId)) }))
/** * @since 2.0.0 * @categories combinators */export const clear = <K, A, E>(self: FiberMap<K, A, E>): Effect.Effect<void> => Effect.withFiberRuntime((clearFiber) => { if (self.state._tag === "Closed") { return Effect.void }
return Effect.forEach(self.state.backing, ([, fiber]) => // will be removed by the observer Fiber.interruptAs(fiber, FiberId.combine(clearFiber.id(), internalFiberId))) })
const constInterruptedFiber = (function() { let fiber: Fiber.RuntimeFiber<never, never> | undefined = undefined return () => { if (fiber === undefined) { fiber = Effect.runFork(Effect.interrupt) } return fiber }})()
/** * Run an Effect and add the forked fiber to the FiberMap. * When the fiber completes, it will be removed from the FiberMap. * * @since 2.0.0 * @categories combinators */export const run: { /** * Run an Effect and add the forked fiber to the FiberMap. * When the fiber completes, it will be removed from the FiberMap. * * @since 2.0.0 * @categories combinators */ <K, A, E>( self: FiberMap<K, A, E>, key: K, options?: { readonly onlyIfMissing?: boolean | undefined readonly propagateInterruption?: boolean | undefined } | undefined ): <R, XE extends E, XA extends A>( effect: Effect.Effect<XA, XE, R> ) => Effect.Effect<Fiber.RuntimeFiber<XA, XE>, never, R> /** * Run an Effect and add the forked fiber to the FiberMap. * When the fiber completes, it will be removed from the FiberMap. * * @since 2.0.0 * @categories combinators */ <K, A, E, R, XE extends E, XA extends A>( self: FiberMap<K, A, E>, key: K, effect: Effect.Effect<XA, XE, R>, options?: { readonly onlyIfMissing?: boolean | undefined readonly propagateInterruption?: boolean | undefined } | undefined ): Effect.Effect<Fiber.RuntimeFiber<XA, XE>, never, R>} = function() { const self = arguments[0] if (Effect.isEffect(arguments[2])) { return runImpl(self, arguments[1], arguments[2], arguments[3]) as any } const key = arguments[1] const options = arguments[2] return (effect: Effect.Effect<any, any, any>) => runImpl(self, key, effect, options)}
const runImpl = <K, A, E, R, XE extends E, XA extends A>( self: FiberMap<K, A, E>, key: K, effect: Effect.Effect<XA, XE, R>, options?: { readonly onlyIfMissing?: boolean readonly propagateInterruption?: boolean | undefined }) => Effect.withFiberRuntime((parent) => { if (self.state._tag === "Closed") { return Effect.interrupt } else if (options?.onlyIfMissing === true && unsafeHas(self, key)) { return Effect.sync(constInterruptedFiber) } const runtime = Runtime.make<R>({ context: parent.currentContext as any, fiberRefs: parent.getFiberRefs(), runtimeFlags: Runtime.defaultRuntime.runtimeFlags }) const fiber = Runtime.runFork(runtime)(effect) unsafeSet(self, key, fiber, { ...options, interruptAs: parent.id() }) return Effect.succeed(fiber) })
/** * Capture a Runtime and use it to fork Effect's, adding the forked fibers to the FiberMap. * * @example * ```ts * import { Context, Effect, FiberMap } from "effect" * * interface Users { * readonly _: unique symbol * } * const Users = Context.GenericTag<Users, { * getAll: Effect.Effect<Array<unknown>> * }>("Users") * * Effect.gen(function*() { * const map = yield* FiberMap.make<string>() * const run = yield* FiberMap.runtime(map)<Users>() * * // run some effects and add the fibers to the map * run("effect-a", Effect.andThen(Users, _ => _.getAll)) * run("effect-b", Effect.andThen(Users, _ => _.getAll)) * }).pipe( * Effect.scoped // The fibers will be interrupted when the scope is closed * ) * ``` * * @since 2.0.0 * @categories combinators */export const runtime: <K, A, E>( self: FiberMap<K, A, E>) => <R = never>() => Effect.Effect< <XE extends E, XA extends A>( key: K, effect: Effect.Effect<XA, XE, R>, options?: | Runtime.RunForkOptions & { readonly onlyIfMissing?: boolean | undefined readonly propagateInterruption?: boolean | undefined } | undefined ) => Fiber.RuntimeFiber<XA, XE>, never, R> = <K, A, E>(self: FiberMap<K, A, E>) => <R>() => Effect.map( Effect.runtime<R>(), (runtime) => { const runFork = Runtime.runFork(runtime) return <XE extends E, XA extends A>( key: K, effect: Effect.Effect<XA, XE, R>, options?: | Runtime.RunForkOptions & { readonly onlyIfMissing?: boolean | undefined readonly propagateInterruption?: boolean | undefined } | undefined ) => { if (self.state._tag === "Closed") { return constInterruptedFiber() } else if (options?.onlyIfMissing === true && unsafeHas(self, key)) { return constInterruptedFiber() } const fiber = runFork(effect, options) unsafeSet(self, key, fiber, options) return fiber } } )
/** * Capture a Runtime and use it to fork Effect's, adding the forked fibers to the FiberMap. * * @since 3.13.0 * @categories combinators */export const runtimePromise = <K, A, E>(self: FiberMap<K, A, E>): <R = never>() => Effect.Effect< <XE extends E, XA extends A>( key: K, effect: Effect.Effect<XA, XE, R>, options?: | Runtime.RunForkOptions & { readonly onlyIfMissing?: boolean | undefined readonly propagateInterruption?: boolean | undefined } | undefined ) => Promise<XA>, never, R> =><R>() => Effect.map( runtime(self)<R>(), (runFork) => <XE extends E, XA extends A>( key: K, effect: Effect.Effect<XA, XE, R>, options?: | Runtime.RunForkOptions & { readonly propagateInterruption?: boolean | undefined } | undefined ): Promise<XA> => new Promise((resolve, reject) => runFork(key, effect, options).addObserver((exit) => { if (Exit.isSuccess(exit)) { resolve(exit.value) } else { reject(Cause.squash(exit.cause)) } }) ) )
/** * @since 2.0.0 * @categories combinators */export const size = <K, A, E>(self: FiberMap<K, A, E>): Effect.Effect<number> => Effect.sync(() => self.state._tag === "Closed" ? 0 : MutableHashMap.size(self.state.backing))
/** * Join all fibers in the FiberMap. If any of the Fiber's in the map terminate with a failure, * the returned Effect will terminate with the first failure that occurred. * * @since 2.0.0 * @categories combinators * @example * ```ts * import { Effect, FiberMap } from "effect"; * * Effect.gen(function* (_) { * const map = yield* _(FiberMap.make()); * yield* _(FiberMap.set(map, "a", Effect.runFork(Effect.fail("error")))); * * // parent fiber will fail with "error" * yield* _(FiberMap.join(map)); * }); * ``` */export const join = <K, A, E>(self: FiberMap<K, A, E>): Effect.Effect<void, E> => Deferred.await(self.deferred as Deferred.Deferred<void, E>)
/** * Wait for the FiberMap to be empty. * * @since 3.13.0 * @categories combinators */export const awaitEmpty = <K, A, E>(self: FiberMap<K, A, E>): Effect.Effect<void, E> => Effect.whileLoop({ while: () => self.state._tag === "Open" && MutableHashMap.size(self.state.backing) > 0, body: () => Fiber.await(Iterable.unsafeHead(self)[1]), step: constVoid })123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511/** * @since 2.0.0 */import type * as Cause from "./Cause.js"import type * as Chunk from "./Chunk.js"import type * as Context from "./Context.js"import type * as Differ from "./Differ.js"import type * as Effect from "./Effect.js"import type { LazyArg } from "./Function.js"import type * as HashMap from "./HashMap.js"import type * as HashSet from "./HashSet.js"import * as core from "./internal/core.js"import * as fiberRuntime from "./internal/fiberRuntime.js"import * as query from "./internal/query.js"import type * as List from "./List.js"import type * as Logger from "./Logger.js"import type * as LogLevel from "./LogLevel.js"import type * as LogSpan from "./LogSpan.js"import type * as MetricLabel from "./MetricLabel.js"import type * as Option from "./Option.js"import type * as Request from "./Request.js"import type * as RuntimeFlags from "./RuntimeFlags.js"import * as Scheduler from "./Scheduler.js"import type * as Scope from "./Scope.js"import type * as Supervisor from "./Supervisor.js"import type * as Tracer from "./Tracer.js"import type * as Types from "./Types.js"import type * as Unify from "./Unify.js"
/** * @since 2.0.0 * @category symbols */export const FiberRefTypeId: unique symbol = core.FiberRefTypeId
/** * @since 2.0.0 * @category symbols */export type FiberRefTypeId = typeof FiberRefTypeId
/** * @since 2.0.0 * @category model */export interface FiberRef<in out A> extends Effect.Effect<A>, Variance<A> { /** @internal */ readonly initial: A /** @internal */ diff(oldValue: A, newValue: A): unknown /** @internal */ combine(first: unknown, second: unknown): unknown /** @internal */ patch(patch: unknown): (oldValue: A) => A /** @internal */ readonly fork: unknown /** @internal */ join(oldValue: A, newValue: A): A readonly [Unify.typeSymbol]?: unknown readonly [Unify.unifySymbol]?: FiberRefUnify<this> readonly [Unify.ignoreSymbol]?: FiberRefUnifyIgnore}
/** * @category models * @since 3.8.0 */export interface FiberRefUnify<A extends { [Unify.typeSymbol]?: any }> extends Effect.EffectUnify<A> { FiberRef?: () => Extract<A[Unify.typeSymbol], FiberRef<any>>}
/** * @category models * @since 3.8.0 */export interface FiberRefUnifyIgnore extends Effect.EffectUnifyIgnore { Effect?: true}
/** * @since 2.0.0 * @category models */export interface Variance<in out A> { readonly [FiberRefTypeId]: { readonly _A: Types.Invariant<A> }}
/** * @since 2.0.0 * @category constructors */export const make: <A>( initial: A, options?: { readonly fork?: ((a: A) => A) | undefined readonly join?: ((left: A, right: A) => A) | undefined }) => Effect.Effect<FiberRef<A>, never, Scope.Scope> = fiberRuntime.fiberRefMake
/** * @since 2.0.0 * @category constructors */export const makeWith: <Value>(ref: LazyArg<FiberRef<Value>>) => Effect.Effect<FiberRef<Value>, never, Scope.Scope> = fiberRuntime.fiberRefMakeWith
/** * @since 2.0.0 * @category constructors */export const makeContext: <A>( initial: Context.Context<A>) => Effect.Effect<FiberRef<Context.Context<A>>, never, Scope.Scope> = fiberRuntime.fiberRefMakeContext
/** * @since 2.0.0 * @category constructors */export const makeRuntimeFlags: ( initial: RuntimeFlags.RuntimeFlags) => Effect.Effect<FiberRef<RuntimeFlags.RuntimeFlags>, never, Scope.Scope> = fiberRuntime.fiberRefMakeRuntimeFlags
/** * @since 2.0.0 * @category constructors */export const unsafeMake: <Value>( initial: Value, options?: { readonly fork?: ((a: Value) => Value) | undefined readonly join?: ((left: Value, right: Value) => Value) | undefined }) => FiberRef<Value> = core.fiberRefUnsafeMake
/** * @since 2.0.0 * @category constructors */export const unsafeMakeHashSet: <A>(initial: HashSet.HashSet<A>) => FiberRef<HashSet.HashSet<A>> = core.fiberRefUnsafeMakeHashSet
/** * @since 2.0.0 * @category constructors */export const unsafeMakeContext: <A>(initial: Context.Context<A>) => FiberRef<Context.Context<A>> = core.fiberRefUnsafeMakeContext
/** * @since 2.0.0 * @category constructors */export const unsafeMakeSupervisor: (initial: Supervisor.Supervisor<any>) => FiberRef<Supervisor.Supervisor<any>> = fiberRuntime.fiberRefUnsafeMakeSupervisor
/** * @since 2.0.0 * @category constructors */export const unsafeMakePatch: <Value, Patch>( initial: Value, options: { readonly differ: Differ.Differ<Value, Patch> readonly fork: Patch readonly join?: ((oldV: Value, newV: Value) => Value) | undefined }) => FiberRef<Value> = core.fiberRefUnsafeMakePatch
/** * @since 2.0.0 * @category getters */export const get: <A>(self: FiberRef<A>) => Effect.Effect<A> = core.fiberRefGet
/** * @since 2.0.0 * @category utils */export const getAndSet: { /** * @since 2.0.0 * @category utils */ <A>(value: A): (self: FiberRef<A>) => Effect.Effect<A> /** * @since 2.0.0 * @category utils */ <A>(self: FiberRef<A>, value: A): Effect.Effect<A>} = core.fiberRefGetAndSet
/** * @since 2.0.0 * @category utils */export const getAndUpdate: { /** * @since 2.0.0 * @category utils */ <A>(f: (a: A) => A): (self: FiberRef<A>) => Effect.Effect<A> /** * @since 2.0.0 * @category utils */ <A>(self: FiberRef<A>, f: (a: A) => A): Effect.Effect<A>} = core.fiberRefGetAndUpdate
/** * @since 2.0.0 * @category utils */export const getAndUpdateSome: { /** * @since 2.0.0 * @category utils */ <A>(pf: (a: A) => Option.Option<A>): (self: FiberRef<A>) => Effect.Effect<A> /** * @since 2.0.0 * @category utils */ <A>(self: FiberRef<A>, pf: (a: A) => Option.Option<A>): Effect.Effect<A>} = core.fiberRefGetAndUpdateSome
/** * @since 2.0.0 * @category utils */export const getWith: { /** * @since 2.0.0 * @category utils */ <A, B, E, R>(f: (a: A) => Effect.Effect<B, E, R>): (self: FiberRef<A>) => Effect.Effect<B, E, R> /** * @since 2.0.0 * @category utils */ <A, B, E, R>(self: FiberRef<A>, f: (a: A) => Effect.Effect<B, E, R>): Effect.Effect<B, E, R>} = core.fiberRefGetWith
/** * @since 2.0.0 * @category utils */export const set: { /** * @since 2.0.0 * @category utils */ <A>(value: A): (self: FiberRef<A>) => Effect.Effect<void> /** * @since 2.0.0 * @category utils */ <A>(self: FiberRef<A>, value: A): Effect.Effect<void>} = core.fiberRefSet
const _delete: <A>(self: FiberRef<A>) => Effect.Effect<void> = core.fiberRefDelete
export { /** * @since 2.0.0 * @category utils */ _delete as delete}
/** * @since 2.0.0 * @category utils */export const reset: <A>(self: FiberRef<A>) => Effect.Effect<void> = core.fiberRefReset
/** * @since 2.0.0 * @category utils */export const modify: { /** * @since 2.0.0 * @category utils */ <A, B>(f: (a: A) => readonly [B, A]): (self: FiberRef<A>) => Effect.Effect<B> /** * @since 2.0.0 * @category utils */ <A, B>(self: FiberRef<A>, f: (a: A) => readonly [B, A]): Effect.Effect<B>} = core.fiberRefModify
/** * @since 2.0.0 * @category utils */export const modifySome: <A, B>( self: FiberRef<A>, def: B, f: (a: A) => Option.Option<readonly [B, A]>) => Effect.Effect<B> = core.fiberRefModifySome
/** * @since 2.0.0 * @category utils */export const update: { /** * @since 2.0.0 * @category utils */ <A>(f: (a: A) => A): (self: FiberRef<A>) => Effect.Effect<void> /** * @since 2.0.0 * @category utils */ <A>(self: FiberRef<A>, f: (a: A) => A): Effect.Effect<void>} = core.fiberRefUpdate
/** * @since 2.0.0 * @category utils */export const updateSome: { /** * @since 2.0.0 * @category utils */ <A>(pf: (a: A) => Option.Option<A>): (self: FiberRef<A>) => Effect.Effect<void> /** * @since 2.0.0 * @category utils */ <A>(self: FiberRef<A>, pf: (a: A) => Option.Option<A>): Effect.Effect<void>} = core.fiberRefUpdateSome
/** * @since 2.0.0 * @category utils */export const updateAndGet: { /** * @since 2.0.0 * @category utils */ <A>(f: (a: A) => A): (self: FiberRef<A>) => Effect.Effect<A> /** * @since 2.0.0 * @category utils */ <A>(self: FiberRef<A>, f: (a: A) => A): Effect.Effect<A>} = core.fiberRefUpdateAndGet
/** * @since 2.0.0 * @category utils */export const updateSomeAndGet: { /** * @since 2.0.0 * @category utils */ <A>(pf: (a: A) => Option.Option<A>): (self: FiberRef<A>) => Effect.Effect<A> /** * @since 2.0.0 * @category utils */ <A>(self: FiberRef<A>, pf: (a: A) => Option.Option<A>): Effect.Effect<A>} = core.fiberRefUpdateSomeAndGet
/** * @since 2.0.0 * @category fiberRefs */export const currentConcurrency: FiberRef<number | "unbounded"> = core.currentConcurrency
/** * @since 2.0.0 * @category fiberRefs */export const currentRequestBatchingEnabled: FiberRef<boolean> = core.currentRequestBatching
/** * @since 2.0.0 * @category fiberRefs */export const currentRequestCache: FiberRef<Request.Cache> = query.currentCache as any
/** * @since 2.0.0 * @category fiberRefs */export const currentRequestCacheEnabled: FiberRef<boolean> = query.currentCacheEnabled
/** * @since 2.0.0 * @category fiberRefs */export const currentContext: FiberRef<Context.Context<never>> = core.currentContext
/** * @since 2.0.0 * @category fiberRefs */export const currentSchedulingPriority: FiberRef<number> = core.currentSchedulingPriority
/** * @since 2.0.0 * @category fiberRefs */export const currentMaxOpsBeforeYield: FiberRef<number> = core.currentMaxOpsBeforeYield
/** * @since 2.0.0 * @category fiberRefs */export const unhandledErrorLogLevel: FiberRef<Option.Option<LogLevel.LogLevel>> = core.currentUnhandledErrorLogLevel
/** * @since 3.17.0 * @category fiberRefs */export const versionMismatchErrorLogLevel: FiberRef<Option.Option<LogLevel.LogLevel>> = core.currentVersionMismatchErrorLogLevel
/** * @since 2.0.0 * @category fiberRefs */export const currentLogAnnotations: FiberRef<HashMap.HashMap<string, unknown>> = core.currentLogAnnotations
/** * @since 2.0.0 * @category fiberRefs */export const currentLoggers: FiberRef<HashSet.HashSet<Logger.Logger<unknown, any>>> = fiberRuntime.currentLoggers
/** * @since 2.0.0 * @category fiberRefs */export const currentLogLevel: FiberRef<LogLevel.LogLevel> = core.currentLogLevel
/** * @since 2.0.0 * @category fiberRefs */export const currentMinimumLogLevel: FiberRef<LogLevel.LogLevel> = fiberRuntime.currentMinimumLogLevel
/** * @since 2.0.0 * @category fiberRefs */export const currentLogSpan: FiberRef<List.List<LogSpan.LogSpan>> = core.currentLogSpan
/** * @since 2.0.0 * @category fiberRefs */export const currentRuntimeFlags: FiberRef<RuntimeFlags.RuntimeFlags> = fiberRuntime.currentRuntimeFlags
/** * @since 2.0.0 * @category fiberRefs */export const currentScheduler: FiberRef<Scheduler.Scheduler> = Scheduler.currentScheduler
/** * @since 2.0.0 * @category fiberRefs */export const currentSupervisor: FiberRef<Supervisor.Supervisor<any>> = fiberRuntime.currentSupervisor
/** * @since 2.0.0 * @category fiberRefs */export const currentMetricLabels: FiberRef<ReadonlyArray<MetricLabel.MetricLabel>> = core.currentMetricLabels
/** * @since 2.0.0 * @category fiberRefs */export const currentTracerEnabled: FiberRef<boolean> = core.currentTracerEnabled
/** * @since 2.0.0 * @category fiberRefs */export const currentTracerTimingEnabled: FiberRef<boolean> = core.currentTracerTimingEnabled
/** * @since 2.0.0 * @category fiberRefs */export const currentTracerSpanAnnotations: FiberRef<HashMap.HashMap<string, unknown>> = core.currentTracerSpanAnnotations
/** * @since 2.0.0 * @category fiberRefs */export const currentTracerSpanLinks: FiberRef<Chunk.Chunk<Tracer.SpanLink>> = core.currentTracerSpanLinks
/** * @since 2.0.0 * @category fiberRefs */export const interruptedCause: FiberRef<Cause.Cause<never>> = core.currentInterruptedCause123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203/** * @since 2.0.0 */import { pipe } from "./Function.js"import { globalValue } from "./GlobalValue.js"import { hasProperty } from "./Predicate.js"import { structuralRegionState } from "./Utils.js"
/** @internal */const randomHashCache = globalValue( Symbol.for("effect/Hash/randomHashCache"), () => new WeakMap<object, number>())
/** * @since 2.0.0 * @category symbols */export const symbol: unique symbol = Symbol.for("effect/Hash")
/** * @since 2.0.0 * @category models */export interface Hash { [symbol](): number}
/** * @since 2.0.0 * @category hashing */export const hash: <A>(self: A) => number = <A>(self: A) => { if (structuralRegionState.enabled === true) { return 0 }
switch (typeof self) { case "number": return number(self) case "bigint": return string(self.toString(10)) case "boolean": return string(String(self)) case "symbol": return string(String(self)) case "string": return string(self) case "undefined": return string("undefined") case "function": case "object": { if (self === null) { return string("null") } else if (self instanceof Date) { if (Number.isNaN(self.getTime())) { return string("Invalid Date") } return hash(self.toISOString()) } else if (self instanceof URL) { return hash(self.href) } else if (isHash(self)) { return self[symbol]() } else { return random(self) } } default: throw new Error( `BUG: unhandled typeof ${typeof self} - please report an issue at https://github.com/Effect-TS/effect/issues` ) }}
/** * @since 2.0.0 * @category hashing */export const random: <A extends object>(self: A) => number = (self) => { if (!randomHashCache.has(self)) { randomHashCache.set(self, number(Math.floor(Math.random() * Number.MAX_SAFE_INTEGER))) } return randomHashCache.get(self)!}
/** * @since 2.0.0 * @category hashing */export const combine: (b: number) => (self: number) => number = (b) => (self) => (self * 53) ^ b
/** * @since 2.0.0 * @category hashing */export const optimize = (n: number): number => (n & 0xbfffffff) | ((n >>> 1) & 0x40000000)
/** * @since 2.0.0 * @category guards */export const isHash = (u: unknown): u is Hash => hasProperty(u, symbol)
/** * @since 2.0.0 * @category hashing */export const number = (n: number) => { if (n !== n || n === Infinity) { return 0 } let h = n | 0 if (h !== n) { h ^= n * 0xffffffff } while (n > 0xffffffff) { h ^= n /= 0xffffffff } return optimize(h)}
/** * @since 2.0.0 * @category hashing */export const string = (str: string) => { let h = 5381, i = str.length while (i) { h = (h * 33) ^ str.charCodeAt(--i) } return optimize(h)}
/** * @since 2.0.0 * @category hashing */export const structureKeys = <A extends object>(o: A, keys: ReadonlyArray<keyof A>) => { let h = 12289 for (let i = 0; i < keys.length; i++) { h ^= pipe(string(keys[i]! as string), combine(hash((o as any)[keys[i]!]))) } return optimize(h)}
/** * @since 2.0.0 * @category hashing */export const structure = <A extends object>(o: A) => structureKeys(o, Object.keys(o) as unknown as ReadonlyArray<keyof A>)
/** * @since 2.0.0 * @category hashing */export const array = <A>(arr: ReadonlyArray<A>) => { let h = 6151 for (let i = 0; i < arr.length; i++) { h = pipe(h, combine(hash(arr[i]))) } return optimize(h)}
/** * @since 2.0.0 * @category hashing */export const cached: { /** * @since 2.0.0 * @category hashing */ (self: object): (hash: number) => number /** * @since 2.0.0 * @category hashing */ (self: object, hash: number): number} = function() { if (arguments.length === 1) { const self = arguments[0] as object return function(hash: number) { Object.defineProperty(self, symbol, { value() { return hash }, enumerable: false }) return hash } as any } const self = arguments[0] as object const hash = arguments[1] as number Object.defineProperty(self, symbol, { value() { return hash }, enumerable: false })
return hash}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387/** * @since 3.19.0 * @experimental */import { dual } from "./Function.js"import * as Hash from "./Hash.js"import * as Inspectable from "./Inspectable.js"import * as Iterable from "./Iterable.js"import { type Pipeable, pipeArguments } from "./Pipeable.js"import { hasProperty } from "./Predicate.js"import * as PrimaryKey from "./PrimaryKey.js"
const TypeId = "~effect/cluster/HashRing" as const
/** * @since 3.19.0 * @category Models * @experimental */export interface HashRing<A extends PrimaryKey.PrimaryKey> extends Pipeable, Iterable<A> { readonly [TypeId]: typeof TypeId readonly baseWeight: number totalWeightCache: number readonly nodes: Map<string, [node: A, weight: number]> ring: Array<[hash: number, node: string]>}
/** * @since 3.19.0 * @category Guards * @experimental */export const isHashRing = (u: unknown): u is HashRing<any> => hasProperty(u, TypeId)
/** * @since 3.19.0 * @category Constructors * @experimental */export const make = <A extends PrimaryKey.PrimaryKey>(options?: { readonly baseWeight?: number | undefined}): HashRing<A> => { const self = Object.create(Proto) self.baseWeight = Math.max(options?.baseWeight ?? 128, 1) self.totalWeightCache = 0 self.nodes = new Map() self.ring = [] return self}
const Proto = { [TypeId]: TypeId, [Symbol.iterator]<A extends PrimaryKey.PrimaryKey>(this: HashRing<A>): Iterator<A> { return Iterable.map(this.nodes.values(), ([n]) => n)[Symbol.iterator]() }, pipe() { return pipeArguments(this, arguments) }, ...Inspectable.BaseProto, toJSON(this: HashRing<any>) { return { _id: "HashRing", baseWeight: this.baseWeight, nodes: this.ring.map(([, n]) => this.nodes.get(n)![0]) } }}
/** * Add new nodes to the ring. If a node already exists in the ring, it * will be updated. For example, you can use this to update the node's weight. * * @since 3.19.0 * @category Combinators * @experimental */export const addMany: { /** * Add new nodes to the ring. If a node already exists in the ring, it * will be updated. For example, you can use this to update the node's weight. * * @since 3.19.0 * @category Combinators * @experimental */ <A extends PrimaryKey.PrimaryKey>( nodes: Iterable<A>, options?: { readonly weight?: number | undefined } ): (self: HashRing<A>) => HashRing<A> /** * Add new nodes to the ring. If a node already exists in the ring, it * will be updated. For example, you can use this to update the node's weight. * * @since 3.19.0 * @category Combinators * @experimental */ <A extends PrimaryKey.PrimaryKey>( self: HashRing<A>, nodes: Iterable<A>, options?: { readonly weight?: number | undefined } ): HashRing<A>} = dual( (args) => isHashRing(args[0]), <A extends PrimaryKey.PrimaryKey>(self: HashRing<A>, nodes: Iterable<A>, options?: { readonly weight?: number | undefined }): HashRing<A> => { const weight = Math.max(options?.weight ?? 1, 0.1) const keys: Array<string> = [] let toRemove: Set<string> | undefined for (const node of nodes) { const key = PrimaryKey.value(node) const entry = self.nodes.get(key) if (entry) { if (entry[1] === weight) continue toRemove ??= new Set() toRemove.add(key) self.totalWeightCache -= entry[1] self.totalWeightCache += weight entry[1] = weight } else { self.nodes.set(key, [node, weight]) self.totalWeightCache += weight } keys.push(key) } if (toRemove) { self.ring = self.ring.filter(([, n]) => !toRemove.has(n)) } addNodesToRing(self, keys, Math.round(weight * self.baseWeight)) return self })
function addNodesToRing<A extends PrimaryKey.PrimaryKey>(self: HashRing<A>, keys: Array<string>, weight: number) { for (let i = weight; i > 0; i--) { for (let j = 0; j < keys.length; j++) { const key = keys[j] self.ring.push([ Hash.string(`${key}:${i}`), key ]) } } self.ring.sort((a, b) => a[0] - b[0])}
/** * Add a new node to the ring. If the node already exists in the ring, it * will be updated. For example, you can use this to update the node's weight. * * @since 3.19.0 * @category Combinators * @experimental */export const add: { /** * Add a new node to the ring. If the node already exists in the ring, it * will be updated. For example, you can use this to update the node's weight. * * @since 3.19.0 * @category Combinators * @experimental */ <A extends PrimaryKey.PrimaryKey>( node: A, options?: { readonly weight?: number | undefined } ): (self: HashRing<A>) => HashRing<A> /** * Add a new node to the ring. If the node already exists in the ring, it * will be updated. For example, you can use this to update the node's weight. * * @since 3.19.0 * @category Combinators * @experimental */ <A extends PrimaryKey.PrimaryKey>( self: HashRing<A>, node: A, options?: { readonly weight?: number | undefined } ): HashRing<A>} = dual((args) => isHashRing(args[0]), <A extends PrimaryKey.PrimaryKey>(self: HashRing<A>, node: A, options?: { readonly weight?: number | undefined}): HashRing<A> => addMany(self, [node], options))
/** * Removes the node from the ring. No-op's if the node does not exist. * * @since 3.19.0 * @category Combinators * @experimental */export const remove: { /** * Removes the node from the ring. No-op's if the node does not exist. * * @since 3.19.0 * @category Combinators * @experimental */ <A extends PrimaryKey.PrimaryKey>(node: A): (self: HashRing<A>) => HashRing<A> /** * Removes the node from the ring. No-op's if the node does not exist. * * @since 3.19.0 * @category Combinators * @experimental */ <A extends PrimaryKey.PrimaryKey>(self: HashRing<A>, node: A): HashRing<A>} = dual(2, <A extends PrimaryKey.PrimaryKey>(self: HashRing<A>, node: A): HashRing<A> => { const key = PrimaryKey.value(node) const entry = self.nodes.get(key) if (entry) { self.nodes.delete(key) self.ring = self.ring.filter(([, n]) => n !== key) self.totalWeightCache -= entry[1] } return self})
/** * @since 3.19.0 * @category Combinators * @experimental */export const has: { /** * @since 3.19.0 * @category Combinators * @experimental */ <A extends PrimaryKey.PrimaryKey>(node: A): (self: HashRing<A>) => boolean /** * @since 3.19.0 * @category Combinators * @experimental */ <A extends PrimaryKey.PrimaryKey>(self: HashRing<A>, node: A): boolean} = dual( 2, <A extends PrimaryKey.PrimaryKey>(self: HashRing<A>, node: A): boolean => self.nodes.has(PrimaryKey.value(node)))
/** * Gets the node which should handle the given input. Returns undefined if * the hashring has no elements with weight. * * @since 3.19.0 * @category Combinators * @experimental */export const get = <A extends PrimaryKey.PrimaryKey>(self: HashRing<A>, input: string): A | undefined => { if (self.ring.length === 0) { return undefined } const index = getIndexForInput(self, Hash.string(input))[0] const node = self.ring[index][1]! return self.nodes.get(node)![0]}
/** * Distributes `count` shards across the nodes in the ring, attempting to * balance the number of shards allocated to each node. Returns undefined if * the hashring has no elements with weight. * * @since 3.19.0 * @category Combinators * @experimental */export const getShards = <A extends PrimaryKey.PrimaryKey>(self: HashRing<A>, count: number): Array<A> | undefined => { if (self.ring.length === 0) { return undefined }
const shards = new Array<A>(count)
// for tracking how many shards have been allocated to each node const allocations = new Map<string, number>() // for tracking which shards still need to be allocated const remaining = new Set<number>() // for tracking which nodes have reached the max allocation const exclude = new Set<string>()
// First pass - allocate the closest nodes, skipping nodes that have reached // max const distances = new Array<[shard: number, node: string, distance: number]>(count) for (let shard = 0; shard < count; shard++) { const hash = (shardHashes[shard] ??= Hash.string(`shard-${shard}`)) const [index, distance] = getIndexForInput(self, hash) const node = self.ring[index][1]! distances[shard] = [shard, node, distance] remaining.add(shard) } distances.sort((a, b) => a[2] - b[2]) for (let i = 0; i < count; i++) { const [shard, node] = distances[i] if (exclude.has(node)) continue const [value, weight] = self.nodes.get(node)! shards[shard] = value remaining.delete(shard) const nodeCount = (allocations.get(node) ?? 0) + 1 allocations.set(node, nodeCount) const maxPerNode = Math.max(1, Math.floor(count * (weight / self.totalWeightCache))) if (nodeCount >= maxPerNode) { exclude.add(node) } }
// Second pass - allocate any remaining shards, skipping nodes that have // reached max let allAtMax = exclude.size === self.nodes.size remaining.forEach((shard) => { const index = getIndexForInput(self, shardHashes[shard], allAtMax ? undefined : exclude)[0] const node = self.ring[index][1] const [value, weight] = self.nodes.get(node)! shards[shard] = value
if (allAtMax) return const nodeCount = (allocations.get(node) ?? 0) + 1 allocations.set(node, nodeCount) const maxPerNode = Math.max(1, Math.floor(count * (weight / self.totalWeightCache))) if (nodeCount >= maxPerNode) { exclude.add(node) if (exclude.size === self.nodes.size) { allAtMax = true } } })
return shards}
const shardHashes: Array<number> = []
function getIndexForInput<A extends PrimaryKey.PrimaryKey>( self: HashRing<A>, hash: number, exclude?: ReadonlySet<string> | undefined): readonly [index: number, distance: number] { const ring = self.ring const len = ring.length
let mid: number let lo = 0 let hi = len - 1
while (lo <= hi) { mid = ((lo + hi) / 2) >>> 0 if (ring[mid][0] >= hash) { hi = mid - 1 } else { lo = mid + 1 } } const a = lo === len ? lo - 1 : lo const distA = Math.abs(ring[a][0] - hash) if (exclude === undefined) { const b = lo - 1 if (b < 0) { return [a, distA] } const distB = Math.abs(ring[b][0] - hash) return distA <= distB ? [a, distA] : [b, distB] } else if (!exclude.has(ring[a][1])) { return [a, distA] } const range = Math.max(lo, len - lo) for (let i = 1; i < range; i++) { let index = lo - i if (index >= 0 && index < len && !exclude.has(ring[index][1])) { return [index, Math.abs(ring[index][0] - hash)] } index = lo + i if (index >= 0 && index < len && !exclude.has(ring[index][1])) { return [index, Math.abs(ring[index][0] - hash)] } } return [a, distA]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346/** * # HashSet * * An immutable `HashSet` provides a collection of unique values with efficient * lookup, insertion and removal. Once created, a `HashSet` cannot be modified; * any operation that would alter the set instead returns a new `HashSet` with * the changes. This immutability offers benefits like predictable state * management and easier reasoning about your code. * * ## What Problem Does It Solve? * * `HashSet` solves the problem of maintaining an unsorted collection where each * value appears exactly once, with fast operations for checking membership and * adding/removing values. * * ## When to Use * * Use `HashSet` when you need: * * - A collection with no duplicate values * - Efficient membership testing (**`O(1)`** average complexity) * - Set operations like union, intersection, and difference * - An immutable data structure that preserves functional programming patterns * * ## Advanced Features * * HashSet provides operations for: * * - Transforming sets with map and flatMap * - Filtering elements with filter * - Combining sets with union, intersection and difference * - Performance optimizations via mutable operations in controlled contexts * * ## Performance Characteristics * * - **Lookup** operations ({@link module:HashSet.has}): **`O(1)`** average time * complexity * - **Insertion** operations ({@link module:HashSet.add}): **`O(1)`** average time * complexity * - **Removal** operations ({@link module:HashSet.remove}): **`O(1)`** average * time complexity * - **Set** operations ({@link module:HashSet.union}, * {@link module:HashSet.intersection}): **`O(n)`** where n is the size of the * smaller set * - **Iteration**: **`O(n)`** where n is the size of the set * * The HashSet data structure implements the following traits: * * - {@link Iterable}: allows iterating over the values in the set * - {@link Equal}: allows comparing two sets for value-based equality * - {@link Pipeable}: allows chaining operations with the pipe operator * - {@link Inspectable}: allows inspecting the contents of the set * * ## Operations Reference * * | Category | Operation | Description | Complexity | * | ------------ | ----------------------------------- | ------------------------------------------- | ---------- | * | constructors | {@link module:HashSet.empty} | Creates an empty HashSet | O(1) | * | constructors | {@link module:HashSet.fromIterable} | Creates a HashSet from an iterable | O(n) | * | constructors | {@link module:HashSet.make} | Creates a HashSet from multiple values | O(n) | * | | | | | * | elements | {@link module:HashSet.has} | Checks if a value exists in the set | O(1) avg | * | elements | {@link module:HashSet.some} | Checks if any element satisfies a predicate | O(n) | * | elements | {@link module:HashSet.every} | Checks if all elements satisfy a predicate | O(n) | * | elements | {@link module:HashSet.isSubset} | Checks if a set is a subset of another | O(n) | * | | | | | * | getters | {@link module:HashSet.values} | Gets an iterator of all values | O(1) | * | getters | {@link module:HashSet.toValues} | Gets an array of all values | O(n) | * | getters | {@link module:HashSet.size} | Gets the number of elements | O(1) | * | | | | | * | mutations | {@link module:HashSet.add} | Adds a value to the set | O(1) avg | * | mutations | {@link module:HashSet.remove} | Removes a value from the set | O(1) avg | * | mutations | {@link module:HashSet.toggle} | Toggles a value's presence | O(1) avg | * | | | | | * | operations | {@link module:HashSet.difference} | Computes set difference (A - B) | O(n) | * | operations | {@link module:HashSet.intersection} | Computes set intersection (A ∩ B) | O(n) | * | operations | {@link module:HashSet.union} | Computes set union (A ∪ B) | O(n) | * | | | | | * | mapping | {@link module:HashSet.map} | Transforms each element | O(n) | * | | | | | * | sequencing | {@link module:HashSet.flatMap} | Transforms and flattens elements | O(n) | * | | | | | * | traversing | {@link module:HashSet.forEach} | Applies a function to each element | O(n) | * | | | | | * | folding | {@link module:HashSet.reduce} | Reduces the set to a single value | O(n) | * | | | | | * | filtering | {@link module:HashSet.filter} | Keeps elements that satisfy a predicate | O(n) | * | | | | | * | partitioning | {@link module:HashSet.partition} | Splits into two sets by a predicate | O(n) | * * ## Notes * * ### Composability with the Effect Ecosystem: * * This `HashSet` is designed to work seamlessly within the Effect ecosystem. It * implements the {@link Iterable}, {@link Equal}, {@link Pipeable}, and * {@link Inspectable} traits from Effect. This ensures compatibility with other * Effect data structures and functionalities. For example, you can easily use * Effect's `pipe` method to chain operations on the `HashSet`. * * **Equality of Elements with Effect's {@link Equal `Equal`} Trait:** * * This `HashSet` relies on Effect's {@link Equal} trait to determine the * uniqueness of elements within the set. The way equality is checked depends on * the type of the elements: * * - **Primitive Values:** For primitive JavaScript values like strings, numbers, * booleans, `null`, and `undefined`, equality is determined by their value * (similar to the `===` operator). * - **Objects and Custom Types:** For objects and other custom types, equality is * determined by whether those types implement the {@link Equal} interface * themselves. If an element type implements `Equal`, the `HashSet` will * delegate to that implementation to perform the equality check. This allows * you to define custom logic for determining when two instances of your * objects should be considered equal based on their properties, rather than * just their object identity. * * ```ts * import { Equal, Hash, HashSet } from "effect" * * class Person implements Equal.Equal { * constructor( * readonly id: number, // Unique identifier * readonly name: string, * readonly age: number * ) {} * * // Define equality based on id, name, and age * [Equal.symbol](that: Equal.Equal): boolean { * if (that instanceof Person) { * return ( * Equal.equals(this.id, that.id) && * Equal.equals(this.name, that.name) && * Equal.equals(this.age, that.age) * ) * } * return false * } * * // Generate a hash code based on the unique id * [Hash.symbol](): number { * return Hash.hash(this.id) * } * } * * // Creating a HashSet with objects that implement the Equal interface * const set = HashSet.empty().pipe( * HashSet.add(new Person(1, "Alice", 30)), * HashSet.add(new Person(1, "Alice", 30)) * ) * * // HashSet recognizes them as equal, so only one element is stored * console.log(HashSet.size(set)) * // Output: 1 * ``` * * **Simplifying Equality and Hashing with `Data` and `Schema`:** * * Effect's {@link Data} and {@link Schema `Schema.Data`} modules offer powerful * ways to automatically handle the implementation of both the {@link Equal} and * {@link Hash} traits for your custom data structures. * * - **`Data` Module:** By using constructors like `Data.struct`, `Data.tuple`, * `Data.array`, or `Data.case` to define your data types, Effect * automatically generates the necessary implementations for value-based * equality and consistent hashing. This significantly reduces boilerplate and * ensures correctness. * * ```ts * import { HashSet, Data, Equal } from "effect" * import assert from "node:assert/strict" * * // Data.* implements the `Equal` traits for us * const person1 = Data.struct({ id: 1, name: "Alice", age: 30 }) * const person2 = Data.struct({ id: 1, name: "Alice", age: 30 }) * * assert(Equal.equals(person1, person2)) * * const set = HashSet.empty().pipe( * HashSet.add(person1), * HashSet.add(person2) * ) * * // HashSet recognizes them as equal, so only one element is stored * console.log(HashSet.size(set)) // Output: 1 * ``` * * - **`Schema` Module:** When defining data schemas using the {@link Schema} * module, you can use `Schema.Data` to automatically include the `Equal` and * `Hash` traits in the decoded objects. This is particularly important when * working with `HashSet`. **For decoded objects to be correctly recognized as * equal within a `HashSet`, ensure that the schema for those objects is * defined using `Schema.Data`.** * * ```ts * import { Equal, HashSet, Schema } from "effect" * import assert from "node:assert/strict" * * // Schema.Data implements the `Equal` traits for us * const PersonSchema = Schema.Data( * Schema.Struct({ * id: Schema.Number, * name: Schema.String, * age: Schema.Number * }) * ) * * const Person = Schema.decode(PersonSchema) * * const person1 = Person({ id: 1, name: "Alice", age: 30 }) * const person2 = Person({ id: 1, name: "Alice", age: 30 }) * * assert(Equal.equals(person1, person2)) // Output: true * * const set = HashSet.empty().pipe( * HashSet.add(person1), * HashSet.add(person2) * ) * * // HashSet thanks to Schema.Data implementation of the `Equal` trait, recognizes the two Person as equal, so only one element is stored * console.log(HashSet.size(set)) // Output: 1 * ``` * * ### Interoperability with the JavaScript Runtime: * * To interoperate with the regular JavaScript runtime, Effect's `HashSet` * provides methods to access its elements in formats readily usable by * JavaScript APIs: {@link values `HashSet.values`}, * {@link toValues `HashSet.toValues`} * * ```ts * import { HashSet } from "effect" * * const hashSet: HashSet.HashSet<number> = HashSet.make(1, 2, 3) * * // Using HashSet.values to convert HashSet.HashSet<A> to IterableIterator<A> * const iterable: IterableIterator<number> = HashSet.values(hashSet) * * console.log(...iterable) // Logs: 1 2 3 * * // Using HashSet.toValues to convert HashSet.HashSet<A> to Array<A> * const array: Array<number> = HashSet.toValues(hashSet) * * console.log(array) // Logs: [ 1, 2, 3 ] * ``` * * Be mindful of performance implications (both time and space complexity) when * frequently converting between Effect's immutable HashSet and mutable * JavaScript data structures, especially for large collections. * * @module HashSet * @since 2.0.0 */
import type { Equal } from "./Equal.js"import type { Inspectable } from "./Inspectable.js"import * as HS from "./internal/hashSet.js"import type { Pipeable } from "./Pipeable.js"import type { Predicate, Refinement } from "./Predicate.js"import type { NoInfer } from "./Types.js"
const TypeId: unique symbol = HS.HashSetTypeId as TypeId
/** * @since 2.0.0 * @category symbol */export type TypeId = typeof TypeId
/** * @memberof HashSet * @since 2.0.0 * @category models * @example * * ```ts * // Syntax * import { HashSet } from "effect" * * let numberSet: HashSet.HashSet<number> * ``` * * @interface */export interface HashSet<out A> extends Iterable<A>, Equal, Pipeable, Inspectable { readonly [TypeId]: TypeId}
/** * @memberof HashSet * @since 2.0.0 * @category refinements */export const isHashSet: { /** * Type guard function to determine if a given iterable is a `HashSet`. * * This overload preserves the type of the iterable's elements. * * @example * * ```ts * import { HashSet } from "effect" * * const numberIterable: Iterable<1 | 2 | 3> = [1, 2, 3] * * if ( * // if passed an Iterable<A> the type guard that preserves the type parameter <A> * HashSet.isHashSet(numberIterable) * ) { * const HashSet: HashSet.HashSet<1 | 2 | 3> = numberIterable * } * ``` * * @param u - The iterable input to be checked. * @returns A boolean indicating whether the provided iterable is a `HashSet`. */ <A>(u: Iterable<A>): u is HashSet<A>
/** * Type guard function that checks if the provided value is a `HashSet` of * unknown type. * * @example * * ```ts * import { HashSet } from "effect" * import assert from "node:assert/strict" * * // Check if a value is a HashSet * const set = HashSet.make(1, 2, 3) * * assert.equal(HashSet.isHashSet(set), true) // true * assert.equal(HashSet.isHashSet(HashSet.empty()), true) * * // Works with any type * assert.equal(HashSet.isHashSet(null), false) // false * assert.equal(HashSet.isHashSet({}), false) // false * assert.equal(HashSet.isHashSet([1, 2, 3]), false) // false * ``` * * @param u - The value to check. * @returns A boolean indicating whether the value is a `HashSet<unknown>`. */ (u: unknown): u is HashSet<unknown>} = HS.isHashSet
/** * Creates an empty `HashSet`. * * Time complexity: **`O(1)`** * * @memberof HashSet * @since 2.0.0 * @category constructors * @example * * ```ts * import { HashSet, pipe } from "effect" * * console.log( * pipe( * // Provide a type argument to create a HashSet of a specific type * HashSet.empty<number>(), * HashSet.add(1), * HashSet.add(1), // Notice the duplicate * HashSet.add(2), * HashSet.toValues * ) * ) // Output: [1, 2] * ``` * * @see Other `HashSet` constructors are {@link module:HashSet.make} {@link module:HashSet.fromIterable} */export const empty: <A = never>() => HashSet<A> = HS.empty
/** * Creates a new `HashSet` from an iterable collection of values. * * Time complexity: **`O(n)`** where n is the number of elements in the iterable * * @memberof HashSet * @since 2.0.0 * @category constructors * @example * * ```ts * // Creating a HashSet from an Array * import { HashSet, pipe } from "effect" * * console.log( * pipe( * [1, 2, 3, 4, 5, 1, 2, 3], // Array<number> is an Iterable<number>; Note the duplicates. * HashSet.fromIterable, * HashSet.toValues * ) * ) // Output: [1, 2, 3, 4, 5] * ``` * * @example * * ```ts * // Creating a HashSet from a Set * import { HashSet, pipe } from "effect" * * console.log( * pipe( * new Set(["apple", "banana", "orange", "apple"]), // Set<string> is an Iterable<string> * HashSet.fromIterable, * HashSet.toValues * ) * ) // Output: ["apple", "banana", "orange"] * ``` * * @example * * ```ts * // Creating a HashSet from a Generator * import { HashSet } from "effect" * * // Generator functions return iterables * function* fibonacci(n: number): Generator<number, void, unknown> { * let [a, b] = [0, 1] * for (let i = 0; i < n; i++) { * yield a * ;[a, b] = [b, a + b] * } * } * * // Create a HashSet from the first 10 Fibonacci numbers * const fibonacciSet = HashSet.fromIterable(fibonacci(10)) * * console.log(HashSet.toValues(fibonacciSet)) * // Outputs: [0, 1, 2, 3, 5, 8, 13, 21, 34] but in unsorted order * ``` * * @example * * ```ts * // Creating a HashSet from another HashSet * import { HashSet, pipe } from "effect" * * console.log( * pipe( * // since HashSet implements the Iterable interface, we can use it to create a new HashSet * HashSet.make(1, 2, 3, 4), * HashSet.fromIterable, * HashSet.toValues // turns the HashSet back into an array * ) * ) // Output: [1, 2, 3, 4] * ``` * * @example * * ```ts * // Creating a HashSet from other Effect's data structures like Chunk * import { Chunk, HashSet, pipe } from "effect" * * console.log( * pipe( * Chunk.make(1, 2, 3, 4), // Iterable<number> * HashSet.fromIterable, * HashSet.toValues // turns the HashSet back into an array * ) * ) // Outputs: [1, 2, 3, 4] * ``` * * @see Other `HashSet` constructors are {@link module:HashSet.empty} {@link module:HashSet.make} */export const fromIterable: <A>(elements: Iterable<A>) => HashSet<A> = HS.fromIterable
/** * Construct a new `HashSet` from a variable number of values. * * Time complexity: **`O(n)`** where n is the number of elements * * @memberof HashSet * @since 2.0.0 * @category constructors * @example * * ```ts * import { Equal, Hash, HashSet, pipe } from "effect" * import assert from "node:assert/strict" * * class Character implements Equal.Equal { * readonly name: string * readonly trait: string * * constructor(name: string, trait: string) { * this.name = name * this.trait = trait * } * * // Define equality based on name, and trait * [Equal.symbol](that: Equal.Equal): boolean { * if (that instanceof Character) { * return ( * Equal.equals(this.name, that.name) && * Equal.equals(this.trait, that.trait) * ) * } * return false * } * * // Generate a hash code based on the sum of the character's name and trait * [Hash.symbol](): number { * return Hash.hash(this.name + this.trait) * } * * static readonly of = (name: string, trait: string): Character => { * return new Character(name, trait) * } * } * * assert.strictEqual( * Equal.equals( * HashSet.make( * Character.of("Alice", "Curious"), * Character.of("Alice", "Curious"), * Character.of("White Rabbit", "Always late"), * Character.of("Mad Hatter", "Tea enthusiast") * ), * // Is the same as adding each character to an empty set * pipe( * HashSet.empty(), * HashSet.add(Character.of("Alice", "Curious")), * HashSet.add(Character.of("Alice", "Curious")), // Alice tried to attend twice! * HashSet.add(Character.of("White Rabbit", "Always late")), * HashSet.add(Character.of("Mad Hatter", "Tea enthusiast")) * ) * ), * true, * "`HashSet.make` and `HashSet.empty() + HashSet.add()` should be equal" * ) * * assert.strictEqual( * Equal.equals( * HashSet.make( * Character.of("Alice", "Curious"), * Character.of("Alice", "Curious"), * Character.of("White Rabbit", "Always late"), * Character.of("Mad Hatter", "Tea enthusiast") * ), * HashSet.fromIterable([ * Character.of("Alice", "Curious"), * Character.of("Alice", "Curious"), * Character.of("White Rabbit", "Always late"), * Character.of("Mad Hatter", "Tea enthusiast") * ]) * ), * true, * "`HashSet.make` and `HashSet.fromIterable` should be equal" * ) * ``` * * @see Other `HashSet` constructors are {@link module:HashSet.fromIterable} {@link module:HashSet.empty} */export const make: <As extends ReadonlyArray<any>>(...elements: As) => HashSet<As[number]> = HS.make
/** * Checks if the specified value exists in the `HashSet`. * * Time complexity: **`O(1)`** average * * @memberof HashSet * @since 2.0.0 * @category elements * @example * * ```ts * // Syntax * import { HashSet, pipe } from "effect" * * // with `data-last`, a.k.a. `pipeable` API * pipe(HashSet.make(0, 1, 2), HashSet.has(3)) // false * * // or piped with the pipe function * HashSet.make(0, 1, 2).pipe(HashSet.has(3)) // false * * // or with `data-first` API * HashSet.has(HashSet.make(0, 1, 2), 3) // false * ``` * * @returns A `boolean` signaling the presence of the value in the HashSet * @see Other `HashSet` elements are {@link module:HashSet.some} {@link module:HashSet.every} {@link module:HashSet.isSubset} */export const has: { /** * @example * * ```ts * // `data-last` a.k.a. `pipeable` API * import * as assert from "node:assert/strict" * import { HashSet, pipe } from "effect" * * const set = HashSet.make(0, 1, 2) * * assert.equal(pipe(set, HashSet.has(0)), true) * assert.equal(pipe(set, HashSet.has(1)), true) * assert.equal(pipe(set, HashSet.has(2)), true) * assert.equal(pipe(set, HashSet.has(3)), false) * ``` */ <A>(value: A): (self: HashSet<A>) => boolean
/** * @example * * ```ts * // `data-first` API * import * as assert from "node:assert/strict" * import { HashSet, pipe } from "effect" * * const set = HashSet.make(0, 1, 2) * * assert.equal(HashSet.has(set, 0), true) * assert.equal(HashSet.has(set, 1), true) * assert.equal(HashSet.has(set, 2), true) * assert.equal(HashSet.has(set, 3), false) * ``` */ <A>(self: HashSet<A>, value: A): boolean} = HS.has
/** * Check if a predicate holds true for some `HashSet` element. * * Time complexity: **`O(n)`** where n is the number of elements in the set * * @memberof HashSet * @since 2.0.0 * @category elements * @example * * ```ts * // Syntax * import { HashSet, pipe } from "effect" * * const set: HashSet.HashSet<number> = HashSet.make(0, 1, 2) * * // with `data-last`, a.k.a. `pipeable` API * pipe( * set, * HashSet.some((n) => n > 0) * ) // true * * // or piped with the pipe function * set.pipe(HashSet.some((n) => n > 0)) // true * * // or with `data-first` API * HashSet.some(set, (n) => n > 0) // true * ``` * * @see Other `HashSet` elements are {@link module:HashSet.has} {@link module:HashSet.every} {@link module:HashSet.isSubset} */export const some: { /** * @example * * ```ts * // `data-last` a.k.a. `pipeable` API * import * as assert from "node:assert/strict" * import { HashSet, pipe } from "effect" * * const set = HashSet.make(0, 1, 2) * * assert.equal( * pipe( * set, * HashSet.some((n) => n > 0) * ), * true * ) * * assert.equal( * pipe( * set, * HashSet.some((n) => n > 2) * ), * false * ) * ``` */ <A>(f: Predicate<A>): (self: HashSet<A>) => boolean
/** * @example * * ```ts * // `data-first` API * import * as assert from "node:assert/strict" * import { HashSet } from "effect" * * const set = HashSet.make(0, 1, 2) * * assert.equal( * HashSet.some(set, (n) => n > 0), * true * ) * * assert.equal( * HashSet.some(set, (n) => n > 2), * false * ) * ``` */ <A>(self: HashSet<A>, f: Predicate<A>): boolean} = HS.some
/** * Check if a predicate holds true for every `HashSet` element. * * Time complexity is **`O(n)`** as it needs to traverse the whole HashSet * collection * * @memberof HashSet * @since 2.0.0 * @category elements * @example * * ```ts * // Syntax with Refinement * import { HashSet, pipe, Predicate } from "effect" * * const numberOrString = HashSet.make(1, "1", "one", "uno") * * // with `data-last`, a.k.a. `pipeable` API and `Refinement` * pipe( * numberOrString, // HashSet.HashSet<number | string> * HashSet.every(Predicate.isString) * ) // HashSet.HashSet<string> * * // or piped with the pipe function and `Refinement` * numberOrString // HashSet.HashSet<number | string> * .pipe(HashSet.every(Predicate.isString)) // HashSet.HashSet<string> * * // or with `data-first` API and `Refinement` * HashSet.every( * numberOrString, // HashSet.HashSet<number | string> * Predicate.isString * ) // HashSet.HashSet<string> * ``` * * @example * * ```ts * // Syntax with Predicate * import { HashSet, pipe } from "effect" * * const set = HashSet.make(1, 2, 3) * * // with `data-last`, a.k.a. `pipeable` API * pipe( * set, * HashSet.every((n) => n >= 0) * ) // true * * // or piped with the pipe function * set.pipe(HashSet.every((n) => n >= 0)) // true * * // or with `data-first` API * HashSet.every(set, (n) => n >= 0) // true * ``` * * @returns A boolean once it has evaluated that whole collection fulfill the * Predicate function * @see Other `HashSet` elements are {@link module:HashSet.has} {@link module:HashSet.some} {@link module:HashSet.isSubset} */export const every: { /** * @example * * ```ts * import * as assert from "node:assert/strict" * import { Effect, HashSet, pipe, Predicate } from "effect" * * const numberOrString: HashSet.HashSet<number | string> = HashSet.make( * 1, * "1", * "one", * "uno" * ) * * assert.equal( * pipe( * numberOrString, // HashSet.HashSet<number | string> * HashSet.every(Predicate.isString) * ), // HashSet.HashSet<string> * false * ) * ``` */ <A, B extends A>( refinement: Refinement<NoInfer<A>, B> ): (self: HashSet<A>) => self is HashSet<B>
/** * @example * * ```ts * import * as assert from "node:assert/strict" * import { HashSet, pipe } from "effect" * * const set = HashSet.make(0, 1, 2) * * assert.equal( * pipe( * set, * HashSet.every((n) => n >= 0) * ), * true * ) * ``` */ <A>(predicate: Predicate<A>): (self: HashSet<A>) => boolean
/** * @example * * ```ts * import * as assert from "node:assert/strict" * import { Effect, HashSet, pipe, Predicate } from "effect" * * const numberOrString: HashSet.HashSet<number | string> = HashSet.make( * 1, * "1", * "one", * "uno" * ) * * assert.equal( * HashSet.every( * numberOrString, // HashSet.HashSet<number | string> * Predicate.isString * ), // HashSet.HashSet<string> * false * ) * ``` */ <A, B extends A>( self: HashSet<A>, refinement: Refinement<A, B> ): self is HashSet<B>
/** * @example * * ```ts * import * as assert from "node:assert/strict" * import { HashSet } from "effect" * * const set = HashSet.make(0, 1, 2) * * assert.equal( * HashSet.every(set, (n) => n >= 0), * true * ) * ``` */ <A>(self: HashSet<A>, predicate: Predicate<A>): boolean} = HS.every
/** * Returns `true` if and only if every element in the this `HashSet` is an * element of the second set, * * **NOTE**: the hash and equal of both sets must be the same. * * Time complexity analysis is of **`O(n)`** * * @memberof HashSet * @since 2.0.0 * @category elements * @example * * ```ts * // Syntax * import { HashSet, pipe } from "effect" * * const set1 = HashSet.make(0, 1) * const set2 = HashSet.make(1, 2) * const set3 = HashSet.make(0, 1, 2) * * // with `data-last`, a.k.a. `pipeable` API * pipe(set1, HashSet.isSubset(set2)) // false * pipe(set1, HashSet.isSubset(set3)) // true * * // or piped with the pipe function * set1.pipe(HashSet.isSubset(set2)) // false * set1.pipe(HashSet.isSubset(set3)) // true * * // or with `data-first` API * HashSet.isSubset(set1, set2) // false * HashSet.isSubset(set1, set3) // true) * ``` * * @see Other `HashSet` elements are {@link module:HashSet.has} {@link module:HashSet.some} {@link module:HashSet.every} */export const isSubset: { /** * @example * * ```ts * import { HashSet, pipe } from "effect" * import * as assert from "node:assert/strict" * * assert.equal( * pipe( * HashSet.make(0, 1), // * HashSet.isSubset(HashSet.make(1, 2)) * ), * false * ) * * assert.equal( * pipe( * HashSet.make(0, 1), // * HashSet.isSubset(HashSet.make(0, 1, 2)) * ), * true * ) * ``` */ <A>(that: HashSet<A>): (self: HashSet<A>) => boolean
/** * @example * * ```ts * import { HashSet } from "effect" * import * as assert from "node:assert/strict" * * assert.equal(HashSet.isSubset(set1, set2), false) * * assert.equal(HashSet.isSubset(set1, set3), true) * ``` */ <A>(self: HashSet<A>, that: HashSet<A>): boolean} = HS.isSubset
/** * Returns an `IterableIterator` of the values in the `HashSet`. * * Time complexity: **`O(1)`** * * @memberof HashSet * @since 2.0.0 * @category getters * @example * * ```ts * import { HashSet, pipe } from "effect" * * const numberIterable = pipe( * HashSet.make(0, 1, 1, 2), // HashSet.HashSet<number> * HashSet.values // takes an HashSet<A> and returns an IterableIterator<A> * ) * * for (const number of numberIterable) { * console.log(number) // it will logs: 0, 1, 2 * } * ``` * * @see Other `HashSet` getters are {@link module:HashSet.toValues} {@link module:HashSet.size} */export const values: <A>(self: HashSet<A>) => IterableIterator<A> = HS.values
/** * Returns an `Array` of the values within the `HashSet`. * * Time complexity: **`O(n)`** where n is the number of elements in the set * * @memberof HashSet * @since 3.13.0 * @category getters * @example * * ```ts * import { HashSet, pipe } from "effect" * import { deepStrictEqual } from "node:assert/strict" * * deepStrictEqual( * pipe( * HashSet.make(0, 1, 1, 2), // HashSet<number> * HashSet.toValues // takes an HashSet<A> and returns an Array<A> * ), * Array.of(0, 1, 2) * ) * ``` * * @see Other `HashSet` getters are {@link module:HashSet.values} {@link module:HashSet.size} */export const toValues = <A>(self: HashSet<A>): Array<A> => Array.from(values(self))
/** * Calculates the number of values in the `HashSet`. * * Time complexity: **`O(1)`** * * @memberof HashSet * @since 2.0.0 * @category getters * @example * * ```ts * import { HashSet, pipe } from "effect" * import assert from "node:assert/strict" * * assert.deepStrictEqual(pipe(HashSet.empty(), HashSet.size), 0) * * assert.deepStrictEqual( * pipe(HashSet.make(1, 2, 2, 3, 4, 3), HashSet.size), * 4 * ) * ``` * * @see Other `HashSet` getters are {@link module:HashSet.values} {@link module:HashSet.toValues} */export const size: <A>(self: HashSet<A>) => number = HS.size
/** * Creates a new mutable version of the `HashSet` * * When a `HashSet` is mutable, operations like {@link add} and {@link remove} * modify the data structure in place instead of creating a new one, which is * more efficient when performing multiple operations. * * @memberof HashSet * @since 2.0.0 * @example * * ```ts * import { HashSet } from "effect" * import assert from "node:assert/strict" * * const UPPER_BOUND = 10_000 * * const immutableSet = HashSet.empty<number>().pipe(HashSet.add(0)) * * // Create a mutable version of the immutableSet * const mutableSet = HashSet.beginMutation(immutableSet) * * for (let i = 1; i < UPPER_BOUND; i++) { * // Operations now modify the set in place instead of creating new instances * // This is more efficient when making multiple changes * const pointerToMutableSet = HashSet.add(mutableSet, i) * * // the two sets have the same identity, hence `add` is mutating mutableSet and not returning a new HashSet instance * assert(Object.is(mutableSet, pointerToMutableSet)) * assert.equal(HashSet.has(mutableSet, i), true) // `i` is in the mutableSet * assert.equal(HashSet.has(immutableSet, i), false) // `i` is not in the immutableSet * } * * const next = UPPER_BOUND + 1 * // When done, mark the set as immutable again * HashSet.endMutation(mutableSet).pipe( * HashSet.add(next) // since this returns a new HashSet, it will not be logged as part of the mutableSet * ) * assert.equal(HashSet.has(mutableSet, next), false) * * console.log(HashSet.toValues(immutableSet)) // [0] * console.log(HashSet.toValues(mutableSet).sort((a, b) => a - b)) // [0, 1, 2, 3, ...rest] * ``` * * @see Other `HashSet` mutations are {@link module:HashSet.add} {@link module:HashSet.remove} {@link module:HashSet.toggle} {@link module:HashSet.endMutation} {@link module:HashSet.mutate} */export const beginMutation: <A>(self: HashSet<A>) => HashSet<A> = HS.beginMutation
/** * Makes the `HashSet` immutable again. * * After calling `endMutation`, operations like {@link add} and {@link remove} * will create new instances of the `HashSet` instead of modifying the existing * one. * * @memberof HashSet * @since 2.0.0 * @example * * ```ts * import { HashSet } from "effect" * import assert from "node:assert/strict" * * // Create a mutable set * const mutableSet = HashSet.beginMutation(HashSet.empty<number>()) * * // Add some elements to the mutable set * HashSet.add(mutableSet, 1) * HashSet.add(mutableSet, 2) * * // Before endMutation, operations modify the set in place * const sameSet = HashSet.add(mutableSet, 3) * assert(Object.is(mutableSet, sameSet)) // true - same object reference * assert.deepStrictEqual(HashSet.toValues(mutableSet).sort(), [1, 2, 3]) * * // Make the set immutable again * const immutableSet = HashSet.endMutation(mutableSet) * * // endMutation returns the same set instance, now made immutable * assert(Object.is(mutableSet, immutableSet)) // true - same object reference * * // After endMutation, operations create new instances * const newSet = HashSet.add(immutableSet, 4) * assert(!Object.is(immutableSet, newSet)) // false - different object references * * // The original set remains unchanged * assert.deepStrictEqual(HashSet.toValues(immutableSet).sort(), [1, 2, 3]) * * // The new set contains the added element * assert.deepStrictEqual(HashSet.toValues(newSet).sort(), [1, 2, 3, 4]) * ``` * * @see Other `HashSet` mutations are {@link module:HashSet.add} {@link module:HashSet.remove} {@link module:HashSet.toggle} {@link module:HashSet.beginMutation} {@link module:HashSet.mutate} */export const endMutation: <A>(self: HashSet<A>) => HashSet<A> = HS.endMutation
/** * Mutates the `HashSet` within the context of the provided function. * * You can consider it a functional abstraction on top of the lower-level * mutation primitives of {@link module:HashSet.beginMutation} `->` `mutable * context` `->` {@link HashSet.endMutation}. * * @memberof HashSet * @since 2.0.0 * @example * * ```ts * // Syntax * import { HashSet, pipe } from "effect" * * // with data-last, a.k.a. pipeable API * pipe( * HashSet.make(1, 2, 3), * HashSet.mutate((set) => { * HashSet.add(set, 4) * HashSet.remove(set, 1) * }) * ) * * // or piped with the pipe function * HashSet.make(1, 2, 3).pipe( * HashSet.mutate((set) => { * HashSet.add(set, 4) * HashSet.remove(set, 1) * }) * ) * * // or with data-first API * HashSet.mutate(HashSet.make(1, 2, 3), (set) => { * HashSet.add(set, 4) * HashSet.remove(set, 1) * }) * ``` * * @see Other `HashSet` mutations are {@link module:HashSet.add} {@link module:HashSet.remove} {@link module:HashSet.toggle} {@link module:HashSet.beginMutation} {@link module:HashSet.endMutation} */export const mutate: { /** * @example * * ```ts * // `data-last` a.k.a. `pipeable` API * import { HashSet, pipe } from "effect" * import assert from "node:assert/strict" * * // Create a set with initial values * const immutableSet = HashSet.make(1, 2, 3) * * // Use mutate to perform multiple operations efficiently * const result = pipe( * immutableSet, * HashSet.mutate((set) => { * assert.equal(Object.is(immutableSet, set), false) * * // The set is temporarily mutable inside this function * const mod1 = HashSet.add(set, 4) * const mod2 = HashSet.remove(set, 1) * assert.equal(Object.is(mod1, mod2), true) // they are the same object by reference * }) * ) * * // The original set is unchanged * assert.equal(Object.is(immutableSet, result), false) * assert.deepStrictEqual( * HashSet.toValues(immutableSet).sort(), * [1, 2, 3] * ) * * // The result contains the mutations * assert.deepStrictEqual(HashSet.toValues(result).sort(), [2, 3, 4]) * ``` */ <A>(f: (set: HashSet<A>) => void): (self: HashSet<A>) => HashSet<A>
/** * @example * * ```ts * // `data-first` API * import { HashSet } from "effect" * import assert from "node:assert/strict" * * // Create a set with initial values * const immutableSet = HashSet.make(1, 2, 3) * * // Use mutate with data-first API * const result = HashSet.mutate(immutableSet, (set) => { * // The set is temporarily mutable inside this function * HashSet.add(set, 4) * HashSet.remove(set, 1) * }) * * // The original set is unchanged * assert.equal(Object.is(immutableSet, result), false) * assert.deepStrictEqual( * HashSet.toValues(immutableSet).sort(), * [1, 2, 3] * ) * * // The result contains the mutations * assert.deepStrictEqual(HashSet.toValues(result).sort(), [2, 3, 4]) * ``` */ <A>(self: HashSet<A>, f: (set: HashSet<A>) => void): HashSet<A>} = HS.mutate
/** * Adds a value to the `HashSet`. * * Time complexity: **`O(1)`** average * * @remarks * Remember that a `HashSet` is a collection of unique values, so adding a value * that already exists in the `HashSet` will not add a duplicate. * * Remember that HashSet is an immutable data structure, so the `add` function, * like all other functions that modify the HashSet, will return a new HashSet * with the added value. * @memberof HashSet * @since 2.0.0 * @example * * ```ts * // Syntax * import { HashSet, pipe } from "effect" * * // with data-last, a.k.a. pipeable API * pipe(HashSet.empty(), HashSet.add(0), HashSet.add(0)) * * // or piped with the pipe function * HashSet.empty().pipe(HashSet.add(0)) * * // or with data-first API * HashSet.add(HashSet.empty(), 0) * ``` * * @see Other `HashSet` mutations are {@link module:HashSet.remove} {@link module:HashSet.toggle} {@link module:HashSet.beginMutation} {@link module:HashSet.endMutation} {@link module:HashSet.mutate} */export const add: { /** * @example * * ```ts * // `data-last` a.k.a. `pipeable` API * import { HashSet, pipe } from "effect" * import assert from "node:assert/strict" * * assert.deepStrictEqual( * pipe( * HashSet.empty<number>(), // HashSet.HashSet<number> * HashSet.add(0), * HashSet.add(1), * HashSet.add(1), * HashSet.add(2), * HashSet.toValues * ), * Array.of(0, 1, 2) * ) * ``` */ <A>(value: A): (self: HashSet<A>) => HashSet<A>
/** * @example * * ```ts * // `data-first` API * import { HashSet, pipe } from "effect" * import assert from "node:assert/strict" * * const empty = HashSet.empty<number>() * const withZero = HashSet.add(empty, 0) * const withOne = HashSet.add(withZero, 1) * const withTwo = HashSet.add(withOne, 2) * const withTwoTwo = HashSet.add(withTwo, 2) * * assert.deepStrictEqual(HashSet.toValues(withTwoTwo), Array.of(0, 1, 2)) * ``` */ <A>(self: HashSet<A>, value: A): HashSet<A>} = HS.add
/** * Removes a value from the `HashSet`. * * Time complexity: **`O(1)`** average * * @memberof HashSet * @since 2.0.0 * @example * * ```ts * // Syntax * import { HashSet, pipe } from "effect" * * // with `data-last`, a.k.a. `pipeable` API * pipe(HashSet.make(0, 1, 2), HashSet.remove(0)) * * // or piped with the pipe function * HashSet.make(0, 1, 2).pipe(HashSet.remove(0)) * * // or with `data-first` API * HashSet.remove(HashSet.make(0, 1, 2), 0) * ``` * * @see Other `HashSet` mutations are {@link module:HashSet.add} {@link module:HashSet.toggle} {@link module:HashSet.beginMutation} {@link module:HashSet.endMutation} {@link module:HashSet.mutate} */export const remove: { /** * @example * * ```ts * // `data-last` a.k.a. `pipeable` API * import { HashSet, pipe } from "effect" * import * as assert from "node:assert/strict" * * const set = HashSet.make(0, 1, 2) * const result = pipe(set, HashSet.remove(0)) * * assert.equal(pipe(result, HashSet.has(0)), false) // it has correctly removed 0 * assert.equal(pipe(set, HashSet.has(0)), true) // it does not mutate the original set * assert.equal(pipe(result, HashSet.has(1)), true) * assert.equal(pipe(result, HashSet.has(2)), true) * ``` */ <A>(value: A): (self: HashSet<A>) => HashSet<A>
/** * @example * * ```ts * // `data-first` API * import { HashSet, pipe } from "effect" * import * as assert from "node:assert/strict" * * const set = HashSet.make(0, 1, 2) * const result = HashSet.remove(set, 0) * * assert.equal(HashSet.has(result, 0), false) // it has correctly removed 0 * assert.equal(HashSet.has(set, 0), true) // it does not mutate the original set * assert.equal(HashSet.has(result, 1), true) * assert.equal(HashSet.has(result, 2), true) * ``` */ <A>(self: HashSet<A>, value: A): HashSet<A>} = HS.remove
/** * Computes the set difference `(A - B)` between this `HashSet` and the * specified `Iterable<A>`. * * Time complexity: **`O(n)`** where n is the number of elements in the set * * **NOTE**: the hash and equal of the values in both the set and the iterable * must be the same; meaning we cannot compute a difference between a `HashSet * of bananas` and a `HashSet of elephants` as they are not the same type and * won't implement the Equal trait in the same way. * * @memberof HashSet * @since 2.0.0 * @example * * ```ts * // Syntax * import { HashSet, pipe } from "effect" * * // with data-last, a.k.a. pipeable API * pipe(HashSet.make(1, 2, 3), HashSet.difference(HashSet.make(3, 4, 5))) * * // or piped with the pipe function * HashSet.make(1, 2, 3).pipe(HashSet.difference(HashSet.make(3, 4, 5))) * * // or with data-first API * HashSet.difference(HashSet.make(1, 2, 3), HashSet.make(3, 4, 5)) * ``` * * @see Other `HashSet` operations are {@link module:HashSet.intersection} {@link module:HashSet.union} */export const difference: { /** * @example * * ```ts * // `data-last` a.k.a. `pipeable` API * import { HashSet, pipe } from "effect" * import * as assert from "node:assert/strict" * * // Create two sets with some overlapping elements * const thisSet = HashSet.make(1, 2, 3) * const thatIterable = HashSet.make(3, 4, 5) * * // Compute the difference (elements in thisSet that are not in thatIterable) * const result = pipe(thisSet, HashSet.difference(thatIterable)) * * // The result contains only elements from thisSet that are not in thatIterable * assert.deepStrictEqual(HashSet.toValues(result).sort(), [1, 2]) * * // The original sets are unchanged * assert.deepStrictEqual(HashSet.toValues(thisSet).sort(), [1, 2, 3]) * assert.deepStrictEqual( * HashSet.toValues(thatIterable).sort(), * [3, 4, 5] * ) * * // You can also use arrays or other iterables * const diffWithArray = pipe(thisSet, HashSet.difference([3, 4])) * assert.deepStrictEqual(HashSet.toValues(diffWithArray).sort(), [1, 2]) * ``` */ <A>(that: Iterable<A>): (self: HashSet<A>) => HashSet<A>
/** * @example * * ```ts * // `data-first` API * import { HashSet } from "effect" * import * as assert from "node:assert/strict" * * // Create two sets with some overlapping elements * const thisSet = HashSet.make(1, 2, 3) * const thatIterable = HashSet.make(3, 4, 5) * * // Compute the difference using data-first API * const result = HashSet.difference(thisSet, thatIterable) * * // The result contains only elements from thisSet that are not in thatIterable * assert.deepStrictEqual(HashSet.toValues(result).sort(), [1, 2]) * * // The original sets are unchanged * assert.deepStrictEqual(HashSet.toValues(thisSet).sort(), [1, 2, 3]) * assert.deepStrictEqual( * HashSet.toValues(thatIterable).sort(), * [3, 4, 5] * ) * * // You can also compute the difference in the other direction * const reverseResult = HashSet.difference(thatIterable, thisSet) * assert.deepStrictEqual(HashSet.toValues(reverseResult).sort(), [4, 5]) * ``` */ <A>(self: HashSet<A>, that: Iterable<A>): HashSet<A>} = HS.difference
/** * Returns a `HashSet` of values which are present in both this set and that * `Iterable<A>`. Computes set intersection (A ∩ B) * * Time complexity: **`O(n)`** where n is the number of elements in the smaller * set * * **NOTE**: the hash and equal of the values in both the set and the iterable * must be the same. * * @memberof HashSet * @since 2.0.0 * @example * * ```ts * // Syntax * import { HashSet, pipe } from "effect" * * // with data-last, a.k.a. pipeable API * pipe(HashSet.make(1, 2, 3), HashSet.intersection(HashSet.make(2, 3, 4))) * * // or piped with the pipe function * HashSet.make(1, 2, 3).pipe(HashSet.intersection(HashSet.make(2, 3, 4))) * * // or with data-first API * HashSet.intersection(HashSet.make(1, 2, 3), HashSet.make(2, 3, 4)) * ``` * * @see Other `HashSet` operations are {@link module:HashSet.difference} {@link module:HashSet.union} */export const intersection: { /** * @example * * ```ts * // `data-last` a.k.a. `pipeable` API * import { HashSet, pipe } from "effect" * import * as assert from "node:assert/strict" * * // Create two sets with some overlapping elements * const set1 = HashSet.make(1, 2, 3) * const set2 = HashSet.make(2, 3, 4) * * // Compute the intersection (elements that are in both sets) * const result = pipe(set1, HashSet.intersection(set2)) * * // The result contains only elements that are in both sets * assert.deepStrictEqual(HashSet.toValues(result).sort(), [2, 3]) * * // The original sets are unchanged * assert.deepStrictEqual(HashSet.toValues(set1).sort(), [1, 2, 3]) * assert.deepStrictEqual(HashSet.toValues(set2).sort(), [2, 3, 4]) * * // You can also use arrays or other iterables * const intersectWithArray = pipe(set1, HashSet.intersection([2, 3, 5])) * assert.deepStrictEqual( * HashSet.toValues(intersectWithArray).sort(), * [2, 3] * ) * ``` */ <A>(that: Iterable<A>): (self: HashSet<A>) => HashSet<A>
/** * @example * * ```ts * // `data-first` API * import { HashSet } from "effect" * import * as assert from "node:assert/strict" * * // Create two sets with some overlapping elements * const set1 = HashSet.make(1, 2, 3) * const set2 = HashSet.make(2, 3, 4) * * // Compute the intersection using data-first API * const result = HashSet.intersection(set1, set2) * * // The result contains only elements that are in both sets * assert.deepStrictEqual(HashSet.toValues(result).sort(), [2, 3]) * * // The original sets are unchanged * assert.deepStrictEqual(HashSet.toValues(set1).sort(), [1, 2, 3]) * assert.deepStrictEqual(HashSet.toValues(set2).sort(), [2, 3, 4]) * * // You can also use arrays or other iterables * const intersectWithArray = HashSet.intersection(set1, [2, 3, 5]) * assert.deepStrictEqual( * HashSet.toValues(intersectWithArray).sort(), * [2, 3] * ) * ``` */ <A>(self: HashSet<A>, that: Iterable<A>): HashSet<A>} = HS.intersection
/** * Computes the set union `( self ∪ that )` between this `HashSet` and the * specified `Iterable<A>`. * * Time complexity: **`O(n)`** where n is the number of elements in the set * * **NOTE**: the hash and equal of the values in both the set and the iterable * must be the same. * * @memberof HashSet * @since 2.0.0 * @example * * ```ts * // Syntax * import { HashSet, pipe } from "effect" * * // with data-last, a.k.a. pipeable API * pipe(HashSet.make(1, 2, 3), HashSet.union(HashSet.make(3, 4, 5))) * * // or piped with the pipe function * HashSet.make(1, 2, 3).pipe(HashSet.union(HashSet.make(3, 4, 5))) * * // or with data-first API * HashSet.union(HashSet.make(1, 2, 3), HashSet.make(3, 4, 5)) * ``` * * @see Other `HashSet` operations are {@link module:HashSet.difference} {@link module:HashSet.intersection} */export const union: { /** * @example * * ```ts * // `data-last` a.k.a. `pipeable` API * import { HashSet, pipe } from "effect" * import * as assert from "node:assert/strict" * * // Create two sets with some overlapping elements * const selfSet = HashSet.make(1, 2, 3) * const thatIterable = HashSet.make(3, 4, 5) * * // Compute the union (all elements from both sets) * const result = pipe(selfSet, HashSet.union(thatIterable)) * * // The result contains all elements from both sets (without duplicates) * assert.deepStrictEqual( * HashSet.toValues(result).sort(), * [1, 2, 3, 4, 5] * ) * * // The original sets are unchanged * assert.deepStrictEqual(HashSet.toValues(selfSet).sort(), [1, 2, 3]) * assert.deepStrictEqual( * HashSet.toValues(thatIterable).sort(), * [3, 4, 5] * ) * * // You can also use arrays or other iterables * const unionWithArray = pipe(selfSet, HashSet.union([4, 5, 6])) * assert.deepStrictEqual( * HashSet.toValues(unionWithArray).sort(), * [1, 2, 3, 4, 5, 6] * ) * ``` */ <A>(that: Iterable<A>): (self: HashSet<A>) => HashSet<A>
/** * @example * * ```ts * // `data-first` API * import { HashSet } from "effect" * import * as assert from "node:assert/strict" * * // Create two sets with some overlapping elements * const selfSet = HashSet.make(1, 2, 3) * const thatIterable = HashSet.make(3, 4, 5) * * // Compute the union using data-first API * const result = HashSet.union(selfSet, thatIterable) * * // The result contains all elements from both sets (without duplicates) * assert.deepStrictEqual( * HashSet.toValues(result).sort(), * [1, 2, 3, 4, 5] * ) * * // The original sets are unchanged * assert.deepStrictEqual(HashSet.toValues(selfSet).sort(), [1, 2, 3]) * assert.deepStrictEqual( * HashSet.toValues(thatIterable).sort(), * [3, 4, 5] * ) * * // You can also use arrays or other iterables * const unionWithArray = HashSet.union(selfSet, [4, 5, 6]) * assert.deepStrictEqual( * HashSet.toValues(unionWithArray).sort(), * [1, 2, 3, 4, 5, 6] * ) * ``` */ <A>(self: HashSet<A>, that: Iterable<A>): HashSet<A>} = HS.union
/** * Checks if a value is present in the `HashSet`. If it is present, the value * will be removed from the `HashSet`, otherwise the value will be added to the * `HashSet`. * * Time complexity: **`O(1)`** average * * @memberof HashSet * @since 2.0.0 * @example * * ```ts * // Syntax * import { HashSet, pipe } from "effect" * * // with `data-last`, a.k.a. `pipeable` API * pipe(HashSet.make(0, 1, 2), HashSet.toggle(0)) * * // or piped with the pipe function * HashSet.make(0, 1, 2).pipe(HashSet.toggle(0)) * * // or with `data-first` API * HashSet.toggle(HashSet.make(0, 1, 2), 0) * ``` * * @returns A new `HashSet` where the toggled value is being either added or * removed based on the initial `HashSet` state. * @see Other `HashSet` mutations are {@link module:HashSet.add} {@link module:HashSet.remove} {@link module:HashSet.beginMutation} {@link module:HashSet.endMutation} {@link module:HashSet.mutate} */export const toggle: { /** * @example * * ```ts * // `data-last` a.k.a. `pipeable` API * import { HashSet, pipe } from "effect" * import assert from "node:assert/strict" * * // arrange * let set = HashSet.make(0, 1, 2) * * // assert 1: 0 is in the set * assert.equal(pipe(set, HashSet.has(0)), true) * * // act 2: toggle 0 once on the set * set = pipe(set, HashSet.toggle(0)) * * // assert 2: 0 is not in the set any longer * assert.equal(pipe(set, HashSet.has(0)), false) * * // act 3: toggle 0 once again on the set * set = pipe(set, HashSet.toggle(0)) * * // assert 3: 0 in now back in the set * assert.equal(pipe(set, HashSet.has(0)), true) * ``` */ <A>(value: A): (self: HashSet<A>) => HashSet<A>
/** * @example * * ```ts * // `data-first` API * import { HashSet, pipe } from "effect" * import assert from "node:assert/strict" * * // arrange * let set = HashSet.make(0, 1, 2) * * // assert 1: 0 is in the set * assert.equal(HashSet.has(set, 0), true) * * // act 2: toggle 0 once on the set * set = HashSet.toggle(set, 0) * * // assert 2: 0 is not in the set any longer * assert.equal(HashSet.has(set, 0), false) * * // act 3: toggle 0 once again on the set * set = HashSet.toggle(set, 0) * * // assert 3: 0 in now back in the set * assert.equal(HashSet.has(set, 0), true) * ``` */ <A>(self: HashSet<A>, value: A): HashSet<A>} = HS.toggle
/** * Maps over the values of the `HashSet` using the specified function. * * The time complexity is of **`O(n)`**. * * @memberof HashSet * @since 2.0.0 * @category mapping * @example * * ```ts * // Syntax * import { HashSet, pipe } from "effect" * * // with `data-last`, a.k.a. `pipeable` API * pipe( * HashSet.make(0, 1, 2), // HashSet.HashSet<number> * HashSet.map(String) // HashSet.HashSet<string> * ) * * // or piped with the pipe method * HashSet.make(0, 1, 2).pipe(HashSet.map(String)) * * // or with `data-first` API * HashSet.map(HashSet.make(0, 1, 2), String) * ``` */export const map: { /** * @example * * ```ts * import { HashSet, pipe } from "effect" * import * as assert from "node:assert/strict" * * assert.deepStrictEqual( * pipe( * HashSet.make(0, 1, 2), // HashSet.HashSet<number> * HashSet.map((n) => String(n + 1)) // HashSet.HashSet<String> * ), * HashSet.make("1", "2", "3") * ) * ``` */ <A, B>(f: (a: A) => B): (self: HashSet<A>) => HashSet<B>
/** * @example * * ```ts * import { HashSet, pipe } from "effect" * import * as assert from "node:assert/strict" * * assert.deepStrictEqual( * HashSet.map( * HashSet.make(0, 1, 2), // HashSet.HashSet<number> * (n) => String(n + 1) * ), // HashSet.HashSet<String> * HashSet.make("1", "2", "3") * ) * ``` */ <A, B>(self: HashSet<A>, f: (a: A) => B): HashSet<B>} = HS.map
/** * Chains over the values of the `HashSet` using the specified function. * * The time complexity is of **`O(n)`**. * * @memberof HashSet * @since 2.0.0 * @category sequencing * @example * * ```ts * // Syntax * import { HashSet, pipe } from "effect" * * // with `data-last`, a.k.a. `pipeable` API * pipe( * HashSet.make(0, 1, 2), // HashSet.HashSet<number> * HashSet.flatMap((n) => Array.of(String(n))) // HashSet.HashSet<string> * ) * * // or piped with the pipe method * HashSet.make(0, 1, 2) // HashSet.HashSet<number> * .pipe( * HashSet.flatMap((n) => Array.of(String(n))) // HashSet.HashSet<string> * ) * * // or with `data-first` API * HashSet.flatMap(HashSet.make(0, 1, 2), (n) => Array.of(String(n))) * ``` */export const flatMap: { /** * @example * * ```ts * import { HashSet, pipe, List } from "effect" * import * as assert from "node:assert/strict" * * assert.deepStrictEqual( * pipe( * HashSet.make(0, 1, 2), * HashSet.flatMap((n) => List.of(String(n * n))) // needs to return an Iterable * ), * HashSet.make("0", "1", "4") * ) * ``` */ <A, B>(f: (a: A) => Iterable<B>): (self: HashSet<A>) => HashSet<B>
/** * @example * * ```ts * import { HashSet, pipe, List } from "effect" * import * as assert from "node:assert/strict" * * assert.deepStrictEqual( * HashSet.flatMap(HashSet.make(0, 1, 2), (n) => * List.of(String(n * n * n)) * ), // needs to return an Iterable * HashSet.make("0", "1", "8") * ) * ``` */ <A, B>(self: HashSet<A>, f: (a: A) => Iterable<B>): HashSet<B>} = HS.flatMap
/** * Applies the specified function to the values of the `HashSet`. * * The time complexity is of **`O(n)`**. * * @memberof HashSet * @since 2.0.0 * @category traversing * @example * * ```ts * // Syntax * import { HashSet, pipe } from "effect" * * // with `data-last`, a.k.a. `pipeable` API * pipe(HashSet.make(0, 1, 2), HashSet.forEach(console.log)) // logs: 0 1 2 * * // or piped with the pipe method * HashSet.make(0, 1, 2).pipe(HashSet.forEach(console.log)) // logs: 0 1 2 * * // or with `data-first` API * HashSet.forEach(HashSet.make(0, 1, 2), console.log) // logs: 0 1 2 * ``` */export const forEach: { /** * @example * * ```ts * import { HashSet, pipe } from "effect" * import * as assert from "node:assert/strict" * * const result: Array<number> = [] * * pipe( * HashSet.make(0, 1, 2), * HashSet.forEach((n): void => { * result.push(n) * }) * ) * * assert.deepStrictEqual(result, [0, 1, 2]) * ``` */ <A>(f: (value: A) => void): (self: HashSet<A>) => void
/** * @example * * ```ts * import { HashSet, pipe } from "effect" * import * as assert from "node:assert/strict" * * const result: Array<number> = [] * * HashSet.forEach(HashSet.make(0, 1, 2), (n): void => { * result.push(n) * }) * * assert.deepStrictEqual(result, [0, 1, 2]) * ``` */ <A>(self: HashSet<A>, f: (value: A) => void): void} = HS.forEach
/** * Reduces the specified state over the values of the `HashSet`. * * The time complexity is of **`O(n)`**. * * @memberof HashSet * @since 2.0.0 * @category folding * @example * * ```ts * // Syntax * import { HashSet, pipe } from "effect" * * const sum = (a: number, b: number): number => a + b * * // with `data-last`, a.k.a. `pipeable` API * pipe(HashSet.make(0, 1, 2), HashSet.reduce(0, sum)) * * // or with the pipe method * HashSet.make(0, 1, 2).pipe(HashSet.reduce(0, sum)) * * // or with `data-first` API * HashSet.reduce(HashSet.make(0, 1, 2), 0, sum) * ``` */export const reduce: { /** * @example * * ```ts * import { HashSet, pipe } from "effect" * import * as assert from "node:assert/strict" * * assert.equal( * pipe( * HashSet.make(0, 1, 2), * HashSet.reduce(10, (accumulator, value) => accumulator + value) * ), * 13 * ) * ``` */ <A, Z>(zero: Z, f: (accumulator: Z, value: A) => Z): (self: HashSet<A>) => Z
/** * @example * * ```ts * import { HashSet } from "effect" * import * as assert from "node:assert/strict" * * assert.equal( * HashSet.reduce( * HashSet.make(0, 1, 2), * -3, * (accumulator, value) => accumulator + value * ), * 0 * ) * ``` */ <A, Z>(self: HashSet<A>, zero: Z, f: (accumulator: Z, value: A) => Z): Z} = HS.reduce
/** * Filters values out of a `HashSet` using the specified predicate. * * The time complexity is of **`O(n)`**. * * @memberof HashSet * @since 2.0.0 * @category filtering * @example * * ```ts * // Syntax with Predicate * import { HashSet, type Predicate, pipe } from "effect" * * const filterPositiveNumbers: Predicate.Predicate<number> = (n) => n > 0 * * // with `data-last`, a.k.a. `pipeable` API * pipe( * HashSet.make(-2, -1, 0, 1, 2), * HashSet.filter(filterPositiveNumbers) * ) * * // or with the pipe method * HashSet.make(-2, -1, 0, 1, 2).pipe(HashSet.filter(filterPositiveNumbers)) * * // or with `data-first` API * HashSet.filter(HashSet.make(-2, -1, 0, 1, 2), filterPositiveNumbers) * ``` * * @example * * ```ts * /// Syntax with Refinement * import { HashSet, pipe } from "effect" * * const stringRefinement = (value: unknown): value is string => * typeof value === "string" * * // with `data-last`, a.k.a. `pipeable` API * pipe( * HashSet.make(1, "unos", 2, "two", 3, "trois", 4, "vier"), // // HashSet.HashSet<number | string> * HashSet.filter(stringRefinement) * ) // HashSet.HashSet<string> * * // or with the pipe method * HashSet.make(1, "unos", 2, "two", 3, "trois", 4, "vier") // HashSet.HashSet<number | string> * .pipe(HashSet.filter(stringRefinement)) // HashSet.HashSet<string> * * // or with `data-first` API * HashSet.filter( * HashSet.make(1, "unos", 2, "two", 3, "trois", 4, "vier"), // HashSet.HashSet<number | string> * stringRefinement * ) // HashSet.HashSet<string> * ``` */export const filter: { /** * @example * * ```ts * import { HashSet, pipe, Predicate } from "effect" * import * as assert from "node:assert/strict" * * const numbersAndStringsHashSet: HashSet.HashSet<number | string> = * HashSet.make(1, "unos", 2, "two", 3, "trois", 4, "vier") * * const stringRefinement: Predicate.Refinement< * string | number, * string * > = (value) => typeof value === "string" * * const stringHashSet: HashSet.HashSet<string> = pipe( * numbersAndStringsHashSet, * HashSet.filter(stringRefinement) * ) * * assert.equal( * pipe(stringHashSet, HashSet.every(Predicate.isString)), * true * ) * ``` */ <A, B extends A>( refinement: Refinement<NoInfer<A>, B> ): (self: HashSet<A>) => HashSet<B>
/** * @example * * ```ts * import { HashSet, pipe, type Predicate } from "effect" * import * as assert from "node:assert/strict" * * const filterPositiveNumbers: Predicate.Predicate<number> = (n) => n > 0 * * assert.deepStrictEqual( * pipe( * HashSet.make(-2, -1, 0, 1, 2), * HashSet.filter(filterPositiveNumbers) * ), * HashSet.make(1, 2) * ) * ``` */ <A>(predicate: Predicate<NoInfer<A>>): (self: HashSet<A>) => HashSet<A>
/** * @example * * ```ts * import { HashSet, Predicate } from "effect" * import * as assert from "node:assert/strict" * * const numbersAndStringsHashSet: HashSet.HashSet<number | string> = * HashSet.make(1, "unos", 2, "two", 3, "trois", 4, "vier") * * const stringRefinement: Predicate.Refinement< * string | number, * string * > = (value) => typeof value === "string" * * const stringHashSet: HashSet.HashSet<string> = HashSet.filter( * numbersAndStringsHashSet, * stringRefinement * ) * * assert.equal(HashSet.every(stringHashSet, Predicate.isString), true) * ``` */ <A, B extends A>( self: HashSet<A>, refinement: Refinement<A, B> ): HashSet<B>
/** * @example * * ```ts * import { HashSet, pipe, type Predicate } from "effect" * import * as assert from "node:assert/strict" * * const filterPositiveNumbers: Predicate.Predicate<number> = (n) => n > 0 * * assert.deepStrictEqual( * HashSet.filter(HashSet.make(-2, -1, 0, 1, 2), filterPositiveNumbers), * HashSet.make(1, 2) * ) * ``` */ <A>(self: HashSet<A>, predicate: Predicate<A>): HashSet<A>} = HS.filter
/** * Partition the values of a `HashSet` using the specified predicate. * * If a value matches the predicate, it will be placed into the `HashSet` on the * right side of the resulting `Tuple`, otherwise the value will be placed into * the left side. * * Time complexity is of **`O(n)`**. * * @memberof HashSet * @since 2.0.0 * @category partitioning * @example * * ```ts * // Syntax with Predicate * import { HashSet, pipe, Predicate } from "effect" * * // with `data-last`, a.k.a. `pipeable` API * pipe( * HashSet.make(0, 1, 2, 3, 4, 5), * HashSet.partition((n) => n % 2 === 0) * ) * * // or with the pipe method * HashSet.make(0, 1, 2, 3, 4, 5).pipe( * HashSet.partition((n) => n % 2 === 0) * ) * * // or with `data-first` API * HashSet.partition(HashSet.make(0, 1, 2, 3, 4, 5), (n) => n % 2 === 0) * ``` * * @example * * ```ts * // Syntax with Refinement * import { HashSet, pipe, Predicate } from "effect" * * const stringRefinement: Predicate.Refinement<string | number, string> = ( * value * ) => typeof value === "string" * * // with `data-last`, a.k.a. `pipeable` API * pipe( * HashSet.make(1, "unos", 2, "two", 3, "trois", 4, "vier"), * HashSet.partition(stringRefinement) * ) * * // or with the pipe method * HashSet.make(1, "unos", 2, "two", 3, "trois", 4, "vier").pipe( * HashSet.partition(stringRefinement) * ) * * // or with `data-first` API * HashSet.partition( * HashSet.make(1, "unos", 2, "two", 3, "trois", 4, "vier"), * stringRefinement * ) * ``` */export const partition: { /** * @example * * ```ts * import { HashSet, pipe, Predicate } from "effect" * import * as assert from "node:assert/strict" * * const numbersAndStringsHashSet: HashSet.HashSet<number | string> = * HashSet.make(1, "unos", 2, "two", 3, "trois", 4, "vier") * * const stringRefinement: Predicate.Refinement< * string | number, * string * > = (value) => typeof value === "string" * * const [ * excluded, // HashSet.HashSet<number> * satisfying // HashSet.HashSet<string> * ] = pipe(numbersAndStringsHashSet, HashSet.partition(stringRefinement)) * * assert.equal(pipe(satisfying, HashSet.every(Predicate.isString)), true) * assert.equal(pipe(excluded, HashSet.every(Predicate.isNumber)), true) * * assert.deepStrictEqual(excluded, HashSet.make(1, 2, 3, 4)) * assert.deepStrictEqual( * satisfying, * HashSet.make("unos", "two", "trois", "vier") * ) * ``` */ <A, B extends A>( refinement: Refinement<NoInfer<A>, B> ): ( self: HashSet<A> ) => [excluded: HashSet<Exclude<A, B>>, satisfying: HashSet<B>]
/** * @example * * ```ts * import { HashSet, pipe } from "effect" * import * as assert from "node:assert/strict" * * const [excluded, satisfying] = pipe( * HashSet.make(0, 1, 2, 3, 4, 5), * HashSet.partition((n) => n % 2 === 0) * ) * * assert.deepStrictEqual(excluded, HashSet.make(1, 3, 5)) * assert.deepStrictEqual(satisfying, HashSet.make(0, 2, 4)) * ``` */ <A>( predicate: Predicate<NoInfer<A>> ): (self: HashSet<A>) => [excluded: HashSet<A>, satisfying: HashSet<A>]
/** * @example * * ```ts * import { HashSet, pipe, Predicate } from "effect" * import * as assert from "node:assert/strict" * * const numbersAndStringsHashSet: HashSet.HashSet<number | string> = * HashSet.make(1, "unos", 2, "two", 3, "trois", 4, "vier") * * const stringRefinement: Predicate.Refinement< * string | number, * string * > = (value) => typeof value === "string" * * const [ * excluded, // HashSet.HashSet<number> * satisfying // HashSet.HashSet<string> * ] = HashSet.partition(numbersAndStringsHashSet, stringRefinement) * * assert.equal(HashSet.every(satisfying, Predicate.isString), true) * assert.equal(HashSet.every(excluded, Predicate.isNumber), true) * * assert.deepStrictEqual(excluded, HashSet.make(1, 2, 3, 4)) * assert.deepStrictEqual( * satisfying, * HashSet.make("unos", "two", "trois", "vier") * ) * ``` */ <A, B extends A>( self: HashSet<A>, refinement: Refinement<A, B> ): [excluded: HashSet<Exclude<A, B>>, satisfying: HashSet<B>]
/** * @example * * ```ts * import { HashSet } from "effect" * import * as assert from "node:assert/strict" * * const [excluded, satisfying] = HashSet.partition( * HashSet.make(0, 1, 2, 3, 4, 5), * (n) => n % 2 === 0 * ) * * assert.deepStrictEqual(excluded, HashSet.make(1, 3, 5)) * assert.deepStrictEqual(satisfying, HashSet.make(0, 2, 4)) * ``` */ <A>( self: HashSet<A>, predicate: Predicate<A> ): [excluded: HashSet<A>, satisfying: HashSet<A>]} = HS.partition123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201/** * @since 2.0.0 */import type * as Duration from "./Duration.js"import type * as Effect from "./Effect.js"import * as internal from "./internal/keyedPool.js"import type { Pipeable } from "./Pipeable.js"import type * as Scope from "./Scope.js"import type * as Types from "./Types.js"
/** * @since 2.0.0 * @category symbols */export const KeyedPoolTypeId: unique symbol = internal.KeyedPoolTypeId
/** * @since 2.0.0 * @category symbols */export type KeyedPoolTypeId = typeof KeyedPoolTypeId
/** * A `KeyedPool<K, A, E>` is a pool of `Pool`s of items of type `A`. Each pool * in the `KeyedPool` is associated with a key of type `K`. * * @since 2.0.0 * @category models */export interface KeyedPool<in K, in out A, out E = never> extends KeyedPool.Variance<K, A, E>, Pipeable { /** * Retrieves an item from the pool belonging to the given key in a scoped * effect. Note that if acquisition fails, then the returned effect will fail * for that same reason. Retrying a failed acquisition attempt will repeat the * acquisition attempt. */ get(key: K): Effect.Effect<A, E, Scope.Scope>
/** * Invalidates the specified item. This will cause the pool to eventually * reallocate the item, although this reallocation may occur lazily rather * than eagerly. */ invalidate(item: A): Effect.Effect<void>}
/** * @since 2.0.0 */export declare namespace KeyedPool { /** * @since 2.0.0 * @category models */ export interface Variance<in K, in out A, out E> { readonly [KeyedPoolTypeId]: { readonly _K: Types.Contravariant<K> readonly _A: Types.Invariant<A> readonly _E: Types.Covariant<E> } }}
/** * Makes a new pool of the specified fixed size. The pool is returned in a * `Scope`, which governs the lifetime of the pool. When the pool is shutdown * because the `Scope` is closed, the individual items allocated by the pool * will be released in some unspecified order. * * @since 2.0.0 * @category constructors */export const make: <K, A, E, R>( options: { readonly acquire: (key: K) => Effect.Effect<A, E, R> readonly size: number }) => Effect.Effect<KeyedPool<K, A, E>, never, Scope.Scope | R> = internal.make
/** * Makes a new pool of the specified fixed size. The pool is returned in a * `Scope`, which governs the lifetime of the pool. When the pool is shutdown * because the `Scope` is closed, the individual items allocated by the pool * will be released in some unspecified order. * * The size of the underlying pools can be configured per key. * * @since 2.0.0 * @category constructors */export const makeWith: <K, A, E, R>( options: { readonly acquire: (key: K) => Effect.Effect<A, E, R> readonly size: (key: K) => number }) => Effect.Effect<KeyedPool<K, A, E>, never, Scope.Scope | R> = internal.makeWith
/** * Makes a new pool with the specified minimum and maximum sizes and time to * live before a pool whose excess items are not being used will be shrunk * down to the minimum size. The pool is returned in a `Scope`, which governs * the lifetime of the pool. When the pool is shutdown because the `Scope` is * used, the individual items allocated by the pool will be released in some * unspecified order. * * The size of the underlying pools can be configured per key. * * @since 2.0.0 * @category constructors */export const makeWithTTL: <K, A, E, R>( options: { readonly acquire: (key: K) => Effect.Effect<A, E, R> readonly min: (key: K) => number readonly max: (key: K) => number readonly timeToLive: Duration.DurationInput }) => Effect.Effect<KeyedPool<K, A, E>, never, Scope.Scope | R> = internal.makeWithTTL
/** * Makes a new pool with the specified minimum and maximum sizes and time to * live before a pool whose excess items are not being used will be shrunk * down to the minimum size. The pool is returned in a `Scope`, which governs * the lifetime of the pool. When the pool is shutdown because the `Scope` is * used, the individual items allocated by the pool will be released in some * unspecified order. * * The size of the underlying pools can be configured per key. * * @since 2.0.0 * @category constructors */export const makeWithTTLBy: <K, A, E, R>( options: { readonly acquire: (key: K) => Effect.Effect<A, E, R> readonly min: (key: K) => number readonly max: (key: K) => number readonly timeToLive: (key: K) => Duration.DurationInput }) => Effect.Effect<KeyedPool<K, A, E>, never, Scope.Scope | R> = internal.makeWithTTLBy
/** * Retrieves an item from the pool belonging to the given key in a scoped * effect. Note that if acquisition fails, then the returned effect will fail * for that same reason. Retrying a failed acquisition attempt will repeat the * acquisition attempt. * * @since 2.0.0 * @category combinators */export const get: { /** * Retrieves an item from the pool belonging to the given key in a scoped * effect. Note that if acquisition fails, then the returned effect will fail * for that same reason. Retrying a failed acquisition attempt will repeat the * acquisition attempt. * * @since 2.0.0 * @category combinators */ <K>(key: K): <A, E>(self: KeyedPool<K, A, E>) => Effect.Effect<A, E, Scope.Scope> /** * Retrieves an item from the pool belonging to the given key in a scoped * effect. Note that if acquisition fails, then the returned effect will fail * for that same reason. Retrying a failed acquisition attempt will repeat the * acquisition attempt. * * @since 2.0.0 * @category combinators */ <K, A, E>(self: KeyedPool<K, A, E>, key: K): Effect.Effect<A, E, Scope.Scope>} = internal.get
/** * Invalidates the specified item. This will cause the pool to eventually * reallocate the item, although this reallocation may occur lazily rather * than eagerly. * * @since 2.0.0 * @category combinators */export const invalidate: { /** * Invalidates the specified item. This will cause the pool to eventually * reallocate the item, although this reallocation may occur lazily rather * than eagerly. * * @since 2.0.0 * @category combinators */ <A>(item: A): <K, E>(self: KeyedPool<K, A, E>) => Effect.Effect<void> /** * Invalidates the specified item. This will cause the pool to eventually * reallocate the item, although this reallocation may occur lazily rather * than eagerly. * * @since 2.0.0 * @category combinators */ <K, A, E>(self: KeyedPool<K, A, E>, item: A): Effect.Effect<void>} = internal.invalidate1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723/** * A `Layer<ROut, E, RIn>` describes how to build one or more services in your * application. Services can be injected into effects via * `Effect.provideService`. Effects can require services via `Effect.service`. * * Layer can be thought of as recipes for producing bundles of services, given * their dependencies (other services). * * Construction of services can be effectful and utilize resources that must be * acquired and safely released when the services are done being utilized. * * By default layers are shared, meaning that if the same layer is used twice * the layer will only be allocated a single time. * * Because of their excellent composition properties, layers are the idiomatic * way in Effect-TS to create services that depend on other services. * * @since 2.0.0 */import type * as Cause from "./Cause.js"import type * as Clock from "./Clock.js"import type { ConfigProvider } from "./ConfigProvider.js"import * as Context from "./Context.js"import type * as Effect from "./Effect.js"import type * as Exit from "./Exit.js"import type { FiberRef } from "./FiberRef.js"import { dual, type LazyArg } from "./Function.js"import { clockTag } from "./internal/clock.js"import * as core from "./internal/core.js"import * as defaultServices from "./internal/defaultServices.js"import * as fiberRuntime from "./internal/fiberRuntime.js"import * as internal from "./internal/layer.js"import * as circularLayer from "./internal/layer/circular.js"import * as query from "./internal/query.js"import { randomTag } from "./internal/random.js"import type { LogLevel } from "./LogLevel.js"import type * as Option from "./Option.js"import type { Pipeable } from "./Pipeable.js"import type * as Random from "./Random.js"import type * as Request from "./Request.js"import type * as Runtime from "./Runtime.js"import type * as Schedule from "./Schedule.js"import * as Scheduler from "./Scheduler.js"import type * as Scope from "./Scope.js"import type * as Stream from "./Stream.js"import type * as Tracer from "./Tracer.js"import type * as Types from "./Types.js"
/** * @since 2.0.0 * @category symbols */export const LayerTypeId: unique symbol = internal.LayerTypeId
/** * @since 2.0.0 * @category symbols */export type LayerTypeId = typeof LayerTypeId
/** * @since 2.0.0 * @category models */export interface Layer<in ROut, out E = never, out RIn = never> extends Layer.Variance<ROut, E, RIn>, Pipeable {}
/** * @since 2.0.0 */export declare namespace Layer { /** * @since 2.0.0 * @category models */ export interface Variance<in ROut, out E, out RIn> { readonly [LayerTypeId]: { readonly _ROut: Types.Contravariant<ROut> readonly _E: Types.Covariant<E> readonly _RIn: Types.Covariant<RIn> } } /** * @since 3.9.0 * @category type-level */ export interface Any { readonly [LayerTypeId]: { readonly _ROut: Types.Contravariant<never> readonly _E: Types.Covariant<any> readonly _RIn: Types.Covariant<any> } } /** * @since 2.0.0 * @category type-level */ export type Context<T extends Any> = [T] extends [Layer<infer _ROut, infer _E, infer _RIn>] ? _RIn : never /** * @since 2.0.0 * @category type-level */ export type Error<T extends Any> = [T] extends [Layer<infer _ROut, infer _E, infer _RIn>] ? _E : never /** * @since 2.0.0 * @category type-level */ export type Success<T extends Any> = [T] extends [Layer<infer _ROut, infer _E, infer _RIn>] ? _ROut : never}
/** * @since 2.0.0 * @category symbols */export const MemoMapTypeId: unique symbol = internal.MemoMapTypeId
/** * @since 2.0.0 * @category symbols */export type MemoMapTypeId = typeof MemoMapTypeId
/** * @since 2.0.0 * @category models */export interface MemoMap { readonly [MemoMapTypeId]: MemoMapTypeId
/** @internal */ readonly getOrElseMemoize: <RIn, E, ROut>( layer: Layer<ROut, E, RIn>, scope: Scope.Scope ) => Effect.Effect<Context.Context<ROut>, E, RIn>}
/** * @since 3.13.0 * @category models */export interface CurrentMemoMap { readonly _: unique symbol}
/** * @since 3.13.0 * @category models */export const CurrentMemoMap: Context.Reference<CurrentMemoMap, MemoMap> = internal.CurrentMemoMap
/** * Returns `true` if the specified value is a `Layer`, `false` otherwise. * * @since 2.0.0 * @category getters */export const isLayer: (u: unknown) => u is Layer<unknown, unknown, unknown> = internal.isLayer
/** * Returns `true` if the specified `Layer` is a fresh version that will not be * shared, `false` otherwise. * * @since 2.0.0 * @category getters */export const isFresh: <RIn, E, ROut>(self: Layer<ROut, E, RIn>) => boolean = internal.isFresh
/** * @since 3.3.0 * @category tracing */export const annotateLogs: { /** * @since 3.3.0 * @category tracing */ (key: string, value: unknown): <A, E, R>(self: Layer<A, E, R>) => Layer<A, E, R> /** * @since 3.3.0 * @category tracing */ (values: Record<string, unknown>): <A, E, R>(self: Layer<A, E, R>) => Layer<A, E, R> /** * @since 3.3.0 * @category tracing */ <A, E, R>(self: Layer<A, E, R>, key: string, value: unknown): Layer<A, E, R> /** * @since 3.3.0 * @category tracing */ <A, E, R>(self: Layer<A, E, R>, values: Record<string, unknown>): Layer<A, E, R>} = internal.annotateLogs
/** * @since 3.3.0 * @category tracing */export const annotateSpans: { /** * @since 3.3.0 * @category tracing */ (key: string, value: unknown): <A, E, R>(self: Layer<A, E, R>) => Layer<A, E, R> /** * @since 3.3.0 * @category tracing */ (values: Record<string, unknown>): <A, E, R>(self: Layer<A, E, R>) => Layer<A, E, R> /** * @since 3.3.0 * @category tracing */ <A, E, R>(self: Layer<A, E, R>, key: string, value: unknown): Layer<A, E, R> /** * @since 3.3.0 * @category tracing */ <A, E, R>(self: Layer<A, E, R>, values: Record<string, unknown>): Layer<A, E, R>} = internal.annotateSpans
/** * Builds a layer into a scoped value. * * @since 2.0.0 * @category destructors */export const build: <RIn, E, ROut>( self: Layer<ROut, E, RIn>) => Effect.Effect<Context.Context<ROut>, E, Scope.Scope | RIn> = internal.build
/** * Builds a layer into an `Effect` value. Any resources associated with this * layer will be released when the specified scope is closed unless their scope * has been extended. This allows building layers where the lifetime of some of * the services output by the layer exceed the lifetime of the effect the * layer is provided to. * * @since 2.0.0 * @category destructors */export const buildWithScope: { /** * Builds a layer into an `Effect` value. Any resources associated with this * layer will be released when the specified scope is closed unless their scope * has been extended. This allows building layers where the lifetime of some of * the services output by the layer exceed the lifetime of the effect the * layer is provided to. * * @since 2.0.0 * @category destructors */ (scope: Scope.Scope): <RIn, E, ROut>(self: Layer<ROut, E, RIn>) => Effect.Effect<Context.Context<ROut>, E, RIn> /** * Builds a layer into an `Effect` value. Any resources associated with this * layer will be released when the specified scope is closed unless their scope * has been extended. This allows building layers where the lifetime of some of * the services output by the layer exceed the lifetime of the effect the * layer is provided to. * * @since 2.0.0 * @category destructors */ <RIn, E, ROut>(self: Layer<ROut, E, RIn>, scope: Scope.Scope): Effect.Effect<Context.Context<ROut>, E, RIn>} = internal.buildWithScope
/** * Recovers from all errors. * * @since 2.0.0 * @category error handling */export const catchAll: { /** * Recovers from all errors. * * @since 2.0.0 * @category error handling */ <E, RIn2, E2, ROut2>(onError: (error: E) => Layer<ROut2, E2, RIn2>): <RIn, ROut>(self: Layer<ROut, E, RIn>) => Layer<ROut & ROut2, E2, RIn2 | RIn> /** * Recovers from all errors. * * @since 2.0.0 * @category error handling */ <RIn, E, ROut, RIn2, E2, ROut2>(self: Layer<ROut, E, RIn>, onError: (error: E) => Layer<ROut2, E2, RIn2>): Layer<ROut & ROut2, E2, RIn | RIn2>} = internal.catchAll
/** * Recovers from all errors. * * @since 2.0.0 * @category error handling */export const catchAllCause: { /** * Recovers from all errors. * * @since 2.0.0 * @category error handling */ <E, RIn2, E2, ROut2>(onError: (cause: Cause.Cause<E>) => Layer<ROut2, E2, RIn2>): <RIn, ROut>(self: Layer<ROut, E, RIn>) => Layer<ROut & ROut2, E2, RIn2 | RIn> /** * Recovers from all errors. * * @since 2.0.0 * @category error handling */ <RIn, E, ROut, RIn2, E2, ROut22>( self: Layer<ROut, E, RIn>, onError: (cause: Cause.Cause<E>) => Layer<ROut22, E2, RIn2> ): Layer<ROut & ROut22, E2, RIn | RIn2>} = internal.catchAllCause
/** * Constructs a `Layer` that passes along the specified context as an * output. * * @since 2.0.0 * @category constructors */export const context: <R>() => Layer<R, never, R> = internal.context
/** * Constructs a layer that dies with the specified defect. * * @since 2.0.0 * @category constructors */export const die: (defect: unknown) => Layer<unknown> = internal.die
/** * Constructs a layer that dies with the specified defect. * * @since 2.0.0 * @category constructors */export const dieSync: (evaluate: LazyArg<unknown>) => Layer<unknown> = internal.dieSync
/** * Replaces the layer's output with `never` and includes the layer only for its * side-effects. * * @since 2.0.0 * @category mapping */export const discard: <RIn, E, ROut>(self: Layer<ROut, E, RIn>) => Layer<never, E, RIn> = internal.discard
/** * Constructs a layer from the specified effect. * * @since 2.0.0 * @category constructors */export const effect: { /** * Constructs a layer from the specified effect. * * @since 2.0.0 * @category constructors */ <I, S>(tag: Context.Tag<I, S>): <E, R>(effect: Effect.Effect<Types.NoInfer<S>, E, R>) => Layer<I, E, R> /** * Constructs a layer from the specified effect. * * @since 2.0.0 * @category constructors */ <I, S, E, R>(tag: Context.Tag<I, S>, effect: Effect.Effect<Types.NoInfer<S>, E, R>): Layer<I, E, R>} = internal.fromEffect
/** * Constructs a layer from the specified effect, discarding its output. * * @since 2.0.0 * @category constructors */export const effectDiscard: <X, E, R>(effect: Effect.Effect<X, E, R>) => Layer<never, E, R> = internal.fromEffectDiscard
/** * Constructs a layer from the specified effect, which must return one or more * services. * * @since 2.0.0 * @category constructors */export const effectContext: <A, E, R>(effect: Effect.Effect<Context.Context<A>, E, R>) => Layer<A, E, R> = internal.fromEffectContext
/** * A Layer that constructs an empty Context. * * @since 2.0.0 * @category constructors */export const empty: Layer<never> = internal.empty
/** * Extends the scope of this layer, returning a new layer that when provided * to an effect will not immediately release its associated resources when * that effect completes execution but instead when the scope the resulting * effect depends on is closed. * * @since 2.0.0 * @category utils */export const extendScope: <RIn, E, ROut>(self: Layer<ROut, E, RIn>) => Layer<ROut, E, Scope.Scope | RIn> = internal.extendScope
/** * Constructs a layer that fails with the specified error. * * @since 2.0.0 * @category constructors */export const fail: <E>(error: E) => Layer<unknown, E> = internal.fail
/** * Constructs a layer that fails with the specified error. * * @since 2.0.0 * @category constructors */export const failSync: <E>(evaluate: LazyArg<E>) => Layer<unknown, E> = internal.failSync
/** * Constructs a layer that fails with the specified cause. * * @since 2.0.0 * @category constructors */export const failCause: <E>(cause: Cause.Cause<E>) => Layer<unknown, E> = internal.failCause
/** * Constructs a layer that fails with the specified cause. * * @since 2.0.0 * @category constructors */export const failCauseSync: <E>(evaluate: LazyArg<Cause.Cause<E>>) => Layer<unknown, E> = internal.failCauseSync
/** * Constructs a layer dynamically based on the output of this layer. * * @since 2.0.0 * @category sequencing */export const flatMap: { /** * Constructs a layer dynamically based on the output of this layer. * * @since 2.0.0 * @category sequencing */ <A, A2, E2, R2>(f: (context: Context.Context<A>) => Layer<A2, E2, R2>): <E, R>(self: Layer<A, E, R>) => Layer<A2, E2 | E, R2 | R> /** * Constructs a layer dynamically based on the output of this layer. * * @since 2.0.0 * @category sequencing */ <A, E, R, A2, E2, R2>( self: Layer<A, E, R>, f: (context: Context.Context<A>) => Layer<A2, E2, R2> ): Layer<A2, E | E2, R | R2>} = internal.flatMap
/** * Flattens layers nested in the context of an effect. * * @since 2.0.0 * @category sequencing */export const flatten: { /** * Flattens layers nested in the context of an effect. * * @since 2.0.0 * @category sequencing */ <I, A, E2, R2>(tag: Context.Tag<I, Layer<A, E2, R2>>): <E, R>(self: Layer<I, E, R>) => Layer<A, E2 | E, R2 | R> /** * Flattens layers nested in the context of an effect. * * @since 2.0.0 * @category sequencing */ <I, E, R, A, E2, R2>(self: Layer<I, E, R>, tag: Context.Tag<I, Layer<A, E2, R2>>): Layer<A, E | E2, R | R2>} = internal.flatten
/** * Creates a fresh version of this layer that will not be shared. * * @since 2.0.0 * @category utils */export const fresh: <A, E, R>(self: Layer<A, E, R>) => Layer<A, E, R> = internal.fresh
/** * @since 3.17.0 * @category Testing */export type PartialEffectful<A extends object> = Types.Simplify< & { [ K in keyof A as A[K] extends | Effect.Effect<any, any, any> | Stream.Stream<any, any, any> | ((...args: any) => Effect.Effect<any, any, any> | Stream.Stream<any, any, any>) ? K : never ]?: A[K] } & { [ K in keyof A as A[K] extends | Effect.Effect<any, any, any> | Stream.Stream<any, any, any> | ((...args: any) => Effect.Effect<any, any, any> | Stream.Stream<any, any, any>) ? never : K ]: A[K] }>
/** * Creates a mock layer for testing purposes. You can provide a partial * implementation of the service, and any methods not provided will * throw an `UnimplementedError` defect when called. * * **Example** * * ```ts * import { Context, Effect, Layer } from "effect" * * class MyService extends Context.Tag("MyService")< * MyService, * { * one: Effect.Effect<number> * two(): Effect.Effect<number> * } * >() {} * * const MyServiceTest = Layer.mock(MyService, { * two: () => Effect.succeed(2) * }) * ``` * * @since 3.17.0 * @category Testing */export const mock: { /** * Creates a mock layer for testing purposes. You can provide a partial * implementation of the service, and any methods not provided will * throw an `UnimplementedError` defect when called. * * **Example** * * ```ts * import { Context, Effect, Layer } from "effect" * * class MyService extends Context.Tag("MyService")< * MyService, * { * one: Effect.Effect<number> * two(): Effect.Effect<number> * } * >() {} * * const MyServiceTest = Layer.mock(MyService, { * two: () => Effect.succeed(2) * }) * ``` * * @since 3.17.0 * @category Testing */ <I, S extends object>(tag: Context.Tag<I, S>): (service: PartialEffectful<S>) => Layer<I> /** * Creates a mock layer for testing purposes. You can provide a partial * implementation of the service, and any methods not provided will * throw an `UnimplementedError` defect when called. * * **Example** * * ```ts * import { Context, Effect, Layer } from "effect" * * class MyService extends Context.Tag("MyService")< * MyService, * { * one: Effect.Effect<number> * two(): Effect.Effect<number> * } * >() {} * * const MyServiceTest = Layer.mock(MyService, { * two: () => Effect.succeed(2) * }) * ``` * * @since 3.17.0 * @category Testing */ <I, S extends object>(tag: Context.Tag<I, S>, service: PartialEffectful<S>): Layer<I>} = internal.mock
const fromFunction: <I1, S1, I2, S2>( tagA: Context.Tag<I1, S1>, tagB: Context.Tag<I2, S2>, f: (a: Types.NoInfer<S1>) => Types.NoInfer<S2>) => Layer<I2, never, I1> = internal.fromFunction
export { /** * Constructs a layer from the context using the specified function. * * @since 2.0.0 * @category constructors */ fromFunction as function}
/** * Builds this layer and uses it until it is interrupted. This is useful when * your entire application is a layer, such as an HTTP server. * * @since 2.0.0 * @category conversions */export const launch: <RIn, E, ROut>(self: Layer<ROut, E, RIn>) => Effect.Effect<never, E, RIn> = internal.launch
/** * Returns a new layer whose output is mapped by the specified function. * * @since 2.0.0 * @category mapping */export const map: { /** * Returns a new layer whose output is mapped by the specified function. * * @since 2.0.0 * @category mapping */ <A, B>(f: (context: Context.Context<A>) => Context.Context<B>): <E, R>(self: Layer<A, E, R>) => Layer<B, E, R> /** * Returns a new layer whose output is mapped by the specified function. * * @since 2.0.0 * @category mapping */ <A, E, R, B>( self: Layer<A, E, R>, f: (context: Context.Context<A>) => Context.Context<B> ): Layer<B, E, R>} = internal.map
/** * Returns a layer with its error channel mapped using the specified function. * * @since 2.0.0 * @category mapping */export const mapError: { /** * Returns a layer with its error channel mapped using the specified function. * * @since 2.0.0 * @category mapping */ <E, E2>(f: (error: E) => E2): <A, R>(self: Layer<A, E, R>) => Layer<A, E2, R> /** * Returns a layer with its error channel mapped using the specified function. * * @since 2.0.0 * @category mapping */ <A, E, R, E2>(self: Layer<A, E, R>, f: (error: E) => E2): Layer<A, E2, R>} = internal.mapError
/** * Feeds the error or output services of this layer into the input of either * the specified `failure` or `success` layers, resulting in a new layer with * the inputs of this layer, and the error or outputs of the specified layer. * * @since 2.0.0 * @category folding */export const match: { /** * Feeds the error or output services of this layer into the input of either * the specified `failure` or `success` layers, resulting in a new layer with * the inputs of this layer, and the error or outputs of the specified layer. * * @since 2.0.0 * @category folding */ <E, A2, E2, R2, A, A3, E3, R3>( options: { readonly onFailure: (error: E) => Layer<A2, E2, R2> readonly onSuccess: (context: Context.Context<A>) => Layer<A3, E3, R3> } ): <R>(self: Layer<A, E, R>) => Layer<A2 & A3, E2 | E3, R2 | R3 | R> /** * Feeds the error or output services of this layer into the input of either * the specified `failure` or `success` layers, resulting in a new layer with * the inputs of this layer, and the error or outputs of the specified layer. * * @since 2.0.0 * @category folding */ <A, E, R, A2, E2, R2, A3, E3, R3>( self: Layer<A, E, R>, options: { readonly onFailure: (error: E) => Layer<A2, E2, R2> readonly onSuccess: (context: Context.Context<A>) => Layer<A3, E3, R3> } ): Layer<A2 & A3, E2 | E3, R | R2 | R3>} = internal.match
/** * Feeds the error or output services of this layer into the input of either * the specified `failure` or `success` layers, resulting in a new layer with * the inputs of this layer, and the error or outputs of the specified layer. * * @since 2.0.0 * @category folding */export const matchCause: { /** * Feeds the error or output services of this layer into the input of either * the specified `failure` or `success` layers, resulting in a new layer with * the inputs of this layer, and the error or outputs of the specified layer. * * @since 2.0.0 * @category folding */ <E, A2, E2, R2, A, A3, E3, R3>( options: { readonly onFailure: (cause: Cause.Cause<E>) => Layer<A2, E2, R2> readonly onSuccess: (context: Context.Context<A>) => Layer<A3, E3, R3> } ): <R>(self: Layer<A, E, R>) => Layer<A2 & A3, E2 | E3, R2 | R3 | R> /** * Feeds the error or output services of this layer into the input of either * the specified `failure` or `success` layers, resulting in a new layer with * the inputs of this layer, and the error or outputs of the specified layer. * * @since 2.0.0 * @category folding */ <A, E, R, A2, E2, R2, A3, E3, R3>( self: Layer<A, E, R>, options: { readonly onFailure: (cause: Cause.Cause<E>) => Layer<A2, E2, R2> readonly onSuccess: (context: Context.Context<A>) => Layer<A3, E3, R3> } ): Layer<A2 & A3, E2 | E3, R | R2 | R3>} = internal.matchCause
/** * Returns a scoped effect that, if evaluated, will return the lazily computed * result of this layer. * * @since 2.0.0 * @category utils */export const memoize: <RIn, E, ROut>( self: Layer<ROut, E, RIn>) => Effect.Effect<Layer<ROut, E, RIn>, never, Scope.Scope> = internal.memoize
/** * Merges this layer with the specified layer concurrently, producing a new layer with combined input and output types. * * @since 2.0.0 * @category zipping */export const merge: { /** * Merges this layer with the specified layer concurrently, producing a new layer with combined input and output types. * * @since 2.0.0 * @category zipping */ <RIn2, E2, ROut2>(that: Layer<ROut2, E2, RIn2>): <RIn, E1, ROut>(self: Layer<ROut, E1, RIn>) => Layer<ROut2 | ROut, E2 | E1, RIn2 | RIn> /** * Merges this layer with the specified layer concurrently, producing a new layer with combined input and output types. * * @since 2.0.0 * @category zipping */ <RIn, E1, ROut, RIn2, E2, ROut2>(self: Layer<ROut, E1, RIn>, that: Layer<ROut2, E2, RIn2>): Layer<ROut | ROut2, E1 | E2, RIn | RIn2>} = internal.merge
/** * Combines all the provided layers concurrently, creating a new layer with merged input, error, and output types. * * @since 2.0.0 * @category zipping */export const mergeAll: <Layers extends readonly [Layer<never, any, any>, ...Array<Layer<never, any, any>>]>( ...layers: Layers) => Layer< { [k in keyof Layers]: Layer.Success<Layers[k]> }[number], { [k in keyof Layers]: Layer.Error<Layers[k]> }[number], { [k in keyof Layers]: Layer.Context<Layers[k]> }[number]> = internal.mergeAll
/** * Translates effect failure into death of the fiber, making all failures * unchecked and not a part of the type of the layer. * * @since 2.0.0 * @category error handling */export const orDie: <A, E, R>(self: Layer<A, E, R>) => Layer<A, never, R> = internal.orDie
/** * Executes this layer and returns its output, if it succeeds, but otherwise * executes the specified layer. * * @since 2.0.0 * @category error handling */export const orElse: { /** * Executes this layer and returns its output, if it succeeds, but otherwise * executes the specified layer. * * @since 2.0.0 * @category error handling */ <A2, E2, R2>(that: LazyArg<Layer<A2, E2, R2>>): <A, E, R>(self: Layer<A, E, R>) => Layer<A & A2, E2 | E, R2 | R> /** * Executes this layer and returns its output, if it succeeds, but otherwise * executes the specified layer. * * @since 2.0.0 * @category error handling */ <A, E, R, A2, E2, R2>(self: Layer<A, E, R>, that: LazyArg<Layer<A2, E2, R2>>): Layer<A & A2, E | E2, R | R2>} = internal.orElse
/** * Returns a new layer that produces the outputs of this layer but also * passes through the inputs. * * @since 2.0.0 * @category utils */export const passthrough: <RIn, E, ROut>(self: Layer<ROut, E, RIn>) => Layer<RIn | ROut, E, RIn> = internal.passthrough
/** * Projects out part of one of the services output by this layer using the * specified function. * * @since 2.0.0 * @category utils */export const project: { /** * Projects out part of one of the services output by this layer using the * specified function. * * @since 2.0.0 * @category utils */ <I1, S1, I2, S2>( tagA: Context.Tag<I1, S1>, tagB: Context.Tag<I2, S2>, f: (a: Types.NoInfer<S1>) => Types.NoInfer<S2> ): <RIn, E>(self: Layer<I1, E, RIn>) => Layer<I2, E, RIn> /** * Projects out part of one of the services output by this layer using the * specified function. * * @since 2.0.0 * @category utils */ <RIn, E, I1, S1, I2, S2>( self: Layer<I1, E, RIn>, tagA: Context.Tag<I1, S1>, tagB: Context.Tag<I2, S2>, f: (a: Types.NoInfer<S1>) => Types.NoInfer<S2> ): Layer<I2, E, RIn>} = internal.project
/** * @since 2.0.0 * @category utils */export const locallyEffect: { /** * @since 2.0.0 * @category utils */ <RIn, E, ROut, RIn2, E2, ROut2>( f: (_: Effect.Effect<RIn, E, Context.Context<ROut>>) => Effect.Effect<RIn2, E2, Context.Context<ROut2>> ): (self: Layer<ROut, E, RIn>) => Layer<ROut2, E2, RIn2> /** * @since 2.0.0 * @category utils */ <RIn, E, ROut, RIn2, E2, ROut2>( self: Layer<ROut, E, RIn>, f: (_: Effect.Effect<RIn, E, Context.Context<ROut>>) => Effect.Effect<RIn2, E2, Context.Context<ROut2>> ): Layer<ROut2, E2, RIn2>} = internal.locallyEffect
/** * @since 2.0.0 * @category utils */export const locally: { /** * @since 2.0.0 * @category utils */ <X>(ref: FiberRef<X>, value: X): <A, E, R>(self: Layer<A, E, R>) => Layer<A, E, R> /** * @since 2.0.0 * @category utils */ <A, E, R, X>(self: Layer<A, E, R>, ref: FiberRef<X>, value: X): Layer<A, E, R>} = internal.fiberRefLocally
/** * @since 2.0.0 * @category utils */export const locallyWith: { /** * @since 2.0.0 * @category utils */ <X>(ref: FiberRef<X>, value: (_: X) => X): <A, E, R>(self: Layer<A, E, R>) => Layer<A, E, R> /** * @since 2.0.0 * @category utils */ <A, E, R, X>(self: Layer<A, E, R>, ref: FiberRef<X>, value: (_: X) => X): Layer<A, E, R>} = internal.fiberRefLocallyWith
/** * @since 2.0.0 * @category utils */export const locallyScoped: <A>(self: FiberRef<A>, value: A) => Layer<never> = internal.fiberRefLocallyScoped
/** * @since 2.0.0 * @category utils */export const fiberRefLocallyScopedWith: <A>(self: FiberRef<A>, value: (_: A) => A) => Layer<never> = internal.fiberRefLocallyScopedWith
/** * Retries constructing this layer according to the specified schedule. * * @since 2.0.0 * @category retrying */export const retry: { /** * Retries constructing this layer according to the specified schedule. * * @since 2.0.0 * @category retrying */ <X, E, RIn2>(schedule: Schedule.Schedule<X, NoInfer<E>, RIn2>): <ROut, RIn>(self: Layer<ROut, E, RIn>) => Layer<ROut, E, RIn2 | RIn> /** * Retries constructing this layer according to the specified schedule. * * @since 2.0.0 * @category retrying */ <ROut, E, RIn, X, RIn2>(self: Layer<ROut, E, RIn>, schedule: Schedule.Schedule<X, E, RIn2>): Layer<ROut, E, RIn | RIn2>} = internal.retry
/** * A layer that constructs a scope and closes it when the workflow the layer * is provided to completes execution, whether by success, failure, or * interruption. This can be used to close a scope when providing a layer to a * workflow. * * @since 2.0.0 * @category constructors */export const scope: Layer<Scope.Scope> = internal.scope
/** * Constructs a layer from the specified scoped effect. * * @since 2.0.0 * @category constructors */export const scoped: { /** * Constructs a layer from the specified scoped effect. * * @since 2.0.0 * @category constructors */ <I, S>(tag: Context.Tag<I, S>): <E, R>(effect: Effect.Effect<Types.NoInfer<S>, E, R>) => Layer<I, E, Exclude<R, Scope.Scope>> /** * Constructs a layer from the specified scoped effect. * * @since 2.0.0 * @category constructors */ <I, S, E, R>(tag: Context.Tag<I, S>, effect: Effect.Effect<Types.NoInfer<S>, E, R>): Layer<I, E, Exclude<R, Scope.Scope>>} = internal.scoped
/** * Constructs a layer from the specified scoped effect, discarding its output. * * @since 2.0.0 * @category constructors */export const scopedDiscard: <X, E, R>(effect: Effect.Effect<X, E, R>) => Layer<never, E, Exclude<R, Scope.Scope>> = internal.scopedDiscard
/** * Constructs a layer from the specified scoped effect, which must return one * or more services. * * @since 2.0.0 * @category constructors */export const scopedContext: <A, E, R>( effect: Effect.Effect<Context.Context<A>, E, R>) => Layer<A, E, Exclude<R, Scope.Scope>> = internal.scopedContext
/** * Constructs a layer that accesses and returns the specified service from the * context. * * @since 2.0.0 * @category constructors */export const service: <I, S>(tag: Context.Tag<I, S>) => Layer<I, never, I> = internal.service
/** * Constructs a layer from the specified value. * * @since 2.0.0 * @category constructors */export const succeed: { /** * Constructs a layer from the specified value. * * @since 2.0.0 * @category constructors */ <I, S>(tag: Context.Tag<I, S>): (resource: Types.NoInfer<S>) => Layer<I> /** * Constructs a layer from the specified value. * * @since 2.0.0 * @category constructors */ <I, S>(tag: Context.Tag<I, S>, resource: Types.NoInfer<S>): Layer<I>} = internal.succeed
/** * Constructs a layer from the specified value, which must return one or more * services. * * @since 2.0.0 * @category constructors */export const succeedContext: <A>(context: Context.Context<A>) => Layer<A> = internal.succeedContext
/** * Lazily constructs a layer. This is useful to avoid infinite recursion when * creating layers that refer to themselves. * * @since 2.0.0 * @category constructors */export const suspend: <RIn, E, ROut>(evaluate: LazyArg<Layer<ROut, E, RIn>>) => Layer<ROut, E, RIn> = internal.suspend
/** * Lazily constructs a layer from the specified value. * * @since 2.0.0 * @category constructors */export const sync: { /** * Lazily constructs a layer from the specified value. * * @since 2.0.0 * @category constructors */ <I, S>(tag: Context.Tag<I, S>): (evaluate: LazyArg<Types.NoInfer<S>>) => Layer<I> /** * Lazily constructs a layer from the specified value. * * @since 2.0.0 * @category constructors */ <I, S>(tag: Context.Tag<I, S>, evaluate: LazyArg<Types.NoInfer<S>>): Layer<I>} = internal.sync
/** * Lazily constructs a layer from the specified value, which must return one or more * services. * * @since 2.0.0 * @category constructors */export const syncContext: <A>(evaluate: LazyArg<Context.Context<A>>) => Layer<A> = internal.syncContext
/** * Performs the specified effect if this layer succeeds. * * @since 2.0.0 * @category sequencing */export const tap: { /** * Performs the specified effect if this layer succeeds. * * @since 2.0.0 * @category sequencing */ <ROut, XR extends ROut, RIn2, E2, X>(f: (context: Context.Context<XR>) => Effect.Effect<X, E2, RIn2>): <RIn, E>(self: Layer<ROut, E, RIn>) => Layer<ROut, E2 | E, RIn2 | RIn> /** * Performs the specified effect if this layer succeeds. * * @since 2.0.0 * @category sequencing */ <RIn, E, ROut, XR extends ROut, RIn2, E2, X>( self: Layer<ROut, E, RIn>, f: (context: Context.Context<XR>) => Effect.Effect<X, E2, RIn2> ): Layer<ROut, E | E2, RIn | RIn2>} = internal.tap
/** * Performs the specified effect if this layer fails. * * @since 2.0.0 * @category sequencing */export const tapError: { /** * Performs the specified effect if this layer fails. * * @since 2.0.0 * @category sequencing */ <E, XE extends E, RIn2, E2, X>(f: (e: XE) => Effect.Effect<X, E2, RIn2>): <RIn, ROut>(self: Layer<ROut, E, RIn>) => Layer<ROut, E | E2, RIn2 | RIn> /** * Performs the specified effect if this layer fails. * * @since 2.0.0 * @category sequencing */ <RIn, E, XE extends E, ROut, RIn2, E2, X>(self: Layer<ROut, E, RIn>, f: (e: XE) => Effect.Effect<X, E2, RIn2>): Layer<ROut, E | E2, RIn | RIn2>} = internal.tapError
/** * Performs the specified effect if this layer fails. * * @since 2.0.0 * @category sequencing */export const tapErrorCause: { /** * Performs the specified effect if this layer fails. * * @since 2.0.0 * @category sequencing */ <E, XE extends E, RIn2, E2, X>(f: (cause: Cause.Cause<XE>) => Effect.Effect<X, E2, RIn2>): <RIn, ROut>(self: Layer<ROut, E, RIn>) => Layer<ROut, E | E2, RIn2 | RIn> /** * Performs the specified effect if this layer fails. * * @since 2.0.0 * @category sequencing */ <RIn, E, XE extends E, ROut, RIn2, E2, X>( self: Layer<ROut, E, RIn>, f: (cause: Cause.Cause<XE>) => Effect.Effect<X, E2, RIn2> ): Layer<ROut, E | E2, RIn | RIn2>} = internal.tapErrorCause
/** * Converts a layer that requires no services into a scoped runtime, which can * be used to execute effects. * * @since 2.0.0 * @category conversions */export const toRuntime: <RIn, E, ROut>( self: Layer<ROut, E, RIn>) => Effect.Effect<Runtime.Runtime<ROut>, E, Scope.Scope | RIn> = internal.toRuntime
/** * Converts a layer that requires no services into a scoped runtime, which can * be used to execute effects. * * @since 2.0.0 * @category conversions */export const toRuntimeWithMemoMap: { /** * Converts a layer that requires no services into a scoped runtime, which can * be used to execute effects. * * @since 2.0.0 * @category conversions */ (memoMap: MemoMap): <RIn, E, ROut>(self: Layer<ROut, E, RIn>) => Effect.Effect<Runtime.Runtime<ROut>, E, Scope.Scope | RIn> /** * Converts a layer that requires no services into a scoped runtime, which can * be used to execute effects. * * @since 2.0.0 * @category conversions */ <RIn, E, ROut>(self: Layer<ROut, E, RIn>, memoMap: MemoMap): Effect.Effect<Runtime.Runtime<ROut>, E, Scope.Scope | RIn>} = internal.toRuntimeWithMemoMap
/** * Feeds the output services of this builder into the input of the specified * builder, resulting in a new builder with the inputs of this builder as * well as any leftover inputs, and the outputs of the specified builder. * * @since 2.0.0 * @category utils */export const provide: { /** * Feeds the output services of this builder into the input of the specified * builder, resulting in a new builder with the inputs of this builder as * well as any leftover inputs, and the outputs of the specified builder. * * @since 2.0.0 * @category utils */ <RIn, E, ROut>(that: Layer<ROut, E, RIn>): <RIn2, E2, ROut2>(self: Layer<ROut2, E2, RIn2>) => Layer<ROut2, E | E2, RIn | Exclude<RIn2, ROut>> /** * Feeds the output services of this builder into the input of the specified * builder, resulting in a new builder with the inputs of this builder as * well as any leftover inputs, and the outputs of the specified builder. * * @since 2.0.0 * @category utils */ <const Layers extends readonly [Layer.Any, ...Array<Layer.Any>]>(that: Layers): <A, E, R>( self: Layer<A, E, R> ) => Layer< A, E | { [k in keyof Layers]: Layer.Error<Layers[k]> }[number], | { [k in keyof Layers]: Layer.Context<Layers[k]> }[number] | Exclude<R, { [k in keyof Layers]: Layer.Success<Layers[k]> }[number]> > /** * Feeds the output services of this builder into the input of the specified * builder, resulting in a new builder with the inputs of this builder as * well as any leftover inputs, and the outputs of the specified builder. * * @since 2.0.0 * @category utils */ <RIn2, E2, ROut2, RIn, E, ROut>(self: Layer<ROut2, E2, RIn2>, that: Layer<ROut, E, RIn>): Layer<ROut2, E | E2, RIn | Exclude<RIn2, ROut>> /** * Feeds the output services of this builder into the input of the specified * builder, resulting in a new builder with the inputs of this builder as * well as any leftover inputs, and the outputs of the specified builder. * * @since 2.0.0 * @category utils */ <A, E, R, const Layers extends readonly [Layer.Any, ...Array<Layer.Any>]>(self: Layer<A, E, R>, that: Layers): Layer< A, E | { [k in keyof Layers]: Layer.Error<Layers[k]> }[number], | { [k in keyof Layers]: Layer.Context<Layers[k]> }[number] | Exclude<R, { [k in keyof Layers]: Layer.Success<Layers[k]> }[number]> >} = internal.provide
/** * Feeds the output services of this layer into the input of the specified * layer, resulting in a new layer with the inputs of this layer, and the * outputs of both layers. * * @since 2.0.0 * @category utils */export const provideMerge: { /** * Feeds the output services of this layer into the input of the specified * layer, resulting in a new layer with the inputs of this layer, and the * outputs of both layers. * * @since 2.0.0 * @category utils */ <RIn, E, ROut>(self: Layer<ROut, E, RIn>): <RIn2, E2, ROut2>(that: Layer<ROut2, E2, RIn2>) => Layer<ROut | ROut2, E | E2, RIn | Exclude<RIn2, ROut>> /** * Feeds the output services of this layer into the input of the specified * layer, resulting in a new layer with the inputs of this layer, and the * outputs of both layers. * * @since 2.0.0 * @category utils */ <RIn2, E2, ROut2, RIn, E, ROut>(that: Layer<ROut2, E2, RIn2>, self: Layer<ROut, E, RIn>): Layer<ROut2 | ROut, E2 | E, RIn | Exclude<RIn2, ROut>>} = internal.provideMerge
/** * Combines this layer with the specified layer concurrently, creating a new layer with merged input types and * combined output types using the provided function. * * @since 2.0.0 * @category zipping */export const zipWith: { /** * Combines this layer with the specified layer concurrently, creating a new layer with merged input types and * combined output types using the provided function. * * @since 2.0.0 * @category zipping */ <B, E2, R2, A, C>( that: Layer<B, E2, R2>, f: (a: Context.Context<A>, b: Context.Context<B>) => Context.Context<C> ): <E, R>(self: Layer<A, E, R>) => Layer<C, E2 | E, R2 | R> /** * Combines this layer with the specified layer concurrently, creating a new layer with merged input types and * combined output types using the provided function. * * @since 2.0.0 * @category zipping */ <A, E, R, B, E2, R2, C>( self: Layer<A, E, R>, that: Layer<B, E2, R2>, f: (a: Context.Context<A>, b: Context.Context<B>) => Context.Context<C> ): Layer<C, E | E2, R | R2>} = internal.zipWith
/** * @since 2.0.0 * @category utils */export const unwrapEffect: <A, E1, R1, E, R>(self: Effect.Effect<Layer<A, E1, R1>, E, R>) => Layer<A, E | E1, R | R1> = internal.unwrapEffect
/** * @since 2.0.0 * @category utils */export const unwrapScoped: <A, E1, R1, E, R>( self: Effect.Effect<Layer<A, E1, R1>, E, R>) => Layer<A, E | E1, R1 | Exclude<R, Scope.Scope>> = internal.unwrapScoped
/** * @since 2.0.0 * @category clock */export const setClock: <A extends Clock.Clock>(clock: A) => Layer<never> = <A extends Clock.Clock>( clock: A): Layer<never> => scopedDiscard( fiberRuntime.fiberRefLocallyScopedWith(defaultServices.currentServices, Context.add(clockTag, clock)) )
/** * Sets the current `ConfigProvider`. * * @since 2.0.0 * @category config */export const setConfigProvider: (configProvider: ConfigProvider) => Layer<never> = circularLayer.setConfigProvider
/** * Adds the provided span to the span stack. * * @since 2.0.0 * @category tracing */export const parentSpan: (span: Tracer.AnySpan) => Layer<Tracer.ParentSpan> = circularLayer.parentSpan
/** * @since 3.15.0 * @category Random */export const setRandom = <A extends Random.Random>(random: A): Layer<never> => scopedDiscard( fiberRuntime.fiberRefLocallyScopedWith(defaultServices.currentServices, Context.add(randomTag, random)) )
/** * @since 2.0.0 * @category requests & batching */export const setRequestBatching: (requestBatching: boolean) => Layer<never> = ( requestBatching: boolean) => scopedDiscard( fiberRuntime.fiberRefLocallyScoped(core.currentRequestBatching, requestBatching) )
/** * @since 2.0.0 * @category requests & batching */export const setRequestCaching: (requestCaching: boolean) => Layer<never> = ( requestCaching: boolean) => scopedDiscard( fiberRuntime.fiberRefLocallyScoped(query.currentCacheEnabled, requestCaching) )
/** * @since 2.0.0 * @category requests & batching */export const setRequestCache: { /** * @since 2.0.0 * @category requests & batching */ <E, R>(cache: Effect.Effect<Request.Cache, E, R>): Layer<never, E, Exclude<R, Scope.Scope>> /** * @since 2.0.0 * @category requests & batching */ (cache: Request.Cache): Layer<never>} = (<E, R>(cache: Request.Cache | Effect.Effect<Request.Cache, E, R>) => scopedDiscard( core.isEffect(cache) ? core.flatMap(cache, (x) => fiberRuntime.fiberRefLocallyScoped(query.currentCache as any, x)) : fiberRuntime.fiberRefLocallyScoped(query.currentCache as any, cache) )) as any
/** * @since 2.0.0 * @category scheduler */export const setScheduler: (scheduler: Scheduler.Scheduler) => Layer<never> = ( scheduler: Scheduler.Scheduler): Layer<never> => scopedDiscard( fiberRuntime.fiberRefLocallyScoped(Scheduler.currentScheduler, scheduler) )
/** * Create and add a span to the current span stack. * * The span is ended when the Layer is released. * * @since 2.0.0 * @category tracing */export const span: ( name: string, options?: Tracer.SpanOptions & { readonly onEnd?: | ((span: Tracer.Span, exit: Exit.Exit<unknown, unknown>) => Effect.Effect<void>) | undefined }) => Layer<Tracer.ParentSpan> = circularLayer.span
/** * Create a Layer that sets the current Tracer * * @since 2.0.0 * @category tracing */export const setTracer: (tracer: Tracer.Tracer) => Layer<never> = circularLayer.setTracer
/** * @since 2.0.0 * @category tracing */export const setTracerEnabled: (enabled: boolean) => Layer<never> = (enabled: boolean) => scopedDiscard( fiberRuntime.fiberRefLocallyScoped(core.currentTracerEnabled, enabled) )
/** * @since 2.0.0 * @category tracing */export const setTracerTiming: (enabled: boolean) => Layer<never> = (enabled: boolean) => scopedDiscard( fiberRuntime.fiberRefLocallyScoped(core.currentTracerTimingEnabled, enabled) )
/** * @since 2.0.0 * @category logging */export const setUnhandledErrorLogLevel: (level: Option.Option<LogLevel>) => Layer<never> = ( level: Option.Option<LogLevel>): Layer<never> => scopedDiscard( fiberRuntime.fiberRefLocallyScoped(core.currentUnhandledErrorLogLevel, level) )
/** * @since 3.17.0 * @category logging */export const setVersionMismatchErrorLogLevel: (level: Option.Option<LogLevel>) => Layer<never> = ( level: Option.Option<LogLevel>): Layer<never> => scopedDiscard( fiberRuntime.fiberRefLocallyScoped(core.currentVersionMismatchErrorLogLevel, level) )
/** * @since 2.0.0 * @category tracing */export const withSpan: { /** * @since 2.0.0 * @category tracing */ ( name: string, options?: Tracer.SpanOptions & { readonly onEnd?: | ((span: Tracer.Span, exit: Exit.Exit<unknown, unknown>) => Effect.Effect<void>) | undefined } ): <A, E, R>(self: Layer<A, E, R>) => Layer<A, E, Exclude<R, Tracer.ParentSpan>> /** * @since 2.0.0 * @category tracing */ <A, E, R>( self: Layer<A, E, R>, name: string, options?: Tracer.SpanOptions & { readonly onEnd?: | ((span: Tracer.Span, exit: Exit.Exit<unknown, unknown>) => Effect.Effect<void>) | undefined } ): Layer<A, E, Exclude<R, Tracer.ParentSpan>>} = internal.withSpan
/** * @since 2.0.0 * @category tracing */export const withParentSpan: { /** * @since 2.0.0 * @category tracing */ (span: Tracer.AnySpan): <A, E, R>(self: Layer<A, E, R>) => Layer<A, E, Exclude<R, Tracer.ParentSpan>> /** * @since 2.0.0 * @category tracing */ <A, E, R>(self: Layer<A, E, R>, span: Tracer.AnySpan): Layer<A, E, Exclude<R, Tracer.ParentSpan>>} = internal.withParentSpan
// -----------------------------------------------------------------------------// memo map// -----------------------------------------------------------------------------
/** * Constructs a `MemoMap` that can be used to build additional layers. * * @since 2.0.0 * @category memo map */export const makeMemoMap: Effect.Effect<MemoMap> = internal.makeMemoMap
/** * Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize * the layer construction. * * @since 2.0.0 * @category memo map */export const buildWithMemoMap: { /** * Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize * the layer construction. * * @since 2.0.0 * @category memo map */ (memoMap: MemoMap, scope: Scope.Scope): <RIn, E, ROut>(self: Layer<ROut, E, RIn>) => Effect.Effect<Context.Context<ROut>, E, RIn> /** * Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize * the layer construction. * * @since 2.0.0 * @category memo map */ <RIn, E, ROut>(self: Layer<ROut, E, RIn>, memoMap: MemoMap, scope: Scope.Scope): Effect.Effect<Context.Context<ROut>, E, RIn>} = internal.buildWithMemoMap
/** * Updates a service in the context with a new implementation. * * **Details** * * This function modifies the existing implementation of a service in the * context. It retrieves the current service, applies the provided * transformation function `f`, and replaces the old service with the * transformed one. * * **When to Use** * * This is useful for adapting or extending a service's behavior during the * creation of a layer. * * @since 3.13.0 * @category utils */export const updateService = dual< /** * Updates a service in the context with a new implementation. * * **Details** * * This function modifies the existing implementation of a service in the * context. It retrieves the current service, applies the provided * transformation function `f`, and replaces the old service with the * transformed one. * * **When to Use** * * This is useful for adapting or extending a service's behavior during the * creation of a layer. * * @since 3.13.0 * @category utils */ <I, A>(tag: Context.Tag<I, A>, f: (a: A) => A) => <A1, E1, R1>(layer: Layer<A1, E1, R1>) => Layer<A1, E1, I | R1>, /** * Updates a service in the context with a new implementation. * * **Details** * * This function modifies the existing implementation of a service in the * context. It retrieves the current service, applies the provided * transformation function `f`, and replaces the old service with the * transformed one. * * **When to Use** * * This is useful for adapting or extending a service's behavior during the * creation of a layer. * * @since 3.13.0 * @category utils */ <A1, E1, R1, I, A>(layer: Layer<A1, E1, R1>, tag: Context.Tag<I, A>, f: (a: A) => A) => Layer<A1, E1, I | R1>>(3, (layer, tag, f) => provide( layer, map(context(), (c) => Context.add(c, tag, f(Context.unsafeGet(c, tag)))) ))
// -----------------------------------------------------------------------------// Type constraints// -----------------------------------------------------------------------------
/** * A no-op type constraint that enforces the success channel of a Layer conforms to * the specified success type `ROut`. * * @example * import { Layer } from "effect" * * // Ensure that the layer produces the expected services. * const program = Layer.succeed(MyService, new MyServiceImpl()).pipe(Layer.ensureSuccessType<MyService>()) * * @since 3.20.0 * @category Type constraints */export const ensureSuccessType = <ROut>() => <ROut2 extends ROut, E, RIn>(layer: Layer<ROut2, E, RIn>): Layer<ROut2, E, RIn> => layer
/** * A no-op type constraint that enforces the error channel of a Layer conforms to * the specified error type `E`. * * @example * import { Layer } from "effect" * * // Ensure that the layer does not expose any unhandled errors. * const program = Layer.succeed(MyService, new MyServiceImpl()).pipe(Layer.ensureErrorType<never>()) * * @since 3.20.0 * @category Type constraints */export const ensureErrorType = <E>() => <ROut, E2 extends E, RIn>(layer: Layer<ROut, E2, RIn>): Layer<ROut, E2, RIn> => layer
/** * A no-op type constraint that enforces the requirements channel of a Layer conforms to * the specified requirements type `RIn`. * * @example * import { Layer } from "effect" * * // Ensure that the layer does not have any requirements. * const program = Layer.succeed(MyService, new MyServiceImpl()).pipe(Layer.ensureRequirementsType<never>()) * * @since 3.20.0 * @category Type constraints */export const ensureRequirementsType = <RIn>() => <ROut, E, RIn2 extends RIn>(layer: Layer<ROut, E, RIn2>): Layer<ROut, E, RIn2> => layer12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469/** * A data type for immutable linked lists representing ordered collections of elements of type `A`. * * This data type is optimal for last-in-first-out (LIFO), stack-like access patterns. If you need another access pattern, for example, random access or FIFO, consider using a collection more suited to this than `List`. * * **Performance** * * - Time: `List` has `O(1)` prepend and head/tail access. Most other operations are `O(n)` on the number of elements in the list. This includes the index-based lookup of elements, `length`, `append` and `reverse`. * - Space: `List` implements structural sharing of the tail list. This means that many operations are either zero- or constant-memory cost. * * @since 2.0.0 */
/** * This file is ported from * * Scala (https://www.scala-lang.org) * * Copyright EPFL and Lightbend, Inc. * * Licensed under Apache License 2.0 * (http://www.apache.org/licenses/LICENSE-2.0). */import * as Arr from "./Array.js"import * as Chunk from "./Chunk.js"import * as Either from "./Either.js"import * as Equal from "./Equal.js"import * as Equivalence from "./Equivalence.js"import { dual, identity, unsafeCoerce } from "./Function.js"import * as Hash from "./Hash.js"import { format, type Inspectable, NodeInspectSymbol, toJSON } from "./Inspectable.js"import type { nonEmpty, NonEmptyIterable } from "./NonEmptyIterable.js"import * as Option from "./Option.js"import type { Pipeable } from "./Pipeable.js"import { pipeArguments } from "./Pipeable.js"import { hasProperty, type Predicate, type Refinement } from "./Predicate.js"import type { NoInfer } from "./Types.js"
/** * Represents an immutable linked list of elements of type `A`. * * A `List` is optimal for last-in-first-out (LIFO), stack-like access patterns. * If you need another access pattern, for example, random access or FIFO, * consider using a collection more suited for that other than `List`. * * @since 2.0.0 * @category models */export type List<A> = Cons<A> | Nil<A>
/** * @since 2.0.0 * @category symbol */export const TypeId: unique symbol = Symbol.for("effect/List")
/** * @since 2.0.0 * @category symbol */export type TypeId = typeof TypeId
/** * @since 2.0.0 * @category models */export interface Nil<out A> extends Iterable<A>, Equal.Equal, Pipeable, Inspectable { readonly [TypeId]: TypeId readonly _tag: "Nil"}
/** * @since 2.0.0 * @category models */export interface Cons<out A> extends NonEmptyIterable<A>, Equal.Equal, Pipeable, Inspectable { readonly [TypeId]: TypeId readonly _tag: "Cons" readonly head: A readonly tail: List<A>}
/** * Converts the specified `List` to an `Array`. * * @category conversions * @since 2.0.0 */export const toArray = <A>(self: List<A>): Array<A> => Arr.fromIterable(self)
/** * @category equivalence * @since 2.0.0 */export const getEquivalence = <A>(isEquivalent: Equivalence.Equivalence<A>): Equivalence.Equivalence<List<A>> => Equivalence.mapInput(Arr.getEquivalence(isEquivalent), toArray<A>)
const _equivalence = getEquivalence(Equal.equals)
const ConsProto: Omit<Cons<unknown>, "head" | "tail" | typeof nonEmpty> = { [TypeId]: TypeId, _tag: "Cons", toString(this: Cons<unknown>) { return format(this.toJSON()) }, toJSON(this: Cons<unknown>) { return { _id: "List", _tag: "Cons", values: toArray(this).map(toJSON) } }, [NodeInspectSymbol]() { return this.toJSON() }, [Equal.symbol](this: Cons<unknown>, that: unknown): boolean { return isList(that) && this._tag === that._tag && _equivalence(this, that) }, [Hash.symbol](this: Cons<unknown>): number { return Hash.cached(this, Hash.array(toArray(this))) }, [Symbol.iterator](this: Cons<unknown>): Iterator<unknown> { let done = false // eslint-disable-next-line @typescript-eslint/no-this-alias let self: List<unknown> = this return { next() { if (done) { return this.return!() } if (self._tag === "Nil") { done = true return this.return!() } const value: unknown = self.head self = self.tail return { done, value } }, return(value?: unknown) { if (!done) { done = true } return { done: true, value } } } }, pipe() { return pipeArguments(this, arguments) }}
interface MutableCons<A> extends Cons<A> { head: A tail: List<A>}
const makeCons = <A>(head: A, tail: List<A>): MutableCons<A> => { const cons = Object.create(ConsProto) cons.head = head cons.tail = tail return cons}
const NilHash = Hash.string("Nil")const NilProto: Nil<unknown> = { [TypeId]: TypeId, _tag: "Nil", toString() { return format(this.toJSON()) }, toJSON() { return { _id: "List", _tag: "Nil" } }, [NodeInspectSymbol]() { return this.toJSON() }, [Hash.symbol](): number { return NilHash }, [Equal.symbol](that: unknown): boolean { return isList(that) && this._tag === that._tag }, [Symbol.iterator](): Iterator<unknown> { return { next() { return { done: true, value: undefined } } } }, pipe() { return pipeArguments(this, arguments) }} as const
const _Nil = Object.create(NilProto) as Nil<never>
/** * Returns `true` if the specified value is a `List`, `false` otherwise. * * @since 2.0.0 * @category refinements */export const isList: { /** * Returns `true` if the specified value is a `List`, `false` otherwise. * * @since 2.0.0 * @category refinements */ <A>(u: Iterable<A>): u is List<A> /** * Returns `true` if the specified value is a `List`, `false` otherwise. * * @since 2.0.0 * @category refinements */ (u: unknown): u is List<unknown>} = (u: unknown): u is List<unknown> => hasProperty(u, TypeId)
/** * Returns `true` if the specified value is a `List.Nil<A>`, `false` otherwise. * * @since 2.0.0 * @category refinements */export const isNil = <A>(self: List<A>): self is Nil<A> => self._tag === "Nil"
/** * Returns `true` if the specified value is a `List.Cons<A>`, `false` otherwise. * * @since 2.0.0 * @category refinements */export const isCons = <A>(self: List<A>): self is Cons<A> => self._tag === "Cons"
/** * Returns the number of elements contained in the specified `List` * * @since 2.0.0 * @category getters */export const size = <A>(self: List<A>): number => { let these = self let len = 0 while (!isNil(these)) { len += 1 these = these.tail } return len}
/** * Constructs a new empty `List<A>`. * * @since 2.0.0 * @category constructors */export const nil = <A = never>(): List<A> => _Nil
/** * Constructs a new `List.Cons<A>` from the specified `head` and `tail` values. * * @since 2.0.0 * @category constructors */export const cons = <A>(head: A, tail: List<A>): Cons<A> => makeCons(head, tail)
/** * Constructs a new empty `List<A>`. * * Alias of {@link nil}. * * @since 2.0.0 * @category constructors */export const empty = nil
/** * Constructs a new `List<A>` from the specified value. * * @since 2.0.0 * @category constructors */export const of = <A>(value: A): Cons<A> => makeCons(value, _Nil)
/** * Creates a new `List` from an iterable collection of values. * * @since 2.0.0 * @category constructors */export const fromIterable = <A>(prefix: Iterable<A>): List<A> => { const iterator = prefix[Symbol.iterator]() let next: IteratorResult<A> if ((next = iterator.next()) && !next.done) { const result = makeCons(next.value, _Nil) let curr = result while ((next = iterator.next()) && !next.done) { const temp = makeCons(next.value, _Nil) curr.tail = temp curr = temp } return result } else { return _Nil }}
/** * Constructs a new `List<A>` from the specified values. * * @since 2.0.0 * @category constructors */export const make = <Elements extends readonly [any, ...Array<any>]>( ...elements: Elements): Cons<Elements[number]> => fromIterable(elements) as any
/** * Appends the specified element to the end of the `List`, creating a new `Cons`. * * @category concatenating * @since 2.0.0 */export const append: { /** * Appends the specified element to the end of the `List`, creating a new `Cons`. * * @category concatenating * @since 2.0.0 */ <B>(element: B): <A>(self: List<A>) => Cons<A | B> /** * Appends the specified element to the end of the `List`, creating a new `Cons`. * * @category concatenating * @since 2.0.0 */ <A, B>(self: List<A>, element: B): Cons<A | B>} = dual(2, <A, B>(self: List<A>, element: B): Cons<A | B> => appendAll(self, of(element)))
/** * Concatenates two lists, combining their elements. * If either list is non-empty, the result is also a non-empty list. * * @example * ```ts * import * as assert from "node:assert" * import { List } from "effect" * * assert.deepStrictEqual( * List.make(1, 2).pipe(List.appendAll(List.make("a", "b")), List.toArray), * [1, 2, "a", "b"] * ) * ``` * * @category concatenating * @since 2.0.0 */export const appendAll: { /** * Concatenates two lists, combining their elements. * If either list is non-empty, the result is also a non-empty list. * * @example * ```ts * import * as assert from "node:assert" * import { List } from "effect" * * assert.deepStrictEqual( * List.make(1, 2).pipe(List.appendAll(List.make("a", "b")), List.toArray), * [1, 2, "a", "b"] * ) * ``` * * @category concatenating * @since 2.0.0 */ <S extends List<any>, T extends List<any>>(that: T): (self: S) => List.OrNonEmpty<S, T, List.Infer<S> | List.Infer<T>> /** * Concatenates two lists, combining their elements. * If either list is non-empty, the result is also a non-empty list. * * @example * ```ts * import * as assert from "node:assert" * import { List } from "effect" * * assert.deepStrictEqual( * List.make(1, 2).pipe(List.appendAll(List.make("a", "b")), List.toArray), * [1, 2, "a", "b"] * ) * ``` * * @category concatenating * @since 2.0.0 */ <A, B>(self: List<A>, that: Cons<B>): Cons<A | B> /** * Concatenates two lists, combining their elements. * If either list is non-empty, the result is also a non-empty list. * * @example * ```ts * import * as assert from "node:assert" * import { List } from "effect" * * assert.deepStrictEqual( * List.make(1, 2).pipe(List.appendAll(List.make("a", "b")), List.toArray), * [1, 2, "a", "b"] * ) * ``` * * @category concatenating * @since 2.0.0 */ <A, B>(self: Cons<A>, that: List<B>): Cons<A | B> /** * Concatenates two lists, combining their elements. * If either list is non-empty, the result is also a non-empty list. * * @example * ```ts * import * as assert from "node:assert" * import { List } from "effect" * * assert.deepStrictEqual( * List.make(1, 2).pipe(List.appendAll(List.make("a", "b")), List.toArray), * [1, 2, "a", "b"] * ) * ``` * * @category concatenating * @since 2.0.0 */ <A, B>(self: List<A>, that: List<B>): List<A | B>} = dual(2, <A, B>(self: List<A>, that: List<B>): List<A | B> => prependAll(that, self))
/** * Prepends the specified element to the beginning of the list. * * @category concatenating * @since 2.0.0 */export const prepend: { /** * Prepends the specified element to the beginning of the list. * * @category concatenating * @since 2.0.0 */ <B>(element: B): <A>(self: List<A>) => Cons<A | B> /** * Prepends the specified element to the beginning of the list. * * @category concatenating * @since 2.0.0 */ <A, B>(self: List<A>, element: B): Cons<A | B>} = dual(2, <A, B>(self: List<A>, element: B): Cons<A | B> => cons</** * Prepends the specified element to the beginning of the list. * * @category concatenating * @since 2.0.0 */A | B>(element, self))
/** * Prepends the specified prefix list to the beginning of the specified list. * If either list is non-empty, the result is also a non-empty list. * * @example * ```ts * import * as assert from "node:assert" * import { List } from "effect" * * assert.deepStrictEqual( * List.make(1, 2).pipe(List.prependAll(List.make("a", "b")), List.toArray), * ["a", "b", 1, 2] * ) * ``` * * @category concatenating * @since 2.0.0 */export const prependAll: { /** * Prepends the specified prefix list to the beginning of the specified list. * If either list is non-empty, the result is also a non-empty list. * * @example * ```ts * import * as assert from "node:assert" * import { List } from "effect" * * assert.deepStrictEqual( * List.make(1, 2).pipe(List.prependAll(List.make("a", "b")), List.toArray), * ["a", "b", 1, 2] * ) * ``` * * @category concatenating * @since 2.0.0 */ <S extends List<any>, T extends List<any>>(that: T): (self: S) => List.OrNonEmpty<S, T, List.Infer<S> | List.Infer<T>> /** * Prepends the specified prefix list to the beginning of the specified list. * If either list is non-empty, the result is also a non-empty list. * * @example * ```ts * import * as assert from "node:assert" * import { List } from "effect" * * assert.deepStrictEqual( * List.make(1, 2).pipe(List.prependAll(List.make("a", "b")), List.toArray), * ["a", "b", 1, 2] * ) * ``` * * @category concatenating * @since 2.0.0 */ <A, B>(self: List<A>, that: Cons<B>): Cons<A | B> /** * Prepends the specified prefix list to the beginning of the specified list. * If either list is non-empty, the result is also a non-empty list. * * @example * ```ts * import * as assert from "node:assert" * import { List } from "effect" * * assert.deepStrictEqual( * List.make(1, 2).pipe(List.prependAll(List.make("a", "b")), List.toArray), * ["a", "b", 1, 2] * ) * ``` * * @category concatenating * @since 2.0.0 */ <A, B>(self: Cons<A>, that: List<B>): Cons<A | B> /** * Prepends the specified prefix list to the beginning of the specified list. * If either list is non-empty, the result is also a non-empty list. * * @example * ```ts * import * as assert from "node:assert" * import { List } from "effect" * * assert.deepStrictEqual( * List.make(1, 2).pipe(List.prependAll(List.make("a", "b")), List.toArray), * ["a", "b", 1, 2] * ) * ``` * * @category concatenating * @since 2.0.0 */ <A, B>(self: List<A>, that: List<B>): List<A | B>} = dual(2, <A, B>(self: List<A>, prefix: List<B>): List<A | B> => { if (isNil(self)) { return prefix } else if (isNil(prefix)) { return self } else { const result = makeCons</** * Prepends the specified prefix list to the beginning of the specified list. * If either list is non-empty, the result is also a non-empty list. * * @example * ```ts * import * as assert from "node:assert" * import { List } from "effect" * * assert.deepStrictEqual( * List.make(1, 2).pipe(List.prependAll(List.make("a", "b")), List.toArray), * ["a", "b", 1, 2] * ) * ``` * * @category concatenating * @since 2.0.0 */ A | B>(prefix.head, self) let curr = result let that = prefix.tail while (!isNil(that)) { const temp = makeCons</** * Prepends the specified prefix list to the beginning of the specified list. * If either list is non-empty, the result is also a non-empty list. * * @example * ```ts * import * as assert from "node:assert" * import { List } from "effect" * * assert.deepStrictEqual( * List.make(1, 2).pipe(List.prependAll(List.make("a", "b")), List.toArray), * ["a", "b", 1, 2] * ) * ``` * * @category concatenating * @since 2.0.0 */ A | B>(that.head, self) curr.tail = temp curr = temp that = that.tail } return result }})
/** * Prepends the specified prefix list (in reverse order) to the beginning of the * specified list. * * @category concatenating * @since 2.0.0 */export const prependAllReversed: { /** * Prepends the specified prefix list (in reverse order) to the beginning of the * specified list. * * @category concatenating * @since 2.0.0 */ <B>(prefix: List<B>): <A>(self: List<A>) => List<A | B> /** * Prepends the specified prefix list (in reverse order) to the beginning of the * specified list. * * @category concatenating * @since 2.0.0 */ <A, B>(self: List<A>, prefix: List<B>): List<A | B>} = dual(2, <A, B>(self: List<A>, prefix: List<B>): List<A | B> => { let out: List<A | B> = self let pres = prefix while (isCons(pres)) { out = makeCons(pres.head, out) pres = pres.tail } return out})
/** * Drops the first `n` elements from the specified list. * * @since 2.0.0 * @category combinators */export const drop: { /** * Drops the first `n` elements from the specified list. * * @since 2.0.0 * @category combinators */ (n: number): <A>(self: List<A>) => List<A> /** * Drops the first `n` elements from the specified list. * * @since 2.0.0 * @category combinators */ <A>(self: List<A>, n: number): List<A>} = dual(2, <A>(self: List<A>, n: number): List<A> => { if (n <= 0) { return self } if (n >= size(self)) { return _Nil } let these = self let i = 0 while (!isNil(these) && i < n) { these = these.tail i += 1 } return these})
/** * Check if a predicate holds true for every `List` element. * * @since 2.0.0 * @category elements */export const every: { /** * Check if a predicate holds true for every `List` element. * * @since 2.0.0 * @category elements */ <A, B extends A>(refinement: Refinement<NoInfer<A>, B>): (self: List<A>) => self is List<B> /** * Check if a predicate holds true for every `List` element. * * @since 2.0.0 * @category elements */ <A>(predicate: Predicate<A>): (self: List<A>) => boolean /** * Check if a predicate holds true for every `List` element. * * @since 2.0.0 * @category elements */ <A, B extends A>(self: List<A>, refinement: Refinement<A, B>): self is List<B> /** * Check if a predicate holds true for every `List` element. * * @since 2.0.0 * @category elements */ <A>(self: List<A>, predicate: Predicate<A>): boolean} = dual(2, <A, B extends A>(self: List<A>, refinement: Refinement<A, B>): self is List<B> => { for (const a of self) { if (!refinement(a)) { return false } } return true})
/** * Check if a predicate holds true for some `List` element. * * @since 2.0.0 * @category elements */export const some: { /** * Check if a predicate holds true for some `List` element. * * @since 2.0.0 * @category elements */ <A>(predicate: Predicate<NoInfer<A>>): (self: List<A>) => self is Cons<A> /** * Check if a predicate holds true for some `List` element. * * @since 2.0.0 * @category elements */ <A>(self: List<A>, predicate: Predicate<A>): self is Cons<A>} = dual(2, <A>(self: List<A>, predicate: Predicate<A>): self is Cons<A> => { let these = self while (!isNil(these)) { if (predicate(these.head)) { return true } these = these.tail } return false})
/** * Filters a list using the specified predicate. * * @since 2.0.0 * @category combinators */export const filter: { /** * Filters a list using the specified predicate. * * @since 2.0.0 * @category combinators */ <A, B extends A>(refinement: Refinement<NoInfer<A>, B>): (self: List<A>) => List<B> /** * Filters a list using the specified predicate. * * @since 2.0.0 * @category combinators */ <A>(predicate: Predicate<NoInfer<A>>): (self: List<A>) => List<A> /** * Filters a list using the specified predicate. * * @since 2.0.0 * @category combinators */ <A, B extends A>(self: List<A>, refinement: Refinement<A, B>): List<B> /** * Filters a list using the specified predicate. * * @since 2.0.0 * @category combinators */ <A>(self: List<A>, predicate: Predicate<A>): List<A>} = dual(2, <A>(self: List<A>, predicate: Predicate<A>): List<A> => noneIn(self, predicate, false))
// everything seen so far is not includedconst noneIn = <A>( self: List<A>, predicate: Predicate<A>, isFlipped: boolean): List<A> => { while (true) { if (isNil(self)) { return _Nil } else { if (predicate(self.head) !== isFlipped) { return allIn(self, self.tail, predicate, isFlipped) } else { self = self.tail } } }}
// everything from 'start' is included, if everything from this point is in we can return the origin// start otherwise if we discover an element that is out we must create a new partial list.const allIn = <A>( start: List<A>, remaining: List<A>, predicate: Predicate<A>, isFlipped: boolean): List<A> => { while (true) { if (isNil(remaining)) { return start } else { if (predicate(remaining.head) !== isFlipped) { remaining = remaining.tail } else { return partialFill(start, remaining, predicate, isFlipped) } } }}
// we have seen elements that should be included then one that should be excluded, start buildingconst partialFill = <A>( origStart: List<A>, firstMiss: List<A>, predicate: Predicate<A>, isFlipped: boolean): List<A> => { const newHead = makeCons<A>(unsafeHead(origStart)!, _Nil) let toProcess = unsafeTail(origStart)! as Cons<A> let currentLast = newHead
// we know that all elements are :: until at least firstMiss.tail while (!(toProcess === firstMiss)) { const newElem = makeCons(unsafeHead(toProcess)!, _Nil) currentLast.tail = newElem currentLast = unsafeCoerce(newElem) toProcess = unsafeCoerce(toProcess.tail) }
// at this point newHead points to a list which is a duplicate of all the 'in' elements up to the first miss. // currentLast is the last element in that list.
// now we are going to try and share as much of the tail as we can, only moving elements across when we have to. let next = firstMiss.tail let nextToCopy: Cons<A> = unsafeCoerce(next) // the next element we would need to copy to our list if we cant share. while (!isNil(next)) { // generally recommended is next.isNonEmpty but this incurs an extra method call. const head = unsafeHead(next)! if (predicate(head) !== isFlipped) { next = next.tail } else { // its not a match - do we have outstanding elements? while (!(nextToCopy === next)) { const newElem = makeCons(unsafeHead(nextToCopy)!, _Nil) currentLast.tail = newElem currentLast = newElem nextToCopy = unsafeCoerce(nextToCopy.tail) } nextToCopy = unsafeCoerce(next.tail) next = next.tail } }
// we have remaining elements - they are unchanged attach them to the end if (!isNil(nextToCopy)) { currentLast.tail = nextToCopy } return newHead}
/** * Filters and maps a list using the specified partial function. The resulting * list may be smaller than the input list due to the possibility of the partial * function not being defined for some elements. * * @since 2.0.0 * @category combinators */export const filterMap: { /** * Filters and maps a list using the specified partial function. The resulting * list may be smaller than the input list due to the possibility of the partial * function not being defined for some elements. * * @since 2.0.0 * @category combinators */ <A, B>(f: (a: A) => Option.Option<B>): (self: List<A>) => List<B> /** * Filters and maps a list using the specified partial function. The resulting * list may be smaller than the input list due to the possibility of the partial * function not being defined for some elements. * * @since 2.0.0 * @category combinators */ <A, B>(self: List<A>, f: (a: A) => Option.Option<B>): List<B>} = dual(2, <A, B>(self: List<A>, f: (a: A) => Option.Option<B>): List<B> => { const bs: Array<B> = [] for (const a of self) { const oa = f(a) if (Option.isSome(oa)) { bs.push(oa.value) } } return fromIterable(bs)})
/** * Removes all `None` values from the specified list. * * @since 2.0.0 * @category combinators */export const compact = <A>(self: List<Option.Option<A>>): List<A> => filterMap(self, identity)
/** * Returns the first element that satisfies the specified * predicate, or `None` if no such element exists. * * @category elements * @since 2.0.0 */export const findFirst: { /** * Returns the first element that satisfies the specified * predicate, or `None` if no such element exists. * * @category elements * @since 2.0.0 */ <A, B extends A>(refinement: Refinement<NoInfer<A>, B>): (self: List<A>) => Option.Option<B> /** * Returns the first element that satisfies the specified * predicate, or `None` if no such element exists. * * @category elements * @since 2.0.0 */ <A>(predicate: Predicate<NoInfer<A>>): (self: List<A>) => Option.Option<A> /** * Returns the first element that satisfies the specified * predicate, or `None` if no such element exists. * * @category elements * @since 2.0.0 */ <A, B extends A>(self: List<A>, refinement: Refinement<A, B>): Option.Option<B> /** * Returns the first element that satisfies the specified * predicate, or `None` if no such element exists. * * @category elements * @since 2.0.0 */ <A>(self: List<A>, predicate: Predicate<A>): Option.Option<A>} = dual(2, <A>(self: List<A>, predicate: Predicate<A>): Option.Option<A> => { let these = self while (!isNil(these)) { if (predicate(these.head)) { return Option.some(these.head) } these = these.tail } return Option.none()})
/** * Applies a function to each element in a list and returns a new list containing the concatenated mapped elements. * * @since 2.0.0 * @category sequencing */export const flatMap: { /** * Applies a function to each element in a list and returns a new list containing the concatenated mapped elements. * * @since 2.0.0 * @category sequencing */ <S extends List<any>, T extends List<any>>(f: (a: List.Infer<S>, i: number) => T): (self: S) => List.AndNonEmpty<S, T, List.Infer<T>> /** * Applies a function to each element in a list and returns a new list containing the concatenated mapped elements. * * @since 2.0.0 * @category sequencing */ <A, B>(self: Cons<A>, f: (a: A, i: number) => Cons<B>): Cons<B> /** * Applies a function to each element in a list and returns a new list containing the concatenated mapped elements. * * @since 2.0.0 * @category sequencing */ <A, B>(self: List<A>, f: (a: A, i: number) => List<B>): List<B>} = dual(2, <A, B>(self: List<A>, f: (a: A) => List<B>): List<B> => { let rest = self let head: MutableCons<B> | undefined = undefined let tail: MutableCons<B> | undefined = undefined while (!isNil(rest)) { let bs = f(rest.head) while (!isNil(bs)) { const next = makeCons(bs.head, _Nil) if (tail === undefined) { head = next } else { tail.tail = next } tail = next bs = bs.tail } rest = rest.tail } if (head === undefined) { return _Nil } return head})
/** * Applies the specified function to each element of the `List`. * * @since 2.0.0 * @category combinators */export const forEach: { /** * Applies the specified function to each element of the `List`. * * @since 2.0.0 * @category combinators */ <A, B>(f: (a: A) => B): (self: List<A>) => void /** * Applies the specified function to each element of the `List`. * * @since 2.0.0 * @category combinators */ <A, B>(self: List<A>, f: (a: A) => B): void} = dual(2, <A, B>(self: List<A>, f: (a: A) => B): void => { let these = self while (!isNil(these)) { f(these.head) these = these.tail }})
/** * Returns the first element of the specified list, or `None` if the list is * empty. * * @since 2.0.0 * @category getters */export const head = <A>(self: List<A>): Option.Option<A> => isNil(self) ? Option.none() : Option.some(self.head)
/** * Returns the last element of the specified list, or `None` if the list is * empty. * * @since 2.0.0 * @category getters */export const last = <A>(self: List<A>): Option.Option<A> => isNil(self) ? Option.none() : Option.some(unsafeLast(self)!)
/** * @since 2.0.0 */export declare namespace List { /** * @since 2.0.0 */ export type Infer<S extends List<any>> = S extends List<infer A> ? A : never
/** * @since 2.0.0 */ export type With<S extends List<any>, A> = S extends Cons<any> ? Cons<A> : List<A>
/** * @since 2.0.0 */ export type OrNonEmpty<S extends List<any>, T extends List<any>, A> = S extends Cons<any> ? Cons<A> : T extends Cons<any> ? Cons<A> : List<A>
/** * @since 2.0.0 */ export type AndNonEmpty<S extends List<any>, T extends List<any>, A> = S extends Cons<any> ? T extends Cons<any> ? Cons<A> : List<A> : List<A>}
/** * Applies the specified mapping function to each element of the list. * * @since 2.0.0 * @category mapping */export const map: { /** * Applies the specified mapping function to each element of the list. * * @since 2.0.0 * @category mapping */ <S extends List<any>, B>(f: (a: List.Infer<S>, i: number) => B): (self: S) => List.With<S, B> /** * Applies the specified mapping function to each element of the list. * * @since 2.0.0 * @category mapping */ <S extends List<any>, B>(self: S, f: (a: List.Infer<S>, i: number) => B): List.With<S, B>} = dual(2, <A, B>(self: List<A>, f: (a: A, i: number) => B): List<B> => { if (isNil(self)) { return self as unknown as List<B> } else { let i = 0 const head = makeCons(f(self.head, i++), _Nil) let nextHead = head let rest = self.tail while (!isNil(rest)) { const next = makeCons(f(rest.head, i++), _Nil) nextHead.tail = next nextHead = next rest = rest.tail } return head }})
/** * Partition a list into two lists, where the first list contains all elements * that did not satisfy the specified predicate, and the second list contains * all elements that did satisfy the specified predicate. * * @since 2.0.0 * @category combinators */export const partition: { /** * Partition a list into two lists, where the first list contains all elements * that did not satisfy the specified predicate, and the second list contains * all elements that did satisfy the specified predicate. * * @since 2.0.0 * @category combinators */ <A, B extends A>(refinement: Refinement<NoInfer<A>, B>): (self: List<A>) => [excluded: List<Exclude<A, B>>, satisfying: List<B>] /** * Partition a list into two lists, where the first list contains all elements * that did not satisfy the specified predicate, and the second list contains * all elements that did satisfy the specified predicate. * * @since 2.0.0 * @category combinators */ <A>(predicate: Predicate<NoInfer<A>>): (self: List<A>) => [excluded: List<A>, satisfying: List<A>] /** * Partition a list into two lists, where the first list contains all elements * that did not satisfy the specified predicate, and the second list contains * all elements that did satisfy the specified predicate. * * @since 2.0.0 * @category combinators */ <A, B extends A>(self: List<A>, refinement: Refinement<A, B>): [excluded: List<Exclude<A, B>>, satisfying: List<B>] /** * Partition a list into two lists, where the first list contains all elements * that did not satisfy the specified predicate, and the second list contains * all elements that did satisfy the specified predicate. * * @since 2.0.0 * @category combinators */ <A>(self: List<A>, predicate: Predicate<A>): [excluded: List<A>, satisfying: List<A>]} = dual(2, <A>(self: List<A>, predicate: Predicate<A>): [excluded: List<A>, satisfying: List<A>] => { const left: Array<A> = [] const right: Array<A> = [] for (const a of self) { if (predicate(a)) { right.push(a) } else { left.push(a) } } return [fromIterable(left), fromIterable(right)]})
/** * Partition a list into two lists, where the first list contains all elements * for which the specified function returned a `Left`, and the second list * contains all elements for which the specified function returned a `Right`. * * @since 2.0.0 * @category combinators */export const partitionMap: { /** * Partition a list into two lists, where the first list contains all elements * for which the specified function returned a `Left`, and the second list * contains all elements for which the specified function returned a `Right`. * * @since 2.0.0 * @category combinators */ <A, B, C>(f: (a: A) => Either.Either<C, B>): (self: List<A>) => [left: List<B>, right: List<C>] /** * Partition a list into two lists, where the first list contains all elements * for which the specified function returned a `Left`, and the second list * contains all elements for which the specified function returned a `Right`. * * @since 2.0.0 * @category combinators */ <A, B, C>(self: List<A>, f: (a: A) => Either.Either<C, B>): [left: List<B>, right: List<C>]} = dual(2, <A, B, C>(self: List<A>, f: (a: A) => Either.Either<C, B>): [left: List<B>, right: List<C>] => { const left: Array<B> = [] const right: Array<C> = [] for (const a of self) { const e = f(a) if (Either.isLeft(e)) { left.push(e.left) } else { right.push(e.right) } } return [fromIterable(left), fromIterable(right)]})
/** * Folds over the elements of the list using the specified function, using the * specified initial value. * * @since 2.0.0 * @category folding */export const reduce: { /** * Folds over the elements of the list using the specified function, using the * specified initial value. * * @since 2.0.0 * @category folding */ <Z, A>(zero: Z, f: (b: Z, a: A) => Z): (self: List<A>) => Z /** * Folds over the elements of the list using the specified function, using the * specified initial value. * * @since 2.0.0 * @category folding */ <A, Z>(self: List<A>, zero: Z, f: (b: Z, a: A) => Z): Z} = dual(3, <A, Z>(self: List<A>, zero: Z, f: (b: Z, a: A) => Z): Z => { let acc = zero let these = self while (!isNil(these)) { acc = f(acc, these.head) these = these.tail } return acc})
/** * Folds over the elements of the list using the specified function, beginning * with the last element of the list, using the specified initial value. * * @since 2.0.0 * @category folding */export const reduceRight: { /** * Folds over the elements of the list using the specified function, beginning * with the last element of the list, using the specified initial value. * * @since 2.0.0 * @category folding */ <Z, A>(zero: Z, f: (accumulator: Z, value: A) => Z): (self: List<A>) => Z /** * Folds over the elements of the list using the specified function, beginning * with the last element of the list, using the specified initial value. * * @since 2.0.0 * @category folding */ <Z, A>(self: List<A>, zero: Z, f: (accumulator: Z, value: A) => Z): Z} = dual(3, <Z, A>(self: List<A>, zero: Z, f: (accumulator: Z, value: A) => Z): Z => { let acc = zero let these = reverse(self) while (!isNil(these)) { acc = f(acc, these.head) these = these.tail } return acc})
/** * Returns a new list with the elements of the specified list in reverse order. * * @since 2.0.0 * @category elements */export const reverse = <A>(self: List<A>): List<A> => { let result = empty<A>() let these = self while (!isNil(these)) { result = prepend(result, these.head) these = these.tail } return result}
/** * Splits the specified list into two lists at the specified index. * * @since 2.0.0 * @category combinators */export const splitAt: { /** * Splits the specified list into two lists at the specified index. * * @since 2.0.0 * @category combinators */ (n: number): <A>(self: List<A>) => [beforeIndex: List<A>, fromIndex: List<A>] /** * Splits the specified list into two lists at the specified index. * * @since 2.0.0 * @category combinators */ <A>(self: List<A>, n: number): [beforeIndex: List<A>, fromIndex: List<A>]} = dual(2, <A>(self: List<A>, n: number): [List<A>, List<A>] => [take(self, n), drop(self, n)])
/** * Returns the tail of the specified list, or `None` if the list is empty. * * @since 2.0.0 * @category getters */export const tail = <A>(self: List<A>): Option.Option<List<A>> => isNil(self) ? Option.none() : Option.some(self.tail)
/** * Takes the specified number of elements from the beginning of the specified * list. * * @since 2.0.0 * @category combinators */export const take: { /** * Takes the specified number of elements from the beginning of the specified * list. * * @since 2.0.0 * @category combinators */ (n: number): <A>(self: List<A>) => List<A> /** * Takes the specified number of elements from the beginning of the specified * list. * * @since 2.0.0 * @category combinators */ <A>(self: List<A>, n: number): List<A>} = dual(2, <A>(self: List<A>, n: number): List<A> => { if (n <= 0) { return _Nil } if (n >= size(self)) { return self } let these = make(unsafeHead(self)) let current = unsafeTail(self)! for (let i = 1; i < n; i++) { these = makeCons(unsafeHead(current), these) current = unsafeTail(current!) } return reverse(these)})
/** * Converts the specified `List` to a `Chunk`. * * @since 2.0.0 * @category conversions */export const toChunk = <A>(self: List<A>): Chunk.Chunk<A> => Chunk.fromIterable(self)
const getExpectedListToBeNonEmptyErrorMessage = "Expected List to be non-empty"
/** * Unsafely returns the first element of the specified `List`. * * @since 2.0.0 * @category unsafe */export const unsafeHead = <A>(self: List<A>): A => { if (isNil(self)) { throw new Error(getExpectedListToBeNonEmptyErrorMessage) } return self.head}
/** * Unsafely returns the last element of the specified `List`. * * @since 2.0.0 * @category unsafe */export const unsafeLast = <A>(self: List<A>): A => { if (isNil(self)) { throw new Error(getExpectedListToBeNonEmptyErrorMessage) } let these = self let scout = self.tail while (!isNil(scout)) { these = scout scout = scout.tail } return these.head}
/** * Unsafely returns the tail of the specified `List`. * * @since 2.0.0 * @category unsafe */export const unsafeTail = <A>(self: List<A>): List<A> => { if (isNil(self)) { throw new Error(getExpectedListToBeNonEmptyErrorMessage) } return self.tail}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387/** * @since 2.0.0 */import type * as Effect from "./Effect.js"import { dual, pipe } from "./Function.js"import * as core from "./internal/core.js"import * as number from "./Number.js"import * as order from "./Order.js"import type { Pipeable } from "./Pipeable.js"
/** * A `LogLevel` represents the log level associated with an individual logging * operation. Log levels are used both to describe the granularity (or * importance) of individual log statements, as well as to enable tuning * verbosity of log output. * * @since 2.0.0 * @category model * @property ordinal - The priority of the log message. Larger values indicate higher priority. * @property label - A label associated with the log level. * @property syslog -The syslog severity level of the log level. */export type LogLevel = All | Fatal | Error | Warning | Info | Debug | Trace | None
/** * @since 2.0.0 * @category model */export type Literal = LogLevel["_tag"]
/** * @since 2.0.0 * @category model */export interface All extends Pipeable { readonly _tag: "All" readonly label: "ALL" readonly syslog: 0 readonly ordinal: number}
/** * @since 2.0.0 * @category model */export interface Fatal extends Pipeable { readonly _tag: "Fatal" readonly label: "FATAL" readonly syslog: 2 readonly ordinal: number}
/** * @since 2.0.0 * @category model */export interface Error extends Pipeable { readonly _tag: "Error" readonly label: "ERROR" readonly syslog: 3 readonly ordinal: number}
/** * @since 2.0.0 * @category model */export interface Warning extends Pipeable { readonly _tag: "Warning" readonly label: "WARN" readonly syslog: 4 readonly ordinal: number}
/** * @since 2.0.0 * @category model */export interface Info extends Pipeable { readonly _tag: "Info" readonly label: "INFO" readonly syslog: 6 readonly ordinal: number}
/** * @since 2.0.0 * @category model */export interface Debug extends Pipeable { readonly _tag: "Debug" readonly label: "DEBUG" readonly syslog: 7 readonly ordinal: number}
/** * @since 2.0.0 * @category model */export interface Trace extends Pipeable { readonly _tag: "Trace" readonly label: "TRACE" readonly syslog: 7 readonly ordinal: number}
/** * @since 2.0.0 * @category model */export interface None extends Pipeable { readonly _tag: "None" readonly label: "OFF" readonly syslog: 7 readonly ordinal: number}
/** * @since 2.0.0 * @category constructors */export const All: LogLevel = core.logLevelAll
/** * @since 2.0.0 * @category constructors */export const Fatal: LogLevel = core.logLevelFatal
/** * @since 2.0.0 * @category constructors */export const Error: LogLevel = core.logLevelError
/** * @since 2.0.0 * @category constructors */export const Warning: LogLevel = core.logLevelWarning
/** * @since 2.0.0 * @category constructors */export const Info: LogLevel = core.logLevelInfo
/** * @since 2.0.0 * @category constructors */export const Debug: LogLevel = core.logLevelDebug
/** * @since 2.0.0 * @category constructors */export const Trace: LogLevel = core.logLevelTrace
/** * @since 2.0.0 * @category constructors */export const None: LogLevel = core.logLevelNone
/** * @since 2.0.0 * @category constructors */export const allLevels = core.allLogLevels
/** * Temporarily sets a `LogLevel` for an `Effect` workflow. * * **Details** * * This function allows you to apply a specific `LogLevel` locally to an * `Effect` workflow. Once the workflow completes, the `LogLevel` reverts to its * previous state. * * **When to Use** * * This is particularly useful when you want to adjust the verbosity of logging * for specific parts of your program without affecting the global log level. * * @example * ```ts * import { Effect, LogLevel } from "effect" * * const program = Effect.gen(function*() { * yield* Effect.log("message1") * yield* Effect.gen(function*() { * yield* Effect.log("message2") * yield* Effect.log("message3") * }).pipe(LogLevel.locally(LogLevel.Warning)) * }) * * Effect.runFork(program) * // timestamp=... level=INFO fiber=#0 message=message1 * // timestamp=... level=WARN fiber=#0 message=message2 * // timestamp=... level=WARN fiber=#0 message=message3 * ``` * * @since 2.0.0 * @category utils */export const locally: { /** * Temporarily sets a `LogLevel` for an `Effect` workflow. * * **Details** * * This function allows you to apply a specific `LogLevel` locally to an * `Effect` workflow. Once the workflow completes, the `LogLevel` reverts to its * previous state. * * **When to Use** * * This is particularly useful when you want to adjust the verbosity of logging * for specific parts of your program without affecting the global log level. * * @example * ```ts * import { Effect, LogLevel } from "effect" * * const program = Effect.gen(function*() { * yield* Effect.log("message1") * yield* Effect.gen(function*() { * yield* Effect.log("message2") * yield* Effect.log("message3") * }).pipe(LogLevel.locally(LogLevel.Warning)) * }) * * Effect.runFork(program) * // timestamp=... level=INFO fiber=#0 message=message1 * // timestamp=... level=WARN fiber=#0 message=message2 * // timestamp=... level=WARN fiber=#0 message=message3 * ``` * * @since 2.0.0 * @category utils */ (self: LogLevel): <A, E, R>(use: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R> /** * Temporarily sets a `LogLevel` for an `Effect` workflow. * * **Details** * * This function allows you to apply a specific `LogLevel` locally to an * `Effect` workflow. Once the workflow completes, the `LogLevel` reverts to its * previous state. * * **When to Use** * * This is particularly useful when you want to adjust the verbosity of logging * for specific parts of your program without affecting the global log level. * * @example * ```ts * import { Effect, LogLevel } from "effect" * * const program = Effect.gen(function*() { * yield* Effect.log("message1") * yield* Effect.gen(function*() { * yield* Effect.log("message2") * yield* Effect.log("message3") * }).pipe(LogLevel.locally(LogLevel.Warning)) * }) * * Effect.runFork(program) * // timestamp=... level=INFO fiber=#0 message=message1 * // timestamp=... level=WARN fiber=#0 message=message2 * // timestamp=... level=WARN fiber=#0 message=message3 * ``` * * @since 2.0.0 * @category utils */ <A, E, R>(use: Effect.Effect<A, E, R>, self: LogLevel): Effect.Effect<A, E, R>} = dual( 2, <A, E, R>(use: Effect.Effect<A, E, R>, self: LogLevel): Effect.Effect<A, E, R> => core.fiberRefLocally(use, core.currentLogLevel, self))
/** * @since 2.0.0 * @category instances */export const Order: order.Order<LogLevel> = pipe( number.Order, order.mapInput((level: LogLevel) => level.ordinal))
/** * @since 2.0.0 * @category ordering */export const lessThan: { /** * @since 2.0.0 * @category ordering */ (that: LogLevel): (self: LogLevel) => boolean /** * @since 2.0.0 * @category ordering */ (self: LogLevel, that: LogLevel): boolean} = order.lessThan(Order)
/** * @since 2.0.0 * @category ordering */export const lessThanEqual: { /** * @since 2.0.0 * @category ordering */ (that: LogLevel): (self: LogLevel) => boolean /** * @since 2.0.0 * @category ordering */ (self: LogLevel, that: LogLevel): boolean} = order.lessThanOrEqualTo(Order)
/** * @since 2.0.0 * @category ordering */export const greaterThan: { /** * @since 2.0.0 * @category ordering */ (that: LogLevel): (self: LogLevel) => boolean /** * @since 2.0.0 * @category ordering */ (self: LogLevel, that: LogLevel): boolean} = order.greaterThan(Order)
/** * @since 2.0.0 * @category ordering */export const greaterThanEqual: { /** * @since 2.0.0 * @category ordering */ (that: LogLevel): (self: LogLevel) => boolean /** * @since 2.0.0 * @category ordering */ (self: LogLevel, that: LogLevel): boolean} = order.greaterThanOrEqualTo(Order)
/** * @since 2.0.0 * @category conversions */export const fromLiteral = (literal: Literal): LogLevel => { switch (literal) { case "All": return All case "Debug": return Debug case "Error": return Error case "Fatal": return Fatal case "Info": return Info case "Trace": return Trace case "None": return None case "Warning": return Warning }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863/** * @since 2.0.0 */import type * as Cause from "./Cause.js"import type { DurationInput } from "./Duration.js"import type { Effect } from "./Effect.js"import type * as FiberId from "./FiberId.js"import type * as FiberRefs from "./FiberRefs.js"import type { LazyArg } from "./Function.js"import type * as HashMap from "./HashMap.js"import * as fiberRuntime from "./internal/fiberRuntime.js"import * as circular from "./internal/layer/circular.js"import * as internalCircular from "./internal/logger-circular.js"import * as internal from "./internal/logger.js"import type * as Layer from "./Layer.js"import type * as List from "./List.js"import type * as LogLevel from "./LogLevel.js"import type * as LogSpan from "./LogSpan.js"import type * as Option from "./Option.js"import type { Pipeable } from "./Pipeable.js"import type { Scope } from "./Scope.js"import type * as Types from "./Types.js"
/** * @since 2.0.0 * @category symbols */export const LoggerTypeId: unique symbol = internal.LoggerTypeId
/** * @since 2.0.0 * @category symbols */export type LoggerTypeId = typeof LoggerTypeId
/** * @since 2.0.0 * @category models */export interface Logger<in Message, out Output> extends Logger.Variance<Message, Output>, Pipeable { log(options: Logger.Options<Message>): Output}
/** * @since 2.0.0 */export declare namespace Logger { /** * @since 2.0.0 * @category models */ export interface Variance<in Message, out Output> { readonly [LoggerTypeId]: { readonly _Message: Types.Contravariant<Message> readonly _Output: Types.Covariant<Output> } }
/** * @since 2.0.0 * @category models */ export interface Options<out Message> { readonly fiberId: FiberId.FiberId readonly logLevel: LogLevel.LogLevel readonly message: Message readonly cause: Cause.Cause<unknown> readonly context: FiberRefs.FiberRefs readonly spans: List.List<LogSpan.LogSpan> readonly annotations: HashMap.HashMap<string, unknown> readonly date: Date }}
/** * Creates a custom logger that formats log messages according to the provided * function. * * @example * ```ts * import { Effect, Logger, LogLevel } from "effect" * * const logger = Logger.make(({ logLevel, message }) => { * globalThis.console.log(`[${logLevel.label}] ${message}`) * }) * * const task1 = Effect.logDebug("task1 done") * const task2 = Effect.logDebug("task2 done") * * const program = Effect.gen(function*() { * yield* Effect.log("start") * yield* task1 * yield* task2 * yield* Effect.log("done") * }).pipe( * Logger.withMinimumLogLevel(LogLevel.Debug), * Effect.provide(Logger.replace(Logger.defaultLogger, logger)) * ) * * Effect.runFork(program) * // [INFO] start * // [DEBUG] task1 done * // [DEBUG] task2 done * // [INFO] done * ``` * * @category constructors * @since 2.0.0 */export const make: <Message, Output>(log: (options: Logger.Options<Message>) => Output) => Logger<Message, Output> = internal.makeLogger
/** * @since 2.0.0 * @category context */export const add: <B>(logger: Logger<unknown, B>) => Layer.Layer<never> = circular.addLogger
/** * @since 2.0.0 * @category context */export const addEffect: <A, E, R>(effect: Effect<Logger<unknown, A>, E, R>) => Layer.Layer<never, E, R> = circular.addLoggerEffect
/** * @since 2.0.0 * @category context */export const addScoped: <A, E, R>( effect: Effect<Logger<unknown, A>, E, R>) => Layer.Layer<never, E, Exclude<R, Scope>> = circular.addLoggerScoped
/** * @since 2.0.0 * @category mapping */export const mapInput: { /** * @since 2.0.0 * @category mapping */ <Message, Message2>(f: (message: Message2) => Message): <Output>(self: Logger<Message, Output>) => Logger<Message2, Output> /** * @since 2.0.0 * @category mapping */ <Output, Message, Message2>(self: Logger<Message, Output>, f: (message: Message2) => Message): Logger<Message2, Output>} = internal.mapInput
/** * @since 2.0.0 * @category mapping */export const mapInputOptions: { /** * @since 2.0.0 * @category mapping */ <Message, Message2>(f: (options: Logger.Options<Message2>) => Logger.Options<Message>): <Output>(self: Logger<Message, Output>) => Logger<Message2, Output> /** * @since 2.0.0 * @category mapping */ <Output, Message, Message2>( self: Logger<Message, Output>, f: (options: Logger.Options<Message2>) => Logger.Options<Message> ): Logger<Message2, Output>} = internal.mapInputOptions
/** * Returns a version of this logger that only logs messages when the log level * satisfies the specified predicate. * * @since 2.0.0 * @category filtering */export const filterLogLevel: { /** * Returns a version of this logger that only logs messages when the log level * satisfies the specified predicate. * * @since 2.0.0 * @category filtering */ (f: (logLevel: LogLevel.LogLevel) => boolean): <Message, Output>(self: Logger<Message, Output>) => Logger<Message, Option.Option<Output>> /** * Returns a version of this logger that only logs messages when the log level * satisfies the specified predicate. * * @since 2.0.0 * @category filtering */ <Message, Output>(self: Logger<Message, Output>, f: (logLevel: LogLevel.LogLevel) => boolean): Logger<Message, Option.Option<Output>>} = internal.filterLogLevel
/** * @since 2.0.0 * @category mapping */export const map: { /** * @since 2.0.0 * @category mapping */ <Output, Output2>(f: (output: Output) => Output2): <Message>(self: Logger<Message, Output>) => Logger<Message, Output2> /** * @since 2.0.0 * @category mapping */ <Message, Output, Output2>(self: Logger<Message, Output>, f: (output: Output) => Output2): Logger<Message, Output2>} = internal.map
/** * Creates a batched logger that groups log messages together and processes them * in intervals. * * @example * ```ts * import { Console, Effect, Logger } from "effect" * * const LoggerLive = Logger.replaceScoped( * Logger.defaultLogger, * Logger.logfmtLogger.pipe( * Logger.batched("500 millis", (messages) => Console.log("BATCH", `[\n${messages.join("\n")}\n]`)) * ) * ) * * const program = Effect.gen(function*() { * yield* Effect.log("one") * yield* Effect.log("two") * yield* Effect.log("three") * }).pipe(Effect.provide(LoggerLive)) * * Effect.runFork(program) * // BATCH [ * // timestamp=... level=INFO fiber=#0 message=one * // timestamp=... level=INFO fiber=#0 message=two * // timestamp=... level=INFO fiber=#0 message=three * // ] * ``` * * @since 2.0.0 * @category mapping */export const batched: { /** * Creates a batched logger that groups log messages together and processes them * in intervals. * * @example * ```ts * import { Console, Effect, Logger } from "effect" * * const LoggerLive = Logger.replaceScoped( * Logger.defaultLogger, * Logger.logfmtLogger.pipe( * Logger.batched("500 millis", (messages) => Console.log("BATCH", `[\n${messages.join("\n")}\n]`)) * ) * ) * * const program = Effect.gen(function*() { * yield* Effect.log("one") * yield* Effect.log("two") * yield* Effect.log("three") * }).pipe(Effect.provide(LoggerLive)) * * Effect.runFork(program) * // BATCH [ * // timestamp=... level=INFO fiber=#0 message=one * // timestamp=... level=INFO fiber=#0 message=two * // timestamp=... level=INFO fiber=#0 message=three * // ] * ``` * * @since 2.0.0 * @category mapping */ <Output, R>( window: DurationInput, f: (messages: Array<Types.NoInfer<Output>>) => Effect<void, never, R> ): <Message>(self: Logger<Message, Output>) => Effect<Logger<Message, void>, never, R | Scope> /** * Creates a batched logger that groups log messages together and processes them * in intervals. * * @example * ```ts * import { Console, Effect, Logger } from "effect" * * const LoggerLive = Logger.replaceScoped( * Logger.defaultLogger, * Logger.logfmtLogger.pipe( * Logger.batched("500 millis", (messages) => Console.log("BATCH", `[\n${messages.join("\n")}\n]`)) * ) * ) * * const program = Effect.gen(function*() { * yield* Effect.log("one") * yield* Effect.log("two") * yield* Effect.log("three") * }).pipe(Effect.provide(LoggerLive)) * * Effect.runFork(program) * // BATCH [ * // timestamp=... level=INFO fiber=#0 message=one * // timestamp=... level=INFO fiber=#0 message=two * // timestamp=... level=INFO fiber=#0 message=three * // ] * ``` * * @since 2.0.0 * @category mapping */ <Message, Output, R>( self: Logger<Message, Output>, window: DurationInput, f: (messages: Array<Types.NoInfer<Output>>) => Effect<void, never, R> ): Effect<Logger<Message, void>, never, Scope | R>} = fiberRuntime.batchedLogger
/** * @since 2.0.0 * @category console */export const withConsoleLog: <M, O>(self: Logger<M, O>) => Logger<M, void> = fiberRuntime.loggerWithConsoleLog
/** * Takes a `Logger<M, O>` and returns a logger that calls the respective `Console` method * based on the log level. * * @example * ```ts * import { Logger, Effect } from "effect" * * const loggerLayer = Logger.replace( * Logger.defaultLogger, * Logger.withLeveledConsole(Logger.stringLogger), * ) * * Effect.gen(function* () { * yield* Effect.logError("an error") * yield* Effect.logInfo("an info") * }).pipe(Effect.provide(loggerLayer)) * ``` * * @since 3.8.0 * @category console */export const withLeveledConsole: <M, O>(self: Logger<M, O>) => Logger<M, void> = fiberRuntime.loggerWithLeveledLog
/** * @since 2.0.0 * @category console */export const withConsoleError: <M, O>(self: Logger<M, O>) => Logger<M, void> = fiberRuntime.loggerWithConsoleError
/** * A logger that does nothing in response to logging events. * * @since 2.0.0 * @category constructors */export const none: Logger<unknown, void> = internal.none
/** * @since 2.0.0 * @category context */export const remove: <A>(logger: Logger<unknown, A>) => Layer.Layer<never> = circular.removeLogger
/** * @since 2.0.0 * @category context */export const replace: { /** * @since 2.0.0 * @category context */ <B>(that: Logger<unknown, B>): <A>(self: Logger<unknown, A>) => Layer.Layer<never> /** * @since 2.0.0 * @category context */ <A, B>(self: Logger<unknown, A>, that: Logger<unknown, B>): Layer.Layer<never>} = circular.replaceLogger
/** * @since 2.0.0 * @category context */export const replaceEffect: { /** * @since 2.0.0 * @category context */ <B, E, R>(that: Effect<Logger<unknown, B>, E, R>): <A>(self: Logger<unknown, A>) => Layer.Layer<never, E, R> /** * @since 2.0.0 * @category context */ <A, B, E, R>(self: Logger<unknown, A>, that: Effect<Logger<unknown, B>, E, R>): Layer.Layer<never, E, R>} = circular.replaceLoggerEffect
/** * @since 2.0.0 * @category context */export const replaceScoped: { /** * @since 2.0.0 * @category context */ <B, E, R>(that: Effect<Logger<unknown, B>, E, R>): <A>(self: Logger<unknown, A>) => Layer.Layer<never, E, Exclude<R, Scope>> /** * @since 2.0.0 * @category context */ <A, B, E, R>(self: Logger<unknown, A>, that: Effect<Logger<unknown, B>, E, R>): Layer.Layer<never, E, Exclude<R, Scope>>} = circular.replaceLoggerScoped
/** * @since 2.0.0 * @category constructors */export const simple: <A, B>(log: (a: A) => B) => Logger<A, B> = internal.simple
/** * @since 2.0.0 * @category constructors */export const succeed: <A>(value: A) => Logger<unknown, A> = internal.succeed
/** * @since 2.0.0 * @category constructors */export const sync: <A>(evaluate: LazyArg<A>) => Logger<unknown, A> = internal.sync
/** * @since 2.0.0 * @category constructors */export const test: { /** * @since 2.0.0 * @category constructors */ <Message>(input: Message): <Output>(self: Logger<Message, Output>) => Output /** * @since 2.0.0 * @category constructors */ <Message, Output>(self: Logger<Message, Output>, input: Message): Output} = internalCircular.test
/** * Sets the minimum log level for subsequent logging operations, allowing * control over which log messages are displayed based on their severity. * * @example * ```ts * import { Effect, Logger, LogLevel } from "effect" * * const program = Effect.logDebug("message1").pipe(Logger.withMinimumLogLevel(LogLevel.Debug)) * * Effect.runFork(program) * // timestamp=... level=DEBUG fiber=#0 message=message1 * ``` * * @since 2.0.0 * @category context */export const withMinimumLogLevel: { /** * Sets the minimum log level for subsequent logging operations, allowing * control over which log messages are displayed based on their severity. * * @example * ```ts * import { Effect, Logger, LogLevel } from "effect" * * const program = Effect.logDebug("message1").pipe(Logger.withMinimumLogLevel(LogLevel.Debug)) * * Effect.runFork(program) * // timestamp=... level=DEBUG fiber=#0 message=message1 * ``` * * @since 2.0.0 * @category context */ (level: LogLevel.LogLevel): <A, E, R>(self: Effect<A, E, R>) => Effect<A, E, R> /** * Sets the minimum log level for subsequent logging operations, allowing * control over which log messages are displayed based on their severity. * * @example * ```ts * import { Effect, Logger, LogLevel } from "effect" * * const program = Effect.logDebug("message1").pipe(Logger.withMinimumLogLevel(LogLevel.Debug)) * * Effect.runFork(program) * // timestamp=... level=DEBUG fiber=#0 message=message1 * ``` * * @since 2.0.0 * @category context */ <A, E, R>(self: Effect<A, E, R>, level: LogLevel.LogLevel): Effect<A, E, R>} = circular.withMinimumLogLevel
/** * @since 2.0.0 * @category tracing */export const withSpanAnnotations: <Message, Output>(self: Logger<Message, Output>) => Logger<Message, Output> = fiberRuntime.loggerWithSpanAnnotations
/** * Combines this logger with the specified logger to produce a new logger that * logs to both this logger and that logger. * * @since 2.0.0 * @category zipping */export const zip: { /** * Combines this logger with the specified logger to produce a new logger that * logs to both this logger and that logger. * * @since 2.0.0 * @category zipping */ <Message2, Output2>(that: Logger<Message2, Output2>): <Message, Output>(self: Logger<Message, Output>) => Logger<Message & Message2, [Output, Output2]> /** * Combines this logger with the specified logger to produce a new logger that * logs to both this logger and that logger. * * @since 2.0.0 * @category zipping */ <Message, Output, Message2, Output2>(self: Logger<Message, Output>, that: Logger<Message2, Output2>): Logger<Message & Message2, [Output, Output2]>} = internal.zip
/** * @since 2.0.0 * @category zipping */export const zipLeft: { /** * @since 2.0.0 * @category zipping */ <Message2, Output2>(that: Logger<Message2, Output2>): <Message, Output>(self: Logger<Message, Output>) => Logger<Message & Message2, Output> /** * @since 2.0.0 * @category zipping */ <Message, Output, Message2, Output2>(self: Logger<Message, Output>, that: Logger<Message2, Output2>): Logger<Message & Message2, Output>} = internal.zipLeft
/** * @since 2.0.0 * @category zipping */export const zipRight: { /** * @since 2.0.0 * @category zipping */ <Message2, Output2>(that: Logger<Message2, Output2>): <Message, Output>(self: Logger<Message, Output>) => Logger<Message & Message2, Output2> /** * @since 2.0.0 * @category zipping */ <Message, Output, Message2, Output2>(self: Logger<Message, Output>, that: Logger<Message2, Output2>): Logger<Message & Message2, Output2>} = internal.zipRight
/** * @since 2.0.0 * @category constructors */export const defaultLogger: Logger<unknown, void> = fiberRuntime.defaultLogger
/** * The `jsonLogger` logger formats log entries as JSON objects, making them easy to * integrate with logging systems that consume JSON data. * * @example * ```ts * import { Effect, Logger } from "effect" * * const program = Effect.log("message1", "message2").pipe( * Effect.annotateLogs({ key1: "value1", key2: "value2" }), * Effect.withLogSpan("myspan") * ) * * Effect.runFork(program.pipe(Effect.provide(Logger.json))) * // {"message":["message1","message2"],"logLevel":"INFO","timestamp":"...","annotations":{"key2":"value2","key1":"value1"},"spans":{"myspan":0},"fiberId":"#0"} * ``` * * @since 2.0.0 * @category constructors */export const jsonLogger: Logger<unknown, string> = internal.jsonLogger
/** * This logger outputs logs in a human-readable format that is easy to read * during development or in a production console. * * @example * ```ts * import { Effect, Logger } from "effect" * * const program = Effect.log("message1", "message2").pipe( * Effect.annotateLogs({ key1: "value1", key2: "value2" }), * Effect.withLogSpan("myspan") * ) * * Effect.runFork(program.pipe(Effect.provide(Logger.logFmt))) * // timestamp=... level=INFO fiber=#0 message=message1 message=message2 myspan=0ms key2=value2 key1=value1 * ``` * * @since 2.0.0 * @category constructors */export const logfmtLogger: Logger<unknown, string> = internal.logfmtLogger
/** * @since 2.0.0 * @category constructors */export const stringLogger: Logger<unknown, string> = internal.stringLogger
/** * The pretty logger utilizes the capabilities of the console API to generate * visually engaging and color-enhanced log outputs. This feature is * particularly useful for improving the readability of log messages during * development and debugging processes. * * @example * ```ts * import { Effect, Logger } from "effect" * * const program = Effect.log("message1", "message2").pipe( * Effect.annotateLogs({ key1: "value1", key2: "value2" }), * Effect.withLogSpan("myspan") * ) * * Effect.runFork(program.pipe(Effect.provide(Logger.pretty))) * // green --v v-- bold and cyan * // [07:51:54.434] INFO (#0) myspan=1ms: message1 * // message2 * // v-- bold * // key2: value2 * // key1: value1 * ``` * * @since 3.5.0 * @category constructors */export const prettyLogger: ( options?: { readonly colors?: "auto" | boolean | undefined readonly stderr?: boolean | undefined readonly formatDate?: ((date: Date) => string) | undefined readonly mode?: "browser" | "tty" | "auto" | undefined }) => Logger<unknown, void> = internal.prettyLogger
/** * A default version of the pretty logger. * * @since 3.8.0 * @category constructors */export const prettyLoggerDefault: Logger<unknown, void> = internal.prettyLoggerDefault
/** * The structured logger provides detailed log outputs, structured in a way that * retains comprehensive traceability of the events, suitable for deeper * analysis and troubleshooting. * * @example * ```ts * import { Effect, Logger } from "effect" * * const program = Effect.log("message1", "message2").pipe( * Effect.annotateLogs({ key1: "value1", key2: "value2" }), * Effect.withLogSpan("myspan") * ) * * Effect.runFork(program.pipe(Effect.provide(Logger.structured))) * // { * // message: [ 'message1', 'message2' ], * // logLevel: 'INFO', * // timestamp: '2024-07-09T14:05:41.623Z', * // cause: undefined, * // annotations: { key2: 'value2', key1: 'value1' }, * // spans: { myspan: 0 }, * // fiberId: '#0' * // } * ``` * * @since 2.0.0 * @category constructors */export const structuredLogger: Logger< unknown, { readonly logLevel: string readonly fiberId: string readonly timestamp: string readonly message: unknown readonly cause: string | undefined readonly annotations: Record<string, unknown> readonly spans: Record<string, number> }> = internal.structuredLogger
/** * @since 2.0.0 * @category constructors */export const tracerLogger: Logger<unknown, void> = fiberRuntime.tracerLogger
/** * The `json` logger formats log entries as JSON objects, making them easy to * integrate with logging systems that consume JSON data. * * @example * ```ts * import { Effect, Logger } from "effect" * * const program = Effect.log("message1", "message2").pipe( * Effect.annotateLogs({ key1: "value1", key2: "value2" }), * Effect.withLogSpan("myspan") * ) * * Effect.runFork(program.pipe(Effect.provide(Logger.json))) * // {"message":["message1","message2"],"logLevel":"INFO","timestamp":"...","annotations":{"key2":"value2","key1":"value1"},"spans":{"myspan":0},"fiberId":"#0"} * ``` * * @since 2.0.0 * @category constructors */export const json: Layer.Layer<never> = replace(fiberRuntime.defaultLogger, fiberRuntime.jsonLogger)
/** * This logger outputs logs in a human-readable format that is easy to read * during development or in a production console. * * @example * ```ts * import { Effect, Logger } from "effect" * * const program = Effect.log("message1", "message2").pipe( * Effect.annotateLogs({ key1: "value1", key2: "value2" }), * Effect.withLogSpan("myspan") * ) * * Effect.runFork(program.pipe(Effect.provide(Logger.logFmt))) * // timestamp=... level=INFO fiber=#0 message=message1 message=message2 myspan=0ms key2=value2 key1=value1 * ``` * * @since 2.0.0 * @category constructors */export const logFmt: Layer.Layer<never> = replace(fiberRuntime.defaultLogger, fiberRuntime.logFmtLogger)
/** * The pretty logger utilizes the capabilities of the console API to generate * visually engaging and color-enhanced log outputs. This feature is * particularly useful for improving the readability of log messages during * development and debugging processes. * * @example * ```ts * import { Effect, Logger } from "effect" * * const program = Effect.log("message1", "message2").pipe( * Effect.annotateLogs({ key1: "value1", key2: "value2" }), * Effect.withLogSpan("myspan") * ) * * Effect.runFork(program.pipe(Effect.provide(Logger.pretty))) * // green --v v-- bold and cyan * // [07:51:54.434] INFO (#0) myspan=1ms: message1 * // message2 * // v-- bold * // key2: value2 * // key1: value1 * ``` * * @since 3.5.0 * @category constructors */export const pretty: Layer.Layer<never> = replace(fiberRuntime.defaultLogger, fiberRuntime.prettyLogger)
/** * The structured logger provides detailed log outputs, structured in a way that * retains comprehensive traceability of the events, suitable for deeper * analysis and troubleshooting. * * @example * ```ts * import { Effect, Logger } from "effect" * * const program = Effect.log("message1", "message2").pipe( * Effect.annotateLogs({ key1: "value1", key2: "value2" }), * Effect.withLogSpan("myspan") * ) * * Effect.runFork(program.pipe(Effect.provide(Logger.structured))) * // { * // message: [ 'message1', 'message2' ], * // logLevel: 'INFO', * // timestamp: '2024-07-09T14:05:41.623Z', * // cause: undefined, * // annotations: { key2: 'value2', key1: 'value1' }, * // spans: { myspan: 0 }, * // fiberId: '#0' * // } * ``` * * @since 2.0.0 * @category constructors */export const structured: Layer.Layer<never> = replace(fiberRuntime.defaultLogger, fiberRuntime.structuredLogger)
/** * Sets the minimum log level for logging operations, allowing control over * which log messages are displayed based on their severity. * * @example * ```ts * import { Effect, Logger, LogLevel } from "effect" * * const program = Effect.gen(function*() { * yield* Effect.log("Executing task...") * yield* Effect.sleep("100 millis") * console.log("task done") * }) * * // Logging disabled using a layer * Effect.runFork(program.pipe(Effect.provide(Logger.minimumLogLevel(LogLevel.None)))) * // task done * ``` * * @since 2.0.0 * @category context */export const minimumLogLevel: (level: LogLevel.LogLevel) => Layer.Layer<never> = circular.minimumLogLevel
/** * Returns `true` if the specified value is a `Logger`, otherwise returns `false`. * * @since 1.0.0 * @category guards */export const isLogger: (u: unknown) => u is Logger<unknown, unknown> = internal.isLogger123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298/** * @since 3.8.0 * @experimental */import type { Cause, NoSuchElementException } from "./Cause.js"import type { Channel } from "./Channel.js"import type { Chunk } from "./Chunk.js"import type { Effect } from "./Effect.js"import type { Exit } from "./Exit.js"import type { Inspectable } from "./Inspectable.js"import * as internal from "./internal/mailbox.js"import type { Option } from "./Option.js"import { hasProperty } from "./Predicate.js"import type { Scope } from "./Scope.js"import type { Stream } from "./Stream.js"
/** * @since 3.8.0 * @experimental * @category type ids */export const TypeId: unique symbol = internal.TypeId
/** * @since 3.8.0 * @experimental * @category type ids */export type TypeId = typeof TypeId
/** * @since 3.8.0 * @experimental * @category type ids */export const ReadonlyTypeId: unique symbol = internal.ReadonlyTypeId
/** * @since 3.8.0 * @experimental * @category type ids */export type ReadonlyTypeId = typeof ReadonlyTypeId
/** * @since 3.8.0 * @experimental * @category guards */export const isMailbox = <A = unknown, E = unknown>(u: unknown): u is Mailbox<A, E> => hasProperty(u, TypeId)
/** * @since 3.8.0 * @experimental * @category guards */export const isReadonlyMailbox = <A = unknown, E = unknown>(u: unknown): u is ReadonlyMailbox<A, E> => hasProperty(u, ReadonlyTypeId)
/** * A `Mailbox` is a queue that can be signaled to be done or failed. * * @since 3.8.0 * @experimental * @category models */export interface Mailbox<in out A, in out E = never> extends ReadonlyMailbox<A, E> { readonly [TypeId]: TypeId /** * Add a message to the mailbox. Returns `false` if the mailbox is done. */ readonly offer: (message: A) => Effect<boolean> /** * Add a message to the mailbox. Returns `false` if the mailbox is done. */ readonly unsafeOffer: (message: A) => boolean /** * Add multiple messages to the mailbox. Returns the remaining messages that * were not added. */ readonly offerAll: (messages: Iterable<A>) => Effect<Chunk<A>> /** * Add multiple messages to the mailbox. Returns the remaining messages that * were not added. */ readonly unsafeOfferAll: (messages: Iterable<A>) => Chunk<A> /** * Fail the mailbox with an error. If the mailbox is already done, `false` is * returned. */ readonly fail: (error: E) => Effect<boolean> /** * Fail the mailbox with a cause. If the mailbox is already done, `false` is * returned. */ readonly failCause: (cause: Cause<E>) => Effect<boolean> /** * Signal that the mailbox is complete. If the mailbox is already done, `false` is * returned. */ readonly end: Effect<boolean> /** * Signal that the mailbox is done. If the mailbox is already done, `false` is * returned. */ readonly done: (exit: Exit<void, E>) => Effect<boolean> /** * Signal that the mailbox is done. If the mailbox is already done, `false` is * returned. */ readonly unsafeDone: (exit: Exit<void, E>) => boolean /** * Shutdown the mailbox, canceling any pending operations. * If the mailbox is already done, `false` is returned. */ readonly shutdown: Effect<boolean>}
/** * A `ReadonlyMailbox` represents a mailbox that can only be read from. * * @since 3.8.0 * @experimental * @category models */export interface ReadonlyMailbox<out A, out E = never> extends Effect<readonly [messages: Chunk<A>, done: boolean], E>, Inspectable{ readonly [ReadonlyTypeId]: ReadonlyTypeId /** * Take all messages from the mailbox, returning an empty Chunk if the mailbox * is empty or done. */ readonly clear: Effect<Chunk<A>, E> /** * Take all messages from the mailbox, or wait for messages to be available. * * If the mailbox is done, the `done` flag will be `true`. If the mailbox * fails, the Effect will fail with the error. */ readonly takeAll: Effect<readonly [messages: Chunk<A>, done: boolean], E> /** * Take a specified number of messages from the mailbox. It will only take * up to the capacity of the mailbox. * * If the mailbox is done, the `done` flag will be `true`. If the mailbox * fails, the Effect will fail with the error. */ readonly takeN: (n: number) => Effect<readonly [messages: Chunk<A>, done: boolean], E> /** * Take a single message from the mailbox, or wait for a message to be * available. * * If the mailbox is done, it will fail with `NoSuchElementException`. If the * mailbox fails, the Effect will fail with the error. */ readonly take: Effect<A, E | NoSuchElementException> /** Wait for the mailbox to be done. */ readonly await: Effect<void, E> /** * Check the size of the mailbox. * * If the mailbox is complete, it will return `None`. */ readonly size: Effect<Option<number>> /** * Check the size of the mailbox. * * If the mailbox is complete, it will return `None`. */ readonly unsafeSize: () => Option<number>}
/** * A `Mailbox` is a queue that can be signaled to be done or failed. * * @since 3.8.0 * @experimental * @category constructors * @example * ```ts * import * as assert from "node:assert" * import { Effect, Mailbox } from "effect" * * Effect.gen(function*() { * const mailbox = yield* Mailbox.make<number, string>() * * // add messages to the mailbox * yield* mailbox.offer(1) * yield* mailbox.offer(2) * yield* mailbox.offerAll([3, 4, 5]) * * // take messages from the mailbox * const [messages, done] = yield* mailbox.takeAll * assert.deepStrictEqual(messages, [1, 2, 3, 4, 5]) * assert.strictEqual(done, false) * * // signal that the mailbox is done * yield* mailbox.end * const [messages2, done2] = yield* mailbox.takeAll * assert.deepStrictEqual(messages2, []) * assert.strictEqual(done2, true) * * // signal that the mailbox has failed * yield* mailbox.fail("boom") * }) * ``` */export const make: <A, E = never>( capacity?: number | { readonly capacity?: number readonly strategy?: "suspend" | "dropping" | "sliding" } | undefined) => Effect<Mailbox<A, E>> = internal.make
/** * Run an `Effect` into a `Mailbox`, where success ends the mailbox and failure * fails the mailbox. * * @since 3.8.0 * @experimental * @category combinators */export const into: { /** * Run an `Effect` into a `Mailbox`, where success ends the mailbox and failure * fails the mailbox. * * @since 3.8.0 * @experimental * @category combinators */ <A, E>(self: Mailbox<A, E>): <AX, EX extends E, RX>(effect: Effect<AX, EX, RX>) => Effect<boolean, never, RX> /** * Run an `Effect` into a `Mailbox`, where success ends the mailbox and failure * fails the mailbox. * * @since 3.8.0 * @experimental * @category combinators */ <AX, E, EX extends E, RX, A>(effect: Effect<AX, EX, RX>, self: Mailbox<A, E>): Effect<boolean, never, RX>} = internal.into
/** * Create a `Channel` from a `Mailbox`. * * @since 3.8.0 * @experimental * @category conversions */export const toChannel: <A, E>(self: ReadonlyMailbox<A, E>) => Channel<Chunk<A>, unknown, E> = internal.toChannel
/** * Create a `Stream` from a `Mailbox`. * * @since 3.8.0 * @experimental * @category conversions */export const toStream: <A, E>(self: ReadonlyMailbox<A, E>) => Stream<A, E> = internal.toStream
/** * Create a `ReadonlyMailbox` from a `Stream`. * * @since 3.11.0 * @experimental * @category conversions */export const fromStream: { /** * Create a `ReadonlyMailbox` from a `Stream`. * * @since 3.11.0 * @experimental * @category conversions */ ( options?: { readonly capacity?: number | undefined readonly strategy?: "suspend" | "dropping" | "sliding" | undefined } ): <A, E, R>(self: Stream<A, E, R>) => Effect<ReadonlyMailbox<A, E>, never, R | Scope> /** * Create a `ReadonlyMailbox` from a `Stream`. * * @since 3.11.0 * @experimental * @category conversions */ <A, E, R>( self: Stream<A, E, R>, options?: { readonly capacity?: number | undefined readonly strategy?: "suspend" | "dropping" | "sliding" | undefined } ): Effect<ReadonlyMailbox<A, E>, never, R | Scope>} = internal.fromStream123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180/** * @since 2.0.0 */import type * as Effect from "./Effect.js"import type * as Exit from "./Exit.js"import type * as Fiber from "./Fiber.js"import * as internal from "./internal/managedRuntime.js"import * as circular from "./internal/managedRuntime/circular.js"import type * as Layer from "./Layer.js"import type * as Runtime from "./Runtime.js"import type * as Unify from "./Unify.js"
/** * @since 3.9.0 * @category symbol */export const TypeId: unique symbol = circular.TypeId as TypeId
/** * @since 3.9.0 * @category symbol */export type TypeId = typeof TypeId
/** * Checks if the provided argument is a `ManagedRuntime`. * * @since 3.9.0 * @category guards */export const isManagedRuntime: (input: unknown) => input is ManagedRuntime<unknown, unknown> = internal.isManagedRuntime
/** * @since 3.4.0 */export declare namespace ManagedRuntime { /** * @category type-level * @since 3.4.0 */ export type Context<T extends ManagedRuntime<never, any>> = [T] extends [ManagedRuntime<infer R, infer _E>] ? R : never /** * @category type-level * @since 3.4.0 */ export type Error<T extends ManagedRuntime<never, any>> = [T] extends [ManagedRuntime<infer _R, infer E>] ? E : never}
/** * @since 2.0.0 * @category models */export interface ManagedRuntime<in R, out ER> extends Effect.Effect<Runtime.Runtime<R>, ER> { readonly [TypeId]: TypeId readonly memoMap: Layer.MemoMap readonly runtimeEffect: Effect.Effect<Runtime.Runtime<R>, ER> readonly runtime: () => Promise<Runtime.Runtime<R>>
/** * Executes the effect using the provided Scheduler or using the global * Scheduler if not provided */ readonly runFork: <A, E>( self: Effect.Effect<A, E, R>, options?: Runtime.RunForkOptions ) => Fiber.RuntimeFiber<A, E | ER>
/** * Executes the effect synchronously returning the exit. * * This method is effectful and should only be invoked at the edges of your * program. */ readonly runSyncExit: <A, E>(effect: Effect.Effect<A, E, R>) => Exit.Exit<A, ER | E>
/** * Executes the effect synchronously throwing in case of errors or async boundaries. * * This method is effectful and should only be invoked at the edges of your * program. */ readonly runSync: <A, E>(effect: Effect.Effect<A, E, R>) => A
/** * Executes the effect asynchronously, eventually passing the exit value to * the specified callback. * * This method is effectful and should only be invoked at the edges of your * program. */ readonly runCallback: <A, E>( effect: Effect.Effect<A, E, R>, options?: Runtime.RunCallbackOptions<A, E | ER> | undefined ) => Runtime.Cancel<A, E | ER>
/** * Runs the `Effect`, returning a JavaScript `Promise` that will be resolved * with the value of the effect once the effect has been executed, or will be * rejected with the first error or exception throw by the effect. * * This method is effectful and should only be used at the edges of your * program. */ readonly runPromise: <A, E>(effect: Effect.Effect<A, E, R>, options?: { readonly signal?: AbortSignal | undefined }) => Promise<A>
/** * Runs the `Effect`, returning a JavaScript `Promise` that will be resolved * with the `Exit` state of the effect once the effect has been executed. * * This method is effectful and should only be used at the edges of your * program. */ readonly runPromiseExit: <A, E>(effect: Effect.Effect<A, E, R>, options?: { readonly signal?: AbortSignal | undefined }) => Promise<Exit.Exit<A, ER | E>>
/** * Dispose of the resources associated with the runtime. */ readonly dispose: () => Promise<void>
/** * Dispose of the resources associated with the runtime. */ readonly disposeEffect: Effect.Effect<void, never, never>
readonly [Unify.typeSymbol]?: unknown readonly [Unify.unifySymbol]?: ManagedRuntimeUnify<this> readonly [Unify.ignoreSymbol]?: ManagedRuntimeUnifyIgnore}
/** * @category models * @since 3.9.0 */export interface ManagedRuntimeUnify<A extends { [Unify.typeSymbol]?: any }> extends Effect.EffectUnify<A> { ManagedRuntime?: () => Extract<A[Unify.typeSymbol], ManagedRuntime<any, any>>}
/** * @category models * @since 3.9.0 */export interface ManagedRuntimeUnifyIgnore extends Effect.EffectUnifyIgnore { Effect?: true}
/** * Convert a Layer into an ManagedRuntime, that can be used to run Effect's using * your services. * * @since 2.0.0 * @category runtime class * @example * ```ts * import { Console, Effect, Layer, ManagedRuntime } from "effect" * * class Notifications extends Effect.Tag("Notifications")< * Notifications, * { readonly notify: (message: string) => Effect.Effect<void> } * >() { * static Live = Layer.succeed(this, { notify: (message) => Console.log(message) }) * } * * async function main() { * const runtime = ManagedRuntime.make(Notifications.Live) * await runtime.runPromise(Notifications.notify("Hello, world!")) * await runtime.dispose() * } * * main() * ``` */export const make: <R, E>( layer: Layer.Layer<R, E, never>, memoMap?: Layer.MemoMap | undefined) => ManagedRuntime<R, E> = internal.make123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103/** * @since 2.0.0 */import type * as Effect from "./Effect.js"import type * as Exit from "./Exit.js"import * as internal from "./internal/channel/mergeDecision.js"import type * as Types from "./Types.js"
/** * @since 2.0.0 * @category symbols */export const MergeDecisionTypeId: unique symbol = internal.MergeDecisionTypeId
/** * @since 2.0.0 * @category symbols */export type MergeDecisionTypeId = typeof MergeDecisionTypeId
/** * @since 2.0.0 * @category models */export interface MergeDecision<out R, in E0, in Z0, out E, out Z> extends MergeDecision.Variance<R, E0, Z0, E, Z> {}
/** * @since 2.0.0 */export declare namespace MergeDecision { /** * @since 2.0.0 * @category models */ export interface Variance<out R, in E0, in Z0, out E, out Z> { readonly [MergeDecisionTypeId]: { _R: Types.Covariant<R> _E0: Types.Contravariant<E0> _Z0: Types.Contravariant<Z0> _E: Types.Covariant<E> _Z: Types.Covariant<Z> } }}
/** * @since 2.0.0 * @category constructors */export const Done: <Z, E, R>(effect: Effect.Effect<Z, E, R>) => MergeDecision<R, unknown, unknown, E, Z> = internal.Done
/** * @since 2.0.0 * @category constructors */export const Await: <R, E0, Z0, E, Z>( f: (exit: Exit.Exit<Z0, E0>) => Effect.Effect<Z, E, R>) => MergeDecision<R, E0, Z0, E, Z> = internal.Await
/** * @since 2.0.0 * @category constructors */export const AwaitConst: <Z, E, R>(effect: Effect.Effect<Z, E, R>) => MergeDecision<R, unknown, unknown, E, Z> = internal.AwaitConst
/** * Returns `true` if the specified value is a `MergeDecision`, `false` * otherwise. * * @since 2.0.0 * @category refinements */export const isMergeDecision: (u: unknown) => u is MergeDecision<unknown, unknown, unknown, unknown, unknown> = internal.isMergeDecision
/** * @since 2.0.0 * @category folding */export const match: { /** * @since 2.0.0 * @category folding */ <R, E0, Z0, E, Z, Z2>( options: { readonly onDone: (effect: Effect.Effect<Z, E, R>) => Z2 readonly onAwait: (f: (exit: Exit.Exit<Z0, E0>) => Effect.Effect<Z, E, R>) => Z2 } ): (self: MergeDecision<R, E0, Z0, E, Z>) => Z2 /** * @since 2.0.0 * @category folding */ <R, E0, Z0, E, Z, Z2>( self: MergeDecision<R, E0, Z0, E, Z>, options: { readonly onDone: (effect: Effect.Effect<Z, E, R>) => Z2 readonly onAwait: (f: (exit: Exit.Exit<Z0, E0>) => Effect.Effect<Z, E, R>) => Z2 } ): Z2} = internal.match123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180/** * @since 2.0.0 */import type * as Effect from "./Effect.js"import type * as Either from "./Either.js"import type * as Exit from "./Exit.js"import type * as Fiber from "./Fiber.js"import * as internal from "./internal/channel/mergeState.js"
/** * @since 2.0.0 * @category symbols */export const MergeStateTypeId: unique symbol = internal.MergeStateTypeId
/** * @since 2.0.0 * @category symbols */export type MergeStateTypeId = typeof MergeStateTypeId
/** * @since 2.0.0 * @category models */export type MergeState<Env, Err, Err1, Err2, Elem, Done, Done1, Done2> = | BothRunning<Env, Err, Err1, Err2, Elem, Done, Done1, Done2> | LeftDone<Env, Err, Err1, Err2, Elem, Done, Done1, Done2> | RightDone<Env, Err, Err1, Err2, Elem, Done, Done1, Done2>
/** * @since 2.0.0 */export declare namespace MergeState { /** * @since 2.0.0 * @category models */ export interface Proto { readonly [MergeStateTypeId]: MergeStateTypeId }}
/** * @since 2.0.0 * @category models */export interface BothRunning<_Env, out Err, out Err1, _Err2, out Elem, out Done, out Done1, _Done2> extends MergeState.Proto{ readonly _tag: "BothRunning" readonly left: Fiber.Fiber<Either.Either<Elem, Done>, Err> readonly right: Fiber.Fiber<Either.Either<Elem, Done1>, Err1>}
/** * @since 2.0.0 * @category models */export interface LeftDone<out Env, _Err, in Err1, out Err2, _Elem, _Done, in Done1, out Done2> extends MergeState.Proto{ readonly _tag: "LeftDone" f(exit: Exit.Exit<Done1, Err1>): Effect.Effect<Done2, Err2, Env>}
/** * @since 2.0.0 * @category models */export interface RightDone<out Env, in Err, _Err1, out Err2, _Elem, in Done, _Done1, out Done2> extends MergeState.Proto{ readonly _tag: "RightDone" f(exit: Exit.Exit<Done, Err>): Effect.Effect<Done2, Err2, Env>}
/** * @since 2.0.0 * @category constructors */export const BothRunning: <Env, Err, Err1, Err2, Elem, Done, Done1, Done2>( left: Fiber.Fiber<Either.Either<Elem, Done>, Err>, right: Fiber.Fiber<Either.Either<Elem, Done1>, Err1>) => MergeState<Env, Err, Err1, Err2, Elem, Done, Done1, Done2> = internal.BothRunning
/** * @since 2.0.0 * @category constructors */export const LeftDone: <Env, Err, Err1, Err2, Elem, Done, Done1, Done2>( f: (exit: Exit.Exit<Done1, Err1>) => Effect.Effect<Done2, Err2, Env>) => MergeState<Env, Err, Err1, Err2, Elem, Done, Done1, Done2> = internal.LeftDone
/** * @since 2.0.0 * @category constructors */export const RightDone: <Env, Err, Err1, Err2, Elem, Done, Done1, Done2>( f: (exit: Exit.Exit<Done, Err>) => Effect.Effect<Done2, Err2, Env>) => MergeState<Env, Err, Err1, Err2, Elem, Done, Done1, Done2> = internal.RightDone
/** * Returns `true` if the specified value is a `MergeState`, `false` otherwise. * * @since 2.0.0 * @category refinements */export const isMergeState: ( u: unknown) => u is MergeState<unknown, unknown, unknown, unknown, unknown, unknown, unknown, unknown> = internal.isMergeState
/** * Returns `true` if the specified `MergeState` is a `BothRunning`, `false` * otherwise. * * @since 2.0.0 * @category refinements */export const isBothRunning: <Env, Err, Err1, Err2, Elem, Done, Done1, Done2>( self: MergeState<Env, Err, Err1, Err2, Elem, Done, Done1, Done2>) => self is BothRunning<Env, Err, Err1, Err2, Elem, Done, Done1, Done2> = internal.isBothRunning
/** * Returns `true` if the specified `MergeState` is a `LeftDone`, `false` * otherwise. * * @since 2.0.0 * @category refinements */export const isLeftDone: <Env, Err, Err1, Err2, Elem, Done, Done1, Done2>( self: MergeState<Env, Err, Err1, Err2, Elem, Done, Done1, Done2>) => self is LeftDone<Env, Err, Err1, Err2, Elem, Done, Done1, Done2> = internal.isLeftDone
/** * Returns `true` if the specified `MergeState` is a `RightDone`, `false` * otherwise. * * @since 2.0.0 * @category refinements */export const isRightDone: <Env, Err, Err1, Err2, Elem, Done, Done1, Done2>( self: MergeState<Env, Err, Err1, Err2, Elem, Done, Done1, Done2>) => self is RightDone<Env, Err, Err1, Err2, Elem, Done, Done1, Done2> = internal.isRightDone
/** * @since 2.0.0 * @category folding */export const match: { /** * @since 2.0.0 * @category folding */ <Env, Err, Err1, Err2, Elem, Done, Done1, Done2, Z>( options: { readonly onBothRunning: ( left: Fiber.Fiber<Either.Either<Elem, Done>, Err>, right: Fiber.Fiber<Either.Either<Elem, Done1>, Err1> ) => Z readonly onLeftDone: (f: (exit: Exit.Exit<Done1, Err1>) => Effect.Effect<Done2, Err2, Env>) => Z readonly onRightDone: (f: (exit: Exit.Exit<Done, Err>) => Effect.Effect<Done2, Err2, Env>) => Z } ): (self: MergeState<Env, Err, Err1, Err2, Elem, Done, Done1, Done2>) => Z /** * @since 2.0.0 * @category folding */ <Env, Err, Err1, Err2, Elem, Done, Done1, Done2, Z>( self: MergeState<Env, Err, Err1, Err2, Elem, Done, Done1, Done2>, options: { readonly onBothRunning: ( left: Fiber.Fiber<Either.Either<Elem, Done>, Err>, right: Fiber.Fiber<Either.Either<Elem, Done1>, Err1> ) => Z readonly onLeftDone: (f: (exit: Exit.Exit<Done1, Err1>) => Effect.Effect<Done2, Err2, Env>) => Z readonly onRightDone: (f: (exit: Exit.Exit<Done, Err>) => Effect.Effect<Done2, Err2, Env>) => Z } ): Z} = internal.match123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124/** * @since 2.0.0 */import * as internal from "./internal/channel/mergeStrategy.js"
/** * @since 2.0.0 * @category symbols */export const MergeStrategyTypeId: unique symbol = internal.MergeStrategyTypeId
/** * @since 2.0.0 * @category symbols */export type MergeStrategyTypeId = typeof MergeStrategyTypeId
/** * @since 2.0.0 * @category models */export type MergeStrategy = BackPressure | BufferSliding
/** * @since 2.0.0 */export declare namespace MergeStrategy { /** * @since 2.0.0 * @category models */ export interface Proto { readonly [MergeStrategyTypeId]: MergeStrategyTypeId }}
/** * @since 2.0.0 * @category models */export interface BackPressure extends MergeStrategy.Proto { readonly _tag: "BackPressure"}
/** * @since 2.0.0 * @category models */export interface BufferSliding extends MergeStrategy.Proto { readonly _tag: "BufferSliding"}
/** * @since 2.0.0 * @category constructors */export const BackPressure: (_: void) => MergeStrategy = internal.BackPressure
/** * @since 2.0.0 * @category constructors */export const BufferSliding: (_: void) => MergeStrategy = internal.BufferSliding
/** * Returns `true` if the specified value is a `MergeStrategy`, `false` * otherwise. * * @since 2.0.0 * @category refinements */export const isMergeStrategy: (u: unknown) => u is MergeStrategy = internal.isMergeStrategy
/** * Returns `true` if the specified `MergeStrategy` is a `BackPressure`, `false` * otherwise. * * @since 2.0.0 * @category refinements */export const isBackPressure: (self: MergeStrategy) => self is BackPressure = internal.isBackPressure
/** * Returns `true` if the specified `MergeStrategy` is a `BufferSliding`, `false` * otherwise. * * @since 2.0.0 * @category refinements */export const isBufferSliding: (self: MergeStrategy) => self is BufferSliding = internal.isBufferSliding
/** * Folds an `MergeStrategy` into a value of type `A`. * * @since 2.0.0 * @category folding */export const match: { /** * Folds an `MergeStrategy` into a value of type `A`. * * @since 2.0.0 * @category folding */ <A>( options: { readonly onBackPressure: () => A readonly onBufferSliding: () => A } ): (self: MergeStrategy) => A /** * Folds an `MergeStrategy` into a value of type `A`. * * @since 2.0.0 * @category folding */ <A>( self: MergeStrategy, options: { readonly onBackPressure: () => A readonly onBufferSliding: () => A } ): A} = internal.match1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165/** * @since 2.0.0 */import type * as Duration from "./Duration.js"import type * as Effect from "./Effect.js"import type { LazyArg } from "./Function.js"import * as fiberRuntime from "./internal/fiberRuntime.js"import * as internal from "./internal/metric.js"import type * as MetricBoundaries from "./MetricBoundaries.js"import type * as MetricKey from "./MetricKey.js"import type * as MetricKeyType from "./MetricKeyType.js"import type * as MetricLabel from "./MetricLabel.js"import type * as MetricPair from "./MetricPair.js"import type * as MetricRegistry from "./MetricRegistry.js"import type * as MetricState from "./MetricState.js"import type { Pipeable } from "./Pipeable.js"import type * as Types from "./Types.js"
/** * @since 2.0.0 * @category symbols */export const MetricTypeId: unique symbol = internal.MetricTypeId
/** * @since 2.0.0 * @category symbols */export type MetricTypeId = typeof MetricTypeId
/** * A `Metric<Type, In, Out>` represents a concurrent metric which accepts * updates of type `In` and are aggregated to a stateful value of type `Out`. * * For example, a counter metric would have type `Metric<number, number>`, * representing the fact that the metric can be updated with numbers (the amount * to increment or decrement the counter by), and the state of the counter is a * number. * * There are five primitive metric types supported by Effect: * * - Counters * - Frequencies * - Gauges * - Histograms * - Summaries * * @since 2.0.0 * @category models */export interface Metric<in out Type, in In, out Out> extends Metric.Variance<Type, In, Out>, Pipeable { /** * The type of the underlying primitive metric. For example, this could be * `MetricKeyType.Counter` or `MetricKeyType.Gauge`. */ readonly keyType: Type unsafeUpdate(input: In, extraTags: ReadonlyArray<MetricLabel.MetricLabel>): void unsafeValue(extraTags: ReadonlyArray<MetricLabel.MetricLabel>): Out unsafeModify(input: In, extraTags: ReadonlyArray<MetricLabel.MetricLabel>): void register(): this <A extends In, E, R>(effect: Effect.Effect<A, E, R>): Effect.Effect<A, E, R>}
/** * @since 2.0.0 * @category models */export interface MetricApply { <Type, In, Out>( keyType: Type, unsafeUpdate: (input: In, extraTags: ReadonlyArray<MetricLabel.MetricLabel>) => void, unsafeValue: (extraTags: ReadonlyArray<MetricLabel.MetricLabel>) => Out, unsafeModify: (input: In, extraTags: ReadonlyArray<MetricLabel.MetricLabel>) => void ): Metric<Type, In, Out>}
/** * @since 2.0.0 */export declare namespace Metric { /** * @since 2.0.0 * @category models */ export interface Counter<In extends number | bigint> extends Metric<MetricKeyType.MetricKeyType.Counter<In>, In, MetricState.MetricState.Counter<In>> {}
/** * @since 2.0.0 * @category models */ export interface Gauge<In extends number | bigint> extends Metric<MetricKeyType.MetricKeyType.Gauge<In>, In, MetricState.MetricState.Gauge<In>> {}
/** * @since 2.0.0 * @category models */ export interface Frequency<In> extends Metric<MetricKeyType.MetricKeyType.Frequency, In, MetricState.MetricState.Frequency> {}
/** * @since 2.0.0 * @category models */ export interface Histogram<In> extends Metric<MetricKeyType.MetricKeyType.Histogram, In, MetricState.MetricState.Histogram> {}
/** * @since 2.0.0 * @category models */ export interface Summary<In> extends Metric<MetricKeyType.MetricKeyType.Summary, In, MetricState.MetricState.Summary> {}
/** * @since 2.0.0 * @category models */ export interface Variance<in out Type, in In, out Out> { readonly [MetricTypeId]: { readonly _Type: Types.Invariant<Type> readonly _In: Types.Contravariant<In> readonly _Out: Types.Covariant<Out> } }}
/** * @since 2.0.0 * @category globals */export const globalMetricRegistry: MetricRegistry.MetricRegistry = internal.globalMetricRegistry
/** * @since 2.0.0 * @category constructors */export const make: MetricApply = internal.make
/** * Returns a new metric that is powered by this one, but which accepts updates * of the specified new type, which must be transformable to the input type of * this metric. * * @since 2.0.0 * @category mapping */export const mapInput: { /** * Returns a new metric that is powered by this one, but which accepts updates * of the specified new type, which must be transformable to the input type of * this metric. * * @since 2.0.0 * @category mapping */ <In, In2>(f: (input: In2) => In): <Type, Out>(self: Metric<Type, In, Out>) => Metric<Type, In2, Out> /** * Returns a new metric that is powered by this one, but which accepts updates * of the specified new type, which must be transformable to the input type of * this metric. * * @since 2.0.0 * @category mapping */ <Type, In, Out, In2>(self: Metric<Type, In, Out>, f: (input: In2) => In): Metric<Type, In2, Out>} = internal.mapInput
/** * Represents a Counter metric that tracks cumulative numerical values over time. * Counters can be incremented and decremented and provide a running total of changes. * * **Options** * * - description - A description of the counter. * - bigint - Indicates if the counter uses 'bigint' data type. * - incremental - Set to 'true' for a counter that only increases. With this configuration, Effect ensures that non-incremental updates have no impact on the counter, making it exclusively suitable for counting upwards. * * @example * ```ts * import { Metric } from "effect" * * const numberCounter = Metric.counter("count", { * description: "A number counter" * }); * * const bigintCounter = Metric.counter("count", { * description: "A bigint counter", * bigint: true * }); * ``` * * @since 2.0.0 * @category constructors */export const counter: { /** * Represents a Counter metric that tracks cumulative numerical values over time. * Counters can be incremented and decremented and provide a running total of changes. * * **Options** * * - description - A description of the counter. * - bigint - Indicates if the counter uses 'bigint' data type. * - incremental - Set to 'true' for a counter that only increases. With this configuration, Effect ensures that non-incremental updates have no impact on the counter, making it exclusively suitable for counting upwards. * * @example * ```ts * import { Metric } from "effect" * * const numberCounter = Metric.counter("count", { * description: "A number counter" * }); * * const bigintCounter = Metric.counter("count", { * description: "A bigint counter", * bigint: true * }); * ``` * * @since 2.0.0 * @category constructors */ ( name: string, options?: { readonly description?: string | undefined readonly bigint?: false | undefined readonly incremental?: boolean | undefined } ): Metric.Counter<number> /** * Represents a Counter metric that tracks cumulative numerical values over time. * Counters can be incremented and decremented and provide a running total of changes. * * **Options** * * - description - A description of the counter. * - bigint - Indicates if the counter uses 'bigint' data type. * - incremental - Set to 'true' for a counter that only increases. With this configuration, Effect ensures that non-incremental updates have no impact on the counter, making it exclusively suitable for counting upwards. * * @example * ```ts * import { Metric } from "effect" * * const numberCounter = Metric.counter("count", { * description: "A number counter" * }); * * const bigintCounter = Metric.counter("count", { * description: "A bigint counter", * bigint: true * }); * ``` * * @since 2.0.0 * @category constructors */ ( name: string, options: { readonly description?: string | undefined readonly bigint: true readonly incremental?: boolean | undefined } ): Metric.Counter<bigint>} = internal.counter
/** * Creates a Frequency metric to count occurrences of events. * Frequency metrics are used to count the number of times specific events or incidents occur. * * @example * ```ts * import { Metric } from "effect" * * const errorFrequency = Metric.frequency("error_frequency", { * description: "Counts the occurrences of errors." * }); * ``` * * @since 2.0.0 * @category constructors */export const frequency: ( name: string, options?: | { readonly description?: string | undefined; readonly preregisteredWords?: ReadonlyArray<string> | undefined } | undefined) => Metric.Frequency<string> = internal.frequency
/** * Returns a new metric that is powered by this one, but which accepts updates * of any type, and translates them to updates with the specified constant * update value. * * @since 2.0.0 * @category constructors */export const withConstantInput: { /** * Returns a new metric that is powered by this one, but which accepts updates * of any type, and translates them to updates with the specified constant * update value. * * @since 2.0.0 * @category constructors */ <In>(input: In): <Type, Out>(self: Metric<Type, In, Out>) => Metric<Type, unknown, Out> /** * Returns a new metric that is powered by this one, but which accepts updates * of any type, and translates them to updates with the specified constant * update value. * * @since 2.0.0 * @category constructors */ <Type, In, Out>(self: Metric<Type, In, Out>, input: In): Metric<Type, unknown, Out>} = internal.withConstantInput
/** * @since 2.0.0 * @category constructors */export const fromMetricKey: <Type extends MetricKeyType.MetricKeyType<any, any>>( key: MetricKey.MetricKey<Type>) => Metric<Type, MetricKeyType.MetricKeyType.InType<Type>, MetricKeyType.MetricKeyType.OutType<Type>> = internal.fromMetricKey
/** * Represents a Gauge metric that tracks and reports a single numerical value at a specific moment. * Gauges are suitable for metrics that represent instantaneous values, such as memory usage or CPU load. * * **Options** * * - description - A description of the gauge metric. * - bigint - Indicates if the counter uses 'bigint' data type. * * @example * ```ts * import { Metric } from "effect" * * const numberGauge = Metric.gauge("memory_usage", { * description: "A gauge for memory usage" * }); * * const bigintGauge = Metric.gauge("cpu_load", { * description: "A gauge for CPU load", * bigint: true * }); * ``` * * @since 2.0.0 * @category constructors */export const gauge: { /** * Represents a Gauge metric that tracks and reports a single numerical value at a specific moment. * Gauges are suitable for metrics that represent instantaneous values, such as memory usage or CPU load. * * **Options** * * - description - A description of the gauge metric. * - bigint - Indicates if the counter uses 'bigint' data type. * * @example * ```ts * import { Metric } from "effect" * * const numberGauge = Metric.gauge("memory_usage", { * description: "A gauge for memory usage" * }); * * const bigintGauge = Metric.gauge("cpu_load", { * description: "A gauge for CPU load", * bigint: true * }); * ``` * * @since 2.0.0 * @category constructors */ ( name: string, options?: { readonly description?: string | undefined readonly bigint?: false | undefined } ): Metric.Gauge<number> /** * Represents a Gauge metric that tracks and reports a single numerical value at a specific moment. * Gauges are suitable for metrics that represent instantaneous values, such as memory usage or CPU load. * * **Options** * * - description - A description of the gauge metric. * - bigint - Indicates if the counter uses 'bigint' data type. * * @example * ```ts * import { Metric } from "effect" * * const numberGauge = Metric.gauge("memory_usage", { * description: "A gauge for memory usage" * }); * * const bigintGauge = Metric.gauge("cpu_load", { * description: "A gauge for CPU load", * bigint: true * }); * ``` * * @since 2.0.0 * @category constructors */ ( name: string, options: { readonly description?: string | undefined readonly bigint: true } ): Metric.Gauge<bigint>} = internal.gauge
/** * Represents a Histogram metric that records observations in specified value boundaries. * Histogram metrics are useful for measuring the distribution of values within a range. * * @example * ```ts * import { Metric, MetricBoundaries } from "effect" * * const latencyHistogram = Metric.histogram("latency_histogram", * MetricBoundaries.linear({ start: 0, width: 10, count: 11 }), * "Measures the distribution of request latency." * ); * ``` * * @since 2.0.0 * @category constructors */export const histogram: ( name: string, boundaries: MetricBoundaries.MetricBoundaries, description?: string) => Metric<MetricKeyType.MetricKeyType.Histogram, number, MetricState.MetricState.Histogram> = internal.histogram
/** * @since 2.0.0 * @category combinators */export const increment: ( self: Metric.Counter<number> | Metric.Counter<bigint> | Metric.Gauge<number> | Metric.Gauge<bigint>) => Effect.Effect<void> = internal.increment
/** * @since 2.0.0 * @category combinators */export const incrementBy: { /** * @since 2.0.0 * @category combinators */ (amount: number): (self: Metric.Counter<number> | Metric.Counter<number>) => Effect.Effect<void> /** * @since 2.0.0 * @category combinators */ (amount: bigint): (self: Metric.Counter<bigint> | Metric.Gauge<bigint>) => Effect.Effect<void> /** * @since 2.0.0 * @category combinators */ (self: Metric.Counter<number> | Metric.Gauge<number>, amount: number): Effect.Effect<void> /** * @since 2.0.0 * @category combinators */ (self: Metric.Counter<bigint> | Metric.Gauge<bigint>, amount: bigint): Effect.Effect<void>} = internal.incrementBy
/** * Returns a new metric that is powered by this one, but which outputs a new * state type, determined by transforming the state type of this metric by the * specified function. * * @since 2.0.0 * @category mapping */export const map: { /** * Returns a new metric that is powered by this one, but which outputs a new * state type, determined by transforming the state type of this metric by the * specified function. * * @since 2.0.0 * @category mapping */ <Out, Out2>(f: (out: Out) => Out2): <Type, In>(self: Metric<Type, In, Out>) => Metric<Type, In, Out2> /** * Returns a new metric that is powered by this one, but which outputs a new * state type, determined by transforming the state type of this metric by the * specified function. * * @since 2.0.0 * @category mapping */ <Type, In, Out, Out2>(self: Metric<Type, In, Out>, f: (out: Out) => Out2): Metric<Type, In, Out2>} = internal.map
/** * @since 2.0.0 * @category mapping */export const mapType: { /** * @since 2.0.0 * @category mapping */ <Type, Type2>(f: (type: Type) => Type2): <In, Out>(self: Metric<Type, In, Out>) => Metric<Type2, In, Out> /** * @since 2.0.0 * @category mapping */ <Type, In, Out, Type2>(self: Metric<Type, In, Out>, f: (type: Type) => Type2): Metric<Type2, In, Out>} = internal.mapType
/** * Modifies the metric with the specified update message. For example, if the * metric were a gauge, the update would increment the method by the provided * amount. * * @since 3.6.5 * @category utils */export const modify: { /** * Modifies the metric with the specified update message. For example, if the * metric were a gauge, the update would increment the method by the provided * amount. * * @since 3.6.5 * @category utils */ <In>(input: In): <Type, Out>(self: Metric<Type, In, Out>) => Effect.Effect<void> /** * Modifies the metric with the specified update message. For example, if the * metric were a gauge, the update would increment the method by the provided * amount. * * @since 3.6.5 * @category utils */ <Type, In, Out>(self: Metric<Type, In, Out>, input: In): Effect.Effect<void>} = internal.modify
/** * @since 2.0.0 * @category aspects */export const set: { /** * @since 2.0.0 * @category aspects */ (value: number): (self: Metric.Gauge<number>) => Effect.Effect<void> /** * @since 2.0.0 * @category aspects */ (value: bigint): (self: Metric.Gauge<bigint>) => Effect.Effect<void> /** * @since 2.0.0 * @category aspects */ (self: Metric.Gauge<number>, value: number): Effect.Effect<void> /** * @since 2.0.0 * @category aspects */ (self: Metric.Gauge<bigint>, value: bigint): Effect.Effect<void>} = internal.set
/** * Captures a snapshot of all metrics recorded by the application. * * @since 2.0.0 * @category getters */export const snapshot: Effect.Effect<Array<MetricPair.MetricPair.Untyped>> = internal.snapshot
/** * Creates a metric that ignores input and produces constant output. * * @since 2.0.0 * @category constructors */export const succeed: <Out>(out: Out) => Metric<void, unknown, Out> = internal.succeed
/** * Creates a metric that ignores input and produces constant output. * * @since 2.0.0 * @category constructors */export const sync: <Out>(evaluate: LazyArg<Out>) => Metric<void, unknown, Out> = internal.sync
/** * Creates a Summary metric that records observations and calculates quantiles. * Summary metrics provide statistical information about a set of values, including quantiles. * * **Options** * * - name - The name of the Summary metric. * - maxAge - The maximum age of observations to retain. * - maxSize - The maximum number of observations to keep. * - error - The error percentage when calculating quantiles. * - quantiles - An `Chunk` of quantiles to calculate (e.g., [0.5, 0.9]). * - description - An optional description of the Summary metric. * * @example * ```ts * import { Metric, Chunk } from "effect" * * const responseTimesSummary = Metric.summary({ * name: "response_times_summary", * maxAge: "60 seconds", // Retain observations for 60 seconds. * maxSize: 1000, // Keep a maximum of 1000 observations. * error: 0.01, // Allow a 1% error when calculating quantiles. * quantiles: [0.5, 0.9, 0.99], // Calculate 50th, 90th, and 99th percentiles. * description: "Measures the distribution of response times." * }); * ``` * * @since 2.0.0 * @category constructors */export const summary: ( options: { readonly name: string readonly maxAge: Duration.DurationInput readonly maxSize: number readonly error: number readonly quantiles: ReadonlyArray<number> readonly description?: string | undefined }) => Metric.Summary<number> = internal.summary
/** * @since 2.0.0 * @category constructors */export const summaryTimestamp: ( options: { readonly name: string readonly maxAge: Duration.DurationInput readonly maxSize: number readonly error: number readonly quantiles: ReadonlyArray<number> readonly description?: string | undefined }) => Metric.Summary<readonly [value: number, timestamp: number]> // readonly because contravariant = internal.summaryTimestamp
/** * Returns a new metric, which is identical in every way to this one, except * the specified tags have been added to the tags of this metric. * * @since 2.0.0 * @category utils */export const tagged: { /** * Returns a new metric, which is identical in every way to this one, except * the specified tags have been added to the tags of this metric. * * @since 2.0.0 * @category utils */ <Type, In, Out>(key: string, value: string): (self: Metric<Type, In, Out>) => Metric<Type, In, Out> /** * Returns a new metric, which is identical in every way to this one, except * the specified tags have been added to the tags of this metric. * * @since 2.0.0 * @category utils */ <Type, In, Out>(self: Metric<Type, In, Out>, key: string, value: string): Metric<Type, In, Out>} = internal.tagged
/** * Returns a new metric, which is identical in every way to this one, except * dynamic tags are added based on the update values. Note that the metric * returned by this method does not return any useful information, due to the * dynamic nature of the added tags. * * @since 2.0.0 * @category utils */export const taggedWithLabelsInput: { /** * Returns a new metric, which is identical in every way to this one, except * dynamic tags are added based on the update values. Note that the metric * returned by this method does not return any useful information, due to the * dynamic nature of the added tags. * * @since 2.0.0 * @category utils */ <In>(f: (input: In) => Iterable<MetricLabel.MetricLabel>): <Type, Out>(self: Metric<Type, In, Out>) => Metric<Type, In, void> /** * Returns a new metric, which is identical in every way to this one, except * dynamic tags are added based on the update values. Note that the metric * returned by this method does not return any useful information, due to the * dynamic nature of the added tags. * * @since 2.0.0 * @category utils */ <Type, In, Out>( self: Metric<Type, In, Out>, f: (input: In) => Iterable<MetricLabel.MetricLabel> ): Metric<Type, In, void>} = internal.taggedWithLabelsInput
/** * Returns a new metric, which is identical in every way to this one, except * the specified tags have been added to the tags of this metric. * * @since 2.0.0 * @category utils */export const taggedWithLabels: { /** * Returns a new metric, which is identical in every way to this one, except * the specified tags have been added to the tags of this metric. * * @since 2.0.0 * @category utils */ <Type, In, Out>(extraTags: Iterable<MetricLabel.MetricLabel>): (self: Metric<Type, In, Out>) => Metric<Type, In, Out> /** * Returns a new metric, which is identical in every way to this one, except * the specified tags have been added to the tags of this metric. * * @since 2.0.0 * @category utils */ <Type, In, Out>(self: Metric<Type, In, Out>, extraTags: Iterable<MetricLabel.MetricLabel>): Metric<Type, In, Out>} = internal.taggedWithLabels
/** * Creates a timer metric, based on a histogram, which keeps track of * durations in milliseconds. The unit of time will automatically be added to * the metric as a tag (i.e. `"time_unit: milliseconds"`). * * @since 2.0.0 * @category constructors */export const timer: ( name: string, description?: string) => Metric<MetricKeyType.MetricKeyType.Histogram, Duration.Duration, MetricState.MetricState.Histogram> = internal.timer
/** * Creates a timer metric, based on a histogram created from the provided * boundaries, which keeps track of durations in milliseconds. The unit of time * will automatically be added to the metric as a tag (i.e. * `"time_unit: milliseconds"`). * * @since 2.0.0 * @category constructors */export const timerWithBoundaries: ( name: string, boundaries: ReadonlyArray<number>, description?: string) => Metric<MetricKeyType.MetricKeyType.Histogram, Duration.Duration, MetricState.MetricState.Histogram> = internal.timerWithBoundaries
/** * Returns an aspect that will update this metric with the specified constant * value every time the aspect is applied to an effect, regardless of whether * that effect fails or succeeds. * * @since 2.0.0 * @category aspects */export const trackAll: { /** * Returns an aspect that will update this metric with the specified constant * value every time the aspect is applied to an effect, regardless of whether * that effect fails or succeeds. * * @since 2.0.0 * @category aspects */ <In>(input: In): <Type, Out>(self: Metric<Type, In, Out>) => <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R> /** * Returns an aspect that will update this metric with the specified constant * value every time the aspect is applied to an effect, regardless of whether * that effect fails or succeeds. * * @since 2.0.0 * @category aspects */ <Type, In, Out>(self: Metric<Type, In, Out>, input: In): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R>} = internal.trackAll
/** * Returns an aspect that will update this metric with the defects of the * effects that it is applied to. * * @since 2.0.0 * @category aspects */export const trackDefect: { /** * Returns an aspect that will update this metric with the defects of the * effects that it is applied to. * * @since 2.0.0 * @category aspects */ <Type, Out>(metric: Metric<Type, unknown, Out>): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R> /** * Returns an aspect that will update this metric with the defects of the * effects that it is applied to. * * @since 2.0.0 * @category aspects */ <A, E, R, Type, Out>(self: Effect.Effect<A, E, R>, metric: Metric<Type, unknown, Out>): Effect.Effect<A, E, R>} = internal.trackDefect
/** * Returns an aspect that will update this metric with the result of applying * the specified function to the defect throwables of the effects that the * aspect is applied to. * * @since 2.0.0 * @category aspects */export const trackDefectWith: { /** * Returns an aspect that will update this metric with the result of applying * the specified function to the defect throwables of the effects that the * aspect is applied to. * * @since 2.0.0 * @category aspects */ <Type, In, Out>(metric: Metric<Type, In, Out>, f: (defect: unknown) => In): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R> /** * Returns an aspect that will update this metric with the result of applying * the specified function to the defect throwables of the effects that the * aspect is applied to. * * @since 2.0.0 * @category aspects */ <A, E, R, Type, In, Out>( self: Effect.Effect<A, E, R>, metric: Metric<Type, In, Out>, f: (defect: unknown) => In ): Effect.Effect<A, E, R>} = internal.trackDefectWith
/** * Returns an aspect that will update this metric with the duration that the * effect takes to execute. To call this method, the input type of the metric * must be `Duration`. * * @since 2.0.0 * @category aspects */export const trackDuration: { /** * Returns an aspect that will update this metric with the duration that the * effect takes to execute. To call this method, the input type of the metric * must be `Duration`. * * @since 2.0.0 * @category aspects */ <Type, Out>(metric: Metric<Type, Duration.Duration, Out>): <A, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R> /** * Returns an aspect that will update this metric with the duration that the * effect takes to execute. To call this method, the input type of the metric * must be `Duration`. * * @since 2.0.0 * @category aspects */ <A, E, R, Type, Out>(self: Effect.Effect<A, E, R>, metric: Metric<Type, Duration.Duration, Out>): Effect.Effect<A, E, R>} = internal.trackDuration
/** * Returns an aspect that will update this metric with the duration that the * effect takes to execute. To call this method, you must supply a function * that can convert the `Duration` to the input type of this metric. * * @since 2.0.0 * @category aspects */export const trackDurationWith: { /** * Returns an aspect that will update this metric with the duration that the * effect takes to execute. To call this method, you must supply a function * that can convert the `Duration` to the input type of this metric. * * @since 2.0.0 * @category aspects */ <Type, In, Out>(metric: Metric<Type, In, Out>, f: (duration: Duration.Duration) => In): <A, E, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R> /** * Returns an aspect that will update this metric with the duration that the * effect takes to execute. To call this method, you must supply a function * that can convert the `Duration` to the input type of this metric. * * @since 2.0.0 * @category aspects */ <A, E, R, Type, In, Out>( self: Effect.Effect<A, E, R>, metric: Metric<Type, In, Out>, f: (duration: Duration.Duration) => In ): Effect.Effect<A, E, R>} = internal.trackDurationWith
/** * Returns an aspect that will update this metric with the failure value of * the effects that it is applied to. * * @since 2.0.0 * @category aspects */export const trackError: { /** * Returns an aspect that will update this metric with the failure value of * the effects that it is applied to. * * @since 2.0.0 * @category aspects */ <Type, In, Out>(metric: Metric<Type, In, Out>): <A, E extends In, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R> /** * Returns an aspect that will update this metric with the failure value of * the effects that it is applied to. * * @since 2.0.0 * @category aspects */ <A, E extends In, R, Type, In, Out>(self: Effect.Effect<A, E, R>, metric: Metric<Type, In, Out>): Effect.Effect<A, E, R>} = internal.trackError
/** * Returns an aspect that will update this metric with the result of applying * the specified function to the error value of the effects that the aspect is * applied to. * * @since 2.0.0 * @category aspects */export const trackErrorWith: { /** * Returns an aspect that will update this metric with the result of applying * the specified function to the error value of the effects that the aspect is * applied to. * * @since 2.0.0 * @category aspects */ <Type, In, Out, In2>(metric: Metric<Type, In, Out>, f: (error: In2) => In): <A, E extends In2, R>(effect: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R> /** * Returns an aspect that will update this metric with the result of applying * the specified function to the error value of the effects that the aspect is * applied to. * * @since 2.0.0 * @category aspects */ <A, E extends In2, R, Type, In, Out, In2>( self: Effect.Effect<A, E, R>, metric: Metric<Type, In, Out>, f: (error: In2) => In ): Effect.Effect<A, E, R>} = internal.trackErrorWith
/** * Returns an aspect that will update this metric with the success value of * the effects that it is applied to. * * @since 2.0.0 * @category aspects */export const trackSuccess: { /** * Returns an aspect that will update this metric with the success value of * the effects that it is applied to. * * @since 2.0.0 * @category aspects */ <Type, In, Out>(metric: Metric<Type, In, Out>): <A extends In, E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R> /** * Returns an aspect that will update this metric with the success value of * the effects that it is applied to. * * @since 2.0.0 * @category aspects */ <A extends In, E, R, Type, In, Out>(self: Effect.Effect<A, E, R>, metric: Metric<Type, In, Out>): Effect.Effect<A, E, R>} = internal.trackSuccess
/** * Returns an aspect that will update this metric with the result of applying * the specified function to the success value of the effects that the aspect is * applied to. * * @since 2.0.0 * @category aspects */export const trackSuccessWith: { /** * Returns an aspect that will update this metric with the result of applying * the specified function to the success value of the effects that the aspect is * applied to. * * @since 2.0.0 * @category aspects */ <Type, In, Out, A>(metric: Metric<Type, In, Out>, f: (value: Types.NoInfer<A>) => In): <E, R>(self: Effect.Effect<A, E, R>) => Effect.Effect<A, E, R> /** * Returns an aspect that will update this metric with the result of applying * the specified function to the success value of the effects that the aspect is * applied to. * * @since 2.0.0 * @category aspects */ <A, E, R, Type, In, Out>( self: Effect.Effect<A, E, R>, metric: Metric<Type, In, Out>, f: (value: Types.NoInfer<A>) => In ): Effect.Effect<A, E, R>} = internal.trackSuccessWith
/** * Updates the metric with the specified update message. For example, if the * metric were a counter, the update would increment the method by the * provided amount. * * @since 2.0.0 * @category utils */export const update: { /** * Updates the metric with the specified update message. For example, if the * metric were a counter, the update would increment the method by the * provided amount. * * @since 2.0.0 * @category utils */ <In>(input: In): <Type, Out>(self: Metric<Type, In, Out>) => Effect.Effect<void> /** * Updates the metric with the specified update message. For example, if the * metric were a counter, the update would increment the method by the * provided amount. * * @since 2.0.0 * @category utils */ <Type, In, Out>(self: Metric<Type, In, Out>, input: In): Effect.Effect<void>} = internal.update
/** * Retrieves a snapshot of the value of the metric at this moment in time. * * @since 2.0.0 * @category getters */export const value: <Type, In, Out>(self: Metric<Type, In, Out>) => Effect.Effect<Out> = internal.value
/** * @since 2.0.0 * @category utils */export const withNow: <Type, In, Out>(self: Metric<Type, readonly [In, number], Out>) => Metric<Type, In, Out> = internal.withNow
/** * @since 2.0.0 * @category zipping */export const zip: { /** * @since 2.0.0 * @category zipping */ <Type2, In2, Out2>(that: Metric<Type2, In2, Out2>): <Type, In, Out>( self: Metric<Type, In, Out> ) => Metric< readonly [Type, Type2], // readonly because invariant readonly [In, In2], // readonly because contravariant [Out, Out2] > /** * @since 2.0.0 * @category zipping */ <Type, In, Out, Type2, In2, Out2>(self: Metric<Type, In, Out>, that: Metric<Type2, In2, Out2>): Metric< readonly [Type, Type2], // readonly because invariant readonly [In, In2], // readonly because contravariant [Out, Out2] >} = internal.zip
/** * Unsafely captures a snapshot of all metrics recorded by the application. * * @since 2.0.0 * @category unsafe */export const unsafeSnapshot: (_: void) => ReadonlyArray<MetricPair.MetricPair.Untyped> = internal.unsafeSnapshot
/** * @since 2.0.0 * @category metrics */export const fiberStarted: Metric.Counter<number> = fiberRuntime.fiberStarted
/** * @since 2.0.0 * @category metrics */export const fiberSuccesses: Metric.Counter<number> = fiberRuntime.fiberSuccesses
/** * @since 2.0.0 * @category metrics */export const fiberFailures: Metric.Counter<number> = fiberRuntime.fiberFailures
/** * @since 2.0.0 * @category metrics */export const fiberLifetimes: Metric<MetricKeyType.MetricKeyType.Histogram, number, MetricState.MetricState.Histogram> = fiberRuntime.fiberLifetimes
/** * @since 2.0.0 * @category metrics */export const fiberActive: Metric.Counter<number> = fiberRuntime.fiberActive123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262/** * @since 2.0.0 */import type * as Duration from "./Duration.js"import type * as Equal from "./Equal.js"import * as internal from "./internal/metric/keyType.js"import type * as MetricBoundaries from "./MetricBoundaries.js"import type * as MetricState from "./MetricState.js"import type { Pipeable } from "./Pipeable.js"import type * as Types from "./Types.js"
/** * @since 2.0.0 * @category symbols */export const MetricKeyTypeTypeId: unique symbol = internal.MetricKeyTypeTypeId
/** * @since 2.0.0 * @category symbols */export type MetricKeyTypeTypeId = typeof MetricKeyTypeTypeId
/** * @since 2.0.0 * @category symbols */export const CounterKeyTypeTypeId: unique symbol = internal.CounterKeyTypeTypeId
/** * @since 2.0.0 * @category symbols */export type CounterKeyTypeTypeId = typeof CounterKeyTypeTypeId
/** * @since 2.0.0 * @category symbols */export const FrequencyKeyTypeTypeId: unique symbol = internal.FrequencyKeyTypeTypeId
/** * @since 2.0.0 * @category symbols */export type FrequencyKeyTypeTypeId = typeof FrequencyKeyTypeTypeId
/** * @since 2.0.0 * @category symbols */export const GaugeKeyTypeTypeId: unique symbol = internal.GaugeKeyTypeTypeId
/** * @since 2.0.0 * @category symbols */export type GaugeKeyTypeTypeId = typeof GaugeKeyTypeTypeId
/** * @since 2.0.0 * @category symbols */export const HistogramKeyTypeTypeId: unique symbol = internal.HistogramKeyTypeTypeId
/** * @since 2.0.0 * @category symbols */export type HistogramKeyTypeTypeId = typeof HistogramKeyTypeTypeId
/** * @since 2.0.0 * @category symbols */export const SummaryKeyTypeTypeId: unique symbol = internal.SummaryKeyTypeTypeId
/** * @since 2.0.0 * @category symbols */export type SummaryKeyTypeTypeId = typeof SummaryKeyTypeTypeId
/** * @since 2.0.0 * @category modelz */export interface MetricKeyType<in In, out Out> extends MetricKeyType.Variance<In, Out>, Equal.Equal, Pipeable {}
/** * @since 2.0.0 */export declare namespace MetricKeyType { /** * @since 2.0.0 * @category models */ export type Untyped = MetricKeyType<any, any>
/** * @since 2.0.0 * @category models */ export type Counter<A extends (number | bigint)> = MetricKeyType<A, MetricState.MetricState.Counter<A>> & { readonly [CounterKeyTypeTypeId]: CounterKeyTypeTypeId readonly incremental: boolean readonly bigint: boolean }
/** * @since 2.0.0 * @category models */ export type Frequency = MetricKeyType<string, MetricState.MetricState.Frequency> & { readonly [FrequencyKeyTypeTypeId]: FrequencyKeyTypeTypeId readonly preregisteredWords: ReadonlyArray<string> }
/** * @since 2.0.0 * @category models */ export type Gauge<A extends (number | bigint)> = MetricKeyType<A, MetricState.MetricState.Gauge<A>> & { readonly [GaugeKeyTypeTypeId]: GaugeKeyTypeTypeId readonly bigint: boolean }
/** * @since 2.0.0 * @category models */ export type Histogram = MetricKeyType<number, MetricState.MetricState.Histogram> & { readonly [HistogramKeyTypeTypeId]: HistogramKeyTypeTypeId readonly boundaries: MetricBoundaries.MetricBoundaries }
/** * @since 2.0.0 * @category models */ export type Summary = MetricKeyType<readonly [number, number], MetricState.MetricState.Summary> & { readonly [SummaryKeyTypeTypeId]: SummaryKeyTypeTypeId readonly maxAge: Duration.Duration readonly maxSize: number readonly error: number readonly quantiles: ReadonlyArray<number> }
/** * @since 2.0.0 * @category models */ export interface Variance<in In, out Out> { readonly [MetricKeyTypeTypeId]: { readonly _In: Types.Contravariant<In> readonly _Out: Types.Covariant<Out> } }
/** * @since 2.0.0 * @category models */ export type InType<Type extends MetricKeyType<any, any>> = [Type] extends [ { readonly [MetricKeyTypeTypeId]: { readonly _In: (_: infer In) => void } } ] ? In : never
/** * @since 2.0.0 * @category models */ export type OutType<Type extends MetricKeyType<any, any>> = [Type] extends [ { readonly [MetricKeyTypeTypeId]: { readonly _Out: (_: never) => infer Out } } ] ? Out : never}
/** * @since 2.0.0 * @category constructors */export const counter: <A extends number | bigint>() => MetricKeyType.Counter<A> = internal.counter
/** * @since 2.0.0 * @category constructors */export const frequency: ( options?: { readonly preregisteredWords?: ReadonlyArray<string> | undefined } | undefined) => MetricKeyType.Frequency = internal.frequency
/** * @since 2.0.0 * @category constructors */export const gauge: <A extends number | bigint>() => MetricKeyType.Gauge<A> = internal.gauge
/** * @since 2.0.0 * @category constructors */export const histogram: (boundaries: MetricBoundaries.MetricBoundaries) => MetricKeyType.Histogram = internal.histogram
/** * @since 2.0.0 * @category constructors */export const summary: ( options: { readonly maxAge: Duration.DurationInput readonly maxSize: number readonly error: number readonly quantiles: ReadonlyArray<number> }) => MetricKeyType.Summary = internal.summary
/** * @since 2.0.0 * @category refinements */export const isMetricKeyType: (u: unknown) => u is MetricKeyType<unknown, unknown> = internal.isMetricKeyType
/** * @since 2.0.0 * @category refinements */export const isCounterKey: (u: unknown) => u is MetricKeyType.Counter<number | bigint> = internal.isCounterKey
/** * @since 2.0.0 * @category refinements */export const isFrequencyKey: (u: unknown) => u is MetricKeyType.Frequency = internal.isFrequencyKey
/** * @since 2.0.0 * @category refinements */export const isGaugeKey: (u: unknown) => u is MetricKeyType.Gauge<number | bigint> = internal.isGaugeKey
/** * @since 2.0.0 * @category refinements */export const isHistogramKey: (u: unknown) => u is MetricKeyType.Histogram = internal.isHistogramKey
/** * @since 2.0.0 * @category refinements */export const isSummaryKey: (u: unknown) => u is MetricKeyType.Summary = internal.isSummaryKey1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071/** * @since 2.0.0 */import * as internal from "./internal/metric/pair.js"import type * as MetricKey from "./MetricKey.js"import type * as MetricKeyType from "./MetricKeyType.js"import type * as MetricState from "./MetricState.js"import type { Pipeable } from "./Pipeable.js"import type * as Types from "./Types.js"
/** * @since 2.0.0 * @category symbols */export const MetricPairTypeId: unique symbol = internal.MetricPairTypeId
/** * @since 2.0.0 * @category symbols */export type MetricPairTypeId = typeof MetricPairTypeId
/** * @since 2.0.0 * @category model */export interface MetricPair<out Type extends MetricKeyType.MetricKeyType<any, any>> extends MetricPair.Variance<Type>, Pipeable{ readonly metricKey: MetricKey.MetricKey<Type> readonly metricState: MetricState.MetricState<MetricKeyType.MetricKeyType.OutType<Type>>}
/** * @since 2.0.0 */export declare namespace MetricPair { /** * @since 2.0.0 * @category models */ export interface Untyped extends MetricPair<MetricKeyType.MetricKeyType<any, any>> {}
/** * @since 2.0.0 * @category models */ export interface Variance<out Type extends MetricKeyType.MetricKeyType<any, any>> { readonly [MetricPairTypeId]: { readonly _Type: Types.Covariant<Type> } }}
/** * @since 2.0.0 * @category constructors */export const make: <Type extends MetricKeyType.MetricKeyType<any, any>>( metricKey: MetricKey.MetricKey<Type>, metricState: MetricState.MetricState<MetricKeyType.MetricKeyType.OutType<Type>>) => MetricPair.Untyped = internal.make
/** * @since 2.0.0 * @category unsafe */export const unsafeMake: <Type extends MetricKeyType.MetricKeyType<any, any>>( metricKey: MetricKey.MetricKey<Type>, metricState: MetricState.MetricState.Untyped) => MetricPair.Untyped = internal.unsafeMake123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182/** * @since 2.0.0 */import type * as Effect from "./Effect.js"import type * as Fiber from "./Fiber.js"import * as internal from "./internal/metric/polling.js"import type * as Metric from "./Metric.js"import type { Pipeable } from "./Pipeable.js"import type * as Schedule from "./Schedule.js"import type * as Scope from "./Scope.js"
/** * @since 2.0.0 * @category symbols */export const MetricPollingTypeId: unique symbol = internal.MetricPollingTypeId
/** * @since 2.0.0 * @category symbols */export type MetricPollingTypeId = typeof MetricPollingTypeId
/** * A `MetricPolling` is a combination of a metric and an effect that polls for * updates to the metric. * * @since 2.0.0 * @category models */export interface MetricPolling<in out Type, in out In, out R, out E, out Out> extends Pipeable { readonly [MetricPollingTypeId]: MetricPollingTypeId /** * The metric that this `MetricPolling` polls to update. */ readonly metric: Metric.Metric<Type, In, Out> /** * An effect that polls a value that may be fed to the metric. */ readonly poll: Effect.Effect<In, E, R>}
/** * Constructs a new polling metric from a metric and poll effect. * * @since 2.0.0 * @category constructors */export const make: <Type, In, Out, R, E>( metric: Metric.Metric<Type, In, Out>, poll: Effect.Effect<In, E, R>) => MetricPolling<Type, In, R, E, Out> = internal.make
/** * Collects all of the polling metrics into a single polling metric, which * polls for, updates, and produces the outputs of all individual metrics. * * @since 2.0.0 * @category constructors */export const collectAll: <R, E, Out>( iterable: Iterable<MetricPolling<any, any, R, E, Out>>) => MetricPolling<Array<any>, Array<any>, R, E, Array<Out>> = internal.collectAll
/** * Returns an effect that will launch the polling metric in a background * fiber, using the specified schedule. * * @since 2.0.0 * @category utils */export const launch: { /** * Returns an effect that will launch the polling metric in a background * fiber, using the specified schedule. * * @since 2.0.0 * @category utils */ <A2, R2>(schedule: Schedule.Schedule<A2, unknown, R2>): <Type, In, R, E, Out>( self: MetricPolling<Type, In, R, E, Out> ) => Effect.Effect<Fiber.Fiber<A2, E>, never, R2 | R | Scope.Scope> /** * Returns an effect that will launch the polling metric in a background * fiber, using the specified schedule. * * @since 2.0.0 * @category utils */ <Type, In, R, E, Out, A2, R2>( self: MetricPolling<Type, In, R, E, Out>, schedule: Schedule.Schedule<A2, unknown, R2> ): Effect.Effect<Fiber.Fiber<A2, E>, never, Scope.Scope | R | R2>} = internal.launch
/** * An effect that polls a value that may be fed to the metric. * * @since 2.0.0 * @category utils */export const poll: <Type, In, R, E, Out>(self: MetricPolling<Type, In, R, E, Out>) => Effect.Effect<In, E, R> = internal.poll
/** * An effect that polls for a value and uses the value to update the metric. * * @since 2.0.0 * @category utils */export const pollAndUpdate: <Type, In, R, E, Out>( self: MetricPolling<Type, In, R, E, Out>) => Effect.Effect<void, E, R> = internal.pollAndUpdate
/** * Returns a new polling metric whose poll function will be retried with the * specified retry policy. * * @since 2.0.0 * @category constructors */export const retry: { /** * Returns a new polling metric whose poll function will be retried with the * specified retry policy. * * @since 2.0.0 * @category constructors */ <X, E, R2>(policy: Schedule.Schedule<X, NoInfer<E>, R2>): <Type, In, R, Out>(self: MetricPolling<Type, In, R, E, Out>) => MetricPolling<Type, In, R2 | R, E, Out> /** * Returns a new polling metric whose poll function will be retried with the * specified retry policy. * * @since 2.0.0 * @category constructors */ <Type, In, R, E, Out, X, R2>( self: MetricPolling<Type, In, R, E, Out>, policy: Schedule.Schedule<X, E, R2> ): MetricPolling<Type, In, R | R2, E, Out>} = internal.retry
/** * Zips this polling metric with the specified polling metric. * * @since 2.0.0 * @category utils */export const zip: { /** * Zips this polling metric with the specified polling metric. * * @since 2.0.0 * @category utils */ <Type2, In2, R2, E2, Out2>(that: MetricPolling<Type2, In2, R2, E2, Out2>): <Type, In, R, E, Out>( self: MetricPolling<Type, In, R, E, Out> ) => MetricPolling< readonly [Type, Type2], // readonly because invariant readonly [In, In2], // readonly because contravariant R2 | R, E2 | E, [Out, Out2] > /** * Zips this polling metric with the specified polling metric. * * @since 2.0.0 * @category utils */ <Type, In, R, E, Out, Type2, In2, R2, E2, Out2>( self: MetricPolling<Type, In, R, E, Out>, that: MetricPolling<Type2, In2, R2, E2, Out2> ): MetricPolling< readonly [Type, Type2], // readonly because invariant readonly [In, In2], // readonly because contravariant R | R2, E | E2, [Out, Out2] >} = internal.zip123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273/** * @since 2.0.0 */import type * as Equal from "./Equal.js"import * as internal from "./internal/metric/state.js"import type * as MetricKeyType from "./MetricKeyType.js"import type * as Option from "./Option.js"import type { Pipeable } from "./Pipeable.js"import type * as Types from "./Types.js"
/** * @since 2.0.0 * @category symbols */export const MetricStateTypeId: unique symbol = internal.MetricStateTypeId
/** * @since 2.0.0 * @category symbols */export type MetricStateTypeId = typeof MetricStateTypeId
/** * @since 2.0.0 * @category symbols */export const CounterStateTypeId: unique symbol = internal.CounterStateTypeId
/** * @since 2.0.0 * @category symbols */export type CounterStateTypeId = typeof CounterStateTypeId
/** * @since 2.0.0 * @category symbols */export const FrequencyStateTypeId: unique symbol = internal.FrequencyStateTypeId
/** * @since 2.0.0 * @category symbols */export type FrequencyStateTypeId = typeof FrequencyStateTypeId
/** * @since 2.0.0 * @category symbols */export const GaugeStateTypeId: unique symbol = internal.GaugeStateTypeId
/** * @since 2.0.0 * @category symbols */export type GaugeStateTypeId = typeof GaugeStateTypeId
/** * @since 2.0.0 * @category symbols */export const HistogramStateTypeId: unique symbol = internal.HistogramStateTypeId
/** * @since 2.0.0 * @category symbols */export type HistogramStateTypeId = typeof HistogramStateTypeId
/** * @since 2.0.0 * @category symbols */export const SummaryStateTypeId: unique symbol = internal.SummaryStateTypeId
/** * @since 2.0.0 * @category symbols */export type SummaryStateTypeId = typeof SummaryStateTypeId
/** * A `MetricState` describes the state of a metric. The type parameter of a * metric state corresponds to the type of the metric key (`MetricStateType`). * This phantom type parameter is used to tie keys to their expected states. * * @since 2.0.0 * @category models */export interface MetricState<in A> extends MetricState.Variance<A>, Equal.Equal, Pipeable {}
/** * @since 2.0.0 */export declare namespace MetricState { /** * @since 2.0.0 * @category models */ export interface Untyped extends MetricState<any> {}
/** * @since 2.0.0 * @category models */ export interface Counter<in out A extends (number | bigint)> extends MetricState<MetricKeyType.MetricKeyType.Counter<A>> { readonly [CounterStateTypeId]: CounterStateTypeId readonly count: A }
/** * @since 2.0.0 * @category models */ export interface Frequency extends MetricState<MetricKeyType.MetricKeyType.Frequency> { readonly [FrequencyStateTypeId]: FrequencyStateTypeId readonly occurrences: ReadonlyMap<string, number> }
/** * @since 2.0.0 * @category models */ export interface Gauge<in out A extends (number | bigint)> extends MetricState<MetricKeyType.MetricKeyType.Gauge<A>> { readonly [GaugeStateTypeId]: GaugeStateTypeId readonly value: A }
/** * @since 2.0.0 * @category models */ export interface Histogram extends MetricState<MetricKeyType.MetricKeyType.Histogram> { readonly [HistogramStateTypeId]: HistogramStateTypeId readonly buckets: ReadonlyArray<readonly [number, number]> readonly count: number readonly min: number readonly max: number readonly sum: number }
/** * @since 2.0.0 * @category models */ export interface Summary extends MetricState<MetricKeyType.MetricKeyType.Summary> { readonly [SummaryStateTypeId]: SummaryStateTypeId readonly error: number readonly quantiles: ReadonlyArray<readonly [number, Option.Option<number>]> readonly count: number readonly min: number readonly max: number readonly sum: number }
/** * @since 2.0.0 * @category models */ export interface Variance<in A> { readonly [MetricStateTypeId]: { readonly _A: Types.Contravariant<A> } }}
/** * @since 2.0.0 * @category constructors */export const counter: { /** * @since 2.0.0 * @category constructors */ (count: number): MetricState.Counter<number> /** * @since 2.0.0 * @category constructors */ (count: bigint): MetricState.Counter<bigint>} = internal.counter
/** * @since 2.0.0 * @category constructors */export const frequency: (occurrences: ReadonlyMap<string, number>) => MetricState.Frequency = internal.frequency
/** * @since 2.0.0 * @category constructors */export const gauge: { /** * @since 2.0.0 * @category constructors */ (count: number): MetricState.Gauge<number> /** * @since 2.0.0 * @category constructors */ (count: bigint): MetricState.Gauge<bigint>} = internal.gauge
/** * @since 2.0.0 * @category constructors */export const histogram: ( options: { readonly buckets: ReadonlyArray<readonly [number, number]> readonly count: number readonly min: number readonly max: number readonly sum: number }) => MetricState.Histogram = internal.histogram
/** * @since 2.0.0 * @category constructors */export const summary: ( options: { readonly error: number readonly quantiles: ReadonlyArray<readonly [number, Option.Option<number>]> readonly count: number readonly min: number readonly max: number readonly sum: number }) => MetricState.Summary = internal.summary
/** * @since 2.0.0 * @category refinements */export const isMetricState: (u: unknown) => u is MetricState.Counter<number | bigint> = internal.isMetricState
/** * @since 2.0.0 * @category refinements */export const isCounterState: (u: unknown) => u is MetricState.Counter<number | bigint> = internal.isCounterState
/** * @since 2.0.0 * @category refinements */export const isFrequencyState: (u: unknown) => u is MetricState.Frequency = internal.isFrequencyState
/** * @since 2.0.0 * @category refinements */export const isGaugeState: (u: unknown) => u is MetricState.Gauge<number | bigint> = internal.isGaugeState
/** * @since 2.0.0 * @category refinements */export const isHistogramState: (u: unknown) => u is MetricState.Histogram = internal.isHistogramState
/** * @since 2.0.0 * @category refinements */export const isSummaryState: (u: unknown) => u is MetricState.Summary = internal.isSummaryState123456789101112131415161718/** * @since 2.0.0 * * Enables low level framework authors to run on their own isolated effect version */import * as internal from "./internal/version.js"
/** * @since 2.0.0 * @category version */export const getCurrentVersion: () => string = internal.getCurrentVersion
/** * @since 2.0.0 * @category version */export const setCurrentVersion: (version: string) => void = internal.setCurrentVersion123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518/** * @since 2.0.0 */import type { NonEmptyArray } from "./Array.js"import * as Equal from "./Equal.js"import { dual } from "./Function.js"import * as Hash from "./Hash.js"import { format, type Inspectable, NodeInspectSymbol, toJSON } from "./Inspectable.js"import * as Option from "./Option.js"import type { Pipeable } from "./Pipeable.js"import { pipeArguments } from "./Pipeable.js"
const TypeId: unique symbol = Symbol.for("effect/MutableHashMap") as TypeId
/** * @since 2.0.0 * @category symbol */export type TypeId = typeof TypeId
/** * @since 2.0.0 * @category models */export interface MutableHashMap<out K, out V> extends Iterable<[K, V]>, Pipeable, Inspectable { readonly [TypeId]: TypeId /** @internal */ readonly referential: Map<K, V> /** @internal */ readonly buckets: Map<number, NonEmptyArray<readonly [K & Equal.Equal, V]>> /** @internal */ bucketsSize: number}
const MutableHashMapProto: Omit<MutableHashMap<unknown, unknown>, "referential" | "buckets" | "bucketsSize"> = { [TypeId]: TypeId, [Symbol.iterator](this: MutableHashMap<unknown, unknown>): Iterator<[unknown, unknown]> { return new MutableHashMapIterator(this) }, toString() { return format(this.toJSON()) }, toJSON() { return { _id: "MutableHashMap", values: Array.from(this).map(toJSON) } }, [NodeInspectSymbol]() { return this.toJSON() }, pipe() { return pipeArguments(this, arguments) }}
class MutableHashMapIterator<K, V> implements IterableIterator<[K, V]> { readonly referentialIterator: Iterator<[K, V]> bucketIterator: Iterator<[K, V]> | undefined
constructor(readonly self: MutableHashMap<K, V>) { this.referentialIterator = self.referential[Symbol.iterator]() } next(): IteratorResult<[K, V]> { if (this.bucketIterator !== undefined) { return this.bucketIterator.next() } const result = this.referentialIterator.next() if (result.done) { this.bucketIterator = new BucketIterator(this.self.buckets.values()) return this.next() } return result }
[Symbol.iterator](): IterableIterator<[K, V]> { return new MutableHashMapIterator(this.self) }}
class BucketIterator<K, V> implements Iterator<[K, V]> { constructor(readonly backing: Iterator<NonEmptyArray<readonly [K, V]>>) {} currentBucket: Iterator<readonly [K, V]> | undefined next(): IteratorResult<[K, V]> { if (this.currentBucket === undefined) { const result = this.backing.next() if (result.done) { return result } this.currentBucket = result.value[Symbol.iterator]() } const result = this.currentBucket.next() if (result.done) { this.currentBucket = undefined return this.next() } return result as IteratorResult<[K, V]> }}
/** * @since 2.0.0 * @category constructors */export const empty = <K = never, V = never>(): MutableHashMap<K, V> => { const self = Object.create(MutableHashMapProto) self.referential = new Map() self.buckets = new Map() self.bucketsSize = 0 return self}
/** * @since 2.0.0 * @category constructors */export const make: <Entries extends Array<readonly [any, any]>>( ...entries: Entries) => MutableHashMap< Entries[number] extends readonly [infer K, any] ? K : never, Entries[number] extends readonly [any, infer V] ? V : never> = (...entries) => fromIterable(entries)
/** * Creates a new `MutableHashMap` from an iterable collection of key/value pairs. * * @since 2.0.0 * @category constructors */export const fromIterable = <K, V>(entries: Iterable<readonly [K, V]>): MutableHashMap<K, V> => { const self = empty<K, V>() for (const [key, value] of entries) { set(self, key, value) } return self}
/** * @since 2.0.0 * @category elements */export const get: { /** * @since 2.0.0 * @category elements */ <K>(key: K): <V>(self: MutableHashMap<K, V>) => Option.Option<V> /** * @since 2.0.0 * @category elements */ <K, V>(self: MutableHashMap<K, V>, key: K): Option.Option<V>} = dual< /** * @since 2.0.0 * @category elements */ <K>(key: K) => <V>(self: MutableHashMap<K, V>) => Option.Option<V>, /** * @since 2.0.0 * @category elements */ <K, V>(self: MutableHashMap<K, V>, key: K) => Option.Option<V>>(2, <K, V>(self: MutableHashMap<K, V>, key: K): Option.Option<V> => { if (Equal.isEqual(key) === false) { return self.referential.has(key) ? Option.some(self.referential.get(key)!) : Option.none() }
const hash = key[Hash.symbol]() const bucket = self.buckets.get(hash) if (bucket === undefined) { return Option.none() }
return getFromBucket(self, bucket, key)})
/** * @since 3.8.0 * @category elements */export const keys = <K, V>(self: MutableHashMap<K, V>): Array<K> => { const keys = Array.from(self.referential.keys()) for (const bucket of self.buckets.values()) { for (let i = 0, len = bucket.length; i < len; i++) { keys.push(bucket[i][0]) } } return keys}
/** * @since 3.8.0 * @category elements */export const values = <K, V>(self: MutableHashMap<K, V>): Array<V> => { const values = Array.from(self.referential.values()) for (const bucket of self.buckets.values()) { for (let i = 0, len = bucket.length; i < len; i++) { values.push(bucket[i][1]) } } return values}
const getFromBucket = <K, V>( self: MutableHashMap<K, V>, bucket: NonEmptyArray<readonly [K & Equal.Equal, V]>, key: K & Equal.Equal, remove = false): Option.Option<V> => { for (let i = 0, len = bucket.length; i < len; i++) { if (key[Equal.symbol](bucket[i][0])) { const value = bucket[i][1] if (remove) { bucket.splice(i, 1) self.bucketsSize-- } return Option.some(value) } }
return Option.none()}
/** * @since 2.0.0 * @category elements */export const has: { /** * @since 2.0.0 * @category elements */ <K>(key: K): <V>(self: MutableHashMap<K, V>) => boolean /** * @since 2.0.0 * @category elements */ <K, V>(self: MutableHashMap<K, V>, key: K): boolean} = dual< /** * @since 2.0.0 * @category elements */ <K>(key: K) => <V>(self: MutableHashMap<K, V>) => boolean, /** * @since 2.0.0 * @category elements */ <K, V>(self: MutableHashMap<K, V>, key: K) => boolean>(2, (self, key) => Option.isSome(get(self, key)))
/** * @since 2.0.0 */export const set: { /** * @since 2.0.0 */ <K, V>(key: K, value: V): (self: MutableHashMap<K, V>) => MutableHashMap<K, V> /** * @since 2.0.0 */ <K, V>(self: MutableHashMap<K, V>, key: K, value: V): MutableHashMap<K, V>} = dual< /** * @since 2.0.0 */ <K, V>(key: K, value: V) => (self: MutableHashMap<K, V>) => MutableHashMap<K, V>, /** * @since 2.0.0 */ <K, V>(self: MutableHashMap<K, V>, key: K, value: V) => MutableHashMap<K, V>>(3, <K, V>(self: MutableHashMap<K, V>, key: K, value: V) => { if (Equal.isEqual(key) === false) { self.referential.set(key, value) return self }
const hash = key[Hash.symbol]() const bucket = self.buckets.get(hash) if (bucket === undefined) { self.buckets.set(hash, [[key, value]]) self.bucketsSize++ return self }
removeFromBucket(self, bucket, key) bucket.push([key, value]) self.bucketsSize++ return self})
const removeFromBucket = <K, V>( self: MutableHashMap<K, V>, bucket: NonEmptyArray<readonly [K & Equal.Equal, V]>, key: K & Equal.Equal) => { for (let i = 0, len = bucket.length; i < len; i++) { if (key[Equal.symbol](bucket[i][0])) { bucket.splice(i, 1) self.bucketsSize-- return } }}
/** * Updates the value of the specified key within the `MutableHashMap` if it exists. * * @since 2.0.0 */export const modify: { /** * Updates the value of the specified key within the `MutableHashMap` if it exists. * * @since 2.0.0 */ <K, V>(key: K, f: (v: V) => V): (self: MutableHashMap<K, V>) => MutableHashMap<K, V> /** * Updates the value of the specified key within the `MutableHashMap` if it exists. * * @since 2.0.0 */ <K, V>(self: MutableHashMap<K, V>, key: K, f: (v: V) => V): MutableHashMap<K, V>} = dual< /** * Updates the value of the specified key within the `MutableHashMap` if it exists. * * @since 2.0.0 */ <K, V>(key: K, f: (v: V) => V) => (self: MutableHashMap<K, V>) => MutableHashMap<K, V>, /** * Updates the value of the specified key within the `MutableHashMap` if it exists. * * @since 2.0.0 */ <K, V>(self: MutableHashMap<K, V>, key: K, f: (v: V) => V) => MutableHashMap<K, V>>(3, <K, V>(self: MutableHashMap<K, V>, key: K, f: (v: V) => V) => { if (Equal.isEqual(key) === false) { if (self.referential.has(key)) { self.referential.set(key, f(self.referential.get(key)!)) } return self }
const hash = key[Hash.symbol]() const bucket = self.buckets.get(hash) if (bucket === undefined) { return self }
const value = getFromBucket(self, bucket, key, true) if (Option.isNone(value)) { return self } bucket.push([key, f(value.value)]) self.bucketsSize++ return self})
/** * Set or remove the specified key in the `MutableHashMap` using the specified * update function. * * @since 2.0.0 */export const modifyAt: { /** * Set or remove the specified key in the `MutableHashMap` using the specified * update function. * * @since 2.0.0 */ <K, V>(key: K, f: (value: Option.Option<V>) => Option.Option<V>): (self: MutableHashMap<K, V>) => MutableHashMap<K, V> /** * Set or remove the specified key in the `MutableHashMap` using the specified * update function. * * @since 2.0.0 */ <K, V>( self: MutableHashMap<K, V>, key: K, f: (value: Option.Option<V>) => Option.Option<V> ): MutableHashMap<K, V>} = dual< /** * Set or remove the specified key in the `MutableHashMap` using the specified * update function. * * @since 2.0.0 */ <K, V>(key: K, f: (value: Option.Option<V>) => Option.Option<V>) => (self: MutableHashMap<K, V>) => MutableHashMap<K, V>, /** * Set or remove the specified key in the `MutableHashMap` using the specified * update function. * * @since 2.0.0 */ <K, V>( self: MutableHashMap<K, V>, key: K, f: (value: Option.Option<V>) => Option.Option<V> ) => MutableHashMap<K, V>>(3, (self, key, f) => { if (Equal.isEqual(key) === false) { const result = f(get(self, key)) if (Option.isSome(result)) { set(self, key, result.value) } else { remove(self, key) } return self }
const hash = key[Hash.symbol]() const bucket = self.buckets.get(hash) if (bucket === undefined) { const result = f(Option.none()) return Option.isSome(result) ? set(self, key, result.value) : self }
const result = f(getFromBucket(self, bucket, key, true)) if (Option.isNone(result)) { if (bucket.length === 0) { self.buckets.delete(hash) } return self } bucket.push([key, result.value]) self.bucketsSize++ return self})
/** * @since 2.0.0 */export const remove: { /** * @since 2.0.0 */ <K>(key: K): <V>(self: MutableHashMap<K, V>) => MutableHashMap<K, V> /** * @since 2.0.0 */ <K, V>(self: MutableHashMap<K, V>, key: K): MutableHashMap<K, V>} = dual< /** * @since 2.0.0 */ <K>(key: K) => <V>(self: MutableHashMap<K, V>) => MutableHashMap<K, V>, /** * @since 2.0.0 */ <K, V>(self: MutableHashMap<K, V>, key: K) => MutableHashMap<K, V>>(2, <K, V>(self: MutableHashMap<K, V>, key: K) => { if (Equal.isEqual(key) === false) { self.referential.delete(key) return self }
const hash = key[Hash.symbol]() const bucket = self.buckets.get(hash) if (bucket === undefined) { return self } removeFromBucket(self, bucket, key) if (bucket.length === 0) { self.buckets.delete(hash) } return self})
/** * @since 2.0.0 */export const clear = <K, V>(self: MutableHashMap<K, V>) => { self.referential.clear() self.buckets.clear() self.bucketsSize = 0 return self}
/** * @since 2.0.0 * @category elements */export const size = <K, V>(self: MutableHashMap<K, V>): number => { return self.referential.size + self.bucketsSize}
/** * @since 2.0.0 */export const isEmpty = <K, V>(self: MutableHashMap<K, V>): boolean => size(self) === 0
/** * @since 2.0.0 */export const forEach: { /** * @since 2.0.0 */ <K, V>(f: (value: V, key: K) => void): (self: MutableHashMap<K, V>) => void /** * @since 2.0.0 */ <K, V>(self: MutableHashMap<K, V>, f: (value: V, key: K) => void): void} = dual(2, <K, V>(self: MutableHashMap<K, V>, f: (value: V, key: K) => void) => { self.referential.forEach(f) for (const bucket of self.buckets.values()) { for (const [key, value] of bucket) { f(value, key) } }})1234567891011121314151617181920212223242526272829303132/** * @since 2.0.0 */
/** * @category symbol * @since 2.0.0 */export declare const nonEmpty: unique symbol
/** * @category model * @since 2.0.0 */export interface NonEmptyIterable<out A> extends Iterable<A> { readonly [nonEmpty]: A}
/** * @category getters * @since 2.0.0 */export const unprepend = <A>(self: NonEmptyIterable<A>): [firstElement: A, remainingElements: Iterator<A>] => { const iterator = self[Symbol.iterator]() const next = iterator.next() if (next.done) { throw new Error( "BUG: NonEmptyIterator should not be empty - please report an issue at https://github.com/Effect-TS/effect/issues" ) } return [next.value, iterator]}backend/node_modules/effect/src/Arbitrary.tsAdded+1101
backend/node_modules/effect/src/BigInt.tsAdded+1139
backend/node_modules/effect/src/Boolean.tsAdded+560
backend/node_modules/effect/src/Cache.tsAdded+281
backend/node_modules/effect/src/Cause.tsAdded+2049
backend/node_modules/effect/src/Channel.tsAdded
backend/node_modules/effect/src/ChildExecutorDecision.tsAdded+158
backend/node_modules/effect/src/Chunk.tsAdded+2350
backend/node_modules/effect/src/Clock.tsAdded+111
backend/node_modules/effect/src/Config.tsAdded+743
backend/node_modules/effect/src/ConfigError.tsAdded+286
backend/node_modules/effect/src/ConfigProviderPathPatch.tsAdded+132
backend/node_modules/effect/src/Context.tsAdded+867
backend/node_modules/effect/src/Cron.tsAdded+848
backend/node_modules/effect/src/DefaultServices.tsAdded+34
backend/node_modules/effect/src/Deferred.tsAdded+471
backend/node_modules/effect/src/Differ.tsAdded+512
backend/node_modules/effect/src/Duration.tsAdded+1140
backend/node_modules/effect/src/Effectable.tsAdded+107
backend/node_modules/effect/src/Encoding.tsAdded+195
backend/node_modules/effect/src/Equal.tsAdded+101
backend/node_modules/effect/src/ExecutionPlan.tsAdded+308
backend/node_modules/effect/src/ExecutionStrategy.tsAdded+138
backend/node_modules/effect/src/FiberHandle.tsAdded+582
backend/node_modules/effect/src/FiberId.tsAdded+219
backend/node_modules/effect/src/FiberMap.tsAdded+779
backend/node_modules/effect/src/FiberRef.tsAdded+511
backend/node_modules/effect/src/Graph.tsAdded
backend/node_modules/effect/src/Hash.tsAdded+203
backend/node_modules/effect/src/HashRing.tsAdded+387
backend/node_modules/effect/src/HashSet.tsAdded+2346
backend/node_modules/effect/src/KeyedPool.tsAdded+201
backend/node_modules/effect/src/Layer.tsAdded+1723
backend/node_modules/effect/src/List.tsAdded+1469
backend/node_modules/effect/src/LogLevel.tsAdded+387
backend/node_modules/effect/src/Logger.tsAdded+863
backend/node_modules/effect/src/Mailbox.tsAdded+298
backend/node_modules/effect/src/ManagedRuntime.tsAdded+180
backend/node_modules/effect/src/MergeDecision.tsAdded+103
backend/node_modules/effect/src/MergeState.tsAdded+180
backend/node_modules/effect/src/MergeStrategy.tsAdded+124
backend/node_modules/effect/src/Metric.tsAdded+1165
backend/node_modules/effect/src/MetricKeyType.tsAdded+262
backend/node_modules/effect/src/MetricPair.tsAdded+71
backend/node_modules/effect/src/MetricPolling.tsAdded+182
backend/node_modules/effect/src/MetricState.tsAdded+273
backend/node_modules/effect/src/Micro.tsAdded
backend/node_modules/effect/src/ModuleVersion.tsAdded+18
backend/node_modules/effect/src/MutableHashMap.tsAdded+518
backend/node_modules/effect/src/NonEmptyIterable.tsAdded+32