diff --git a/.opencode/node_modules/effect/src/Brand.ts b/.opencode/node_modules/effect/src/Brand.ts index 70ec43116e1b3b492fdc7ece28a31e5f594a9b11..39789b23af19651a21bf8bc1682c89a2d3487230 100644 --- a/.opencode/node_modules/effect/src/Brand.ts +++ b/.opencode/node_modules/effect/src/Brand.ts @@ -1,7 +1,9 @@ /** - * This module provides types and utility functions to create and work with - * branded types, which are TypeScript types with an added type tag to prevent - * accidental usage of a value in the wrong context. + * The `Brand` module adds compile-time names to ordinary TypeScript values so + * structurally identical values cannot be mixed accidentally. A branded value + * has the same runtime representation as its unbranded value; the extra + * information lives in the type system unless you choose a validating + * constructor. * * @since 2.0.0 */ @@ -9,8 +11,8 @@ import * as Arr from "./Array.ts" import * as Option from "./Option.ts" import * as Result from "./Result.ts" import type * as Schema from "./Schema.ts" -import * as AST from "./SchemaAST.ts" -import type * as Issue from "./SchemaIssue.ts" +import * as SchemaAST from "./SchemaAST.ts" +import type * as SchemaIssue from "./SchemaIssue.ts" import type * as Types from "./Types.ts" const TypeId = "~effect/Brand" @@ -18,8 +20,17 @@ const TypeId = "~effect/Brand" /** * A generic interface that defines a branded type. * - * @since 2.0.0 + * **When to use** + * + * Use to define a branded type such as `number & Brand<"Positive">` when + * TypeScript should keep structurally identical values separate without + * changing their runtime value. + * + * @see {@link Branded} for applying a brand key to a base type + * @see {@link Constructor} for validating or constructing branded values + * * @category models + * @since 2.0.0 */ export interface Brand { readonly [TypeId]: { @@ -31,6 +42,17 @@ export interface Brand { * A constructor for a branded type that provides validation and safe * construction methods. * + * **When to use** + * + * Use as the shared callable interface for branded values when an API accepts + * or returns a brand constructor and callers need throwing, `Option`, `Result`, + * or type-guard validation forms. + * + * @see {@link nominal} for a constructor without runtime validation + * @see {@link make} for creating a constructor from a validation predicate + * @see {@link check} for creating a constructor from schema checks + * @see {@link all} for combining brand constructors + * * @category models * @since 2.0.0 */ @@ -62,39 +84,58 @@ export interface Constructor> { * * @internal */ - checks?: readonly [AST.Check>, ...Array>>] | undefined + checks?: readonly [SchemaAST.Check>, ...Array>>] | undefined } /** - * A `BrandError` is returned when a branded type is constructed from an invalid - * value. + * Error returned when a branded type is constructed from an invalid value. * - * @category models + * **Details** + * + * The error wraps a `SchemaIssue.Issue`, exposes `message` through + * `issue.toString()`, and formats as `BrandError()`. + * + * **Gotchas** + * + * `BrandError` is an error-like model with `_tag`, `name`, `message`, and + * `toString`; it does not extend JavaScript `Error`. + * + * @category errors * @since 4.0.0 */ export class BrandError { - constructor(issue: Issue.Issue) { + constructor(issue: SchemaIssue.Issue) { this.issue = issue } /** + * Discriminant used to identify brand construction failures. + * * @since 4.0.0 */ readonly _tag = "BrandError" /** + * Error name used by tools that inspect JavaScript error-like objects. + * * @since 4.0.0 */ readonly name: string = "BrandError" /** + * Schema issue describing why brand validation failed. + * * @since 4.0.0 */ - readonly issue: Issue.Issue + readonly issue: SchemaIssue.Issue /** + * Human-readable rendering of the validation issue. + * * @since 4.0.0 */ get message() { return this.issue.toString() } /** + * Formats the brand error together with its validation message. + * * @since 4.0.0 */ toString() { @@ -103,12 +144,16 @@ export class BrandError { } /** + * Namespace containing type-level helpers for working with branded types and + * brand constructors. + * * @since 2.0.0 */ export declare namespace Brand { /** * A utility type to extract a branded type from a `Constructor`. * + * @category utility types * @since 2.0.0 */ export type FromConstructor = C extends Constructor ? B : never @@ -116,6 +161,7 @@ export declare namespace Brand { /** * A utility type to extract the unbranded value type from a brand. * + * @category utility types * @since 2.0.0 */ export type Unbranded> = B extends infer U & Brands ? U : B @@ -123,13 +169,15 @@ export declare namespace Brand { /** * A utility type to extract the keys of a branded type. * - * @since 2.0.0 + * @category utility types + * @since 4.0.0 */ export type Keys> = keyof B[typeof TypeId] /** * A utility type to extract the brands from a branded type. * + * @category utility types * @since 2.0.0 */ export type Brands> = Types.UnionToIntersection< @@ -139,6 +187,7 @@ export declare namespace Brand { /** * A utility type that checks that all brands have the same base type. * + * @category utility types * @since 2.0.0 */ export type EnsureCommonBase< @@ -156,19 +205,22 @@ export declare namespace Brand { /** * A type alias for creating branded types more concisely. * - * @category alias + * @category utility types * @since 2.0.0 */ export type Branded = A & Brand /** - * This function returns a `Constructor` that **does not apply any runtime - * checks**, it just returns the provided value. It can be used to create - * nominal types that allow distinguishing between two values of the same type - * but with different meanings. + * Returns a `Constructor` that **does not apply any runtime checks** and just + * returns the provided value. + * + * **When to use** * - * If you also want to perform some validation, see {@link make} or - * {@link check} or {@link refine}. + * Use to create nominal types that allow distinguishing between two values + * of the same type but with different meanings. + * + * @see {@link make} for constructing branded values with validation. + * @see {@link check} for constructing branded values from schema checks. * * @category constructors * @since 2.0.0 @@ -182,33 +234,51 @@ export function nominal>(): Constructor { } /** - * Returns a `Constructor` that can construct a branded type from an - * unbranded value using the provided `filter` predicate as validation of - * the input data. + * Returns a `Constructor` that can construct a branded type from an unbranded + * value using the provided `filter` predicate as validation of the input data. + * + * **When to use** * - * If you don't want to perform any validation but only distinguish between two - * values of the same type but with different meanings, see {@link nominal}. + * Use when you want validation while constructing the branded type. + * + * @see {@link nominal} for a brand constructor that performs no validation. * * @category constructors - * @since 2.0.0 + * @since 4.0.0 */ export function make>( filter: (unbranded: Brand.Unbranded) => Schema.FilterOutput ): Constructor { - return check(AST.makeFilter(filter)) + return check(SchemaAST.makeFilter(filter)) } /** + * Creates a branded type `Constructor` from one or more schema checks. + * + * **When to use** + * + * Use when you need a branded type constructor that performs runtime validation + * via schema checks. + * + * **Details** + * + * Calling the returned constructor validates the unbranded value and throws on + * failure. Use the returned `option`, `result`, or `is` methods for + * non-throwing validation. + * + * @see {@link nominal} for a brand constructor without runtime validation + * @see {@link all} for combining multiple brand constructors + * @category constructors * @since 4.0.0 */ export function check>( ...checks: readonly [ - AST.Check>, - ...Array>> + SchemaAST.Check>, + ...Array>> ] ): Constructor { const result = (input: Brand.Unbranded): Result.Result => { - return Result.mapError(AST.runChecks(checks, input), (issue) => new BrandError(issue)) as any + return Result.mapError(SchemaAST.runChecks(checks, input), (issue) => new BrandError(issue)) as any } return Object.assign((input: Brand.Unbranded) => Result.getOrThrow(result(input)), { option: (input: Brand.Unbranded) => Option.getSuccess(result(input)), @@ -219,9 +289,18 @@ export function check>( } /** - * Combines two or more brands together to form a single branded type. This API - * is useful when you want to validate that the input data passes multiple brand - * validators. + * Combines one or more brand constructors to form a single branded type. + * + * **When to use** + * + * Use to require an input to satisfy every runtime check collected by the + * provided brand constructors. + * + * **Details** + * + * If the provided constructors contain runtime checks, the combined + * constructor succeeds only when all checks pass. If no runtime checks are + * present, it behaves as a nominal constructor. * * @category combining * @since 2.0.0 diff --git a/.opencode/node_modules/effect/src/Cache.ts b/.opencode/node_modules/effect/src/Cache.ts index 4e812d160eb412678bcec1bbf55f9533848ebb4e..7d6347fdf2afed39a240eca68d20689b12a31cf4 100644 --- a/.opencode/node_modules/effect/src/Cache.ts +++ b/.opencode/node_modules/effect/src/Cache.ts @@ -1,4 +1,11 @@ /** + * Caches values loaded by an Effect lookup function. + * + * A cache stores successful and failed lookup results, shares an in-progress + * lookup when multiple callers request the same missing key, and limits entries + * by capacity and optional time-to-live rules. This module includes helpers for + * reading, setting, refreshing, invalidating, and inspecting cache contents. + * * @since 4.0.0 */ import * as Context from "./Context.ts" @@ -24,7 +31,8 @@ const TypeId = "~effect/Cache" * A cache interface that provides a mutable key-value store with automatic TTL management, * capacity limits, and lookup functions for cache misses. * - * @example + * **Example** (Creating a basic cache) + * * ```ts * import { Cache, Effect } from "effect" * @@ -44,7 +52,8 @@ const TypeId = "~effect/Cache" * }) * ``` * - * @example + * **Example** (Handling lookup failures) + * * ```ts * import { Cache, Effect } from "effect" * @@ -66,7 +75,8 @@ const TypeId = "~effect/Cache" * }) * ``` * - * @example + * **Example** (Using complex keys with TTL) + * * ```ts * import { Cache, Data, Duration, Effect } from "effect" * @@ -87,8 +97,8 @@ const TypeId = "~effect/Cache" * }) * ``` * - * @since 4.0.0 - * @category Models + * @category models + * @since 2.0.0 */ export interface Cache extends Pipeable { readonly [TypeId]: typeof TypeId @@ -99,11 +109,23 @@ export interface Cache ex } /** - * Represents a cache entry containing a deferred value and optional expiration time. - * This is used internally by the cache implementation to track cached values and their lifetimes. + * Represents a low-level cache entry containing a deferred lookup result and + * an optional expiration timestamp. + * + * **When to use** + * + * Use when inspecting a `Cache`'s low-level map and you need the stored + * deferred lookup result or expiration timestamp for a key. + * + * **Details** * + * An `expiresAt` value of `undefined` means the entry does not expire. + * + * @see {@link Cache} for the public cache API that manages entries through + * combinators + * + * @category models * @since 4.0.0 - * @category Models */ export interface Entry { expiresAt: number | undefined @@ -113,10 +135,18 @@ export interface Entry { /** * Creates a cache with dynamic time-to-live based on the result and key. * + * **When to use** + * + * Use when you need different cache entry lifetimes based on the lookup result + * or key characteristics. + * + * **Details** + * * The timeToLive function receives both the exit result and the key, allowing * for flexible TTL policies based on success/failure state and key characteristics. * - * @example + * **Example** (Using dynamic time to live) + * * ```ts * import { Cache, Effect, Exit } from "effect" * @@ -140,8 +170,9 @@ export interface Entry { * }) * ``` * - * @since 4.0.0 - * @category Constructors + * @see {@link make} for a simpler cache constructor with a fixed time-to-live for all entries + * @category constructors + * @since 2.0.0 */ export const makeWith = < Key, @@ -176,10 +207,13 @@ export const makeWith = < /** * Creates a cache with a fixed time-to-live for all entries. * + * **Details** + * * This is the basic cache constructor where all entries share the same TTL. * The lookup function will be called when a key is not found or has expired. * - * @example + * **Example** (Creating a basic cache) + * * ```ts * import { Cache, Effect } from "effect" * @@ -196,12 +230,17 @@ export const makeWith = < * }) * ``` * - * @example + * **Example** (Creating a cache with TTL) + * * ```ts * import { Cache, Effect } from "effect" * - * // Cache with TTL and async lookup - * const fetchUserCache = Effect.gen(function*() { + * const program = Effect.gen(function*() { + * const users = new Map([ + * [123, { name: "Ada", email: "ada@example.com" }], + * [456, { name: "Grace", email: "grace@example.com" }] + * ]) + * * const cache = yield* Cache.make< * number, * { name: string; email: string }, @@ -209,22 +248,25 @@ export const makeWith = < * >({ * capacity: 500, * lookup: (userId) => - * Effect.tryPromise({ - * try: () => fetch(`/api/users/${userId}`).then((r) => r.json()), - * catch: () => "Failed to fetch user" + * Effect.suspend(() => { + * const user = users.get(userId) + * return user === undefined + * ? Effect.fail(`User ${userId} not found`) + * : Effect.succeed(user) * }), * timeToLive: "15 minutes" * }) * - * // First call fetches from API, second call returns cached result * const user1 = yield* Cache.get(cache, 123) - * const user2 = yield* Cache.get(cache, 123) // From cache - * return { user1, user2 } + * console.log(user1) // { name: "Ada", email: "ada@example.com" } + * + * const user2 = yield* Cache.get(cache, 123) + * console.log(user2) // { name: "Ada", email: "ada@example.com" } * }) * ``` * - * @since 4.0.0 - * @category Constructors + * @category constructors + * @since 2.0.0 */ export const make = < Key, @@ -264,12 +306,17 @@ const Proto = { const defaultTimeToLive = (_: Exit.Exit, _key: unknown): Duration.Duration => Duration.infinity /** - * Retrieves the value associated with the specified key from the cache. + * Retrieves the value for a key, invoking the lookup function on a cache miss + * or expired entry. + * + * **Details** * - * If the key is not present or has expired, it will invoke the lookup function - * to construct the value, store it in the cache, and return it. + * Concurrent `get` calls for the same missing key share the same pending + * lookup. The cache stores the lookup `Exit`, so failed lookups are cached and + * will fail again until the entry expires, is invalidated, or is refreshed. + * + * **Example** (Getting cached values) * - * @example * ```ts * import { Cache, Effect } from "effect" * @@ -291,7 +338,8 @@ const defaultTimeToLive = (_: Exit.Exit, _key: unknown): Duration.Du * }) * ``` * - * @example + * **Example** (Handling lookup failures) + * * ```ts * import { Cache, Effect } from "effect" * @@ -315,7 +363,8 @@ const defaultTimeToLive = (_: Exit.Exit, _key: unknown): Duration.Du * }) * ``` * - * @example + * **Example** (Sharing concurrent lookups) + * * ```ts * import { Cache, Effect } from "effect" * @@ -343,17 +392,22 @@ const defaultTimeToLive = (_: Exit.Exit, _key: unknown): Duration.Du * }) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ export const get: { /** - * Retrieves the value associated with the specified key from the cache. + * Retrieves the value for a key, invoking the lookup function on a cache miss + * or expired entry. + * + * **Details** * - * If the key is not present or has expired, it will invoke the lookup function - * to construct the value, store it in the cache, and return it. + * Concurrent `get` calls for the same missing key share the same pending + * lookup. The cache stores the lookup `Exit`, so failed lookups are cached and + * will fail again until the entry expires, is invalidated, or is refreshed. + * + * **Example** (Getting cached values) * - * @example * ```ts * import { Cache, Effect } from "effect" * @@ -375,7 +429,8 @@ export const get: { * }) * ``` * - * @example + * **Example** (Handling lookup failures) + * * ```ts * import { Cache, Effect } from "effect" * @@ -399,7 +454,8 @@ export const get: { * }) * ``` * - * @example + * **Example** (Sharing concurrent lookups) + * * ```ts * import { Cache, Effect } from "effect" * @@ -427,17 +483,22 @@ export const get: { * }) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ (key: Key): (self: Cache) => Effect.Effect /** - * Retrieves the value associated with the specified key from the cache. + * Retrieves the value for a key, invoking the lookup function on a cache miss + * or expired entry. + * + * **Details** * - * If the key is not present or has expired, it will invoke the lookup function - * to construct the value, store it in the cache, and return it. + * Concurrent `get` calls for the same missing key share the same pending + * lookup. The cache stores the lookup `Exit`, so failed lookups are cached and + * will fail again until the entry expires, is invalidated, or is refreshed. + * + * **Example** (Getting cached values) * - * @example * ```ts * import { Cache, Effect } from "effect" * @@ -459,7 +520,8 @@ export const get: { * }) * ``` * - * @example + * **Example** (Handling lookup failures) + * * ```ts * import { Cache, Effect } from "effect" * @@ -483,7 +545,8 @@ export const get: { * }) * ``` * - * @example + * **Example** (Sharing concurrent lookups) + * * ```ts * import { Cache, Effect } from "effect" * @@ -511,8 +574,8 @@ export const get: { * }) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ (self: Cache, key: Key): Effect.Effect } = dual( @@ -527,12 +590,17 @@ export const get: { return Deferred.await(oentry.value.deferred) } const deferred = Deferred.makeUnsafe() const entry: Entry = { @@ -733,14 +810,17 @@ const checkCapacity = (self: Cache) => { } /** - * Retrieves the value associated with the specified key from the cache, - * returning an `Option` that is `Some` if the key exists and has not expired, - * or `None` if the key does not exist or has expired. + * Reads an existing cache entry without invoking the lookup function. * - * Unlike `get`, this function will not invoke the lookup function if the key - * is missing or expired. + * **Details** + * + * Returns `Option.none()` when the key is missing or expired, and `Option.some` + * when a cached lookup has succeeded. If the entry is still pending, waits for + * it to complete. If the cached or pending lookup fails, this effect fails with + * the same error. + * + * **Example** (Reading cached values without lookup) * - * @example * ```ts * import { Cache, Effect } from "effect" * @@ -765,7 +845,8 @@ const checkCapacity = (self: Cache) => { * }) * ``` * - * @example + * **Example** (Skipping expired entries) + * * ```ts * import { Cache, Effect } from "effect" * import { TestClock } from "effect/testing" @@ -794,7 +875,8 @@ const checkCapacity = (self: Cache) => { * }) * ``` * - * @example + * **Example** (Waiting for pending lookups) + * * ```ts * import { Cache, Deferred, Effect, Fiber } from "effect" * @@ -817,22 +899,28 @@ const checkCapacity = (self: Cache) => { * * const result = yield* Fiber.join(optionFiber) * console.log(result) // Option.some(42) + * + * const value = yield* Fiber.join(getFiber) + * console.log(value) // 42 * }) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ export const getOption: { /** - * Retrieves the value associated with the specified key from the cache, - * returning an `Option` that is `Some` if the key exists and has not expired, - * or `None` if the key does not exist or has expired. + * Reads an existing cache entry without invoking the lookup function. + * + * **Details** * - * Unlike `get`, this function will not invoke the lookup function if the key - * is missing or expired. + * Returns `Option.none()` when the key is missing or expired, and `Option.some` + * when a cached lookup has succeeded. If the entry is still pending, waits for + * it to complete. If the cached or pending lookup fails, this effect fails with + * the same error. + * + * **Example** (Reading cached values without lookup) * - * @example * ```ts * import { Cache, Effect } from "effect" * @@ -857,7 +945,8 @@ export const getOption: { * }) * ``` * - * @example + * **Example** (Skipping expired entries) + * * ```ts * import { Cache, Effect } from "effect" * import { TestClock } from "effect/testing" @@ -886,7 +975,8 @@ export const getOption: { * }) * ``` * - * @example + * **Example** (Waiting for pending lookups) + * * ```ts * import { Cache, Deferred, Effect, Fiber } from "effect" * @@ -909,22 +999,28 @@ export const getOption: { * * const result = yield* Fiber.join(optionFiber) * console.log(result) // Option.some(42) + * + * const value = yield* Fiber.join(getFiber) + * console.log(value) // 42 * }) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ (key: Key): (self: Cache) => Effect.Effect, E> /** - * Retrieves the value associated with the specified key from the cache, - * returning an `Option` that is `Some` if the key exists and has not expired, - * or `None` if the key does not exist or has expired. + * Reads an existing cache entry without invoking the lookup function. + * + * **Details** * - * Unlike `get`, this function will not invoke the lookup function if the key - * is missing or expired. + * Returns `Option.none()` when the key is missing or expired, and `Option.some` + * when a cached lookup has succeeded. If the entry is still pending, waits for + * it to complete. If the cached or pending lookup fails, this effect fails with + * the same error. + * + * **Example** (Reading cached values without lookup) * - * @example * ```ts * import { Cache, Effect } from "effect" * @@ -949,7 +1045,8 @@ export const getOption: { * }) * ``` * - * @example + * **Example** (Skipping expired entries) + * * ```ts * import { Cache, Effect } from "effect" * import { TestClock } from "effect/testing" @@ -978,7 +1075,8 @@ export const getOption: { * }) * ``` * - * @example + * **Example** (Waiting for pending lookups) + * * ```ts * import { Cache, Deferred, Effect, Fiber } from "effect" * @@ -1001,11 +1099,14 @@ export const getOption: { * * const result = yield* Fiber.join(optionFiber) * console.log(result) // Option.some(42) + * + * const value = yield* Fiber.join(getFiber) + * console.log(value) // 42 * }) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ (self: Cache, key: Key): Effect.Effect, E> } = dual( @@ -1040,24 +1141,51 @@ const getImpl = ( * Retrieves the value associated with the specified key from the cache, only if * it contains a resolved successful value. * + * **Details** + * + * This checks only an existing non-expired entry. It returns `Option.some` when + * the entry has already resolved successfully, and `Option.none` for missing, + * expired, failed, or still-pending entries. + * + * @see {@link get} for triggering or awaiting the cache lookup + * @see {@link getOption} for reading an existing entry as an optional effect + * + * @category combinators * @since 4.0.0 - * @category Combinators */ export const getSuccess: { /** * Retrieves the value associated with the specified key from the cache, only if * it contains a resolved successful value. * + * **Details** + * + * This checks only an existing non-expired entry. It returns `Option.some` when + * the entry has already resolved successfully, and `Option.none` for missing, + * expired, failed, or still-pending entries. + * + * @see {@link get} for triggering or awaiting the cache lookup + * @see {@link getOption} for reading an existing entry as an optional effect + * + * @category combinators * @since 4.0.0 - * @category Combinators */ (key: Key): (self: Cache) => Effect.Effect> /** * Retrieves the value associated with the specified key from the cache, only if * it contains a resolved successful value. * + * **Details** + * + * This checks only an existing non-expired entry. It returns `Option.some` when + * the entry has already resolved successfully, and `Option.none` for missing, + * expired, failed, or still-pending entries. + * + * @see {@link get} for triggering or awaiting the cache lookup + * @see {@link getOption} for reading an existing entry as an optional effect + * + * @category combinators * @since 4.0.0 - * @category Combinators */ (self: Cache, key: Key): Effect.Effect> } = dual( @@ -1076,7 +1204,8 @@ export const getSuccess: { * Sets the value associated with the specified key in the cache. This will * overwrite any existing value for that key, skipping the lookup function. * - * @example + * **Example** (Setting values directly) + * * ```ts * import { Cache, Effect } from "effect" * @@ -1093,7 +1222,8 @@ export const getSuccess: { * }) * ``` * - * @example + * **Example** (Overwriting cached values) + * * ```ts * import { Cache, Effect } from "effect" * @@ -1115,7 +1245,8 @@ export const getSuccess: { * }) * ``` * - * @example + * **Example** (Applying TTL to set values) + * * ```ts * import { Cache, Effect } from "effect" * import { TestClock } from "effect/testing" @@ -1138,7 +1269,8 @@ export const getSuccess: { * }) * ``` * - * @example + * **Example** (Enforcing capacity when setting values) + * * ```ts * import { Cache, Effect } from "effect" * @@ -1162,15 +1294,16 @@ export const getSuccess: { * }) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ export const set: { /** * Sets the value associated with the specified key in the cache. This will * overwrite any existing value for that key, skipping the lookup function. * - * @example + * **Example** (Setting values directly) + * * ```ts * import { Cache, Effect } from "effect" * @@ -1187,7 +1320,8 @@ export const set: { * }) * ``` * - * @example + * **Example** (Overwriting cached values) + * * ```ts * import { Cache, Effect } from "effect" * @@ -1209,7 +1343,8 @@ export const set: { * }) * ``` * - * @example + * **Example** (Applying TTL to set values) + * * ```ts * import { Cache, Effect } from "effect" * import { TestClock } from "effect/testing" @@ -1232,7 +1367,8 @@ export const set: { * }) * ``` * - * @example + * **Example** (Enforcing capacity when setting values) + * * ```ts * import { Cache, Effect } from "effect" * @@ -1256,15 +1392,16 @@ export const set: { * }) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ (key: Key, value: A): (self: Cache) => Effect.Effect /** * Sets the value associated with the specified key in the cache. This will * overwrite any existing value for that key, skipping the lookup function. * - * @example + * **Example** (Setting values directly) + * * ```ts * import { Cache, Effect } from "effect" * @@ -1281,7 +1418,8 @@ export const set: { * }) * ``` * - * @example + * **Example** (Overwriting cached values) + * * ```ts * import { Cache, Effect } from "effect" * @@ -1303,7 +1441,8 @@ export const set: { * }) * ``` * - * @example + * **Example** (Applying TTL to set values) + * * ```ts * import { Cache, Effect } from "effect" * import { TestClock } from "effect/testing" @@ -1326,7 +1465,8 @@ export const set: { * }) * ``` * - * @example + * **Example** (Enforcing capacity when setting values) + * * ```ts * import { Cache, Effect } from "effect" * @@ -1350,8 +1490,8 @@ export const set: { * }) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ (self: Cache, key: Key, value: A): Effect.Effect } = dual( @@ -1363,7 +1503,8 @@ export const set: { * Sets the value associated with the specified key in the cache. This will * overwrite any existing value for that key, skipping the lookup function. * - * @example + * **Example** (Setting values directly) + * * ```ts * import { Cache, Effect } from "effect" * @@ -1380,7 +1521,8 @@ export const set: { * }) * ``` * - * @example + * **Example** (Overwriting cached values) + * * ```ts * import { Cache, Effect } from "effect" * @@ -1402,7 +1544,8 @@ export const set: { * }) * ``` * - * @example + * **Example** (Applying TTL to set values) + * * ```ts * import { Cache, Effect } from "effect" * import { TestClock } from "effect/testing" @@ -1425,7 +1568,8 @@ export const set: { * }) * ``` * - * @example + * **Example** (Enforcing capacity when setting values) + * * ```ts * import { Cache, Effect } from "effect" * @@ -1449,14 +1593,15 @@ export const set: { * }) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ A, /** * Sets the value associated with the specified key in the cache. This will * overwrite any existing value for that key, skipping the lookup function. * - * @example + * **Example** (Setting values directly) + * * ```ts * import { Cache, Effect } from "effect" * @@ -1473,7 +1618,8 @@ export const set: { * }) * ``` * - * @example + * **Example** (Overwriting cached values) + * * ```ts * import { Cache, Effect } from "effect" * @@ -1495,7 +1641,8 @@ export const set: { * }) * ``` * - * @example + * **Example** (Applying TTL to set values) + * * ```ts * import { Cache, Effect } from "effect" * import { TestClock } from "effect/testing" @@ -1518,7 +1665,8 @@ export const set: { * }) * ``` * - * @example + * **Example** (Enforcing capacity when setting values) + * * ```ts * import { Cache, Effect } from "effect" * @@ -1542,8 +1690,8 @@ export const set: { * }) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ E>() Deferred.doneUnsafe(deferred, exit) @@ -1564,9 +1712,15 @@ export const set: { ) /** - * Checks if the cache contains an entry for the specified key. + * Checks whether the cache contains an entry for the specified key. + * + * **Details** + * + * This checks for an existing non-expired entry without invoking the cache + * lookup function. Expired entries are treated as absent. + * + * **Example** (Checking for cached keys) * - * @example * ```ts * import { Cache, Effect } from "effect" * @@ -1585,7 +1739,8 @@ export const set: { * }) * ``` * - * @example + * **Example** (Checking TTL expiration) + * * ```ts * import { Cache, Effect } from "effect" * import { TestClock } from "effect/testing" @@ -1612,7 +1767,8 @@ export const set: { * }) * ``` * - * @example + * **Example** (Checking multiple keys) + * * ```ts * import { Cache, Effect } from "effect" * @@ -1641,14 +1797,20 @@ export const set: { * }) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ export const has: { /** - * Checks if the cache contains an entry for the specified key. + * Checks whether the cache contains an entry for the specified key. + * + * **Details** + * + * This checks for an existing non-expired entry without invoking the cache + * lookup function. Expired entries are treated as absent. + * + * **Example** (Checking for cached keys) * - * @example * ```ts * import { Cache, Effect } from "effect" * @@ -1667,7 +1829,8 @@ export const has: { * }) * ``` * - * @example + * **Example** (Checking TTL expiration) + * * ```ts * import { Cache, Effect } from "effect" * import { TestClock } from "effect/testing" @@ -1694,7 +1857,8 @@ export const has: { * }) * ``` * - * @example + * **Example** (Checking multiple keys) + * * ```ts * import { Cache, Effect } from "effect" * @@ -1723,14 +1887,20 @@ export const has: { * }) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ (key: Key): (self: Cache) => Effect.Effect /** - * Checks if the cache contains an entry for the specified key. + * Checks whether the cache contains an entry for the specified key. + * + * **Details** + * + * This checks for an existing non-expired entry without invoking the cache + * lookup function. Expired entries are treated as absent. + * + * **Example** (Checking for cached keys) * - * @example * ```ts * import { Cache, Effect } from "effect" * @@ -1749,7 +1919,8 @@ export const has: { * }) * ``` * - * @example + * **Example** (Checking TTL expiration) + * * ```ts * import { Cache, Effect } from "effect" * import { TestClock } from "effect/testing" @@ -1776,7 +1947,8 @@ export const has: { * }) * ``` * - * @example + * **Example** (Checking multiple keys) + * * ```ts * import { Cache, Effect } from "effect" * @@ -1805,8 +1977,8 @@ export const has: { * }) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ (self: Cache, key: Key): Effect.Effect } = dual( @@ -1821,7 +1993,8 @@ export const has: { /** * Invalidates the entry associated with the specified key in the cache. * - * @example + * **Example** (Invalidating cached entries) + * * ```ts * import { Cache, Effect } from "effect" * @@ -1859,14 +2032,15 @@ export const has: { * }) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ export const invalidate: { /** * Invalidates the entry associated with the specified key in the cache. * - * @example + * **Example** (Invalidating cached entries) + * * ```ts * import { Cache, Effect } from "effect" * @@ -1904,14 +2078,15 @@ export const invalidate: { * }) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ (key: Key): (self: Cache) => Effect.Effect /** * Invalidates the entry associated with the specified key in the cache. * - * @example + * **Example** (Invalidating cached entries) + * * ```ts * import { Cache, Effect } from "effect" * @@ -1949,8 +2124,8 @@ export const invalidate: { * }) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ (self: Cache, key: Key): Effect.Effect } = dual(2, (self: Cache, key: Key): Effect.Effect => @@ -1959,10 +2134,11 @@ export const invalidate: { })) /** - * Conditionally invalidates the entry associated with the specified key in the cache - * if the predicate returns true for the cached value. + * Invalidates the entry associated with the specified key in the cache when the + * predicate returns true for the cached value. + * + * **Example** (Invalidating entries conditionally) * - * @example * ```ts * import { Cache, Effect } from "effect" * @@ -2019,15 +2195,16 @@ export const invalidate: { * }) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ export const invalidateWhen: { /** - * Conditionally invalidates the entry associated with the specified key in the cache - * if the predicate returns true for the cached value. + * Invalidates the entry associated with the specified key in the cache when the + * predicate returns true for the cached value. + * + * **Example** (Invalidating entries conditionally) * - * @example * ```ts * import { Cache, Effect } from "effect" * @@ -2084,15 +2261,16 @@ export const invalidateWhen: { * }) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ (key: Key, f: Predicate): (self: Cache) => Effect.Effect /** - * Conditionally invalidates the entry associated with the specified key in the cache - * if the predicate returns true for the cached value. + * Invalidates the entry associated with the specified key in the cache when the + * predicate returns true for the cached value. + * + * **Example** (Invalidating entries conditionally) * - * @example * ```ts * import { Cache, Effect } from "effect" * @@ -2149,8 +2327,8 @@ export const invalidateWhen: { * }) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ (self: Cache, key: Key, f: Predicate): Effect.Effect } = dual( @@ -2177,10 +2355,13 @@ export const invalidateWhen: { /** * Forces a refresh of the value associated with the specified key in the cache. * + * **Details** + * * It will always invoke the lookup function to construct a new value, * overwriting any existing value for that key. * - * @example + * **Example** (Refreshing cached values) + * * ```ts * import { Cache, Effect } from "effect" * @@ -2210,7 +2391,8 @@ export const invalidateWhen: { * }) * ``` * - * @example + * **Example** (Resetting TTL on refresh) + * * ```ts * import { Cache, Effect } from "effect" * import { TestClock } from "effect/testing" @@ -2238,7 +2420,8 @@ export const invalidateWhen: { * }) * ``` * - * @example + * **Example** (Refreshing missing keys) + * * ```ts * import { Cache, Effect } from "effect" * @@ -2258,17 +2441,20 @@ export const invalidateWhen: { * }) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ export const refresh: { /** * Forces a refresh of the value associated with the specified key in the cache. * + * **Details** + * * It will always invoke the lookup function to construct a new value, * overwriting any existing value for that key. * - * @example + * **Example** (Refreshing cached values) + * * ```ts * import { Cache, Effect } from "effect" * @@ -2298,7 +2484,8 @@ export const refresh: { * }) * ``` * - * @example + * **Example** (Resetting TTL on refresh) + * * ```ts * import { Cache, Effect } from "effect" * import { TestClock } from "effect/testing" @@ -2326,7 +2513,8 @@ export const refresh: { * }) * ``` * - * @example + * **Example** (Refreshing missing keys) + * * ```ts * import { Cache, Effect } from "effect" * @@ -2346,17 +2534,20 @@ export const refresh: { * }) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ (key: Key): (self: Cache) => Effect.Effect /** * Forces a refresh of the value associated with the specified key in the cache. * + * **Details** + * * It will always invoke the lookup function to construct a new value, * overwriting any existing value for that key. * - * @example + * **Example** (Refreshing cached values) + * * ```ts * import { Cache, Effect } from "effect" * @@ -2386,7 +2577,8 @@ export const refresh: { * }) * ``` * - * @example + * **Example** (Resetting TTL on refresh) + * * ```ts * import { Cache, Effect } from "effect" * import { TestClock } from "effect/testing" @@ -2414,7 +2606,8 @@ export const refresh: { * }) * ``` * - * @example + * **Example** (Refreshing missing keys) + * * ```ts * import { Cache, Effect } from "effect" * @@ -2434,8 +2627,8 @@ export const refresh: { * }) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ (self: Cache, key: Key): Effect.Effect } = dual( @@ -2445,10 +2638,13 @@ export const refresh: { const deferred = Deferred.makeUnsafe() const entry: Entry = { @@ -2647,7 +2850,8 @@ export const refresh: { /** * Invalidates all entries in the cache. * - * @example + * **Example** (Invalidating all entries) + * * ```ts * import { Cache, Effect } from "effect" * @@ -2677,8 +2881,8 @@ export const refresh: { * }) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ export const invalidateAll = (self: Cache): Effect.Effect => effect.sync(() => { @@ -2688,11 +2892,14 @@ export const invalidateAll = (self: Cache): Effect.E /** * Retrieves the approximate number of entries in the cache. * + * **Details** + * * Note that expired entries are counted until they are accessed and removed. * The size reflects the current number of entries stored, not the number * of valid entries. * - * @example + * **Example** (Reading cache size) + * * ```ts * import { Cache, Effect } from "effect" * @@ -2719,8 +2926,8 @@ export const invalidateAll = (self: Cache): Effect.E * }) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ export const size = (self: Cache): Effect.Effect => effect.sync(() => MutableHashMap.size(self.map)) @@ -2728,7 +2935,8 @@ export const size = (self: Cache): Effect.Effect(self: Cache): Effect.Effect(self: Cache): Effect.Effect> => core.withFiber((fiber) => { @@ -2770,7 +2978,8 @@ export const keys = (self: Cache): Effect.Effect(self: Cache): Effect.Effect(self: Cache): Effect.Effect> => effect.map(entries(self), Iterable.map(([, value]) => value)) @@ -2804,8 +3013,15 @@ export const values = (self: Cache): Effect.Effect(self: Cache): Effect.Effect> => core.withFiber((fiber) => { diff --git a/.opencode/node_modules/effect/src/Cause.ts b/.opencode/node_modules/effect/src/Cause.ts index ae256e47580cb69246494ed924437453e14a8ffe..59c92fd006f9ec9d1580df9a7b69274889ee1a89 100644 --- a/.opencode/node_modules/effect/src/Cause.ts +++ b/.opencode/node_modules/effect/src/Cause.ts @@ -1,79 +1,11 @@ /** - * Structured representation of how an Effect can fail. - * - * A `Cause` holds a flat array of `Reason` values, where each reason is one of: - * - * - **Fail** — a typed, expected error `E` (created by `Effect.fail`) - * - **Die** — an untyped defect (`unknown`) from `Effect.die` or uncaught throws - * - **Interrupt** — a fiber interruption, optionally carrying the interrupting fiber's ID - * - * ## Mental model - * - * - A `Cause` is always flat: concurrent and sequential failures are stored together - * in `cause.reasons` (a `ReadonlyArray>`). - * - Each `Reason` carries an `annotations` map with tracing metadata (stack frames, spans). - * - An empty `reasons` array means the computation succeeded or the cause was empty - * ({@link empty}). - * - `Cause` implements `Equal`, so two causes with identical reasons compare as equal. - * - * ## Common tasks - * - * | Intent | API | - * |--------|-----| - * | Create a cause | {@link fail}, {@link die}, {@link interrupt}, {@link fromReasons} | - * | Test for reason types | {@link hasFails}, {@link hasDies}, {@link hasInterrupts} | - * | Extract the first error/defect | {@link findError}, {@link findDefect}, {@link findFail}, {@link findDie} | - * | Iterate over reasons manually | `cause.reasons.filter(Cause.isFailReason)` | - * | Combine two causes | {@link combine} | - * | Transform errors | {@link map} | - * | Collapse to a single thrown value | {@link squash} | - * | Render for logging | {@link pretty}, {@link prettyErrors} | - * | Attach/read tracing metadata | {@link annotate}, {@link annotations}, {@link reasonAnnotations} | - * - * ## Gotchas - * - * - `findError`/`findDefect` return `Filter.fail` (not `Option.none`) when no match is - * found. Use {@link findErrorOption} if you need an `Option`. - * - `squash` picks the first `Fail` error, then the first `Die` defect, then falls back - * to a generic "interrupted" / "empty" error. It is lossy — use `prettyErrors` or - * iterate `reasons` directly when you need all failures. - * - The module also exports several built-in error classes (`NoSuchElementError`, - * `TimeoutError`, `IllegalArgumentError`, `ExceededCapacityError`, `UnknownError`) - * and the `Done` completion signal. These all implement `YieldableError` and can be - * yielded directly inside `Effect.gen`. - * - * **Example** (inspecting a concurrent failure) + * Records the full reason an `Effect` failed. * - * ```ts - * import { Cause, Effect } from "effect" - * - * const program = Effect.gen(function*() { - * const cause = yield* Effect.sandbox( - * Effect.all([ - * Effect.fail("err1"), - * Effect.die("defect"), - * Effect.fail("err2") - * ], { concurrency: "unbounded" }) - * ).pipe(Effect.flip) - * - * const errors = cause.reasons - * .filter(Cause.isFailReason) - * .map((r) => r.error) - * - * const defects = cause.reasons - * .filter(Cause.isDieReason) - * .map((r) => r.defect) - * - * console.log(errors) // ["err1", "err2"] (order may vary) - * console.log(defects) // ["defect"] - * }) - * - * Effect.runPromise(program) - * ``` - * - * @see {@link Cause} — the core interface - * @see {@link Reason} — the union of failure kinds - * @see {@link pretty} — human-readable rendering + * A `Cause` can contain typed failures, unexpected defects, interruptions, + * and annotations. Keeping those details together lets code inspect or format + * failures without first collapsing them to a single error value. This module + * includes the `Cause` and `Reason` data types, helpers for building and + * checking causes, and small error types used by several Effect APIs. * * @since 2.0.0 */ @@ -93,22 +25,29 @@ import type * as Types from "./Types.ts" /** * Unique brand for `Cause` values, used for runtime type checks via {@link isCause}. * - * @since 2.0.0 - * @category symbols + * @category type IDs + * @since 4.0.0 */ export const TypeId: "~effect/Cause" = core.CauseTypeId /** * Unique brand for `Reason` values, used for runtime type checks via {@link isReason}. * - * @since 2.0.0 - * @category symbols + * @category type IDs + * @since 4.0.0 */ export const ReasonTypeId: "~effect/Cause/Reason" = core.CauseReasonTypeId /** * A structured representation of how an Effect failed. * + * **When to use** + * + * Use to preserve the full structured failure information for an effect instead + * of collapsing it to a single error value. + * + * **Details** + * * Access the individual failure entries through the `reasons` array, then * narrow each entry with {@link isFailReason}, {@link isDieReason}, or * {@link isInterruptReason}. @@ -132,10 +71,8 @@ export const ReasonTypeId: "~effect/Cause/Reason" = core.CauseReasonTypeId * console.log(Cause.isFailReason(cause.reasons[0])) // true * ``` * - * @see {@link Reason} — the union type stored in `reasons` - * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface Cause extends Pipeable, Inspectable, Equal { readonly [TypeId]: typeof TypeId @@ -143,7 +80,7 @@ export interface Cause extends Pipeable, Inspectable, Equal { } /** - * Tests if an arbitrary value is a {@link Cause}. + * Checks whether an arbitrary value is a `Cause`. * * **Example** (runtime type check) * @@ -160,7 +97,7 @@ export interface Cause extends Pipeable, Inspectable, Equal { export const isCause: (self: unknown) => self is Cause = core.isCause /** - * Tests if an arbitrary value is a {@link Reason} (`Fail`, `Die`, or `Interrupt`). + * Checks whether an arbitrary value is a `Reason` (`Fail`, `Die`, or `Interrupt`). * * **Example** (runtime type check) * @@ -173,12 +110,14 @@ export const isCause: (self: unknown) => self is Cause = core.isCause * ``` * * @category guards - * @since 2.0.0 + * @since 4.0.0 */ export const isReason: (self: unknown) => self is Reason = core.isCauseReason /** - * A single entry inside a {@link Cause}'s `reasons` array. + * A single entry inside a `Cause`'s `reasons` array. + * + * **Details** * * Narrow to a concrete type with {@link isFailReason}, {@link isDieReason}, * or {@link isInterruptReason}. @@ -201,19 +140,18 @@ export const isReason: (self: unknown) => self is Reason = core.isCause * } * ``` * - * @see {@link Fail} — typed error reason - * @see {@link Die} — untyped defect reason - * @see {@link Interrupt} — interruption reason - * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type Reason = Fail | Die | Interrupt /** - * Narrows a {@link Reason} to {@link Fail}. + * Narrows a `Reason` to `Fail`. + * + * **When to use** * - * Useful as a predicate for `Array.filter` when iterating over `cause.reasons`. + * Use as a predicate for `Array.filter` to pick out typed `Fail` reasons when + * iterating over `cause.reasons`. * * **Example** (filtering fail reasons) * @@ -234,9 +172,12 @@ export type Reason = Fail | Die | Interrupt export const isFailReason: (self: Reason) => self is Fail = core.isFailReason /** - * Narrows a {@link Reason} to {@link Die}. + * Narrows a `Reason` to `Die`. * - * Useful as a predicate for `Array.filter` when iterating over `cause.reasons`. + * **When to use** + * + * Use as a predicate for `Array.filter` to pick out `Die` (defect) reasons when + * iterating over `cause.reasons`. * * **Example** (filtering die reasons) * @@ -257,9 +198,12 @@ export const isFailReason: (self: Reason) => self is Fail = core.isFail export const isDieReason: (self: Reason) => self is Die = core.isDieReason /** - * Narrows a {@link Reason} to {@link Interrupt}. + * Narrows a `Reason` to `Interrupt`. + * + * **When to use** * - * Useful as a predicate for `Array.filter` when iterating over `cause.reasons`. + * Use as a predicate for `Array.filter` to pick out `Interrupt` reasons when + * iterating over `cause.reasons`. * * **Example** (filtering interrupt reasons) * @@ -280,10 +224,9 @@ export const isDieReason: (self: Reason) => self is Die = core.isDieReason export const isInterruptReason: (self: Reason) => self is Interrupt = core.isInterruptReason /** - * Companion namespace for the {@link Cause} interface. + * Companion namespace for the `Cause` interface. * * @since 2.0.0 - * @category models */ export declare namespace Cause { /** @@ -298,22 +241,23 @@ export declare namespace Cause { * type E = Cause.Cause.Error> * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type Error = T extends Cause ? E : never /** - * Base interface shared by all reason types ({@link Fail}, {@link Die}, - * {@link Interrupt}). + * Base interface shared by all reason types (`Fail`, `Die`, `Interrupt`). + * + * **Details** * * Every reason carries: * - `_tag` — discriminant string (`"Fail"`, `"Die"`, or `"Interrupt"`) * - `annotations` — tracing metadata attached by the runtime * - `annotate()` — returns a copy with additional annotations * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface ReasonProto extends Inspectable, Equal { readonly [ReasonTypeId]: typeof ReasonTypeId @@ -326,10 +270,9 @@ export declare namespace Cause { } /** - * Companion namespace for the {@link Reason} type. + * Companion namespace for the `Reason` type. * - * @since 2.0.0 - * @category models + * @since 4.0.0 */ export declare namespace Reason { /** @@ -344,8 +287,8 @@ export declare namespace Reason { * type E = Cause.Reason.Error> * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type Error = T extends Reason ? E : never } @@ -353,8 +296,15 @@ export declare namespace Reason { /** * An untyped defect — typically a programming error or an uncaught exception. * + * **When to use** + * + * Use when inspecting `Cause` reasons that represent defects instead of typed + * failures or interruptions. + * + * **Details** + * * The `defect` property is `unknown` because defects are not part of the - * typed error channel. Use {@link isDieReason} to narrow a {@link Reason} + * typed error channel. Use {@link isDieReason} to narrow a `Reason` * to this type. * * **Example** (accessing the defect) @@ -362,18 +312,18 @@ export declare namespace Reason { * ```ts * import { Cause } from "effect" * - * const cause = Cause.die(new Error("Unexpected")) + * const cause = Cause.die("Unexpected") * const reason = cause.reasons[0] * if (Cause.isDieReason(reason)) { - * console.log(reason.defect) // Error: Unexpected + * console.log(reason.defect) // "Unexpected" * } * ``` * - * @see {@link die} — create a `Cause` containing a single `Die` - * @see {@link isDieReason} — type guard + * @see {@link die} for constructing a cause with a single `Die` reason + * @see {@link isDieReason} for narrowing a `Reason` to `Die` * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface Die extends Cause.ReasonProto<"Die"> { readonly defect: unknown @@ -382,8 +332,15 @@ export interface Die extends Cause.ReasonProto<"Die"> { /** * A typed, expected error produced by `Effect.fail`. * + * **When to use** + * + * Use when inspecting `Cause` reasons that represent expected failures from the + * typed error channel. + * + * **Details** + * * The `error` property carries the typed value `E`. Use {@link isFailReason} - * to narrow a {@link Reason} to this type. + * to narrow a `Reason` to this type. * * **Example** (accessing the error) * @@ -397,11 +354,11 @@ export interface Die extends Cause.ReasonProto<"Die"> { * } * ``` * - * @see {@link fail} — create a `Cause` containing a single `Fail` - * @see {@link isFailReason} — type guard + * @see {@link fail} for constructing a cause with a single `Fail` reason + * @see {@link isFailReason} for narrowing a `Reason` to `Fail` * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface Fail extends Cause.ReasonProto<"Fail"> { readonly error: E @@ -411,7 +368,9 @@ export interface Fail extends Cause.ReasonProto<"Fail"> { * A fiber interruption signal, optionally carrying the ID of the fiber that * initiated the interruption. * - * Use {@link isInterruptReason} to narrow a {@link Reason} to this type. + * **Details** + * + * Use {@link isInterruptReason} to narrow a `Reason` to this type. * * **Example** (accessing the fiber ID) * @@ -425,25 +384,31 @@ export interface Fail extends Cause.ReasonProto<"Fail"> { * } * ``` * - * @see {@link interrupt} — create a `Cause` containing a single `Interrupt` - * @see {@link isInterruptReason} — type guard - * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface Interrupt extends Cause.ReasonProto<"Interrupt"> { readonly fiberId: number | undefined } /** - * Creates a {@link Cause} from an array of {@link Reason} values. + * Creates a `Cause` from an array of `Reason` values. * - * Use this when you already have individual reasons (e.g. from filtering or + * **When to use** + * + * Use when you already have individual reasons (e.g. from filtering or * transforming another cause's `reasons` array) and need to wrap them back * into a `Cause`. * - * - Returns a new `Cause`; does not mutate the input array. - * - An empty array produces a cause equivalent to {@link empty}. + * **Details** + * + * - Returns a new `Cause`. + * - An empty array produces a cause equivalent to `empty`. + * + * **Gotchas** + * + * The `reasons` array is stored as provided. Treat the array as immutable + * after passing it to this function. * * **Example** (building a cause from reasons) * @@ -461,19 +426,37 @@ export interface Interrupt extends Cause.ReasonProto<"Interrupt"> { * @see {@link combine} — merge two existing causes * * @category constructors - * @since 2.0.0 + * @since 4.0.0 */ export const fromReasons: ( reasons: ReadonlyArray> ) => Cause = core.causeFromReasons /** - * A {@link Cause} with an empty `reasons` array. + * Represents a `Cause` with an empty `reasons` array. + * + * **When to use** + * + * Use to represent the absence of failure when constructing or combining + * causes. + * + * **Details** * * Represents the absence of failure. Combining any cause with `empty` via * {@link combine} returns the original cause unchanged. * - * @see {@link combine} + * **Example** (combining with the empty cause) + * + * ```ts + * import { Cause } from "effect" + * + * const cause = Cause.combine(Cause.empty, Cause.fail("boom")) + * + * console.log(cause.reasons.length) // 1 + * console.log(Cause.hasFails(cause)) // true + * ``` + * + * @see {@link combine} for merging causes where `empty` acts as the identity * * @category constructors * @since 2.0.0 @@ -481,9 +464,13 @@ export const fromReasons: ( export const empty: Cause = core.causeEmpty /** - * Creates a {@link Cause} containing a single {@link Fail} reason with the + * Creates a `Cause` containing a single `Fail` reason with the * given typed error. * + * **When to use** + * + * Use to construct a cause from an expected typed error. + * * **Example** (creating a fail cause) * * ```ts @@ -503,15 +490,19 @@ export const empty: Cause = core.causeEmpty export const fail: (error: E) => Cause = core.causeFail /** - * Creates a {@link Cause} containing a single {@link Die} reason with the + * Creates a `Cause` containing a single `Die` reason with the * given defect. * + * **When to use** + * + * Use to construct a cause from an untyped defect or unexpected thrown value. + * * **Example** (creating a die cause) * * ```ts * import { Cause } from "effect" * - * const cause = Cause.die(new Error("Unexpected")) + * const cause = Cause.die("Unexpected") * console.log(cause.reasons.length) // 1 * console.log(Cause.isDieReason(cause.reasons[0])) // true * ``` @@ -525,7 +516,7 @@ export const fail: (error: E) => Cause = core.causeFail export const die: (defect: unknown) => Cause = core.causeDie /** - * Creates a {@link Cause} containing a single {@link Interrupt} reason, + * Creates a `Cause` containing a single `Interrupt` reason, * optionally carrying the interrupting fiber's ID. * * **Example** (creating an interrupt cause) @@ -547,10 +538,12 @@ export const die: (defect: unknown) => Cause = core.causeDie export const interrupt: (fiberId?: number | undefined) => Cause = effect.causeInterrupt /** - * Creates a standalone {@link Fail} reason (not wrapped in a {@link Cause}). + * Creates a standalone `Fail` reason (not wrapped in a `Cause`). + * + * **When to use** * - * Use this when you need to construct individual reasons for - * {@link fromReasons} or for direct comparison. + * Use when constructing a standalone typed failure reason for + * {@link fromReasons} or direct comparison. * * **Example** (creating a Fail reason) * @@ -571,15 +564,21 @@ export const interrupt: (fiberId?: number | undefined) => Cause = effect. export const makeFailReason = (error: E): Fail => new core.Fail(error) /** - * Creates a standalone {@link Die} reason (not wrapped in a {@link Cause}). + * Creates a standalone `Die` reason (not wrapped in a `Cause`). + * + * **When to use** + * + * Use when constructing a standalone defect reason for {@link fromReasons} or + * direct comparison. * * **Example** (creating a Die reason) * * ```ts * import { Cause } from "effect" * - * const reason = Cause.makeDieReason(new Error("bug")) + * const reason = Cause.makeDieReason("bug") * console.log(reason._tag) // "Die" + * console.log(reason.defect) // "bug" * ``` * * @see {@link makeFailReason} — create a `Fail` reason @@ -591,9 +590,14 @@ export const makeFailReason = (error: E): Fail => new core.Fail(error) export const makeDieReason = (defect: unknown): Die => new core.Die(defect) /** - * Creates a standalone {@link Interrupt} reason (not wrapped in a {@link Cause}), + * Creates a standalone `Interrupt` reason (not wrapped in a `Cause`), * optionally carrying the interrupting fiber's ID. * + * **When to use** + * + * Use when constructing a standalone interrupt reason for {@link fromReasons} + * or direct comparison. + * * **Example** (creating an Interrupt reason) * * ```ts @@ -613,11 +617,12 @@ export const makeDieReason = (defect: unknown): Die => new core.Die(defect) export const makeInterruptReason: (fiberId?: number | undefined) => Interrupt = effect.makeInterruptReason /** - * Returns `true` if every reason in the cause is an {@link Interrupt} (and + * Returns `true` if every reason in the cause is an `Interrupt` (and * there is at least one reason). * - * Useful for deciding whether a failure was entirely due to interruption and - * can be silently discarded. + * **When to use** + * + * Use when you need to detect failures caused only by interruption. * * **Example** (checking interrupt-only causes) * @@ -632,16 +637,25 @@ export const makeInterruptReason: (fiberId?: number | undefined) => Interrupt = * @see {@link hasInterrupts} — `true` if the cause contains *any* interrupts * * @category predicates - * @since 2.0.0 + * @since 4.0.0 */ export const hasInterruptsOnly: (self: Cause) => boolean = effect.hasInterruptsOnly /** - * Transforms the typed error values inside a {@link Cause} using the - * provided function. Only {@link Fail} reasons are affected; {@link Die} - * and {@link Interrupt} reasons pass through unchanged. + * Transforms the typed error values inside a `Cause` using the + * provided function. Only `Fail` reasons are affected; `Die` and `Interrupt` + * reasons pass through unchanged. + * + * **When to use** + * + * Use to transform expected typed failures while preserving defects and + * interruptions unchanged. * - * Returns a new `Cause`; does not mutate the original. + * **Details** + * + * If at least one `Fail` reason exists, this returns a new `Cause` + * containing the mapped failures. If the cause has no `Fail` reasons, the + * original cause is returned unchanged. * * **Example** (mapping errors to uppercase) * @@ -657,15 +671,24 @@ export const hasInterruptsOnly: (self: Cause) => boolean = effect.hasInter * ``` * * @category mapping - * @since 4.0.0 + * @since 2.0.0 */ export const map: { /** - * Transforms the typed error values inside a {@link Cause} using the - * provided function. Only {@link Fail} reasons are affected; {@link Die} - * and {@link Interrupt} reasons pass through unchanged. + * Transforms the typed error values inside a `Cause` using the + * provided function. Only `Fail` reasons are affected; `Die` and `Interrupt` + * reasons pass through unchanged. + * + * **When to use** * - * Returns a new `Cause`; does not mutate the original. + * Use to transform expected typed failures while preserving defects and + * interruptions unchanged. + * + * **Details** + * + * If at least one `Fail` reason exists, this returns a new `Cause` + * containing the mapped failures. If the cause has no `Fail` reasons, the + * original cause is returned unchanged. * * **Example** (mapping errors to uppercase) * @@ -681,15 +704,24 @@ export const map: { * ``` * * @category mapping - * @since 4.0.0 + * @since 2.0.0 */ (f: (error: Types.NoInfer) => E2): (self: Cause) => Cause /** - * Transforms the typed error values inside a {@link Cause} using the - * provided function. Only {@link Fail} reasons are affected; {@link Die} - * and {@link Interrupt} reasons pass through unchanged. + * Transforms the typed error values inside a `Cause` using the + * provided function. Only `Fail` reasons are affected; `Die` and `Interrupt` + * reasons pass through unchanged. + * + * **When to use** + * + * Use to transform expected typed failures while preserving defects and + * interruptions unchanged. * - * Returns a new `Cause`; does not mutate the original. + * **Details** + * + * If at least one `Fail` reason exists, this returns a new `Cause` + * containing the mapped failures. If the cause has no `Fail` reasons, the + * original cause is returned unchanged. * * **Example** (mapping errors to uppercase) * @@ -705,7 +737,7 @@ export const map: { * ``` * * @category mapping - * @since 4.0.0 + * @since 2.0.0 */ (self: Cause, f: (error: Types.NoInfer) => E2): Cause } = effect.causeMap @@ -714,7 +746,13 @@ export const map: { * Merges two causes into a single cause whose `reasons` array is the union * of both inputs (de-duplicated by value equality). * - * - Combining with {@link empty} returns the other cause unchanged. + * **When to use** + * + * Use to merge independent causes into one structured failure value. + * + * **Details** + * + * - Combining with `empty` returns the other cause unchanged. * - If the result is structurally equal to `self`, `self` is returned * (referential shortcut). * @@ -730,6 +768,7 @@ export const map: { * ``` * * @see {@link fromReasons} — build a cause from an array of reasons + * @see {@link empty} for the identity cause used when combining * * @category combining * @since 4.0.0 @@ -739,7 +778,13 @@ export const combine: { * Merges two causes into a single cause whose `reasons` array is the union * of both inputs (de-duplicated by value equality). * - * - Combining with {@link empty} returns the other cause unchanged. + * **When to use** + * + * Use to merge independent causes into one structured failure value. + * + * **Details** + * + * - Combining with `empty` returns the other cause unchanged. * - If the result is structurally equal to `self`, `self` is returned * (referential shortcut). * @@ -755,6 +800,7 @@ export const combine: { * ``` * * @see {@link fromReasons} — build a cause from an array of reasons + * @see {@link empty} for the identity cause used when combining * * @category combining * @since 4.0.0 @@ -764,7 +810,13 @@ export const combine: { * Merges two causes into a single cause whose `reasons` array is the union * of both inputs (de-duplicated by value equality). * - * - Combining with {@link empty} returns the other cause unchanged. + * **When to use** + * + * Use to merge independent causes into one structured failure value. + * + * **Details** + * + * - Combining with `empty` returns the other cause unchanged. * - If the result is structurally equal to `self`, `self` is returned * (referential shortcut). * @@ -780,6 +832,7 @@ export const combine: { * ``` * * @see {@link fromReasons} — build a cause from an array of reasons + * @see {@link empty} for the identity cause used when combining * * @category combining * @since 4.0.0 @@ -788,17 +841,28 @@ export const combine: { } = effect.causeCombine /** - * Collapses a {@link Cause} into a single `unknown` value, picking the "most + * Collapses a `Cause` into a single `unknown` value, picking the "most * important" failure in this order: * - * 1. First {@link Fail} error (the `E` value) - * 2. First {@link Die} defect + * **When to use** + * + * Use to collapse a structured cause to the single value that synchronous and + * promise runners would throw. + * + * **Details** + * + * 1. First `Fail` error (the `E` value) + * 2. First `Die` defect * 3. A generic `Error("All fibers interrupted without error")` for interrupt-only causes - * 4. A generic `Error("Empty cause")` for {@link empty} + * 4. A generic `Error("Empty cause")` for `empty` * * This is the function used by `Effect.runPromise` and `Effect.runSync` to - * decide what to throw. It is lossy — use {@link prettyErrors} or iterate - * `cause.reasons` when you need all failures. + * decide what to throw. + * + * **Gotchas** + * + * This function is lossy. Use {@link prettyErrors} or iterate `cause.reasons` + * when you need all failures. * * **Example** (squashing a cause) * @@ -818,7 +882,12 @@ export const combine: { export const squash: (self: Cause) => unknown = effect.causeSquash /** - * Returns `true` if the cause contains at least one {@link Fail} reason. + * Returns `true` if the cause contains at least one `Fail` reason. + * + * **When to use** + * + * Use to check whether a cause includes typed failures before extracting, + * mapping, or rendering them. * * **Example** (checking for typed errors) * @@ -833,16 +902,20 @@ export const squash: (self: Cause) => unknown = effect.causeSquash * @see {@link hasInterrupts} — check for interruptions * * @category predicates - * @since 2.0.0 + * @since 4.0.0 */ export const hasFails: (self: Cause) => boolean = effect.hasFails /** - * Returns the first {@link Fail} reason from a cause, including its - * annotations. Returns `Filter.fail` with the remaining cause when no - * `Fail` is found. + * Returns a `Result` whose success value is the first `Fail` reason in + * the cause, including its annotations. If the cause has no `Fail` reason, the + * failure value is the original cause narrowed to `Cause`, because it + * contains no typed error reasons. + * + * **When to use** * - * Use {@link findError} if you only need the unwrapped error value `E`. + * Use when you need the full `Fail` reason from a `Cause`, including + * annotations. * * **Example** (extracting the first Fail reason) * @@ -858,17 +931,21 @@ export const hasFails: (self: Cause) => boolean = effect.hasFails * @see {@link findError} — extract the unwrapped `E` value * @see {@link findDie} — extract the first `Die` reason * - * @category filters + * @category filtering * @since 4.0.0 */ export const findFail: (self: Cause) => Result.Result, Cause> = effect.findFail /** - * Returns the first typed error value `E` from a cause. - * Returns `Filter.fail` with the remaining cause when no `Fail` is found. + * Returns a `Result` whose success value is the first typed error value `E` + * from a `Fail` reason in the cause. If the cause has no `Fail` reason, + * the failure value is the original cause narrowed to `Cause`, because + * it contains no typed error reasons. * - * Use {@link findFail} if you need the full {@link Fail} reason (including - * annotations). Use {@link findErrorOption} if you prefer an `Option`. + * **When to use** + * + * Use when you need the first typed error value from a `Cause` as a `Result` + * that preserves the original cause when no match is found. * * **Example** (extracting the first error value) * @@ -884,17 +961,19 @@ export const findFail: (self: Cause) => Result.Result, Cause(self: Cause) => Result.Result> = effect.findError /** * Returns the first typed error value `E` from a cause wrapped in - * `Option.some`, or `Option.none` if no {@link Fail} reason exists. + * `Option.some`, or `Option.none` if no `Fail` reason exists. + * + * **When to use** * - * This is a convenience wrapper around {@link findError} for code that - * already works with `Option` instead of `Filter`. + * Use when you need the first typed error value from a `Cause` as an `Option`, + * discarding the original cause. * * **Example** (extracting an error as Option) * @@ -908,15 +987,20 @@ export const findError: (self: Cause) => Result.Result> = * console.log(Option.isNone(none)) // true * ``` * - * @see {@link findError} — `Filter`-based variant + * @see {@link findError} — `Result`-based variant * - * @category filters + * @category filtering * @since 4.0.0 */ export const findErrorOption: (input: Cause) => Option = effect.findErrorOption /** - * Returns `true` if the cause contains at least one {@link Die} reason. + * Returns `true` if the cause contains at least one `Die` reason. + * + * **When to use** + * + * Use to check whether a cause includes defects before extracting or rendering + * them. * * **Example** (checking for defects) * @@ -931,16 +1015,19 @@ export const findErrorOption: (input: Cause) => Option = effect.findErr * @see {@link hasInterrupts} — check for interruptions * * @category predicates - * @since 2.0.0 + * @since 4.0.0 */ export const hasDies: (self: Cause) => boolean = effect.hasDies /** - * Returns the first {@link Die} reason from a cause, including its - * annotations. Returns `Filter.fail` with the original cause when no - * `Die` is found. + * Returns a `Result` whose success value is the first `Die` reason in + * the cause, including its annotations. If the cause has no `Die` reason, the + * failure value is the original cause. * - * Use {@link findDefect} if you only need the unwrapped defect value. + * **When to use** + * + * Use when you need the full `Die` reason from a `Cause`, including + * annotations. * * **Example** (extracting the first Die reason) * @@ -956,18 +1043,20 @@ export const hasDies: (self: Cause) => boolean = effect.hasDies * @see {@link findDefect} — extract the unwrapped defect value * @see {@link findFail} — extract the first `Fail` reason * - * @category filters + * @category filtering * @since 4.0.0 */ export const findDie: (self: Cause) => Result.Result> = effect.findDie /** - * Returns the first defect value (`unknown`) from a cause. - * Returns `Filter.fail` with the original cause when no {@link Die} reason - * is found. + * Returns a `Result` whose success value is the first defect value from a + * `Die` reason in the cause. If the cause has no `Die` reason, the + * failure value is the original cause. + * + * **When to use** * - * Use {@link findDie} if you need the full `Die` reason (including - * annotations). + * Use when you need the first defect value from a `Cause` as a `Result`, + * without the full `Die` reason. * * **Example** (extracting the first defect) * @@ -983,13 +1072,13 @@ export const findDie: (self: Cause) => Result.Result> = effe * @see {@link findDie} — extract the full `Die` reason * @see {@link findError} — extract the first typed error * - * @category filters + * @category filtering * @since 4.0.0 */ export const findDefect: (self: Cause) => Result.Result> = effect.findDefect /** - * Returns `true` if the cause contains at least one {@link Interrupt} reason. + * Returns `true` if the cause contains at least one `Interrupt` reason. * * **Example** (checking for interruptions) * @@ -1005,14 +1094,19 @@ export const findDefect: (self: Cause) => Result.Result> * @see {@link hasDies} — check for defects * * @category predicates - * @since 2.0.0 + * @since 4.0.0 */ export const hasInterrupts: (self: Cause) => boolean = effect.hasInterrupts /** - * Returns the first {@link Interrupt} reason from a cause, including its - * annotations. Returns `Filter.fail` with the original cause when no - * `Interrupt` is found. + * Returns a `Result` whose success value is the first `Interrupt` reason + * in the cause, including its annotations. If the cause has no `Interrupt` + * reason, the failure value is the original cause. + * + * **When to use** + * + * Use when you need the first `Interrupt` reason from a `Cause`, including the + * fiber ID and annotations. * * **Example** (extracting the first interrupt) * @@ -1027,17 +1121,20 @@ export const hasInterrupts: (self: Cause) => boolean = effect.hasInterrupt * * @see {@link interruptors} — collect all interrupting fiber IDs as a `Set` * - * @category filters + * @category filtering * @since 4.0.0 */ export const findInterrupt: (self: Cause) => Result.Result> = effect.findInterrupt /** - * Collects the fiber IDs of all {@link Interrupt} reasons in the cause into - * a `ReadonlySet`. Returns an empty set when the cause has no interrupts. + * Collects the defined fiber IDs from all `Interrupt` reasons in the + * cause into a `ReadonlySet`. Interrupt reasons without a `fiberId` are + * ignored. Returns an empty set when the cause has no interrupting fiber IDs. + * + * **When to use** * - * This always succeeds (no `Filter.fail`). Use {@link filterInterruptors} - * for the `Filter`-based variant. + * Use when you need interrupting fiber IDs as a set, with absence represented + * as an empty set. * * **Example** (collecting interruptors) * @@ -1048,48 +1145,64 @@ export const findInterrupt: (self: Cause) => Result.Result(self: Cause) => ReadonlySet = effect.causeInterruptors /** - * Extracts the set of interrupting fiber IDs from a cause. - * Returns `Filter.fail` with the original cause when no {@link Interrupt} - * reason is found. + * Returns a `Result` whose success value is the set of defined fiber IDs from + * the cause's `Interrupt` reasons. If the cause has no `Interrupt` + * reason, the failure value is the original cause. + * + * **When to use** * - * Use {@link interruptors} if you always want a `Set` (possibly empty) - * without `Filter` wrapping. + * Use when you need absence of interrupt reasons to fail with the original + * cause. * - * **Example** (extracting interruptors with Filter) + * **Gotchas** + * + * Interrupt reasons without a `fiberId` still count as interrupts, so the + * function succeeds with an empty `Set` when every interrupt reason has an + * undefined fiber ID. + * + * **Example** (extracting interruptors with Result) * * ```ts * import { Cause, Result } from "effect" * * const result = Cause.filterInterruptors(Cause.interrupt(1)) * if (!Result.isFailure(result)) { - * console.log(result.success) // Set { 1 } + * console.log(result.success) // Set(1) { 1 } * } * ``` * * @see {@link interruptors} — always-succeeding variant * - * @category filters + * @category filtering * @since 4.0.0 */ export const filterInterruptors: (self: Cause) => Result.Result, Cause> = effect.causeFilterInterruptors /** - * Converts a {@link Cause} into an `Array` suitable for logging or + * Converts a `Cause` into an `Array` suitable for logging or * rethrowing. * - * Each {@link Fail} and {@link Die} reason is converted into a standard + * **When to use** + * + * Use to convert every renderable failure in a cause into individual `Error` + * values before logging or rethrowing. + * + * **Details** + * + * Each `Fail` and `Die` reason is converted into a standard * `Error`: * * - **Objects / Error instances** — `message`, `name`, `stack`, and `cause` @@ -1099,10 +1212,12 @@ export const filterInterruptors: (self: Cause) => Result.Result"`. * - * {@link Interrupt} reasons are collected separately. If the cause contains + * `Interrupt` reasons are collected separately. If the cause contains * **only** interrupts (no `Fail` or `Die`), a single `InterruptError` is * returned whose `cause` lists the interrupting fiber IDs. * + * An empty cause returns an empty array. + * * **Example** (converting a cause to errors) * * ```ts @@ -1116,14 +1231,20 @@ export const filterInterruptors: (self: Cause) => Result.Result(self: Cause) => Array = effect.causePrettyErrors /** - * Renders a {@link Cause} as a human-readable string for logging or - * debugging. + * Formats a `Cause` as a human-readable string for logging or debugging. + * + * **When to use** + * + * Use to render a whole cause as one human-readable string for logs or + * diagnostics. + * + * **Details** * * Delegates to {@link prettyErrors} to convert each reason to an `Error`, * then joins their stack traces with newlines. Nested `Error.cause` chains @@ -1140,33 +1261,37 @@ export const prettyErrors: (self: Cause) => Array = effect.causePre * * Span annotations are appended to the relevant stack frames when available. * + * **Gotchas** + * + * Rendering an empty cause produces an empty string because there are no + * errors to render. + * * **Example** (rendering a cause) * * ```ts * import { Cause } from "effect" * - * const cause = Cause.fail("something went wrong") - * console.log(Cause.pretty(cause)) - * // Error: something went wrong - * // at ... + * const rendered = Cause.pretty(Cause.fail("something went wrong")) + * console.log(rendered.includes("something went wrong")) // true * ``` * * @see {@link prettyErrors} — get the individual `Error` instances * - * @since 4.0.0 * @category rendering + * @since 2.0.0 */ export const pretty: (cause: Cause) => string = effect.causePretty /** * Base interface for error classes that can be yielded directly inside - * `Effect.gen` (via `Symbol.iterator`) or converted to a failing Effect - * via `.asEffect()`. + * `Effect.gen`. Yielding one of these errors fails the generator with that + * error as the typed failure value. + * + * **Details** * - * All built-in error classes in this module ({@link NoSuchElementError}, - * {@link TimeoutError}, {@link IllegalArgumentError}, - * {@link ExceededCapacityError}, {@link UnknownError}) extend this - * interface. + * All built-in error classes in this module (`NoSuchElementError`, + * `TimeoutError`, `IllegalArgumentError`, `ExceededCapacityError`, + * `AsyncFiberError`, and `UnknownError`) implement this interface. * * **Example** (yielding an error in Effect.gen) * @@ -1180,16 +1305,16 @@ export const pretty: (cause: Cause) => string = effect.causePretty * }) * ``` * - * @since 2.0.0 * @category errors + * @since 2.0.0 */ -export interface YieldableError extends Error, Pipeable { - [Symbol.iterator](): Effect.EffectIterator - asEffect(): Effect.Effect +export interface YieldableError extends Error, Pipeable, Inspectable { + readonly [Effect.TypeId]: Effect.Variance + [Symbol.iterator](): Effect.EffectIterator> } /** - * Tests if an arbitrary value is a {@link NoSuchElementError}. + * Checks whether an arbitrary value is a `NoSuchElementError`. * * **Example** (runtime type check) * @@ -1206,20 +1331,32 @@ export interface YieldableError extends Error, Pipeable { export const isNoSuchElementError: (u: unknown) => u is NoSuchElementError = core.isNoSuchElementError /** - * Unique brand for {@link NoSuchElementError}. + * Unique brand for `NoSuchElementError`. * + * @category type IDs * @since 4.0.0 - * @category symbols */ export const NoSuchElementErrorTypeId: "~effect/Cause/NoSuchElementError" = core.NoSuchElementErrorTypeId /** - * An error indicating that a requested element does not exist. + * An error indicating that an expected value was absent. * - * Thrown by APIs like `Array.head`, `Option.getOrThrow`, `Map.get`, etc. - * when no element matches. Implements {@link YieldableError} so it can be + * **When to use** + * + * Use to model APIs that intentionally turn absence into an error. + * + * **Details** + * + * Used by APIs that convert absence into an exception or effect failure, such + * as `Option.getOrThrow`. Implements `YieldableError` so it can be * yielded directly in `Effect.gen`. * + * **Gotchas** + * + * Prefer APIs that return `Option` or a typed failure when absence is an + * expected case. This error is mainly for APIs that intentionally turn absence + * into a thrown value or failed effect. + * * **Example** (creating and checking) * * ```ts @@ -1230,11 +1367,8 @@ export const NoSuchElementErrorTypeId: "~effect/Cause/NoSuchElementError" = core * console.log(error.message) // "Element not found" * ``` * - * @see {@link isNoSuchElementError} — type guard - * @see {@link NoSuchElementError:var | NoSuchElementError constructor} - * - * @since 4.0.0 * @category errors + * @since 4.0.0 */ export interface NoSuchElementError extends YieldableError { readonly [NoSuchElementErrorTypeId]: typeof NoSuchElementErrorTypeId @@ -1242,7 +1376,12 @@ export interface NoSuchElementError extends YieldableError { } /** - * Constructs a {@link NoSuchElementError} with an optional message. + * Constructs a `NoSuchElementError` with an optional message. + * + * **When to use** + * + * Use to create the error value for APIs that intentionally fail when an + * expected element is absent. * * **Example** (creating a NoSuchElementError) * @@ -1253,13 +1392,15 @@ export interface NoSuchElementError extends YieldableError { * console.log(error.message) // "Element not found" * ``` * + * @see {@link isNoSuchElementError} for checking unknown values + * * @category constructors * @since 4.0.0 */ export const NoSuchElementError: new(message?: string) => NoSuchElementError = core.NoSuchElementError /** - * Tests if an arbitrary value is a {@link Done} signal. + * Checks whether an arbitrary value is a `Done` signal. * * **Example** (runtime type check) * @@ -1276,16 +1417,23 @@ export const NoSuchElementError: new(message?: string) => NoSuchElementError = c export const isDone: (u: unknown) => u is Done = core.isDone /** - * Unique brand for {@link Done} values. + * Unique brand for `Done` values. * + * @category type IDs * @since 4.0.0 - * @category symbols */ export const DoneTypeId: "~effect/Cause/Done" = core.DoneTypeId /** * A graceful completion signal for queues and streams. * + * **When to use** + * + * Use to model normal producer completion through a stream or queue error + * channel. + * + * **Details** + * * `Done` indicates that a producer has finished normally — no more elements * will arrive. It is distinct from an error or interruption; it represents * successful completion. The optional `value` field can carry a final @@ -1306,11 +1454,8 @@ export const DoneTypeId: "~effect/Cause/Done" = core.DoneTypeId * }) * ``` * - * @see {@link isDone} — type guard - * @see {@link done} — create a failing Effect with `Done` - * - * @since 4.0.0 * @category errors + * @since 4.0.0 */ export interface Done { readonly [DoneTypeId]: typeof DoneTypeId @@ -1319,16 +1464,16 @@ export interface Done { } /** - * Companion namespace for the {@link Done} interface. + * Companion namespace for the `Done` interface. * * @since 4.0.0 - * @category errors */ export declare namespace Done { /** * Extracts the value type `A` from a `Done` that may be nested in an * error union. * + * @category utility types * @since 4.0.0 */ export type Extract = E extends Done ? L : never @@ -1336,13 +1481,18 @@ export declare namespace Done { /** * Filters a type union to only keep `Done` members. * + * @category filtering * @since 4.0.0 */ export type Only = E extends Done ? Done : never } /** - * Creates a {@link Done} signal with an optional value. + * Creates a `Done` signal with an optional value. + * + * **When to use** + * + * Use when you need to construct a low-level pull completion signal directly. * * @see {@link done} — create a failing `Effect` with `Done` * @@ -1352,10 +1502,26 @@ export declare namespace Done { export const Done: (value?: A) => Done = core.Done /** - * Creates an Effect that fails with a {@link Done} error. Shorthand for + * Creates an Effect that fails with a `Done` error. Shorthand for * `Effect.fail(Cause.Done(value))`. * - * @see {@link Done:var | Done} — create the signal value without an Effect + * **When to use** + * + * Use when you model stream or queue completion through the error channel. + * + * **Example** (failing with Done) + * + * ```ts + * import { Cause, Effect } from "effect" + * + * const program = Cause.done("finished") + * + * Effect.runPromiseExit(program).then((exit) => { + * console.log(exit._tag) // "Failure" + * }) + * ``` + * + * @see {@link Done} — create the signal value without an Effect * * @category constructors * @since 4.0.0 @@ -1363,15 +1529,15 @@ export const Done: (value?: A) => Done = core.Done export const done: (value?: A) => Effect.Effect> = core.done /** - * Unique brand for {@link TimeoutError}. + * Unique brand for `TimeoutError`. * + * @category type IDs * @since 4.0.0 - * @category symbols */ export const TimeoutErrorTypeId: "~effect/Cause/TimeoutError" = effect.TimeoutErrorTypeId /** - * Tests if an arbitrary value is a {@link TimeoutError}. + * Checks whether an arbitrary value is a `TimeoutError`. * * **Example** (runtime type check) * @@ -1390,8 +1556,10 @@ export const isTimeoutError: (u: unknown) => u is TimeoutError = effect.isTimeou /** * An error indicating that an operation exceeded its time limit. * + * **Details** + * * Produced by `Effect.timeout` and related APIs. Implements - * {@link YieldableError}. + * `YieldableError`. * * **Example** (creating and checking) * @@ -1403,10 +1571,8 @@ export const isTimeoutError: (u: unknown) => u is TimeoutError = effect.isTimeou * console.log(error.message) // "Operation timed out" * ``` * - * @see {@link isTimeoutError} — type guard - * - * @since 4.0.0 * @category errors + * @since 4.0.0 */ export interface TimeoutError extends YieldableError { readonly [TimeoutErrorTypeId]: typeof TimeoutErrorTypeId @@ -1414,7 +1580,7 @@ export interface TimeoutError extends YieldableError { } /** - * Constructs a {@link TimeoutError} with an optional message. + * Constructs a `TimeoutError` with an optional message. * * **Example** (creating a TimeoutError) * @@ -1431,15 +1597,15 @@ export interface TimeoutError extends YieldableError { export const TimeoutError: new(message?: string) => TimeoutError = effect.TimeoutError /** - * Unique brand for {@link IllegalArgumentError}. + * Unique brand for `IllegalArgumentError`. * + * @category type IDs * @since 4.0.0 - * @category symbols */ export const IllegalArgumentErrorTypeId: "~effect/Cause/IllegalArgumentError" = effect.IllegalArgumentErrorTypeId /** - * Tests if an arbitrary value is an {@link IllegalArgumentError}. + * Checks whether an arbitrary value is an `IllegalArgumentError`. * * **Example** (runtime type check) * @@ -1459,7 +1625,9 @@ export const isIllegalArgumentError: (u: unknown) => u is IllegalArgumentError = * An error indicating that a function received an argument that violates * its contract (e.g. negative where positive was expected). * - * Implements {@link YieldableError}. + * **Details** + * + * Implements `YieldableError`. * * **Example** (creating and checking) * @@ -1471,10 +1639,8 @@ export const isIllegalArgumentError: (u: unknown) => u is IllegalArgumentError = * console.log(error.message) // "Expected positive number" * ``` * - * @see {@link isIllegalArgumentError} — type guard - * - * @since 4.0.0 * @category errors + * @since 4.0.0 */ export interface IllegalArgumentError extends YieldableError { readonly [IllegalArgumentErrorTypeId]: typeof IllegalArgumentErrorTypeId @@ -1482,7 +1648,7 @@ export interface IllegalArgumentError extends YieldableError { } /** - * Constructs an {@link IllegalArgumentError} with an optional message. + * Constructs an `IllegalArgumentError` with an optional message. * * **Example** (creating an IllegalArgumentError) * @@ -1499,7 +1665,7 @@ export interface IllegalArgumentError extends YieldableError { export const IllegalArgumentError: new(message?: string) => IllegalArgumentError = effect.IllegalArgumentError /** - * Tests if an arbitrary value is an {@link ExceededCapacityError}. + * Checks whether an arbitrary value is an `ExceededCapacityError`. * * **Example** (runtime type check) * @@ -1516,10 +1682,10 @@ export const IllegalArgumentError: new(message?: string) => IllegalArgumentError export const isExceededCapacityError: (u: unknown) => u is ExceededCapacityError = effect.isExceededCapacityError /** - * Unique brand for {@link ExceededCapacityError}. + * Unique brand for `ExceededCapacityError`. * + * @category type IDs * @since 4.0.0 - * @category symbols */ export const ExceededCapacityErrorTypeId: "~effect/Cause/ExceededCapacityError" = effect.ExceededCapacityErrorTypeId @@ -1527,7 +1693,14 @@ export const ExceededCapacityErrorTypeId: "~effect/Cause/ExceededCapacityError" * An error indicating that a bounded resource (queue, pool, semaphore, etc.) * has exceeded its capacity. * - * Implements {@link YieldableError}. + * **When to use** + * + * Use to model bounded-resource failures where an operation cannot proceed + * because capacity has been exhausted. + * + * **Details** + * + * Implements `YieldableError`. * * **Example** (creating and checking) * @@ -1539,10 +1712,8 @@ export const ExceededCapacityErrorTypeId: "~effect/Cause/ExceededCapacityError" * console.log(error.message) // "Queue full" * ``` * - * @see {@link isExceededCapacityError} — type guard - * - * @since 4.0.0 * @category errors + * @since 4.0.0 */ export interface ExceededCapacityError extends YieldableError { readonly [ExceededCapacityErrorTypeId]: typeof ExceededCapacityErrorTypeId @@ -1550,7 +1721,11 @@ export interface ExceededCapacityError extends YieldableError { } /** - * Constructs an {@link ExceededCapacityError} with an optional message. + * Constructs an `ExceededCapacityError` with an optional message. + * + * **When to use** + * + * Use to create the error value for bounded-resource capacity failures. * * **Example** (creating an ExceededCapacityError) * @@ -1561,20 +1736,38 @@ export interface ExceededCapacityError extends YieldableError { * console.log(error.message) // "Queue full" * ``` * + * @see {@link isExceededCapacityError} for checking unknown values + * * @category constructors * @since 4.0.0 */ export const ExceededCapacityError: new(message?: string) => ExceededCapacityError = effect.ExceededCapacityError /** - * Unique brand for {@link AsyncFiberError}. + * Unique brand present on `AsyncFiberError` values and used by + * `isAsyncFiberError` for runtime checks. * + * @category type IDs * @since 4.0.0 - * @category symbols */ export const AsyncFiberErrorTypeId: "~effect/Cause/AsyncFiberError" = effect.AsyncFiberErrorTypeId /** + * Checks whether an arbitrary value is an `AsyncFiberError`. + * + * **Example** (runtime type check) + * + * ```ts + * import { Cause } from "effect" + * import type { Fiber } from "effect" + * + * declare const fiber: Fiber.Fiber + * + * const error = new Cause.AsyncFiberError(fiber) + * console.log(Cause.isAsyncFiberError(error)) // true + * console.log(Cause.isAsyncFiberError("nope")) // false + * ``` + * * @category guards * @since 4.0.0 */ @@ -1583,8 +1776,31 @@ export const isAsyncFiberError: (u: unknown) => u is AsyncFiberError = effect.is /** * An error that occurs when trying to run an async fiber with Effect.runSync. * - * @since 4.0.0 + * **When to use** + * + * Use to inspect failures produced when synchronous runners encounter an effect + * that cannot complete synchronously. + * + * **Details** + * + * The `fiber` property stores the fiber that could not be synchronously + * resolved. This error implements `YieldableError`. + * + * **Example** (accessing the fiber) + * + * ```ts + * import { Cause } from "effect" + * import type { Fiber } from "effect" + * + * declare const fiber: Fiber.Fiber + * + * const error = new Cause.AsyncFiberError(fiber) + * console.log(error._tag) // "AsyncFiberError" + * console.log(error.fiber === fiber) // true + * ``` + * * @category errors + * @since 4.0.0 */ export interface AsyncFiberError extends YieldableError { readonly [AsyncFiberErrorTypeId]: typeof AsyncFiberErrorTypeId @@ -1593,7 +1809,27 @@ export interface AsyncFiberError extends YieldableError { } /** - * An error that occurs when trying to run an async fiber with Effect.runSync. + * Constructs an `AsyncFiberError` for a fiber that could not be resolved + * synchronously. + * + * **When to use** + * + * Use to create the error value for a fiber that could not be completed by a + * synchronous runner. + * + * **Example** (creating an AsyncFiberError) + * + * ```ts + * import { Cause } from "effect" + * import type { Fiber } from "effect" + * + * declare const fiber: Fiber.Fiber + * + * const error = new Cause.AsyncFiberError(fiber) + * console.log(error.message) // "An asynchronous Effect was executed with Effect.runSync" + * ``` + * + * @see {@link isAsyncFiberError} for checking unknown values * * @category constructors * @since 4.0.0 @@ -1601,15 +1837,15 @@ export interface AsyncFiberError extends YieldableError { export const AsyncFiberError: new(fiber: Fiber) => AsyncFiberError = effect.AsyncFiberError /** - * Unique brand for {@link UnknownError}. + * Unique brand for `UnknownError`. * + * @category type IDs * @since 4.0.0 - * @category symbols */ export const UnknownErrorTypeId: "~effect/Cause/UnknownError" = effect.UnknownErrorTypeId /** - * Tests if an arbitrary value is an {@link UnknownError}. + * Checks whether an arbitrary value is an `UnknownError`. * * **Example** (runtime type check) * @@ -1628,9 +1864,11 @@ export const isUnknownError: (u: unknown) => u is UnknownError = effect.isUnknow /** * A wrapper for errors whose type is not statically known. * - * Produced by the runtime when an effect throws a non-`Error` value. - * The original thrown value is stored in the `cause` property (inherited - * from `Error`). Implements {@link YieldableError}. + * **Details** + * + * Used when a thrown or rejected value is not represented by a more specific + * typed error. The original value is stored in the `cause` property inherited + * from `Error`. Implements `YieldableError`. * * **Example** (creating and checking) * @@ -1642,10 +1880,8 @@ export const isUnknownError: (u: unknown) => u is UnknownError = effect.isUnknow * console.log(error.message) // "Something unknown" * ``` * - * @see {@link isUnknownError} — type guard - * - * @since 4.0.0 * @category errors + * @since 4.0.0 */ export interface UnknownError extends YieldableError { readonly [UnknownErrorTypeId]: typeof UnknownErrorTypeId @@ -1653,7 +1889,7 @@ export interface UnknownError extends YieldableError { } /** - * Constructs an {@link UnknownError}. The first argument is the original + * Constructs an `UnknownError`. The first argument is the original * cause (stored in `Error.cause`); the second is an optional human-readable * message. * @@ -1672,13 +1908,19 @@ export interface UnknownError extends YieldableError { export const UnknownError: new(cause: unknown, message?: string) => UnknownError = effect.UnknownError /** - * Attaches metadata to every reason in a {@link Cause}. + * Attaches metadata to every reason in a `Cause`. + * + * **When to use** + * + * Use to attach diagnostic metadata to every reason in a cause. + * + * **Details** * * Annotations are stored as a `Context` on each reason and can be * retrieved later via {@link reasonAnnotations} or {@link annotations}. * The runtime uses this to attach stack traces and spans. * - * - Returns a new `Cause`; does not mutate the input. + * - Returns a new `Cause`. * - By default, existing keys are preserved. Pass `{ overwrite: true }` to * replace them. * @@ -1687,25 +1929,35 @@ export const UnknownError: new(cause: unknown, message?: string) => UnknownError * ```ts * import { Cause, Context } from "effect" * + * class RequestId extends Context.Service()("RequestId") {} + * * const cause = Cause.fail("error") - * const annotated = Cause.annotate(cause, Context.empty()) + * const annotated = Cause.annotate(cause, Context.make(RequestId, "req-1")) + * + * console.log(Context.getOrUndefined(Cause.annotations(annotated), RequestId)) // "req-1" * ``` * - * @see {@link annotations} — read merged annotations from a cause - * @see {@link reasonAnnotations} — read annotations from a single reason + * @see {@link annotations} for reading merged annotations from a cause + * @see {@link reasonAnnotations} for reading annotations from a single reason * * @category annotations * @since 4.0.0 */ export const annotate: { /** - * Attaches metadata to every reason in a {@link Cause}. + * Attaches metadata to every reason in a `Cause`. + * + * **When to use** + * + * Use to attach diagnostic metadata to every reason in a cause. + * + * **Details** * * Annotations are stored as a `Context` on each reason and can be * retrieved later via {@link reasonAnnotations} or {@link annotations}. * The runtime uses this to attach stack traces and spans. * - * - Returns a new `Cause`; does not mutate the input. + * - Returns a new `Cause`. * - By default, existing keys are preserved. Pass `{ overwrite: true }` to * replace them. * @@ -1714,12 +1966,16 @@ export const annotate: { * ```ts * import { Cause, Context } from "effect" * + * class RequestId extends Context.Service()("RequestId") {} + * * const cause = Cause.fail("error") - * const annotated = Cause.annotate(cause, Context.empty()) + * const annotated = Cause.annotate(cause, Context.make(RequestId, "req-1")) + * + * console.log(Context.getOrUndefined(Cause.annotations(annotated), RequestId)) // "req-1" * ``` * - * @see {@link annotations} — read merged annotations from a cause - * @see {@link reasonAnnotations} — read annotations from a single reason + * @see {@link annotations} for reading merged annotations from a cause + * @see {@link reasonAnnotations} for reading annotations from a single reason * * @category annotations * @since 4.0.0 @@ -1729,13 +1985,19 @@ export const annotate: { options?: { readonly overwrite?: boolean | undefined } ): (self: Cause) => Cause /** - * Attaches metadata to every reason in a {@link Cause}. + * Attaches metadata to every reason in a `Cause`. + * + * **When to use** + * + * Use to attach diagnostic metadata to every reason in a cause. + * + * **Details** * * Annotations are stored as a `Context` on each reason and can be * retrieved later via {@link reasonAnnotations} or {@link annotations}. * The runtime uses this to attach stack traces and spans. * - * - Returns a new `Cause`; does not mutate the input. + * - Returns a new `Cause`. * - By default, existing keys are preserved. Pass `{ overwrite: true }` to * replace them. * @@ -1744,12 +2006,16 @@ export const annotate: { * ```ts * import { Cause, Context } from "effect" * + * class RequestId extends Context.Service()("RequestId") {} + * * const cause = Cause.fail("error") - * const annotated = Cause.annotate(cause, Context.empty()) + * const annotated = Cause.annotate(cause, Context.make(RequestId, "req-1")) + * + * console.log(Context.getOrUndefined(Cause.annotations(annotated), RequestId)) // "req-1" * ``` * - * @see {@link annotations} — read merged annotations from a cause - * @see {@link reasonAnnotations} — read annotations from a single reason + * @see {@link annotations} for reading merged annotations from a cause + * @see {@link reasonAnnotations} for reading annotations from a single reason * * @category annotations * @since 4.0.0 @@ -1762,13 +2028,27 @@ export const annotate: { } = core.causeAnnotate /** - * Reads the annotations from a single {@link Reason} as a `Context`. + * Reads the annotations from a single `Reason` as a `Context`. + * + * **When to use** * - * Use this when you need tracing metadata (e.g. {@link StackTrace}) from + * Use when you need tracing metadata (e.g. `StackTrace`) from * a specific reason rather than the whole cause. * + * **Example** (reading reason annotations) + * + * ```ts + * import { Cause, Context } from "effect" + * + * class RequestId extends Context.Service()("RequestId") {} + * + * const reason = Cause.makeFailReason("error") + * const annotated = reason.annotate(Context.make(RequestId, "req-1")) + * + * console.log(Context.getOrUndefined(Cause.reasonAnnotations(annotated), RequestId)) // "req-1" + * ``` + * * @see {@link annotations} — merged annotations from all reasons in a cause - * @see {@link annotate} — attach annotations * * @category annotations * @since 4.0.0 @@ -1776,12 +2056,33 @@ export const annotate: { export const reasonAnnotations: (self: Reason) => Context.Context = effect.reasonAnnotations /** - * Reads the merged annotations from all reasons in a {@link Cause}. + * Reads the merged annotations from all reasons in a `Cause`. + * + * **When to use** + * + * Use to read diagnostic metadata merged from the whole cause. + * + * **Gotchas** * - * Annotations from later reasons overwrite earlier ones when keys collide. + * When multiple reasons contain the same annotation key, the value from the + * later reason wins. + * + * **Example** (reading merged annotations) + * + * ```ts + * import { Cause, Context } from "effect" + * + * class RequestId extends Context.Service()("RequestId") {} + * + * const cause = Cause.annotate( + * Cause.fail("error"), + * Context.make(RequestId, "req-1") + * ) + * + * console.log(Context.getOrUndefined(Cause.annotations(cause), RequestId)) // "req-1" + * ``` * * @see {@link reasonAnnotations} — annotations from a single reason - * @see {@link annotate} — attach annotations * * @category annotations * @since 4.0.0 @@ -1789,22 +2090,44 @@ export const reasonAnnotations: (self: Reason) => Context.Context = export const annotations: (self: Cause) => Context.Context = effect.causeAnnotations /** - * `Context` key for the stack frame captured at the point of failure. + * Context annotation used to store the stack frame captured at the point of failure. + * + * **When to use** + * + * Use to read the failure stack-frame annotation from a `Reason` when building + * diagnostics, logging, or custom cause renderers. + * + * **Details** * * The runtime annotates every reason with this when a stack frame is * available. Retrieve it via * `Context.get(Cause.reasonAnnotations(reason), Cause.StackTrace)`. * + * @see {@link reasonAnnotations} for reading annotations from a single reason + * @see {@link annotations} for reading merged annotations from a cause + * @see {@link InterruptorStackTrace} for the interrupt-specific stack-frame annotation + * * @category annotations * @since 4.0.0 */ export class StackTrace extends Context.Service()("effect/Cause/StackTrace") {} /** - * `Context` key for the stack frame captured at the point of + * Context annotation used to store the stack frame captured at the point of * interruption. * - * Similar to {@link StackTrace} but specific to {@link Interrupt} reasons. + * **When to use** + * + * Use when you need the stack-frame annotation used by interrupt-only cause + * rendering. + * + * **Details** + * + * Similar to `StackTrace` but specific to `Interrupt` reasons. + * + * @see {@link StackTrace} for stack frames attached to failures + * @see {@link reasonAnnotations} for reading annotations from a single reason + * @see {@link annotate} for attaching annotations to a cause * * @category annotations * @since 4.0.0 diff --git a/.opencode/node_modules/effect/src/Channel.ts b/.opencode/node_modules/effect/src/Channel.ts index 2a23ab1d1d77a42e86cdd0ed166cd2fdd7d8c594..57f33c86d3174b8197a317bd3dd7bc5d9bb9c445 100644 --- a/.opencode/node_modules/effect/src/Channel.ts +++ b/.opencode/node_modules/effect/src/Channel.ts @@ -1,58 +1,11 @@ /** - * The `Channel` module provides a powerful abstraction for bi-directional communication - * and streaming operations. A `Channel` is a nexus of I/O operations that supports both - * reading and writing, forming the foundation for Effect's Stream and Sink abstractions. + * Provides low-level building blocks for streaming data through Effect. * - * ## What is a Channel? - * - * A `Channel` represents: - * - **OutElem**: The type of elements the channel outputs - * - **OutErr**: The type of errors the channel can produce - * - **OutDone**: The type of the final value when the channel completes - * - **InElem**: The type of elements the channel reads - * - **InErr**: The type of errors the channel can receive - * - **InDone**: The type of the final value from upstream - * - **Env**: The environment/context required by the channel - * - * ## Key Features - * - * - **Bi-directional**: Channels can both read and write - * - **Composable**: Channels can be piped, sequenced, and concatenated - * - **Resource-safe**: Automatic cleanup and resource management - * - **Error-handling**: Built-in error propagation and handling - * - **Concurrent**: Support for concurrent operations - * - * ## Composition Patterns - * - * 1. **Piping**: Connect channels where output of one becomes input of another - * 2. **Sequencing**: Use the result of one channel to create another - * 3. **Concatenating**: Combine multiple channels into a single channel - * - * @example - * ```ts - * import { Channel } from "effect" - * - * // Simple channel that outputs numbers - * const numberChannel = Channel.succeed(42) - * - * // Transform channel that doubles values - * const doubleChannel = Channel.map(numberChannel, (n) => n * 2) - * - * // Running the channel would output: 84 - * ``` - * - * @example - * ```ts - * import { Channel } from "effect" - * - * // Channel from an array of values - * const arrayChannel = Channel.fromArray([1, 2, 3, 4, 5]) - * - * // Transform the channel by mapping over values - * const transformedChannel = Channel.map(arrayChannel, (n) => n * 2) - * - * // This channel will output: 2, 4, 6, 8, 10 - * ``` + * A `Channel` can read input elements, write output elements, fail with a typed + * error, and finish with a typed result while managing resources safely. + * Streams and sinks are built on channels, so most application code uses those + * higher-level modules instead. This module is useful when implementing stream + * operators or specialized streaming workflows. * * @since 2.0.0 */ @@ -93,21 +46,27 @@ import type * as Types from "./Types.ts" import type * as Unify from "./Unify.ts" /** + * String literal type used as the unique brand for `Channel` values. + * + * @category type IDs * @since 4.0.0 - * @category Type Identifiers */ export type TypeId = "~effect/Channel" /** + * Runtime identifier stored on `Channel` values and used by `isChannel` to + * recognize them. + * + * @category type IDs * @since 4.0.0 - * @category Type Identifiers */ export const TypeId: TypeId = "~effect/Channel" /** - * Tests if a value is a `Channel`. + * Checks whether a value is a `Channel`. + * + * **Example** (Checking for channels) * - * @example * ```ts * import { Channel } from "effect" * @@ -129,6 +88,8 @@ export const isChannel = ( * `OutElem`. When the channel finishes, it yields a value of type `OutDone`. A * channel may fail with a value of type `OutErr`. * + * **Details** + * * Channels are the foundation of Streams: both streams and sinks are built on * channels. Most users shouldn't have to use channels directly, as streams and * sinks are much more convenient and cover all common use cases. However, when @@ -146,7 +107,8 @@ export const isChannel = ( * channels, which are all concatenated together. The first channel and the * function that makes the other channels can be composed into a channel. * - * @example + * **Example** (Typing channels) + * * ```ts * import type { Channel } from "effect" * @@ -168,8 +130,8 @@ export const isChannel = ( * > * ``` * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface Channel< out OutElem, @@ -186,8 +148,16 @@ export interface Channel< } /** - * @since 2.0.0 + * Type-level unification support for `Channel` values. + * + * **Details** + * + * This preserves all `Channel` type parameters when `Unify` normalizes unions + * or generic return types that include channels. Users normally do not need to + * reference this interface directly. + * * @category models + * @since 2.0.0 */ export interface ChannelUnify extends Effect.EffectUnify { Channel?: () => A[Unify.typeSymbol] extends @@ -197,6 +167,15 @@ export interface ChannelUnify extends Ef } /** + * Marker used by `Unify` while resolving `Channel` values. + * + * **Details** + * + * It prevents the inherited `Effect` unifier from being selected when the + * channel-specific unifier should preserve `Channel` input, output, and + * environment type parameters. Users normally do not need to reference this + * interface directly. + * * @category models * @since 2.0.0 */ @@ -209,8 +188,17 @@ type TagsWithReason = { }[Types.Tags] /** - * @since 2.0.0 + * Phantom variance marker for the type parameters of `Channel`. + * + * **Details** + * + * Output element, output error, output done, and environment types are + * covariant. Input element, input error, and input done types are + * contravariant. This is type-level machinery and is not used directly at + * runtime. + * * @category models + * @since 2.0.0 */ export interface Variance< out OutElem, @@ -224,8 +212,17 @@ export interface Variance< readonly [TypeId]: VarianceStruct } /** - * @since 2.0.0 + * Structural encoding used by `Variance` to record each `Channel` type + * parameter's variance. + * + * **Details** + * + * The `_OutElem`, `_OutErr`, `_OutDone`, and `_Env` fields are covariant; the + * `_InElem`, `_InErr`, and `_InDone` fields are contravariant. Users normally + * do not need to reference this interface directly. + * * @category models + * @since 2.0.0 */ export interface VarianceStruct< out OutElem, @@ -265,7 +262,8 @@ const ChannelProto = { /** * Creates a `Channel` from a transformation function that operates on upstream pulls. * - * @example + * **Example** (Creating channels from transforms) + * * ```ts * import { Channel, Effect } from "effect" * @@ -300,7 +298,8 @@ export const fromTransform = ( * pulls, but also provides a forked scope that closes when the resulting * Channel completes. * - * @since 4.0.0 + * **When to use** + * + * Use when building channels that require scoped resource lifecycle management, + * providing both the channel scope and a forked scope that automatically closes + * when the channel completes. + * + * @see {@link fromTransform} for a simpler transformation without a forked scope * @category constructors + * @since 4.0.0 */ export const fromTransformBracket = ( f: ( @@ -401,7 +408,8 @@ export const fromTransformBracket = ( /** * Creates a `Channel` that interacts with a callback function using a queue. * - * @example + * **Example** (Creating channels from callbacks) + * * ```ts * import { Channel, Effect, Queue } from "effect" * @@ -468,7 +478,7 @@ const asyncQueue = ( * ``` * * @category constructors - * @since 2.0.0 + * @since 4.0.0 */ export const callback = ( f: (queue: Queue.Queue) => Effect.Effect, @@ -482,7 +492,8 @@ export const callback = ( /** * Creates a `Channel` that interacts with a callback function using a queue, emitting arrays. * - * @example + * **Example** (Creating array channels from callbacks) + * * ```ts * import { Channel, Effect, Queue } from "effect" * @@ -508,7 +519,8 @@ export const callbackArray = ( /** * Creates a `Channel` that lazily evaluates to another channel. * - * @example + * **Example** (Suspending channel creation) + * * ```ts * import { Channel } from "effect" * @@ -525,9 +537,17 @@ export const suspend = ( fromTransform((upstream, scope) => Effect.suspend(() => toTransform(evaluate())(upstream, scope))) /** - * Creates a `Channel` with resource management using acquire-use-release pattern. + * Acquires a resource, uses it to build a `Channel`, and guarantees that + * `release` runs with the channel's `Exit` when the channel completes, fails, + * or is interrupted. + * + * **Details** + * + * Acquisition is uninterruptible. If acquisition fails, `use` is not run and + * `release` is not registered. + * + * **Example** (Managing resources with acquire-use-release) * - * @example * ```ts * import { Channel, Effect } from "effect" * @@ -560,9 +580,17 @@ export const acquireUseRelease = (release: (z: Z, e: Exit.Exit) => Effect.Effect): (self: Effect.Effect) => Channel /** - * Creates a `Channel` with resource management using acquire-release pattern. + * Acquires a resource, emits the acquired value as a single channel element, + * and registers `release` in the channel scope. + * + * **Details** + * + * The release action runs when the channel scope closes and receives the scope + * exit. If acquisition fails, no element is emitted and `release` is not + * registered. + * + * **Example** (Managing resources with acquire-release) * - * @example * ```ts * import { Channel, Effect } from "effect" * @@ -607,7 +651,7 @@ export const acquireRelease: { * ``` * * @category constructors - * @since 2.0.0 + * @since 4.0.0 */ ( self: Effect.Effect, @@ -625,7 +669,8 @@ export const acquireRelease: { /** * Creates a `Channel` from an iterator. * - * @example + * **Example** (Creating channels from iterators) + * * ```ts * import { Channel } from "effect" * @@ -635,7 +680,7 @@ export const acquireRelease: { * ``` * * @category constructors - * @since 2.0.0 + * @since 4.0.0 */ export const fromIterator = (iterator: LazyArg>): Channel => fromPull( @@ -651,7 +696,8 @@ export const fromIterator = (iterator: LazyArg>): Channel(iterator: LazyArg>): Channel(array: ReadonlyArray): Channel => fromPull(Effect.sync(() => { @@ -671,7 +717,8 @@ export const fromArray = (array: ReadonlyArray): Channel => /** * Creates a `Channel` that emits all elements from a chunk. * - * @example + * **Example** (Creating channels from chunks) + * * ```ts * import { Channel, Chunk } from "effect" * @@ -681,14 +728,15 @@ export const fromArray = (array: ReadonlyArray): Channel => * ``` * * @category constructors - * @since 2.0.0 + * @since 4.0.0 */ export const fromChunk = (chunk: Chunk.Chunk): Channel => fromArray(Chunk.toReadonlyArray(chunk)) /** * Creates a `Channel` from an iterator that emits arrays of elements. * - * @example + * **Example** (Batching iterator output) + * * ```ts * import { Channel } from "effect" * @@ -709,7 +757,8 @@ export const fromChunk = (chunk: Chunk.Chunk): Channel => fromArray(Chu * // This will emit arrays: [0, 1], [2], then complete with "finished" * ``` * - * @example + * **Example** (Batching generator output) + * * ```ts * import { Channel } from "effect" * @@ -726,8 +775,8 @@ export const fromChunk = (chunk: Chunk.Chunk): Channel => fromArray(Chu * // Emits: [0, 1, 1], [2, 3], then completes * ``` * - * @since 2.0.0 * @category constructors + * @since 4.0.0 */ export const fromIteratorArray = ( iterator: LazyArg>, @@ -759,7 +808,8 @@ export const fromIteratorArray = ( /** * Creates a `Channel` that emits all elements from an iterable. * - * @example + * **Example** (Creating channels from iterables) + * * ```ts * import { Channel } from "effect" * @@ -769,7 +819,7 @@ export const fromIteratorArray = ( * ``` * * @category constructors - * @since 2.0.0 + * @since 4.0.0 */ export const fromIterable = (iterable: Iterable): Channel => fromIterator(() => iterable[Symbol.iterator]()) @@ -777,7 +827,8 @@ export const fromIterable = (iterable: Iterable): Channel(iterable: Iterable): Channel( iterable: Iterable, @@ -797,7 +848,8 @@ export const fromIterableArray = ( /** * Creates a `Channel` that emits a single value and then ends. * - * @example + * **Example** (Creating channels that succeed) + * * ```ts * import { Channel } from "effect" * @@ -813,7 +865,8 @@ export const succeed = (value: A): Channel => fromEffect(Effect.succeed(va /** * Creates a `Channel` that immediately ends with the specified value. * - * @example + * **Example** (Ending with a value) + * * ```ts * import { Channel } from "effect" * @@ -838,12 +891,18 @@ export const endSync = (evaluate: LazyArg): Channel => /** * Creates a `Channel` that emits a single value computed by a lazy evaluation. * - * @example + * **Example** (Computing values lazily) + * * ```ts * import { Channel } from "effect" * - * const channel = Channel.sync(() => Math.random()) - * // Emits a random number computed when the channel runs + * let requests = 0 + * + * const channel = Channel.sync(() => { + * requests += 1 + * return `request-${requests}` + * }) + * // Emits "request-1" when the channel runs for the first time * ``` * * @category constructors @@ -852,9 +911,10 @@ export const endSync = (evaluate: LazyArg): Channel => export const sync = (evaluate: LazyArg): Channel => fromEffect(Effect.sync(evaluate)) /** - * Represents an Channel that emits no elements + * Represents a `Channel` that emits no elements. + * + * **Example** (Using empty channels) * - * @example * ```ts * import { Channel } from "effect" * @@ -870,15 +930,16 @@ export const sync = (evaluate: LazyArg): Channel => fromEffect(Effect.s * shouldEmit ? Channel.succeed("data") : Channel.empty * ``` * - * @since 2.0.0 * @category constructors + * @since 4.0.0 */ export const empty: Channel = fromPull(Effect.succeed(Cause.done())) /** - * Represents an Channel that never completes + * Represents a `Channel` that never completes. + * + * **Example** (Using non-terminating channels) * - * @example * ```ts * import { Channel } from "effect" * @@ -896,15 +957,16 @@ export const empty: Channel = fromPull(Effect.succeed(Cause.done())) * shouldComplete ? Channel.succeed("done") : Channel.never * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const never: Channel = fromPull(Effect.succeed(Effect.never)) /** * Constructs a channel that fails immediately with the specified error. * - * @example + * **Example** (Failing with an error) + * * ```ts * import { Channel } from "effect" * @@ -927,8 +989,8 @@ export const never: Channel = fromPull(Effect.succeed(Effec * ) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const fail = (error: E): Channel => fromPull(Effect.succeed(Effect.fail(error))) @@ -936,7 +998,13 @@ export const fail = (error: E): Channel => fromPull(Effect.s * Constructs a channel that fails immediately with the specified lazily * evaluated error. * - * @example + * **When to use** + * + * Use when the error value should be computed each time the channel runs instead + * of when the channel is constructed. + * + * **Example** (Failing with a lazy error) + * * ```ts * import { Channel } from "effect" * @@ -947,26 +1015,34 @@ export const fail = (error: E): Channel => fromPull(Effect.s * }) * * // The error computation is deferred until the channel runs - * const conditionalError = Channel.failSync(() => - * Math.random() > 0.5 ? "Error A" : "Error B" - * ) + * let attempts = 0 + * const conditionalError = Channel.failSync(() => { + * attempts += 1 + * return `Error after attempt ${attempts}` + * }) * * // Use with expensive error construction * const expensiveError = Channel.failSync(() => { - * const timestamp = Date.now() - * return new Error(`Failed at: ${timestamp}`) + * const requestId = "request-123" + * return new Error(`Failed while processing ${requestId}`) * }) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const failSync = (evaluate: LazyArg): Channel => fromPull(Effect.failSync(evaluate)) /** * Constructs a channel that fails immediately with the specified `Cause`. * - * @example + * **When to use** + * + * Use when the channel failure must preserve a full `Cause`, such as defects, + * interruptions, or combined failures. + * + * **Example** (Failing with causes) + * * ```ts * import { Cause, Channel } from "effect" * @@ -983,8 +1059,8 @@ export const failSync = (evaluate: LazyArg): Channel => f * const simpleFail = Channel.failCause(failCause) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const failCause = (cause: Cause.Cause): Channel => fromPull(Effect.failCause(cause)) @@ -992,25 +1068,27 @@ export const failCause = (cause: Cause.Cause): Channel => * Constructs a channel that fails immediately with the specified lazily * evaluated `Cause`. * - * @example + * **Example** (Failing with lazy causes) + * * ```ts * import { Cause, Channel } from "effect" * * // Create a channel that fails with a lazily computed cause + * let attempts = 0 * const failedChannel = Channel.failCauseSync(() => { - * const errorType = Math.random() > 0.5 ? "A" : "B" - * return Cause.fail(`Runtime error ${errorType}`) + * attempts += 1 + * return Cause.fail(`Runtime error after attempt ${attempts}`) * }) * * // Create a channel with die cause computation * const dieCauseChannel = Channel.failCauseSync(() => { - * const timestamp = Date.now() - * return Cause.die(`Error at ${timestamp}`) + * const operation = "load-profile" + * return Cause.die(`Unexpected defect during ${operation}`) * }) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const failCauseSync = ( evaluate: LazyArg> @@ -1019,7 +1097,8 @@ export const failCauseSync = ( /** * Constructs a channel that fails immediately with the specified defect. * - * @example + * **Example** (Dying with defects) + * * ```ts * import { Channel } from "effect" * @@ -1036,15 +1115,16 @@ export const failCauseSync = ( * }) * ``` * - * @since 2.0.0 * @category constructors + * @since 4.0.0 */ export const die = (defect: unknown): Channel => failCause(Cause.die(defect)) /** - * Use an effect to write a single value to the channel. + * Uses an effect to write a single value to the channel. + * + * **Example** (Creating channels from effects) * - * @example * ```ts * import { Channel, Data, Effect } from "effect" * @@ -1074,8 +1154,8 @@ export const die = (defect: unknown): Channel => failCause( * ) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const fromEffect = ( effect: Effect.Effect @@ -1092,8 +1172,15 @@ export const fromEffect = ( ) /** - * @since 4.0.0 + * Creates a channel that evaluates an effect and uses its successful value as + * the channel's done value without emitting any output elements. + * + * **Details** + * + * If the effect fails, the channel fails with the effect's error. + * * @category constructors + * @since 4.0.0 */ export const fromEffectDone = ( effect: Effect.Effect @@ -1101,18 +1188,26 @@ export const fromEffectDone = ( fromPull(Effect.succeed(Effect.flatMap(effect, Cause.done))) /** - * Use an effect and discard its result. + * Uses an effect and discards its result. * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fromEffectDrain = ( effect: Effect.Effect ): Channel => fromPull(Effect.flatMap(effect, () => Cause.done())) as any /** - * @since 4.0.0 + * Creates a channel from an effect that produces a `Take`. + * + * **Details** + * + * A successful `Take` emits a non-empty array of output elements. A failed + * `Take` fails the channel. A done `Take` completes the channel with its done + * value. + * * @category constructors + * @since 4.0.0 */ export const fromEffectTake = ( effect: Effect.Effect, E2, R> @@ -1120,9 +1215,10 @@ export const fromEffectTake = ( fromPull(Effect.succeed(Effect.flatMap(effect, Take.toPull))) /** - * Create a channel from a queue + * Creates a channel from a queue. + * + * **Example** (Creating channels from queues) * - * @example * ```ts * import { Channel, Data, Effect, Queue } from "effect" * @@ -1154,17 +1250,18 @@ export const fromEffectTake = ( * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 2.0.0 */ export const fromQueue = ( queue: Queue.Dequeue ): Channel> => fromPull(Effect.succeed(Queue.take(queue))) /** - * Create a channel from a queue that emits arrays of elements + * Creates a channel from a queue that emits arrays of elements. + * + * **Example** (Creating batched channels from queues) * - * @example * ```ts * import { Channel, Data, Effect, Queue } from "effect" * @@ -1200,24 +1297,28 @@ export const fromQueue = ( * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fromQueueArray = ( queue: Queue.Dequeue ): Channel, Exclude> => fromPull(Effect.succeed(Queue.takeAll(queue))) /** + * Creates a channel that forwards upstream input elements, input errors, and + * the upstream done value unchanged. + * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const identity = (): Channel => fromTransform((upstream, _scope) => Effect.succeed(upstream)) /** - * Create a channel from a PubSub subscription + * Creates a channel from a PubSub subscription. + * + * **Example** (Creating channels from subscriptions) * - * @example * ```ts * import { Channel, Data, Effect, PubSub } from "effect" * @@ -1254,24 +1355,24 @@ export const identity = (): Channel( subscription: PubSub.Subscription ): Channel => fromPull(Effect.succeed(Effect.onInterrupt(PubSub.take(subscription), () => Cause.done()))) /** - * Create a channel from a PubSub subscription that outputs arrays of values. + * Creates a channel from a PubSub subscription that outputs arrays of values. + * + * **Details** * * This constructor creates a channel that reads from a PubSub subscription and outputs * arrays of values in chunks. It's useful when you want to process multiple values at once * for better performance. * - * @param subscription - The PubSub subscription to read from - * @param chunkSize - The maximum number of elements to read in each chunk (default: 4096) + * **Example** (Batching subscription values) * - * @example * ```ts * import { Channel, Data, Effect, PubSub } from "effect" * @@ -1297,7 +1398,8 @@ export const fromSubscription = ( * }) * ``` * - * @example + * **Example** (Processing subscription values in batches) + * * ```ts * import { Channel, Data, Effect, PubSub } from "effect" * @@ -1322,13 +1424,10 @@ export const fromSubscription = ( * }) * ``` * - * @example - * ```ts - * import { Channel, Data, Effect, PubSub } from "effect" + * **Example** (Aggregating subscription metrics) * - * class MetricsError extends Data.TaggedError("MetricsError")<{ - * readonly cause: string - * }> {} + * ```ts + * import { Channel, Effect, PubSub } from "effect" * * const metricsAggregator = Effect.gen(function*() { * const metricsPubSub = yield* PubSub.bounded< @@ -1353,7 +1452,8 @@ export const fromSubscription = ( * average: avg, * min, * max, - * timestamp: Date.now() + * firstTimestamp: Math.min(...metrics.map((m) => m.timestamp)), + * lastTimestamp: Math.max(...metrics.map((m) => m.timestamp)) * } * }) * @@ -1361,8 +1461,8 @@ export const fromSubscription = ( * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fromSubscriptionArray = ( subscription: PubSub.Subscription @@ -1370,15 +1470,16 @@ export const fromSubscriptionArray = ( fromPull(Effect.succeed(Effect.onInterrupt(PubSub.takeAll(subscription), () => Cause.done()))) /** - * Create a channel from a PubSub that outputs individual values. + * Creates a channel from a PubSub that outputs individual values. + * + * **Details** * * This constructor creates a channel that reads from a PubSub by automatically * subscribing to it. The channel outputs individual values as they are published * to the PubSub, making it ideal for real-time streaming scenarios. * - * @param pubsub - The PubSub to read from + * **Example** (Creating channels from PubSubs) * - * @example * ```ts * import { Channel, Data, Effect, PubSub } from "effect" * @@ -1402,13 +1503,10 @@ export const fromSubscriptionArray = ( * }) * ``` * - * @example - * ```ts - * import { Channel, Data, Effect, PubSub } from "effect" + * **Example** (Streaming PubSub notifications) * - * class NotificationError extends Data.TaggedError("NotificationError")<{ - * readonly reason: string - * }> {} + * ```ts + * import { Channel, Effect, PubSub } from "effect" * * const notificationService = Effect.gen(function*() { * const notificationPubSub = yield* PubSub.bounded(50) @@ -1417,24 +1515,21 @@ export const fromSubscriptionArray = ( * const notificationChannel = Channel.fromPubSub(notificationPubSub) * * // Transform notifications to add timestamps + * const receivedAt = "2024-01-01T00:00:00.000Z" * const timestampedChannel = Channel.map(notificationChannel, (message) => ({ * message, - * timestamp: new Date().toISOString(), - * id: Math.random().toString(36).substr(2, 9) + * receivedAt, + * id: `notification:${message}` * })) * * return timestampedChannel * }) * ``` * - * @example - * ```ts - * import { Channel, Data, Effect, PubSub } from "effect" + * **Example** (Processing PubSub events) * - * class EventProcessingError extends Data.TaggedError("EventProcessingError")<{ - * readonly eventType: string - * readonly cause: string - * }> {} + * ```ts + * import { Channel, Effect, PubSub } from "effect" * * interface DomainEvent { * readonly type: string @@ -1454,7 +1549,7 @@ export const fromSubscriptionArray = ( * return { * ...event, * processed: true, - * processedAt: Date.now() + * processedAt: event.timestamp + 1 * } * } * return event @@ -1464,24 +1559,24 @@ export const fromSubscriptionArray = ( * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 2.0.0 */ export const fromPubSub = ( pubsub: PubSub.PubSub ): Channel => unwrap(Effect.map(PubSub.subscribe(pubsub), fromSubscription)) /** - * Create a channel from a PubSub that outputs arrays of values. + * Creates a channel from a PubSub that outputs arrays of values. + * + * **Details** * * This constructor creates a channel that reads from a PubSub by automatically * subscribing to it and collecting values into arrays. The channel outputs * arrays of values in chunks, making it ideal for batch processing scenarios. * - * @param pubsub - The PubSub to read from - * @param chunkSize - The maximum number of elements to collect in each array (default: 4096) + * **Example** (Batching PubSub values) * - * @example * ```ts * import { Channel, Data, Effect, PubSub } from "effect" * @@ -1506,20 +1601,17 @@ export const fromPubSub = ( * }) * ``` * - * @example - * ```ts - * import { Channel, Data, Effect, PubSub } from "effect" + * **Example** (Processing PubSub orders in batches) * - * class OrderProcessingError extends Data.TaggedError("OrderProcessingError")<{ - * readonly orderId: string - * readonly reason: string - * }> {} + * ```ts + * import { Channel, Effect, PubSub } from "effect" * * interface Order { * readonly id: string * readonly customerId: string * readonly items: ReadonlyArray * readonly total: number + * readonly submittedAt: number * } * * const orderBatchProcessor = Effect.gen(function*() { @@ -1539,7 +1631,7 @@ export const fromPubSub = ( * batchSize: orderBatch.length, * totalRevenue, * uniqueCustomers: customerCount, - * processedAt: Date.now(), + * firstSubmittedAt: Math.min(...orderBatch.map((order) => order.submittedAt)), * orders: orderBatch * } * }) @@ -1548,14 +1640,10 @@ export const fromPubSub = ( * }) * ``` * - * @example - * ```ts - * import { Channel, Data, Effect, PubSub } from "effect" + * **Example** (Processing PubSub logs in batches) * - * class LogProcessingError extends Data.TaggedError("LogProcessingError")<{ - * readonly batchId: string - * readonly cause: string - * }> {} + * ```ts + * import { Channel, Effect, PubSub } from "effect" * * interface LogEntry { * readonly timestamp: number @@ -1582,7 +1670,7 @@ export const fromPubSub = ( * } * * return { - * batchId: Math.random().toString(36).substr(2, 9), + * batchId: `${timeRange.start}-${timeRange.end}`, * totalEntries: logBatch.length, * errorCount, * warnCount, @@ -1596,15 +1684,22 @@ export const fromPubSub = ( * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fromPubSubArray = (pubsub: PubSub.PubSub): Channel> => unwrap(Effect.map(PubSub.subscribe(pubsub), fromSubscriptionArray)) /** - * @since 4.0.0 + * Subscribes to a `PubSub` of `Take` values and exposes them as a channel. + * + * **Details** + * + * Output `Take` values are emitted as non-empty arrays. Failed `Take` values + * fail the channel. Done `Take` values complete the channel. + * * @category constructors + * @since 4.0.0 */ export const fromPubSubTake = ( pubsub: PubSub.PubSub> @@ -1614,8 +1709,8 @@ export const fromPubSubTake = ( /** * Creates a Channel from a Schedule. * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fromSchedule = ( schedule: Schedule.Schedule @@ -1623,10 +1718,17 @@ export const fromSchedule = ( fromPull(Effect.map(Schedule.toStepWithSleep(schedule), (step) => step(void 0))) /** - * Creates a Channel from a AsyncIterable. + * Creates a channel that pulls values from an `AsyncIterable`. + * + * **Details** + * + * Each yielded value is emitted as an output element. The iterator's return + * value becomes the channel's done value. Thrown or rejected iterator errors + * are converted with `onError`. If the channel scope closes early and the + * iterator has a `return` method, that method is called. * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fromAsyncIterable = ( iterable: AsyncIterable, @@ -1647,10 +1749,17 @@ export const fromAsyncIterable = ( })) /** - * Creates a Channel from a AsyncIterable that emits arrays of elements. + * Creates a channel from an `AsyncIterable`, emitting each yielded value as a + * single-element non-empty array. + * + * **Details** + * + * The iterator's return value becomes the channel's done value. Thrown or + * rejected iterator errors are converted with `onError`. If the channel scope + * closes early and the iterator has a `return` method, that method is called. * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fromAsyncIterableArray = ( iterable: AsyncIterable, @@ -1660,7 +1769,8 @@ export const fromAsyncIterableArray = ( /** * Maps the output of this channel using the specified function. * - * @example + * **Example** (Mapping channel output) + * * ```ts * import { Channel, Data } from "effect" * @@ -1692,14 +1802,15 @@ export const fromAsyncIterableArray = ( * })) * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const map: { /** * Maps the output of this channel using the specified function. * - * @example + * **Example** (Mapping channel output) + * * ```ts * import { Channel, Data } from "effect" * @@ -1731,8 +1842,8 @@ export const map: { * })) * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (f: (o: OutElem, i: number) => OutElem2): ( self: Channel @@ -1740,7 +1851,8 @@ export const map: { /** * Maps the output of this channel using the specified function. * - * @example + * **Example** (Mapping channel output) + * * ```ts * import { Channel, Data } from "effect" * @@ -1772,8 +1884,8 @@ export const map: { * })) * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ ( self: Channel, @@ -1795,15 +1907,15 @@ export const map: { /** * Maps the done value of this channel using the specified function. * - * @since 2.0.0 - * @category Sequencing + * @category sequencing + * @since 4.0.0 */ export const mapDone: { /** * Maps the done value of this channel using the specified function. * - * @since 2.0.0 - * @category Sequencing + * @category sequencing + * @since 4.0.0 */ (f: (o: OutDone) => OutDone2): ( self: Channel @@ -1811,8 +1923,8 @@ export const mapDone: { /** * Maps the done value of this channel using the specified function. * - * @since 2.0.0 - * @category Sequencing + * @category sequencing + * @since 4.0.0 */ ( self: Channel, @@ -1829,15 +1941,25 @@ export const mapDone: { /** * Maps the done value of this channel using the specified effectful function. * - * @since 2.0.0 - * @category Sequencing + * **When to use** + * + * Use when the terminal done value transformation needs services or can fail, + * while emitted elements should pass through unchanged. + * + * @category sequencing + * @since 4.0.0 */ export const mapDoneEffect: { /** * Maps the done value of this channel using the specified effectful function. * - * @since 2.0.0 - * @category Sequencing + * **When to use** + * + * Use when the terminal done value transformation needs services or can fail, + * while emitted elements should pass through unchanged. + * + * @category sequencing + * @since 4.0.0 */ (f: (o: OutDone) => Effect.Effect): ( self: Channel @@ -1845,8 +1967,13 @@ export const mapDoneEffect: { /** * Maps the done value of this channel using the specified effectful function. * - * @since 2.0.0 - * @category Sequencing + * **When to use** + * + * Use when the terminal done value transformation needs services or can fail, + * while emitted elements should pass through unchanged. + * + * @category sequencing + * @since 4.0.0 */ ( self: Channel, @@ -1870,13 +1997,23 @@ const concurrencyIsSequential = ( ) => concurrency === undefined || (concurrency !== "unbounded" && concurrency <= 1) /** - * Returns a new channel, which sequentially combines this channel, together - * with the provided factory function, which creates a second channel based on - * the output values of this channel. The result is a channel that will first - * perform the functions of this channel, before performing the functions of - * the created channel (including yielding its terminal value). + * Maps each output element with an effectful function, preserving the source + * channel's done value. + * + * **When to use** + * + * Use when transforming each channel output needs an Effect, service + * dependency, failure channel, or configured concurrency. + * + * **Details** + * + * The mapping function receives the output element and its zero-based index. + * By default elements are mapped sequentially. Use `options.concurrency` to + * map multiple elements concurrently, and `options.unordered` to allow + * concurrently mapped outputs to be emitted as soon as they complete. + * + * **Example** (Mapping channel output with effects) * - * @example * ```ts * import { Channel, Data, Effect } from "effect" * @@ -1913,18 +2050,28 @@ const concurrencyIsSequential = ( * ) * ``` * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ export const mapEffect: { /** - * Returns a new channel, which sequentially combines this channel, together - * with the provided factory function, which creates a second channel based on - * the output values of this channel. The result is a channel that will first - * perform the functions of this channel, before performing the functions of - * the created channel (including yielding its terminal value). + * Maps each output element with an effectful function, preserving the source + * channel's done value. + * + * **When to use** + * + * Use when transforming each channel output needs an Effect, service + * dependency, failure channel, or configured concurrency. + * + * **Details** + * + * The mapping function receives the output element and its zero-based index. + * By default elements are mapped sequentially. Use `options.concurrency` to + * map multiple elements concurrently, and `options.unordered` to allow + * concurrently mapped outputs to be emitted as soon as they complete. + * + * **Example** (Mapping channel output with effects) * - * @example * ```ts * import { Channel, Data, Effect } from "effect" * @@ -1961,8 +2108,8 @@ export const mapEffect: { * ) * ``` * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ ( f: (d: OutElem, i: number) => Effect.Effect, @@ -1974,13 +2121,23 @@ export const mapEffect: { self: Channel ) => Channel /** - * Returns a new channel, which sequentially combines this channel, together - * with the provided factory function, which creates a second channel based on - * the output values of this channel. The result is a channel that will first - * perform the functions of this channel, before performing the functions of - * the created channel (including yielding its terminal value). + * Maps each output element with an effectful function, preserving the source + * channel's done value. + * + * **When to use** + * + * Use when transforming each channel output needs an Effect, service + * dependency, failure channel, or configured concurrency. + * + * **Details** + * + * The mapping function receives the output element and its zero-based index. + * By default elements are mapped sequentially. Use `options.concurrency` to + * map multiple elements concurrently, and `options.unordered` to allow + * concurrently mapped outputs to be emitted as soon as they complete. + * + * **Example** (Mapping channel output with effects) * - * @example * ```ts * import { Channel, Data, Effect } from "effect" * @@ -2017,8 +2174,8 @@ export const mapEffect: { * ) * ``` * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ ( self: Channel, @@ -2166,16 +2323,16 @@ const mapEffectConcurrent = < * Returns a new channel which is the same as this one but applies the given * function to the input channel’s input elements. * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ export const mapInput: { /** * Returns a new channel which is the same as this one but applies the given * function to the input channel’s input elements. * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ (f: (i: InElem2) => Effect.Effect): ( self: Channel @@ -2184,8 +2341,8 @@ export const mapInput: { * Returns a new channel which is the same as this one but applies the given * function to the input channel’s input elements. * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ ( self: Channel, @@ -2206,16 +2363,16 @@ export const mapInput: { * Returns a new channel which is the same as this one but applies the given * function to the input errors. * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ export const mapInputError: { /** * Returns a new channel which is the same as this one but applies the given * function to the input errors. * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ (f: (i: InErr2) => Effect.Effect): ( self: Channel @@ -2224,8 +2381,8 @@ export const mapInputError: { * Returns a new channel which is the same as this one but applies the given * function to the input errors. * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ ( self: Channel, @@ -2249,11 +2406,14 @@ export const mapInputError: { * Applies a side effect function to each output element of the channel, * returning a new channel that emits the same elements. * + * **Details** + * * The `tap` function allows you to perform side effects (like logging or * debugging) on each element emitted by a channel without modifying the * elements themselves. * - * @example + * **Example** (Tapping channel output) + * * ```ts * import { Channel, Console, Data } from "effect" * @@ -2274,19 +2434,22 @@ export const mapInputError: { * // Outputs: 1, 2, 3 (while logging each) * ``` * - * @since 4.0.0 * @category sequencing + * @since 4.0.0 */ export const tap: { /** * Applies a side effect function to each output element of the channel, * returning a new channel that emits the same elements. * + * **Details** + * * The `tap` function allows you to perform side effects (like logging or * debugging) on each element emitted by a channel without modifying the * elements themselves. * - * @example + * **Example** (Tapping channel output) + * * ```ts * import { Channel, Console, Data } from "effect" * @@ -2307,8 +2470,8 @@ export const tap: { * // Outputs: 1, 2, 3 (while logging each) * ``` * - * @since 4.0.0 * @category sequencing + * @since 4.0.0 */ ( f: (d: Types.NoInfer) => Effect.Effect, @@ -2322,11 +2485,14 @@ export const tap: { * Applies a side effect function to each output element of the channel, * returning a new channel that emits the same elements. * + * **Details** + * * The `tap` function allows you to perform side effects (like logging or * debugging) on each element emitted by a channel without modifying the * elements themselves. * - * @example + * **Example** (Tapping channel output) + * * ```ts * import { Channel, Console, Data } from "effect" * @@ -2347,8 +2513,8 @@ export const tap: { * // Outputs: 1, 2, 3 (while logging each) * ``` * - * @since 4.0.0 * @category sequencing + * @since 4.0.0 */ ( self: Channel, @@ -2370,13 +2536,18 @@ export const tap: { ) /** - * Returns a new channel, which sequentially combines this channel, together - * with the provided factory function, which creates a second channel based on - * the output values of this channel. The result is a channel that will first - * perform the functions of this channel, before performing the functions of - * the created channel (including yielding its terminal value). + * Maps each output element to a channel and flattens the child channel + * outputs. + * + * **Details** + * + * The source channel's done value is preserved. Child channel done values are + * used only for child-channel completion. By default child channels are run + * sequentially. Use `options.concurrency` and `options.bufferSize` to run child + * channels concurrently. + * + * **Example** (FlatMapping channel output) * - * @example * ```ts * import { Channel, Data } from "effect" * @@ -2398,18 +2569,23 @@ export const tap: { * // Outputs: "item-1-0", "item-2-0", "item-2-1", "item-3-0", "item-3-1", "item-3-2" * ``` * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ export const flatMap: { /** - * Returns a new channel, which sequentially combines this channel, together - * with the provided factory function, which creates a second channel based on - * the output values of this channel. The result is a channel that will first - * perform the functions of this channel, before performing the functions of - * the created channel (including yielding its terminal value). + * Maps each output element to a channel and flattens the child channel + * outputs. + * + * **Details** + * + * The source channel's done value is preserved. Child channel done values are + * used only for child-channel completion. By default child channels are run + * sequentially. Use `options.concurrency` and `options.bufferSize` to run child + * channels concurrently. + * + * **Example** (FlatMapping channel output) * - * @example * ```ts * import { Channel, Data } from "effect" * @@ -2431,8 +2607,8 @@ export const flatMap: { * // Outputs: "item-1-0", "item-2-0", "item-2-1", "item-3-0", "item-3-1", "item-3-2" * ``` * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ ( f: (d: OutElem) => Channel, @@ -2452,13 +2628,18 @@ export const flatMap: { Env1 | Env > /** - * Returns a new channel, which sequentially combines this channel, together - * with the provided factory function, which creates a second channel based on - * the output values of this channel. The result is a channel that will first - * perform the functions of this channel, before performing the functions of - * the created channel (including yielding its terminal value). + * Maps each output element to a channel and flattens the child channel + * outputs. + * + * **Details** + * + * The source channel's done value is preserved. Child channel done values are + * used only for child-channel completion. By default child channels are run + * sequentially. Use `options.concurrency` and `options.bufferSize` to run child + * channels concurrently. + * + * **Example** (FlatMapping channel output) * - * @example * ```ts * import { Channel, Data } from "effect" * @@ -2480,8 +2661,8 @@ export const flatMap: { * // Outputs: "item-1-0", "item-2-0", "item-2-1", "item-3-0", "item-3-1", "item-3-2" * ``` * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ < OutElem, @@ -2645,7 +2826,8 @@ const flatMapConcurrent = < * Concatenates this channel with another channel created from the terminal value * of this channel. The new channel is created using the provided function. * - * @example + * **Example** (Concatenating with completion values) + * * ```ts * import { Channel, Data } from "effect" * @@ -2662,15 +2844,16 @@ const flatMapConcurrent = < * // Outputs: 1, 2, 3, then "Completed processing" * ``` * - * @since 2.0.0 * @category sequencing + * @since 4.0.0 */ export const concatWith: { /** * Concatenates this channel with another channel created from the terminal value * of this channel. The new channel is created using the provided function. * - * @example + * **Example** (Concatenating with completion values) + * * ```ts * import { Channel, Data } from "effect" * @@ -2687,8 +2870,8 @@ export const concatWith: { * // Outputs: 1, 2, 3, then "Completed processing" * ``` * - * @since 2.0.0 * @category sequencing + * @since 4.0.0 */ ( f: (leftover: Types.NoInfer) => Channel @@ -2707,7 +2890,8 @@ export const concatWith: { * Concatenates this channel with another channel created from the terminal value * of this channel. The new channel is created using the provided function. * - * @example + * **Example** (Concatenating with completion values) + * * ```ts * import { Channel, Data } from "effect" * @@ -2724,8 +2908,8 @@ export const concatWith: { * // Outputs: 1, 2, 3, then "Completed processing" * ``` * - * @since 2.0.0 * @category sequencing + * @since 4.0.0 */ < OutElem, @@ -2805,7 +2989,8 @@ export const concatWith: { * Concatenates this channel with another channel, so that the second channel * starts emitting values after the first channel has completed. * - * @example + * **Example** (Concatenating channels) + * * ```ts * import { Channel, Data } from "effect" * @@ -2823,15 +3008,16 @@ export const concatWith: { * // Outputs: 1, 2, 3, "a", "b", "c" * ``` * - * @since 2.0.0 * @category sequencing + * @since 4.0.0 */ export const concat: { /** * Concatenates this channel with another channel, so that the second channel * starts emitting values after the first channel has completed. * - * @example + * **Example** (Concatenating channels) + * * ```ts * import { Channel, Data } from "effect" * @@ -2849,8 +3035,8 @@ export const concat: { * // Outputs: 1, 2, 3, "a", "b", "c" * ``` * - * @since 2.0.0 * @category sequencing + * @since 4.0.0 */ (that: Channel): ( self: Channel @@ -2867,7 +3053,8 @@ export const concat: { * Concatenates this channel with another channel, so that the second channel * starts emitting values after the first channel has completed. * - * @example + * **Example** (Concatenating channels) + * * ```ts * import { Channel, Data } from "effect" * @@ -2885,8 +3072,8 @@ export const concat: { * // Outputs: 1, 2, 3, "a", "b", "c" * ``` * - * @since 2.0.0 * @category sequencing + * @since 4.0.0 */ < OutElem, @@ -2944,25 +3131,39 @@ export const concat: { > => concatWith(self, (_) => that)) /** - * Combines the elements from this channel and the specified channel by - * repeatedly applying the function `f` to extract an element using both sides - * and conceptually "offer" it to the destination channel. `f` can maintain - * some internal state to control the combining process, with the initial - * state being specified by `s`. + * Combines two channels with a stateful pull function. + * + * **When to use** + * + * Use to coordinate pulling from two channels when each output element depends + * on both sides and local state. + * + * **Details** + * + * The combining function receives the current state and pull functions for the + * left and right channels. It returns the next output element together with the + * next state. * - * @since 4.0.0 * @category sequencing + * @since 4.0.0 */ export const combine: { /** - * Combines the elements from this channel and the specified channel by - * repeatedly applying the function `f` to extract an element using both sides - * and conceptually "offer" it to the destination channel. `f` can maintain - * some internal state to control the combining process, with the initial - * state being specified by `s`. + * Combines two channels with a stateful pull function. + * + * **When to use** + * + * Use to coordinate pulling from two channels when each output element depends + * on both sides and local state. + * + * **Details** + * + * The combining function receives the current state and pull functions for the + * left and right channels. It returns the next output element together with the + * next state. * - * @since 4.0.0 * @category sequencing + * @since 4.0.0 */ ( that: Channel, @@ -2982,14 +3183,21 @@ export const combine: { Env | Env2 | R > /** - * Combines the elements from this channel and the specified channel by - * repeatedly applying the function `f` to extract an element using both sides - * and conceptually "offer" it to the destination channel. `f` can maintain - * some internal state to control the combining process, with the initial - * state being specified by `s`. + * Combines two channels with a stateful pull function. + * + * **When to use** + * + * Use to coordinate pulling from two channels when each output element depends + * on both sides and local state. + * + * **Details** + * + * The combining function receives the current state and pull functions for the + * left and right channels. It returns the next output element together with the + * next state. * - * @since 4.0.0 * @category sequencing + * @since 4.0.0 */ < OutElem, @@ -3079,13 +3287,31 @@ export const combine: { }))) /** - * @since 2.0.0 + * Runs a fallback channel if this channel completes without emitting any + * output elements. + * + * **Details** + * + * If the source emits at least one element, the source is used unchanged. If + * the source completes before emitting an element, the fallback function + * receives the source done value and returns the replacement channel. + * * @category sequencing + * @since 4.0.0 */ export const orElseIfEmpty: { /** - * @since 2.0.0 + * Runs a fallback channel if this channel completes without emitting any + * output elements. + * + * **Details** + * + * If the source emits at least one element, the source is used unchanged. If + * the source completes before emitting an element, the fallback function + * receives the source done value and returns the replacement channel. + * * @category sequencing + * @since 4.0.0 */ ( f: (leftover: Types.NoInfer) => Channel @@ -3101,8 +3327,17 @@ export const orElseIfEmpty: { Env1 | Env > /** - * @since 2.0.0 + * Runs a fallback channel if this channel completes without emitting any + * output elements. + * + * **Details** + * + * If the source emits at least one element, the source is used unchanged. If + * the source completes before emitting an element, the fallback function + * receives the source done value and returns the replacement channel. + * * @category sequencing + * @since 4.0.0 */ < OutElem, @@ -3186,9 +3421,10 @@ export const orElseIfEmpty: { )) /** - * Flatten a channel of channels. + * Flattens a channel of channels. + * + * **Example** (Flattening nested channels) * - * @example * ```ts * import { Channel, Data } from "effect" * @@ -3209,8 +3445,8 @@ export const orElseIfEmpty: { * // Outputs: 1, 2, 3, 4, 5, 6 * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const flatten = < OutElem, @@ -3242,7 +3478,8 @@ export const flatten = < /** * Flattens a channel that outputs arrays into a channel that outputs individual elements. * - * @example + * **Example** (Flattening arrays of channel output) + * * ```ts * import { Channel, Data } from "effect" * @@ -3263,8 +3500,8 @@ export const flatten = < * // Outputs: 1, 2, 3, 4, 5, 6, 7, 8, 9 * ``` * + * @category transforming * @since 4.0.0 - * @category utils */ export const flattenArray = < OutElem, @@ -3306,8 +3543,16 @@ export const flattenArray = < }) /** + * Flattens a channel that emits `Take` values into a channel that emits the + * `Take` outputs directly. + * + * **Details** + * + * Output `Take` values are emitted as non-empty arrays. Failed `Take` values + * fail the returned channel. Done `Take` values complete the returned channel. + * + * @category transforming * @since 4.0.0 - * @category utils */ export const flattenTake = < OutElem, @@ -3328,7 +3573,8 @@ export const flattenTake = < * Creates a new channel that consumes all output from the source channel * but emits nothing, preserving only the completion value. * - * @example + * **Example** (Draining channel output) + * * ```ts * import { Channel } from "effect" * @@ -3342,8 +3588,8 @@ export const flattenTake = < * // Useful for consuming side effects without collecting output * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const drain = < OutElem, @@ -3369,15 +3615,15 @@ export const drain = < /** * Repeats this channel according to the provided schedule. * + * @category repetition * @since 4.0.0 - * @category utils */ export const repeat: { /** * Repeats this channel according to the provided schedule. * + * @category repetition * @since 4.0.0 - * @category utils */ ( schedule: @@ -3391,8 +3637,8 @@ export const repeat: { /** * Repeats this channel according to the provided schedule. * + * @category repetition * @since 4.0.0 - * @category utils */ ( self: Channel, @@ -3441,28 +3687,58 @@ export const repeat: { /** * Repeats this channel forever. * + * @category repetition * @since 4.0.0 - * @category utils */ export const forever = ( self: Channel ): Channel => concatWith(self, () => forever(self)) /** + * Runs a schedule step for each output element while preserving the emitted + * elements. + * + * **Details** + * + * The schedule receives each output element as input. Schedule delays are + * applied between emitted elements. If the schedule fails, the returned channel + * fails. If the schedule finishes, the returned channel completes with the + * schedule output. + * + * @category sequencing * @since 4.0.0 - * @category utils */ export const schedule: { /** + * Runs a schedule step for each output element while preserving the emitted + * elements. + * + * **Details** + * + * The schedule receives each output element as input. Schedule delays are + * applied between emitted elements. If the schedule fails, the returned channel + * fails. If the schedule finishes, the returned channel completes with the + * schedule output. + * + * @category sequencing * @since 4.0.0 - * @category utils */ (schedule: Schedule.Schedule, SE, SR>): ( self: Channel ) => Channel /** + * Runs a schedule step for each output element while preserving the emitted + * elements. + * + * **Details** + * + * The schedule receives each output element as input. Schedule delays are + * applied between emitted elements. If the schedule fails, the returned channel + * fails. If the schedule finishes, the returned channel completes with the + * schedule output. + * + * @category sequencing * @since 4.0.0 - * @category utils */ ( self: Channel, @@ -3493,7 +3769,8 @@ export const schedule: { * Filters the output elements of a channel using a predicate function. * Elements that don't match the predicate are discarded. * - * @example + * **Example** (Filtering channel output) + * * ```ts * import { Channel } from "effect" * @@ -3513,15 +3790,16 @@ export const schedule: { * // Outputs: 1, 2, 3 (all typed as numbers) * ``` * - * @since 2.0.0 - * @category Filtering + * @category filtering + * @since 4.0.0 */ export const filter: { /** * Filters the output elements of a channel using a predicate function. * Elements that don't match the predicate are discarded. * - * @example + * **Example** (Filtering channel output) + * * ```ts * import { Channel } from "effect" * @@ -3541,8 +3819,8 @@ export const filter: { * // Outputs: 1, 2, 3 (all typed as numbers) * ``` * - * @since 2.0.0 - * @category Filtering + * @category filtering + * @since 4.0.0 */ (refinement: Predicate.Refinement): ( self: Channel @@ -3551,7 +3829,8 @@ export const filter: { * Filters the output elements of a channel using a predicate function. * Elements that don't match the predicate are discarded. * - * @example + * **Example** (Filtering channel output) + * * ```ts * import { Channel } from "effect" * @@ -3571,8 +3850,8 @@ export const filter: { * // Outputs: 1, 2, 3 (all typed as numbers) * ``` * - * @since 2.0.0 - * @category Filtering + * @category filtering + * @since 4.0.0 */ (predicate: Predicate.Predicate): ( self: Channel @@ -3581,7 +3860,8 @@ export const filter: { * Filters the output elements of a channel using a predicate function. * Elements that don't match the predicate are discarded. * - * @example + * **Example** (Filtering channel output) + * * ```ts * import { Channel } from "effect" * @@ -3601,8 +3881,8 @@ export const filter: { * // Outputs: 1, 2, 3 (all typed as numbers) * ``` * - * @since 2.0.0 - * @category Filtering + * @category filtering + * @since 4.0.0 */ ( self: Channel, @@ -3612,7 +3892,8 @@ export const filter: { * Filters the output elements of a channel using a predicate function. * Elements that don't match the predicate are discarded. * - * @example + * **Example** (Filtering channel output) + * * ```ts * import { Channel } from "effect" * @@ -3632,8 +3913,8 @@ export const filter: { * // Outputs: 1, 2, 3 (all typed as numbers) * ``` * - * @since 2.0.0 - * @category Filtering + * @category filtering + * @since 4.0.0 */ ( self: Channel, @@ -3656,20 +3937,71 @@ export const filter: { )) /** + * Filters and maps output elements using a `Filter`. + * + * **When to use** + * + * Use to keep only channel output elements accepted by a `Filter` and emit + * each filter success value. + * + * **Details** + * + * Successful filter results are emitted as mapped values. Failed filter + * results are discarded. The source channel's errors and done value are + * preserved. + * + * @see {@link filter} for keeping original output elements with a predicate + * @see {@link filterMapEffect} for using an effectful `Filter` + * @see {@link filterMapArray} for filtering arrays of output elements + * + * @category filtering * @since 4.0.0 - * @category Filtering */ export const filterMap: { /** + * Filters and maps output elements using a `Filter`. + * + * **When to use** + * + * Use to keep only channel output elements accepted by a `Filter` and emit + * each filter success value. + * + * **Details** + * + * Successful filter results are emitted as mapped values. Failed filter + * results are discarded. The source channel's errors and done value are + * preserved. + * + * @see {@link filter} for keeping original output elements with a predicate + * @see {@link filterMapEffect} for using an effectful `Filter` + * @see {@link filterMapArray} for filtering arrays of output elements + * + * @category filtering * @since 4.0.0 - * @category Filtering */ (filter: Filter.Filter): ( self: Channel ) => Channel /** + * Filters and maps output elements using a `Filter`. + * + * **When to use** + * + * Use to keep only channel output elements accepted by a `Filter` and emit + * each filter success value. + * + * **Details** + * + * Successful filter results are emitted as mapped values. Failed filter + * results are discarded. The source channel's errors and done value are + * preserved. + * + * @see {@link filter} for keeping original output elements with a predicate + * @see {@link filterMapEffect} for using an effectful `Filter` + * @see {@link filterMapArray} for filtering arrays of output elements + * + * @category filtering * @since 4.0.0 - * @category Filtering */ ( self: Channel, @@ -3693,20 +4025,59 @@ export const filterMap: { )) /** + * Filters output elements with an effectful predicate. + * + * **When to use** + * + * Use when the keep/discard decision depends on an Effect or service and + * predicate failures should fail the returned channel. + * + * **Details** + * + * Elements for which the predicate succeeds with `true` are emitted. Elements + * for which the predicate succeeds with `false` are discarded. Predicate + * failures fail the returned channel. + * + * @category filtering * @since 4.0.0 - * @category Filtering */ export const filterEffect: { /** + * Filters output elements with an effectful predicate. + * + * **When to use** + * + * Use when the keep/discard decision depends on an Effect or service and + * predicate failures should fail the returned channel. + * + * **Details** + * + * Elements for which the predicate succeeds with `true` are emitted. Elements + * for which the predicate succeeds with `false` are discarded. Predicate + * failures fail the returned channel. + * + * @category filtering * @since 4.0.0 - * @category Filtering */ (predicate: (a: OutElem) => Effect.Effect): ( self: Channel ) => Channel /** + * Filters output elements with an effectful predicate. + * + * **When to use** + * + * Use when the keep/discard decision depends on an Effect or service and + * predicate failures should fail the returned channel. + * + * **Details** + * + * Elements for which the predicate succeeds with `true` are emitted. Elements + * for which the predicate succeeds with `false` are discarded. Predicate + * failures fail the returned channel. + * + * @category filtering * @since 4.0.0 - * @category Filtering */ ( self: Channel, @@ -3733,20 +4104,74 @@ export const filterEffect: { )) /** + * Filters and maps output elements using an effectful `Filter`. + * + * **When to use** + * + * Use to apply effectful logic that can discard channel output elements and + * emit transformed values for the elements that pass. + * + * **Details** + * + * Successful filter results are emitted as mapped values. Failed filter + * results are discarded. Failures from the effectful filter fail the returned + * channel. + * + * @see {@link filterMap} for using a synchronous `Filter` + * @see {@link filterEffect} for effectfully keeping original output elements + * @see {@link mapEffect} for effectfully transforming every output element + * @see {@link filterMapArrayEffect} for effectful filtering of array outputs + * + * @category filtering * @since 4.0.0 - * @category Filtering */ export const filterMapEffect: { /** + * Filters and maps output elements using an effectful `Filter`. + * + * **When to use** + * + * Use to apply effectful logic that can discard channel output elements and + * emit transformed values for the elements that pass. + * + * **Details** + * + * Successful filter results are emitted as mapped values. Failed filter + * results are discarded. Failures from the effectful filter fail the returned + * channel. + * + * @see {@link filterMap} for using a synchronous `Filter` + * @see {@link filterEffect} for effectfully keeping original output elements + * @see {@link mapEffect} for effectfully transforming every output element + * @see {@link filterMapArrayEffect} for effectful filtering of array outputs + * + * @category filtering * @since 4.0.0 - * @category Filtering */ (filter: Filter.FilterEffect): ( self: Channel ) => Channel /** + * Filters and maps output elements using an effectful `Filter`. + * + * **When to use** + * + * Use to apply effectful logic that can discard channel output elements and + * emit transformed values for the elements that pass. + * + * **Details** + * + * Successful filter results are emitted as mapped values. Failed filter + * results are discarded. Failures from the effectful filter fail the returned + * channel. + * + * @see {@link filterMap} for using a synchronous `Filter` + * @see {@link filterEffect} for effectfully keeping original output elements + * @see {@link mapEffect} for effectfully transforming every output element + * @see {@link filterMapArrayEffect} for effectful filtering of array outputs + * + * @category filtering * @since 4.0.0 - * @category Filtering */ ( self: Channel, @@ -3776,7 +4201,8 @@ export const filterMapEffect: { * Filters arrays of elements emitted by a channel, applying the filter * to each element within the arrays and only emitting non-empty filtered arrays. * - * @example + * **Example** (Filtering array output) + * * ```ts * import { Array, Channel } from "effect" * @@ -3804,15 +4230,16 @@ export const filterMapEffect: { * // Outputs: [2, 4] (the arrays [1,3,5] and [7,9] are discarded) * ``` * + * @category filtering * @since 4.0.0 - * @category Filtering */ export const filterArray: { /** * Filters arrays of elements emitted by a channel, applying the filter * to each element within the arrays and only emitting non-empty filtered arrays. * - * @example + * **Example** (Filtering array output) + * * ```ts * import { Array, Channel } from "effect" * @@ -3840,8 +4267,8 @@ export const filterArray: { * // Outputs: [2, 4] (the arrays [1,3,5] and [7,9] are discarded) * ``` * + * @category filtering * @since 4.0.0 - * @category Filtering */ (refinement: Predicate.Refinement): ( self: Channel, OutErr, OutDone, InElem, InErr, InDone, Env> @@ -3850,7 +4277,8 @@ export const filterArray: { * Filters arrays of elements emitted by a channel, applying the filter * to each element within the arrays and only emitting non-empty filtered arrays. * - * @example + * **Example** (Filtering array output) + * * ```ts * import { Array, Channel } from "effect" * @@ -3878,8 +4306,8 @@ export const filterArray: { * // Outputs: [2, 4] (the arrays [1,3,5] and [7,9] are discarded) * ``` * + * @category filtering * @since 4.0.0 - * @category Filtering */ (predicate: Predicate.Predicate>): ( self: Channel, OutErr, OutDone, InElem, InErr, InDone, Env> @@ -3888,7 +4316,8 @@ export const filterArray: { * Filters arrays of elements emitted by a channel, applying the filter * to each element within the arrays and only emitting non-empty filtered arrays. * - * @example + * **Example** (Filtering array output) + * * ```ts * import { Array, Channel } from "effect" * @@ -3916,8 +4345,8 @@ export const filterArray: { * // Outputs: [2, 4] (the arrays [1,3,5] and [7,9] are discarded) * ``` * + * @category filtering * @since 4.0.0 - * @category Filtering */ ( self: Channel, OutErr, OutDone, InElem, InErr, InDone, Env>, @@ -3927,7 +4356,8 @@ export const filterArray: { * Filters arrays of elements emitted by a channel, applying the filter * to each element within the arrays and only emitting non-empty filtered arrays. * - * @example + * **Example** (Filtering array output) + * * ```ts * import { Array, Channel } from "effect" * @@ -3955,8 +4385,8 @@ export const filterArray: { * // Outputs: [2, 4] (the arrays [1,3,5] and [7,9] are discarded) * ``` * + * @category filtering * @since 4.0.0 - * @category Filtering */ ( self: Channel, OutErr, OutDone, InElem, InErr, InDone, Env>, @@ -3983,20 +4413,44 @@ export const filterArray: { )))) /** + * Filters and maps each element inside emitted non-empty arrays using a + * `Filter`. + * + * **Details** + * + * Successful filter results are kept as mapped values. Failed filter results + * are removed from the array. Arrays that become empty are discarded. + * + * @category filtering * @since 4.0.0 - * @category Filtering */ export const filterMapArray: { /** + * Filters and maps each element inside emitted non-empty arrays using a + * `Filter`. + * + * **Details** + * + * Successful filter results are kept as mapped values. Failed filter results + * are removed from the array. Arrays that become empty are discarded. + * + * @category filtering * @since 4.0.0 - * @category Filtering */ (filter: Filter.Filter, B, X>): ( self: Channel, OutErr, OutDone, InElem, InErr, InDone, Env> ) => Channel, OutErr, OutDone, InElem, InErr, InDone, Env> /** + * Filters and maps each element inside emitted non-empty arrays using a + * `Filter`. + * + * **Details** + * + * Successful filter results are kept as mapped values. Failed filter results + * are removed from the array. Arrays that become empty are discarded. + * + * @category filtering * @since 4.0.0 - * @category Filtering */ ( self: Channel, OutErr, OutDone, InElem, InErr, InDone, Env>, @@ -4024,13 +4478,41 @@ export const filterMapArray: { )))) /** + * Filters each element inside emitted non-empty arrays with an effectful + * predicate. + * + * **When to use** + * + * Use when filtering array-valued channel outputs requires Effects or services, + * and arrays that become empty should be skipped. + * + * **Details** + * + * The predicate receives the element and its index within the array. Elements + * for which the predicate succeeds with `true` are kept. Arrays that become + * empty are discarded. Predicate failures fail the returned channel. + * + * @category filtering * @since 4.0.0 - * @category Filtering */ export const filterArrayEffect: { /** + * Filters each element inside emitted non-empty arrays with an effectful + * predicate. + * + * **When to use** + * + * Use when filtering array-valued channel outputs requires Effects or services, + * and arrays that become empty should be skipped. + * + * **Details** + * + * The predicate receives the element and its index within the array. Elements + * for which the predicate succeeds with `true` are kept. Arrays that become + * empty are discarded. Predicate failures fail the returned channel. + * + * @category filtering * @since 4.0.0 - * @category Filtering */ ( predicate: (a: Types.NoInfer, index: number) => Effect.Effect @@ -4038,8 +4520,22 @@ export const filterArrayEffect: { self: Channel, OutErr, OutDone, InElem, InErr, InDone, Env> ) => Channel, OutErr | E, OutDone, InElem, InErr, InDone, Env | R> /** + * Filters each element inside emitted non-empty arrays with an effectful + * predicate. + * + * **When to use** + * + * Use when filtering array-valued channel outputs requires Effects or services, + * and arrays that become empty should be skipped. + * + * **Details** + * + * The predicate receives the element and its index within the array. Elements + * for which the predicate succeeds with `true` are kept. Arrays that become + * empty are discarded. Predicate failures fail the returned channel. + * + * @category filtering * @since 4.0.0 - * @category Filtering */ ( self: Channel, OutErr, OutDone, InElem, InErr, InDone, Env>, @@ -4060,20 +4556,62 @@ export const filterArrayEffect: { })) /** + * Filters and maps each element inside emitted non-empty arrays using an + * effectful `Filter`. + * + * **When to use** + * + * Use when array-valued channel outputs need an effectful filter-map that can + * fail and can discard arrays that become empty. + * + * **Details** + * + * Successful filter results are kept as mapped values. Failed filter results + * are removed from the array. Arrays that become empty are discarded. Failures + * from the effectful filter fail the returned channel. + * + * @category filtering * @since 4.0.0 - * @category Filtering */ export const filterMapArrayEffect: { /** + * Filters and maps each element inside emitted non-empty arrays using an + * effectful `Filter`. + * + * **When to use** + * + * Use when array-valued channel outputs need an effectful filter-map that can + * fail and can discard arrays that become empty. + * + * **Details** + * + * Successful filter results are kept as mapped values. Failed filter results + * are removed from the array. Arrays that become empty are discarded. Failures + * from the effectful filter fail the returned channel. + * + * @category filtering * @since 4.0.0 - * @category Filtering */ (filter: Filter.FilterEffect, B, X, EX, RX>): ( self: Channel, OutErr, OutDone, InElem, InErr, InDone, Env> ) => Channel, OutErr | EX, OutDone, InElem, InErr, InDone, Env | RX> /** + * Filters and maps each element inside emitted non-empty arrays using an + * effectful `Filter`. + * + * **When to use** + * + * Use when array-valued channel outputs need an effectful filter-map that can + * fail and can discard arrays that become empty. + * + * **Details** + * + * Successful filter results are kept as mapped values. Failed filter results + * are removed from the array. Arrays that become empty are discarded. Failures + * from the effectful filter fail the returned channel. + * + * @category filtering * @since 4.0.0 - * @category Filtering */ ( self: Channel, OutErr, OutDone, InElem, InErr, InDone, Env>, @@ -4098,9 +4636,10 @@ export const filterMapArrayEffect: { )))) /** - * Statefully maps over a channel with an accumulator, where each element can produce multiple output values. + * Maps over a channel statefully with an accumulator, where each element can produce multiple output values. + * + * **Example** (Mapping with accumulated state) * - * @example * ```ts * import { Channel, Effect } from "effect" * @@ -4131,14 +4670,15 @@ export const filterMapArrayEffect: { * ) * ``` * - * @since 2.0.0 - * @category Sequencing + * @category sequencing + * @since 4.0.0 */ export const mapAccum: { /** - * Statefully maps over a channel with an accumulator, where each element can produce multiple output values. + * Maps over a channel statefully with an accumulator, where each element can produce multiple output values. + * + * **Example** (Mapping with accumulated state) * - * @example * ```ts * import { Channel, Effect } from "effect" * @@ -4169,8 +4709,8 @@ export const mapAccum: { * ) * ``` * - * @since 2.0.0 - * @category Sequencing + * @category sequencing + * @since 4.0.0 */ ( initial: LazyArg, @@ -4200,9 +4740,10 @@ export const mapAccum: { Env | R > /** - * Statefully maps over a channel with an accumulator, where each element can produce multiple output values. + * Maps over a channel statefully with an accumulator, where each element can produce multiple output values. + * + * **Example** (Mapping with accumulated state) * - * @example * ```ts * import { Channel, Effect } from "effect" * @@ -4233,8 +4774,8 @@ export const mapAccum: { * ) * ``` * - * @since 2.0.0 - * @category Sequencing + * @category sequencing + * @since 4.0.0 */ ( self: Channel, @@ -4312,10 +4853,11 @@ export const mapAccum: { ) /** - * Statefully transforms a channel by scanning over its output with an accumulator function. + * Transforms a channel statefully by scanning over its output with an accumulator function. * Emits the intermediate results of the scan operation. * - * @example + * **Example** (Scanning channel output) + * * ```ts * import { Channel } from "effect" * @@ -4337,15 +4879,16 @@ export const mapAccum: { * // Outputs: "", "hello", "hello world", "hello world from", "hello world from effect" * ``` * - * @since 2.0.0 - * @category Sequencing + * @category sequencing + * @since 4.0.0 */ export const scan: { /** - * Statefully transforms a channel by scanning over its output with an accumulator function. + * Transforms a channel statefully by scanning over its output with an accumulator function. * Emits the intermediate results of the scan operation. * - * @example + * **Example** (Scanning channel output) + * * ```ts * import { Channel } from "effect" * @@ -4367,8 +4910,8 @@ export const scan: { * // Outputs: "", "hello", "hello world", "hello world from", "hello world from effect" * ``` * - * @since 2.0.0 - * @category Sequencing + * @category sequencing + * @since 4.0.0 */ (initial: S, f: (s: S, a: Types.NoInfer) => S): < OutErr, @@ -4387,10 +4930,11 @@ export const scan: { Env > /** - * Statefully transforms a channel by scanning over its output with an accumulator function. + * Transforms a channel statefully by scanning over its output with an accumulator function. * Emits the intermediate results of the scan operation. * - * @example + * **Example** (Scanning channel output) + * * ```ts * import { Channel } from "effect" * @@ -4412,8 +4956,8 @@ export const scan: { * // Outputs: "", "hello", "hello world", "hello world from", "hello world from effect" * ``` * - * @since 2.0.0 - * @category Sequencing + * @category sequencing + * @since 4.0.0 */ ( self: Channel, @@ -4428,10 +4972,16 @@ export const scan: { scanEffect(self, initial, (s, a) => Effect.succeed(f(s, a)))) /** - * Statefully transforms a channel by scanning over its output with an effectful accumulator function. + * Transforms a channel statefully by scanning over its output with an effectful accumulator function. * Emits the intermediate results of the scan operation. * - * @example + * **When to use** + * + * Use when maintaining accumulated state over channel output requires Effects + * or can fail, while still emitting each intermediate state. + * + * **Example** (Scanning channel output with effects) + * * ```ts * import { Channel, Data, Effect } from "effect" * @@ -4468,16 +5018,22 @@ export const scan: { * ) * ``` * - * @since 2.0.0 - * @category Sequencing + * @category sequencing + * @since 4.0.0 */ export const scanEffect: { /** - * Statefully transforms a channel by scanning over its output with an effectful accumulator function. + * Transforms a channel statefully by scanning over its output with an effectful accumulator function. * Emits the intermediate results of the scan operation. * - * @example - * ```ts + * **When to use** + * + * Use when maintaining accumulated state over channel output requires Effects + * or can fail, while still emitting each intermediate state. + * + * **Example** (Scanning channel output with effects) + * + * ```ts * import { Channel, Data, Effect } from "effect" * * class ScanError extends Data.TaggedError("ScanError")<{ @@ -4513,8 +5069,8 @@ export const scanEffect: { * ) * ``` * - * @since 2.0.0 - * @category Sequencing + * @category sequencing + * @since 4.0.0 */ (initial: S, f: (s: S, a: Types.NoInfer) => Effect.Effect): < OutErr, @@ -4533,10 +5089,16 @@ export const scanEffect: { Env | R > /** - * Statefully transforms a channel by scanning over its output with an effectful accumulator function. + * Transforms a channel statefully by scanning over its output with an effectful accumulator function. * Emits the intermediate results of the scan operation. * - * @example + * **When to use** + * + * Use when maintaining accumulated state over channel output requires Effects + * or can fail, while still emitting each intermediate state. + * + * **Example** (Scanning channel output with effects) + * * ```ts * import { Channel, Data, Effect } from "effect" * @@ -4573,8 +5135,8 @@ export const scanEffect: { * ) * ``` * - * @since 2.0.0 - * @category Sequencing + * @category sequencing + * @since 4.0.0 */ ( self: Channel, @@ -4610,7 +5172,8 @@ export const scanEffect: { * Catches any cause of failure from the channel and allows recovery by * creating a new channel based on the caught cause. * - * @example + * **Example** (Recovering from failure causes) + * * ```ts * import { Cause, Channel, Data } from "effect" * @@ -4638,15 +5201,16 @@ export const scanEffect: { * // The channel recovers gracefully from errors * ``` * - * @since 4.0.0 - * @category Error handling + * @category error handling + * @since 2.0.0 */ export const catchCause: { /** * Catches any cause of failure from the channel and allows recovery by * creating a new channel based on the caught cause. * - * @example + * **Example** (Recovering from failure causes) + * * ```ts * import { Cause, Channel, Data } from "effect" * @@ -4674,8 +5238,8 @@ export const catchCause: { * // The channel recovers gracefully from errors * ``` * - * @since 4.0.0 - * @category Error handling + * @category error handling + * @since 2.0.0 */ ( f: (d: Cause.Cause) => Channel @@ -4699,7 +5263,8 @@ export const catchCause: { * Catches any cause of failure from the channel and allows recovery by * creating a new channel based on the caught cause. * - * @example + * **Example** (Recovering from failure causes) + * * ```ts * import { Cause, Channel, Data } from "effect" * @@ -4727,8 +5292,8 @@ export const catchCause: { * // The channel recovers gracefully from errors * ``` * - * @since 4.0.0 - * @category Error handling + * @category error handling + * @since 2.0.0 */ < OutElem, @@ -4808,13 +5373,39 @@ export const catchCause: { })) /** + * Runs an effect with the full failure `Cause` when the channel fails, then + * fails the returned channel with the original cause. + * + * **When to use** + * + * Use when observing the full channel failure `Cause` is needed without + * changing successful output or replacing the original cause. + * + * **Details** + * + * Use this for observing failures, such as logging or metrics. If the observer + * effect fails, that failure can fail the returned channel. + * + * @category error handling * @since 4.0.0 - * @category Error handling */ export const tapCause: { /** + * Runs an effect with the full failure `Cause` when the channel fails, then + * fails the returned channel with the original cause. + * + * **When to use** + * + * Use when observing the full channel failure `Cause` is needed without + * changing successful output or replacing the original cause. + * + * **Details** + * + * Use this for observing failures, such as logging or metrics. If the observer + * effect fails, that failure can fail the returned channel. + * + * @category error handling * @since 4.0.0 - * @category Error handling */ (f: (d: Cause.Cause) => Effect.Effect): < OutElem, @@ -4833,8 +5424,21 @@ export const tapCause: { Env | R > /** + * Runs an effect with the full failure `Cause` when the channel fails, then + * fails the returned channel with the original cause. + * + * **When to use** + * + * Use when observing the full channel failure `Cause` is needed without + * changing successful output or replacing the original cause. + * + * **Details** + * + * Use this for observing failures, such as logging or metrics. If the observer + * effect fails, that failure can fail the returned channel. + * + * @category error handling * @since 4.0.0 - * @category Error handling */ < OutElem, @@ -4887,16 +5491,46 @@ export const tapCause: { * Catches causes of failure that match a specific filter, allowing * conditional error recovery based on the type of failure. * + * **When to use** + * + * Use to recover a channel only when its full `Cause` satisfies a boolean + * predicate. + * + * **Details** + * + * When the predicate matches, the recovery function receives the original + * cause. When it does not match, the returned channel fails with the original + * cause. + * + * @see {@link catchCauseFilter} for selecting causes with a `Filter` + * @see {@link catchCause} for recovering from every cause + * @see {@link catchIf} for recovering from typed channel errors + * + * @category error handling * @since 4.0.0 - * @category Error handling */ export const catchCauseIf: { /** * Catches causes of failure that match a specific filter, allowing * conditional error recovery based on the type of failure. * + * **When to use** + * + * Use to recover a channel only when its full `Cause` satisfies a boolean + * predicate. + * + * **Details** + * + * When the predicate matches, the recovery function receives the original + * cause. When it does not match, the returned channel fails with the original + * cause. + * + * @see {@link catchCauseFilter} for selecting causes with a `Filter` + * @see {@link catchCause} for recovering from every cause + * @see {@link catchIf} for recovering from typed channel errors + * + * @category error handling * @since 4.0.0 - * @category Error handling */ < OutErr, @@ -4930,8 +5564,23 @@ export const catchCauseIf: { * Catches causes of failure that match a specific filter, allowing * conditional error recovery based on the type of failure. * + * **When to use** + * + * Use to recover a channel only when its full `Cause` satisfies a boolean + * predicate. + * + * **Details** + * + * When the predicate matches, the recovery function receives the original + * cause. When it does not match, the returned channel fails with the original + * cause. + * + * @see {@link catchCauseFilter} for selecting causes with a `Filter` + * @see {@link catchCause} for recovering from every cause + * @see {@link catchIf} for recovering from typed channel errors + * + * @category error handling * @since 4.0.0 - * @category Error handling */ < OutElem, @@ -5009,13 +5658,49 @@ export const catchCauseIf: { )) /** + * Recovers from channel failures whose full `Cause` is selected by a `Filter`. + * + * **When to use** + * + * Use when you need to recover a channel only from causes selected by a + * `Filter`, while giving the recovery both the selected value and the original + * `Cause`. + * + * **Details** + * + * When the filter succeeds, the recovery function receives the selected value + * and the original cause. When the filter fails, the returned channel fails + * with the residual cause produced by the filter. + * + * @see {@link catchCauseIf} for selecting causes with a predicate + * @see {@link catchFilter} for selecting typed errors with a `Filter` + * @see {@link catchCause} for recovering from every cause + * + * @category error handling * @since 4.0.0 - * @category Error handling */ export const catchCauseFilter: { /** + * Recovers from channel failures whose full `Cause` is selected by a `Filter`. + * + * **When to use** + * + * Use when you need to recover a channel only from causes selected by a + * `Filter`, while giving the recovery both the selected value and the original + * `Cause`. + * + * **Details** + * + * When the filter succeeds, the recovery function receives the selected value + * and the original cause. When the filter fails, the returned channel fails + * with the residual cause produced by the filter. + * + * @see {@link catchCauseIf} for selecting causes with a predicate + * @see {@link catchFilter} for selecting typed errors with a `Filter` + * @see {@link catchCause} for recovering from every cause + * + * @category error handling * @since 4.0.0 - * @category Error handling */ < OutErr, @@ -5051,8 +5736,26 @@ export const catchCauseFilter: { Env | Env1 > /** + * Recovers from channel failures whose full `Cause` is selected by a `Filter`. + * + * **When to use** + * + * Use when you need to recover a channel only from causes selected by a + * `Filter`, while giving the recovery both the selected value and the original + * `Cause`. + * + * **Details** + * + * When the filter succeeds, the recovery function receives the selected value + * and the original cause. When the filter fails, the returned channel fails + * with the residual cause produced by the filter. + * + * @see {@link catchCauseIf} for selecting causes with a predicate + * @see {@link catchFilter} for selecting typed errors with a `Filter` + * @see {@link catchCause} for recovering from every cause + * + * @category error handling * @since 4.0.0 - * @category Error handling */ < OutElem, @@ -5216,20 +5919,38 @@ const catch_: { export { /** + * Recovers from typed channel errors by running a fallback channel. + * + * @category error handling * @since 4.0.0 - * @category Error handling */ catch_ as catch } /** + * Runs an effect when the channel fails with a typed error, then preserves the + * original channel failure. + * + * **Details** + * + * The effect is not run for normal channel completion. If the observer effect + * fails, that failure can fail the returned channel. + * + * @category error handling * @since 4.0.0 - * @category Error handling */ export const tapError: { /** + * Runs an effect when the channel fails with a typed error, then preserves the + * original channel failure. + * + * **Details** + * + * The effect is not run for normal channel completion. If the observer effect + * fails, that failure can fail the returned channel. + * + * @category error handling * @since 4.0.0 - * @category Error handling */ (f: (d: OutErr) => Effect.Effect): < OutElem, @@ -5248,8 +5969,16 @@ export const tapError: { Env | R > /** + * Runs an effect when the channel fails with a typed error, then preserves the + * original channel failure. + * + * **Details** + * + * The effect is not run for normal channel completion. If the observer effect + * fails, that failure can fail the returned channel. + * + * @category error handling * @since 4.0.0 - * @category Error handling */ < OutElem, @@ -5307,13 +6036,49 @@ export const tapError: { )) /** + * Recovers from typed channel errors that match a predicate or refinement. + * + * **When to use** + * + * Use to recover from typed channel errors when a predicate or refinement + * selects the failures that should switch to a recovery channel. + * + * **Details** + * + * Matching errors are handled by the recovery function. Non-matching errors + * are handled by `orElse` when provided. Without `orElse`, non-matching errors + * are re-failed. + * + * @see {@link catch_ catch} for recovering from every typed channel error + * @see {@link catchFilter} for selecting typed errors with a `Filter` + * @see {@link catchTag} for selecting tagged typed errors + * @see {@link catchCauseFilter} for selecting full causes with a `Filter` + * + * @category error handling * @since 4.0.0 - * @category Error handling */ export const catchIf: { /** + * Recovers from typed channel errors that match a predicate or refinement. + * + * **When to use** + * + * Use to recover from typed channel errors when a predicate or refinement + * selects the failures that should switch to a recovery channel. + * + * **Details** + * + * Matching errors are handled by the recovery function. Non-matching errors + * are handled by `orElse` when provided. Without `orElse`, non-matching errors + * are re-failed. + * + * @see {@link catch_ catch} for recovering from every typed channel error + * @see {@link catchFilter} for selecting typed errors with a `Filter` + * @see {@link catchTag} for selecting tagged typed errors + * @see {@link catchCauseFilter} for selecting full causes with a `Filter` + * + * @category error handling * @since 4.0.0 - * @category Error handling */ < OutErr, @@ -5325,8 +6090,8 @@ export const catchIf: { InErr1, InDone1, Env1, - OutElem2 = never, - OutErr2 = Exclude, + OutElem2 = Types.unassigned, + OutErr2 = never, OutDone2 = never, InElem2 = unknown, InErr2 = unknown, @@ -5348,8 +6113,8 @@ export const catchIf: { InDone, Env >(self: Channel) => Channel< - OutElem | OutElem1 | OutElem2, - OutErr1 | OutErr2, + OutElem | OutElem1 | Exclude, + OutErr1 | OutErr2 | (OutElem2 extends Types.unassigned ? Exclude : never), OutDone | OutDone1 | OutDone2, InElem & InElem1 & InElem2, InErr & InErr1 & InErr2, @@ -5357,8 +6122,26 @@ export const catchIf: { Env | Env1 | Env2 > /** + * Recovers from typed channel errors that match a predicate or refinement. + * + * **When to use** + * + * Use to recover from typed channel errors when a predicate or refinement + * selects the failures that should switch to a recovery channel. + * + * **Details** + * + * Matching errors are handled by the recovery function. Non-matching errors + * are handled by `orElse` when provided. Without `orElse`, non-matching errors + * are re-failed. + * + * @see {@link catch_ catch} for recovering from every typed channel error + * @see {@link catchFilter} for selecting typed errors with a `Filter` + * @see {@link catchTag} for selecting tagged typed errors + * @see {@link catchCauseFilter} for selecting full causes with a `Filter` + * + * @category error handling * @since 4.0.0 - * @category Error handling */ < OutErr, @@ -5369,8 +6152,8 @@ export const catchIf: { InErr1, InDone1, Env1, - OutElem2 = never, - OutErr2 = OutErr, + OutElem2 = Types.unassigned, + OutErr2 = never, OutDone2 = never, InElem2 = unknown, InErr2 = unknown, @@ -5392,8 +6175,8 @@ export const catchIf: { InDone, Env >(self: Channel) => Channel< - OutElem | OutElem1 | OutElem2, - OutErr1 | OutErr2, + OutElem | OutElem1 | Exclude, + OutErr1 | OutErr2 | (OutElem2 extends Types.unassigned ? OutErr : never), OutDone | OutDone1 | OutDone2, InElem & InElem1 & InElem2, InErr & InErr1 & InErr2, @@ -5401,8 +6184,26 @@ export const catchIf: { Env | Env1 | Env2 > /** + * Recovers from typed channel errors that match a predicate or refinement. + * + * **When to use** + * + * Use to recover from typed channel errors when a predicate or refinement + * selects the failures that should switch to a recovery channel. + * + * **Details** + * + * Matching errors are handled by the recovery function. Non-matching errors + * are handled by `orElse` when provided. Without `orElse`, non-matching errors + * are re-failed. + * + * @see {@link catch_ catch} for recovering from every typed channel error + * @see {@link catchFilter} for selecting typed errors with a `Filter` + * @see {@link catchTag} for selecting tagged typed errors + * @see {@link catchCauseFilter} for selecting full causes with a `Filter` + * + * @category error handling * @since 4.0.0 - * @category Error handling */ < OutElem, @@ -5420,8 +6221,8 @@ export const catchIf: { InErr1, InDone1, Env1, - OutElem2 = never, - OutErr2 = Exclude, + OutElem2 = Types.unassigned, + OutErr2 = never, OutDone2 = never, InElem2 = unknown, InErr2 = unknown, @@ -5437,8 +6238,8 @@ export const catchIf: { ) => Channel) | undefined ): Channel< - OutElem | OutElem1 | OutElem2, - OutErr1 | OutErr2, + OutElem | OutElem1 | Exclude, + OutErr1 | OutErr2 | (OutElem2 extends Types.unassigned ? Exclude : never), OutDone | OutDone1 | OutDone2, InElem & InElem1 & InElem2, InErr & InErr1 & InErr2, @@ -5446,8 +6247,26 @@ export const catchIf: { Env | Env1 | Env2 > /** + * Recovers from typed channel errors that match a predicate or refinement. + * + * **When to use** + * + * Use to recover from typed channel errors when a predicate or refinement + * selects the failures that should switch to a recovery channel. + * + * **Details** + * + * Matching errors are handled by the recovery function. Non-matching errors + * are handled by `orElse` when provided. Without `orElse`, non-matching errors + * are re-failed. + * + * @see {@link catch_ catch} for recovering from every typed channel error + * @see {@link catchFilter} for selecting typed errors with a `Filter` + * @see {@link catchTag} for selecting tagged typed errors + * @see {@link catchCauseFilter} for selecting full causes with a `Filter` + * + * @category error handling * @since 4.0.0 - * @category Error handling */ < OutElem, @@ -5464,8 +6283,8 @@ export const catchIf: { InErr1, InDone1, Env1, - OutElem2 = never, - OutErr2 = OutErr, + OutElem2 = Types.unassigned, + OutErr2 = never, OutDone2 = never, InElem2 = unknown, InErr2 = unknown, @@ -5481,8 +6300,8 @@ export const catchIf: { ) => Channel) | undefined ): Channel< - OutElem | OutElem1 | OutElem2, - OutErr1 | OutErr2, + OutElem | OutElem1 | Exclude, + OutErr1 | OutErr2 | (OutElem2 extends Types.unassigned ? OutErr : never), OutDone | OutDone1 | OutDone2, InElem & InElem1 & InElem2, InErr & InErr1 & InErr2, @@ -5549,13 +6368,47 @@ export const catchIf: { )) /** + * Recovers from typed channel errors selected by a `Filter`. + * + * **When to use** + * + * Use to recover from channel errors with a reusable `Filter` when matching + * can also narrow or transform the error before choosing the recovery channel. + * + * **Details** + * + * Successful filter results are handled by the recovery function. Failed + * filter results are handled by `orElse` when provided. Without `orElse`, + * failed filter results are re-failed. + * + * @see {@link catchIf} for selecting typed errors with a predicate + * @see {@link catchTag} for selecting tagged typed errors + * @see {@link catchCauseFilter} for selecting full causes with a `Filter` + * + * @category error handling * @since 4.0.0 - * @category Error handling */ export const catchFilter: { /** + * Recovers from typed channel errors selected by a `Filter`. + * + * **When to use** + * + * Use to recover from channel errors with a reusable `Filter` when matching + * can also narrow or transform the error before choosing the recovery channel. + * + * **Details** + * + * Successful filter results are handled by the recovery function. Failed + * filter results are handled by `orElse` when provided. Without `orElse`, + * failed filter results are re-failed. + * + * @see {@link catchIf} for selecting typed errors with a predicate + * @see {@link catchTag} for selecting tagged typed errors + * @see {@link catchCauseFilter} for selecting full causes with a `Filter` + * + * @category error handling * @since 4.0.0 - * @category Error handling */ < OutErr, @@ -5568,8 +6421,8 @@ export const catchFilter: { InErr1, InDone1, Env1, - OutElem2 = never, - OutErr2 = X, + OutElem2 = Types.unassigned, + OutErr2 = never, OutDone2 = never, InElem2 = unknown, InErr2 = unknown, @@ -5591,8 +6444,8 @@ export const catchFilter: { InDone, Env >(self: Channel) => Channel< - OutElem | OutElem1 | OutElem2, - OutErr1 | OutErr2, + OutElem | OutElem1 | Exclude, + OutErr1 | OutErr2 | (OutElem2 extends Types.unassigned ? X : never), OutDone | OutDone1 | OutDone2, InElem & InElem1 & InElem2, InErr & InErr1 & InErr2, @@ -5600,8 +6453,25 @@ export const catchFilter: { Env | Env1 | Env2 > /** + * Recovers from typed channel errors selected by a `Filter`. + * + * **When to use** + * + * Use to recover from channel errors with a reusable `Filter` when matching + * can also narrow or transform the error before choosing the recovery channel. + * + * **Details** + * + * Successful filter results are handled by the recovery function. Failed + * filter results are handled by `orElse` when provided. Without `orElse`, + * failed filter results are re-failed. + * + * @see {@link catchIf} for selecting typed errors with a predicate + * @see {@link catchTag} for selecting tagged typed errors + * @see {@link catchCauseFilter} for selecting full causes with a `Filter` + * + * @category error handling * @since 4.0.0 - * @category Error handling */ < OutElem, @@ -5620,8 +6490,8 @@ export const catchFilter: { InErr1, InDone1, Env1, - OutElem2 = never, - OutErr2 = X, + OutElem2 = Types.unassigned, + OutErr2 = never, OutDone2 = never, InElem2 = unknown, InErr2 = unknown, @@ -5637,8 +6507,8 @@ export const catchFilter: { ) => Channel) | undefined ): Channel< - OutElem | OutElem1 | OutElem2, - OutErr1 | OutErr2, + OutElem | OutElem1 | Exclude, + OutErr1 | OutErr2 | (OutElem2 extends Types.unassigned ? X : never), OutDone | OutDone1 | OutDone2, InElem & InElem1 & InElem2, InErr & InErr1 & InErr2, @@ -5708,13 +6578,29 @@ export const catchFilter: { )) /** + * Recovers from tagged channel errors whose `_tag` matches one or more tags. + * + * **Details** + * + * Matching tagged errors are handled by the recovery function. Non-matching + * errors are handled by `orElse` when provided. Without `orElse`, + * non-matching errors are re-failed. + * + * @category error handling * @since 4.0.0 - * @category Error handling */ export const catchTag: { /** + * Recovers from tagged channel errors whose `_tag` matches one or more tags. + * + * **Details** + * + * Matching tagged errors are handled by the recovery function. Non-matching + * errors are handled by `orElse` when provided. Without `orElse`, + * non-matching errors are re-failed. + * + * @category error handling * @since 4.0.0 - * @category Error handling */ < OutErr, @@ -5726,8 +6612,8 @@ export const catchTag: { InErr1, InDone1, Env1, - OutElem2 = never, - OutErr2 = Types.ExcludeTag ? K[number] : K>, + OutElem2 = Types.unassigned, + OutErr2 = never, OutDone2 = never, InElem2 = unknown, InErr2 = unknown, @@ -5751,8 +6637,12 @@ export const catchTag: { InDone, Env >(self: Channel) => Channel< - OutElem | OutElem1 | OutElem2, - OutErr1 | OutErr2, + OutElem | OutElem1 | Exclude, + | OutErr1 + | OutErr2 + | (OutElem2 extends Types.unassigned + ? Types.ExcludeTag ? K[number] : K> + : never), OutDone | OutDone1 | OutDone2, InElem & InElem1 & InElem2, InErr & InErr1 & InErr2, @@ -5760,8 +6650,16 @@ export const catchTag: { Env | Env1 | Env2 > /** + * Recovers from tagged channel errors whose `_tag` matches one or more tags. + * + * **Details** + * + * Matching tagged errors are handled by the recovery function. Non-matching + * errors are handled by `orElse` when provided. Without `orElse`, + * non-matching errors are re-failed. + * + * @category error handling * @since 4.0.0 - * @category Error handling */ < OutElem, @@ -5779,8 +6677,8 @@ export const catchTag: { InErr1, InDone1, Env1, - OutElem2 = never, - OutErr2 = Types.ExcludeTag ? K[number] : K>, + OutElem2 = Types.unassigned, + OutErr2 = never, OutDone2 = never, InElem2 = unknown, InErr2 = unknown, @@ -5798,8 +6696,12 @@ export const catchTag: { ) => Channel) | undefined ): Channel< - OutElem | OutElem1 | OutElem2, - OutErr1 | OutErr2, + OutElem | OutElem1 | Exclude, + | OutErr1 + | OutErr2 + | (OutElem2 extends Types.unassigned + ? Types.ExcludeTag ? K[number] : K> + : never), OutDone | OutDone1 | OutDone2, InElem & InElem1 & InElem2, InErr & InErr1 & InErr2, @@ -5858,7 +6760,8 @@ export const catchTag: { /** * Catches a specific reason within a tagged error. * - * @example + * **Example** (Recovering from nested reasons) + * * ```ts * import { Channel, Data } from "effect" * @@ -5885,14 +6788,15 @@ export const catchTag: { * ) * ``` * + * @category error handling * @since 4.0.0 - * @category Error handling */ export const catchReason: { /** * Catches a specific reason within a tagged error. * - * @example + * **Example** (Recovering from nested reasons) + * * ```ts * import { Channel, Data } from "effect" * @@ -5919,8 +6823,8 @@ export const catchReason: { * ) * ``` * + * @category error handling * @since 4.0.0 - * @category Error handling */ < OutErr, @@ -5964,7 +6868,10 @@ export const catchReason: { self: Channel ) => Channel< OutElem | OutElem1 | Exclude, - (OutElem2 extends Types.unassigned ? OutErr : Types.ExcludeTag) | OutErr1 | OutErr2, + | Types.ExcludeTag + | OutErr1 + | OutErr2 + | (OutElem2 extends Types.unassigned ? Types.ExtractTag : never), OutDone | OutDone1 | OutDone2, InElem & InElem1 & InElem2, InErr & InErr1 & InErr2, @@ -5974,7 +6881,8 @@ export const catchReason: { /** * Catches a specific reason within a tagged error. * - * @example + * **Example** (Recovering from nested reasons) + * * ```ts * import { Channel, Data } from "effect" * @@ -6001,8 +6909,8 @@ export const catchReason: { * ) * ``` * + * @category error handling * @since 4.0.0 - * @category Error handling */ < OutElem, @@ -6044,7 +6952,10 @@ export const catchReason: { | undefined ): Channel< OutElem | OutElem1 | Exclude, - (OutElem2 extends Types.unassigned ? OutErr : Types.ExcludeTag) | OutErr1 | OutErr2, + | Types.ExcludeTag + | OutErr1 + | OutErr2 + | (OutElem2 extends Types.unassigned ? Types.ExtractTag : never), OutDone | OutDone1 | OutDone2, InElem & InElem1 & InElem2, InErr & InErr1 & InErr2, @@ -6091,7 +7002,10 @@ export const catchReason: { | undefined ): Channel< OutElem | OutElem1 | Exclude, - (OutElem2 extends Types.unassigned ? OutErr : Types.ExcludeTag) | OutErr1 | OutErr2, + | Types.ExcludeTag + | OutErr1 + | OutErr2 + | (OutElem2 extends Types.unassigned ? Types.ExtractTag : never), OutDone | OutDone1 | OutDone2, InElem & InElem1 & InElem2, InErr & InErr1 & InErr2, @@ -6123,15 +7037,15 @@ export const catchReason: { /** * Catches multiple reasons within a tagged error using an object of handlers. * + * @category error handling * @since 4.0.0 - * @category Error handling */ export const catchReasons: { /** * Catches multiple reasons within a tagged error using an object of handlers. * + * @category error handling * @since 4.0.0 - * @category Error handling */ < K extends Types.Tags, @@ -6167,8 +7081,9 @@ export const catchReasons: { [RK in keyof Cases]: Cases[RK] extends (...args: Array) => Channel ? OutElem1 : never }[keyof Cases], - | (OutElem2 extends Types.unassigned ? OutErr : Types.ExcludeTag) + | Types.ExcludeTag | OutErr2 + | (OutElem2 extends Types.unassigned ? Types.ExtractTag : never) | { [RK in keyof Cases]: Cases[RK] extends (...args: Array) => Channel ? OutErr1 : never @@ -6207,8 +7122,8 @@ export const catchReasons: { /** * Catches multiple reasons within a tagged error using an object of handlers. * + * @category error handling * @since 4.0.0 - * @category Error handling */ < OutElem, @@ -6249,8 +7164,9 @@ export const catchReasons: { [RK in keyof Cases]: Cases[RK] extends (...args: Array) => Channel ? OutElem1 : never }[keyof Cases], - | (OutElem2 extends Types.unassigned ? OutErr : Types.ExcludeTag) + | Types.ExcludeTag | OutErr2 + | (OutElem2 extends Types.unassigned ? Types.ExtractTag : never) | { [RK in keyof Cases]: Cases[RK] extends (...args: Array) => Channel ? OutErr1 : never @@ -6309,7 +7225,8 @@ export const catchReasons: { /** * Promotes nested reason errors into the channel error, replacing the parent error. * - * @example + * **Example** (Promoting nested reasons) + * * ```ts * import { Channel, Data } from "effect" * @@ -6332,14 +7249,15 @@ export const catchReasons: { * const unwrapped = channel.pipe(Channel.unwrapReason("AiError")) * ``` * + * @category error handling * @since 4.0.0 - * @category Error handling */ export const unwrapReason: { /** * Promotes nested reason errors into the channel error, replacing the parent error. * - * @example + * **Example** (Promoting nested reasons) + * * ```ts * import { Channel, Data } from "effect" * @@ -6362,8 +7280,8 @@ export const unwrapReason: { * const unwrapped = channel.pipe(Channel.unwrapReason("AiError")) * ``` * + * @category error handling * @since 4.0.0 - * @category Error handling */ < K extends TagsWithReason, @@ -6382,7 +7300,8 @@ export const unwrapReason: { /** * Promotes nested reason errors into the channel error, replacing the parent error. * - * @example + * **Example** (Promoting nested reasons) + * * ```ts * import { Channel, Data } from "effect" * @@ -6405,8 +7324,8 @@ export const unwrapReason: { * const unwrapped = channel.pipe(Channel.unwrapReason("AiError")) * ``` * + * @category error handling * @since 4.0.0 - * @category Error handling */ < OutElem, @@ -6462,8 +7381,8 @@ export const unwrapReason: { * value of the returned channel is created by applying the specified function * to the failure value of this channel. * + * @category error handling * @since 2.0.0 - * @category Error handling */ export const mapError: { /** @@ -6471,8 +7390,8 @@ export const mapError: { * value of the returned channel is created by applying the specified function * to the failure value of this channel. * + * @category error handling * @since 2.0.0 - * @category Error handling */ (f: (err: OutErr) => OutErr2): ( self: Channel @@ -6482,8 +7401,8 @@ export const mapError: { * value of the returned channel is created by applying the specified function * to the failure value of this channel. * + * @category error handling * @since 2.0.0 - * @category Error handling */ ( self: Channel, @@ -6498,7 +7417,8 @@ export const mapError: { * Converts all errors in the channel to defects (unrecoverable failures). * This is useful when you want to treat errors as programming errors. * - * @example + * **Example** (Converting failures to defects) + * * ```ts * import { Channel, Data } from "effect" * @@ -6515,8 +7435,8 @@ export const mapError: { * // Any failure will now become a defect (uncaught exception) * ``` * - * @since 4.0.0 - * @category Error handling + * @category error handling + * @since 2.0.0 */ export const orDie = < OutElem, @@ -6533,10 +7453,12 @@ export const orDie = < /** * Ignores all errors in the channel, converting them to an empty channel. * + * **Details** + * * Use the `log` option to emit the full {@link Cause} when the channel fails. * + * @category error handling * @since 4.0.0 - * @category Error handling */ export const ignore: < Arg extends Channel | { @@ -6588,10 +7510,17 @@ const ignoreCause_ = < /** * Ignores all errors in the channel including defects, converting them to an empty channel. * + * **When to use** + * + * Use when a channel should become best-effort and all failure causes, including + * defects and interruptions, can be converted to empty output. + * + * **Details** + * * Use the `log` option to emit the full {@link Cause} when the channel fails. * + * @category error handling * @since 4.0.0 - * @category Error handling */ export const ignoreCause: < Arg extends Channel | { @@ -6625,16 +7554,16 @@ export const ignoreCause: < * Returns a new channel that retries this channel according to the specified * schedule whenever it fails. * + * @category error handling * @since 4.0.0 - * @category utils */ export const retry: { /** * Returns a new channel that retries this channel according to the specified * schedule whenever it fails. * + * @category error handling * @since 4.0.0 - * @category utils */ ( schedule: @@ -6651,8 +7580,8 @@ export const retry: { * Returns a new channel that retries this channel according to the specified * schedule whenever it fails. * + * @category error handling * @since 4.0.0 - * @category utils */ ( self: Channel, @@ -6707,13 +7636,17 @@ export const retry: { })) /** - * Returns a new channel, which sequentially combines this channel, together - * with the provided factory function, which creates a second channel based on - * the output values of this channel. The result is a channel that will first - * perform the functions of this channel, before performing the functions of - * the created channel (including yielding its terminal value). + * Maps each output element to a channel and emits values from the most recent + * active child channels. + * + * **Details** + * + * With the default concurrency of `1`, starting a new child channel interrupts + * the previous child channel. Use `options.concurrency` to allow more active + * child channels. The source channel's done value is preserved. + * + * **Example** (Switching mapped channels) * - * @example * ```ts * import { Channel, Data } from "effect" * @@ -6733,18 +7666,22 @@ export const retry: { * // Outputs: "value-1", "value-2", "value-3" * ``` * - * @since 2.0.0 * @category sequencing + * @since 4.0.0 */ export const switchMap: { /** - * Returns a new channel, which sequentially combines this channel, together - * with the provided factory function, which creates a second channel based on - * the output values of this channel. The result is a channel that will first - * perform the functions of this channel, before performing the functions of - * the created channel (including yielding its terminal value). + * Maps each output element to a channel and emits values from the most recent + * active child channels. + * + * **Details** + * + * With the default concurrency of `1`, starting a new child channel interrupts + * the previous child channel. Use `options.concurrency` to allow more active + * child channels. The source channel's done value is preserved. + * + * **Example** (Switching mapped channels) * - * @example * ```ts * import { Channel, Data } from "effect" * @@ -6764,8 +7701,8 @@ export const switchMap: { * // Outputs: "value-1", "value-2", "value-3" * ``` * - * @since 2.0.0 * @category sequencing + * @since 4.0.0 */ ( f: (d: OutElem) => Channel, @@ -6785,13 +7722,17 @@ export const switchMap: { Env1 | Env > /** - * Returns a new channel, which sequentially combines this channel, together - * with the provided factory function, which creates a second channel based on - * the output values of this channel. The result is a channel that will first - * perform the functions of this channel, before performing the functions of - * the created channel (including yielding its terminal value). + * Maps each output element to a channel and emits values from the most recent + * active child channels. + * + * **Details** + * + * With the default concurrency of `1`, starting a new child channel interrupts + * the previous child channel. Use `options.concurrency` to allow more active + * child channels. The source channel's done value is preserved. + * + * **Example** (Switching mapped channels) * - * @example * ```ts * import { Channel, Data } from "effect" * @@ -6811,8 +7752,8 @@ export const switchMap: { * // Outputs: "value-1", "value-2", "value-3" * ``` * - * @since 2.0.0 * @category sequencing + * @since 4.0.0 */ < OutElem, @@ -6891,7 +7832,13 @@ export const switchMap: { /** * Merges multiple channels with specified concurrency and buffering options. * - * @example + * **When to use** + * + * Use when channel outputs are themselves channels and multiple inner channels + * should run with configured concurrency and buffering. + * + * **Example** (Merging nested channels) + * * ```ts * import { Channel, Data } from "effect" * @@ -6915,14 +7862,20 @@ export const switchMap: { * // Outputs: 1, 2, 3, 4, 5, 6 (order may vary due to concurrency) * ``` * + * @category combining * @since 2.0.0 - * @category utils */ export const mergeAll: { /** * Merges multiple channels with specified concurrency and buffering options. * - * @example + * **When to use** + * + * Use when channel outputs are themselves channels and multiple inner channels + * should run with configured concurrency and buffering. + * + * **Example** (Merging nested channels) + * * ```ts * import { Channel, Data } from "effect" * @@ -6946,8 +7899,8 @@ export const mergeAll: { * // Outputs: 1, 2, 3, 4, 5, 6 (order may vary due to concurrency) * ``` * + * @category combining * @since 2.0.0 - * @category utils */ ( options: { @@ -6977,7 +7930,13 @@ export const mergeAll: { /** * Merges multiple channels with specified concurrency and buffering options. * - * @example + * **When to use** + * + * Use when channel outputs are themselves channels and multiple inner channels + * should run with configured concurrency and buffering. + * + * **Example** (Merging nested channels) + * * ```ts * import { Channel, Data } from "effect" * @@ -7001,8 +7960,8 @@ export const mergeAll: { * // Outputs: 1, 2, 3, 4, 5, 6 (order may vary due to concurrency) * ``` * + * @category combining * @since 2.0.0 - * @category utils */ ( channels: Channel< @@ -7066,7 +8025,13 @@ export const mergeAll: { const queue = yield* Queue.bounded>( bufferSize @@ -7180,7 +8151,8 @@ export const mergeAll: { /** * Represents strategies for halting merged channels when one completes or fails. * - * @example + * **Example** (Choosing merge halt strategies) + * * ```ts * import type { Channel } from "effect" * @@ -7191,8 +8163,8 @@ export const mergeAll: { * const either: Channel.HaltStrategy = "either" // Stop when either channel halts * ``` * - * @since 2.0.0 * @category models + * @since 4.0.0 */ export type HaltStrategy = "left" | "right" | "both" | "either" @@ -7200,7 +8172,8 @@ export type HaltStrategy = "left" | "right" | "both" | "either" * Returns a new channel, which is the merge of this channel and the specified * channel. * - * @example + * **Example** (Merging channels) + * * ```ts * import { Channel, Data } from "effect" * @@ -7221,15 +8194,16 @@ export type HaltStrategy = "left" | "right" | "both" | "either" * // Order may vary: 1, "a", 2, "b", 3, "c" * ``` * - * @since 2.0.0 - * @category utils + * @category combining + * @since 4.0.0 */ export const merge: { /** * Returns a new channel, which is the merge of this channel and the specified * channel. * - * @example + * **Example** (Merging channels) + * * ```ts * import { Channel, Data } from "effect" * @@ -7250,8 +8224,8 @@ export const merge: { * // Order may vary: 1, "a", 2, "b", 3, "c" * ``` * - * @since 2.0.0 - * @category utils + * @category combining + * @since 4.0.0 */ ( right: Channel, @@ -7273,7 +8247,8 @@ export const merge: { * Returns a new channel, which is the merge of this channel and the specified * channel. * - * @example + * **Example** (Merging channels) + * * ```ts * import { Channel, Data } from "effect" * @@ -7294,8 +8269,8 @@ export const merge: { * // Order may vary: 1, "a", 2, "b", 3, "c" * ``` * - * @since 2.0.0 - * @category utils + * @category combining + * @since 4.0.0 */ < OutElem, @@ -7363,7 +8338,8 @@ export const merge: { * Returns a new channel, which is the merge of this channel and the specified * channel. * - * @example + * **Example** (Merging channels) + * * ```ts * import { Channel, Data } from "effect" * @@ -7384,14 +8360,15 @@ export const merge: { * // Order may vary: 1, "a", 2, "b", 3, "c" * ``` * - * @since 2.0.0 - * @category utils + * @category combining + * @since 4.0.0 */ OutElem | OutElem1, /** * Returns a new channel, which is the merge of this channel and the specified * channel. * - * @example + * **Example** (Merging channels) + * * ```ts * import { Channel, Data } from "effect" * @@ -7412,8 +8389,8 @@ export const merge: { * // Order may vary: 1, "a", 2, "b", 3, "c" * ``` * - * @since 2.0.0 - * @category utils + * @category combining + * @since 4.0.0 */ OutErr | OutErr1 | Cause.Done>(0) yield* Scope.addFinalizer(forkedScope, Queue.shutdown(queue)) @@ -7473,20 +8450,59 @@ export const merge: { }))) /** + * Runs an effect concurrently with a channel while emitting only the channel's + * output elements. + * + * **When to use** + * + * Use when a side effect should run for the lifetime of a channel and only the + * channel's output elements should be emitted. + * + * **Details** + * + * The effect's successful value is ignored. If the effect fails while the + * channel is running, the returned channel fails with that error. + * + * @category combining * @since 4.0.0 - * @category utils */ export const mergeEffect: { /** + * Runs an effect concurrently with a channel while emitting only the channel's + * output elements. + * + * **When to use** + * + * Use when a side effect should run for the lifetime of a channel and only the + * channel's output elements should be emitted. + * + * **Details** + * + * The effect's successful value is ignored. If the effect fails while the + * channel is running, the returned channel fails with that error. + * + * @category combining * @since 4.0.0 - * @category utils */ (effect: Effect.Effect): ( self: Channel ) => Channel /** + * Runs an effect concurrently with a channel while emitting only the channel's + * output elements. + * + * **When to use** + * + * Use when a side effect should run for the lifetime of a channel and only the + * channel's output elements should be emitted. + * + * **Details** + * + * The effect's successful value is ignored. If the effect fails while the + * channel is running, the returned channel fails with that error. + * + * @category combining * @since 4.0.0 - * @category utils */ ( self: Channel, @@ -7507,12 +8523,14 @@ export const mergeEffect: { * standalone `\r` as line terminators. The behavior matches * `String.linesIterator` regardless of how the input is chunked. * + * **Details** + * * A line terminator at the very end of the stream does **not** produce a * trailing empty line (consistent with `String.linesIterator`). Conversely, * if the stream ends without a terminator the final partial line is still * emitted. * - * **Example** + * **Example** (Splitting string chunks into lines) * * ```ts * import { Effect, Stream } from "effect" @@ -7526,8 +8544,8 @@ export const mergeEffect: { * })) * ``` * - * @since 2.0.0 * @category String manipulation + * @since 2.0.0 */ export const splitLines = (): Channel< Arr.NonEmptyReadonlyArray, @@ -7632,8 +8650,16 @@ export const splitLines = (): Channel< ) /** - * @since 4.0.0 + * Decodes incoming `Uint8Array` chunks into strings using `TextDecoder`. + * + * **Details** + * + * Input chunks are decoded with streaming enabled so multi-byte characters may + * span `Uint8Array` boundaries. The optional `encoding` and `options` are + * passed to `TextDecoder`. + * * @category String manipulation + * @since 4.0.0 */ export const decodeText = (encoding?: string, options?: TextDecoderOptions): Channel< Arr.NonEmptyReadonlyArray, @@ -7646,13 +8672,20 @@ export const decodeText = (encoding?: string, options?: TextDecoderOp fromTransform((upstream, _scope) => Effect.sync(() => { const decoder = new TextDecoder(encoding, options) - return Effect.map(upstream, Arr.map((line) => decoder.decode(line))) + const streamOptions = { stream: true } + return Effect.map(upstream, Arr.map((line) => decoder.decode(line, streamOptions))) }) ) /** - * @since 4.0.0 + * Encodes incoming string chunks into `Uint8Array` values using `TextEncoder`. + * + * **Details** + * + * Each string inside an emitted array is encoded independently. + * * @category String manipulation + * @since 4.0.0 */ export const encodeText = (): Channel< Arr.NonEmptyReadonlyArray, @@ -7675,7 +8708,8 @@ export const encodeText = (): Channel< * and the output type of the specified channel, terminating with the value of * the specified channel. * - * @example + * **Example** (Piping one channel into another) + * * ```ts * import { Channel, Data } from "effect" * @@ -7693,8 +8727,8 @@ export const encodeText = (): Channel< * // Outputs: 2, 4, 6 * ``` * + * @category sequencing * @since 2.0.0 - * @category utils */ export const pipeTo: { /** @@ -7703,7 +8737,8 @@ export const pipeTo: { * and the output type of the specified channel, terminating with the value of * the specified channel. * - * @example + * **Example** (Piping one channel into another) + * * ```ts * import { Channel, Data } from "effect" * @@ -7721,8 +8756,8 @@ export const pipeTo: { * // Outputs: 2, 4, 6 * ``` * + * @category sequencing * @since 2.0.0 - * @category utils */ (that: Channel): ( self: Channel @@ -7733,7 +8768,8 @@ export const pipeTo: { * and the output type of the specified channel, terminating with the value of * the specified channel. * - * @example + * **Example** (Piping one channel into another) + * * ```ts * import { Channel, Data } from "effect" * @@ -7751,8 +8787,8 @@ export const pipeTo: { * // Outputs: 2, 4, 6 * ``` * + * @category sequencing * @since 2.0.0 - * @category utils */ ( self: Channel, @@ -7774,7 +8810,8 @@ export const pipeTo: { * specified channel and preserves this channel's failures without providing * them to the other channel for observation. * - * @example + * **Example** (Piping while preserving failures) + * * ```ts * import { Channel, Data } from "effect" * @@ -7792,8 +8829,8 @@ export const pipeTo: { * // Source errors are preserved and not sent to transform channel * ``` * + * @category sequencing * @since 2.0.0 - * @category utils */ export const pipeToOrFail: { /** @@ -7801,7 +8838,8 @@ export const pipeToOrFail: { * specified channel and preserves this channel's failures without providing * them to the other channel for observation. * - * @example + * **Example** (Piping while preserving failures) + * * ```ts * import { Channel, Data } from "effect" * @@ -7819,8 +8857,8 @@ export const pipeToOrFail: { * // Source errors are preserved and not sent to transform channel * ``` * + * @category sequencing * @since 2.0.0 - * @category utils */ (that: Channel): ( self: Channel @@ -7830,7 +8868,8 @@ export const pipeToOrFail: { * specified channel and preserves this channel's failures without providing * them to the other channel for observation. * - * @example + * **Example** (Piping while preserving failures) + * * ```ts * import { Channel, Data } from "effect" * @@ -7848,8 +8887,8 @@ export const pipeToOrFail: { * // Source errors are preserved and not sent to transform channel * ``` * + * @category sequencing * @since 2.0.0 - * @category utils */ ( self: Channel, @@ -7885,7 +8924,8 @@ export const pipeToOrFail: { * Constructs a `Channel` from a scoped effect that will result in a * `Channel` if successful. * - * @example + * **Example** (Unwrapping channel effects) + * * ```ts * import { Channel, Data, Effect } from "effect" * @@ -7904,8 +8944,8 @@ export const pipeToOrFail: { * // The resulting channel outputs: 1, 2, 3 * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const unwrap = ( channel: Effect.Effect, E, R> @@ -7923,62 +8963,90 @@ export const unwrap = ( self: Channel ): Channel> => - fromTransformBracket((upstream, scope, forkedScope) => Scope.provide(toTransform(self)(upstream, scope), forkedScope)) + fromTransformBracket((upstream, scope, forkedScope) => + Effect.map( + Scope.provide(toTransform(self)(upstream, scope), forkedScope), + Scope.provide(forkedScope) + ) + ) /** - * Returns a new channel which embeds the given input handler into a Channel. + * Runs an input handler against the upstream pull while the wrapped channel + * runs without receiving upstream input directly. * - * @example - * ```ts - * import { Channel, Data, Effect } from "effect" + * **Details** * - * class EmbedError extends Data.TaggedError("EmbedError")<{ - * readonly stage: string - * }> {} + * The input handler is forked in the channel scope. The wrapped channel is run + * with an already-completed input. + * + * **Example** (Embedding custom input handling) + * + * ```ts + * import { Channel, Effect } from "effect" * * // Create a base channel * const baseChannel = Channel.fromIterable([1, 2, 3]) * - * // Embed input handling - simplified example + * // Drain the embedded input while the base channel runs * const embeddedChannel = Channel.embedInput( * baseChannel, - * (_upstream) => Effect.void + * (upstream) => + * upstream.pipe( + * Effect.tap((message) => + * Effect.sync(() => console.log(message)) + * ), + * Effect.forever, + * Effect.ignore + * ) * ) * ``` * + * @category sequencing * @since 2.0.0 - * @category utils */ export const embedInput: { /** - * Returns a new channel which embeds the given input handler into a Channel. + * Runs an input handler against the upstream pull while the wrapped channel + * runs without receiving upstream input directly. * - * @example - * ```ts - * import { Channel, Data, Effect } from "effect" + * **Details** * - * class EmbedError extends Data.TaggedError("EmbedError")<{ - * readonly stage: string - * }> {} + * The input handler is forked in the channel scope. The wrapped channel is run + * with an already-completed input. + * + * **Example** (Embedding custom input handling) + * + * ```ts + * import { Channel, Effect } from "effect" * * // Create a base channel * const baseChannel = Channel.fromIterable([1, 2, 3]) * - * // Embed input handling - simplified example + * // Drain the embedded input while the base channel runs * const embeddedChannel = Channel.embedInput( * baseChannel, - * (_upstream) => Effect.void + * (upstream) => + * upstream.pipe( + * Effect.tap((message) => + * Effect.sync(() => console.log(message)) + * ), + * Effect.forever, + * Effect.ignore + * ) * ) * ``` * + * @category sequencing * @since 2.0.0 - * @category utils */ ( input: ( @@ -7988,28 +9056,38 @@ export const embedInput: { self: Channel ) => Channel /** - * Returns a new channel which embeds the given input handler into a Channel. + * Runs an input handler against the upstream pull while the wrapped channel + * runs without receiving upstream input directly. * - * @example - * ```ts - * import { Channel, Data, Effect } from "effect" + * **Details** * - * class EmbedError extends Data.TaggedError("EmbedError")<{ - * readonly stage: string - * }> {} + * The input handler is forked in the channel scope. The wrapped channel is run + * with an already-completed input. + * + * **Example** (Embedding custom input handling) + * + * ```ts + * import { Channel, Effect } from "effect" * * // Create a base channel * const baseChannel = Channel.fromIterable([1, 2, 3]) * - * // Embed input handling - simplified example + * // Drain the embedded input while the base channel runs * const embeddedChannel = Channel.embedInput( * baseChannel, - * (_upstream) => Effect.void + * (upstream) => + * upstream.pipe( + * Effect.tap((message) => + * Effect.sync(() => console.log(message)) + * ), + * Effect.forever, + * Effect.ignore + * ) * ) * ``` * + * @category sequencing * @since 2.0.0 - * @category utils */ ( self: Channel, @@ -8034,19 +9112,55 @@ export const embedInput: { ) /** - * Allows a faster producer to progress independently of a slower consumer by - * buffering up to `capacity` elements in a queue. + * Buffers individual output elements in a queue with the configured `capacity` + * so a faster producer can progress independently of a slower consumer. + * + * **When to use** + * + * Use when output elements can be decoupled from downstream demand and the + * configured backpressure or loss strategy is acceptable. + * + * **Details** + * + * Finite queues use the `strategy` option. The default `"suspend"` strategy + * applies backpressure, while `"dropping"` and `"sliding"` can discard output + * elements when the queue is full. `"unbounded"` capacity does not use a finite + * capacity strategy. + * + * **Gotchas** + * + * Dropping and sliding strategies can lose output elements under backpressure. + * + * @see {@link bufferArray} for buffering elements from array outputs * - * @since 2.0.0 * @category Buffering + * @since 2.0.0 */ export const buffer: { /** - * Allows a faster producer to progress independently of a slower consumer by - * buffering up to `capacity` elements in a queue. + * Buffers individual output elements in a queue with the configured `capacity` + * so a faster producer can progress independently of a slower consumer. + * + * **When to use** + * + * Use when output elements can be decoupled from downstream demand and the + * configured backpressure or loss strategy is acceptable. + * + * **Details** + * + * Finite queues use the `strategy` option. The default `"suspend"` strategy + * applies backpressure, while `"dropping"` and `"sliding"` can discard output + * elements when the queue is full. `"unbounded"` capacity does not use a finite + * capacity strategy. + * + * **Gotchas** + * + * Dropping and sliding strategies can lose output elements under backpressure. + * + * @see {@link bufferArray} for buffering elements from array outputs * - * @since 2.0.0 * @category Buffering + * @since 2.0.0 */ ( options: { readonly capacity: "unbounded" } | { @@ -8057,11 +9171,29 @@ export const buffer: { self: Channel ) => Channel /** - * Allows a faster producer to progress independently of a slower consumer by - * buffering up to `capacity` elements in a queue. + * Buffers individual output elements in a queue with the configured `capacity` + * so a faster producer can progress independently of a slower consumer. + * + * **When to use** + * + * Use when output elements can be decoupled from downstream demand and the + * configured backpressure or loss strategy is acceptable. + * + * **Details** + * + * Finite queues use the `strategy` option. The default `"suspend"` strategy + * applies backpressure, while `"dropping"` and `"sliding"` can discard output + * elements when the queue is full. `"unbounded"` capacity does not use a finite + * capacity strategy. + * + * **Gotchas** + * + * Dropping and sliding strategies can lose output elements under backpressure. + * + * @see {@link bufferArray} for buffering elements from array outputs * - * @since 2.0.0 * @category Buffering + * @since 2.0.0 */ ( self: Channel, @@ -8080,18 +9212,54 @@ export const buffer: { fromTransform(Effect.fnUntraced(function*(upstream, scope) { const pull = yield* toTransform(self)(upstream, scope) const queue = yield* Queue.make>({ capacity: options.capacity === "unbounded" ? undefined : options.capacity, @@ -8108,19 +9276,59 @@ export const buffer: { }))) /** - * Allows a faster producer to progress independently of a slower consumer by - * buffering up to `capacity` elements in a queue. + * Buffers array output elements in a queue with the configured `capacity` so a + * faster producer can progress independently of a slower consumer. + * + * **When to use** + * + * Use when emitted arrays are batches of elements and it is acceptable for + * buffering to flatten and rebuild those batches. + * + * **Details** + * + * Finite queues use the `strategy` option. The default `"suspend"` strategy + * applies backpressure, while `"dropping"` and `"sliding"` can discard output + * elements when the queue is full. `"unbounded"` capacity does not use a finite + * capacity strategy. + * + * **Gotchas** + * + * Input arrays are offered to the queue element-by-element and outputs are + * rebuilt from the currently available queued elements, so upstream array + * boundaries are not preserved. + * + * @see {@link buffer} for buffering output elements without flattening arrays * - * @since 2.0.0 * @category Buffering + * @since 4.0.0 */ export const bufferArray: { /** - * Allows a faster producer to progress independently of a slower consumer by - * buffering up to `capacity` elements in a queue. + * Buffers array output elements in a queue with the configured `capacity` so a + * faster producer can progress independently of a slower consumer. + * + * **When to use** + * + * Use when emitted arrays are batches of elements and it is acceptable for + * buffering to flatten and rebuild those batches. + * + * **Details** + * + * Finite queues use the `strategy` option. The default `"suspend"` strategy + * applies backpressure, while `"dropping"` and `"sliding"` can discard output + * elements when the queue is full. `"unbounded"` capacity does not use a finite + * capacity strategy. + * + * **Gotchas** + * + * Input arrays are offered to the queue element-by-element and outputs are + * rebuilt from the currently available queued elements, so upstream array + * boundaries are not preserved. + * + * @see {@link buffer} for buffering output elements without flattening arrays * - * @since 2.0.0 * @category Buffering + * @since 4.0.0 */ ( options: { readonly capacity: "unbounded" } | { @@ -8131,11 +9339,31 @@ export const bufferArray: { self: Channel, OutErr, OutDone, InElem, InErr, InDone, Env> ) => Channel, OutErr, OutDone, InElem, InErr, InDone, Env> /** - * Allows a faster producer to progress independently of a slower consumer by - * buffering up to `capacity` elements in a queue. + * Buffers array output elements in a queue with the configured `capacity` so a + * faster producer can progress independently of a slower consumer. + * + * **When to use** + * + * Use when emitted arrays are batches of elements and it is acceptable for + * buffering to flatten and rebuild those batches. + * + * **Details** + * + * Finite queues use the `strategy` option. The default `"suspend"` strategy + * applies backpressure, while `"dropping"` and `"sliding"` can discard output + * elements when the queue is full. `"unbounded"` capacity does not use a finite + * capacity strategy. + * + * **Gotchas** + * + * Input arrays are offered to the queue element-by-element and outputs are + * rebuilt from the currently available queued elements, so upstream array + * boundaries are not preserved. + * + * @see {@link buffer} for buffering output elements without flattening arrays * - * @since 2.0.0 * @category Buffering + * @since 4.0.0 */ ( self: Channel, OutErr, OutDone, InElem, InErr, InDone, Env>, @@ -8154,18 +9382,58 @@ export const bufferArray: { fromTransform(Effect.fnUntraced(function*(upstream, scope) { const pull = yield* toTransform(self)(upstream, scope) const queue = yield* Queue.make>({ capacity: options.capacity === "unbounded" ? undefined : options.capacity, @@ -8182,44 +9450,59 @@ export const bufferArray: { }))) /** - * Returns a new channel, which is the same as this one, except it will be - * interrupted when the specified effect completes. If the effect completes - * successfully before the underlying channel is done, then the returned - * channel will yield the success value of the effect as its terminal value. - * On the other hand, if the underlying channel finishes first, then the - * returned channel will yield the success value of the underlying channel as - * its terminal value. + * Interrupts a channel when another effect completes. + * + * **When to use** * + * Use to race channel execution against an external effect whose success can + * become the channel's done value. + * + * **Details** + * + * If the effect completes first, its success value becomes the returned + * channel's done value. If the channel completes first, the original channel's + * done value is preserved. + * + * @category interruption * @since 2.0.0 - * @category utils */ export const interruptWhen: { /** - * Returns a new channel, which is the same as this one, except it will be - * interrupted when the specified effect completes. If the effect completes - * successfully before the underlying channel is done, then the returned - * channel will yield the success value of the effect as its terminal value. - * On the other hand, if the underlying channel finishes first, then the - * returned channel will yield the success value of the underlying channel as - * its terminal value. + * Interrupts a channel when another effect completes. + * + * **When to use** * + * Use to race channel execution against an external effect whose success can + * become the channel's done value. + * + * **Details** + * + * If the effect completes first, its success value becomes the returned + * channel's done value. If the channel completes first, the original channel's + * done value is preserved. + * + * @category interruption * @since 2.0.0 - * @category utils */ (effect: Effect.Effect): ( self: Channel ) => Channel /** - * Returns a new channel, which is the same as this one, except it will be - * interrupted when the specified effect completes. If the effect completes - * successfully before the underlying channel is done, then the returned - * channel will yield the success value of the effect as its terminal value. - * On the other hand, if the underlying channel finishes first, then the - * returned channel will yield the success value of the underlying channel as - * its terminal value. + * Interrupts a channel when another effect completes. + * + * **When to use** * + * Use to race channel execution against an external effect whose success can + * become the channel's done value. + * + * **Details** + * + * If the effect completes first, its success value becomes the returned + * channel's done value. If the channel completes first, the original channel's + * done value is preserved. + * + * @category interruption * @since 2.0.0 - * @category utils */ ( self: Channel, @@ -8236,20 +9519,47 @@ export const interruptWhen: { )) /** + * Stops a channel when the specified effect completes or fails. + * + * **Details** + * + * If the effect completes before the channel is done, its success value becomes + * the returned channel's done value. If the effect fails, the returned channel + * fails with that error. If the channel completes first, the channel's done + * value is preserved. + * + * @category interruption * @since 4.0.0 - * @category utils */ export const haltWhen: { /** + * Stops a channel when the specified effect completes or fails. + * + * **Details** + * + * If the effect completes before the channel is done, its success value becomes + * the returned channel's done value. If the effect fails, the returned channel + * fails with that error. If the channel completes first, the channel's done + * value is preserved. + * + * @category interruption * @since 4.0.0 - * @category utils */ (effect: Effect.Effect): ( self: Channel ) => Channel /** + * Stops a channel when the specified effect completes or fails. + * + * **Details** + * + * If the effect completes before the channel is done, its success value becomes + * the returned channel's done value. If the effect fails, the returned channel + * fails with that error. If the channel completes first, the channel's done + * value is preserved. + * + * @category interruption * @since 4.0.0 - * @category utils */ ( self: Channel, @@ -8275,13 +9585,27 @@ export const haltWhen: { }))) /** + * Attaches a finalizer that runs only when the channel exits with failure. + * + * **Details** + * + * The finalizer receives the failure `Cause`. The original channel failure is + * preserved. The finalizer itself must not fail. + * + * @category error handling * @since 4.0.0 - * @category utils */ export const onError: { /** + * Attaches a finalizer that runs only when the channel exits with failure. + * + * **Details** + * + * The finalizer receives the failure `Cause`. The original channel failure is + * preserved. The finalizer itself must not fail. + * + * @category error handling * @since 4.0.0 - * @category utils */ ( finalizer: (cause: Cause.Cause) => Effect.Effect @@ -8289,8 +9613,15 @@ export const onError: { self: Channel ) => Channel /** + * Attaches a finalizer that runs only when the channel exits with failure. + * + * **Details** + * + * The finalizer receives the failure `Cause`. The original channel failure is + * preserved. The finalizer itself must not fail. + * + * @category error handling * @since 4.0.0 - * @category utils */ ( self: Channel, @@ -8303,11 +9634,11 @@ export const onError: { onExit(self, (exit) => Exit.isFailure(exit) ? finalizer(exit.cause) : Effect.void)) /** - * Returns a new channel with an attached finalizer. The finalizer is - * guaranteed to be executed so long as the channel begins execution (and - * regardless of whether or not it completes). + * Returns a channel with an exit-aware finalizer that is guaranteed to run once + * the channel begins execution, whether it succeeds or fails. + * + * **Example** (Running exit finalizers) * - * @example * ```ts * import { Channel, Console, Data, Exit } from "effect" * @@ -8328,16 +9659,16 @@ export const onError: { * }) * ``` * + * @category resource management * @since 4.0.0 - * @category utils */ export const onExit: { /** - * Returns a new channel with an attached finalizer. The finalizer is - * guaranteed to be executed so long as the channel begins execution (and - * regardless of whether or not it completes). + * Returns a channel with an exit-aware finalizer that is guaranteed to run once + * the channel begins execution, whether it succeeds or fails. + * + * **Example** (Running exit finalizers) * - * @example * ```ts * import { Channel, Console, Data, Exit } from "effect" * @@ -8358,8 +9689,8 @@ export const onExit: { * }) * ``` * + * @category resource management * @since 4.0.0 - * @category utils */ ( finalizer: (e: Exit.Exit) => Effect.Effect @@ -8367,11 +9698,11 @@ export const onExit: { self: Channel ) => Channel /** - * Returns a new channel with an attached finalizer. The finalizer is - * guaranteed to be executed so long as the channel begins execution (and - * regardless of whether or not it completes). + * Returns a channel with an exit-aware finalizer that is guaranteed to run once + * the channel begins execution, whether it succeeds or fails. + * + * **Example** (Running exit finalizers) * - * @example * ```ts * import { Channel, Console, Data, Exit } from "effect" * @@ -8392,8 +9723,8 @@ export const onExit: { * }) * ``` * + * @category resource management * @since 4.0.0 - * @category utils */ ( self: Channel, @@ -8410,20 +9741,41 @@ export const onExit: { )) /** + * Runs an effect before the channel starts. + * + * **Details** + * + * The effect's successful value is ignored. If the effect fails, the returned + * channel fails before running the source channel. + * + * @category hooks * @since 4.0.0 - * @category utils */ export const onStart: { /** + * Runs an effect before the channel starts. + * + * **Details** + * + * The effect's successful value is ignored. If the effect fails, the returned + * channel fails before running the source channel. + * + * @category hooks * @since 4.0.0 - * @category utils */ (onStart: Effect.Effect): ( self: Channel ) => Channel /** + * Runs an effect before the channel starts. + * + * **Details** + * + * The effect's successful value is ignored. If the effect fails, the returned + * channel fails before running the source channel. + * + * @category hooks * @since 4.0.0 - * @category utils */ ( self: Channel, @@ -8435,20 +9787,59 @@ export const onStart: { ): Channel => unwrap(Effect.as(onStart, self))) /** + * Runs an effect the first time the channel emits an output element. + * + * **When to use** + * + * Use when initialization depends on the first output element rather than only + * on channel startup. + * + * **Details** + * + * The effect receives the first emitted element. The first element is still + * emitted unchanged. The effect is not run if the channel completes without + * emitting an element. + * + * @category hooks * @since 4.0.0 - * @category utils */ export const onFirst: { /** + * Runs an effect the first time the channel emits an output element. + * + * **When to use** + * + * Use when initialization depends on the first output element rather than only + * on channel startup. + * + * **Details** + * + * The effect receives the first emitted element. The first element is still + * emitted unchanged. The effect is not run if the channel completes without + * emitting an element. + * + * @category hooks * @since 4.0.0 - * @category utils */ (onFirst: (element: Types.NoInfer) => Effect.Effect): ( self: Channel ) => Channel /** + * Runs an effect the first time the channel emits an output element. + * + * **When to use** + * + * Use when initialization depends on the first output element rather than only + * on channel startup. + * + * **Details** + * + * The effect receives the first emitted element. The first element is still + * emitted unchanged. The effect is not run if the channel completes without + * emitting an element. + * + * @category hooks * @since 4.0.0 - * @category utils */ ( self: Channel, @@ -8469,20 +9860,44 @@ export const onFirst: { }))) /** + * Runs an effect when the channel completes successfully. + * + * **Details** + * + * The effect runs before the original done value is propagated. The effect is + * not run when the channel fails. If the effect fails, the returned channel + * fails with that error. + * + * @category hooks * @since 4.0.0 - * @category utils */ export const onEnd: { /** + * Runs an effect when the channel completes successfully. + * + * **Details** + * + * The effect runs before the original done value is propagated. The effect is + * not run when the channel fails. If the effect fails, the returned channel + * fails with that error. + * + * @category hooks * @since 4.0.0 - * @category utils */ (onEnd: Effect.Effect): ( self: Channel ) => Channel /** + * Runs an effect when the channel completes successfully. + * + * **Details** + * + * The effect runs before the original done value is propagated. The effect is + * not run when the channel fails. If the effect fails, the returned channel + * fails with that error. + * + * @category hooks * @since 4.0.0 - * @category utils */ ( self: Channel, @@ -8499,11 +9914,11 @@ export const onEnd: { )))) /** - * Returns a new channel with an attached finalizer. The finalizer is - * guaranteed to be executed so long as the channel begins execution (and - * regardless of whether or not it completes). + * Returns a channel with a finalizer effect that is guaranteed to run once the + * channel begins execution, whether it succeeds or fails. + * + * **Example** (Ensuring cleanup runs) * - * @example * ```ts * import { Channel, Console, Data } from "effect" * @@ -8521,16 +9936,16 @@ export const onEnd: { * ) * ``` * + * @category resource management * @since 2.0.0 - * @category utils */ export const ensuring: { /** - * Returns a new channel with an attached finalizer. The finalizer is - * guaranteed to be executed so long as the channel begins execution (and - * regardless of whether or not it completes). + * Returns a channel with a finalizer effect that is guaranteed to run once the + * channel begins execution, whether it succeeds or fails. + * + * **Example** (Ensuring cleanup runs) * - * @example * ```ts * import { Channel, Console, Data } from "effect" * @@ -8548,18 +9963,18 @@ export const ensuring: { * ) * ``` * + * @category resource management * @since 2.0.0 - * @category utils */ (finalizer: Effect.Effect): ( self: Channel ) => Channel /** - * Returns a new channel with an attached finalizer. The finalizer is - * guaranteed to be executed so long as the channel begins execution (and - * regardless of whether or not it completes). + * Returns a channel with a finalizer effect that is guaranteed to run once the + * channel begins execution, whether it succeeds or fails. + * + * **Example** (Ensuring cleanup runs) * - * @example * ```ts * import { Channel, Console, Data } from "effect" * @@ -8577,8 +9992,8 @@ export const ensuring: { * ) * ``` * + * @category resource management * @since 2.0.0 - * @category utils */ ( self: Channel, @@ -8613,10 +10028,10 @@ const runWith = < }) /** - * Create a channel from the specified services. + * Creates a channel from the specified services. * + * @category services * @since 2.0.0 - * @category Services */ export const contextWith = ( f: (context: Context.Context) => Channel @@ -8626,32 +10041,29 @@ export const contextWith = (context: Context.Context): ( self: Channel ) => Channel> /** - * Provides a layer or context to the channel, removing the corresponding - * service requirements. Use `options.local` to build the layer every time; by - * default, layers are shared between provide calls. + * Provides a `Context` to the channel, removing the corresponding service + * requirements from the returned channel. * - * @since 4.0.0 - * @category Services + * @category services + * @since 2.0.0 */ ( self: Channel, @@ -8669,20 +10081,29 @@ export const provideContext: { )) /** - * @since 4.0.0 - * @category Services + * Provides a concrete service for a context key, removing that service + * requirement from the returned channel. + * + * @category services + * @since 2.0.0 */ export const provideService: { /** - * @since 4.0.0 - * @category Services + * Provides a concrete service for a context key, removing that service + * requirement from the returned channel. + * + * @category services + * @since 2.0.0 */ (key: Context.Key, service: NoInfer): ( self: Channel ) => Channel> /** - * @since 4.0.0 - * @category Services + * Provides a concrete service for a context key, removing that service + * requirement from the returned channel. + * + * @category services + * @since 2.0.0 */ ( self: Channel, @@ -8702,20 +10123,56 @@ export const provideService: { )) /** + * Provides a service to the channel after obtaining it from an effect. + * + * **When to use** + * + * Use to supply a channel dependency when constructing the service itself is + * effectful or can fail. + * + * **Details** + * + * If the service effect fails, the returned channel fails. The provided service + * removes the corresponding service requirement from the returned channel. + * + * @category services * @since 4.0.0 - * @category Services */ export const provideServiceEffect: { /** + * Provides a service to the channel after obtaining it from an effect. + * + * **When to use** + * + * Use to supply a channel dependency when constructing the service itself is + * effectful or can fail. + * + * **Details** + * + * If the service effect fails, the returned channel fails. The provided service + * removes the corresponding service requirement from the returned channel. + * + * @category services * @since 4.0.0 - * @category Services */ (key: Context.Key, service: Effect.Effect, ES, RS>): ( self: Channel ) => Channel | RS> /** + * Provides a service to the channel after obtaining it from an effect. + * + * **When to use** + * + * Use to supply a channel dependency when constructing the service itself is + * effectful or can fail. + * + * **Details** + * + * If the service effect fails, the returned channel fails. The provided service + * removes the corresponding service requirement from the returned channel. + * + * @category services * @since 4.0.0 - * @category Services */ ( self: Channel, @@ -8735,13 +10192,31 @@ export const provideServiceEffect: { )) /** + * Provides a `Layer` or `Context` to the channel, removing the corresponding + * service requirements. + * + * **Details** + * + * Providing a `Context` delegates to `provideContext`. Providing a `Layer` + * builds the layer in the channel scope. Use `options.local` to build a fresh + * layer instance for this provision. + * + * @category services * @since 4.0.0 - * @category Services */ export const provide: { /** + * Provides a `Layer` or `Context` to the channel, removing the corresponding + * service requirements. + * + * **Details** + * + * Providing a `Context` delegates to `provideContext`. Providing a `Layer` + * builds the layer in the channel scope. Use `options.local` to build a fresh + * layer instance for this provision. + * + * @category services * @since 4.0.0 - * @category Services */ ( layer: Layer.Layer | Context.Context, @@ -8752,8 +10227,17 @@ export const provide: { self: Channel ) => Channel | R> /** + * Provides a `Layer` or `Context` to the channel, removing the corresponding + * service requirements. + * + * **Details** + * + * Providing a `Context` delegates to `provideContext`. Providing a `Layer` + * builds the layer in the channel scope. Use `options.local` to build a fresh + * layer instance for this provision. + * + * @category services * @since 4.0.0 - * @category Services */ ( self: Channel, @@ -8783,20 +10267,44 @@ export const provide: { )) /** - * @since 2.0.0 - * @category Services + * Transforms the current context before running the channel. + * + * **Details** + * + * The function receives the surrounding context and returns the context to + * provide to the channel. The returned channel requires the services needed to + * build that context. + * + * @category services + * @since 4.0.0 */ export const updateContext: { /** - * @since 2.0.0 - * @category Services + * Transforms the current context before running the channel. + * + * **Details** + * + * The function receives the surrounding context and returns the context to + * provide to the channel. The returned channel requires the services needed to + * build that context. + * + * @category services + * @since 4.0.0 */ (f: (context: Context.Context) => Context.Context): ( self: Channel ) => Channel /** - * @since 2.0.0 - * @category Services + * Transforms the current context before running the channel. + * + * **Details** + * + * The function receives the surrounding context and returns the context to + * provide to the channel. The returned channel requires the services needed to + * build that context. + * + * @category services + * @since 4.0.0 */ ( self: Channel, @@ -8814,20 +10322,41 @@ export const updateContext: { )) /** + * Updates a service in the current context before running the channel. + * + * **Details** + * + * The existing service is read from the context. The updated service is + * provided to the channel under the same key. + * + * @category services * @since 2.0.0 - * @category Services */ export const updateService: { /** + * Updates a service in the current context before running the channel. + * + * **Details** + * + * The existing service is read from the context. The updated service is + * provided to the channel under the same key. + * + * @category services * @since 2.0.0 - * @category Services */ (key: Context.Key, f: (service: NoInfer) => S): ( self: Channel ) => Channel /** + * Updates a service in the current context before running the channel. + * + * **Details** + * + * The existing service is read from the context. The updated service is + * provided to the channel under the same key. + * + * @category services * @since 2.0.0 - * @category Services */ ( self: Channel, @@ -8847,20 +10376,41 @@ export const updateService: { ))) /** - * @since 4.0.0 - * @category Tracing + * Runs the channel inside a tracing span with the specified name and options. + * + * **Details** + * + * The created span is provided as the current parent span while the channel + * runs. The span is ended with the channel's exit value. + * + * @category tracing + * @since 2.0.0 */ export const withSpan: { /** - * @since 4.0.0 - * @category Tracing + * Runs the channel inside a tracing span with the specified name and options. + * + * **Details** + * + * The created span is provided as the current parent span while the channel + * runs. The span is ended with the channel's exit value. + * + * @category tracing + * @since 2.0.0 */ (name: string, options?: SpanOptions): ( self: Channel ) => Channel> /** - * @since 4.0.0 - * @category Tracing + * Runs the channel inside a tracing span with the specified name and options. + * + * **Details** + * + * The created span is provided as the current parent span while the channel + * runs. The span is ended with the channel's exit value. + * + * @category tracing + * @since 2.0.0 */ ( self: Channel, @@ -8895,8 +10445,10 @@ const withSpanImpl = ( ) /** + * The starting channel for Do notation, emitting an empty object. + * + * @category do notation * @since 4.0.0 - * @category Do notation */ export const Do: Channel<{}> = succeed({}) @@ -8940,26 +10492,47 @@ const let_: { InErr, InDone, R -> => map(self, (elem) => (({ - ...elem, - [name]: f(elem) -}) as any))) +> => + map(self, (elem) => (({ + ...elem, + [name]: f(elem) + }) as any))) export { /** + * Adds a computed field to each object emitted by a channel. + * + * @category do notation * @since 4.0.0 - * @category Do notation */ let_ as let } /** + * Adds a field to each object emitted by a channel by running another channel + * derived from that object. + * + * **Details** + * + * The field name must not already exist on the emitted object. The derived + * channel's output becomes the value of the new field. `options.concurrency` + * and `options.bufferSize` control how derived channels are flattened. + * + * @category do notation * @since 4.0.0 - * @category Do notation */ export const bind: { /** + * Adds a field to each object emitted by a channel by running another channel + * derived from that object. + * + * **Details** + * + * The field name must not already exist on the emitted object. The derived + * channel's output becomes the value of the new field. `options.concurrency` + * and `options.bufferSize` control how derived channels are flattened. + * + * @category do notation * @since 4.0.0 - * @category Do notation */ ( name: Exclude, @@ -8980,8 +10553,17 @@ export const bind: { Env2 | Env > /** + * Adds a field to each object emitted by a channel by running another channel + * derived from that object. + * + * **Details** + * + * The field name must not already exist on the emitted object. The derived + * channel's output becomes the value of the new field. `options.concurrency` + * and `options.bufferSize` control how derived channels are flattened. + * + * @category do notation * @since 4.0.0 - * @category Do notation */ < OutElem extends object, @@ -9056,13 +10638,35 @@ export const bind: { )) /** + * Wraps each output element in an object under the specified field name. + * + * **When to use** + * + * Use when you need to start a Channel Do-notation chain from an existing + * output value by assigning that value to a field name. + * + * @see {@link Do} for starting Do notation from an empty object + * @see {@link bind} for adding a field produced by another channel + * @see {@link let_ let} for adding a computed field + * + * @category do notation * @since 4.0.0 - * @category Do notation */ export const bindTo: { /** + * Wraps each output element in an object under the specified field name. + * + * **When to use** + * + * Use when you need to start a Channel Do-notation chain from an existing + * output value by assigning that value to a field name. + * + * @see {@link Do} for starting Do notation from an empty object + * @see {@link bind} for adding a field produced by another channel + * @see {@link let_ let} for adding a computed field + * + * @category do notation * @since 4.0.0 - * @category Do notation */ (name: N): ( self: Channel @@ -9076,8 +10680,19 @@ export const bindTo: { Env > /** + * Wraps each output element in an object under the specified field name. + * + * **When to use** + * + * Use when you need to start a Channel Do-notation chain from an existing + * output value by assigning that value to a field name. + * + * @see {@link Do} for starting Do notation from an empty object + * @see {@link bind} for adding a field produced by another channel + * @see {@link let_ let} for adding a computed field + * + * @category do notation * @since 4.0.0 - * @category Do notation */ ( self: Channel, @@ -9107,7 +10722,8 @@ export const bindTo: { /** * Runs a channel and counts the number of elements it outputs. * - * @example + * **Example** (Counting channel output) + * * ```ts * import { Channel, Data } from "effect" * @@ -9124,8 +10740,8 @@ export const bindTo: { * // Effect.runSync(countEffect) // Returns: 5 * ``` * - * @since 2.0.0 * @category execution + * @since 4.0.0 */ export const runCount = ( self: Channel @@ -9134,7 +10750,8 @@ export const runCount = ( /** * Runs a channel and discards all output elements, returning only the final result. * - * @example + * **Example** (Draining channel output at runtime) + * * ```ts * import { Channel, Data } from "effect" * @@ -9155,8 +10772,8 @@ export const runCount = ( * // Effect.runSync(drainEffect) // Returns: "completed" * ``` * - * @since 2.0.0 * @category execution + * @since 2.0.0 */ export const runDrain = ( self: Channel @@ -9165,7 +10782,8 @@ export const runDrain = ( /** * Runs a channel and applies an effect to each output element. * - * @example + * **Example** (Running effects for each output) + * * ```ts * import { Channel, Console, Data } from "effect" * @@ -9185,14 +10803,15 @@ export const runDrain = ( * // Logs: "Processing: 1", "Processing: 2", "Processing: 3" * ``` * - * @since 2.0.0 * @category execution + * @since 4.0.0 */ export const runForEach: { /** * Runs a channel and applies an effect to each output element. * - * @example + * **Example** (Running effects for each output) + * * ```ts * import { Channel, Console, Data } from "effect" * @@ -9212,8 +10831,8 @@ export const runForEach: { * // Logs: "Processing: 1", "Processing: 2", "Processing: 3" * ``` * - * @since 2.0.0 * @category execution + * @since 4.0.0 */ (f: (o: OutElem) => Effect.Effect): ( self: Channel @@ -9221,7 +10840,8 @@ export const runForEach: { /** * Runs a channel and applies an effect to each output element. * - * @example + * **Example** (Running effects for each output) + * * ```ts * import { Channel, Console, Data } from "effect" * @@ -9241,8 +10861,8 @@ export const runForEach: { * // Logs: "Processing: 1", "Processing: 2", "Processing: 3" * ``` * - * @since 2.0.0 * @category execution + * @since 4.0.0 */ ( self: Channel, @@ -9258,20 +10878,44 @@ export const runForEach: { ) /** - * @since 2.0.0 + * Runs a channel and applies an effectful predicate to each output element + * until the predicate returns `false`. + * + * **Details** + * + * Returning `true` continues consuming the channel. Returning `false` stops + * consumption early. The returned effect completes with `void`. + * * @category execution + * @since 4.0.0 */ export const runForEachWhile: { /** - * @since 2.0.0 + * Runs a channel and applies an effectful predicate to each output element + * until the predicate returns `false`. + * + * **Details** + * + * Returning `true` continues consuming the channel. Returning `false` stops + * consumption early. The returned effect completes with `void`. + * * @category execution + * @since 4.0.0 */ (f: (o: OutElem) => Effect.Effect): ( self: Channel ) => Effect.Effect /** - * @since 2.0.0 + * Runs a channel and applies an effectful predicate to each output element + * until the predicate returns `false`. + * + * **Details** + * + * Returning `true` continues consuming the channel. Returning `false` stops + * consumption early. The returned effect completes with `void`. + * * @category execution + * @since 4.0.0 */ ( self: Channel, @@ -9294,7 +10938,8 @@ export const runForEachWhile: { /** * Runs a channel and collects all output elements into an array. * - * @example + * **Example** (Collecting channel output) + * * ```ts * import { Channel, Data } from "effect" * @@ -9311,8 +10956,8 @@ export const runForEachWhile: { * // Effect.runSync(collectEffect) // Returns: [1, 2, 3, 4, 5] * ``` * - * @since 2.0.0 * @category execution + * @since 2.0.0 */ export const runCollect = ( self: Channel @@ -9325,16 +10970,24 @@ export const runCollect = ( /** * Runs a channel and outputs the done value. * - * @since 4.0.0 * @category execution + * @since 4.0.0 */ export const runDone = ( self: Channel ): Effect.Effect => runWith(self, identity_, Effect.succeed) /** - * @since 2.0.0 + * Runs a channel until the first output element is available, returning it in + * an `Option`. + * + * **Details** + * + * Returns `Option.some` with the first output element, or `Option.none` if the + * channel completes without emitting output. + * * @category execution + * @since 4.0.0 */ export const runHead = ( self: Channel @@ -9352,8 +11005,16 @@ export const runHead = ( }) /** - * @since 2.0.0 + * Runs a channel to completion and returns the last output element in an + * `Option`. + * + * **Details** + * + * Returns `Option.some` with the last emitted element, or `Option.none` if the + * channel completes without emitting output. + * * @category execution + * @since 4.0.0 */ export const runLast = ( self: Channel @@ -9378,7 +11039,8 @@ export const runLast = ( /** * Runs a channel and folds over all output elements with an accumulator. * - * @example + * **Example** (Folding channel output) + * * ```ts * import { Channel, Data } from "effect" * @@ -9395,14 +11057,15 @@ export const runLast = ( * // Effect.runSync(sumEffect) // Returns: 15 * ``` * - * @since 2.0.0 * @category execution + * @since 4.0.0 */ export const runFold: { /** * Runs a channel and folds over all output elements with an accumulator. * - * @example + * **Example** (Folding channel output) + * * ```ts * import { Channel, Data } from "effect" * @@ -9419,8 +11082,8 @@ export const runFold: { * // Effect.runSync(sumEffect) // Returns: 15 * ``` * - * @since 2.0.0 * @category execution + * @since 4.0.0 */ (initial: LazyArg, f: (acc: Z, o: OutElem) => Z): ( self: Channel @@ -9428,7 +11091,8 @@ export const runFold: { /** * Runs a channel and folds over all output elements with an accumulator. * - * @example + * **Example** (Folding channel output) + * * ```ts * import { Channel, Data } from "effect" * @@ -9445,8 +11109,8 @@ export const runFold: { * // Effect.runSync(sumEffect) // Returns: 15 * ``` * - * @since 2.0.0 * @category execution + * @since 4.0.0 */ ( self: Channel, @@ -9475,20 +11139,59 @@ export const runFold: { })) /** - * @since 2.0.0 + * Runs a channel and effectfully folds all output elements with an accumulator. + * + * **When to use** + * + * Use when folding channel output needs effects, services, or an additional + * failure channel during accumulation. + * + * **Details** + * + * The initial accumulator is evaluated lazily. Each output element is passed to + * the effectful accumulator function. The returned effect succeeds with the + * final accumulator value. + * * @category execution + * @since 4.0.0 */ export const runFoldEffect: { /** - * @since 2.0.0 + * Runs a channel and effectfully folds all output elements with an accumulator. + * + * **When to use** + * + * Use when folding channel output needs effects, services, or an additional + * failure channel during accumulation. + * + * **Details** + * + * The initial accumulator is evaluated lazily. Each output element is passed to + * the effectful accumulator function. The returned effect succeeds with the + * final accumulator value. + * * @category execution + * @since 4.0.0 */ (initial: LazyArg, f: (acc: Z, o: OutElem) => Effect.Effect): ( self: Channel ) => Effect.Effect /** - * @since 2.0.0 + * Runs a channel and effectfully folds all output elements with an accumulator. + * + * **When to use** + * + * Use when folding channel output needs effects, services, or an additional + * failure channel during accumulation. + * + * **Details** + * + * The initial accumulator is evaluated lazily. Each output element is passed to + * the effectful accumulator function. The returned effect succeeds with the + * final accumulator value. + * * @category execution + * @since 4.0.0 */ ( self: Channel, @@ -9520,9 +11223,16 @@ export const runFoldEffect: { })) /** - * Converts a channel to a Pull data structure for low-level consumption. + * Converts a channel to a scoped `Pull` for low-level consumption. + * + * **Details** + * + * The effect requires a `Scope`. The returned pull should be consumed only + * while that scope remains open. Pulls are serialized so only one pull is + * evaluated at a time. + * + * **Example** (Converting channels to pulls) * - * @example * ```ts * import { Channel, Data, Effect } from "effect" * @@ -9541,8 +11251,8 @@ export const runFoldEffect: { * // Use the Pull to manually consume elements * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const toPull: ( self: Channel @@ -9570,7 +11280,8 @@ export const toPull: ( /** * Converts a channel to a Pull within an existing scope. * - * @example + * **Example** (Converting channels to scoped pulls) + * * ```ts * import { Channel, Data, Effect, Scope } from "effect" * @@ -9589,8 +11300,8 @@ export const toPull: ( * }) * ``` * + * @category destructors * @since 4.0.0 - * @category Destructors */ export const toPullScoped = ( self: Channel, @@ -9598,20 +11309,44 @@ export const toPullScoped = ( ): Effect.Effect, never, Env> => toTransform(self)(Cause.done(), scope) /** + * Runs a channel and offers each output element into a queue. + * + * **Details** + * + * When the channel completes, the queue is ended. When the channel fails, the + * queue is failed with the channel's cause. The returned effect itself + * completes with `void`. + * + * @category destructors * @since 4.0.0 - * @category Destructors */ export const runIntoQueue: { /** + * Runs a channel and offers each output element into a queue. + * + * **Details** + * + * When the channel completes, the queue is ended. When the channel fails, the + * queue is failed with the channel's cause. The returned effect itself + * completes with `void`. + * + * @category destructors * @since 4.0.0 - * @category Destructors */ (queue: Queue.Queue): ( self: Channel ) => Effect.Effect /** + * Runs a channel and offers each output element into a queue. + * + * **Details** + * + * When the channel completes, the queue is ended. When the channel fails, the + * queue is failed with the channel's cause. The returned effect itself + * completes with `void`. + * + * @category destructors * @since 4.0.0 - * @category Destructors */ ( self: Channel, @@ -9640,20 +11375,47 @@ export const runIntoQueue: { ) /** + * Runs a channel that emits non-empty arrays and offers each array element into + * a queue. + * + * **Details** + * + * When the channel completes, the queue is ended. When the channel fails, the + * queue is failed with the channel's cause. The returned effect itself + * completes with `void`. + * + * @category destructors * @since 4.0.0 - * @category Destructors */ export const runIntoQueueArray: { /** + * Runs a channel that emits non-empty arrays and offers each array element into + * a queue. + * + * **Details** + * + * When the channel completes, the queue is ended. When the channel fails, the + * queue is failed with the channel's cause. The returned effect itself + * completes with `void`. + * + * @category destructors * @since 4.0.0 - * @category Destructors */ (queue: Queue.Queue): ( self: Channel, OutErr, OutDone, unknown, unknown, unknown, Env> ) => Effect.Effect /** + * Runs a channel that emits non-empty arrays and offers each array element into + * a queue. + * + * **Details** + * + * When the channel completes, the queue is ended. When the channel fails, the + * queue is failed with the channel's cause. The returned effect itself + * completes with `void`. + * + * @category destructors * @since 4.0.0 - * @category Destructors */ ( self: Channel, OutErr, OutDone, unknown, unknown, unknown, Env>, @@ -9682,9 +11444,17 @@ export const runIntoQueueArray: { ) /** - * Converts a channel to a queue for concurrent consumption. + * Creates a scoped queue and forks the channel to feed it for concurrent + * consumption. + * + * **Details** + * + * Output elements are offered to the queue. Channel completion and failure are + * signaled through the queue. The queue is shut down when the surrounding scope + * closes. + * + * **Example** (Converting channels to queues) * - * @example * ```ts * import { Channel, Data } from "effect" * @@ -9702,14 +11472,22 @@ export const runIntoQueueArray: { * // Multiple consumers can read from the queue * ``` * - * @since 4.0.0 - * @category Destructors + * @category destructors + * @since 2.0.0 */ export const toQueue: { /** - * Converts a channel to a queue for concurrent consumption. + * Creates a scoped queue and forks the channel to feed it for concurrent + * consumption. + * + * **Details** + * + * Output elements are offered to the queue. Channel completion and failure are + * signaled through the queue. The queue is shut down when the surrounding scope + * closes. + * + * **Example** (Converting channels to queues) * - * @example * ```ts * import { Channel, Data } from "effect" * @@ -9727,8 +11505,8 @@ export const toQueue: { * // Multiple consumers can read from the queue * ``` * - * @since 4.0.0 - * @category Destructors + * @category destructors + * @since 2.0.0 */ ( options: { @@ -9741,9 +11519,17 @@ export const toQueue: { self: Channel ) => Effect.Effect, never, Env | Scope.Scope> /** - * Converts a channel to a queue for concurrent consumption. + * Creates a scoped queue and forks the channel to feed it for concurrent + * consumption. + * + * **Details** + * + * Output elements are offered to the queue. Channel completion and failure are + * signaled through the queue. The queue is shut down when the surrounding scope + * closes. + * + * **Example** (Converting channels to queues) * - * @example * ```ts * import { Channel, Data } from "effect" * @@ -9761,8 +11547,8 @@ export const toQueue: { * // Multiple consumers can read from the queue * ``` * - * @since 4.0.0 - * @category Destructors + * @category destructors + * @since 2.0.0 */ ( self: Channel, @@ -9786,9 +11572,17 @@ export const toQueue: { ) { const scope = yield* Effect.scope const queue = yield* Queue.make({ capacity: typeof options.capacity === "number" ? options.capacity : undefined, @@ -9844,13 +11646,29 @@ export const toQueue: { ) /** + * Creates a scoped queue and forks an array-emitting channel to feed it. + * + * **Details** + * + * Each element inside emitted non-empty arrays is offered to the queue. Channel + * completion and failure are signaled through the queue. The queue is shut down + * when the surrounding scope closes. + * + * @category destructors * @since 4.0.0 - * @category Destructors */ export const toQueueArray: { /** + * Creates a scoped queue and forks an array-emitting channel to feed it. + * + * **Details** + * + * Each element inside emitted non-empty arrays is offered to the queue. Channel + * completion and failure are signaled through the queue. The queue is shut down + * when the surrounding scope closes. + * + * @category destructors * @since 4.0.0 - * @category Destructors */ ( options: { @@ -9863,8 +11681,16 @@ export const toQueueArray: { self: Channel, OutErr, OutDone, unknown, unknown, unknown, Env> ) => Effect.Effect, never, Env | Scope.Scope> /** + * Creates a scoped queue and forks an array-emitting channel to feed it. + * + * **Details** + * + * Each element inside emitted non-empty arrays is offered to the queue. Channel + * completion and failure are signaled through the queue. The queue is shut down + * when the surrounding scope closes. + * + * @category destructors * @since 4.0.0 - * @category Destructors */ ( self: Channel, OutErr, OutDone, unknown, unknown, unknown, Env>, @@ -9888,12 +11714,28 @@ export const toQueueArray: { ) { const scope = yield* Effect.scope const queue = yield* Queue.make({ capacity: typeof options.capacity === "number" ? options.capacity : undefined, @@ -9908,21 +11750,25 @@ export const toQueueArray: { /** * Converts a channel to a PubSub for concurrent consumption. * + * **Details** + * * `shutdownOnEnd` indicates whether the PubSub should be shut down when the * channel ends. By default this is `true`. * - * @since 4.0.0 - * @category Destructors + * @category destructors + * @since 2.0.0 */ export const toPubSub: { /** * Converts a channel to a PubSub for concurrent consumption. * + * **Details** + * * `shutdownOnEnd` indicates whether the PubSub should be shut down when the * channel ends. By default this is `true`. * - * @since 4.0.0 - * @category Destructors + * @category destructors + * @since 2.0.0 */ ( options: { @@ -9941,11 +11787,13 @@ export const toPubSub: { /** * Converts a channel to a PubSub for concurrent consumption. * + * **Details** + * * `shutdownOnEnd` indicates whether the PubSub should be shut down when the * channel ends. By default this is `true`. * - * @since 4.0.0 - * @category Destructors + * @category destructors + * @since 2.0.0 */ ( self: Channel, @@ -9978,11 +11826,13 @@ export const toPubSub: { const pubsub = yield* makePubSub(options) yield* Effect.forkScoped(runIntoPubSub(self, pubsub, { @@ -9993,13 +11843,27 @@ export const toPubSub: { ) /** + * Runs a channel and publishes each output element to a `PubSub`. + * + * **Details** + * + * The channel's output values are published as individual PubSub messages. Use + * `options.shutdownOnEnd` to shut down the PubSub when channel execution ends. + * + * @category destructors * @since 4.0.0 - * @category Destructors */ export const runIntoPubSub: { /** + * Runs a channel and publishes each output element to a `PubSub`. + * + * **Details** + * + * The channel's output values are published as individual PubSub messages. Use + * `options.shutdownOnEnd` to shut down the PubSub when channel execution ends. + * + * @category destructors * @since 4.0.0 - * @category Destructors */ ( pubsub: PubSub.PubSub, @@ -10010,8 +11874,15 @@ export const runIntoPubSub: { self: Channel ) => Effect.Effect /** + * Runs a channel and publishes each output element to a `PubSub`. + * + * **Details** + * + * The channel's output values are published as individual PubSub messages. Use + * `options.shutdownOnEnd` to shut down the PubSub when channel execution ends. + * + * @category destructors * @since 4.0.0 - * @category Destructors */ ( self: Channel, @@ -10056,23 +11927,31 @@ const makePubSub = ( ) /** - * Converts a channel to a PubSub for concurrent consumption. + * Converts an array-emitting channel to a scoped `PubSub` for concurrent + * consumption. * - * `shutdownOnEnd` indicates whether the PubSub should be shut down when the - * channel ends. By default this is `true`. + * **Details** + * + * Each element inside emitted non-empty arrays is published as an individual + * PubSub message. `shutdownOnEnd` indicates whether the PubSub should be shut + * down when the channel ends. By default this is `true`. * + * @category destructors * @since 4.0.0 - * @category Destructors */ export const toPubSubArray: { /** - * Converts a channel to a PubSub for concurrent consumption. + * Converts an array-emitting channel to a scoped `PubSub` for concurrent + * consumption. * - * `shutdownOnEnd` indicates whether the PubSub should be shut down when the - * channel ends. By default this is `true`. + * **Details** * + * Each element inside emitted non-empty arrays is published as an individual + * PubSub message. `shutdownOnEnd` indicates whether the PubSub should be shut + * down when the channel ends. By default this is `true`. + * + * @category destructors * @since 4.0.0 - * @category Destructors */ ( options: { @@ -10089,13 +11968,17 @@ export const toPubSubArray: { self: Channel, OutErr, OutDone, unknown, unknown, unknown, Env> ) => Effect.Effect, never, Env | Scope.Scope> /** - * Converts a channel to a PubSub for concurrent consumption. + * Converts an array-emitting channel to a scoped `PubSub` for concurrent + * consumption. * - * `shutdownOnEnd` indicates whether the PubSub should be shut down when the - * channel ends. By default this is `true`. + * **Details** * + * Each element inside emitted non-empty arrays is published as an individual + * PubSub message. `shutdownOnEnd` indicates whether the PubSub should be shut + * down when the channel ends. By default this is `true`. + * + * @category destructors * @since 4.0.0 - * @category Destructors */ ( self: Channel, OutErr, OutDone, unknown, unknown, unknown, Env>, @@ -10126,13 +12009,17 @@ export const toPubSubArray: { } ) { const pubsub = yield* makePubSub(options) yield* Effect.forkScoped(runIntoPubSubArray(self, pubsub, { @@ -10143,13 +12030,31 @@ export const toPubSubArray: { ) /** + * Runs an array-emitting channel and publishes each array element to a + * `PubSub`. + * + * **Details** + * + * Each element inside emitted non-empty arrays is published as an individual + * PubSub message. Use `options.shutdownOnEnd` to shut down the PubSub when + * channel execution ends. + * + * @category destructors * @since 4.0.0 - * @category Destructors */ export const runIntoPubSubArray: { /** + * Runs an array-emitting channel and publishes each array element to a + * `PubSub`. + * + * **Details** + * + * Each element inside emitted non-empty arrays is published as an individual + * PubSub message. Use `options.shutdownOnEnd` to shut down the PubSub when + * channel execution ends. + * + * @category destructors * @since 4.0.0 - * @category Destructors */ ( pubsub: PubSub.PubSub, @@ -10160,8 +12065,17 @@ export const runIntoPubSubArray: { self: Channel, OutErr, OutDone, unknown, unknown, unknown, Env> ) => Effect.Effect /** + * Runs an array-emitting channel and publishes each array element to a + * `PubSub`. + * + * **Details** + * + * Each element inside emitted non-empty arrays is published as an individual + * PubSub message. Use `options.shutdownOnEnd` to shut down the PubSub when + * channel execution ends. + * + * @category destructors * @since 4.0.0 - * @category Destructors */ ( self: Channel, OutErr, OutDone, unknown, unknown, unknown, Env>, @@ -10185,17 +12099,29 @@ export const runIntoPubSubArray: { ) /** - * Converts a channel to a PubSub for concurrent consumption. + * Converts a channel to a scoped `PubSub` of `Take` values. * + * **Details** + * + * Emitted non-empty arrays are published as output `Take` values. When the + * channel ends, its final `Exit` is published so subscribers can observe + * completion or failure. + * + * @category destructors * @since 4.0.0 - * @category Destructors */ export const toPubSubTake: { /** - * Converts a channel to a PubSub for concurrent consumption. + * Converts a channel to a scoped `PubSub` of `Take` values. * + * **Details** + * + * Emitted non-empty arrays are published as output `Take` values. When the + * channel ends, its final `Exit` is published so subscribers can observe + * completion or failure. + * + * @category destructors * @since 4.0.0 - * @category Destructors */ ( options: { @@ -10214,10 +12140,16 @@ export const toPubSubTake: { Env | Scope.Scope > /** - * Converts a channel to a PubSub for concurrent consumption. + * Converts a channel to a scoped `PubSub` of `Take` values. + * + * **Details** * + * Emitted non-empty arrays are published as output `Take` values. When the + * channel ends, its final `Exit` is published so subscribers can observe + * completion or failure. + * + * @category destructors * @since 4.0.0 - * @category Destructors */ ( self: Channel, OutErr, OutDone, unknown, unknown, unknown, Env>, @@ -10248,10 +12180,16 @@ export const toPubSubTake: { } ) { const pubsub = yield* makePubSub>(options) yield* runForEach(self, (value) => PubSub.publish(pubsub, value)).pipe( diff --git a/.opencode/node_modules/effect/src/ChannelSchema.ts b/.opencode/node_modules/effect/src/ChannelSchema.ts index 6a06db818175ec3121cbd9c5d333996e02d174e7..b06e044467ae13535afd1b58deac4387dc294c04 100644 --- a/.opencode/node_modules/effect/src/ChannelSchema.ts +++ b/.opencode/node_modules/effect/src/ChannelSchema.ts @@ -1,4 +1,10 @@ /** + * Schema adapters for `Channel` boundaries. The helpers encode typed channel + * chunks before they cross an encoded boundary, decode encoded chunks before + * application code receives them, and wrap bidirectional channels so callers + * work with schema-typed input and output while the inner channel uses encoded + * values. + * * @since 4.0.0 */ import type * as Arr from "./Array.ts" @@ -8,8 +14,24 @@ import { dual } from "./Function.ts" import * as Schema from "./Schema.ts" /** - * @since 4.0.0 + * Creates a channel that encodes non-empty chunks of schema values into the + * schema's encoded representation. + * + * **When to use** + * + * Use to encode typed channel input into the schema's encoded representation + * before passing chunks to an encoded downstream boundary. + * + * **Details** + * + * Encoding failures are emitted as `SchemaError`, and any encoding services + * required by the schema become channel requirements. + * + * @see {@link encodeUnknown} for encoded output chunks that should be typed as `unknown` + * @see {@link decode} for the inverse channel that decodes encoded chunks into schema values + * * @category constructors + * @since 4.0.0 */ export const encode = ( schema: S @@ -28,8 +50,18 @@ export const encode = ( } /** - * @since 4.0.0 + * Creates an `encode` channel variant whose encoded output chunks are typed as + * `unknown`. + * + * **When to use** + * + * Use when a channel boundary should encode typed input chunks while the encoded + * output representation is intentionally untyped. + * + * @see {@link encode} for the variant that preserves the schema encoded type + * * @category constructors + * @since 4.0.0 */ export const encodeUnknown: ( schema: S @@ -44,8 +76,24 @@ export const encodeUnknown: ( > = encode /** - * @since 4.0.0 + * Creates a channel that decodes non-empty chunks from the schema's encoded + * representation into schema values. + * + * **When to use** + * + * Use to validate and decode encoded channel output into typed schema values + * before application code consumes it. + * + * **Details** + * + * Decoding failures are emitted as `SchemaError`, and any decoding services + * required by the schema become channel requirements. + * + * @see {@link decodeUnknown} for boundaries where the encoded input side is intentionally untyped + * @see {@link encode} for the inverse adapter that encodes typed schema values + * * @category constructors + * @since 4.0.0 */ export const decode = ( schema: S @@ -64,8 +112,23 @@ export const decode = ( } /** - * @since 4.0.0 + * Creates a `decode` channel variant for schema-decoding channel boundaries. + * + * **When to use** + * + * Use when you need an intentionally unknown or untyped encoded input while + * keeping only the decoded output statically typed according to the schema. + * + * **Details** + * + * The channel decodes non-empty encoded chunks into schema values, emits + * `SchemaError` when decoding fails, and requires the schema's decoding + * services. + * + * @see {@link decode} for the typed variant that preserves the schema's encoded type + * * @category constructors + * @since 4.0.0 */ export const decodeUnknown: ( schema: S @@ -80,13 +143,51 @@ export const decodeUnknown: ( > = decode /** - * @since 4.0.0 + * Wraps a channel so callers work with typed input and output chunks while the + * wrapped channel uses encoded chunks. + * + * **When to use** + * + * Use to expose typed input and output at a bidirectional channel boundary + * while the wrapped channel continues to operate on schema-encoded chunks. + * + * **Details** + * + * Values sent into the resulting channel are encoded with `inputSchema` before + * reaching the wrapped channel. Values emitted by the wrapped channel are + * decoded with `outputSchema` before they are emitted downstream. Schema + * failures are surfaced as `SchemaError`. + * + * @see {@link duplexUnknown} for the variant whose encoded side is intentionally untyped + * @see {@link encode} for encoding typed chunks at one-way channel boundaries + * @see {@link decode} for decoding encoded chunks at one-way channel boundaries + * * @category combinators + * @since 4.0.0 */ export const duplex: { /** - * @since 4.0.0 + * Wraps a channel so callers work with typed input and output chunks while the + * wrapped channel uses encoded chunks. + * + * **When to use** + * + * Use to expose typed input and output at a bidirectional channel boundary + * while the wrapped channel continues to operate on schema-encoded chunks. + * + * **Details** + * + * Values sent into the resulting channel are encoded with `inputSchema` before + * reaching the wrapped channel. Values emitted by the wrapped channel are + * decoded with `outputSchema` before they are emitted downstream. Schema + * failures are surfaced as `SchemaError`. + * + * @see {@link duplexUnknown} for the variant whose encoded side is intentionally untyped + * @see {@link encode} for encoding typed chunks at one-way channel boundaries + * @see {@link decode} for decoding encoded chunks at one-way channel boundaries + * * @category combinators + * @since 4.0.0 */ ( options: { @@ -113,8 +214,27 @@ export const duplex: { R | In["EncodingServices"] | Out["DecodingServices"] > /** - * @since 4.0.0 + * Wraps a channel so callers work with typed input and output chunks while the + * wrapped channel uses encoded chunks. + * + * **When to use** + * + * Use to expose typed input and output at a bidirectional channel boundary + * while the wrapped channel continues to operate on schema-encoded chunks. + * + * **Details** + * + * Values sent into the resulting channel are encoded with `inputSchema` before + * reaching the wrapped channel. Values emitted by the wrapped channel are + * decoded with `outputSchema` before they are emitted downstream. Schema + * failures are surfaced as `SchemaError`. + * + * @see {@link duplexUnknown} for the variant whose encoded side is intentionally untyped + * @see {@link encode} for encoding typed chunks at one-way channel boundaries + * @see {@link decode} for decoding encoded chunks at one-way channel boundaries + * * @category combinators + * @since 4.0.0 */ ( self: Channel.Channel< @@ -163,12 +283,50 @@ export const duplex: { R | In["EncodingServices"] | Out["DecodingServices"] > => encode(options.inputSchema)().pipe( Channel.pipeTo(self), @@ -176,13 +334,45 @@ export const duplex: { )) /** - * @since 4.0.0 + * Wraps a bidirectional channel whose encoded chunks are typed as `unknown`. + * + * **When to use** + * + * Use when you need a bidirectional channel to cross an encoded boundary whose + * chunk types are intentionally erased, while callers send and receive + * schema-typed chunks. + * + * **Details** + * + * The resulting channel accepts typed input chunks, encodes them with + * `inputSchema`, decodes unknown output chunks with `outputSchema`, and + * surfaces schema failures as `SchemaError`. + * + * @see {@link duplex} for the variant that preserves the schema encoded types on the wrapped channel + * * @category combinators + * @since 4.0.0 */ export const duplexUnknown: { /** - * @since 4.0.0 + * Wraps a bidirectional channel whose encoded chunks are typed as `unknown`. + * + * **When to use** + * + * Use when you need a bidirectional channel to cross an encoded boundary whose + * chunk types are intentionally erased, while callers send and receive + * schema-typed chunks. + * + * **Details** + * + * The resulting channel accepts typed input chunks, encodes them with + * `inputSchema`, decodes unknown output chunks with `outputSchema`, and + * surfaces schema failures as `SchemaError`. + * + * @see {@link duplex} for the variant that preserves the schema encoded types on the wrapped channel + * * @category combinators + * @since 4.0.0 */ ( options: { @@ -209,8 +399,24 @@ export const duplexUnknown: { R | In["EncodingServices"] | Out["DecodingServices"] > /** - * @since 4.0.0 + * Wraps a bidirectional channel whose encoded chunks are typed as `unknown`. + * + * **When to use** + * + * Use when you need a bidirectional channel to cross an encoded boundary whose + * chunk types are intentionally erased, while callers send and receive + * schema-typed chunks. + * + * **Details** + * + * The resulting channel accepts typed input chunks, encodes them with + * `inputSchema`, decodes unknown output chunks with `outputSchema`, and + * surfaces schema failures as `SchemaError`. + * + * @see {@link duplex} for the variant that preserves the schema encoded types on the wrapped channel + * * @category combinators + * @since 4.0.0 */ ( self: Channel.Channel< diff --git a/.opencode/node_modules/effect/src/Chunk.ts b/.opencode/node_modules/effect/src/Chunk.ts index 6596ac9cc04aea2698ac1679e40b15c461001978..3aa706bcdc52fef541b2c7f1595d9c2bea801434 100644 --- a/.opencode/node_modules/effect/src/Chunk.ts +++ b/.opencode/node_modules/effect/src/Chunk.ts @@ -1,70 +1,11 @@ /** - * The `Chunk` module provides an immutable, high-performance sequence data structure - * optimized for functional programming patterns. A `Chunk` is a persistent data structure - * that supports efficient append, prepend, and concatenation operations. + * Stores many values in an immutable ordered collection. * - * ## What is a Chunk? - * - * A `Chunk` is an immutable sequence of elements of type `A` that provides: - * - **O(1) append and prepend operations** - * - **Efficient concatenation** through tree-like structure - * - **Memory efficiency** with structural sharing - * - **Rich API** with functional programming operations - * - **Type safety** with full TypeScript integration - * - * ## Key Features - * - * - **Immutable**: All operations return new chunks without modifying the original - * - **Efficient**: Optimized data structure with logarithmic complexity for most operations - * - **Functional**: Rich set of transformation and combination operators - * - **Lazy evaluation**: Many operations are deferred until needed - * - **Interoperable**: Easy conversion to/from arrays and other collections - * - * ## Performance Characteristics - * - * - **Append/Prepend**: O(1) amortized - * - **Random Access**: O(log n) - * - **Concatenation**: O(log min(m, n)) - * - **Iteration**: O(n) - * - **Memory**: Structural sharing minimizes allocation - * - * @example - * ```ts - * import { Chunk } from "effect" - * - * // Creating chunks - * const chunk1 = Chunk.fromIterable([1, 2, 3]) - * const chunk2 = Chunk.fromIterable([4, 5, 6]) - * const empty = Chunk.empty() - * - * // Combining chunks - * const combined = Chunk.appendAll(chunk1, chunk2) - * console.log(Chunk.toReadonlyArray(combined)) // [1, 2, 3, 4, 5, 6] - * ``` - * - * @example - * ```ts - * import { Chunk } from "effect" - * - * // Functional transformations - * const numbers = Chunk.range(1, 5) // [1, 2, 3, 4, 5] - * const doubled = Chunk.map(numbers, (n) => n * 2) // [2, 4, 6, 8, 10] - * const evens = Chunk.filter(doubled, (n) => n % 4 === 0) // [4, 8] - * const sum = Chunk.reduce(evens, 0, (acc, n) => acc + n) // 12 - * ``` - * - * @example - * ```ts - * import { Chunk, Effect } from "effect" - * - * // Working with Effects - * const processChunk = (chunk: Chunk.Chunk) => - * Effect.gen(function*() { - * const mapped = Chunk.map(chunk, (n) => n * 2) - * const filtered = Chunk.filter(mapped, (n) => n > 5) - * return Chunk.toReadonlyArray(filtered) - * }) - * ``` + * A `Chunk` is useful when you need to build or transform collections + * without changing the original collection. It is designed for efficient + * append, prepend, and concatenation. This module includes helpers for + * creating, reading, slicing, mapping, filtering, sorting, zipping, combining, + * and converting chunks to and from arrays and iterables. * * @since 2.0.0 */ @@ -94,7 +35,8 @@ const TypeId = "~effect/collections/Chunk" /** * A Chunk is an immutable, ordered collection optimized for efficient concatenation and access patterns. * - * @example + * **Example** (Inspecting chunk values) + * * ```ts * import { Chunk } from "effect" * @@ -120,7 +62,8 @@ export interface Chunk extends Iterable, Equal.Equal, Pipeable, Inspec /** * A non-empty Chunk guaranteed to contain at least one element. * - * @example + * **Example** (Working with non-empty chunks) + * * ```ts * import { Chunk } from "effect" * @@ -137,13 +80,13 @@ export interface NonEmptyChunk extends Chunk, NonEmptyIterable {} /** * Type lambda for Chunk, used for higher-kinded type operations. * - * @example + * **Example** (Applying the Chunk type lambda) + * * ```ts - * import type { ChunkTypeLambda } from "effect/Chunk" - * import type { Kind } from "effect/HKT" + * import type { Chunk, HKT } from "effect" * * // Create a Chunk type using the type lambda - * type NumberChunk = Kind + * type NumberChunk = HKT.Kind * // Equivalent to: Chunk * ``` * @@ -204,12 +147,13 @@ function copy( const emptyArray: ReadonlyArray = [] /** - * Compares the two chunks of equal length using the specified function + * Creates an `Equivalence` for chunks that compares chunk lengths and then + * compares corresponding elements with the provided element equivalence. + * + * **Example** (Comparing chunks for equivalence) * - * @example * ```ts - * import { Chunk } from "effect" - * import * as Equivalence from "effect/Equivalence" + * import { Chunk, Equivalence } from "effect" * * const chunk1 = Chunk.make(1, 2, 3) * const chunk2 = Chunk.make(1, 2, 3) @@ -220,8 +164,8 @@ const emptyArray: ReadonlyArray = [] * console.log(eq(chunk1, chunk3)) // false * ``` * - * @category equivalence - * @since 2.0.0 + * @category instances + * @since 4.0.0 */ export const makeEquivalence = (isEquivalent: Equivalence.Equivalence): Equivalence.Equivalence> => Equivalence.make((self, that) => @@ -314,9 +258,10 @@ const makeChunk = (backing: Backing): Chunk => { } /** - * Checks if `u` is a `Chunk` + * Checks whether `u` is a `Chunk` + * + * **Example** (Checking for chunks) * - * @example * ```ts * import { Chunk } from "effect" * @@ -333,9 +278,10 @@ const makeChunk = (backing: Backing): Chunk => { */ export const isChunk: { /** - * Checks if `u` is a `Chunk` + * Checks whether `u` is a `Chunk` + * + * **Example** (Checking for chunks) * - * @example * ```ts * import { Chunk } from "effect" * @@ -352,9 +298,10 @@ export const isChunk: { */ (u: Iterable): u is Chunk /** - * Checks if `u` is a `Chunk` + * Checks whether `u` is a `Chunk` + * + * **Example** (Checking for chunks) * - * @example * ```ts * import { Chunk } from "effect" * @@ -377,7 +324,8 @@ const _empty = makeChunk({ _tag: "IEmpty" }) /** * Creates an empty `Chunk`. * - * @example + * **Example** (Creating an empty chunk) + * * ```ts * import { Chunk } from "effect" * @@ -393,13 +341,13 @@ export const empty: () => Chunk = () => _empty /** * Builds a `NonEmptyChunk` from an non-empty collection of elements. * - * @example + * **Example** (Creating a non-empty chunk) + * * ```ts * import { Chunk } from "effect" * * const chunk = Chunk.make(1, 2, 3, 4) - * console.log(chunk) - * // { _id: 'Chunk', values: [ 1, 2, 3, 4 ] } + * console.log(Chunk.toArray(chunk)) // [1, 2, 3, 4] * ``` * * @category constructors @@ -411,13 +359,13 @@ export const make = ]>(...as: As): NonEm /** * Builds a `NonEmptyChunk` from a single element. * - * @example + * **Example** (Creating a single-element chunk) + * * ```ts * import { Chunk } from "effect" * * const chunk = Chunk.of("hello") - * console.log(chunk) - * // { _id: 'Chunk', values: [ "hello" ] } + * console.log(Chunk.toArray(chunk)) // ["hello"] * ``` * * @category constructors @@ -428,13 +376,13 @@ export const of = (a: A): NonEmptyChunk => makeChunk({ _tag: "ISingleton", /** * Creates a new `Chunk` from an iterable collection of values. * - * @example + * **Example** (Creating chunks from iterables) + * * ```ts * import { Chunk } from "effect" * * const chunk = Chunk.fromIterable([1, 2, 3]) - * console.log(chunk) - * // { _id: 'Chunk', values: [ 1, 2, 3 ] } + * console.log(Chunk.toArray(chunk)) // [1, 2, 3] * ``` * * @category constructors @@ -478,7 +426,8 @@ const toArray_ = (self: Chunk): Array => toReadonlyArray(self).slice() * (`NonEmptyChunk`), the function will return a `NonEmptyArray`, ensuring the * non-empty property is preserved. * - * @example + * **Example** (Converting chunks to mutable arrays) + * * ```ts * import { Chunk } from "effect" * @@ -492,7 +441,7 @@ const toArray_ = (self: Chunk): Array => toReadonlyArray(self).slice() * console.log(Chunk.toArray(emptyChunk)) // [] * ``` * - * @category conversions + * @category converting * @since 2.0.0 */ export const toArray: >( @@ -527,7 +476,8 @@ const toReadonlyArray_ = (self: Chunk): ReadonlyArray => { * non-empty (`NonEmptyChunk`), the function will return a * `NonEmptyReadonlyArray`, ensuring the non-empty property is preserved. * - * @example + * **Example** (Converting chunks to readonly arrays) + * * ```ts * import { Chunk } from "effect" * @@ -543,7 +493,7 @@ const toReadonlyArray_ = (self: Chunk): ReadonlyArray => { * console.log(Chunk.toReadonlyArray(emptyChunk)) // [] * ``` * - * @category conversions + * @category converting * @since 2.0.0 */ export const toReadonlyArray: >( @@ -569,9 +519,17 @@ const reverseChunk = (self: Chunk): Chunk => { /** * 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 + * **When to use** + * + * Use to read or process chunk elements in reverse order. + * + * **Details** + * + * If the input chunk is a `NonEmptyChunk`, the reversed chunk is also a + * `NonEmptyChunk`. + * + * **Example** (Reversing chunks) * * ```ts * import { Chunk } from "effect" @@ -579,19 +537,20 @@ const reverseChunk = (self: Chunk): Chunk => { * const chunk = Chunk.make(1, 2, 3) * const result = Chunk.reverse(chunk) * - * console.log(result) - * // { _id: 'Chunk', values: [ 3, 2, 1 ] } + * console.log(Chunk.toArray(result)) // [3, 2, 1] * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ export const reverse: >(self: S) => Chunk.With> = reverseChunk as any /** - * This function provides a safe way to read a value at a particular index from a `Chunk`. + * Gets the value at an index in a `Chunk` safely, returning `None` when the index is + * out of bounds. + * + * **Example** (Accessing elements safely) * - * @example * ```ts * import { Chunk } from "effect" * @@ -611,9 +570,11 @@ export const reverse: >(self: S) => Chunk.With(self: Chunk) => Option /** - * This function provides a safe way to read a value at a particular index from a `Chunk`. + * Gets the value at an index in a `Chunk` safely, returning `None` when the index is + * out of bounds. + * + * **Example** (Accessing elements safely) * - * @example * ```ts * import { Chunk } from "effect" * @@ -661,9 +624,19 @@ export const get: { ) /** - * Wraps an array into a chunk without copying, unsafe on mutable arrays + * Wraps an array into a chunk without copying. + * + * **When to use** + * + * Use when the input array can be shared with the resulting `Chunk` and avoiding + * a copy matters. + * + * **Gotchas** + * + * Mutating the source array after wrapping can mutate the resulting `Chunk`. + * + * **Example** (Creating chunks without copying arrays) * - * @example * ```ts * import { Chunk } from "effect" * @@ -676,19 +649,28 @@ export const get: { * console.log(Chunk.toArray(chunk)) // [999, 2, 3, 4, 5] * ``` * - * @since 2.0.0 * @category unsafe + * @since 4.0.0 */ export const fromArrayUnsafe = (self: ReadonlyArray): Chunk => 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 + * Wraps a non-empty array into a non-empty chunk without copying. + * + * **When to use** + * + * Use when the input array is already known to be non-empty, can be shared with + * the resulting `Chunk`, and avoiding a copy matters. + * + * **Gotchas** + * + * Mutating the source array after wrapping can mutate the resulting `Chunk`. + * + * **Example** (Creating non-empty chunks without copying arrays) * - * @example * ```ts - * import { Chunk } from "effect" - * import * as Array from "effect/Array" + * import { Array, Chunk } from "effect" * * const nonEmptyArray = Array.make(1, 2, 3, 4, 5) * const chunk = Chunk.fromNonEmptyArrayUnsafe(nonEmptyArray) @@ -698,82 +680,100 @@ export const fromArrayUnsafe = (self: ReadonlyArray): Chunk => * console.log(Chunk.isNonEmpty(chunk)) // true * ``` * - * @since 2.0.0 * @category unsafe + * @since 4.0.0 */ export const fromNonEmptyArrayUnsafe = (self: NonEmptyReadonlyArray): NonEmptyChunk => fromArrayUnsafe(self) as any /** - * Gets an element unsafely, will throw on out of bounds + * Gets an element at the specified index without returning an `Option`. + * + * **When to use** + * + * Use when reading from a `Chunk` at an index known to be in bounds and direct + * element access is preferred over handling `Option.none`. + * + * **Gotchas** + * + * Throws if the index is out of bounds. + * + * **Example** (Accessing elements unsafely) * - * @example * ```ts - * import { Chunk } from "effect" + * import { Chunk, Option } from "effect" * * const chunk = Chunk.make("a", "b", "c", "d") * * console.log(Chunk.getUnsafe(chunk, 1)) // "b" * console.log(Chunk.getUnsafe(chunk, 3)) // "d" * - * // Warning: This will throw an error for invalid indices - * try { - * Chunk.getUnsafe(chunk, 10) // throws "Index out of bounds" - * } catch (error) { - * console.log((error as Error).message) // "Index out of bounds" - * } + * // Use Chunk.get when the index may be out of bounds + * console.log(Option.isNone(Chunk.get(chunk, 10))) // true * ``` * - * @since 2.0.0 * @category unsafe + * @since 4.0.0 */ export const getUnsafe: { /** - * Gets an element unsafely, will throw on out of bounds + * Gets an element at the specified index without returning an `Option`. + * + * **When to use** + * + * Use when reading from a `Chunk` at an index known to be in bounds and direct + * element access is preferred over handling `Option.none`. + * + * **Gotchas** + * + * Throws if the index is out of bounds. + * + * **Example** (Accessing elements unsafely) * - * @example * ```ts - * import { Chunk } from "effect" + * import { Chunk, Option } from "effect" * * const chunk = Chunk.make("a", "b", "c", "d") * * console.log(Chunk.getUnsafe(chunk, 1)) // "b" * console.log(Chunk.getUnsafe(chunk, 3)) // "d" * - * // Warning: This will throw an error for invalid indices - * try { - * Chunk.getUnsafe(chunk, 10) // throws "Index out of bounds" - * } catch (error) { - * console.log((error as Error).message) // "Index out of bounds" - * } + * // Use Chunk.get when the index may be out of bounds + * console.log(Option.isNone(Chunk.get(chunk, 10))) // true * ``` * - * @since 2.0.0 * @category unsafe + * @since 4.0.0 */ (index: number): (self: Chunk) => A /** - * Gets an element unsafely, will throw on out of bounds + * Gets an element at the specified index without returning an `Option`. + * + * **When to use** + * + * Use when reading from a `Chunk` at an index known to be in bounds and direct + * element access is preferred over handling `Option.none`. + * + * **Gotchas** + * + * Throws if the index is out of bounds. + * + * **Example** (Accessing elements unsafely) * - * @example * ```ts - * import { Chunk } from "effect" + * import { Chunk, Option } from "effect" * * const chunk = Chunk.make("a", "b", "c", "d") * * console.log(Chunk.getUnsafe(chunk, 1)) // "b" * console.log(Chunk.getUnsafe(chunk, 3)) // "d" * - * // Warning: This will throw an error for invalid indices - * try { - * Chunk.getUnsafe(chunk, 10) // throws "Index out of bounds" - * } catch (error) { - * console.log((error as Error).message) // "Index out of bounds" - * } + * // Use Chunk.get when the index may be out of bounds + * console.log(Option.isNone(Chunk.get(chunk, 10))) // true * ``` * - * @since 2.0.0 * @category unsafe + * @since 4.0.0 */ (self: Chunk, index: number): A } = dual(2, (self: Chunk, index: number): A => { @@ -808,7 +808,13 @@ export const getUnsafe: { /** * Appends the specified element to the end of the `Chunk`. * - * @example + * **When to use** + * + * Use to add one element after the existing chunk elements and return a + * `NonEmptyChunk`. + * + * **Example** (Appending an element) + * * ```ts * import { Chunk } from "effect" * @@ -822,14 +828,23 @@ export const getUnsafe: { * console.log(Chunk.toArray(singleElement)) // [42] * ``` * - * @category concatenating + * @see {@link prepend} for adding one element before the existing elements + * @see {@link appendAll} for appending all elements from another chunk + * + * @category combining * @since 2.0.0 */ export const append: { /** * Appends the specified element to the end of the `Chunk`. * - * @example + * **When to use** + * + * Use to add one element after the existing chunk elements and return a + * `NonEmptyChunk`. + * + * **Example** (Appending an element) + * * ```ts * import { Chunk } from "effect" * @@ -843,14 +858,23 @@ export const append: { * console.log(Chunk.toArray(singleElement)) // [42] * ``` * - * @category concatenating + * @see {@link prepend} for adding one element before the existing elements + * @see {@link appendAll} for appending all elements from another chunk + * + * @category combining * @since 2.0.0 */ (a: A2): (self: Chunk) => NonEmptyChunk /** * Appends the specified element to the end of the `Chunk`. * - * @example + * **When to use** + * + * Use to add one element after the existing chunk elements and return a + * `NonEmptyChunk`. + * + * **Example** (Appending an element) + * * ```ts * import { Chunk } from "effect" * @@ -864,16 +888,20 @@ export const append: { * console.log(Chunk.toArray(singleElement)) // [42] * ``` * - * @category concatenating + * @see {@link prepend} for adding one element before the existing elements + * @see {@link appendAll} for appending all elements from another chunk + * + * @category combining * @since 2.0.0 */ (self: Chunk, a: A2): NonEmptyChunk } = dual(2, (self: Chunk, a: A2): NonEmptyChunk => appendAll(self, of(a))) /** - * Prepend an element to the front of a `Chunk`, creating a new `NonEmptyChunk`. + * Prepends an element to the front of a `Chunk`, creating a new `NonEmptyChunk`. + * + * **Example** (Prepending an element) * - * @example * ```ts * import { Chunk } from "effect" * @@ -887,14 +915,15 @@ export const append: { * console.log(Chunk.toArray(singleElement)) // ["first"] * ``` * - * @category concatenating + * @category combining * @since 2.0.0 */ export const prepend: { /** - * Prepend an element to the front of a `Chunk`, creating a new `NonEmptyChunk`. + * Prepends an element to the front of a `Chunk`, creating a new `NonEmptyChunk`. + * + * **Example** (Prepending an element) * - * @example * ```ts * import { Chunk } from "effect" * @@ -908,14 +937,15 @@ export const prepend: { * console.log(Chunk.toArray(singleElement)) // ["first"] * ``` * - * @category concatenating + * @category combining * @since 2.0.0 */ (elem: B): (self: Chunk) => NonEmptyChunk /** - * Prepend an element to the front of a `Chunk`, creating a new `NonEmptyChunk`. + * Prepends an element to the front of a `Chunk`, creating a new `NonEmptyChunk`. + * + * **Example** (Prepending an element) * - * @example * ```ts * import { Chunk } from "effect" * @@ -929,7 +959,7 @@ export const prepend: { * console.log(Chunk.toArray(singleElement)) // ["first"] * ``` * - * @category concatenating + * @category combining * @since 2.0.0 */ (self: Chunk, elem: B): NonEmptyChunk @@ -938,14 +968,14 @@ export const prepend: { /** * Takes the first up to `n` elements from the chunk. * - * @example + * **Example** (Taking elements from the start) + * * ```ts * import { Chunk } from "effect" * * const chunk = Chunk.make(1, 2, 3, 4, 5) * const result = Chunk.take(chunk, 3) - * console.log(result) - * // { _id: 'Chunk', values: [ 1, 2, 3 ] } + * console.log(Chunk.toArray(result)) // [1, 2, 3] * ``` * * @category elements @@ -955,14 +985,14 @@ export const take: { /** * Takes the first up to `n` elements from the chunk. * - * @example + * **Example** (Taking elements from the start) + * * ```ts * import { Chunk } from "effect" * * const chunk = Chunk.make(1, 2, 3, 4, 5) * const result = Chunk.take(chunk, 3) - * console.log(result) - * // { _id: 'Chunk', values: [ 1, 2, 3 ] } + * console.log(Chunk.toArray(result)) // [1, 2, 3] * ``` * * @category elements @@ -972,14 +1002,14 @@ export const take: { /** * Takes the first up to `n` elements from the chunk. * - * @example + * **Example** (Taking elements from the start) + * * ```ts * import { Chunk } from "effect" * * const chunk = Chunk.make(1, 2, 3, 4, 5) * const result = Chunk.take(chunk, 3) - * console.log(result) - * // { _id: 'Chunk', values: [ 1, 2, 3 ] } + * console.log(Chunk.toArray(result)) // [1, 2, 3] * ``` * * @category elements @@ -1027,14 +1057,14 @@ export const take: { /** * Drops the first up to `n` elements from the chunk. * - * @example + * **Example** (Dropping elements from the start) + * * ```ts * import { Chunk } from "effect" * * const chunk = Chunk.make(1, 2, 3, 4, 5) * const result = Chunk.drop(chunk, 2) - * console.log(result) - * // { _id: 'Chunk', values: [ 3, 4, 5 ] } + * console.log(Chunk.toArray(result)) // [3, 4, 5] * ``` * * @category elements @@ -1044,14 +1074,14 @@ export const drop: { /** * Drops the first up to `n` elements from the chunk. * - * @example + * **Example** (Dropping elements from the start) + * * ```ts * import { Chunk } from "effect" * * const chunk = Chunk.make(1, 2, 3, 4, 5) * const result = Chunk.drop(chunk, 2) - * console.log(result) - * // { _id: 'Chunk', values: [ 3, 4, 5 ] } + * console.log(Chunk.toArray(result)) // [3, 4, 5] * ``` * * @category elements @@ -1061,14 +1091,14 @@ export const drop: { /** * Drops the first up to `n` elements from the chunk. * - * @example + * **Example** (Dropping elements from the start) + * * ```ts * import { Chunk } from "effect" * * const chunk = Chunk.make(1, 2, 3, 4, 5) * const result = Chunk.drop(chunk, 2) - * console.log(result) - * // { _id: 'Chunk', values: [ 3, 4, 5 ] } + * console.log(Chunk.toArray(result)) // [3, 4, 5] * ``` * * @category elements @@ -1115,14 +1145,14 @@ export const drop: { /** * Drops the last `n` elements. * - * @example + * **Example** (Dropping elements from the end) + * * ```ts * import { Chunk } from "effect" * * const chunk = Chunk.make(1, 2, 3, 4, 5) * const result = Chunk.dropRight(chunk, 2) - * console.log(result) - * // { _id: 'Chunk', values: [ 1, 2, 3 ] } + * console.log(Chunk.toArray(result)) // [1, 2, 3] * ``` * * @category elements @@ -1132,14 +1162,14 @@ export const dropRight: { /** * Drops the last `n` elements. * - * @example + * **Example** (Dropping elements from the end) + * * ```ts * import { Chunk } from "effect" * * const chunk = Chunk.make(1, 2, 3, 4, 5) * const result = Chunk.dropRight(chunk, 2) - * console.log(result) - * // { _id: 'Chunk', values: [ 1, 2, 3 ] } + * console.log(Chunk.toArray(result)) // [1, 2, 3] * ``` * * @category elements @@ -1149,14 +1179,14 @@ export const dropRight: { /** * Drops the last `n` elements. * - * @example + * **Example** (Dropping elements from the end) + * * ```ts * import { Chunk } from "effect" * * const chunk = Chunk.make(1, 2, 3, 4, 5) * const result = Chunk.dropRight(chunk, 2) - * console.log(result) - * // { _id: 'Chunk', values: [ 1, 2, 3 ] } + * console.log(Chunk.toArray(result)) // [1, 2, 3] * ``` * * @category elements @@ -1168,14 +1198,14 @@ export const dropRight: { /** * Drops all elements so long as the predicate returns true. * - * @example + * **Example** (Dropping elements while a predicate matches) + * * ```ts * import { Chunk } from "effect" * * const chunk = Chunk.make(1, 2, 3, 4, 5) * const result = Chunk.dropWhile(chunk, (n) => n < 3) - * console.log(result) - * // { _id: 'Chunk', values: [ 3, 4, 5 ] } + * console.log(Chunk.toArray(result)) // [3, 4, 5] * ``` * * @category elements @@ -1185,14 +1215,14 @@ export const dropWhile: { /** * Drops all elements so long as the predicate returns true. * - * @example + * **Example** (Dropping elements while a predicate matches) + * * ```ts * import { Chunk } from "effect" * * const chunk = Chunk.make(1, 2, 3, 4, 5) * const result = Chunk.dropWhile(chunk, (n) => n < 3) - * console.log(result) - * // { _id: 'Chunk', values: [ 3, 4, 5 ] } + * console.log(Chunk.toArray(result)) // [3, 4, 5] * ``` * * @category elements @@ -1202,14 +1232,14 @@ export const dropWhile: { /** * Drops all elements so long as the predicate returns true. * - * @example + * **Example** (Dropping elements while a predicate matches) + * * ```ts * import { Chunk } from "effect" * * const chunk = Chunk.make(1, 2, 3, 4, 5) * const result = Chunk.dropWhile(chunk, (n) => n < 3) - * console.log(result) - * // { _id: 'Chunk', values: [ 3, 4, 5 ] } + * console.log(Chunk.toArray(result)) // [3, 4, 5] * ``` * * @category elements @@ -1230,7 +1260,7 @@ export const dropWhile: { * 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 + * **Example** (Prepending all elements) * * ```ts * import { Chunk } from "effect" @@ -1244,7 +1274,7 @@ export const dropWhile: { * // [ "a", "b", 1, 2 ] * ``` * - * @category concatenating + * @category combining * @since 2.0.0 */ export const prependAll: { @@ -1252,7 +1282,7 @@ 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 + * **Example** (Prepending all elements) * * ```ts * import { Chunk } from "effect" @@ -1266,7 +1296,7 @@ export const prependAll: { * // [ "a", "b", 1, 2 ] * ``` * - * @category concatenating + * @category combining * @since 2.0.0 */ , T extends Chunk>(that: T): (self: S) => Chunk.OrNonEmpty | Chunk.Infer> @@ -1274,7 +1304,7 @@ 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 + * **Example** (Prepending all elements) * * ```ts * import { Chunk } from "effect" @@ -1288,7 +1318,7 @@ export const prependAll: { * // [ "a", "b", 1, 2 ] * ``` * - * @category concatenating + * @category combining * @since 2.0.0 */ (self: Chunk, that: NonEmptyChunk): NonEmptyChunk @@ -1296,7 +1326,7 @@ 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 + * **Example** (Prepending all elements) * * ```ts * import { Chunk } from "effect" @@ -1310,7 +1340,7 @@ export const prependAll: { * // [ "a", "b", 1, 2 ] * ``` * - * @category concatenating + * @category combining * @since 2.0.0 */ (self: NonEmptyChunk, that: Chunk): NonEmptyChunk @@ -1318,7 +1348,7 @@ 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 + * **Example** (Prepending all elements) * * ```ts * import { Chunk } from "effect" @@ -1332,7 +1362,7 @@ export const prependAll: { * // [ "a", "b", 1, 2 ] * ``` * - * @category concatenating + * @category combining * @since 2.0.0 */ (self: Chunk, that: Chunk): Chunk @@ -1342,7 +1372,12 @@ export const prependAll: { * Concatenates two chunks, combining their elements. * If either chunk is non-empty, the result is also a non-empty chunk. * - * @example + * **When to use** + * + * Use to concatenate two chunks when the second chunk's elements should come + * after the first. + * + * **Example** (Appending all elements) * * ```ts * import { Chunk } from "effect" @@ -1356,7 +1391,10 @@ export const prependAll: { * // [ 1, 2, "a", "b" ] * ``` * - * @category concatenating + * @see {@link prependAll} for concatenating chunks in the opposite order + * @see {@link append} for adding a single element to the end + * + * @category combining * @since 2.0.0 */ export const appendAll: { @@ -1364,7 +1402,12 @@ export const appendAll: { * Concatenates two chunks, combining their elements. * If either chunk is non-empty, the result is also a non-empty chunk. * - * @example + * **When to use** + * + * Use to concatenate two chunks when the second chunk's elements should come + * after the first. + * + * **Example** (Appending all elements) * * ```ts * import { Chunk } from "effect" @@ -1378,7 +1421,10 @@ export const appendAll: { * // [ 1, 2, "a", "b" ] * ``` * - * @category concatenating + * @see {@link prependAll} for concatenating chunks in the opposite order + * @see {@link append} for adding a single element to the end + * + * @category combining * @since 2.0.0 */ , T extends Chunk>(that: T): (self: S) => Chunk.OrNonEmpty | Chunk.Infer> @@ -1386,7 +1432,12 @@ export const appendAll: { * Concatenates two chunks, combining their elements. * If either chunk is non-empty, the result is also a non-empty chunk. * - * @example + * **When to use** + * + * Use to concatenate two chunks when the second chunk's elements should come + * after the first. + * + * **Example** (Appending all elements) * * ```ts * import { Chunk } from "effect" @@ -1400,7 +1451,10 @@ export const appendAll: { * // [ 1, 2, "a", "b" ] * ``` * - * @category concatenating + * @see {@link prependAll} for concatenating chunks in the opposite order + * @see {@link append} for adding a single element to the end + * + * @category combining * @since 2.0.0 */ (self: Chunk, that: NonEmptyChunk): NonEmptyChunk @@ -1408,7 +1462,12 @@ export const appendAll: { * Concatenates two chunks, combining their elements. * If either chunk is non-empty, the result is also a non-empty chunk. * - * @example + * **When to use** + * + * Use to concatenate two chunks when the second chunk's elements should come + * after the first. + * + * **Example** (Appending all elements) * * ```ts * import { Chunk } from "effect" @@ -1422,7 +1481,10 @@ export const appendAll: { * // [ 1, 2, "a", "b" ] * ``` * - * @category concatenating + * @see {@link prependAll} for concatenating chunks in the opposite order + * @see {@link append} for adding a single element to the end + * + * @category combining * @since 2.0.0 */ (self: NonEmptyChunk, that: Chunk): NonEmptyChunk @@ -1430,7 +1492,12 @@ export const appendAll: { * Concatenates two chunks, combining their elements. * If either chunk is non-empty, the result is also a non-empty chunk. * - * @example + * **When to use** + * + * Use to concatenate two chunks when the second chunk's elements should come + * after the first. + * + * **Example** (Appending all elements) * * ```ts * import { Chunk } from "effect" @@ -1444,7 +1511,10 @@ export const appendAll: { * // [ 1, 2, "a", "b" ] * ``` * - * @category concatenating + * @see {@link prependAll} for concatenating chunks in the opposite order + * @see {@link append} for adding a single element to the end + * + * @category combining * @since 2.0.0 */ (self: Chunk, that: Chunk): Chunk @@ -1461,7 +1531,12 @@ export const appendAll: { * Concatenates two chunks, combining their elements. * If either chunk is non-empty, the result is also a non-empty chunk. * - * @example + * **When to use** + * + * Use to concatenate two chunks when the second chunk's elements should come + * after the first. + * + * **Example** (Appending all elements) * * ```ts * import { Chunk } from "effect" @@ -1475,7 +1550,10 @@ export const appendAll: { * // [ 1, 2, "a", "b" ] * ``` * - * @category concatenating + * @see {@link prependAll} for concatenating chunks in the opposite order + * @see {@link append} for adding a single element to the end + * + * @category combining * @since 2.0.0 */ A | B>({ _tag: "IConcat", left: self, right: that }); @@ -1513,10 +1591,10 @@ export const appendAll: { /** * Returns a filtered and mapped subset of the elements. * - * @example + * **Example** (Filtering and mapping values) + * * ```ts - * import { Chunk } from "effect" - * import * as Result from "effect/Result" + * import { Chunk, Result } from "effect" * * const chunk = Chunk.make("1", "2", "hello", "3", "world") * const numbers = Chunk.filterMap(chunk, (str) => { @@ -1533,17 +1611,17 @@ export const appendAll: { * console.log(Chunk.toArray(evenIndexNumbers)) // [1] * ``` * - * @since 2.0.0 * @category filtering + * @since 2.0.0 */ export const filterMap: { /** * Returns a filtered and mapped subset of the elements. * - * @example + * **Example** (Filtering and mapping values) + * * ```ts - * import { Chunk } from "effect" - * import * as Result from "effect/Result" + * import { Chunk, Result } from "effect" * * const chunk = Chunk.make("1", "2", "hello", "3", "world") * const numbers = Chunk.filterMap(chunk, (str) => { @@ -1560,17 +1638,17 @@ export const filterMap: { * console.log(Chunk.toArray(evenIndexNumbers)) // [1] * ``` * - * @since 2.0.0 * @category filtering + * @since 2.0.0 */ (f: (input: A, i: number) => Result): (self: Chunk) => Chunk /** * Returns a filtered and mapped subset of the elements. * - * @example + * **Example** (Filtering and mapping values) + * * ```ts - * import { Chunk } from "effect" - * import * as Result from "effect/Result" + * import { Chunk, Result } from "effect" * * const chunk = Chunk.make("1", "2", "hello", "3", "world") * const numbers = Chunk.filterMap(chunk, (str) => { @@ -1587,8 +1665,8 @@ export const filterMap: { * console.log(Chunk.toArray(evenIndexNumbers)) // [1] * ``` * - * @since 2.0.0 * @category filtering + * @since 2.0.0 */ (self: Chunk, f: (input: A, i: number) => Result): Chunk } = dual( @@ -1609,7 +1687,8 @@ export const filterMap: { /** * Returns a filtered subset of the elements. * - * @example + * **Example** (Filtering values) + * * ```ts * import { Chunk } from "effect" * @@ -1623,14 +1702,15 @@ export const filterMap: { * console.log(Chunk.toArray(numbers)) // [42, 100] * ``` * - * @since 2.0.0 * @category filtering + * @since 2.0.0 */ export const filter: { /** * Returns a filtered subset of the elements. * - * @example + * **Example** (Filtering values) + * * ```ts * import { Chunk } from "effect" * @@ -1644,14 +1724,15 @@ export const filter: { * console.log(Chunk.toArray(numbers)) // [42, 100] * ``` * - * @since 2.0.0 * @category filtering + * @since 2.0.0 */ (refinement: Refinement, B>): (self: Chunk) => Chunk /** * Returns a filtered subset of the elements. * - * @example + * **Example** (Filtering values) + * * ```ts * import { Chunk } from "effect" * @@ -1665,14 +1746,15 @@ export const filter: { * console.log(Chunk.toArray(numbers)) // [42, 100] * ``` * - * @since 2.0.0 * @category filtering + * @since 2.0.0 */ (predicate: Predicate>): (self: Chunk) => Chunk /** * Returns a filtered subset of the elements. * - * @example + * **Example** (Filtering values) + * * ```ts * import { Chunk } from "effect" * @@ -1686,14 +1768,15 @@ export const filter: { * console.log(Chunk.toArray(numbers)) // [42, 100] * ``` * - * @since 2.0.0 * @category filtering + * @since 2.0.0 */ (self: Chunk, refinement: Refinement): Chunk /** * Returns a filtered subset of the elements. * - * @example + * **Example** (Filtering values) + * * ```ts * import { Chunk } from "effect" * @@ -1707,8 +1790,8 @@ export const filter: { * console.log(Chunk.toArray(numbers)) // [42, 100] * ``` * - * @since 2.0.0 * @category filtering + * @since 2.0.0 */ (self: Chunk, predicate: Predicate): Chunk } = dual( @@ -1719,10 +1802,10 @@ export const filter: { /** * Transforms all elements of the chunk for as long as the specified function succeeds. * - * @example + * **Example** (Filtering and mapping while values match) + * * ```ts - * import { Chunk } from "effect" - * import * as Result from "effect/Result" + * import { Chunk, Result } from "effect" * * const chunk = Chunk.make("1", "2", "hello", "3", "4") * const result = Chunk.filterMapWhile(chunk, (s) => { @@ -1740,17 +1823,17 @@ export const filter: { * console.log(Chunk.toArray(allNumbers)) // [1, 2, 3, 4] * ``` * - * @since 2.0.0 * @category filtering + * @since 2.0.0 */ export const filterMapWhile: { /** * Transforms all elements of the chunk for as long as the specified function succeeds. * - * @example + * **Example** (Filtering and mapping while values match) + * * ```ts - * import { Chunk } from "effect" - * import * as Result from "effect/Result" + * import { Chunk, Result } from "effect" * * const chunk = Chunk.make("1", "2", "hello", "3", "4") * const result = Chunk.filterMapWhile(chunk, (s) => { @@ -1768,17 +1851,17 @@ export const filterMapWhile: { * console.log(Chunk.toArray(allNumbers)) // [1, 2, 3, 4] * ``` * - * @since 2.0.0 * @category filtering + * @since 2.0.0 */ (f: Filter.Filter): (self: Chunk) => Chunk /** * Transforms all elements of the chunk for as long as the specified function succeeds. * - * @example + * **Example** (Filtering and mapping while values match) + * * ```ts - * import { Chunk } from "effect" - * import * as Result from "effect/Result" + * import { Chunk, Result } from "effect" * * const chunk = Chunk.make("1", "2", "hello", "3", "4") * const result = Chunk.filterMapWhile(chunk, (s) => { @@ -1796,8 +1879,8 @@ export const filterMapWhile: { * console.log(Chunk.toArray(allNumbers)) // [1, 2, 3, 4] * ``` * - * @since 2.0.0 * @category filtering + * @since 2.0.0 */ (self: Chunk, f: Filter.Filter): Chunk } = dual(2, (self: Chunk, f: Filter.Filter): Chunk => { @@ -1814,17 +1897,16 @@ export const filterMapWhile: { }) /** - * Filter out optional values + * Filters out optional values + * + * **Example** (Compacting optional values) * - * @example * ```ts - * import { Chunk } from "effect" - * import * as Option from "effect/Option" + * import { Chunk, Option } from "effect" * * const chunk = Chunk.make(Option.some(1), Option.none(), Option.some(3)) * const result = Chunk.compact(chunk) - * console.log(result) - * // { _id: 'Chunk', values: [ 1, 3 ] } + * console.log(Chunk.toArray(result)) // [1, 3] * ``` * * @category filtering @@ -1843,7 +1925,8 @@ export const compact = (self: Chunk>): Chunk => { /** * Applies a function to each element in a chunk and returns a new chunk containing the concatenated mapped elements. * - * @example + * **Example** (Flat mapping chunks) + * * ```ts * import { Chunk } from "effect" * @@ -1864,14 +1947,15 @@ export const compact = (self: Chunk>): Chunk => { * console.log(Chunk.toArray(indexed)) // [1, 3, 5] * ``` * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ export const flatMap: { /** * Applies a function to each element in a chunk and returns a new chunk containing the concatenated mapped elements. * - * @example + * **Example** (Flat mapping chunks) + * * ```ts * import { Chunk } from "effect" * @@ -1892,14 +1976,15 @@ export const flatMap: { * console.log(Chunk.toArray(indexed)) // [1, 3, 5] * ``` * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ , T extends Chunk>(f: (a: Chunk.Infer, i: number) => T): (self: S) => Chunk.AndNonEmpty> /** * Applies a function to each element in a chunk and returns a new chunk containing the concatenated mapped elements. * - * @example + * **Example** (Flat mapping chunks) + * * ```ts * import { Chunk } from "effect" * @@ -1920,14 +2005,15 @@ export const flatMap: { * console.log(Chunk.toArray(indexed)) // [1, 3, 5] * ``` * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ (self: NonEmptyChunk, f: (a: A, i: number) => NonEmptyChunk): NonEmptyChunk /** * Applies a function to each element in a chunk and returns a new chunk containing the concatenated mapped elements. * - * @example + * **Example** (Flat mapping chunks) + * * ```ts * import { Chunk } from "effect" * @@ -1948,8 +2034,8 @@ export const flatMap: { * console.log(Chunk.toArray(indexed)) // [1, 3, 5] * ``` * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ (self: Chunk, f: (a: A, i: number) => Chunk): Chunk } = dual(2, (self: Chunk, f: (a: A, i: number) => Chunk) => { @@ -1974,7 +2060,8 @@ export const flatMap: { * instead, it is primarily used for side effects, such as logging or * accumulating data in an external variable. * - * @example + * **Example** (Iterating over chunk values) + * * ```ts * import { Chunk } from "effect" * @@ -1997,8 +2084,8 @@ export const flatMap: { * // Index 3: 4 * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const forEach: { /** @@ -2011,7 +2098,8 @@ export const forEach: { * instead, it is primarily used for side effects, such as logging or * accumulating data in an external variable. * - * @example + * **Example** (Iterating over chunk values) + * * ```ts * import { Chunk } from "effect" * @@ -2034,8 +2122,8 @@ export const forEach: { * // Index 3: 4 * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (f: (a: A, index: number) => B): (self: Chunk) => void /** @@ -2048,7 +2136,8 @@ export const forEach: { * instead, it is primarily used for side effects, such as logging or * accumulating data in an external variable. * - * @example + * **Example** (Iterating over chunk values) + * * ```ts * import { Chunk } from "effect" * @@ -2071,8 +2160,8 @@ export const forEach: { * // Index 3: 4 * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (self: Chunk, f: (a: A, index: number) => B): void } = dual(2, (self: Chunk, f: (a: A) => B): void => toReadonlyArray(self).forEach(f)) @@ -2080,7 +2169,8 @@ export const forEach: { /** * Flattens a chunk of chunks into a single chunk by concatenating all chunks. * - * @example + * **Example** (Flattening nested chunks) + * * ```ts * import { Chunk } from "effect" * @@ -2101,15 +2191,30 @@ export const forEach: { * console.log(Chunk.toArray(Chunk.flatten(withEmpty))) // [1, 2, 3, 4] * ``` * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ export const flatten: >>(self: S) => Chunk.Flatten = flatMap(identity) as any /** * Groups elements in chunks of up to `n` elements. * - * @example + * **When to use** + * + * Use to divide a chunk into ordered, non-overlapping chunks with at most `n` + * elements each. + * + * **Details** + * + * The final chunk may contain fewer than `n` elements. Empty input produces an + * empty chunk of chunks. + * + * **Gotchas** + * + * Values of `n` less than or equal to zero produce singleton chunks. + * + * **Example** (Splitting into fixed-size chunks) + * * ```ts * import { Chunk } from "effect" * @@ -2126,14 +2231,31 @@ export const flatten: >>(self: S) => Chunk.Flatten * // [[1, 2], [3, 4], [5]] * ``` * - * @since 2.0.0 + * @see {@link split} for splitting into a target number of chunks instead of a fixed chunk size + * * @category elements + * @since 2.0.0 */ export const chunksOf: { /** * Groups elements in chunks of up to `n` elements. * - * @example + * **When to use** + * + * Use to divide a chunk into ordered, non-overlapping chunks with at most `n` + * elements each. + * + * **Details** + * + * The final chunk may contain fewer than `n` elements. Empty input produces an + * empty chunk of chunks. + * + * **Gotchas** + * + * Values of `n` less than or equal to zero produce singleton chunks. + * + * **Example** (Splitting into fixed-size chunks) + * * ```ts * import { Chunk } from "effect" * @@ -2150,14 +2272,31 @@ export const chunksOf: { * // [[1, 2], [3, 4], [5]] * ``` * - * @since 2.0.0 + * @see {@link split} for splitting into a target number of chunks instead of a fixed chunk size + * * @category elements + * @since 2.0.0 */ (n: number): (self: Chunk) => Chunk> /** * Groups elements in chunks of up to `n` elements. * - * @example + * **When to use** + * + * Use to divide a chunk into ordered, non-overlapping chunks with at most `n` + * elements each. + * + * **Details** + * + * The final chunk may contain fewer than `n` elements. Empty input produces an + * empty chunk of chunks. + * + * **Gotchas** + * + * Values of `n` less than or equal to zero produce singleton chunks. + * + * **Example** (Splitting into fixed-size chunks) + * * ```ts * import { Chunk } from "effect" * @@ -2174,8 +2313,10 @@ export const chunksOf: { * // [[1, 2], [3, 4], [5]] * ``` * - * @since 2.0.0 + * @see {@link split} for splitting into a target number of chunks instead of a fixed chunk size + * * @category elements + * @since 2.0.0 */ (self: Chunk, n: number): Chunk> } = dual(2, (self: Chunk, n: number) => { @@ -2195,11 +2336,14 @@ export const chunksOf: { }) /** - * Creates a Chunk of unique values that are included in all given Chunks. + * Creates a `Chunk` of values that are included in both chunks. * - * The order and references of result values are determined by the Chunk. + * **Details** + * + * The order and references of result values are determined by the first chunk. + * + * **Example** (Intersecting chunks) * - * @example * ```ts * import { Chunk } from "effect" * @@ -2219,16 +2363,19 @@ export const chunksOf: { * console.log(Chunk.toArray(Chunk.intersection(chunk3, chunk4))) // [] * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ export const intersection: { /** - * Creates a Chunk of unique values that are included in all given Chunks. + * Creates a `Chunk` of values that are included in both chunks. * - * The order and references of result values are determined by the Chunk. + * **Details** + * + * The order and references of result values are determined by the first chunk. + * + * **Example** (Intersecting chunks) * - * @example * ```ts * import { Chunk } from "effect" * @@ -2248,16 +2395,19 @@ export const intersection: { * console.log(Chunk.toArray(Chunk.intersection(chunk3, chunk4))) // [] * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (that: Chunk): (self: Chunk) => Chunk /** - * Creates a Chunk of unique values that are included in all given Chunks. + * Creates a `Chunk` of values that are included in both chunks. + * + * **Details** * - * The order and references of result values are determined by the Chunk. + * The order and references of result values are determined by the first chunk. + * + * **Example** (Intersecting chunks) * - * @example * ```ts * import { Chunk } from "effect" * @@ -2277,8 +2427,8 @@ export const intersection: { * console.log(Chunk.toArray(Chunk.intersection(chunk3, chunk4))) // [] * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (self: Chunk, that: Chunk): Chunk } = dual( @@ -2290,7 +2440,8 @@ export const intersection: { /** * Determines if the chunk is empty. * - * @example + * **Example** (Checking for empty chunks) + * * ```ts * import { Chunk } from "effect" * @@ -2306,7 +2457,8 @@ export const isEmpty = (self: Chunk): boolean => self.length === 0 /** * Determines if the chunk is not empty. * - * @example + * **Example** (Checking for non-empty chunks) + * * ```ts * import { Chunk } from "effect" * @@ -2320,9 +2472,10 @@ export const isEmpty = (self: Chunk): boolean => self.length === 0 export const isNonEmpty = (self: Chunk): self is NonEmptyChunk => self.length > 0 /** - * Returns the first element of this chunk if it exists. + * Returns the first element of this chunk safely if it exists. + * + * **Example** (Getting the first element) * - * @example * ```ts * import { Chunk } from "effect" * @@ -2338,11 +2491,19 @@ export const head: (self: Chunk) => Option = get(0) /** * Returns the first element of this chunk. * - * It will throw an error if the chunk is empty. + * **When to use** + * + * Use when you know the chunk is non-empty and need the first element directly + * without handling `Option.none`. + * + * **Gotchas** + * + * Throws an error if the chunk is empty. + * + * **Example** (Getting the first element unsafely) * - * @example * ```ts - * import { Chunk } from "effect" + * import { Chunk, Option } from "effect" * * const chunk = Chunk.make(1, 2, 3, 4) * console.log(Chunk.headUnsafe(chunk)) // 1 @@ -2350,23 +2511,20 @@ export const head: (self: Chunk) => Option = get(0) * const singleElement = Chunk.make("hello") * console.log(Chunk.headUnsafe(singleElement)) // "hello" * - * // Warning: This will throw for empty chunks - * try { - * Chunk.headUnsafe(Chunk.empty()) - * } catch (error) { - * console.log((error as Error).message) // "Index out of bounds" - * } + * // Use Chunk.head when the chunk may be empty + * console.log(Option.isNone(Chunk.head(Chunk.empty()))) // true * ``` * - * @since 2.0.0 * @category unsafe + * @since 4.0.0 */ export const headUnsafe = (self: Chunk): A => getUnsafe(self, 0) /** * Returns the first element of this non empty chunk. * - * @example + * **Example** (Getting the first element of a non-empty chunk) + * * ```ts * import { Chunk } from "effect" * @@ -2380,15 +2538,16 @@ export const headUnsafe = (self: Chunk): A => getUnsafe(self, 0) * // Chunk.headNonEmpty(Chunk.empty()) // TypeScript error * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ export const headNonEmpty: (self: NonEmptyChunk) => A = headUnsafe /** - * Returns the last element of this chunk if it exists. + * Returns the last element of this chunk safely if it exists. + * + * **Example** (Getting the last element) * - * @example * ```ts * import { Chunk } from "effect" * @@ -2404,11 +2563,19 @@ export const last = (self: Chunk): Option => get(self, self.length - 1) /** * Returns the last element of this chunk. * - * It will throw an error if the chunk is empty. + * **When to use** + * + * Use when you know the chunk is non-empty and need the last element directly + * without handling `Option.none`. + * + * **Gotchas** + * + * Throws an error if the chunk is empty. + * + * **Example** (Getting the last element unsafely) * - * @example * ```ts - * import { Chunk } from "effect" + * import { Chunk, Option } from "effect" * * const chunk = Chunk.make(1, 2, 3, 4) * console.log(Chunk.lastUnsafe(chunk)) // 4 @@ -2416,23 +2583,20 @@ export const last = (self: Chunk): Option => get(self, self.length - 1) * const singleElement = Chunk.make("hello") * console.log(Chunk.lastUnsafe(singleElement)) // "hello" * - * // Warning: This will throw for empty chunks - * try { - * Chunk.lastUnsafe(Chunk.empty()) - * } catch (error) { - * console.log((error as Error).message) // "Index out of bounds" - * } + * // Use Chunk.last when the chunk may be empty + * console.log(Option.isNone(Chunk.last(Chunk.empty()))) // true * ``` * - * @since 2.0.0 * @category unsafe + * @since 4.0.0 */ export const lastUnsafe = (self: Chunk): A => getUnsafe(self, self.length - 1) /** * Returns the last element of this non empty chunk. * - * @example + * **Example** (Getting the last element of a non-empty chunk) + * * ```ts * import { Chunk } from "effect" * @@ -2446,15 +2610,16 @@ export const lastUnsafe = (self: Chunk): A => getUnsafe(self, self.length * // Chunk.lastNonEmpty(Chunk.empty()) // TypeScript error * ``` * - * @since 3.4.0 * @category elements + * @since 3.4.0 */ export const lastNonEmpty: (self: NonEmptyChunk) => A = lastUnsafe /** * A namespace containing utility types for Chunk operations. * - * @example + * **Example** (Working with Chunk utility types) + * * ```ts * import type { Chunk } from "effect" * @@ -2467,14 +2632,14 @@ export const lastNonEmpty: (self: NonEmptyChunk) => A = lastUnsafe * type WithString = Chunk.Chunk.With // Chunk.NonEmptyChunk * ``` * - * @category types * @since 2.0.0 */ export declare namespace Chunk { /** * Infers the element type of a Chunk. * - * @example + * **Example** (Inferring element types) + * * ```ts * import type { Chunk } from "effect" * @@ -2493,7 +2658,8 @@ export declare namespace Chunk { /** * Constructs a Chunk type preserving non-emptiness. * - * @example + * **Example** (Preserving non-emptiness) + * * ```ts * import type { Chunk } from "effect" * @@ -2512,7 +2678,8 @@ export declare namespace Chunk { /** * Creates a non-empty Chunk if either input is non-empty. * - * @example + * **Example** (Preserving non-emptiness from either input) + * * ```ts * import type { Chunk } from "effect" * @@ -2547,7 +2714,8 @@ export declare namespace Chunk { /** * Creates a non-empty Chunk only if both inputs are non-empty. * - * @example + * **Example** (Requiring non-emptiness from both inputs) + * * ```ts * import type { Chunk } from "effect" * @@ -2582,7 +2750,8 @@ export declare namespace Chunk { /** * Flattens a nested Chunk type. * - * @example + * **Example** (Flattening nested chunk types) + * * ```ts * import type { Chunk } from "effect" * @@ -2605,76 +2774,72 @@ export declare namespace Chunk { * 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 + * **Example** (Mapping values) * * ```ts * import { Chunk } from "effect" * * const result = Chunk.map(Chunk.make(1, 2), (n) => n + 1) * - * console.log(result) - * // { _id: 'Chunk', values: [ 2, 3 ] } + * console.log(Chunk.toArray(result)) // [2, 3] * ``` * - * @since 2.0.0 * @category mapping + * @since 2.0.0 */ 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 + * **Example** (Mapping values) * * ```ts * import { Chunk } from "effect" * * const result = Chunk.map(Chunk.make(1, 2), (n) => n + 1) * - * console.log(result) - * // { _id: 'Chunk', values: [ 2, 3 ] } + * console.log(Chunk.toArray(result)) // [2, 3] * ``` * - * @since 2.0.0 * @category mapping + * @since 2.0.0 */ , B>(f: (a: Chunk.Infer, i: number) => B): (self: S) => Chunk.With /** * 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 + * **Example** (Mapping values) * * ```ts * import { Chunk } from "effect" * * const result = Chunk.map(Chunk.make(1, 2), (n) => n + 1) * - * console.log(result) - * // { _id: 'Chunk', values: [ 2, 3 ] } + * console.log(Chunk.toArray(result)) // [2, 3] * ``` * - * @since 2.0.0 * @category mapping + * @since 2.0.0 */ (self: NonEmptyChunk, f: (a: A, i: number) => B): NonEmptyChunk /** * 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 + * **Example** (Mapping values) * * ```ts * import { Chunk } from "effect" * * const result = Chunk.map(Chunk.make(1, 2), (n) => n + 1) * - * console.log(result) - * // { _id: 'Chunk', values: [ 2, 3 ] } + * console.log(Chunk.toArray(result)) // [2, 3] * ``` * - * @since 2.0.0 * @category mapping + * @since 2.0.0 */ (self: Chunk, f: (a: A, i: number) => B): Chunk } = dual(2, (self: Chunk, f: (a: A, i: number) => B): Chunk => @@ -2683,9 +2848,10 @@ export const map: { fromArrayUnsafe(pipe(toReadonlyArray(self), RA.map((a, i) => f(a, i))))) /** - * Statefully maps over the chunk, producing new elements of type `B`. + * Maps over the chunk statefully, producing new elements of type `B`. + * + * **Example** (Mapping with accumulated state) * - * @example * ```ts * import { Chunk } from "effect" * @@ -2708,14 +2874,15 @@ export const map: { * console.log(Chunk.toArray(indexed)) // ["0: hello", "1: world", "2: effect"] * ``` * - * @since 2.0.0 * @category folding + * @since 2.0.0 */ export const mapAccum: { /** - * Statefully maps over the chunk, producing new elements of type `B`. + * Maps over the chunk statefully, producing new elements of type `B`. + * + * **Example** (Mapping with accumulated state) * - * @example * ```ts * import { Chunk } from "effect" * @@ -2738,14 +2905,15 @@ export const mapAccum: { * console.log(Chunk.toArray(indexed)) // ["0: hello", "1: world", "2: effect"] * ``` * - * @since 2.0.0 * @category folding + * @since 2.0.0 */ (s: S, f: (s: S, a: A) => readonly [S, B]): (self: Chunk) => [S, Chunk] /** - * Statefully maps over the chunk, producing new elements of type `B`. + * Maps over the chunk statefully, producing new elements of type `B`. + * + * **Example** (Mapping with accumulated state) * - * @example * ```ts * import { Chunk } from "effect" * @@ -2768,8 +2936,8 @@ export const mapAccum: { * console.log(Chunk.toArray(indexed)) // ["0: hello", "1: world", "2: effect"] * ``` * - * @since 2.0.0 * @category folding + * @since 2.0.0 */ (self: Chunk, s: S, f: (s: S, a: A) => readonly [S, B]): [S, Chunk] } = dual(3, (self: Chunk, s: S, f: (s: S, a: A) => readonly [S, B]): [S, Chunk] => { @@ -2780,10 +2948,12 @@ export const mapAccum: { /** * Splits a chunk using a `Filter` into failures and successes. * - * - Returns `[excluded, satisfying]`. - * - The filter receives `(element, index)`. + * **Details** + * + * Returns `[excluded, satisfying]`. The filter receives `(element, index)`. + * + * **Example** (Partitioning with a Result) * - * @example * ```ts * import { Chunk, Result } from "effect" * @@ -2802,10 +2972,12 @@ export const partition: { /** * Splits a chunk using a `Filter` into failures and successes. * - * - Returns `[excluded, satisfying]`. - * - The filter receives `(element, index)`. + * **Details** + * + * Returns `[excluded, satisfying]`. The filter receives `(element, index)`. + * + * **Example** (Partitioning with a Result) * - * @example * ```ts * import { Chunk, Result } from "effect" * @@ -2824,10 +2996,12 @@ export const partition: { /** * Splits a chunk using a `Filter` into failures and successes. * - * - Returns `[excluded, satisfying]`. - * - The filter receives `(element, index)`. + * **Details** + * + * Returns `[excluded, satisfying]`. The filter receives `(element, index)`. + * + * **Example** (Partitioning with a Result) * - * @example * ```ts * import { Chunk, Result } from "effect" * @@ -2855,12 +3029,18 @@ export const partition: { ) /** - * Partitions the elements of this chunk into two chunks. + * Separates a chunk of `Result` values into a chunk of failures and a chunk of + * successes. + * + * **Details** + * + * The returned tuple is `[failures, successes]`, preserving the original order + * within each side. + * + * **Example** (Separating failures and successes) * - * @example * ```ts - * import { Chunk } from "effect" - * import * as Result from "effect/Result" + * import { Chunk, Result } from "effect" * * const chunk = Chunk.make( * Result.succeed(1), @@ -2893,7 +3073,8 @@ export const separate = (self: Chunk>): [Chunk, Chunk] /** * Retrieves the size of the chunk. * - * @example + * **Example** (Getting chunk size) + * * ```ts * import { Chunk } from "effect" * @@ -2907,12 +3088,12 @@ export const separate = (self: Chunk>): [Chunk, Chunk] export const size = (self: Chunk): number => self.length /** - * Sort the elements of a Chunk in increasing order, creating a new Chunk. + * Sorts the elements of a `Chunk` in increasing order, creating a new `Chunk`. + * + * **Example** (Sorting chunks) * - * @example * ```ts - * import { Chunk } from "effect" - * import * as Order from "effect/Order" + * import { Chunk, Order } from "effect" * * const numbers = Chunk.make(3, 1, 4, 1, 5, 9, 2, 6) * const sorted = Chunk.sort(numbers, Order.Number) @@ -2928,17 +3109,17 @@ export const size = (self: Chunk): number => self.length * console.log(Chunk.toArray(sortedWords)) // ["apple", "banana", "cherry"] * ``` * - * @since 2.0.0 * @category sorting + * @since 2.0.0 */ export const sort: { /** - * Sort the elements of a Chunk in increasing order, creating a new Chunk. + * Sorts the elements of a `Chunk` in increasing order, creating a new `Chunk`. + * + * **Example** (Sorting chunks) * - * @example * ```ts - * import { Chunk } from "effect" - * import * as Order from "effect/Order" + * import { Chunk, Order } from "effect" * * const numbers = Chunk.make(3, 1, 4, 1, 5, 9, 2, 6) * const sorted = Chunk.sort(numbers, Order.Number) @@ -2954,17 +3135,17 @@ export const sort: { * console.log(Chunk.toArray(sortedWords)) // ["apple", "banana", "cherry"] * ``` * - * @since 2.0.0 * @category sorting + * @since 2.0.0 */ (O: Order.Order): (self: Chunk) => Chunk /** - * Sort the elements of a Chunk in increasing order, creating a new Chunk. + * Sorts the elements of a `Chunk` in increasing order, creating a new `Chunk`. + * + * **Example** (Sorting chunks) * - * @example * ```ts - * import { Chunk } from "effect" - * import * as Order from "effect/Order" + * import { Chunk, Order } from "effect" * * const numbers = Chunk.make(3, 1, 4, 1, 5, 9, 2, 6) * const sorted = Chunk.sort(numbers, Order.Number) @@ -2980,8 +3161,8 @@ export const sort: { * console.log(Chunk.toArray(sortedWords)) // ["apple", "banana", "cherry"] * ``` * - * @since 2.0.0 * @category sorting + * @since 2.0.0 */ (self: Chunk, O: Order.Order): Chunk } = dual( @@ -2990,12 +3171,12 @@ export const sort: { ) /** - * Sorts the elements of a Chunk based on a projection function. + * Sorts the elements of a `Chunk` based on a projection function. + * + * **Example** (Sorting chunks by a derived value) * - * @example * ```ts - * import { Chunk } from "effect" - * import * as Order from "effect/Order" + * import { Chunk, Order } from "effect" * * const people = Chunk.make( * { name: "Alice", age: 30 }, @@ -3019,17 +3200,17 @@ export const sort: { * console.log(Chunk.toArray(byLength)) // ["a", "ab", "abc"] * ``` * - * @since 2.0.0 * @category sorting + * @since 2.0.0 */ export const sortWith: { /** - * Sorts the elements of a Chunk based on a projection function. + * Sorts the elements of a `Chunk` based on a projection function. + * + * **Example** (Sorting chunks by a derived value) * - * @example * ```ts - * import { Chunk } from "effect" - * import * as Order from "effect/Order" + * import { Chunk, Order } from "effect" * * const people = Chunk.make( * { name: "Alice", age: 30 }, @@ -3053,17 +3234,17 @@ export const sortWith: { * console.log(Chunk.toArray(byLength)) // ["a", "ab", "abc"] * ``` * - * @since 2.0.0 * @category sorting + * @since 2.0.0 */ (f: (a: A) => B, order: Order.Order): (self: Chunk) => Chunk /** - * Sorts the elements of a Chunk based on a projection function. + * Sorts the elements of a `Chunk` based on a projection function. + * + * **Example** (Sorting chunks by a derived value) * - * @example * ```ts - * import { Chunk } from "effect" - * import * as Order from "effect/Order" + * import { Chunk, Order } from "effect" * * const people = Chunk.make( * { name: "Alice", age: 30 }, @@ -3087,8 +3268,8 @@ export const sortWith: { * console.log(Chunk.toArray(byLength)) // ["a", "ab", "abc"] * ``` * - * @since 2.0.0 * @category sorting + * @since 2.0.0 */ (self: Chunk, f: (a: A) => B, order: Order.Order): Chunk } = dual( @@ -3099,7 +3280,8 @@ export const sortWith: { /** * Returns two splits of this chunk at the specified index. * - * @example + * **Example** (Splitting at an index) + * * ```ts * import { Chunk } from "effect" * @@ -3119,14 +3301,15 @@ export const sortWith: { * console.log(Chunk.toArray(empty2)) // [] * ``` * - * @since 2.0.0 * @category splitting + * @since 2.0.0 */ export const splitAt: { /** * Returns two splits of this chunk at the specified index. * - * @example + * **Example** (Splitting at an index) + * * ```ts * import { Chunk } from "effect" * @@ -3146,14 +3329,15 @@ export const splitAt: { * console.log(Chunk.toArray(empty2)) // [] * ``` * - * @since 2.0.0 * @category splitting + * @since 2.0.0 */ (n: number): (self: Chunk) => [beforeIndex: Chunk, fromIndex: Chunk] /** * Returns two splits of this chunk at the specified index. * - * @example + * **Example** (Splitting at an index) + * * ```ts * import { Chunk } from "effect" * @@ -3173,17 +3357,24 @@ export const splitAt: { * console.log(Chunk.toArray(empty2)) // [] * ``` * - * @since 2.0.0 * @category splitting + * @since 2.0.0 */ (self: Chunk, n: number): [beforeIndex: Chunk, fromIndex: Chunk] } = dual(2, (self: Chunk, n: number): [Chunk, Chunk] => [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`. + * Splits a `NonEmptyChunk` at `n`, returning a non-empty prefix and the + * remaining suffix. + * + * **Details** + * + * `n` is floored and normalized to at least `1`. If `n` is greater than or + * equal to the chunk length, the first result is the original chunk and the + * second result is empty. + * + * **Example** (Splitting non-empty chunks at an index) * - * @example * ```ts * import { Chunk } from "effect" * @@ -3206,10 +3397,17 @@ export const splitAt: { */ 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`. + * Splits a `NonEmptyChunk` at `n`, returning a non-empty prefix and the + * remaining suffix. + * + * **Details** + * + * `n` is floored and normalized to at least `1`. If `n` is greater than or + * equal to the chunk length, the first result is the original chunk and the + * second result is empty. + * + * **Example** (Splitting non-empty chunks at an index) * - * @example * ```ts * import { Chunk } from "effect" * @@ -3232,10 +3430,17 @@ export const splitNonEmptyAt: { */ (n: number): (self: NonEmptyChunk) => [beforeIndex: NonEmptyChunk, fromIndex: Chunk] /** - * Splits a `NonEmptyChunk` into two segments, with the first segment containing a maximum of `n` elements. - * The value of `n` must be `>= 1`. + * Splits a `NonEmptyChunk` at `n`, returning a non-empty prefix and the + * remaining suffix. + * + * **Details** + * + * `n` is floored and normalized to at least `1`. If `n` is greater than or + * equal to the chunk length, the first result is the original chunk and the + * second result is empty. + * + * **Example** (Splitting non-empty chunks at an index) * - * @example * ```ts * import { Chunk } from "effect" * @@ -3265,9 +3470,15 @@ export const splitNonEmptyAt: { }) /** - * Splits this chunk into `n` equally sized chunks. + * Splits a chunk into up to `n` chunks, distributing elements in order. + * + * **Details** + * + * The chunk size is derived from the input length and `n`; the final chunk may + * contain fewer elements than the others. + * + * **Example** (Splitting chunks into groups) * - * @example * ```ts * import { Chunk } from "effect" * @@ -3288,14 +3499,20 @@ export const splitNonEmptyAt: { * // [[1, 2, 3, 4, 5, 6, 7, 8, 9]] * ``` * - * @since 2.0.0 * @category splitting + * @since 2.0.0 */ export const split: { /** - * Splits this chunk into `n` equally sized chunks. + * Splits a chunk into up to `n` chunks, distributing elements in order. + * + * **Details** + * + * The chunk size is derived from the input length and `n`; the final chunk may + * contain fewer elements than the others. + * + * **Example** (Splitting chunks into groups) * - * @example * ```ts * import { Chunk } from "effect" * @@ -3316,14 +3533,20 @@ export const split: { * // [[1, 2, 3, 4, 5, 6, 7, 8, 9]] * ``` * - * @since 2.0.0 * @category splitting + * @since 2.0.0 */ (n: number): (self: Chunk) => Chunk> /** - * Splits this chunk into `n` equally sized chunks. + * Splits a chunk into up to `n` chunks, distributing elements in order. + * + * **Details** + * + * The chunk size is derived from the input length and `n`; the final chunk may + * contain fewer elements than the others. + * + * **Example** (Splitting chunks into groups) * - * @example * ```ts * import { Chunk } from "effect" * @@ -3344,8 +3567,8 @@ export const split: { * // [[1, 2, 3, 4, 5, 6, 7, 8, 9]] * ``` * - * @since 2.0.0 * @category splitting + * @since 2.0.0 */ (self: Chunk, n: number): Chunk> } = dual(2, (self: Chunk, n: number) => chunksOf(self, Math.ceil(self.length / Math.floor(n)))) @@ -3354,7 +3577,8 @@ export const split: { * 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. * - * @example + * **Example** (Splitting at a matching element) + * * ```ts * import { Chunk } from "effect" * @@ -3382,7 +3606,8 @@ 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. * - * @example + * **Example** (Splitting at a matching element) + * * ```ts * import { Chunk } from "effect" * @@ -3410,7 +3635,8 @@ 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. * - * @example + * **Example** (Splitting at a matching element) + * * ```ts * import { Chunk } from "effect" * @@ -3447,9 +3673,10 @@ export const splitWhere: { }) /** - * Returns every elements after the first. + * Returns every element after the first safely, or `None` when the chunk is empty. + * + * **Example** (Getting the tail safely) * - * @example * ```ts * import { Chunk } from "effect" * @@ -3463,15 +3690,16 @@ export const splitWhere: { * console.log(Chunk.tail(empty)) // Option.none() * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ export const tail = (self: Chunk): O.Option> => self.length > 0 ? O.some(drop(self, 1)) : O.none() /** - * Returns every elements after the first. + * Returns every element after the first from a non-empty chunk. + * + * **Example** (Getting the tail of a non-empty chunk) * - * @example * ```ts * import { Chunk } from "effect" * @@ -3487,15 +3715,16 @@ export const tail = (self: Chunk): O.Option> => self.length > 0 ? * // Chunk.tailNonEmpty(Chunk.empty()) // TypeScript error * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ export const tailNonEmpty = (self: NonEmptyChunk): Chunk => drop(self, 1) /** * Takes the last `n` elements. * - * @example + * **Example** (Taking elements from the end) + * * ```ts * import { Chunk } from "effect" * @@ -3512,14 +3741,15 @@ export const tailNonEmpty = (self: NonEmptyChunk): Chunk => drop(self, * console.log(Chunk.toArray(none)) // [] * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ export const takeRight: { /** * Takes the last `n` elements. * - * @example + * **Example** (Taking elements from the end) + * * ```ts * import { Chunk } from "effect" * @@ -3536,14 +3766,15 @@ export const takeRight: { * console.log(Chunk.toArray(none)) // [] * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (n: number): (self: Chunk) => Chunk /** * Takes the last `n` elements. * - * @example + * **Example** (Taking elements from the end) + * * ```ts * import { Chunk } from "effect" * @@ -3560,8 +3791,8 @@ export const takeRight: { * console.log(Chunk.toArray(none)) // [] * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (self: Chunk, n: number): Chunk } = dual(2, (self: Chunk, n: number): Chunk => drop(self, self.length - n)) @@ -3569,7 +3800,8 @@ export const takeRight: { /** * Takes all elements so long as the predicate returns true. * - * @example + * **Example** (Taking elements while a predicate matches) + * * ```ts * import { Chunk } from "effect" * @@ -3587,14 +3819,15 @@ export const takeRight: { * console.log(Chunk.toArray(all)) // [1, 2, 3] * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ export const takeWhile: { /** * Takes all elements so long as the predicate returns true. * - * @example + * **Example** (Taking elements while a predicate matches) + * * ```ts * import { Chunk } from "effect" * @@ -3612,14 +3845,15 @@ export const takeWhile: { * console.log(Chunk.toArray(all)) // [1, 2, 3] * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (refinement: Refinement, B>): (self: Chunk) => Chunk /** * Takes all elements so long as the predicate returns true. * - * @example + * **Example** (Taking elements while a predicate matches) + * * ```ts * import { Chunk } from "effect" * @@ -3637,14 +3871,15 @@ export const takeWhile: { * console.log(Chunk.toArray(all)) // [1, 2, 3] * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (predicate: Predicate>): (self: Chunk) => Chunk /** * Takes all elements so long as the predicate returns true. * - * @example + * **Example** (Taking elements while a predicate matches) + * * ```ts * import { Chunk } from "effect" * @@ -3662,14 +3897,15 @@ export const takeWhile: { * console.log(Chunk.toArray(all)) // [1, 2, 3] * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (self: Chunk, refinement: Refinement): Chunk /** * Takes all elements so long as the predicate returns true. * - * @example + * **Example** (Taking elements while a predicate matches) + * * ```ts * import { Chunk } from "effect" * @@ -3687,8 +3923,8 @@ export const takeWhile: { * console.log(Chunk.toArray(all)) // [1, 2, 3] * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (self: Chunk, predicate: Predicate): Chunk } = dual(2, (self: Chunk, predicate: Predicate): Chunk => { @@ -3706,7 +3942,8 @@ export const takeWhile: { /** * Creates a Chunks of unique values, in order, from all given Chunks. * - * @example + * **Example** (Unioning chunks) + * * ```ts * import { Chunk } from "effect" * @@ -3722,14 +3959,15 @@ export const takeWhile: { * console.log(Chunk.toArray(unified)) // [1, 2, 3] * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ export const union: { /** * Creates a Chunks of unique values, in order, from all given Chunks. * - * @example + * **Example** (Unioning chunks) + * * ```ts * import { Chunk } from "effect" * @@ -3745,14 +3983,15 @@ export const union: { * console.log(Chunk.toArray(unified)) // [1, 2, 3] * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (that: Chunk): (self: Chunk) => Chunk /** * Creates a Chunks of unique values, in order, from all given Chunks. * - * @example + * **Example** (Unioning chunks) + * * ```ts * import { Chunk } from "effect" * @@ -3768,8 +4007,8 @@ export const union: { * console.log(Chunk.toArray(unified)) // [1, 2, 3] * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (self: Chunk, that: Chunk): Chunk } = dual( @@ -3778,9 +4017,11 @@ export const union: { ) /** - * Remove duplicates from an array, keeping the first occurrence of an element. + * Removes duplicate elements from a `Chunk`, preserving the first occurrence + * of each value. + * + * **Example** (Removing duplicate values) * - * @example * ```ts * import { Chunk } from "effect" * @@ -3799,15 +4040,16 @@ export const union: { * console.log(Chunk.toArray(uniqueDeduped)) // [1, 2, 3] * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ export const dedupe = (self: Chunk): Chunk => fromArrayUnsafe(RA.dedupe(toReadonlyArray(self))) /** * Deduplicates adjacent elements that are identical. * - * @example + * **Example** (Removing adjacent duplicates) + * * ```ts * import { Chunk } from "effect" * @@ -3821,17 +4063,20 @@ export const dedupe = (self: Chunk): Chunk => fromArrayUnsafe(RA.dedupe * console.log(Chunk.toArray(mixedResult)) // ["a", "b", "a"] * ``` * - * @since 2.0.0 * @category filtering + * @since 2.0.0 */ export const dedupeAdjacent = (self: Chunk): Chunk => fromArrayUnsafe(RA.dedupeAdjacent(self)) /** - * Takes a `Chunk` of pairs and return two corresponding `Chunk`s. + * Takes a `Chunk` of pairs and returns two corresponding `Chunk`s. + * + * **Details** + * + * This function is the reverse of `zip`. * - * Note: The function is reverse of `zip`. + * **Example** (Unzipping pairs) * - * @example * ```ts * import { Chunk } from "effect" * @@ -3851,8 +4096,8 @@ export const dedupeAdjacent = (self: Chunk): Chunk => fromArrayUnsafe(R * console.log(Chunk.toArray(emptyStrs)) // [] * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ export const unzip = (self: Chunk): [Chunk, Chunk] => { const [left, right] = RA.unzip(self) @@ -3862,7 +4107,8 @@ export const unzip = (self: Chunk): [Chunk, Chunk] /** * Zips this chunk pointwise with the specified chunk using the specified combiner. * - * @example + * **Example** (Zipping chunks with a function) + * * ```ts * import { Chunk } from "effect" * @@ -3878,14 +4124,15 @@ export const unzip = (self: Chunk): [Chunk, Chunk] * console.log(Chunk.toArray(mixed)) // [[1, "a"], [2, "b"]] * ``` * - * @since 2.0.0 * @category zipping + * @since 2.0.0 */ export const zipWith: { /** * Zips this chunk pointwise with the specified chunk using the specified combiner. * - * @example + * **Example** (Zipping chunks with a function) + * * ```ts * import { Chunk } from "effect" * @@ -3901,14 +4148,15 @@ export const zipWith: { * console.log(Chunk.toArray(mixed)) // [[1, "a"], [2, "b"]] * ``` * - * @since 2.0.0 * @category zipping + * @since 2.0.0 */ (that: Chunk, f: (a: A, b: B) => C): (self: Chunk) => Chunk /** * Zips this chunk pointwise with the specified chunk using the specified combiner. * - * @example + * **Example** (Zipping chunks with a function) + * * ```ts * import { Chunk } from "effect" * @@ -3924,8 +4172,8 @@ export const zipWith: { * console.log(Chunk.toArray(mixed)) // [[1, "a"], [2, "b"]] * ``` * - * @since 2.0.0 * @category zipping + * @since 2.0.0 */ (self: Chunk, that: Chunk, f: (a: A, b: B) => C): Chunk } = dual( @@ -3937,7 +4185,8 @@ export const zipWith: { /** * Zips this chunk pointwise with the specified chunk. * - * @example + * **Example** (Zipping chunks) + * * ```ts * import { Chunk } from "effect" * @@ -3953,14 +4202,15 @@ export const zipWith: { * console.log(Chunk.toArray(zipped)) // [[1, "a"], [2, "b"]] * ``` * - * @since 2.0.0 * @category zipping + * @since 2.0.0 */ export const zip: { /** * Zips this chunk pointwise with the specified chunk. * - * @example + * **Example** (Zipping chunks) + * * ```ts * import { Chunk } from "effect" * @@ -3976,14 +4226,15 @@ export const zip: { * console.log(Chunk.toArray(zipped)) // [[1, "a"], [2, "b"]] * ``` * - * @since 2.0.0 * @category zipping + * @since 2.0.0 */ (that: Chunk): (self: Chunk) => Chunk<[A, B]> /** * Zips this chunk pointwise with the specified chunk. * - * @example + * **Example** (Zipping chunks) + * * ```ts * import { Chunk } from "effect" * @@ -3999,8 +4250,8 @@ export const zip: { * console.log(Chunk.toArray(zipped)) // [[1, "a"], [2, "b"]] * ``` * - * @since 2.0.0 * @category zipping + * @since 2.0.0 */ (self: Chunk, that: Chunk): Chunk<[A, B]> } = dual( @@ -4009,9 +4260,10 @@ export const zip: { ) /** - * Delete the element at the specified index, creating a new `Chunk`. + * Deletes the element at the specified index, creating a new `Chunk`. + * + * **Example** (Removing an element) * - * @example * ```ts * import { Chunk } from "effect" * @@ -4033,9 +4285,10 @@ export const zip: { */ export const remove: { /** - * Delete the element at the specified index, creating a new `Chunk`. + * Deletes the element at the specified index, creating a new `Chunk`. + * + * **Example** (Removing an element) * - * @example * ```ts * import { Chunk } from "effect" * @@ -4057,9 +4310,10 @@ export const remove: { */ (i: number): (self: Chunk) => Chunk /** - * Delete the element at the specified index, creating a new `Chunk`. + * Deletes the element at the specified index, creating a new `Chunk`. + * + * **Example** (Removing an element) * - * @example * ```ts * import { Chunk } from "effect" * @@ -4086,10 +4340,11 @@ export const remove: { ) /** - * Applies a function to the element at the specified index, creating a new `Chunk`, + * Applies a function to the element at the specified index safely, creating a new `Chunk`, * or returns `None` if the index is out of bounds. * - * @example + * **Example** (Modifying an element) + * * ```ts * import { Chunk } from "effect" * @@ -4111,10 +4366,11 @@ export const remove: { */ export const modify: { /** - * Applies a function to the element at the specified index, creating a new `Chunk`, + * Applies a function to the element at the specified index safely, creating a new `Chunk`, * or returns `None` if the index is out of bounds. * - * @example + * **Example** (Modifying an element) + * * ```ts * import { Chunk } from "effect" * @@ -4136,10 +4392,11 @@ export const modify: { */ (i: number, f: (a: A) => B): (self: Chunk) => O.Option> /** - * Applies a function to the element at the specified index, creating a new `Chunk`, + * Applies a function to the element at the specified index safely, creating a new `Chunk`, * or returns `None` if the index is out of bounds. * - * @example + * **Example** (Modifying an element) + * * ```ts * import { Chunk } from "effect" * @@ -4167,10 +4424,11 @@ export const modify: { ) /** - * Change the element at the specified index, creating a new `Chunk`, + * Changes the element at the specified index safely, creating a new `Chunk`, * or returns `None` if the index is out of bounds. * - * @example + * **Example** (Replacing an element) + * * ```ts * import { Chunk } from "effect" * @@ -4192,10 +4450,11 @@ export const modify: { */ export const replace: { /** - * Change the element at the specified index, creating a new `Chunk`, + * Changes the element at the specified index safely, creating a new `Chunk`, * or returns `None` if the index is out of bounds. * - * @example + * **Example** (Replacing an element) + * * ```ts * import { Chunk } from "effect" * @@ -4217,10 +4476,11 @@ export const replace: { */ (i: number, b: B): (self: Chunk) => O.Option> /** - * Change the element at the specified index, creating a new `Chunk`, + * Changes the element at the specified index safely, creating a new `Chunk`, * or returns `None` if the index is out of bounds. * - * @example + * **Example** (Replacing an element) + * * ```ts * import { Chunk } from "effect" * @@ -4244,17 +4504,19 @@ export const replace: { } = dual(3, (self: Chunk, i: number, b: B): O.Option> => modify(self, i, () => b)) /** - * Return a Chunk of length n with element i initialized with f(i). + * Returns a non-empty `Chunk` of length `n` with element `i` initialized by `f(i)`. + * + * **Details** + * + * `n` is normalized to an integer greater than or equal to `1`. * - * **Note**. `n` is normalized to an integer >= 1. + * **Example** (Generating chunks from indices) * - * @example * ```ts * import { Chunk } from "effect" * * const chunk = Chunk.makeBy(5, (i) => i * 2) - * console.log(chunk) - * // { _id: 'Chunk', values: [ 0, 2, 4, 6, 8 ] } + * console.log(Chunk.toArray(chunk)) // [0, 2, 4, 6, 8] * ``` * * @category constructors @@ -4262,17 +4524,19 @@ export const replace: { */ export const makeBy: { /** - * Return a Chunk of length n with element i initialized with f(i). + * Returns a non-empty `Chunk` of length `n` with element `i` initialized by `f(i)`. + * + * **Details** * - * **Note**. `n` is normalized to an integer >= 1. + * `n` is normalized to an integer greater than or equal to `1`. + * + * **Example** (Generating chunks from indices) * - * @example * ```ts * import { Chunk } from "effect" * * const chunk = Chunk.makeBy(5, (i) => i * 2) - * console.log(chunk) - * // { _id: 'Chunk', values: [ 0, 2, 4, 6, 8 ] } + * console.log(Chunk.toArray(chunk)) // [0, 2, 4, 6, 8] * ``` * * @category constructors @@ -4280,17 +4544,19 @@ export const makeBy: { */ (f: (i: number) => A): (n: number) => NonEmptyChunk /** - * Return a Chunk of length n with element i initialized with f(i). + * Returns a non-empty `Chunk` of length `n` with element `i` initialized by `f(i)`. + * + * **Details** + * + * `n` is normalized to an integer greater than or equal to `1`. * - * **Note**. `n` is normalized to an integer >= 1. + * **Example** (Generating chunks from indices) * - * @example * ```ts * import { Chunk } from "effect" * * const chunk = Chunk.makeBy(5, (i) => i * 2) - * console.log(chunk) - * // { _id: 'Chunk', values: [ 0, 2, 4, 6, 8 ] } + * console.log(Chunk.toArray(chunk)) // [0, 2, 4, 6, 8] * ``` * * @category constructors @@ -4300,15 +4566,21 @@ export const makeBy: { } = dual(2, (n, f) => fromIterable(RA.makeBy(n, f))) /** - * Create a non empty `Chunk` containing a range of integers, including both endpoints. + * Creates a non-empty `Chunk` of consecutive integers from `start` through + * `end`, inclusive. + * + * **Details** + * + * If `start` is greater than `end`, returns a single-element chunk containing + * `start`. + * + * **Example** (Creating a range) * - * @example * ```ts * import { Chunk } from "effect" * * const chunk = Chunk.range(1, 5) - * console.log(chunk) - * // { _id: 'Chunk', values: [ 1, 2, 3, 4, 5 ] } + * console.log(Chunk.toArray(chunk)) // [1, 2, 3, 4, 5] * ``` * * @category constructors @@ -4324,7 +4596,8 @@ export const range = (start: number, end: number): NonEmptyChunk => /** * Returns a function that checks if a `Chunk` contains a given value using the default `Equivalence`. * - * @example + * **Example** (Checking membership) + * * ```ts * import { Chunk } from "effect" * @@ -4353,7 +4626,8 @@ export const contains: { /** * Returns a function that checks if a `Chunk` contains a given value using the default `Equivalence`. * - * @example + * **Example** (Checking membership) + * * ```ts * import { Chunk } from "effect" * @@ -4382,7 +4656,8 @@ export const contains: { /** * Returns a function that checks if a `Chunk` contains a given value using the default `Equivalence`. * - * @example + * **Example** (Checking membership) + * * ```ts * import { Chunk } from "effect" * @@ -4409,7 +4684,8 @@ export const contains: { /** * Returns a function that checks if a `Chunk` contains a given value using a provided `isEquivalent` function. * - * @example + * **Example** (Checking membership with custom equivalence) + * * ```ts * import { Chunk } from "effect" * @@ -4445,7 +4721,8 @@ export const containsWith: ( * Returns the first element that satisfies the specified * predicate, or `None` if no such element exists. * - * @example + * **Example** (Finding the first matching element) + * * ```ts * import { Chunk, Option } from "effect" * @@ -4475,7 +4752,8 @@ export const findFirst: { * Returns the first element that satisfies the specified * predicate, or `None` if no such element exists. * - * @example + * **Example** (Finding the first matching element) + * * ```ts * import { Chunk, Option } from "effect" * @@ -4505,7 +4783,8 @@ export const findFirst: { * Returns the first element that satisfies the specified * predicate, or `None` if no such element exists. * - * @example + * **Example** (Finding the first matching element) + * * ```ts * import { Chunk, Option } from "effect" * @@ -4535,7 +4814,8 @@ export const findFirst: { * Returns the first element that satisfies the specified * predicate, or `None` if no such element exists. * - * @example + * **Example** (Finding the first matching element) + * * ```ts * import { Chunk, Option } from "effect" * @@ -4565,7 +4845,8 @@ export const findFirst: { * Returns the first element that satisfies the specified * predicate, or `None` if no such element exists. * - * @example + * **Example** (Finding the first matching element) + * * ```ts * import { Chunk, Option } from "effect" * @@ -4594,9 +4875,10 @@ export const findFirst: { } = RA.findFirst /** - * Return the first index for which a predicate holds. + * Returns the first index for which a predicate holds. + * + * **Example** (Finding the first matching index) * - * @example * ```ts * import { Chunk } from "effect" * @@ -4618,9 +4900,10 @@ export const findFirst: { */ export const findFirstIndex: { /** - * Return the first index for which a predicate holds. + * Returns the first index for which a predicate holds. + * + * **Example** (Finding the first matching index) * - * @example * ```ts * import { Chunk } from "effect" * @@ -4642,9 +4925,10 @@ export const findFirstIndex: { */ (predicate: Predicate): (self: Chunk) => O.Option /** - * Return the first index for which a predicate holds. + * Returns the first index for which a predicate holds. + * + * **Example** (Finding the first matching index) * - * @example * ```ts * import { Chunk } from "effect" * @@ -4671,12 +4955,12 @@ export const findFirstIndex: { ) /** - * Find the last element for which a predicate holds. + * Finds the last element for which a predicate holds. + * + * **Example** (Finding the last matching element) * - * @example * ```ts - * import { Chunk } from "effect" - * import * as Option from "effect/Option" + * import { Chunk, Option } from "effect" * * const chunk = Chunk.make(1, 2, 3, 4, 5) * const result = Chunk.findLast(chunk, (n) => n < 4) @@ -4697,12 +4981,12 @@ export const findFirstIndex: { */ export const findLast: { /** - * Find the last element for which a predicate holds. + * Finds the last element for which a predicate holds. + * + * **Example** (Finding the last matching element) * - * @example * ```ts - * import { Chunk } from "effect" - * import * as Option from "effect/Option" + * import { Chunk, Option } from "effect" * * const chunk = Chunk.make(1, 2, 3, 4, 5) * const result = Chunk.findLast(chunk, (n) => n < 4) @@ -4723,12 +5007,12 @@ export const findLast: { */ (refinement: Refinement, B>): (self: Chunk) => Option /** - * Find the last element for which a predicate holds. + * Finds the last element for which a predicate holds. + * + * **Example** (Finding the last matching element) * - * @example * ```ts - * import { Chunk } from "effect" - * import * as Option from "effect/Option" + * import { Chunk, Option } from "effect" * * const chunk = Chunk.make(1, 2, 3, 4, 5) * const result = Chunk.findLast(chunk, (n) => n < 4) @@ -4749,12 +5033,12 @@ export const findLast: { */ (predicate: Predicate>): (self: Chunk) => Option /** - * Find the last element for which a predicate holds. + * Finds the last element for which a predicate holds. + * + * **Example** (Finding the last matching element) * - * @example * ```ts - * import { Chunk } from "effect" - * import * as Option from "effect/Option" + * import { Chunk, Option } from "effect" * * const chunk = Chunk.make(1, 2, 3, 4, 5) * const result = Chunk.findLast(chunk, (n) => n < 4) @@ -4775,12 +5059,12 @@ export const findLast: { */ (self: Chunk, refinement: Refinement): Option /** - * Find the last element for which a predicate holds. + * Finds the last element for which a predicate holds. + * + * **Example** (Finding the last matching element) * - * @example * ```ts - * import { Chunk } from "effect" - * import * as Option from "effect/Option" + * import { Chunk, Option } from "effect" * * const chunk = Chunk.make(1, 2, 3, 4, 5) * const result = Chunk.findLast(chunk, (n) => n < 4) @@ -4803,9 +5087,10 @@ export const findLast: { } = RA.findLast /** - * Return the last index for which a predicate holds. + * Returns the last index for which a predicate holds. + * + * **Example** (Finding the last matching index) * - * @example * ```ts * import { Chunk } from "effect" * @@ -4827,9 +5112,10 @@ export const findLast: { */ export const findLastIndex: { /** - * Return the last index for which a predicate holds. + * Returns the last index for which a predicate holds. + * + * **Example** (Finding the last matching index) * - * @example * ```ts * import { Chunk } from "effect" * @@ -4851,9 +5137,10 @@ export const findLastIndex: { */ (predicate: Predicate): (self: Chunk) => O.Option /** - * Return the last index for which a predicate holds. + * Returns the last index for which a predicate holds. + * + * **Example** (Finding the last matching index) * - * @example * ```ts * import { Chunk } from "effect" * @@ -4880,9 +5167,10 @@ export const findLastIndex: { ) /** - * Check if a predicate holds true for every `Chunk` element. + * Checks whether a predicate holds true for every `Chunk` element. + * + * **Example** (Checking every element) * - * @example * ```ts * import { Chunk } from "effect" * @@ -4907,9 +5195,10 @@ export const findLastIndex: { */ export const every: { /** - * Check if a predicate holds true for every `Chunk` element. + * Checks whether a predicate holds true for every `Chunk` element. + * + * **Example** (Checking every element) * - * @example * ```ts * import { Chunk } from "effect" * @@ -4934,9 +5223,10 @@ export const every: { */ (refinement: Refinement, B>): (self: Chunk) => self is Chunk /** - * Check if a predicate holds true for every `Chunk` element. + * Checks whether a predicate holds true for every `Chunk` element. + * + * **Example** (Checking every element) * - * @example * ```ts * import { Chunk } from "effect" * @@ -4961,9 +5251,10 @@ export const every: { */ (predicate: Predicate): (self: Chunk) => boolean /** - * Check if a predicate holds true for every `Chunk` element. + * Checks whether a predicate holds true for every `Chunk` element. + * + * **Example** (Checking every element) * - * @example * ```ts * import { Chunk } from "effect" * @@ -4988,9 +5279,10 @@ export const every: { */ (self: Chunk, refinement: Refinement): self is Chunk /** - * Check if a predicate holds true for every `Chunk` element. + * Checks whether a predicate holds true for every `Chunk` element. + * + * **Example** (Checking every element) * - * @example * ```ts * import { Chunk } from "effect" * @@ -5021,9 +5313,10 @@ export const every: { ) /** - * Check if a predicate holds true for some `Chunk` element. + * Checks whether a predicate holds true for some `Chunk` element. + * + * **Example** (Checking for some matching element) * - * @example * ```ts * import { Chunk } from "effect" * @@ -5045,9 +5338,10 @@ export const every: { */ export const some: { /** - * Check if a predicate holds true for some `Chunk` element. + * Checks whether a predicate holds true for some `Chunk` element. + * + * **Example** (Checking for some matching element) * - * @example * ```ts * import { Chunk } from "effect" * @@ -5069,9 +5363,10 @@ export const some: { */ (predicate: Predicate>): (self: Chunk) => self is NonEmptyChunk /** - * Check if a predicate holds true for some `Chunk` element. + * Checks whether a predicate holds true for some `Chunk` element. + * + * **Example** (Checking for some matching element) * - * @example * ```ts * import { Chunk } from "effect" * @@ -5100,7 +5395,8 @@ export const some: { /** * Joins the elements together with "sep" in the middle. * - * @example + * **Example** (Joining chunks into a string) + * * ```ts * import { Chunk } from "effect" * @@ -5128,7 +5424,8 @@ export const join: { /** * Joins the elements together with "sep" in the middle. * - * @example + * **Example** (Joining chunks into a string) + * * ```ts * import { Chunk } from "effect" * @@ -5156,7 +5453,8 @@ export const join: { /** * Joins the elements together with "sep" in the middle. * - * @example + * **Example** (Joining chunks into a string) + * * ```ts * import { Chunk } from "effect" * @@ -5186,7 +5484,8 @@ export const join: { /** * Reduces the elements of a chunk from left to right. * - * @example + * **Example** (Reducing from the left) + * * ```ts * import { Chunk } from "effect" * @@ -5211,7 +5510,8 @@ export const reduce: { /** * Reduces the elements of a chunk from left to right. * - * @example + * **Example** (Reducing from the left) + * * ```ts * import { Chunk } from "effect" * @@ -5236,7 +5536,8 @@ export const reduce: { /** * Reduces the elements of a chunk from left to right. * - * @example + * **Example** (Reducing from the left) + * * ```ts * import { Chunk } from "effect" * @@ -5263,7 +5564,8 @@ export const reduce: { /** * Reduces the elements of a chunk from right to left. * - * @example + * **Example** (Reducing from the right) + * * ```ts * import { Chunk } from "effect" * @@ -5292,7 +5594,8 @@ export const reduceRight: { /** * Reduces the elements of a chunk from right to left. * - * @example + * **Example** (Reducing from the right) + * * ```ts * import { Chunk } from "effect" * @@ -5321,7 +5624,8 @@ export const reduceRight: { /** * Reduces the elements of a chunk from right to left. * - * @example + * **Example** (Reducing from the right) + * * ```ts * import { Chunk } from "effect" * @@ -5353,7 +5657,8 @@ export const 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`. * - * @example + * **Example** (Computing difference with custom equivalence) + * * ```ts * import { Chunk } from "effect" * @@ -5394,7 +5699,8 @@ export const differenceWith = (isEquivalent: (self: A, that: A) => boolean): * 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`. * - * @example + * **Example** (Computing chunk difference) + * * ```ts * import { Chunk } from "effect" * @@ -5423,7 +5729,8 @@ 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`. * - * @example + * **Example** (Computing chunk difference) + * * ```ts * import { Chunk } from "effect" * @@ -5452,7 +5759,8 @@ 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`. * - * @example + * **Example** (Computing chunk difference) + * * ```ts * import { Chunk } from "effect" * diff --git a/.opencode/node_modules/effect/src/Clock.ts b/.opencode/node_modules/effect/src/Clock.ts index 19e854bf637e7bfb524c70b8ec8ff7bc8e5b07cb..b4e4c802f572666aa9ad3ad750e4ae665435061f 100644 --- a/.opencode/node_modules/effect/src/Clock.ts +++ b/.opencode/node_modules/effect/src/Clock.ts @@ -1,58 +1,8 @@ /** - * The `Clock` module provides functionality for time-based operations in Effect applications. - * It offers precise time measurements, scheduling capabilities, and controlled time management - * for testing scenarios. - * - * The Clock service is a core component of the Effect runtime, providing: - * - Current time access in milliseconds and nanoseconds - * - Sleep operations for delaying execution - * - Time-based scheduling primitives - * - Testable time control through `TestClock` - * - * ## Key Features - * - * - **Precise timing**: Access to both millisecond and nanosecond precision - * - **Sleep operations**: Non-blocking sleep with proper interruption handling - * - **Service integration**: Seamless integration with Effect's dependency injection - * - **Testable**: Mock time control for deterministic testing - * - **Resource-safe**: Automatic cleanup of time-based resources - * - * @example - * ```ts - * import { Clock, Effect } from "effect" - * - * // Get current time in milliseconds - * const getCurrentTime = Clock.currentTimeMillis - * - * // Sleep for 1 second - * const sleep1Second = Effect.sleep("1 seconds") - * - * // Measure execution time - * const measureTime = Effect.gen(function*() { - * const start = yield* Clock.currentTimeMillis - * yield* Effect.sleep("100 millis") - * const end = yield* Clock.currentTimeMillis - * return end - start - * }) - * ``` - * - * @example - * ```ts - * import { Clock, Effect } from "effect" - * - * // Using Clock service directly - * const program = Effect.gen(function*() { - * const clock = yield* Clock.Clock - * const currentTime = yield* clock.currentTimeMillis - * console.log(`Current time: ${currentTime}`) - * - * // Sleep for 500ms - * yield* Effect.sleep("500 millis") - * - * const afterSleep = yield* clock.currentTimeMillis - * console.log(`After sleep: ${afterSleep}`) - * }) - * ``` + * Service and helpers for reading time and sleeping inside Effect programs. + * The active `Clock` provides current time in milliseconds or nanoseconds and a + * `sleep` operation for delaying work. Because time is accessed through a + * service, tests can replace the clock with a controlled implementation. * * @since 2.0.0 */ @@ -65,7 +15,13 @@ import * as effect from "./internal/effect.ts" * Represents a time-based clock which provides functionality related to time * and scheduling. * - * @example + * **When to use** + * + * Use to define or provide a clock service for current-time and sleep + * operations. + * + * **Example** (Reading current time) + * * ```ts * import { Clock, Effect } from "effect" * @@ -78,36 +34,64 @@ import * as effect from "./internal/effect.ts" * }) * ``` * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface Clock { /** - * Unsafely returns the current time in milliseconds. + * Returns the current time in milliseconds unsafely. + * + * **When to use** + * + * Use to read millisecond time synchronously when you already have a `Clock` + * service and can accept non-effectful access. */ currentTimeMillisUnsafe(): number /** * Returns the current time in milliseconds. + * + * **When to use** + * + * Use to read millisecond time through this `Clock` service in `Effect`. */ readonly currentTimeMillis: Effect /** - * Unsafely returns the current time in nanoseconds. + * Returns the current time in nanoseconds unsafely. + * + * **When to use** + * + * Use to read nanosecond time synchronously when you already have a `Clock` + * service and can accept non-effectful access. */ currentTimeNanosUnsafe(): bigint /** * Returns the current time in nanoseconds. + * + * **When to use** + * + * Use to read nanosecond time through this `Clock` service in `Effect`. */ readonly currentTimeNanos: Effect /** * Asynchronously sleeps for the specified duration. + * + * **When to use** + * + * Use to delay an `Effect` workflow by a duration through this `Clock` service. */ sleep(duration: Duration.Duration): Effect } /** - * A reference to the current Clock service in the environment. + * Context reference for the active time service in the environment. + * + * **When to use** + * + * Use when you need to access or provide the full time service, including sleep + * operations, rather than a single timestamp accessor. + * + * **Example** (Accessing the Clock service) * - * @example * ```ts * import { Clock, Effect } from "effect" * @@ -117,15 +101,25 @@ export interface Clock { * }) * ``` * + * @see {@link clockWith} for using the current Clock service inside an effect + * @see {@link currentTimeMillis} for reading the current time in milliseconds + * @see {@link currentTimeNanos} for reading the current time in nanoseconds + * * @category references - * @since 4.0.0 + * @since 2.0.0 */ export const Clock: Context.Reference = effect.ClockRef /** * Accesses the current Clock service and uses it to run the provided function. * - * @example + * **When to use** + * + * Use when you need the full Clock service interface to perform multiple time + * operations or call unsafe variants within a single effect. + * + * **Example** (Using the current Clock service) + * * ```ts * import { Clock, Effect } from "effect" * @@ -138,6 +132,9 @@ export const Clock: Context.Reference = effect.ClockRef * ) * ``` * + * @see {@link Clock} for the service reference + * @see {@link currentTimeMillis} for convenience accessor that returns milliseconds + * @see {@link currentTimeNanos} for convenience accessor that returns nanoseconds * @category constructors * @since 2.0.0 */ @@ -146,7 +143,13 @@ export const clockWith: (f: (clock: Clock) => Effect) => Effec /** * Returns an Effect that succeeds with the current time in milliseconds. * - * @example + * **When to use** + * + * Use to read wall-clock time from the active Clock service with millisecond + * precision. + * + * **Example** (Reading milliseconds) + * * ```ts * import { Clock, Effect } from "effect" * @@ -157,6 +160,9 @@ export const clockWith: (f: (clock: Clock) => Effect) => Effec * }) * ``` * + * @see {@link currentTimeNanos} for nanosecond precision + * @see {@link clockWith} for accessing the full Clock service + * * @category constructors * @since 2.0.0 */ @@ -165,7 +171,13 @@ export const currentTimeMillis: Effect = effect.currentTimeMillis /** * Returns an Effect that succeeds with the current time in nanoseconds. * - * @example + * **When to use** + * + * Use to read wall-clock time from the active `Clock` service with nanosecond + * precision. + * + * **Example** (Reading nanoseconds) + * * ```ts * import { Clock, Effect } from "effect" * diff --git a/.opencode/node_modules/effect/src/Combiner.ts b/.opencode/node_modules/effect/src/Combiner.ts index c91c86f454fa3ae37c39de41312d80f060ae6ecc..1ab51881e0e6115f5b39f93402f409da6e41ffd6 100644 --- a/.opencode/node_modules/effect/src/Combiner.ts +++ b/.opencode/node_modules/effect/src/Combiner.ts @@ -1,79 +1,28 @@ /** - * A module for combining two values of the same type into one. + * Defines reusable rules for merging two values of the same type. * - * A `Combiner` wraps a single binary function `(self: A, that: A) => A`. - * It describes *how* two values merge but carries no initial/empty value - * (for that, see {@link Reducer} which extends `Combiner` with an - * `initialValue`). - * - * ## Mental model - * - * - **Combiner** – an object with a `combine(self, that)` method that returns - * a value of the same type. - * - **Argument order** – `self` is the "left" / accumulator side, `that` is - * the "right" / incoming side. - * - **No identity element** – unlike a monoid, a `Combiner` does not require - * a neutral element. Use {@link Reducer} when you need one. - * - **Purity** – all combiners produced by this module are pure; they never - * mutate their arguments. - * - **Composability** – combiners can be lifted into `Option`, `Struct`, - * `Tuple`, and other container types via helpers in those modules. - * - * ## Common tasks - * - * - Create a combiner from any binary function → {@link make} - * - Swap argument order → {@link flip} - * - Pick the smaller / larger of two values → {@link min} / {@link max} - * - Always keep the first or last value → {@link first} / {@link last} - * - Ignore both values and return a fixed result → {@link constant} - * - Insert a separator between combined values → {@link intercalate} - * - * ## Gotchas - * - * - `min` and `max` require an `Order`, not a raw comparator. Import from - * e.g. `Number.Order` or `String.Order`. - * - `intercalate` is curried: call it with the separator first, then pass the - * base combiner. - * - A `Reducer` (which adds `initialValue`) is also a valid `Combiner` — you - * can pass a `Reducer` anywhere a `Combiner` is expected. - * - * ## Quickstart - * - * **Example** (combining strings with a separator) - * - * ```ts - * import { Combiner, String } from "effect" - * - * const csv = Combiner.intercalate(",")(String.ReducerConcat) - * - * console.log(csv.combine("a", "b")) - * // Output: "a,b" - * - * console.log(csv.combine(csv.combine("a", "b"), "c")) - * // Output: "a,b,c" - * ``` - * - * ## See also - * - * - {@link make} – the primary constructor - * - {@link Combiner} – the core interface + * A `Combiner` contains one operation, `combine(self, that)`, which returns + * the merged value. It does not define an initial value for reducing a + * collection; use a `Reducer` when you need that. This module includes the + * `Combiner` interface, a constructor for custom combining logic, and common + * combiners for choosing or ordering values. * * @since 4.0.0 */ import type * as Order from "./Order.ts" /** - * Represents a strategy for combining two values of the same type `A`. - * - * A `Combiner` contains a single `combine` method that takes two values and + * Represents a strategy for combining two values of the same type `A`. A + * `Combiner` contains a single `combine` method that takes two values and * returns a merged result. It does not include an identity/empty value; use * `Reducer` when you need one. * - * When to use: - * - You need to describe how two values of the same type merge. - * - You want to pass a reusable combining strategy to library functions like - * `Struct.makeCombiner` or `Option.makeCombinerFailFast`. - * - You are building a `Reducer` and need to define the combining step first. + * **When to use** + * + * Use when you need to describe how two values of the same type + * merge, pass a reusable combining strategy to library functions like + * `Struct.makeCombiner` or `Option.makeCombinerFailFast`, or define the + * combining step for a `Reducer`. * * **Example** (number addition combiner) * @@ -87,13 +36,16 @@ import type * as Order from "./Order.ts" * ``` * * @see {@link make} – create a `Combiner` from a function - * - * @category model + * @category models * @since 4.0.0 */ export interface Combiner { /** * Combines two values into a new value. + * + * **When to use** + * + * Use to merge two values according to this combining strategy. */ readonly combine: (self: A, that: A) => A } @@ -101,14 +53,15 @@ export interface Combiner { /** * Creates a `Combiner` from a binary function. * - * When to use: - * - You have a custom combining operation that is not covered by the built-in - * constructors (`min`, `max`, `first`, `last`, `constant`). + * **When to use** + * + * Use when you have a custom combining operation that is not covered by + * the built-in constructors (`min`, `max`, `first`, `last`, `constant`). + * + * **Details** * - * Behavior: - * - Returns a new `Combiner` whose `combine` method delegates to the provided - * function. - * - Pure – the returned combiner does not mutate its arguments. + * The returned combiner's `combine` method delegates to the provided function. + * Any purity, associativity, or mutation behavior comes from that function. * * **Example** (multiplying numbers) * @@ -122,7 +75,7 @@ export interface Combiner { * ``` * * @see {@link Combiner} – the interface this creates - * + * @category constructors * @since 4.0.0 */ export function make(combine: (self: A, that: A) => A): Combiner { @@ -132,15 +85,15 @@ export function make(combine: (self: A, that: A) => A): Combiner { /** * Reverses the argument order of a combiner's `combine` method. * - * When to use: - * - You need the "right" value to act as the accumulator side. - * - You want to reverse the natural direction of a non-commutative combiner - * (e.g. string concatenation). + * **When to use** + * + * Use when you want the right-hand value to act as the accumulator, or need to + * reverse a non-commutative combiner such as string concatenation. + * + * **Details** * - * Behavior: - * - Returns a new `Combiner` where `combine(self, that)` calls the original - * combiner as `combine(that, self)`. - * - Does not mutate the input combiner. + * Returns a new `Combiner` where `combine(self, that)` calls the original + * combiner as `combine(that, self)`. * * **Example** (reversing string concatenation) * @@ -154,7 +107,7 @@ export function make(combine: (self: A, that: A) => A): Combiner { * ``` * * @see {@link make} - * + * @category combinators * @since 4.0.0 */ export function flip(combiner: Combiner): Combiner { @@ -165,14 +118,15 @@ export function flip(combiner: Combiner): Combiner { * Creates a `Combiner` that returns the smaller of two values according to * the provided `Order`. * - * When to use: - * - You want to accumulate the minimum value across a collection. - * - You are building a `Reducer` that tracks the running minimum. + * **When to use** + * + * Use when you want to accumulate the minimum value across a collection or + * build a `Reducer` that tracks the running minimum. + * + * **Details** * - * Behavior: - * - Compares using the given `Order`. When values are equal, returns `that` - * (the second argument). - * - Pure – does not mutate either argument. + * The combiner compares values using the given `Order`. When values are equal, + * it returns `that` (the second argument). * * **Example** (minimum of two numbers) * @@ -189,7 +143,7 @@ export function flip(combiner: Combiner): Combiner { * ``` * * @see {@link max} - * + * @category constructors * @since 4.0.0 */ export function min(order: Order.Order): Combiner { @@ -200,14 +154,15 @@ export function min(order: Order.Order): Combiner { * Creates a `Combiner` that returns the larger of two values according to * the provided `Order`. * - * When to use: - * - You want to accumulate the maximum value across a collection. - * - You are building a `Reducer` that tracks the running maximum. + * **When to use** + * + * Use when you want to accumulate the maximum value across a collection or + * build a `Reducer` that tracks the running maximum. + * + * **Details** * - * Behavior: - * - Compares using the given `Order`. When values are equal, returns `that` - * (the second argument). - * - Pure – does not mutate either argument. + * The combiner compares values using the given `Order`. When values are equal, + * it returns `that` (the second argument). * * **Example** (maximum of two numbers) * @@ -224,7 +179,7 @@ export function min(order: Order.Order): Combiner { * ``` * * @see {@link min} - * + * @category constructors * @since 4.0.0 */ export function max(order: Order.Order): Combiner { @@ -234,14 +189,13 @@ export function max(order: Order.Order): Combiner { /** * Creates a `Combiner` that always returns the first (left) argument. * - * When to use: - * - You want "first write wins" semantics when merging values. - * - You need a combiner but the combining logic should be a no-op that keeps - * the existing value. + * **When to use** + * + * Use when you want "first write wins" semantics while merging values. * - * Behavior: - * - `combine(self, that)` returns `self`, ignoring `that`. - * - Pure – the second argument is discarded, not mutated. + * **Details** + * + * `combine(self, that)` returns `self` and ignores `that`. * * **Example** (keeping the first value) * @@ -255,7 +209,7 @@ export function max(order: Order.Order): Combiner { * ``` * * @see {@link last} - * + * @category constructors * @since 4.0.0 */ export function first(): Combiner { @@ -265,13 +219,13 @@ export function first(): Combiner { /** * Creates a `Combiner` that always returns the last (right) argument. * - * When to use: - * - You want "last write wins" semantics when merging values. - * - You need a combiner that replaces the accumulator with each new value. + * **When to use** + * + * Use when you want "last write wins" semantics while merging values. * - * Behavior: - * - `combine(self, that)` returns `that`, ignoring `self`. - * - Pure – the first argument is discarded, not mutated. + * **Details** + * + * `combine(self, that)` returns `that` and ignores `self`. * * **Example** (keeping the last value) * @@ -285,7 +239,7 @@ export function first(): Combiner { * ``` * * @see {@link first} - * + * @category constructors * @since 4.0.0 */ export function last(): Combiner { @@ -296,14 +250,14 @@ export function last(): Combiner { * Creates a `Combiner` that ignores both arguments and always returns the * given constant value. * - * When to use: - * - You need a combiner that produces a fixed result regardless of input. - * - You are providing a combiner to a generic API but the combined value is - * predetermined. + * **When to use** + * + * Use when you need a combiner that always returns a fixed value, including + * when a generic API requires a combiner but the result is predetermined. * - * Behavior: - * - `combine(self, that)` returns the constant `a`, ignoring both arguments. - * - Pure – no mutation occurs. + * **Details** + * + * `combine(self, that)` returns the constant `a` and ignores both arguments. * * **Example** (always returning zero) * @@ -318,7 +272,7 @@ export function last(): Combiner { * * @see {@link first} * @see {@link last} - * + * @category constructors * @since 4.0.0 */ export function constant(a: A): Combiner { @@ -329,16 +283,17 @@ export function constant(a: A): Combiner { * Wraps a `Combiner` so that a separator value is inserted between every * pair of combined elements. * - * When to use: - * - You are building delimited strings (CSV, paths, etc.) by repeated - * combination. - * - You need to inject a fixed separator between accumulated values. + * **When to use** + * + * Use when you need to inject a fixed separator between accumulated values, + * such as when building delimited strings, paths, or CSV-like output by + * repeated combination. * - * Behavior: - * - `intercalate(middle)(combiner).combine(self, that)` is equivalent to - * `combiner.combine(self, combiner.combine(middle, that))`. - * - Curried: first provide the separator, then the base combiner. - * - Does not mutate the input combiner; returns a new one. + * **Details** + * + * `intercalate(middle)(combiner).combine(self, that)` is equivalent to + * `combiner.combine(self, combiner.combine(middle, that))`. This function is + * curried: first provide the separator, then the base combiner. * * **Example** (joining strings with a separator) * @@ -352,7 +307,7 @@ export function constant(a: A): Combiner { * ``` * * @see {@link make} - * + * @category combinators * @since 4.0.0 */ export function intercalate(middle: A) { diff --git a/.opencode/node_modules/effect/src/Config.ts b/.opencode/node_modules/effect/src/Config.ts index f54c99691ed3166df86c49b8afa59819890f0c75..85321180241b98b118ca1c73b5d1beb4e9d6c295 100644 --- a/.opencode/node_modules/effect/src/Config.ts +++ b/.opencode/node_modules/effect/src/Config.ts @@ -1,100 +1,37 @@ /** - * Declarative, schema-driven configuration loading. A `Config` describes - * how to read and validate a value of type `T` from a `ConfigProvider`. Configs - * can be composed, transformed, and used directly as Effects. - * - * ## Mental model - * - * - **Config\** – a recipe for extracting a typed value from a - * `ConfigProvider`. Created via convenience constructors or {@link schema}. - * - **ConfigProvider** – the backing data source (env vars, JSON, `.env` - * files). See the `ConfigProvider` module. - * - **ConfigError** – wraps either a `SourceError` (provider I/O failure) or - * a `SchemaError` (validation / decoding failure). - * - **parse** – instance method on every `Config` that takes a provider and - * returns `Effect`. - * - **Yieldable** – every `Config` can be yielded inside `Effect.gen`. It - * automatically resolves the current `ConfigProvider` from the context. - * - * ## Common tasks - * - * - Read a single env var → {@link string}, {@link number}, {@link boolean}, - * {@link int}, {@link port}, {@link url}, {@link date}, {@link duration}, - * {@link logLevel}, {@link redacted} - * - Read a structured config → {@link schema} with a `Schema.Struct` - * - Provide a default → {@link withDefault} - * - Make a config optional → {@link option} - * - Transform a value → {@link map} / {@link mapOrFail} - * - Fall back on error → {@link orElse} - * - Combine multiple configs → {@link all} - * - Build from a `Schema.Codec` → {@link schema} - * - Always succeed or fail → {@link succeed} / {@link fail} - * - * ## Gotchas - * - * - `withDefault` and `option` only apply when the error is caused by - * **missing data**. Validation errors (wrong type, out of range) still - * propagate. - * - When yielded in `Effect.gen`, the config resolves using the current - * `ConfigProvider` service. To use a specific provider, call `.parse(provider)` - * instead. - * - The `name` parameter on convenience constructors (e.g. `Config.string("HOST")`) - * sets the root path segment. Omit it when the config is part of a larger - * schema. - * - * ## Quickstart - * - * **Example** (Reading typed config from environment variables) - * - * ```ts - * import { Config, ConfigProvider, Effect, Schema } from "effect" - * - * const AppConfig = Config.schema( - * Schema.Struct({ - * host: Schema.String, - * port: Schema.Int - * }), - * "app" - * ) - * - * const provider = ConfigProvider.fromEnv({ - * env: { app_host: "localhost", app_port: "8080" } - * }) - * - * // Effect.runSync(AppConfig.parse(provider)) - * // { host: "localhost", port: 8080 } - * ``` - * - * @see {@link schema} – build a Config from any Schema.Codec - * @see {@link ConfigError} – the error type for config failures - * @see {@link make} – low-level Config constructor + * Descriptions of configuration values that can be read from a + * `ConfigProvider`. A `Config` explains which keys to read, how to decode + * and validate them, and how to combine defaults, fallbacks, nested paths, and + * multiple settings. Configs are also Effects, so they can be yielded in + * `Effect.gen` after a provider has been supplied. * * @since 4.0.0 */ import type { Path, SourceError } from "./ConfigProvider.ts" import * as ConfigProvider from "./ConfigProvider.ts" import * as Effect from "./Effect.ts" +import * as Effectable from "./Effectable.ts" import { dual } from "./Function.ts" -import { PipeInspectableProto, YieldableProto } from "./internal/core.ts" import * as LogLevel_ from "./LogLevel.ts" import * as Option from "./Option.ts" -import type { Pipeable } from "./Pipeable.ts" import * as Predicate from "./Predicate.ts" import * as Rec from "./Record.ts" import * as Schema from "./Schema.ts" -import * as AST from "./SchemaAST.ts" -import * as Issue from "./SchemaIssue.ts" -import * as Parser from "./SchemaParser.ts" -import * as Transformation from "./SchemaTransformation.ts" +import * as SchemaAST from "./SchemaAST.ts" +import * as SchemaGetter from "./SchemaGetter.ts" +import * as SchemaIssue from "./SchemaIssue.ts" +import * as SchemaParser from "./SchemaParser.ts" +import * as SchemaTransformation from "./SchemaTransformation.ts" const TypeId = "~effect/Config" /** * Returns `true` if `u` is a `Config` instance. * - * When to use: - * - Runtime type-checking before calling `.parse()` on an unknown value. - * - Distinguishing a `Config` from a plain value inside {@link unwrap}. + * **When to use** + * + * Use when you need to distinguish a `Config` from an unknown value before + * calling `.parse` or {@link unwrap}. * * **Example** (Type guard) * @@ -105,29 +42,30 @@ const TypeId = "~effect/Config" * console.log(Config.isConfig("not a config")) // false * ``` * - * @since 4.0.0 - * @category Guards + * @category guards + * @since 2.0.0 */ export const isConfig = (u: unknown): u is Config => Predicate.hasProperty(u, TypeId) /** - * The error type produced when config loading or validation fails. + * Represents the error type produced when config loading or validation fails. + * + * **When to use** + * + * Use when you need to inspect config loading or validation failures. + * + * **Details** * * Wraps either: * - A `SourceError` — the provider could not read data (I/O failure). * - A `SchemaError` — the data was found but did not match the schema * (wrong type, out of range, missing key, etc.). * - * When to use: - * - Match on `error.cause._tag` to distinguish source failures from - * validation failures. - * - Pass to {@link fail} to create a Config that always errors. - * * @see {@link orElse} – recover from a ConfigError * @see {@link withDefault} – provide a fallback for missing-data errors * + * @category errors * @since 4.0.0 - * @category Models */ export class ConfigError { readonly _tag = "ConfigError" @@ -147,6 +85,13 @@ export class ConfigError { /** * A recipe for extracting a typed value `T` from a `ConfigProvider`. * + * **When to use** + * + * Use to describe typed configuration that can be parsed from a provider or + * yielded inside `Effect.gen`. + * + * **Details** + * * Key members: * - `parse(provider)` – runs the config against a specific provider, * returning `Effect`. @@ -157,20 +102,22 @@ export class ConfigError { * @see {@link schema} – the main way to create a Config * @see {@link make} – low-level constructor * - * @since 4.0.0 + * @category models + * @since 2.0.0 */ -export interface Config extends Pipeable, Effect.Yieldable, T, ConfigError> { +export interface Config extends Effect.Effect { readonly [TypeId]: typeof TypeId readonly parse: (provider: ConfigProvider.ConfigProvider) => Effect.Effect } const Proto = { - ...PipeInspectableProto, - ...YieldableProto, + ...Effectable.Prototype>({ + label: "Config", + evaluate(fiber) { + return this.parse(fiber.getRef(ConfigProvider.ConfigProvider)) + } + }), [TypeId]: TypeId, - asEffect(this: Config) { - return Effect.flatMap(ConfigProvider.ConfigProvider.asEffect(), (provider) => this.parse(provider)) - }, toJSON(this: Config) { return { _id: "Config" @@ -181,10 +128,12 @@ const Proto = { /** * Creates a `Config` from a raw parsing function. * - * When to use: - * - Building a custom config that cannot be expressed with {@link schema} or - * the convenience constructors. - * - Composing configs programmatically. + * **When to use** + * + * Use to build a custom config that cannot be expressed with {@link schema} or + * convenience constructors, or compose configs programmatically. + * + * **Details** * * The `parse` callback receives a `ConfigProvider` and must return * `Effect`. @@ -208,7 +157,7 @@ const Proto = { * * @see {@link schema} – higher-level constructor using Schema codecs * - * @category Constructors + * @category constructors * @since 4.0.0 */ export function make( @@ -222,9 +171,12 @@ export function make( /** * Transforms the parsed value of a config with a pure function. * - * When to use: - * - Post-processing a config value (e.g. trimming, uppercasing, wrapping). - * - The transformation cannot fail. Use {@link mapOrFail} if it can. + * **When to use** + * + * Use when you need to transform a parsed config value with a function that + * cannot fail. + * + * **Details** * * Supports both data-last and data-first calling conventions. * @@ -243,16 +195,19 @@ export function make( * * @see {@link mapOrFail} – when the transformation can fail * - * @category Mapping - * @since 4.0.0 + * @category mapping + * @since 2.0.0 */ export const map: { /** * Transforms the parsed value of a config with a pure function. * - * When to use: - * - Post-processing a config value (e.g. trimming, uppercasing, wrapping). - * - The transformation cannot fail. Use {@link mapOrFail} if it can. + * **When to use** + * + * Use when you need to transform a parsed config value with a function that + * cannot fail. + * + * **Details** * * Supports both data-last and data-first calling conventions. * @@ -271,16 +226,19 @@ export const map: { * * @see {@link mapOrFail} – when the transformation can fail * - * @category Mapping - * @since 4.0.0 + * @category mapping + * @since 2.0.0 */ (f: (a: A) => B): (self: Config) => Config /** * Transforms the parsed value of a config with a pure function. * - * When to use: - * - Post-processing a config value (e.g. trimming, uppercasing, wrapping). - * - The transformation cannot fail. Use {@link mapOrFail} if it can. + * **When to use** + * + * Use when you need to transform a parsed config value with a function that + * cannot fail. + * + * **Details** * * Supports both data-last and data-first calling conventions. * @@ -299,8 +257,8 @@ export const map: { * * @see {@link mapOrFail} – when the transformation can fail * - * @category Mapping - * @since 4.0.0 + * @category mapping + * @since 2.0.0 */ (self: Config, f: (a: A) => B): Config } = dual(2, (self: Config, f: (a: A) => B): Config => { @@ -310,9 +268,12 @@ export const map: { /** * Transforms the parsed value with a function that may fail. * - * When to use: - * - Validating or converting a config value where the transformation can - * produce a `ConfigError` (e.g. parsing a URL, checking a range). + * **When to use** + * + * Use when you need to transform a parsed config value with a function that can + * produce a `ConfigError` (e.g. parsing a URL, checking a range). + * + * **Details** * * Supports both data-last and data-first calling conventions. * @@ -328,16 +289,19 @@ export const map: { * * @see {@link map} – when the transformation cannot fail * - * @category Mapping - * @since 4.0.0 + * @category mapping + * @since 2.0.0 */ export const mapOrFail: { /** * Transforms the parsed value with a function that may fail. * - * When to use: - * - Validating or converting a config value where the transformation can - * produce a `ConfigError` (e.g. parsing a URL, checking a range). + * **When to use** + * + * Use when you need to transform a parsed config value with a function that can + * produce a `ConfigError` (e.g. parsing a URL, checking a range). + * + * **Details** * * Supports both data-last and data-first calling conventions. * @@ -353,16 +317,19 @@ export const mapOrFail: { * * @see {@link map} – when the transformation cannot fail * - * @category Mapping - * @since 4.0.0 + * @category mapping + * @since 2.0.0 */ (f: (a: A) => Effect.Effect): (self: Config) => Config /** * Transforms the parsed value with a function that may fail. * - * When to use: - * - Validating or converting a config value where the transformation can - * produce a `ConfigError` (e.g. parsing a URL, checking a range). + * **When to use** + * + * Use when you need to transform a parsed config value with a function that can + * produce a `ConfigError` (e.g. parsing a URL, checking a range). + * + * **Details** * * Supports both data-last and data-first calling conventions. * @@ -378,8 +345,8 @@ export const mapOrFail: { * * @see {@link map} – when the transformation cannot fail * - * @category Mapping - * @since 4.0.0 + * @category mapping + * @since 2.0.0 */ (self: Config, f: (a: A) => Effect.Effect): Config } = dual(2, (self: Config, f: (a: A) => Effect.Effect): Config => { @@ -387,11 +354,14 @@ export const mapOrFail: { }) /** - * Falls back to another config when parsing fails with a `ConfigError`. + * Provides a fallback config when parsing fails with a `ConfigError`. + * + * **When to use** * - * When to use: - * - Trying an alternative config source when the primary one errors. - * - Providing environment-specific overrides. + * Use when you need to try an alternative config source after the primary one + * fails. + * + * **Details** * * Unlike {@link withDefault}, this catches **all** `ConfigError`s (not just * missing data). The fallback function receives the error and returns a new @@ -411,15 +381,19 @@ export const mapOrFail: { * * @see {@link withDefault} – fallback only on missing data * - * @since 4.0.0 + * @category combinators + * @since 2.0.0 */ export const orElse: { /** - * Falls back to another config when parsing fails with a `ConfigError`. + * Provides a fallback config when parsing fails with a `ConfigError`. + * + * **When to use** * - * When to use: - * - Trying an alternative config source when the primary one errors. - * - Providing environment-specific overrides. + * Use when you need to try an alternative config source after the primary one + * fails. + * + * **Details** * * Unlike {@link withDefault}, this catches **all** `ConfigError`s (not just * missing data). The fallback function receives the error and returns a new @@ -439,15 +413,19 @@ export const orElse: { * * @see {@link withDefault} – fallback only on missing data * - * @since 4.0.0 + * @category combinators + * @since 2.0.0 */ (that: (error: ConfigError) => Config): (self: Config) => Config /** - * Falls back to another config when parsing fails with a `ConfigError`. + * Provides a fallback config when parsing fails with a `ConfigError`. + * + * **When to use** * - * When to use: - * - Trying an alternative config source when the primary one errors. - * - Providing environment-specific overrides. + * Use when you need to try an alternative config source after the primary one + * fails. + * + * **Details** * * Unlike {@link withDefault}, this catches **all** `ConfigError`s (not just * missing data). The fallback function receives the error and returns a new @@ -467,7 +445,8 @@ export const orElse: { * * @see {@link withDefault} – fallback only on missing data * - * @since 4.0.0 + * @category combinators + * @since 2.0.0 */ (self: Config, that: (error: ConfigError) => Config): Config } = dual(2, (self: Config, that: (error: ConfigError) => Config): Config => { @@ -477,8 +456,11 @@ export const orElse: { /** * Combines multiple configs into a single config that parses all of them. * - * When to use: - * - Grouping related configs into a tuple or named struct. + * **When to use** + * + * Use when you need to group related configs into a tuple or named struct. + * + * **Details** * * Accepts a tuple (preserves positions), an iterable, or a record of configs. * Returns a config whose parsed value mirrors the input shape. @@ -498,7 +480,8 @@ export const orElse: { * // { host: "localhost", port: 5432 } * ``` * - * @since 4.0.0 + * @category combinators + * @since 2.0.0 */ export function all> | Record>>( arg: Arg @@ -524,7 +507,7 @@ export function all> | Record(defaultValue: A2): (self: Config) => Config /** * Provides a fallback value when the config fails due to missing data. * - * When to use: - * - Making a config key optional with a sensible default. + * **When to use** + * + * Use when you need to make a config key optional with a sensible default. + * + * **Details** + * + * The default is lazily evaluated. Supports both data-last and data-first + * calling conventions. + * + * **Gotchas** * * Only applies when the error is a `SchemaError` caused exclusively by * missing data (missing keys, undefined values). Validation errors (wrong - * type, out of range) still propagate. The default is lazily evaluated. - * - * Supports both data-last and data-first calling conventions. + * type, out of range) still propagate. * * **Example** (Defaulting a missing port) * @@ -634,7 +640,8 @@ export const withDefault: { * @see {@link option} – returns `Option` instead of a default value * @see {@link orElse} – catches all errors, not just missing data * - * @since 4.0.0 + * @category combinators + * @since 2.0.0 */ (self: Config, defaultValue: A2): Config } = dual(2, (self: Config, defaultValue: A2): Config => { @@ -653,9 +660,11 @@ export const withDefault: { * Makes a config optional: returns `Some(value)` on success and `None` when * data is missing. * - * When to use: - * - A config key may or may not be present and you want to handle both - * cases explicitly. + * **When to use** + * + * Use when you need to handle a config key that may or may not be present. + * + * **Gotchas** * * Like {@link withDefault}, only missing-data errors produce `None`. * Validation errors still propagate. @@ -673,13 +682,25 @@ export const withDefault: { * * @see {@link withDefault} – provide a concrete fallback value instead * - * @since 4.0.0 + * @category combinators + * @since 2.0.0 */ export const option = (self: Config): Config> => self.pipe(map(Option.some), withDefault(Option.none())) /** - * @since 3.0.0 + * Extracts the successfully parsed value type from a `Config`. + * + * **When to use** + * + * Use to derive the parsed value type from an existing `Config` value when + * declaring reusable config-driven types. + * + * @see {@link Config} for the config type whose parsed value is extracted + * @see {@link Effect.Success} for extracting the success type from any `Effect` + * + * @category utility types + * @since 2.5.0 */ export type Success = [T] extends [Config] ? A : never @@ -687,16 +708,19 @@ export type Success = [T] extends [Config] ? A : never * Utility type that recursively replaces primitives with `Config` in a nested * structure. * - * `Config.Wrap<{ key: string }>` becomes `{ key: Config } | Config<{ key: string }>` + * **When to use** * - * When to use: - * - Typing the input of {@link unwrap} so callers can pass either a `Config` + * Use when typing the input of {@link unwrap} so callers can pass either a `Config` * or a record of `Config`s. * + * **Details** + * + * `Config.Wrap<{ key: string }>` becomes `{ key: Config } | Config<{ key: string }>` + * * @see {@link unwrap} – construct a `Config` from a `Wrap` * * @category Wrap - * @since 4.0.0 + * @since 2.0.0 */ export type Wrap = [NonNullable] extends [infer T] ? [IsPlainObject] extends [true] ? | { readonly [K in keyof A]: Wrap } @@ -711,10 +735,13 @@ type IsPlainObject = [A] extends [Record] /** * Constructs a `Config` from a value matching `Wrap`. * - * When to use: - * - Accepting config from callers who may pass either a single `Config` or a + * **When to use** + * + * Use when accepting config from callers who may pass either a single `Config` or a * record of individual `Config`s. * + * **Details** + * * If the input is already a `Config`, it is returned as-is. Otherwise, each * key is recursively unwrapped and combined. * @@ -734,7 +761,7 @@ type IsPlainObject = [A] extends [Record] * @see {@link Wrap} – the utility type accepted by this function * * @category Wrap - * @since 4.0.0 + * @since 2.0.0 */ export const unwrap = (wrapped: Wrap): Config => { if (isConfig(wrapped)) return wrapped @@ -784,7 +811,7 @@ const dump: ( }) const recur: ( - ast: AST.AST, + ast: SchemaAST.AST, provider: ConfigProvider.ConfigProvider, path: Path ) => Effect.Effect = Effect.fnUntraced( @@ -803,7 +830,7 @@ const recur: ( const stat = yield* provider.load(path) if (stat && stat._tag === "Record") { for (const is of ast.indexSignatures) { - const matches = Parser._is(is.parameter) + const matches = SchemaParser._is(is.parameter) for (const key of stat.keys) { if (!Object.hasOwn(out, key) && matches(key)) { const value = yield* recur(is.type, provider, [...path, key]) @@ -846,14 +873,18 @@ const recur: ( /** * Creates a `Config` from a `Schema.Codec`. * - * When to use: - * - Reading structured or validated config (structs, arrays, unions, branded - * types, etc.). - * - All convenience constructors (`string`, `number`, …) delegate to this. + * **When to use** + * + * Use when you need to read structured or schema-validated configuration. + * + * **Details** * * The optional `path` sets the root path segment(s) for the config lookup. * Pass a single string for a flat key or an array for nested paths. * + * Convenience constructors such as `string`, `number`, and `boolean` delegate + * to this API. + * * The codec is used to decode the raw `StringTree` produced by the provider * into `T`. Schema validation errors are wrapped in `ConfigError`. * @@ -881,13 +912,13 @@ const recur: ( * @see {@link string} / {@link number} / {@link boolean} – shortcuts for * single-value configs * - * @category Schema + * @category schemas * @since 4.0.0 */ export function schema(codec: Schema.Codec, path?: string | ConfigProvider.Path): Config { const codecStringTree = Schema.toCodecStringTree(codec) - const decodeUnknownEffect = Parser.decodeUnknownEffect(codecStringTree) - const codecStringTreeEncoded = AST.toEncoded(codecStringTree.ast) + const decodeUnknownEffect = SchemaParser.decodeUnknownEffect(codecStringTree) + const codecStringTreeEncoded = SchemaAST.toEncoded(codecStringTree.ast) const defaultPath = typeof path === "string" ? [path] : path ?? [] return make((provider) => { const path = provider.prefix ? [...provider.prefix, ...defaultPath] : defaultPath @@ -895,7 +926,7 @@ export function schema(codec: Schema.Codec, path?: string | ConfigPr Effect.flatMapEager((tree) => decodeUnknownEffect(tree).pipe( Effect.mapErrorEager((issue) => - new Schema.SchemaError(path.length > 0 ? new Issue.Pointer(path, issue) : issue) + new Schema.SchemaError(path.length > 0 ? new SchemaIssue.Pointer(path, issue) : issue) ) ) ), @@ -911,24 +942,27 @@ export const TrueValues = Schema.Literals(["true", "yes", "on", "1", "y"]) export const FalseValues = Schema.Literals(["false", "no", "off", "0", "n"]) /** - * A `Schema.Codec` for boolean values encoded as strings. + * Schema for boolean values encoded as strings. * - * When to use: - * - Pass to {@link schema} for custom paths, or use the {@link boolean} - * convenience constructor. + * **When to use** + * + * Use when you need the reusable boolean schema value for `Config.schema` with + * custom paths. + * + * **Details** * * Accepted string values: `true`, `false`, `yes`, `no`, `on`, `off`, `1`, * `0`, `y`, `n` (case-sensitive). * * @see {@link boolean} – convenience constructor * - * @category Schema + * @category schemas * @since 4.0.0 */ export const Boolean = Schema.Literals([...TrueValues.literals, ...FalseValues.literals]).pipe( Schema.decodeTo( Schema.Boolean, - Transformation.transform({ + SchemaTransformation.transform({ decode: (value) => value === "true" || value === "yes" || value === "on" || value === "1" || value === "y", encode: (value) => value ? "true" : "false" }) @@ -936,44 +970,51 @@ export const Boolean = Schema.Literals([...TrueValues.literals, ...FalseValues.l ) /** - * A `Schema.Codec` for port numbers (integers in 1–65535). + * Schema for port numbers (integers in 1–65535). + * + * **When to use** * - * When to use: - * - Pass to {@link schema} for custom paths, or use the {@link port} - * convenience constructor. + * Use when you need the reusable port schema value for `Config.schema` with + * custom paths. * * @see {@link port} – convenience constructor * - * @category Schema + * @category schemas * @since 4.0.0 */ export const Port = Schema.Int.check(Schema.isBetween({ minimum: 1, maximum: 65535 })) /** - * A `Schema.Codec` for `LogLevel` string literals. + * Schema for `LogLevel` string literals. * - * When to use: - * - Pass to {@link schema} for custom paths, or use the {@link logLevel} - * convenience constructor. + * **When to use** + * + * Use when you need the reusable log-level schema value for `Config.schema` + * with custom paths. + * + * **Details** * * Accepted values: `"All"`, `"Fatal"`, `"Error"`, `"Warn"`, `"Info"`, * `"Debug"`, `"Trace"`, `"None"`. * * @see {@link logLevel} – convenience constructor * - * @category Schema + * @category schemas * @since 4.0.0 */ export const LogLevel = Schema.Literals(LogLevel_.values) /** - * A `Schema.Codec` for key-value record types that can also be parsed from + * Schema for key-value record types that can also be parsed from * a flat comma-separated string. * - * When to use: - * - Reading key-value maps from a single env var (e.g. OpenTelemetry + * **When to use** + * + * Use when reading key-value maps from a single env var (e.g. OpenTelemetry * resource attributes). * + * **Details** + * * Accepts either a JSON-like record from the provider or a flat string like * `"key1=val1,key2=val2"`. The `separator` (default `","`) and * `keyValueSeparator` (default `"="`) can be customized. @@ -1001,7 +1042,7 @@ export const LogLevel = Schema.Literals(LogLevel_.values) * // } * ``` * - * @category Schemas + * @category schemas * @since 4.0.0 */ export const Record = (key: K, value: V, options?: { @@ -1012,7 +1053,7 @@ export const Record = (key: K const recordString = Schema.String.pipe( Schema.decodeTo( Schema.Record(Schema.String, Schema.String), - Transformation.splitKeyValue(options) + SchemaTransformation.splitKeyValue(options) ), Schema.decodeTo(record) ) @@ -1020,6 +1061,49 @@ export const Record = (key: K return Schema.Union([record, recordString]) } +/** + * @category schemas + * @since 4.0.0 + */ +const ArrayConfig = (value: V, options?: { + readonly separator?: string | undefined +}) => { + const array = Schema.Array(value) + const separator = options?.separator ?? "," + const arrayString = Schema.String.pipe( + Schema.decodeTo( + Schema.Array(Schema.String), + { + decode: SchemaGetter.split(options), + encode: SchemaGetter.transform((input: ReadonlyArray) => input.join(separator)) + } + ), + Schema.decodeTo(array) + ) + + return Schema.Union([arrayString, array]) +} + +export { + /** + * Schema for array types that can also be parsed from a flat separated string. + * + * **When to use** + * + * Use when reading array values from a single env var, such as comma-separated + * exporter names. + * + * **Details** + * + * Accepts either a JSON-like array from the provider or a flat string like + * `"a,b,c"`. The `separator` defaults to `","` and can be customized. + * + * @category schemas + * @since 4.0.0 + */ + ArrayConfig as Array +} + // ----------------------------------------------------------------------------- // constructors // ----------------------------------------------------------------------------- @@ -1027,12 +1111,13 @@ export const Record = (key: K /** * Creates a config that always fails with the given error. * - * When to use: - * - Inside {@link orElse} to re-raise a specific error. - * - Testing error handling paths. + * **When to use** * - * @category Constructors - * @since 4.0.0 + * Use when you need to re-raise a specific config error, such as inside + * {@link orElse}. + * + * @category constructors + * @since 2.0.0 */ export function fail(err: SourceError | Schema.SchemaError) { return make(() => Effect.fail(new ConfigError(err))) @@ -1042,9 +1127,10 @@ export function fail(err: SourceError | Schema.SchemaError) { * Creates a config that always succeeds with the given value, ignoring the * provider entirely. * - * When to use: - * - Providing a hardcoded constant inside {@link orElse}. - * - Testing. + * **When to use** + * + * Use when you need a hardcoded config value, such as inside {@link orElse} or + * tests. * * **Example** (Constant fallback) * @@ -1056,8 +1142,8 @@ export function fail(err: SourceError | Schema.SchemaError) { * ) * ``` * - * @category Constructors - * @since 4.0.0 + * @category constructors + * @since 2.0.0 */ export function succeed(value: T) { return make(() => Effect.succeed(value)) @@ -1066,10 +1152,13 @@ export function succeed(value: T) { /** * Creates a config for a single string value. * - * Shortcut for `Config.schema(Schema.String, name)`. + * **When to use** * - * When to use: - * - Reading a single string env var or config key. + * Use when reading a single string env var or config key. + * + * **Details** + * + * Shortcut for `Config.schema(Schema.String, name)`. * * **Example** (Reading a string config) * @@ -1085,8 +1174,8 @@ export function succeed(value: T) { * @see {@link nonEmptyString} – rejects empty strings * @see {@link schema} – for more complex types * - * @category Constructors - * @since 4.0.0 + * @category constructors + * @since 2.0.0 */ export function string(name?: string) { return schema(Schema.String, name) @@ -1096,12 +1185,18 @@ export function string(name?: string) { * Creates a config for a non-empty string value. Fails if the value is an * empty string. * + * **When to use** + * + * Use to read a string config value that must contain at least one character. + * + * **Details** + * * Shortcut for `Config.schema(Schema.NonEmptyString, name)`. * - * @see {@link string} – allows empty strings + * @see {@link string} for allowing empty strings * - * @category Constructors - * @since 4.0.0 + * @category constructors + * @since 3.7.0 */ export function nonEmptyString(name?: string) { return schema(Schema.NonEmptyString, name) @@ -1110,13 +1205,20 @@ export function nonEmptyString(name?: string) { /** * Creates a config for a numeric value (including `NaN`, `Infinity`). * + * **When to use** + * + * Use when you need config input to accept JavaScript's full number domain, + * including NaN and infinities, rather than reject non-finite values. + * + * **Details** + * * Shortcut for `Config.schema(Schema.Number, name)`. * - * @see {@link finite} – rejects `NaN` and `Infinity` - * @see {@link int} – only integers + * @see {@link finite} for rejecting `NaN` and `Infinity` + * @see {@link int} for accepting only integers * - * @category Constructors - * @since 4.0.0 + * @category constructors + * @since 2.0.0 */ export function number(name?: string) { return schema(Schema.Number, name) @@ -1125,12 +1227,18 @@ export function number(name?: string) { /** * Creates a config for a finite number (rejects `NaN` and `Infinity`). * + * **When to use** + * + * Use to read a numeric config value that must be finite. + * + * **Details** + * * Shortcut for `Config.schema(Schema.Finite, name)`. * - * @see {@link number} – allows `NaN` and `Infinity` - * @see {@link int} – only integers + * @see {@link number} for accepting `NaN` and `Infinity` + * @see {@link int} for accepting only integers * - * @category Constructors + * @category constructors * @since 4.0.0 */ export function finite(name?: string) { @@ -1140,12 +1248,18 @@ export function finite(name?: string) { /** * Creates a config for an integer value. Rejects floats. * + * **When to use** + * + * Use to read a numeric config value that must be an integer. + * + * **Details** + * * Shortcut for `Config.schema(Schema.Int, name)`. * - * @see {@link number} – allows any number - * @see {@link port} – integers in 1–65535 + * @see {@link number} for accepting any number + * @see {@link port} for accepting only integers in `1` through `65535` * - * @category Constructors + * @category constructors * @since 4.0.0 */ export function int(name?: string) { @@ -1155,6 +1269,12 @@ export function int(name?: string) { /** * Creates a config that only accepts a specific literal value. * + * **When to use** + * + * Use to restrict a config to a single, specific literal value. + * + * **Details** + * * Shortcut for `Config.schema(Schema.Literal(literal), name)`. * * **Example** (Restricting to a literal) @@ -1165,16 +1285,23 @@ export function int(name?: string) { * const env = Config.literal("production", "ENV") * ``` * - * @category Constructors - * @since 4.0.0 + * @see {@link literals} – accepts multiple literal values + * @category constructors + * @since 2.0.0 */ -export function literal(literal: L, name?: string) { +export function literal(literal: L, name?: string) { return schema(Schema.Literal(literal), name) } /** * Creates a config that only accepts one of the specified literal values. * + * **When to use** + * + * Use to restrict a config to a fixed set of allowed literal values. + * + * **Details** + * * Shortcut for `Config.schema(Schema.Literals(literals), name)`. * * **Example** (Restricting to a set of literals) @@ -1185,10 +1312,12 @@ export function literal(literal: L, name?: string) { * const env = Config.literals(["development", "production"], "ENV") * ``` * - * @category Constructors + * @see {@link literal} for accepting one specific literal value + * + * @category constructors * @since 4.0.0 */ -export function literals>(literals: L, name?: string) { +export function literals>(literals: L, name?: string) { return schema(Schema.Literals(literals), name) } @@ -1196,6 +1325,12 @@ export function literals>(litera * Creates a config for a boolean value parsed from common string * representations. * + * **When to use** + * + * Use to read boolean flags from string-like config sources. + * + * **Details** + * * Shortcut for `Config.schema(Config.Boolean, name)`. * * Accepted values: `true`, `false`, `yes`, `no`, `on`, `off`, `1`, `0`, @@ -1223,8 +1358,10 @@ export function literals>(litera * // Output: true * ``` * - * @category Constructors - * @since 4.0.0 + * @see {@link Boolean} for the underlying boolean codec + * + * @category constructors + * @since 2.0.0 */ export function boolean(name?: string) { return schema(Boolean, name) @@ -1234,6 +1371,12 @@ export function boolean(name?: string) { * Creates a config for a `Duration` value parsed from a human-readable * string. * + * **When to use** + * + * Use to read time duration settings such as timeouts, intervals, or TTLs. + * + * **Details** + * * Shortcut for `Config.schema(Schema.DurationFromString, name)`. * * Accepts any string that `Duration.fromInput` can parse (e.g. @@ -1261,8 +1404,10 @@ export function boolean(name?: string) { * // Output: Duration { _tag: "millis", value: 10000 } * ``` * - * @category Constructors - * @since 4.0.0 + * @see {@link schema} for decoding configuration values with a custom codec + * + * @category constructors + * @since 2.5.0 */ export function duration(name?: string) { return schema(Schema.DurationFromString, name) @@ -1271,6 +1416,12 @@ export function duration(name?: string) { /** * Creates a config for a port number (integer in 1–65535). * + * **When to use** + * + * Use to read network port settings that must be valid port numbers. + * + * **Details** + * * Shortcut for `Config.schema(Config.Port, name)`. * * **Example** (Reading a port) @@ -1295,8 +1446,11 @@ export function duration(name?: string) { * // Output: 8080 * ``` * - * @category Constructors - * @since 4.0.0 + * @see {@link int} for integer config values outside the port range + * @see {@link Port} for the underlying port codec + * + * @category constructors + * @since 3.16.0 */ export function port(name?: string) { return schema(Port, name) @@ -1305,6 +1459,12 @@ export function port(name?: string) { /** * Creates a config for a log level string. * + * **When to use** + * + * Use to read Effect log-level settings from configuration. + * + * **Details** + * * Shortcut for `Config.schema(Config.LogLevel, name)`. * * Accepted values: `"All"`, `"Fatal"`, `"Error"`, `"Warn"`, `"Info"`, @@ -1332,8 +1492,10 @@ export function port(name?: string) { * // Output: "Info" * ``` * - * @category Constructors - * @since 4.0.0 + * @see {@link LogLevel} for the underlying log-level codec + * + * @category constructors + * @since 2.0.0 */ export function logLevel(name?: string) { return schema(LogLevel, name) @@ -1343,6 +1505,13 @@ export function logLevel(name?: string) { * Creates a config for a redacted string value. The parsed result is wrapped * in a `Redacted` container that hides the value from logs and `toString`. * + * **When to use** + * + * Use to read secret string settings that should not be exposed in logs or + * string output. + * + * **Details** + * * Shortcut for `Config.schema(Schema.Redacted(Schema.String), name)`. * * **Example** (Reading a secret) @@ -1367,8 +1536,10 @@ export function logLevel(name?: string) { * // Output: * ``` * - * @category Constructors - * @since 4.0.0 + * @see {@link string} for non-secret string settings + * + * @category constructors + * @since 2.0.0 */ export function redacted(name?: string) { return schema(Schema.Redacted(Schema.String), name) @@ -1377,6 +1548,16 @@ export function redacted(name?: string) { /** * Creates a config for a `URL` value parsed from a string. * + * **When to use** + * + * Use to read configuration values that must be valid URL strings. + * + * **Details** + * + * This is a shortcut for `Config.schema(Schema.URL, name)`. + * + * **Gotchas** + * * Fails if the string cannot be parsed by the `URL` constructor. * * **Example** (Reading a URL) @@ -1415,8 +1596,10 @@ export function redacted(name?: string) { * // } * ``` * - * @category Constructors - * @since 4.0.0 + * @see {@link schema} for decoding configuration values with a custom codec + * + * @category constructors + * @since 3.11.0 */ export function url(name?: string) { return schema(Schema.URL, name) @@ -1425,10 +1608,18 @@ export function url(name?: string) { /** * Creates a config for a `Date` value parsed from a string. * - * Fails with a `SchemaError` if the string produces an invalid `Date`. + * **When to use** + * + * Use to read date settings that must parse to valid `Date` values. + * + * **Details** * * Shortcut for `Config.schema(Schema.DateValid, name)`. * + * **Gotchas** + * + * Fails with a `SchemaError` if the string produces an invalid `Date`. + * * **Example** (Reading a date) * * ```ts @@ -1441,8 +1632,8 @@ export function url(name?: string) { * // Date("2024-01-15T00:00:00.000Z") * ``` * - * @category Constructors - * @since 4.0.0 + * @category constructors + * @since 2.0.0 */ export function date(name?: string) { return schema(Schema.DateValid, name) @@ -1451,10 +1642,11 @@ export function date(name?: string) { /** * Scopes a config under a named prefix. * - * When to use: - * - Grouping related config keys under a common namespace (e.g. - * `"database"`, `"redis"`). - * - Building reusable config fragments that callers nest at different paths. + * **When to use** + * + * Use when you need to group related config keys under a common namespace. + * + * **Details** * * The prefix is prepended to every key the inner config reads. With * `fromUnknown` this means an extra object level; with `fromEnv` it means @@ -1496,17 +1688,18 @@ export function date(name?: string) { * @see {@link all} – combine multiple configs into a struct * @see {@link schema} – read structured config from a schema * - * @category Combinators - * @since 4.0.0 + * @category combinators + * @since 2.0.0 */ export const nested: { /** * Scopes a config under a named prefix. * - * When to use: - * - Grouping related config keys under a common namespace (e.g. - * `"database"`, `"redis"`). - * - Building reusable config fragments that callers nest at different paths. + * **When to use** + * + * Use when you need to group related config keys under a common namespace. + * + * **Details** * * The prefix is prepended to every key the inner config reads. With * `fromUnknown` this means an extra object level; with `fromEnv` it means @@ -1548,17 +1741,18 @@ export const nested: { * @see {@link all} – combine multiple configs into a struct * @see {@link schema} – read structured config from a schema * - * @category Combinators - * @since 4.0.0 + * @category combinators + * @since 2.0.0 */ (name: string): (self: Config) => Config /** * Scopes a config under a named prefix. * - * When to use: - * - Grouping related config keys under a common namespace (e.g. - * `"database"`, `"redis"`). - * - Building reusable config fragments that callers nest at different paths. + * **When to use** + * + * Use when you need to group related config keys under a common namespace. + * + * **Details** * * The prefix is prepended to every key the inner config reads. With * `fromUnknown` this means an extra object level; with `fromEnv` it means @@ -1600,8 +1794,8 @@ export const nested: { * @see {@link all} – combine multiple configs into a struct * @see {@link schema} – read structured config from a schema * - * @category Combinators - * @since 4.0.0 + * @category combinators + * @since 2.0.0 */ (self: Config, name: string): Config } = dual( diff --git a/.opencode/node_modules/effect/src/ConfigProvider.ts b/.opencode/node_modules/effect/src/ConfigProvider.ts index 7a231ca64d706807d6e9f2203c985eb40157d72e..3198193bf6c3e642416403f5aba05ff244b8dcee 100644 --- a/.opencode/node_modules/effect/src/ConfigProvider.ts +++ b/.opencode/node_modules/effect/src/ConfigProvider.ts @@ -1,79 +1,10 @@ /** - * Provides the data source layer for the `Config` module. A `ConfigProvider` - * knows how to load raw configuration nodes from a backing store (environment - * variables, JSON objects, `.env` files, file trees) and expose them through a - * uniform `Node` interface that `Config` schemas consume. - * - * ## Mental model - * - * - **Node** – a discriminated union (`Value | Record | Array`) that describes - * what lives at a given path in the configuration tree. - * - **Path** – an array of string or numeric segments used to address a node - * (e.g. `["database", "host"]`). - * - **ConfigProvider** – an object with a `load(path)` method that resolves a - * path to a `Node | undefined`. Providers can be composed and transformed. - * - **Context.Reference** – `ConfigProvider` is registered as a reference - * service that defaults to `fromEnv()`, so it works without explicit - * provision. - * - **SourceError** – the typed error returned when a backing store is - * unreadable (I/O failure, permission error, etc.). - * - * ## Common tasks - * - * - Read from environment variables → {@link fromEnv} - * - Read from a JSON / plain object → {@link fromUnknown} - * - Parse a `.env` string → {@link fromDotEnvContents} - * - Load a `.env` file → {@link fromDotEnv} - * - Read from a directory tree → {@link fromDir} - * - Build a custom provider → {@link make} - * - Fall back to another provider → {@link orElse} - * - Scope a provider under a prefix → {@link nested} - * - Convert path segments to `CONSTANT_CASE` → {@link constantCase} - * - Transform path segments arbitrarily → {@link mapInput} - * - Install a provider as a Layer → {@link layer} / {@link layerAdd} - * - * ## Gotchas - * - * - `fromEnv` joins path segments with `_` for lookup **and** splits env var - * names on `_` to discover child keys. `DATABASE_HOST=x` is therefore - * accessible at both `["DATABASE_HOST"]` and `["DATABASE", "HOST"]`. - * - Because of `_` splitting, querying a parent path like `["DATABASE"]` - * returns a `Record` node with child key `"HOST"`, even if no env var - * named `DATABASE` exists. - * - When using `fromEnv` with schemas that use camelCase keys, pipe the - * provider through {@link constantCase} so `databaseHost` resolves to - * `DATABASE_HOST`. - * - `orElse` only falls back when the primary provider returns `undefined` - * (path not found). It does **not** catch `SourceError`. - * - `nested` prepends segments to the path *after* `mapInput` has run, so - * the order of composition matters. - * - * ## Quickstart - * - * **Example** (Reading config from environment variables) - * - * ```ts - * import { Config, ConfigProvider, Effect } from "effect" - * - * const provider = ConfigProvider.fromEnv({ - * env: { APP_PORT: "3000", APP_HOST: "localhost" } - * }) - * - * const port = Config.number("port") - * - * const program = port.parse( - * provider.pipe( - * ConfigProvider.nested("app"), - * ConfigProvider.constantCase - * ) - * ) - * - * // Effect.runSync(program) // 3000 - * ``` - * - * @see {@link make} – build a provider from a lookup function - * @see {@link fromEnv} – the default provider backed by `process.env` - * @see {@link fromUnknown} – provider backed by a plain JS object + * Data sources used by `Config` to load raw configuration values. A + * `ConfigProvider` reads paths from places such as environment variables, + * JavaScript objects, `.env` contents, or directories, and returns a uniform + * `Node` shape that config schemas can decode. The module also includes helpers + * for composing providers, changing paths, and installing providers through + * layers. * * @since 4.0.0 */ @@ -97,22 +28,24 @@ import * as Str from "./String.ts" * A discriminated union describing the shape of a configuration value at a * given path. * - * - `Value` – a terminal string leaf. - * - `Record` – an object-like container whose immediate child keys are known. - * May carry an optional co-located `value`. - * - `Array` – an indexed container with a known `length`. May carry an - * optional co-located `value`. + * **When to use** + * + * Use when implementing a custom `ConfigProvider` by returning raw + * nodes from the `get` callback passed to {@link make}, or when inspecting raw + * provider output before schema parsing. + * + * **Details** * - * When to use: - * - Implement a custom `ConfigProvider` by returning `Node` values from the - * `get` callback passed to {@link make}. - * - Inspect raw provider output before schema parsing. + * `Value` is a terminal string leaf. `Record` is an object-like container + * whose immediate child keys are known and may carry an optional co-located + * `value`. `Array` is an indexed container with a known `length` and may also + * carry an optional co-located `value`. * * @see {@link makeValue} – construct a `Value` node * @see {@link makeRecord} – construct a `Record` node * @see {@link makeArray} – construct an `Array` node * - * @category Models + * @category models * @since 4.0.0 */ export type Node = @@ -137,10 +70,14 @@ export type Node = /** * Creates a `Value` node representing a terminal string leaf. * - * When to use: - * - Building nodes inside a custom `ConfigProvider`'s `get` callback. + * **When to use** * - * Does not mutate input. Returns a new plain object. + * Use when building nodes inside a custom `ConfigProvider`'s `get` + * callback. + * + * **Details** + * + * The function returns a new plain object. * * **Example** (Creating a value node) * @@ -154,7 +91,7 @@ export type Node = * @see {@link makeRecord} – for object-like containers * @see {@link makeArray} – for array-like containers * - * @category Constructors + * @category constructors * @since 4.0.0 */ export function makeValue(value: string): Node { @@ -165,11 +102,16 @@ export function makeValue(value: string): Node { * Creates a `Record` node representing an object-like container with known * child keys. * - * When to use: - * - Describing a directory or JSON object inside a custom provider. + * **When to use** + * + * Use when you need to describe a directory or JSON object inside a custom + * provider. + * + * **Details** * * The optional `value` allows a node to be both a container and a leaf at the - * same time (e.g. an env var `A=x` that also has children `A_FOO`, `A_BAR`). + * same time (for example, an env var `A=x` that also has children `A_FOO` and + * `A_BAR`). * * **Example** (Creating a record node) * @@ -183,7 +125,7 @@ export function makeValue(value: string): Node { * @see {@link makeValue} – for terminal leaves * @see {@link makeArray} – for array-like containers * - * @category Constructors + * @category constructors * @since 4.0.0 */ export function makeRecord(keys: ReadonlySet, value?: string): Node { @@ -194,9 +136,12 @@ export function makeRecord(keys: ReadonlySet, value?: string): Node { * Creates an `Array` node representing an indexed container with a known * length. * - * When to use: - * - Describing a JSON array or a set of numerically-indexed env vars inside a - * custom provider. + * **When to use** + * + * Use when you need to describe a JSON array or numerically indexed env vars + * inside a custom provider. + * + * **Details** * * The optional `value` allows a node to be both a container and a leaf at the * same time. @@ -213,7 +158,7 @@ export function makeRecord(keys: ReadonlySet, value?: string): Node { * @see {@link makeValue} – for terminal leaves * @see {@link makeRecord} – for object-like containers * - * @category Constructors + * @category constructors * @since 4.0.0 */ export function makeArray(length: number, value?: string): Node { @@ -223,13 +168,15 @@ export function makeArray(length: number, value?: string): Node { /** * Typed error indicating that a configuration source could not be read. * - * When to use: - * - Return from a custom provider's `get` callback when the underlying store - * is unreachable or produces an I/O error. - * - Match on in error channels when consuming provider output directly. + * **When to use** * - * Not used for "key not found" — that case is represented by returning - * `undefined` from `load` / `get`. + * Use when you need to report that a custom provider's underlying store is + * unreachable or produced an I/O error while reading configuration data. + * + * **Gotchas** + * + * Do not use `SourceError` for "key not found". That case is represented by + * returning `undefined` from `load` or `get`. * * **Example** (Failing with a SourceError) * @@ -246,7 +193,7 @@ export function makeArray(length: number, value?: string): Node { * @see {@link ConfigProvider} – the interface whose `load`/`get` may fail * with this error * - * @category Models + * @category models * @since 4.0.0 */ export class SourceError extends Data.TaggedError("SourceError")<{ @@ -256,9 +203,13 @@ export class SourceError extends Data.TaggedError("SourceError")<{ /** * An ordered sequence of string or numeric segments that addresses a node in - * the configuration tree. + * the configuration tree. String segments name object keys; numeric segments + * index into arrays. + * + * **When to use** * - * String segments name object keys; numeric segments index into arrays. + * Use to address raw configuration nodes when implementing or transforming a + * `ConfigProvider`. * * **Example** (A typical config path) * @@ -268,7 +219,7 @@ export class SourceError extends Data.TaggedError("SourceError")<{ * const path: ConfigProvider.Path = ["database", "replicas", 0, "host"] * ``` * - * @category Models + * @category models * @since 4.0.0 */ export type Path = ReadonlyArray @@ -276,63 +227,78 @@ export type Path = ReadonlyArray /** * The core interface for loading raw configuration data. * - * When to use: - * - Type-annotate variables that hold a provider. - * - Implement a custom provider via {@link make}. + * **When to use** * - * Key members: - * - `load(path)` – resolves `mapInput` and `prefix` transformations, then - * delegates to `get`. This is what the `Config` module calls. - * - `get(path)` – raw access to the underlying store, without path - * transformations. - * - `mapInput` / `prefix` – optional path transformations set by - * {@link mapInput} and {@link nested}. + * Use to type-annotate variables that hold a provider or to implement a + * custom provider via {@link make}. * - * All methods return `Effect`: - * - `undefined` means "not found" (not an error). - * - `SourceError` means the source itself failed. + * **Details** + * + * `load(path)` resolves `mapInput` and `prefix` transformations, then + * delegates to `get`. This is what the `Config` module calls. `get(path)` is + * raw access to the underlying store without path transformations. + * `mapInput` and `prefix` are optional path transformations set by + * {@link mapInput} and {@link nested}. All methods return + * `Effect`: `undefined` means "not found" and + * `SourceError` means the source itself failed. * * @see {@link make} – construct a provider from a lookup function * @see {@link orElse} – compose providers with fallback * - * @category Models - * @since 4.0.0 + * @category models + * @since 2.0.0 */ export interface ConfigProvider extends Pipeable { /** * Returns the node found at `path`, or `undefined` if it does not exist. * Fails with `SourceError` when the underlying source cannot be read. + * + * **When to use** + * + * Use to resolve a path through this provider's path transformations before + * reading the backing source. */ readonly load: (path: Path) => Effect.Effect /** * Raw access to the underlying source. + * + * **When to use** + * + * Use to read from the backing source without applying this provider's path + * transformations. */ readonly get: (path: Path) => Effect.Effect /** * Function to map the input path. + * + * **When to use** + * + * Use to store the path transformation applied before raw provider lookup. */ readonly mapInput: ((path: Path) => Path) | undefined /** * Prefix to add to the input path. + * + * **When to use** + * + * Use to store the path prefix applied before raw provider lookup. */ readonly prefix: Path | undefined } /** - * The `ConfigProvider` service reference, registered in the context with a - * default value of `fromEnv()`. + * Context reference for the active raw configuration provider, registered in the context with a + * default value of `fromEnv()`. Because it is a `Context.Reference`, it is + * available without explicit provision; `Config` schemas automatically resolve + * it. * - * Because it is a `Context.Reference`, it is available without explicit - * provision — `Config` schemas automatically resolve it. + * **When to use** * - * When to use: - * - Override the provider for an entire program via - * `Effect.provideService(ConfigProvider.ConfigProvider, myProvider)`. - * - Retrieve the current provider inside an Effect with - * `yield* ConfigProvider.ConfigProvider`. + * Use to override the active raw configuration provider for an entire program, + * or retrieve the current provider inside an Effect. * * **Example** (Providing a custom provider) * @@ -352,8 +318,8 @@ export interface ConfigProvider extends Pipeable { * @see {@link layer} – install a provider as a Layer * @see {@link layerAdd} – add a fallback provider as a Layer * - * @category Services - * @since 4.0.0 + * @category services + * @since 2.0.0 */ export const ConfigProvider: Context.Reference = Context.Reference( "effect/ConfigProvider", @@ -372,9 +338,12 @@ const Proto = { /** * Creates a `ConfigProvider` from a raw lookup function. * - * When to use: - * - Implementing a provider backed by a custom store (database, remote API, - * in-memory map, etc.). + * **When to use** + * + * Use when implementing a provider backed by a custom store, such as a + * database, remote API, or in-memory map. + * + * **Details** * * The `get` callback receives a `Path` and must return * `Effect`. Return `undefined` when the path @@ -406,8 +375,8 @@ const Proto = { * @see {@link fromEnv} – pre-built provider for environment variables * @see {@link fromUnknown} – pre-built provider for JSON objects * - * @category Constructors - * @since 4.0.0 + * @category constructors + * @since 2.0.0 */ export function make( get: (path: Path) => Effect.Effect, @@ -430,15 +399,20 @@ export function make( * Returns a provider that falls back to `that` when `self` returns `undefined` * for a path. * - * When to use: - * - Layering multiple config sources (e.g. env vars + defaults file). - * - Providing partial overrides on top of a base config. + * **When to use** + * + * Use to layer multiple config sources, such as env vars plus a defaults file, + * or provide partial overrides on top of a base config. * - * Only triggers the fallback when the path is not found (`undefined`). A - * `SourceError` from `self` is **not** caught — it propagates immediately. + * **Details** * * Supports both data-last and data-first calling conventions. * + * **Gotchas** + * + * The fallback only runs when the path is not found (`undefined`). A + * `SourceError` from `self` is not caught; it propagates immediately. + * * **Example** (Falling back to a default provider) * * ```ts @@ -454,23 +428,28 @@ export function make( * * @see {@link layerAdd} – install a fallback provider via a Layer * - * @category Combinators - * @since 4.0.0 + * @category combinators + * @since 2.0.0 */ export const orElse: { /** * Returns a provider that falls back to `that` when `self` returns `undefined` * for a path. * - * When to use: - * - Layering multiple config sources (e.g. env vars + defaults file). - * - Providing partial overrides on top of a base config. + * **When to use** * - * Only triggers the fallback when the path is not found (`undefined`). A - * `SourceError` from `self` is **not** caught — it propagates immediately. + * Use to layer multiple config sources, such as env vars plus a defaults file, + * or provide partial overrides on top of a base config. + * + * **Details** * * Supports both data-last and data-first calling conventions. * + * **Gotchas** + * + * The fallback only runs when the path is not found (`undefined`). A + * `SourceError` from `self` is not caught; it propagates immediately. + * * **Example** (Falling back to a default provider) * * ```ts @@ -486,23 +465,28 @@ export const orElse: { * * @see {@link layerAdd} – install a fallback provider via a Layer * - * @category Combinators - * @since 4.0.0 + * @category combinators + * @since 2.0.0 */ (that: ConfigProvider): (self: ConfigProvider) => ConfigProvider /** * Returns a provider that falls back to `that` when `self` returns `undefined` * for a path. * - * When to use: - * - Layering multiple config sources (e.g. env vars + defaults file). - * - Providing partial overrides on top of a base config. + * **When to use** + * + * Use to layer multiple config sources, such as env vars plus a defaults file, + * or provide partial overrides on top of a base config. * - * Only triggers the fallback when the path is not found (`undefined`). A - * `SourceError` from `self` is **not** caught — it propagates immediately. + * **Details** * * Supports both data-last and data-first calling conventions. * + * **Gotchas** + * + * The fallback only runs when the path is not found (`undefined`). A + * `SourceError` from `self` is not caught; it propagates immediately. + * * **Example** (Falling back to a default provider) * * ```ts @@ -518,8 +502,8 @@ export const orElse: { * * @see {@link layerAdd} – install a fallback provider via a Layer * - * @category Combinators - * @since 4.0.0 + * @category combinators + * @since 2.0.0 */ (self: ConfigProvider, that: ConfigProvider): ConfigProvider } = dual( @@ -531,16 +515,17 @@ export const orElse: { /** * Transforms the path segments before they reach the underlying store. * - * When to use: - * - Renaming or re-casing path segments (see {@link constantCase} for a - * common specialization). - * - Adding suffixes or other per-segment transformations. + * **When to use** * - * The function `f` receives the full path and must return a new path. If the - * provider already has a `mapInput`, the functions compose (existing first, - * then `f`). + * Use when you need to rename, re-case, or otherwise transform config path + * segments before lookup. * - * Supports both data-last and data-first calling conventions. + * **Details** + * + * The function `f` receives the full path and must return a new path. If the + * provider already has a `mapInput`, the functions compose: the existing + * mapping runs first, then `f`. Supports both data-last and data-first calling + * conventions. * * **Example** (Uppercasing path segments) * @@ -561,23 +546,24 @@ export const orElse: { * @see {@link constantCase} – a preset that converts to `CONSTANT_CASE` * @see {@link nested} – for prepending a prefix instead of transforming * - * @category Combinators + * @category combinators * @since 4.0.0 */ export const mapInput: { /** * Transforms the path segments before they reach the underlying store. * - * When to use: - * - Renaming or re-casing path segments (see {@link constantCase} for a - * common specialization). - * - Adding suffixes or other per-segment transformations. + * **When to use** * - * The function `f` receives the full path and must return a new path. If the - * provider already has a `mapInput`, the functions compose (existing first, - * then `f`). + * Use when you need to rename, re-case, or otherwise transform config path + * segments before lookup. * - * Supports both data-last and data-first calling conventions. + * **Details** + * + * The function `f` receives the full path and must return a new path. If the + * provider already has a `mapInput`, the functions compose: the existing + * mapping runs first, then `f`. Supports both data-last and data-first calling + * conventions. * * **Example** (Uppercasing path segments) * @@ -598,23 +584,24 @@ export const mapInput: { * @see {@link constantCase} – a preset that converts to `CONSTANT_CASE` * @see {@link nested} – for prepending a prefix instead of transforming * - * @category Combinators + * @category combinators * @since 4.0.0 */ (f: (path: Path) => Path): (self: ConfigProvider) => ConfigProvider /** * Transforms the path segments before they reach the underlying store. * - * When to use: - * - Renaming or re-casing path segments (see {@link constantCase} for a - * common specialization). - * - Adding suffixes or other per-segment transformations. + * **When to use** * - * The function `f` receives the full path and must return a new path. If the - * provider already has a `mapInput`, the functions compose (existing first, - * then `f`). + * Use when you need to rename, re-case, or otherwise transform config path + * segments before lookup. * - * Supports both data-last and data-first calling conventions. + * **Details** + * + * The function `f` receives the full path and must return a new path. If the + * provider already has a `mapInput`, the functions compose: the existing + * mapping runs first, then `f`. Supports both data-last and data-first calling + * conventions. * * **Example** (Uppercasing path segments) * @@ -635,7 +622,7 @@ export const mapInput: { * @see {@link constantCase} – a preset that converts to `CONSTANT_CASE` * @see {@link nested} – for prepending a prefix instead of transforming * - * @category Combinators + * @category combinators * @since 4.0.0 */ (self: ConfigProvider, f: (path: Path) => Path): ConfigProvider @@ -649,9 +636,12 @@ export const mapInput: { /** * Converts all string path segments to `CONSTANT_CASE` before lookup. * - * When to use: - * - Bridging camelCase schema keys to `SCREAMING_SNAKE_CASE` environment - * variables (the most common pattern). + * **When to use** + * + * Use to bridge camelCase schema keys to `SCREAMING_SNAKE_CASE` + * environment variables. + * + * **Details** * * Numeric segments are left unchanged. This is a specialization of * {@link mapInput}. @@ -670,8 +660,8 @@ export const mapInput: { * * @see {@link mapInput} – for arbitrary path transformations * - * @since 4.0.0 - * @category Combinators + * @category combinators + * @since 2.0.0 */ export const constantCase: (self: ConfigProvider) => ConfigProvider = mapInput((path) => path.map((seg) => typeof seg === "number" ? seg : Str.constantCase(seg)) @@ -681,15 +671,21 @@ export const constantCase: (self: ConfigProvider) => ConfigProvider = mapInput(( * Scopes a provider so that all lookups are prefixed with the given path * segments. * - * When to use: - * - Namespacing config under a prefix like `"app"` or `"database"`. - * - Reusing the same provider shape for multiple sub-configs. + * **When to use** * - * Accepts a single string or a full `Path` array. The prefix is prepended - * *after* any `mapInput` transformation runs, so ordering matters when - * composing with {@link mapInput} or {@link constantCase}. + * Use to namespace config under a prefix like `"app"` or `"database"`, or + * reuse the same provider shape for multiple sub-configs. * - * Supports both data-last and data-first calling conventions. + * **Details** + * + * Accepts a single string or a full `Path` array. Supports both data-last and + * data-first calling conventions. + * + * **Gotchas** + * + * The prefix is prepended after any `mapInput` transformation runs, so + * ordering matters when composing with {@link mapInput} or + * {@link constantCase}. * * **Example** (Nesting under a prefix) * @@ -706,23 +702,29 @@ export const constantCase: (self: ConfigProvider) => ConfigProvider = mapInput(( * * @see {@link mapInput} – for arbitrary path transformations * - * @category Combinators - * @since 4.0.0 + * @category combinators + * @since 2.0.0 */ export const nested: { /** * Scopes a provider so that all lookups are prefixed with the given path * segments. * - * When to use: - * - Namespacing config under a prefix like `"app"` or `"database"`. - * - Reusing the same provider shape for multiple sub-configs. + * **When to use** * - * Accepts a single string or a full `Path` array. The prefix is prepended - * *after* any `mapInput` transformation runs, so ordering matters when - * composing with {@link mapInput} or {@link constantCase}. + * Use to namespace config under a prefix like `"app"` or `"database"`, or + * reuse the same provider shape for multiple sub-configs. * - * Supports both data-last and data-first calling conventions. + * **Details** + * + * Accepts a single string or a full `Path` array. Supports both data-last and + * data-first calling conventions. + * + * **Gotchas** + * + * The prefix is prepended after any `mapInput` transformation runs, so + * ordering matters when composing with {@link mapInput} or + * {@link constantCase}. * * **Example** (Nesting under a prefix) * @@ -739,23 +741,29 @@ export const nested: { * * @see {@link mapInput} – for arbitrary path transformations * - * @category Combinators - * @since 4.0.0 + * @category combinators + * @since 2.0.0 */ (prefix: string | Path): (self: ConfigProvider) => ConfigProvider /** * Scopes a provider so that all lookups are prefixed with the given path * segments. * - * When to use: - * - Namespacing config under a prefix like `"app"` or `"database"`. - * - Reusing the same provider shape for multiple sub-configs. + * **When to use** * - * Accepts a single string or a full `Path` array. The prefix is prepended - * *after* any `mapInput` transformation runs, so ordering matters when - * composing with {@link mapInput} or {@link constantCase}. + * Use to namespace config under a prefix like `"app"` or `"database"`, or + * reuse the same provider shape for multiple sub-configs. * - * Supports both data-last and data-first calling conventions. + * **Details** + * + * Accepts a single string or a full `Path` array. Supports both data-last and + * data-first calling conventions. + * + * **Gotchas** + * + * The prefix is prepended after any `mapInput` transformation runs, so + * ordering matters when composing with {@link mapInput} or + * {@link constantCase}. * * **Example** (Nesting under a prefix) * @@ -772,8 +780,8 @@ export const nested: { * * @see {@link mapInput} – for arbitrary path transformations * - * @category Combinators - * @since 4.0.0 + * @category combinators + * @since 2.0.0 */ (self: ConfigProvider, prefix: string | Path): ConfigProvider } = dual( @@ -785,11 +793,14 @@ export const nested: { ) /** - * Installs a `ConfigProvider` as the active provider for all downstream - * effects, replacing any previously installed provider. + * Provides a layer that installs a `ConfigProvider` as the active provider for + * all downstream effects, replacing any previously installed provider. + * + * **When to use** * - * When to use: - * - Setting the config source for an entire application or test suite. + * Use to set the config source for an entire application or test suite. + * + * **Details** * * Accepts either a plain `ConfigProvider` or an `Effect` that produces one. * When given an Effect, it is evaluated once when the layer is built. @@ -813,7 +824,7 @@ export const nested: { * * @see {@link layerAdd} – add a provider without replacing the existing one * - * @category Layers + * @category layers * @since 4.0.0 */ export const layer = ( @@ -825,15 +836,17 @@ export const layer = ( * Creates a Layer that composes a new `ConfigProvider` with the currently * active one, rather than replacing it. * - * When to use: - * - Adding defaults that should only apply when the primary provider has no - * value for a path. - * - Overriding specific keys while keeping the rest from the existing provider - * (use `asPrimary: true`). + * **When to use** + * + * Use to add defaults that should only apply when the primary provider has no + * value for a path, or override specific keys while keeping the rest from the + * existing provider by setting `asPrimary: true`. + * + * **Details** * - * By default, the new provider acts as a **fallback** (consulted only when - * the current provider returns `undefined`). Set `asPrimary: true` to make - * the new provider the **primary** source, with the existing one as fallback. + * By default, the new provider acts as a fallback and is consulted only when + * the current provider returns `undefined`. Set `asPrimary: true` to make the + * new provider the primary source, with the existing one as fallback. * * **Example** (Adding default values) * @@ -852,7 +865,7 @@ export const layer = ( * @see {@link layer} – replace the provider entirely * @see {@link orElse} – compose providers without layers * - * @category Layers + * @category layers * @since 4.0.0 */ export const layerAdd = ( @@ -873,14 +886,16 @@ export const layerAdd = ( * Creates a `ConfigProvider` backed by an in-memory JavaScript value * (typically a parsed JSON object). * - * When to use: - * - Unit / integration tests where you want deterministic config without - * touching the environment. - * - Embedding config directly in code or reading a JSON file. + * **When to use** * - * Path traversal follows standard JS rules: string segments index into - * object keys, numeric segments index into arrays. Returns `undefined` - * for any path that cannot be resolved. Never fails with `SourceError`. + * Use when you need deterministic config from an in-memory JavaScript value, + * such as in tests, embedded config, or parsed JSON. + * + * **Details** + * + * Path traversal follows standard JS rules: string segments index into object + * keys, numeric segments index into arrays. Returns `undefined` for any path + * that cannot be resolved. Never fails with `SourceError`. * * Primitive values (`number`, `boolean`, `bigint`) are stringified via * `String(...)`. @@ -957,10 +972,13 @@ function describeUnknown(u: unknown): Node | undefined { /** * Creates a `ConfigProvider` backed by environment variables. * - * When to use: - * - Reading configuration from `process.env` (the default when no provider - * is explicitly set). - * - Passing a custom env record for testing or non-Node runtimes. + * **When to use** + * + * Use to read configuration from `process.env`, which is the default when no + * provider is explicitly set, or pass a custom env record for testing or + * non-Node runtimes. + * + * **Details** * * Path segments are joined with `_` for direct lookup, and env var names are * also split on `_` to build a trie for child key discovery. This means @@ -997,7 +1015,7 @@ function describeUnknown(u: unknown): Node | undefined { * @see {@link constantCase} – bridge camelCase keys to SCREAMING_SNAKE_CASE * * @category ConfigProviders - * @since 4.0.0 + * @since 2.0.0 */ export function fromEnv(options?: { readonly env?: Record | undefined }): ConfigProvider { const env = options?.env ?? { @@ -1074,15 +1092,16 @@ function trieNodeAt(root: EnvTrieNode, path: Path): EnvTrieNode | undefined { /** * Creates a `ConfigProvider` by parsing the string contents of a `.env` file. * - * When to use: - * - You already have the `.env` contents as a string (e.g. fetched from a - * remote store or embedded in a test). - * - Use {@link fromDotEnv} instead if you want to read a `.env` file from - * disk. + * **When to use** + * + * Use when you already have the `.env` contents as a string, such as contents + * fetched from a remote store or embedded in a test. * - * Supports `export` prefixes, single/double/backtick quoting, inline - * comments, and escaped newlines. Variable expansion (e.g. `${VAR}`) is - * disabled by default; enable with `{ expandVariables: true }`. + * **Details** + * + * Supports `export` prefixes, single/double/backtick quoting, inline comments, + * and escaped newlines. Variable expansion (for example, `${VAR}`) is disabled + * by default; enable with `{ expandVariables: true }`. * * Parsing is based on the `dotenv` / `dotenv-expand` algorithm. * @@ -1214,13 +1233,14 @@ function searchLast(str: string, rgx: RegExp): number { * Creates a `ConfigProvider` by reading and parsing a `.env` file from the * file system. * - * When to use: - * - Loading environment config from a `.env` file at application startup. - * - Use {@link fromDotEnvContents} if you already have the file contents as - * a string. + * **When to use** + * + * Use to load environment config from a `.env` file at application startup. + * + * **Details** * - * Requires `FileSystem` in the Effect context. Defaults to reading `".env"` - * in the current directory; override with `{ path: "/custom/.env" }`. + * Requires `FileSystem` in the Effect context. Defaults to reading `".env"` in + * the current directory; override with `{ path: "/custom/.env" }`. * * Returns an `Effect` that resolves to a `ConfigProvider`. Fails with a * `PlatformError` if the file cannot be read. @@ -1239,6 +1259,7 @@ function searchLast(str: string, rgx: RegExp): number { * @see {@link fromDotEnvContents} – parse a `.env` string directly * @see {@link fromEnv} – read from the runtime environment * + * @category constructors * @since 4.0.0 */ export const fromDotEnv: (options?: { @@ -1256,16 +1277,17 @@ export const fromDotEnv: (options?: { * Creates a `ConfigProvider` that reads configuration from a directory tree * on disk, where each file is a leaf value and each directory is a container. * - * When to use: - * - Kubernetes ConfigMap / Secret volume mounts, where each key is a file - * under a mount path. - * - Any file-per-key configuration layout. + * **When to use** + * + * Use when you expose each config key as a file under a directory, such as + * Kubernetes ConfigMap or Secret volume mounts. + * + * **Details** * - * Resolution rules: - * - Regular file → `Value` node (file contents trimmed). - * - Directory → `Record` node with immediate child names as keys. - * - Not found → tries as file first, then as directory; returns - * `SourceError` if both fail. + * Resolution tries a regular file first and returns a `Value` node with + * trimmed file contents. If the file read fails, it tries a directory and + * returns a `Record` node with immediate child names as keys. If both fail, it + * returns `SourceError`. * * Requires `Path` and `FileSystem` in the Effect context. Defaults to root * path `/`; override with `{ rootPath: "/etc/config" }`. diff --git a/.opencode/node_modules/effect/src/Console.ts b/.opencode/node_modules/effect/src/Console.ts index ec0483ca28764b4a6f39425cf3720d317df80096..79b5eef58a8a9312467ef7758a0e324d5537f4b7 100644 --- a/.opencode/node_modules/effect/src/Console.ts +++ b/.opencode/node_modules/effect/src/Console.ts @@ -1,72 +1,11 @@ /** - * The `Console` module provides a functional interface for console operations within - * the Effect ecosystem. It offers type-safe logging, debugging, and console manipulation - * capabilities with built-in support for testing and environment isolation. + * Wraps console operations in Effect. * - * ## Key Features - * - * - **Type-safe logging**: All console operations return Effects for composability - * - **Testable**: Mock console output for testing scenarios - * - **Service-based**: Integrated with Effect's dependency injection system - * - **Environment isolation**: Different console implementations per environment - * - **Rich API**: Support for all standard console methods (log, error, debug, etc.) - * - **Performance tracking**: Built-in timing and profiling capabilities - * - * ## Core Operations - * - * - **Basic logging**: `log`, `error`, `warn`, `info`, `debug` - * - **Assertions**: `assert` for conditional logging - * - **Grouping**: `group`, `groupCollapsed`, `groupEnd` for organized output - * - **Timing**: `time`, `timeEnd`, `timeLog` for performance measurement - * - **Data display**: `table`, `dir`, `dirxml` for structured data visualization - * - **Utilities**: `clear`, `count`, `countReset`, `trace` - * - * @example - * ```ts - * import { Console, Effect } from "effect" - * - * // Basic logging - * const program = Effect.gen(function*() { - * yield* Console.log("Hello, World!") - * yield* Console.error("Something went wrong") - * yield* Console.warn("This is a warning") - * yield* Console.info("Information message") - * }) - * ``` - * - * @example - * ```ts - * import { Console, Effect } from "effect" - * - * // Grouped logging with timing - * const debugProgram = Console.withGroup( - * Effect.gen(function*() { - * yield* Console.log("Step 1: Loading...") - * yield* Effect.sleep("100 millis") - * - * yield* Console.log("Step 2: Processing...") - * yield* Effect.sleep("200 millis") - * }), - * { label: "Processing Data" } - * ) - * ``` - * - * @example - * ```ts - * import { Console, Effect } from "effect" - * - * // Data visualization and debugging - * const dataProgram = Effect.gen(function*() { - * const users = [ - * { id: 1, name: "Alice", age: 30 }, - * { id: 2, name: "Bob", age: 25 } - * ] - * - * yield* Console.table(users) - * yield* Console.dir(users[0], { depth: 2 }) - * yield* Console.assert(users.length > 0, "Users array should not be empty") - * }) - * ``` + * The `Console` service exposes common console methods such as logging, + * warnings, errors, groups, counters, tables, and timers. Because console access + * goes through a service, programs can use custom console implementations in + * tests or other environments. This module also includes scoped helpers that + * close console groups or timers automatically. * * @since 2.0.0 */ @@ -78,13 +17,10 @@ import * as effect from "./internal/effect.ts" import type { Scope } from "./Scope.ts" /** - * Represents a console interface for logging and debugging operations. - * - * Provides methods for various console operations including logging, debugging, - * timing, and grouping output. + * Represents a console interface for logging, debugging, timing, and grouping output. * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface Console { assert(condition: boolean, ...args: ReadonlyArray): void @@ -109,12 +45,19 @@ export interface Console { } /** - * A reference to the current console service in the Effect system. + * Context reference for the current console service in the Effect system, allowing access to the active console implementation from within the Effect context. + * + * **When to use** + * + * Use when you need an effect to run against a provided console implementation, + * such as tests or alternate runtimes, rather than the default console. + * + * **Details** + * + * When no override is provided, the reference resolves to `globalThis.console`. * - * This reference allows you to access the current console implementation - * from within the Effect context. + * **Example** (Accessing the current console) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -125,18 +68,18 @@ export interface Console { * ) * ``` * - * @since 4.0.0 + * @see {@link consoleWith} for using the current console service inside an effect + * * @category references + * @since 2.0.0 */ export const Console: Context.Reference = effect.ConsoleRef /** - * Creates an Effect that provides access to the current console instance. + * Creates an Effect that provides access to the current console service and lets you perform operations with it within an Effect context. * - * This function allows you to access the console service and perform operations - * with it within an Effect context. + * **Example** (Using the current console service) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -148,19 +91,17 @@ export const Console: Context.Reference = effect.ConsoleRef * ) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const consoleWith = (f: (console: Console) => Effect.Effect): Effect.Effect => core.withFiber((fiber) => f(fiber.getRef(Console))) /** - * Writes an assertion message to the console if the condition is false. + * Writes the supplied assertion message to the console as an error when `condition` is false; when `condition` is true, no console output is produced. * - * If the condition is true, nothing happens. If the condition is false, - * the message is logged to the console as an error. + * **Example** (Logging failed assertions) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -170,8 +111,8 @@ export const consoleWith = (f: (console: Console) => Effect.Effect): Effect.Effect => consoleWith((console) => @@ -181,11 +122,20 @@ export const assert = (condition: boolean, ...args: ReadonlyArray): Effect. ) /** - * Clears the console. + * Runs the current console service's clear operation. + * + * **When to use** + * + * Use to request that the active console implementation clear its visible + * output. * - * This function clears all previously logged messages from the console. + * **Gotchas** + * + * The clearing behavior depends on the active console implementation and host + * environment. + * + * **Example** (Clearing console output) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -196,8 +146,8 @@ export const assert = (condition: boolean, ...args: ReadonlyArray): Effect. * }) * ``` * + * @category accessors * @since 2.0.0 - * @category accessor */ export const clear: Effect.Effect = consoleWith((console) => effect.sync(() => { @@ -206,12 +156,10 @@ export const clear: Effect.Effect = consoleWith((console) => ) /** - * Logs the number of times that this particular call to count has been called. + * Logs and increments the counter associated with `label`, using the console's default counter when no label is provided. * - * This function maintains a counter for each unique label and increments it - * each time count is called with that label. + * **Example** (Counting repeated calls) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -222,8 +170,8 @@ export const clear: Effect.Effect = consoleWith((console) => * }) * ``` * + * @category accessors * @since 2.0.0 - * @category accessor */ export const count = (label?: string): Effect.Effect => consoleWith((console) => @@ -233,12 +181,10 @@ export const count = (label?: string): Effect.Effect => ) /** - * Resets the counter for the given label. + * Resets the counter associated with the specified label back to zero. * - * This function resets the counter associated with the specified label - * back to zero. + * **Example** (Resetting a counter) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -250,8 +196,8 @@ export const count = (label?: string): Effect.Effect => * }) * ``` * + * @category accessors * @since 2.0.0 - * @category accessor */ export const countReset = (label?: string): Effect.Effect => consoleWith((console) => @@ -261,12 +207,16 @@ export const countReset = (label?: string): Effect.Effect => ) /** - * Outputs a debug message to the console. + * Writes a debug message through the current `Console` service. + * + * **Details** * - * This function logs messages at the debug level, which may be filtered - * out in production environments. + * The arguments are passed to the service's `debug` method when the returned + * Effect is executed. Any filtering behavior depends on the active console + * implementation. + * + * **Example** (Writing debug messages) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -276,8 +226,8 @@ export const countReset = (label?: string): Effect.Effect => * }) * ``` * + * @category accessors * @since 2.0.0 - * @category accessor */ export const debug = (...args: ReadonlyArray): Effect.Effect => consoleWith((console) => @@ -287,12 +237,10 @@ export const debug = (...args: ReadonlyArray): Effect.Effect => ) /** - * Displays an interactive list of the properties of the specified object. + * Displays an interactive list of the properties of the specified object, optionally using console-specific inspection options for debugging complex data structures. * - * This function provides a detailed view of an object's properties, - * which can be useful for debugging complex data structures. + * **Example** (Inspecting an object) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -303,8 +251,8 @@ export const debug = (...args: ReadonlyArray): Effect.Effect => * }) * ``` * + * @category accessors * @since 2.0.0 - * @category accessor */ export const dir = (item: any, options?: any): Effect.Effect => consoleWith((console) => @@ -314,23 +262,23 @@ export const dir = (item: any, options?: any): Effect.Effect => ) /** - * Displays an interactive tree of the descendant elements of the specified XML/HTML element. + * Displays an interactive tree of descendant XML or HTML elements, which is particularly useful for inspecting DOM elements in browser environments. * - * This function is particularly useful for inspecting DOM elements in browser environments. + * **Example** (Inspecting XML-like data) * - * @example * ```ts * import { Console, Effect } from "effect" * * const program = Effect.gen(function*() { - * // In a browser environment - * const element = document.getElementById("myElement") - * yield* Console.dirxml(element) + * yield* Console.dirxml("Ada") * }) + * + * Effect.runSync(program) + * // Ada * ``` * + * @category accessors * @since 2.0.0 - * @category accessor */ export const dirxml = (...args: ReadonlyArray): Effect.Effect => consoleWith((console) => @@ -340,12 +288,11 @@ export const dirxml = (...args: ReadonlyArray): Effect.Effect => ) /** - * Outputs an error message to the console. + * Writes an error-level message to the console, typically displayed with error + * styling by the active console implementation. * - * This function logs messages at the error level, typically displayed - * in red or with an error icon in most console implementations. + * **Example** (Writing error messages) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -358,8 +305,8 @@ export const dirxml = (...args: ReadonlyArray): Effect.Effect => * }) * ``` * + * @category accessors * @since 2.0.0 - * @category accessor */ export const error = (...args: ReadonlyArray): Effect.Effect => consoleWith((console) => @@ -369,12 +316,10 @@ export const error = (...args: ReadonlyArray): Effect.Effect => ) /** - * Creates a new inline group in the console and returns a scoped Effect. + * Creates a scoped console group, optionally collapsed and labeled, and closes it automatically when the Effect scope is finalized. * - * This function creates a collapsible group of console messages. The group - * is automatically closed when the Effect's scope is finalized. + * **Example** (Grouping scoped output) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -390,8 +335,8 @@ export const error = (...args: ReadonlyArray): Effect.Effect => * }) * ``` * + * @category accessors * @since 2.0.0 - * @category accessor */ export const group = ( options?: { label?: string | undefined; collapsed?: boolean | undefined } | undefined @@ -413,12 +358,11 @@ export const group = ( ) /** - * Outputs an informational message to the console. + * Writes an informational message to the console, typically displayed with info + * styling by the active console implementation. * - * This function logs messages at the info level, typically displayed - * with an info icon in most console implementations. + * **Example** (Writing informational messages) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -431,8 +375,8 @@ export const group = ( * }) * ``` * + * @category accessors * @since 2.0.0 - * @category accessor */ export const info = (...args: ReadonlyArray): Effect.Effect => consoleWith((console) => @@ -442,11 +386,10 @@ export const info = (...args: ReadonlyArray): Effect.Effect => ) /** - * Outputs a message to the console. + * Logs a general-purpose message to the console. * - * This is the most commonly used console method for general purpose logging. + * **Example** (Writing log messages) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -457,8 +400,8 @@ export const info = (...args: ReadonlyArray): Effect.Effect => * }) * ``` * + * @category accessors * @since 2.0.0 - * @category accessor */ export const log = (...args: ReadonlyArray): Effect.Effect => consoleWith((console) => @@ -468,12 +411,10 @@ export const log = (...args: ReadonlyArray): Effect.Effect => ) /** - * Displays tabular data as a table in the console. + * Displays tabular data as a formatted table in the console, optionally limited to selected properties. * - * This function takes tabular data and displays it in a formatted table, - * making it easier to read structured data. + * **Example** (Displaying tabular data) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -488,8 +429,8 @@ export const log = (...args: ReadonlyArray): Effect.Effect => * }) * ``` * + * @category accessors * @since 2.0.0 - * @category accessor */ export const table = (tabularData: any, properties?: ReadonlyArray): Effect.Effect => consoleWith((console) => @@ -499,12 +440,10 @@ export const table = (tabularData: any, properties?: ReadonlyArray): Eff ) /** - * Starts a timer that can be used to compute the duration of an operation. + * Starts a scoped timer for `label` and automatically ends it when the Effect scope is finalized. * - * This function returns a scoped Effect that starts a timer when entered - * and automatically ends the timer when the scope is finalized. + * **Example** (Timing scoped work) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -520,8 +459,8 @@ export const table = (tabularData: any, properties?: ReadonlyArray): Eff * }) * ``` * + * @category accessors * @since 2.0.0 - * @category accessor */ export const time = (label?: string | undefined): Effect.Effect => consoleWith((console) => @@ -537,12 +476,10 @@ export const time = (label?: string | undefined): Effect.Effect): Effect.Effect => consoleWith((console) => @@ -570,12 +507,11 @@ export const timeLog = (label?: string, ...args: ReadonlyArray): Effect.Eff ) /** - * Outputs a stack trace to the console. + * Writes the current stack trace to the console to show how the current point in + * the code was reached. * - * This function logs the current stack trace, which is useful for debugging - * to understand how the current point in the code was reached. + * **Example** (Writing stack traces) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -585,8 +521,8 @@ export const timeLog = (label?: string, ...args: ReadonlyArray): Effect.Eff * }) * ``` * + * @category accessors * @since 2.0.0 - * @category accessor */ export const trace = (...args: ReadonlyArray): Effect.Effect => consoleWith((console) => @@ -596,12 +532,11 @@ export const trace = (...args: ReadonlyArray): Effect.Effect => ) /** - * Outputs a warning message to the console. + * Writes a warning-level message to the console, typically displayed with + * warning styling by the active console implementation. * - * This function logs messages at the warning level, typically displayed - * in yellow or with a warning icon in most console implementations. + * **Example** (Writing warning messages) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -613,8 +548,8 @@ export const trace = (...args: ReadonlyArray): Effect.Effect => * }) * ``` * + * @category accessors * @since 2.0.0 - * @category accessor */ export const warn = (...args: ReadonlyArray): Effect.Effect => consoleWith((console) => @@ -624,13 +559,10 @@ export const warn = (...args: ReadonlyArray): Effect.Effect => ) /** - * Wraps an Effect with a console group. + * Runs an Effect inside an optionally labeled or collapsed console group, starting the group before execution and ending it after the Effect completes. * - * This function creates a console group around the execution of an Effect, - * automatically starting the group before the Effect runs and ending it - * after the Effect completes. + * **Example** (Wrapping an effect in a group) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -646,18 +578,15 @@ export const warn = (...args: ReadonlyArray): Effect.Effect => * }) * ``` * + * @category accessors * @since 2.0.0 - * @category accessor */ export const withGroup = dual< /** - * Wraps an Effect with a console group. + * Runs an Effect inside an optionally labeled or collapsed console group, starting the group before execution and ending it after the Effect completes. * - * This function creates a console group around the execution of an Effect, - * automatically starting the group before the Effect runs and ending it - * after the Effect completes. + * **Example** (Wrapping an effect in a group) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -673,8 +602,8 @@ export const withGroup = dual< * }) * ``` * + * @category accessors * @since 2.0.0 - * @category accessor */ ( options?: { @@ -683,13 +612,10 @@ export const withGroup = dual< } ) => (self: Effect.Effect) => Effect.Effect, /** - * Wraps an Effect with a console group. + * Runs an Effect inside an optionally labeled or collapsed console group, starting the group before execution and ending it after the Effect completes. * - * This function creates a console group around the execution of an Effect, - * automatically starting the group before the Effect runs and ending it - * after the Effect completes. + * **Example** (Wrapping an effect in a group) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -705,8 +631,8 @@ export const withGroup = dual< * }) * ``` * + * @category accessors * @since 2.0.0 - * @category accessor */ ( self: Effect.Effect, @@ -734,13 +660,10 @@ export const withGroup = dual< )) /** - * Wraps an Effect with a timer. + * Runs an Effect with a console timer, starting the timer before execution and ending it after the Effect completes. * - * This function measures the execution time of an Effect, automatically - * starting a timer before the Effect runs and logging the elapsed time - * after the Effect completes. + * **Example** (Timing an effect) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -755,18 +678,15 @@ export const withGroup = dual< * }) * ``` * + * @category accessors * @since 2.0.0 - * @category accessor */ export const withTime = dual< /** - * Wraps an Effect with a timer. + * Runs an Effect with a console timer, starting the timer before execution and ending it after the Effect completes. * - * This function measures the execution time of an Effect, automatically - * starting a timer before the Effect runs and logging the elapsed time - * after the Effect completes. + * **Example** (Timing an effect) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -781,18 +701,15 @@ export const withTime = dual< * }) * ``` * + * @category accessors * @since 2.0.0 - * @category accessor */ (label?: string) => (self: Effect.Effect) => Effect.Effect, /** - * Wraps an Effect with a timer. + * Runs an Effect with a console timer, starting the timer before execution and ending it after the Effect completes. * - * This function measures the execution time of an Effect, automatically - * starting a timer before the Effect runs and logging the elapsed time - * after the Effect completes. + * **Example** (Timing an effect) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -807,8 +724,8 @@ export const withTime = dual< * }) * ``` * + * @category accessors * @since 2.0.0 - * @category accessor */ (self: Effect.Effect, label?: string) => Effect.Effect >((args) => core.isEffect(args[0]), (self, label) => diff --git a/.opencode/node_modules/effect/src/Context.ts b/.opencode/node_modules/effect/src/Context.ts index d403ced446172eb8afa6d63a501717f4ef600b3c..6511d1f934e08d199f70a63c1285b92ffa3f97f1 100644 --- a/.opencode/node_modules/effect/src/Context.ts +++ b/.opencode/node_modules/effect/src/Context.ts @@ -1,21 +1,22 @@ /** - * This module provides a data structure called `Context` that can be used - * for dependency injection in effectful programs. It is essentially a table - * mapping `Service`s identifiers to their implementations, 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 a `Context`. + * Stores Effect services in typed maps. + * + * A `Context` holds service implementations under `Context.Service` or + * `Context.Reference` keys, and its type records which keys are present. + * Effects use contexts as their environment, so services can be provided once + * instead of passed through every function call. This module includes helpers + * for creating keys, building contexts, adding and reading services, merging + * contexts, and selecting or removing services. * * @since 4.0.0 */ -import type { Effect, EffectIterator, Yieldable } from "./Effect.ts" +import type { Effect, EffectIterator } from "./Effect.ts" +import * as Effectable from "./Effectable.ts" import * as Equal from "./Equal.ts" -import { constant, dual, type LazyArg } from "./Function.ts" +import { dual, type LazyArg } from "./Function.ts" import * as Hash from "./Hash.ts" import type { Inspectable } from "./Inspectable.ts" -import { exitSucceed, PipeInspectableProto, withFiber, YieldableProto } from "./internal/core.ts" +import { exitSucceed, PipeInspectableProto, withFiber } from "./internal/core.ts" import type { ErrorWithStackTraceLimit } from "./internal/tracer.ts" import * as Option from "./Option.ts" import type { Pipeable } from "./Pipeable.ts" @@ -23,34 +24,63 @@ import { hasProperty } from "./Predicate.ts" import type * as Types from "./Types.ts" /** + * String literal type used as the runtime type identifier for `Context` + * service keys. + * + * @category type IDs * @since 4.0.0 - * @category Type Identifiers */ export type ServiceTypeId = "~effect/Context/Service" /** + * Runtime type identifier attached to `Context` service keys and used by + * `isKey` to recognize them. + * + * @category type IDs * @since 4.0.0 - * @category Type Identifiers */ export const ServiceTypeId: ServiceTypeId = "~effect/Context/Service" /** - * The base type used for all Context keys. + * Typed identifier for a service stored in a `Context`. * + * **When to use** + * + * Use as the typed handle for storing, retrieving, and requiring a specific + * service in a `Context`. + * + * **Details** + * + * `Identifier` tracks the requirement in Effect types, while `Shape` is the + * service implementation retrieved by the key. A key is also an Effect value, + * so yielding it inside `Effect.gen` retrieves the service from the current + * fiber context. + * + * @see {@link Service} for creating required service keys + * @see {@link Reference} for creating service keys with default values + * + * @category models * @since 4.0.0 - * @category Models */ -export interface Key extends Pipeable, Inspectable { +export interface Key extends Effect { readonly [ServiceTypeId]: ServiceTypeId readonly Service: Shape readonly Identifier: Identifier readonly key: string readonly stack?: string | undefined - asEffect(): Effect } /** - * @example + * Context key with helper methods for working with a service. + * + * **Details** + * + * `context` creates a one-service `Context`, `use` and `useSync` retrieve the + * service from the current Effect context before applying a function, and `of` + * is a type-level helper for service values. + * + * **Example** (Defining a service key) + * * ```ts * import { Context } from "effect" * @@ -63,12 +93,10 @@ export interface Key extends Pipeable, Inspectable { * const context = Context.make(Database, { query: (sql) => `Result: ${sql}` }) * ``` * + * @category models * @since 4.0.0 - * @category Models */ -export interface Service - extends Key, Yieldable, Shape, never, Identifier> -{ +export interface Service extends Key { of(this: void, self: Shape): Shape context(self: Shape): Context use(f: (service: Shape) => Effect): Effect @@ -76,8 +104,22 @@ export interface Service } /** + * Class-style service key produced by `Context.Service()("Id")`. + * + * **When to use** + * + * Use when declaring a service as a class so the class value can serve as the + * `Context` key. + * + * **Details** + * + * The class itself is the `Context` key, and its string `key` identifies the + * service at runtime. + * + * @see {@link Service} for creating function-style keys or class-style service keys + * + * @category models * @since 4.0.0 - * @category Models */ export interface ServiceClass extends Service @@ -87,13 +129,18 @@ export interface ServiceClass { readonly [ServiceTypeId]: typeof ServiceTypeId @@ -103,7 +150,28 @@ export declare namespace ServiceClass { } /** - * @example + * Creates a `Context` service key. + * + * **When to use** + * + * Use when you need to define a context service key for a dependency that must + * be provided by the surrounding context. + * + * **Details** + * + * Call `Context.Service("Key")` for a function-style key, or use the two-stage + * form `Context.Service()("Key")` for class-style service + * declarations. The returned key can be yielded as an Effect and passed to + * `Context.make`, `Context.add`, and the Context getter functions. + * + * **Gotchas** + * + * The string key is the runtime identity of the service. Reusing the same key + * string for unrelated services makes them occupy the same slot in a + * `Context`. + * + * **Example** (Creating service keys) + * * ```ts * import { Context } from "effect" * @@ -124,12 +192,35 @@ export declare namespace ServiceClass { * const config = Context.make(Config, { port: 8080 }) * ``` * + * @see {@link Reference} for service keys with default values + * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const Service: { /** - * @example + * Creates a `Context` service key. + * + * **When to use** + * + * Use when you need to define a context service key for a dependency that must + * be provided by the surrounding context. + * + * **Details** + * + * Call `Context.Service("Key")` for a function-style key, or use the two-stage + * form `Context.Service()("Key")` for class-style service + * declarations. The returned key can be yielded as an Effect and passed to + * `Context.make`, `Context.add`, and the Context getter functions. + * + * **Gotchas** + * + * The string key is the runtime identity of the service. Reusing the same key + * string for unrelated services makes them occupy the same slot in a + * `Context`. + * + * **Example** (Creating service keys) + * * ```ts * import { Context } from "effect" * @@ -150,12 +241,35 @@ export const Service: { * const config = Context.make(Config, { port: 8080 }) * ``` * + * @see {@link Reference} for service keys with default values + * + * @category constructors * @since 4.0.0 - * @category Constructors */ (key: string): Service /** - * @example + * Creates a `Context` service key. + * + * **When to use** + * + * Use when you need to define a context service key for a dependency that must + * be provided by the surrounding context. + * + * **Details** + * + * Call `Context.Service("Key")` for a function-style key, or use the two-stage + * form `Context.Service()("Key")` for class-style service + * declarations. The returned key can be yielded as an Effect and passed to + * `Context.make`, `Context.add`, and the Context getter functions. + * + * **Gotchas** + * + * The string key is the runtime identity of the service. Reusing the same key + * string for unrelated services makes them occupy the same slot in a + * `Context`. + * + * **Example** (Creating service keys) + * * ```ts * import { Context } from "effect" * @@ -176,8 +290,10 @@ export const Service: { * const config = Context.make(Config, { port: 8080 }) * ``` * + * @see {@link Reference} for service keys with default values + * + * @category constructors * @since 4.0.0 - * @category Constructors */ (): < const Identifier extends string, @@ -194,7 +310,28 @@ export const Service: { & ([Types.unassigned] extends [R] ? unknown : { readonly make: [Args] extends [never] ? Effect : (...args: Args) => Effect }) /** - * @example + * Creates a `Context` service key. + * + * **When to use** + * + * Use when you need to define a context service key for a dependency that must + * be provided by the surrounding context. + * + * **Details** + * + * Call `Context.Service("Key")` for a function-style key, or use the two-stage + * form `Context.Service()("Key")` for class-style service + * declarations. The returned key can be yielded as an Effect and passed to + * `Context.make`, `Context.add`, and the Context getter functions. + * + * **Gotchas** + * + * The string key is the runtime identity of the service. Reusing the same key + * string for unrelated services makes them occupy the same slot in a + * `Context`. + * + * **Example** (Creating service keys) + * * ```ts * import { Context } from "effect" * @@ -215,8 +352,10 @@ export const Service: { * const config = Context.make(Config, { port: 8080 }) * ``` * + * @see {@link Reference} for service keys with default values + * + * @category constructors * @since 4.0.0 - * @category Constructors */ (): < const Identifier extends string, @@ -244,6 +383,7 @@ export const Service: { function KeyClass() {} const self = KeyClass as any as Types.Mutable> Object.setPrototypeOf(self, ServiceProto) + // @effect-diagnostics-next-line floatingEffect:off Object.defineProperty(self, "stack", { get() { return err.stack @@ -270,8 +410,12 @@ export const Service: { const ServiceProto: any = { [ServiceTypeId]: ServiceTypeId, - ...PipeInspectableProto, - ...YieldableProto, + ...Effectable.Prototype>({ + label: "Service", + evaluate(fiber) { + return exitSucceed(get(fiber.context, this)) + } + }), toJSON(this: Service) { return { _id: "Service", @@ -279,10 +423,6 @@ const ServiceProto: any = { stack: this.stack } }, - asEffect(this: any) { - const fn = this.asEffect = constant(withFiber((fiber) => exitSucceed(get(fiber.context, this)))) - return fn() - }, of(this: void, self: Service): Service { return self }, @@ -303,7 +443,16 @@ const ServiceProto: any = { const ReferenceTypeId = "~effect/Context/Reference" as const /** - * @example + * Service key with a lazily computed default value. + * + * **Details** + * + * When a `Reference` is requested from a `Context` that does not contain an + * override, Context getters that resolve references return the cached default + * value instead of failing. + * + * **Example** (Defining a reference with a default value) + * * ```ts * import { Context } from "effect" * @@ -318,8 +467,8 @@ const ReferenceTypeId = "~effect/Context/Reference" as const * const logger = Context.get(context, LoggerRef) // Uses default value * ``` * - * @since 4.0.0 - * @category Models + * @category models + * @since 3.11.0 */ export interface Reference extends Service { readonly [ReferenceTypeId]: typeof ReferenceTypeId @@ -329,7 +478,10 @@ export interface Reference extends Service { } /** - * @example + * Namespace containing utility types for `Context` service keys. + * + * **Example** (Extracting service types) + * * ```ts * import { Context } from "effect" * @@ -344,12 +496,15 @@ export interface Reference extends Service { * type DatabaseId = Context.Service.Identifier * ``` * - * @since 4.0.0 - * @category Models + * @since 2.0.0 */ export declare namespace Service { /** - * @example + * Type that matches any `Context` service key regardless of its identifier or + * service shape. + * + * **Example** (Typing any service key) + * * ```ts * import { Context } from "effect" * @@ -360,13 +515,17 @@ export declare namespace Service { * ] * ``` * + * @category models * @since 4.0.0 - * @category Models */ export type Any = Key | Key /** - * @example + * Extracts the service implementation type stored behind a `Context` service + * key. + * + * **Example** (Extracting a service shape) + * * ```ts * import { Context } from "effect" * @@ -379,13 +538,17 @@ export declare namespace Service { * // DatabaseService is { query: (sql: string) => string } * ``` * + * @category models * @since 4.0.0 - * @category Models */ export type Shape = T extends Key ? S : never /** - * @example + * Extracts the identifier, or requirement type, associated with a `Context` + * service key. + * + * **Example** (Extracting a service identifier) + * * ```ts * import { Context } from "effect" * @@ -398,8 +561,8 @@ export declare namespace Service { * // DatabaseId is the identifier type * ``` * - * @since 4.0.0 - * @category Models + * @category models + * @since 2.0.0 */ export type Identifier = T extends Key ? I : never } @@ -407,7 +570,16 @@ export declare namespace Service { const TypeId = "~effect/Context" as const /** - * @example + * Immutable collection of service implementations used for dependency + * injection in Effect programs. + * + * **Details** + * + * The type parameter tracks the service identifiers available in the context. + * At runtime, services are stored by each key's string `key`. + * + * **Example** (Creating a context with multiple services) + * * ```ts * import { Context } from "effect" * @@ -423,8 +595,8 @@ const TypeId = "~effect/Context" as const * .pipe(Context.add(Database, { query: (sql) => `Result: ${sql}` })) * ``` * - * @since 4.0.0 - * @category Models + * @category models + * @since 2.0.0 */ export interface Context extends Equal.Equal, Pipeable, Inspectable { readonly [TypeId]: { @@ -435,7 +607,21 @@ export interface Context extends Equal.Equal, Pipeable, Inspectable } /** - * @example + * Creates a `Context` from an existing service map. + * + * **When to use** + * + * Use when constructing a low-level `Context` from a trusted map whose lifecycle + * you control. + * + * **Gotchas** + * + * This is unsafe because later mutation of the provided map can affect the + * created `Context`. Prefer `empty`, `make`, `add`, or `merge` for normal + * Context construction. + * + * **Example** (Creating a context from a map) + * * ```ts * import { Context } from "effect" * @@ -447,8 +633,8 @@ export interface Context extends Equal.Equal, Pipeable, Inspectable * const context = Context.makeUnsafe(map) * ``` * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const makeUnsafe = (mapUnsafe: ReadonlyMap): Context => { const self = Object.create(Proto) @@ -489,9 +675,25 @@ const Proto: Omit, "mapUnsafe" | "mutable"> = { } /** - * Checks if the provided argument is a `Context`. + * Checks whether the provided argument is a `Context`. + * + * **When to use** + * + * Use to narrow an unknown value before passing it to APIs that require a + * `Context`. + * + * **Details** + * + * This checks the runtime `Context` marker and does not inspect which services + * the context contains. + * + * **Gotchas** + * + * This guard only proves that the value is a `Context`; it does not prove that + * any specific service is present. + * + * **Example** (Checking for contexts) * - * @example * ```ts * import { Context } from "effect" * import * as assert from "node:assert" @@ -499,15 +701,19 @@ const Proto: Omit, "mapUnsafe" | "mutable"> = { * assert.strictEqual(Context.isContext(Context.empty()), true) * ``` * - * @since 4.0.0 - * @category Guards + * @see {@link isKey} for checking service keys + * @see {@link isReference} for checking references with defaults + * + * @category guards + * @since 2.0.0 */ export const isContext = (u: unknown): u is Context => hasProperty(u, TypeId) /** - * Checks if the provided argument is a `Key`. + * Checks whether the provided argument is a `Key`. + * + * **Example** (Checking for keys) * - * @example * ```ts * import { Context } from "effect" * import * as assert from "node:assert" @@ -515,15 +721,16 @@ export const isContext = (u: unknown): u is Context => hasProperty(u, Typ * assert.strictEqual(Context.isKey(Context.Service("Service")), true) * ``` * + * @category guards * @since 4.0.0 - * @category Guards */ export const isKey = (u: unknown): u is Key => hasProperty(u, ServiceTypeId) /** - * Checks if the provided argument is a `Reference`. + * Checks whether the provided argument is a `Reference`. + * + * **Example** (Checking for references) * - * @example * ```ts * import { Context } from "effect" * import * as assert from "node:assert" @@ -536,15 +743,16 @@ export const isKey = (u: unknown): u is Key => hasProperty(u, ServiceT * assert.strictEqual(Context.isReference(Context.Service("Key")), false) * ``` * - * @since 4.0.0 - * @category Guards + * @category guards + * @since 3.11.0 */ export const isReference = (u: unknown): u is Reference => hasProperty(u, ReferenceTypeId) /** * Returns an empty `Context`. * - * @example + * **Example** (Creating an empty context) + * * ```ts * import { Context } from "effect" * import * as assert from "node:assert" @@ -552,8 +760,8 @@ export const isReference = (u: unknown): u is Reference => hasProperty(u, R * assert.strictEqual(Context.isContext(Context.empty()), true) * ``` * - * @since 4.0.0 - * @category Constructors + * @category constructors + * @since 2.0.0 */ export const empty = (): Context => emptyContext const emptyContext = makeUnsafe(new Map()) @@ -561,7 +769,8 @@ const emptyContext = makeUnsafe(new Map()) /** * Creates a new `Context` with a single service associated to the key. * - * @example + * **Example** (Creating a context with one service) + * * ```ts * import { Context } from "effect" * import * as assert from "node:assert" @@ -573,8 +782,8 @@ const emptyContext = makeUnsafe(new Map()) * assert.deepStrictEqual(Context.get(context, Port), { PORT: 8080 }) * ``` * - * @since 4.0.0 - * @category Constructors + * @category constructors + * @since 2.0.0 */ export const make = ( key: Key, @@ -584,9 +793,19 @@ export const make = ( /** * Adds a service to a given `Context`. * - * @example + * **When to use** + * + * Use when you need to store a known service value in a `Context`. + * + * **Details** + * + * If the context already contains the same service key, the new service + * replaces the previous one. + * + * **Example** (Adding a service to a context) + * * ```ts - * import { pipe, Context } from "effect" + * import { Context, pipe } from "effect" * import * as assert from "node:assert" * * const Port = Context.Service<{ PORT: number }>("Port") @@ -603,16 +822,28 @@ export const make = ( * assert.deepStrictEqual(Context.get(context, Timeout), { TIMEOUT: 5000 }) * ``` * - * @since 4.0.0 - * @category Adders + * @see {@link addOrOmit} for adding or removing a service from an `Option` + * + * @category adders + * @since 2.0.0 */ export const add: { /** * Adds a service to a given `Context`. * - * @example + * **When to use** + * + * Use when you need to store a known service value in a `Context`. + * + * **Details** + * + * If the context already contains the same service key, the new service + * replaces the previous one. + * + * **Example** (Adding a service to a context) + * * ```ts - * import { pipe, Context } from "effect" + * import { Context, pipe } from "effect" * import * as assert from "node:assert" * * const Port = Context.Service<{ PORT: number }>("Port") @@ -629,16 +860,28 @@ export const add: { * assert.deepStrictEqual(Context.get(context, Timeout), { TIMEOUT: 5000 }) * ``` * - * @since 4.0.0 - * @category Adders + * @see {@link addOrOmit} for adding or removing a service from an `Option` + * + * @category adders + * @since 2.0.0 */ (key: Key, service: Types.NoInfer): (self: Context) => Context /** * Adds a service to a given `Context`. * - * @example + * **When to use** + * + * Use when you need to store a known service value in a `Context`. + * + * **Details** + * + * If the context already contains the same service key, the new service + * replaces the previous one. + * + * **Example** (Adding a service to a context) + * * ```ts - * import { pipe, Context } from "effect" + * import { Context, pipe } from "effect" * import * as assert from "node:assert" * * const Port = Context.Service<{ PORT: number }>("Port") @@ -655,8 +898,10 @@ export const add: { * assert.deepStrictEqual(Context.get(context, Timeout), { TIMEOUT: 5000 }) * ``` * - * @since 4.0.0 - * @category Adders + * @see {@link addOrOmit} for adding or removing a service from an `Option` + * + * @category adders + * @since 2.0.0 */ (self: Context, key: Key, service: Types.NoInfer): Context } = dual(3, ( @@ -669,18 +914,105 @@ export const add: { })) /** + * Adds or removes a service depending on an `Option`. + * + * **When to use** + * + * Use when you need to add or omit a `Context` service based on an `Option`. + * + * **Details** + * + * When `service` is `Option.some`, the value is stored for the key. When it is + * `Option.none`, the key is removed from the returned `Context`. + * + * **Example** (Adding optional services) + * + * ```ts + * import { Context, Option } from "effect" + * + * const Port = Context.Service<{ PORT: number }>("Port") + * + * const withPort = Context.empty().pipe( + * Context.addOrOmit(Port, Option.some({ PORT: 8080 })) + * ) + * + * const withoutPort = withPort.pipe( + * Context.addOrOmit(Port, Option.none()) + * ) + * ``` + * + * @see {@link add} for always storing a service value + * + * @category adders * @since 4.0.0 - * @category Adders */ export const addOrOmit: { /** + * Adds or removes a service depending on an `Option`. + * + * **When to use** + * + * Use when you need to add or omit a `Context` service based on an `Option`. + * + * **Details** + * + * When `service` is `Option.some`, the value is stored for the key. When it is + * `Option.none`, the key is removed from the returned `Context`. + * + * **Example** (Adding optional services) + * + * ```ts + * import { Context, Option } from "effect" + * + * const Port = Context.Service<{ PORT: number }>("Port") + * + * const withPort = Context.empty().pipe( + * Context.addOrOmit(Port, Option.some({ PORT: 8080 })) + * ) + * + * const withoutPort = withPort.pipe( + * Context.addOrOmit(Port, Option.none()) + * ) + * ``` + * + * @see {@link add} for always storing a service value + * + * @category adders * @since 4.0.0 - * @category Adders */ (key: Key, service: Option.Option>): (self: Context) => Context /** + * Adds or removes a service depending on an `Option`. + * + * **When to use** + * + * Use when you need to add or omit a `Context` service based on an `Option`. + * + * **Details** + * + * When `service` is `Option.some`, the value is stored for the key. When it is + * `Option.none`, the key is removed from the returned `Context`. + * + * **Example** (Adding optional services) + * + * ```ts + * import { Context, Option } from "effect" + * + * const Port = Context.Service<{ PORT: number }>("Port") + * + * const withPort = Context.empty().pipe( + * Context.addOrOmit(Port, Option.some({ PORT: 8080 })) + * ) + * + * const withoutPort = withPort.pipe( + * Context.addOrOmit(Port, Option.none()) + * ) + * ``` + * + * @see {@link add} for always storing a service value + * + * @category adders * @since 4.0.0 - * @category Adders */ ( self: Context, @@ -701,13 +1033,28 @@ export const addOrOmit: { })) /** - * Get a service from the context that corresponds to the given key, or - * use the fallback value. + * Gets the service for a key, or evaluates the fallback when a non-reference + * key is absent. + * + * **When to use** + * + * Use when you need a fallback for a missing `Context.Service` key while still + * resolving `Context.Reference` defaults. + * + * **Details** + * + * If the key is a `Context.Reference` and no override is stored in the + * context, its cached default value is returned instead of the fallback. + * + * **Gotchas** + * + * The fallback is not evaluated for missing `Context.Reference` keys because + * references resolve to their default value. + * + * **Example** (Falling back for missing services) * - * @example * ```ts * import { Context } from "effect" - * import * as assert from "node:assert" * * const Logger = Context.Service<{ log: (msg: string) => void }>("Logger") * const Database = Context.Service<{ query: (sql: string) => string }>( @@ -725,22 +1072,39 @@ export const addOrOmit: { * () => ({ query: () => "fallback" }) * ) * - * assert.deepStrictEqual(logger, { log: (msg: string) => console.log(msg) }) - * assert.deepStrictEqual(database, { query: () => "fallback" }) + * console.log(logger === Context.get(context, Logger)) // true + * console.log(database.query("SELECT 1")) // "fallback" * ``` * - * @since 4.0.0 - * @category Getters + * @see {@link getOption} for returning `Option.none` when a non-reference key is missing + * + * @category getters + * @since 3.7.0 */ export const getOrElse: { /** - * Get a service from the context that corresponds to the given key, or - * use the fallback value. + * Gets the service for a key, or evaluates the fallback when a non-reference + * key is absent. + * + * **When to use** + * + * Use when you need a fallback for a missing `Context.Service` key while still + * resolving `Context.Reference` defaults. + * + * **Details** + * + * If the key is a `Context.Reference` and no override is stored in the + * context, its cached default value is returned instead of the fallback. + * + * **Gotchas** + * + * The fallback is not evaluated for missing `Context.Reference` keys because + * references resolve to their default value. + * + * **Example** (Falling back for missing services) * - * @example * ```ts * import { Context } from "effect" - * import * as assert from "node:assert" * * const Logger = Context.Service<{ log: (msg: string) => void }>("Logger") * const Database = Context.Service<{ query: (sql: string) => string }>( @@ -758,22 +1122,39 @@ export const getOrElse: { * () => ({ query: () => "fallback" }) * ) * - * assert.deepStrictEqual(logger, { log: (msg: string) => console.log(msg) }) - * assert.deepStrictEqual(database, { query: () => "fallback" }) + * console.log(logger === Context.get(context, Logger)) // true + * console.log(database.query("SELECT 1")) // "fallback" * ``` * - * @since 4.0.0 - * @category Getters + * @see {@link getOption} for returning `Option.none` when a non-reference key is missing + * + * @category getters + * @since 3.7.0 */ (key: Key, orElse: LazyArg): (self: Context) => S | B /** - * Get a service from the context that corresponds to the given key, or - * use the fallback value. + * Gets the service for a key, or evaluates the fallback when a non-reference + * key is absent. + * + * **When to use** + * + * Use when you need a fallback for a missing `Context.Service` key while still + * resolving `Context.Reference` defaults. + * + * **Details** + * + * If the key is a `Context.Reference` and no override is stored in the + * context, its cached default value is returned instead of the fallback. + * + * **Gotchas** + * + * The fallback is not evaluated for missing `Context.Reference` keys because + * references resolve to their default value. + * + * **Example** (Falling back for missing services) * - * @example * ```ts * import { Context } from "effect" - * import * as assert from "node:assert" * * const Logger = Context.Service<{ log: (msg: string) => void }>("Logger") * const Database = Context.Service<{ query: (sql: string) => string }>( @@ -791,12 +1172,14 @@ export const getOrElse: { * () => ({ query: () => "fallback" }) * ) * - * assert.deepStrictEqual(logger, { log: (msg: string) => console.log(msg) }) - * assert.deepStrictEqual(database, { query: () => "fallback" }) + * console.log(logger === Context.get(context, Logger)) // true + * console.log(database.query("SELECT 1")) // "fallback" * ``` * - * @since 4.0.0 - * @category Getters + * @see {@link getOption} for returning `Option.none` when a non-reference key is missing + * + * @category getters + * @since 3.7.0 */ (self: Context, key: Key, orElse: LazyArg): S | B } = dual(3, (self: Context, key: Key, orElse: LazyArg): S | B => { @@ -807,18 +1190,63 @@ export const getOrElse: { }) /** + * Returns the service currently stored for a key, or `undefined` when the key + * is absent. + * + * **When to use** + * + * Use when you need to read the service stored for a key without resolving + * `Context.Reference` defaults. + * + * **Gotchas** + * + * This is a raw lookup and does not resolve default values for + * `Context.Reference` keys. + * + * @see {@link getOption} for a reference-aware optional lookup + * + * @category getters * @since 4.0.0 - * @category Getters */ export const getOrUndefined: { /** + * Returns the service currently stored for a key, or `undefined` when the key + * is absent. + * + * **When to use** + * + * Use when you need to read the service stored for a key without resolving + * `Context.Reference` defaults. + * + * **Gotchas** + * + * This is a raw lookup and does not resolve default values for + * `Context.Reference` keys. + * + * @see {@link getOption} for a reference-aware optional lookup + * + * @category getters * @since 4.0.0 - * @category Getters */ (key: Key): (self: Context) => S | undefined /** + * Returns the service currently stored for a key, or `undefined` when the key + * is absent. + * + * **When to use** + * + * Use when you need to read the service stored for a key without resolving + * `Context.Reference` defaults. + * + * **Gotchas** + * + * This is a raw lookup and does not resolve default values for + * `Context.Reference` keys. + * + * @see {@link getOption} for a reference-aware optional lookup + * + * @category getters * @since 4.0.0 - * @category Getters */ (self: Context, key: Key): S | undefined } = dual( @@ -827,17 +1255,22 @@ export const getOrUndefined: { ) /** - * Get a service from the context that corresponds to the given key. + * Gets the service for a key, throwing if an absent non-reference key cannot be + * resolved. + * + * **When to use** * - * This function is unsafe because if the key is not present in the context, a - * runtime error will be thrown. + * Use when you need to read a service from a context whose type does not prove + * the service is present. * - * For a safer version see {@link getOption}. + * **Details** * - * @param self - The `Context` to search for the service. - * @param service - The `Service` of the service to retrieve. + * If the key is a `Context.Reference` and no override is stored in the + * context, its cached default value is returned. For absent non-reference keys, + * this function throws a runtime error. + * + * **Example** (Getting services unsafely) * - * @example * ```ts * import { Context } from "effect" * import * as assert from "node:assert" @@ -851,22 +1284,30 @@ export const getOrUndefined: { * assert.throws(() => Context.getUnsafe(context, Timeout)) * ``` * - * @since 4.0.0 + * @see {@link get} for type-checked service access + * @see {@link getOption} for optional service access + * * @category unsafe + * @since 4.0.0 */ export const getUnsafe: { /** - * Get a service from the context that corresponds to the given key. + * Gets the service for a key, throwing if an absent non-reference key cannot be + * resolved. + * + * **When to use** * - * This function is unsafe because if the key is not present in the context, a - * runtime error will be thrown. + * Use when you need to read a service from a context whose type does not prove + * the service is present. * - * For a safer version see {@link getOption}. + * **Details** * - * @param self - The `Context` to search for the service. - * @param service - The `Service` of the service to retrieve. + * If the key is a `Context.Reference` and no override is stored in the + * context, its cached default value is returned. For absent non-reference keys, + * this function throws a runtime error. + * + * **Example** (Getting services unsafely) * - * @example * ```ts * import { Context } from "effect" * import * as assert from "node:assert" @@ -880,22 +1321,30 @@ export const getUnsafe: { * assert.throws(() => Context.getUnsafe(context, Timeout)) * ``` * - * @since 4.0.0 + * @see {@link get} for type-checked service access + * @see {@link getOption} for optional service access + * * @category unsafe + * @since 4.0.0 */ (service: Key): (self: Context) => S /** - * Get a service from the context that corresponds to the given key. + * Gets the service for a key, throwing if an absent non-reference key cannot be + * resolved. + * + * **When to use** + * + * Use when you need to read a service from a context whose type does not prove + * the service is present. * - * This function is unsafe because if the key is not present in the context, a - * runtime error will be thrown. + * **Details** * - * For a safer version see {@link getOption}. + * If the key is a `Context.Reference` and no override is stored in the + * context, its cached default value is returned. For absent non-reference keys, + * this function throws a runtime error. * - * @param self - The `Context` to search for the service. - * @param service - The `Service` of the service to retrieve. + * **Example** (Getting services unsafely) * - * @example * ```ts * import { Context } from "effect" * import * as assert from "node:assert" @@ -909,8 +1358,11 @@ export const getUnsafe: { * assert.throws(() => Context.getUnsafe(context, Timeout)) * ``` * - * @since 4.0.0 + * @see {@link get} for type-checked service access + * @see {@link getOption} for optional service access + * * @category unsafe + * @since 4.0.0 */ (self: Context, services: Key): S } = dual( @@ -925,14 +1377,17 @@ export const getUnsafe: { ) /** - * Get a service from the context that corresponds to the given key. + * Gets a service from the context that corresponds to the given key. + * + * **When to use** + * + * Use when you need type-checked access to a service already included in the + * context type. * - * @param self - The `Context` to search for the service. - * @param service - The `Service` of the service to retrieve. + * **Example** (Getting a service from a context) * - * @example * ```ts - * import { pipe, Context } from "effect" + * import { Context, pipe } from "effect" * import * as assert from "node:assert" * * const Port = Context.Service<{ PORT: number }>("Port") @@ -946,19 +1401,25 @@ export const getUnsafe: { * assert.deepStrictEqual(Context.get(context, Timeout), { TIMEOUT: 5000 }) * ``` * - * @since 4.0.0 - * @category Getters + * @see {@link getOption} for optional service access + * @see {@link getOrElse} for fallback values + * + * @category getters + * @since 2.0.0 */ export const get: { /** - * Get a service from the context that corresponds to the given key. + * Gets a service from the context that corresponds to the given key. + * + * **When to use** * - * @param self - The `Context` to search for the service. - * @param service - The `Service` of the service to retrieve. + * Use when you need type-checked access to a service already included in the + * context type. + * + * **Example** (Getting a service from a context) * - * @example * ```ts - * import { pipe, Context } from "effect" + * import { Context, pipe } from "effect" * import * as assert from "node:assert" * * const Port = Context.Service<{ PORT: number }>("Port") @@ -972,19 +1433,25 @@ export const get: { * assert.deepStrictEqual(Context.get(context, Timeout), { TIMEOUT: 5000 }) * ``` * - * @since 4.0.0 - * @category Getters + * @see {@link getOption} for optional service access + * @see {@link getOrElse} for fallback values + * + * @category getters + * @since 2.0.0 */ (service: Key): (self: Context) => S /** - * Get a service from the context that corresponds to the given key. + * Gets a service from the context that corresponds to the given key. + * + * **When to use** + * + * Use when you need type-checked access to a service already included in the + * context type. * - * @param self - The `Context` to search for the service. - * @param service - The `Service` of the service to retrieve. + * **Example** (Getting a service from a context) * - * @example * ```ts - * import { pipe, Context } from "effect" + * import { Context, pipe } from "effect" * import * as assert from "node:assert" * * const Port = Context.Service<{ PORT: number }>("Port") @@ -998,17 +1465,38 @@ export const get: { * assert.deepStrictEqual(Context.get(context, Timeout), { TIMEOUT: 5000 }) * ``` * - * @since 4.0.0 - * @category Getters + * @see {@link getOption} for optional service access + * @see {@link getOrElse} for fallback values + * + * @category getters + * @since 2.0.0 */ (self: Context, service: Key): S } = getUnsafe /** - * @example + * Gets the value for a `Context.Reference`, returning its cached default when + * the context does not contain an override. + * + * **When to use** + * + * Use when you need a `Context.Reference` value resolved from either a stored + * override or the reference's default value. + * + * **Details** + * + * Stored overrides take precedence. If no override is present, the reference's + * default value is computed lazily and cached on the reference itself. + * + * **Gotchas** + * + * Mutable default values can be shared across contexts unless an override is + * provided, because the default is cached on the `Context.Reference`. + * + * **Example** (Getting reference defaults unsafely) + * * ```ts * import { Context } from "effect" - * import * as assert from "node:assert" * * const LoggerRef = Context.Reference("Logger", { * defaultValue: () => ({ log: (msg: string) => console.log(msg) }) @@ -1017,11 +1505,15 @@ export const get: { * const context = Context.empty() * const logger = Context.getReferenceUnsafe(context, LoggerRef) * - * assert.deepStrictEqual(logger, { log: (msg: string) => console.log(msg) }) + * console.log(typeof logger.log) // "function" * ``` * - * @since 4.0.0 + * @see {@link getUnsafe} for unsafe access with any service key + * @see {@link get} for type-checked reference-aware access + * @see {@link getOption} for optional access to non-reference keys + * * @category unsafe + * @since 4.0.0 */ export const getReferenceUnsafe = (self: Context, service: Reference): S => { if (!self.mapUnsafe.has(service.key)) { @@ -1061,16 +1553,23 @@ const serviceNotFoundError = (service: Key) => { } /** - * Get the value associated with the specified key from the context wrapped in - * an `Option` object. If the key is not found, the `Option` object will be - * `None`. + * Gets the service for a key safely wrapped in an `Option`. + * + * **When to use** + * + * Use when you need to read a `Context` service as an `Option` so absence is + * represented as data. + * + * **Details** * - * @param self - The `Context` to search for the service. - * @param service - The `Service` of the service to retrieve. + * Returns `Option.some` when the service is stored in the context. If the key + * is a `Context.Reference` and no override is stored, returns `Option.some` of + * the cached default value. Missing non-reference keys return `Option.none`. + * + * **Example** (Getting optional services) * - * @example * ```ts - * import { Option, Context } from "effect" + * import { Context, Option } from "effect" * import * as assert from "node:assert" * * const Port = Context.Service<{ PORT: number }>("Port") @@ -1085,21 +1584,30 @@ const serviceNotFoundError = (service: Key) => { * assert.deepStrictEqual(Context.getOption(context, Timeout), Option.none()) * ``` * - * @since 4.0.0 - * @category Getters + * @see {@link getOrElse} for returning a fallback value directly + * + * @category getters + * @since 2.0.0 */ export const getOption: { /** - * Get the value associated with the specified key from the context wrapped in - * an `Option` object. If the key is not found, the `Option` object will be - * `None`. + * Gets the service for a key safely wrapped in an `Option`. + * + * **When to use** + * + * Use when you need to read a `Context` service as an `Option` so absence is + * represented as data. * - * @param self - The `Context` to search for the service. - * @param service - The `Service` of the service to retrieve. + * **Details** + * + * Returns `Option.some` when the service is stored in the context. If the key + * is a `Context.Reference` and no override is stored, returns `Option.some` of + * the cached default value. Missing non-reference keys return `Option.none`. + * + * **Example** (Getting optional services) * - * @example * ```ts - * import { Option, Context } from "effect" + * import { Context, Option } from "effect" * import * as assert from "node:assert" * * const Port = Context.Service<{ PORT: number }>("Port") @@ -1114,21 +1622,30 @@ export const getOption: { * assert.deepStrictEqual(Context.getOption(context, Timeout), Option.none()) * ``` * - * @since 4.0.0 - * @category Getters + * @see {@link getOrElse} for returning a fallback value directly + * + * @category getters + * @since 2.0.0 */ (service: Key): (self: Context) => Option.Option /** - * Get the value associated with the specified key from the context wrapped in - * an `Option` object. If the key is not found, the `Option` object will be - * `None`. + * Gets the service for a key safely wrapped in an `Option`. + * + * **When to use** + * + * Use when you need to read a `Context` service as an `Option` so absence is + * represented as data. * - * @param self - The `Context` to search for the service. - * @param service - The `Service` of the service to retrieve. + * **Details** + * + * Returns `Option.some` when the service is stored in the context. If the key + * is a `Context.Reference` and no override is stored, returns `Option.some` of + * the cached default value. Missing non-reference keys return `Option.none`. + * + * **Example** (Getting optional services) * - * @example * ```ts - * import { Option, Context } from "effect" + * import { Context, Option } from "effect" * import * as assert from "node:assert" * * const Port = Context.Service<{ PORT: number }>("Port") @@ -1143,8 +1660,10 @@ export const getOption: { * assert.deepStrictEqual(Context.getOption(context, Timeout), Option.none()) * ``` * - * @since 4.0.0 - * @category Getters + * @see {@link getOrElse} for returning a fallback value directly + * + * @category getters + * @since 2.0.0 */ (self: Context, service: Key): Option.Option } = dual(2, (self: Context, service: Key): Option.Option => { @@ -1155,12 +1674,19 @@ export const getOption: { }) /** - * Merges two `Context`s, returning a new `Context` containing the services of both. + * Merges two `Context`s into one. + * + * **When to use** * - * @param self - The first `Context` to merge. - * @param that - The second `Context` to merge. + * Use when you need to combine two contexts. + * + * **Details** + * + * When both contexts contain the same service key, the service from `that` + * overrides the service from `self`. + * + * **Example** (Merging two contexts) * - * @example * ```ts * import { Context } from "effect" * import * as assert from "node:assert" @@ -1177,17 +1703,26 @@ export const getOption: { * assert.deepStrictEqual(Context.get(context, Timeout), { TIMEOUT: 5000 }) * ``` * - * @since 4.0.0 - * @category Utils + * @see {@link mergeAll} for merging more than two contexts at once + * + * @category combining + * @since 2.0.0 */ export const merge: { /** - * Merges two `Context`s, returning a new `Context` containing the services of both. + * Merges two `Context`s into one. + * + * **When to use** + * + * Use when you need to combine two contexts. + * + * **Details** + * + * When both contexts contain the same service key, the service from `that` + * overrides the service from `self`. * - * @param self - The first `Context` to merge. - * @param that - The second `Context` to merge. + * **Example** (Merging two contexts) * - * @example * ```ts * import { Context } from "effect" * import * as assert from "node:assert" @@ -1204,17 +1739,26 @@ export const merge: { * assert.deepStrictEqual(Context.get(context, Timeout), { TIMEOUT: 5000 }) * ``` * - * @since 4.0.0 - * @category Utils + * @see {@link mergeAll} for merging more than two contexts at once + * + * @category combining + * @since 2.0.0 */ (that: Context): (self: Context) => Context /** - * Merges two `Context`s, returning a new `Context` containing the services of both. + * Merges two `Context`s into one. + * + * **When to use** + * + * Use when you need to combine two contexts. + * + * **Details** + * + * When both contexts contain the same service key, the service from `that` + * overrides the service from `self`. * - * @param self - The first `Context` to merge. - * @param that - The second `Context` to merge. + * **Example** (Merging two contexts) * - * @example * ```ts * import { Context } from "effect" * import * as assert from "node:assert" @@ -1231,8 +1775,10 @@ export const merge: { * assert.deepStrictEqual(Context.get(context, Timeout), { TIMEOUT: 5000 }) * ``` * - * @since 4.0.0 - * @category Utils + * @see {@link mergeAll} for merging more than two contexts at once + * + * @category combining + * @since 2.0.0 */ (self: Context, that: Context): Context } = dual(2, (self: Context, that: Context): Context => { @@ -1244,9 +1790,19 @@ export const merge: { }) /** - * Merges any number of `Context`s, returning a new `Context` containing the services of all. + * Merges any number of `Context`s into one. + * + * **When to use** + * + * Use when you need to combine a variadic list of contexts. + * + * **Details** + * + * When multiple contexts contain the same service key, the service from the + * last context with that key is kept. + * + * **Example** (Merging multiple contexts) * - * @example * ```ts * import { Context } from "effect" * import * as assert from "node:assert" @@ -1270,6 +1826,9 @@ export const merge: { * assert.deepStrictEqual(Context.get(context, Host), { HOST: "localhost" }) * ``` * + * @see {@link merge} for merging two contexts + * + * @category combining * @since 3.12.0 */ export const mergeAll = >( @@ -1287,12 +1846,14 @@ export const mergeAll = >( /** * Returns a new `Context` that contains only the specified services. * - * @param self - The `Context` to prune services from. - * @param services - The list of `Service`s to be included in the new `Context`. + * **When to use** + * + * Use when you want to keep an allowlist of services in a `Context`. + * + * **Example** (Picking services from a context) * - * @example * ```ts - * import { Option, pipe, Context } from "effect" + * import { Context, Option, pipe } from "effect" * import * as assert from "node:assert" * * const Port = Context.Service<{ PORT: number }>("Port") @@ -1312,8 +1873,10 @@ export const mergeAll = >( * assert.deepStrictEqual(Context.getOption(context, Timeout), Option.none()) * ``` * - * @since 4.0.0 - * @category Utils + * @see {@link omit} for removing selected services + * + * @category filtering + * @since 2.0.0 */ export const pick = >>( ...services: S @@ -1328,9 +1891,16 @@ export const pick = >>( }) /** - * @example + * Returns a new `Context` with the specified service keys removed. + * + * **When to use** + * + * Use when you want to remove a denylist of services from a `Context`. + * + * **Example** (Omitting services from a context) + * * ```ts - * import { Option, pipe, Context } from "effect" + * import { Context, Option, pipe } from "effect" * import * as assert from "node:assert" * * const Port = Context.Service<{ PORT: number }>("Port") @@ -1350,8 +1920,10 @@ export const pick = >>( * assert.deepStrictEqual(Context.getOption(context, Timeout), Option.none()) * ``` * - * @since 4.0.0 - * @category Utils + * @see {@link pick} for keeping selected services + * + * @category filtering + * @since 2.0.0 */ export const omit = >>( ...keys: S @@ -1364,38 +1936,82 @@ export const omit = >>( }) /** - * Perform a series of mutations on a `Context`. Prevents unnecessary copying + * Performs a series of mutations on a `Context`. Prevents unnecessary copying * of the underlying map when multiple mutations are needed. * + * **When to use** + * + * Use to apply several `Context` transformations in one callback while copying + * the underlying service map only once. + * + * @see {@link add} for adding or replacing a service + * @see {@link addOrOmit} for adding or removing a service from an `Option` + * @see {@link merge} for combining two contexts + * @see {@link pick} for keeping selected services + * @see {@link omit} for removing selected services + * + * @category mutations * @since 4.0.0 - * @category Utils */ export const mutate: { /** - * Perform a series of mutations on a `Context`. Prevents unnecessary copying + * Performs a series of mutations on a `Context`. Prevents unnecessary copying * of the underlying map when multiple mutations are needed. * + * **When to use** + * + * Use to apply several `Context` transformations in one callback while copying + * the underlying service map only once. + * + * @see {@link add} for adding or replacing a service + * @see {@link addOrOmit} for adding or removing a service from an `Option` + * @see {@link merge} for combining two contexts + * @see {@link pick} for keeping selected services + * @see {@link omit} for removing selected services + * + * @category mutations * @since 4.0.0 - * @category Utils */ (f: (context: Context) => Context): (self: Context) => Context /** - * Perform a series of mutations on a `Context`. Prevents unnecessary copying + * Performs a series of mutations on a `Context`. Prevents unnecessary copying * of the underlying map when multiple mutations are needed. * + * **When to use** + * + * Use to apply several `Context` transformations in one callback while copying + * the underlying service map only once. + * + * @see {@link add} for adding or replacing a service + * @see {@link addOrOmit} for adding or removing a service from an `Option` + * @see {@link merge} for combining two contexts + * @see {@link pick} for keeping selected services + * @see {@link omit} for removing selected services + * + * @category mutations * @since 4.0.0 - * @category Utils */ (self: Context, f: (context: Context) => Context): Context } = dual( 2, (self: Context, f: (context: Context) => Context): Context => { const next = makeUnsafe(new Map(self.mapUnsafe)) next.mutable = true @@ -1418,14 +2034,21 @@ const withMapUnsafe = (self: Context, f: (map: Map(self: Context, f: (map: Map( key: string, diff --git a/.opencode/node_modules/effect/src/Cron.ts b/.opencode/node_modules/effect/src/Cron.ts index 97075f10283d6127f8ad8a1df328070f0e7d6e58..9f3e84382caf6e4b8dd3d10d61ac0d6e34647f47 100644 --- a/.opencode/node_modules/effect/src/Cron.ts +++ b/.opencode/node_modules/effect/src/Cron.ts @@ -1,4 +1,10 @@ /** + * Utilities for recurring calendar schedules written as cron expressions or + * explicit field constraints. A `Cron` value stores allowed seconds, minutes, + * hours, days of month, months, weekdays, and an optional time zone. The module + * can create or parse schedules, compare them, test whether a date matches, and + * find previous or next scheduled occurrences. + * * @since 2.0.0 */ import * as Arr from "./Array.ts" @@ -24,11 +30,19 @@ const TypeId = "~effect/time/Cron" /** * Represents a cron schedule with time constraints and timezone information. * - * A Cron instance defines when a scheduled task should run, supporting - * seconds, minutes, hours, days, months, and weekdays constraints. - * It also supports timezone-aware scheduling. + * **When to use** + * + * Use to represent a recurring calendar schedule that can be matched against + * dates or used to compute scheduled occurrences. + * + * **Details** + * + * A `Cron` instance defines when a scheduled task should run, supporting + * seconds, minutes, hours, days, months, and weekday constraints. It also + * supports timezone-aware scheduling. + * + * **Example** (Creating a cron schedule) * - * @example * ```ts * import { Cron } from "effect" * @@ -78,8 +92,13 @@ const TypeId = "~effect/time/Cron" * console.log(matches) // true if it's 9 AM on a weekday * ``` * - * @since 2.0.0 + * @see {@link make} for creating a schedule from explicit field constraints + * @see {@link parse} for creating a schedule from a cron expression string + * @see {@link match} for testing a date against a schedule + * @see {@link next} for finding the next scheduled occurrence + * * @category models + * @since 2.0.0 */ export interface Cron extends Pipeable, Equal.Equal, Inspectable { readonly [TypeId]: typeof TypeId @@ -184,13 +203,20 @@ const CronProto = { } /** - * Checks if a given value is a Cron instance. + * Checks whether a given value is a Cron instance. + * + * **When to use** + * + * Use to narrow an unknown value before treating it as a `Cron` schedule. + * + * **Details** * * This function is a type guard that determines whether the provided * value is a valid Cron instance by checking for the presence of the * Cron type identifier. * - * @example + * **Example** (Checking cron values) + * * ```ts * import { Cron } from "effect" * @@ -207,19 +233,29 @@ const CronProto = { * console.log(Cron.isCron("not a cron")) // false * ``` * - * @since 2.0.0 + * @see {@link make} for constructing a `Cron` value directly + * @see {@link parse} for constructing a `Cron` value from a string + * * @category guards + * @since 2.0.0 */ export const isCron = (u: unknown): u is Cron => hasProperty(u, TypeId) /** * Creates a Cron instance from time constraints. * + * **When to use** + * + * Use to build a cron schedule from explicit sets of allowed time-field values. + * + * **Details** + * * Constructs a cron schedule by specifying which seconds, minutes, hours, * days, months, and weekdays the schedule should match. Empty arrays mean * "match all" for that time unit. * - * @example + * **Example** (Creating schedules from constraints) + * * ```ts * import { Cron } from "effect" * @@ -306,8 +342,10 @@ export const isCron = (u: unknown): u is Cron => hasProperty(u, TypeId) * }) * ``` * - * @since 2.0.0 + * @see {@link parse} for building a schedule from a cron expression string + * * @category constructors + * @since 2.0.0 */ export const make = (values: { readonly seconds?: Iterable | undefined @@ -411,11 +449,17 @@ const CronParseErrorTypeId = "~effect/time/Cron/CronParseError" /** * Represents an error that occurs when parsing a cron expression fails. * - * This error provides detailed information about what went wrong during - * the parsing process, including the error message and optionally the - * input that caused the error. + * **When to use** + * + * Use to handle invalid cron expression failures returned by `parse`. + * + * **Details** + * + * This error provides information about what went wrong during parsing, + * including the error message and optionally the input that caused the error. + * + * **Example** (Handling cron parse failures) * - * @example * ```ts * import { Cron, Result } from "effect" * @@ -427,8 +471,11 @@ const CronParseErrorTypeId = "~effect/time/Cron/CronParseError" * } * ``` * - * @since 4.0.0 + * @see {@link parse} for the parser that returns this error in `Result.fail` + * @see {@link isCronParseError} for narrowing unknown values to this error type + * * @category models + * @since 4.0.0 */ export class CronParseError extends Data.TaggedError("CronParseError")<{ readonly message: string @@ -438,13 +485,20 @@ export class CronParseError extends Data.TaggedError("CronParseError")<{ } /** - * Checks if a given value is a CronParseError instance. + * Checks whether a given value is a CronParseError instance. + * + * **When to use** + * + * Use to narrow an unknown failure before handling it as a cron parse error. + * + * **Details** * * This function is a type guard that determines whether the provided * value is a CronParseError by checking for the presence of the * CronParseError type identifier. * - * @example + * **Example** (Checking cron parse errors) + * * ```ts * import { Cron, Result } from "effect" * @@ -458,17 +512,32 @@ export class CronParseError extends Data.TaggedError("CronParseError")<{ * console.log(Cron.isCronParseError("not an error")) // false * ``` * - * @since 2.0.0 + * @see {@link CronParseError} for the parse error type + * @see {@link parse} for producing `CronParseError` values on invalid input + * * @category guards + * @since 4.0.0 */ export const isCronParseError = (u: unknown): u is CronParseError => hasProperty(u, CronParseErrorTypeId) /** - * Parses a cron expression into a `Cron` instance. + * Parses a cron expression safely into a `Cron` instance, returning a `Result` + * instead of throwing. + * + * **When to use** + * + * Use to parse cron expressions from configuration or user input while handling + * invalid input as a `Result`. * - * @param cron - The cron expression to parse. + * **Details** + * + * The expression may contain five fields, where seconds default to `0`, or six + * fields including seconds. Fields support `*`, comma-separated values, ranges, + * steps, and month or weekday aliases. Invalid expressions fail with + * `CronParseError`. + * + * **Example** (Parsing cron expressions) * - * @example * ```ts * import { Cron, Result } from "effect" * import * as assert from "node:assert" @@ -487,8 +556,11 @@ export const isCronParseError = (u: unknown): u is CronParseError => hasProperty * ) * ``` * - * @since 2.0.0 + * @see {@link parseUnsafe} for throwing on invalid cron expressions + * @see {@link make} for constructing a schedule from explicit field constraints + * * @category constructors + * @since 2.0.0 */ export const parse = (cron: string, tz?: DateTime.TimeZone | string): Result.Result => { const segments = cron.split(" ").filter(String.isNonEmpty) @@ -520,13 +592,15 @@ export const parse = (cron: string, tz?: DateTime.TimeZone | string): Result.Res } /** - * Parses a cron expression into a Cron instance, throwing on failure. + * Parses a cron expression into a `Cron` instance, throwing on failure. + * + * **When to use** * - * This function provides a convenience method for parsing cron expressions - * when you're confident the input is valid and want to avoid handling - * the Result type. + * Use when you expect the input to be valid and want to avoid handling the + * `Result` type. + * + * **Example** (Parsing cron expressions unsafely) * - * @example * ```ts * import { Cron } from "effect" * @@ -540,19 +614,27 @@ export const parse = (cron: string, tz?: DateTime.TimeZone | string): Result.Res * // const invalid = Cron.parseUnsafe("invalid expression") * ``` * - * @since 2.0.0 * @category constructors + * @since 4.0.0 */ export const parseUnsafe = (cron: string, tz?: DateTime.TimeZone | string): Cron => Result.getOrThrow(parse(cron, tz)) /** - * Checks if a given date/time falls within an active Cron time window. + * Returns `true` when a date/time matches a `Cron` schedule. + * + * **When to use** + * + * Use to test whether a specific date/time satisfies a cron schedule. + * + * **Details** * - * This function determines whether a specific date and time matches - * the cron schedule, taking into account all time constraints and - * the optional timezone. + * Seconds, minutes, hours, months, and the optional timezone are checked + * directly. For day constraints, an empty `days` or `weekdays` set means that + * field matches every value; when both sets are non-empty, a date matches if + * either the day-of-month or weekday matches. + * + * **Example** (Matching dates against a schedule) * - * @example * ```ts * import { Cron, Result } from "effect" * @@ -569,8 +651,11 @@ export const parseUnsafe = (cron: string, tz?: DateTime.TimeZone | string): Cron * console.log(matches3) // false - wrong day * ``` * + * @see {@link next} for finding the next matching date/time + * @see {@link prev} for finding the previous matching date/time + * + * @category predicates * @since 2.0.0 - * @category utils */ export const match = (cron: Cron, date: DateTime.DateTime.Input): boolean => { const parts = dateTime.makeZonedUnsafe(date, { @@ -614,11 +699,19 @@ const daysInMonth = (date: Date): number => /** * Returns the next scheduled date/time for the given Cron instance. * - * This function calculates the next date and time when the cron schedule - * should trigger, starting from the specified date (or current time if - * not provided). + * **When to use** + * + * Use to find the next occurrence of a cron schedule after a specific date/time + * or after the current time. + * + * **Details** + * + * Searches for the next date and time when the cron schedule should trigger, + * starting after the specified date/time or after the current time when no + * date is provided. + * + * **Example** (Finding the next occurrence) * - * @example * ```ts * import { Cron, Result } from "effect" * @@ -634,8 +727,11 @@ const daysInMonth = (date: Date): number => * console.log(nextFromNow) // Next occurrence from now * ``` * + * @see {@link prev} for finding the previous scheduled occurrence + * @see {@link sequence} for iterating future scheduled occurrences + * + * @category getters * @since 2.0.0 - * @category utils */ export const next = (cron: Cron, now?: DateTime.DateTime.Input): Date => { return stepCron(cron, now, "next") @@ -644,8 +740,24 @@ export const next = (cron: Cron, now?: DateTime.DateTime.Input): Date => { /** * Returns the previous scheduled date/time for the given Cron instance. * - * @since 4.0.0 - * @category utils + * **When to use** + * + * Use to find the most recent occurrence of a cron schedule before a specific + * date/time or before the current time. + * + * **Details** + * + * When no date/time is provided, the search starts from the current time. + * + * **Gotchas** + * + * The search is strict: if the supplied date/time already matches the schedule, + * the result is the earlier occurrence. + * + * @see {@link next} for finding the next scheduled occurrence + * + * @category getters + * @since 3.20.0 */ export const prev = (cron: Cron, now?: DateTime.DateTime.Input): Date => { return stepCron(cron, now, "prev") @@ -808,11 +920,18 @@ const stepCron = (cron: Cron, now: DateTime.DateTime.Input | undefined, directio /** * Returns an infinite iterator that yields dates matching the Cron schedule. * - * This function creates an iterator that generates an infinite sequence - * of dates when the cron schedule should trigger, starting from the - * specified date. + * **When to use** + * + * Use to lazily iterate future occurrences of a cron schedule. + * + * **Details** + * + * The iterator generates an infinite sequence of dates when the cron schedule + * should trigger, starting after the specified date/time or after the current + * time when no date is provided. + * + * **Example** (Iterating scheduled occurrences) * - * @example * ```ts * import { Cron, Result } from "effect" * @@ -826,8 +945,10 @@ const stepCron = (cron: Cron, now: DateTime.DateTime.Input | undefined, directio * // [Mon Jan 02 2023 09:00:00, Tue Jan 03 2023 09:00:00, ...] * ``` * + * @see {@link next} for computing one next occurrence + * + * @category sequencing * @since 2.0.0 - * @category utils */ export const sequence = function*(cron: Cron, now?: DateTime.DateTime.Input): IterableIterator { while (true) { @@ -836,13 +957,21 @@ export const sequence = function*(cron: Cron, now?: DateTime.DateTime.Input): It } /** - * An Equivalence instance for comparing Cron schedules. + * Equivalence instance for comparing the field restrictions of two `Cron` + * schedules. + * + * **When to use** + * + * Use to compare cron schedules through APIs that accept an equivalence + * relation. + * + * **Details** + * + * This comparison checks seconds, minutes, hours, days, months, and weekdays. + * It does not compare the optional timezone. * - * This equivalence compares two Cron instances by checking if their - * time constraints (seconds, minutes, hours, days, months, weekdays) - * are equivalent, regardless of the internal order. + * **Example** (Comparing schedules with equivalence) * - * @example * ```ts * import { Cron } from "effect" * @@ -865,8 +994,10 @@ export const sequence = function*(cron: Cron, now?: DateTime.DateTime.Input): It * console.log(Cron.Equivalence(cron1, cron2)) // true * ``` * - * @since 2.0.0 + * @see {@link equals} for directly comparing two `Cron` values + * * @category instances + * @since 2.0.0 */ export const Equivalence: Equ.Equivalence = Equ.make((self, that) => restrictionsEquals(self.seconds, that.seconds) && @@ -882,12 +1013,20 @@ const restrictionsEquals = (self: ReadonlySet, that: ReadonlySet restrictionsArrayEquals(Arr.fromIterable(self), Arr.fromIterable(that)) /** - * Checks if two Cron instances are equal. + * Checks whether two `Cron` instances have the same field restrictions. + * + * **When to use** + * + * Use to directly compare whether two cron schedules have the same field + * restrictions. + * + * **Details** * - * This function compares two Cron instances to determine if they represent - * the same schedule by checking all their time constraints for equality. + * The comparison checks seconds, minutes, hours, days, months, and weekdays. + * It does not compare the optional timezone. + * + * **Example** (Checking schedule equality) * - * @example * ```ts * import { Cron } from "effect" * @@ -911,17 +1050,27 @@ const restrictionsEquals = (self: ReadonlySet, that: ReadonlySet * console.log(Cron.equals(cron1)(cron2)) // true (curried form) * ``` * - * @since 2.0.0 + * @see {@link Equivalence} for the reusable equivalence instance + * * @category predicates + * @since 2.0.0 */ export const equals: { /** - * Checks if two Cron instances are equal. + * Checks whether two `Cron` instances have the same field restrictions. + * + * **When to use** + * + * Use to directly compare whether two cron schedules have the same field + * restrictions. * - * This function compares two Cron instances to determine if they represent - * the same schedule by checking all their time constraints for equality. + * **Details** + * + * The comparison checks seconds, minutes, hours, days, months, and weekdays. + * It does not compare the optional timezone. + * + * **Example** (Checking schedule equality) * - * @example * ```ts * import { Cron } from "effect" * @@ -945,17 +1094,27 @@ export const equals: { * console.log(Cron.equals(cron1)(cron2)) // true (curried form) * ``` * - * @since 2.0.0 + * @see {@link Equivalence} for the reusable equivalence instance + * * @category predicates + * @since 2.0.0 */ (that: Cron): (self: Cron) => boolean /** - * Checks if two Cron instances are equal. + * Checks whether two `Cron` instances have the same field restrictions. + * + * **When to use** * - * This function compares two Cron instances to determine if they represent - * the same schedule by checking all their time constraints for equality. + * Use to directly compare whether two cron schedules have the same field + * restrictions. + * + * **Details** + * + * The comparison checks seconds, minutes, hours, days, months, and weekdays. + * It does not compare the optional timezone. + * + * **Example** (Checking schedule equality) * - * @example * ```ts * import { Cron } from "effect" * @@ -979,8 +1138,10 @@ export const equals: { * console.log(Cron.equals(cron1)(cron2)) // true (curried form) * ``` * - * @since 2.0.0 + * @see {@link Equivalence} for the reusable equivalence instance + * * @category predicates + * @since 2.0.0 */ (self: Cron, that: Cron): boolean } = dual(2, (self: Cron, that: Cron): boolean => Equivalence(self, that)) diff --git a/.opencode/node_modules/effect/src/Crypto.ts b/.opencode/node_modules/effect/src/Crypto.ts new file mode 100644 index 0000000000000000000000000000000000000000..d3cdc018b2e185bc6691fef418e9f844b090ea6c --- /dev/null +++ b/.opencode/node_modules/effect/src/Crypto.ts @@ -0,0 +1,318 @@ +/** + * Defines a platform-independent service for cryptographic operations. + * + * Runtime packages provide concrete implementations backed by the host + * platform's cryptography APIs. This module defines the service interface and a + * constructor from random-byte and digest primitives. The service provides + * secure random bytes and numbers, UUIDv4 and UUIDv7 generation, shuffling, and + * SHA message digests. + * + * @since 4.0.0 + */ +import * as Context from "./Context.ts" +import * as Effect from "./Effect.ts" +import * as PlatformError from "./PlatformError.ts" + +const TypeId = "~effect/platform/Crypto" + +/** + * Digest algorithms supported by the platform `Crypto` service. + * + * **Gotchas** + * + * SHA-1 is included for interoperability with existing protocols. Do not use + * SHA-1 for new security-sensitive designs. + * + * **Example** (Using a digest algorithm) + * + * ```ts + * import { Crypto } from "effect" + * + * const algorithm: Crypto.DigestAlgorithm = "SHA-256" + * ``` + * + * @category models + * @since 4.0.0 + */ +export type DigestAlgorithm = "SHA-1" | "SHA-256" | "SHA-384" | "SHA-512" + +/** + * Platform-agnostic cryptographic operations. + * + * **Details** + * + * `Crypto` implementations must use cryptographically secure platform APIs. + * The random generator helpers are derived by the `make` constructor from + * the random methods on this service. + * + * **Example** (Using cryptographic operations) + * + * ```ts + * import { Crypto, Effect, Layer } from "effect" + * + * const TestCrypto = Layer.succeed( + * Crypto.Crypto, + * Crypto.make({ + * randomBytes: (size) => new Uint8Array(size), + * digest: (_algorithm, data) => Effect.succeed(data) + * }) + * ) + * + * const program = Effect.gen(function*() { + * const crypto = yield* Crypto.Crypto + * const bytes = yield* crypto.randomBytes(16) + * const uuidv4 = yield* crypto.randomUUIDv4 + * const uuidv7 = yield* crypto.randomUUIDv7 + * const hash = yield* crypto.digest("SHA-256", bytes) + * return { uuidv4, uuidv7, hash } + * }) + * + * Effect.runPromise(Effect.provide(program, TestCrypto)) + * ``` + * + * @category models + * @since 4.0.0 + */ +export interface Crypto { + readonly [TypeId]: typeof TypeId + + /** + * Generates a random integer in the range Number.MIN_SAFE_INTEGER to + * Number.MAX_SAFE_INTEGER (both inclusive). + */ + nextIntUnsafe(): number + + /** + * Generates a random number in the range 0 (inclusive) to 1 (exclusive). + */ + nextDoubleUnsafe(): number + + /** + * Generates cryptographically secure random bytes. + */ + randomBytes(size: number): Effect.Effect + + /** + * Computes a cryptographic digest for the supplied data. + */ + digest( + algorithm: DigestAlgorithm, + data: Uint8Array + ): Effect.Effect + + /** + * Generates a cryptographically secure random number between 0 (inclusive) + * and 1 (exclusive). + */ + readonly random: Effect.Effect + + /** + * Generates a cryptographically secure random boolean. + */ + readonly randomBoolean: Effect.Effect + + /** + * Generates a cryptographically secure random integer between + * `Number.MIN_SAFE_INTEGER` and `Number.MAX_SAFE_INTEGER` (both inclusive). + */ + readonly randomInt: Effect.Effect + + /** + * Generates a cryptographically secure random number between `min` + * (inclusive) and `max` (exclusive). + */ + randomBetween(min: number, max: number): Effect.Effect + + /** + * Generates a cryptographically secure random integer between `min` and `max`. + * + * **Details** + * + * The lower bound is rounded up with `Math.ceil` and the upper bound is + * rounded down with `Math.floor`. By default the range is inclusive; set + * `options.halfOpen: true` to exclude the upper bound. + */ + randomIntBetween(min: number, max: number, options?: { + readonly halfOpen?: boolean | undefined + }): Effect.Effect + + /** + * Uses the cryptographically secure random generator to shuffle the supplied + * iterable. + */ + randomShuffle(elements: Iterable): Effect.Effect> + + /** + * Generates a cryptographically secure UUIDv4 string. + */ + readonly randomUUIDv4: Effect.Effect + + /** + * Generates a cryptographically secure UUIDv7 string. + */ + readonly randomUUIDv7: Effect.Effect +} + +/** + * Service tag for platform cryptography. + * + * **When to use** + * + * Use when you need to provide or retrieve the full platform cryptography + * service from an effect's context. + * + * **Details** + * + * Providing this service supplies platform-agnostic cryptographic operations + * such as hashing, UUID generation, and secure random values. + * + * @see {@link make} for constructing a Crypto service from primitive operations + * + * @category services + * @since 4.0.0 + */ +export const Crypto: Context.Service = Context.Service("effect/Crypto") + +/** + * Creates a `Crypto` service from the primitive implementation, deriving the + * random generator helpers and UUID generation from those primitives. + * + * **When to use** + * + * Use to build a Crypto service for a platform integration, test layer, or + * custom runtime from primitive random-byte and digest operations. + * + * **Details** + * + * The constructor derives random numbers, booleans, integer ranges, shuffling, + * and UUID generation from `impl.randomBytes`. Digest operations delegate to + * `impl.digest`. + * + * **Gotchas** + * + * `impl.randomBytes` must return cryptographically secure bytes of the + * requested length. UUID formatting mutates the byte array returned for UUID + * generation, so the implementation should return a fresh array for each call. + * + * **Example** (Creating a Crypto service) + * + * ```ts + * import { Crypto, Effect, Layer } from "effect" + * + * const TestCrypto = Layer.succeed( + * Crypto.Crypto, + * Crypto.make({ + * randomBytes: (size) => new Uint8Array(size), + * digest: (_algorithm, data) => Effect.succeed(data) + * }) + * ) + * ``` + * + * @category constructors + * @since 4.0.0 + */ +export const make = ( + impl: { + readonly randomBytes: (size: number) => Uint8Array + readonly digest: ( + algorithm: DigestAlgorithm, + data: Uint8Array + ) => Effect.Effect + } +): Crypto => { + const randomBytesUnsafe = impl.randomBytes + + const randomBytes: Crypto["randomBytes"] = (size) => Effect.map(validateSize("randomBytes", size), randomBytesUnsafe) + + const nextDoubleUnsafe = (): number => { + const bytes = randomBytesUnsafe(7) + const value = ((bytes[0] & 0x1f) * 2 ** 48) + (bytes[1] * 2 ** 40) + (bytes[2] * 2 ** 32) + + (bytes[3] * 2 ** 24) + (bytes[4] * 2 ** 16) + (bytes[5] * 2 ** 8) + bytes[6] + return value / 2 ** 53 + } + + const nextIntUnsafe = (): number => + Math.floor(nextDoubleUnsafe() * (Number.MAX_SAFE_INTEGER - Number.MIN_SAFE_INTEGER + 1)) + Number.MIN_SAFE_INTEGER + + return Crypto.of({ + [TypeId]: TypeId, + randomBytes, + nextDoubleUnsafe, + nextIntUnsafe, + digest: impl.digest, + random: Effect.sync(() => nextDoubleUnsafe()), + randomBoolean: Effect.sync(() => nextDoubleUnsafe() > 0.5), + randomInt: Effect.sync(() => nextIntUnsafe()), + randomBetween: (min, max) => Effect.sync(() => nextDoubleUnsafe() * (max - min) + min), + randomIntBetween(min, max, options) { + const extra = options?.halfOpen === true ? 0 : 1 + return Effect.sync(() => { + const minInt = Math.ceil(min) + const maxInt = Math.floor(max) + return Math.floor(nextDoubleUnsafe() * (maxInt - minInt + extra)) + minInt + }) + }, + randomShuffle: (elements) => + Effect.sync(() => { + const buffer = Array.from(elements) + for (let i = buffer.length - 1; i >= 1; i = i - 1) { + const index = Math.min(i, Math.floor(nextDoubleUnsafe() * (i + 1))) + const value = buffer[i]! + buffer[i] = buffer[index]! + buffer[index] = value + } + return buffer + }), + randomUUIDv4: Effect.sync(() => formatUUIDv4(randomBytesUnsafe(16))), + randomUUIDv7: Effect.clockWith((clock) => + Effect.succeed(formatUUIDv7(clock.currentTimeMillisUnsafe(), randomBytesUnsafe(16))) + ) + }) +} + +const validateSize = (method: string, size: number): Effect.Effect => + Number.isSafeInteger(size) && size >= 0 + ? Effect.succeed(size) + : Effect.fail(PlatformError.badArgument({ + module: "Crypto", + method, + description: "size must be a non-negative safe integer" + })) + +const hex = (byte: number): string => byte.toString(16).padStart(2, "0") + +const formatUUID = (bytes: Uint8Array): string => { + const segments = [ + bytes.subarray(0, 4), + bytes.subarray(4, 6), + bytes.subarray(6, 8), + bytes.subarray(8, 10), + bytes.subarray(10, 16) + ] + + return segments.map((segment) => Array.from(segment, hex).join("")).join("-") +} + +const formatUUIDv4 = (bytes: Uint8Array): string => { + bytes[6] = (bytes[6] & 0x0f) | 0x40 + bytes[8] = (bytes[8] & 0x3f) | 0x80 + + return formatUUID(bytes) +} + +const maxUUIDv7Timestamp = 2 ** 48 - 1 + +const formatUUIDv7 = (timestampMillis: number, bytes: Uint8Array): string => { + const timestamp = Math.min(Math.max(0, Math.trunc(timestampMillis)), maxUUIDv7Timestamp) + + bytes[0] = Math.floor(timestamp / 2 ** 40) + bytes[1] = Math.floor(timestamp / 2 ** 32) & 0xff + bytes[2] = Math.floor(timestamp / 2 ** 24) & 0xff + bytes[3] = Math.floor(timestamp / 2 ** 16) & 0xff + bytes[4] = Math.floor(timestamp / 2 ** 8) & 0xff + bytes[5] = timestamp & 0xff + bytes[6] = (bytes[6] & 0x0f) | 0x70 + bytes[8] = (bytes[8] & 0x3f) | 0x80 + + return formatUUID(bytes) +} diff --git a/.opencode/node_modules/effect/src/Data.ts b/.opencode/node_modules/effect/src/Data.ts index 991caea94bc2973142914b45ae76ddc407a70b89..706997a4360076bb74e1258c8d21927d834a5404 100644 --- a/.opencode/node_modules/effect/src/Data.ts +++ b/.opencode/node_modules/effect/src/Data.ts @@ -1,73 +1,10 @@ /** - * Immutable data constructors with discriminated-union support. - * - * The `Data` module provides base classes and factory functions for creating - * immutable value types with a `_tag` field for discriminated unions. - * It is the recommended way to define domain models, error types, and - * lightweight ADTs in Effect applications. - * - * ## Mental model - * - * - **`Class`** — base class for plain immutable data. Extend it with a type - * parameter to declare the fields. Instances are `Pipeable`. - * - **`TaggedClass`** — like `Class` but automatically adds a `readonly _tag` - * string literal field. Useful for single-variant types or ad-hoc tagged - * values. - * - **`TaggedEnum`** (type) + **`taggedEnum`** (value) — define a multi-variant - * discriminated union from a simple record. `taggedEnum()` returns per-variant - * constructors plus `$is` / `$match` helpers. - * - **`Error`** — like `Class` but extends `Cause.YieldableError`, so instances - * can be yielded inside `Effect.gen` to fail the effect. - * - **`TaggedError`** — like `TaggedClass` but extends `Cause.YieldableError`. - * Works with `Effect.catchTag` for tag-based error recovery. - * - * ## Common tasks - * - * - Define a simple value class → {@link Class} - * - Define a value class with a `_tag` → {@link TaggedClass} - * - Define a discriminated union with constructors → {@link TaggedEnum} + {@link taggedEnum} - * - Define a yieldable error → {@link Error} - * - Define a yieldable tagged error → {@link TaggedError} - * - Type-guard a tagged value → `$is` from {@link taggedEnum} - * - Pattern-match on a tagged union → `$match` from {@link taggedEnum} - * - * ## Gotchas - * - * - Variant records passed to `TaggedEnum` must **not** contain a `_tag` key; - * the `_tag` is added automatically from the record key. - * - When a class has no fields, the constructor argument is optional (`void`). - * - `taggedEnum()` creates **plain objects**, not class instances. If you need - * class-based variants, use `TaggedClass` or `TaggedError` instead. - * - `TaggedEnum.WithGenerics` supports up to 4 generic type parameters. - * - * ## Quickstart - * - * **Example** (tagged union with pattern matching) + * Defines helpers for small immutable data models. * - * ```ts - * import { Data } from "effect" - * - * type Shape = Data.TaggedEnum<{ - * Circle: { readonly radius: number } - * Rect: { readonly width: number; readonly height: number } - * }> - * const { Circle, Rect, $match } = Data.taggedEnum() - * - * const area = $match({ - * Circle: ({ radius }) => Math.PI * radius ** 2, - * Rect: ({ width, height }) => width * height - * }) - * - * console.log(area(Circle({ radius: 5 }))) - * // 78.53981633974483 - * console.log(area(Rect({ width: 3, height: 4 }))) - * // 12 - * ``` - * - * @see {@link Class} — plain immutable data class - * @see {@link TaggedEnum} — discriminated union type - * @see {@link taggedEnum} — discriminated union constructors - * @see {@link TaggedError} — yieldable tagged error class + * This module helps create plain classes, tagged classes, tagged unions, and + * typed errors with readonly fields. Tagged values carry a `_tag` field, which + * makes them easy to narrow with pattern matching or simple checks. These + * helpers are commonly used for domain values and errors in Effect programs. * * @since 2.0.0 */ @@ -79,18 +16,19 @@ import type * as Types from "./Types.ts" import type { Unify } from "./Unify.ts" /** - * Base class for immutable data types. + * Provides a base class for immutable data types. + * + * **When to use** + * + * Use when you need a lightweight immutable value type with `.pipe()` support. + * + * **Details** * * Extend `Class` with a type parameter to declare fields. The constructor * accepts those fields as a single object argument. When there are no fields - * the argument is optional. - * - * - Use when you need a lightweight immutable value type with `.pipe()` support. - * - Instances are `Readonly` and `Pipeable`. - * - If you also need a `_tag` discriminator, use {@link TaggedClass} instead. - * - If you need a yieldable error, use {@link Error} or {@link TaggedError}. + * the argument is optional. Instances are `Readonly` and `Pipeable`. * - * **Example** (defining a value class) + * **Example** (Defining a value class) * * ```ts * import { Data, Equal } from "effect" @@ -122,17 +60,19 @@ export const Class: new = {}>( } as any /** - * Base class for immutable data types with a `_tag` discriminator. + * Provides a base class for immutable data types with a `_tag` discriminator. + * + * **When to use** + * + * Use when you need a single-variant tagged type or an ad-hoc discriminator. + * + * **Details** * * Like {@link Class}, but the resulting instances also carry a * `readonly _tag: Tag` property. The `_tag` is excluded from the constructor * argument. * - * - Use when you need a single-variant tagged type or an ad-hoc discriminator. - * - For multi-variant unions, prefer {@link TaggedEnum} + {@link taggedEnum}. - * - For yieldable errors, use {@link TaggedError}. - * - * **Example** (defining a tagged class) + * **Example** (Defining a tagged class) * * ```ts * import { Data } from "effect" @@ -165,17 +105,20 @@ export const TaggedClass = ( /** * Transforms a record of variant definitions into a discriminated union type. * + * **When to use** + * + * Use when you have two or more variants that share a common `_tag` discriminator. + * + * **Details** + * * Each key in the record becomes a variant with `readonly _tag` set to that - * key. Use with {@link taggedEnum} to get runtime constructors, type guards, - * and pattern matching. + * key. Use with {@link taggedEnum} to get constructors and matchers. * - * - Use when you have two or more variants that share a common `_tag` - * discriminator. - * - Variant records must **not** include a `_tag` property — it is added - * automatically. - * - For generic tagged enums, see {@link TaggedEnum.WithGenerics}. + * **Gotchas** * - * **Example** (defining a tagged enum) + * Variant records must **not** include a `_tag` property; it is added automatically. + * + * **Example** (Defining a tagged enum) * * ```ts * import { Data } from "effect" @@ -196,7 +139,7 @@ export const TaggedClass = ( * // "BadRequest" * ``` * - * @see {@link taggedEnum} — runtime constructors for a `TaggedEnum` + * @see {@link taggedEnum} — constructors and matchers for a `TaggedEnum` * @see {@link TaggedEnum.WithGenerics} — generic tagged enums * @see {@link TaggedEnum.Constructor} — the constructor object type * @@ -223,28 +166,36 @@ type UntaggedChildren = true extends ChildrenAreTagged /** * Namespace for `TaggedEnum` utility types. * + * **When to use** + * + * Use to reference utility types for constructing, extracting, and matching + * `TaggedEnum` variants. + * + * **Details** + * * Provides helper types for: * - Generic tagged enums ({@link TaggedEnum.WithGenerics}, {@link TaggedEnum.Kind}) * - Extracting constructor arguments ({@link TaggedEnum.Args}) and variant * values ({@link TaggedEnum.Value}) * - Full constructor objects ({@link TaggedEnum.Constructor}) * - * @category types * @since 2.0.0 */ export declare namespace TaggedEnum { /** * Defines a tagged enum shape that accepts generic type parameters. * + * **When to use** + * + * Use when variant payloads need to be parameterized, such as `Result`. + * + * **Details** + * * Extend this interface and set `taggedEnum` to your union type, using * `this["A"]`, `this["B"]`, etc. as placeholders for the generics. The * `Count` parameter declares how many generics are used (up to 4). * - * - Use when variant payloads need to be parameterized (e.g., `Result`). - * - Pass the interface (not the type alias) to {@link taggedEnum} to get - * generic-aware constructors. - * - * **Example** (generic tagged enum) + * **Example** (Generic tagged enum) * * ```ts * import { Data } from "effect" @@ -265,8 +216,9 @@ export declare namespace TaggedEnum { * ``` * * @see {@link Kind} — apply concrete types to a `WithGenerics` definition - * @see {@link taggedEnum} — runtime constructors + * @see {@link taggedEnum} — constructors and matchers * + * @category models * @since 2.0.0 */ export interface WithGenerics { @@ -283,10 +235,11 @@ export declare namespace TaggedEnum { * Applies concrete type arguments to a `WithGenerics` definition, producing * the resulting tagged union type. * - * - Use to refer to a specific instantiation of a generic tagged enum in - * type signatures. + * **When to use** * - * **Example** (applying generics) + * Use to refer to a specific instantiation of a generic tagged enum in type signatures. + * + * **Example** (Applying generics) * * ```ts * import type { Data } from "effect" @@ -306,6 +259,7 @@ export declare namespace TaggedEnum { * * @see {@link WithGenerics} — define the generic shape * + * @category utility types * @since 2.0.0 */ export type Kind< @@ -325,9 +279,16 @@ export declare namespace TaggedEnum { * Extracts the constructor argument type for a specific variant of a tagged * union. * + * **When to use** + * + * Use to derive the argument object expected by a constructor for one tagged + * union variant. + * + * **Details** + * * Returns `void` if the variant has no fields beyond `_tag`. * - * **Example** (extracting variant args) + * **Example** (Extracting variant args) * * ```ts * import type { Data } from "effect" @@ -345,6 +306,7 @@ export declare namespace TaggedEnum { * * @see {@link Value} — extracts the full variant type (including `_tag`) * + * @category utility types * @since 2.0.0 */ export type Args< @@ -359,6 +321,10 @@ export declare namespace TaggedEnum { /** * Extracts the full variant type (including `_tag`) for a specific tag. * + * **When to use** + * + * Use to select one full tagged-union variant by its `_tag` value. + * * **Example** (extracting a variant type) * * ```ts @@ -374,6 +340,7 @@ export declare namespace TaggedEnum { * * @see {@link Args} — extracts fields without `_tag` * + * @category utility types * @since 2.0.0 */ export type Value< @@ -382,14 +349,23 @@ export declare namespace TaggedEnum { > = Extract /** - * The full constructor-object type returned by {@link taggedEnum}. + * The full constructors-and-matchers object type returned by {@link taggedEnum}. + * + * **When to use** + * + * Use when you want to annotate an exported constructor bundle so downstream + * code keeps exact variant constructors and exhaustive matching. + * + * **Details** * * Includes: * - A constructor function for each variant (keyed by tag name) - * - `$is(tag)` — returns a type-guard for the given variant + * - `$is(tag)` — returns a type-guard that checks only the `_tag` field; + * safe when the tag is globally unique and the value was produced by your + * constructors. For untrusted input, validate with the `Schema` module first. * - `$match` — exhaustive pattern matching (data-last or data-first) * - * **Example** (using the constructor object) + * **Example** (Using the constructor object) * * ```ts * import { Data } from "effect" @@ -414,10 +390,10 @@ export declare namespace TaggedEnum { * }) * ``` * - * @see {@link taggedEnum} — creates a `Constructor` + * @see {@link taggedEnum} — creates constructors and matchers * - * @since 3.1.0 * @category types + * @since 3.1.0 */ export type Constructor = Types.Simplify< { @@ -457,8 +433,16 @@ export declare namespace TaggedEnum { * Function type that constructs a tagged-union variant from its fields, * excluding the keys listed in `Tag`. * - * Returns `void` when no fields remain after excluding `Tag` keys. + * **When to use** * + * Use to type an individual constructor for one tagged-union variant. + * + * **Details** + * + * The constructor returns the full variant type `A`. If no fields remain + * after excluding `Tag` keys, the constructor argument type becomes `void`. + * + * @category utility types * @since 4.0.0 */ export type ConstructorFrom = ( @@ -468,11 +452,18 @@ export declare namespace TaggedEnum { /** * Type-guard and pattern-matching interface for generic tagged enums. * + * **When to use** + * + * Use to type the `$is` and `$match` helpers for generic tagged enums. + * + * **Details** + * * This is the `$is` / `$match` portion of the object returned by * {@link taggedEnum} when used with a {@link WithGenerics} definition. * * @see {@link Constructor} — the non-generic equivalent * + * @category models * @since 3.2.0 */ export interface GenericMatchers> { @@ -525,19 +516,28 @@ export declare namespace TaggedEnum { } /** - * Creates runtime constructors, type guards, and pattern matching for a - * {@link TaggedEnum} type. + * Creates constructors and matchers for a `TaggedEnum` type. + * + * **When to use** + * + * Use when you model a closed union with plain data objects and want + * construction, tag checks, and exhaustive matching from the same definition. + * + * **Details** * * Returns an object with: * - One constructor per variant (keyed by tag name) - * - `$is(tag)` — returns a type-guard function + * - `$is(tag)` — returns a type-guard function that checks only the `_tag` field * - `$match` — exhaustive pattern matching (data-first or data-last) * - * - Use when you have a `TaggedEnum` type and need to construct/inspect values. - * - Constructors produce **plain objects** (not class instances). - * - For generic enums, pass a {@link TaggedEnum.WithGenerics} interface. + * **Gotchas** + * + * - Constructors produce **plain objects**, not class instances. + * - `$is(tag)` only checks the `_tag` field, not the full structure. It relies + * on the tag being globally unique and the value being produced by your + * constructors. For untrusted input, validate with the `Schema` module first. * - * **Example** (basic usage) + * **Example** (Basic usage) * * ```ts * import { Data } from "effect" @@ -562,7 +562,7 @@ export declare namespace TaggedEnum { * console.log(msg) // "/missing not found" * ``` * - * **Example** (generic tagged enum) + * **Example** (Generic tagged enum) * * ```ts * import { Data } from "effect" @@ -589,19 +589,28 @@ export declare namespace TaggedEnum { */ export const taggedEnum: { /** - * Creates runtime constructors, type guards, and pattern matching for a - * {@link TaggedEnum} type. + * Creates constructors and matchers for a `TaggedEnum` type. + * + * **When to use** + * + * Use when you model a closed union with plain data objects and want + * construction, tag checks, and exhaustive matching from the same definition. + * + * **Details** * * Returns an object with: * - One constructor per variant (keyed by tag name) - * - `$is(tag)` — returns a type-guard function + * - `$is(tag)` — returns a type-guard function that checks only the `_tag` field * - `$match` — exhaustive pattern matching (data-first or data-last) * - * - Use when you have a `TaggedEnum` type and need to construct/inspect values. - * - Constructors produce **plain objects** (not class instances). - * - For generic enums, pass a {@link TaggedEnum.WithGenerics} interface. + * **Gotchas** * - * **Example** (basic usage) + * - Constructors produce **plain objects**, not class instances. + * - `$is(tag)` only checks the `_tag` field, not the full structure. It relies + * on the tag being globally unique and the value being produced by your + * constructors. For untrusted input, validate with the `Schema` module first. + * + * **Example** (Basic usage) * * ```ts * import { Data } from "effect" @@ -626,7 +635,7 @@ export const taggedEnum: { * console.log(msg) // "/missing not found" * ``` * - * **Example** (generic tagged enum) + * **Example** (Generic tagged enum) * * ```ts * import { Data } from "effect" @@ -664,19 +673,28 @@ export const taggedEnum: { > /** - * Creates runtime constructors, type guards, and pattern matching for a - * {@link TaggedEnum} type. + * Creates constructors and matchers for a `TaggedEnum` type. + * + * **When to use** + * + * Use when you model a closed union with plain data objects and want + * construction, tag checks, and exhaustive matching from the same definition. + * + * **Details** * * Returns an object with: * - One constructor per variant (keyed by tag name) - * - `$is(tag)` — returns a type-guard function + * - `$is(tag)` — returns a type-guard function that checks only the `_tag` field * - `$match` — exhaustive pattern matching (data-first or data-last) * - * - Use when you have a `TaggedEnum` type and need to construct/inspect values. - * - Constructors produce **plain objects** (not class instances). - * - For generic enums, pass a {@link TaggedEnum.WithGenerics} interface. + * **Gotchas** * - * **Example** (basic usage) + * - Constructors produce **plain objects**, not class instances. + * - `$is(tag)` only checks the `_tag` field, not the full structure. It relies + * on the tag being globally unique and the value being produced by your + * constructors. For untrusted input, validate with the `Schema` module first. + * + * **Example** (Basic usage) * * ```ts * import { Data } from "effect" @@ -701,7 +719,7 @@ export const taggedEnum: { * console.log(msg) // "/missing not found" * ``` * - * **Example** (generic tagged enum) + * **Example** (Generic tagged enum) * * ```ts * import { Data } from "effect" @@ -739,19 +757,28 @@ export const taggedEnum: { > /** - * Creates runtime constructors, type guards, and pattern matching for a - * {@link TaggedEnum} type. + * Creates constructors and matchers for a `TaggedEnum` type. + * + * **When to use** + * + * Use when you model a closed union with plain data objects and want + * construction, tag checks, and exhaustive matching from the same definition. + * + * **Details** * * Returns an object with: * - One constructor per variant (keyed by tag name) - * - `$is(tag)` — returns a type-guard function + * - `$is(tag)` — returns a type-guard function that checks only the `_tag` field * - `$match` — exhaustive pattern matching (data-first or data-last) * - * - Use when you have a `TaggedEnum` type and need to construct/inspect values. - * - Constructors produce **plain objects** (not class instances). - * - For generic enums, pass a {@link TaggedEnum.WithGenerics} interface. + * **Gotchas** + * + * - Constructors produce **plain objects**, not class instances. + * - `$is(tag)` only checks the `_tag` field, not the full structure. It relies + * on the tag being globally unique and the value being produced by your + * constructors. For untrusted input, validate with the `Schema` module first. * - * **Example** (basic usage) + * **Example** (Basic usage) * * ```ts * import { Data } from "effect" @@ -776,7 +803,7 @@ export const taggedEnum: { * console.log(msg) // "/missing not found" * ``` * - * **Example** (generic tagged enum) + * **Example** (Generic tagged enum) * * ```ts * import { Data } from "effect" @@ -814,19 +841,28 @@ export const taggedEnum: { > /** - * Creates runtime constructors, type guards, and pattern matching for a - * {@link TaggedEnum} type. + * Creates constructors and matchers for a `TaggedEnum` type. + * + * **When to use** + * + * Use when you model a closed union with plain data objects and want + * construction, tag checks, and exhaustive matching from the same definition. + * + * **Details** * * Returns an object with: * - One constructor per variant (keyed by tag name) - * - `$is(tag)` — returns a type-guard function + * - `$is(tag)` — returns a type-guard function that checks only the `_tag` field * - `$match` — exhaustive pattern matching (data-first or data-last) * - * - Use when you have a `TaggedEnum` type and need to construct/inspect values. - * - Constructors produce **plain objects** (not class instances). - * - For generic enums, pass a {@link TaggedEnum.WithGenerics} interface. + * **Gotchas** + * + * - Constructors produce **plain objects**, not class instances. + * - `$is(tag)` only checks the `_tag` field, not the full structure. It relies + * on the tag being globally unique and the value being produced by your + * constructors. For untrusted input, validate with the `Schema` module first. * - * **Example** (basic usage) + * **Example** (Basic usage) * * ```ts * import { Data } from "effect" @@ -851,7 +887,7 @@ export const taggedEnum: { * console.log(msg) // "/missing not found" * ``` * - * **Example** (generic tagged enum) + * **Example** (Generic tagged enum) * * ```ts * import { Data } from "effect" @@ -889,19 +925,28 @@ export const taggedEnum: { > /** - * Creates runtime constructors, type guards, and pattern matching for a - * {@link TaggedEnum} type. + * Creates constructors and matchers for a `TaggedEnum` type. + * + * **When to use** + * + * Use when you model a closed union with plain data objects and want + * construction, tag checks, and exhaustive matching from the same definition. + * + * **Details** * * Returns an object with: * - One constructor per variant (keyed by tag name) - * - `$is(tag)` — returns a type-guard function + * - `$is(tag)` — returns a type-guard function that checks only the `_tag` field * - `$match` — exhaustive pattern matching (data-first or data-last) * - * - Use when you have a `TaggedEnum` type and need to construct/inspect values. - * - Constructors produce **plain objects** (not class instances). - * - For generic enums, pass a {@link TaggedEnum.WithGenerics} interface. + * **Gotchas** * - * **Example** (basic usage) + * - Constructors produce **plain objects**, not class instances. + * - `$is(tag)` only checks the `_tag` field, not the full structure. It relies + * on the tag being globally unique and the value being produced by your + * constructors. For untrusted input, validate with the `Schema` module first. + * + * **Example** (Basic usage) * * ```ts * import { Data } from "effect" @@ -926,7 +971,7 @@ export const taggedEnum: { * console.log(msg) // "/missing not found" * ``` * - * **Example** (generic tagged enum) + * **Example** (Generic tagged enum) * * ```ts * import { Data } from "effect" @@ -997,17 +1042,21 @@ function taggedMatch< } /** - * Base class for yieldable errors. + * Provides a base class for yieldable errors. + * + * **When to use** + * + * Use when you need yieldable errors that do **not** need tag-based + * discrimination. + * + * **Details** * * Extends `Cause.YieldableError`, so instances can be yielded inside * `Effect.gen` to fail the enclosing effect. Fields are passed as a single - * object; when there are no fields the argument is optional. - * - * - Use for errors that do **not** need tag-based discrimination. - * - If you need `Effect.catchTag` support, use {@link TaggedError} instead. - * - If a `message` field is provided, it becomes the error's `.message`. + * object; when there are no fields the argument is optional. If a `message` + * field is provided, it becomes the error's `.message`. * - * **Example** (defining a yieldable error) + * **Example** (Defining a yieldable error) * * ```ts * import { Data, Effect } from "effect" @@ -1038,15 +1087,18 @@ export const Error: new = {}>( /** * Creates a tagged error class with a `_tag` discriminator. * + * **When to use** + * + * Use when you need domain errors with discriminated-union handling. + * + * **Details** + * * Like {@link Error}, but instances also carry a `readonly _tag` property, * enabling `Effect.catchTag` and `Effect.catchTags` for tag-based recovery. - * The `_tag` is excluded from the constructor argument. - * - * - Use for domain errors in Effect applications where you want - * discriminated-union error handling. - * - Yielding an instance inside `Effect.gen` fails the effect with this error. + * The `_tag` is excluded from the constructor argument. Yielding an instance + * inside `Effect.gen` fails the effect with this error. * - * **Example** (tag-based error recovery) + * **Example** (Tag-based error recovery) * * ```ts * import { Data, Effect } from "effect" diff --git a/.opencode/node_modules/effect/src/DateTime.ts b/.opencode/node_modules/effect/src/DateTime.ts index 462cc55ec157e8bd169827e70dff5aa3765a2853..0dfbe809934e4316a41d4292addc3aab0fc6e51b 100644 --- a/.opencode/node_modules/effect/src/DateTime.ts +++ b/.opencode/node_modules/effect/src/DateTime.ts @@ -1,4 +1,13 @@ /** + * Works with absolute instants, UTC date-times, zoned date-times, and time + * zones. + * + * A `DateTime` always represents an absolute point in time with epoch + * milliseconds. It may also carry a `TimeZone` for calendar parts, formatting, + * and zone-aware transformations. This module includes constructors, time-zone + * helpers, comparisons, date arithmetic, current-time effects, and formatting + * functions. + * * @since 3.6.0 */ import type { IllegalArgumentError } from "./Cause.ts" @@ -22,14 +31,21 @@ const TimeZoneTypeId = Internal.TimeZoneTypeId * A `DateTime` represents a point in time. It can optionally have a time zone * associated with it. * - * @since 3.6.0 * @category models + * @since 3.6.0 */ export type DateTime = Utc | Zoned /** - * @since 3.6.0 + * Represents a `DateTime` stored as an absolute UTC instant with no associated + * time zone. + * + * **Details** + * + * Use `DateTime.isUtc` to narrow a `DateTime` to this variant. + * * @category models + * @since 3.6.0 */ export interface Utc extends DateTime.Proto { readonly _tag: "Utc" @@ -38,8 +54,16 @@ export interface Utc extends DateTime.Proto { } /** - * @since 3.6.0 + * Represents a `DateTime` with an associated `TimeZone`. + * + * **Details** + * + * A zoned value still represents an absolute instant through + * `epochMilliseconds`, while the time zone is used for wall-clock parts, + * formatting, and zone-aware transformations. + * * @category models + * @since 3.6.0 */ export interface Zoned extends DateTime.Proto { readonly _tag: "Zoned" @@ -51,31 +75,60 @@ export interface Zoned extends DateTime.Proto { } /** + * Companion namespace containing the public helper types used by `DateTime` + * constructors, parts APIs, formatting, and date/time arithmetic. + * * @since 3.6.0 - * @category models */ export declare namespace DateTime { /** - * @since 3.6.0 + * Input accepted by `DateTime.make`, `DateTime.makeUnsafe`, and the zoned + * constructors. + * + * **Details** + * + * Includes existing `DateTime` values, partial date parts, epoch-millisecond + * objects, epoch milliseconds, JavaScript `Date` instances, and parseable date + * strings. + * * @category models + * @since 3.6.0 */ export type Input = DateTime | Partial | Instant | InstantWithZone | Date | number | string /** - * @since 3.6.0 + * Type-level helper used by constructors to preserve a zoned input. + * + * **Details** + * + * When the input type is `DateTime.Zoned`, the result type is + * `DateTime.Zoned`; otherwise the result type is `DateTime.Utc`. + * * @category models + * @since 3.6.0 */ export type PreserveZone = A extends Zoned ? Zoned : Utc /** - * @since 3.6.0 + * Date and time unit name accepted by `DateTime` rounding and arithmetic + * APIs. + * + * **Details** + * + * Includes both singular units, such as `"day"`, and plural units, such as + * `"days"`. + * * @category models + * @since 3.6.0 */ export type Unit = UnitSingular | UnitPlural /** - * @since 3.6.0 + * Singular date and time unit names used by rounding APIs such as + * `DateTime.startOf`, `DateTime.endOf`, and `DateTime.nearest`. + * * @category models + * @since 3.6.0 */ export type UnitSingular = | "millisecond" @@ -88,8 +141,11 @@ export declare namespace DateTime { | "year" /** - * @since 3.6.0 + * Plural date and time unit names used by `DateTime.PartsForMath` for + * amount-based arithmetic. + * * @category models + * @since 3.6.0 */ export type UnitPlural = | "milliseconds" @@ -102,8 +158,16 @@ export declare namespace DateTime { | "years" /** - * @since 3.6.0 + * Calendar and time components of a `DateTime`, including the weekday. + * + * **Details** + * + * `month` is one-based (`1` for January through `12` for December), and + * `weekDay` follows JavaScript `Date#getUTCDay` numbering (`0` for Sunday + * through `6` for Saturday). + * * @category models + * @since 3.6.0 */ export interface PartsWithWeekday { readonly millisecond: number @@ -117,8 +181,14 @@ export declare namespace DateTime { } /** - * @since 3.6.0 + * Calendar and time components of a `DateTime`, without weekday information. + * + * **Details** + * + * `month` is one-based (`1` for January through `12` for December). + * * @category models + * @since 3.6.0 */ export interface Parts { readonly millisecond: number @@ -131,8 +201,14 @@ export declare namespace DateTime { } /** - * @since 3.6.0 + * Plural amount fields accepted by `DateTime.add` and `DateTime.subtract`. + * + * **Details** + * + * Each field represents the number of units to add or subtract for that part. + * * @category models + * @since 3.6.0 */ export interface PartsForMath { readonly milliseconds: number @@ -146,16 +222,26 @@ export declare namespace DateTime { } /** - * @since 4.0.0 + * Object input representing an absolute instant as milliseconds since the Unix + * epoch. + * * @category models + * @since 4.0.0 */ export interface Instant { readonly epochMilliseconds: number } /** - * @since 4.0.0 + * Object input representing an absolute instant plus a time zone identifier. + * + * **Details** + * + * `DateTime.makeZoned` and `DateTime.makeZonedUnsafe` use `timeZoneId` when + * no explicit `timeZone` option is supplied. + * * @category models + * @since 4.0.0 */ export interface InstantWithZone { readonly timeZoneId: string @@ -163,8 +249,15 @@ export declare namespace DateTime { } /** - * @since 3.6.0 + * Shared protocol implemented by all `DateTime` values. + * + * **Details** + * + * Provides the `DateTime` type identifier along with pipe and inspection + * support. + * * @category models + * @since 3.6.0 */ export interface Proto extends Pipeable, Inspectable { readonly [TypeId]: typeof TypeId @@ -172,27 +265,48 @@ export declare namespace DateTime { } /** - * @since 3.6.0 + * Represents a time zone used by `DateTime.Zoned`. + * + * **Details** + * + * A `TimeZone` is either a fixed offset from UTC or a named IANA time zone. + * * @category models + * @since 3.6.0 */ export type TimeZone = TimeZone.Offset | TimeZone.Named /** + * Companion namespace containing the public variant and protocol types for + * `TimeZone`. + * * @since 3.6.0 - * @category models */ export declare namespace TimeZone { /** - * @since 3.6.0 + * Shared protocol implemented by all `TimeZone` values. + * + * **Details** + * + * Provides the `TimeZone` type identifier and inspection support. + * * @category models + * @since 3.6.0 */ export interface Proto extends Inspectable { readonly [TimeZoneTypeId]: typeof TimeZoneTypeId } /** - * @since 3.6.0 + * Fixed-offset time zone. + * + * **Details** + * + * The `offset` is measured in milliseconds from UTC. Positive offsets are + * ahead of UTC, and negative offsets are behind UTC. + * * @category models + * @since 3.6.0 */ export interface Offset extends Proto { readonly _tag: "Offset" @@ -200,8 +314,15 @@ export declare namespace TimeZone { } /** - * @since 3.6.0 + * Named IANA time zone. + * + * **Details** + * + * The `id` field contains the resolved time zone identifier, such as + * `"Europe/London"` or `"America/New_York"`. + * * @category models + * @since 3.6.0 */ export interface Named extends Proto { readonly _tag: "Named" @@ -215,6 +336,8 @@ export declare namespace TimeZone { * A `Disambiguation` is used to resolve ambiguities when a `DateTime` is * ambiguous, such as during a daylight saving time transition. * + * **Details** + * * For more information, see the [Temporal documentation](https://tc39.es/proposal-temporal/docs/timezone.html#ambiguity-due-to-dst-or-other-time-zone-offset-changes) * * - `"compatible"`: (default) Behavior matching Temporal API and legacy JavaScript Date and moment.js. @@ -228,7 +351,8 @@ export declare namespace TimeZone { * * - `"reject"`: Throw an `RangeError` when encountering ambiguous or non-existent times. * - * @example + * **Example** (Resolving ambiguous local times) + * * ```ts * import { DateTime } from "effect" * @@ -268,8 +392,8 @@ export declare namespace TimeZone { * // Time after gap: 2025-03-09T07:30:00.000Z (03:30 EDT) * ``` * - * @since 3.18.0 * @category models + * @since 3.18.0 */ export type Disambiguation = "compatible" | "earlier" | "later" | "reject" @@ -278,48 +402,97 @@ export type Disambiguation = "compatible" | "earlier" | "later" | "reject" // ============================================================================= /** - * @since 3.6.0 + * Checks whether a value is a `DateTime`. + * + * **When to use** + * + * Use to narrow an unknown value before treating it as a `DateTime`. + * + * @see {@link isUtc} for narrowing a known `DateTime` to UTC + * @see {@link isZoned} for narrowing a known `DateTime` to zoned + * * @category guards + * @since 3.6.0 */ export const isDateTime: (u: unknown) => u is DateTime = Internal.isDateTime /** - * Checks if a value is a `TimeZone`. + * Checks whether a value is a `TimeZone`. + * + * **When to use** + * + * Use to narrow unknown input to any `TimeZone` before passing it to APIs that + * accept either fixed-offset or named time zones. + * + * @see {@link isTimeZoneOffset} for narrowing to fixed-offset time zones + * @see {@link isTimeZoneNamed} for narrowing to named time zones * - * @since 3.6.0 * @category guards + * @since 3.6.0 */ export const isTimeZone: (u: unknown) => u is TimeZone = Internal.isTimeZone /** - * Checks if a value is an offset-based `TimeZone`. + * Checks whether a value is an offset-based `TimeZone`. + * + * **When to use** + * + * Use when you need to narrow an unknown or union `TimeZone` value to the + * fixed-offset variant before reading its offset in milliseconds. + * + * @see {@link isTimeZone} for checking either time zone variant + * @see {@link isTimeZoneNamed} for narrowing to named time zones * - * @since 3.6.0 * @category guards + * @since 3.6.0 */ export const isTimeZoneOffset: (u: unknown) => u is TimeZone.Offset = Internal.isTimeZoneOffset /** - * Checks if a value is a named `TimeZone` (IANA time zone). + * Checks whether a value is a named `TimeZone` (IANA time zone). + * + * **When to use** + * + * Use to narrow an unknown value to the `TimeZone.Named` variant before + * reading named-zone fields such as `id`. + * + * @see {@link isTimeZone} for checking either time zone variant + * @see {@link isTimeZoneOffset} for narrowing to fixed-offset time zones * - * @since 3.6.0 * @category guards + * @since 3.6.0 */ export const isTimeZoneNamed: (u: unknown) => u is TimeZone.Named = Internal.isTimeZoneNamed /** - * Checks if a `DateTime` is a UTC `DateTime` (no time zone information). + * Checks whether a `DateTime` is a UTC `DateTime` (no time zone information). + * + * **When to use** + * + * Use to narrow a `DateTime` before passing it to code that requires a UTC + * value without an associated time zone. + * + * @see {@link isZoned} for narrowing to zoned date-times + * @see {@link match} for handling both UTC and zoned cases * - * @since 3.6.0 * @category guards + * @since 3.6.0 */ export const isUtc: (self: DateTime) => self is Utc = Internal.isUtc /** - * Checks if a `DateTime` is a zoned `DateTime` (has time zone information). + * Checks whether a `DateTime` is a zoned `DateTime` (has time zone information). + * + * **When to use** + * + * Use to narrow a known `DateTime` before reading its zone or passing it to + * APIs that require `DateTime.Zoned`. + * + * @see {@link isUtc} for narrowing to UTC date-times + * @see {@link match} for handling both UTC and zoned cases * - * @since 3.6.0 * @category guards + * @since 3.6.0 */ export const isZoned: (self: DateTime) => self is Zoned = Internal.isZoned @@ -328,12 +501,15 @@ export const isZoned: (self: DateTime) => self is Zoned = Internal.isZoned // ============================================================================= /** - * An `Equivalence` for comparing two `DateTime` values for equality. + * Provides an `Equivalence` for comparing two `DateTime` values for equality. + * + * **Details** * * Two `DateTime` values are considered equivalent if they represent the same * point in time, regardless of their time zone. * - * @example + * **Example** (Comparing DateTime values for equivalence) + * * ```ts * import { DateTime } from "effect" * @@ -351,12 +527,15 @@ export const isZoned: (self: DateTime) => self is Zoned = Internal.isZoned export const Equivalence: Equ.Equivalence = Internal.Equivalence /** - * An `Order` for comparing and sorting `DateTime` values. + * Provides an `Order` for comparing and sorting `DateTime` values. + * + * **Details** * * `DateTime` values are ordered by their epoch milliseconds, so earlier times * come before later times regardless of time zone. * - * @example + * **Example** (Sorting DateTime values chronologically) + * * ```ts * import { Array, DateTime } from "effect" * @@ -376,13 +555,16 @@ export const Equivalence: Equ.Equivalence = Internal.Equivalence export const Order: order.Order = Internal.Order /** - * Clamp a `DateTime` between a minimum and maximum value. + * Returns a `DateTime` constrained between a minimum and maximum value. + * + * **Details** * * If the `DateTime` is before the minimum, the minimum is returned. * If the `DateTime` is after the maximum, the maximum is returned. * Otherwise, the original `DateTime` is returned. * - * @example + * **Example** (Clamping DateTime values) + * * ```ts * import { DateTime } from "effect" * @@ -394,18 +576,21 @@ export const Order: order.Order = Internal.Order * // clamped equals max (2024-12-31) * ``` * - * @category instances + * @category ordering * @since 3.6.0 */ export const clamp: { /** - * Clamp a `DateTime` between a minimum and maximum value. + * Returns a `DateTime` constrained between a minimum and maximum value. + * + * **Details** * * If the `DateTime` is before the minimum, the minimum is returned. * If the `DateTime` is after the maximum, the maximum is returned. * Otherwise, the original `DateTime` is returned. * - * @example + * **Example** (Clamping DateTime values) + * * ```ts * import { DateTime } from "effect" * @@ -417,18 +602,21 @@ export const clamp: { * // clamped equals max (2024-12-31) * ``` * - * @category instances + * @category ordering * @since 3.6.0 */ (options: { readonly minimum: Min; readonly maximum: Max }): (self: A) => A | Min | Max /** - * Clamp a `DateTime` between a minimum and maximum value. + * Returns a `DateTime` constrained between a minimum and maximum value. + * + * **Details** * * If the `DateTime` is before the minimum, the minimum is returned. * If the `DateTime` is after the maximum, the maximum is returned. * Otherwise, the original `DateTime` is returned. * - * @example + * **Example** (Clamping DateTime values) + * * ```ts * import { DateTime } from "effect" * @@ -440,7 +628,7 @@ export const clamp: { * // clamped equals max (2024-12-31) * ``` * - * @category instances + * @category ordering * @since 3.6.0 */ (self: A, options: { readonly minimum: Min; readonly maximum: Max }): A | Min | Max @@ -453,9 +641,12 @@ export const clamp: { /** * Create a `DateTime` from a `Date`. * + * **Details** + * * If the `Date` is invalid, an `IllegalArgumentError` will be thrown. * - * @example + * **Example** (Creating DateTime values from Dates) + * * ```ts * import { DateTime } from "effect" * @@ -466,12 +657,19 @@ export const clamp: { * ``` * * @category constructors - * @since 3.6.0 + * @since 4.0.0 */ export const fromDateUnsafe: (date: Date) => Utc = Internal.fromDateUnsafe /** - * Create a `DateTime` from one of the following: + * Create a `DateTime` from supported input values. + * + * **When to use** + * + * Use when creating a `DateTime` from trusted input and construction failures + * should throw an `IllegalArgumentError` instead of returning `Option.none`. + * + * **Details** * * - A `DateTime` * - A `Date` instance (invalid dates will throw an `IllegalArgumentError`) @@ -479,27 +677,39 @@ export const fromDateUnsafe: (date: Date) => Utc = Internal.fromDateUnsafe * - An object with the parts of a date * - A `string` that can be parsed by `Date.parse` * - * @since 3.6.0 - * @category constructors - * @example + * **Example** (Creating DateTime values unsafely) + * * ```ts * import { DateTime } from "effect" * * // from Date - * DateTime.makeUnsafe(new Date()) + * const fromDate = DateTime.makeUnsafe(new Date("2024-01-01T12:00:00Z")) + * console.log(DateTime.formatIso(fromDate)) // "2024-01-01T12:00:00.000Z" * * // from parts - * DateTime.makeUnsafe({ year: 2024 }) + * const fromParts = DateTime.makeUnsafe({ year: 2024 }) + * console.log(DateTime.formatIso(fromParts)) // "2024-01-01T00:00:00.000Z" * * // from string - * DateTime.makeUnsafe("2024-01-01") + * const fromString = DateTime.makeUnsafe("2024-01-01") + * console.log(DateTime.formatIso(fromString)) // "2024-01-01T00:00:00.000Z" * ``` + * + * @category constructors + * @since 4.0.0 */ export const makeUnsafe: (input: A) => DateTime.PreserveZone = Internal.makeUnsafe /** * Create a `DateTime.Zoned` using `DateTime.makeUnsafe` and a time zone. * + * **When to use** + * + * Use when the date/time input and zone options are trusted and invalid or + * rejected ambiguous times should throw instead of returning `Option.none`. + * + * **Details** + * * The input is treated as UTC and then the time zone is attached, unless * `adjustForTimeZone` is set to `true`. In that case, the input is treated as * already in the time zone. @@ -511,14 +721,20 @@ export const makeUnsafe: (input: A) => DateTime.Preser * - `later`: Always choose the later of two possible times * - `reject`: Throw an error when ambiguous times are encountered * - * @since 3.6.0 - * @category constructors - * @example + * **Example** (Creating zoned DateTime values unsafely) + * * ```ts * import { DateTime } from "effect" * - * DateTime.makeZonedUnsafe(new Date(), { timeZone: "Europe/London" }) + * const zoned = DateTime.makeZonedUnsafe("2024-06-15T14:30:00Z", { + * timeZone: "Europe/London" + * }) + * + * console.log(DateTime.formatIsoZoned(zoned)) // "2024-06-15T15:30:00.000+01:00[Europe/London]" * ``` + * + * @category constructors + * @since 4.0.0 */ export const makeZonedUnsafe: (input: DateTime.Input, options?: { readonly timeZone?: number | string | TimeZone | undefined @@ -527,29 +743,43 @@ export const makeZonedUnsafe: (input: DateTime.Input, options?: { }) => Zoned = Internal.makeZonedUnsafe /** - * Create a `DateTime.Zoned` using `DateTime.make` and a time zone. + * Creates a `DateTime.Zoned` safely from an input and a time zone. * - * The input is treated as UTC and then the time zone is attached, unless - * `adjustForTimeZone` is set to `true`. In that case, the input is treated as - * already in the time zone. + * **Details** * - * When `adjustForTimeZone` is true and ambiguous times occur during DST transitions, - * the `disambiguation` option controls how to resolve the ambiguity: - * - `compatible` (default): Choose earlier time for repeated times, later for gaps - * - `earlier`: Always choose the earlier of two possible times - * - `later`: Always choose the later of two possible times - * - `reject`: Throw an error when ambiguous times are encountered + * By default, the input is interpreted as a UTC instant and the time zone is + * attached without changing that instant. When `adjustForTimeZone` is `true`, + * the input is interpreted as wall-clock time in the target zone. * - * If the date time input or time zone is invalid, `None` will be returned. + * When `adjustForTimeZone` is `true`, `disambiguation` controls + * daylight-saving gaps and repeated times: + * + * - `"compatible"` (default): chooses the earlier occurrence for repeated + * times and the later interpretation for gaps + * - `"earlier"`: chooses the earlier possible instant + * - `"later"`: chooses the later possible instant + * - `"reject"`: rejects ambiguous or nonexistent wall-clock times + * + * Returns `Some` when construction succeeds, or `None` when the input, time + * zone, or disambiguation cannot be resolved. + * + * **Example** (Creating optional zoned DateTime values) * - * @since 3.6.0 - * @category constructors - * @example * ```ts * import { DateTime } from "effect" * - * DateTime.makeZoned(new Date(), { timeZone: "Europe/London" }) + * const result = DateTime.makeZoned("2024-06-15T14:30:00Z", { + * timeZone: "Europe/London" + * }) + * + * console.log(result._tag) // "Some" + * if (result._tag === "Some") { + * console.log(DateTime.formatIsoZoned(result.value)) // "2024-06-15T15:30:00.000+01:00[Europe/London]" + * } * ``` + * + * @category constructors + * @since 3.6.0 */ export const makeZoned: ( input: DateTime.Input, @@ -561,40 +791,58 @@ export const makeZoned: ( ) => Option.Option = Internal.makeZoned /** - * Create a `DateTime` from one of the following: + * Creates a `DateTime` safely from supported input values. + * + * **Details** * * - A `DateTime` - * - A `Date` instance (invalid dates will throw an `IllegalArgumentError`) - * - The `number` of milliseconds since the Unix epoch - * - An object with the parts of a date - * - A `string` that can be parsed by `Date.parse` + * - A JavaScript `Date` + * - The number of milliseconds since the Unix epoch + * - An object with date and time parts + * - A string that can be parsed as a date * - * If the input is invalid, `None` will be returned. + * Returns `Some` with the constructed `DateTime` when the input is valid, or + * `None` when construction would fail, including invalid `Date` instances or + * unparseable strings. + * + * **Example** (Creating optional DateTime values) * - * @since 3.6.0 - * @category constructors - * @example * ```ts * import { DateTime } from "effect" * * // from Date - * DateTime.make(new Date()) + * const fromDate = DateTime.make(new Date("2024-01-01T12:00:00Z")) + * console.log(fromDate._tag) // "Some" * * // from parts - * DateTime.make({ year: 2024 }) + * const fromParts = DateTime.make({ year: 2024 }) + * console.log(fromParts._tag) // "Some" * * // from string - * DateTime.make("2024-01-01") + * const fromString = DateTime.make("2024-01-01") + * console.log(fromString._tag) // "Some" + * + * const invalid = DateTime.make("not a date") + * console.log(invalid._tag) // "None" * ``` + * + * @category constructors + * @since 3.6.0 */ export const make: (input: A) => Option.Option> = Internal.make /** - * Create a `DateTime.Zoned` from a string. + * Parses an ISO zoned date-time string into a `DateTime.Zoned` safely. * - * It uses the format: `YYYY-MM-DDTHH:mm:ss.sss+HH:MM[Time/Zone]`. + * **Details** + * + * Accepts named-zone strings such as + * `YYYY-MM-DDTHH:mm:ss.sss+HH:MM[Time/Zone]` and offset-only strings such as + * `YYYY-MM-DDTHH:mm:ss.sss+HH:MM`. Returns `None` when the input cannot be + * parsed. + * + * **Example** (Parsing zoned DateTime strings) * - * @example * ```ts * import { DateTime } from "effect" * @@ -610,33 +858,36 @@ export const make: (input: A) => Option.Option Option.Option = Internal.makeZonedFromString /** - * Get the current time using the `Clock` service and convert it to a `DateTime`. + * Gets the current time using the `Clock` service and convert it to a `DateTime`. + * + * **Example** (Getting the current DateTime) * - * @since 3.6.0 - * @category constructors - * @example * ```ts * import { DateTime, Effect } from "effect" * * Effect.gen(function*() { - * const now = yield* DateTime.now + * const now = yield* DateTime.nowAsDate + * console.log(now instanceof Date) // true * }) * ``` + * + * @category constructors + * @since 3.6.0 */ export const now: Effect.Effect = Internal.now /** - * Get the current time using the `Clock` service and convert it to a `DateTime`. + * Gets the current time from the `Clock` service and returns it as a + * JavaScript `Date`. + * + * **Example** (Getting the current Date) * - * @since 3.6.0 - * @category constructors - * @example * ```ts * import { DateTime, Effect } from "effect" * @@ -644,16 +895,27 @@ export const now: Effect.Effect = Internal.now * const now = yield* DateTime.now * }) * ``` + * + * @category constructors + * @since 3.14.0 */ export const nowAsDate: Effect.Effect = Internal.nowAsDate /** - * Get the current time using `Date.now`. + * Gets the current time using `Date.now`. + * + * **When to use** + * + * Use when synchronous wall-clock access outside an Effect program is + * acceptable and testability through the `Clock` service is not needed. + * + * **Details** * * This is a synchronous version of `now` that directly uses `Date.now()` * instead of the Effect `Clock` service. * - * @example + * **Example** (Getting the current DateTime unsafely) + * * ```ts * import { DateTime } from "effect" * @@ -662,7 +924,7 @@ export const nowAsDate: Effect.Effect = Internal.nowAsDate * ``` * * @category constructors - * @since 3.6.0 + * @since 4.0.0 */ export const nowUnsafe: LazyArg = Internal.nowUnsafe @@ -671,11 +933,19 @@ export const nowUnsafe: LazyArg = Internal.nowUnsafe // ============================================================================= /** - * For a `DateTime` returns a new `DateTime.Utc`. + * Converts a `DateTime` to a UTC `DateTime`. + * + * **When to use** + * + * Use to represent the same instant in UTC instead of its current time zone. + * + * **Details** + * + * The returned value keeps the same epoch milliseconds and changes only the + * `DateTime` representation to UTC. + * + * **Example** (Converting DateTime values to UTC) * - * @since 3.13.0 - * @category time zones - * @example * ```ts * import { DateTime } from "effect" * @@ -686,15 +956,17 @@ export const nowUnsafe: LazyArg = Internal.nowUnsafe * // set as UTC * const utc: DateTime.Utc = DateTime.toUtc(now) * ``` + * + * @category time zones + * @since 3.13.0 */ export const toUtc: (self: DateTime) => Utc = Internal.toUtc /** - * Set the time zone of a `DateTime`, returning a new `DateTime.Zoned`. + * Sets the time zone of a `DateTime`, returning a new `DateTime.Zoned`. + * + * **Example** (Setting time zones) * - * @since 3.6.0 - * @category time zones - * @example * ```ts * import { DateTime, Effect } from "effect" * @@ -706,14 +978,16 @@ export const toUtc: (self: DateTime) => Utc = Internal.toUtc * const zoned: DateTime.Zoned = DateTime.setZone(now, zone) * }) * ``` + * + * @category time zones + * @since 3.6.0 */ export const setZone: { /** - * Set the time zone of a `DateTime`, returning a new `DateTime.Zoned`. + * Sets the time zone of a `DateTime`, returning a new `DateTime.Zoned`. + * + * **Example** (Setting time zones) * - * @since 3.6.0 - * @category time zones - * @example * ```ts * import { DateTime, Effect } from "effect" * @@ -725,6 +999,9 @@ export const setZone: { * const zoned: DateTime.Zoned = DateTime.setZone(now, zone) * }) * ``` + * + * @category time zones + * @since 3.6.0 */ ( zone: TimeZone, @@ -734,11 +1011,10 @@ export const setZone: { } ): (self: DateTime) => Zoned /** - * Set the time zone of a `DateTime`, returning a new `DateTime.Zoned`. + * Sets the time zone of a `DateTime`, returning a new `DateTime.Zoned`. + * + * **Example** (Setting time zones) * - * @since 3.6.0 - * @category time zones - * @example * ```ts * import { DateTime, Effect } from "effect" * @@ -750,6 +1026,9 @@ export const setZone: { * const zoned: DateTime.Zoned = DateTime.setZone(now, zone) * }) * ``` + * + * @category time zones + * @since 3.6.0 */ ( self: DateTime, @@ -762,13 +1041,14 @@ export const setZone: { } = Internal.setZone /** - * Add a fixed offset time zone to a `DateTime`. + * Adds a fixed offset time zone to a `DateTime`. + * + * **Details** * * The offset is in milliseconds. * - * @since 3.6.0 - * @category time zones - * @example + * **Example** (Setting fixed-offset time zones) + * * ```ts * import { DateTime, Effect } from "effect" * @@ -779,16 +1059,20 @@ export const setZone: { * const zoned: DateTime.Zoned = DateTime.setZoneOffset(now, 3 * 60 * 60 * 1000) * }) * ``` + * + * @category time zones + * @since 3.6.0 */ export const setZoneOffset: { /** - * Add a fixed offset time zone to a `DateTime`. + * Adds a fixed offset time zone to a `DateTime`. + * + * **Details** * * The offset is in milliseconds. * - * @since 3.6.0 - * @category time zones - * @example + * **Example** (Setting fixed-offset time zones) + * * ```ts * import { DateTime, Effect } from "effect" * @@ -799,6 +1083,9 @@ export const setZoneOffset: { * const zoned: DateTime.Zoned = DateTime.setZoneOffset(now, 3 * 60 * 60 * 1000) * }) * ``` + * + * @category time zones + * @since 3.6.0 */ ( offset: number, @@ -808,13 +1095,14 @@ export const setZoneOffset: { } ): (self: DateTime) => Zoned /** - * Add a fixed offset time zone to a `DateTime`. + * Adds a fixed offset time zone to a `DateTime`. + * + * **Details** * * The offset is in milliseconds. * - * @since 3.6.0 - * @category time zones - * @example + * **Example** (Setting fixed-offset time zones) + * * ```ts * import { DateTime, Effect } from "effect" * @@ -825,6 +1113,9 @@ export const setZoneOffset: { * const zoned: DateTime.Zoned = DateTime.setZoneOffset(now, 3 * 60 * 60 * 1000) * }) * ``` + * + * @category time zones + * @since 3.6.0 */ ( self: DateTime, @@ -837,11 +1128,19 @@ export const setZoneOffset: { } = Internal.setZoneOffset /** - * Attempt to create a named time zone from a IANA time zone identifier. + * Attempts to create a named time zone from an IANA time zone identifier. + * + * **When to use** + * + * Use when the IANA zone id is trusted and invalid zones should throw instead + * of returning `Option.none` or failing in `Effect`. + * + * **Details** * * If the time zone is invalid, an `IllegalArgumentError` will be thrown. * - * @example + * **Example** (Creating named time zones unsafely) + * * ```ts * import { DateTime } from "effect" * @@ -855,18 +1154,21 @@ export const setZoneOffset: { * // DateTime.zoneMakeNamedUnsafe("Invalid/Zone") * ``` * - * @since 3.6.0 * @category time zones + * @since 4.0.0 */ export const zoneMakeNamedUnsafe: (zoneId: string) => TimeZone.Named = Internal.zoneMakeNamedUnsafe /** * Create a fixed offset time zone. * + * **Details** + * * The offset is specified in milliseconds from UTC. Positive values are * ahead of UTC, negative values are behind UTC. * - * @example + * **Example** (Creating fixed-offset time zones) + * * ```ts * import { DateTime } from "effect" * @@ -884,11 +1186,14 @@ export const zoneMakeNamedUnsafe: (zoneId: string) => TimeZone.Named = Internal. export const zoneMakeOffset: (offset: number) => TimeZone.Offset = Internal.zoneMakeOffset /** - * Create a named time zone from a IANA time zone identifier. + * Creates a named time zone safely from an IANA time zone identifier. + * + * **Details** * * If the time zone is invalid, `None` will be returned. * - * @example + * **Example** (Creating optional named time zones) + * * ```ts * import { DateTime } from "effect" * @@ -905,11 +1210,15 @@ export const zoneMakeOffset: (offset: number) => TimeZone.Offset = Internal.zone export const zoneMakeNamed: (zoneId: string) => Option.Option = Internal.zoneMakeNamed /** - * Create a named time zone from a IANA time zone identifier. + * Creates a named time zone effectfully from an IANA time zone identifier. * - * If the time zone is invalid, it will fail with an `IllegalArgumentError`. + * **When to use** + * + * Use when invalid IANA zone ids should fail in the Effect error channel + * instead of returning `Option.none` or throwing. + * + * **Example** (Creating named time zones effectfully) * - * @example * ```ts * import { DateTime, Effect } from "effect" * @@ -929,18 +1238,18 @@ export const zoneMakeNamedEffect: (zoneId: string) => Effect.Effect Effect.Effect TimeZone.Named = Internal.zoneMakeLocal /** - * Try to parse a `TimeZone` from a string. + * Tries to parse a `TimeZone` from a string safely. + * + * **Details** * * Supports both IANA time zone identifiers and offset formats like "+03:00". * - * @example + * **Example** (Parsing time zones) + * * ```ts * import { DateTime } from "effect" * @@ -972,11 +1284,10 @@ export const zoneMakeLocal: () => TimeZone.Named = Internal.zoneMakeLocal export const zoneFromString: (zone: string) => Option.Option = Internal.zoneFromString /** - * Format a `TimeZone` as a string. + * Formats a `TimeZone` as a string. + * + * **Example** (Formatting time zones) * - * @since 3.6.0 - * @category time zones - * @example * ```ts * import { DateTime } from "effect" * @@ -986,16 +1297,18 @@ export const zoneFromString: (zone: string) => Option.Option = Interna * // Outputs "Europe/London" * DateTime.zoneToString(DateTime.zoneMakeNamedUnsafe("Europe/London")) * ``` + * + * @category time zones + * @since 3.6.0 */ export const zoneToString: (self: TimeZone) => string = Internal.zoneToString /** - * Set the time zone of a `DateTime` from an IANA time zone identifier. If the + * Sets the time zone of a `DateTime` safely from an IANA time zone identifier. If the * time zone is invalid, `None` will be returned. * - * @since 3.6.0 - * @category time zones - * @example + * **Example** (Setting named time zones safely) + * * ```ts * import { DateTime, Effect } from "effect" * @@ -1005,15 +1318,17 @@ export const zoneToString: (self: TimeZone) => string = Internal.zoneToString * DateTime.setZoneNamed(now, "Europe/London") * }) * ``` + * + * @category time zones + * @since 3.6.0 */ export const setZoneNamed: { /** - * Set the time zone of a `DateTime` from an IANA time zone identifier. If the + * Sets the time zone of a `DateTime` safely from an IANA time zone identifier. If the * time zone is invalid, `None` will be returned. * - * @since 3.6.0 - * @category time zones - * @example + * **Example** (Setting named time zones safely) + * * ```ts * import { DateTime, Effect } from "effect" * @@ -1023,6 +1338,9 @@ export const setZoneNamed: { * DateTime.setZoneNamed(now, "Europe/London") * }) * ``` + * + * @category time zones + * @since 3.6.0 */ ( zoneId: string, @@ -1032,12 +1350,11 @@ export const setZoneNamed: { } ): (self: DateTime) => Option.Option /** - * Set the time zone of a `DateTime` from an IANA time zone identifier. If the + * Sets the time zone of a `DateTime` safely from an IANA time zone identifier. If the * time zone is invalid, `None` will be returned. * - * @since 3.6.0 - * @category time zones - * @example + * **Example** (Setting named time zones safely) + * * ```ts * import { DateTime, Effect } from "effect" * @@ -1047,6 +1364,9 @@ export const setZoneNamed: { * DateTime.setZoneNamed(now, "Europe/London") * }) * ``` + * + * @category time zones + * @since 3.6.0 */ ( self: DateTime, @@ -1059,12 +1379,11 @@ export const setZoneNamed: { } = Internal.setZoneNamed /** - * Set the time zone of a `DateTime` from an IANA time zone identifier. If the + * Sets the time zone of a `DateTime` from an IANA time zone identifier. If the * time zone is invalid, an `IllegalArgumentError` will be thrown. * - * @since 3.6.0 - * @category time zones - * @example + * **Example** (Setting named time zones unsafely) + * * ```ts * import { DateTime, Effect } from "effect" * @@ -1074,15 +1393,17 @@ export const setZoneNamed: { * DateTime.setZoneNamedUnsafe(now, "Europe/London") * }) * ``` + * + * @category time zones + * @since 4.0.0 */ export const setZoneNamedUnsafe: { /** - * Set the time zone of a `DateTime` from an IANA time zone identifier. If the + * Sets the time zone of a `DateTime` from an IANA time zone identifier. If the * time zone is invalid, an `IllegalArgumentError` will be thrown. * - * @since 3.6.0 - * @category time zones - * @example + * **Example** (Setting named time zones unsafely) + * * ```ts * import { DateTime, Effect } from "effect" * @@ -1092,6 +1413,9 @@ export const setZoneNamedUnsafe: { * DateTime.setZoneNamedUnsafe(now, "Europe/London") * }) * ``` + * + * @category time zones + * @since 4.0.0 */ ( zoneId: string, @@ -1101,12 +1425,11 @@ export const setZoneNamedUnsafe: { } ): (self: DateTime) => Zoned /** - * Set the time zone of a `DateTime` from an IANA time zone identifier. If the + * Sets the time zone of a `DateTime` from an IANA time zone identifier. If the * time zone is invalid, an `IllegalArgumentError` will be thrown. * - * @since 3.6.0 - * @category time zones - * @example + * **Example** (Setting named time zones unsafely) + * * ```ts * import { DateTime, Effect } from "effect" * @@ -1116,6 +1439,9 @@ export const setZoneNamedUnsafe: { * DateTime.setZoneNamedUnsafe(now, "Europe/London") * }) * ``` + * + * @category time zones + * @since 4.0.0 */ ( self: DateTime, @@ -1132,16 +1458,17 @@ export const setZoneNamedUnsafe: { // ============================================================================= /** - * Calulate the difference between two `DateTime` values, returning a + * Computes the difference between two `DateTime` values, returning a * `Duration` representing the amount of time between them. * + * **Details** + * * If `other` is *after* `self`, the result will be a positive `Duration`. If * `other` is *before* `self`, the result will be a negative `Duration`. If they * are equal, the result will be a `Duration` of zero. * - * @since 3.6.0 - * @category comparisons - * @example + * **Example** (Measuring distance between DateTime values) + * * ```ts * import { DateTime, Effect } from "effect" * @@ -1153,6 +1480,9 @@ export const setZoneNamedUnsafe: { * DateTime.distance(now, other) * }) * ``` + * + * @category comparisons + * @since 3.6.0 */ export const distance: { // ============================================================================= @@ -1160,16 +1490,17 @@ export const distance: { // ============================================================================= /** - * Calulate the difference between two `DateTime` values, returning a + * Computes the difference between two `DateTime` values, returning a * `Duration` representing the amount of time between them. * + * **Details** + * * If `other` is *after* `self`, the result will be a positive `Duration`. If * `other` is *before* `self`, the result will be a negative `Duration`. If they * are equal, the result will be a `Duration` of zero. * - * @since 3.6.0 - * @category comparisons - * @example + * **Example** (Measuring distance between DateTime values) + * * ```ts * import { DateTime, Effect } from "effect" * @@ -1181,6 +1512,9 @@ export const distance: { * DateTime.distance(now, other) * }) * ``` + * + * @category comparisons + * @since 3.6.0 */ (other: DateTime): (self: DateTime) => Duration.Duration // ============================================================================= @@ -1188,16 +1522,17 @@ export const distance: { // ============================================================================= /** - * Calulate the difference between two `DateTime` values, returning a + * Computes the difference between two `DateTime` values, returning a * `Duration` representing the amount of time between them. * + * **Details** + * * If `other` is *after* `self`, the result will be a positive `Duration`. If * `other` is *before* `self`, the result will be a negative `Duration`. If they * are equal, the result will be a `Duration` of zero. * - * @since 3.6.0 - * @category comparisons - * @example + * **Example** (Measuring distance between DateTime values) + * * ```ts * import { DateTime, Effect } from "effect" * @@ -1209,6 +1544,9 @@ export const distance: { * DateTime.distance(now, other) * }) * ``` + * + * @category comparisons + * @since 3.6.0 */ (self: DateTime, other: DateTime): Duration.Duration } = Internal.distance @@ -1216,7 +1554,8 @@ export const distance: { /** * Returns the earlier of two `DateTime` values. * - * @example + * **Example** (Selecting the earlier DateTime) + * * ```ts * import { DateTime } from "effect" * @@ -1234,7 +1573,8 @@ export const min: { /** * Returns the earlier of two `DateTime` values. * - * @example + * **Example** (Selecting the earlier DateTime) + * * ```ts * import { DateTime } from "effect" * @@ -1252,7 +1592,8 @@ export const min: { /** * Returns the earlier of two `DateTime` values. * - * @example + * **Example** (Selecting the earlier DateTime) + * * ```ts * import { DateTime } from "effect" * @@ -1272,7 +1613,8 @@ export const min: { /** * Returns the later of two `DateTime` values. * - * @example + * **Example** (Selecting the later DateTime) + * * ```ts * import { DateTime } from "effect" * @@ -1290,7 +1632,8 @@ export const max: { /** * Returns the later of two `DateTime` values. * - * @example + * **Example** (Selecting the later DateTime) + * * ```ts * import { DateTime } from "effect" * @@ -1308,7 +1651,8 @@ export const max: { /** * Returns the later of two `DateTime` values. * - * @example + * **Example** (Selecting the later DateTime) + * * ```ts * import { DateTime } from "effect" * @@ -1326,9 +1670,10 @@ export const max: { } = Internal.max /** - * Checks if the first `DateTime` is after the second `DateTime`. + * Checks whether the first `DateTime` is after the second `DateTime`. + * + * **Example** (Checking whether a DateTime is later) * - * @example * ```ts * import { DateTime } from "effect" * @@ -1340,13 +1685,14 @@ export const max: { * ``` * * @category comparisons - * @since 3.6.0 + * @since 4.0.0 */ export const isGreaterThan: { /** - * Checks if the first `DateTime` is after the second `DateTime`. + * Checks whether the first `DateTime` is after the second `DateTime`. + * + * **Example** (Checking whether a DateTime is later) * - * @example * ```ts * import { DateTime } from "effect" * @@ -1358,13 +1704,14 @@ export const isGreaterThan: { * ``` * * @category comparisons - * @since 3.6.0 + * @since 4.0.0 */ (that: DateTime): (self: DateTime) => boolean /** - * Checks if the first `DateTime` is after the second `DateTime`. + * Checks whether the first `DateTime` is after the second `DateTime`. + * + * **Example** (Checking whether a DateTime is later) * - * @example * ```ts * import { DateTime } from "effect" * @@ -1376,15 +1723,16 @@ export const isGreaterThan: { * ``` * * @category comparisons - * @since 3.6.0 + * @since 4.0.0 */ (self: DateTime, that: DateTime): boolean } = Internal.isGreaterThan /** - * Checks if the first `DateTime` is after or equal to the second `DateTime`. + * Checks whether the first `DateTime` is after or equal to the second `DateTime`. + * + * **Example** (Checking whether a DateTime is later or equal) * - * @example * ```ts * import { DateTime } from "effect" * @@ -1398,13 +1746,14 @@ export const isGreaterThan: { * ``` * * @category comparisons - * @since 3.6.0 + * @since 4.0.0 */ export const isGreaterThanOrEqualTo: { /** - * Checks if the first `DateTime` is after or equal to the second `DateTime`. + * Checks whether the first `DateTime` is after or equal to the second `DateTime`. + * + * **Example** (Checking whether a DateTime is later or equal) * - * @example * ```ts * import { DateTime } from "effect" * @@ -1418,13 +1767,14 @@ export const isGreaterThanOrEqualTo: { * ``` * * @category comparisons - * @since 3.6.0 + * @since 4.0.0 */ (that: DateTime): (self: DateTime) => boolean /** - * Checks if the first `DateTime` is after or equal to the second `DateTime`. + * Checks whether the first `DateTime` is after or equal to the second `DateTime`. + * + * **Example** (Checking whether a DateTime is later or equal) * - * @example * ```ts * import { DateTime } from "effect" * @@ -1438,15 +1788,16 @@ export const isGreaterThanOrEqualTo: { * ``` * * @category comparisons - * @since 3.6.0 + * @since 4.0.0 */ (self: DateTime, that: DateTime): boolean } = Internal.isGreaterThanOrEqualTo /** - * Checks if the first `DateTime` is before the second `DateTime`. + * Checks whether the first `DateTime` is before the second `DateTime`. + * + * **Example** (Checking whether a DateTime is earlier) * - * @example * ```ts * import { DateTime } from "effect" * @@ -1458,13 +1809,14 @@ export const isGreaterThanOrEqualTo: { * ``` * * @category comparisons - * @since 3.6.0 + * @since 4.0.0 */ export const isLessThan: { /** - * Checks if the first `DateTime` is before the second `DateTime`. + * Checks whether the first `DateTime` is before the second `DateTime`. + * + * **Example** (Checking whether a DateTime is earlier) * - * @example * ```ts * import { DateTime } from "effect" * @@ -1476,13 +1828,14 @@ export const isLessThan: { * ``` * * @category comparisons - * @since 3.6.0 + * @since 4.0.0 */ (that: DateTime): (self: DateTime) => boolean /** - * Checks if the first `DateTime` is before the second `DateTime`. + * Checks whether the first `DateTime` is before the second `DateTime`. + * + * **Example** (Checking whether a DateTime is earlier) * - * @example * ```ts * import { DateTime } from "effect" * @@ -1494,15 +1847,16 @@ export const isLessThan: { * ``` * * @category comparisons - * @since 3.6.0 + * @since 4.0.0 */ (self: DateTime, that: DateTime): boolean } = Internal.isLessThan /** - * Checks if the first `DateTime` is before or equal to the second `DateTime`. + * Checks whether the first `DateTime` is before or equal to the second `DateTime`. + * + * **Example** (Checking whether a DateTime is earlier or equal) * - * @example * ```ts * import { DateTime } from "effect" * @@ -1516,13 +1870,14 @@ export const isLessThan: { * ``` * * @category comparisons - * @since 3.6.0 + * @since 4.0.0 */ export const isLessThanOrEqualTo: { /** - * Checks if the first `DateTime` is before or equal to the second `DateTime`. + * Checks whether the first `DateTime` is before or equal to the second `DateTime`. + * + * **Example** (Checking whether a DateTime is earlier or equal) * - * @example * ```ts * import { DateTime } from "effect" * @@ -1536,13 +1891,14 @@ export const isLessThanOrEqualTo: { * ``` * * @category comparisons - * @since 3.6.0 + * @since 4.0.0 */ (that: DateTime): (self: DateTime) => boolean /** - * Checks if the first `DateTime` is before or equal to the second `DateTime`. + * Checks whether the first `DateTime` is before or equal to the second `DateTime`. + * + * **Example** (Checking whether a DateTime is earlier or equal) * - * @example * ```ts * import { DateTime } from "effect" * @@ -1556,15 +1912,16 @@ export const isLessThanOrEqualTo: { * ``` * * @category comparisons - * @since 3.6.0 + * @since 4.0.0 */ (self: DateTime, that: DateTime): boolean } = Internal.isLessThanOrEqualTo /** - * Checks if a `DateTime` is between two other `DateTime` values (inclusive). + * Checks whether a `DateTime` is between two other `DateTime` values (inclusive). + * + * **Example** (Checking whether a DateTime is within bounds) * - * @example * ```ts * import { DateTime } from "effect" * @@ -1580,9 +1937,10 @@ export const isLessThanOrEqualTo: { */ export const between: { /** - * Checks if a `DateTime` is between two other `DateTime` values (inclusive). + * Checks whether a `DateTime` is between two other `DateTime` values (inclusive). + * + * **Example** (Checking whether a DateTime is within bounds) * - * @example * ```ts * import { DateTime } from "effect" * @@ -1598,9 +1956,10 @@ export const between: { */ (options: { minimum: DateTime; maximum: DateTime }): (self: DateTime) => boolean /** - * Checks if a `DateTime` is between two other `DateTime` values (inclusive). + * Checks whether a `DateTime` is between two other `DateTime` values (inclusive). + * + * **Example** (Checking whether a DateTime is within bounds) * - * @example * ```ts * import { DateTime } from "effect" * @@ -1618,11 +1977,14 @@ export const between: { } = Internal.between /** - * Checks if a `DateTime` is in the future compared to the current time. + * Checks effectfully if a `DateTime` is in the future compared to the current time. + * + * **Details** * * This is an effectful operation that uses the current time from the `Clock` service. * - * @example + * **Example** (Checking future DateTime values effectfully) + * * ```ts * import { DateTime, Effect } from "effect" * @@ -1639,11 +2001,19 @@ export const between: { export const isFuture: (self: DateTime) => Effect.Effect = Internal.isFuture /** - * Checks if a `DateTime` is in the future compared to the current time. + * Checks synchronously if a `DateTime` is in the future compared to the current time. + * + * **When to use** + * + * Use when checking whether a `DateTime` is in the future with a synchronous + * live-clock read and `Clock`-based testability is not needed. + * + * **Details** * * This is a synchronous version that uses `Date.now()` directly. * - * @example + * **Example** (Checking future DateTime values unsafely) + * * ```ts * import { DateTime } from "effect" * @@ -1655,16 +2025,19 @@ export const isFuture: (self: DateTime) => Effect.Effect = Internal.isF * ``` * * @category comparisons - * @since 3.6.0 + * @since 4.0.0 */ export const isFutureUnsafe: (self: DateTime) => boolean = Internal.isFutureUnsafe /** - * Checks if a `DateTime` is in the past compared to the current time. + * Checks effectfully if a `DateTime` is in the past compared to the current time. + * + * **Details** * * This is an effectful operation that uses the current time from the `Clock` service. * - * @example + * **Example** (Checking past DateTime values effectfully) + * * ```ts * import { DateTime, Effect } from "effect" * @@ -1681,11 +2054,19 @@ export const isFutureUnsafe: (self: DateTime) => boolean = Internal.isFutureUnsa export const isPast: (self: DateTime) => Effect.Effect = Internal.isPast /** - * Checks if a `DateTime` is in the past compared to the current time. + * Checks synchronously if a `DateTime` is in the past compared to the current time. + * + * **When to use** + * + * Use when checking whether a `DateTime` is in the past with a synchronous + * live-clock read and `Clock`-based testability is not needed. + * + * **Details** * * This is a synchronous version that uses `Date.now()` directly. * - * @example + * **Example** (Checking past DateTime values unsafely) + * * ```ts * import { DateTime } from "effect" * @@ -1697,7 +2078,7 @@ export const isPast: (self: DateTime) => Effect.Effect = Internal.isPas * ``` * * @category comparisons - * @since 3.6.0 + * @since 4.0.0 */ export const isPastUnsafe: (self: DateTime) => boolean = Internal.isPastUnsafe @@ -1706,11 +2087,14 @@ export const isPastUnsafe: (self: DateTime) => boolean = Internal.isPastUnsafe // ============================================================================= /** - * Get the UTC `Date` of a `DateTime`. + * Gets the UTC `Date` of a `DateTime`. + * + * **Details** * * This always returns the UTC representation, ignoring any time zone information. * - * @example + * **Example** (Converting DateTime values to UTC Dates) + * * ```ts * import { DateTime } from "effect" * @@ -1722,18 +2106,21 @@ export const isPastUnsafe: (self: DateTime) => boolean = Internal.isPastUnsafe * console.log(utcDate.toISOString()) // "2024-01-01T12:00:00.000Z" * ``` * - * @category conversions + * @category converting * @since 3.6.0 */ export const toDateUtc: (self: DateTime) => Date = Internal.toDateUtc /** - * Convert a `DateTime` to a `Date`, applying the time zone first. + * Converts a `DateTime` to a `Date`, applying the time zone first. + * + * **Details** * * For `DateTime.Zoned`, this adjusts for the time zone before converting. * For `DateTime.Utc`, this is equivalent to `toDateUtc`. * - * @example + * **Example** (Converting DateTime values to Dates) + * * ```ts * import { DateTime } from "effect" * @@ -1746,18 +2133,21 @@ export const toDateUtc: (self: DateTime) => Date = Internal.toDateUtc * console.log(DateTime.toDate(zoned).toISOString()) * ``` * - * @category conversions + * @category converting * @since 3.6.0 */ export const toDate: (self: DateTime) => Date = Internal.toDate /** - * Calculate the time zone offset of a `DateTime.Zoned` in milliseconds. + * Computes the time zone offset of a `DateTime.Zoned` in milliseconds. + * + * **Details** * * Returns the offset from UTC in milliseconds. Positive values indicate * time zones ahead of UTC, negative values indicate time zones behind UTC. * - * @example + * **Example** (Reading zoned offsets) + * * ```ts * import { DateTime } from "effect" * @@ -1769,17 +2159,20 @@ export const toDate: (self: DateTime) => Date = Internal.toDate * console.log(offset) // 0 (London is UTC+0 in winter) * ``` * - * @category conversions + * @category converting * @since 3.6.0 */ export const zonedOffset: (self: Zoned) => number = Internal.zonedOffset /** - * Format the time zone offset of a `DateTime.Zoned` as an ISO string. + * Formats the time zone offset of a `DateTime.Zoned` as an ISO string. + * + * **Details** * * The offset is formatted as "±HH:MM". * - * @example + * **Example** (Formatting zoned offsets) + * * ```ts * import { DateTime } from "effect" * @@ -1791,17 +2184,20 @@ export const zonedOffset: (self: Zoned) => number = Internal.zonedOffset * console.log(offsetString) // "+03:00" * ``` * - * @category conversions + * @category converting * @since 3.6.0 */ export const zonedOffsetIso: (self: Zoned) => string = Internal.zonedOffsetIso /** - * Get the milliseconds since the Unix epoch of a `DateTime`. + * Gets the milliseconds since the Unix epoch of a `DateTime`. + * + * **Details** * * This returns the UTC timestamp regardless of any time zone information. * - * @example + * **Example** (Reading epoch milliseconds) + * * ```ts * import { DateTime } from "effect" * @@ -1809,21 +2205,19 @@ export const zonedOffsetIso: (self: Zoned) => string = Internal.zonedOffsetIso * const epochMillis = DateTime.toEpochMillis(dt) * * console.log(epochMillis) // 1704067200000 - * console.log(new Date(epochMillis).toISOString()) // "2024-01-01T00:00:00.000Z" * ``` * - * @category conversions + * @category converting * @since 3.6.0 */ export const toEpochMillis: (self: DateTime) => number = Internal.toEpochMillis /** - * Remove the time aspect of a `DateTime`, first adjusting for the time + * Removes the time aspect of a `DateTime`, first adjusting for the time * zone. It will return a `DateTime.Utc` only containing the date. * - * @since 3.6.0 - * @category conversions - * @example + * **Example** (Removing time components) + * * ```ts * import { DateTime } from "effect" * @@ -1836,6 +2230,9 @@ export const toEpochMillis: (self: DateTime) => number = Internal.toEpochMillis * DateTime.formatIso * ) * ``` + * + * @category converting + * @since 3.6.0 */ export const removeTime: (self: DateTime) => Utc = Internal.removeTime @@ -1844,11 +2241,14 @@ export const removeTime: (self: DateTime) => Utc = Internal.removeTime // ============================================================================= /** - * Get the different parts of a `DateTime` as an object. + * Gets the time-zone-adjusted parts of a `DateTime` as an object. + * + * **Details** * * The parts will be time zone adjusted if the `DateTime` is zoned. * - * @example + * **Example** (Reading DateTime parts) + * * ```ts * import { DateTime } from "effect" * @@ -1874,11 +2274,14 @@ export const removeTime: (self: DateTime) => Utc = Internal.removeTime export const toParts: (self: DateTime) => DateTime.PartsWithWeekday = Internal.toParts /** - * Get the different parts of a `DateTime` as an object. + * Gets the UTC parts of a `DateTime` as an object. + * + * **Details** * * The parts will always be in UTC, ignoring any time zone information. * - * @example + * **Example** (Reading UTC DateTime parts) + * * ```ts * import { DateTime } from "effect" * @@ -1897,129 +2300,150 @@ export const toParts: (self: DateTime) => DateTime.PartsWithWeekday = Internal.t export const toPartsUtc: (self: DateTime) => DateTime.PartsWithWeekday = Internal.toPartsUtc /** - * Get a part of a `DateTime` as a number. + * Gets one UTC part of a `DateTime` as a number. + * + * **Details** * * The part will be in the UTC time zone. * - * @since 3.6.0 - * @category parts - * @example + * **Example** (Reading UTC DateTime parts by key) + * * ```ts * import { DateTime } from "effect" - * import * as assert from "node:assert" * - * const now = DateTime.makeUnsafe({ year: 2024 }) - * const year = DateTime.getPartUtc(now, "year") - * assert.strictEqual(year, 2024) + * const dateTime = DateTime.makeUnsafe({ year: 2024 }) + * const year = DateTime.getPartUtc(dateTime, "year") + * console.log(year) // 2024 * ``` + * + * @category parts + * @since 3.6.0 */ export const getPartUtc: { /** - * Get a part of a `DateTime` as a number. + * Gets one UTC part of a `DateTime` as a number. + * + * **Details** * * The part will be in the UTC time zone. * - * @since 3.6.0 - * @category parts - * @example + * **Example** (Reading UTC DateTime parts by key) + * * ```ts * import { DateTime } from "effect" - * import * as assert from "node:assert" * - * const now = DateTime.makeUnsafe({ year: 2024 }) - * const year = DateTime.getPartUtc(now, "year") - * assert.strictEqual(year, 2024) + * const dateTime = DateTime.makeUnsafe({ year: 2024 }) + * const year = DateTime.getPartUtc(dateTime, "year") + * console.log(year) // 2024 * ``` + * + * @category parts + * @since 3.6.0 */ (part: keyof DateTime.PartsWithWeekday): (self: DateTime) => number /** - * Get a part of a `DateTime` as a number. + * Gets one UTC part of a `DateTime` as a number. + * + * **Details** * * The part will be in the UTC time zone. * - * @since 3.6.0 - * @category parts - * @example + * **Example** (Reading UTC DateTime parts by key) + * * ```ts * import { DateTime } from "effect" - * import * as assert from "node:assert" * - * const now = DateTime.makeUnsafe({ year: 2024 }) - * const year = DateTime.getPartUtc(now, "year") - * assert.strictEqual(year, 2024) + * const dateTime = DateTime.makeUnsafe({ year: 2024 }) + * const year = DateTime.getPartUtc(dateTime, "year") + * console.log(year) // 2024 * ``` + * + * @category parts + * @since 3.6.0 */ (self: DateTime, part: keyof DateTime.PartsWithWeekday): number } = Internal.getPartUtc /** - * Get a part of a `DateTime` as a number. + * Gets one time-zone-adjusted part of a `DateTime` as a number. + * + * **Details** * * The part will be time zone adjusted. * - * @since 3.6.0 - * @category parts - * @example + * **Example** (Reading DateTime parts by key) + * * ```ts * import { DateTime } from "effect" - * import * as assert from "node:assert" * - * const now = DateTime.makeZonedUnsafe({ year: 2024 }, { + * const dateTime = DateTime.makeZonedUnsafe({ year: 2024 }, { * timeZone: "Europe/London" * }) - * const year = DateTime.getPart(now, "year") - * assert.strictEqual(year, 2024) + * const year = DateTime.getPart(dateTime, "year") + * console.log(year) // 2024 * ``` + * + * @category parts + * @since 3.6.0 */ export const getPart: { /** - * Get a part of a `DateTime` as a number. + * Gets one time-zone-adjusted part of a `DateTime` as a number. + * + * **Details** * * The part will be time zone adjusted. * - * @since 3.6.0 - * @category parts - * @example + * **Example** (Reading DateTime parts by key) + * * ```ts * import { DateTime } from "effect" - * import * as assert from "node:assert" * - * const now = DateTime.makeZonedUnsafe({ year: 2024 }, { + * const dateTime = DateTime.makeZonedUnsafe({ year: 2024 }, { * timeZone: "Europe/London" * }) - * const year = DateTime.getPart(now, "year") - * assert.strictEqual(year, 2024) + * const year = DateTime.getPart(dateTime, "year") + * console.log(year) // 2024 * ``` + * + * @category parts + * @since 3.6.0 */ (part: keyof DateTime.PartsWithWeekday): (self: DateTime) => number /** - * Get a part of a `DateTime` as a number. + * Gets one time-zone-adjusted part of a `DateTime` as a number. + * + * **Details** * * The part will be time zone adjusted. * - * @since 3.6.0 - * @category parts - * @example + * **Example** (Reading DateTime parts by key) + * * ```ts * import { DateTime } from "effect" - * import * as assert from "node:assert" * - * const now = DateTime.makeZonedUnsafe({ year: 2024 }, { + * const dateTime = DateTime.makeZonedUnsafe({ year: 2024 }, { * timeZone: "Europe/London" * }) - * const year = DateTime.getPart(now, "year") - * assert.strictEqual(year, 2024) + * const year = DateTime.getPart(dateTime, "year") + * console.log(year) // 2024 * ``` + * + * @category parts + * @since 3.6.0 */ (self: DateTime, part: keyof DateTime.PartsWithWeekday): number } = Internal.getPart /** - * Set the different parts of a `DateTime` as an object. + * Sets time-zone-adjusted parts on a `DateTime`. + * + * **Details** * * The date will be time zone adjusted for `DateTime.Zoned`. * - * @example + * **Example** (Updating DateTime parts) + * * ```ts * import { DateTime } from "effect" * @@ -2038,11 +2462,14 @@ export const getPart: { */ export const setParts: { /** - * Set the different parts of a `DateTime` as an object. + * Sets time-zone-adjusted parts on a `DateTime`. + * + * **Details** * * The date will be time zone adjusted for `DateTime.Zoned`. * - * @example + * **Example** (Updating DateTime parts) + * * ```ts * import { DateTime } from "effect" * @@ -2061,11 +2488,14 @@ export const setParts: { */ (parts: Partial): (self: A) => A /** - * Set the different parts of a `DateTime` as an object. + * Sets time-zone-adjusted parts on a `DateTime`. + * + * **Details** * * The date will be time zone adjusted for `DateTime.Zoned`. * - * @example + * **Example** (Updating DateTime parts) + * * ```ts * import { DateTime } from "effect" * @@ -2086,11 +2516,14 @@ export const setParts: { } = Internal.setParts /** - * Set the different parts of a `DateTime` as an object. + * Sets UTC parts on a `DateTime`. + * + * **Details** * * The parts are always interpreted as UTC, ignoring any time zone information. * - * @example + * **Example** (Updating UTC DateTime parts) + * * ```ts * import { DateTime } from "effect" * @@ -2108,11 +2541,14 @@ export const setParts: { */ export const setPartsUtc: { /** - * Set the different parts of a `DateTime` as an object. + * Sets UTC parts on a `DateTime`. + * + * **Details** * * The parts are always interpreted as UTC, ignoring any time zone information. * - * @example + * **Example** (Updating UTC DateTime parts) + * * ```ts * import { DateTime } from "effect" * @@ -2130,11 +2566,14 @@ export const setPartsUtc: { */ (parts: Partial): (self: A) => A /** - * Set the different parts of a `DateTime` as an object. + * Sets UTC parts on a `DateTime`. + * + * **Details** * * The parts are always interpreted as UTC, ignoring any time zone information. * - * @example + * **Example** (Updating UTC DateTime parts) + * * ```ts * import { DateTime } from "effect" * @@ -2158,13 +2597,23 @@ export const setPartsUtc: { // ============================================================================= /** - * @example + * Context service that supplies the ambient `TimeZone` for APIs that work in + * the current zone, such as `DateTime.setZoneCurrent` and + * `DateTime.nowInCurrentZone`. + * + * **Details** + * + * Provide it with `DateTime.withCurrentZone`, one of the `withCurrentZone*` + * helpers, or one of the `layerCurrentZone*` layers. + * + * **Example** (Accessing the current time zone service) + * * ```ts * import { DateTime, Effect } from "effect" * * const program = Effect.gen(function*() { * // Access the current time zone service - * const zone = yield* DateTime.CurrentTimeZone.asEffect() + * const zone = yield* DateTime.CurrentTimeZone * console.log(DateTime.zoneToString(zone)) * }) * @@ -2173,20 +2622,19 @@ export const setPartsUtc: { * Effect.provide(program, layer) * ``` * - * @since 3.11.0 * @category current time zone + * @since 3.11.0 */ export class CurrentTimeZone extends Context.Service()( "effect/DateTime/CurrentTimeZone" ) {} /** - * Set the time zone of a `DateTime` to the current time zone, which is + * Sets the time zone of a `DateTime` to the current time zone, which is * determined by the `CurrentTimeZone` service. * - * @since 3.6.0 - * @category current time zone - * @example + * **Example** (Setting the current time zone) + * * ```ts * import { DateTime, Effect } from "effect" * @@ -2197,16 +2645,18 @@ export class CurrentTimeZone extends Context.Service( * const zoned = yield* DateTime.setZoneCurrent(now) * }).pipe(DateTime.withCurrentZoneNamed("Europe/London")) * ``` + * + * @category current time zone + * @since 3.6.0 */ export const setZoneCurrent = (self: DateTime): Effect.Effect => - Effect.map(CurrentTimeZone.asEffect(), (zone) => setZone(self, zone)) + Effect.map(CurrentTimeZone, (zone) => setZone(self, zone)) /** - * Provide the `CurrentTimeZone` to an effect. + * Provides the `CurrentTimeZone` to an effect. + * + * **Example** (Providing the current time zone) * - * @since 3.6.0 - * @category current time zone - * @example * ```ts * import { DateTime, Effect } from "effect" * @@ -2216,14 +2666,16 @@ export const setZoneCurrent = (self: DateTime): Effect.Effect(self: Effect.Effect) => Effect.Effect> /** - * Provide the `CurrentTimeZone` to an effect. + * Provides the `CurrentTimeZone` to an effect. + * + * **Example** (Providing the current time zone) * - * @since 3.6.0 - * @category current time zone - * @example * ```ts * import { DateTime, Effect } from "effect" * @@ -2250,17 +2704,19 @@ export const withCurrentZone: { * const now = yield* DateTime.nowInCurrentZone * }).pipe(DateTime.withCurrentZone(zone)) * ``` + * + * @category current time zone + * @since 3.6.0 */ (self: Effect.Effect, value: TimeZone): Effect.Effect> } = provideService(CurrentTimeZone) /** - * Provide the `CurrentTimeZone` to an effect, using the system's local time + * Provides the `CurrentTimeZone` to an effect, using the system's local time * zone. * - * @since 3.6.0 - * @category current time zone - * @example + * **Example** (Providing the local time zone) + * * ```ts * import { DateTime, Effect } from "effect" * @@ -2269,6 +2725,9 @@ export const withCurrentZone: { * const now = yield* DateTime.nowInCurrentZone * }).pipe(DateTime.withCurrentZoneLocal) * ``` + * + * @category current time zone + * @since 3.6.0 */ export const withCurrentZoneLocal = ( effect: Effect.Effect @@ -2276,53 +2735,59 @@ export const withCurrentZoneLocal = ( Effect.provideServiceEffect(effect, CurrentTimeZone, Effect.sync(zoneMakeLocal)) /** - * Provide the `CurrentTimeZone` to an effect, using a offset. + * Provides the `CurrentTimeZone` to an effect, using an offset. + * + * **Example** (Providing a fixed-offset time zone) * - * @since 3.6.0 - * @category current time zone - * @example * ```ts * import { DateTime, Effect } from "effect" * * Effect.gen(function*() { - * // will use the system's local time zone - * const now = yield* DateTime.nowInCurrentZone + * const zone = yield* DateTime.CurrentTimeZone + * console.log(DateTime.zoneToString(zone)) // "+03:00" * }).pipe(DateTime.withCurrentZoneOffset(3 * 60 * 60 * 1000)) * ``` + * + * @category current time zone + * @since 3.6.0 */ export const withCurrentZoneOffset: { /** - * Provide the `CurrentTimeZone` to an effect, using a offset. + * Provides the `CurrentTimeZone` to an effect, using an offset. + * + * **Example** (Providing a fixed-offset time zone) * - * @since 3.6.0 - * @category current time zone - * @example * ```ts * import { DateTime, Effect } from "effect" * * Effect.gen(function*() { - * // will use the system's local time zone - * const now = yield* DateTime.nowInCurrentZone + * const zone = yield* DateTime.CurrentTimeZone + * console.log(DateTime.zoneToString(zone)) // "+03:00" * }).pipe(DateTime.withCurrentZoneOffset(3 * 60 * 60 * 1000)) * ``` + * + * @category current time zone + * @since 3.6.0 */ (offset: number): ( effect: Effect.Effect ) => Effect.Effect> /** - * Provide the `CurrentTimeZone` to an effect, using a offset. + * Provides the `CurrentTimeZone` to an effect, using an offset. + * + * **Example** (Providing a fixed-offset time zone) * - * @since 3.6.0 - * @category current time zone - * @example * ```ts * import { DateTime, Effect } from "effect" * * Effect.gen(function*() { - * // will use the system's local time zone - * const now = yield* DateTime.nowInCurrentZone + * const zone = yield* DateTime.CurrentTimeZone + * console.log(DateTime.zoneToString(zone)) // "+03:00" * }).pipe(DateTime.withCurrentZoneOffset(3 * 60 * 60 * 1000)) * ``` + * + * @category current time zone + * @since 3.6.0 */ (effect: Effect.Effect, offset: number): Effect.Effect> } = dual( @@ -2332,14 +2797,15 @@ export const withCurrentZoneOffset: { ) /** - * Provide the `CurrentTimeZone` to an effect using an IANA time zone + * Provides the `CurrentTimeZone` to an effect using an IANA time zone * identifier. * + * **Details** + * * If the time zone is invalid, it will fail with an `IllegalArgumentError`. * - * @since 3.6.0 - * @category current time zone - * @example + * **Example** (Providing a named time zone) + * * ```ts * import { DateTime, Effect } from "effect" * @@ -2348,17 +2814,21 @@ export const withCurrentZoneOffset: { * const now = yield* DateTime.nowInCurrentZone * }).pipe(DateTime.withCurrentZoneNamed("Europe/London")) * ``` + * + * @category current time zone + * @since 3.6.0 */ export const withCurrentZoneNamed: { /** - * Provide the `CurrentTimeZone` to an effect using an IANA time zone + * Provides the `CurrentTimeZone` to an effect using an IANA time zone * identifier. * + * **Details** + * * If the time zone is invalid, it will fail with an `IllegalArgumentError`. * - * @since 3.6.0 - * @category current time zone - * @example + * **Example** (Providing a named time zone) + * * ```ts * import { DateTime, Effect } from "effect" * @@ -2367,19 +2837,23 @@ export const withCurrentZoneNamed: { * const now = yield* DateTime.nowInCurrentZone * }).pipe(DateTime.withCurrentZoneNamed("Europe/London")) * ``` + * + * @category current time zone + * @since 3.6.0 */ (zone: string): ( effect: Effect.Effect ) => Effect.Effect> /** - * Provide the `CurrentTimeZone` to an effect using an IANA time zone + * Provides the `CurrentTimeZone` to an effect using an IANA time zone * identifier. * + * **Details** + * * If the time zone is invalid, it will fail with an `IllegalArgumentError`. * - * @since 3.6.0 - * @category current time zone - * @example + * **Example** (Providing a named time zone) + * * ```ts * import { DateTime, Effect } from "effect" * @@ -2388,6 +2862,9 @@ export const withCurrentZoneNamed: { * const now = yield* DateTime.nowInCurrentZone * }).pipe(DateTime.withCurrentZoneNamed("Europe/London")) * ``` + * + * @category current time zone + * @since 3.6.0 */ (effect: Effect.Effect, zone: string): Effect.Effect> } = dual( @@ -2400,11 +2877,10 @@ export const withCurrentZoneNamed: { ) /** - * Get the current time as a `DateTime.Zoned`, using the `CurrentTimeZone`. + * Gets the current time as a `DateTime.Zoned`, using the `CurrentTimeZone`. + * + * **Example** (Getting the current time in the current zone) * - * @since 3.6.0 - * @category current time zone - * @example * ```ts * import { DateTime, Effect } from "effect" * @@ -2413,6 +2889,9 @@ export const withCurrentZoneNamed: { * const now = yield* DateTime.nowInCurrentZone * }).pipe(DateTime.withCurrentZoneNamed("Europe/London")) * ``` + * + * @category current time zone + * @since 3.6.0 */ export const nowInCurrentZone: Effect.Effect = Effect.flatMap(now, setZoneCurrent) @@ -2421,14 +2900,22 @@ export const nowInCurrentZone: Effect.Effect = Ef // ============================================================================= /** - * Modify a `DateTime` by applying a function to a cloned `Date` instance. + * Modifies a `DateTime` with a mutable local `Date` copy. + * + * **When to use** + * + * Use to adjust calendar fields in the `DateTime`'s own time zone with an + * existing `Date` mutation API. + * + * **Details** * * The `Date` will first have the time zone applied if possible, and then be * converted back to a `DateTime` within the same time zone. * * Supports `disambiguation` when the new wall clock time is ambiguous. * - * @example + * **Example** (Mutating DateTime values with Dates) + * * ```ts * import { DateTime } from "effect" * @@ -2442,8 +2929,8 @@ export const nowInCurrentZone: Effect.Effect = Ef * console.log(DateTime.formatIso(modified)) // "2024-01-01T15:30:00.000Z" * ``` * - * @since 3.6.0 * @category mapping + * @since 3.6.0 */ export const mutate: { // ============================================================================= @@ -2451,14 +2938,22 @@ export const mutate: { // ============================================================================= /** - * Modify a `DateTime` by applying a function to a cloned `Date` instance. + * Modifies a `DateTime` with a mutable local `Date` copy. + * + * **When to use** + * + * Use to adjust calendar fields in the `DateTime`'s own time zone with an + * existing `Date` mutation API. + * + * **Details** * * The `Date` will first have the time zone applied if possible, and then be * converted back to a `DateTime` within the same time zone. * * Supports `disambiguation` when the new wall clock time is ambiguous. * - * @example + * **Example** (Mutating DateTime values with Dates) + * * ```ts * import { DateTime } from "effect" * @@ -2472,8 +2967,8 @@ export const mutate: { * console.log(DateTime.formatIso(modified)) // "2024-01-01T15:30:00.000Z" * ``` * - * @since 3.6.0 * @category mapping + * @since 3.6.0 */ ( f: (date: Date) => void, @@ -2486,14 +2981,22 @@ export const mutate: { // ============================================================================= /** - * Modify a `DateTime` by applying a function to a cloned `Date` instance. + * Modifies a `DateTime` with a mutable local `Date` copy. + * + * **When to use** + * + * Use to adjust calendar fields in the `DateTime`'s own time zone with an + * existing `Date` mutation API. + * + * **Details** * * The `Date` will first have the time zone applied if possible, and then be * converted back to a `DateTime` within the same time zone. * * Supports `disambiguation` when the new wall clock time is ambiguous. * - * @example + * **Example** (Mutating DateTime values with Dates) + * * ```ts * import { DateTime } from "effect" * @@ -2507,8 +3010,8 @@ export const mutate: { * console.log(DateTime.formatIso(modified)) // "2024-01-01T15:30:00.000Z" * ``` * - * @since 3.6.0 * @category mapping + * @since 3.6.0 */ ( self: A, @@ -2520,9 +3023,15 @@ export const mutate: { } = Internal.mutate /** - * Modify a `DateTime` by applying a function to a cloned UTC `Date` instance. + * Modifies a `DateTime` with a mutable UTC `Date` copy. + * + * **When to use** + * + * Use to adjust the instant with an existing `Date` mutation API that works on + * UTC calendar fields. + * + * **Example** (Mutating DateTime values with UTC Dates) * - * @example * ```ts * import { DateTime } from "effect" * @@ -2537,14 +3046,20 @@ export const mutate: { * console.log(DateTime.formatIso(modified)) // "2024-01-01T18:00:00.000Z" * ``` * - * @since 3.6.0 * @category mapping + * @since 3.6.0 */ export const mutateUtc: { /** - * Modify a `DateTime` by applying a function to a cloned UTC `Date` instance. + * Modifies a `DateTime` with a mutable UTC `Date` copy. + * + * **When to use** + * + * Use to adjust the instant with an existing `Date` mutation API that works on + * UTC calendar fields. + * + * **Example** (Mutating DateTime values with UTC Dates) * - * @example * ```ts * import { DateTime } from "effect" * @@ -2559,14 +3074,20 @@ export const mutateUtc: { * console.log(DateTime.formatIso(modified)) // "2024-01-01T18:00:00.000Z" * ``` * - * @since 3.6.0 * @category mapping + * @since 3.6.0 */ (f: (date: Date) => void): (self: A) => A /** - * Modify a `DateTime` by applying a function to a cloned UTC `Date` instance. + * Modifies a `DateTime` with a mutable UTC `Date` copy. + * + * **When to use** + * + * Use to adjust the instant with an existing `Date` mutation API that works on + * UTC calendar fields. + * + * **Example** (Mutating DateTime values with UTC Dates) * - * @example * ```ts * import { DateTime } from "effect" * @@ -2581,19 +3102,18 @@ export const mutateUtc: { * console.log(DateTime.formatIso(modified)) // "2024-01-01T18:00:00.000Z" * ``` * - * @since 3.6.0 * @category mapping + * @since 3.6.0 */ (self: A, f: (date: Date) => void): A } = Internal.mutateUtc /** - * Transform a `DateTime` by applying a function to the number of milliseconds + * Transforms a `DateTime` by applying a function to the number of milliseconds * since the Unix epoch. * - * @since 3.6.0 - * @category mapping - * @example + * **Example** (Mapping epoch milliseconds) + * * ```ts * import { DateTime } from "effect" * @@ -2602,15 +3122,17 @@ export const mutateUtc: { * DateTime.mapEpochMillis((millis) => millis + 10) * ) * ``` + * + * @category mapping + * @since 3.6.0 */ export const mapEpochMillis: { /** - * Transform a `DateTime` by applying a function to the number of milliseconds + * Transforms a `DateTime` by applying a function to the number of milliseconds * since the Unix epoch. * - * @since 3.6.0 - * @category mapping - * @example + * **Example** (Mapping epoch milliseconds) + * * ```ts * import { DateTime } from "effect" * @@ -2619,15 +3141,17 @@ export const mapEpochMillis: { * DateTime.mapEpochMillis((millis) => millis + 10) * ) * ``` + * + * @category mapping + * @since 3.6.0 */ (f: (millis: number) => number): (self: A) => A /** - * Transform a `DateTime` by applying a function to the number of milliseconds + * Transforms a `DateTime` by applying a function to the number of milliseconds * since the Unix epoch. * - * @since 3.6.0 - * @category mapping - * @example + * **Example** (Mapping epoch milliseconds) + * * ```ts * import { DateTime } from "effect" * @@ -2636,17 +3160,25 @@ export const mapEpochMillis: { * DateTime.mapEpochMillis((millis) => millis + 10) * ) * ``` + * + * @category mapping + * @since 3.6.0 */ (self: A, f: (millis: number) => number): A } = Internal.mapEpochMillis /** - * Using the time zone adjusted `Date`, apply a function to the `Date` and - * return the result. + * Applies a function to a JavaScript `Date` representing the `DateTime` and + * returns the function's result. + * + * **Details** + * + * The callback receives the time-zone-adjusted wall-clock date for + * `DateTime.Zoned` values. Use `DateTime.withDateUtc` when the callback should + * receive the UTC instant. + * + * **Example** (Using time zone adjusted Dates) * - * @since 3.6.0 - * @category mapping - * @example * ```ts * import { DateTime } from "effect" * @@ -2655,15 +3187,23 @@ export const mapEpochMillis: { * DateTime.withDate((date) => date.getTime()) * ) * ``` + * + * @category mapping + * @since 3.6.0 */ export const withDate: { /** - * Using the time zone adjusted `Date`, apply a function to the `Date` and - * return the result. + * Applies a function to a JavaScript `Date` representing the `DateTime` and + * returns the function's result. + * + * **Details** + * + * The callback receives the time-zone-adjusted wall-clock date for + * `DateTime.Zoned` values. Use `DateTime.withDateUtc` when the callback should + * receive the UTC instant. + * + * **Example** (Using time zone adjusted Dates) * - * @since 3.6.0 - * @category mapping - * @example * ```ts * import { DateTime } from "effect" * @@ -2672,15 +3212,23 @@ export const withDate: { * DateTime.withDate((date) => date.getTime()) * ) * ``` + * + * @category mapping + * @since 3.6.0 */ (f: (date: Date) => A): (self: DateTime) => A /** - * Using the time zone adjusted `Date`, apply a function to the `Date` and - * return the result. + * Applies a function to a JavaScript `Date` representing the `DateTime` and + * returns the function's result. + * + * **Details** + * + * The callback receives the time-zone-adjusted wall-clock date for + * `DateTime.Zoned` values. Use `DateTime.withDateUtc` when the callback should + * receive the UTC instant. + * + * **Example** (Using time zone adjusted Dates) * - * @since 3.6.0 - * @category mapping - * @example * ```ts * import { DateTime } from "effect" * @@ -2689,17 +3237,24 @@ export const withDate: { * DateTime.withDate((date) => date.getTime()) * ) * ``` + * + * @category mapping + * @since 3.6.0 */ (self: DateTime, f: (date: Date) => A): A } = Internal.withDate /** - * Using the time zone adjusted `Date`, apply a function to the `Date` and - * return the result. + * Applies a function to a JavaScript `Date` representing the `DateTime`'s UTC + * instant and returns the function's result. + * + * **Details** + * + * This ignores any associated time zone. Use `DateTime.withDate` when the + * callback should receive the time-zone-adjusted wall-clock date. + * + * **Example** (Using UTC Dates) * - * @since 3.6.0 - * @category mapping - * @example * ```ts * import { DateTime } from "effect" * @@ -2708,15 +3263,22 @@ export const withDate: { * DateTime.withDateUtc((date) => date.getTime()) * ) * ``` + * + * @category mapping + * @since 3.6.0 */ export const withDateUtc: { /** - * Using the time zone adjusted `Date`, apply a function to the `Date` and - * return the result. + * Applies a function to a JavaScript `Date` representing the `DateTime`'s UTC + * instant and returns the function's result. + * + * **Details** + * + * This ignores any associated time zone. Use `DateTime.withDate` when the + * callback should receive the time-zone-adjusted wall-clock date. + * + * **Example** (Using UTC Dates) * - * @since 3.6.0 - * @category mapping - * @example * ```ts * import { DateTime } from "effect" * @@ -2725,15 +3287,22 @@ export const withDateUtc: { * DateTime.withDateUtc((date) => date.getTime()) * ) * ``` + * + * @category mapping + * @since 3.6.0 */ (f: (date: Date) => A): (self: DateTime) => A /** - * Using the time zone adjusted `Date`, apply a function to the `Date` and - * return the result. + * Applies a function to a JavaScript `Date` representing the `DateTime`'s UTC + * instant and returns the function's result. + * + * **Details** + * + * This ignores any associated time zone. Use `DateTime.withDate` when the + * callback should receive the time-zone-adjusted wall-clock date. + * + * **Example** (Using UTC Dates) * - * @since 3.6.0 - * @category mapping - * @example * ```ts * import { DateTime } from "effect" * @@ -2742,6 +3311,9 @@ export const withDateUtc: { * DateTime.withDateUtc((date) => date.getTime()) * ) * ``` + * + * @category mapping + * @since 3.6.0 */ (self: DateTime, f: (date: Date) => A): A } = Internal.withDateUtc @@ -2749,12 +3321,15 @@ export const withDateUtc: { /** * Pattern match on a `DateTime` to handle `Utc` and `Zoned` cases differently. * - * @example + * **Example** (Pattern matching DateTime variants) + * * ```ts * import { DateTime } from "effect" * - * const dt1 = DateTime.nowUnsafe() // Utc - * const dt2 = DateTime.makeZonedUnsafe(new Date(), { timeZone: "Europe/London" }) // Zoned + * const dt1 = DateTime.makeUnsafe("2024-01-01T12:00:00Z") // Utc + * const dt2 = DateTime.makeZonedUnsafe("2024-06-15T14:30:00Z", { + * timeZone: "Europe/London" + * }) // Zoned * * const result1 = DateTime.match(dt1, { * onUtc: (utc) => `UTC: ${DateTime.formatIso(utc)}`, @@ -2765,6 +3340,9 @@ export const withDateUtc: { * onUtc: (utc) => `UTC: ${DateTime.formatIso(utc)}`, * onZoned: (zoned) => `Zoned: ${DateTime.formatIsoZoned(zoned)}` * }) + * + * console.log(result1) // "UTC: 2024-01-01T12:00:00.000Z" + * console.log(result2) // "Zoned: 2024-06-15T15:30:00.000+01:00[Europe/London]" * ``` * * @category mapping @@ -2774,12 +3352,15 @@ export const match: { /** * Pattern match on a `DateTime` to handle `Utc` and `Zoned` cases differently. * - * @example + * **Example** (Pattern matching DateTime variants) + * * ```ts * import { DateTime } from "effect" * - * const dt1 = DateTime.nowUnsafe() // Utc - * const dt2 = DateTime.makeZonedUnsafe(new Date(), { timeZone: "Europe/London" }) // Zoned + * const dt1 = DateTime.makeUnsafe("2024-01-01T12:00:00Z") // Utc + * const dt2 = DateTime.makeZonedUnsafe("2024-06-15T14:30:00Z", { + * timeZone: "Europe/London" + * }) // Zoned * * const result1 = DateTime.match(dt1, { * onUtc: (utc) => `UTC: ${DateTime.formatIso(utc)}`, @@ -2790,6 +3371,9 @@ export const match: { * onUtc: (utc) => `UTC: ${DateTime.formatIso(utc)}`, * onZoned: (zoned) => `Zoned: ${DateTime.formatIsoZoned(zoned)}` * }) + * + * console.log(result1) // "UTC: 2024-01-01T12:00:00.000Z" + * console.log(result2) // "Zoned: 2024-06-15T15:30:00.000+01:00[Europe/London]" * ``` * * @category mapping @@ -2804,12 +3388,15 @@ export const match: { /** * Pattern match on a `DateTime` to handle `Utc` and `Zoned` cases differently. * - * @example + * **Example** (Pattern matching DateTime variants) + * * ```ts * import { DateTime } from "effect" * - * const dt1 = DateTime.nowUnsafe() // Utc - * const dt2 = DateTime.makeZonedUnsafe(new Date(), { timeZone: "Europe/London" }) // Zoned + * const dt1 = DateTime.makeUnsafe("2024-01-01T12:00:00Z") // Utc + * const dt2 = DateTime.makeZonedUnsafe("2024-06-15T14:30:00Z", { + * timeZone: "Europe/London" + * }) // Zoned * * const result1 = DateTime.match(dt1, { * onUtc: (utc) => `UTC: ${DateTime.formatIso(utc)}`, @@ -2820,6 +3407,9 @@ export const match: { * onUtc: (utc) => `UTC: ${DateTime.formatIso(utc)}`, * onZoned: (zoned) => `Zoned: ${DateTime.formatIsoZoned(zoned)}` * }) + * + * console.log(result1) // "UTC: 2024-01-01T12:00:00.000Z" + * console.log(result2) // "Zoned: 2024-06-15T15:30:00.000+01:00[Europe/London]" * ``` * * @category mapping @@ -2839,11 +3429,26 @@ export const match: { // ============================================================================= /** - * Add the given `Duration` to a `DateTime`. + * Adds the given `Duration` to a `DateTime`. + * + * **When to use** + * + * Use to move a `DateTime` by an elapsed duration such as minutes, seconds, or + * milliseconds. + * + * **Details** + * + * The duration is converted to milliseconds and added to the epoch + * milliseconds. Zoned values keep their original time zone. + * + * **Gotchas** + * + * This is elapsed-time arithmetic, not calendar-aware local date arithmetic. + * Use `add` when adding days, weeks, months, or years should account for the + * date/time zone rules. + * + * **Example** (Adding durations) * - * @since 3.6.0 - * @category math - * @example * ```ts * import { DateTime } from "effect" * @@ -2852,6 +3457,12 @@ export const match: { * DateTime.addDuration("5 minutes") * ) * ``` + * + * @see {@link add} for calendar-aware date/time part arithmetic + * @see {@link subtractDuration} for subtracting an elapsed duration + * + * @category math + * @since 3.6.0 */ export const addDuration: { // ============================================================================= @@ -2859,11 +3470,26 @@ export const addDuration: { // ============================================================================= /** - * Add the given `Duration` to a `DateTime`. + * Adds the given `Duration` to a `DateTime`. + * + * **When to use** + * + * Use to move a `DateTime` by an elapsed duration such as minutes, seconds, or + * milliseconds. + * + * **Details** + * + * The duration is converted to milliseconds and added to the epoch + * milliseconds. Zoned values keep their original time zone. + * + * **Gotchas** + * + * This is elapsed-time arithmetic, not calendar-aware local date arithmetic. + * Use `add` when adding days, weeks, months, or years should account for the + * date/time zone rules. + * + * **Example** (Adding durations) * - * @since 3.6.0 - * @category math - * @example * ```ts * import { DateTime } from "effect" * @@ -2872,6 +3498,12 @@ export const addDuration: { * DateTime.addDuration("5 minutes") * ) * ``` + * + * @see {@link add} for calendar-aware date/time part arithmetic + * @see {@link subtractDuration} for subtracting an elapsed duration + * + * @category math + * @since 3.6.0 */ (duration: Duration.Input): (self: A) => A // ============================================================================= @@ -2879,11 +3511,26 @@ export const addDuration: { // ============================================================================= /** - * Add the given `Duration` to a `DateTime`. + * Adds the given `Duration` to a `DateTime`. + * + * **When to use** + * + * Use to move a `DateTime` by an elapsed duration such as minutes, seconds, or + * milliseconds. + * + * **Details** + * + * The duration is converted to milliseconds and added to the epoch + * milliseconds. Zoned values keep their original time zone. + * + * **Gotchas** + * + * This is elapsed-time arithmetic, not calendar-aware local date arithmetic. + * Use `add` when adding days, weeks, months, or years should account for the + * date/time zone rules. + * + * **Example** (Adding durations) * - * @since 3.6.0 - * @category math - * @example * ```ts * import { DateTime } from "effect" * @@ -2892,16 +3539,21 @@ export const addDuration: { * DateTime.addDuration("5 minutes") * ) * ``` + * + * @see {@link add} for calendar-aware date/time part arithmetic + * @see {@link subtractDuration} for subtracting an elapsed duration + * + * @category math + * @since 3.6.0 */ (self: A, duration: Duration.Input): A } = Internal.addDuration /** - * Subtract the given `Duration` from a `DateTime`. + * Subtracts the given `Duration` from a `DateTime`. + * + * **Example** (Subtracting durations) * - * @since 3.6.0 - * @category math - * @example * ```ts * import { DateTime } from "effect" * @@ -2910,14 +3562,16 @@ export const addDuration: { * DateTime.subtractDuration("5 minutes") * ) * ``` + * + * @category math + * @since 3.6.0 */ export const subtractDuration: { /** - * Subtract the given `Duration` from a `DateTime`. + * Subtracts the given `Duration` from a `DateTime`. + * + * **Example** (Subtracting durations) * - * @since 3.6.0 - * @category math - * @example * ```ts * import { DateTime } from "effect" * @@ -2926,14 +3580,16 @@ export const subtractDuration: { * DateTime.subtractDuration("5 minutes") * ) * ``` + * + * @category math + * @since 3.6.0 */ (duration: Duration.Input): (self: A) => A /** - * Subtract the given `Duration` from a `DateTime`. + * Subtracts the given `Duration` from a `DateTime`. + * + * **Example** (Subtracting durations) * - * @since 3.6.0 - * @category math - * @example * ```ts * import { DateTime } from "effect" * @@ -2942,19 +3598,23 @@ export const subtractDuration: { * DateTime.subtractDuration("5 minutes") * ) * ``` + * + * @category math + * @since 3.6.0 */ (self: A, duration: Duration.Input): A } = Internal.subtractDuration /** - * Add the given `amount` of `unit`'s to a `DateTime`. + * Adds the given `amount` of `unit` to a `DateTime`. + * + * **Details** * * The time zone is taken into account when adding days, weeks, months, and * years. * - * @since 3.6.0 - * @category math - * @example + * **Example** (Adding date and time parts) + * * ```ts * import { DateTime } from "effect" * @@ -2963,17 +3623,21 @@ export const subtractDuration: { * DateTime.add({ minutes: 5 }) * ) * ``` + * + * @category math + * @since 3.6.0 */ export const add: { /** - * Add the given `amount` of `unit`'s to a `DateTime`. + * Adds the given `amount` of `unit` to a `DateTime`. + * + * **Details** * * The time zone is taken into account when adding days, weeks, months, and * years. * - * @since 3.6.0 - * @category math - * @example + * **Example** (Adding date and time parts) + * * ```ts * import { DateTime } from "effect" * @@ -2982,17 +3646,21 @@ export const add: { * DateTime.add({ minutes: 5 }) * ) * ``` + * + * @category math + * @since 3.6.0 */ (parts: Partial): (self: A) => A /** - * Add the given `amount` of `unit`'s to a `DateTime`. + * Adds the given `amount` of `unit` to a `DateTime`. + * + * **Details** * * The time zone is taken into account when adding days, weeks, months, and * years. * - * @since 3.6.0 - * @category math - * @example + * **Example** (Adding date and time parts) + * * ```ts * import { DateTime } from "effect" * @@ -3001,16 +3669,18 @@ export const add: { * DateTime.add({ minutes: 5 }) * ) * ``` + * + * @category math + * @since 3.6.0 */ (self: A, parts: Partial): A } = Internal.add /** - * Subtract the given `amount` of `unit`'s from a `DateTime`. + * Subtracts the given `amount` of `unit` from a `DateTime`. + * + * **Example** (Subtracting date and time parts) * - * @since 3.6.0 - * @category math - * @example * ```ts * import { DateTime } from "effect" * @@ -3019,14 +3689,16 @@ export const add: { * DateTime.subtract({ minutes: 5 }) * ) * ``` + * + * @category math + * @since 3.6.0 */ export const subtract: { /** - * Subtract the given `amount` of `unit`'s from a `DateTime`. + * Subtracts the given `amount` of `unit` from a `DateTime`. + * + * **Example** (Subtracting date and time parts) * - * @since 3.6.0 - * @category math - * @example * ```ts * import { DateTime } from "effect" * @@ -3035,14 +3707,16 @@ export const subtract: { * DateTime.subtract({ minutes: 5 }) * ) * ``` + * + * @category math + * @since 3.6.0 */ (parts: Partial): (self: A) => A /** - * Subtract the given `amount` of `unit`'s from a `DateTime`. + * Subtracts the given `amount` of `unit` from a `DateTime`. + * + * **Example** (Subtracting date and time parts) * - * @since 3.6.0 - * @category math - * @example * ```ts * import { DateTime } from "effect" * @@ -3051,6 +3725,9 @@ export const subtract: { * DateTime.subtract({ minutes: 5 }) * ) * ``` + * + * @category math + * @since 3.6.0 */ (self: A, parts: Partial): A } = Internal.subtract @@ -3058,12 +3735,13 @@ export const subtract: { /** * Converts a `DateTime` to the start of the given `part`. * + * **Details** + * * If the part is `week`, the `weekStartsOn` option can be used to specify the * day of the week that the week starts on. The default is 0 (Sunday). * - * @since 3.6.0 - * @category math - * @example + * **Example** (Rounding down DateTime values) + * * ```ts * import { DateTime } from "effect" * @@ -3073,17 +3751,21 @@ export const subtract: { * DateTime.formatIso * ) * ``` + * + * @category math + * @since 3.6.0 */ export const startOf: { /** * Converts a `DateTime` to the start of the given `part`. * + * **Details** + * * If the part is `week`, the `weekStartsOn` option can be used to specify the * day of the week that the week starts on. The default is 0 (Sunday). * - * @since 3.6.0 - * @category math - * @example + * **Example** (Rounding down DateTime values) + * * ```ts * import { DateTime } from "effect" * @@ -3093,6 +3775,9 @@ export const startOf: { * DateTime.formatIso * ) * ``` + * + * @category math + * @since 3.6.0 */ ( part: DateTime.UnitSingular, @@ -3101,12 +3786,13 @@ export const startOf: { /** * Converts a `DateTime` to the start of the given `part`. * + * **Details** + * * If the part is `week`, the `weekStartsOn` option can be used to specify the * day of the week that the week starts on. The default is 0 (Sunday). * - * @since 3.6.0 - * @category math - * @example + * **Example** (Rounding down DateTime values) + * * ```ts * import { DateTime } from "effect" * @@ -3116,6 +3802,9 @@ export const startOf: { * DateTime.formatIso * ) * ``` + * + * @category math + * @since 3.6.0 */ ( self: A, @@ -3127,12 +3816,13 @@ export const startOf: { /** * Converts a `DateTime` to the end of the given `part`. * + * **Details** + * * If the part is `week`, the `weekStartsOn` option can be used to specify the * day of the week that the week starts on. The default is 0 (Sunday). * - * @since 3.6.0 - * @category math - * @example + * **Example** (Rounding up DateTime values) + * * ```ts * import { DateTime } from "effect" * @@ -3142,17 +3832,21 @@ export const startOf: { * DateTime.formatIso * ) * ``` + * + * @category math + * @since 3.6.0 */ export const endOf: { /** * Converts a `DateTime` to the end of the given `part`. * + * **Details** + * * If the part is `week`, the `weekStartsOn` option can be used to specify the * day of the week that the week starts on. The default is 0 (Sunday). * - * @since 3.6.0 - * @category math - * @example + * **Example** (Rounding up DateTime values) + * * ```ts * import { DateTime } from "effect" * @@ -3162,6 +3856,9 @@ export const endOf: { * DateTime.formatIso * ) * ``` + * + * @category math + * @since 3.6.0 */ ( part: DateTime.UnitSingular, @@ -3170,12 +3867,13 @@ export const endOf: { /** * Converts a `DateTime` to the end of the given `part`. * + * **Details** + * * If the part is `week`, the `weekStartsOn` option can be used to specify the * day of the week that the week starts on. The default is 0 (Sunday). * - * @since 3.6.0 - * @category math - * @example + * **Example** (Rounding up DateTime values) + * * ```ts * import { DateTime } from "effect" * @@ -3185,6 +3883,9 @@ export const endOf: { * DateTime.formatIso * ) * ``` + * + * @category math + * @since 3.6.0 */ ( self: A, @@ -3196,12 +3897,13 @@ export const endOf: { /** * Converts a `DateTime` to the nearest given `part`. * + * **Details** + * * If the part is `week`, the `weekStartsOn` option can be used to specify the * day of the week that the week starts on. The default is 0 (Sunday). * - * @since 3.6.0 - * @category math - * @example + * **Example** (Rounding DateTime values to nearest units) + * * ```ts * import { DateTime } from "effect" * @@ -3211,17 +3913,21 @@ export const endOf: { * DateTime.formatIso * ) * ``` + * + * @category math + * @since 3.6.0 */ export const nearest: { /** * Converts a `DateTime` to the nearest given `part`. * + * **Details** + * * If the part is `week`, the `weekStartsOn` option can be used to specify the * day of the week that the week starts on. The default is 0 (Sunday). * - * @since 3.6.0 - * @category math - * @example + * **Example** (Rounding DateTime values to nearest units) + * * ```ts * import { DateTime } from "effect" * @@ -3231,6 +3937,9 @@ export const nearest: { * DateTime.formatIso * ) * ``` + * + * @category math + * @since 3.6.0 */ ( part: DateTime.UnitSingular, @@ -3239,12 +3948,13 @@ export const nearest: { /** * Converts a `DateTime` to the nearest given `part`. * + * **Details** + * * If the part is `week`, the `weekStartsOn` option can be used to specify the * day of the week that the week starts on. The default is 0 (Sunday). * - * @since 3.6.0 - * @category math - * @example + * **Example** (Rounding DateTime values to nearest units) + * * ```ts * import { DateTime } from "effect" * @@ -3254,6 +3964,9 @@ export const nearest: { * DateTime.formatIso * ) * ``` + * + * @category math + * @since 3.6.0 */ ( self: A, @@ -3267,14 +3980,19 @@ export const nearest: { // ============================================================================= /** - * Format a `DateTime` as a string using the `DateTimeFormat` API. + * Formats a `DateTime` with `Intl.DateTimeFormat`. + * + * **Details** + * + * Unless a `timeZone` option is supplied, UTC values are formatted in UTC and + * zoned values are formatted in their named zone or fixed-offset zone. * - * The `timeZone` option is set to the offset of the time zone. + * Fixed-offset zones depend on runtime support for offset `timeZone` + * identifiers. When unsupported, formatting falls back to UTC with the + * `DateTime` adjusted to the offset. * - * Note: On Node versions < 22, fixed "Offset" zones will set the time zone to - * "UTC" and use the adjusted `Date`. + * **Example** (Formatting DateTime values with Intl options) * - * @example * ```ts * import { DateTime } from "effect" * @@ -3291,8 +4009,8 @@ export const nearest: { * console.log(formatted) // "Saturday, June 15, 2024 at 3:30 PM" * ``` * - * @since 3.6.0 * @category formatting + * @since 3.6.0 */ export const format: { // ============================================================================= @@ -3300,14 +4018,19 @@ export const format: { // ============================================================================= /** - * Format a `DateTime` as a string using the `DateTimeFormat` API. + * Formats a `DateTime` with `Intl.DateTimeFormat`. + * + * **Details** + * + * Unless a `timeZone` option is supplied, UTC values are formatted in UTC and + * zoned values are formatted in their named zone or fixed-offset zone. * - * The `timeZone` option is set to the offset of the time zone. + * Fixed-offset zones depend on runtime support for offset `timeZone` + * identifiers. When unsupported, formatting falls back to UTC with the + * `DateTime` adjusted to the offset. * - * Note: On Node versions < 22, fixed "Offset" zones will set the time zone to - * "UTC" and use the adjusted `Date`. + * **Example** (Formatting DateTime values with Intl options) * - * @example * ```ts * import { DateTime } from "effect" * @@ -3324,8 +4047,8 @@ export const format: { * console.log(formatted) // "Saturday, June 15, 2024 at 3:30 PM" * ``` * - * @since 3.6.0 * @category formatting + * @since 3.6.0 */ ( options?: @@ -3339,14 +4062,19 @@ export const format: { // ============================================================================= /** - * Format a `DateTime` as a string using the `DateTimeFormat` API. + * Formats a `DateTime` with `Intl.DateTimeFormat`. + * + * **Details** + * + * Unless a `timeZone` option is supplied, UTC values are formatted in UTC and + * zoned values are formatted in their named zone or fixed-offset zone. * - * The `timeZone` option is set to the offset of the time zone. + * Fixed-offset zones depend on runtime support for offset `timeZone` + * identifiers. When unsupported, formatting falls back to UTC with the + * `DateTime` adjusted to the offset. * - * Note: On Node versions < 22, fixed "Offset" zones will set the time zone to - * "UTC" and use the adjusted `Date`. + * **Example** (Formatting DateTime values with Intl options) * - * @example * ```ts * import { DateTime } from "effect" * @@ -3363,8 +4091,8 @@ export const format: { * console.log(formatted) // "Saturday, June 15, 2024 at 3:30 PM" * ``` * - * @since 3.6.0 * @category formatting + * @since 3.6.0 */ ( self: DateTime, @@ -3377,11 +4105,11 @@ export const format: { } = Internal.format /** - * Format a `DateTime` as a string using the `DateTimeFormat` API. + * Formats a `DateTime` with `Intl.DateTimeFormat` using the system local time + * zone and locale. * - * It will use the system's local time zone & locale. + * **Example** (Formatting DateTime values locally) * - * @example * ```ts * import { DateTime } from "effect" * @@ -3399,16 +4127,16 @@ export const format: { * console.log(local) // Output depends on system locale/timezone * ``` * - * @since 3.6.0 * @category formatting + * @since 3.6.0 */ export const formatLocal: { /** - * Format a `DateTime` as a string using the `DateTimeFormat` API. + * Formats a `DateTime` with `Intl.DateTimeFormat` using the system local time + * zone and locale. * - * It will use the system's local time zone & locale. + * **Example** (Formatting DateTime values locally) * - * @example * ```ts * import { DateTime } from "effect" * @@ -3426,8 +4154,8 @@ export const formatLocal: { * console.log(local) // Output depends on system locale/timezone * ``` * - * @since 3.6.0 * @category formatting + * @since 3.6.0 */ ( options?: @@ -3437,11 +4165,11 @@ export const formatLocal: { | undefined ): (self: DateTime) => string /** - * Format a `DateTime` as a string using the `DateTimeFormat` API. + * Formats a `DateTime` with `Intl.DateTimeFormat` using the system local time + * zone and locale. * - * It will use the system's local time zone & locale. + * **Example** (Formatting DateTime values locally) * - * @example * ```ts * import { DateTime } from "effect" * @@ -3459,8 +4187,8 @@ export const formatLocal: { * console.log(local) // Output depends on system locale/timezone * ``` * - * @since 3.6.0 * @category formatting + * @since 3.6.0 */ ( self: DateTime, @@ -3473,11 +4201,14 @@ export const formatLocal: { } = Internal.formatLocal /** - * Format a `DateTime` as a string using the `DateTimeFormat` API. + * Formats a `DateTime` with `Intl.DateTimeFormat` using the UTC time zone. + * + * **Details** * * This forces the time zone to be UTC. * - * @example + * **Example** (Formatting DateTime values in UTC) + * * ```ts * import { DateTime } from "effect" * @@ -3498,16 +4229,19 @@ export const formatLocal: { * console.log(utcFormatted) // "06/15/2024, 02:30 PM UTC" * ``` * - * @since 3.6.0 * @category formatting + * @since 3.6.0 */ export const formatUtc: { /** - * Format a `DateTime` as a string using the `DateTimeFormat` API. + * Formats a `DateTime` with `Intl.DateTimeFormat` using the UTC time zone. + * + * **Details** * * This forces the time zone to be UTC. * - * @example + * **Example** (Formatting DateTime values in UTC) + * * ```ts * import { DateTime } from "effect" * @@ -3528,8 +4262,8 @@ export const formatUtc: { * console.log(utcFormatted) // "06/15/2024, 02:30 PM UTC" * ``` * - * @since 3.6.0 * @category formatting + * @since 3.6.0 */ ( options?: @@ -3539,11 +4273,14 @@ export const formatUtc: { | undefined ): (self: DateTime) => string /** - * Format a `DateTime` as a string using the `DateTimeFormat` API. + * Formats a `DateTime` with `Intl.DateTimeFormat` using the UTC time zone. + * + * **Details** * * This forces the time zone to be UTC. * - * @example + * **Example** (Formatting DateTime values in UTC) + * * ```ts * import { DateTime } from "effect" * @@ -3564,8 +4301,8 @@ export const formatUtc: { * console.log(utcFormatted) // "06/15/2024, 02:30 PM UTC" * ``` * - * @since 3.6.0 * @category formatting + * @since 3.6.0 */ ( self: DateTime, @@ -3578,9 +4315,20 @@ export const formatUtc: { } = Internal.formatUtc /** - * Format a `DateTime` as a string using the `DateTimeFormat` API. + * Formats a `DateTime` as a string using the `Intl.DateTimeFormat` API. + * + * **When to use** + * + * Use when you already have an `Intl.DateTimeFormat` and want it to control the + * locale, time zone, and formatting options. + * + * **Details** + * + * The formatter receives the `DateTime` epoch milliseconds. Any time zone + * conversion comes from the supplied formatter. + * + * **Example** (Formatting DateTime values with custom formatters) * - * @example * ```ts * import { DateTime } from "effect" * @@ -3597,17 +4345,31 @@ export const formatUtc: { * }) * * const formatted = DateTime.formatIntl(dt, formatter) - * console.log(formatted) // "15. Juni 2024, 16:30" + * console.log(formatted.length > 0) // true * ``` * - * @since 3.6.0 + * @see {@link formatUtc} for formatting with options forced to UTC + * @see {@link formatIso} for stable ISO formatting + * * @category formatting + * @since 3.6.0 */ export const formatIntl: { /** - * Format a `DateTime` as a string using the `DateTimeFormat` API. + * Formats a `DateTime` as a string using the `Intl.DateTimeFormat` API. + * + * **When to use** + * + * Use when you already have an `Intl.DateTimeFormat` and want it to control the + * locale, time zone, and formatting options. + * + * **Details** + * + * The formatter receives the `DateTime` epoch milliseconds. Any time zone + * conversion comes from the supplied formatter. + * + * **Example** (Formatting DateTime values with custom formatters) * - * @example * ```ts * import { DateTime } from "effect" * @@ -3624,17 +4386,31 @@ export const formatIntl: { * }) * * const formatted = DateTime.formatIntl(dt, formatter) - * console.log(formatted) // "15. Juni 2024, 16:30" + * console.log(formatted.length > 0) // true * ``` * - * @since 3.6.0 + * @see {@link formatUtc} for formatting with options forced to UTC + * @see {@link formatIso} for stable ISO formatting + * * @category formatting + * @since 3.6.0 */ (format: Intl.DateTimeFormat): (self: DateTime) => string /** - * Format a `DateTime` as a string using the `DateTimeFormat` API. + * Formats a `DateTime` as a string using the `Intl.DateTimeFormat` API. + * + * **When to use** + * + * Use when you already have an `Intl.DateTimeFormat` and want it to control the + * locale, time zone, and formatting options. + * + * **Details** + * + * The formatter receives the `DateTime` epoch milliseconds. Any time zone + * conversion comes from the supplied formatter. + * + * **Example** (Formatting DateTime values with custom formatters) * - * @example * ```ts * import { DateTime } from "effect" * @@ -3651,21 +4427,27 @@ export const formatIntl: { * }) * * const formatted = DateTime.formatIntl(dt, formatter) - * console.log(formatted) // "15. Juni 2024, 16:30" + * console.log(formatted.length > 0) // true * ``` * - * @since 3.6.0 + * @see {@link formatUtc} for formatting with options forced to UTC + * @see {@link formatIso} for stable ISO formatting + * * @category formatting + * @since 3.6.0 */ (self: DateTime, format: Intl.DateTimeFormat): string } = Internal.formatIntl /** - * Format a `DateTime` as a UTC ISO string. + * Formats a `DateTime` as a UTC ISO string. + * + * **Details** * * Always returns the UTC representation in ISO 8601 format, ignoring any time zone. * - * @example + * **Example** (Formatting DateTime values as ISO strings) + * * ```ts * import { DateTime } from "effect" * @@ -3684,11 +4466,14 @@ export const formatIntl: { export const formatIso: (self: DateTime) => string = Internal.formatIso /** - * Format a `DateTime` as a time zone adjusted ISO date string. + * Formats a `DateTime` as a time zone adjusted ISO date string. + * + * **Details** * * Returns only the date part (YYYY-MM-DD) after applying time zone adjustments. * - * @example + * **Example** (Formatting DateTime values as ISO dates) + * * ```ts * import { DateTime } from "effect" * @@ -3707,11 +4492,14 @@ export const formatIso: (self: DateTime) => string = Internal.formatIso export const formatIsoDate: (self: DateTime) => string = Internal.formatIsoDate /** - * Format a `DateTime` as a UTC ISO date string. + * Formats a `DateTime` as a UTC ISO date string. + * + * **Details** * * Returns only the date part (YYYY-MM-DD) in UTC, ignoring any time zone. * - * @example + * **Example** (Formatting DateTime values as UTC ISO dates) + * * ```ts * import { DateTime } from "effect" * @@ -3730,12 +4518,15 @@ export const formatIsoDate: (self: DateTime) => string = Internal.formatIsoDate export const formatIsoDateUtc: (self: DateTime) => string = Internal.formatIsoDateUtc /** - * Format a `DateTime.Zoned` as an ISO string with an offset. + * Formats a `DateTime.Zoned` as an ISO string with an offset. + * + * **Details** * * For `DateTime.Utc`, returns the same as `formatIso`. For `DateTime.Zoned`, * includes the time zone offset in the format. * - * @example + * **Example** (Formatting DateTime values with offsets) + * * ```ts * import { DateTime } from "effect" * @@ -3754,11 +4545,14 @@ export const formatIsoDateUtc: (self: DateTime) => string = Internal.formatIsoDa export const formatIsoOffset: (self: DateTime) => string = Internal.formatIsoOffset /** - * Format a `DateTime.Zoned` as a string. + * Formats a `DateTime.Zoned` as a string. + * + * **Details** * * It uses the format: `YYYY-MM-DDTHH:mm:ss.sss+HH:MM[Time/Zone]`. * - * @example + * **Example** (Formatting zoned DateTime values) + * * ```ts * import { DateTime } from "effect" * @@ -3777,17 +4571,20 @@ export const formatIsoOffset: (self: DateTime) => string = Internal.formatIsoOff * console.log(offsetFormatted) // "2024-06-15T17:30:45.123+03:00" * ``` * - * @since 3.6.0 * @category formatting + * @since 3.6.0 */ export const formatIsoZoned: (self: Zoned) => string = Internal.formatIsoZoned /** * Create a Layer from the given time zone. * + * **Details** + * * This layer provides the `CurrentTimeZone` service with the specified time zone. * - * @example + * **Example** (Providing current time zone layers) + * * ```ts * import { DateTime, Effect } from "effect" * @@ -3813,9 +4610,12 @@ export const layerCurrentZone: (resource: NoInfer) => Layer.Layer Layer.Layer< /** * Create a Layer from the system's local time zone. * + * **Details** + * * This layer provides the `CurrentTimeZone` service using the system's * configured local time zone. * - * @example + * **Example** (Providing local time zone layers) + * * ```ts * import { DateTime, Effect } from "effect" * diff --git a/.opencode/node_modules/effect/src/Deferred.ts b/.opencode/node_modules/effect/src/Deferred.ts index 8e0a22511606ebf4e73f6645529f3f639e8c247b..f6d37948bfbe690a7998b06c562e434e1b8ae084 100644 --- a/.opencode/node_modules/effect/src/Deferred.ts +++ b/.opencode/node_modules/effect/src/Deferred.ts @@ -1,68 +1,9 @@ /** - * This module provides utilities for working with `Deferred`, a powerful concurrency - * primitive that represents an asynchronous variable that can be set exactly once. - * Multiple fibers can await the same `Deferred` and will all be notified when it - * completes. - * - * A `Deferred` can be: - * - **Completed successfully** with a value of type `A` - * - **Failed** with an error of type `E` - * - **Interrupted** if the fiber setting it is interrupted - * - * Key characteristics: - * - **Single assignment**: Can only be completed once - * - **Multiple waiters**: Many fibers can await the same `Deferred` - * - **Fiber-safe**: Thread-safe operations across concurrent fibers - * - **Composable**: Works seamlessly with other Effect operations - * - * @example - * ```ts - * import { Deferred, Effect, Fiber } from "effect" - * - * // Basic usage: coordinate between fibers - * const program = Effect.gen(function*() { - * const deferred = yield* Deferred.make() - * - * // Fiber 1: waits for the value - * const waiter = yield* Effect.forkChild( - * Effect.gen(function*() { - * const value = yield* Deferred.await(deferred) - * console.log("Received:", value) - * return value - * }) - * ) - * - * // Fiber 2: sets the value after a delay - * const setter = yield* Effect.forkChild( - * Effect.gen(function*() { - * yield* Effect.sleep("1 second") - * yield* Deferred.succeed(deferred, "Hello from setter!") - * }) - * ) - * - * // Wait for both fibers - * yield* Fiber.join(waiter) - * yield* Fiber.join(setter) - * }) - * - * // Producer-consumer pattern - * const producerConsumer = Effect.gen(function*() { - * const buffer = yield* Deferred.make, never>() - * - * const producer = Effect.gen(function*() { - * const data = [1, 2, 3, 4, 5] - * yield* Deferred.succeed(buffer, data) - * }) - * - * const consumer = Effect.gen(function*() { - * const data = yield* Deferred.await(buffer) - * return data.reduce((sum, n) => sum + n, 0) - * }) - * - * const [, result] = yield* Effect.all([producer, consumer]) - * return result // 15 - * }) - * ``` + * One-time coordination cells for Effect programs. A `Deferred` starts + * empty, can be completed exactly once with a success, failure, defect, or + * interruption, and lets any number of fibers wait for that result. Awaiting a + * `Deferred` suspends the fiber instead of blocking an operating-system thread, + * and every waiter observes the same completion. * * @since 2.0.0 */ @@ -85,11 +26,13 @@ const TypeId = "~effect/Deferred" * 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. + * **When to use** + * + * Use to coordinate multiple fibers around a value or failure that will be + * supplied exactly once. + * + * **Example** (Creating a Deferred for inter-fiber communication) * - * @example * ```ts * import { Deferred, Effect, Fiber } from "effect" * @@ -122,8 +65,8 @@ const TypeId = "~effect/Deferred" * }) * ``` * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface Deferred extends Deferred.Variance, Pipeable { effect?: Effect @@ -131,19 +74,43 @@ export interface Deferred extends Deferred.Variance< } /** - * @since 2.0.0 - * @category Guards + * Checks whether a value is a `Deferred`. + * + * **When to use** + * + * Use to validate unknown values at runtime boundaries before treating them as + * `Deferred` values. + * + * @category guards + * @since 4.0.0 */ export const isDeferred = (u: unknown): u is Deferred => hasProperty(u, TypeId) /** + * Companion namespace containing type-level metadata for `Deferred`. + * + * **When to use** + * + * Use to reference type-level metadata associated with `Deferred`. + * * @since 2.0.0 - * @category models */ export declare namespace Deferred { /** - * @since 2.0.0 + * Type-level variance marker for the value and error channels of `Deferred`. + * + * **When to use** + * + * Use to carry the value and error type parameters for `Deferred` in Effect's + * type machinery. + * + * **Details** + * + * This interface is part of the public type structure and is not intended to + * be constructed directly. + * * @category models + * @since 2.0.0 */ export interface Variance { readonly [TypeId]: { @@ -164,9 +131,15 @@ const DeferredProto = { } /** - * Unsafely creates a new `Deferred` + * Creates an empty `Deferred` synchronously outside the `Effect` runtime. + * + * **When to use** + * + * Use to allocate a `Deferred` synchronously when direct allocation outside + * `Effect` is required. + * + * **Example** (Creating a Deferred unsafely) * - * @example * ```ts * import { Deferred } from "effect" * @@ -174,8 +147,8 @@ const DeferredProto = { * console.log(deferred) * ``` * - * @since 2.0.0 * @category unsafe + * @since 4.0.0 */ export const makeUnsafe = (): Deferred => { const self = Object.create(DeferredProto) @@ -187,7 +160,12 @@ export const makeUnsafe = (): Deferred => { /** * Creates a new `Deferred`. * - * @example + * **When to use** + * + * Use to allocate an empty `Deferred` inside an `Effect` workflow. + * + * **Example** (Creating a Deferred) + * * ```ts * import { Deferred, Effect } from "effect" * @@ -199,8 +177,8 @@ export const makeUnsafe = (): Deferred => { * }) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const make = (): Effect> => internalEffect.sync(() => makeUnsafe()) @@ -220,7 +198,17 @@ export { * Retrieves the value of the `Deferred`, suspending the fiber running the * workflow until the result is available. * - * @example + * **When to use** + * + * Use to wait for a `Deferred` to be completed and resume with its success, + * failure, defect, or interruption. + * + * **Details** + * + * Awaiters observe the completion effect stored in the `Deferred`. + * + * **Example** (Awaiting a Deferred value) + * * ```ts * import { Deferred, Effect } from "effect" * @@ -233,20 +221,31 @@ export { * }) * ``` * - * @since 2.0.0 + * @see {@link complete} for completing from an effect and memoizing its result + * @see {@link completeWith} for completing with an effect directly + * * @category getters + * @since 2.0.0 */ _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. + * Runs the supplied `Effect` and attempts to complete the `Deferred` with its + * memoized result. * - * 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. + * **When to use** + * + * Use when completing a `Deferred` should run an effect once and share its + * result with all awaiters. + * + * **Details** + * + * The returned effect succeeds with `true` when this call completed the + * `Deferred`, or `false` if it was already completed. + * + * **Example** (Completing a Deferred from an effect) * - * @example * ```ts * import { Deferred, Effect } from "effect" * @@ -260,18 +259,28 @@ export { * }) * ``` * + * @see {@link completeWith} for storing an effect directly without memoizing its result + * + * @category completion * @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. + * Runs the supplied `Effect` and attempts to complete the `Deferred` with its + * memoized result. + * + * **When to use** * - * 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. + * Use when completing a `Deferred` should run an effect once and share its + * result with all awaiters. + * + * **Details** + * + * The returned effect succeeds with `true` when this call completed the + * `Deferred`, or `false` if it was already completed. + * + * **Example** (Completing a Deferred from an effect) * - * @example * ```ts * import { Deferred, Effect } from "effect" * @@ -285,18 +294,28 @@ export const complete: { * }) * ``` * + * @see {@link completeWith} for storing an effect directly without memoizing its result + * + * @category completion * @since 2.0.0 - * @category utils */ (effect: Effect): (self: Deferred) => Effect /** - * Completes the deferred with the result of the specified effect. If the - * deferred has already been completed, the method will produce false. + * Runs the supplied `Effect` and attempts to complete the `Deferred` with its + * memoized result. * - * 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. + * **When to use** + * + * Use when completing a `Deferred` should run an effect once and share its + * result with all awaiters. + * + * **Details** + * + * The returned effect succeeds with `true` when this call completed the + * `Deferred`, or `false` if it was already completed. + * + * **Example** (Completing a Deferred from an effect) * - * @example * ```ts * import { Deferred, Effect } from "effect" * @@ -310,8 +329,10 @@ export const complete: { * }) * ``` * + * @see {@link completeWith} for storing an effect directly without memoizing its result + * + * @category completion * @since 2.0.0 - * @category utils */ (self: Deferred, effect: Effect): Effect } = dual( @@ -321,10 +342,25 @@ 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. + * Attempts to complete the `Deferred` with the specified effect directly. + * + * **When to use** + * + * Use to store an already environment-free effect as the completion without + * running it during completion. + * + * **Details** + * + * The returned effect succeeds with `true` when this call completed the + * `Deferred`, or `false` if it was already completed. + * + * **Gotchas** + * + * The supplied effect is not memoized by `completeWith`; each awaiter may run + * the stored effect independently. + * + * **Example** (Completing a Deferred with an effect) * - * @example * ```ts * import { Deferred, Effect } from "effect" * @@ -338,15 +374,33 @@ export const complete: { * }) * ``` * + * @see {@link complete} for running an effect once and sharing its result + * @see {@link done} for completing from an already computed `Exit` + * + * @category completion * @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. + * Attempts to complete the `Deferred` with the specified effect directly. + * + * **When to use** + * + * Use to store an already environment-free effect as the completion without + * running it during completion. + * + * **Details** + * + * The returned effect succeeds with `true` when this call completed the + * `Deferred`, or `false` if it was already completed. + * + * **Gotchas** + * + * The supplied effect is not memoized by `completeWith`; each awaiter may run + * the stored effect independently. + * + * **Example** (Completing a Deferred with an effect) * - * @example * ```ts * import { Deferred, Effect } from "effect" * @@ -360,15 +414,33 @@ export const completeWith: { * }) * ``` * + * @see {@link complete} for running an effect once and sharing its result + * @see {@link done} for completing from an already computed `Exit` + * + * @category completion * @since 2.0.0 - * @category utils */ (effect: Effect): (self: Deferred) => Effect /** - * Completes the deferred with the result of the specified effect. If the - * deferred has already been completed, the method will produce false. + * Attempts to complete the `Deferred` with the specified effect directly. + * + * **When to use** + * + * Use to store an already environment-free effect as the completion without + * running it during completion. + * + * **Details** + * + * The returned effect succeeds with `true` when this call completed the + * `Deferred`, or `false` if it was already completed. + * + * **Gotchas** + * + * The supplied effect is not memoized by `completeWith`; each awaiter may run + * the stored effect independently. + * + * **Example** (Completing a Deferred with an effect) * - * @example * ```ts * import { Deferred, Effect } from "effect" * @@ -382,8 +454,11 @@ export const completeWith: { * }) * ``` * + * @see {@link complete} for running an effect once and sharing its result + * @see {@link done} for completing from an already computed `Exit` + * + * @category completion * @since 2.0.0 - * @category utils */ (self: Deferred, effect: Effect): Effect } = dual( @@ -393,10 +468,20 @@ export const completeWith: { ) /** - * Exits the `Deferred` with the specified `Exit` value, which will be + * Completes the `Deferred` with the specified `Exit` value, which will be * propagated to all fibers waiting on the value of the `Deferred`. * - * @example + * **When to use** + * + * Use to complete a `Deferred` from an already computed `Exit`. + * + * **Details** + * + * The returned effect succeeds with `true` when this call completed the + * `Deferred`, or `false` if it was already completed. + * + * **Example** (Completing a Deferred with an Exit) + * * ```ts * import { Deferred, Effect, Exit } from "effect" * @@ -409,15 +494,30 @@ export const completeWith: { * }) * ``` * + * @see {@link complete} for completing from an effect and memoizing its result + * @see {@link completeWith} for storing an effect directly + * @see {@link succeed} for completing with a success value + * @see {@link failCause} for completing with a failure cause + * + * @category completion * @since 2.0.0 - * @category utils */ export const done: { /** - * Exits the `Deferred` with the specified `Exit` value, which will be + * Completes the `Deferred` with the specified `Exit` value, which will be * propagated to all fibers waiting on the value of the `Deferred`. * - * @example + * **When to use** + * + * Use to complete a `Deferred` from an already computed `Exit`. + * + * **Details** + * + * The returned effect succeeds with `true` when this call completed the + * `Deferred`, or `false` if it was already completed. + * + * **Example** (Completing a Deferred with an Exit) + * * ```ts * import { Deferred, Effect, Exit } from "effect" * @@ -430,15 +530,30 @@ export const done: { * }) * ``` * + * @see {@link complete} for completing from an effect and memoizing its result + * @see {@link completeWith} for storing an effect directly + * @see {@link succeed} for completing with a success value + * @see {@link failCause} for completing with a failure cause + * + * @category completion * @since 2.0.0 - * @category utils */ (exit: Exit.Exit): (self: Deferred) => Effect /** - * Exits the `Deferred` with the specified `Exit` value, which will be + * Completes the `Deferred` with the specified `Exit` value, which will be * propagated to all fibers waiting on the value of the `Deferred`. * - * @example + * **When to use** + * + * Use to complete a `Deferred` from an already computed `Exit`. + * + * **Details** + * + * The returned effect succeeds with `true` when this call completed the + * `Deferred`, or `false` if it was already completed. + * + * **Example** (Completing a Deferred with an Exit) + * * ```ts * import { Deferred, Effect, Exit } from "effect" * @@ -451,17 +566,32 @@ export const done: { * }) * ``` * + * @see {@link complete} for completing from an effect and memoizing its result + * @see {@link completeWith} for storing an effect directly + * @see {@link succeed} for completing with a success value + * @see {@link failCause} for completing with a failure cause + * + * @category completion * @since 2.0.0 - * @category utils */ (self: Deferred, exit: Exit.Exit): Effect } = completeWith as any /** - * Fails the `Deferred` with the specified error, which will be propagated to - * all fibers waiting on the value of the `Deferred`. + * Attempts to complete the `Deferred` with the specified error. + * + * **When to use** + * + * Use to complete a `Deferred` with a typed failure value. + * + * **Details** + * + * Fibers waiting on the `Deferred` fail with that error only if this call + * completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Failing a Deferred with an error) * - * @example * ```ts * import { Deferred, Effect } from "effect" * @@ -472,15 +602,25 @@ export const done: { * }) * ``` * + * @category completion * @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`. + * Attempts to complete the `Deferred` with the specified error. + * + * **When to use** + * + * Use to complete a `Deferred` with a typed failure value. + * + * **Details** + * + * Fibers waiting on the `Deferred` fail with that error only if this call + * completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Failing a Deferred with an error) * - * @example * ```ts * import { Deferred, Effect } from "effect" * @@ -491,15 +631,25 @@ export const fail: { * }) * ``` * + * @category completion * @since 2.0.0 - * @category utils */ (error: E): (self: Deferred) => Effect /** - * Fails the `Deferred` with the specified error, which will be propagated to - * all fibers waiting on the value of the `Deferred`. + * Attempts to complete the `Deferred` with the specified error. + * + * **When to use** + * + * Use to complete a `Deferred` with a typed failure value. + * + * **Details** + * + * Fibers waiting on the `Deferred` fail with that error only if this call + * completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Failing a Deferred with an error) * - * @example * ```ts * import { Deferred, Effect } from "effect" * @@ -510,17 +660,29 @@ export const fail: { * }) * ``` * + * @category completion * @since 2.0.0 - * @category utils */ (self: Deferred, error: E): Effect } = dual(2, (self: Deferred, error: E): Effect => done(self, core.exitFail(error))) /** - * Fails the `Deferred` with the specified error, which will be propagated to - * all fibers waiting on the value of the `Deferred`. + * Computes an error when the returned effect is run, then attempts to complete + * the `Deferred` with that error. + * + * **When to use** + * + * Use to lazily compute a typed failure value when the `Deferred` completion + * effect runs. + * + * **Details** + * + * Fibers waiting on the `Deferred` fail with the computed error only if this + * call completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Failing a Deferred with a lazy error) * - * @example * ```ts * import { Deferred, Effect } from "effect" * @@ -531,15 +693,27 @@ export const fail: { * }) * ``` * + * @category completion * @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`. + * Computes an error when the returned effect is run, then attempts to complete + * the `Deferred` with that error. + * + * **When to use** + * + * Use to lazily compute a typed failure value when the `Deferred` completion + * effect runs. + * + * **Details** + * + * Fibers waiting on the `Deferred` fail with the computed error only if this + * call completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Failing a Deferred with a lazy error) * - * @example * ```ts * import { Deferred, Effect } from "effect" * @@ -550,15 +724,27 @@ export const failSync: { * }) * ``` * + * @category completion * @since 2.0.0 - * @category utils */ (evaluate: LazyArg): (self: Deferred) => Effect /** - * Fails the `Deferred` with the specified error, which will be propagated to - * all fibers waiting on the value of the `Deferred`. + * Computes an error when the returned effect is run, then attempts to complete + * the `Deferred` with that error. + * + * **When to use** + * + * Use to lazily compute a typed failure value when the `Deferred` completion + * effect runs. + * + * **Details** + * + * Fibers waiting on the `Deferred` fail with the computed error only if this + * call completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Failing a Deferred with a lazy error) * - * @example * ```ts * import { Deferred, Effect } from "effect" * @@ -569,8 +755,8 @@ export const failSync: { * }) * ``` * + * @category completion * @since 2.0.0 - * @category utils */ (self: Deferred, evaluate: LazyArg): Effect } = dual( @@ -580,10 +766,20 @@ export const failSync: { ) /** - * Fails the `Deferred` with the specified `Cause`, which will be propagated to - * all fibers waiting on the value of the `Deferred`. + * Attempts to complete the `Deferred` with the specified `Cause`. + * + * **When to use** + * + * Use to complete a `Deferred` with a full failure cause. + * + * **Details** + * + * Fibers waiting on the `Deferred` observe that cause only if this call + * completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Failing a Deferred with a Cause) * - * @example * ```ts * import { Cause, Deferred, Effect } from "effect" * @@ -597,15 +793,25 @@ export const failSync: { * }) * ``` * + * @category completion * @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`. + * Attempts to complete the `Deferred` with the specified `Cause`. + * + * **When to use** + * + * Use to complete a `Deferred` with a full failure cause. + * + * **Details** + * + * Fibers waiting on the `Deferred` observe that cause only if this call + * completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Failing a Deferred with a Cause) * - * @example * ```ts * import { Cause, Deferred, Effect } from "effect" * @@ -619,15 +825,25 @@ export const failCause: { * }) * ``` * + * @category completion * @since 2.0.0 - * @category utils */ (cause: Cause.Cause): (self: Deferred) => Effect /** - * Fails the `Deferred` with the specified `Cause`, which will be propagated to - * all fibers waiting on the value of the `Deferred`. + * Attempts to complete the `Deferred` with the specified `Cause`. + * + * **When to use** + * + * Use to complete a `Deferred` with a full failure cause. + * + * **Details** + * + * Fibers waiting on the `Deferred` observe that cause only if this call + * completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Failing a Deferred with a Cause) * - * @example * ```ts * import { Cause, Deferred, Effect } from "effect" * @@ -641,8 +857,8 @@ export const failCause: { * }) * ``` * + * @category completion * @since 2.0.0 - * @category utils */ (self: Deferred, cause: Cause.Cause): Effect } = dual( @@ -651,10 +867,22 @@ export const failCause: { ) /** - * Fails the `Deferred` with the specified `Cause`, which will be propagated to - * all fibers waiting on the value of the `Deferred`. + * Computes a `Cause` when the returned effect is run, then attempts to + * complete the `Deferred` with that cause. + * + * **When to use** + * + * Use to lazily compute a full failure cause when the `Deferred` completion + * effect runs. + * + * **Details** + * + * Fibers waiting on the `Deferred` observe the computed cause only if this + * call completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Failing a Deferred with a lazy Cause) * - * @example * ```ts * import { Cause, Deferred, Effect } from "effect" * @@ -668,15 +896,27 @@ export const failCause: { * }) * ``` * + * @category completion * @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`. + * Computes a `Cause` when the returned effect is run, then attempts to + * complete the `Deferred` with that cause. + * + * **When to use** + * + * Use to lazily compute a full failure cause when the `Deferred` completion + * effect runs. + * + * **Details** + * + * Fibers waiting on the `Deferred` observe the computed cause only if this + * call completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Failing a Deferred with a lazy Cause) * - * @example * ```ts * import { Cause, Deferred, Effect } from "effect" * @@ -690,15 +930,27 @@ export const failCauseSync: { * }) * ``` * + * @category completion * @since 2.0.0 - * @category utils */ (evaluate: LazyArg>): (self: Deferred) => Effect /** - * Fails the `Deferred` with the specified `Cause`, which will be propagated to - * all fibers waiting on the value of the `Deferred`. + * Computes a `Cause` when the returned effect is run, then attempts to + * complete the `Deferred` with that cause. + * + * **When to use** + * + * Use to lazily compute a full failure cause when the `Deferred` completion + * effect runs. + * + * **Details** + * + * Fibers waiting on the `Deferred` observe the computed cause only if this + * call completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Failing a Deferred with a lazy Cause) * - * @example * ```ts * import { Cause, Deferred, Effect } from "effect" * @@ -712,8 +964,8 @@ export const failCauseSync: { * }) * ``` * + * @category completion * @since 2.0.0 - * @category utils */ (self: Deferred, evaluate: LazyArg>): Effect } = dual( @@ -723,10 +975,20 @@ export const failCauseSync: { ) /** - * Kills the `Deferred` with the specified defect, which will be propagated to - * all fibers waiting on the value of the `Deferred`. + * Attempts to complete the `Deferred` with a defect. + * + * **When to use** + * + * Use to complete a `Deferred` with an unexpected defect. + * + * **Details** + * + * Fibers waiting on the `Deferred` die with that defect only if this call + * completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Killing a Deferred with a defect) * - * @example * ```ts * import { Deferred, Effect } from "effect" * @@ -740,15 +1002,25 @@ export const failCauseSync: { * }) * ``` * + * @category completion * @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`. + * Attempts to complete the `Deferred` with a defect. + * + * **When to use** + * + * Use to complete a `Deferred` with an unexpected defect. + * + * **Details** + * + * Fibers waiting on the `Deferred` die with that defect only if this call + * completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Killing a Deferred with a defect) * - * @example * ```ts * import { Deferred, Effect } from "effect" * @@ -762,15 +1034,25 @@ export const die: { * }) * ``` * + * @category completion * @since 2.0.0 - * @category utils */ (defect: unknown): (self: Deferred) => Effect /** - * Kills the `Deferred` with the specified defect, which will be propagated to - * all fibers waiting on the value of the `Deferred`. + * Attempts to complete the `Deferred` with a defect. + * + * **When to use** + * + * Use to complete a `Deferred` with an unexpected defect. + * + * **Details** + * + * Fibers waiting on the `Deferred` die with that defect only if this call + * completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Killing a Deferred with a defect) * - * @example * ```ts * import { Deferred, Effect } from "effect" * @@ -784,17 +1066,28 @@ export const die: { * }) * ``` * + * @category completion * @since 2.0.0 - * @category utils */ (self: Deferred, defect: unknown): Effect } = dual(2, (self: Deferred, defect: unknown): Effect => done(self, core.exitDie(defect))) /** - * Kills the `Deferred` with the specified defect, which will be propagated to - * all fibers waiting on the value of the `Deferred`. + * Computes a defect when the returned effect is run, then attempts to complete + * the `Deferred` with that defect. + * + * **When to use** + * + * Use to lazily compute an unexpected defect when the completion effect runs. + * + * **Details** + * + * Fibers waiting on the `Deferred` die with the computed defect only if this + * call completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Killing a Deferred with a lazy defect) * - * @example * ```ts * import { Deferred, Effect } from "effect" * @@ -808,15 +1101,26 @@ export const die: { * }) * ``` * + * @category completion * @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`. + * Computes a defect when the returned effect is run, then attempts to complete + * the `Deferred` with that defect. + * + * **When to use** + * + * Use to lazily compute an unexpected defect when the completion effect runs. + * + * **Details** + * + * Fibers waiting on the `Deferred` die with the computed defect only if this + * call completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Killing a Deferred with a lazy defect) * - * @example * ```ts * import { Deferred, Effect } from "effect" * @@ -830,15 +1134,26 @@ export const dieSync: { * }) * ``` * + * @category completion * @since 2.0.0 - * @category utils */ (evaluate: LazyArg): (self: Deferred) => Effect /** - * Kills the `Deferred` with the specified defect, which will be propagated to - * all fibers waiting on the value of the `Deferred`. + * Computes a defect when the returned effect is run, then attempts to complete + * the `Deferred` with that defect. + * + * **When to use** + * + * Use to lazily compute an unexpected defect when the completion effect runs. + * + * **Details** + * + * Fibers waiting on the `Deferred` die with the computed defect only if this + * call completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Killing a Deferred with a lazy defect) * - * @example * ```ts * import { Deferred, Effect } from "effect" * @@ -852,8 +1167,8 @@ export const dieSync: { * }) * ``` * + * @category completion * @since 2.0.0 - * @category utils */ (self: Deferred, evaluate: LazyArg): Effect } = dual( @@ -863,11 +1178,21 @@ export const dieSync: { ) /** - * 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. + * Attempts to complete the `Deferred` with interruption by the current fiber. + * + * **When to use** + * + * Use to complete a `Deferred` as interrupted by the current fiber. + * + * **Details** + * + * Fibers waiting on the `Deferred` are interrupted with the current fiber id + * only if this call completes it. The returned effect succeeds with `true` + * when this call completed the `Deferred`, or `false` if it was already + * completed. + * + * **Example** (Interrupting a Deferred) * - * @example * ```ts * import { Deferred, Effect } from "effect" * @@ -878,17 +1203,28 @@ export const dieSync: { * }) * ``` * + * @category completion * @since 2.0.0 - * @category utils */ export const interrupt = (self: Deferred): Effect => core.withFiber((fiber) => interruptWith(self, fiber.id)) /** - * Completes the `Deferred` with interruption. This will interrupt all fibers - * waiting on the value of the `Deferred` with the specified `FiberId`. + * Attempts to complete the `Deferred` with interruption by the specified + * `FiberId`. + * + * **When to use** + * + * Use to complete a `Deferred` as interrupted by a specific fiber id. + * + * **Details** + * + * Fibers waiting on the `Deferred` are interrupted with that fiber id only if + * this call completes it. The returned effect succeeds with `true` when this + * call completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Interrupting a Deferred with a fiber id) * - * @example * ```ts * import { Deferred, Effect } from "effect" * @@ -899,15 +1235,26 @@ export const interrupt = (self: Deferred): Effect => * }) * ``` * + * @category completion * @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`. + * Attempts to complete the `Deferred` with interruption by the specified + * `FiberId`. + * + * **When to use** + * + * Use to complete a `Deferred` as interrupted by a specific fiber id. + * + * **Details** + * + * Fibers waiting on the `Deferred` are interrupted with that fiber id only if + * this call completes it. The returned effect succeeds with `true` when this + * call completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Interrupting a Deferred with a fiber id) * - * @example * ```ts * import { Deferred, Effect } from "effect" * @@ -918,15 +1265,26 @@ export const interruptWith: { * }) * ``` * + * @category completion * @since 2.0.0 - * @category utils */ (fiberId: number): (self: Deferred) => Effect /** - * Completes the `Deferred` with interruption. This will interrupt all fibers - * waiting on the value of the `Deferred` with the specified `FiberId`. + * Attempts to complete the `Deferred` with interruption by the specified + * `FiberId`. + * + * **When to use** + * + * Use to complete a `Deferred` as interrupted by a specific fiber id. + * + * **Details** + * + * Fibers waiting on the `Deferred` are interrupted with that fiber id only if + * this call completes it. The returned effect succeeds with `true` when this + * call completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Interrupting a Deferred with a fiber id) * - * @example * ```ts * import { Deferred, Effect } from "effect" * @@ -937,8 +1295,8 @@ export const interruptWith: { * }) * ``` * + * @category completion * @since 2.0.0 - * @category utils */ (self: Deferred, fiberId: number): Effect } = dual( @@ -951,7 +1309,12 @@ export const interruptWith: { * Returns `true` if this `Deferred` has already been completed with a value or * an error, `false` otherwise. * - * @example + * **When to use** + * + * Use to check completion status inside an `Effect` workflow. + * + * **Example** (Checking Deferred completion) + * * ```ts * import { Deferred, Effect } from "effect" * @@ -966,17 +1329,24 @@ export const interruptWith: { * }) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export const isDone = (self: Deferred): Effect => internalEffect.sync(() => isDoneUnsafe(self)) /** - * Returns `true` if this `Deferred` has already been completed with a value or - * an error, `false` otherwise. + * Returns whether this `Deferred` has already been completed synchronously. + * + * **When to use** + * + * Use to check `Deferred` completion synchronously in code that cannot return + * an `Effect`, such as low-level integration code. + * + * @see {@link isDone} for checking completion inside `Effect` + * @see {@link poll} for reading the completed effect when available * - * @since 2.0.0 * @category getters + * @since 4.0.0 */ export const isDoneUnsafe = (self: Deferred): boolean => self.effect !== undefined @@ -985,7 +1355,13 @@ export const isDoneUnsafe = (self: Deferred): boolean => self.effect * `Option.some(effect)` when the `Deferred` is completed, `Option.none()` * otherwise. * - * @example + * **When to use** + * + * Use to inspect whether a `Deferred` is already completed and retrieve its + * stored completion effect when available. + * + * **Example** (Polling Deferred completion) + * * ```ts * import { Deferred, Effect } from "effect" * @@ -1000,17 +1376,28 @@ export const isDoneUnsafe = (self: Deferred): boolean => self.effect * }) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export function poll(self: Deferred): Effect>> { return internalEffect.sync(() => Option.fromUndefinedOr(self.effect)) } /** - * Completes the `Deferred` with the specified value. + * Attempts to complete the `Deferred` with the specified value. + * + * **When to use** + * + * Use to complete a `Deferred` with a successful value. + * + * **Details** + * + * Fibers waiting on the `Deferred` receive the value only if this call + * completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Completing a Deferred with a value) * - * @example * ```ts * import { Deferred, Effect } from "effect" * @@ -1023,14 +1410,25 @@ export function poll(self: Deferred): Effect(value: A): (self: Deferred) => Effect /** - * Completes the `Deferred` with the specified value. + * Attempts to complete the `Deferred` with the specified value. + * + * **When to use** + * + * Use to complete a `Deferred` with a successful value. + * + * **Details** + * + * Fibers waiting on the `Deferred` receive the value only if this call + * completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Completing a Deferred with a value) * - * @example * ```ts * import { Deferred, Effect } from "effect" * @@ -1063,16 +1472,29 @@ export const succeed: { * }) * ``` * + * @category completion * @since 2.0.0 - * @category utils */ (self: Deferred, value: A): Effect } = dual(2, (self: Deferred, value: A): Effect => done(self, core.exitSucceed(value))) /** - * Completes the `Deferred` with the specified lazily evaluated value. + * Computes a value when the returned effect is run, then attempts to complete + * the `Deferred` with that value. + * + * **When to use** + * + * Use to lazily compute a successful value when the `Deferred` completion + * effect runs. + * + * **Details** + * + * Fibers waiting on the `Deferred` receive the computed value only if this call + * completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Completing a Deferred with a lazy value) * - * @example * ```ts * import { Deferred, Effect } from "effect" * @@ -1085,14 +1507,27 @@ export const succeed: { * }) * ``` * + * @category completion * @since 2.0.0 - * @category utils */ export const sync: { /** - * Completes the `Deferred` with the specified lazily evaluated value. + * Computes a value when the returned effect is run, then attempts to complete + * the `Deferred` with that value. + * + * **When to use** + * + * Use to lazily compute a successful value when the `Deferred` completion + * effect runs. + * + * **Details** + * + * Fibers waiting on the `Deferred` receive the computed value only if this call + * completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Completing a Deferred with a lazy value) * - * @example * ```ts * import { Deferred, Effect } from "effect" * @@ -1105,14 +1540,27 @@ export const sync: { * }) * ``` * + * @category completion * @since 2.0.0 - * @category utils */ (evaluate: LazyArg): (self: Deferred) => Effect /** - * Completes the `Deferred` with the specified lazily evaluated value. + * Computes a value when the returned effect is run, then attempts to complete + * the `Deferred` with that value. + * + * **When to use** + * + * Use to lazily compute a successful value when the `Deferred` completion + * effect runs. + * + * **Details** + * + * Fibers waiting on the `Deferred` receive the computed value only if this call + * completes it. The returned effect succeeds with `true` when this call + * completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Completing a Deferred with a lazy value) * - * @example * ```ts * import { Deferred, Effect } from "effect" * @@ -1125,8 +1573,8 @@ export const sync: { * }) * ``` * + * @category completion * @since 2.0.0 - * @category utils */ (self: Deferred, evaluate: LazyArg): Effect } = dual( @@ -1136,10 +1584,22 @@ export const sync: { ) /** - * Unsafely exits the `Deferred` with the specified `Exit` value, which will be - * propagated to all fibers waiting on the value of the `Deferred`. + * Attempts to complete the `Deferred` synchronously with the specified + * completion effect. + * + * **When to use** + * + * Use to complete a `Deferred` synchronously in low-level code that already has + * the completion effect. + * + * **Details** + * + * This mutates the `Deferred` directly and should be reserved for low-level + * code; prefer the effectful completion APIs when possible. Returns `true` if + * this call completed the `Deferred`, or `false` if it was already completed. + * + * **Example** (Completing a Deferred unsafely) * - * @example * ```ts * import { Deferred, Effect } from "effect" * @@ -1148,8 +1608,8 @@ export const sync: { * console.log(success) // true * ``` * - * @since 2.0.0 * @category unsafe + * @since 4.0.0 */ export const doneUnsafe = (self: Deferred, effect: Effect): boolean => { if (self.effect) return false @@ -1164,16 +1624,23 @@ export const doneUnsafe = (self: Deferred, effect: Effect): bo } /** - * Converts an `Effect` into an operation that completes a `Deferred` with its result. + * Runs an `Effect` and attempts to complete a `Deferred` with the effect's + * result. + * + * **When to use** + * + * Use to pipe an effect result into a `Deferred` while preserving success, + * failure, defects, and interruption. * * **Details** * - * The `into` function takes an effect and a `Deferred` and ensures that the `Deferred` - * is completed based on the outcome of the effect. If the effect succeeds, the `Deferred` is - * completed with the success value. If the effect fails, the `Deferred` is completed with the - * failure. Additionally, if the effect is interrupted, the `Deferred` will also be interrupted. + * If the effect succeeds, fails, dies, or is interrupted, that result is used + * as the attempted completion. The returned effect cannot fail; it succeeds + * with `true` if it completed the `Deferred`, or `false` if the `Deferred` was + * already completed. + * + * **Example** (Completing a Deferred from an effect result) * - * @example * ```ts * import { Deferred, Effect } from "effect" * @@ -1200,21 +1667,28 @@ export const doneUnsafe = (self: Deferred, effect: Effect): bo * // true * ``` * - * @since 2.0.0 * @category Synchronization Utilities + * @since 4.0.0 */ export const into: { /** - * Converts an `Effect` into an operation that completes a `Deferred` with its result. + * Runs an `Effect` and attempts to complete a `Deferred` with the effect's + * result. + * + * **When to use** + * + * Use to pipe an effect result into a `Deferred` while preserving success, + * failure, defects, and interruption. * * **Details** * - * The `into` function takes an effect and a `Deferred` and ensures that the `Deferred` - * is completed based on the outcome of the effect. If the effect succeeds, the `Deferred` is - * completed with the success value. If the effect fails, the `Deferred` is completed with the - * failure. Additionally, if the effect is interrupted, the `Deferred` will also be interrupted. + * If the effect succeeds, fails, dies, or is interrupted, that result is used + * as the attempted completion. The returned effect cannot fail; it succeeds + * with `true` if it completed the `Deferred`, or `false` if the `Deferred` was + * already completed. + * + * **Example** (Completing a Deferred from an effect result) * - * @example * ```ts * import { Deferred, Effect } from "effect" * @@ -1241,21 +1715,28 @@ export const into: { * // true * ``` * - * @since 2.0.0 * @category Synchronization Utilities + * @since 4.0.0 */ (deferred: Deferred): (self: Effect) => Effect /** - * Converts an `Effect` into an operation that completes a `Deferred` with its result. + * Runs an `Effect` and attempts to complete a `Deferred` with the effect's + * result. + * + * **When to use** + * + * Use to pipe an effect result into a `Deferred` while preserving success, + * failure, defects, and interruption. * * **Details** * - * The `into` function takes an effect and a `Deferred` and ensures that the `Deferred` - * is completed based on the outcome of the effect. If the effect succeeds, the `Deferred` is - * completed with the success value. If the effect fails, the `Deferred` is completed with the - * failure. Additionally, if the effect is interrupted, the `Deferred` will also be interrupted. + * If the effect succeeds, fails, dies, or is interrupted, that result is used + * as the attempted completion. The returned effect cannot fail; it succeeds + * with `true` if it completed the `Deferred`, or `false` if the `Deferred` was + * already completed. + * + * **Example** (Completing a Deferred from an effect result) * - * @example * ```ts * import { Deferred, Effect } from "effect" * @@ -1282,8 +1763,8 @@ export const into: { * // true * ``` * - * @since 2.0.0 * @category Synchronization Utilities + * @since 4.0.0 */ (self: Effect, deferred: Deferred): Effect } = dual( diff --git a/.opencode/node_modules/effect/src/Differ.ts b/.opencode/node_modules/effect/src/Differ.ts index f6216b9c4e3c491ee9e8174861a1da308ab568e4..ba636ba64caeae53ce6920ea830674189dac67fb 100644 --- a/.opencode/node_modules/effect/src/Differ.ts +++ b/.opencode/node_modules/effect/src/Differ.ts @@ -1,10 +1,28 @@ /** + * Interfaces for describing changes to a value as patches. A + * `Differ` compares an old and new value, creates a patch for the + * difference, combines patches in order, and applies a patch to an old value to + * produce an updated value. + * * @since 4.0.0 */ /** - * @category Model - * @since 4.0.0 + * Describes how to compute, combine, and apply patches for values of type `T`. + * + * **When to use** + * + * Use to model patch-based updates for a value type when callers need to + * compute a patch from two values, combine patches, and apply a patch later. + * + * **Details** + * + * A `Differ` provides an empty patch, computes the patch between two values, + * combines patches, and applies a patch to an old value to produce an updated + * value. + * + * @category models + * @since 2.0.0 */ export interface Differ { readonly empty: Patch diff --git a/.opencode/node_modules/effect/src/Duration.ts b/.opencode/node_modules/effect/src/Duration.ts index eb84a174a40db7ec39aa07d3a0d5a947af2883f9..2973221eb6cd9f7bc9b8553fd3556185120b46c0 100644 --- a/.opencode/node_modules/effect/src/Duration.ts +++ b/.opencode/node_modules/effect/src/Duration.ts @@ -1,15 +1,11 @@ /** - * This module provides utilities for working with durations of time. A `Duration` - * is an immutable data type that represents a span of time with high precision, - * supporting operations from nanoseconds to weeks. - * - * Durations support: - * - **High precision**: Nanosecond-level accuracy using BigInt - * - **Multiple formats**: Numbers (millis), BigInt (nanos), tuples, strings - * - **Arithmetic operations**: Add, subtract, multiply, divide - * - **Comparisons**: Equal, less than, greater than - * - **Conversions**: Between different time units - * - **Human-readable formatting**: Pretty printing and parsing + * Represents immutable spans of time. + * + * A `Duration` can be finite, positive infinity, or negative infinity. It is + * the standard representation for delays, timeouts, intervals, and + * time-to-live values across Effect APIs. This module includes constructors + * from common input shapes, unit conversions, comparisons, arithmetic, + * formatting, and reusable reducer or combiner helpers. * * @since 2.0.0 */ @@ -30,18 +26,46 @@ import * as Reducer from "./Reducer.ts" const TypeId = "~effect/time/Duration" const bigint0 = BigInt(0) +const bigint1 = BigInt(1) 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) +const roundTiesAwayFromZero = (input: number): bigint => + BigInt(input < 0 ? Math.ceil(input - 0.5) : Math.floor(input + 0.5)) + +const roundMillisToNanos = (millis: number): bigint => roundTiesAwayFromZero(millis * 1_000_000) + +const parseNanos = (input: string, scale: bigint): bigint => + input.includes(".") ? roundTiesAwayFromZero(Number(input) * Number(scale)) : BigInt(input) * scale + +const nanosToHrTime = (nanos: bigint): [seconds: number, nanos: number] => { + const sign = nanos < bigint0 ? -bigint1 : bigint1 + const absolute = nanos < bigint0 ? -nanos : nanos + return [ + Number(sign * (absolute / bigint1e9)), + Number(sign * (absolute % bigint1e9)) + ] +} + /** * Represents a span of time with high precision, supporting operations from * nanoseconds to weeks. * - * @since 2.0.0 + * **When to use** + * + * Use to model elapsed time, delays, timeouts, schedule intervals, and cache + * TTLs as immutable duration values. + * + * @see {@link Input} for values accepted by APIs that decode duration-like + * inputs + * @see {@link DurationValue} for the tagged representation exposed by the + * `value` field + * * @category models + * @since 2.0.0 */ export interface Duration extends Equal.Equal, Pipeable, Inspectable.Inspectable { readonly [TypeId]: typeof TypeId @@ -49,10 +73,25 @@ export interface Duration extends Equal.Equal, Pipeable, Inspectable.Inspectable } /** - * The internal representation of a `Duration` value. + * Tagged representation of a `Duration` value. + * + * **When to use** + * + * Use when modeling or inspecting the exact tagged representation stored in a + * `Duration`, including finite millisecond or nanosecond values and infinite + * sentinels. + * + * **Details** + * + * A duration is represented as milliseconds, nanoseconds, positive infinity, + * or negative infinity. + * + * @see {@link Duration} for the public type whose `value` field contains this + * representation + * @see {@link match} for pattern matching without reading `value` directly * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export type DurationValue = | { _tag: "Millis"; millis: number } @@ -63,8 +102,15 @@ export type DurationValue = /** * Valid time units that can be used in duration string representations. * - * @since 2.0.0 + * **When to use** + * + * Use when typing the unit portion of duration string inputs accepted by + * `Duration.Input`. + * + * @see {@link Input} for the full duration input union + * * @category models + * @since 2.0.0 */ export type Unit = | "nano" @@ -87,11 +133,27 @@ export type Unit = /** * Valid input types that can be converted to a Duration. * + * **When to use** + * + * Use when an API should accept any value that Effect can convert into a + * `Duration`, including existing durations, millisecond numbers, nanosecond + * bigints, high-resolution tuples, duration strings, infinity strings, or + * duration objects. + * + * **Details** + * * String inputs accept values like `"10 seconds"`, `"500 millis"`, - * `"Infinity"`, and `"-Infinity"`. + * `"Infinity"`, and `"-Infinity"`. Finite fractional values that are + * normalized to nanoseconds are rounded to the nearest nanosecond, with ties + * away from zero. + * + * @see {@link fromInput} for safe conversion to `Option` + * @see {@link fromInputUnsafe} for throwing conversion + * @see {@link DurationObject} for object-shaped duration input + * @see {@link Unit} for supported string units * - * @since 2.0.0 * @category models + * @since 4.0.0 */ export type Input = | Duration @@ -107,9 +169,12 @@ export type Input = * An object with optional duration components that can be combined to create * a Duration. All fields are optional and additive. * + * **Details** + * * Compatible with Temporal.Duration-like objects. * - * @example + * **Example** (Combining duration object fields) + * * ```ts * import { Duration } from "effect" * @@ -118,8 +183,8 @@ export type Input = * Duration.fromInputUnsafe({ seconds: 1, nanoseconds: 500 }) * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface DurationObject { readonly weeks?: number | undefined @@ -137,9 +202,17 @@ const DURATION_REGEXP = /^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|m /** * Decodes a `Duration.Input` into a `Duration`. * + * **When to use** + * + * Use when the input has already been validated or comes from a trusted source + * and throwing is acceptable for invalid duration syntax. + * + * **Gotchas** + * * If the input is not a valid `Duration.Input`, it throws an error. * - * @example + * **Example** (Decoding duration inputs) + * * ```ts * import { Duration } from "effect" * @@ -149,8 +222,8 @@ const DURATION_REGEXP = /^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|m * const duration4 = Duration.fromInputUnsafe([2, 500_000_000]) // 2 seconds and 500ms * ``` * - * @since 2.0.0 * @category constructors + * @since 4.0.0 */ export const fromInputUnsafe = (input: Input): Duration => { switch (typeof input) { @@ -168,14 +241,14 @@ export const fromInputUnsafe = (input: Input): Duration => { const match = DURATION_REGEXP.exec(input) if (!match) break const [_, valueStr, unit] = match + if (unit === "nano" || unit === "nanos") { + return nanos(parseNanos(valueStr, bigint1)) + } + if (unit === "micro" || unit === "micros") { + return nanos(parseNanos(valueStr, bigint1e3)) + } 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) @@ -213,7 +286,7 @@ export const fromInputUnsafe = (input: Input): Duration => { if (input[0] === Infinity || input[1] === Infinity) { return infinity } - return make(BigInt(Math.round(input[0] * 1_000_000_000)) + BigInt(Math.round(input[1]))) + return make(roundTiesAwayFromZero(input[0] * 1_000_000_000 + input[1])) } const obj = input as DurationObject let millis = 0 @@ -225,10 +298,9 @@ export const fromInputUnsafe = (input: Input): Duration => { if (obj.seconds) millis += obj.seconds * 1_000 if (obj.milliseconds) millis += obj.milliseconds if (!obj.microseconds && !obj.nanoseconds) return make(millis) - let nanos = BigInt(millis) * bigint1e6 - if (obj.microseconds) nanos += BigInt(obj.microseconds) * bigint1e3 - if (obj.nanoseconds) nanos += BigInt(obj.nanoseconds) - return make(nanos) + return make(roundTiesAwayFromZero( + millis * 1_000_000 + (obj.microseconds ?? 0) * 1_000 + (obj.nanoseconds ?? 0) + )) } } return invalid(input) @@ -239,10 +311,10 @@ const invalid = (input: unknown): never => { } /** - * Safely decodes a `Input` value into a `Duration`, returning + * Decodes a `Input` value into a `Duration` safely, returning * `Option.none()` if decoding fails. * - * **Example** + * **Example** (Safely decoding duration inputs) * * ```ts * import { Duration, Option } from "effect" @@ -311,7 +383,7 @@ const make = (input: number | bigint): Duration => { } else if (!Number.isFinite(input)) { duration.value = input > 0 ? infinityDurationValue : negativeInfinityDurationValue } else if (!Number.isInteger(input)) { - duration.value = { _tag: "Nanos", nanos: BigInt(Math.round(input * 1_000_000)) } + duration.value = { _tag: "Nanos", nanos: roundMillisToNanos(input) } } else { duration.value = { _tag: "Millis", millis: input } } @@ -324,9 +396,10 @@ const make = (input: number | bigint): Duration => { } /** - * Checks if a value is a Duration. + * Checks whether a value is a Duration. + * + * **Example** (Checking for durations) * - * @example * ```ts * import { Duration } from "effect" * @@ -334,15 +407,16 @@ const make = (input: number | bigint): Duration => { * console.log(Duration.isDuration(1000)) // false * ``` * - * @since 2.0.0 * @category guards + * @since 2.0.0 */ export const isDuration = (u: unknown): u is Duration => hasProperty(u, TypeId) /** - * Checks if a Duration is finite (not infinite). + * Checks whether a Duration is finite (not infinite). + * + * **Example** (Checking finite durations) * - * @example * ```ts * import { Duration } from "effect" * @@ -350,16 +424,17 @@ export const isDuration = (u: unknown): u is Duration => hasProperty(u, TypeId) * console.log(Duration.isFinite(Duration.infinity)) // false * ``` * - * @since 2.0.0 * @category guards + * @since 2.0.0 */ export const isFinite = (self: Duration): boolean => self.value._tag !== "Infinity" && self.value._tag !== "NegativeInfinity" /** - * Checks if a Duration is zero. + * Checks whether a Duration is zero. + * + * **Example** (Checking for zero durations) * - * @example * ```ts * import { Duration } from "effect" * @@ -367,8 +442,8 @@ export const isFinite = (self: Duration): boolean => * console.log(Duration.isZero(Duration.seconds(1))) // false * ``` * - * @since 3.5.0 * @category guards + * @since 3.5.0 */ export const isZero = (self: Duration): boolean => { switch (self.value._tag) { @@ -385,7 +460,8 @@ export const isZero = (self: Duration): boolean => { /** * Returns `true` if the duration is negative (strictly less than zero). * - * @example + * **Example** (Checking for negative durations) + * * ```ts * import { Duration } from "effect" * @@ -394,8 +470,8 @@ export const isZero = (self: Duration): boolean => { * console.log(Duration.isNegative(Duration.negativeInfinity)) // true * ``` * - * @since 4.0.0 * @category guards + * @since 4.0.0 */ export const isNegative = (self: Duration): boolean => { switch (self.value._tag) { @@ -413,7 +489,8 @@ export const isNegative = (self: Duration): boolean => { /** * Returns `true` if the duration is positive (strictly greater than zero). * - * @example + * **Example** (Checking for positive durations) + * * ```ts * import { Duration } from "effect" * @@ -422,8 +499,8 @@ export const isNegative = (self: Duration): boolean => { * console.log(Duration.isPositive(Duration.infinity)) // true * ``` * - * @since 4.0.0 * @category guards + * @since 4.0.0 */ export const isPositive = (self: Duration): boolean => { switch (self.value._tag) { @@ -441,7 +518,8 @@ export const isPositive = (self: Duration): boolean => { /** * Returns the absolute value of the duration. * - * @example + * **Example** (Taking absolute duration values) + * * ```ts * import { Duration } from "effect" * @@ -449,8 +527,8 @@ export const isPositive = (self: Duration): boolean => { * Duration.abs(Duration.negativeInfinity) === Duration.infinity // true * ``` * - * @since 4.0.0 * @category math + * @since 4.0.0 */ export const abs = (self: Duration): Duration => { switch (self.value._tag) { @@ -465,9 +543,10 @@ export const abs = (self: Duration): Duration => { } /** - * Negates the duration. + * Returns the negated duration. + * + * **Example** (Negating durations) * - * @example * ```ts * import { Duration } from "effect" * @@ -475,8 +554,8 @@ export const abs = (self: Duration): Duration => { * Duration.negate(Duration.infinity) === Duration.negativeInfinity // true * ``` * - * @since 4.0.0 * @category math + * @since 4.0.0 */ export const negate = (self: Duration): Duration => { switch (self.value._tag) { @@ -494,52 +573,56 @@ export const negate = (self: Duration): Duration => { /** * A Duration representing zero time. * - * @example + * **Example** (Using the zero duration) + * * ```ts * import { Duration } from "effect" * * console.log(Duration.toMillis(Duration.zero)) // 0 * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const zero: Duration = make(0) /** * A Duration representing infinite time. * - * @example + * **Example** (Using infinite duration) + * * ```ts * import { Duration } from "effect" * * console.log(Duration.toMillis(Duration.infinity)) // Infinity * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const infinity: Duration = make(Infinity) /** * A Duration representing negative infinite time. * - * @example + * **Example** (Using negative infinite duration) + * * ```ts * import { Duration } from "effect" * * console.log(Duration.toMillis(Duration.negativeInfinity)) // -Infinity * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const negativeInfinity: Duration = make(-Infinity) /** * Creates a Duration from nanoseconds. * - * @example + * **Example** (Creating durations from nanoseconds) + * * ```ts * import { Duration } from "effect" * @@ -547,15 +630,16 @@ export const negativeInfinity: Duration = make(-Infinity) * console.log(Duration.toMillis(duration)) // 500 * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const nanos = (nanos: bigint): Duration => make(nanos) /** * Creates a Duration from microseconds. * - * @example + * **Example** (Creating durations from microseconds) + * * ```ts * import { Duration } from "effect" * @@ -563,15 +647,16 @@ export const nanos = (nanos: bigint): Duration => make(nanos) * console.log(Duration.toMillis(duration)) // 500 * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const micros = (micros: bigint): Duration => make(micros * bigint1e3) /** * Creates a Duration from milliseconds. * - * @example + * **Example** (Creating durations from milliseconds) + * * ```ts * import { Duration } from "effect" * @@ -579,15 +664,16 @@ export const micros = (micros: bigint): Duration => make(micros * bigint1e3) * console.log(Duration.toMillis(duration)) // 1000 * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const millis = (millis: number): Duration => make(millis) /** * Creates a Duration from seconds. * - * @example + * **Example** (Creating durations from seconds) + * * ```ts * import { Duration } from "effect" * @@ -595,15 +681,16 @@ export const millis = (millis: number): Duration => make(millis) * console.log(Duration.toMillis(duration)) // 30000 * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const seconds = (seconds: number): Duration => make(seconds * 1000) /** * Creates a Duration from minutes. * - * @example + * **Example** (Creating durations from minutes) + * * ```ts * import { Duration } from "effect" * @@ -611,15 +698,16 @@ export const seconds = (seconds: number): Duration => make(seconds * 1000) * console.log(Duration.toMillis(duration)) // 300000 * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const minutes = (minutes: number): Duration => make(minutes * 60_000) /** * Creates a Duration from hours. * - * @example + * **Example** (Creating durations from hours) + * * ```ts * import { Duration } from "effect" * @@ -627,15 +715,16 @@ export const minutes = (minutes: number): Duration => make(minutes * 60_000) * console.log(Duration.toMillis(duration)) // 7200000 * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const hours = (hours: number): Duration => make(hours * 3_600_000) /** * Creates a Duration from days. * - * @example + * **Example** (Creating durations from days) + * * ```ts * import { Duration } from "effect" * @@ -643,15 +732,16 @@ export const hours = (hours: number): Duration => make(hours * 3_600_000) * console.log(Duration.toMillis(duration)) // 86400000 * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const days = (days: number): Duration => make(days * 86_400_000) /** * Creates a Duration from weeks. * - * @example + * **Example** (Creating durations from weeks) + * * ```ts * import { Duration } from "effect" * @@ -659,15 +749,16 @@ export const days = (days: number): Duration => make(days * 86_400_000) * console.log(Duration.toMillis(duration)) // 604800000 * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const weeks = (weeks: number): Duration => make(weeks * 604_800_000) /** * Converts a Duration to milliseconds. * - * @example + * **Example** (Converting durations to milliseconds) + * * ```ts * import { Duration } from "effect" * @@ -675,8 +766,8 @@ export const weeks = (weeks: number): Duration => make(weeks * 604_800_000) * console.log(Duration.toMillis(Duration.minutes(2))) // 120000 * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export const toMillis = (self: Input): number => match(fromInputUnsafe(self), { @@ -689,7 +780,8 @@ export const toMillis = (self: Input): number => /** * Converts a Duration to seconds. * - * @example + * **Example** (Converting durations to seconds) + * * ```ts * import { Duration } from "effect" * @@ -697,8 +789,8 @@ export const toMillis = (self: Input): number => * console.log(Duration.toSeconds(Duration.minutes(2))) // 120 * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export const toSeconds = (self: Input): number => match(fromInputUnsafe(self), { @@ -711,7 +803,8 @@ export const toSeconds = (self: Input): number => /** * Converts a Duration to minutes. * - * @example + * **Example** (Converting durations to minutes) + * * ```ts * import { Duration } from "effect" * @@ -719,8 +812,8 @@ export const toSeconds = (self: Input): number => * console.log(Duration.toMinutes(Duration.hours(1))) // 60 * ``` * - * @since 3.8.0 * @category getters + * @since 3.8.0 */ export const toMinutes = (self: Input): number => match(fromInputUnsafe(self), { @@ -733,7 +826,8 @@ export const toMinutes = (self: Input): number => /** * Converts a Duration to hours. * - * @example + * **Example** (Converting durations to hours) + * * ```ts * import { Duration } from "effect" * @@ -741,8 +835,8 @@ export const toMinutes = (self: Input): number => * console.log(Duration.toHours(Duration.days(1))) // 24 * ``` * - * @since 3.8.0 * @category getters + * @since 3.8.0 */ export const toHours = (self: Input): number => match(fromInputUnsafe(self), { @@ -755,7 +849,8 @@ export const toHours = (self: Input): number => /** * Converts a Duration to days. * - * @example + * **Example** (Converting durations to days) + * * ```ts * import { Duration } from "effect" * @@ -763,8 +858,8 @@ export const toHours = (self: Input): number => * console.log(Duration.toDays(Duration.weeks(1))) // 7 * ``` * - * @since 3.8.0 * @category getters + * @since 3.8.0 */ export const toDays = (self: Input): number => match(fromInputUnsafe(self), { @@ -777,7 +872,8 @@ export const toDays = (self: Input): number => /** * Converts a Duration to weeks. * - * @example + * **Example** (Converting durations to weeks) + * * ```ts * import { Duration } from "effect" * @@ -785,8 +881,8 @@ export const toDays = (self: Input): number => * console.log(Duration.toWeeks(Duration.days(7))) // 1 * ``` * - * @since 3.8.0 * @category getters + * @since 3.8.0 */ export const toWeeks = (self: Input): number => match(fromInputUnsafe(self), { @@ -797,11 +893,24 @@ export const toWeeks = (self: Input): number => }) /** - * Get the duration in nanoseconds as a bigint. + * Gets the duration in nanoseconds as a bigint. + * + * **When to use** + * + * Use when the duration is known to be finite and you need the nanosecond value + * as a `bigint`. + * + * **Details** + * + * Millisecond-backed fractional durations are rounded to the nearest + * nanosecond, with ties away from zero. + * + * **Gotchas** * * If the duration is infinite, it throws an error. * - * @example + * **Example** (Reading nanoseconds unsafely) + * * ```ts * import { Duration } from "effect" * @@ -809,16 +918,12 @@ export const toWeeks = (self: Input): number => * const nanos = Duration.toNanosUnsafe(duration) * console.log(nanos) // 2000000000n * - * // This will throw an error - * try { - * Duration.toNanosUnsafe(Duration.infinity) - * } catch (error) { - * console.log((error as Error).message) // "Cannot convert infinite duration to nanos" - * } + * // Duration.toNanosUnsafe(Duration.infinity) + * // throws Error: "Cannot convert infinite duration to nanos" * ``` * - * @since 2.0.0 * @category getters + * @since 4.0.0 */ export const toNanosUnsafe = (input: Input): bigint => { const self = fromInputUnsafe(input) @@ -829,16 +934,18 @@ export const toNanosUnsafe = (input: Input): bigint => { case "Nanos": return self.value.nanos case "Millis": - return BigInt(Math.round(self.value.millis * 1_000_000)) + return roundMillisToNanos(self.value.millis) } } /** - * Get the duration in nanoseconds as a bigint. + * Gets the duration in nanoseconds safely as an `Option`. + * + * **Details** * * If the duration is infinite, returns `Option.none()`. * - * **Example** + * **Example** (Safely reading nanoseconds) * * ```ts * import { Duration, Option } from "effect" @@ -850,14 +957,15 @@ export const toNanosUnsafe = (input: Input): bigint => { * ``` * * @category getters - * @since 4.0.0 + * @since 2.0.0 */ export const toNanos: (self: Input) => Option.Option = Option.liftThrowable(toNanosUnsafe) /** * Converts a Duration to high-resolution time format [seconds, nanoseconds]. * - * @example + * **Example** (Converting durations to high-resolution time) + * * ```ts * import { Duration } from "effect" * @@ -866,8 +974,8 @@ export const toNanos: (self: Input) => Option.Option = Option.liftThrowa * console.log(hrtime) // [1, 500000000] * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export const toHrTime = (input: Input): [seconds: number, nanos: number] => { const self = fromInputUnsafe(input) @@ -876,31 +984,24 @@ export const toHrTime = (input: Input): [seconds: number, nanos: number] => { return [Infinity, 0] case "NegativeInfinity": return [-Infinity, 0] - case "Nanos": { - const n = self.value.nanos - const sign = n < bigint0 ? -BigInt(1) : BigInt(1) - const a = n < bigint0 ? -n : n - return [ - Number(sign * (a / bigint1e9)), - Number(sign * (a % bigint1e9)) - ] - } - case "Millis": { - const m = self.value.millis - const sign = m < 0 ? -1 : 1 - const a = Math.abs(m) - return [ - sign * Math.floor(a / 1000), - sign * Math.round((a % 1000) * 1_000_000) - ] - } + case "Nanos": + return nanosToHrTime(self.value.nanos) + case "Millis": + return nanosToHrTime(roundMillisToNanos(self.value.millis)) } } /** - * Pattern matches on a Duration, providing different handlers for millis and nanos. + * Pattern matches on the representation of a `Duration`. + * + * **Details** + * + * Provide handlers for millisecond-backed values, nanosecond-backed values, + * and positive infinity. Use `onNegativeInfinity` to handle negative infinity + * separately; otherwise negative infinity is handled by `onInfinity`. + * + * **Example** (Pattern matching on duration representations) * - * @example * ```ts * import { Duration } from "effect" * @@ -912,14 +1013,21 @@ export const toHrTime = (input: Input): [seconds: number, nanos: number] => { * console.log(result) // "5000 milliseconds" * ``` * - * @since 2.0.0 * @category pattern matching + * @since 2.0.0 */ export const match: { /** - * Pattern matches on a Duration, providing different handlers for millis and nanos. + * Pattern matches on the representation of a `Duration`. + * + * **Details** + * + * Provide handlers for millisecond-backed values, nanosecond-backed values, + * and positive infinity. Use `onNegativeInfinity` to handle negative infinity + * separately; otherwise negative infinity is handled by `onInfinity`. + * + * **Example** (Pattern matching on duration representations) * - * @example * ```ts * import { Duration } from "effect" * @@ -931,8 +1039,8 @@ export const match: { * console.log(result) // "5000 milliseconds" * ``` * - * @since 2.0.0 * @category pattern matching + * @since 2.0.0 */ ( options: { @@ -943,9 +1051,16 @@ export const match: { } ): (self: Duration) => A | B | C | D /** - * Pattern matches on a Duration, providing different handlers for millis and nanos. + * Pattern matches on the representation of a `Duration`. + * + * **Details** + * + * Provide handlers for millisecond-backed values, nanosecond-backed values, + * and positive infinity. Use `onNegativeInfinity` to handle negative infinity + * separately; otherwise negative infinity is handled by `onInfinity`. + * + * **Example** (Pattern matching on duration representations) * - * @example * ```ts * import { Duration } from "effect" * @@ -957,8 +1072,8 @@ export const match: { * console.log(result) // "5000 milliseconds" * ``` * - * @since 2.0.0 * @category pattern matching + * @since 2.0.0 */ ( self: Duration, @@ -993,7 +1108,8 @@ export const match: { /** * Pattern matches on two `Duration`s, providing handlers that receive both values. * - * @example + * **Example** (Pattern matching on duration pairs) + * * ```ts * import { Duration } from "effect" * @@ -1005,14 +1121,15 @@ export const match: { * console.log(sum) // 5000 * ``` * - * @since 2.0.0 * @category pattern matching + * @since 4.0.0 */ export const matchPair: { /** * Pattern matches on two `Duration`s, providing handlers that receive both values. * - * @example + * **Example** (Pattern matching on duration pairs) + * * ```ts * import { Duration } from "effect" * @@ -1024,8 +1141,8 @@ export const matchPair: { * console.log(sum) // 5000 * ``` * - * @since 2.0.0 * @category pattern matching + * @since 4.0.0 */ ( that: Duration, @@ -1038,7 +1155,8 @@ export const matchPair: { /** * Pattern matches on two `Duration`s, providing handlers that receive both values. * - * @example + * **Example** (Pattern matching on duration pairs) + * * ```ts * import { Duration } from "effect" * @@ -1050,8 +1168,8 @@ export const matchPair: { * console.log(sum) // 5000 * ``` * - * @since 2.0.0 * @category pattern matching + * @since 4.0.0 */ ( self: Duration, @@ -1085,11 +1203,14 @@ export const matchPair: { }) /** - * Order instance for `Duration`, allowing comparison operations. + * Provides an `Order` instance for comparing `Duration` values. + * + * **Details** * * `NegativeInfinity` < any finite value < `Infinity`. * - * @example + * **Example** (Sorting durations) + * * ```ts * import { Duration } from "effect" * @@ -1122,9 +1243,24 @@ export const Order: order.Order = order.make((self, that) => ) /** - * Checks if a `Duration` is between a `minimum` and `maximum` value. + * Returns `true` if a `Duration` is greater than or equal to `minimum` and + * less than or equal to `maximum`, according to `Duration.Order`. + * + * **When to use** + * + * Use to test whether a duration is inside an inclusive range. + * + * **Details** + * + * Both bounds are inclusive and compared with `Duration.Order`. + * + * **Gotchas** + * + * The bounds are not normalized. If `minimum` is greater than `maximum`, the + * predicate returns `false` for every duration. + * + * **Example** (Checking duration ranges) * - * @example * ```ts * import { Duration } from "effect" * @@ -1135,14 +1271,33 @@ export const Order: order.Order = order.make((self, that) => * console.log(isInRange) // true * ``` * + * @see {@link clamp} for constraining a duration to a range + * @see {@link isGreaterThanOrEqualTo} for checking only the lower bound + * @see {@link isLessThanOrEqualTo} for checking only the upper bound + * * @category predicates * @since 2.0.0 */ export const between: { /** - * Checks if a `Duration` is between a `minimum` and `maximum` value. + * Returns `true` if a `Duration` is greater than or equal to `minimum` and + * less than or equal to `maximum`, according to `Duration.Order`. + * + * **When to use** + * + * Use to test whether a duration is inside an inclusive range. + * + * **Details** + * + * Both bounds are inclusive and compared with `Duration.Order`. + * + * **Gotchas** + * + * The bounds are not normalized. If `minimum` is greater than `maximum`, the + * predicate returns `false` for every duration. + * + * **Example** (Checking duration ranges) * - * @example * ```ts * import { Duration } from "effect" * @@ -1153,14 +1308,33 @@ export const between: { * console.log(isInRange) // true * ``` * + * @see {@link clamp} for constraining a duration to a range + * @see {@link isGreaterThanOrEqualTo} for checking only the lower bound + * @see {@link isLessThanOrEqualTo} for checking only the upper bound + * * @category predicates * @since 2.0.0 */ (options: { minimum: Duration; maximum: Duration }): (self: Duration) => boolean /** - * Checks if a `Duration` is between a `minimum` and `maximum` value. + * Returns `true` if a `Duration` is greater than or equal to `minimum` and + * less than or equal to `maximum`, according to `Duration.Order`. + * + * **When to use** + * + * Use to test whether a duration is inside an inclusive range. + * + * **Details** + * + * Both bounds are inclusive and compared with `Duration.Order`. + * + * **Gotchas** + * + * The bounds are not normalized. If `minimum` is greater than `maximum`, the + * predicate returns `false` for every duration. + * + * **Example** (Checking duration ranges) * - * @example * ```ts * import { Duration } from "effect" * @@ -1171,6 +1345,10 @@ export const between: { * console.log(isInRange) // true * ``` * + * @see {@link clamp} for constraining a duration to a range + * @see {@link isGreaterThanOrEqualTo} for checking only the lower bound + * @see {@link isLessThanOrEqualTo} for checking only the upper bound + * * @category predicates * @since 2.0.0 */ @@ -1178,9 +1356,10 @@ export const between: { } = order.isBetween(Order) /** - * Equivalence instance for `Duration`, allowing equality comparisons. + * Provides an `Equivalence` instance for comparing `Duration` values. + * + * **Example** (Comparing durations for equivalence) * - * @example * ```ts * import { Duration } from "effect" * @@ -1201,7 +1380,8 @@ export const Equivalence: Equ.Equivalence = (self, that) => /** * Returns the smaller of two Durations. * - * @example + * **Example** (Selecting the shorter duration) + * * ```ts * import { Duration } from "effect" * @@ -1209,14 +1389,15 @@ export const Equivalence: Equ.Equivalence = (self, that) => * console.log(Duration.toSeconds(shorter)) // 3 * ``` * + * @category ordering * @since 2.0.0 - * @category order */ export const min: { /** * Returns the smaller of two Durations. * - * @example + * **Example** (Selecting the shorter duration) + * * ```ts * import { Duration } from "effect" * @@ -1224,14 +1405,15 @@ export const min: { * console.log(Duration.toSeconds(shorter)) // 3 * ``` * + * @category ordering * @since 2.0.0 - * @category order */ (that: Duration): (self: Duration) => Duration /** * Returns the smaller of two Durations. * - * @example + * **Example** (Selecting the shorter duration) + * * ```ts * import { Duration } from "effect" * @@ -1239,8 +1421,8 @@ export const min: { * console.log(Duration.toSeconds(shorter)) // 3 * ``` * + * @category ordering * @since 2.0.0 - * @category order */ (self: Duration, that: Duration): Duration } = order.min(Order) @@ -1248,7 +1430,8 @@ export const min: { /** * Returns the larger of two Durations. * - * @example + * **Example** (Selecting the longer duration) + * * ```ts * import { Duration } from "effect" * @@ -1256,14 +1439,15 @@ export const min: { * console.log(Duration.toSeconds(longer)) // 5 * ``` * + * @category ordering * @since 2.0.0 - * @category order */ export const max: { /** * Returns the larger of two Durations. * - * @example + * **Example** (Selecting the longer duration) + * * ```ts * import { Duration } from "effect" * @@ -1271,14 +1455,15 @@ export const max: { * console.log(Duration.toSeconds(longer)) // 5 * ``` * + * @category ordering * @since 2.0.0 - * @category order */ (that: Duration): (self: Duration) => Duration /** * Returns the larger of two Durations. * - * @example + * **Example** (Selecting the longer duration) + * * ```ts * import { Duration } from "effect" * @@ -1286,16 +1471,17 @@ export const max: { * console.log(Duration.toSeconds(longer)) // 5 * ``` * + * @category ordering * @since 2.0.0 - * @category order */ (self: Duration, that: Duration): Duration } = order.max(Order) /** - * Clamps a Duration between a minimum and maximum value. + * Returns a `Duration` constrained between a minimum and maximum value. + * + * **Example** (Clamping durations to a range) * - * @example * ```ts * import { Duration } from "effect" * @@ -1306,14 +1492,15 @@ export const max: { * console.log(Duration.toSeconds(clamped)) // 5 * ``` * + * @category ordering * @since 2.0.0 - * @category order */ export const clamp: { /** - * Clamps a Duration between a minimum and maximum value. + * Returns a `Duration` constrained between a minimum and maximum value. + * + * **Example** (Clamping durations to a range) * - * @example * ```ts * import { Duration } from "effect" * @@ -1324,14 +1511,15 @@ export const clamp: { * console.log(Duration.toSeconds(clamped)) // 5 * ``` * + * @category ordering * @since 2.0.0 - * @category order */ (options: { minimum: Duration; maximum: Duration }): (self: Duration) => Duration /** - * Clamps a Duration between a minimum and maximum value. + * Returns a `Duration` constrained between a minimum and maximum value. + * + * **Example** (Clamping durations to a range) * - * @example * ```ts * import { Duration } from "effect" * @@ -1342,16 +1530,22 @@ export const clamp: { * console.log(Duration.toSeconds(clamped)) // 5 * ``` * + * @category ordering * @since 2.0.0 - * @category order */ (self: Duration, options: { minimum: Duration; maximum: Duration }): Duration } = order.clamp(Order) /** - * Divides a Duration by a number, returning `Option.none()` if division is invalid. + * Divides a `Duration` by a finite, non-zero number safely. + * + * **Details** * - * **Example** + * Returns `Option.none()` for zero, negative zero, or non-finite divisors. For + * nanosecond-backed durations, also returns `Option.none()` when the divisor + * cannot be converted to a `bigint`, such as a fractional divisor. + * + * **Example** (Safely dividing durations) * * ```ts * import { Duration, Option } from "effect" @@ -1362,14 +1556,20 @@ export const clamp: { * Duration.divide(Duration.seconds(10), 0) // None * ``` * - * @since 4.0.0 * @category math + * @since 2.4.19 */ export const divide: { /** - * Divides a Duration by a number, returning `Option.none()` if division is invalid. + * Divides a `Duration` by a finite, non-zero number safely. * - * **Example** + * **Details** + * + * Returns `Option.none()` for zero, negative zero, or non-finite divisors. For + * nanosecond-backed durations, also returns `Option.none()` when the divisor + * cannot be converted to a `bigint`, such as a fractional divisor. + * + * **Example** (Safely dividing durations) * * ```ts * import { Duration, Option } from "effect" @@ -1380,14 +1580,20 @@ export const divide: { * Duration.divide(Duration.seconds(10), 0) // None * ``` * - * @since 4.0.0 * @category math + * @since 2.4.19 */ (by: number): (self: Duration) => Option.Option /** - * Divides a Duration by a number, returning `Option.none()` if division is invalid. + * Divides a `Duration` by a finite, non-zero number safely. + * + * **Details** * - * **Example** + * Returns `Option.none()` for zero, negative zero, or non-finite divisors. For + * nanosecond-backed durations, also returns `Option.none()` when the divisor + * cannot be converted to a `bigint`, such as a fractional divisor. + * + * **Example** (Safely dividing durations) * * ```ts * import { Duration, Option } from "effect" @@ -1398,8 +1604,8 @@ export const divide: { * Duration.divide(Duration.seconds(10), 0) // None * ``` * - * @since 4.0.0 * @category math + * @since 2.4.19 */ (self: Duration, by: number): Option.Option } = dual( @@ -1423,9 +1629,24 @@ export const divide: { ) /** - * Divides a Duration by a number, potentially returning infinity or zero. + * Divides a `Duration` by a number using fallback rules instead of returning + * an `Option`. + * + * **When to use** + * + * Use when dividing a `Duration` should return `Duration.zero` or signed + * infinity for invalid cases instead of forcing callers to handle `Option.none`. + * + * **Details** + * + * Non-finite divisors return `Duration.zero`. Division by positive or negative + * zero can produce signed infinity for non-zero finite durations, while zero + * or infinite durations divided by zero produce `Duration.zero`. + * Nanosecond-backed durations return `Duration.zero` when the divisor cannot + * be converted to a `bigint`. + * + * **Example** (Dividing durations unsafely) * - * @example * ```ts * import { Duration } from "effect" * @@ -1436,14 +1657,29 @@ export const divide: { * console.log(Duration.toMillis(infinite)) // Infinity * ``` * - * @since 2.4.19 * @category math + * @since 4.0.0 */ export const divideUnsafe: { /** - * Divides a Duration by a number, potentially returning infinity or zero. + * Divides a `Duration` by a number using fallback rules instead of returning + * an `Option`. + * + * **When to use** + * + * Use when dividing a `Duration` should return `Duration.zero` or signed + * infinity for invalid cases instead of forcing callers to handle `Option.none`. + * + * **Details** + * + * Non-finite divisors return `Duration.zero`. Division by positive or negative + * zero can produce signed infinity for non-zero finite durations, while zero + * or infinite durations divided by zero produce `Duration.zero`. + * Nanosecond-backed durations return `Duration.zero` when the divisor cannot + * be converted to a `bigint`. + * + * **Example** (Dividing durations unsafely) * - * @example * ```ts * import { Duration } from "effect" * @@ -1454,14 +1690,29 @@ export const divideUnsafe: { * console.log(Duration.toMillis(infinite)) // Infinity * ``` * - * @since 2.4.19 * @category math + * @since 4.0.0 */ (by: number): (self: Duration) => Duration /** - * Divides a Duration by a number, potentially returning infinity or zero. + * Divides a `Duration` by a number using fallback rules instead of returning + * an `Option`. + * + * **When to use** + * + * Use when dividing a `Duration` should return `Duration.zero` or signed + * infinity for invalid cases instead of forcing callers to handle `Option.none`. + * + * **Details** + * + * Non-finite divisors return `Duration.zero`. Division by positive or negative + * zero can produce signed infinity for non-zero finite durations, while zero + * or infinite durations divided by zero produce `Duration.zero`. + * Nanosecond-backed durations return `Duration.zero` when the divisor cannot + * be converted to a `bigint`. + * + * **Example** (Dividing durations unsafely) * - * @example * ```ts * import { Duration } from "effect" * @@ -1472,8 +1723,8 @@ export const divideUnsafe: { * console.log(Duration.toMillis(infinite)) // Infinity * ``` * - * @since 2.4.19 * @category math + * @since 4.0.0 */ (self: Duration, by: number): Duration } = dual( @@ -1503,9 +1754,17 @@ export const divideUnsafe: { ) /** - * Multiplies a Duration by a number. + * Returns a `Duration` multiplied by a number. + * + * **Details** + * + * For nanosecond-backed durations, the multiplier must be convertible to a + * `bigint`; fractional or non-finite multipliers can throw. Infinite + * durations return positive infinity, negative infinity, or zero depending on + * the multiplier sign. + * + * **Example** (Multiplying durations) * - * @example * ```ts * import { Duration } from "effect" * @@ -1513,14 +1772,22 @@ export const divideUnsafe: { * console.log(Duration.toSeconds(doubled)) // 10 * ``` * - * @since 2.0.0 * @category math + * @since 2.0.0 */ export const times: { /** - * Multiplies a Duration by a number. + * Returns a `Duration` multiplied by a number. + * + * **Details** + * + * For nanosecond-backed durations, the multiplier must be convertible to a + * `bigint`; fractional or non-finite multipliers can throw. Infinite + * durations return positive infinity, negative infinity, or zero depending on + * the multiplier sign. + * + * **Example** (Multiplying durations) * - * @example * ```ts * import { Duration } from "effect" * @@ -1528,14 +1795,22 @@ export const times: { * console.log(Duration.toSeconds(doubled)) // 10 * ``` * - * @since 2.0.0 * @category math + * @since 2.0.0 */ (times: number): (self: Duration) => Duration /** - * Multiplies a Duration by a number. + * Returns a `Duration` multiplied by a number. + * + * **Details** + * + * For nanosecond-backed durations, the multiplier must be convertible to a + * `bigint`; fractional or non-finite multipliers can throw. Infinite + * durations return positive infinity, negative infinity, or zero depending on + * the multiplier sign. + * + * **Example** (Multiplying durations) * - * @example * ```ts * import { Duration } from "effect" * @@ -1543,8 +1818,8 @@ export const times: { * console.log(Duration.toSeconds(doubled)) // 10 * ``` * - * @since 2.0.0 * @category math + * @since 2.0.0 */ (self: Duration, times: number): Duration } = dual( @@ -1561,17 +1836,17 @@ export const times: { /** * Subtracts one Duration from another. The result can be negative. * - * **Infinity Subtraction Rules** - * - infinity - infinity = 0 - * - infinity - negativeInfinity = infinity - * - infinity - finite = infinity - * - negativeInfinity - negativeInfinity = 0 - * - negativeInfinity - infinity = negativeInfinity - * - negativeInfinity - finite = negativeInfinity - * - finite - infinity = negativeInfinity - * - finite - negativeInfinity = infinity - * - * @example + * **Details** + * + * Infinity subtraction follows signed-infinity arithmetic. Subtracting the + * same infinity from itself returns zero. Positive infinity minus negative + * infinity or any finite duration remains positive infinity. Negative infinity + * minus positive infinity or any finite duration remains negative infinity. + * Finite durations minus positive infinity produce negative infinity, and + * finite durations minus negative infinity produce positive infinity. + * + * **Example** (Subtracting durations) + * * ```ts * import { Duration } from "effect" * @@ -1579,24 +1854,24 @@ export const times: { * console.log(Duration.toSeconds(result)) // 7 * ``` * - * @since 2.0.0 * @category math + * @since 2.0.0 */ export const subtract: { /** * Subtracts one Duration from another. The result can be negative. * - * **Infinity Subtraction Rules** - * - infinity - infinity = 0 - * - infinity - negativeInfinity = infinity - * - infinity - finite = infinity - * - negativeInfinity - negativeInfinity = 0 - * - negativeInfinity - infinity = negativeInfinity - * - negativeInfinity - finite = negativeInfinity - * - finite - infinity = negativeInfinity - * - finite - negativeInfinity = infinity - * - * @example + * **Details** + * + * Infinity subtraction follows signed-infinity arithmetic. Subtracting the + * same infinity from itself returns zero. Positive infinity minus negative + * infinity or any finite duration remains positive infinity. Negative infinity + * minus positive infinity or any finite duration remains negative infinity. + * Finite durations minus positive infinity produce negative infinity, and + * finite durations minus negative infinity produce positive infinity. + * + * **Example** (Subtracting durations) + * * ```ts * import { Duration } from "effect" * @@ -1604,24 +1879,24 @@ export const subtract: { * console.log(Duration.toSeconds(result)) // 7 * ``` * - * @since 2.0.0 * @category math + * @since 2.0.0 */ (that: Duration): (self: Duration) => Duration /** * Subtracts one Duration from another. The result can be negative. * - * **Infinity Subtraction Rules** - * - infinity - infinity = 0 - * - infinity - negativeInfinity = infinity - * - infinity - finite = infinity - * - negativeInfinity - negativeInfinity = 0 - * - negativeInfinity - infinity = negativeInfinity - * - negativeInfinity - finite = negativeInfinity - * - finite - infinity = negativeInfinity - * - finite - negativeInfinity = infinity - * - * @example + * **Details** + * + * Infinity subtraction follows signed-infinity arithmetic. Subtracting the + * same infinity from itself returns zero. Positive infinity minus negative + * infinity or any finite duration remains positive infinity. Negative infinity + * minus positive infinity or any finite duration remains negative infinity. + * Finite durations minus positive infinity produce negative infinity, and + * finite durations minus negative infinity produce positive infinity. + * + * **Example** (Subtracting durations) + * * ```ts * import { Duration } from "effect" * @@ -1629,8 +1904,8 @@ export const subtract: { * console.log(Duration.toSeconds(result)) // 7 * ``` * - * @since 2.0.0 * @category math + * @since 2.0.0 */ (self: Duration, that: Duration): Duration } = dual( @@ -1652,14 +1927,18 @@ export const subtract: { /** * Adds two Durations together. * - * **Infinity Addition Rules** + * **Details** + * + * Infinity addition follows these rules: + * * - infinity + infinity = infinity * - infinity + negativeInfinity = zero * - infinity + finite = infinity * - negativeInfinity + negativeInfinity = negativeInfinity * - negativeInfinity + finite = negativeInfinity * - * @example + * **Example** (Adding durations) + * * ```ts * import { Duration } from "effect" * @@ -1667,21 +1946,25 @@ export const subtract: { * console.log(Duration.toSeconds(total)) // 8 * ``` * - * @since 2.0.0 * @category math + * @since 2.0.0 */ export const sum: { /** * Adds two Durations together. * - * **Infinity Addition Rules** + * **Details** + * + * Infinity addition follows these rules: + * * - infinity + infinity = infinity * - infinity + negativeInfinity = zero * - infinity + finite = infinity * - negativeInfinity + negativeInfinity = negativeInfinity * - negativeInfinity + finite = negativeInfinity * - * @example + * **Example** (Adding durations) + * * ```ts * import { Duration } from "effect" * @@ -1689,21 +1972,25 @@ export const sum: { * console.log(Duration.toSeconds(total)) // 8 * ``` * - * @since 2.0.0 * @category math + * @since 2.0.0 */ (that: Duration): (self: Duration) => Duration /** * Adds two Durations together. * - * **Infinity Addition Rules** + * **Details** + * + * Infinity addition follows these rules: + * * - infinity + infinity = infinity * - infinity + negativeInfinity = zero * - infinity + finite = infinity * - negativeInfinity + negativeInfinity = negativeInfinity * - negativeInfinity + finite = negativeInfinity * - * @example + * **Example** (Adding durations) + * * ```ts * import { Duration } from "effect" * @@ -1711,8 +1998,8 @@ export const sum: { * console.log(Duration.toSeconds(total)) // 8 * ``` * - * @since 2.0.0 * @category math + * @since 2.0.0 */ (self: Duration, that: Duration): Duration } = dual( @@ -1735,9 +2022,10 @@ export const sum: { ) /** - * Checks if the first Duration is less than the second. + * Checks whether the first Duration is less than the second. + * + * **Example** (Comparing durations with less than) * - * @example * ```ts * import { Duration } from "effect" * @@ -1745,14 +2033,15 @@ export const sum: { * console.log(isLess) // true * ``` * - * @since 2.0.0 * @category predicates + * @since 4.0.0 */ export const isLessThan: { /** - * Checks if the first Duration is less than the second. + * Checks whether the first Duration is less than the second. + * + * **Example** (Comparing durations with less than) * - * @example * ```ts * import { Duration } from "effect" * @@ -1760,14 +2049,15 @@ export const isLessThan: { * console.log(isLess) // true * ``` * - * @since 2.0.0 * @category predicates + * @since 4.0.0 */ (that: Duration): (self: Duration) => boolean /** - * Checks if the first Duration is less than the second. + * Checks whether the first Duration is less than the second. + * + * **Example** (Comparing durations with less than) * - * @example * ```ts * import { Duration } from "effect" * @@ -1775,16 +2065,17 @@ export const isLessThan: { * console.log(isLess) // true * ``` * - * @since 2.0.0 * @category predicates + * @since 4.0.0 */ (self: Duration, that: Duration): boolean } = order.isLessThan(Order) /** - * Checks if the first Duration is less than or equal to the second. + * Checks whether the first Duration is less than or equal to the second. + * + * **Example** (Comparing durations with less than or equal) * - * @example * ```ts * import { Duration } from "effect" * @@ -1795,14 +2086,15 @@ export const isLessThan: { * console.log(isLessOrEqual) // true * ``` * - * @since 2.0.0 * @category predicates + * @since 4.0.0 */ export const isLessThanOrEqualTo: { /** - * Checks if the first Duration is less than or equal to the second. + * Checks whether the first Duration is less than or equal to the second. + * + * **Example** (Comparing durations with less than or equal) * - * @example * ```ts * import { Duration } from "effect" * @@ -1813,14 +2105,15 @@ export const isLessThanOrEqualTo: { * console.log(isLessOrEqual) // true * ``` * - * @since 2.0.0 * @category predicates + * @since 4.0.0 */ (that: Duration): (self: Duration) => boolean /** - * Checks if the first Duration is less than or equal to the second. + * Checks whether the first Duration is less than or equal to the second. + * + * **Example** (Comparing durations with less than or equal) * - * @example * ```ts * import { Duration } from "effect" * @@ -1831,16 +2124,17 @@ export const isLessThanOrEqualTo: { * console.log(isLessOrEqual) // true * ``` * - * @since 2.0.0 * @category predicates + * @since 4.0.0 */ (self: Duration, that: Duration): boolean } = order.isLessThanOrEqualTo(Order) /** - * Checks if the first Duration is greater than the second. + * Checks whether the first Duration is greater than the second. + * + * **Example** (Comparing durations with greater than) * - * @example * ```ts * import { Duration } from "effect" * @@ -1848,14 +2142,15 @@ export const isLessThanOrEqualTo: { * console.log(isGreater) // true * ``` * - * @since 2.0.0 * @category predicates + * @since 4.0.0 */ export const isGreaterThan: { /** - * Checks if the first Duration is greater than the second. + * Checks whether the first Duration is greater than the second. + * + * **Example** (Comparing durations with greater than) * - * @example * ```ts * import { Duration } from "effect" * @@ -1863,14 +2158,15 @@ export const isGreaterThan: { * console.log(isGreater) // true * ``` * - * @since 2.0.0 * @category predicates + * @since 4.0.0 */ (that: Duration): (self: Duration) => boolean /** - * Checks if the first Duration is greater than the second. + * Checks whether the first Duration is greater than the second. + * + * **Example** (Comparing durations with greater than) * - * @example * ```ts * import { Duration } from "effect" * @@ -1878,16 +2174,17 @@ export const isGreaterThan: { * console.log(isGreater) // true * ``` * - * @since 2.0.0 * @category predicates + * @since 4.0.0 */ (self: Duration, that: Duration): boolean } = order.isGreaterThan(Order) /** - * Checks if the first Duration is greater than or equal to the second. + * Checks whether the first Duration is greater than or equal to the second. + * + * **Example** (Comparing durations with greater than or equal) * - * @example * ```ts * import { Duration } from "effect" * @@ -1898,14 +2195,15 @@ export const isGreaterThan: { * console.log(isGreaterOrEqual) // true * ``` * - * @since 2.0.0 * @category predicates + * @since 4.0.0 */ export const isGreaterThanOrEqualTo: { /** - * Checks if the first Duration is greater than or equal to the second. + * Checks whether the first Duration is greater than or equal to the second. + * + * **Example** (Comparing durations with greater than or equal) * - * @example * ```ts * import { Duration } from "effect" * @@ -1916,14 +2214,15 @@ export const isGreaterThanOrEqualTo: { * console.log(isGreaterOrEqual) // true * ``` * - * @since 2.0.0 * @category predicates + * @since 4.0.0 */ (that: Duration): (self: Duration) => boolean /** - * Checks if the first Duration is greater than or equal to the second. + * Checks whether the first Duration is greater than or equal to the second. + * + * **Example** (Comparing durations with greater than or equal) * - * @example * ```ts * import { Duration } from "effect" * @@ -1934,16 +2233,17 @@ export const isGreaterThanOrEqualTo: { * console.log(isGreaterOrEqual) // true * ``` * - * @since 2.0.0 * @category predicates + * @since 4.0.0 */ (self: Duration, that: Duration): boolean } = order.isGreaterThanOrEqualTo(Order) /** - * Checks if two Durations are equal. + * Checks whether two Durations are equal. + * + * **Example** (Checking duration equality) * - * @example * ```ts * import { Duration } from "effect" * @@ -1951,14 +2251,15 @@ export const isGreaterThanOrEqualTo: { * console.log(isEqual) // true * ``` * - * @since 2.0.0 * @category predicates + * @since 2.0.0 */ export const equals: { /** - * Checks if two Durations are equal. + * Checks whether two Durations are equal. + * + * **Example** (Checking duration equality) * - * @example * ```ts * import { Duration } from "effect" * @@ -1966,14 +2267,15 @@ export const equals: { * console.log(isEqual) // true * ``` * - * @since 2.0.0 * @category predicates + * @since 2.0.0 */ (that: Duration): (self: Duration) => boolean /** - * Checks if two Durations are equal. + * Checks whether two Durations are equal. + * + * **Example** (Checking duration equality) * - * @example * ```ts * import { Duration } from "effect" * @@ -1981,16 +2283,23 @@ export const equals: { * console.log(isEqual) // true * ``` * - * @since 2.0.0 * @category predicates + * @since 2.0.0 */ (self: Duration, that: Duration): boolean } = dual(2, (self: Duration, that: Duration): boolean => Equivalence(self, that)) /** - * Converts a `Duration` to its parts. + * Decomposes a `Duration` into normalized signed components. + * + * **Details** + * + * Finite durations are returned as `{ days, hours, minutes, seconds, millis, + * nanos }`. Infinite durations return every component as `Infinity` or + * `-Infinity`. + * + * **Example** (Decomposing durations into parts) * - * @example * ```ts * import { Duration } from "effect" * @@ -2026,8 +2335,8 @@ export const equals: { * // } * ``` * + * @category converting * @since 3.8.0 - * @category conversions */ export const parts = (self: Duration): { days: number @@ -2081,15 +2390,17 @@ export const parts = (self: Duration): { /** * Converts a `Duration` to a human readable string. * - * @since 2.0.0 - * @category conversions - * @example + * **Example** (Formatting durations) + * * ```ts * import { Duration } from "effect" * * Duration.format(Duration.millis(1000)) // "1s" * Duration.format(Duration.millis(1001)) // "1s 1ms" * ``` + * + * @category converting + * @since 2.0.0 */ export const format = (self: Duration): string => { if (self.value._tag === "Infinity") { @@ -2135,22 +2446,52 @@ export const format = (self: Duration): string => { } /** - * A `Reducer` for summing `Duration`s. + * Reducer for summing `Duration`s. + * + * **When to use** + * + * Use to sum many `Duration` values through APIs that consume a `Reducer`. + * + * **Details** + * + * `ReducerSum` uses `sum` and starts from `zero`, so `combineAll([])` returns + * `zero`. * + * @see {@link sum} for adding two duration values directly + * @see {@link CombinerMax} for keeping the longest duration instead of summing + * @see {@link CombinerMin} for keeping the shortest duration instead of summing + * + * @category math * @since 4.0.0 */ export const ReducerSum: Reducer.Reducer = Reducer.make(sum, zero) /** - * A `Combiner` that returns the maximum `Duration`. + * Combiner that returns the maximum `Duration`. + * + * **When to use** + * + * Use to keep the longest `Duration` when an API consumes a `Combiner`. + * + * @see {@link CombinerMin} for keeping the shortest `Duration` + * @see {@link max} for comparing two `Duration` values directly * + * @category math * @since 4.0.0 */ export const CombinerMax: Combiner.Combiner = Combiner.max(Order) /** - * A `Combiner` that returns the minimum `Duration`. + * Combiner that returns the minimum `Duration`. + * + * **When to use** + * + * Use to keep the shortest `Duration` through APIs that consume a `Combiner`. * + * @see {@link CombinerMax} for keeping the longest `Duration` + * @see {@link min} for comparing two `Duration` values directly + * + * @category math * @since 4.0.0 */ export const CombinerMin: Combiner.Combiner = Combiner.min(Order) diff --git a/.opencode/node_modules/effect/src/Effect.ts b/.opencode/node_modules/effect/src/Effect.ts index 45089fa9b761b4b5a870172b9f555f9a0bc24ab2..9c4faefa72d68d3b5cfd22b584c69910ab54cad5 100644 --- a/.opencode/node_modules/effect/src/Effect.ts +++ b/.opencode/node_modules/effect/src/Effect.ts @@ -1,70 +1,12 @@ /** - * The `Effect` module is the core of the Effect library, providing a powerful and expressive - * way to model and compose asynchronous, concurrent, and effectful computations. + * Describes workflows that run only when executed by the Effect runtime. * - * An `Effect` represents a computation that: - * - May succeed with a value of type `A` - * - May fail with an error of type `E` - * - Requires a context/environment of type `R` - * - * Effects are lazy and immutable - they describe computations that can be executed later. - * This allows for powerful composition, error handling, resource management, and concurrency - * patterns. - * - * ## Key Features - * - * - **Type-safe error handling**: Errors are tracked in the type system - * - **Resource management**: Automatic cleanup with scoped resources - * - **Structured concurrency**: Safe parallel and concurrent execution - * - **Composable**: Effects can be combined using operators like `flatMap`, `map`, `zip` - * - **Testable**: Built-in support for testing with controlled environments - * - **Interruptible**: Effects can be safely interrupted and cancelled - * - * @example - * ```ts - * import { Console, Effect } from "effect" - * - * // Creating a simple effect - * const hello = Effect.succeed("Hello, World!") - * - * // Composing effects - * const program = Effect.gen(function*() { - * const message = yield* hello - * yield* Console.log(message) - * return message.length - * }) - * - * // Running the effect - * Effect.runPromise(program).then(console.log) // 13 - * ``` - * - * @example - * ```ts - * import { Data, Effect } from "effect" - * - * class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} - * - * // Effect that may fail - * const divide = (a: number, b: number) => - * b === 0 - * ? Effect.fail(new DiscountRateError()) - * : Effect.succeed(a / b) - * - * // Error handling - * const program = Effect.gen(function*() { - * const result = yield* divide(10, 2) - * console.log("Result:", result) // Result: 5 - * return result - * }) - * - * // Handle errors - * const safeProgram = program.pipe( - * Effect.match({ - * onFailure: (error) => -1, - * onSuccess: (value) => value - * }) - * ) - * ``` + * An `Effect` can succeed with an `A`, fail with an `E`, and require + * services `R`. Creating an effect does not perform the work; it builds a value + * that can be composed, provided with services, retried, interrupted, run + * concurrently, or inspected by the runtime. This module is the main API for + * creating effects, combining them, handling failures, managing resources, and + * running effect programs. * * @since 2.0.0 */ @@ -129,15 +71,36 @@ import type { unassigned } from "./Types.ts" import type * as Unify from "./Unify.ts" -import { internalCall, SingleShotGen } from "./Utils.ts" +import { internalCall } from "./Utils.ts" -const TypeId = core.EffectTypeId +/** + * Type-level identifier for `Effect` values. + * + * @category type IDs + * @since 4.0.0 + */ +export type TypeId = "~effect/Effect" + +/** + * Runtime identifier used to recognize `Effect` values. + * + * @category type IDs + * @since 4.0.0 + */ +export const TypeId: TypeId = core.EffectTypeId /** * The `Effect` interface defines a value that lazily describes a workflow or * job. The workflow requires some context `R`, and may fail with an error of * type `E`, or succeed with a value of type `A`. * + * **When to use** + * + * Use when you need to represent a lazy, composable workflow that can require + * services, fail with a typed error, or succeed with a typed value. + * + * **Details** + * * `Effect` values model resourceful interaction with the outside world, * including synchronous, asynchronous, concurrent, and parallel interaction. * They use a fiber-based concurrency model, with built-in support for @@ -147,96 +110,22 @@ const TypeId = core.EffectTypeId * To run an `Effect` value, you need a `Runtime`, which is a type that is * capable of executing `Effect` values. * - * @example - * ```ts - * import { Data, Effect } from "effect" - * - * class TaskError extends Data.TaggedError("TaskError")<{ readonly message: string }> {} - * - * // A simple effect that succeeds with a value - * const success = Effect.succeed(42) - * - * // An effect that will always fail - * const risky = Effect.fail(new TaskError({ message: "Something went wrong" })) - * - * // Effects can be composed using generator functions - * const program = Effect.gen(function*() { - * const value = yield* success - * console.log(value) // 42 - * return value * 2 - * }) - * ``` - * + * @category models * @since 2.0.0 - * @category Models */ -export interface Effect - extends Pipeable, Inspectable, Yieldable, A, E, R> -{ +export interface Effect extends Pipeable, Inspectable { readonly [TypeId]: Variance + [Symbol.iterator](): EffectIterator> [Unify.typeSymbol]?: unknown [Unify.unifySymbol]?: EffectUnify [Unify.ignoreSymbol]?: {} } /** - * A type that can be yielded in an Effect generator function. - * - * The `Yieldable` interface allows values to be used with the `yield*` syntax - * in Effect generator functions, providing a clean way to sequence effectful operations. - * - * @example - * ```ts - * import { Effect } from "effect" + * Type-level unification support for `Effect` values. * - * // Effects implement Yieldable and can be used with yield* - * const effect1 = Effect.succeed(10) - * const effect2 = Effect.succeed(20) - * - * const program = Effect.gen(function*() { - * const a = yield* effect1 // yields the Effect which implements Yieldable - * const b = yield* effect2 - * return a + b - * }) - * - * Effect.runPromise(program).then(console.log) // 30 - * ``` - * - * @since 4.0.0 - * @category Yieldable - */ -export interface Yieldable< - out Self extends Yieldable, - out A, - out E = never, - out R = never -> { - asEffect(): Effect - [Symbol.iterator](): EffectIterator -} - -/** - * @since 4.0.0 - * @category Yieldable - */ -export abstract class YieldableClass implements Yieldable { - [Symbol.iterator](): EffectIterator { - return new SingleShotGen(this) as any - } - abstract asEffect(): Effect -} - -/** - * @category Models + * @category models * @since 2.0.0 - * @example - * ```ts - * import type { Effect } from "effect" - * - * // EffectUnify is used internally for type unification - * // It enables automatic unification of Effect types in unions - * declare const unified: Effect.EffectUnify - * ``` */ export interface EffectUnify { Effect?: () => A[Unify.typeSymbol] extends @@ -246,16 +135,10 @@ export interface EffectUnify { } /** - * @category Type Lambdas - * @since 2.0.0 - * @example - * ```ts - * import type { Effect } from "effect" + * Type lambda used to represent `Effect` in higher-kinded APIs. * - * // EffectTypeLambda is used for higher-kinded type operations - * // It defines the type structure for Effect in higher-kinded contexts - * declare const lambda: Effect.EffectTypeLambda - * ``` + * @category type lambdas + * @since 2.0.0 */ export interface EffectTypeLambda extends TypeLambda { readonly type: Effect @@ -264,8 +147,8 @@ export interface EffectTypeLambda extends TypeLambda { /** * Variance interface for Effect, encoding the type parameters' variance. * + * @category models * @since 2.0.0 - * @category Models */ export interface Variance { _A: Covariant @@ -274,82 +157,65 @@ export interface Variance { } /** - * @since 2.0.0 - * @category Models - * @example - * ```ts - * import type { Effect } from "effect" + * Extracts the success type from an `Effect`. * - * // Extract the success type from an Effect - * declare const myEffect: Effect.Effect - * // This type utility extracts the success type A from Effect - * ``` + * **When to use** + * + * Use to derive the value produced by an existing effect when declaring + * reusable type aliases, service interfaces, or function signatures. + * + * @see {@link Error} for extracting the failure type from the same `Effect` + * @see {@link Services} for extracting the required services from the same `Effect` + * + * @category models + * @since 2.0.0 */ export type Success = T extends Effect ? _A : never /** - * @since 2.0.0 - * @category Models - * @example - * ```ts - * import type { Effect } from "effect" + * Extracts the error type from an `Effect`. * - * // Extract the error type from an Effect - * declare const myEffect: Effect.Effect - * // This type utility extracts the error type E from Effect - * ``` + * **When to use** + * + * Use to derive the error type from an existing `Effect` type when declaring + * helper types, wrappers, or APIs that preserve the effect's failure channel. + * + * **Details** + * + * Non-`Effect` inputs resolve to `never`. + * + * @see {@link Success} for extracting the success value type instead + * @see {@link Services} for extracting the required services type instead + * + * @category models + * @since 2.0.0 */ export type Error = T extends Effect ? _E : never /** - * @since 2.0.0 - * @category Models - * @example - * ```ts - * import type { Effect } from "effect" + * Extracts the required services type from an `Effect`. * - * // Extract the context/services type from an Effect - * declare const myEffect: Effect.Effect - * // This type utility extracts the context type R from Effect - * ``` + * **When to use** + * + * Use to derive the context requirements of a generic or inferred `Effect` + * without restating its `R` type parameter. + * + * @see {@link Success} for extracting the success value type instead + * @see {@link Error} for extracting the failure type instead + * + * @category models + * @since 4.0.0 */ export type Services = T extends Effect ? _R : never /** - * Namespace containing type utilities for Yieldable values. + * Checks whether a value is an `Effect`. * - * @since 4.0.0 - * @category Yieldable - */ -export declare namespace Yieldable { - /** - * @since 4.0.0 - * @category Yieldable - */ - export type Any = Yieldable - - /** - * @since 4.0.0 - * @category Yieldable - * @example - * ```ts - * import type { Effect } from "effect" - * - * // Extract the success type from a Yieldable - * type SuccessType = Effect.Yieldable.Success> // string - * ``` - */ - export type Success = T extends Yieldable ? _A - : never -} - -/** - * Tests if a value is an `Effect`. + * **Example** (Checking whether a value is an Effect) * - * @example * ```ts * import { Effect } from "effect" * @@ -357,37 +223,28 @@ export declare namespace Yieldable { * console.log(Effect.isEffect("hello")) // false * ``` * + * @category guards * @since 2.0.0 - * @category Guards */ export const isEffect: (u: unknown) => u is Effect = core.isEffect /** * Iterator interface for Effect generators, enabling Effect values to work with generator functions. * - * @example - * ```ts - * import { Effect } from "effect" + * **When to use** * - * // Effects are iterable and work with generator functions - * const program = Effect.gen(function*() { - * const effect: Effect.Effect = Effect.succeed(42) + * Use when defining or typing `[Symbol.iterator]()` for values typed as + * `Effect`s so `yield*` can pass their success type back into `Effect.gen`. * - * // The effect's iterator is used internally by yield* - * const result = yield* effect - * return result * 2 - * }) + * @see {@link gen} for writing generator-based `Effect` programs that consume this iterator protocol * - * Effect.runPromise(program).then(console.log) // 84 - * ``` - * - * @since 2.0.0 - * @category Models + * @category models + * @since 4.0.0 */ -export interface EffectIterator> { +export interface EffectIterator> { next( ...args: ReadonlyArray - ): IteratorResult> + ): IteratorResult> } // ======================================================================== @@ -398,59 +255,22 @@ export interface EffectIterator> { * Namespace containing type utilities for the `Effect.all` function, which handles * collecting multiple effects into various output structures. * - * @example - * ```ts - * import { Effect } from "effect" - * - * // All namespace types are used when working with Effect.all - * const effects = [ - * Effect.succeed(1), - * Effect.succeed("hello"), - * Effect.succeed(true) - * ] as const - * - * const program = Effect.all(effects).pipe( - * Effect.map(([num, str, bool]) => ({ num, str, bool })) - * ) - * - * Effect.runPromise(program).then(console.log) // { num: 1, str: "hello", bool: true } - * ``` - * * @since 2.0.0 - * @category Models */ export declare namespace All { /** - * @since 2.0.0 - * @category Models - * @example - * ```ts - * import { Data, Effect } from "effect" - * - * class OopsError extends Data.TaggedError("OopsError")<{}> {} + * Alias for any `Effect` value accepted by `Effect.all`. * - * // EffectAny represents an Effect with any type parameters - * const effects: Array = [ - * Effect.succeed(42), - * Effect.succeed("hello"), - * Effect.fail(new OopsError()) - * ] - * ``` + * @category utility types + * @since 2.0.0 */ export type EffectAny = Effect /** - * @since 2.0.0 - * @category Models - * @example - * ```ts - * import type { Effect } from "effect" + * Computes the return type for `Effect.all` when collecting an iterable. * - * // ReturnIterable computes the return type for Effect.all with iterables - * type EffectArray = Array> - * type Result = Effect.All.ReturnIterable - * // Result: Effect, string, never> - * ``` + * @category utility types + * @since 2.0.0 */ export type ReturnIterable< T extends Iterable, @@ -464,20 +284,10 @@ export declare namespace All { : never /** - * @since 2.0.0 - * @category Models - * @example - * ```ts - * import type { Effect } from "effect" + * Computes the return type for `Effect.all` when collecting a tuple. * - * // ReturnTuple computes the return type for Effect.all with tuples - * type EffectTuple = [ - * Effect.Effect, - * Effect.Effect - * ] - * type Result = Effect.All.ReturnTuple - * // Result: Effect<[string, number], Error, never> - * ``` + * @category utility types + * @since 2.0.0 */ export type ReturnTuple< T extends ReadonlyArray, @@ -505,20 +315,10 @@ export declare namespace All { : never /** - * @since 2.0.0 - * @category Models - * @example - * ```ts - * import type { Effect } from "effect" + * Computes the return type for `Effect.all` when collecting a record. * - * // ReturnObject computes the return type for Effect.all with objects - * type EffectRecord = { - * a: Effect.Effect - * b: Effect.Effect - * } - * type Result = Effect.All.ReturnObject - * // Result: Effect<{ a: string, b: number }, Error, never> - * ``` + * @category utility types + * @since 2.0.0 */ export type ReturnObject = [T] extends [ Record @@ -541,18 +341,10 @@ export declare namespace All { : never /** - * @since 2.0.0 - * @category Models - * @example - * ```ts - * import type { Effect } from "effect" + * Detects whether `Effect.all` should discard collected values. * - * // IsDiscard checks if options have discard flag set to true - * type DiscardOptions = { discard: true } - * type NoDiscardOptions = { discard: false } - * type WithDiscard = Effect.All.IsDiscard // true - * type WithoutDiscard = Effect.All.IsDiscard // false - * ``` + * @category utility types + * @since 2.0.0 */ export type IsDiscard = [Extract] extends [ never @@ -560,24 +352,18 @@ export declare namespace All { : true /** + * Detects whether `Effect.all` should collect results in `Result` mode. + * + * @category utility types * @since 4.0.0 - * @category Models */ export type IsResult = [Extract] extends [never] ? false : true /** - * @since 2.0.0 - * @category Models - * @example - * ```ts - * import type { Effect } from "effect" + * Computes the return type for `Effect.all` from its input and options. * - * // Return determines the result type based on input and options - * type EffectArray = Array> - * type Options = { discard: false } - * type Result = Effect.All.Return - * // Result: Effect, string, never> - * ``` + * @category utility types + * @since 2.0.0 */ export type Return< Arg extends Iterable | Record, @@ -593,49 +379,30 @@ export declare namespace All { } /** - * Combines multiple effects into one, returning results based on the input - * structure. - * - * **Details** - * - * Use this function when you need to run multiple effects and combine their - * results into a single output. It supports tuples, iterables, structs, and - * records, making it flexible for different input types. - * - * For instance, if the input is a tuple: + * Combines an iterable or record of effects into one effect whose success shape + * follows the input. * - * ```ts skip-type-checking - * // ┌─── a tuple of effects - * // ▼ - * Effect.all([effect1, effect2, ...]) - * ``` - * - * the effects are executed sequentially, and the result is a new effect - * containing the results as a tuple. The results in the tuple match the order - * of the effects passed to `Effect.all`. + * **When to use** * - * **Concurrency** + * Use to run a known collection of effects and collect results in the same + * tuple, iterable, or record shape. * - * You can control the execution order (e.g., sequential vs. concurrent) using - * the `concurrency` option. + * **Details** * - * **Short-Circuiting Behavior** + * Tuple and iterable inputs collect results in order. Record inputs collect + * results under the same keys. By default, the combined effect fails on the + * first failure; with concurrent execution, effects that have already started + * may be interrupted, while effects not yet started are skipped. * - * This function stops execution on the first error it encounters, this is - * called "short-circuiting". If any effect in the collection fails, the - * remaining effects will not run, and the error will be propagated. To change - * this behavior, you can use the `mode` option, which allows all effects to run - * and collect every success / failure as `Result` values. + * Options: * - * **The `mode` option** + * Use `concurrency` to control sequential or concurrent execution. Use + * `mode: "result"` to run every effect and collect each success or failure as a + * `Result` in the same output shape. Use `discard: true` to ignore successful + * values and return `void`. * - * The `{ mode: "result" }` option changes the behavior of `Effect.all` to - * ensure all effects run, even if some fail. Instead of stopping on the first - * failure, this mode collects both successes and failures, returning an array - * of `Result` instances where each result is either an `Ok` (success) or a - * `Err` (failure). + * **Example** (Collecting tuple results in order) * - * @example Combining Effects in Tuples * ```ts * import { Console, Effect } from "effect" * @@ -655,7 +422,8 @@ export declare namespace All { * // [ 42, 'Hello' ] * ``` * - * @example Combining Effects in Iterables + * **Example** (Collecting iterable results in order) + * * ```ts * import { Console, Effect } from "effect" * @@ -675,7 +443,8 @@ export declare namespace All { * // [ 1, 2, 3 ] * ``` * - * @example Combining Effects in Structs + * **Example** (Collecting struct results by key) + * * ```ts * import { Console, Effect } from "effect" * @@ -695,7 +464,8 @@ export declare namespace All { * // { a: 42, b: 'Hello' } * ``` * - * @example Combining Effects in Records + * **Example** (Collecting record results by key) + * * ```ts * import { Console, Effect } from "effect" * @@ -715,7 +485,8 @@ export declare namespace All { * // { key1: 1, key2: 2 } * ``` * - * @example Short-Circuiting Behavior + * **Example** (Stopping on the first failure) + * * ```ts * import { Console, Effect } from "effect" * @@ -737,9 +508,8 @@ export declare namespace All { * ``` * * @see {@link forEach} for iterating over elements and applying an effect. - * + * @category collecting * @since 2.0.0 - * @category Collecting */ export const all: < const Arg extends @@ -759,15 +529,16 @@ export const all: < * Applies an effectful function to each element and partitions failures and * successes. * - * The returned tuple is `[excluded, satisfying]`, where: + * **Details** * - * - `excluded` contains all failures. - * - `satisfying` contains all successes. + * The returned tuple is `[excluded, satisfying]`, where `excluded` contains + * all failures and `satisfying` contains all successes. * * This function runs every effect and never fails. Use `concurrency` to control * parallelism. * - * @example + * **Example** (Separating successes and failures) + * * ```ts * import { Effect } from "effect" * @@ -779,23 +550,24 @@ export const all: < * // [ ["0 is even", "2 is even"], [1, 3] ] * ``` * - * @since 3.0.0 - * @category Collecting + * @category collecting + * @since 2.0.0 */ export const partition: { /** * Applies an effectful function to each element and partitions failures and * successes. * - * The returned tuple is `[excluded, satisfying]`, where: + * **Details** * - * - `excluded` contains all failures. - * - `satisfying` contains all successes. + * The returned tuple is `[excluded, satisfying]`, where `excluded` contains + * all failures and `satisfying` contains all successes. * * This function runs every effect and never fails. Use `concurrency` to control * parallelism. * - * @example + * **Example** (Separating successes and failures) + * * ```ts * import { Effect } from "effect" * @@ -807,8 +579,8 @@ export const partition: { * // [ ["0 is even", "2 is even"], [1, 3] ] * ``` * - * @since 3.0.0 - * @category Collecting + * @category collecting + * @since 2.0.0 */ ( f: (a: A, i: number) => Effect, @@ -818,15 +590,16 @@ export const partition: { * Applies an effectful function to each element and partitions failures and * successes. * - * The returned tuple is `[excluded, satisfying]`, where: + * **Details** * - * - `excluded` contains all failures. - * - `satisfying` contains all successes. + * The returned tuple is `[excluded, satisfying]`, where `excluded` contains + * all failures and `satisfying` contains all successes. * * This function runs every effect and never fails. Use `concurrency` to control * parallelism. * - * @example + * **Example** (Separating successes and failures) + * * ```ts * import { Effect } from "effect" * @@ -838,8 +611,8 @@ export const partition: { * // [ ["0 is even", "2 is even"], [1, 3] ] * ``` * - * @since 3.0.0 - * @category Collecting + * @category collecting + * @since 2.0.0 */ ( elements: Iterable, @@ -851,6 +624,8 @@ export const partition: { /** * Applies an effectful function to each element and accumulates all failures. * + * **Details** + * * This function always evaluates every element. If at least one effect fails, * all failures are returned as a non-empty array and successes are discarded. * If all effects succeed, it returns all collected successes. @@ -858,7 +633,8 @@ export const partition: { * Use `discard: true` to ignore successful values while still validating all * elements. * - * @example + * **Example** (Validating every element) + * * ```ts * import { Effect } from "effect" * @@ -880,13 +656,15 @@ export const partition: { * // } * ``` * - * @since 4.0.0 - * @category Error Accumulation + * @category error accumulation + * @since 2.0.0 */ export const validate: { /** * Applies an effectful function to each element and accumulates all failures. * + * **Details** + * * This function always evaluates every element. If at least one effect fails, * all failures are returned as a non-empty array and successes are discarded. * If all effects succeed, it returns all collected successes. @@ -894,7 +672,8 @@ export const validate: { * Use `discard: true` to ignore successful values while still validating all * elements. * - * @example + * **Example** (Validating every element) + * * ```ts * import { Effect } from "effect" * @@ -916,8 +695,8 @@ export const validate: { * // } * ``` * - * @since 4.0.0 - * @category Error Accumulation + * @category error accumulation + * @since 2.0.0 */ ( f: (a: A, i: number) => Effect, @@ -929,6 +708,8 @@ export const validate: { /** * Applies an effectful function to each element and accumulates all failures. * + * **Details** + * * This function always evaluates every element. If at least one effect fails, * all failures are returned as a non-empty array and successes are discarded. * If all effects succeed, it returns all collected successes. @@ -936,7 +717,8 @@ export const validate: { * Use `discard: true` to ignore successful values while still validating all * elements. * - * @example + * **Example** (Validating every element) + * * ```ts * import { Effect } from "effect" * @@ -958,8 +740,8 @@ export const validate: { * // } * ``` * - * @since 4.0.0 - * @category Error Accumulation + * @category error accumulation + * @since 2.0.0 */ ( f: (a: A, i: number) => Effect, @@ -971,6 +753,8 @@ export const validate: { /** * Applies an effectful function to each element and accumulates all failures. * + * **Details** + * * This function always evaluates every element. If at least one effect fails, * all failures are returned as a non-empty array and successes are discarded. * If all effects succeed, it returns all collected successes. @@ -978,7 +762,8 @@ export const validate: { * Use `discard: true` to ignore successful values while still validating all * elements. * - * @example + * **Example** (Validating every element) + * * ```ts * import { Effect } from "effect" * @@ -1000,8 +785,8 @@ export const validate: { * // } * ``` * - * @since 4.0.0 - * @category Error Accumulation + * @category error accumulation + * @since 2.0.0 */ ( elements: Iterable, @@ -1014,6 +799,8 @@ export const validate: { /** * Applies an effectful function to each element and accumulates all failures. * + * **Details** + * * This function always evaluates every element. If at least one effect fails, * all failures are returned as a non-empty array and successes are discarded. * If all effects succeed, it returns all collected successes. @@ -1021,7 +808,8 @@ export const validate: { * Use `discard: true` to ignore successful values while still validating all * elements. * - * @example + * **Example** (Validating every element) + * * ```ts * import { Effect } from "effect" * @@ -1043,8 +831,8 @@ export const validate: { * // } * ``` * - * @since 4.0.0 - * @category Error Accumulation + * @category error accumulation + * @since 2.0.0 */ ( elements: Iterable, @@ -1059,10 +847,13 @@ export const validate: { /** * Returns the first element that satisfies an effectful predicate. * + * **Details** + * * The predicate receives the element and its index. Evaluation short-circuits * as soon as an element matches. * - * @example + * **Example** (Finding the first successful match) + * * ```ts * import { Effect } from "effect" * @@ -1072,17 +863,20 @@ export const validate: { * // { _id: 'Option', _tag: 'Some', value: 3 } * ``` * + * @category collecting * @since 2.0.0 - * @category Collecting */ export const findFirst: { /** * Returns the first element that satisfies an effectful predicate. * + * **Details** + * * The predicate receives the element and its index. Evaluation short-circuits * as soon as an element matches. * - * @example + * **Example** (Finding the first successful match) + * * ```ts * import { Effect } from "effect" * @@ -1092,17 +886,20 @@ export const findFirst: { * // { _id: 'Option', _tag: 'Some', value: 3 } * ``` * + * @category collecting * @since 2.0.0 - * @category Collecting */ (predicate: (a: NoInfer, i: number) => Effect): (elements: Iterable) => Effect, E, R> /** * Returns the first element that satisfies an effectful predicate. * + * **Details** + * * The predicate receives the element and its index. Evaluation short-circuits * as soon as an element matches. * - * @example + * **Example** (Finding the first successful match) + * * ```ts * import { Effect } from "effect" * @@ -1112,8 +909,8 @@ export const findFirst: { * // { _id: 'Option', _tag: 'Some', value: 3 } * ``` * + * @category collecting * @since 2.0.0 - * @category Collecting */ ( elements: Iterable, @@ -1124,21 +921,39 @@ export const findFirst: { /** * Returns the first value that passes an effectful `FilterEffect`. * + * **When to use** + * + * Use when you need to find the first element that satisfies an effectful + * filter returning a `Result`, which also transforms the matching element. + * + * **Details** + * * The filter receives the element and index. Evaluation short-circuits on the * first `Result.succeed` and returns the transformed value in `Option.some`. * + * @see {@link findFirst} for the simpler effectful predicate-based variant + * + * @category collecting * @since 4.0.0 - * @category Collecting */ export const findFirstFilter: { /** * Returns the first value that passes an effectful `FilterEffect`. * + * **When to use** + * + * Use when you need to find the first element that satisfies an effectful + * filter returning a `Result`, which also transforms the matching element. + * + * **Details** + * * The filter receives the element and index. Evaluation short-circuits on the * first `Result.succeed` and returns the transformed value in `Option.some`. * + * @see {@link findFirst} for the simpler effectful predicate-based variant + * + * @category collecting * @since 4.0.0 - * @category Collecting */ ( filter: (input: NoInfer, i: number) => Effect, E, R> @@ -1146,11 +961,20 @@ export const findFirstFilter: { /** * Returns the first value that passes an effectful `FilterEffect`. * + * **When to use** + * + * Use when you need to find the first element that satisfies an effectful + * filter returning a `Result`, which also transforms the matching element. + * + * **Details** + * * The filter receives the element and index. Evaluation short-circuits on the * first `Result.succeed` and returns the transformed value in `Option.some`. * + * @see {@link findFirst} for the simpler effectful predicate-based variant + * + * @category collecting * @since 4.0.0 - * @category Collecting */ ( elements: Iterable, @@ -1161,6 +985,11 @@ export const findFirstFilter: { /** * Executes an effectful operation for each element in an `Iterable`. * + * **When to use** + * + * Use to traverse an iterable with an effectful function while preserving + * element order in the collected results. + * * **Details** * * The `forEach` function applies a provided operation to each element in the @@ -1169,23 +998,20 @@ export const findFirstFilter: { * If any effect fails, the iteration stops immediately (short-circuiting), and * the error is propagated. * - * **Concurrency** + * Concurrency: * * The `concurrency` option controls how many operations are performed * concurrently. By default, the operations are performed sequentially. * - * **Discarding Results** + * Discarding Results: * * If the `discard` option is set to `true`, the intermediate results are not * collected, and the final result of the operation is `void`. * - * @see {@link all} for combining multiple effects into one. + * **Example** (Mapping over an iterable with effects) * - * @example * ```ts - * // Title: Applying Effects to Iterable Elements - * import { Effect } from "effect" - * import { Console } from "effect" + * import { Console, Effect } from "effect" * * const result = Effect.forEach( * [1, 2, 3, 4, 5], @@ -1203,10 +1029,10 @@ export const findFirstFilter: { * // [ 2, 4, 6, 8, 10 ] * ``` * - * @example - * // Title: Using discard to Ignore Results - * import { Effect } from "effect" - * import { Console } from "effect" + * **Example** (Running effects without collecting results) + * + * ```ts + * import { Console, Effect } from "effect" * * // Apply effects but discard the results * const result = Effect.forEach( @@ -1224,14 +1050,21 @@ export const findFirstFilter: { * // Currently at index 3 * // Currently at index 4 * // undefined + * ``` * + * @see {@link all} for combining multiple effects into one. + * @category collecting * @since 2.0.0 - * @category Collecting */ export const forEach: { /** * Executes an effectful operation for each element in an `Iterable`. * + * **When to use** + * + * Use to traverse an iterable with an effectful function while preserving + * element order in the collected results. + * * **Details** * * The `forEach` function applies a provided operation to each element in the @@ -1240,23 +1073,20 @@ export const forEach: { * If any effect fails, the iteration stops immediately (short-circuiting), and * the error is propagated. * - * **Concurrency** + * Concurrency: * * The `concurrency` option controls how many operations are performed * concurrently. By default, the operations are performed sequentially. * - * **Discarding Results** + * Discarding Results: * * If the `discard` option is set to `true`, the intermediate results are not * collected, and the final result of the operation is `void`. * - * @see {@link all} for combining multiple effects into one. + * **Example** (Mapping over an iterable with effects) * - * @example * ```ts - * // Title: Applying Effects to Iterable Elements - * import { Effect } from "effect" - * import { Console } from "effect" + * import { Console, Effect } from "effect" * * const result = Effect.forEach( * [1, 2, 3, 4, 5], @@ -1274,10 +1104,10 @@ export const forEach: { * // [ 2, 4, 6, 8, 10 ] * ``` * - * @example - * // Title: Using discard to Ignore Results - * import { Effect } from "effect" - * import { Console } from "effect" + * **Example** (Running effects without collecting results) + * + * ```ts + * import { Console, Effect } from "effect" * * // Apply effects but discard the results * const result = Effect.forEach( @@ -1295,9 +1125,11 @@ export const forEach: { * // Currently at index 3 * // Currently at index 4 * // undefined + * ``` * + * @see {@link all} for combining multiple effects into one. + * @category collecting * @since 2.0.0 - * @category Collecting */ , const Discard extends boolean = false>( f: (a: Arr.ReadonlyArray.Infer, i: number) => Effect, @@ -1306,6 +1138,11 @@ export const forEach: { /** * Executes an effectful operation for each element in an `Iterable`. * + * **When to use** + * + * Use to traverse an iterable with an effectful function while preserving + * element order in the collected results. + * * **Details** * * The `forEach` function applies a provided operation to each element in the @@ -1314,23 +1151,20 @@ export const forEach: { * If any effect fails, the iteration stops immediately (short-circuiting), and * the error is propagated. * - * **Concurrency** + * Concurrency: * * The `concurrency` option controls how many operations are performed * concurrently. By default, the operations are performed sequentially. * - * **Discarding Results** + * Discarding Results: * * If the `discard` option is set to `true`, the intermediate results are not * collected, and the final result of the operation is `void`. * - * @see {@link all} for combining multiple effects into one. + * **Example** (Mapping over an iterable with effects) * - * @example * ```ts - * // Title: Applying Effects to Iterable Elements - * import { Effect } from "effect" - * import { Console } from "effect" + * import { Console, Effect } from "effect" * * const result = Effect.forEach( * [1, 2, 3, 4, 5], @@ -1348,10 +1182,10 @@ export const forEach: { * // [ 2, 4, 6, 8, 10 ] * ``` * - * @example - * // Title: Using discard to Ignore Results - * import { Effect } from "effect" - * import { Console } from "effect" + * **Example** (Running effects without collecting results) + * + * ```ts + * import { Console, Effect } from "effect" * * // Apply effects but discard the results * const result = Effect.forEach( @@ -1369,9 +1203,11 @@ export const forEach: { * // Currently at index 3 * // Currently at index 4 * // undefined + * ``` * + * @see {@link all} for combining multiple effects into one. + * @category collecting * @since 2.0.0 - * @category Collecting */ , const Discard extends boolean = false>( self: S, @@ -1383,7 +1219,8 @@ export const forEach: { /** * Executes a body effect repeatedly while a condition holds true. * - * @example + * **Example** (Repeating an effectful loop) + * * ```ts * import { Effect } from "effect" * @@ -1404,8 +1241,8 @@ export const forEach: { * // Current count: 5 * ``` * + * @category collecting * @since 2.0.0 - * @category Collecting */ export const whileLoop: (options: { readonly while: LazyArg @@ -1421,30 +1258,27 @@ export const whileLoop: (options: { * Creates an `Effect` that represents an asynchronous computation guaranteed to * succeed. * - * **When to Use** + * **When to use** * - * Use `promise` when you are sure the operation will not reject. + * Use to convert a `Promise` into an `Effect` when the async operation is + * guaranteed to succeed and will not reject. * * **Details** * - * The provided function (`thunk`) returns a `Promise` that should never reject; if it does, the error - * will be treated as a "defect". + * An optional `AbortSignal` can be provided to allow for interruption of the + * wrapped `Promise` API. * - * This defect is not a standard error but indicates a flaw in the logic that - * was expected to be error-free. You can think of it similar to an unexpected - * crash in the program, which can be further managed or logged using tools like - * {@link catchAllDefect}. + * **Gotchas** * - * **Interruptions** + * The `Promise` must not reject. If it rejects, the rejection is treated as a + * defect, not as a typed failure. Use `tryPromise` when rejection is expected. * - * An optional `AbortSignal` can be provided to allow for interruption of the - * wrapped `Promise` API. + * Interruption aborts the provided `AbortSignal`, but the underlying + * asynchronous operation only stops if it observes that signal. * - * @see {@link tryPromise} for a version that can handle failures. + * **Example** (Wrapping a non-rejecting Promise) * - * @example * ```ts - * // Title: Delayed Message * import { Effect } from "effect" * * const delay = (message: string) => @@ -1462,8 +1296,9 @@ export const whileLoop: (options: { * const program = delay("Async operation completed successfully!") * ``` * + * @see {@link tryPromise} for a version that can handle failures. + * @category constructors * @since 2.0.0 - * @category Creating Effects */ export const promise: ( evaluate: (signal: AbortSignal) => PromiseLike @@ -1473,15 +1308,15 @@ export const promise: ( * Creates an `Effect` that represents an asynchronous computation that might * fail. * - * **When to Use** + * **When to use** + * + * Use when you need to perform asynchronous operations that might fail, such + * as fetching data from an API, and want thrown exceptions or rejected promises + * captured as Effect errors. * - * In situations where you need to perform asynchronous operations that might - * fail, such as fetching data from an API, you can use the `tryPromise` - * constructor. This constructor is designed to handle operations that could - * throw exceptions by capturing those exceptions and transforming them into - * manageable errors. + * **Details** * - * **Error Handling** + * Error Handling: * * There are two ways to handle errors with `tryPromise`: * @@ -1490,12 +1325,13 @@ export const promise: ( * 2. If you provide a `catch` function, the error is caught and the `catch` * function maps it to an error of type `E`. * - * **Interruptions** + * Interruptions: * * An optional `AbortSignal` can be provided to allow for interruption of the * wrapped `Promise` API. * - * @example Fetching a TODO Item + * **Example** (Wrapping a fetch request that may fail) + * * ```ts * import { Effect } from "effect" * @@ -1510,7 +1346,8 @@ export const promise: ( * const program = getTodo(1) * ``` * - * @example Custom Error Handling + * **Example** (Mapping Promise rejections to a tagged error) + * * ```ts * import { Data, Effect } from "effect" * @@ -1529,9 +1366,8 @@ export const promise: ( * ``` * * @see {@link promise} if the effectful computation is asynchronous and does not throw errors. - * + * @category constructors * @since 2.0.0 - * @category Creating Effects */ export const tryPromise: ( options: @@ -1542,16 +1378,14 @@ export const tryPromise: ( /** * Creates an `Effect` that always succeeds with a given value. * - * **When to Use** + * **When to use** * - * Use this function when you need an effect that completes successfully with a - * specific value without any errors or external dependencies. + * Use when an effect should complete successfully with a specific value without any errors + * or external dependencies. * - * @see {@link fail} to create an effect that represents a failure. + * **Example** (Creating a successful effect) * - * @example * ```ts - * // Title: Creating a Successful Effect * import { Effect } from "effect" * * // Creating an effect that represents a successful scenario @@ -1561,15 +1395,17 @@ export const tryPromise: ( * const success = Effect.succeed(42) * ``` * + * @see {@link fail} to create an effect that represents a failure. + * @category constructors * @since 2.0.0 - * @category Creating Effects */ export const succeed: (value: A) => Effect = internal.succeed /** * Returns an effect which succeeds with `None`. * - * @example + * **Example** (Succeeding with Option.none) + * * ```ts * import { Effect } from "effect" * @@ -1579,15 +1415,16 @@ export const succeed: (value: A) => Effect = internal.succeed * // Output: { _id: 'Option', _tag: 'None' } * ``` * + * @category constructors * @since 2.0.0 - * @category Creating Effects */ export const succeedNone: Effect> = internal.succeedNone /** * Returns an effect which succeeds with the value wrapped in a `Some`. * - * @example + * **Example** (Succeeding with Option.some) + * * ```ts * import { Effect } from "effect" * @@ -1597,28 +1434,30 @@ export const succeedNone: Effect> = internal.succeedNone * // Output: { _id: 'Option', _tag: 'Some', value: 42 } * ``` * + * @category constructors * @since 2.0.0 - * @category Creating Effects */ export const succeedSome: (value: A) => Effect> = internal.succeedSome /** - * Delays the creation of an `Effect` until it is actually needed. + * Creates an `Effect` lazily, delaying construction until it is needed. * - * **When to Use** + * **When to use** * - * Use `suspend` when you need to defer the evaluation of an effect until it is required. This is particularly useful for optimizing expensive computations, managing circular dependencies, or resolving type inference issues. + * Use when you need to defer the evaluation of an effect until it is required. * * **Details** * - * `suspend` takes a thunk that represents the effect and wraps it in a suspended effect. This means the effect will not be created until it is explicitly needed, which is helpful in various scenarios: - * - **Lazy Evaluation**: Helps optimize performance by deferring computations, especially when the effect might not be needed, or when its computation is expensive. This also ensures that any side effects or scoped captures are re-executed on each invocation. - * - **Handling Circular Dependencies**: Useful in managing circular dependencies, such as recursive functions that need to avoid eager evaluation to prevent stack overflow. - * - **Unifying Return Types**: Can help TypeScript unify return types in situations where multiple branches of logic return different effects, simplifying type inference. + * `suspend` takes a thunk that represents an effect and delays creating it + * until the suspended effect is evaluated. This is useful for optimizing + * expensive computations, managing circular dependencies such as recursive + * functions, and helping TypeScript unify return types when branches construct + * different effects. Any side effects or scoped captures inside the thunk are + * re-executed on each invocation. + * + * **Example** (Lazily evaluating side effects) * - * @example * ```ts - * // Title: Lazy Evaluation with Side Effects * import { Effect } from "effect" * * let i = 0 @@ -1634,8 +1473,9 @@ export const succeedSome: (value: A) => Effect> = internal.succeedS * console.log(Effect.runSync(good)) // Output: 2 * ``` * - * @example - * // Title: Recursive Fibonacci + * **Example** (Suspending recursive Fibonacci evaluation) + * + * ```ts * import { Effect } from "effect" * * const blowsUp = (n: number): Effect.Effect => @@ -1657,9 +1497,11 @@ export const succeedSome: (value: A) => Effect> = internal.succeedS * * console.log(Effect.runSync(allGood(32))) * // Output: 3524578 + * ``` * - * @example - * // Title: Using Effect.suspend to Help TypeScript Infer Types + * **Example** (Helping TypeScript infer recursive effect types) + * + * ```ts * import { Effect } from "effect" * * // Without suspend, TypeScript may struggle with type inference. @@ -1680,9 +1522,10 @@ export const succeedSome: (value: A) => Effect> = internal.succeedS * ? Effect.fail(new Error("Cannot divide by zero")) * : Effect.succeed(a / b) * ) + * ``` * + * @category constructors * @since 2.0.0 - * @category Creating Effects */ export const suspend: ( effect: LazyArg> @@ -1691,25 +1534,23 @@ export const suspend: ( /** * Creates an `Effect` that represents a synchronous side-effectful computation. * - * **When to Use** + * **When to use** * - * Use `sync` when you are sure the operation will not fail. + * Use when you need to wrap a synchronous side-effectful operation that is not + * expected to throw. * * **Details** * - * The provided function (`thunk`) must not throw errors; if it does, the error - * will be treated as a "defect". + * The provided function is evaluated lazily when the effect runs. * - * This defect is not a standard error but indicates a flaw in the logic that - * was expected to be error-free. You can think of it similar to an unexpected - * crash in the program, which can be further managed or logged using tools like - * {@link catchAllDefect}. + * **Gotchas** * - * @see {@link try_ | try} for a version that can handle failures. + * The function must not throw. If it throws, the thrown value is treated as a + * defect, not as a typed failure. Use `try` when throwing is expected. + * + * **Example** (Capturing synchronous logging in an Effect) * - * @example * ```ts - * // Title: Logging a Message * import { Effect } from "effect" * * const log = (message: string) => @@ -1722,16 +1563,19 @@ export const suspend: ( * const program = log("Hello, World!") * ``` * + * @see {@link try_ | try} for a version that can handle failures. + * @category constructors * @since 2.0.0 - * @category Creating Effects */ export const sync: (thunk: LazyArg) => Effect = internal.sync const void_: Effect = internal.void export { /** + * Returns an effect that succeeds with `void`. + * + * @category constructors * @since 2.0.0 - * @category Creating Effects */ void_ as void } @@ -1739,42 +1583,31 @@ export { const undefined_: Effect = internal.undefined export { /** + * Returns an effect that succeeds with `undefined`. + * + * @category constructors * @since 4.0.0 - * @category Creating Effects */ undefined_ as undefined } /** - * Creates an `Effect` from a callback-based asynchronous function. - * - * **Details** + * Creates an `Effect` from a callback-based asynchronous API. * - * The `resume` function: - * - Must be called exactly once. Any additional calls will be ignored. - * - Can return an optional `Effect` that will be run if the `Fiber` executing - * this `Effect` is interrupted. This can be useful in scenarios where you - * need to handle resource cleanup if the operation is interrupted. - * - Can receive an `AbortSignal` to handle interruption if needed. + * **When to use** * - * The `FiberId` of the fiber that may complete the async callback may also be - * specified using the `blockingOn` argument. This is called the "blocking - * fiber" because it suspends the fiber executing the `async` effect (i.e. - * semantically blocks the fiber from making progress). Specifying this fiber id - * in cases where it is known will improve diagnostics, but not affect the - * behavior of the returned effect. + * Use when you need to integrate APIs that complete through callbacks instead + * of returning a `Promise`. * - * **When to Use** - * - * Use `Effect.callback` when dealing with APIs that use callback-style instead of - * `async/await` or `Promise`. - * * **Previously Known As** + * **Details** * - * This API replaces the following from Effect 3.x: + * The registration function receives a `resume` callback and, when requested, + * an `AbortSignal`. Call `resume` at most once with the effect that should + * complete the fiber; later calls are ignored. Return an optional cleanup + * effect from the registration function to run if the fiber is interrupted. * - * - `Effect.async` + * **Example** (Integrating callback APIs) * - * @example * ```ts * import { Effect } from "effect" * @@ -1790,8 +1623,8 @@ export { * const program = delay(1000) * ``` * - * @since 2.0.0 - * @category Creating Effects + * @category constructors + * @since 4.0.0 */ export const callback: ( register: ( @@ -1805,7 +1638,8 @@ export const callback: ( * Returns an effect that will never produce anything. The moral equivalent of * `while(true) {}`, only without the wasted CPU cycles. * - * @example + * **Example** (Creating a never-ending effect) + * * ```ts * import { Effect } from "effect" * @@ -1819,19 +1653,19 @@ export const callback: ( * const timedProgram = Effect.timeout(program, "1 second") * ``` * + * @category constructors * @since 2.0.0 - * @category Creating Effects */ export const never: Effect = internal.never /** - * An `Effect` containing an empty record `{}`, used as the starting point for - * do notation chains. + * Effect that succeeds with an empty record `{}`, used as the starting point + * for do notation chains. + * + * **Example** (Starting do notation) * - * @example * ```ts - * import { Effect } from "effect" - * import { pipe } from "effect/Function" + * import { Effect, pipe } from "effect" * * const program = pipe( * Effect.Do, @@ -1841,8 +1675,8 @@ export const never: Effect = internal.never * ) * ``` * - * @since 4.0.0 - * @category Do notation + * @category do notation + * @since 2.0.0 */ export const Do: Effect<{}> = internal.Do @@ -1850,24 +1684,48 @@ export const Do: Effect<{}> = internal.Do * Gives a name to the success value of an `Effect`, creating a single-key * record used in do notation pipelines. * - * @since 4.0.0 - * @category Do notation + * **When to use** + * + * Use to start a do-notation pipeline from an existing `Effect` when its + * success value should become the first named field in the accumulated record. + * + * @see {@link Do} for starting from an empty accumulated record + * @see {@link bind} for adding fields produced by effects + * + * @category do notation + * @since 2.0.0 */ export const bindTo: { /** * Gives a name to the success value of an `Effect`, creating a single-key * record used in do notation pipelines. * - * @since 4.0.0 - * @category Do notation + * **When to use** + * + * Use to start a do-notation pipeline from an existing `Effect` when its + * success value should become the first named field in the accumulated record. + * + * @see {@link Do} for starting from an empty accumulated record + * @see {@link bind} for adding fields produced by effects + * + * @category do notation + * @since 2.0.0 */ (name: N): (self: Effect) => Effect<{ [K in N]: A }, E, R> /** * Gives a name to the success value of an `Effect`, creating a single-key * record used in do notation pipelines. * - * @since 4.0.0 - * @category Do notation + * **When to use** + * + * Use to start a do-notation pipeline from an existing `Effect` when its + * success value should become the first named field in the accumulated record. + * + * @see {@link Do} for starting from an empty accumulated record + * @see {@link bind} for adding fields produced by effects + * + * @category do notation + * @since 2.0.0 */ (self: Effect, name: N): Effect<{ [K in N]: A }, E, R> } = internal.bindTo @@ -1890,8 +1748,24 @@ export { /** * Adds a computed plain value to the do notation record. * - * @since 4.0.0 - * @category Do notation + * **When to use** + * + * Use to add a derived, synchronous value to a do-notation pipeline when it + * depends on fields already accumulated in the record and does not need to run + * another `Effect`. + * + * **Details** + * + * The new field is added with object spreading. If the name already exists in + * the record, the computed value replaces it in the returned type. + * + * @see {@link bind} for adding fields produced by effects + * @see {@link bindTo} for naming an existing success value + * @see {@link Do} for starting from an empty accumulated record + * @see {@link gen} for sequencing without accumulating a record + * + * @category do notation + * @since 2.0.0 */ let_ as let } @@ -1899,15 +1773,57 @@ export { /** * Adds an `Effect` value to the do notation record under a given name. * - * @since 4.0.0 - * @category Do notation + * **When to use** + * + * Use to sequence an effectful step in a do-notation pipeline when that step + * depends on fields already accumulated in the record and its success value + * should be stored under a name. + * + * **Details** + * + * The function receives the current record, runs the returned effect after the + * input effect succeeds, and inserts its success value under `name`. The + * resulting effect combines the error and service requirements of both steps. + * + * **Gotchas** + * + * Binding a name that already exists replaces that field in the resulting + * record. + * + * @see {@link Do} for starting from an empty do-notation record + * @see {@link bindTo} for naming the success value of an existing effect + * @see {@link gen} for generator-based sequencing without accumulating a record + * + * @category do notation + * @since 2.0.0 */ export const bind: { /** * Adds an `Effect` value to the do notation record under a given name. * - * @since 4.0.0 - * @category Do notation + * **When to use** + * + * Use to sequence an effectful step in a do-notation pipeline when that step + * depends on fields already accumulated in the record and its success value + * should be stored under a name. + * + * **Details** + * + * The function receives the current record, runs the returned effect after the + * input effect succeeds, and inserts its success value under `name`. The + * resulting effect combines the error and service requirements of both steps. + * + * **Gotchas** + * + * Binding a name that already exists replaces that field in the resulting + * record. + * + * @see {@link Do} for starting from an empty do-notation record + * @see {@link bindTo} for naming the success value of an existing effect + * @see {@link gen} for generator-based sequencing without accumulating a record + * + * @category do notation + * @since 2.0.0 */ , B, E2, R2>(name: N, f: (a: NoInfer) => Effect): ( self: Effect @@ -1915,8 +1831,29 @@ export const bind: { /** * Adds an `Effect` value to the do notation record under a given name. * - * @since 4.0.0 - * @category Do notation + * **When to use** + * + * Use to sequence an effectful step in a do-notation pipeline when that step + * depends on fields already accumulated in the record and its success value + * should be stored under a name. + * + * **Details** + * + * The function receives the current record, runs the returned effect after the + * input effect succeeds, and inserts its success value under `name`. The + * resulting effect combines the error and service requirements of both steps. + * + * **Gotchas** + * + * Binding a name that already exists replaces that field in the resulting + * record. + * + * @see {@link Do} for starting from an empty do-notation record + * @see {@link bindTo} for naming the success value of an existing effect + * @see {@link gen} for generator-based sequencing without accumulating a record + * + * @category do notation + * @since 2.0.0 */ , E, R, B, E2, R2, N extends string>(self: Effect, name: N, f: (a: NoInfer) => Effect): Effect & Record>, E | E2, R | R2> } = internal.bind @@ -1925,18 +1862,18 @@ export const bind: { * Provides a way to write effectful code using generator functions, simplifying * control flow and error handling. * - * **When to Use** + * **When to use** * - * `gen` allows you to write code that looks and behaves like synchronous - * code, but it can handle asynchronous tasks, errors, and complex control flow - * (like loops and conditions). It helps make asynchronous code more readable - * and easier to manage. + * Use when you want to write effectful code that looks and behaves like + * synchronous code, while still handling asynchronous tasks, errors, and complex + * control flow such as loops and conditions. * - * The generator functions work similarly to `async/await` but with more - * explicit control over the execution of effects. You can `yield*` values from - * effects and return the final result at the end. + * Generator functions work similarly to `async/await` but keep errors, + * requirements, and interruption in the Effect type. You can `yield*` values + * from effects and return the final result at the end. + * + * **Example** (Sequencing effects with generators) * - * @example * ```ts * import { Data, Effect } from "effect" * @@ -1968,26 +1905,26 @@ export const bind: { * }) * ``` * + * @category constructors * @since 2.0.0 - * @category Creating Effects */ export const gen: { /** * Provides a way to write effectful code using generator functions, simplifying * control flow and error handling. * - * **When to Use** + * **When to use** + * + * Use when you want to write effectful code that looks and behaves like + * synchronous code, while still handling asynchronous tasks, errors, and complex + * control flow such as loops and conditions. * - * `gen` allows you to write code that looks and behaves like synchronous - * code, but it can handle asynchronous tasks, errors, and complex control flow - * (like loops and conditions). It helps make asynchronous code more readable - * and easier to manage. + * Generator functions work similarly to `async/await` but keep errors, + * requirements, and interruption in the Effect type. You can `yield*` values + * from effects and return the final result at the end. * - * The generator functions work similarly to `async/await` but with more - * explicit control over the execution of effects. You can `yield*` values from - * effects and return the final result at the end. + * **Example** (Sequencing effects with generators) * - * @example * ```ts * import { Data, Effect } from "effect" * @@ -2019,34 +1956,34 @@ export const gen: { * }) * ``` * + * @category constructors * @since 2.0.0 - * @category Creating Effects */ - , AEff>(f: () => Generator): Effect< + , AEff>(f: () => Generator): Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never > /** * Provides a way to write effectful code using generator functions, simplifying * control flow and error handling. * - * **When to Use** + * **When to use** * - * `gen` allows you to write code that looks and behaves like synchronous - * code, but it can handle asynchronous tasks, errors, and complex control flow - * (like loops and conditions). It helps make asynchronous code more readable - * and easier to manage. + * Use when you want to write effectful code that looks and behaves like + * synchronous code, while still handling asynchronous tasks, errors, and complex + * control flow such as loops and conditions. * - * The generator functions work similarly to `async/await` but with more - * explicit control over the execution of effects. You can `yield*` values from - * effects and return the final result at the end. + * Generator functions work similarly to `async/await` but keep errors, + * requirements, and interruption in the Effect type. You can `yield*` values + * from effects and return the final result at the end. + * + * **Example** (Sequencing effects with generators) * - * @example * ```ts * import { Data, Effect } from "effect" * @@ -2078,10 +2015,10 @@ export const gen: { * }) * ``` * + * @category constructors * @since 2.0.0 - * @category Creating Effects */ - , AEff>( + , AEff>( options: { readonly self: Self }, @@ -2089,10 +2026,10 @@ export const gen: { ): Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never > } = internal.gen @@ -2100,29 +2037,33 @@ export const gen: { /** * Type helpers for `Effect.gen` generator return signatures. * - * @since 4.0.0 + * @since 2.0.0 */ -export namespace gen { +export declare namespace gen { /** + * Generator return type accepted by `Effect.gen`. + * + * @category constructors * @since 4.0.0 */ - export type Return = Generator, A, any> + export type Return = Generator, A, any> } /** * Creates an `Effect` that represents a recoverable error. * - * **When to Use** + * **When to use** * - * Use this function to explicitly signal an error in an `Effect`. The error - * will keep propagating unless it is handled. You can handle the error with - * functions like {@link catchAll} or {@link catchTag}. + * Use to explicitly signal a recoverable error in an `Effect`. * - * @see {@link succeed} to create an effect that represents a successful value. + * **Details** + * + * The error keeps propagating unless it is handled. You can handle tagged + * errors with functions like {@link catchTag} or {@link catchTags}. + * + * **Example** (Creating a failed effect) * - * @example * ```ts - * // Title: Creating a Failed Effect * import { Data, Effect } from "effect" * * class OperationFailedError extends Data.TaggedError("OperationFailedError")<{}> {} @@ -2134,18 +2075,25 @@ export namespace gen { * ) * ``` * + * @see {@link succeed} to create an effect that represents a successful value. + * @category constructors * @since 2.0.0 - * @category Creating Effects */ export const fail: (error: E) => Effect = internal.fail /** * Creates an `Effect` that represents a recoverable error using a lazy evaluation. * - * This function is useful when you need to create an error effect but want to - * defer the computation of the error value until the effect is actually run. + * **When to use** + * + * Use to defer computing a recoverable error value until the effect is run. + * + * **Details** + * + * The error-producing function is evaluated each time the effect is executed. + * + * **Example** (Lazily creating failures) * - * @example * ```ts * import { Data, Effect } from "effect" * @@ -2157,18 +2105,27 @@ export const fail: (error: E) => Effect = internal.fail * // Output: { _id: 'Exit', _tag: 'Failure', cause: ... } * ``` * + * @category constructors * @since 2.0.0 - * @category Creating Effects */ export const failSync: (evaluate: LazyArg) => Effect = internal.failSync /** * Creates an `Effect` that represents a failure with a specific `Cause`. * + * **When to use** + * + * Use when you already have a full `Cause` and need to preserve defects, + * interruptions, annotations, or combined failures in the effect's failure + * channel. + * + * **Details** + * * This function allows you to create effects that fail with complex error * structures, including multiple errors, defects, interruptions, and more. * - * @example + * **Example** (Failing with a full Cause) + * * ```ts * import { Cause, Effect } from "effect" * @@ -2180,18 +2137,24 @@ export const failSync: (evaluate: LazyArg) => Effect = internal. * // Output: { _id: 'Exit', _tag: 'Failure', cause: ... } * ``` * + * @category constructors * @since 2.0.0 - * @category Creating Effects */ export const failCause: (cause: Cause.Cause) => Effect = internal.failCause /** * Creates an `Effect` that represents a failure with a `Cause` computed lazily. * - * This function is useful when you need to create a failure effect with a - * complex cause but want to defer the computation until the effect is run. + * **When to use** + * + * Use to defer computing a full `Cause` until the effect is run. + * + * **Details** + * + * The cause-producing function is evaluated each time the effect is executed. + * + * **Example** (Lazily creating a Cause) * - * @example * ```ts * import { Cause, Effect } from "effect" * @@ -2203,8 +2166,8 @@ export const failCause: (cause: Cause.Cause) => Effect = interna * // Output: { _id: 'Exit', _tag: 'Failure', cause: ... } * ``` * + * @category constructors * @since 2.0.0 - * @category Creating Effects */ export const failCauseSync: ( evaluate: LazyArg> @@ -2213,10 +2176,10 @@ export const failCauseSync: ( /** * Creates an effect that terminates a fiber with a specified error. * - * **When to Use** + * **When to use** * - * Use `die` when encountering unexpected conditions in your code that should - * not be handled as regular errors but instead represent unrecoverable defects. + * Use when you need an `Effect` to report an unrecoverable defect instead of a + * typed error. * * **Details** * @@ -2227,12 +2190,9 @@ export const failCauseSync: ( * The error channel of the resulting effect is of type `never`, indicating that * it cannot recover from this failure. * - * @see {@link dieSync} for a variant that throws a specified error, evaluated lazily. - * @see {@link dieMessage} for a variant that throws a `RuntimeException` with a message. + * **Example** (Failing when division by zero) * - * @example * ```ts - * // Title: Terminating on Division by Zero with a Specified Error * import { Effect } from "effect" * * const divide = (a: number, b: number) => @@ -2250,8 +2210,8 @@ export const failCauseSync: ( * // ...stack trace... * ``` * + * @category constructors * @since 2.0.0 - * @category Creating Effects */ export const die: (defect: unknown) => Effect = internal.die @@ -2265,14 +2225,14 @@ export { * Creates an `Effect` that represents a synchronous computation that might * fail. * - * **When to Use** + * **When to use** * - * In situations where you need to perform synchronous operations that might - * fail, such as parsing JSON, you can use the `try` constructor. This - * constructor is designed to handle operations that could throw exceptions by - * capturing those exceptions and transforming them into manageable errors. + * Use when you need to perform synchronous operations that might throw, such + * as parsing JSON, and convert thrown exceptions into typed Effect failures. + * + * **Details** * - * **Error Handling** + * Error Handling: * * There are two ways to handle errors with `try`: * @@ -2281,10 +2241,8 @@ export { * 2. If you provide a `catch` function, the error is caught and the `catch` * function maps it to an error of type `E`. * - * @see {@link sync} if the effectful computation is synchronous and does not - * throw errors. + * **Example** (Parsing JSON with typed error mapping) * - * @example Basic Usage with Default Error Handling * ```ts * import { Effect } from "effect" * @@ -2303,7 +2261,8 @@ export { * // Output: Exit.failure with Error * ``` * - * @example Custom Error Handling + * **Example** (Mapping synchronous exceptions to a tagged error) + * * ```ts * import { Data, Effect } from "effect" * @@ -2319,8 +2278,10 @@ export { * // Output: Exit.failure with custom Error message * ``` * + * @see {@link sync} if the effectful computation is synchronous and does not + * throw errors. + * @category constructors * @since 2.0.0 - * @category Creating Effects */ try_ as try } @@ -2328,7 +2289,8 @@ export { /** * Yields control back to the Effect runtime, allowing other fibers to execute. * - * @example + * **Example** (Yielding to other fibers) + * * ```ts * import { Effect } from "effect" * @@ -2341,15 +2303,16 @@ export { * Effect.runPromise(program) * ``` * + * @category constructors * @since 2.0.0 - * @category Creating Effects */ export const yieldNow: Effect = internal.yieldNow /** * Yields control back to the Effect runtime with a specified priority, allowing other fibers to execute. * - * @example + * **Example** (Yielding with priority) + * * ```ts * import { Effect } from "effect" * @@ -2362,15 +2325,16 @@ export const yieldNow: Effect = internal.yieldNow * Effect.runPromise(program) * ``` * - * @since 2.0.0 - * @category Creating Effects + * @category constructors + * @since 4.0.0 */ export const yieldNowWith: (priority?: number) => Effect = internal.yieldNowWith /** * Provides access to the current fiber within an effect computation. * - * @example + * **Example** (Reading the current fiber) + * * ```ts * import { Effect } from "effect" * @@ -2382,8 +2346,8 @@ export const yieldNowWith: (priority?: number) => Effect = internal.yieldN * // Output: Fiber ID: 1 * ``` * - * @since 2.0.0 - * @category Creating Effects + * @category constructors + * @since 4.0.0 */ export const withFiber: ( evaluate: (fiber: Fiber) => Effect @@ -2396,7 +2360,8 @@ export const withFiber: ( /** * Converts a `Result` to an `Effect`. * - * @example + * **Example** (Converting a Result into an Effect) + * * ```ts * import { Effect, Result } from "effect" * @@ -2411,15 +2376,26 @@ export const withFiber: ( * // { _id: 'Exit', _tag: 'Failure', cause: { _id: 'Cause', _tag: 'Fail', failure: 'Something went wrong' } } * ``` * + * @category converting * @since 4.0.0 - * @category Conversions */ export const fromResult: (result: Result.Result) => Effect = internal.fromResult /** - * Converts an `Option` to an `Effect`. + * Converts an `Option` into an `Effect`. + * + * **When to use** + * + * Use when absence should become a typed `NoSuchElementError` in the effect error + * channel. + * + * **Details** + * + * `Option.some` becomes a successful effect with the contained value, while + * `Option.none` becomes a failed effect with `NoSuchElementError`. + * + * **Example** (Converting an Option into an Effect) * - * @example * ```ts * import { Effect, Option } from "effect" * @@ -2434,8 +2410,8 @@ export const fromResult: (result: Result.Result) => Effect = i * // { _id: 'Exit', _tag: 'Failure', cause: { _id: 'Cause', _tag: 'Fail', failure: { _id: 'NoSuchElementError' } } } * ``` * + * @category converting * @since 4.0.0 - * @category Conversions */ export const fromOption: ( option: Option @@ -2445,7 +2421,8 @@ export const fromOption: ( * Converts a nullable value to an `Effect`, failing with a `NoSuchElementError` * when the value is `null` or `undefined`. * - * @example + * **Example** (Failing on nullish values) + * * ```ts * import { Console, Effect } from "effect" * @@ -2462,36 +2439,11 @@ export const fromOption: ( * // Output: hello * ``` * + * @category converting * @since 4.0.0 - * @category Conversions */ export const fromNullishOr: (value: A) => Effect, Cause.NoSuchElementError> = internal.fromNullishOr -/** - * Converts a yieldable value to an Effect. - * - * @example - * ```ts - * import { Effect } from "effect" - * import * as Option from "effect/Option" - * - * // Option is yieldable in Effect - * const program = Effect.gen(function*() { - * const value = yield* Effect.fromYieldable(Option.some(42)) - * return value * 2 - * }) - * - * Effect.runPromise(program).then(console.log) - * // Output: 84 - * ``` - * - * @since 4.0.0 - * @category Conversions - */ -export const fromYieldable: ( - yieldable: Yieldable -) => Effect = internal.fromYieldable - // ----------------------------------------------------------------------------- // Mapping // ----------------------------------------------------------------------------- @@ -2500,15 +2452,11 @@ export const fromYieldable: ( * Chains effects to produce new `Effect` instances, useful for combining * operations that depend on previous results. * - * **Syntax** + * **When to use** * - * ```ts skip-type-checking - * const flatMappedEffect = pipe(myEffect, Effect.flatMap(transformation)) - * // or - * const flatMappedEffect = Effect.flatMap(myEffect, transformation) - * // or - * const flatMappedEffect = myEffect.pipe(Effect.flatMap(transformation)) - * ``` + * Use when you need to chain multiple effects, ensuring that each + * step produces a new `Effect` while flattening any nested effects that may + * occur. * * **Details** * @@ -2520,13 +2468,21 @@ export const fromYieldable: ( * Since effects are immutable, `flatMap` always returns a new effect instead of * changing the original one. * - * **When to Use** + * **Example** (Syntax) * - * Use `flatMap` when you need to chain multiple effects, ensuring that each - * step produces a new `Effect` while flattening any nested effects that may - * occur. + * ```ts + * import { Effect, pipe } from "effect" + * + * const myEffect = Effect.succeed(1) + * const transformation = (n: number) => Effect.succeed(n + 1) + * + * const flatMappedWithPipe = pipe(myEffect, Effect.flatMap(transformation)) + * const flatMappedWithDataFirst = Effect.flatMap(myEffect, transformation) + * const flatMappedWithMethod = myEffect.pipe(Effect.flatMap(transformation)) + * ``` + * + * **Example** (Sequencing dependent effects) * - * @example * ```ts * import { Data, Effect, pipe } from "effect" * @@ -2555,9 +2511,8 @@ export const fromYieldable: ( * ``` * * @see {@link tap} for a version that ignores the result of the effect. - * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const flatMap: { // ----------------------------------------------------------------------------- @@ -2568,15 +2523,11 @@ export const flatMap: { * Chains effects to produce new `Effect` instances, useful for combining * operations that depend on previous results. * - * **Syntax** + * **When to use** * - * ```ts skip-type-checking - * const flatMappedEffect = pipe(myEffect, Effect.flatMap(transformation)) - * // or - * const flatMappedEffect = Effect.flatMap(myEffect, transformation) - * // or - * const flatMappedEffect = myEffect.pipe(Effect.flatMap(transformation)) - * ``` + * Use when you need to chain multiple effects, ensuring that each + * step produces a new `Effect` while flattening any nested effects that may + * occur. * * **Details** * @@ -2588,13 +2539,21 @@ export const flatMap: { * Since effects are immutable, `flatMap` always returns a new effect instead of * changing the original one. * - * **When to Use** + * **Example** (Syntax) * - * Use `flatMap` when you need to chain multiple effects, ensuring that each - * step produces a new `Effect` while flattening any nested effects that may - * occur. + * ```ts + * import { Effect, pipe } from "effect" + * + * const myEffect = Effect.succeed(1) + * const transformation = (n: number) => Effect.succeed(n + 1) + * + * const flatMappedWithPipe = pipe(myEffect, Effect.flatMap(transformation)) + * const flatMappedWithDataFirst = Effect.flatMap(myEffect, transformation) + * const flatMappedWithMethod = myEffect.pipe(Effect.flatMap(transformation)) + * ``` + * + * **Example** (Sequencing dependent effects) * - * @example * ```ts * import { Data, Effect, pipe } from "effect" * @@ -2623,9 +2582,8 @@ export const flatMap: { * ``` * * @see {@link tap} for a version that ignores the result of the effect. - * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (f: (a: A) => Effect): (self: Effect) => Effect // ----------------------------------------------------------------------------- @@ -2636,15 +2594,11 @@ export const flatMap: { * Chains effects to produce new `Effect` instances, useful for combining * operations that depend on previous results. * - * **Syntax** + * **When to use** * - * ```ts skip-type-checking - * const flatMappedEffect = pipe(myEffect, Effect.flatMap(transformation)) - * // or - * const flatMappedEffect = Effect.flatMap(myEffect, transformation) - * // or - * const flatMappedEffect = myEffect.pipe(Effect.flatMap(transformation)) - * ``` + * Use when you need to chain multiple effects, ensuring that each + * step produces a new `Effect` while flattening any nested effects that may + * occur. * * **Details** * @@ -2656,13 +2610,21 @@ export const flatMap: { * Since effects are immutable, `flatMap` always returns a new effect instead of * changing the original one. * - * **When to Use** + * **Example** (Syntax) * - * Use `flatMap` when you need to chain multiple effects, ensuring that each - * step produces a new `Effect` while flattening any nested effects that may - * occur. + * ```ts + * import { Effect, pipe } from "effect" + * + * const myEffect = Effect.succeed(1) + * const transformation = (n: number) => Effect.succeed(n + 1) + * + * const flatMappedWithPipe = pipe(myEffect, Effect.flatMap(transformation)) + * const flatMappedWithDataFirst = Effect.flatMap(myEffect, transformation) + * const flatMappedWithMethod = myEffect.pipe(Effect.flatMap(transformation)) + * ``` + * + * **Example** (Sequencing dependent effects) * - * @example * ```ts * import { Data, Effect, pipe } from "effect" * @@ -2691,9 +2653,8 @@ export const flatMap: { * ``` * * @see {@link tap} for a version that ignores the result of the effect. - * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (self: Effect, f: (a: A) => Effect): Effect } = internal.flatMap @@ -2701,7 +2662,8 @@ export const flatMap: { /** * Flattens an `Effect` that produces another `Effect` into a single effect. * - * @example + * **Example** (Flattening nested effects) + * * ```ts * import { Console, Effect } from "effect" * @@ -2714,53 +2676,46 @@ export const flatMap: { * }) * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const flatten: (self: Effect, E2, R2>) => Effect = internal.flatten /** - * Chains two actions, where the second action can depend on the result of the - * first. - * - * **Syntax** + * Runs this effect and then runs another effect, optionally using the first + * effect's success value to choose the next effect. * - * ```ts skip-type-checking - * const transformedEffect = pipe(myEffect, Effect.andThen(anotherEffect)) - * // or - * const transformedEffect = Effect.andThen(myEffect, anotherEffect) - * // or - * const transformedEffect = myEffect.pipe(Effect.andThen(anotherEffect)) - * ``` - * - * **When to Use** + * **When to use** * - * Use `andThen` when you need to run multiple actions in sequence, with the - * second action depending on the result of the first. This is useful for - * combining effects or handling computations that must happen in order. + * Use when you need one effect to run after another and the second effect may + * depend on the first effect's success value. * * **Details** * - * The second action can be: + * When the second argument is an `Effect`, the first success value is discarded + * and the returned effect produces the second effect's value. When the second + * argument is a function, it receives the first success value and must return + * the next `Effect`. + * + * Failures or requirements from either effect are preserved in the returned + * effect. * - * - A constant value (similar to {@link as}) - * - A function returning a value (similar to {@link map}) - * - A `Promise` - * - A function returning a `Promise` - * - An `Effect` - * - A function returning an `Effect` (similar to {@link flatMap}) + * **Example** (Syntax) * - * **Note:** `andThen` works well with both `Option` and `Result` types, - * treating them as effects. + * ```ts + * import { Effect, pipe } from "effect" * - * **Previously Known As** + * const myEffect = Effect.succeed(1) + * const anotherEffect = Effect.succeed("done") * - * This API replaces the following from Effect 3.x: + * const transformedWithPipe = pipe(myEffect, Effect.andThen(anotherEffect)) + * const transformedWithDataFirst = Effect.andThen(myEffect, anotherEffect) + * const transformedWithMethod = myEffect.pipe(Effect.andThen(anotherEffect)) + * ``` * - * - `Effect.zipRight` + * **Example** (Sequencing a discount calculation after fetching a total) * - * @example Applying a Discount Based on Fetched Amount * ```ts * import { Data, Effect, pipe } from "effect" * @@ -2799,51 +2754,44 @@ export const flatten: (self: Effect, E2, R2>) = * // Output: 190 * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const andThen: { /** - * Chains two actions, where the second action can depend on the result of the - * first. - * - * **Syntax** + * Runs this effect and then runs another effect, optionally using the first + * effect's success value to choose the next effect. * - * ```ts skip-type-checking - * const transformedEffect = pipe(myEffect, Effect.andThen(anotherEffect)) - * // or - * const transformedEffect = Effect.andThen(myEffect, anotherEffect) - * // or - * const transformedEffect = myEffect.pipe(Effect.andThen(anotherEffect)) - * ``` - * - * **When to Use** + * **When to use** * - * Use `andThen` when you need to run multiple actions in sequence, with the - * second action depending on the result of the first. This is useful for - * combining effects or handling computations that must happen in order. + * Use when you need one effect to run after another and the second effect may + * depend on the first effect's success value. * * **Details** * - * The second action can be: + * When the second argument is an `Effect`, the first success value is discarded + * and the returned effect produces the second effect's value. When the second + * argument is a function, it receives the first success value and must return + * the next `Effect`. + * + * Failures or requirements from either effect are preserved in the returned + * effect. * - * - A constant value (similar to {@link as}) - * - A function returning a value (similar to {@link map}) - * - A `Promise` - * - A function returning a `Promise` - * - An `Effect` - * - A function returning an `Effect` (similar to {@link flatMap}) + * **Example** (Syntax) * - * **Note:** `andThen` works well with both `Option` and `Result` types, - * treating them as effects. + * ```ts + * import { Effect, pipe } from "effect" * - * **Previously Known As** + * const myEffect = Effect.succeed(1) + * const anotherEffect = Effect.succeed("done") * - * This API replaces the following from Effect 3.x: + * const transformedWithPipe = pipe(myEffect, Effect.andThen(anotherEffect)) + * const transformedWithDataFirst = Effect.andThen(myEffect, anotherEffect) + * const transformedWithMethod = myEffect.pipe(Effect.andThen(anotherEffect)) + * ``` * - * - `Effect.zipRight` + * **Example** (Sequencing a discount calculation after fetching a total) * - * @example Applying a Discount Based on Fetched Amount * ```ts * import { Data, Effect, pipe } from "effect" * @@ -2882,51 +2830,44 @@ export const andThen: { * // Output: 190 * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (f: (a: A) => Effect): (self: Effect) => Effect /** - * Chains two actions, where the second action can depend on the result of the - * first. - * - * **Syntax** + * Runs this effect and then runs another effect, optionally using the first + * effect's success value to choose the next effect. * - * ```ts skip-type-checking - * const transformedEffect = pipe(myEffect, Effect.andThen(anotherEffect)) - * // or - * const transformedEffect = Effect.andThen(myEffect, anotherEffect) - * // or - * const transformedEffect = myEffect.pipe(Effect.andThen(anotherEffect)) - * ``` - * - * **When to Use** + * **When to use** * - * Use `andThen` when you need to run multiple actions in sequence, with the - * second action depending on the result of the first. This is useful for - * combining effects or handling computations that must happen in order. + * Use when you need one effect to run after another and the second effect may + * depend on the first effect's success value. * * **Details** * - * The second action can be: + * When the second argument is an `Effect`, the first success value is discarded + * and the returned effect produces the second effect's value. When the second + * argument is a function, it receives the first success value and must return + * the next `Effect`. + * + * Failures or requirements from either effect are preserved in the returned + * effect. * - * - A constant value (similar to {@link as}) - * - A function returning a value (similar to {@link map}) - * - A `Promise` - * - A function returning a `Promise` - * - An `Effect` - * - A function returning an `Effect` (similar to {@link flatMap}) + * **Example** (Syntax) * - * **Note:** `andThen` works well with both `Option` and `Result` types, - * treating them as effects. + * ```ts + * import { Effect, pipe } from "effect" * - * **Previously Known As** + * const myEffect = Effect.succeed(1) + * const anotherEffect = Effect.succeed("done") * - * This API replaces the following from Effect 3.x: + * const transformedWithPipe = pipe(myEffect, Effect.andThen(anotherEffect)) + * const transformedWithDataFirst = Effect.andThen(myEffect, anotherEffect) + * const transformedWithMethod = myEffect.pipe(Effect.andThen(anotherEffect)) + * ``` * - * - `Effect.zipRight` + * **Example** (Sequencing a discount calculation after fetching a total) * - * @example Applying a Discount Based on Fetched Amount * ```ts * import { Data, Effect, pipe } from "effect" * @@ -2965,51 +2906,44 @@ export const andThen: { * // Output: 190 * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (f: Effect): (self: Effect) => Effect /** - * Chains two actions, where the second action can depend on the result of the - * first. - * - * **Syntax** + * Runs this effect and then runs another effect, optionally using the first + * effect's success value to choose the next effect. * - * ```ts skip-type-checking - * const transformedEffect = pipe(myEffect, Effect.andThen(anotherEffect)) - * // or - * const transformedEffect = Effect.andThen(myEffect, anotherEffect) - * // or - * const transformedEffect = myEffect.pipe(Effect.andThen(anotherEffect)) - * ``` - * - * **When to Use** + * **When to use** * - * Use `andThen` when you need to run multiple actions in sequence, with the - * second action depending on the result of the first. This is useful for - * combining effects or handling computations that must happen in order. + * Use when you need one effect to run after another and the second effect may + * depend on the first effect's success value. * * **Details** * - * The second action can be: + * When the second argument is an `Effect`, the first success value is discarded + * and the returned effect produces the second effect's value. When the second + * argument is a function, it receives the first success value and must return + * the next `Effect`. + * + * Failures or requirements from either effect are preserved in the returned + * effect. * - * - A constant value (similar to {@link as}) - * - A function returning a value (similar to {@link map}) - * - A `Promise` - * - A function returning a `Promise` - * - An `Effect` - * - A function returning an `Effect` (similar to {@link flatMap}) + * **Example** (Syntax) * - * **Note:** `andThen` works well with both `Option` and `Result` types, - * treating them as effects. + * ```ts + * import { Effect, pipe } from "effect" * - * **Previously Known As** + * const myEffect = Effect.succeed(1) + * const anotherEffect = Effect.succeed("done") * - * This API replaces the following from Effect 3.x: + * const transformedWithPipe = pipe(myEffect, Effect.andThen(anotherEffect)) + * const transformedWithDataFirst = Effect.andThen(myEffect, anotherEffect) + * const transformedWithMethod = myEffect.pipe(Effect.andThen(anotherEffect)) + * ``` * - * - `Effect.zipRight` + * **Example** (Sequencing a discount calculation after fetching a total) * - * @example Applying a Discount Based on Fetched Amount * ```ts * import { Data, Effect, pipe } from "effect" * @@ -3048,51 +2982,44 @@ export const andThen: { * // Output: 190 * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (self: Effect, f: (a: A) => Effect): Effect /** - * Chains two actions, where the second action can depend on the result of the - * first. - * - * **Syntax** + * Runs this effect and then runs another effect, optionally using the first + * effect's success value to choose the next effect. * - * ```ts skip-type-checking - * const transformedEffect = pipe(myEffect, Effect.andThen(anotherEffect)) - * // or - * const transformedEffect = Effect.andThen(myEffect, anotherEffect) - * // or - * const transformedEffect = myEffect.pipe(Effect.andThen(anotherEffect)) - * ``` - * - * **When to Use** + * **When to use** * - * Use `andThen` when you need to run multiple actions in sequence, with the - * second action depending on the result of the first. This is useful for - * combining effects or handling computations that must happen in order. + * Use when you need one effect to run after another and the second effect may + * depend on the first effect's success value. * * **Details** * - * The second action can be: + * When the second argument is an `Effect`, the first success value is discarded + * and the returned effect produces the second effect's value. When the second + * argument is a function, it receives the first success value and must return + * the next `Effect`. + * + * Failures or requirements from either effect are preserved in the returned + * effect. * - * - A constant value (similar to {@link as}) - * - A function returning a value (similar to {@link map}) - * - A `Promise` - * - A function returning a `Promise` - * - An `Effect` - * - A function returning an `Effect` (similar to {@link flatMap}) + * **Example** (Syntax) * - * **Note:** `andThen` works well with both `Option` and `Result` types, - * treating them as effects. + * ```ts + * import { Effect, pipe } from "effect" * - * **Previously Known As** + * const myEffect = Effect.succeed(1) + * const anotherEffect = Effect.succeed("done") * - * This API replaces the following from Effect 3.x: + * const transformedWithPipe = pipe(myEffect, Effect.andThen(anotherEffect)) + * const transformedWithDataFirst = Effect.andThen(myEffect, anotherEffect) + * const transformedWithMethod = myEffect.pipe(Effect.andThen(anotherEffect)) + * ``` * - * - `Effect.zipRight` + * **Example** (Sequencing a discount calculation after fetching a total) * - * @example Applying a Discount Based on Fetched Amount * ```ts * import { Data, Effect, pipe } from "effect" * @@ -3131,8 +3058,8 @@ export const andThen: { * // Output: 190 * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (self: Effect, f: Effect): Effect } = internal.andThen @@ -3141,11 +3068,10 @@ export const andThen: { * Runs a side effect with the result of an effect without changing the original * value. * - * **When to Use** + * **When to use** * - * Use `tap` when you want to perform a side effect, like logging or tracking, - * without modifying the main value. This is useful when you need to observe or - * record an action but want the original value to be passed to the next step. + * Use when you need to run an effectful observation, such as logging or + * tracking, while passing the original success value to the next step. * * **Details** * @@ -3154,17 +3080,10 @@ export const andThen: { * next part of the chain. Note that if the side effect fails, the entire chain * will fail too. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Logging a step in a pipeline) * - * - `Effect.zipLeft` - * - * @example * ```ts - * // Title: Logging a step in a pipeline - * import { Data, Effect, pipe } from "effect" - * import { Console } from "effect" + * import { Console, Data, Effect, pipe } from "effect" * * class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} * @@ -3194,19 +3113,18 @@ export const andThen: { * // 95 * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const tap: { /** * Runs a side effect with the result of an effect without changing the original * value. * - * **When to Use** + * **When to use** * - * Use `tap` when you want to perform a side effect, like logging or tracking, - * without modifying the main value. This is useful when you need to observe or - * record an action but want the original value to be passed to the next step. + * Use when you need to run an effectful observation, such as logging or + * tracking, while passing the original success value to the next step. * * **Details** * @@ -3215,17 +3133,10 @@ export const tap: { * next part of the chain. Note that if the side effect fails, the entire chain * will fail too. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: - * - * - `Effect.zipLeft` + * **Example** (Logging a step in a pipeline) * - * @example * ```ts - * // Title: Logging a step in a pipeline - * import { Data, Effect, pipe } from "effect" - * import { Console } from "effect" + * import { Console, Data, Effect, pipe } from "effect" * * class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} * @@ -3255,19 +3166,18 @@ export const tap: { * // 95 * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (f: (a: NoInfer) => Effect): (self: Effect) => Effect /** * Runs a side effect with the result of an effect without changing the original * value. * - * **When to Use** + * **When to use** * - * Use `tap` when you want to perform a side effect, like logging or tracking, - * without modifying the main value. This is useful when you need to observe or - * record an action but want the original value to be passed to the next step. + * Use when you need to run an effectful observation, such as logging or + * tracking, while passing the original success value to the next step. * * **Details** * @@ -3276,17 +3186,10 @@ export const tap: { * next part of the chain. Note that if the side effect fails, the entire chain * will fail too. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Logging a step in a pipeline) * - * - `Effect.zipLeft` - * - * @example * ```ts - * // Title: Logging a step in a pipeline - * import { Data, Effect, pipe } from "effect" - * import { Console } from "effect" + * import { Console, Data, Effect, pipe } from "effect" * * class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} * @@ -3316,19 +3219,18 @@ export const tap: { * // 95 * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (f: Effect): (self: Effect) => Effect /** * Runs a side effect with the result of an effect without changing the original * value. * - * **When to Use** + * **When to use** * - * Use `tap` when you want to perform a side effect, like logging or tracking, - * without modifying the main value. This is useful when you need to observe or - * record an action but want the original value to be passed to the next step. + * Use when you need to run an effectful observation, such as logging or + * tracking, while passing the original success value to the next step. * * **Details** * @@ -3337,17 +3239,10 @@ export const tap: { * next part of the chain. Note that if the side effect fails, the entire chain * will fail too. * - * **Previously Known As** + * **Example** (Logging a step in a pipeline) * - * This API replaces the following from Effect 3.x: - * - * - `Effect.zipLeft` - * - * @example * ```ts - * // Title: Logging a step in a pipeline - * import { Data, Effect, pipe } from "effect" - * import { Console } from "effect" + * import { Console, Data, Effect, pipe } from "effect" * * class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} * @@ -3377,19 +3272,18 @@ export const tap: { * // 95 * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (self: Effect, f: (a: NoInfer) => Effect): Effect /** * Runs a side effect with the result of an effect without changing the original * value. * - * **When to Use** + * **When to use** * - * Use `tap` when you want to perform a side effect, like logging or tracking, - * without modifying the main value. This is useful when you need to observe or - * record an action but want the original value to be passed to the next step. + * Use when you need to run an effectful observation, such as logging or + * tracking, while passing the original success value to the next step. * * **Details** * @@ -3398,17 +3292,10 @@ export const tap: { * next part of the chain. Note that if the side effect fails, the entire chain * will fail too. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Logging a step in a pipeline) * - * - `Effect.zipLeft` - * - * @example * ```ts - * // Title: Logging a step in a pipeline - * import { Data, Effect, pipe } from "effect" - * import { Console } from "effect" + * import { Console, Data, Effect, pipe } from "effect" * * class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} * @@ -3438,42 +3325,43 @@ export const tap: { * // 95 * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (self: Effect, f: Effect): Effect } = internal.tap /** - * Encapsulates both success and failure of an `Effect` into a `Result` type. + * Converts both success and failure of an `Effect` into a `Result` type. + * + * **When to use** + * + * Use when you want an `Effect`'s typed failures to be handled as `Result` + * data while preserving the original error value. * * **Details** * * This function converts an effect that may fail into an effect that always * succeeds, wrapping the outcome in a `Result` type. The result will be - * `Result.Err` if the effect fails, containing the recoverable error, or - * `Result.Ok` if it succeeds, containing the result. + * `Result.Failure` if the effect fails, containing the recoverable error, or + * `Result.Success` if it succeeds, containing the result. * * Using this function, you can handle recoverable errors explicitly without * causing the effect to fail. This is particularly useful in scenarios where * you want to chain effects and manage both success and failure in the same * logical flow. * - * It's important to note that unrecoverable errors, often referred to as - * "defects," are still thrown and not captured within the `Result` type. Only - * failures that are explicitly represented as recoverable errors in the effect - * are encapsulated. - * * The resulting effect cannot fail directly because all recoverable failures * are represented inside the `Result` type. * - * **Previously Known As** + * **Gotchas** * - * This API replaces the following from Effect 3.x: + * `result` only captures typed, recoverable failures. Defects and + * interruptions are not captured inside the `Result` and still fail the + * effect. * - * - `Effect.either` + * **Example** (Capturing success or failure as Result) * - * @example * ```ts * import { Effect } from "effect" * @@ -3493,20 +3381,35 @@ export const tap: { * @see {@link option} for a version that uses `Option` instead. * @see {@link exit} for a version that encapsulates both recoverable errors and defects in an `Exit`. * + * @category outcome encapsulation * @since 4.0.0 - * @category Outcome Encapsulation */ export const result: (self: Effect) => Effect, never, R> = internal.result /** - * Convert success to `Option.some` and failure to `Option.none`. + * Converts success to `Option.some` and failure to `Option.none`. + * + * **When to use** + * + * Use when you only care whether an effect succeeds and want recoverable + * failures represented as `Option.none`. * * **Details** * * Success values become `Option.some`, recoverable failures become * `Option.none`, and defects still fail the effect. * - * @example + * **Gotchas** + * + * `option` only captures typed, recoverable failures as `Option.none`. + * Defects and interruptions are not captured inside the `Option` and still + * fail the effect. + * + * `option` also discards typed failure values. Use `result` if the failure + * value matters. + * + * **Example** (Capturing success or failure as Option) + * * ```ts * import { Console, Effect, Option } from "effect" * @@ -3526,8 +3429,8 @@ export const result: (self: Effect) => Effect(self: Effect) => Effect, never, R> = internal.option @@ -3535,6 +3438,11 @@ export const option: (self: Effect) => Effect, never * Transforms an effect to encapsulate both failure and success using the `Exit` * data type. * + * **When to use** + * + * Use when you need to inspect the full outcome, including typed failures, defects, + * and interruptions. + * * **Details** * * `exit` wraps an effect's success or failure inside an `Exit` type, allowing @@ -3544,7 +3452,8 @@ export const option: (self: Effect) => Effect, never * the `Exit.Failure` type. The error type is set to `never`, indicating that * the effect is structured to never fail directly. * - * @example + * **Example** (Capturing completion as Exit) + * * ```ts * import { Effect } from "effect" * @@ -3564,8 +3473,8 @@ export const option: (self: Effect) => Effect, never * @see {@link option} for a version that uses `Option` instead. * @see {@link result} for a version that uses `Result` instead. * + * @category outcome encapsulation * @since 2.0.0 - * @category Outcome Encapsulation */ export const exit: ( self: Effect @@ -3574,15 +3483,11 @@ export const exit: ( /** * Transforms the value inside an effect by applying a function to it. * - * **Syntax** + * **When to use** * - * ```ts skip-type-checking - * const mappedEffect = pipe(myEffect, Effect.map(transformation)) - * // or - * const mappedEffect = Effect.map(myEffect, transformation) - * // or - * const mappedEffect = myEffect.pipe(Effect.map(transformation)) - * ``` + * Use to transform an effect's success value with a function that returns a + * plain value, producing a new effect without changing the original effect's + * typed error or context requirements. * * **Details** * @@ -3593,7 +3498,21 @@ export const exit: ( * effect is not modified. Instead, a new effect is returned with the updated * value. * - * @example Adding a Service Charge + * **Example** (Syntax) + * + * ```ts + * import { Effect, pipe } from "effect" + * + * const myEffect = Effect.succeed(1) + * const transformation = (n: number) => n + 1 + * + * const mappedWithPipe = pipe(myEffect, Effect.map(transformation)) + * const mappedWithDataFirst = Effect.map(myEffect, transformation) + * const mappedWithMethod = myEffect.pipe(Effect.map(transformation)) + * ``` + * + * **Example** (Adding a service charge) + * * ```ts * import { Effect, pipe } from "effect" * @@ -3613,23 +3532,18 @@ export const exit: ( * @see {@link mapError} for a version that operates on the error channel. * @see {@link mapBoth} for a version that operates on both channels. * @see {@link flatMap} or {@link andThen} for a version that can return a new effect. - * + * @category mapping * @since 2.0.0 - * @category Mapping */ export const map: { /** * Transforms the value inside an effect by applying a function to it. * - * **Syntax** + * **When to use** * - * ```ts skip-type-checking - * const mappedEffect = pipe(myEffect, Effect.map(transformation)) - * // or - * const mappedEffect = Effect.map(myEffect, transformation) - * // or - * const mappedEffect = myEffect.pipe(Effect.map(transformation)) - * ``` + * Use to transform an effect's success value with a function that returns a + * plain value, producing a new effect without changing the original effect's + * typed error or context requirements. * * **Details** * @@ -3640,7 +3554,21 @@ export const map: { * effect is not modified. Instead, a new effect is returned with the updated * value. * - * @example Adding a Service Charge + * **Example** (Syntax) + * + * ```ts + * import { Effect, pipe } from "effect" + * + * const myEffect = Effect.succeed(1) + * const transformation = (n: number) => n + 1 + * + * const mappedWithPipe = pipe(myEffect, Effect.map(transformation)) + * const mappedWithDataFirst = Effect.map(myEffect, transformation) + * const mappedWithMethod = myEffect.pipe(Effect.map(transformation)) + * ``` + * + * **Example** (Adding a service charge) + * * ```ts * import { Effect, pipe } from "effect" * @@ -3660,23 +3588,18 @@ export const map: { * @see {@link mapError} for a version that operates on the error channel. * @see {@link mapBoth} for a version that operates on both channels. * @see {@link flatMap} or {@link andThen} for a version that can return a new effect. - * + * @category mapping * @since 2.0.0 - * @category Mapping */ (f: (a: A) => B): (self: Effect) => Effect /** * Transforms the value inside an effect by applying a function to it. * - * **Syntax** + * **When to use** * - * ```ts skip-type-checking - * const mappedEffect = pipe(myEffect, Effect.map(transformation)) - * // or - * const mappedEffect = Effect.map(myEffect, transformation) - * // or - * const mappedEffect = myEffect.pipe(Effect.map(transformation)) - * ``` + * Use to transform an effect's success value with a function that returns a + * plain value, producing a new effect without changing the original effect's + * typed error or context requirements. * * **Details** * @@ -3687,7 +3610,21 @@ export const map: { * effect is not modified. Instead, a new effect is returned with the updated * value. * - * @example Adding a Service Charge + * **Example** (Syntax) + * + * ```ts + * import { Effect, pipe } from "effect" + * + * const myEffect = Effect.succeed(1) + * const transformation = (n: number) => n + 1 + * + * const mappedWithPipe = pipe(myEffect, Effect.map(transformation)) + * const mappedWithDataFirst = Effect.map(myEffect, transformation) + * const mappedWithMethod = myEffect.pipe(Effect.map(transformation)) + * ``` + * + * **Example** (Adding a service charge) + * * ```ts * import { Effect, pipe } from "effect" * @@ -3707,9 +3644,8 @@ export const map: { * @see {@link mapError} for a version that operates on the error channel. * @see {@link mapBoth} for a version that operates on both channels. * @see {@link flatMap} or {@link andThen} for a version that can return a new effect. - * + * @category mapping * @since 2.0.0 - * @category Mapping */ (self: Effect, f: (a: A) => B): Effect } = internal.map @@ -3717,12 +3653,19 @@ export const map: { /** * Replaces the value inside an effect with a constant value. * + * **When to use** + * + * Use to replace a successful value with a constant while preserving failures + * and requirements. + * + * **Details** + * * `as` allows you to ignore the original value inside an effect and * replace it with a new constant value. * - * @example + * **Example** (Replacing a success value) + * * ```ts - * // Title: Replacing a Value * import { Effect, pipe } from "effect" * * // Replaces the value 5 with the constant "new value" @@ -3732,19 +3675,29 @@ export const map: { * // Output: "new value" * ``` * + * @see {@link map} for deriving the replacement value from the success value + * @see {@link asVoid} for replacing the success value with `void` + * + * @category mapping * @since 2.0.0 - * @category Mapping */ export const as: { /** * Replaces the value inside an effect with a constant value. * + * **When to use** + * + * Use to replace a successful value with a constant while preserving failures + * and requirements. + * + * **Details** + * * `as` allows you to ignore the original value inside an effect and * replace it with a new constant value. * - * @example + * **Example** (Replacing a success value) + * * ```ts - * // Title: Replacing a Value * import { Effect, pipe } from "effect" * * // Replaces the value 5 with the constant "new value" @@ -3754,19 +3707,29 @@ export const as: { * // Output: "new value" * ``` * + * @see {@link map} for deriving the replacement value from the success value + * @see {@link asVoid} for replacing the success value with `void` + * + * @category mapping * @since 2.0.0 - * @category Mapping */ (value: B): (self: Effect) => Effect /** * Replaces the value inside an effect with a constant value. * + * **When to use** + * + * Use to replace a successful value with a constant while preserving failures + * and requirements. + * + * **Details** + * * `as` allows you to ignore the original value inside an effect and * replace it with a new constant value. * - * @example + * **Example** (Replacing a success value) + * * ```ts - * // Title: Replacing a Value * import { Effect, pipe } from "effect" * * // Replaces the value 5 with the constant "new value" @@ -3776,18 +3739,20 @@ export const as: { * // Output: "new value" * ``` * + * @see {@link map} for deriving the replacement value from the success value + * @see {@link asVoid} for replacing the success value with `void` + * + * @category mapping * @since 2.0.0 - * @category Mapping */ (self: Effect, value: B): Effect } = internal.as /** - * This function maps the success value of an `Effect` value to a `Some` value - * in an `Option` value. If the original `Effect` value fails, the returned - * `Effect` value will also fail. + * Maps the success value of an `Effect` to `Some`, preserving failures. + * + * **Example** (Wrapping success in Option.some) * - * @example * ```ts * import { Effect } from "effect" * @@ -3797,18 +3762,16 @@ export const as: { * // { _id: 'Option', _tag: 'Some', value: 42 } * ``` * - * @category Mapping + * @category mapping * @since 2.0.0 */ export const asSome: (self: Effect) => Effect, E, R> = internal.asSome /** - * This function maps the success value of an `Effect` value to `void`. If the - * original `Effect` value succeeds, the returned `Effect` value will also - * succeed. If the original `Effect` value fails, the returned `Effect` value - * will fail with the same error. + * Maps the success value of an `Effect` to `void`, preserving failures. + * + * **Example** (Discarding success values) * - * @example * ```ts * import { Effect } from "effect" * @@ -3818,21 +3781,24 @@ export const asSome: (self: Effect) => Effect, E, R> * // undefined (void) * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ export const asVoid: (self: Effect) => Effect = internal.asVoid /** - * The `flip` function swaps the success and error channels of an effect, - * so that the success becomes the error, and the error becomes the success. + * Swaps an effect's success and failure channels. + * + * **When to use** + * + * Use to swap an `Effect`'s success and failure channels. + * + * **Details** + * + * For an `Effect`, the returned effect has type `Effect`. * - * This function is useful when you need to reverse the flow of an effect, - * treating the previously successful values as errors and vice versa. This can - * be helpful in scenarios where you want to handle a success as a failure or - * treat an error as a valid result. + * **Example** (Swapping success and failure channels) * - * @example * ```ts * import { Effect } from "effect" * @@ -3845,8 +3811,8 @@ export const asVoid: (self: Effect) => Effect = in * const flipped = Effect.flip(program) * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ export const flip: (self: Effect) => Effect = internal.flip @@ -3857,20 +3823,23 @@ export const flip: (self: Effect) => Effect = interna /** * Combines two effects into a single effect, producing a tuple with the results of both effects. * + * **When to use** + * + * Use to combine exactly two effects into a tuple. + * + * **Details** + * * The `zip` function executes the first effect (left) and then the second effect (right). * Once both effects succeed, their results are combined into a tuple. * - * **Concurrency** + * Concurrency: * * By default, `zip` processes the effects sequentially. To execute the effects concurrently, * use the `{ concurrent: true }` option. * - * @see {@link zipWith} for a version that combines the results with a custom function. - * @see {@link validate} for a version that accumulates errors. + * **Example** (Combining two effects sequentially) * - * @example * ```ts - * // Title: Combining Two Effects Sequentially * import { Effect } from "effect" * * const task1 = Effect.succeed(1).pipe( @@ -3895,8 +3864,9 @@ export const flip: (self: Effect) => Effect = interna * // [ 1, 'hello' ] * ``` * - * @example - * // Title: Combining Two Effects Concurrently + * **Example** (Combining two effects concurrently) + * + * ```ts * import { Effect } from "effect" * * const task1 = Effect.succeed(1).pipe( @@ -3916,9 +3886,13 @@ export const flip: (self: Effect) => Effect = interna * // timestamp=... level=INFO fiber=#0 message="task2 done" * // timestamp=... level=INFO fiber=#0 message="task1 done" * // [ 1, 'hello' ] + * ``` + * + * @see {@link zipWith} for a version that combines the results with a custom function. + * @see {@link all} for collecting a larger structure of effects. * + * @category zipping * @since 2.0.0 - * @category Zipping */ export const zip: { // ----------------------------------------------------------------------------- @@ -3928,20 +3902,23 @@ export const zip: { /** * Combines two effects into a single effect, producing a tuple with the results of both effects. * + * **When to use** + * + * Use to combine exactly two effects into a tuple. + * + * **Details** + * * The `zip` function executes the first effect (left) and then the second effect (right). * Once both effects succeed, their results are combined into a tuple. * - * **Concurrency** + * Concurrency: * * By default, `zip` processes the effects sequentially. To execute the effects concurrently, * use the `{ concurrent: true }` option. * - * @see {@link zipWith} for a version that combines the results with a custom function. - * @see {@link validate} for a version that accumulates errors. + * **Example** (Combining two effects sequentially) * - * @example * ```ts - * // Title: Combining Two Effects Sequentially * import { Effect } from "effect" * * const task1 = Effect.succeed(1).pipe( @@ -3966,8 +3943,9 @@ export const zip: { * // [ 1, 'hello' ] * ``` * - * @example - * // Title: Combining Two Effects Concurrently + * **Example** (Combining two effects concurrently) + * + * ```ts * import { Effect } from "effect" * * const task1 = Effect.succeed(1).pipe( @@ -3987,9 +3965,13 @@ export const zip: { * // timestamp=... level=INFO fiber=#0 message="task2 done" * // timestamp=... level=INFO fiber=#0 message="task1 done" * // [ 1, 'hello' ] + * ``` * + * @see {@link zipWith} for a version that combines the results with a custom function. + * @see {@link all} for collecting a larger structure of effects. + * + * @category zipping * @since 2.0.0 - * @category Zipping */ ( that: Effect, @@ -4002,20 +3984,23 @@ export const zip: { /** * Combines two effects into a single effect, producing a tuple with the results of both effects. * + * **When to use** + * + * Use to combine exactly two effects into a tuple. + * + * **Details** + * * The `zip` function executes the first effect (left) and then the second effect (right). * Once both effects succeed, their results are combined into a tuple. * - * **Concurrency** + * Concurrency: * * By default, `zip` processes the effects sequentially. To execute the effects concurrently, * use the `{ concurrent: true }` option. * - * @see {@link zipWith} for a version that combines the results with a custom function. - * @see {@link validate} for a version that accumulates errors. + * **Example** (Combining two effects sequentially) * - * @example * ```ts - * // Title: Combining Two Effects Sequentially * import { Effect } from "effect" * * const task1 = Effect.succeed(1).pipe( @@ -4040,8 +4025,9 @@ export const zip: { * // [ 1, 'hello' ] * ``` * - * @example - * // Title: Combining Two Effects Concurrently + * **Example** (Combining two effects concurrently) + * + * ```ts * import { Effect } from "effect" * * const task1 = Effect.succeed(1).pipe( @@ -4061,9 +4047,13 @@ export const zip: { * // timestamp=... level=INFO fiber=#0 message="task2 done" * // timestamp=... level=INFO fiber=#0 message="task1 done" * // [ 1, 'hello' ] + * ``` + * + * @see {@link zipWith} for a version that combines the results with a custom function. + * @see {@link all} for collecting a larger structure of effects. * + * @category zipping * @since 2.0.0 - * @category Zipping */ ( self: Effect, @@ -4076,20 +4066,21 @@ export const zip: { * Combines two effects sequentially and applies a function to their results to * produce a single value. * - * **When to Use** + * **When to use** * - * The `zipWith` function is similar to {@link zip}, but instead of returning a - * tuple of results, it applies a provided function to the results of the two - * effects, combining them into a single value. + * Use when you need to run two effects sequentially and combine their results + * with a function instead of keeping the results as a tuple. * - * **Concurrency** + * **Details** + * + * Concurrency: * * By default, the effects are run sequentially. To execute them concurrently, * use the `{ concurrent: true }` option. * - * @example + * **Example** (Combining two success values with a function) + * * ```ts - * // Title: Combining Effects with a Custom Function * import { Effect } from "effect" * * const task1 = Effect.succeed(1).pipe( @@ -4115,28 +4106,29 @@ export const zip: { * // 6 * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ export const zipWith: { /** * Combines two effects sequentially and applies a function to their results to * produce a single value. * - * **When to Use** + * **When to use** + * + * Use when you need to run two effects sequentially and combine their results + * with a function instead of keeping the results as a tuple. * - * The `zipWith` function is similar to {@link zip}, but instead of returning a - * tuple of results, it applies a provided function to the results of the two - * effects, combining them into a single value. + * **Details** * - * **Concurrency** + * Concurrency: * * By default, the effects are run sequentially. To execute them concurrently, * use the `{ concurrent: true }` option. * - * @example + * **Example** (Combining two success values with a function) + * * ```ts - * // Title: Combining Effects with a Custom Function * import { Effect } from "effect" * * const task1 = Effect.succeed(1).pipe( @@ -4162,8 +4154,8 @@ export const zipWith: { * // 6 * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ ( that: Effect, @@ -4174,20 +4166,21 @@ export const zipWith: { * Combines two effects sequentially and applies a function to their results to * produce a single value. * - * **When to Use** + * **When to use** * - * The `zipWith` function is similar to {@link zip}, but instead of returning a - * tuple of results, it applies a provided function to the results of the two - * effects, combining them into a single value. + * Use when you need to run two effects sequentially and combine their results + * with a function instead of keeping the results as a tuple. + * + * **Details** * - * **Concurrency** + * Concurrency: * * By default, the effects are run sequentially. To execute them concurrently, * use the `{ concurrent: true }` option. * - * @example + * **Example** (Combining two success values with a function) + * * ```ts - * // Title: Combining Effects with a Custom Function * import { Effect } from "effect" * * const task1 = Effect.succeed(1).pipe( @@ -4213,8 +4206,8 @@ export const zipWith: { * // 6 * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ ( self: Effect, @@ -4242,6 +4235,11 @@ export { /** * Handles all errors in an effect by providing a fallback effect. * + * **When to use** + * + * Use when every recoverable error from an effect should be handled by the same + * fallback function while unrecoverable defects remain defects. + * * **Details** * * The `catch` function catches any errors that may occur during the @@ -4249,19 +4247,15 @@ export { * effect. This ensures that the program continues without failing by recovering * from errors using the provided fallback logic. * - * **Note**: `catch` only handles recoverable errors. It will not recover - * from unrecoverable defects. - * - * @see {@link catchCause} for a version that can recover from both recoverable and unrecoverable errors. - * - * **Previously Known As** + * **Gotchas** * - * This API replaces the following from Effect 3.x: + * `catch` only handles recoverable errors. It will not recover from + * unrecoverable defects. * - * - `Effect.catchAll` + * @see {@link catchCause} for a version that can recover from both recoverable and unrecoverable errors. * + * @category error handling * @since 4.0.0 - * @category Error Handling */ catch_ as catch } @@ -4270,17 +4264,18 @@ export { * Catches and handles specific errors by their `_tag` field, which is used as a * discriminator. * - * **When to Use** + * **When to use** * - * `catchTag` is useful when your errors are tagged with a readonly `_tag` field - * that identifies the error type. You can use this function to handle specific - * error types by matching the `_tag` value. This allows for precise error - * handling, ensuring that only specific errors are caught and handled. + * Use when you need to recover from one specific tagged error in an effect + * error channel. * - * The error type must have a readonly `_tag` field to use `catchTag`. This - * field is used to identify and match errors. + * **Details** + * + * The error type must have a readonly `_tag` field. `catchTag` matches that + * field and only handles errors with the requested tag. + * + * **Example** (Handling a tagged error) * - * @example * ```ts * import { Effect } from "effect" * @@ -4303,25 +4298,29 @@ export { * ) * ``` * + * @see {@link catchTags} for handling multiple tagged errors in one call + * @see {@link catchIf} for recovering from errors that match a predicate + * + * @category error handling * @since 2.0.0 - * @category Error Handling */ export const catchTag: { /** * Catches and handles specific errors by their `_tag` field, which is used as a * discriminator. * - * **When to Use** + * **When to use** * - * `catchTag` is useful when your errors are tagged with a readonly `_tag` field - * that identifies the error type. You can use this function to handle specific - * error types by matching the `_tag` value. This allows for precise error - * handling, ensuring that only specific errors are caught and handled. + * Use when you need to recover from one specific tagged error in an effect + * error channel. * - * The error type must have a readonly `_tag` field to use `catchTag`. This - * field is used to identify and match errors. + * **Details** + * + * The error type must have a readonly `_tag` field. `catchTag` matches that + * field and only handles errors with the requested tag. + * + * **Example** (Handling a tagged error) * - * @example * ```ts * import { Effect } from "effect" * @@ -4344,8 +4343,11 @@ export const catchTag: { * ) * ``` * + * @see {@link catchTags} for handling multiple tagged errors in one call + * @see {@link catchIf} for recovering from errors that match a predicate + * + * @category error handling * @since 2.0.0 - * @category Error Handling */ < const K extends Tags | Arr.NonEmptyReadonlyArray>, @@ -4353,8 +4355,8 @@ export const catchTag: { A1, E1, R1, - A2 = never, - E2 = ExcludeTag, + A2 = unassigned, + E2 = never, R2 = never >( k: K, @@ -4362,22 +4364,31 @@ export const catchTag: { orElse?: | ((e: ExcludeTag ? K[number] : K>) => Effect) | undefined - ): (self: Effect) => Effect + ): ( + self: Effect + ) => Effect< + A | A1 | Exclude, + | E1 + | E2 + | (A2 extends unassigned ? ExcludeTag ? K[number] : K> : never), + R | R1 | R2 + > /** * Catches and handles specific errors by their `_tag` field, which is used as a * discriminator. * - * **When to Use** + * **When to use** * - * `catchTag` is useful when your errors are tagged with a readonly `_tag` field - * that identifies the error type. You can use this function to handle specific - * error types by matching the `_tag` value. This allows for precise error - * handling, ensuring that only specific errors are caught and handled. + * Use when you need to recover from one specific tagged error in an effect + * error channel. * - * The error type must have a readonly `_tag` field to use `catchTag`. This - * field is used to identify and match errors. + * **Details** + * + * The error type must have a readonly `_tag` field. `catchTag` matches that + * field and only handles errors with the requested tag. + * + * **Example** (Handling a tagged error) * - * @example * ```ts * import { Effect } from "effect" * @@ -4400,8 +4411,11 @@ export const catchTag: { * ) * ``` * + * @see {@link catchTags} for handling multiple tagged errors in one call + * @see {@link catchIf} for recovering from errors that match a predicate + * + * @category error handling * @since 2.0.0 - * @category Error Handling */ < A, @@ -4411,8 +4425,8 @@ export const catchTag: { R1, E1, A1, - A2 = never, - E2 = ExcludeTag, + A2 = unassigned, + E2 = never, R2 = never >( self: Effect, @@ -4421,25 +4435,33 @@ export const catchTag: { orElse?: | ((e: ExcludeTag ? K[number] : K>) => Effect) | undefined - ): Effect + ): Effect< + A | A1 | Exclude, + | E1 + | E2 + | (A2 extends unassigned ? ExcludeTag ? K[number] : K> : never), + R | R1 | R2 + > } = internal.catchTag /** * Handles multiple errors in a single block of code using their `_tag` field. * - * **When to Use** + * **When to use** + * + * Use when one recovery step should handle several tagged error types by + * matching their readonly `_tag` fields. + * + * **Details** * - * `catchTags` is a convenient way to handle multiple error types at - * once. Instead of using {@link catchTag} multiple times, you can pass an - * object where each key is an error type's `_tag`, and the value is the handler - * for that specific error. This allows you to catch and recover from multiple - * error types in a single call. You can also provide a fallback handler for - * unhandled errors. + * Pass a handler table whose keys are tags, plus an optional fallback for + * unmatched errors. * - * The error type must have a readonly `_tag` field to use `catchTag`. This + * The error type must have a readonly `_tag` field to use `catchTags`. This * field is used to identify and match errors. * - * @example + * **Example** (Handling multiple tagged errors) + * * ```ts * import { Data, Effect } from "effect" * @@ -4463,26 +4485,28 @@ export const catchTag: { * }) * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ export const catchTags: { /** * Handles multiple errors in a single block of code using their `_tag` field. * - * **When to Use** + * **When to use** + * + * Use when one recovery step should handle several tagged error types by + * matching their readonly `_tag` fields. + * + * **Details** * - * `catchTags` is a convenient way to handle multiple error types at - * once. Instead of using {@link catchTag} multiple times, you can pass an - * object where each key is an error type's `_tag`, and the value is the handler - * for that specific error. This allows you to catch and recover from multiple - * error types in a single call. You can also provide a fallback handler for - * unhandled errors. + * Pass a handler table whose keys are tags, plus an optional fallback for + * unmatched errors. * - * The error type must have a readonly `_tag` field to use `catchTag`. This + * The error type must have a readonly `_tag` field to use `catchTags`. This * field is used to identify and match errors. * - * @example + * **Example** (Handling multiple tagged errors) + * * ```ts * import { Data, Effect } from "effect" * @@ -4506,16 +4530,16 @@ export const catchTags: { * }) * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ < E, Cases extends & { [K in Extract["_tag"]]+?: ((error: Extract) => Effect) } & (unknown extends E ? {} : { [K in Exclude["_tag"]>]: never }), - A2 = never, - E2 = Exclude, + A2 = unassigned, + E2 = never, R2 = never >( cases: Cases, @@ -4524,11 +4548,12 @@ export const catchTags: { self: Effect ) => Effect< | A - | A2 + | Exclude | { [K in keyof Cases]: Cases[K] extends (...args: Array) => Effect ? A : never }[keyof Cases], | E2 + | (A2 extends unassigned ? Exclude : never) | { [K in keyof Cases]: Cases[K] extends (...args: Array) => Effect ? E : never }[keyof Cases], @@ -4541,19 +4566,21 @@ export const catchTags: { /** * Handles multiple errors in a single block of code using their `_tag` field. * - * **When to Use** + * **When to use** + * + * Use when one recovery step should handle several tagged error types by + * matching their readonly `_tag` fields. + * + * **Details** * - * `catchTags` is a convenient way to handle multiple error types at - * once. Instead of using {@link catchTag} multiple times, you can pass an - * object where each key is an error type's `_tag`, and the value is the handler - * for that specific error. This allows you to catch and recover from multiple - * error types in a single call. You can also provide a fallback handler for - * unhandled errors. + * Pass a handler table whose keys are tags, plus an optional fallback for + * unmatched errors. * - * The error type must have a readonly `_tag` field to use `catchTag`. This + * The error type must have a readonly `_tag` field to use `catchTags`. This * field is used to identify and match errors. * - * @example + * **Example** (Handling multiple tagged errors) + * * ```ts * import { Data, Effect } from "effect" * @@ -4577,8 +4604,8 @@ export const catchTags: { * }) * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ < R, @@ -4587,8 +4614,8 @@ export const catchTags: { Cases extends & { [K in Extract["_tag"]]+?: ((error: Extract) => Effect) } & (unknown extends E ? {} : { [K in Exclude["_tag"]>]: never }), - A2 = never, - E2 = Exclude, + A2 = unassigned, + E2 = never, R2 = never >( self: Effect, @@ -4596,11 +4623,12 @@ export const catchTags: { orElse?: ((e: Exclude) => Effect) | undefined ): Effect< | A - | A2 + | Exclude | { [K in keyof Cases]: Cases[K] extends (...args: Array) => Effect ? A : never }[keyof Cases], | E2 + | (A2 extends unassigned ? Exclude : never) | { [K in keyof Cases]: Cases[K] extends (...args: Array) => Effect ? E : never }[keyof Cases], @@ -4615,10 +4643,18 @@ export const catchTags: { /** * Catches a specific reason within a tagged error. * + * **When to use** + * + * Use to handle one nested reason inside an `Effect`'s tagged error while + * preserving the parent error shape for unmatched reasons. + * + * **Details** + * * Use this to handle nested error causes without removing the parent error * from the error channel. The handler receives the unwrapped reason. * - * @example + * **Example** (Handling an error reason) + * * ```ts * import { Data, Effect } from "effect" * @@ -4644,17 +4680,27 @@ export const catchTags: { * ) * ``` * + * @see {@link catchReasons} for handling several nested reason tags + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const catchReason: { /** * Catches a specific reason within a tagged error. * + * **When to use** + * + * Use to handle one nested reason inside an `Effect`'s tagged error while + * preserving the parent error shape for unmatched reasons. + * + * **Details** + * * Use this to handle nested error causes without removing the parent error * from the error channel. The handler receives the unwrapped reason. * - * @example + * **Example** (Handling an error reason) + * * ```ts * import { Data, Effect } from "effect" * @@ -4680,8 +4726,10 @@ export const catchReason: { * ) * ``` * + * @see {@link catchReasons} for handling several nested reason tags + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ < K extends Tags, @@ -4708,14 +4756,26 @@ export const catchReason: { | undefined ): ( self: Effect - ) => Effect, (A3 extends unassigned ? E : ExcludeTag) | E2 | E3, R | R2 | R3> + ) => Effect< + A | A2 | Exclude, + ExcludeTag | E2 | E3 | (A3 extends unassigned ? ExtractTag : never), + R | R2 | R3 + > /** * Catches a specific reason within a tagged error. * + * **When to use** + * + * Use to handle one nested reason inside an `Effect`'s tagged error while + * preserving the parent error shape for unmatched reasons. + * + * **Details** + * * Use this to handle nested error causes without removing the parent error * from the error channel. The handler receives the unwrapped reason. * - * @example + * **Example** (Handling an error reason) + * * ```ts * import { Data, Effect } from "effect" * @@ -4741,8 +4801,10 @@ export const catchReason: { * ) * ``` * + * @see {@link catchReasons} for handling several nested reason tags + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ < A, @@ -4764,13 +4826,18 @@ export const catchReason: { orElse?: | ((reasons: ExcludeReason, RK>, error: OmitReason, RK>) => Effect) | undefined - ): Effect, (A3 extends unassigned ? E : ExcludeTag) | E2 | E3, R | R2 | R3> + ): Effect< + A | A2 | Exclude, + ExcludeTag | E2 | E3 | (A3 extends unassigned ? ExtractTag : never), + R | R2 | R3 + > } = internal.catchReason /** * Catches multiple reasons within a tagged error using an object of handlers. * - * @example + * **Example** (Handling multiple error reasons) + * * ```ts * import { Data, Effect } from "effect" * @@ -4798,14 +4865,15 @@ export const catchReason: { * ) * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const catchReasons: { /** * Catches multiple reasons within a tagged error using an object of handlers. * - * @example + * **Example** (Handling multiple error reasons) + * * ```ts * import { Data, Effect } from "effect" * @@ -4833,8 +4901,8 @@ export const catchReasons: { * ) * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ < K extends Tags, @@ -4865,8 +4933,9 @@ export const catchReasons: { | { [RK in keyof Cases]: Cases[RK] extends (...args: Array) => Effect ? A : never }[keyof Cases], - | (A2 extends unassigned ? E : ExcludeTag) + | ExcludeTag | E2 + | (A2 extends unassigned ? ExtractTag : never) | { [RK in keyof Cases]: Cases[RK] extends (...args: Array) => Effect ? E : never }[keyof Cases], @@ -4879,7 +4948,8 @@ export const catchReasons: { /** * Catches multiple reasons within a tagged error using an object of handlers. * - * @example + * **Example** (Handling multiple error reasons) + * * ```ts * import { Data, Effect } from "effect" * @@ -4907,8 +4977,8 @@ export const catchReasons: { * ) * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ < A, @@ -4940,8 +5010,9 @@ export const catchReasons: { | { [RK in keyof Cases]: Cases[RK] extends (...args: Array) => Effect ? A : never }[keyof Cases], - | (A2 extends unassigned ? E : ExcludeTag) + | ExcludeTag | E2 + | (A2 extends unassigned ? ExtractTag : never) | { [RK in keyof Cases]: Cases[RK] extends (...args: Array) => Effect ? E : never }[keyof Cases], @@ -4956,10 +5027,22 @@ export const catchReasons: { /** * Type helper that keeps only error tags whose tagged error contains a tagged `reason` field. * - * Used by `catchReasons` and `unwrapReason` to constrain the parent error tag to reason-bearing errors. + * **When to use** + * + * Use to constrain custom helpers or overloads to parent error tags whose error + * contains a tagged reason. + * + * **Details** + * + * The mapped type keeps each parent error tag whose extracted tagged error has + * at least one reason tag, and removes tags that do not carry tagged reasons. + * + * @see {@link unwrapReason} for promoting nested reason errors into the error channel + * @see {@link catchReason} for handling one nested reason tag + * @see {@link catchReasons} for handling several nested reason tags * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export type TagsWithReason = { [T in Tags]: ReasonTags> extends never ? never : T @@ -4969,7 +5052,8 @@ export type TagsWithReason = { * Promotes nested reason errors into the Effect error channel, replacing * the parent error. * - * @example + * **Example** (Extracting the reason from a tagged error) + * * ```ts * import { Data, Effect } from "effect" * @@ -4992,15 +5076,16 @@ export type TagsWithReason = { * const unwrapped = program.pipe(Effect.unwrapReason("AiError")) * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const unwrapReason: { /** * Promotes nested reason errors into the Effect error channel, replacing * the parent error. * - * @example + * **Example** (Extracting the reason from a tagged error) + * * ```ts * import { Data, Effect } from "effect" * @@ -5023,8 +5108,8 @@ export const unwrapReason: { * const unwrapped = program.pipe(Effect.unwrapReason("AiError")) * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ < K extends TagsWithReason, @@ -5034,7 +5119,8 @@ export const unwrapReason: { * Promotes nested reason errors into the Effect error channel, replacing * the parent error. * - * @example + * **Example** (Extracting the reason from a tagged error) + * * ```ts * import { Data, Effect } from "effect" * @@ -5057,8 +5143,8 @@ export const unwrapReason: { * const unwrapped = program.pipe(Effect.unwrapReason("AiError")) * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ < A, @@ -5072,26 +5158,22 @@ export const unwrapReason: { * Handles both recoverable and unrecoverable errors by providing a recovery * effect. * - * **When to Use** + * **When to use** + * + * Use when you need to recover from an `Effect` by inspecting the full `Cause`, + * including recoverable failures, defects, and interruptions, instead of only + * the typed error value. * - * The `catchCause` function allows you to handle all errors, including - * unrecoverable defects, by providing a recovery effect. The recovery logic is - * based on the `Cause` of the error, which provides detailed information about - * the failure. + * **Details** * - * **When to Recover from Defects** + * When to Recover from Defects: * * Defects are unexpected errors that typically shouldn't be recovered from, as * they often indicate serious issues. However, in some cases, such as * dynamically loaded plugins, controlled recovery might be needed. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Recovering from full failure causes) * - * - `Effect.catchAllCause` - * - * @example * ```ts * import { Cause, Console, Effect } from "effect" * @@ -5109,34 +5191,30 @@ export const unwrapReason: { * }) * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const catchCause: { /** * Handles both recoverable and unrecoverable errors by providing a recovery * effect. * - * **When to Use** + * **When to use** + * + * Use when you need to recover from an `Effect` by inspecting the full `Cause`, + * including recoverable failures, defects, and interruptions, instead of only + * the typed error value. * - * The `catchCause` function allows you to handle all errors, including - * unrecoverable defects, by providing a recovery effect. The recovery logic is - * based on the `Cause` of the error, which provides detailed information about - * the failure. + * **Details** * - * **When to Recover from Defects** + * When to Recover from Defects: * * Defects are unexpected errors that typically shouldn't be recovered from, as * they often indicate serious issues. However, in some cases, such as * dynamically loaded plugins, controlled recovery might be needed. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Recovering from full failure causes) * - * - `Effect.catchAllCause` - * - * @example * ```ts * import { Cause, Console, Effect } from "effect" * @@ -5154,34 +5232,30 @@ export const catchCause: { * }) * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ (f: (cause: Cause.Cause) => Effect): (self: Effect) => Effect /** * Handles both recoverable and unrecoverable errors by providing a recovery * effect. * - * **When to Use** + * **When to use** + * + * Use when you need to recover from an `Effect` by inspecting the full `Cause`, + * including recoverable failures, defects, and interruptions, instead of only + * the typed error value. * - * The `catchCause` function allows you to handle all errors, including - * unrecoverable defects, by providing a recovery effect. The recovery logic is - * based on the `Cause` of the error, which provides detailed information about - * the failure. + * **Details** * - * **When to Recover from Defects** + * When to Recover from Defects: * * Defects are unexpected errors that typically shouldn't be recovered from, as * they often indicate serious issues. However, in some cases, such as * dynamically loaded plugins, controlled recovery might be needed. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Recovering from full failure causes) * - * - `Effect.catchAllCause` - * - * @example * ```ts * import { Cause, Console, Effect } from "effect" * @@ -5199,42 +5273,32 @@ export const catchCause: { * }) * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ (self: Effect, f: (cause: Cause.Cause) => Effect): Effect } = internal.catchCause /** - * Recovers from all defects using a provided recovery function. + * Recovers from defects using a provided recovery function. * - * **When to Use** + * **When to use** * - * There is no sensible way to recover from defects. This method should be used - * only at the boundary between Effect and an external system, to transmit - * information on a defect for diagnostic or explanatory purposes. + * Use when you need to report or translate defects at integration boundaries. * * **Details** * - * `catchAllDefect` allows you to handle defects, which are unexpected errors - * that usually cause the program to terminate. This function lets you recover - * from these defects by providing a function that handles the error. However, - * it does not handle expected errors (like those from {@link fail}) or - * execution interruptions (like those from {@link interrupt}). - * - * **When to Recover from Defects** - * - * Defects are unexpected errors that typically shouldn't be recovered from, as - * they often indicate serious issues. However, in some cases, such as - * dynamically loaded plugins, controlled recovery might be needed. + * `catchDefect` handles unexpected defects, such as thrown exceptions or + * values passed to `die`, without catching typed failures or interruptions. * - * **Previously Known As** + * When to Recover from Defects: * - * This API replaces the following from Effect 3.x: + * Defects are unexpected errors that typically should not be recovered from, as + * they often indicate serious issues. In some cases, such as dynamically loaded + * plugins, controlled recovery may be needed. * - * - `Effect.catchAllDefect` + * **Example** (Recovering from defects) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -5251,40 +5315,30 @@ export const catchCause: { * }) * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const catchDefect: { /** - * Recovers from all defects using a provided recovery function. + * Recovers from defects using a provided recovery function. * - * **When to Use** + * **When to use** * - * There is no sensible way to recover from defects. This method should be used - * only at the boundary between Effect and an external system, to transmit - * information on a defect for diagnostic or explanatory purposes. + * Use when you need to report or translate defects at integration boundaries. * * **Details** * - * `catchAllDefect` allows you to handle defects, which are unexpected errors - * that usually cause the program to terminate. This function lets you recover - * from these defects by providing a function that handles the error. However, - * it does not handle expected errors (like those from {@link fail}) or - * execution interruptions (like those from {@link interrupt}). - * - * **When to Recover from Defects** - * - * Defects are unexpected errors that typically shouldn't be recovered from, as - * they often indicate serious issues. However, in some cases, such as - * dynamically loaded plugins, controlled recovery might be needed. + * `catchDefect` handles unexpected defects, such as thrown exceptions or + * values passed to `die`, without catching typed failures or interruptions. * - * **Previously Known As** + * When to Recover from Defects: * - * This API replaces the following from Effect 3.x: + * Defects are unexpected errors that typically should not be recovered from, as + * they often indicate serious issues. In some cases, such as dynamically loaded + * plugins, controlled recovery may be needed. * - * - `Effect.catchAllDefect` + * **Example** (Recovering from defects) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -5301,40 +5355,30 @@ export const catchDefect: { * }) * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ (f: (defect: unknown) => Effect): (self: Effect) => Effect /** - * Recovers from all defects using a provided recovery function. + * Recovers from defects using a provided recovery function. * - * **When to Use** + * **When to use** * - * There is no sensible way to recover from defects. This method should be used - * only at the boundary between Effect and an external system, to transmit - * information on a defect for diagnostic or explanatory purposes. + * Use when you need to report or translate defects at integration boundaries. * * **Details** * - * `catchAllDefect` allows you to handle defects, which are unexpected errors - * that usually cause the program to terminate. This function lets you recover - * from these defects by providing a function that handles the error. However, - * it does not handle expected errors (like those from {@link fail}) or - * execution interruptions (like those from {@link interrupt}). - * - * **When to Recover from Defects** + * `catchDefect` handles unexpected defects, such as thrown exceptions or + * values passed to `die`, without catching typed failures or interruptions. * - * Defects are unexpected errors that typically shouldn't be recovered from, as - * they often indicate serious issues. However, in some cases, such as - * dynamically loaded plugins, controlled recovery might be needed. - * - * **Previously Known As** + * When to Recover from Defects: * - * This API replaces the following from Effect 3.x: + * Defects are unexpected errors that typically should not be recovered from, as + * they often indicate serious issues. In some cases, such as dynamically loaded + * plugins, controlled recovery may be needed. * - * - `Effect.catchAllDefect` + * **Example** (Recovering from defects) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -5351,8 +5395,8 @@ export const catchDefect: { * }) * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ (self: Effect, f: (defect: unknown) => Effect): Effect } = internal.catchDefect @@ -5360,21 +5404,18 @@ export const catchDefect: { /** * Recovers from specific errors using a `Predicate` or `Refinement`. * - * **When to Use** + * **When to use** * - * `catchIf` lets you recover from errors that match a condition. Use a - * `Refinement` for type narrowing or a `Predicate` for simple boolean - * matching. Non-matching errors re-fail with the original cause. Defects and - * interrupts are not caught. + * Use when you need to recover from errors that match a condition. * - * **Previously Known As** + * **Details** * - * This API replaces the following: + * Use a `Refinement` for type narrowing or a `Predicate` for simple boolean + * matching. Non-matching errors re-fail with the original cause. Defects and + * interrupts are not caught. * - * - `Effect.catchSome` (Effect 3.x) - * - `Effect.catchIf` + * **Example** (Recovering when a predicate matches) * - * @example * ```ts * import { Data, Effect, Filter } from "effect" * @@ -5399,28 +5440,25 @@ export const catchDefect: { * ) * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ export const catchIf: { /** * Recovers from specific errors using a `Predicate` or `Refinement`. * - * **When to Use** + * **When to use** * - * `catchIf` lets you recover from errors that match a condition. Use a - * `Refinement` for type narrowing or a `Predicate` for simple boolean - * matching. Non-matching errors re-fail with the original cause. Defects and - * interrupts are not caught. + * Use when you need to recover from errors that match a condition. * - * **Previously Known As** + * **Details** * - * This API replaces the following: + * Use a `Refinement` for type narrowing or a `Predicate` for simple boolean + * matching. Non-matching errors re-fail with the original cause. Defects and + * interrupts are not caught. * - * - `Effect.catchSome` (Effect 3.x) - * - `Effect.catchIf` + * **Example** (Recovering when a predicate matches) * - * @example * ```ts * import { Data, Effect, Filter } from "effect" * @@ -5445,32 +5483,31 @@ export const catchIf: { * ) * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ - , R3 = never>( + ( refinement: Predicate.Refinement, EB>, f: (e: EB) => Effect, orElse?: ((e: Exclude) => Effect) | undefined - ): (self: Effect) => Effect + ): ( + self: Effect + ) => Effect, E2 | E3 | (A3 extends unassigned ? Exclude : never), R | R2 | R3> /** * Recovers from specific errors using a `Predicate` or `Refinement`. * - * **When to Use** + * **When to use** * - * `catchIf` lets you recover from errors that match a condition. Use a - * `Refinement` for type narrowing or a `Predicate` for simple boolean - * matching. Non-matching errors re-fail with the original cause. Defects and - * interrupts are not caught. + * Use when you need to recover from errors that match a condition. * - * **Previously Known As** + * **Details** * - * This API replaces the following: + * Use a `Refinement` for type narrowing or a `Predicate` for simple boolean + * matching. Non-matching errors re-fail with the original cause. Defects and + * interrupts are not caught. * - * - `Effect.catchSome` (Effect 3.x) - * - `Effect.catchIf` + * **Example** (Recovering when a predicate matches) * - * @example * ```ts * import { Data, Effect, Filter } from "effect" * @@ -5495,32 +5532,31 @@ export const catchIf: { * ) * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ - ( + ( predicate: Predicate.Predicate>, f: (e: NoInfer) => Effect, orElse?: ((e: NoInfer) => Effect) | undefined - ): (self: Effect) => Effect + ): ( + self: Effect + ) => Effect, E2 | E3 | (A3 extends unassigned ? E : never), R | R2 | R3> /** * Recovers from specific errors using a `Predicate` or `Refinement`. * - * **When to Use** + * **When to use** * - * `catchIf` lets you recover from errors that match a condition. Use a - * `Refinement` for type narrowing or a `Predicate` for simple boolean - * matching. Non-matching errors re-fail with the original cause. Defects and - * interrupts are not caught. + * Use when you need to recover from errors that match a condition. * - * **Previously Known As** + * **Details** * - * This API replaces the following: + * Use a `Refinement` for type narrowing or a `Predicate` for simple boolean + * matching. Non-matching errors re-fail with the original cause. Defects and + * interrupts are not caught. * - * - `Effect.catchSome` (Effect 3.x) - * - `Effect.catchIf` + * **Example** (Recovering when a predicate matches) * - * @example * ```ts * import { Data, Effect, Filter } from "effect" * @@ -5545,33 +5581,30 @@ export const catchIf: { * ) * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ - , R3 = never>( + ( self: Effect, refinement: Predicate.Refinement, f: (e: EB) => Effect, orElse?: ((e: Exclude) => Effect) | undefined - ): Effect + ): Effect, E2 | E3 | (A3 extends unassigned ? Exclude : never), R | R2 | R3> /** * Recovers from specific errors using a `Predicate` or `Refinement`. * - * **When to Use** + * **When to use** * - * `catchIf` lets you recover from errors that match a condition. Use a - * `Refinement` for type narrowing or a `Predicate` for simple boolean - * matching. Non-matching errors re-fail with the original cause. Defects and - * interrupts are not caught. + * Use when you need to recover from errors that match a condition. * - * **Previously Known As** + * **Details** * - * This API replaces the following: + * Use a `Refinement` for type narrowing or a `Predicate` for simple boolean + * matching. Non-matching errors re-fail with the original cause. Defects and + * interrupts are not caught. * - * - `Effect.catchSome` (Effect 3.x) - * - `Effect.catchIf` + * **Example** (Recovering when a predicate matches) * - * @example * ```ts * import { Data, Effect, Filter } from "effect" * @@ -5596,56 +5629,120 @@ export const catchIf: { * ) * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ - ( + ( self: Effect, predicate: Predicate.Predicate, f: (e: E) => Effect, orElse?: ((e: E) => Effect) | undefined - ): Effect + ): Effect, E2 | E3 | (A3 extends unassigned ? E : never), R | R2 | R3> } = internal.catchIf /** * Recovers from specific errors using a `Filter`. * + * **When to use** + * + * Use to recover from typed `Effect` errors with a reusable `Filter` when + * matching can also narrow or transform the error before choosing the recovery + * effect. + * + * **Details** + * + * The filter runs on typed failures extracted from the `Cause`. Successful + * filter results are passed to `f`; failed filter results are passed to + * `orElse` when provided. Without `orElse`, the original failure cause is + * preserved. + * + * @see {@link catchIf} for predicate-based recovery from typed errors + * @see {@link catchTag} for recovering from a single tagged error + * @see {@link catchTags} for recovering from several tagged errors + * @see {@link catchCauseFilter} for filtering full causes instead of typed errors + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const catchFilter: { /** * Recovers from specific errors using a `Filter`. * + * **When to use** + * + * Use to recover from typed `Effect` errors with a reusable `Filter` when + * matching can also narrow or transform the error before choosing the recovery + * effect. + * + * **Details** + * + * The filter runs on typed failures extracted from the `Cause`. Successful + * filter results are passed to `f`; failed filter results are passed to + * `orElse` when provided. Without `orElse`, the original failure cause is + * preserved. + * + * @see {@link catchIf} for predicate-based recovery from typed errors + * @see {@link catchTag} for recovering from a single tagged error + * @see {@link catchTags} for recovering from several tagged errors + * @see {@link catchCauseFilter} for filtering full causes instead of typed errors + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ - ( + ( filter: Filter.Filter, EB, X>, f: (e: EB) => Effect, orElse?: ((e: X) => Effect) | undefined - ): (self: Effect) => Effect + ): ( + self: Effect + ) => Effect, E2 | E3 | (A3 extends unassigned ? X : never), R | R2 | R3> /** * Recovers from specific errors using a `Filter`. * + * **When to use** + * + * Use to recover from typed `Effect` errors with a reusable `Filter` when + * matching can also narrow or transform the error before choosing the recovery + * effect. + * + * **Details** + * + * The filter runs on typed failures extracted from the `Cause`. Successful + * filter results are passed to `f`; failed filter results are passed to + * `orElse` when provided. Without `orElse`, the original failure cause is + * preserved. + * + * @see {@link catchIf} for predicate-based recovery from typed errors + * @see {@link catchTag} for recovering from a single tagged error + * @see {@link catchTags} for recovering from several tagged errors + * @see {@link catchCauseFilter} for filtering full causes instead of typed errors + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ - ( + ( self: Effect, filter: Filter.Filter, EB, X>, f: (e: EB) => Effect, orElse?: ((e: X) => Effect) | undefined - ): Effect + ): Effect, E2 | E3 | (A3 extends unassigned ? X : never), R | R2 | R3> } = internal.catchFilter /** * Catches `NoSuchElementError` failures and converts them to `Option.none`. * + * **When to use** + * + * Use when you expect missing-value failures and want them to become an + * optional success while all other failures keep failing. + * + * **Details** + * * Success values become `Option.some`, `NoSuchElementError` becomes * `Option.none`, and all other errors are preserved. * - * @example + * **Example** (Recovering from missing Option values) + * * ```ts * import { Effect, Option } from "effect" * @@ -5656,14 +5753,12 @@ export const catchFilter: { * Effect.runPromise(none).then(console.log) // { _id: 'Option', _tag: 'None' } * ``` * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * @see {@link fromOption} for converting `Option.none` into `NoSuchElementError` + * @see {@link fromNullishOr} for converting nullish values into `NoSuchElementError` + * @see {@link option} for converting any failure into `Option.none` * - * - `Effect.optionFromOptional` - * - * @since 2.0.0 - * @category Error Handling + * @category error handling + * @since 4.0.0 */ export const catchNoSuchElement: ( self: Effect @@ -5672,17 +5767,18 @@ export const catchNoSuchElement: ( /** * Recovers from specific failures based on a predicate. * + * **When to use** + * + * Use to recover an `Effect` from full causes selected by a predicate. + * + * **Details** + * * This function allows you to conditionally catch and recover from failures * that match a specific predicate. This is useful when you want to handle * only certain types of errors while letting others propagate. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Recovering from selected causes) * - * - `Effect.catchSomeCause` - * - * @example * ```ts * import { Cause, Console, Effect } from "effect" * @@ -5704,24 +5800,29 @@ export const catchNoSuchElement: ( * // Then: "Fallback response" * ``` * + * @see {@link catchCause} for recovering from every cause + * @see {@link catchCauseFilter} for selecting full causes with a `Filter` + * @see {@link catchIf} for predicate-based recovery from typed errors + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const catchCauseIf: { /** * Recovers from specific failures based on a predicate. * + * **When to use** + * + * Use to recover an `Effect` from full causes selected by a predicate. + * + * **Details** + * * This function allows you to conditionally catch and recover from failures * that match a specific predicate. This is useful when you want to handle * only certain types of errors while letting others propagate. * - * **Previously Known As** + * **Example** (Recovering from selected causes) * - * This API replaces the following from Effect 3.x: - * - * - `Effect.catchSomeCause` - * - * @example * ```ts * import { Cause, Console, Effect } from "effect" * @@ -5743,8 +5844,12 @@ export const catchCauseIf: { * // Then: "Fallback response" * ``` * + * @see {@link catchCause} for recovering from every cause + * @see {@link catchCauseFilter} for selecting full causes with a `Filter` + * @see {@link catchIf} for predicate-based recovery from typed errors + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ ( predicate: Predicate.Predicate>, @@ -5753,17 +5858,18 @@ export const catchCauseIf: { /** * Recovers from specific failures based on a predicate. * + * **When to use** + * + * Use to recover an `Effect` from full causes selected by a predicate. + * + * **Details** + * * This function allows you to conditionally catch and recover from failures * that match a specific predicate. This is useful when you want to handle * only certain types of errors while letting others propagate. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Recovering from selected causes) * - * - `Effect.catchSomeCause` - * - * @example * ```ts * import { Cause, Console, Effect } from "effect" * @@ -5785,8 +5891,12 @@ export const catchCauseIf: { * // Then: "Fallback response" * ``` * + * @see {@link catchCause} for recovering from every cause + * @see {@link catchCauseFilter} for selecting full causes with a `Filter` + * @see {@link catchIf} for predicate-based recovery from typed errors + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ ( self: Effect, @@ -5798,15 +5908,47 @@ export const catchCauseIf: { /** * Recovers from specific failures based on a `Filter`. * + * **When to use** + * + * Use when you need to recover an `Effect` only from causes selected by a + * `Filter`, while giving the recovery both the selected value and the original + * `Cause`. + * + * **Details** + * + * The filter is applied to the full `Cause`. When it succeeds, the handler + * receives the selected value and the original cause. When it fails, the effect + * re-fails with the residual cause returned by the filter. + * + * @see {@link catchCauseIf} for predicate-based cause selection + * @see {@link catchFilter} for filtering typed error values instead of full causes + * @see {@link catchCause} for recovering from every cause without filtering + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const catchCauseFilter: { /** * Recovers from specific failures based on a `Filter`. * + * **When to use** + * + * Use when you need to recover an `Effect` only from causes selected by a + * `Filter`, while giving the recovery both the selected value and the original + * `Cause`. + * + * **Details** + * + * The filter is applied to the full `Cause`. When it succeeds, the handler + * receives the selected value and the original cause. When it fails, the effect + * re-fails with the residual cause returned by the filter. + * + * @see {@link catchCauseIf} for predicate-based cause selection + * @see {@link catchFilter} for filtering typed error values instead of full causes + * @see {@link catchCause} for recovering from every cause without filtering + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ >( filter: Filter.Filter, EB, X>, @@ -5815,8 +5957,24 @@ export const catchCauseFilter: { /** * Recovers from specific failures based on a `Filter`. * + * **When to use** + * + * Use when you need to recover an `Effect` only from causes selected by a + * `Filter`, while giving the recovery both the selected value and the original + * `Cause`. + * + * **Details** + * + * The filter is applied to the full `Cause`. When it succeeds, the handler + * receives the selected value and the original cause. When it fails, the effect + * re-fails with the residual cause returned by the filter. + * + * @see {@link catchCauseIf} for predicate-based cause selection + * @see {@link catchFilter} for filtering typed error values instead of full causes + * @see {@link catchCause} for recovering from every cause without filtering + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ >( self: Effect, @@ -5826,19 +5984,20 @@ export const catchCauseFilter: { } = internal.catchCauseFilter /** - * The `mapError` function is used to transform or modify the error - * produced by an effect, without affecting its success value. + * Transforms the failure value of an effect without changing its success value. * - * This function is helpful when you want to enhance the error with additional - * information, change the error type, or apply custom error handling while - * keeping the original behavior of the effect's success values intact. It only - * operates on the error channel and leaves the success channel unchanged. + * **When to use** * - * @see {@link map} for a version that operates on the success channel. - * @see {@link mapBoth} for a version that operates on both channels. - * @see {@link orElseFail} if you want to replace the error with a new one. + * Use to translate an `Effect`'s typed failures while leaving successful values + * unchanged. + * + * **Details** + * + * Only the failure channel is transformed. The success channel and requirements + * are preserved. + * + * **Example** (Transforming the error channel) * - * @example * ```ts * import { Data, Effect } from "effect" * @@ -5856,24 +6015,28 @@ export const catchCauseFilter: { * ) * ``` * + * @see {@link map} for a version that operates on the success channel. + * @see {@link mapBoth} for a version that operates on both channels. + * + * @category error handling * @since 2.0.0 - * @category Error Handling */ export const mapError: { /** - * The `mapError` function is used to transform or modify the error - * produced by an effect, without affecting its success value. + * Transforms the failure value of an effect without changing its success value. * - * This function is helpful when you want to enhance the error with additional - * information, change the error type, or apply custom error handling while - * keeping the original behavior of the effect's success values intact. It only - * operates on the error channel and leaves the success channel unchanged. + * **When to use** * - * @see {@link map} for a version that operates on the success channel. - * @see {@link mapBoth} for a version that operates on both channels. - * @see {@link orElseFail} if you want to replace the error with a new one. + * Use to translate an `Effect`'s typed failures while leaving successful values + * unchanged. + * + * **Details** + * + * Only the failure channel is transformed. The success channel and requirements + * are preserved. + * + * **Example** (Transforming the error channel) * - * @example * ```ts * import { Data, Effect } from "effect" * @@ -5891,24 +6054,28 @@ export const mapError: { * ) * ``` * + * @see {@link map} for a version that operates on the success channel. + * @see {@link mapBoth} for a version that operates on both channels. + * + * @category error handling * @since 2.0.0 - * @category Error Handling */ (f: (e: E) => E2): (self: Effect) => Effect /** - * The `mapError` function is used to transform or modify the error - * produced by an effect, without affecting its success value. + * Transforms the failure value of an effect without changing its success value. * - * This function is helpful when you want to enhance the error with additional - * information, change the error type, or apply custom error handling while - * keeping the original behavior of the effect's success values intact. It only - * operates on the error channel and leaves the success channel unchanged. + * **When to use** * - * @see {@link map} for a version that operates on the success channel. - * @see {@link mapBoth} for a version that operates on both channels. - * @see {@link orElseFail} if you want to replace the error with a new one. + * Use to translate an `Effect`'s typed failures while leaving successful values + * unchanged. + * + * **Details** + * + * Only the failure channel is transformed. The success channel and requirements + * are preserved. + * + * **Example** (Transforming the error channel) * - * @example * ```ts * import { Data, Effect } from "effect" * @@ -5926,8 +6093,11 @@ export const mapError: { * ) * ``` * + * @see {@link map} for a version that operates on the success channel. + * @see {@link mapBoth} for a version that operates on both channels. + * + * @category error handling * @since 2.0.0 - * @category Error Handling */ (self: Effect, f: (e: E) => E2): Effect } = internal.mapError @@ -5935,6 +6105,11 @@ export const mapError: { /** * Applies transformations to both the success and error channels of an effect. * + * **When to use** + * + * Use to transform both success and failure channels of an `Effect` without + * changing whether it succeeds or fails. + * * **Details** * * This function takes two map functions as arguments: one for the error channel @@ -5942,7 +6117,8 @@ export const mapError: { * the error and the success values without altering the overall success or * failure status of the effect. * - * @example + * **Example** (Transforming success and failure channels) + * * ```ts * import { Data, Effect } from "effect" * @@ -5963,13 +6139,18 @@ export const mapError: { * @see {@link map} for a version that operates on the success channel. * @see {@link mapError} for a version that operates on the error channel. * + * @category mapping * @since 2.0.0 - * @category Mapping */ export const mapBoth: { /** * Applies transformations to both the success and error channels of an effect. * + * **When to use** + * + * Use to transform both success and failure channels of an `Effect` without + * changing whether it succeeds or fails. + * * **Details** * * This function takes two map functions as arguments: one for the error channel @@ -5977,7 +6158,8 @@ export const mapBoth: { * the error and the success values without altering the overall success or * failure status of the effect. * - * @example + * **Example** (Transforming success and failure channels) + * * ```ts * import { Data, Effect } from "effect" * @@ -5998,8 +6180,8 @@ export const mapBoth: { * @see {@link map} for a version that operates on the success channel. * @see {@link mapError} for a version that operates on the error channel. * + * @category mapping * @since 2.0.0 - * @category Mapping */ ( options: { readonly onFailure: (e: E) => E2; readonly onSuccess: (a: A) => A2 } @@ -6007,6 +6189,11 @@ export const mapBoth: { /** * Applies transformations to both the success and error channels of an effect. * + * **When to use** + * + * Use to transform both success and failure channels of an `Effect` without + * changing whether it succeeds or fails. + * * **Details** * * This function takes two map functions as arguments: one for the error channel @@ -6014,7 +6201,8 @@ export const mapBoth: { * the error and the success values without altering the overall success or * failure status of the effect. * - * @example + * **Example** (Transforming success and failure channels) + * * ```ts * import { Data, Effect } from "effect" * @@ -6035,8 +6223,8 @@ export const mapBoth: { * @see {@link map} for a version that operates on the success channel. * @see {@link mapError} for a version that operates on the error channel. * + * @category mapping * @since 2.0.0 - * @category Mapping */ ( self: Effect, @@ -6045,23 +6233,17 @@ export const mapBoth: { } = internal.mapBoth /** - * Converts an effect's failure into a fiber termination, removing the error from the effect's type. + * Converts typed failures from the error channel into defects, removing the + * error type from the returned effect. * - * **When to Use* + * **When to use** * - * Use `orDie` when failures should be treated as unrecoverable defects and no error handling is required. + * Use when you need to turn an `Effect` typed failure that represents an + * unrecoverable bug or invalid state into a defect. * - * **Details** - * - * The `orDie` function is used when you encounter errors that you do not want to handle or recover from. - * It removes the error type from the effect and ensures that any failure will terminate the fiber. - * This is useful for propagating failures as defects, signaling that they should not be handled within the effect. + * **Example** (Converting typed failures into defects) * - * @see {@link orDieWith} if you need to customize the error. - * - * @example * ```ts - * // Title: Propagating an Error as a Defect * import { Data, Effect } from "effect" * * class DivideByZeroError extends Data.TaggedError("DivideByZeroError")<{}> {} @@ -6081,21 +6263,23 @@ export const mapBoth: { * // ...stack trace... * ``` * + * @category converting failures to defects * @since 2.0.0 - * @category Converting Failures to Defects */ export const orDie: (self: Effect) => Effect = internal.orDie /** - * The `tapError` function executes an effectful operation to inspect the - * failure of an effect without modifying it. + * Runs an effectful operation when the source effect fails, while preserving + * the original failure when the operation succeeds. + * + * **Details** + * + * Use this for logging, metrics, or other failure-side observations. If the + * operation passed to `tapError` fails, that error is also represented in the + * returned effect's error channel. * - * This function is useful when you want to perform some side effect (like - * logging or tracking) on the failure of an effect, but without changing the - * result of the effect itself. The error remains in the effect's error channel, - * while the operation you provide can inspect or act on it. + * **Example** (Running effects on failure) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -6113,20 +6297,22 @@ export const orDie: (self: Effect) => Effect = in * // expected error: NetworkError * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const tapError: { /** - * The `tapError` function executes an effectful operation to inspect the - * failure of an effect without modifying it. + * Runs an effectful operation when the source effect fails, while preserving + * the original failure when the operation succeeds. + * + * **Details** * - * This function is useful when you want to perform some side effect (like - * logging or tracking) on the failure of an effect, but without changing the - * result of the effect itself. The error remains in the effect's error channel, - * while the operation you provide can inspect or act on it. + * Use this for logging, metrics, or other failure-side observations. If the + * operation passed to `tapError` fails, that error is also represented in the + * returned effect's error channel. + * + * **Example** (Running effects on failure) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -6144,20 +6330,22 @@ export const tapError: { * // expected error: NetworkError * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (f: (e: NoInfer) => Effect): (self: Effect) => Effect /** - * The `tapError` function executes an effectful operation to inspect the - * failure of an effect without modifying it. + * Runs an effectful operation when the source effect fails, while preserving + * the original failure when the operation succeeds. + * + * **Details** + * + * Use this for logging, metrics, or other failure-side observations. If the + * operation passed to `tapError` fails, that error is also represented in the + * returned effect's error channel. * - * This function is useful when you want to perform some side effect (like - * logging or tracking) on the failure of an effect, but without changing the - * result of the effect itself. The error remains in the effect's error channel, - * while the operation you provide can inspect or act on it. + * **Example** (Running effects on failure) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -6175,8 +6363,8 @@ export const tapError: { * // expected error: NetworkError * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (self: Effect, f: (e: E) => Effect): Effect } = internal.tapError @@ -6184,10 +6372,14 @@ export const tapError: { /** * Runs an effectful handler when a failure's `_tag` matches. * - * Use this with tagged-union errors to perform side effects for a tag (or tag - * list) while preserving the original failure. + * **Details** + * + * Use this with tagged-union errors to perform side effects for one tag or a + * list of tags. When the handler succeeds, the original failure is preserved; + * if the handler fails, its error is also included in the returned effect. + * + * **Example** (Running effects for tagged failures) * - * @example * ```ts * import { Console, Data, Effect } from "effect" * @@ -6211,17 +6403,21 @@ export const tapError: { * // expected error: 504 * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const tapErrorTag: { /** * Runs an effectful handler when a failure's `_tag` matches. * - * Use this with tagged-union errors to perform side effects for a tag (or tag - * list) while preserving the original failure. + * **Details** + * + * Use this with tagged-union errors to perform side effects for one tag or a + * list of tags. When the handler succeeds, the original failure is preserved; + * if the handler fails, its error is also included in the returned effect. + * + * **Example** (Running effects for tagged failures) * - * @example * ```ts * import { Console, Data, Effect } from "effect" * @@ -6245,8 +6441,8 @@ export const tapErrorTag: { * // expected error: 504 * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ | Arr.NonEmptyReadonlyArray>, E, A1, E1, R1>( k: K, @@ -6255,10 +6451,14 @@ export const tapErrorTag: { /** * Runs an effectful handler when a failure's `_tag` matches. * - * Use this with tagged-union errors to perform side effects for a tag (or tag - * list) while preserving the original failure. + * **Details** + * + * Use this with tagged-union errors to perform side effects for one tag or a + * list of tags. When the handler succeeds, the original failure is preserved; + * if the handler fails, its error is also included in the returned effect. + * + * **Example** (Running effects for tagged failures) * - * @example * ```ts * import { Console, Data, Effect } from "effect" * @@ -6282,8 +6482,8 @@ export const tapErrorTag: { * // expected error: 504 * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ < A, @@ -6301,21 +6501,22 @@ export const tapErrorTag: { } = internal.tapErrorTag /** - * The `tapCause` function allows you to inspect the complete cause - * of an error, including failures and defects. + * Runs an effectful operation with the full `Cause` when the source effect + * fails. + * + * **When to use** * - * This function is helpful when you need to log, monitor, or handle specific - * error causes in your effects. It gives you access to the full error cause, - * whether it's a failure, defect, or other exceptional conditions, without - * altering the error or the overall result of the effect. + * Use when failure observation needs typed failures, defects, and interruptions + * rather than only the typed error value. * - * **Previously Known As** + * **Details** * - * This API replaces the following from Effect 3.x: + * Use this to log or inspect typed failures, defects, and interruptions. When + * the operation succeeds, the original cause is preserved. If the operation + * fails, its error is also represented in the returned effect. * - * - `Effect.tapErrorCause` + * **Example** (Observing full failure causes) * - * @example * ```ts * import { Cause, Console, Effect } from "effect" * @@ -6331,26 +6532,27 @@ export const tapErrorTag: { * // Then: { _id: 'Exit', _tag: 'Failure', cause: ... } * ``` * - * @since 2.0.0 - * @category Sequencing + * @category sequencing + * @since 4.0.0 */ export const tapCause: { /** - * The `tapCause` function allows you to inspect the complete cause - * of an error, including failures and defects. + * Runs an effectful operation with the full `Cause` when the source effect + * fails. + * + * **When to use** * - * This function is helpful when you need to log, monitor, or handle specific - * error causes in your effects. It gives you access to the full error cause, - * whether it's a failure, defect, or other exceptional conditions, without - * altering the error or the overall result of the effect. + * Use when failure observation needs typed failures, defects, and interruptions + * rather than only the typed error value. * - * **Previously Known As** + * **Details** * - * This API replaces the following from Effect 3.x: + * Use this to log or inspect typed failures, defects, and interruptions. When + * the operation succeeds, the original cause is preserved. If the operation + * fails, its error is also represented in the returned effect. * - * - `Effect.tapErrorCause` + * **Example** (Observing full failure causes) * - * @example * ```ts * import { Cause, Console, Effect } from "effect" * @@ -6366,26 +6568,27 @@ export const tapCause: { * // Then: { _id: 'Exit', _tag: 'Failure', cause: ... } * ``` * - * @since 2.0.0 - * @category Sequencing + * @category sequencing + * @since 4.0.0 */ (f: (cause: Cause.Cause>) => Effect): (self: Effect) => Effect /** - * The `tapCause` function allows you to inspect the complete cause - * of an error, including failures and defects. + * Runs an effectful operation with the full `Cause` when the source effect + * fails. + * + * **When to use** * - * This function is helpful when you need to log, monitor, or handle specific - * error causes in your effects. It gives you access to the full error cause, - * whether it's a failure, defect, or other exceptional conditions, without - * altering the error or the overall result of the effect. + * Use when failure observation needs typed failures, defects, and interruptions + * rather than only the typed error value. * - * **Previously Known As** + * **Details** * - * This API replaces the following from Effect 3.x: + * Use this to log or inspect typed failures, defects, and interruptions. When + * the operation succeeds, the original cause is preserved. If the operation + * fails, its error is also represented in the returned effect. * - * - `Effect.tapErrorCause` + * **Example** (Observing full failure causes) * - * @example * ```ts * import { Cause, Console, Effect } from "effect" * @@ -6401,20 +6604,23 @@ export const tapCause: { * // Then: { _id: 'Exit', _tag: 'Failure', cause: ... } * ``` * - * @since 2.0.0 - * @category Sequencing + * @category sequencing + * @since 4.0.0 */ (self: Effect, f: (cause: Cause.Cause) => Effect): Effect } = internal.tapCause /** - * Conditionally executes a side effect based on the cause of a failed effect. + * Executes a side effect conditionally when a failed effect's cause matches a predicate. + * + * **Details** * * This function allows you to tap into the cause of an effect's failure only when * the cause matches a specific predicate. This is useful for conditional logging, * monitoring, or other side effects based on the type of failure. * - * @example + * **Example** (Observing selected failure causes) + * * ```ts * import { Cause, Console, Effect } from "effect" * @@ -6432,18 +6638,21 @@ export const tapCause: { * // Then: { _id: 'Exit', _tag: 'Failure', cause: ... } * ``` * + * @category sequencing * @since 4.0.0 - * @category Sequencing */ export const tapCauseIf: { /** - * Conditionally executes a side effect based on the cause of a failed effect. + * Executes a side effect conditionally when a failed effect's cause matches a predicate. + * + * **Details** * * This function allows you to tap into the cause of an effect's failure only when * the cause matches a specific predicate. This is useful for conditional logging, * monitoring, or other side effects based on the type of failure. * - * @example + * **Example** (Observing selected failure causes) + * * ```ts * import { Cause, Console, Effect } from "effect" * @@ -6461,21 +6670,24 @@ export const tapCauseIf: { * // Then: { _id: 'Exit', _tag: 'Failure', cause: ... } * ``` * + * @category sequencing * @since 4.0.0 - * @category Sequencing */ ( predicate: Predicate.Predicate>, f: (cause: Cause.Cause) => Effect ): (self: Effect) => Effect /** - * Conditionally executes a side effect based on the cause of a failed effect. + * Executes a side effect conditionally when a failed effect's cause matches a predicate. + * + * **Details** * * This function allows you to tap into the cause of an effect's failure only when * the cause matches a specific predicate. This is useful for conditional logging, * monitoring, or other side effects based on the type of failure. * - * @example + * **Example** (Observing selected failure causes) + * * ```ts * import { Cause, Console, Effect } from "effect" * @@ -6493,8 +6705,8 @@ export const tapCauseIf: { * // Then: { _id: 'Exit', _tag: 'Failure', cause: ... } * ``` * + * @category sequencing * @since 4.0.0 - * @category Sequencing */ ( self: Effect, @@ -6504,27 +6716,75 @@ export const tapCauseIf: { } = internal.tapCauseIf /** - * Conditionally executes a side effect based on the cause of a failed effect. + * Executes a side effect conditionally when a failed effect's cause passes a filter. + * + * **When to use** + * + * Use when you need to observe only failure causes selected by a `Filter`, + * while giving the side effect both the selected value and the original + * `Cause`. * + * **Details** + * + * A successful filter result runs the side effect with the selected value and + * original cause. A failed filter result skips the side effect and preserves the + * original cause. + * + * @see {@link tapCauseIf} for selecting causes with a boolean predicate + * @see {@link tapCause} for observing every failure cause + * @see {@link catchCauseFilter} for recovering from selected causes instead of only observing them + * + * @category sequencing * @since 4.0.0 - * @category Sequencing */ export const tapCauseFilter: { /** - * Conditionally executes a side effect based on the cause of a failed effect. + * Executes a side effect conditionally when a failed effect's cause passes a filter. + * + * **When to use** + * + * Use when you need to observe only failure causes selected by a `Filter`, + * while giving the side effect both the selected value and the original + * `Cause`. + * + * **Details** * + * A successful filter result runs the side effect with the selected value and + * original cause. A failed filter result skips the side effect and preserves the + * original cause. + * + * @see {@link tapCauseIf} for selecting causes with a boolean predicate + * @see {@link tapCause} for observing every failure cause + * @see {@link catchCauseFilter} for recovering from selected causes instead of only observing them + * + * @category sequencing * @since 4.0.0 - * @category Sequencing */ >( filter: Filter.Filter, EB, X>, f: (a: EB, cause: Cause.Cause) => Effect ): (self: Effect) => Effect /** - * Conditionally executes a side effect based on the cause of a failed effect. + * Executes a side effect conditionally when a failed effect's cause passes a filter. + * + * **When to use** + * + * Use when you need to observe only failure causes selected by a `Filter`, + * while giving the side effect both the selected value and the original + * `Cause`. + * + * **Details** + * + * A successful filter result runs the side effect with the selected value and + * original cause. A failed filter result skips the side effect and preserves the + * original cause. + * + * @see {@link tapCauseIf} for selecting causes with a boolean predicate + * @see {@link tapCause} for observing every failure cause + * @see {@link catchCauseFilter} for recovering from selected causes instead of only observing them * + * @category sequencing * @since 4.0.0 - * @category Sequencing */ >( self: Effect, @@ -6534,22 +6794,17 @@ export const tapCauseFilter: { } = internal.tapCauseFilter /** - * Inspect severe errors or defects (non-recoverable failures) in an effect. + * Runs an effectful operation when the source effect dies with a defect. * * **Details** * - * This function is specifically designed to handle and inspect defects, which - * are critical failures in your program, such as unexpected runtime exceptions - * or system-level errors. Unlike normal recoverable errors, defects typically - * indicate serious issues that cannot be addressed through standard error - * handling. + * Use this for diagnostics such as logging unexpected thrown exceptions or + * values passed to `die`. Recoverable failures are not handled. When the + * operation succeeds, the original defect is preserved; if the operation fails, + * its error is also represented in the returned effect. * - * When a defect occurs in an effect, the function you provide to this function - * will be executed, allowing you to log, monitor, or handle the defect in some - * way. Importantly, this does not alter the main result of the effect. If no - * defect occurs, the effect behaves as if this function was not used. + * **Example** (Observing defects) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -6582,27 +6837,22 @@ export const tapCauseFilter: { * // ... stack trace ... * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const tapDefect: { /** - * Inspect severe errors or defects (non-recoverable failures) in an effect. + * Runs an effectful operation when the source effect dies with a defect. * * **Details** * - * This function is specifically designed to handle and inspect defects, which - * are critical failures in your program, such as unexpected runtime exceptions - * or system-level errors. Unlike normal recoverable errors, defects typically - * indicate serious issues that cannot be addressed through standard error - * handling. + * Use this for diagnostics such as logging unexpected thrown exceptions or + * values passed to `die`. Recoverable failures are not handled. When the + * operation succeeds, the original defect is preserved; if the operation fails, + * its error is also represented in the returned effect. * - * When a defect occurs in an effect, the function you provide to this function - * will be executed, allowing you to log, monitor, or handle the defect in some - * way. Importantly, this does not alter the main result of the effect. If no - * defect occurs, the effect behaves as if this function was not used. + * **Example** (Observing defects) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -6635,27 +6885,22 @@ export const tapDefect: { * // ... stack trace ... * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (f: (defect: unknown) => Effect): (self: Effect) => Effect /** - * Inspect severe errors or defects (non-recoverable failures) in an effect. + * Runs an effectful operation when the source effect dies with a defect. * * **Details** * - * This function is specifically designed to handle and inspect defects, which - * are critical failures in your program, such as unexpected runtime exceptions - * or system-level errors. Unlike normal recoverable errors, defects typically - * indicate serious issues that cannot be addressed through standard error - * handling. + * Use this for diagnostics such as logging unexpected thrown exceptions or + * values passed to `die`. Recoverable failures are not handled. When the + * operation succeeds, the original defect is preserved; if the operation fails, + * its error is also represented in the returned effect. * - * When a defect occurs in an effect, the function you provide to this function - * will be executed, allowing you to log, monitor, or handle the defect in some - * way. Importantly, this does not alter the main result of the effect. If no - * defect occurs, the effect behaves as if this function was not used. + * **Example** (Observing defects) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -6688,8 +6933,8 @@ export const tapDefect: { * // ... stack trace ... * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (self: Effect, f: (defect: unknown) => Effect): Effect } = internal.tapDefect @@ -6697,9 +6942,12 @@ export const tapDefect: { /** * Retries an effect until it succeeds, discarding failures. * + * **Details** + * * Yields between attempts so other fibers can run. * - * @example + * **Example** (Retrying until success) + * * ```ts * import { Console, Effect } from "effect" * @@ -6724,8 +6972,8 @@ export const tapDefect: { * // Ready * ``` * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ export const eventually: (self: Effect) => Effect = internal.eventually @@ -6734,31 +6982,16 @@ export const eventually: (self: Effect) => Effect // ----------------------------------------------------------------------------- /** - * @since 2.0.0 - * @category Error Handling - * @example - * ```ts - * import type { Effect } from "effect" + * Type helpers for retrying effects. * - * // Retry namespace contains types for retry operations - * declare const effect: Effect.Effect - * declare const options: Effect.Retry.Options - * // Use Effect.retry with these types for retrying failed effects - * ``` + * @since 2.0.0 */ export declare namespace Retry { /** - * @since 2.0.0 - * @category Error Handling - * @example - * ```ts - * import type { Effect } from "effect" + * Computes the result type of `Effect.retry` from the original effect and retry options. * - * // Return type for retry operations with specific options - * declare const options: Effect.Retry.Options - * type RetryResult = Effect.Retry.Return - * // Result: Effect with retried operation result types - * ``` + * @category error handling + * @since 2.0.0 */ export type Return> = Effect< A, @@ -6784,20 +7017,10 @@ export declare namespace Retry { : never /** - * @since 2.0.0 - * @category Error Handling - * @example - * ```ts - * import { Schedule } from "effect" - * import type { Effect } from "effect" + * Options that control whether and how a failing effect is retried. * - * // Options for configuring retry behavior - * const retryOptions: Effect.Retry.Options = { - * times: 3, - * schedule: Schedule.exponential("100 millis"), - * while: (error) => error.message !== "STOP" - * } - * ``` + * @category error handling + * @since 2.0.0 */ export interface Options { while?: ((error: E) => boolean | Effect) | undefined @@ -6808,27 +7031,30 @@ export declare namespace Retry { } /** - * Retries a failing effect based on a defined retry policy. + * Retries typed failures from an effect according to a retry policy. + * + * **When to use** + * + * Use when you need to rerun an effect after transient typed failures, such as + * network issues or temporary resource unavailability. * * **Details** * - * The `Effect.retry` function takes an effect and a {@link Schedule} policy, - * and will automatically retry the effect if it fails, following the rules of - * the policy. + * The policy can be a `Schedule`, a schedule builder, or a `Retry.Options` + * object using `schedule`, `times`, `while`, or `until`. If a retry eventually + * succeeds, the returned effect succeeds with that value. If the policy stops + * while the effect is still failing, the last failure is propagated. * - * If the effect ultimately succeeds, the result will be returned. + * **Gotchas** * - * If the maximum retries are exhausted and the effect still fails, the failure - * is propagated. + * The source effect is always evaluated once before any retry policy is + * applied. For example, `Schedule.recurs(3)` allows up to three retries after + * the initial attempt. * - * **When to Use** + * Defects and interruptions are not retried. * - * This can be useful when dealing with intermittent failures, such as network - * issues or temporary resource unavailability. By defining a retry policy, you - * can control the number of retries, the delay between them, and when to stop - * retrying. + * **Example** (Retrying with a schedule) * - * @example * ```ts * import { Data, Effect, Schedule } from "effect" * @@ -6853,33 +7079,35 @@ export declare namespace Retry { * * @see {@link retryOrElse} for a version that allows you to run a fallback. * @see {@link repeat} if your retry condition is based on successful outcomes rather than errors. - * + * @category error handling * @since 2.0.0 - * @category Error Handling */ export const retry: { /** - * Retries a failing effect based on a defined retry policy. + * Retries typed failures from an effect according to a retry policy. + * + * **When to use** + * + * Use when you need to rerun an effect after transient typed failures, such as + * network issues or temporary resource unavailability. * * **Details** * - * The `Effect.retry` function takes an effect and a {@link Schedule} policy, - * and will automatically retry the effect if it fails, following the rules of - * the policy. + * The policy can be a `Schedule`, a schedule builder, or a `Retry.Options` + * object using `schedule`, `times`, `while`, or `until`. If a retry eventually + * succeeds, the returned effect succeeds with that value. If the policy stops + * while the effect is still failing, the last failure is propagated. * - * If the effect ultimately succeeds, the result will be returned. + * **Gotchas** * - * If the maximum retries are exhausted and the effect still fails, the failure - * is propagated. + * The source effect is always evaluated once before any retry policy is + * applied. For example, `Schedule.recurs(3)` allows up to three retries after + * the initial attempt. * - * **When to Use** + * Defects and interruptions are not retried. * - * This can be useful when dealing with intermittent failures, such as network - * issues or temporary resource unavailability. By defining a retry policy, you - * can control the number of retries, the delay between them, and when to stop - * retrying. + * **Example** (Retrying with a schedule) * - * @example * ```ts * import { Data, Effect, Schedule } from "effect" * @@ -6904,33 +7132,35 @@ export const retry: { * * @see {@link retryOrElse} for a version that allows you to run a fallback. * @see {@link repeat} if your retry condition is based on successful outcomes rather than errors. - * + * @category error handling * @since 2.0.0 - * @category Error Handling */ >(options: O): (self: Effect) => Retry.Return /** - * Retries a failing effect based on a defined retry policy. + * Retries typed failures from an effect according to a retry policy. + * + * **When to use** + * + * Use when you need to rerun an effect after transient typed failures, such as + * network issues or temporary resource unavailability. * * **Details** * - * The `Effect.retry` function takes an effect and a {@link Schedule} policy, - * and will automatically retry the effect if it fails, following the rules of - * the policy. + * The policy can be a `Schedule`, a schedule builder, or a `Retry.Options` + * object using `schedule`, `times`, `while`, or `until`. If a retry eventually + * succeeds, the returned effect succeeds with that value. If the policy stops + * while the effect is still failing, the last failure is propagated. * - * If the effect ultimately succeeds, the result will be returned. + * **Gotchas** * - * If the maximum retries are exhausted and the effect still fails, the failure - * is propagated. + * The source effect is always evaluated once before any retry policy is + * applied. For example, `Schedule.recurs(3)` allows up to three retries after + * the initial attempt. * - * **When to Use** + * Defects and interruptions are not retried. * - * This can be useful when dealing with intermittent failures, such as network - * issues or temporary resource unavailability. By defining a retry policy, you - * can control the number of retries, the delay between them, and when to stop - * retrying. + * **Example** (Retrying with a schedule) * - * @example * ```ts * import { Data, Effect, Schedule } from "effect" * @@ -6955,33 +7185,35 @@ export const retry: { * * @see {@link retryOrElse} for a version that allows you to run a fallback. * @see {@link repeat} if your retry condition is based on successful outcomes rather than errors. - * + * @category error handling * @since 2.0.0 - * @category Error Handling */ (policy: Schedule, Error, Env>): (self: Effect) => Effect /** - * Retries a failing effect based on a defined retry policy. + * Retries typed failures from an effect according to a retry policy. + * + * **When to use** + * + * Use when you need to rerun an effect after transient typed failures, such as + * network issues or temporary resource unavailability. * * **Details** * - * The `Effect.retry` function takes an effect and a {@link Schedule} policy, - * and will automatically retry the effect if it fails, following the rules of - * the policy. + * The policy can be a `Schedule`, a schedule builder, or a `Retry.Options` + * object using `schedule`, `times`, `while`, or `until`. If a retry eventually + * succeeds, the returned effect succeeds with that value. If the policy stops + * while the effect is still failing, the last failure is propagated. * - * If the effect ultimately succeeds, the result will be returned. + * **Gotchas** * - * If the maximum retries are exhausted and the effect still fails, the failure - * is propagated. + * The source effect is always evaluated once before any retry policy is + * applied. For example, `Schedule.recurs(3)` allows up to three retries after + * the initial attempt. * - * **When to Use** + * Defects and interruptions are not retried. * - * This can be useful when dealing with intermittent failures, such as network - * issues or temporary resource unavailability. By defining a retry policy, you - * can control the number of retries, the delay between them, and when to stop - * retrying. + * **Example** (Retrying with a schedule) * - * @example * ```ts * import { Data, Effect, Schedule } from "effect" * @@ -7006,9 +7238,8 @@ export const retry: { * * @see {@link retryOrElse} for a version that allows you to run a fallback. * @see {@link repeat} if your retry condition is based on successful outcomes rather than errors. - * + * @category error handling * @since 2.0.0 - * @category Error Handling */ ( builder: ( @@ -7016,27 +7247,30 @@ export const retry: { ) => Schedule, Error, Env> ): (self: Effect) => Effect /** - * Retries a failing effect based on a defined retry policy. + * Retries typed failures from an effect according to a retry policy. + * + * **When to use** + * + * Use when you need to rerun an effect after transient typed failures, such as + * network issues or temporary resource unavailability. * * **Details** * - * The `Effect.retry` function takes an effect and a {@link Schedule} policy, - * and will automatically retry the effect if it fails, following the rules of - * the policy. + * The policy can be a `Schedule`, a schedule builder, or a `Retry.Options` + * object using `schedule`, `times`, `while`, or `until`. If a retry eventually + * succeeds, the returned effect succeeds with that value. If the policy stops + * while the effect is still failing, the last failure is propagated. * - * If the effect ultimately succeeds, the result will be returned. + * **Gotchas** * - * If the maximum retries are exhausted and the effect still fails, the failure - * is propagated. + * The source effect is always evaluated once before any retry policy is + * applied. For example, `Schedule.recurs(3)` allows up to three retries after + * the initial attempt. * - * **When to Use** + * Defects and interruptions are not retried. * - * This can be useful when dealing with intermittent failures, such as network - * issues or temporary resource unavailability. By defining a retry policy, you - * can control the number of retries, the delay between them, and when to stop - * retrying. + * **Example** (Retrying with a schedule) * - * @example * ```ts * import { Data, Effect, Schedule } from "effect" * @@ -7061,33 +7295,35 @@ export const retry: { * * @see {@link retryOrElse} for a version that allows you to run a fallback. * @see {@link repeat} if your retry condition is based on successful outcomes rather than errors. - * + * @category error handling * @since 2.0.0 - * @category Error Handling */ >(self: Effect, options: O): Retry.Return /** - * Retries a failing effect based on a defined retry policy. + * Retries typed failures from an effect according to a retry policy. + * + * **When to use** + * + * Use when you need to rerun an effect after transient typed failures, such as + * network issues or temporary resource unavailability. * * **Details** * - * The `Effect.retry` function takes an effect and a {@link Schedule} policy, - * and will automatically retry the effect if it fails, following the rules of - * the policy. + * The policy can be a `Schedule`, a schedule builder, or a `Retry.Options` + * object using `schedule`, `times`, `while`, or `until`. If a retry eventually + * succeeds, the returned effect succeeds with that value. If the policy stops + * while the effect is still failing, the last failure is propagated. * - * If the effect ultimately succeeds, the result will be returned. + * **Gotchas** * - * If the maximum retries are exhausted and the effect still fails, the failure - * is propagated. + * The source effect is always evaluated once before any retry policy is + * applied. For example, `Schedule.recurs(3)` allows up to three retries after + * the initial attempt. * - * **When to Use** + * Defects and interruptions are not retried. * - * This can be useful when dealing with intermittent failures, such as network - * issues or temporary resource unavailability. By defining a retry policy, you - * can control the number of retries, the delay between them, and when to stop - * retrying. + * **Example** (Retrying with a schedule) * - * @example * ```ts * import { Data, Effect, Schedule } from "effect" * @@ -7112,33 +7348,35 @@ export const retry: { * * @see {@link retryOrElse} for a version that allows you to run a fallback. * @see {@link repeat} if your retry condition is based on successful outcomes rather than errors. - * + * @category error handling * @since 2.0.0 - * @category Error Handling */ (self: Effect, policy: Schedule, Error, Env>): Effect /** - * Retries a failing effect based on a defined retry policy. + * Retries typed failures from an effect according to a retry policy. + * + * **When to use** + * + * Use when you need to rerun an effect after transient typed failures, such as + * network issues or temporary resource unavailability. * * **Details** * - * The `Effect.retry` function takes an effect and a {@link Schedule} policy, - * and will automatically retry the effect if it fails, following the rules of - * the policy. + * The policy can be a `Schedule`, a schedule builder, or a `Retry.Options` + * object using `schedule`, `times`, `while`, or `until`. If a retry eventually + * succeeds, the returned effect succeeds with that value. If the policy stops + * while the effect is still failing, the last failure is propagated. * - * If the effect ultimately succeeds, the result will be returned. + * **Gotchas** * - * If the maximum retries are exhausted and the effect still fails, the failure - * is propagated. + * The source effect is always evaluated once before any retry policy is + * applied. For example, `Schedule.recurs(3)` allows up to three retries after + * the initial attempt. * - * **When to Use** + * Defects and interruptions are not retried. * - * This can be useful when dealing with intermittent failures, such as network - * issues or temporary resource unavailability. By defining a retry policy, you - * can control the number of retries, the delay between them, and when to stop - * retrying. + * **Example** (Retrying with a schedule) * - * @example * ```ts * import { Data, Effect, Schedule } from "effect" * @@ -7163,9 +7401,8 @@ export const retry: { * * @see {@link retryOrElse} for a version that allows you to run a fallback. * @see {@link repeat} if your retry condition is based on successful outcomes rather than errors. - * + * @category error handling * @since 2.0.0 - * @category Error Handling */ ( self: Effect, @@ -7178,6 +7415,11 @@ export const retry: { /** * Retries a failing effect and runs a fallback effect if retries are exhausted. * + * **When to use** + * + * Use when you want to handle failures gracefully by specifying an alternative + * action after repeated failures. + * * **Details** * * The `Effect.retryOrElse` function attempts to retry a failing effect multiple @@ -7186,14 +7428,8 @@ export const retry: { * If the retries are exhausted and the effect still fails, it runs a fallback * effect instead. * - * **When to Use** - * - * This function is useful when you want to handle failures gracefully by - * specifying an alternative action after repeated failures. + * **Example** (Falling back after retries are exhausted) * - * @see {@link retry} for a version that does not run a fallback effect. - * - * @example * ```ts * import { Console, Data, Effect, Schedule } from "effect" * @@ -7228,13 +7464,19 @@ export const retry: { * // Network data * ``` * + * @see {@link retry} for a version that does not run a fallback effect. + * @category error handling * @since 2.0.0 - * @category Error Handling */ export const retryOrElse: { /** * Retries a failing effect and runs a fallback effect if retries are exhausted. * + * **When to use** + * + * Use when you want to handle failures gracefully by specifying an alternative + * action after repeated failures. + * * **Details** * * The `Effect.retryOrElse` function attempts to retry a failing effect multiple @@ -7243,14 +7485,8 @@ export const retryOrElse: { * If the retries are exhausted and the effect still fails, it runs a fallback * effect instead. * - * **When to Use** - * - * This function is useful when you want to handle failures gracefully by - * specifying an alternative action after repeated failures. - * - * @see {@link retry} for a version that does not run a fallback effect. + * **Example** (Falling back after retries are exhausted) * - * @example * ```ts * import { Console, Data, Effect, Schedule } from "effect" * @@ -7285,8 +7521,9 @@ export const retryOrElse: { * // Network data * ``` * + * @see {@link retry} for a version that does not run a fallback effect. + * @category error handling * @since 2.0.0 - * @category Error Handling */ ( policy: Schedule, E1, R1>, @@ -7295,6 +7532,11 @@ export const retryOrElse: { /** * Retries a failing effect and runs a fallback effect if retries are exhausted. * + * **When to use** + * + * Use when you want to handle failures gracefully by specifying an alternative + * action after repeated failures. + * * **Details** * * The `Effect.retryOrElse` function attempts to retry a failing effect multiple @@ -7303,14 +7545,8 @@ export const retryOrElse: { * If the retries are exhausted and the effect still fails, it runs a fallback * effect instead. * - * **When to Use** - * - * This function is useful when you want to handle failures gracefully by - * specifying an alternative action after repeated failures. + * **Example** (Falling back after retries are exhausted) * - * @see {@link retry} for a version that does not run a fallback effect. - * - * @example * ```ts * import { Console, Data, Effect, Schedule } from "effect" * @@ -7345,8 +7581,9 @@ export const retryOrElse: { * // Network data * ``` * + * @see {@link retry} for a version that does not run a fallback effect. + * @category error handling * @since 2.0.0 - * @category Error Handling */ ( self: Effect, @@ -7356,19 +7593,16 @@ export const retryOrElse: { } = internalSchedule.retryOrElse /** - * The `sandbox` function transforms an effect by exposing the full cause - * of any error, defect, or fiber interruption that might occur during its - * execution. It changes the error channel of the effect to include detailed - * information about the cause, which is wrapped in a `Cause` type. - * - * This function is useful when you need access to the complete underlying cause - * of failures, defects, or interruptions, enabling more detailed error - * handling. Once you apply `sandbox`, you can use operators like - * {@link catchAll} and {@link catchTags} to handle specific error conditions. - * If necessary, you can revert the sandboxing operation with {@link unsandbox} - * to return to the original error handling behavior. - * - * @example + * Exposes an effect's full failure cause in the error channel as `Cause`. + * + * **Details** + * + * Use `sandbox` when downstream error handling needs to distinguish typed + * failures, defects, and interruptions. Use `unsandbox` to restore the original + * typed error channel after cause-level handling. + * + * **Example** (Exposing failures as causes) + * * ```ts * import { Cause, Effect } from "effect" * @@ -7384,10 +7618,8 @@ export const retryOrElse: { * // Output: "Caught cause: Something went wrong" * ``` * - * @see {@link unsandbox} to restore the original error handling. - * + * @category error handling * @since 2.0.0 - * @category Error Handling */ export const sandbox: ( self: Effect @@ -7396,18 +7628,19 @@ export const sandbox: ( /** * Discards both the success and failure values of an effect. * - * **When to Use** + * **When to use** + * + * Use when an effect should run for its side effects while both success and + * failure values are discarded. * - * `ignore` allows you to run an effect without caring about its result, whether - * it succeeds or fails. This is useful when you only care about the side - * effects of the effect and do not need to handle or process its outcome. + * **Details** * * Use the `log` option to emit the full {@link Cause} when the effect fails, * and `message` to prepend a custom log message. * - * @example + * **Example** (Discarding success and failure values) + * * ```ts - * // Title: Using Effect.ignore to Discard Values * import { Effect } from "effect" * * // ┌─── Effect @@ -7419,9 +7652,9 @@ export const sandbox: ( * const program = task.pipe(Effect.ignore) * ``` * - * @example + * **Example** (Logging failures while ignoring results) + * * ```ts - * // Title: Logging failures while ignoring results * import { Effect } from "effect" * * const task = Effect.fail("Uh oh!") @@ -7430,14 +7663,8 @@ export const sandbox: ( * const programWarn = task.pipe(Effect.ignore({ log: "Warn", message: "Ignoring task failure" })) * ``` * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: - * - * - `Effect.ignoreLogged` - * + * @category error handling * @since 2.0.0 - * @category Error Handling */ export const ignore: < Arg extends Effect | { @@ -7459,10 +7686,18 @@ export const ignore: < /** * Ignores the effect's failure cause, including defects and interruptions. * + * **When to use** + * + * Use when a best-effort effect should never fail, even from defects or + * interruption, and optional cause logging is enough. + * + * **Details** + * * Use the `log` option to emit the full {@link Cause} when the effect fails, * and `message` to prepend a custom log message. * - * @example + * **Example** (Ignoring failures and logging causes) + * * ```ts * import { Effect } from "effect" * @@ -7472,8 +7707,8 @@ export const ignore: < * const programLog = task.pipe(Effect.ignoreCause({ log: true, message: "Ignoring failure cause" })) * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const ignoreCause: < Arg extends Effect | { @@ -7493,16 +7728,19 @@ export const ignoreCause: < : (self: Effect) => Effect = internal.ignoreCause /** - * Apply an `ExecutionPlan` to an effect, retrying with step-provided resources + * Applies an `ExecutionPlan` to an effect, retrying with step-provided resources * until it succeeds or the plan is exhausted. * + * **Details** + * * Each attempt updates `ExecutionPlan.CurrentMetadata` (attempt and step index), * and retry timing is derived per step (the first attempt uses the remaining * attempts schedule; later retries apply the step schedule at least once). * - * @example + * **Example** (Retrying with an execution plan) + * * ```ts - * import { Effect, ExecutionPlan, Layer, Context } from "effect" + * import { Context, Effect, ExecutionPlan, Layer } from "effect" * * const Endpoint = Context.Service<{ url: string }>("Endpoint") * @@ -7522,21 +7760,24 @@ export const ignoreCause: < * const program = Effect.withExecutionPlan(fetchUrl, plan) * ``` * + * @category fallback * @since 3.16.0 - * @category Fallback */ export const withExecutionPlan: { /** - * Apply an `ExecutionPlan` to an effect, retrying with step-provided resources + * Applies an `ExecutionPlan` to an effect, retrying with step-provided resources * until it succeeds or the plan is exhausted. * + * **Details** + * * Each attempt updates `ExecutionPlan.CurrentMetadata` (attempt and step index), * and retry timing is derived per step (the first attempt uses the remaining * attempts schedule; later retries apply the step schedule at least once). * - * @example + * **Example** (Retrying with an execution plan) + * * ```ts - * import { Effect, ExecutionPlan, Layer, Context } from "effect" + * import { Context, Effect, ExecutionPlan, Layer } from "effect" * * const Endpoint = Context.Service<{ url: string }>("Endpoint") * @@ -7556,8 +7797,8 @@ export const withExecutionPlan: { * const program = Effect.withExecutionPlan(fetchUrl, plan) * ``` * + * @category fallback * @since 3.16.0 - * @category Fallback */ ( plan: ExecutionPlan<{ provides: Provides; input: Input; error: PlanE; requirements: PlanR }> @@ -7565,16 +7806,19 @@ export const withExecutionPlan: { effect: Effect ) => Effect | PlanR> /** - * Apply an `ExecutionPlan` to an effect, retrying with step-provided resources + * Applies an `ExecutionPlan` to an effect, retrying with step-provided resources * until it succeeds or the plan is exhausted. * + * **Details** + * * Each attempt updates `ExecutionPlan.CurrentMetadata` (attempt and step index), * and retry timing is derived per step (the first attempt uses the remaining * attempts schedule; later retries apply the step schedule at least once). * - * @example + * **Example** (Retrying with an execution plan) + * * ```ts - * import { Effect, ExecutionPlan, Layer, Context } from "effect" + * import { Context, Effect, ExecutionPlan, Layer } from "effect" * * const Endpoint = Context.Service<{ url: string }>("Endpoint") * @@ -7594,8 +7838,8 @@ export const withExecutionPlan: { * const program = Effect.withExecutionPlan(fetchUrl, plan) * ``` * + * @category fallback * @since 3.16.0 - * @category Fallback */ ( effect: Effect, @@ -7606,11 +7850,13 @@ export const withExecutionPlan: { /** * Runs an effect and reports any errors to the configured `ErrorReporter`s. * + * **Details** + * * If the `defectsOnly` option is set to `true`, only defects (unrecoverable * errors) will be reported, while regular failures will be ignored. * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const withErrorReporting: < Arg extends Effect | { readonly defectsOnly?: boolean | undefined } | undefined = { @@ -7627,23 +7873,18 @@ export const withErrorReporting: < // ----------------------------------------------------------------------------- /** - * Replaces the original failure with a success value, ensuring the effect - * cannot fail. + * Recovers from a typed failure by producing a fallback success value. * - * `orElseSucceed` allows you to replace the failure of an effect with a - * success value. If the effect fails, it will instead succeed with the provided - * value, ensuring the effect always completes successfully. This is useful when - * you want to guarantee a successful result regardless of whether the original - * effect failed. + * **Details** + * + * If the source effect succeeds, its value is preserved. If it fails in the + * error channel, `orElseSucceed` evaluates the fallback and succeeds with that + * value, removing the typed error from the returned effect. * - * The function ensures that any failure is effectively "swallowed" and replaced - * by a successful value, which can be helpful for providing default values in - * case of failure. + * Defects and interruptions are not recovered by this operator. * - * **Important**: This function only applies to failed effects. If the effect - * already succeeds, it will remain unchanged. + * **Example** (Replacing failures with a value) * - * @example * ```ts * import { Effect } from "effect" * @@ -7664,8 +7905,8 @@ export const withErrorReporting: < * // { _id: 'Exit', _tag: 'Success', value: 18 } * ``` * + * @category fallback * @since 2.0.0 - * @category Fallback */ export const orElseSucceed: { // ----------------------------------------------------------------------------- @@ -7673,23 +7914,18 @@ export const orElseSucceed: { // ----------------------------------------------------------------------------- /** - * Replaces the original failure with a success value, ensuring the effect - * cannot fail. + * Recovers from a typed failure by producing a fallback success value. + * + * **Details** * - * `orElseSucceed` allows you to replace the failure of an effect with a - * success value. If the effect fails, it will instead succeed with the provided - * value, ensuring the effect always completes successfully. This is useful when - * you want to guarantee a successful result regardless of whether the original - * effect failed. + * If the source effect succeeds, its value is preserved. If it fails in the + * error channel, `orElseSucceed` evaluates the fallback and succeeds with that + * value, removing the typed error from the returned effect. * - * The function ensures that any failure is effectively "swallowed" and replaced - * by a successful value, which can be helpful for providing default values in - * case of failure. + * Defects and interruptions are not recovered by this operator. * - * **Important**: This function only applies to failed effects. If the effect - * already succeeds, it will remain unchanged. + * **Example** (Replacing failures with a value) * - * @example * ```ts * import { Effect } from "effect" * @@ -7710,8 +7946,8 @@ export const orElseSucceed: { * // { _id: 'Exit', _tag: 'Success', value: 18 } * ``` * + * @category fallback * @since 2.0.0 - * @category Fallback */ (evaluate: LazyArg): (self: Effect) => Effect // ----------------------------------------------------------------------------- @@ -7719,23 +7955,18 @@ export const orElseSucceed: { // ----------------------------------------------------------------------------- /** - * Replaces the original failure with a success value, ensuring the effect - * cannot fail. + * Recovers from a typed failure by producing a fallback success value. * - * `orElseSucceed` allows you to replace the failure of an effect with a - * success value. If the effect fails, it will instead succeed with the provided - * value, ensuring the effect always completes successfully. This is useful when - * you want to guarantee a successful result regardless of whether the original - * effect failed. + * **Details** + * + * If the source effect succeeds, its value is preserved. If it fails in the + * error channel, `orElseSucceed` evaluates the fallback and succeeds with that + * value, removing the typed error from the returned effect. * - * The function ensures that any failure is effectively "swallowed" and replaced - * by a successful value, which can be helpful for providing default values in - * case of failure. + * Defects and interruptions are not recovered by this operator. * - * **Important**: This function only applies to failed effects. If the effect - * already succeeds, it will remain unchanged. + * **Example** (Replacing failures with a value) * - * @example * ```ts * import { Effect } from "effect" * @@ -7756,8 +7987,8 @@ export const orElseSucceed: { * // { _id: 'Exit', _tag: 'Success', value: 18 } * ``` * + * @category fallback * @since 2.0.0 - * @category Fallback */ (self: Effect, evaluate: LazyArg): Effect } = internal.orElseSucceed @@ -7766,6 +7997,12 @@ export const orElseSucceed: { * Runs a sequence of effects and returns the result of the first successful * one. * + * **When to use** + * + * Use when you have prioritized fallback `Effect`s, such as attempting + * multiple APIs, reading configuration from several sources, or trying + * alternative resource locations in order. + * * **Details** * * This function executes the provided effects in sequence, stopping at the @@ -7776,13 +8013,8 @@ export const orElseSucceed: { * effect. If the collection is empty, the returned effect defects with an * `Error` whose message is `"Received an empty collection of effects"`. * - * **When to Use** + * **Example** (Trying alternatives until one succeeds) * - * Use `firstSuccessOf` when you have prioritized fallback strategies, such as - * attempting multiple APIs, reading configuration from several sources, or - * trying alternative resource locations in order. - * - * @example * ```ts * import { Effect } from "effect" * @@ -7802,8 +8034,8 @@ export const orElseSucceed: { * // Output: "secondary result" * ``` * + * @category fallback * @since 2.0.0 - * @category Fallback */ export const firstSuccessOf: >( effects: Iterable @@ -7817,17 +8049,25 @@ export const firstSuccessOf: >( * Adds a time limit to an effect, triggering a timeout if the effect exceeds * the duration. * + * **When to use** + * + * Use when you need a timeout of an `Effect` to be represented as a typed + * failure. + * + * **Details** + * * The `timeout` function allows you to specify a time limit for an * effect's execution. If the effect does not complete within the given time, a * `TimeoutException` is raised. This can be useful for controlling how long * your program waits for a task to finish, ensuring that it doesn't hang * indefinitely if the task takes too long. * - * @see {@link timeoutFail} for a version that raises a custom error. - * @see {@link timeoutFailCause} for a version that raises a custom defect. - * @see {@link timeoutTo} for a version that allows specifying both success and timeout handlers. + * **Gotchas** + * + * If the timeout wins, the source effect is interrupted. + * + * **Example** (Failing when work takes too long) * - * @example * ```ts * import { Effect } from "effect" * @@ -7856,8 +8096,11 @@ export const firstSuccessOf: >( * // } * ``` * + * @see {@link timeoutOption} for returning `Option.none` on timeout. + * @see {@link timeoutOrElse} for a version that allows specifying both success and timeout handlers. + * + * @category delays & timeouts * @since 2.0.0 - * @category Delays & Timeouts */ export const timeout: { // ----------------------------------------------------------------------------- @@ -7868,17 +8111,25 @@ export const timeout: { * Adds a time limit to an effect, triggering a timeout if the effect exceeds * the duration. * + * **When to use** + * + * Use when you need a timeout of an `Effect` to be represented as a typed + * failure. + * + * **Details** + * * The `timeout` function allows you to specify a time limit for an * effect's execution. If the effect does not complete within the given time, a * `TimeoutException` is raised. This can be useful for controlling how long * your program waits for a task to finish, ensuring that it doesn't hang * indefinitely if the task takes too long. * - * @see {@link timeoutFail} for a version that raises a custom error. - * @see {@link timeoutFailCause} for a version that raises a custom defect. - * @see {@link timeoutTo} for a version that allows specifying both success and timeout handlers. + * **Gotchas** + * + * If the timeout wins, the source effect is interrupted. + * + * **Example** (Failing when work takes too long) * - * @example * ```ts * import { Effect } from "effect" * @@ -7907,8 +8158,11 @@ export const timeout: { * // } * ``` * + * @see {@link timeoutOption} for returning `Option.none` on timeout. + * @see {@link timeoutOrElse} for a version that allows specifying both success and timeout handlers. + * + * @category delays & timeouts * @since 2.0.0 - * @category Delays & Timeouts */ (duration: Duration.Input): (self: Effect) => Effect // ----------------------------------------------------------------------------- @@ -7919,17 +8173,25 @@ export const timeout: { * Adds a time limit to an effect, triggering a timeout if the effect exceeds * the duration. * + * **When to use** + * + * Use when you need a timeout of an `Effect` to be represented as a typed + * failure. + * + * **Details** + * * The `timeout` function allows you to specify a time limit for an * effect's execution. If the effect does not complete within the given time, a * `TimeoutException` is raised. This can be useful for controlling how long * your program waits for a task to finish, ensuring that it doesn't hang * indefinitely if the task takes too long. * - * @see {@link timeoutFail} for a version that raises a custom error. - * @see {@link timeoutFailCause} for a version that raises a custom defect. - * @see {@link timeoutTo} for a version that allows specifying both success and timeout handlers. + * **Gotchas** + * + * If the timeout wins, the source effect is interrupted. + * + * **Example** (Failing when work takes too long) * - * @example * ```ts * import { Effect } from "effect" * @@ -7958,32 +8220,32 @@ export const timeout: { * // } * ``` * + * @see {@link timeoutOption} for returning `Option.none` on timeout. + * @see {@link timeoutOrElse} for a version that allows specifying both success and timeout handlers. + * + * @category delays & timeouts * @since 2.0.0 - * @category Delays & Timeouts */ (self: Effect, duration: Duration.Input): Effect } = internal.timeout /** - * Handles timeouts by returning an `Option` that represents either the result - * or a timeout. + * Runs an effect with a time limit and represents only the timeout case as + * `Option.none`. * - * The `timeoutOption` function provides a way to gracefully handle - * timeouts by wrapping the outcome of an effect in an `Option` type. If the - * effect completes within the specified time, it returns a `Some` containing - * the result. If the effect times out, it returns a `None`, allowing you to - * treat the timeout as a regular result instead of throwing an error. + * **When to use** * - * This is useful when you want to handle timeouts without causing the program - * to fail, making it easier to manage situations where you expect tasks might - * take too long but want to continue executing other tasks. + * Use when a timeout of an `Effect` should be handled as `Option.none`. * - * @see {@link timeout} for a version that raises a `TimeoutException`. - * @see {@link timeoutFail} for a version that raises a custom error. - * @see {@link timeoutFailCause} for a version that raises a custom defect. - * @see {@link timeoutTo} for a version that allows specifying both success and timeout handlers. + * **Details** + * + * If the source effect succeeds before the timeout, the returned effect + * succeeds with `Option.some(value)`. If the timeout wins, the source effect is + * interrupted and the returned effect succeeds with `Option.none`. If the + * source effect fails before the timeout, that failure is preserved. + * + * **Example** (Returning None on timeout) * - * @example * ```ts * import { Effect } from "effect" * @@ -8010,30 +8272,30 @@ export const timeout: { * // ] * ``` * + * @see {@link timeout} for a version that raises a `TimeoutException`. + * @see {@link timeoutOrElse} for a version that allows specifying both success and timeout handlers. + * + * @category delays & timeouts * @since 3.1.0 - * @category Delays & Timeouts */ export const timeoutOption: { /** - * Handles timeouts by returning an `Option` that represents either the result - * or a timeout. + * Runs an effect with a time limit and represents only the timeout case as + * `Option.none`. * - * The `timeoutOption` function provides a way to gracefully handle - * timeouts by wrapping the outcome of an effect in an `Option` type. If the - * effect completes within the specified time, it returns a `Some` containing - * the result. If the effect times out, it returns a `None`, allowing you to - * treat the timeout as a regular result instead of throwing an error. + * **When to use** * - * This is useful when you want to handle timeouts without causing the program - * to fail, making it easier to manage situations where you expect tasks might - * take too long but want to continue executing other tasks. + * Use when a timeout of an `Effect` should be handled as `Option.none`. * - * @see {@link timeout} for a version that raises a `TimeoutException`. - * @see {@link timeoutFail} for a version that raises a custom error. - * @see {@link timeoutFailCause} for a version that raises a custom defect. - * @see {@link timeoutTo} for a version that allows specifying both success and timeout handlers. + * **Details** + * + * If the source effect succeeds before the timeout, the returned effect + * succeeds with `Option.some(value)`. If the timeout wins, the source effect is + * interrupted and the returned effect succeeds with `Option.none`. If the + * source effect fails before the timeout, that failure is preserved. + * + * **Example** (Returning None on timeout) * - * @example * ```ts * import { Effect } from "effect" * @@ -8060,30 +8322,30 @@ export const timeoutOption: { * // ] * ``` * + * @see {@link timeout} for a version that raises a `TimeoutException`. + * @see {@link timeoutOrElse} for a version that allows specifying both success and timeout handlers. + * + * @category delays & timeouts * @since 3.1.0 - * @category Delays & Timeouts */ (duration: Duration.Input): (self: Effect) => Effect, E, R> /** - * Handles timeouts by returning an `Option` that represents either the result - * or a timeout. + * Runs an effect with a time limit and represents only the timeout case as + * `Option.none`. * - * The `timeoutOption` function provides a way to gracefully handle - * timeouts by wrapping the outcome of an effect in an `Option` type. If the - * effect completes within the specified time, it returns a `Some` containing - * the result. If the effect times out, it returns a `None`, allowing you to - * treat the timeout as a regular result instead of throwing an error. + * **When to use** * - * This is useful when you want to handle timeouts without causing the program - * to fail, making it easier to manage situations where you expect tasks might - * take too long but want to continue executing other tasks. + * Use when a timeout of an `Effect` should be handled as `Option.none`. * - * @see {@link timeout} for a version that raises a `TimeoutException`. - * @see {@link timeoutFail} for a version that raises a custom error. - * @see {@link timeoutFailCause} for a version that raises a custom defect. - * @see {@link timeoutTo} for a version that allows specifying both success and timeout handlers. + * **Details** + * + * If the source effect succeeds before the timeout, the returned effect + * succeeds with `Option.some(value)`. If the timeout wins, the source effect is + * interrupted and the returned effect succeeds with `Option.none`. If the + * source effect fails before the timeout, that failure is preserved. + * + * **Example** (Returning None on timeout) * - * @example * ```ts * import { Effect } from "effect" * @@ -8110,8 +8372,11 @@ export const timeoutOption: { * // ] * ``` * + * @see {@link timeout} for a version that raises a `TimeoutException`. + * @see {@link timeoutOrElse} for a version that allows specifying both success and timeout handlers. + * + * @category delays & timeouts * @since 3.1.0 - * @category Delays & Timeouts */ (self: Effect, duration: Duration.Input): Effect, E, R> } = internal.timeoutOption @@ -8119,10 +8384,22 @@ export const timeoutOption: { /** * Applies a timeout to an effect, with a fallback effect executed if the timeout is reached. * - * This function is useful when you want to set a maximum duration for an operation - * and provide an alternative action if the timeout is exceeded. + * **When to use** + * + * Use when a timeout of an `Effect` should switch to a fallback effect. + * + * **Details** + * + * The fallback effect is created lazily by `orElse` and may introduce its own + * success, failure, and requirement types. + * + * **Gotchas** + * + * If the timeout wins, the source effect is interrupted before the fallback is + * run. + * + * **Example** (Falling back on timeout) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -8149,17 +8426,32 @@ export const timeoutOption: { * // Cached result * ``` * - * @since 3.1.0 - * @category Delays & Timeouts + * @see {@link timeout} for failing with a `TimeoutException`. + * @see {@link timeoutOption} for returning `Option.none` on timeout. + * + * @category delays & timeouts + * @since 4.0.0 */ export const timeoutOrElse: { /** * Applies a timeout to an effect, with a fallback effect executed if the timeout is reached. * - * This function is useful when you want to set a maximum duration for an operation - * and provide an alternative action if the timeout is exceeded. + * **When to use** + * + * Use when a timeout of an `Effect` should switch to a fallback effect. + * + * **Details** + * + * The fallback effect is created lazily by `orElse` and may introduce its own + * success, failure, and requirement types. + * + * **Gotchas** + * + * If the timeout wins, the source effect is interrupted before the fallback is + * run. + * + * **Example** (Falling back on timeout) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -8186,8 +8478,11 @@ export const timeoutOrElse: { * // Cached result * ``` * - * @since 3.1.0 - * @category Delays & Timeouts + * @see {@link timeout} for failing with a `TimeoutException`. + * @see {@link timeoutOption} for returning `Option.none` on timeout. + * + * @category delays & timeouts + * @since 4.0.0 */ ( options: { @@ -8198,10 +8493,22 @@ export const timeoutOrElse: { /** * Applies a timeout to an effect, with a fallback effect executed if the timeout is reached. * - * This function is useful when you want to set a maximum duration for an operation - * and provide an alternative action if the timeout is exceeded. + * **When to use** + * + * Use when a timeout of an `Effect` should switch to a fallback effect. + * + * **Details** + * + * The fallback effect is created lazily by `orElse` and may introduce its own + * success, failure, and requirement types. + * + * **Gotchas** + * + * If the timeout wins, the source effect is interrupted before the fallback is + * run. + * + * **Example** (Falling back on timeout) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -8228,8 +8535,11 @@ export const timeoutOrElse: { * // Cached result * ``` * - * @since 3.1.0 - * @category Delays & Timeouts + * @see {@link timeout} for failing with a `TimeoutException`. + * @see {@link timeoutOption} for returning `Option.none` on timeout. + * + * @category delays & timeouts + * @since 4.0.0 */ ( self: Effect, @@ -8244,7 +8554,8 @@ export const timeoutOrElse: { * Returns an effect that is delayed from this effect by the specified * `Duration`. * - * @example + * **Example** (Delaying an effect) + * * ```ts * import { Console, Effect } from "effect" * @@ -8257,15 +8568,16 @@ export const timeoutOrElse: { * // Waits 1 second, then prints: "Delayed message" * ``` * + * @category delays & timeouts * @since 2.0.0 - * @category Delays & Timeouts */ export const delay: { /** * Returns an effect that is delayed from this effect by the specified * `Duration`. * - * @example + * **Example** (Delaying an effect) + * * ```ts * import { Console, Effect } from "effect" * @@ -8278,15 +8590,16 @@ export const delay: { * // Waits 1 second, then prints: "Delayed message" * ``` * + * @category delays & timeouts * @since 2.0.0 - * @category Delays & Timeouts */ (duration: Duration.Input): (self: Effect) => Effect /** * Returns an effect that is delayed from this effect by the specified * `Duration`. * - * @example + * **Example** (Delaying an effect) + * * ```ts * import { Console, Effect } from "effect" * @@ -8299,17 +8612,18 @@ export const delay: { * // Waits 1 second, then prints: "Delayed message" * ``` * + * @category delays & timeouts * @since 2.0.0 - * @category Delays & Timeouts */ (self: Effect, duration: Duration.Input): Effect } = internal.delay /** - * Returns an effect that suspends for the specified duration. This method is - * asynchronous, and does not actually block the fiber executing the effect. + * Returns an effect that suspends the current fiber for the specified duration + * without blocking a JavaScript thread. + * + * **Example** (Pausing without blocking) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -8324,18 +8638,21 @@ export const delay: { * // Output: "End" (after 2 seconds) * ``` * + * @category delays & timeouts * @since 2.0.0 - * @category Delays & Timeouts */ export const sleep: (duration: Duration.Input) => Effect = internal.sleep /** - * Measures the runtime of an effect and returns the duration with its result. + * Returns the runtime duration of an effect together with its result. + * + * **Details** * * The original success, failure, or interruption is preserved; only the success * value is paired with the duration. * - * @example + * **Example** (Measuring execution time) + * * ```ts * import { Console, Duration, Effect } from "effect" * @@ -8345,8 +8662,8 @@ export const sleep: (duration: Duration.Input) => Effect = internal.sleep * }) * ``` * + * @category delays & timeouts * @since 2.0.0 - * @category Delays & Timeouts */ export const timed: (self: Effect) => Effect<[duration: Duration.Duration, result: A], E, R> = internal.timed @@ -8356,27 +8673,22 @@ export const timed: (self: Effect) => Effect<[duration: Durati // ----------------------------------------------------------------------------- /** - * Races multiple effects and returns the first successful result. - * - * **Details** + * Runs multiple effects concurrently and returns the first successful result. * - * This function runs multiple effects concurrently and returns the result of - * the first one to succeed. If one effect succeeds, the others will be - * interrupted. + * **When to use** * - * If none of the effects succeed, the function will fail with the last error - * encountered. + * Use when early failures should be ignored until a success occurs + * or all effects fail. * - * **When to Use** + * **Details** * - * This is useful when you want to race multiple effects, but only care about - * the first one to succeed. It is commonly used in cases like timeouts, - * retries, or when you want to optimize for the faster response without - * worrying about the other effects. + * Early failures do not finish the race; `raceAll` keeps waiting until one + * effect succeeds or every effect has failed. When one effect succeeds, the + * remaining effects are interrupted. If every effect fails, the returned effect + * fails with a cause containing the collected failure reasons. * - * @see {@link race} for a version that handles only two effects. + * **Example** (Racing many effects) * - * @example * ```ts * import { Duration, Effect } from "effect" * @@ -8391,8 +8703,9 @@ export const timed: (self: Effect) => Effect<[duration: Durati * // Result: "Fast" (after ~100ms) * ``` * + * @see {@link race} for a version that handles only two effects. + * @category racing * @since 2.0.0 - * @category Racing */ export const raceAll: >( all: Iterable, @@ -8406,15 +8719,17 @@ export const raceAll: >( ) => Effect, Error, Services> = internal.raceAll /** - * Races multiple effects and returns the first successful result. + * Runs multiple effects concurrently and completes with the first effect to + * finish, whether it succeeds or fails. * * **Details** * - * Similar to `raceAll`, this function runs multiple effects concurrently - * and returns the result of the first one to succeed. If one effect succeeds, - * the others will be interrupted. + * After the first effect completes, all remaining effects are interrupted. Use + * `raceAll` when early failures should be ignored until a success occurs or + * all effects fail. + * + * **Example** (Taking the first settled result) * - * @example * ```ts * import { Duration, Effect } from "effect" * @@ -8429,8 +8744,8 @@ export const raceAll: >( * // Result: "First" (after ~200ms, even though effect2 completes first but fails) * ``` * + * @category racing * @since 4.0.0 - * @category Racing */ export const raceAllFirst: >( all: Iterable, @@ -8446,10 +8761,13 @@ export const raceAllFirst: >( /** * Races two effects and returns the first successful result. * + * **Details** + * * If one effect succeeds, the other is interrupted and `onWinner` can observe the * winning fiber. If both fail, the race fails. * - * @example + * **Example** (Racing two effects) + * * ```ts * import { Console, Duration, Effect } from "effect" * @@ -8465,17 +8783,20 @@ export const raceAllFirst: >( * // Output: winner: slow-success * ``` * + * @category racing * @since 2.0.0 - * @category Racing */ export const race: { /** * Races two effects and returns the first successful result. * + * **Details** + * * If one effect succeeds, the other is interrupted and `onWinner` can observe the * winning fiber. If both fail, the race fails. * - * @example + * **Example** (Racing two effects) + * * ```ts * import { Console, Duration, Effect } from "effect" * @@ -8491,8 +8812,8 @@ export const race: { * // Output: winner: slow-success * ``` * + * @category racing * @since 2.0.0 - * @category Racing */ ( that: Effect, @@ -8505,10 +8826,13 @@ export const race: { /** * Races two effects and returns the first successful result. * + * **Details** + * * If one effect succeeds, the other is interrupted and `onWinner` can observe the * winning fiber. If both fail, the race fails. * - * @example + * **Example** (Racing two effects) + * * ```ts * import { Console, Duration, Effect } from "effect" * @@ -8524,8 +8848,8 @@ export const race: { * // Output: winner: slow-success * ``` * + * @category racing * @since 2.0.0 - * @category Racing */ ( self: Effect, @@ -8542,9 +8866,17 @@ export const race: { * Races two effects and returns the result of the first one to complete, whether * it succeeds or fails. * + * **When to use** + * + * Use when any completion, including failure, should decide the race and + * interrupt the losing effect. + * + * **Details** + * * The losing effect is interrupted, and `onWinner` can observe the winning fiber. * - * @example + * **Example** (Observing the winning fiber) + * * ```ts * import { Console, Duration, Effect } from "effect" * @@ -8563,17 +8895,25 @@ export const race: { * // Output: failed: fast-fail * ``` * + * @category racing * @since 2.0.0 - * @category Racing */ export const raceFirst: { /** * Races two effects and returns the result of the first one to complete, whether * it succeeds or fails. * + * **When to use** + * + * Use when any completion, including failure, should decide the race and + * interrupt the losing effect. + * + * **Details** + * * The losing effect is interrupted, and `onWinner` can observe the winning fiber. * - * @example + * **Example** (Observing the winning fiber) + * * ```ts * import { Console, Duration, Effect } from "effect" * @@ -8592,8 +8932,8 @@ export const raceFirst: { * // Output: failed: fast-fail * ``` * + * @category racing * @since 2.0.0 - * @category Racing */ ( that: Effect, @@ -8607,9 +8947,17 @@ export const raceFirst: { * Races two effects and returns the result of the first one to complete, whether * it succeeds or fails. * + * **When to use** + * + * Use when any completion, including failure, should decide the race and + * interrupt the losing effect. + * + * **Details** + * * The losing effect is interrupted, and `onWinner` can observe the winning fiber. * - * @example + * **Example** (Observing the winning fiber) + * * ```ts * import { Console, Duration, Effect } from "effect" * @@ -8628,8 +8976,8 @@ export const raceFirst: { * // Output: failed: fast-fail * ``` * + * @category racing * @since 2.0.0 - * @category Racing */ ( self: Effect, @@ -8650,7 +8998,8 @@ export const raceFirst: { * Filters elements of an iterable using a predicate, refinement, or effectful * predicate. * - * @example + * **Example** (Filtering success values) + * * ```ts * import { Effect } from "effect" * @@ -8663,8 +9012,8 @@ export const raceFirst: { * // Use Effect.filterMapEffect for effectful Filter.Filter callbacks * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ export const filter: { // ----------------------------------------------------------------------------- @@ -8675,7 +9024,8 @@ export const filter: { * Filters elements of an iterable using a predicate, refinement, or effectful * predicate. * - * @example + * **Example** (Filtering success values) + * * ```ts * import { Effect } from "effect" * @@ -8688,8 +9038,8 @@ export const filter: { * // Use Effect.filterMapEffect for effectful Filter.Filter callbacks * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (refinement: Predicate.Refinement, B>): (elements: Iterable) => Effect> // ----------------------------------------------------------------------------- @@ -8700,7 +9050,8 @@ export const filter: { * Filters elements of an iterable using a predicate, refinement, or effectful * predicate. * - * @example + * **Example** (Filtering success values) + * * ```ts * import { Effect } from "effect" * @@ -8713,8 +9064,8 @@ export const filter: { * // Use Effect.filterMapEffect for effectful Filter.Filter callbacks * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (predicate: Predicate.Predicate>): (elements: Iterable) => Effect> // ----------------------------------------------------------------------------- @@ -8725,7 +9076,8 @@ export const filter: { * Filters elements of an iterable using a predicate, refinement, or effectful * predicate. * - * @example + * **Example** (Filtering success values) + * * ```ts * import { Effect } from "effect" * @@ -8738,8 +9090,8 @@ export const filter: { * // Use Effect.filterMapEffect for effectful Filter.Filter callbacks * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ ( predicate: (a: NoInfer, i: number) => Effect, @@ -8753,7 +9105,8 @@ export const filter: { * Filters elements of an iterable using a predicate, refinement, or effectful * predicate. * - * @example + * **Example** (Filtering success values) + * * ```ts * import { Effect } from "effect" * @@ -8766,8 +9119,8 @@ export const filter: { * // Use Effect.filterMapEffect for effectful Filter.Filter callbacks * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (elements: Iterable, refinement: Predicate.Refinement): Effect> // ----------------------------------------------------------------------------- @@ -8778,7 +9131,8 @@ export const filter: { * Filters elements of an iterable using a predicate, refinement, or effectful * predicate. * - * @example + * **Example** (Filtering success values) + * * ```ts * import { Effect } from "effect" * @@ -8791,8 +9145,8 @@ export const filter: { * // Use Effect.filterMapEffect for effectful Filter.Filter callbacks * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (elements: Iterable, predicate: Predicate.Predicate): Effect> // ----------------------------------------------------------------------------- @@ -8803,7 +9157,8 @@ export const filter: { * Filters elements of an iterable using a predicate, refinement, or effectful * predicate. * - * @example + * **Example** (Filtering success values) + * * ```ts * import { Effect } from "effect" * @@ -8816,8 +9171,8 @@ export const filter: { * // Use Effect.filterMapEffect for effectful Filter.Filter callbacks * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ ( iterable: Iterable, @@ -8829,48 +9184,141 @@ export const filter: { /** * Filters and maps elements of an iterable with a `Filter`. * - * @since 4.0.0 - * @category Filtering + * **When to use** + * + * Use when you need to filter an iterable with a `Filter` inside an `Effect`, + * collecting each filter success value. + * + * **Details** + * + * `Result.succeed` values are collected in the returned array, and + * `Result.fail` values are skipped. + * + * @see {@link filter} for keeping original elements with a boolean predicate, refinement, or effectful predicate + * @see {@link filterMapEffect} for using an effectful `Filter` + * + * @category filtering + * @since 2.0.0 */ export const filterMap: { /** * Filters and maps elements of an iterable with a `Filter`. * - * @since 4.0.0 - * @category Filtering + * **When to use** + * + * Use when you need to filter an iterable with a `Filter` inside an `Effect`, + * collecting each filter success value. + * + * **Details** + * + * `Result.succeed` values are collected in the returned array, and + * `Result.fail` values are skipped. + * + * @see {@link filter} for keeping original elements with a boolean predicate, refinement, or effectful predicate + * @see {@link filterMapEffect} for using an effectful `Filter` + * + * @category filtering + * @since 2.0.0 */ (filter: Filter.Filter, B, X>): (elements: Iterable) => Effect> /** * Filters and maps elements of an iterable with a `Filter`. * - * @since 4.0.0 - * @category Filtering + * **When to use** + * + * Use when you need to filter an iterable with a `Filter` inside an `Effect`, + * collecting each filter success value. + * + * **Details** + * + * `Result.succeed` values are collected in the returned array, and + * `Result.fail` values are skipped. + * + * @see {@link filter} for keeping original elements with a boolean predicate, refinement, or effectful predicate + * @see {@link filterMapEffect} for using an effectful `Filter` + * + * @category filtering + * @since 2.0.0 */ (elements: Iterable, filter: Filter.Filter, B, X>): Effect> } = internal.filterMap /** - * Effectfully filters and maps elements of an iterable with a `FilterEffect`. + * Filters and maps elements of an iterable effectfully with a `FilterEffect`. + * + * **When to use** + * + * Use when you need to filter each iterable element effectfully and transform + * accepted elements into successful output values. * + * **Details** + * + * `Result.succeed` values are collected in the returned array, and + * `Result.fail` values are skipped. + * + * **Gotchas** + * + * With concurrent execution, successful values are collected in completion + * order, not input order. + * + * @see {@link filterMap} for using a synchronous `Filter` + * @see {@link filter} for keeping original elements with a predicate + * + * @category filtering * @since 4.0.0 - * @category Filtering */ export const filterMapEffect: { /** - * Effectfully filters and maps elements of an iterable with a `FilterEffect`. + * Filters and maps elements of an iterable effectfully with a `FilterEffect`. + * + * **When to use** + * + * Use when you need to filter each iterable element effectfully and transform + * accepted elements into successful output values. * + * **Details** + * + * `Result.succeed` values are collected in the returned array, and + * `Result.fail` values are skipped. + * + * **Gotchas** + * + * With concurrent execution, successful values are collected in completion + * order, not input order. + * + * @see {@link filterMap} for using a synchronous `Filter` + * @see {@link filter} for keeping original elements with a predicate + * + * @category filtering * @since 4.0.0 - * @category Filtering */ ( filter: Filter.FilterEffect, B, X, E, R>, options?: { readonly concurrency?: Concurrency | undefined } ): (elements: Iterable) => Effect, E, R> /** - * Effectfully filters and maps elements of an iterable with a `FilterEffect`. + * Filters and maps elements of an iterable effectfully with a `FilterEffect`. + * + * **When to use** + * + * Use when you need to filter each iterable element effectfully and transform + * accepted elements into successful output values. * + * **Details** + * + * `Result.succeed` values are collected in the returned array, and + * `Result.fail` values are skipped. + * + * **Gotchas** + * + * With concurrent execution, successful values are collected in completion + * order, not input order. + * + * @see {@link filterMap} for using a synchronous `Filter` + * @see {@link filter} for keeping original elements with a predicate + * + * @category filtering * @since 4.0.0 - * @category Filtering */ ( elements: Iterable, @@ -8882,6 +9330,11 @@ export const filterMapEffect: { /** * Filters an effect, providing an alternative effect if the predicate fails. * + * **When to use** + * + * Use when a successful value that fails a predicate should continue with an + * effectful fallback instead of failing the effect. + * * **Details** * * This function applies a predicate to the result of an effect. If the @@ -8889,7 +9342,8 @@ export const filterMapEffect: { * `orElse` effect can produce an alternative value or perform additional * computations. * - * @example + * **Example** (Filtering with a fallback effect) + * * ```ts * import { Effect } from "effect" * @@ -8906,13 +9360,18 @@ export const filterMapEffect: { * // Result: "Number 5 is odd" (since 5 is not even) * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ export const filterOrElse: { /** * Filters an effect, providing an alternative effect if the predicate fails. * + * **When to use** + * + * Use when a successful value that fails a predicate should continue with an + * effectful fallback instead of failing the effect. + * * **Details** * * This function applies a predicate to the result of an effect. If the @@ -8920,7 +9379,8 @@ export const filterOrElse: { * `orElse` effect can produce an alternative value or perform additional * computations. * - * @example + * **Example** (Filtering with a fallback effect) + * * ```ts * import { Effect } from "effect" * @@ -8937,8 +9397,8 @@ export const filterOrElse: { * // Result: "Number 5 is odd" (since 5 is not even) * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ ( refinement: Predicate.Refinement, B>, @@ -8947,6 +9407,11 @@ export const filterOrElse: { /** * Filters an effect, providing an alternative effect if the predicate fails. * + * **When to use** + * + * Use when a successful value that fails a predicate should continue with an + * effectful fallback instead of failing the effect. + * * **Details** * * This function applies a predicate to the result of an effect. If the @@ -8954,7 +9419,8 @@ export const filterOrElse: { * `orElse` effect can produce an alternative value or perform additional * computations. * - * @example + * **Example** (Filtering with a fallback effect) + * * ```ts * import { Effect } from "effect" * @@ -8971,8 +9437,8 @@ export const filterOrElse: { * // Result: "Number 5 is odd" (since 5 is not even) * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ ( predicate: Predicate.Predicate>, @@ -8981,6 +9447,11 @@ export const filterOrElse: { /** * Filters an effect, providing an alternative effect if the predicate fails. * + * **When to use** + * + * Use when a successful value that fails a predicate should continue with an + * effectful fallback instead of failing the effect. + * * **Details** * * This function applies a predicate to the result of an effect. If the @@ -8988,7 +9459,8 @@ export const filterOrElse: { * `orElse` effect can produce an alternative value or perform additional * computations. * - * @example + * **Example** (Filtering with a fallback effect) + * * ```ts * import { Effect } from "effect" * @@ -9005,8 +9477,8 @@ export const filterOrElse: { * // Result: "Number 5 is odd" (since 5 is not even) * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ ( self: Effect, @@ -9016,6 +9488,11 @@ export const filterOrElse: { /** * Filters an effect, providing an alternative effect if the predicate fails. * + * **When to use** + * + * Use when a successful value that fails a predicate should continue with an + * effectful fallback instead of failing the effect. + * * **Details** * * This function applies a predicate to the result of an effect. If the @@ -9023,7 +9500,8 @@ export const filterOrElse: { * `orElse` effect can produce an alternative value or perform additional * computations. * - * @example + * **Example** (Filtering with a fallback effect) + * * ```ts * import { Effect } from "effect" * @@ -9040,8 +9518,8 @@ export const filterOrElse: { * // Result: "Number 5 is odd" (since 5 is not even) * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ ( self: Effect, @@ -9053,15 +9531,43 @@ export const filterOrElse: { /** * Filters an effect with a `Filter`, providing an alternative effect on failure. * + * **When to use** + * + * Use when a successful effect value should be accepted and transformed by a + * `Filter`, while rejected values should continue with an alternative effect + * built from the filter failure. + * + * **Details** + * + * `Result.succeed` becomes the returned success value, and `Result.fail` is + * passed to `orElse`. + * + * @see {@link filterOrElse} for using a predicate and fallback effect + * @see {@link filterMapOrFail} for failing the effect when the filter fails + * + * @category filtering * @since 4.0.0 - * @category Filtering */ export const filterMapOrElse: { /** * Filters an effect with a `Filter`, providing an alternative effect on failure. * + * **When to use** + * + * Use when a successful effect value should be accepted and transformed by a + * `Filter`, while rejected values should continue with an alternative effect + * built from the filter failure. + * + * **Details** + * + * `Result.succeed` becomes the returned success value, and `Result.fail` is + * passed to `orElse`. + * + * @see {@link filterOrElse} for using a predicate and fallback effect + * @see {@link filterMapOrFail} for failing the effect when the filter fails + * + * @category filtering * @since 4.0.0 - * @category Filtering */ ( filter: Filter.Filter, B, X>, @@ -9070,8 +9576,22 @@ export const filterMapOrElse: { /** * Filters an effect with a `Filter`, providing an alternative effect on failure. * + * **When to use** + * + * Use when a successful effect value should be accepted and transformed by a + * `Filter`, while rejected values should continue with an alternative effect + * built from the filter failure. + * + * **Details** + * + * `Result.succeed` becomes the returned success value, and `Result.fail` is + * passed to `orElse`. + * + * @see {@link filterOrElse} for using a predicate and fallback effect + * @see {@link filterMapOrFail} for failing the effect when the filter fails + * + * @category filtering * @since 4.0.0 - * @category Filtering */ ( self: Effect, @@ -9089,7 +9609,8 @@ export const filterMapOrElse: { * predicate evaluates to `false`, the effect fails with either a custom * error (if `orFailWith` is provided) or a `NoSuchElementError`. * - * @example + * **Example** (Filtering with a custom failure) + * * ```ts * import { Effect } from "effect" * @@ -9106,8 +9627,8 @@ export const filterMapOrElse: { * // Result: Effect.fail("Expected even number, got 5") * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ export const filterOrFail: { /** @@ -9119,7 +9640,8 @@ export const filterOrFail: { * predicate evaluates to `false`, the effect fails with either a custom * error (if `orFailWith` is provided) or a `NoSuchElementError`. * - * @example + * **Example** (Filtering with a custom failure) + * * ```ts * import { Effect } from "effect" * @@ -9136,8 +9658,8 @@ export const filterOrFail: { * // Result: Effect.fail("Expected even number, got 5") * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ ( refinement: Predicate.Refinement, B>, @@ -9152,7 +9674,8 @@ export const filterOrFail: { * predicate evaluates to `false`, the effect fails with either a custom * error (if `orFailWith` is provided) or a `NoSuchElementError`. * - * @example + * **Example** (Filtering with a custom failure) + * * ```ts * import { Effect } from "effect" * @@ -9169,8 +9692,8 @@ export const filterOrFail: { * // Result: Effect.fail("Expected even number, got 5") * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ ( predicate: Predicate.Predicate>, @@ -9185,7 +9708,8 @@ export const filterOrFail: { * predicate evaluates to `false`, the effect fails with either a custom * error (if `orFailWith` is provided) or a `NoSuchElementError`. * - * @example + * **Example** (Filtering with a custom failure) + * * ```ts * import { Effect } from "effect" * @@ -9202,8 +9726,8 @@ export const filterOrFail: { * // Result: Effect.fail("Expected even number, got 5") * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (refinement: Predicate.Refinement, B>): (self: Effect) => Effect /** @@ -9215,7 +9739,8 @@ export const filterOrFail: { * predicate evaluates to `false`, the effect fails with either a custom * error (if `orFailWith` is provided) or a `NoSuchElementError`. * - * @example + * **Example** (Filtering with a custom failure) + * * ```ts * import { Effect } from "effect" * @@ -9232,8 +9757,8 @@ export const filterOrFail: { * // Result: Effect.fail("Expected even number, got 5") * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (predicate: Predicate.Predicate>): (self: Effect) => Effect /** @@ -9245,7 +9770,8 @@ export const filterOrFail: { * predicate evaluates to `false`, the effect fails with either a custom * error (if `orFailWith` is provided) or a `NoSuchElementError`. * - * @example + * **Example** (Filtering with a custom failure) + * * ```ts * import { Effect } from "effect" * @@ -9262,8 +9788,8 @@ export const filterOrFail: { * // Result: Effect.fail("Expected even number, got 5") * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ ( self: Effect, @@ -9279,7 +9805,8 @@ export const filterOrFail: { * predicate evaluates to `false`, the effect fails with either a custom * error (if `orFailWith` is provided) or a `NoSuchElementError`. * - * @example + * **Example** (Filtering with a custom failure) + * * ```ts * import { Effect } from "effect" * @@ -9296,8 +9823,8 @@ export const filterOrFail: { * // Result: Effect.fail("Expected even number, got 5") * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ ( self: Effect, @@ -9313,7 +9840,8 @@ export const filterOrFail: { * predicate evaluates to `false`, the effect fails with either a custom * error (if `orFailWith` is provided) or a `NoSuchElementError`. * - * @example + * **Example** (Filtering with a custom failure) + * * ```ts * import { Effect } from "effect" * @@ -9330,8 +9858,8 @@ export const filterOrFail: { * // Result: Effect.fail("Expected even number, got 5") * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (self: Effect, refinement: Predicate.Refinement, B>): Effect /** @@ -9343,7 +9871,8 @@ export const filterOrFail: { * predicate evaluates to `false`, the effect fails with either a custom * error (if `orFailWith` is provided) or a `NoSuchElementError`. * - * @example + * **Example** (Filtering with a custom failure) + * * ```ts * import { Effect } from "effect" * @@ -9360,38 +9889,94 @@ export const filterOrFail: { * // Result: Effect.fail("Expected even number, got 5") * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (self: Effect, predicate: Predicate.Predicate>): Effect } = internal.filterOrFail /** - * Filters an effect with a `Filter`, failing when the filter fails. + * Filters and maps an effect with a `Filter`, failing when the filter fails. * + * **When to use** + * + * Use when validating and transforming one effect success with a synchronous + * `Filter`, while rejected values should fail the effect. + * + * **Details** + * + * `Result.succeed` becomes the returned success value. `Result.fail` is mapped + * with `orFailWith` when provided, or fails with `NoSuchElementError`. + * + * @see {@link filterMapOrElse} for continuing with a fallback effect when the filter fails + * @see {@link filterOrFail} for validating with a predicate instead of a `Filter` + * @see {@link filterMap} for filtering and mapping iterable elements + * + * @category filtering * @since 4.0.0 - * @category Filtering */ export const filterMapOrFail: { /** - * Filters an effect with a `Filter`, failing when the filter fails. + * Filters and maps an effect with a `Filter`, failing when the filter fails. + * + * **When to use** + * + * Use when validating and transforming one effect success with a synchronous + * `Filter`, while rejected values should fail the effect. * + * **Details** + * + * `Result.succeed` becomes the returned success value. `Result.fail` is mapped + * with `orFailWith` when provided, or fails with `NoSuchElementError`. + * + * @see {@link filterMapOrElse} for continuing with a fallback effect when the filter fails + * @see {@link filterOrFail} for validating with a predicate instead of a `Filter` + * @see {@link filterMap} for filtering and mapping iterable elements + * + * @category filtering * @since 4.0.0 - * @category Filtering */ (filter: Filter.Filter, B, X>, orFailWith: (x: X) => E2): (self: Effect) => Effect /** - * Filters an effect with a `Filter`, failing when the filter fails. + * Filters and maps an effect with a `Filter`, failing when the filter fails. + * + * **When to use** + * + * Use when validating and transforming one effect success with a synchronous + * `Filter`, while rejected values should fail the effect. + * + * **Details** * + * `Result.succeed` becomes the returned success value. `Result.fail` is mapped + * with `orFailWith` when provided, or fails with `NoSuchElementError`. + * + * @see {@link filterMapOrElse} for continuing with a fallback effect when the filter fails + * @see {@link filterOrFail} for validating with a predicate instead of a `Filter` + * @see {@link filterMap} for filtering and mapping iterable elements + * + * @category filtering * @since 4.0.0 - * @category Filtering */ (filter: Filter.Filter, B, X>): (self: Effect) => Effect /** - * Filters an effect with a `Filter`, failing when the filter fails. + * Filters and maps an effect with a `Filter`, failing when the filter fails. + * + * **When to use** + * + * Use when validating and transforming one effect success with a synchronous + * `Filter`, while rejected values should fail the effect. + * + * **Details** + * + * `Result.succeed` becomes the returned success value. `Result.fail` is mapped + * with `orFailWith` when provided, or fails with `NoSuchElementError`. + * + * @see {@link filterMapOrElse} for continuing with a fallback effect when the filter fails + * @see {@link filterOrFail} for validating with a predicate instead of a `Filter` + * @see {@link filterMap} for filtering and mapping iterable elements * + * @category filtering * @since 4.0.0 - * @category Filtering */ ( self: Effect, @@ -9399,10 +9984,24 @@ export const filterMapOrFail: { orFailWith: (x: X) => E2 ): Effect /** - * Filters an effect with a `Filter`, failing when the filter fails. + * Filters and maps an effect with a `Filter`, failing when the filter fails. * + * **When to use** + * + * Use when validating and transforming one effect success with a synchronous + * `Filter`, while rejected values should fail the effect. + * + * **Details** + * + * `Result.succeed` becomes the returned success value. `Result.fail` is mapped + * with `orFailWith` when provided, or fails with `NoSuchElementError`. + * + * @see {@link filterMapOrElse} for continuing with a fallback effect when the filter fails + * @see {@link filterOrFail} for validating with a predicate instead of a `Filter` + * @see {@link filterMap} for filtering and mapping iterable elements + * + * @category filtering * @since 4.0.0 - * @category Filtering */ (self: Effect, filter: Filter.Filter): Effect } = internal.filterMapOrFail @@ -9412,22 +10011,23 @@ export const filterMapOrFail: { // ----------------------------------------------------------------------------- /** - * Conditionally executes an effect based on a boolean condition. + * Runs an effect conditionally based on the result of an effectful boolean + * condition. * - * **Details** + * **When to use** + * + * Use when you need an effectful check to decide whether another effect should + * run while representing the skipped case explicitly. * - * This function allows you to run an effect only if a given condition evaluates - * to `true`. If the condition is `true`, the effect is executed, and its result - * is wrapped in an `Option.some`. If the condition is `false`, the effect is - * skipped, and the result is `Option.none`. + * **Details** * - * **When to Use** + * The condition effect is evaluated first. If it succeeds with `true`, the + * source effect is run and its success value is wrapped in `Option.some`. If it + * succeeds with `false`, the source effect is skipped and the result is + * `Option.none`. If the condition effect fails, that failure is preserved. * - * This function is useful for scenarios where you need to dynamically decide - * whether to execute an effect based on runtime logic, while also representing - * the skipped case explicitly. + * **Example** (Conditionally running an effect) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -9443,11 +10043,8 @@ export const filterMapOrFail: { * // { _id: 'Option', _tag: 'Some', value: undefined } * ``` * - * @see {@link whenEffect} for a version that allows the condition to be an effect. - * @see {@link unless} for a version that executes the effect when the condition is `false`. - * + * @category conditional operators * @since 2.0.0 - * @category Conditional Operators */ export const when: { // ----------------------------------------------------------------------------- @@ -9455,22 +10052,23 @@ export const when: { // ----------------------------------------------------------------------------- /** - * Conditionally executes an effect based on a boolean condition. + * Runs an effect conditionally based on the result of an effectful boolean + * condition. * - * **Details** + * **When to use** + * + * Use when you need an effectful check to decide whether another effect should + * run while representing the skipped case explicitly. * - * This function allows you to run an effect only if a given condition evaluates - * to `true`. If the condition is `true`, the effect is executed, and its result - * is wrapped in an `Option.some`. If the condition is `false`, the effect is - * skipped, and the result is `Option.none`. + * **Details** * - * **When to Use** + * The condition effect is evaluated first. If it succeeds with `true`, the + * source effect is run and its success value is wrapped in `Option.some`. If it + * succeeds with `false`, the source effect is skipped and the result is + * `Option.none`. If the condition effect fails, that failure is preserved. * - * This function is useful for scenarios where you need to dynamically decide - * whether to execute an effect based on runtime logic, while also representing - * the skipped case explicitly. + * **Example** (Conditionally running an effect) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -9486,11 +10084,8 @@ export const when: { * // { _id: 'Option', _tag: 'Some', value: undefined } * ``` * - * @see {@link whenEffect} for a version that allows the condition to be an effect. - * @see {@link unless} for a version that executes the effect when the condition is `false`. - * + * @category conditional operators * @since 2.0.0 - * @category Conditional Operators */ (condition: Effect): (self: Effect) => Effect, E | E2, R | R2> // ----------------------------------------------------------------------------- @@ -9498,22 +10093,23 @@ export const when: { // ----------------------------------------------------------------------------- /** - * Conditionally executes an effect based on a boolean condition. + * Runs an effect conditionally based on the result of an effectful boolean + * condition. * - * **Details** + * **When to use** + * + * Use when you need an effectful check to decide whether another effect should + * run while representing the skipped case explicitly. * - * This function allows you to run an effect only if a given condition evaluates - * to `true`. If the condition is `true`, the effect is executed, and its result - * is wrapped in an `Option.some`. If the condition is `false`, the effect is - * skipped, and the result is `Option.none`. + * **Details** * - * **When to Use** + * The condition effect is evaluated first. If it succeeds with `true`, the + * source effect is run and its success value is wrapped in `Option.some`. If it + * succeeds with `false`, the source effect is skipped and the result is + * `Option.none`. If the condition effect fails, that failure is preserved. * - * This function is useful for scenarios where you need to dynamically decide - * whether to execute an effect based on runtime logic, while also representing - * the skipped case explicitly. + * **Example** (Conditionally running an effect) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -9529,11 +10125,8 @@ export const when: { * // { _id: 'Option', _tag: 'Some', value: undefined } * ``` * - * @see {@link whenEffect} for a version that allows the condition to be an effect. - * @see {@link unless} for a version that executes the effect when the condition is `false`. - * + * @category conditional operators * @since 2.0.0 - * @category Conditional Operators */ (self: Effect, condition: Effect): Effect, E | E2, R | R2> } = internal.when @@ -9546,6 +10139,11 @@ export const when: { * Handles both success and failure cases of an effect without performing side * effects. * + * **When to use** + * + * Use when you need to fold an `Effect` into a value by handling success and + * failure differently without triggering side effects. + * * **Details** * * `match` lets you define custom handlers for both success and failure @@ -9553,16 +10151,9 @@ export const when: { * to process the result if the effect succeeds, or handle the error if the * effect fails. * - * **When to Use** + * **Example** (Matching success and failure values) * - * This is useful for structuring your code to respond differently to success or - * failure without triggering side effects. - * - * @see {@link matchEffect} if you need to perform side effects in the handlers. - * - * @example * ```ts - * // Title: Handling Both Success and Failure Cases * import { Data, Effect } from "effect" * * class ExampleError extends Data.TaggedError("ExampleError")<{ readonly message: string }> {} @@ -9592,8 +10183,9 @@ export const when: { * // Output: "failure: Uh oh!" * ``` * + * @see {@link matchEffect} if you need to perform side effects in the handlers. + * @category pattern matching * @since 2.0.0 - * @category Pattern Matching */ export const match: { // ----------------------------------------------------------------------------- @@ -9604,6 +10196,11 @@ export const match: { * Handles both success and failure cases of an effect without performing side * effects. * + * **When to use** + * + * Use when you need to fold an `Effect` into a value by handling success and + * failure differently without triggering side effects. + * * **Details** * * `match` lets you define custom handlers for both success and failure @@ -9611,16 +10208,9 @@ export const match: { * to process the result if the effect succeeds, or handle the error if the * effect fails. * - * **When to Use** - * - * This is useful for structuring your code to respond differently to success or - * failure without triggering side effects. - * - * @see {@link matchEffect} if you need to perform side effects in the handlers. + * **Example** (Matching success and failure values) * - * @example * ```ts - * // Title: Handling Both Success and Failure Cases * import { Data, Effect } from "effect" * * class ExampleError extends Data.TaggedError("ExampleError")<{ readonly message: string }> {} @@ -9650,8 +10240,9 @@ export const match: { * // Output: "failure: Uh oh!" * ``` * + * @see {@link matchEffect} if you need to perform side effects in the handlers. + * @category pattern matching * @since 2.0.0 - * @category Pattern Matching */ ( options: { @@ -9667,6 +10258,11 @@ export const match: { * Handles both success and failure cases of an effect without performing side * effects. * + * **When to use** + * + * Use when you need to fold an `Effect` into a value by handling success and + * failure differently without triggering side effects. + * * **Details** * * `match` lets you define custom handlers for both success and failure @@ -9674,16 +10270,9 @@ export const match: { * to process the result if the effect succeeds, or handle the error if the * effect fails. * - * **When to Use** + * **Example** (Matching success and failure values) * - * This is useful for structuring your code to respond differently to success or - * failure without triggering side effects. - * - * @see {@link matchEffect} if you need to perform side effects in the handlers. - * - * @example * ```ts - * // Title: Handling Both Success and Failure Cases * import { Data, Effect } from "effect" * * class ExampleError extends Data.TaggedError("ExampleError")<{ readonly message: string }> {} @@ -9713,8 +10302,9 @@ export const match: { * // Output: "failure: Uh oh!" * ``` * + * @see {@link matchEffect} if you need to perform side effects in the handlers. + * @category pattern matching * @since 2.0.0 - * @category Pattern Matching */ ( self: Effect, @@ -9729,6 +10319,11 @@ export const match: { * Handles both success and failure cases of an effect without performing side * effects, with eager evaluation for resolved effects. * + * **When to use** + * + * Use when you need to handle both success and failure cases of an + * already-resolved `Effect` with optimized handling. + * * **Details** * * `matchEager` works like `match` but provides better performance for resolved @@ -9736,13 +10331,8 @@ export const match: { * the handlers immediately without fiber scheduling. For unresolved effects, * it falls back to the regular `match` behavior. * - * **When to Use** + * **Example** (Pattern matching eagerly when possible) * - * Use this when you need to handle both success and failure cases and want - * optimal performance for resolved effects. This is particularly useful in - * scenarios where you frequently work with already computed values. - * - * @example * ```ts * import { Effect } from "effect" * @@ -9757,15 +10347,19 @@ export const match: { * * @see {@link match} for the non-eager version. * @see {@link matchEffect} if you need to perform side effects in the handlers. - * - * @since 2.0.0 - * @category Pattern Matching + * @category pattern matching + * @since 4.0.0 */ export const matchEager: { /** * Handles both success and failure cases of an effect without performing side * effects, with eager evaluation for resolved effects. * + * **When to use** + * + * Use when you need to handle both success and failure cases of an + * already-resolved `Effect` with optimized handling. + * * **Details** * * `matchEager` works like `match` but provides better performance for resolved @@ -9773,13 +10367,8 @@ export const matchEager: { * the handlers immediately without fiber scheduling. For unresolved effects, * it falls back to the regular `match` behavior. * - * **When to Use** + * **Example** (Pattern matching eagerly when possible) * - * Use this when you need to handle both success and failure cases and want - * optimal performance for resolved effects. This is particularly useful in - * scenarios where you frequently work with already computed values. - * - * @example * ```ts * import { Effect } from "effect" * @@ -9794,9 +10383,8 @@ export const matchEager: { * * @see {@link match} for the non-eager version. * @see {@link matchEffect} if you need to perform side effects in the handlers. - * - * @since 2.0.0 - * @category Pattern Matching + * @category pattern matching + * @since 4.0.0 */ ( options: { @@ -9808,6 +10396,11 @@ export const matchEager: { * Handles both success and failure cases of an effect without performing side * effects, with eager evaluation for resolved effects. * + * **When to use** + * + * Use when you need to handle both success and failure cases of an + * already-resolved `Effect` with optimized handling. + * * **Details** * * `matchEager` works like `match` but provides better performance for resolved @@ -9815,13 +10408,8 @@ export const matchEager: { * the handlers immediately without fiber scheduling. For unresolved effects, * it falls back to the regular `match` behavior. * - * **When to Use** + * **Example** (Pattern matching eagerly when possible) * - * Use this when you need to handle both success and failure cases and want - * optimal performance for resolved effects. This is particularly useful in - * scenarios where you frequently work with already computed values. - * - * @example * ```ts * import { Effect } from "effect" * @@ -9836,9 +10424,8 @@ export const matchEager: { * * @see {@link match} for the non-eager version. * @see {@link matchEffect} if you need to perform side effects in the handlers. - * - * @since 2.0.0 - * @category Pattern Matching + * @category pattern matching + * @since 4.0.0 */ ( self: Effect, @@ -9852,18 +10439,18 @@ export const matchEager: { /** * Handles failures by matching the cause of failure. * + * **When to use** + * + * Use when you need to fold an `Effect` while the failure handler inspects the + * full `Cause`. + * * **Details** * * The `matchCause` function allows you to handle failures with access to the * full cause of the failure within a fiber. * - * **When to Use** + * **Example** (Matching on success or failure causes) * - * This is useful for differentiating between different types of errors, such as - * regular failures, defects, or interruptions. You can provide specific - * handling logic for each failure type based on the cause. - * - * @example * ```ts * import { Cause, Effect } from "effect" * @@ -9881,26 +10468,25 @@ export const matchEager: { * @see {@link matchCauseEffect} if you need to perform side effects in the * handlers. * @see {@link match} if you don't need to handle the cause of the failure. - * + * @category pattern matching * @since 2.0.0 - * @category Pattern Matching */ export const matchCause: { /** * Handles failures by matching the cause of failure. * + * **When to use** + * + * Use when you need to fold an `Effect` while the failure handler inspects the + * full `Cause`. + * * **Details** * * The `matchCause` function allows you to handle failures with access to the * full cause of the failure within a fiber. * - * **When to Use** + * **Example** (Matching on success or failure causes) * - * This is useful for differentiating between different types of errors, such as - * regular failures, defects, or interruptions. You can provide specific - * handling logic for each failure type based on the cause. - * - * @example * ```ts * import { Cause, Effect } from "effect" * @@ -9918,9 +10504,8 @@ export const matchCause: { * @see {@link matchCauseEffect} if you need to perform side effects in the * handlers. * @see {@link match} if you don't need to handle the cause of the failure. - * + * @category pattern matching * @since 2.0.0 - * @category Pattern Matching */ ( options: { @@ -9931,18 +10516,18 @@ export const matchCause: { /** * Handles failures by matching the cause of failure. * + * **When to use** + * + * Use when you need to fold an `Effect` while the failure handler inspects the + * full `Cause`. + * * **Details** * * The `matchCause` function allows you to handle failures with access to the * full cause of the failure within a fiber. * - * **When to Use** + * **Example** (Matching on success or failure causes) * - * This is useful for differentiating between different types of errors, such as - * regular failures, defects, or interruptions. You can provide specific - * handling logic for each failure type based on the cause. - * - * @example * ```ts * import { Cause, Effect } from "effect" * @@ -9960,9 +10545,8 @@ export const matchCause: { * @see {@link matchCauseEffect} if you need to perform side effects in the * handlers. * @see {@link match} if you don't need to handle the cause of the failure. - * + * @category pattern matching * @since 2.0.0 - * @category Pattern Matching */ ( self: Effect, @@ -9976,19 +10560,19 @@ export const matchCause: { /** * Handles failures by matching the cause of failure with eager evaluation. * + * **When to use** + * + * Use when you expect an `Effect` to already be resolved and want to match the + * `Cause` without regular effect pipeline overhead. + * * **Details** * * `matchCauseEager` works like `matchCause` but provides better performance for resolved * effects by immediately applying the matching function instead of deferring it * through the effect pipeline. * - * **When to Use** + * **Example** (Eagerly matching already completed effects) * - * This is useful when you have effects that are likely to be already resolved - * and you want to avoid the overhead of the effect pipeline. For pending effects, - * it automatically falls back to the regular `matchCause` behavior. - * - * @example * ```ts * import { Effect } from "effect" * @@ -9998,26 +10582,26 @@ export const matchCause: { * }) * ``` * - * @since 3.8.0 - * @category Pattern Matching + * @category pattern matching + * @since 4.0.0 */ export const matchCauseEager: { /** * Handles failures by matching the cause of failure with eager evaluation. * + * **When to use** + * + * Use when you expect an `Effect` to already be resolved and want to match the + * `Cause` without regular effect pipeline overhead. + * * **Details** * * `matchCauseEager` works like `matchCause` but provides better performance for resolved * effects by immediately applying the matching function instead of deferring it * through the effect pipeline. * - * **When to Use** + * **Example** (Eagerly matching already completed effects) * - * This is useful when you have effects that are likely to be already resolved - * and you want to avoid the overhead of the effect pipeline. For pending effects, - * it automatically falls back to the regular `matchCause` behavior. - * - * @example * ```ts * import { Effect } from "effect" * @@ -10027,8 +10611,8 @@ export const matchCauseEager: { * }) * ``` * - * @since 3.8.0 - * @category Pattern Matching + * @category pattern matching + * @since 4.0.0 */ ( options: { @@ -10039,19 +10623,19 @@ export const matchCauseEager: { /** * Handles failures by matching the cause of failure with eager evaluation. * + * **When to use** + * + * Use when you expect an `Effect` to already be resolved and want to match the + * `Cause` without regular effect pipeline overhead. + * * **Details** * * `matchCauseEager` works like `matchCause` but provides better performance for resolved * effects by immediately applying the matching function instead of deferring it * through the effect pipeline. * - * **When to Use** + * **Example** (Eagerly matching already completed effects) * - * This is useful when you have effects that are likely to be already resolved - * and you want to avoid the overhead of the effect pipeline. For pending effects, - * it automatically falls back to the regular `matchCause` behavior. - * - * @example * ```ts * import { Effect } from "effect" * @@ -10061,8 +10645,8 @@ export const matchCauseEager: { * }) * ``` * - * @since 3.8.0 - * @category Pattern Matching + * @category pattern matching + * @since 4.0.0 */ ( self: Effect, @@ -10074,23 +10658,45 @@ export const matchCauseEager: { } = internal.matchCauseEager /** - * Eagerly handles success or failure with effectful handlers when the effect is already resolved. + * Handles success or failure eagerly with effectful handlers when the effect is already resolved. + * + * **When to use** + * + * Use when you need effectful success and cause-aware failure handlers for + * `Effect` inputs that may already be resolved. + * + * **Details** * * If the effect is an `Exit`, the matching handler runs immediately; otherwise it behaves like * {@link matchCauseEffect}. * + * @see {@link matchCauseEffect} for the non-eager effectful variant + * @see {@link matchCauseEager} for eager cause matching with pure handlers + * @see {@link matchEffect} for effectful matching on typed failures instead of full causes + * + * @category pattern matching * @since 4.0.0 - * @category Pattern Matching */ export const matchCauseEffectEager: { /** - * Eagerly handles success or failure with effectful handlers when the effect is already resolved. + * Handles success or failure eagerly with effectful handlers when the effect is already resolved. + * + * **When to use** + * + * Use when you need effectful success and cause-aware failure handlers for + * `Effect` inputs that may already be resolved. + * + * **Details** * * If the effect is an `Exit`, the matching handler runs immediately; otherwise it behaves like * {@link matchCauseEffect}. * + * @see {@link matchCauseEffect} for the non-eager effectful variant + * @see {@link matchCauseEager} for eager cause matching with pure handlers + * @see {@link matchEffect} for effectful matching on typed failures instead of full causes + * + * @category pattern matching * @since 4.0.0 - * @category Pattern Matching */ ( options: { @@ -10099,13 +10705,24 @@ export const matchCauseEffectEager: { } ): (self: Effect) => Effect /** - * Eagerly handles success or failure with effectful handlers when the effect is already resolved. + * Handles success or failure eagerly with effectful handlers when the effect is already resolved. + * + * **When to use** + * + * Use when you need effectful success and cause-aware failure handlers for + * `Effect` inputs that may already be resolved. + * + * **Details** * * If the effect is an `Exit`, the matching handler runs immediately; otherwise it behaves like * {@link matchCauseEffect}. * + * @see {@link matchCauseEffect} for the non-eager effectful variant + * @see {@link matchCauseEager} for eager cause matching with pure handlers + * @see {@link matchEffect} for effectful matching on typed failures instead of full causes + * + * @category pattern matching * @since 4.0.0 - * @category Pattern Matching */ ( self: Effect, @@ -10119,6 +10736,11 @@ export const matchCauseEffectEager: { /** * Handles failures with access to the cause and allows performing side effects. * + * **When to use** + * + * Use when you need to fold an `Effect` with effectful success handlers and + * `Cause`-aware failure handlers. + * * **Details** * * The `matchCauseEffect` function works similarly to {@link matchCause}, but it @@ -10128,7 +10750,8 @@ export const matchCauseEffectEager: { * you to respond accordingly while performing side effects (like logging or * other operations). * - * @example + * **Example** (Effectfully matching on causes) + * * ```ts * import { Cause, Console, Data, Effect, Result } from "effect" * @@ -10166,13 +10789,18 @@ export const matchCauseEffectEager: { * @see {@link matchCause} if you don't need side effects and only want to handle the result or failure. * @see {@link matchEffect} if you don't need to handle the cause of the failure. * + * @category pattern matching * @since 2.0.0 - * @category Pattern Matching */ export const matchCauseEffect: { /** * Handles failures with access to the cause and allows performing side effects. * + * **When to use** + * + * Use when you need to fold an `Effect` with effectful success handlers and + * `Cause`-aware failure handlers. + * * **Details** * * The `matchCauseEffect` function works similarly to {@link matchCause}, but it @@ -10182,7 +10810,8 @@ export const matchCauseEffect: { * you to respond accordingly while performing side effects (like logging or * other operations). * - * @example + * **Example** (Effectfully matching on causes) + * * ```ts * import { Cause, Console, Data, Effect, Result } from "effect" * @@ -10220,8 +10849,8 @@ export const matchCauseEffect: { * @see {@link matchCause} if you don't need side effects and only want to handle the result or failure. * @see {@link matchEffect} if you don't need to handle the cause of the failure. * + * @category pattern matching * @since 2.0.0 - * @category Pattern Matching */ ( options: { @@ -10232,6 +10861,11 @@ export const matchCauseEffect: { /** * Handles failures with access to the cause and allows performing side effects. * + * **When to use** + * + * Use when you need to fold an `Effect` with effectful success handlers and + * `Cause`-aware failure handlers. + * * **Details** * * The `matchCauseEffect` function works similarly to {@link matchCause}, but it @@ -10241,7 +10875,8 @@ export const matchCauseEffect: { * you to respond accordingly while performing side effects (like logging or * other operations). * - * @example + * **Example** (Effectfully matching on causes) + * * ```ts * import { Cause, Console, Data, Effect, Result } from "effect" * @@ -10279,8 +10914,8 @@ export const matchCauseEffect: { * @see {@link matchCause} if you don't need side effects and only want to handle the result or failure. * @see {@link matchEffect} if you don't need to handle the cause of the failure. * + * @category pattern matching * @since 2.0.0 - * @category Pattern Matching */ ( self: Effect, @@ -10292,25 +10927,22 @@ export const matchCauseEffect: { } = internal.matchCauseEffect /** - * Handles both success and failure cases of an effect, allowing for additional - * side effects. + * Handles both success and failure by running effectful handlers. * - * **Details** + * **When to use** * - * The `matchEffect` function is similar to {@link match}, but it enables you to - * perform side effects in the handlers for both success and failure outcomes. + * Use when you need to handle an `Effect`'s failure or success with handlers + * that return effects. * - * **When to Use** + * **Details** * - * This is useful when you need to execute additional actions, like logging or - * notifying users, based on whether an effect succeeds or fails. + * Use `matchEffect` when either branch needs to return an `Effect`, such as + * performing logging, recovery, notification, or other effectful work. The + * returned effect succeeds or fails according to the handler that is run. * - * @see {@link match} if you don't need side effects and only want to handle the - * result or failure. + * **Example** (Matching success and failure with effectful handlers) * - * @example * ```ts - * // Title: Handling Both Success and Failure Cases with Side Effects * import { Data, Effect } from "effect" * * class ExampleError extends Data.TaggedError("ExampleError")<{ readonly message: string }> {} @@ -10349,30 +10981,29 @@ export const matchCauseEffect: { * // failure: Uh oh! * ``` * + * @see {@link match} if you don't need side effects and only want to handle the + * result or failure. + * @category pattern matching * @since 2.0.0 - * @category Pattern Matching */ export const matchEffect: { /** - * Handles both success and failure cases of an effect, allowing for additional - * side effects. + * Handles both success and failure by running effectful handlers. * - * **Details** + * **When to use** * - * The `matchEffect` function is similar to {@link match}, but it enables you to - * perform side effects in the handlers for both success and failure outcomes. + * Use when you need to handle an `Effect`'s failure or success with handlers + * that return effects. * - * **When to Use** + * **Details** * - * This is useful when you need to execute additional actions, like logging or - * notifying users, based on whether an effect succeeds or fails. + * Use `matchEffect` when either branch needs to return an `Effect`, such as + * performing logging, recovery, notification, or other effectful work. The + * returned effect succeeds or fails according to the handler that is run. * - * @see {@link match} if you don't need side effects and only want to handle the - * result or failure. + * **Example** (Matching success and failure with effectful handlers) * - * @example * ```ts - * // Title: Handling Both Success and Failure Cases with Side Effects * import { Data, Effect } from "effect" * * class ExampleError extends Data.TaggedError("ExampleError")<{ readonly message: string }> {} @@ -10411,8 +11042,10 @@ export const matchEffect: { * // failure: Uh oh! * ``` * + * @see {@link match} if you don't need side effects and only want to handle the + * result or failure. + * @category pattern matching * @since 2.0.0 - * @category Pattern Matching */ ( options: { @@ -10421,25 +11054,22 @@ export const matchEffect: { } ): (self: Effect) => Effect /** - * Handles both success and failure cases of an effect, allowing for additional - * side effects. + * Handles both success and failure by running effectful handlers. * - * **Details** + * **When to use** * - * The `matchEffect` function is similar to {@link match}, but it enables you to - * perform side effects in the handlers for both success and failure outcomes. + * Use when you need to handle an `Effect`'s failure or success with handlers + * that return effects. * - * **When to Use** + * **Details** * - * This is useful when you need to execute additional actions, like logging or - * notifying users, based on whether an effect succeeds or fails. + * Use `matchEffect` when either branch needs to return an `Effect`, such as + * performing logging, recovery, notification, or other effectful work. The + * returned effect succeeds or fails according to the handler that is run. * - * @see {@link match} if you don't need side effects and only want to handle the - * result or failure. + * **Example** (Matching success and failure with effectful handlers) * - * @example * ```ts - * // Title: Handling Both Success and Failure Cases with Side Effects * import { Data, Effect } from "effect" * * class ExampleError extends Data.TaggedError("ExampleError")<{ readonly message: string }> {} @@ -10478,8 +11108,10 @@ export const matchEffect: { * // failure: Uh oh! * ``` * + * @see {@link match} if you don't need side effects and only want to handle the + * result or failure. + * @category pattern matching * @since 2.0.0 - * @category Pattern Matching */ ( self: Effect, @@ -10497,9 +11129,11 @@ export const matchEffect: { /** * Determines whether an effect fails. * + * **Details** + * * Defects are not converted; if the effect dies, the resulting effect dies too. * - * **Example** + * **Example** (Checking whether an effect fails) * * ```ts * import { Console, Effect } from "effect" @@ -10513,18 +11147,20 @@ export const matchEffect: { * // Output: true * ``` * + * @category condition checking * @since 2.0.0 - * @category Condition Checking */ export const isFailure: (self: Effect) => Effect = internal.isFailure /** * Returns whether an effect completes successfully. * + * **Details** + * * Returns `false` for failures in the error channel, but defects still fail the * effect. * - * **Example** + * **Example** (Checking whether an effect succeeds) * * ```ts * import { Console, Effect } from "effect" @@ -10542,8 +11178,8 @@ export const isFailure: (self: Effect) => Effect(self: Effect) => Effect = internal.isSuccess @@ -10554,13 +11190,20 @@ export const isSuccess: (self: Effect) => Effect void @@ -10586,21 +11229,31 @@ export const isSuccess: (self: Effect) => Effect() => Effect, never, R> = internal.context /** * Transforms the current context using the provided function. * + * **When to use** + * + * Use to derive an effect from the complete `Context`. + * + * **Details** + * * This function allows you to access the complete context and perform * computations based on all available services. This is useful when you need * to conditionally execute logic based on what services are available. * - * @example + * **Example** (Deriving values from the context) + * * ```ts - * import { Console, Effect, Option, Context } from "effect" + * import { Console, Context, Effect, Option } from "effect" * * const Logger = Context.Service<{ * log: (msg: string) => void @@ -10632,8 +11285,11 @@ export const context: () => Effect, never, R> = in * }) * ``` * + * @see {@link context} for reading the complete context as a value + * @see {@link service} for reading one service from the context + * + * @category environment * @since 2.0.0 - * @category Environment */ export const contextWith: ( f: (context: Context.Context) => Effect @@ -10644,9 +11300,10 @@ export const contextWith: ( * to build the layer every time; by default, layers are shared between provide * calls. * - * @example + * **Example** (Providing dependencies with a layer) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * interface Database { * readonly query: (sql: string) => Effect.Effect @@ -10669,8 +11326,8 @@ export const contextWith: ( * // Output: "Result for: SELECT * FROM users" * ``` * + * @category environment * @since 2.0.0 - * @category Environment */ export const provide: { /** @@ -10678,9 +11335,10 @@ export const provide: { * to build the layer every time; by default, layers are shared between provide * calls. * - * @example + * **Example** (Providing dependencies with a layer) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * interface Database { * readonly query: (sql: string) => Effect.Effect @@ -10703,8 +11361,8 @@ export const provide: { * // Output: "Result for: SELECT * FROM users" * ``` * + * @category environment * @since 2.0.0 - * @category Environment */ ]>( layers: Layers, @@ -10723,9 +11381,10 @@ export const provide: { * to build the layer every time; by default, layers are shared between provide * calls. * - * @example + * **Example** (Providing dependencies with a layer) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * interface Database { * readonly query: (sql: string) => Effect.Effect @@ -10748,8 +11407,8 @@ export const provide: { * // Output: "Result for: SELECT * FROM users" * ``` * + * @category environment * @since 2.0.0 - * @category Environment */ ( layer: Layer.Layer, @@ -10764,9 +11423,10 @@ export const provide: { * to build the layer every time; by default, layers are shared between provide * calls. * - * @example + * **Example** (Providing dependencies with a layer) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * interface Database { * readonly query: (sql: string) => Effect.Effect @@ -10789,8 +11449,8 @@ export const provide: { * // Output: "Result for: SELECT * FROM users" * ``` * + * @category environment * @since 2.0.0 - * @category Environment */ (context: Context.Context): (self: Effect) => Effect> /** @@ -10798,9 +11458,10 @@ export const provide: { * to build the layer every time; by default, layers are shared between provide * calls. * - * @example + * **Example** (Providing dependencies with a layer) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * interface Database { * readonly query: (sql: string) => Effect.Effect @@ -10823,8 +11484,8 @@ export const provide: { * // Output: "Result for: SELECT * FROM users" * ``` * + * @category environment * @since 2.0.0 - * @category Environment */ ]>( self: Effect, @@ -10842,9 +11503,10 @@ export const provide: { * to build the layer every time; by default, layers are shared between provide * calls. * - * @example + * **Example** (Providing dependencies with a layer) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * interface Database { * readonly query: (sql: string) => Effect.Effect @@ -10867,8 +11529,8 @@ export const provide: { * // Output: "Result for: SELECT * FROM users" * ``` * + * @category environment * @since 2.0.0 - * @category Environment */ ( self: Effect, @@ -10882,9 +11544,10 @@ export const provide: { * to build the layer every time; by default, layers are shared between provide * calls. * - * @example + * **Example** (Providing dependencies with a layer) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * interface Database { * readonly query: (sql: string) => Effect.Effect @@ -10907,8 +11570,8 @@ export const provide: { * // Output: "Result for: SELECT * FROM users" * ``` * + * @category environment * @since 2.0.0 - * @category Environment */ (self: Effect, context: Context.Context): Effect> } = internalLayer.provide @@ -10922,9 +11585,10 @@ export const provide: { * that contains all the required services. It removes the provided services * from the effect's requirements, making them available to the effect. * - * @example + * **Example** (Providing a complete context) + * * ```ts - * import { Effect, Context } from "effect" + * import { Context, Effect } from "effect" * * // Define service keys * const Logger = Context.Service<{ @@ -10949,8 +11613,8 @@ export const provide: { * const provided = Effect.provideContext(program, context) * ``` * - * @since 2.0.0 - * @category Environment + * @category environment + * @since 4.0.0 */ export const provideContext: { /** @@ -10962,9 +11626,10 @@ export const provideContext: { * that contains all the required services. It removes the provided services * from the effect's requirements, making them available to the effect. * - * @example + * **Example** (Providing a complete context) + * * ```ts - * import { Effect, Context } from "effect" + * import { Context, Effect } from "effect" * * // Define service keys * const Logger = Context.Service<{ @@ -10989,8 +11654,8 @@ export const provideContext: { * const provided = Effect.provideContext(program, context) * ``` * - * @since 2.0.0 - * @category Environment + * @category environment + * @since 4.0.0 */ (context: Context.Context): (self: Effect) => Effect> /** @@ -11002,9 +11667,10 @@ export const provideContext: { * that contains all the required services. It removes the provided services * from the effect's requirements, making them available to the effect. * - * @example + * **Example** (Providing a complete context) + * * ```ts - * import { Effect, Context } from "effect" + * import { Context, Effect } from "effect" * * // Define service keys * const Logger = Context.Service<{ @@ -11029,8 +11695,8 @@ export const provideContext: { * const provided = Effect.provideContext(program, context) * ``` * - * @since 2.0.0 - * @category Environment + * @category environment + * @since 4.0.0 */ (self: Effect, context: Context.Context): Effect> } = internal.provideContext @@ -11038,9 +11704,10 @@ export const provideContext: { /** * Accesses a service from the context. * - * @example + * **Example** (Accessing a required service) + * * ```ts - * import { Effect, Context } from "effect" + * import { Context, Effect } from "effect" * * interface Database { * readonly query: (sql: string) => Effect.Effect @@ -11054,14 +11721,19 @@ export const provideContext: { * }) * ``` * + * @category context * @since 4.0.0 - * @category Context */ export const service: (service: Context.Key) => Effect = internal.service /** * Optionally accesses a service from the environment. * + * **When to use** + * + * Use to read an optional dependency from the current context without making + * that dependency part of the effect's required environment. + * * **Details** * * This function attempts to access a service from the environment. If the @@ -11069,9 +11741,10 @@ export const service: (service: Context.Key) => Effect * available, it returns `None`. Unlike `service`, this function does not * require the service to be present in the environment. * - * @example + * **Example** (Accessing an optional service) + * * ```ts - * import { Effect, Option, Context } from "effect" + * import { Context, Effect, Option } from "effect" * * // Define a service key * const Logger = Context.Service<{ @@ -11090,8 +11763,8 @@ export const service: (service: Context.Key) => Effect * }) * ``` * + * @category context * @since 2.0.0 - * @category Context */ export const serviceOption: (key: Context.Key) => Effect> = internal.serviceOption @@ -11103,9 +11776,10 @@ export const serviceOption: (key: Context.Key) => Effect> * This function allows you to transform the context required by an effect, * providing part of the context and leaving the rest to be fulfilled later. * - * @example + * **Example** (Updating the context before running) + * * ```ts - * import { Effect, Context } from "effect" + * import { Context, Effect } from "effect" * * // Define services * const Logger = Context.Service<{ @@ -11132,8 +11806,8 @@ export const serviceOption: (key: Context.Key) => Effect> * }) * ``` * + * @category context * @since 4.0.0 - * @category Context */ export const updateContext: { /** @@ -11144,9 +11818,10 @@ export const updateContext: { * This function allows you to transform the context required by an effect, * providing part of the context and leaving the rest to be fulfilled later. * - * @example + * **Example** (Updating the context before running) + * * ```ts - * import { Effect, Context } from "effect" + * import { Context, Effect } from "effect" * * // Define services * const Logger = Context.Service<{ @@ -11173,8 +11848,8 @@ export const updateContext: { * }) * ``` * + * @category context * @since 4.0.0 - * @category Context */ (f: (context: Context.Context) => Context.Context>): (self: Effect) => Effect /** @@ -11185,9 +11860,10 @@ export const updateContext: { * This function allows you to transform the context required by an effect, * providing part of the context and leaving the rest to be fulfilled later. * - * @example + * **Example** (Updating the context before running) + * * ```ts - * import { Effect, Context } from "effect" + * import { Context, Effect } from "effect" * * // Define services * const Logger = Context.Service<{ @@ -11214,8 +11890,8 @@ export const updateContext: { * }) * ``` * + * @category context * @since 4.0.0 - * @category Context */ ( self: Effect, @@ -11224,11 +11900,18 @@ export const updateContext: { } = internal.updateContext /** - * Updates the service with the required service entry. + * Runs an effect with a service implementation transformed by the provided + * function. + * + * **Details** + * + * The service must be available in the effect's context; `updateService` + * replaces it for the wrapped effect with the value returned by the updater. + * + * **Example** (Replacing a service for one effect) * - * @example * ```ts - * import { Console, Effect, Context } from "effect" + * import { Console, Context, Effect } from "effect" * * // Define a counter service * const Counter = Context.Service<{ count: number }>("Counter") @@ -11248,16 +11931,23 @@ export const updateContext: { * // 1 * ``` * + * @category context * @since 2.0.0 - * @category Context */ export const updateService: { /** - * Updates the service with the required service entry. + * Runs an effect with a service implementation transformed by the provided + * function. + * + * **Details** + * + * The service must be available in the effect's context; `updateService` + * replaces it for the wrapped effect with the value returned by the updater. + * + * **Example** (Replacing a service for one effect) * - * @example * ```ts - * import { Console, Effect, Context } from "effect" + * import { Console, Context, Effect } from "effect" * * // Define a counter service * const Counter = Context.Service<{ count: number }>("Counter") @@ -11277,16 +11967,23 @@ export const updateService: { * // 1 * ``` * + * @category context * @since 2.0.0 - * @category Context */ (service: Context.Key, f: (value: A) => A): (self: Effect) => Effect /** - * Updates the service with the required service entry. + * Runs an effect with a service implementation transformed by the provided + * function. + * + * **Details** + * + * The service must be available in the effect's context; `updateService` + * replaces it for the wrapped effect with the value returned by the updater. + * + * **Example** (Replacing a service for one effect) * - * @example * ```ts - * import { Console, Effect, Context } from "effect" + * import { Console, Context, Effect } from "effect" * * // Define a counter service * const Counter = Context.Service<{ count: number }>("Counter") @@ -11306,27 +12003,28 @@ export const updateService: { * // 1 * ``` * + * @category context * @since 2.0.0 - * @category Context */ (self: Effect, service: Context.Key, f: (value: A) => A): Effect } = internal.updateService /** - * The `provideService` function is used to provide an actual - * implementation for a service in the context of an effect. + * Provides one concrete service implementation to an effect. * - * This function allows you to associate a service with its implementation so - * that it can be used in your program. You define the service (e.g., a random - * number generator), and then you use `provideService` to link that - * service to its implementation. Once the implementation is provided, the - * effect can be run successfully without further requirements. + * **When to use** * - * @see {@link provide} for providing multiple layers to an effect. + * Use to satisfy one service requirement with an already-built implementation. + * + * **Details** + * + * The service requirement identified by the `Context.Key` is removed from the + * effect requirements after the implementation is provided. + * + * **Example** (Providing a service value) * - * @example * ```ts - * import { Console, Effect, Context } from "effect" + * import { Console, Context, Effect } from "effect" * * // Define a service for configuration * const Config = Context.Service<{ @@ -11354,25 +12052,29 @@ export const updateService: { * // data * ``` * + * @see {@link provide} for providing multiple layers to an effect. + * @see {@link provideServiceEffect} for acquiring the service implementation effectfully. + * @see {@link provideContext} for providing a complete context. + * @category context * @since 2.0.0 - * @category Context */ export const provideService: { /** - * The `provideService` function is used to provide an actual - * implementation for a service in the context of an effect. + * Provides one concrete service implementation to an effect. * - * This function allows you to associate a service with its implementation so - * that it can be used in your program. You define the service (e.g., a random - * number generator), and then you use `provideService` to link that - * service to its implementation. Once the implementation is provided, the - * effect can be run successfully without further requirements. + * **When to use** * - * @see {@link provide} for providing multiple layers to an effect. + * Use to satisfy one service requirement with an already-built implementation. + * + * **Details** + * + * The service requirement identified by the `Context.Key` is removed from the + * effect requirements after the implementation is provided. + * + * **Example** (Providing a service value) * - * @example * ```ts - * import { Console, Effect, Context } from "effect" + * import { Console, Context, Effect } from "effect" * * // Define a service for configuration * const Config = Context.Service<{ @@ -11400,25 +12102,29 @@ export const provideService: { * // data * ``` * + * @see {@link provide} for providing multiple layers to an effect. + * @see {@link provideServiceEffect} for acquiring the service implementation effectfully. + * @see {@link provideContext} for providing a complete context. + * @category context * @since 2.0.0 - * @category Context */ (service: Context.Key): { /** - * The `provideService` function is used to provide an actual - * implementation for a service in the context of an effect. + * Provides one concrete service implementation to an effect. * - * This function allows you to associate a service with its implementation so - * that it can be used in your program. You define the service (e.g., a random - * number generator), and then you use `provideService` to link that - * service to its implementation. Once the implementation is provided, the - * effect can be run successfully without further requirements. + * **When to use** * - * @see {@link provide} for providing multiple layers to an effect. + * Use to satisfy one service requirement with an already-built implementation. + * + * **Details** + * + * The service requirement identified by the `Context.Key` is removed from the + * effect requirements after the implementation is provided. + * + * **Example** (Providing a service value) * - * @example * ```ts - * import { Console, Effect, Context } from "effect" + * import { Console, Context, Effect } from "effect" * * // Define a service for configuration * const Config = Context.Service<{ @@ -11446,25 +12152,29 @@ export const provideService: { * // data * ``` * + * @see {@link provide} for providing multiple layers to an effect. + * @see {@link provideServiceEffect} for acquiring the service implementation effectfully. + * @see {@link provideContext} for providing a complete context. + * @category context * @since 2.0.0 - * @category Context */ (implementation: S): (self: Effect) => Effect> /** - * The `provideService` function is used to provide an actual - * implementation for a service in the context of an effect. + * Provides one concrete service implementation to an effect. * - * This function allows you to associate a service with its implementation so - * that it can be used in your program. You define the service (e.g., a random - * number generator), and then you use `provideService` to link that - * service to its implementation. Once the implementation is provided, the - * effect can be run successfully without further requirements. + * **When to use** * - * @see {@link provide} for providing multiple layers to an effect. + * Use to satisfy one service requirement with an already-built implementation. + * + * **Details** + * + * The service requirement identified by the `Context.Key` is removed from the + * effect requirements after the implementation is provided. + * + * **Example** (Providing a service value) * - * @example * ```ts - * import { Console, Effect, Context } from "effect" + * import { Console, Context, Effect } from "effect" * * // Define a service for configuration * const Config = Context.Service<{ @@ -11492,26 +12202,30 @@ export const provideService: { * // data * ``` * + * @see {@link provide} for providing multiple layers to an effect. + * @see {@link provideServiceEffect} for acquiring the service implementation effectfully. + * @see {@link provideContext} for providing a complete context. + * @category context * @since 2.0.0 - * @category Context */ (self: Effect, implementation: S): Effect> } /** - * The `provideService` function is used to provide an actual - * implementation for a service in the context of an effect. + * Provides one concrete service implementation to an effect. * - * This function allows you to associate a service with its implementation so - * that it can be used in your program. You define the service (e.g., a random - * number generator), and then you use `provideService` to link that - * service to its implementation. Once the implementation is provided, the - * effect can be run successfully without further requirements. + * **When to use** * - * @see {@link provide} for providing multiple layers to an effect. + * Use to satisfy one service requirement with an already-built implementation. + * + * **Details** + * + * The service requirement identified by the `Context.Key` is removed from the + * effect requirements after the implementation is provided. + * + * **Example** (Providing a service value) * - * @example * ```ts - * import { Console, Effect, Context } from "effect" + * import { Console, Context, Effect } from "effect" * * // Define a service for configuration * const Config = Context.Service<{ @@ -11539,25 +12253,29 @@ export const provideService: { * // data * ``` * + * @see {@link provide} for providing multiple layers to an effect. + * @see {@link provideServiceEffect} for acquiring the service implementation effectfully. + * @see {@link provideContext} for providing a complete context. + * @category context * @since 2.0.0 - * @category Context */ (service: Context.Key, implementation: S): (self: Effect) => Effect> /** - * The `provideService` function is used to provide an actual - * implementation for a service in the context of an effect. + * Provides one concrete service implementation to an effect. * - * This function allows you to associate a service with its implementation so - * that it can be used in your program. You define the service (e.g., a random - * number generator), and then you use `provideService` to link that - * service to its implementation. Once the implementation is provided, the - * effect can be run successfully without further requirements. + * **When to use** * - * @see {@link provide} for providing multiple layers to an effect. + * Use to satisfy one service requirement with an already-built implementation. + * + * **Details** + * + * The service requirement identified by the `Context.Key` is removed from the + * effect requirements after the implementation is provided. + * + * **Example** (Providing a service value) * - * @example * ```ts - * import { Console, Effect, Context } from "effect" + * import { Console, Context, Effect } from "effect" * * // Define a service for configuration * const Config = Context.Service<{ @@ -11585,25 +12303,34 @@ export const provideService: { * // data * ``` * + * @see {@link provide} for providing multiple layers to an effect. + * @see {@link provideServiceEffect} for acquiring the service implementation effectfully. + * @see {@link provideContext} for providing a complete context. + * @category context * @since 2.0.0 - * @category Context */ (self: Effect, service: Context.Key, implementation: S): Effect> } = internal.provideService /** - * Provides the effect with the single service it requires. If the effect - * requires more than one service use `provide` instead. + * Provides one service to an effect using an effectful acquisition. + * + * **When to use** + * + * Use when the service implementation must be created by an effect and its + * acquisition failure should remain in the returned effect. * - * This function is similar to `provideService`, but instead of providing a - * static service implementation, it allows you to provide an effect that - * will produce the service. This is useful when the service needs to be - * acquired through an effectful computation (e.g., reading from a database, - * making an HTTP request, or allocating resources). + * **Details** + * + * `provideServiceEffect` runs the acquisition effect to produce the service + * implementation, removes that service from the wrapped effect's requirements, + * and leaves any other requirements to be provided later. Acquisition failures + * are included in the returned effect's error channel. + * + * **Example** (Providing a service with an effect) * - * @example * ```ts - * import { Console, Effect, Context } from "effect" + * import { Console, Context, Effect } from "effect" * * // Define a database connection service * interface DatabaseConnection { @@ -11640,23 +12367,29 @@ export const provideService: { * // Result for: SELECT * FROM users * ``` * + * @category context * @since 2.0.0 - * @category Context */ export const provideServiceEffect: { /** - * Provides the effect with the single service it requires. If the effect - * requires more than one service use `provide` instead. + * Provides one service to an effect using an effectful acquisition. + * + * **When to use** + * + * Use when the service implementation must be created by an effect and its + * acquisition failure should remain in the returned effect. + * + * **Details** + * + * `provideServiceEffect` runs the acquisition effect to produce the service + * implementation, removes that service from the wrapped effect's requirements, + * and leaves any other requirements to be provided later. Acquisition failures + * are included in the returned effect's error channel. * - * This function is similar to `provideService`, but instead of providing a - * static service implementation, it allows you to provide an effect that - * will produce the service. This is useful when the service needs to be - * acquired through an effectful computation (e.g., reading from a database, - * making an HTTP request, or allocating resources). + * **Example** (Providing a service with an effect) * - * @example * ```ts - * import { Console, Effect, Context } from "effect" + * import { Console, Context, Effect } from "effect" * * // Define a database connection service * interface DatabaseConnection { @@ -11693,23 +12426,29 @@ export const provideServiceEffect: { * // Result for: SELECT * FROM users * ``` * + * @category context * @since 2.0.0 - * @category Context */ (service: Context.Key, acquire: Effect): (self: Effect) => Effect | R2> /** - * Provides the effect with the single service it requires. If the effect - * requires more than one service use `provide` instead. + * Provides one service to an effect using an effectful acquisition. * - * This function is similar to `provideService`, but instead of providing a - * static service implementation, it allows you to provide an effect that - * will produce the service. This is useful when the service needs to be - * acquired through an effectful computation (e.g., reading from a database, - * making an HTTP request, or allocating resources). + * **When to use** + * + * Use when the service implementation must be created by an effect and its + * acquisition failure should remain in the returned effect. + * + * **Details** + * + * `provideServiceEffect` runs the acquisition effect to produce the service + * implementation, removes that service from the wrapped effect's requirements, + * and leaves any other requirements to be provided later. Acquisition failures + * are included in the returned effect's error channel. + * + * **Example** (Providing a service with an effect) * - * @example * ```ts - * import { Console, Effect, Context } from "effect" + * import { Console, Context, Effect } from "effect" * * // Define a database connection service * interface DatabaseConnection { @@ -11746,8 +12485,8 @@ export const provideServiceEffect: { * // Result for: SELECT * FROM users * ``` * + * @category context * @since 2.0.0 - * @category Context */ ( self: Effect, @@ -11763,7 +12502,8 @@ export const provideServiceEffect: { /** * Sets the concurrency level for parallel operations within an effect. * - * @example + * **Example** (Setting local concurrency) + * * ```ts * import { Console, Effect } from "effect" * @@ -11788,8 +12528,8 @@ export const provideServiceEffect: { * // [1, 2, 3, 4, 5] * ``` * + * @category references * @since 2.0.0 - * @category References */ export const withConcurrency: { // ----------------------------------------------------------------------------- @@ -11799,7 +12539,8 @@ export const withConcurrency: { /** * Sets the concurrency level for parallel operations within an effect. * - * @example + * **Example** (Setting local concurrency) + * * ```ts * import { Console, Effect } from "effect" * @@ -11824,8 +12565,8 @@ export const withConcurrency: { * // [1, 2, 3, 4, 5] * ``` * + * @category references * @since 2.0.0 - * @category References */ (concurrency: number | "unbounded"): (self: Effect) => Effect // ----------------------------------------------------------------------------- @@ -11835,7 +12576,8 @@ export const withConcurrency: { /** * Sets the concurrency level for parallel operations within an effect. * - * @example + * **Example** (Setting local concurrency) + * * ```ts * import { Console, Effect } from "effect" * @@ -11860,8 +12602,8 @@ export const withConcurrency: { * // [1, 2, 3, 4, 5] * ``` * + * @category references * @since 2.0.0 - * @category References */ (self: Effect, concurrency: number | "unbounded"): Effect } = internal.withConcurrency @@ -11873,7 +12615,8 @@ export const withConcurrency: { /** * Returns the current scope for resource management. * - * @example + * **Example** (Accessing the current scope) + * * ```ts * import { Console, Effect } from "effect" * @@ -11898,17 +12641,25 @@ export const withConcurrency: { * // Releasing resource * ``` * + * @category resource management * @since 2.0.0 - * @category Resource Management & Finalization */ export const scope: Effect = internal.scope /** - * Scopes all resources used in this workflow to the lifetime of the workflow, - * ensuring that their finalizers are run as soon as this workflow completes - * execution, whether by success, failure, or interruption. + * Runs an effect with a scope that closes when the effect completes. + * + * **When to use** + * + * Use to acquire scoped resources for the duration of a single workflow. + * + * **Details** + * + * Finalizers for resources acquired inside the workflow run as soon as the + * workflow completes, whether by success, failure, or interruption. + * + * **Example** (Running a scoped acquisition) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -11931,8 +12682,8 @@ export const scope: Effect = internal.scope * // Output: "Releasing resource" * ``` * + * @category resource management * @since 2.0.0 - * @category Resource Management & Finalization */ export const scoped: ( self: Effect @@ -11941,7 +12692,13 @@ export const scoped: ( /** * Creates a scoped effect by providing access to the scope. * - * @example + * **When to use** + * + * Use when resource acquisition needs direct access to the scope being created, + * for example to register finalizers manually. + * + * **Example** (Working with an explicit scope) + * * ```ts * import { Console, Effect, Scope } from "effect" * @@ -11973,27 +12730,32 @@ export const scoped: ( * // Manual finalizer * ``` * - * @since 2.0.0 - * @category Resource Management & Finalization + * @category resource management + * @since 3.11.0 */ export const scopedWith: ( f: (scope: Scope) => Effect ) => Effect = internal.scopedWith /** - * This function constructs a scoped resource from an `acquire` and `release` - * `Effect` value. + * Constructs a scoped resource from an acquisition effect and a release + * finalizer. + * + * **When to use** + * + * Use to acquire a scoped resource with an explicit release finalizer. + * + * **Details** + * + * If acquisition succeeds, the release finalizer is added to the current scope + * and is guaranteed to run when that scope closes. The finalizer receives the + * `Exit` value used to close the scope. * - * If the `acquire` `Effect` value successfully completes execution, then the - * `release` `Effect` value will be added to the finalizers associated with the - * scope of this `Effect` value, and it is guaranteed to be run when the scope - * is closed. + * By default, acquisition is protected by an uninterruptible region. Pass + * `{ interruptible: true }` to allow the acquisition effect to be interrupted. * - * The `acquire` and `release` `Effect` values will be run uninterruptibly. - * Additionally, the `release` `Effect` value may depend on the `Exit` value - * specified when the scope is closed. + * **Example** (Acquiring and releasing a resource) * - * @example * ```ts * import { Console, Effect, Exit } from "effect" * @@ -12030,8 +12792,11 @@ export const scopedWith: ( * ) * ``` * + * @see {@link acquireDisposable} for resources that implement JavaScript disposal protocols + * @see {@link acquireUseRelease} for bracketing acquire, use, and release in one effect + * + * @category resource management * @since 2.0.0 - * @category Resource Management & Finalization */ export const acquireRelease: ( acquire: Effect, @@ -12040,8 +12805,14 @@ export const acquireRelease: ( ) => Effect = internal.acquireRelease /** - * This function constructs a scoped resource from an Effect that acquires a - * disposable value. + * Acquires a scoped resource that implements JavaScript disposal protocols. + * + * **When to use** + * + * Use when you work with JavaScript `Disposable` or `AsyncDisposable` resources + * that should be closed with the surrounding scope. + * + * **Details** * * The resource is automatically disposed when the surrounding * {@link Scope} is closed, using {@link Symbol.dispose} for @@ -12049,15 +12820,15 @@ export const acquireRelease: ( * disposables. * * This is similar to {@link acquireRelease}, but uses the standard - * JavaScript disposal protocal instead of requiring an explicit release - * function. + * JavaScript disposal protocol instead of requiring an explicit release + * function. It works with JavaScript `Disposable` and `AsyncDisposable` + * resources. * - * @see {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/using} + * **Example** (Acquiring a disposable resource) * - * @example * ```ts * import sqlite from "node:sqlite"; - * import { Effect } from "effect"; + * import { Effect } from "effect" * * const program = Effect.scoped( * Effect.gen(function* () { @@ -12073,18 +12844,23 @@ export const acquireRelease: ( * ) * ``` * + * @see {@link acquireRelease} for resources that need an explicit finalizer + * + * @category resource management * @since 4.0.0 - * @category Resource Management & Finalization */ export const acquireDisposable: ( acquire: Effect ) => Effect = internal.acquireDisposable /** - * This function is used to ensure that an `Effect` value that represents the - * acquisition of a resource (for example, opening a file, launching a thread, - * etc.) will not be interrupted, and that the resource will always be released - * when the `Effect` value completes execution. + * Runs resource acquisition, usage, and release as one bracketed effect. + * + * **When to use** + * + * Use to bracket acquire, use, and release logic in one effect. + * + * **Details** * * `acquireUseRelease` does the following: * @@ -12103,7 +12879,8 @@ export const acquireDisposable: ( * is not desired, errors produced by the `release` `Effect` value can be caught * and ignored. * - * @example + * **Example** (Using a resource with cleanup) + * * ```ts * import { Console, Effect, Exit } from "effect" * @@ -12148,8 +12925,10 @@ export const acquireDisposable: ( * // Closing connection to db://localhost:5432 (success) * ``` * + * @see {@link acquireRelease} for scoped resources whose use happens later + * + * @category resource management * @since 2.0.0 - * @category Resource Management & Finalization */ export const acquireUseRelease: ( acquire: Effect, @@ -12158,15 +12937,19 @@ export const acquireUseRelease: ( ) => Effect = internal.acquireUseRelease /** - * This function adds a finalizer to the scope of the calling `Effect` value. - * The finalizer is guaranteed to be run when the scope is closed, and it may - * depend on the `Exit` value that the scope is closed with. + * Adds a finalizer to the current scope. + * + * **When to use** + * + * Use to register low-level cleanup in the current scope. * - * Finalizers are useful for cleanup operations that must run regardless of - * whether the effect succeeds or fails. They're commonly used for resource - * cleanup, logging, or other side effects that should always occur. + * **Details** + * + * The finalizer runs when the surrounding scope is closed and receives the + * `Exit` value used to close the scope. + * + * **Example** (Registering scope finalizers) * - * @example * ```ts * import { Console, Effect, Exit } from "effect" * @@ -12195,8 +12978,11 @@ export const acquireUseRelease: ( * // operation result * ``` * + * @see {@link acquireRelease} for resource acquisition with a release finalizer + * @see {@link ensuring} for attaching a finalizer to one effect + * + * @category resource management * @since 2.0.0 - * @category Resource Management & Finalization */ export const addFinalizer: ( finalizer: (exit: Exit.Exit) => Effect @@ -12207,13 +12993,16 @@ export const addFinalizer: ( * specified `finalizer` is guaranteed to be executed, whether this effect * succeeds, fails, or is interrupted. * + * **Details** + * * For use cases that need access to the effect's result, see `onExit`. * * Finalizers offer very powerful guarantees, but they are low-level, and * should generally not be used for releasing resources. For higher-level * logic built on `ensuring`, see the `acquireRelease` family of methods. * - * @example + * **Example** (Always running cleanup) + * * ```ts * import { Console, Effect } from "effect" * @@ -12238,8 +13027,8 @@ export const addFinalizer: ( * // 42 * ``` * + * @category resource management * @since 2.0.0 - * @category Resource Management & Finalization */ export const ensuring: { /** @@ -12247,13 +13036,16 @@ export const ensuring: { * specified `finalizer` is guaranteed to be executed, whether this effect * succeeds, fails, or is interrupted. * + * **Details** + * * For use cases that need access to the effect's result, see `onExit`. * * Finalizers offer very powerful guarantees, but they are low-level, and * should generally not be used for releasing resources. For higher-level * logic built on `ensuring`, see the `acquireRelease` family of methods. * - * @example + * **Example** (Always running cleanup) + * * ```ts * import { Console, Effect } from "effect" * @@ -12278,8 +13070,8 @@ export const ensuring: { * // 42 * ``` * + * @category resource management * @since 2.0.0 - * @category Resource Management & Finalization */ (finalizer: Effect): (self: Effect) => Effect /** @@ -12287,13 +13079,16 @@ export const ensuring: { * specified `finalizer` is guaranteed to be executed, whether this effect * succeeds, fails, or is interrupted. * + * **Details** + * * For use cases that need access to the effect's result, see `onExit`. * * Finalizers offer very powerful guarantees, but they are low-level, and * should generally not be used for releasing resources. For higher-level * logic built on `ensuring`, see the `acquireRelease` family of methods. * - * @example + * **Example** (Always running cleanup) + * * ```ts * import { Console, Effect } from "effect" * @@ -12318,8 +13113,8 @@ export const ensuring: { * // 42 * ``` * + * @category resource management * @since 2.0.0 - * @category Resource Management & Finalization */ (self: Effect, finalizer: Effect): Effect } = internal.ensuring @@ -12328,9 +13123,10 @@ export const ensuring: { * Runs the specified effect if this effect fails, providing the error to the * effect if it exists. The provided effect will not be interrupted. * - * @example + * **Example** (Running cleanup on failure) + * * ```ts - * import { Cause, Data, Console, Effect } from "effect" + * import { Cause, Console, Data, Effect } from "effect" * * class TaskError extends Data.TaggedError("TaskError")<{ readonly message: string }> {} * @@ -12347,17 +13143,18 @@ export const ensuring: { * // TaskError: Something went wrong * ``` * + * @category resource management * @since 2.0.0 - * @category Resource Management & Finalization */ export const onError: { /** * Runs the specified effect if this effect fails, providing the error to the * effect if it exists. The provided effect will not be interrupted. * - * @example + * **Example** (Running cleanup on failure) + * * ```ts - * import { Cause, Data, Console, Effect } from "effect" + * import { Cause, Console, Data, Effect } from "effect" * * class TaskError extends Data.TaggedError("TaskError")<{ readonly message: string }> {} * @@ -12374,17 +13171,18 @@ export const onError: { * // TaskError: Something went wrong * ``` * + * @category resource management * @since 2.0.0 - * @category Resource Management & Finalization */ (cleanup: (cause: Cause.Cause) => Effect): (self: Effect) => Effect /** * Runs the specified effect if this effect fails, providing the error to the * effect if it exists. The provided effect will not be interrupted. * - * @example + * **Example** (Running cleanup on failure) + * * ```ts - * import { Cause, Data, Console, Effect } from "effect" + * import { Cause, Console, Data, Effect } from "effect" * * class TaskError extends Data.TaggedError("TaskError")<{ readonly message: string }> {} * @@ -12401,8 +13199,8 @@ export const onError: { * // TaskError: Something went wrong * ``` * + * @category resource management * @since 2.0.0 - * @category Resource Management & Finalization */ ( self: Effect, @@ -12414,7 +13212,8 @@ export const onError: { * Runs the finalizer only when this effect fails and the `Cause` matches the * provided predicate. * - * @example + * **Example** (Running cleanup for selected failures) + * * ```ts * import { Cause, Console, Effect } from "effect" * @@ -12430,15 +13229,16 @@ export const onError: { * ) * ``` * + * @category resource management * @since 4.0.0 - * @category Resource Management & Finalization */ export const onErrorIf: { /** * Runs the finalizer only when this effect fails and the `Cause` matches the * provided predicate. * - * @example + * **Example** (Running cleanup for selected failures) + * * ```ts * import { Cause, Console, Effect } from "effect" * @@ -12454,8 +13254,8 @@ export const onErrorIf: { * ) * ``` * + * @category resource management * @since 4.0.0 - * @category Resource Management & Finalization */ ( predicate: Predicate.Predicate>, @@ -12465,7 +13265,8 @@ export const onErrorIf: { * Runs the finalizer only when this effect fails and the `Cause` matches the * provided predicate. * - * @example + * **Example** (Running cleanup for selected failures) + * * ```ts * import { Cause, Console, Effect } from "effect" * @@ -12481,8 +13282,8 @@ export const onErrorIf: { * ) * ``` * + * @category resource management * @since 4.0.0 - * @category Resource Management & Finalization */ ( self: Effect, @@ -12494,15 +13295,35 @@ export const onErrorIf: { /** * Runs the finalizer only when this effect fails and the cause matches the provided `Filter`. * + * **When to use** + * + * Use when cleanup or diagnostics should run only for failures whose full + * `Cause` is accepted or transformed by a `Filter`, and the finalizer needs the + * filter's pass value plus the original cause. + * + * @see {@link onError} for cleanup on every failure + * @see {@link onErrorIf} for selecting failures with a boolean predicate + * @see {@link onExitFilter} for selecting from every exit instead of only failures + * + * @category resource management * @since 4.0.0 - * @category Resource Management & Finalization */ export const onErrorFilter: { /** * Runs the finalizer only when this effect fails and the cause matches the provided `Filter`. * + * **When to use** + * + * Use when cleanup or diagnostics should run only for failures whose full + * `Cause` is accepted or transformed by a `Filter`, and the finalizer needs the + * filter's pass value plus the original cause. + * + * @see {@link onError} for cleanup on every failure + * @see {@link onErrorIf} for selecting failures with a boolean predicate + * @see {@link onExitFilter} for selecting from every exit instead of only failures + * + * @category resource management * @since 4.0.0 - * @category Resource Management & Finalization */ ( filter: Filter.Filter, EB, X>, @@ -12511,8 +13332,18 @@ export const onErrorFilter: { /** * Runs the finalizer only when this effect fails and the cause matches the provided `Filter`. * + * **When to use** + * + * Use when cleanup or diagnostics should run only for failures whose full + * `Cause` is accepted or transformed by a `Filter`, and the finalizer needs the + * filter's pass value plus the original cause. + * + * @see {@link onError} for cleanup on every failure + * @see {@link onErrorIf} for selecting failures with a boolean predicate + * @see {@link onExitFilter} for selecting from every exit instead of only failures + * + * @category resource management * @since 4.0.0 - * @category Resource Management & Finalization */ ( self: Effect, @@ -12522,12 +13353,24 @@ export const onErrorFilter: { } = internal.onErrorFilter /** - * The low level primitive that powers `onExit`. - * function is used to run a finalizer when the effect exits, regardless of the - * exit status. + * Runs an optional finalizer with the effect's `Exit` value when the effect + * completes. * - * @since 2.0.0 - * @category Resource Management & Finalization + * **When to use** + * + * Use when you are building a low-level `Effect` operator that must inspect the + * source effect's `Exit`, may skip finalization by returning `undefined`, or + * must choose whether finalization is forced into an uninterruptible region. + * + * **Details** + * + * This low-level operator preserves the source effect's result unless the + * finalizer fails. Prefer `onExit` for normal cleanup logic. + * + * @see {@link onExit} for ordinary exit-aware cleanup whose finalizer always returns an effect + * + * @category resource management + * @since 4.0.0 */ export const onExitPrimitive: ( self: Effect, @@ -12536,10 +13379,11 @@ export const onExitPrimitive: ( ) => Effect = internal.onExitPrimitive /** - * Ensures that a cleanup functions runs, whether this effect succeeds, fails, - * or is interrupted. + * Ensures that a cleanup function runs whether this effect succeeds, fails, or + * is interrupted. + * + * **Example** (Observing every exit) * - * @example * ```ts * import { Console, Effect, Exit } from "effect" * @@ -12558,15 +13402,16 @@ export const onExitPrimitive: ( * // 42 * ``` * + * @category resource management * @since 2.0.0 - * @category Resource Management & Finalization */ export const onExit: { /** - * Ensures that a cleanup functions runs, whether this effect succeeds, fails, - * or is interrupted. + * Ensures that a cleanup function runs whether this effect succeeds, fails, or + * is interrupted. + * + * **Example** (Observing every exit) * - * @example * ```ts * import { Console, Effect, Exit } from "effect" * @@ -12585,15 +13430,16 @@ export const onExit: { * // 42 * ``` * + * @category resource management * @since 2.0.0 - * @category Resource Management & Finalization */ (f: (exit: Exit.Exit) => Effect): (self: Effect) => Effect /** - * Ensures that a cleanup functions runs, whether this effect succeeds, fails, - * or is interrupted. + * Ensures that a cleanup function runs whether this effect succeeds, fails, or + * is interrupted. + * + * **Example** (Observing every exit) * - * @example * ```ts * import { Console, Effect, Exit } from "effect" * @@ -12612,8 +13458,8 @@ export const onExit: { * // 42 * ``` * + * @category resource management * @since 2.0.0 - * @category Resource Management & Finalization */ (self: Effect, f: (exit: Exit.Exit) => Effect): Effect } = internal.onExit @@ -12622,7 +13468,8 @@ export const onExit: { * Runs the cleanup effect only when the `Exit` satisfies the provided * predicate. * - * @example + * **Example** (Observing selected exits) + * * ```ts * import { Console, Effect, Exit } from "effect" * @@ -12636,15 +13483,16 @@ export const onExit: { * ) * ``` * + * @category resource management * @since 4.0.0 - * @category Resource Management & Finalization */ export const onExitIf: { /** * Runs the cleanup effect only when the `Exit` satisfies the provided * predicate. * - * @example + * **Example** (Observing selected exits) + * * ```ts * import { Console, Effect, Exit } from "effect" * @@ -12658,8 +13506,8 @@ export const onExitIf: { * ) * ``` * + * @category resource management * @since 4.0.0 - * @category Resource Management & Finalization */ ( predicate: Predicate.Predicate, NoInfer>>, @@ -12669,7 +13517,8 @@ export const onExitIf: { * Runs the cleanup effect only when the `Exit` satisfies the provided * predicate. * - * @example + * **Example** (Observing selected exits) + * * ```ts * import { Console, Effect, Exit } from "effect" * @@ -12683,8 +13532,8 @@ export const onExitIf: { * ) * ``` * + * @category resource management * @since 4.0.0 - * @category Resource Management & Finalization */ ( self: Effect, @@ -12696,15 +13545,45 @@ export const onExitIf: { /** * Runs the cleanup effect only when the `Exit` matches the provided `Filter`. * + * **When to use** + * + * Use when cleanup should run only for `Exit` values selected by a `Filter`, + * and the cleanup needs the extracted pass value together with the original + * `Exit`. + * + * **Details** + * + * `Result.fail` skips cleanup, and `Result.succeed` runs cleanup with the + * selected value and the original `Exit`. + * + * @see {@link onExit} for cleanup on every exit + * @see {@link onExitIf} for selecting exits with a boolean predicate + * @see {@link onErrorFilter} for selecting only failure causes + * + * @category resource management * @since 4.0.0 - * @category Resource Management & Finalization */ export const onExitFilter: { /** * Runs the cleanup effect only when the `Exit` matches the provided `Filter`. * + * **When to use** + * + * Use when cleanup should run only for `Exit` values selected by a `Filter`, + * and the cleanup needs the extracted pass value together with the original + * `Exit`. + * + * **Details** + * + * `Result.fail` skips cleanup, and `Result.succeed` runs cleanup with the + * selected value and the original `Exit`. + * + * @see {@link onExit} for cleanup on every exit + * @see {@link onExitIf} for selecting exits with a boolean predicate + * @see {@link onErrorFilter} for selecting only failure causes + * + * @category resource management * @since 4.0.0 - * @category Resource Management & Finalization */ ( filter: Filter.Filter, NoInfer>, B, X>, @@ -12713,8 +13592,23 @@ export const onExitFilter: { /** * Runs the cleanup effect only when the `Exit` matches the provided `Filter`. * + * **When to use** + * + * Use when cleanup should run only for `Exit` values selected by a `Filter`, + * and the cleanup needs the extracted pass value together with the original + * `Exit`. + * + * **Details** + * + * `Result.fail` skips cleanup, and `Result.succeed` runs cleanup with the + * selected value and the original `Exit`. + * + * @see {@link onExit} for cleanup on every exit + * @see {@link onExitIf} for selecting exits with a boolean predicate + * @see {@link onErrorFilter} for selecting only failure causes + * + * @category resource management * @since 4.0.0 - * @category Resource Management & Finalization */ ( self: Effect, @@ -12731,6 +13625,11 @@ export const onExitFilter: { * Returns an effect that lazily computes a result and caches it for subsequent * evaluations. * + * **When to use** + * + * Use when you need an expensive or time-consuming operation to be evaluated + * once and reused by later callers. + * * **Details** * * This function wraps an effect and ensures that its result is computed only @@ -12738,19 +13637,8 @@ export const onExitFilter: { * evaluations of the same effect will return the cached result without * re-executing the logic. * - * **When to Use** - * - * Use this function when you have an expensive or time-consuming operation that - * you want to avoid repeating. The first evaluation will compute the result, - * and all following evaluations will immediately return the cached value, - * improving performance and reducing unnecessary work. + * **Example** (Memoizing an effect until invalidated) * - * @see {@link cachedWithTTL} for a similar function that includes a - * time-to-live duration for the cached value. - * @see {@link cachedInvalidateWithTTL} for a similar function that includes an - * additional effect for manually invalidating the cached value. - * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -12787,8 +13675,12 @@ export const onExitFilter: { * // result 3 * ``` * + * @see {@link cachedWithTTL} for a similar function that includes a + * time-to-live duration for the cached value. + * @see {@link cachedInvalidateWithTTL} for a similar function that includes an + * additional effect for manually invalidating the cached value. + * @category caching * @since 2.0.0 - * @category Caching */ export const cached: (self: Effect) => Effect> = internal.cached @@ -12796,6 +13688,11 @@ export const cached: (self: Effect) => Effect> * Returns an effect that caches its result for a specified `Duration`, * known as "timeToLive" (TTL). * + * **When to use** + * + * Use when you need a costly effect result to be reused for a bounded duration + * before being recomputed. + * * **Details** * * This function is used to cache the result of an effect for a specified amount @@ -12808,23 +13705,8 @@ export const cached: (self: Effect) => Effect> * After the specified duration has passed, the cache expires, and the effect * will be recomputed upon the next evaluation. * - * **When to Use** - * - * Use this function when you have an effect that involves costly operations or - * computations, and you want to avoid repeating them within a short time frame. - * - * It's ideal for scenarios where the result of an effect doesn't change - * frequently and can be reused for a specified duration. - * - * By caching the result, you can improve efficiency and reduce unnecessary - * computations, especially in performance-critical applications. - * - * @see {@link cached} for a similar function that caches the result - * indefinitely. - * @see {@link cachedInvalidateWithTTL} for a similar function that includes an - * additional effect for manually invalidating the cached value. + * **Example** (Memoizing an effect with TTL) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -12855,14 +13737,23 @@ export const cached: (self: Effect) => Effect> * // result 2 * ``` * + * @see {@link cached} for a similar function that caches the result + * indefinitely. + * @see {@link cachedInvalidateWithTTL} for a similar function that includes an + * additional effect for manually invalidating the cached value. + * @category caching * @since 2.0.0 - * @category Caching */ export const cachedWithTTL: { /** * Returns an effect that caches its result for a specified `Duration`, * known as "timeToLive" (TTL). * + * **When to use** + * + * Use when you need a costly effect result to be reused for a bounded duration + * before being recomputed. + * * **Details** * * This function is used to cache the result of an effect for a specified amount @@ -12875,23 +13766,8 @@ export const cachedWithTTL: { * After the specified duration has passed, the cache expires, and the effect * will be recomputed upon the next evaluation. * - * **When to Use** - * - * Use this function when you have an effect that involves costly operations or - * computations, and you want to avoid repeating them within a short time frame. - * - * It's ideal for scenarios where the result of an effect doesn't change - * frequently and can be reused for a specified duration. - * - * By caching the result, you can improve efficiency and reduce unnecessary - * computations, especially in performance-critical applications. - * - * @see {@link cached} for a similar function that caches the result - * indefinitely. - * @see {@link cachedInvalidateWithTTL} for a similar function that includes an - * additional effect for manually invalidating the cached value. + * **Example** (Memoizing an effect with TTL) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -12922,14 +13798,23 @@ export const cachedWithTTL: { * // result 2 * ``` * + * @see {@link cached} for a similar function that caches the result + * indefinitely. + * @see {@link cachedInvalidateWithTTL} for a similar function that includes an + * additional effect for manually invalidating the cached value. + * @category caching * @since 2.0.0 - * @category Caching */ (timeToLive: Duration.Input): (self: Effect) => Effect> /** * Returns an effect that caches its result for a specified `Duration`, * known as "timeToLive" (TTL). * + * **When to use** + * + * Use when you need a costly effect result to be reused for a bounded duration + * before being recomputed. + * * **Details** * * This function is used to cache the result of an effect for a specified amount @@ -12942,23 +13827,8 @@ export const cachedWithTTL: { * After the specified duration has passed, the cache expires, and the effect * will be recomputed upon the next evaluation. * - * **When to Use** - * - * Use this function when you have an effect that involves costly operations or - * computations, and you want to avoid repeating them within a short time frame. + * **Example** (Memoizing an effect with TTL) * - * It's ideal for scenarios where the result of an effect doesn't change - * frequently and can be reused for a specified duration. - * - * By caching the result, you can improve efficiency and reduce unnecessary - * computations, especially in performance-critical applications. - * - * @see {@link cached} for a similar function that caches the result - * indefinitely. - * @see {@link cachedInvalidateWithTTL} for a similar function that includes an - * additional effect for manually invalidating the cached value. - * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -12989,16 +13859,26 @@ export const cachedWithTTL: { * // result 2 * ``` * + * @see {@link cached} for a similar function that caches the result + * indefinitely. + * @see {@link cachedInvalidateWithTTL} for a similar function that includes an + * additional effect for manually invalidating the cached value. + * @category caching * @since 2.0.0 - * @category Caching */ (self: Effect, timeToLive: Duration.Input): Effect> } = internal.cachedWithTTL /** - * Caches an effect's result for a specified duration and allows manual + * Creates a cached effect result for a specified duration and allows manual * invalidation before expiration. * + * **When to use** + * + * Use when an effect result should be cached for a bounded time and callers + * also need a manual invalidation effect to force recomputation before + * expiration. + * * **Details** * * This function behaves similarly to {@link cachedWithTTL} by caching the @@ -13012,22 +13892,8 @@ export const cachedWithTTL: { * Once the cache is invalidated, the next time the effect is evaluated, the * result will be recomputed, and the cache will be refreshed. * - * **When to Use** - * - * Use this function when you have an effect whose result needs to be cached for - * a certain period, but you also want the option to refresh the cache manually - * before the expiration time. - * - * This is useful when you need to ensure that the cached data remains valid for - * a certain period but still want to invalidate it if the underlying data - * changes or if you want to force a recomputation. - * - * @see {@link cached} for a similar function that caches the result - * indefinitely. - * @see {@link cachedWithTTL} for a similar function that caches the result for - * a specified duration but does not include an effect for manual invalidation. + * **Example** (Memoizing with TTL and invalidation) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -13061,14 +13927,24 @@ export const cachedWithTTL: { * // result 2 * ``` * + * @see {@link cached} for a similar function that caches the result + * indefinitely. + * @see {@link cachedWithTTL} for a similar function that caches the result for + * a specified duration but does not include an effect for manual invalidation. + * @category caching * @since 2.0.0 - * @category Caching */ export const cachedInvalidateWithTTL: { /** - * Caches an effect's result for a specified duration and allows manual + * Creates a cached effect result for a specified duration and allows manual * invalidation before expiration. * + * **When to use** + * + * Use when an effect result should be cached for a bounded time and callers + * also need a manual invalidation effect to force recomputation before + * expiration. + * * **Details** * * This function behaves similarly to {@link cachedWithTTL} by caching the @@ -13082,22 +13958,8 @@ export const cachedInvalidateWithTTL: { * Once the cache is invalidated, the next time the effect is evaluated, the * result will be recomputed, and the cache will be refreshed. * - * **When to Use** - * - * Use this function when you have an effect whose result needs to be cached for - * a certain period, but you also want the option to refresh the cache manually - * before the expiration time. - * - * This is useful when you need to ensure that the cached data remains valid for - * a certain period but still want to invalidate it if the underlying data - * changes or if you want to force a recomputation. - * - * @see {@link cached} for a similar function that caches the result - * indefinitely. - * @see {@link cachedWithTTL} for a similar function that caches the result for - * a specified duration but does not include an effect for manual invalidation. + * **Example** (Memoizing with TTL and invalidation) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -13131,14 +13993,24 @@ export const cachedInvalidateWithTTL: { * // result 2 * ``` * + * @see {@link cached} for a similar function that caches the result + * indefinitely. + * @see {@link cachedWithTTL} for a similar function that caches the result for + * a specified duration but does not include an effect for manual invalidation. + * @category caching * @since 2.0.0 - * @category Caching */ (timeToLive: Duration.Input): (self: Effect) => Effect<[Effect, Effect]> /** - * Caches an effect's result for a specified duration and allows manual + * Creates a cached effect result for a specified duration and allows manual * invalidation before expiration. * + * **When to use** + * + * Use when an effect result should be cached for a bounded time and callers + * also need a manual invalidation effect to force recomputation before + * expiration. + * * **Details** * * This function behaves similarly to {@link cachedWithTTL} by caching the @@ -13152,22 +14024,8 @@ export const cachedInvalidateWithTTL: { * Once the cache is invalidated, the next time the effect is evaluated, the * result will be recomputed, and the cache will be refreshed. * - * **When to Use** - * - * Use this function when you have an effect whose result needs to be cached for - * a certain period, but you also want the option to refresh the cache manually - * before the expiration time. + * **Example** (Memoizing with TTL and invalidation) * - * This is useful when you need to ensure that the cached data remains valid for - * a certain period but still want to invalidate it if the underlying data - * changes or if you want to force a recomputation. - * - * @see {@link cached} for a similar function that caches the result - * indefinitely. - * @see {@link cachedWithTTL} for a similar function that caches the result for - * a specified duration but does not include an effect for manual invalidation. - * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -13201,8 +14059,12 @@ export const cachedInvalidateWithTTL: { * // result 2 * ``` * + * @see {@link cached} for a similar function that caches the result + * indefinitely. + * @see {@link cachedWithTTL} for a similar function that caches the result for + * a specified duration but does not include an effect for manual invalidation. + * @category caching * @since 2.0.0 - * @category Caching */ (self: Effect, timeToLive: Duration.Input): Effect<[Effect, Effect]> } = internal.cachedInvalidateWithTTL @@ -13214,7 +14076,8 @@ export const cachedInvalidateWithTTL: { /** * Returns an effect that is immediately interrupted. * - * @example + * **Example** (Creating an interrupted effect) + * * ```ts * import { Effect } from "effect" * @@ -13227,15 +14090,16 @@ export const cachedInvalidateWithTTL: { * // Throws: InterruptedException * ``` * + * @category interruption * @since 2.0.0 - * @category Interruption */ export const interrupt: Effect = internal.interrupt /** * Returns a new effect that allows the effect to be interruptible. * - * @example + * **Example** (Allowing interruption) + * * ```ts * import { Effect } from "effect" * @@ -13248,8 +14112,8 @@ export const interrupt: Effect = internal.interrupt * // Later: fiber.interrupt() * ``` * + * @category interruption * @since 2.0.0 - * @category Interruption */ export const interruptible: ( self: Effect @@ -13258,7 +14122,8 @@ export const interruptible: ( /** * Runs the specified finalizer effect if this effect is interrupted. * - * @example + * **Example** (Running cleanup on interruption) + * * ```ts * import { Console, Effect, Fiber } from "effect" * @@ -13275,14 +14140,15 @@ export const interruptible: ( * // Output: Task was interrupted, cleaning up... * ``` * + * @category interruption * @since 2.0.0 - * @category Interruption */ export const onInterrupt: { /** * Runs the specified finalizer effect if this effect is interrupted. * - * @example + * **Example** (Running cleanup on interruption) + * * ```ts * import { Console, Effect, Fiber } from "effect" * @@ -13299,14 +14165,15 @@ export const onInterrupt: { * // Output: Task was interrupted, cleaning up... * ``` * + * @category interruption * @since 2.0.0 - * @category Interruption */ (finalizer: (interruptors: ReadonlySet) => Effect): (self: Effect) => Effect /** * Runs the specified finalizer effect if this effect is interrupted. * - * @example + * **Example** (Running cleanup on interruption) + * * ```ts * import { Console, Effect, Fiber } from "effect" * @@ -13323,8 +14190,8 @@ export const onInterrupt: { * // Output: Task was interrupted, cleaning up... * ``` * + * @category interruption * @since 2.0.0 - * @category Interruption */ ( self: Effect, @@ -13335,7 +14202,8 @@ export const onInterrupt: { /** * Returns a new effect that disables interruption for the given effect. * - * @example + * **Example** (Preventing interruption) + * * ```ts * import { Console, Effect, Fiber } from "effect" * @@ -13352,8 +14220,8 @@ export const onInterrupt: { * Effect.runPromise(Fiber.interrupt(fiber)) * ``` * + * @category interruption * @since 2.0.0 - * @category Interruption */ export const uninterruptible: ( self: Effect @@ -13363,7 +14231,8 @@ export const uninterruptible: ( * Disables interruption and provides a restore function to restore the * interruptible state within the effect. * - * @example + * **Example** (Restoring interruption in protected regions) + * * ```ts * import { Console, Effect } from "effect" * @@ -13385,8 +14254,8 @@ export const uninterruptible: ( * ) * ``` * + * @category interruption * @since 2.0.0 - * @category Interruption */ export const uninterruptibleMask: ( f: ( @@ -13395,11 +14264,11 @@ export const uninterruptibleMask: ( ) => Effect = internal.uninterruptibleMask /** - * This function behaves like {@link interruptible}, but it also provides a - * `restore` function. This function can be used to restore the interruptibility - * of any specific region of code. + * Runs an effect in an interruptible region while providing `restore` for + * locally restoring the previous interruptibility. + * + * **Example** (Controlling interruptibility locally) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -13421,8 +14290,8 @@ export const uninterruptibleMask: ( * ) * ``` * + * @category interruption * @since 2.0.0 - * @category Interruption */ export const interruptibleMask: ( f: ( @@ -13433,8 +14302,26 @@ export const interruptibleMask: ( /** * Creates an AbortSignal that is managed by the provided scope. * + * **When to use** + * + * Use to obtain a scope-managed `AbortSignal` for APIs that accept cancellation + * through a signal. + * + * **Details** + * + * Each acquisition creates a fresh `AbortController`. Closing the owning scope + * runs a finalizer that aborts the controller and the effect succeeds with the + * controller's signal. + * + * **Gotchas** + * + * The signal is aborted when its owning scope closes, so avoid keeping it for + * work that outlives that scope. + * + * @see {@link scoped} for binding resource lifetime to a scope + * + * @category interruption * @since 4.0.0 - * @category Interruption */ export const abortSignal: Effect = internal.abortSignal @@ -13443,31 +14330,16 @@ export const abortSignal: Effect = internal.abortSign // ----------------------------------------------------------------------------- /** - * @since 2.0.0 - * @category Repetition / Recursion - * @example - * ```ts - * import type { Effect } from "effect" + * Type helpers for repeating effects. * - * // Repeat namespace contains types for repeating operations - * declare const effect: Effect.Effect - * declare const options: Effect.Repeat.Options - * // Use Effect.repeat with these types for repeating successful effects - * ``` + * @since 2.0.0 */ export declare namespace Repeat { /** - * @since 2.0.0 - * @category Repetition / Recursion - * @example - * ```ts - * import type { Effect } from "effect" + * Computes the result type of `Effect.repeat` from the original effect and repeat options. * - * // Return type for repeat operations with specific options - * declare const options: Effect.Repeat.Options - * type RepeatResult = Effect.Repeat.Return - * // Result: Effect with repeated operation result types - * ``` + * @category repetition + * @since 2.0.0 */ export type Return> = Effect< O extends { until: Predicate.Refinement } ? B @@ -13495,20 +14367,10 @@ export declare namespace Repeat { : never /** - * @since 2.0.0 - * @category Repetition / Recursion - * @example - * ```ts - * import { Schedule } from "effect" - * import type { Effect } from "effect" + * Options that control whether and how an effect is repeated. * - * // Options for configuring repeat behavior - * const repeatOptions: Effect.Repeat.Options = { - * times: 5, - * schedule: Schedule.fixed("100 millis"), - * while: (result) => result < 10 - * } - * ``` + * @category repetition + * @since 2.0.0 */ export interface Options { while?: ((_: A) => boolean | Effect) | undefined @@ -13521,7 +14383,8 @@ export declare namespace Repeat { /** * Repeats this effect forever (until the first error). * - * @example + * **Example** (Repeating forever) + * * ```ts * import { Console, Effect, Fiber } from "effect" * @@ -13544,8 +14407,8 @@ export declare namespace Repeat { * }) * ``` * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ export const forever: < Arg extends Effect | { @@ -13564,6 +14427,10 @@ export const forever: < /** * Repeats an effect based on a specified schedule or until the first failure. * + * **When to use** + * + * Use to rerun an effect after successful executions. + * * **Details** * * This function executes an effect repeatedly according to the given schedule. @@ -13583,12 +14450,16 @@ export const forever: < * delays, limiting recursions, or dynamically adjusting based on the outcome of * each execution. * - * @example + * **Gotchas** + * + * The source effect is always evaluated once before the schedule is stepped. + * The schedule controls additional repetitions, not the initial execution. + * + * **Example** (Repeating successful effects with a schedule) + * * ```ts * // Success Example - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * const action = Console.log("success") * const policy = Schedule.addDelay(Schedule.recurs(2), () => Effect.succeed("100 millis")) @@ -13597,10 +14468,11 @@ export const forever: < * // Effect.runPromise(program).then((n) => console.log(`repetitions: ${n}`)) * ``` * - * @example + * **Example** (Stopping repetition on failure) + * + * ```ts * // Failure Example - * import { Effect } from "effect" - * import { Schedule } from "effect" + * import { Effect, Schedule } from "effect" * * let count = 0 * @@ -13620,14 +14492,22 @@ export const forever: < * const program = Effect.repeat(action, policy) * * // Effect.runPromiseExit(program).then(console.log) + * ``` + * + * @see {@link retry} for failure-based repetition + * @see {@link repeatOrElse} for fallback handling when repetition fails * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ export const repeat: { /** * Repeats an effect based on a specified schedule or until the first failure. * + * **When to use** + * + * Use to rerun an effect after successful executions. + * * **Details** * * This function executes an effect repeatedly according to the given schedule. @@ -13647,12 +14527,16 @@ export const repeat: { * delays, limiting recursions, or dynamically adjusting based on the outcome of * each execution. * - * @example + * **Gotchas** + * + * The source effect is always evaluated once before the schedule is stepped. + * The schedule controls additional repetitions, not the initial execution. + * + * **Example** (Repeating successful effects with a schedule) + * * ```ts * // Success Example - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * const action = Console.log("success") * const policy = Schedule.addDelay(Schedule.recurs(2), () => Effect.succeed("100 millis")) @@ -13661,10 +14545,11 @@ export const repeat: { * // Effect.runPromise(program).then((n) => console.log(`repetitions: ${n}`)) * ``` * - * @example + * **Example** (Stopping repetition on failure) + * + * ```ts * // Failure Example - * import { Effect } from "effect" - * import { Schedule } from "effect" + * import { Effect, Schedule } from "effect" * * let count = 0 * @@ -13684,14 +14569,22 @@ export const repeat: { * const program = Effect.repeat(action, policy) * * // Effect.runPromiseExit(program).then(console.log) + * ``` + * + * @see {@link retry} for failure-based repetition + * @see {@link repeatOrElse} for fallback handling when repetition fails * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ , A>(options: O): (self: Effect) => Repeat.Return /** * Repeats an effect based on a specified schedule or until the first failure. * + * **When to use** + * + * Use to rerun an effect after successful executions. + * * **Details** * * This function executes an effect repeatedly according to the given schedule. @@ -13711,12 +14604,16 @@ export const repeat: { * delays, limiting recursions, or dynamically adjusting based on the outcome of * each execution. * - * @example + * **Gotchas** + * + * The source effect is always evaluated once before the schedule is stepped. + * The schedule controls additional repetitions, not the initial execution. + * + * **Example** (Repeating successful effects with a schedule) + * * ```ts * // Success Example - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * const action = Console.log("success") * const policy = Schedule.addDelay(Schedule.recurs(2), () => Effect.succeed("100 millis")) @@ -13725,10 +14622,11 @@ export const repeat: { * // Effect.runPromise(program).then((n) => console.log(`repetitions: ${n}`)) * ``` * - * @example + * **Example** (Stopping repetition on failure) + * + * ```ts * // Failure Example - * import { Effect } from "effect" - * import { Schedule } from "effect" + * import { Effect, Schedule } from "effect" * * let count = 0 * @@ -13748,14 +14646,22 @@ export const repeat: { * const program = Effect.repeat(action, policy) * * // Effect.runPromiseExit(program).then(console.log) + * ``` + * + * @see {@link retry} for failure-based repetition + * @see {@link repeatOrElse} for fallback handling when repetition fails * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ (schedule: Schedule, Error, Env>): (self: Effect) => Effect /** * Repeats an effect based on a specified schedule or until the first failure. * + * **When to use** + * + * Use to rerun an effect after successful executions. + * * **Details** * * This function executes an effect repeatedly according to the given schedule. @@ -13775,12 +14681,16 @@ export const repeat: { * delays, limiting recursions, or dynamically adjusting based on the outcome of * each execution. * - * @example + * **Gotchas** + * + * The source effect is always evaluated once before the schedule is stepped. + * The schedule controls additional repetitions, not the initial execution. + * + * **Example** (Repeating successful effects with a schedule) + * * ```ts * // Success Example - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * const action = Console.log("success") * const policy = Schedule.addDelay(Schedule.recurs(2), () => Effect.succeed("100 millis")) @@ -13789,10 +14699,11 @@ export const repeat: { * // Effect.runPromise(program).then((n) => console.log(`repetitions: ${n}`)) * ``` * - * @example + * **Example** (Stopping repetition on failure) + * + * ```ts * // Failure Example - * import { Effect } from "effect" - * import { Schedule } from "effect" + * import { Effect, Schedule } from "effect" * * let count = 0 * @@ -13812,9 +14723,13 @@ export const repeat: { * const program = Effect.repeat(action, policy) * * // Effect.runPromiseExit(program).then(console.log) + * ``` + * + * @see {@link retry} for failure-based repetition + * @see {@link repeatOrElse} for fallback handling when repetition fails * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ ( builder: ( @@ -13824,6 +14739,10 @@ export const repeat: { /** * Repeats an effect based on a specified schedule or until the first failure. * + * **When to use** + * + * Use to rerun an effect after successful executions. + * * **Details** * * This function executes an effect repeatedly according to the given schedule. @@ -13843,12 +14762,16 @@ export const repeat: { * delays, limiting recursions, or dynamically adjusting based on the outcome of * each execution. * - * @example + * **Gotchas** + * + * The source effect is always evaluated once before the schedule is stepped. + * The schedule controls additional repetitions, not the initial execution. + * + * **Example** (Repeating successful effects with a schedule) + * * ```ts * // Success Example - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * const action = Console.log("success") * const policy = Schedule.addDelay(Schedule.recurs(2), () => Effect.succeed("100 millis")) @@ -13857,10 +14780,11 @@ export const repeat: { * // Effect.runPromise(program).then((n) => console.log(`repetitions: ${n}`)) * ``` * - * @example + * **Example** (Stopping repetition on failure) + * + * ```ts * // Failure Example - * import { Effect } from "effect" - * import { Schedule } from "effect" + * import { Effect, Schedule } from "effect" * * let count = 0 * @@ -13880,14 +14804,22 @@ export const repeat: { * const program = Effect.repeat(action, policy) * * // Effect.runPromiseExit(program).then(console.log) + * ``` + * + * @see {@link retry} for failure-based repetition + * @see {@link repeatOrElse} for fallback handling when repetition fails * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ >(self: Effect, options: O): Repeat.Return /** * Repeats an effect based on a specified schedule or until the first failure. * + * **When to use** + * + * Use to rerun an effect after successful executions. + * * **Details** * * This function executes an effect repeatedly according to the given schedule. @@ -13907,12 +14839,16 @@ export const repeat: { * delays, limiting recursions, or dynamically adjusting based on the outcome of * each execution. * - * @example + * **Gotchas** + * + * The source effect is always evaluated once before the schedule is stepped. + * The schedule controls additional repetitions, not the initial execution. + * + * **Example** (Repeating successful effects with a schedule) + * * ```ts * // Success Example - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * const action = Console.log("success") * const policy = Schedule.addDelay(Schedule.recurs(2), () => Effect.succeed("100 millis")) @@ -13921,10 +14857,11 @@ export const repeat: { * // Effect.runPromise(program).then((n) => console.log(`repetitions: ${n}`)) * ``` * - * @example + * **Example** (Stopping repetition on failure) + * + * ```ts * // Failure Example - * import { Effect } from "effect" - * import { Schedule } from "effect" + * import { Effect, Schedule } from "effect" * * let count = 0 * @@ -13944,9 +14881,13 @@ export const repeat: { * const program = Effect.repeat(action, policy) * * // Effect.runPromiseExit(program).then(console.log) + * ``` + * + * @see {@link retry} for failure-based repetition + * @see {@link repeatOrElse} for fallback handling when repetition fails * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ ( self: Effect, @@ -13955,6 +14896,10 @@ export const repeat: { /** * Repeats an effect based on a specified schedule or until the first failure. * + * **When to use** + * + * Use to rerun an effect after successful executions. + * * **Details** * * This function executes an effect repeatedly according to the given schedule. @@ -13974,12 +14919,16 @@ export const repeat: { * delays, limiting recursions, or dynamically adjusting based on the outcome of * each execution. * - * @example + * **Gotchas** + * + * The source effect is always evaluated once before the schedule is stepped. + * The schedule controls additional repetitions, not the initial execution. + * + * **Example** (Repeating successful effects with a schedule) + * * ```ts * // Success Example - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * const action = Console.log("success") * const policy = Schedule.addDelay(Schedule.recurs(2), () => Effect.succeed("100 millis")) @@ -13988,10 +14937,11 @@ export const repeat: { * // Effect.runPromise(program).then((n) => console.log(`repetitions: ${n}`)) * ``` * - * @example + * **Example** (Stopping repetition on failure) + * + * ```ts * // Failure Example - * import { Effect } from "effect" - * import { Schedule } from "effect" + * import { Effect, Schedule } from "effect" * * let count = 0 * @@ -14011,9 +14961,13 @@ export const repeat: { * const program = Effect.repeat(action, policy) * * // Effect.runPromiseExit(program).then(console.log) + * ``` + * + * @see {@link retry} for failure-based repetition + * @see {@link repeatOrElse} for fallback handling when repetition fails * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ ( self: Effect, @@ -14024,27 +14978,25 @@ export const repeat: { } = internalSchedule.repeat /** - * Repeats an effect with a schedule, handling failures using a custom handler. + * Repeats an effect according to a schedule and runs a fallback effect if + * repetition fails before the schedule completes. + * + * **When to use** + * + * Use when successful repetitions should follow a schedule, but failures from + * the repeated effect or schedule need an effectful fallback. * * **Details** * - * This function allows you to execute an effect repeatedly based on a specified - * schedule. If the effect fails at any point, a custom failure handler is - * invoked. The handler is provided with both the failure value and the output - * of the schedule at the time of failure. If the effect fails immediately, the - * schedule will never be executed and the output provided to the handler will - * be `None`. This enables advanced error recovery or alternative fallback logic - * while maintaining flexibility in how repetitions are handled. + * If the repeated effect or schedule step fails, `orElse` receives the failure + * and the latest schedule metadata when at least one schedule step has run; + * otherwise it receives `None`. If the schedule completes normally, the + * returned effect succeeds with the schedule's output. * - * For example, using a schedule with `recurs(2)` will allow for two additional - * repetitions after the initial execution, provided the effect succeeds. If a - * failure occurs during any iteration, the failure handler is invoked to handle - * the situation. + * **Example** (Recovering after repetition stops) * - * @example * ```ts - * import { Console, Effect, Schedule } from "effect" - * import * as Option from "effect/Option" + * import { Console, Effect, Option, Schedule } from "effect" * * let attempt = 0 * const task = Effect.gen(function*() { @@ -14069,32 +15021,30 @@ export const repeat: { * ) * ``` * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ export const repeatOrElse: { /** - * Repeats an effect with a schedule, handling failures using a custom handler. + * Repeats an effect according to a schedule and runs a fallback effect if + * repetition fails before the schedule completes. + * + * **When to use** + * + * Use when successful repetitions should follow a schedule, but failures from + * the repeated effect or schedule need an effectful fallback. * * **Details** * - * This function allows you to execute an effect repeatedly based on a specified - * schedule. If the effect fails at any point, a custom failure handler is - * invoked. The handler is provided with both the failure value and the output - * of the schedule at the time of failure. If the effect fails immediately, the - * schedule will never be executed and the output provided to the handler will - * be `None`. This enables advanced error recovery or alternative fallback logic - * while maintaining flexibility in how repetitions are handled. + * If the repeated effect or schedule step fails, `orElse` receives the failure + * and the latest schedule metadata when at least one schedule step has run; + * otherwise it receives `None`. If the schedule completes normally, the + * returned effect succeeds with the schedule's output. * - * For example, using a schedule with `recurs(2)` will allow for two additional - * repetitions after the initial execution, provided the effect succeeds. If a - * failure occurs during any iteration, the failure handler is invoked to handle - * the situation. + * **Example** (Recovering after repetition stops) * - * @example * ```ts - * import { Console, Effect, Schedule } from "effect" - * import * as Option from "effect/Option" + * import { Console, Effect, Option, Schedule } from "effect" * * let attempt = 0 * const task = Effect.gen(function*() { @@ -14119,35 +15069,33 @@ export const repeatOrElse: { * ) * ``` * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ ( schedule: Schedule, orElse: (error: E | E2, option: Option) => Effect ): (self: Effect) => Effect /** - * Repeats an effect with a schedule, handling failures using a custom handler. + * Repeats an effect according to a schedule and runs a fallback effect if + * repetition fails before the schedule completes. + * + * **When to use** + * + * Use when successful repetitions should follow a schedule, but failures from + * the repeated effect or schedule need an effectful fallback. * * **Details** * - * This function allows you to execute an effect repeatedly based on a specified - * schedule. If the effect fails at any point, a custom failure handler is - * invoked. The handler is provided with both the failure value and the output - * of the schedule at the time of failure. If the effect fails immediately, the - * schedule will never be executed and the output provided to the handler will - * be `None`. This enables advanced error recovery or alternative fallback logic - * while maintaining flexibility in how repetitions are handled. + * If the repeated effect or schedule step fails, `orElse` receives the failure + * and the latest schedule metadata when at least one schedule step has run; + * otherwise it receives `None`. If the schedule completes normally, the + * returned effect succeeds with the schedule's output. * - * For example, using a schedule with `recurs(2)` will allow for two additional - * repetitions after the initial execution, provided the effect succeeds. If a - * failure occurs during any iteration, the failure handler is invoked to handle - * the situation. + * **Example** (Recovering after repetition stops) * - * @example * ```ts - * import { Console, Effect, Schedule } from "effect" - * import * as Option from "effect/Option" + * import { Console, Effect, Option, Schedule } from "effect" * * let attempt = 0 * const task = Effect.gen(function*() { @@ -14172,8 +15120,8 @@ export const repeatOrElse: { * ) * ``` * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ ( self: Effect, @@ -14185,28 +15133,58 @@ export const repeatOrElse: { /** * Returns an array of `n` identical effects. * - * Use with `Effect.all` to run the replicated effects and collect results. + * **When to use** + * + * Use when you need an array of identical effect values without running them + * yet. + * + * **Details** + * + * This only creates the array of effects. It does not run or collect them. + * + * @see {@link all} for running the returned effects and collecting results + * @see {@link replicateEffect} for repeating an effect and collecting results in one step with concurrency and discard options * + * @category collecting * @since 2.0.0 - * @category Collecting */ export const replicate: { /** * Returns an array of `n` identical effects. * - * Use with `Effect.all` to run the replicated effects and collect results. + * **When to use** + * + * Use when you need an array of identical effect values without running them + * yet. + * + * **Details** + * + * This only creates the array of effects. It does not run or collect them. * + * @see {@link all} for running the returned effects and collecting results + * @see {@link replicateEffect} for repeating an effect and collecting results in one step with concurrency and discard options + * + * @category collecting * @since 2.0.0 - * @category Collecting */ (n: number): (self: Effect) => Array> /** * Returns an array of `n` identical effects. * - * Use with `Effect.all` to run the replicated effects and collect results. + * **When to use** + * + * Use when you need an array of identical effect values without running them + * yet. * + * **Details** + * + * This only creates the array of effects. It does not run or collect them. + * + * @see {@link all} for running the returned effects and collecting results + * @see {@link replicateEffect} for repeating an effect and collecting results in one step with concurrency and discard options + * + * @category collecting * @since 2.0.0 - * @category Collecting */ (self: Effect, n: number): Array> } = internal.replicate @@ -14214,9 +15192,17 @@ export const replicate: { /** * Performs this effect `n` times and collects results with `Effect.all` semantics. * + * **When to use** + * + * Use when you want to run the repeated effects immediately, with optional + * concurrency control or result discarding. + * + * **Details** + * * Use `concurrency` to control parallelism and `discard: true` to ignore results. * - * @example + * **Example** (Replicating an effect) + * * ```ts * import { Console, Effect } from "effect" * @@ -14226,16 +15212,24 @@ export const replicate: { * }) * ``` * + * @category collecting * @since 2.0.0 - * @category Collecting */ export const replicateEffect: { /** * Performs this effect `n` times and collects results with `Effect.all` semantics. * + * **When to use** + * + * Use when you want to run the repeated effects immediately, with optional + * concurrency control or result discarding. + * + * **Details** + * * Use `concurrency` to control parallelism and `discard: true` to ignore results. * - * @example + * **Example** (Replicating an effect) + * * ```ts * import { Console, Effect } from "effect" * @@ -14245,8 +15239,8 @@ export const replicateEffect: { * }) * ``` * + * @category collecting * @since 2.0.0 - * @category Collecting */ ( n: number, @@ -14255,9 +15249,17 @@ export const replicateEffect: { /** * Performs this effect `n` times and collects results with `Effect.all` semantics. * + * **When to use** + * + * Use when you want to run the repeated effects immediately, with optional + * concurrency control or result discarding. + * + * **Details** + * * Use `concurrency` to control parallelism and `discard: true` to ignore results. * - * @example + * **Example** (Replicating an effect) + * * ```ts * import { Console, Effect } from "effect" * @@ -14267,8 +15269,8 @@ export const replicateEffect: { * }) * ``` * + * @category collecting * @since 2.0.0 - * @category Collecting */ ( n: number, @@ -14277,9 +15279,17 @@ export const replicateEffect: { /** * Performs this effect `n` times and collects results with `Effect.all` semantics. * + * **When to use** + * + * Use when you want to run the repeated effects immediately, with optional + * concurrency control or result discarding. + * + * **Details** + * * Use `concurrency` to control parallelism and `discard: true` to ignore results. * - * @example + * **Example** (Replicating an effect) + * * ```ts * import { Console, Effect } from "effect" * @@ -14289,8 +15299,8 @@ export const replicateEffect: { * }) * ``` * + * @category collecting * @since 2.0.0 - * @category Collecting */ ( self: Effect, @@ -14300,9 +15310,17 @@ export const replicateEffect: { /** * Performs this effect `n` times and collects results with `Effect.all` semantics. * + * **When to use** + * + * Use when you want to run the repeated effects immediately, with optional + * concurrency control or result discarding. + * + * **Details** + * * Use `concurrency` to control parallelism and `discard: true` to ignore results. * - * @example + * **Example** (Replicating an effect) + * * ```ts * import { Console, Effect } from "effect" * @@ -14312,8 +15330,8 @@ export const replicateEffect: { * }) * ``` * + * @category collecting * @since 2.0.0 - * @category Collecting */ ( self: Effect, @@ -14323,22 +15341,24 @@ export const replicateEffect: { } = internal.replicateEffect /** - * Repeats an effect based on a specified schedule. + * Runs an effect repeatedly according to a schedule and returns the schedule's + * final output. + * + * **When to use** + * + * Use to rerun a successful effect according to a `Schedule` when the schedule + * does not need a custom initial input. * * **Details** * - * This function allows you to execute an effect repeatedly according to a given - * schedule. The schedule determines the timing and number of repetitions. Each - * repetition can also depend on the decision of the schedule, providing - * flexibility for complex workflows. This function does not modify the effect's - * success or failure; it only controls its repetition. + * The schedule is first stepped with `undefined`. After each successful + * execution, the effect's success value is fed to the schedule to decide + * whether to run again. The returned effect fails if the effect or schedule + * fails, and otherwise succeeds with the schedule output when the schedule + * completes. * - * For example, you can use a schedule that recurs a specific number of times, - * adds delays between repetitions, or customizes repetition behavior based on - * external inputs. The effect runs initially and is repeated according to the - * schedule. + * **Example** (Scheduling repeated execution) * - * @example * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -14364,27 +15384,29 @@ export const replicateEffect: { * @see {@link scheduleFrom} for a variant that allows the schedule's decision * to depend on the result of this effect. * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ export const schedule: { /** - * Repeats an effect based on a specified schedule. + * Runs an effect repeatedly according to a schedule and returns the schedule's + * final output. + * + * **When to use** + * + * Use to rerun a successful effect according to a `Schedule` when the schedule + * does not need a custom initial input. * * **Details** * - * This function allows you to execute an effect repeatedly according to a given - * schedule. The schedule determines the timing and number of repetitions. Each - * repetition can also depend on the decision of the schedule, providing - * flexibility for complex workflows. This function does not modify the effect's - * success or failure; it only controls its repetition. + * The schedule is first stepped with `undefined`. After each successful + * execution, the effect's success value is fed to the schedule to decide + * whether to run again. The returned effect fails if the effect or schedule + * fails, and otherwise succeeds with the schedule output when the schedule + * completes. * - * For example, you can use a schedule that recurs a specific number of times, - * adds delays between repetitions, or customizes repetition behavior based on - * external inputs. The effect runs initially and is repeated according to the - * schedule. + * **Example** (Scheduling repeated execution) * - * @example * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -14410,27 +15432,29 @@ export const schedule: { * @see {@link scheduleFrom} for a variant that allows the schedule's decision * to depend on the result of this effect. * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ (schedule: Schedule): (self: Effect) => Effect /** - * Repeats an effect based on a specified schedule. + * Runs an effect repeatedly according to a schedule and returns the schedule's + * final output. + * + * **When to use** + * + * Use to rerun a successful effect according to a `Schedule` when the schedule + * does not need a custom initial input. * * **Details** * - * This function allows you to execute an effect repeatedly according to a given - * schedule. The schedule determines the timing and number of repetitions. Each - * repetition can also depend on the decision of the schedule, providing - * flexibility for complex workflows. This function does not modify the effect's - * success or failure; it only controls its repetition. + * The schedule is first stepped with `undefined`. After each successful + * execution, the effect's success value is fed to the schedule to decide + * whether to run again. The returned effect fails if the effect or schedule + * fails, and otherwise succeeds with the schedule output when the schedule + * completes. * - * For example, you can use a schedule that recurs a specific number of times, - * adds delays between repetitions, or customizes repetition behavior based on - * external inputs. The effect runs initially and is repeated according to the - * schedule. + * **Example** (Scheduling repeated execution) * - * @example * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -14456,8 +15480,8 @@ export const schedule: { * @see {@link scheduleFrom} for a variant that allows the schedule's decision * to depend on the result of this effect. * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ (self: Effect, schedule: Schedule): Effect } = dual(2, ( @@ -14466,21 +15490,19 @@ export const schedule: { ): Effect => scheduleFrom(self, undefined, schedule)) /** - * Runs an effect repeatedly according to a schedule, starting from a specified - * initial input value. + * Runs an effect repeatedly according to a schedule that is initialized with a + * specific schedule input. * * **Details** * - * This function allows you to repeatedly execute an effect based on a schedule. - * The schedule starts with the given `initial` input value, which is passed to - * the first execution. Subsequent executions of the effect are controlled by - * the schedule's rules, using the output of the previous iteration as the input - * for the next one. + * `initial` is passed to the schedule before the first execution, not to the + * effect itself. After each successful execution, the effect's success value is + * fed back into the schedule to decide whether to continue. The returned effect + * succeeds with the schedule output when the schedule completes and fails if + * the effect or schedule fails. * - * The returned effect will complete when the schedule ends or the effect fails, - * propagating the error. + * **Example** (Scheduling from an initial value) * - * @example * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -14501,26 +15523,24 @@ export const schedule: { * // Returns the schedule count * ``` * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ export const scheduleFrom: { /** - * Runs an effect repeatedly according to a schedule, starting from a specified - * initial input value. + * Runs an effect repeatedly according to a schedule that is initialized with a + * specific schedule input. * * **Details** * - * This function allows you to repeatedly execute an effect based on a schedule. - * The schedule starts with the given `initial` input value, which is passed to - * the first execution. Subsequent executions of the effect are controlled by - * the schedule's rules, using the output of the previous iteration as the input - * for the next one. + * `initial` is passed to the schedule before the first execution, not to the + * effect itself. After each successful execution, the effect's success value is + * fed back into the schedule to decide whether to continue. The returned effect + * succeeds with the schedule output when the schedule completes and fails if + * the effect or schedule fails. * - * The returned effect will complete when the schedule ends or the effect fails, - * propagating the error. + * **Example** (Scheduling from an initial value) * - * @example * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -14541,26 +15561,24 @@ export const scheduleFrom: { * // Returns the schedule count * ``` * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ (initial: Input, schedule: Schedule): (self: Effect) => Effect /** - * Runs an effect repeatedly according to a schedule, starting from a specified - * initial input value. + * Runs an effect repeatedly according to a schedule that is initialized with a + * specific schedule input. * * **Details** * - * This function allows you to repeatedly execute an effect based on a schedule. - * The schedule starts with the given `initial` input value, which is passed to - * the first execution. Subsequent executions of the effect are controlled by - * the schedule's rules, using the output of the previous iteration as the input - * for the next one. + * `initial` is passed to the schedule before the first execution, not to the + * effect itself. After each successful execution, the effect's success value is + * fed back into the schedule to decide whether to continue. The returned effect + * succeeds with the schedule output when the schedule completes and fails if + * the effect or schedule fails. * - * The returned effect will complete when the schedule ends or the effect fails, - * propagating the error. + * **Example** (Scheduling from an initial value) * - * @example * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -14581,8 +15599,8 @@ export const scheduleFrom: { * // Returns the schedule count * ``` * + * @category repetition * @since 2.0.0 - * @category Repetition / Recursion */ ( self: Effect, @@ -14598,7 +15616,8 @@ export const scheduleFrom: { /** * Returns the current tracer from the context. * - * @example + * **Example** (Accessing the current tracer) + * * ```ts * import { Effect } from "effect" * @@ -14609,15 +15628,16 @@ export const scheduleFrom: { * }) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ export const tracer: Effect = internal.tracer /** * Provides a tracer to an effect. * - * @example + * **Example** (Providing a tracer) + * * ```ts * import { Effect } from "effect" * @@ -14630,14 +15650,15 @@ export const tracer: Effect = internal.tracer * // const traced = Effect.withTracer(program, customTracer) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ export const withTracer: { /** * Provides a tracer to an effect. * - * @example + * **Example** (Providing a tracer) + * * ```ts * import { Effect } from "effect" * @@ -14650,14 +15671,15 @@ export const withTracer: { * // const traced = Effect.withTracer(program, customTracer) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ (value: Tracer): (effect: Effect) => Effect /** * Provides a tracer to an effect. * - * @example + * **Example** (Providing a tracer) + * * ```ts * import { Effect } from "effect" * @@ -14670,16 +15692,22 @@ export const withTracer: { * // const traced = Effect.withTracer(program, customTracer) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ (effect: Effect, value: Tracer): Effect } = internal.withTracer /** - * Disable the tracer for the given Effect. + * Enables or disables tracing for spans created by the given effect. + * + * **Details** + * + * When `enabled` is `false`, spans created inside the effect are not registered + * with the current tracer and do not propagate as normal trace parents. + * + * **Example** (Enabling or disabling tracing) * - * @example * ```ts * import { Effect } from "effect" * @@ -14690,14 +15718,20 @@ export const withTracer: { * ) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ export const withTracerEnabled: { /** - * Disable the tracer for the given Effect. + * Enables or disables tracing for spans created by the given effect. + * + * **Details** + * + * When `enabled` is `false`, spans created inside the effect are not registered + * with the current tracer and do not propagate as normal trace parents. + * + * **Example** (Enabling or disabling tracing) * - * @example * ```ts * import { Effect } from "effect" * @@ -14708,14 +15742,20 @@ export const withTracerEnabled: { * ) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ (enabled: boolean): (effect: Effect) => Effect /** - * Disable the tracer for the given Effect. + * Enables or disables tracing for spans created by the given effect. + * + * **Details** + * + * When `enabled` is `false`, spans created inside the effect are not registered + * with the current tracer and do not propagate as normal trace parents. + * + * **Example** (Enabling or disabling tracing) * - * @example * ```ts * import { Effect } from "effect" * @@ -14726,8 +15766,8 @@ export const withTracerEnabled: { * ) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ (effect: Effect, enabled: boolean): Effect } = internal.withTracerEnabled @@ -14735,7 +15775,8 @@ export const withTracerEnabled: { /** * Enables or disables tracer timing for the given Effect. * - * @example + * **Example** (Enabling or disabling tracing timing) + * * ```ts * import { Effect } from "effect" * @@ -14746,14 +15787,15 @@ export const withTracerEnabled: { * ) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ export const withTracerTiming: { /** * Enables or disables tracer timing for the given Effect. * - * @example + * **Example** (Enabling or disabling tracing timing) + * * ```ts * import { Effect } from "effect" * @@ -14764,14 +15806,15 @@ export const withTracerTiming: { * ) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ (enabled: boolean): (effect: Effect) => Effect /** * Enables or disables tracer timing for the given Effect. * - * @example + * **Example** (Enabling or disabling tracing timing) + * * ```ts * import { Effect } from "effect" * @@ -14782,8 +15825,8 @@ export const withTracerTiming: { * ) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ (effect: Effect, enabled: boolean): Effect } = internal.withTracerTiming @@ -14791,7 +15834,8 @@ export const withTracerTiming: { /** * Adds an annotation to each span in this effect. * - * @example + * **Example** (Annotating all spans) + * * ```ts * import { Effect } from "effect" * @@ -14811,14 +15855,15 @@ export const withTracerTiming: { * }) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ export const annotateSpans: { /** * Adds an annotation to each span in this effect. * - * @example + * **Example** (Annotating all spans) + * * ```ts * import { Effect } from "effect" * @@ -14838,14 +15883,15 @@ export const annotateSpans: { * }) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ (key: string, value: unknown): (effect: Effect) => Effect /** * Adds an annotation to each span in this effect. * - * @example + * **Example** (Annotating all spans) + * * ```ts * import { Effect } from "effect" * @@ -14865,14 +15911,15 @@ export const annotateSpans: { * }) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ (values: Record): (effect: Effect) => Effect /** * Adds an annotation to each span in this effect. * - * @example + * **Example** (Annotating all spans) + * * ```ts * import { Effect } from "effect" * @@ -14892,14 +15939,15 @@ export const annotateSpans: { * }) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ (effect: Effect, key: string, value: unknown): Effect /** * Adds an annotation to each span in this effect. * - * @example + * **Example** (Annotating all spans) + * * ```ts * import { Effect } from "effect" * @@ -14919,8 +15967,8 @@ export const annotateSpans: { * }) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ (effect: Effect, values: Record): Effect } = internal.annotateSpans @@ -14928,7 +15976,8 @@ export const annotateSpans: { /** * Adds an annotation to the current span if available. * - * @example + * **Example** (Annotating the current span) + * * ```ts * import { Effect } from "effect" * @@ -14945,14 +15994,15 @@ export const annotateSpans: { * const traced = Effect.withSpan(program, "user-operation") * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ export const annotateCurrentSpan: { /** * Adds an annotation to the current span if available. * - * @example + * **Example** (Annotating the current span) + * * ```ts * import { Effect } from "effect" * @@ -14969,14 +16019,15 @@ export const annotateCurrentSpan: { * const traced = Effect.withSpan(program, "user-operation") * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ (key: string, value: unknown): Effect /** * Adds an annotation to the current span if available. * - * @example + * **Example** (Annotating the current span) + * * ```ts * import { Effect } from "effect" * @@ -14993,16 +16044,22 @@ export const annotateCurrentSpan: { * const traced = Effect.withSpan(program, "user-operation") * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ (values: Record): Effect } = internal.annotateCurrentSpan /** - * Returns the current span from the context. + * Returns the currently active local tracing span. + * + * **Details** + * + * The effect fails with `NoSuchElementError` when there is no active local + * `Span`. + * + * **Example** (Reading the current span) * - * @example * ```ts * import { Effect } from "effect" * @@ -15015,15 +16072,22 @@ export const annotateCurrentSpan: { * const traced = Effect.withSpan(program, "my-span") * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ export const currentSpan: Effect = internal.currentSpan /** - * Returns the current parent span from the context. + * Returns the current parent span from the effect context. + * + * **Details** + * + * The effect succeeds with either a local span or external span when one is + * present, and fails with `NoSuchElementError` when no parent span is + * available. + * + * **Example** (Reading the parent span) * - * @example * ```ts * import { Effect } from "effect" * @@ -15041,15 +16105,21 @@ export const currentSpan: Effect = internal.curr * const traced = Effect.withSpan(program, "parent-span") * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ export const currentParentSpan: Effect = internal.currentParentSpan /** - * Returns the annotations of the current span. + * Returns the tracing span annotations currently carried in the effect context. + * + * **Details** + * + * These annotations are applied to spans created inside the context, such as + * spans created by `withSpan`, `useSpan`, or `makeSpan`. + * + * **Example** (Providing span annotations) * - * @example * ```ts * import { Effect } from "effect" * @@ -15069,19 +16139,21 @@ export const currentParentSpan: Effect = inte * // Output: Current span annotations: { userId: "123", operation: "data-processing" } * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ export const spanAnnotations: Effect>> = internal.spanAnnotations /** - * Retrieves the span links associated with the current span. + * Returns the tracing span links currently carried in the effect context. + * + * **Details** + * + * These links are attached to spans created inside the context. Span links + * connect related spans without making one span the parent of another. * - * Span links are connections between spans that are related but not in a - * parent-child relationship. They are useful for linking spans across different - * traces or connecting spans from parallel operations. + * **Example** (Providing span links) * - * @example * ```ts * import { Effect } from "effect" * @@ -15093,19 +16165,22 @@ export const spanAnnotations: Effect>> = intern * }) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ export const spanLinks: Effect> = internal.spanLinks /** - * For all spans in this effect, add a link with the provided span. + * Adds a link with the provided span to all spans in this effect. + * + * **Details** * * This is useful for connecting spans that are related but not in a direct * parent-child relationship. For example, you might want to link spans from * parallel operations or connect spans across different traces. * - * @example + * **Example** (Linking one span to another span) + * * ```ts * import { Effect } from "effect" * @@ -15127,7 +16202,8 @@ export const spanLinks: Effect> = internal.spanLinks * }) * ``` * - * @example + * **Example** (Linking multiple spans at once) + * * ```ts * import { Effect } from "effect" * @@ -15145,18 +16221,21 @@ export const spanLinks: Effect> = internal.spanLinks * }) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ export const linkSpans: { /** - * For all spans in this effect, add a link with the provided span. + * Adds a link with the provided span to all spans in this effect. + * + * **Details** * * This is useful for connecting spans that are related but not in a direct * parent-child relationship. For example, you might want to link spans from * parallel operations or connect spans across different traces. * - * @example + * **Example** (Linking one span to another span) + * * ```ts * import { Effect } from "effect" * @@ -15178,7 +16257,8 @@ export const linkSpans: { * }) * ``` * - * @example + * **Example** (Linking multiple spans at once) + * * ```ts * import { Effect } from "effect" * @@ -15196,21 +16276,24 @@ export const linkSpans: { * }) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ ( span: AnySpan | ReadonlyArray, attributes?: Record ): (self: Effect) => Effect /** - * For all spans in this effect, add a link with the provided span. + * Adds a link with the provided span to all spans in this effect. + * + * **Details** * * This is useful for connecting spans that are related but not in a direct * parent-child relationship. For example, you might want to link spans from * parallel operations or connect spans across different traces. * - * @example + * **Example** (Linking one span to another span) + * * ```ts * import { Effect } from "effect" * @@ -15232,7 +16315,8 @@ export const linkSpans: { * }) * ``` * - * @example + * **Example** (Linking multiple spans at once) + * * ```ts * import { Effect } from "effect" * @@ -15250,8 +16334,8 @@ export const linkSpans: { * }) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ ( self: Effect, @@ -15261,9 +16345,16 @@ export const linkSpans: { } = internal.linkSpans /** - * Create a new span for tracing. + * Creates a new tracing span and returns it without managing its lifetime. + * + * **Details** + * + * The span is not added to the current span stack and is not ended + * automatically. Use `withSpan`, `useSpan`, or `makeSpanScoped` when the span + * should be installed as context or closed automatically. + * + * **Example** (Creating a span manually) * - * @example * ```ts * import { Effect } from "effect" * @@ -15274,8 +16365,8 @@ export const linkSpans: { * }) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ export const makeSpan: (name: string, options?: SpanOptionsNoTrace) => Effect = internal.makeSpan @@ -15283,10 +16374,13 @@ export const makeSpan: (name: string, options?: SpanOptionsNoTrace) => Effect Effect(name: string, evaluate: (span: Span) => Effect): Effect /** * Create a new span for tracing, and automatically close it when the effect * completes. * + * **Details** + * * The span is not added to the current span stack, so no child spans will be * created for it. * - * @example + * **Example** (Running an effect with a standalone span) + * * ```ts * import { Effect } from "effect" * @@ -15379,8 +16482,8 @@ export const useSpan: { * ) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ ( name: string, @@ -15390,9 +16493,10 @@ export const useSpan: { } = internal.useSpan /** - * Wraps the effect with a new span for tracing. + * Wraps the effect with a child span for tracing. + * + * **Example** (Wrapping an effect in a child span) * - * @example * ```ts * import { Effect } from "effect" * @@ -15406,14 +16510,15 @@ export const useSpan: { * }) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ export const withSpan: { /** - * Wraps the effect with a new span for tracing. + * Wraps the effect with a child span for tracing. + * + * **Example** (Wrapping an effect in a child span) * - * @example * ```ts * import { Effect } from "effect" * @@ -15427,8 +16532,8 @@ export const withSpan: { * }) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ >( name: string, @@ -15439,9 +16544,10 @@ export const withSpan: { traceOptions?: TraceOptions | undefined ): (self: Effect, ...args: Args) => Effect> /** - * Wraps the effect with a new span for tracing. + * Wraps the effect with a child span for tracing. + * + * **Example** (Wrapping an effect in a child span) * - * @example * ```ts * import { Effect } from "effect" * @@ -15455,18 +16561,21 @@ export const withSpan: { * }) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ (self: Effect, name: string, options?: SpanOptions | undefined): Effect> } = internal.withSpan /** - * Wraps the effect with a new span for tracing. + * Wraps the effect with a scoped child span for tracing. + * + * **Details** * * The span is ended when the Scope is finalized. * - * @example + * **Example** (Creating a scoped child span) + * * ```ts * import { Effect } from "effect" * @@ -15479,16 +16588,19 @@ export const withSpan: { * ) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ export const withSpanScoped: { /** - * Wraps the effect with a new span for tracing. + * Wraps the effect with a scoped child span for tracing. + * + * **Details** * * The span is ended when the Scope is finalized. * - * @example + * **Example** (Creating a scoped child span) + * * ```ts * import { Effect } from "effect" * @@ -15501,18 +16613,21 @@ export const withSpanScoped: { * ) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ (name: string, options?: SpanOptions): ( self: Effect ) => Effect | Scope> /** - * Wraps the effect with a new span for tracing. + * Wraps the effect with a scoped child span for tracing. + * + * **Details** * * The span is ended when the Scope is finalized. * - * @example + * **Example** (Creating a scoped child span) + * * ```ts * import { Effect } from "effect" * @@ -15525,8 +16640,8 @@ export const withSpanScoped: { * ) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ (self: Effect, name: string, options?: SpanOptions): Effect | Scope> } = internal.withSpanScoped @@ -15534,7 +16649,8 @@ export const withSpanScoped: { /** * Adds the provided span to the current span stack. * - * @example + * **Example** (Setting a parent span) + * * ```ts * import { Effect } from "effect" * @@ -15546,14 +16662,15 @@ export const withSpanScoped: { * }) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ export const withParentSpan: { /** * Adds the provided span to the current span stack. * - * @example + * **Example** (Setting a parent span) + * * ```ts * import { Effect } from "effect" * @@ -15565,14 +16682,15 @@ export const withParentSpan: { * }) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ (value: AnySpan, options?: TraceOptions): (self: Effect) => Effect> /** * Adds the provided span to the current span stack. * - * @example + * **Example** (Setting a parent span) + * * ```ts * import { Effect } from "effect" * @@ -15584,8 +16702,8 @@ export const withParentSpan: { * }) * ``` * + * @category tracing * @since 2.0.0 - * @category Tracing */ (self: Effect, value: AnySpan, options?: TraceOptions): Effect> } = internal.withParentSpan @@ -15597,10 +16715,12 @@ export const withParentSpan: { /** * Executes a request using the provided resolver. * - * @since 2.0.0 - * @category Requests & Batching + * **When to use** + * + * Use when you need resolver-driven batching for a typed `Request`. + * + * **Example** (Executing a request through a resolver) * - * @example * ```ts * import { Console, Effect, Exit, Request, RequestResolver } from "effect" * @@ -15623,6 +16743,11 @@ export const withParentSpan: { * yield* Console.log(name) * }) * ``` + * + * @see {@link requestUnsafe} for the low-level entry point when you already have a `Context` and need to enqueue outside an `Effect` + * + * @category requests & batching + * @since 2.0.0 */ export const request: { // ----------------------------------------------------------------------------- @@ -15632,10 +16757,12 @@ export const request: { /** * Executes a request using the provided resolver. * - * @since 2.0.0 - * @category Requests & Batching + * **When to use** + * + * Use when you need resolver-driven batching for a typed `Request`. + * + * **Example** (Executing a request through a resolver) * - * @example * ```ts * import { Console, Effect, Exit, Request, RequestResolver } from "effect" * @@ -15658,6 +16785,11 @@ export const request: { * yield* Console.log(name) * }) * ``` + * + * @see {@link requestUnsafe} for the low-level entry point when you already have a `Context` and need to enqueue outside an `Effect` + * + * @category requests & batching + * @since 2.0.0 */ (resolver: RequestResolver | Effect, EX, RX>): (self: A) => Effect, Request.Error | EX, Request.Services | RX> // ----------------------------------------------------------------------------- @@ -15667,10 +16799,12 @@ export const request: { /** * Executes a request using the provided resolver. * - * @since 2.0.0 - * @category Requests & Batching + * **When to use** + * + * Use when you need resolver-driven batching for a typed `Request`. + * + * **Example** (Executing a request through a resolver) * - * @example * ```ts * import { Console, Effect, Exit, Request, RequestResolver } from "effect" * @@ -15693,18 +16827,31 @@ export const request: { * yield* Console.log(name) * }) * ``` + * + * @see {@link requestUnsafe} for the low-level entry point when you already have a `Context` and need to enqueue outside an `Effect` + * + * @category requests & batching + * @since 2.0.0 */ (self: A, resolver: RequestResolver | Effect, EX, RX>): Effect, Request.Error | EX, Request.Services | RX> } = internalRequest.request /** - * Low-level entry point that registers a request with a resolver and delivers the exit value via `onExit`. - * Use this when you already have a `Context` and need to enqueue a request outside an `Effect`. + * Registers a request with a resolver and delivers the exit value via `onExit`. + * + * **When to use** + * + * Use when you already have a `Context` and need to enqueue a request outside + * an `Effect` while receiving completion through `onExit`. + * + * **Details** * * It returns a canceler that removes the pending request entry. * + * @see {@link request} for the `Effect`-returning API used for normal request execution + * + * @category requests & batching * @since 4.0.0 - * @category Requests & Batching */ export const requestUnsafe: ( self: A, @@ -15724,6 +16871,8 @@ export const requestUnsafe: ( * returning the fiber immediately, without waiting for it to begin executing * the effect. * + * **Details** + * * You can use the `forkChild` method whenever you want to execute an effect in a * new fiber, concurrently and without "blocking" the fiber executing other * effects. Using fibers can be tricky, so instead of using this method @@ -15740,7 +16889,8 @@ export const requestUnsafe: ( * fibers leak. This behavior is called "auto supervision", and if this * behavior is not desired, you may use the `forkDetach` or `forkIn` methods. * - * @example + * **Example** (Forking a child fiber) + * * ```ts * import { Effect, Fiber } from "effect" * @@ -15762,8 +16912,8 @@ export const requestUnsafe: ( * }) * ``` * + * @category supervision & fibers * @since 4.0.0 - * @category Supervision & Fibers */ export const forkChild: < Arg extends Effect | { @@ -15786,7 +16936,8 @@ export const forkChild: < * Forks the effect in the specified scope. The fiber will be interrupted * when the scope is closed. * - * @example + * **Example** (Forking into a supplied scope) + * * ```ts * import { Effect } from "effect" * @@ -15806,15 +16957,16 @@ export const forkChild: < * ) * ``` * + * @category supervision & fibers * @since 2.0.0 - * @category Supervision & Fibers */ export const forkIn: { /** * Forks the effect in the specified scope. The fiber will be interrupted * when the scope is closed. * - * @example + * **Example** (Forking into a supplied scope) + * * ```ts * import { Effect } from "effect" * @@ -15834,8 +16986,8 @@ export const forkIn: { * ) * ``` * + * @category supervision & fibers * @since 2.0.0 - * @category Supervision & Fibers */ ( scope: Scope, @@ -15848,7 +17000,8 @@ export const forkIn: { * Forks the effect in the specified scope. The fiber will be interrupted * when the scope is closed. * - * @example + * **Example** (Forking into a supplied scope) + * * ```ts * import { Effect } from "effect" * @@ -15868,8 +17021,8 @@ export const forkIn: { * ) * ``` * + * @category supervision & fibers * @since 2.0.0 - * @category Supervision & Fibers */ ( self: Effect, @@ -15884,7 +17037,8 @@ export const forkIn: { /** * Forks the fiber in a `Scope`, interrupting it when the scope is closed. * - * @example + * **Example** (Forking into the current scope) + * * ```ts * import { Effect } from "effect" * @@ -15910,8 +17064,8 @@ export const forkIn: { * ) * ``` * + * @category supervision & fibers * @since 2.0.0 - * @category Supervision & Fibers */ export const forkScoped: < Arg extends Effect | { @@ -15935,7 +17089,8 @@ export const forkScoped: < * new fiber is attached to the global scope, when the fiber executing the * returned effect terminates, the forked fiber will continue running. * - * @example + * **Example** (Forking a detached fiber) + * * ```ts * import { Effect } from "effect" * @@ -15959,8 +17114,8 @@ export const forkScoped: < * }) * ``` * - * @since 2.0.0 - * @category Supervision & Fibers + * @category supervision & fibers + * @since 4.0.0 */ export const forkDetach: < Arg extends Effect | { @@ -15983,15 +17138,31 @@ export const forkDetach: < * Waits for all child fibers forked by this effect to complete before this * effect completes. * + * **When to use** + * + * Use to let an effect start child work concurrently while still delaying its + * own completion until that child work is done. + * + * **Gotchas** + * + * Child fibers that already exist before the wrapped effect starts are not + * awaited. + * + * @see {@link forkChild} for forking child fibers that are awaited by this operator + * @see {@link forkDetach} for forking fibers outside the child scope + * @see {@link forkIn} for forking into an explicit scope + * @see {@link forkScoped} for forking fibers tied to the current scope + * + * @category supervision & fibers * @since 2.0.0 - * @category Supervision & Fibers */ export const awaitAllChildren: (self: Effect) => Effect = internal.awaitAllChildren /** - * Access the fiber currently executing the effect. + * Accesses the fiber currently executing the effect. + * + * **Example** (Accessing the current fiber) * - * @example * ```ts * import { Console, Effect } from "effect" * @@ -16001,15 +17172,16 @@ export const awaitAllChildren: (self: Effect) => Effect> = internal.fiber /** - * Access the current fiber id executing the effect. + * Accesses the current fiber id executing the effect. + * + * **Example** (Accessing the current fiber id) * - * @example * ```ts * import { Effect } from "effect" * @@ -16024,8 +17196,8 @@ export const fiber: Effect> = internal.fiber * ) * ``` * - * @since 4.0.0 - * @category Supervision & Fibers + * @category supervision & fibers + * @since 2.0.0 */ export const fiberId: Effect = internal.fiberId @@ -16037,27 +17209,24 @@ export const fiberId: Effect = internal.fiberId * Configuration options for running Effect programs, providing control over * interruption and scheduling behavior. * - * @example - * ```ts - * import { Effect } from "effect" + * **When to use** * - * const program = Effect.gen(function*() { - * yield* Effect.sleep("2 seconds") - * return "completed" - * }) + * Use to pass cancellation, scheduler, interruptibility, and fiber-start hooks + * when running an `Effect` at a program boundary. * - * // Run with abort signal for cancellation - * const controller = new AbortController() - * const options: Effect.RunOptions = { - * signal: controller.signal - * } + * **Details** * - * const fiber = Effect.runFork(program, options) - * // Later: controller.abort() to cancel - * ``` + * `signal` interrupts the fiber, `scheduler` provides the scheduler service, + * `uninterruptible` starts the fiber uninterruptibly, and `onFiberStart` + * receives the created fiber. * + * @see {@link runFork} for starting a fiber with these options + * @see {@link runCallback} for callback-based running with these options + * @see {@link runPromise} for promise-based running with these options + * @see {@link runPromiseExit} for promise-based running that returns an `Exit` + * + * @category running * @since 4.0.0 - * @category Running Effects */ export interface RunOptions { readonly signal?: AbortSignal | undefined @@ -16067,25 +17236,17 @@ export interface RunOptions { } /** - * The foundational function for running effects, returning a "fiber" that can + * Runs an effect in the background, returning a fiber that can * be observed or interrupted. * - * **When to Use** + * **When to use** * - * `runFork` is used to run an effect in the background by creating a - * fiber. It is the base function for all other run functions. It starts a fiber - * that can be observed or interrupted. + * Use when you need to start an effect in the background and receive a fiber. * - * Unless you specifically need a `Promise` or synchronous operation, - * `runFork` is a good default choice. + * **Example** (Running an effect in the background) * - * @example * ```ts - * // Title: Running an Effect in the Background - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Fiber } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Fiber, Schedule } from "effect" * * // ┌─── Effect * // ▼ @@ -16103,8 +17264,8 @@ export interface RunOptions { * }, 500) * ``` * + * @category running * @since 2.0.0 - * @category Running Effects */ export const runFork: (effect: Effect, options?: RunOptions | undefined) => Fiber = internal.runFork @@ -16112,9 +17273,15 @@ export const runFork: (effect: Effect, options?: RunOptions | /** * Runs an effect in the background with the provided services. * - * @example + * **When to use** + * + * Use when an effect still requires services, you already have a `Context`, and + * you want a background fiber. + * + * **Example** (Running with services in the background) + * * ```ts - * import { Effect, Context } from "effect" + * import { Context, Effect } from "effect" * * interface Logger { * log: (message: string) => void @@ -16135,8 +17302,8 @@ export const runFork: (effect: Effect, options?: RunOptions | * const fiber = Effect.runForkWith(services)(program) * ``` * + * @category running * @since 4.0.0 - * @category Running Effects */ export const runForkWith: ( context: Context.Context @@ -16145,11 +17312,19 @@ export const runForkWith: ( /** * Forks an effect with the provided services, registers `onExit` as a fiber observer, and returns an interruptor. * + * **When to use** + * + * Use when embedding an effect into callback-style code with explicit services + * and a synchronous interruptor. + * + * **Details** + * * The returned interruptor calls `fiber.interruptUnsafe`, optionally with an interruptor id. * - * @example + * **Example** (Running with services and a callback) + * * ```ts - * import { Console, Effect, Exit, Context } from "effect" + * import { Console, Context, Effect, Exit } from "effect" * * interface Logger { * log: (message: string) => Effect.Effect @@ -16179,8 +17354,8 @@ export const runForkWith: ( * interrupt() * ``` * + * @category running * @since 4.0.0 - * @category Running Effects */ export const runCallbackWith: ( context: Context.Context @@ -16193,10 +17368,13 @@ export const runCallbackWith: ( * Runs an effect asynchronously, registering `onExit` as a fiber observer and * returning an interruptor. * + * **Details** + * * The interruptor calls `fiber.interruptUnsafe` with the optional interruptor * id. * - * @example + * **Example** (Running with a callback) + * * ```ts * import { Console, Effect, Exit } from "effect" * @@ -16223,8 +17401,8 @@ export const runCallbackWith: ( * // interrupt() to cancel the fiber if needed * ``` * - * @since 4.0.0 - * @category Running Effects + * @category running + * @since 2.0.0 */ export const runCallback: ( effect: Effect, @@ -16234,36 +17412,38 @@ export const runCallback: ( /** * Executes an effect and returns the result as a `Promise`. * - * **When to Use** + * **When to use** * - * Use `runPromise` when you need to execute an effect and work with the + * Use when you need to execute an effect and work with the * result using `Promise` syntax, typically for compatibility with other * promise-based code. * * If the effect succeeds, the promise will resolve with the result. If the * effect fails, the promise will reject with an error. * - * @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. + * **Example** (Running a successful effect as a Promise) * - * @example * ```ts - * // Title: Running a Successful Effect as a Promise * import { Effect } from "effect" * * Effect.runPromise(Effect.succeed(1)).then(console.log) * // Output: 1 * ``` * - * @example + * **Example** (Running effects as promises) + * + * ```ts * //Example: Handling a Failing Effect as a Rejected Promise * import { Effect } from "effect" * * Effect.runPromise(Effect.fail("my error")).catch(console.error) * // Output: * // (FiberFailure) Error: my error + * ``` * + * @see {@link runPromiseExit} for a version that returns an `Exit` type instead of rejecting. + * @category running * @since 2.0.0 - * @category Running Effects */ export const runPromise: ( effect: Effect, @@ -16273,9 +17453,15 @@ export const runPromise: ( /** * Executes an effect as a Promise with the provided services. * - * @example + * **When to use** + * + * Use when you already have a `Context` and need Promise interop that rejects on + * effect failure. + * + * **Example** (Running with services as a promise) + * * ```ts - * import { Effect, Context } from "effect" + * import { Context, Effect } from "effect" * * interface Config { * apiUrl: string @@ -16295,8 +17481,8 @@ export const runPromise: ( * Effect.runPromiseWith(context)(program).then(console.log) * ``` * + * @category running * @since 4.0.0 - * @category Running Effects */ export const runPromiseWith: ( context: Context.Context @@ -16306,21 +17492,20 @@ export const runPromiseWith: ( * Runs an effect and returns a `Promise` that resolves to an `Exit`, which * represents the outcome (success or failure) of the effect. * - * **When to Use** + * **When to use** * - * Use `runPromiseExit` when you need to determine if an effect succeeded + * Use when you need to determine if an effect succeeded * or failed, including any defects, and you want to work with a `Promise`. * * **Details** * - * The `Exit` type represents the result of the effect: - * - If the effect succeeds, the result is wrapped in a `Success`. - * - If it fails, the failure information is provided as a `Failure` containing - * a `Cause` type. + * The `Exit` type represents the result of the effect. Successful effects are + * wrapped in `Success`, and failed effects are wrapped in `Failure` with a + * `Cause`. + * + * **Example** (Observing promise results as Exit) * - * @example * ```ts - * // Title: Handling Results as Exit * import { Effect } from "effect" * * // Execute a successful effect and get the Exit result as a Promise @@ -16346,8 +17531,10 @@ export const runPromiseWith: ( * // } * ``` * + * @see {@link runPromise} for a version that rejects on failure. + * + * @category running * @since 2.0.0 - * @category Running Effects */ export const runPromiseExit: ( effect: Effect, @@ -16357,9 +17544,15 @@ export const runPromiseExit: ( /** * Runs an effect and returns a Promise of Exit with provided services. * - * @example + * **When to use** + * + * Use when you already have a `Context` and need Promise interop that preserves + * success and failure as an `Exit`. + * + * **Example** (Running with services as an Exit promise) + * * ```ts - * import { Effect, Exit, Context } from "effect" + * import { Context, Effect, Exit } from "effect" * * interface Database { * query: (sql: string) => string @@ -16383,8 +17576,8 @@ export const runPromiseExit: ( * }) * ``` * + * @category running * @since 4.0.0 - * @category Running Effects */ export const runPromiseExitWith: ( context: Context.Context @@ -16392,23 +17585,22 @@ export const runPromiseExitWith: ( internal.runPromiseExitWith /** - * Executes an effect synchronously, running it immediately and returning the - * result. + * Executes an effect synchronously and returns its success value. * - * **When to Use** + * **When to use** * - * Use `runSync` to run an effect that does not fail and does not include - * any asynchronous operations. + * Use when you need to execute an effect that is guaranteed to complete + * synchronously. * - * If the effect fails or involves asynchronous work, it will throw an error, - * and execution will stop where the failure or async operation occurs. + * **Details** * - * @see {@link runSyncExit} for a version that returns an `Exit` type instead of - * throwing an error. + * If the effect fails, dies, is interrupted, or performs asynchronous work, + * `runSync` throws a `FiberFailure` instead of returning a value. Use + * `runSyncExit` when you want the failure captured as an `Exit`. + * + * **Example** (Running a synchronous effect) * - * @example * ```ts - * // Title: Synchronous Logging * import { Effect } from "effect" * * const program = Effect.sync(() => { @@ -16423,8 +17615,9 @@ export const runPromiseExitWith: ( * // Output: 1 * ``` * - * @example - * // Title: Incorrect Usage with Failing or Async Effects + * **Example** (Throwing for failed or async effects) + * + * ```ts * import { Effect } from "effect" * * try { @@ -16444,18 +17637,27 @@ export const runPromiseExitWith: ( * } * // Output: * // (FiberFailure) AsyncFiberException: Fiber #0 cannot be resolved synchronously. This is caused by using runSync on an effect that performs async work + * ``` * + * @see {@link runSyncExit} for a version that returns an `Exit` type instead of + * throwing an error. + * @category running * @since 2.0.0 - * @category Running Effects */ export const runSync: (effect: Effect) => A = internal.runSync /** * Executes an effect synchronously with provided services. * - * @example + * **When to use** + * + * Use when you already have a `Context`, the effect is known to complete + * synchronously, and failures should throw. + * + * **Example** (Running synchronously with services) + * * ```ts - * import { Effect, Context } from "effect" + * import { Context, Effect } from "effect" * * interface MathService { * add: (a: number, b: number) => number @@ -16476,36 +17678,35 @@ export const runSync: (effect: Effect) => A = internal.runSync * console.log(result) // 5 * ``` * + * @category running * @since 4.0.0 - * @category Running Effects */ export const runSyncWith: ( context: Context.Context ) => (effect: Effect) => A = internal.runSyncWith /** - * Runs an effect synchronously and returns the result as an `Exit` type, which + * Runs an effect synchronously and captures the outcome safely as an `Exit` type, which * represents the outcome (success or failure) of the effect. * - * **When to Use** + * **When to use** * - * Use `runSyncExit` to find out whether an effect succeeded or failed, + * Use to find out whether an effect succeeded or failed, * including any defects, without dealing with asynchronous operations. * * **Details** * - * The `Exit` type represents the result of the effect: - * - If the effect succeeds, the result is wrapped in a `Success`. - * - If it fails, the failure information is provided as a `Failure` containing - * a `Cause` type. + * The `Exit` type represents the result of the effect. Successful effects are + * wrapped in `Success`, and failed effects are wrapped in `Failure` with a + * `Cause`. * * If the effect contains asynchronous operations, `runSyncExit` will * return an `Failure` with a `Die` cause, indicating that the effect cannot be * resolved synchronously. * - * @example + * **Example** (Observing synchronous results as Exit) + * * ```ts - * // Title: Handling Results as Exit * import { Effect } from "effect" * * console.log(Effect.runSyncExit(Effect.succeed(1))) @@ -16529,8 +17730,9 @@ export const runSyncWith: ( * // } * ``` * - * @example - * // Title: Asynchronous Operation Resulting in Die + * **Example** (Capturing async work as a Die cause) + * + * ```ts * import { Effect } from "effect" * * console.log(Effect.runSyncExit(Effect.promise(() => Promise.resolve(1)))) @@ -16548,18 +17750,27 @@ export const runSyncWith: ( * // } * // } * // } + * ``` * + * @see {@link runSync} for a version that throws on failure. + * + * @category running * @since 2.0.0 - * @category Running Effects */ export const runSyncExit: (effect: Effect) => Exit.Exit = internal.runSyncExit /** - * Runs an effect synchronously with provided services, returning an Exit result. + * Runs an effect synchronously with provided services, returning an Exit result safely. + * + * **When to use** + * + * Use when you already have a `Context` and need a synchronous `Exit` instead of + * throwing on failure. + * + * **Example** (Running synchronously with services as Exit) * - * @example * ```ts - * import { Effect, Exit, Context } from "effect" + * import { Context, Effect, Exit } from "effect" * * // Define a logger service * const Logger = Context.Service<{ @@ -16589,8 +17800,8 @@ export const runSyncExit: (effect: Effect) => Exit.Exit = inte * // Success: 42 * ``` * + * @category running * @since 4.0.0 - * @category Running Effects */ export const runSyncExitWith: ( context: Context.Context @@ -16603,102 +17814,144 @@ export const runSyncExitWith: ( /** * Type helpers for functions built with `Effect.fn` and `Effect.fnUntraced`. * + * **Details** + * * Use these to describe generator-based signatures and traced or untraced variants. * - * @since 3.12.0 - * @category Function + * @since 3.11.0 */ -export namespace fn { +export declare namespace fn { /** + * Generator return type accepted by {@link fn} and {@link fnUntraced}. + * + * **When to use** + * + * Use when you need to annotate the return type of a generator body while + * keeping the produced function's `Effect` return type inferred. + * + * **Example** (Annotating an Effect function) + * + * ```ts + * import { Effect } from "effect" + * + * const f = Effect.fnUntraced(function*( + * value: string + * ): Effect.fn.Return { + * return yield* Effect.succeed(value.length) + * }) + * + * // ┌─── Effect.Effect + * // ▼ + * const program = f("hello") + * ``` + * + * **Example** (Annotating a parametric Effect function) + * + * ```ts + * import { Effect } from "effect" + * + * const f = Effect.fnUntraced(function*( + * value: A + * ): Effect.fn.Return { + * return yield* Effect.succeed(value) + * }) + * + * // ┌─── Effect.Effect + * // ▼ + * const program = f("hello") + * ``` + * + * @category utility types * @since 3.19.0 - * @category Models */ - export type Return = Generator, A, any> + export type Return = Generator, A, any> /** + * Type of the untraced function builder used by `Effect.fnUntraced`. + * + * @category utility types * @since 3.11.0 - * @category Models */ export type Untraced = { - , AEff, Args extends Array>( + , AEff, Args extends Array>( body: (this: unassigned, ...args: Args) => Generator ): (...args: Args) => Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never > - , AEff, Args extends Array>( + , AEff, Args extends Array>( body: (this: Self, ...args: Args) => Generator ): (this: Self, ...args: Args) => Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never > - , AEff, Args extends Array, A>( + , AEff, Args extends Array, A>( body: (this: unassigned, ...args: Args) => Generator, a: ( _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args ) => A ): (...args: Args) => A - , AEff, Args extends Array, A>( + , AEff, Args extends Array, A>( body: (this: Self, ...args: Args) => Generator, a: ( _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args ) => A ): (this: Self, ...args: Args) => A - , AEff, Args extends Array, A, B>( + , AEff, Args extends Array, A, B>( body: (this: unassigned, ...args: Args) => Generator, a: ( _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args ) => A, b: (_: A, ...args: Args) => B ): (...args: Args) => B - , AEff, Args extends Array, A, B>( + , AEff, Args extends Array, A, B>( body: (this: Self, ...args: Args) => Generator, a: ( _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -16706,7 +17959,7 @@ export namespace fn { b: (_: A, ...args: Args) => B ): (this: Self, ...args: Args) => B < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -16718,10 +17971,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -16731,7 +17984,7 @@ export namespace fn { ): (...args: Args) => C < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -16743,10 +17996,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -16755,7 +18008,7 @@ export namespace fn { c: (_: B, ...args: Args) => C ): (this: Self, ...args: Args) => C < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -16768,10 +18021,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -16782,7 +18035,7 @@ export namespace fn { ): (...args: Args) => D < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -16795,10 +18048,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -16808,7 +18061,7 @@ export namespace fn { d: (_: C, ...args: Args) => D ): (this: Self, ...args: Args) => D < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -16822,10 +18075,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -16837,7 +18090,7 @@ export namespace fn { ): (...args: Args) => E < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -16851,10 +18104,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -16865,7 +18118,7 @@ export namespace fn { e: (_: D, ...args: Args) => E ): (this: Self, ...args: Args) => E < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -16880,10 +18133,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -16896,7 +18149,7 @@ export namespace fn { ): (...args: Args) => F < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -16911,10 +18164,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -16926,7 +18179,7 @@ export namespace fn { f: (_: E, ...args: Args) => F ): (this: Self, ...args: Args) => F < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -16942,10 +18195,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -16959,7 +18212,7 @@ export namespace fn { ): (...args: Args) => G < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -16975,10 +18228,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -16991,7 +18244,7 @@ export namespace fn { g: (_: F, ...args: Args) => G ): (this: Self, ...args: Args) => G < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17008,10 +18261,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17026,7 +18279,7 @@ export namespace fn { ): (...args: Args) => H < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17043,10 +18296,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17060,7 +18313,7 @@ export namespace fn { h: (_: G, ...args: Args) => H ): (this: Self, ...args: Args) => H < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17078,10 +18331,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17097,7 +18350,7 @@ export namespace fn { ): (...args: Args) => I < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17115,10 +18368,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17133,7 +18386,7 @@ export namespace fn { i: (_: H, ...args: Args) => I ): (this: Self, ...args: Args) => I < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17152,10 +18405,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17172,7 +18425,7 @@ export namespace fn { ): (...args: Args) => J < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17191,10 +18444,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17210,7 +18463,7 @@ export namespace fn { j: (_: I, ...args: Args) => J ): (this: Self, ...args: Args) => J < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17230,10 +18483,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17251,7 +18504,7 @@ export namespace fn { ): (...args: Args) => K < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17271,10 +18524,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17291,7 +18544,7 @@ export namespace fn { k: (_: J, ...args: Args) => K ): (this: Self, ...args: Args) => K < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17312,10 +18565,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17334,7 +18587,7 @@ export namespace fn { ): (...args: Args) => L < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17355,10 +18608,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17376,7 +18629,7 @@ export namespace fn { l: (_: K, ...args: Args) => L ): (this: Self, ...args: Args) => L < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17398,10 +18651,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17421,7 +18674,7 @@ export namespace fn { ): (...args: Args) => M < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17443,10 +18696,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17465,7 +18718,7 @@ export namespace fn { m: (_: L, ...args: Args) => M ): (this: Self, ...args: Args) => M < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17488,10 +18741,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17512,7 +18765,7 @@ export namespace fn { ): (...args: Args) => N < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17535,10 +18788,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17558,7 +18811,7 @@ export namespace fn { n: (_: M, ...args: Args) => N ): (this: Self, ...args: Args) => N < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17582,10 +18835,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17607,7 +18860,7 @@ export namespace fn { ): (...args: Args) => O < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17631,10 +18884,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17655,7 +18908,7 @@ export namespace fn { o: (_: N, ...args: Args) => O ): (this: Self, ...args: Args) => O < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17680,10 +18933,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17706,7 +18959,7 @@ export namespace fn { ): (...args: Args) => P < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17731,10 +18984,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17756,7 +19009,7 @@ export namespace fn { p: (_: O, ...args: Args) => P ): (this: Self, ...args: Args) => P < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17782,10 +19035,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17809,7 +19062,7 @@ export namespace fn { ): (...args: Args) => Q < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17835,10 +19088,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17861,7 +19114,7 @@ export namespace fn { q: (_: P, ...args: Args) => Q ): (this: Self, ...args: Args) => Q < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17888,10 +19141,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17916,7 +19169,7 @@ export namespace fn { ): (...args: Args) => R < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17943,10 +19196,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -17970,7 +19223,7 @@ export namespace fn { r: (_: Q, ...args: Args) => R ): (this: Self, ...args: Args) => R < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -17998,10 +19251,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18027,7 +19280,7 @@ export namespace fn { ): (...args: Args) => S < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18055,10 +19308,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18083,7 +19336,7 @@ export namespace fn { s: (_: R, ...args: Args) => S ): (this: Self, ...args: Args) => S < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18112,10 +19365,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18142,7 +19395,7 @@ export namespace fn { ): (...args: Args) => T < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18171,10 +19424,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18202,135 +19455,137 @@ export namespace fn { } /** - * @since 3.11.0 - * @category Models + * Type of the traced function builder used by `Effect.fn`. + * + * @category utility types + * @since 4.0.0 */ export type Traced = { - , AEff, Args extends Array>( + , AEff, Args extends Array>( body: (this: unassigned, ...args: Args) => Generator | (Eff & Effect) ): (...args: Args) => Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never > - , AEff, Args extends Array>( + , AEff, Args extends Array>( body: (this: Self, ...args: Args) => Generator | (Eff & Effect) ): (this: Self, ...args: Args) => Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never > - , AEff, Args extends Array>( + , AEff, Args extends Array>( options: { readonly self: Self }, body: (this: Self, ...args: Args) => Generator | (Eff & Effect) ): (...args: Args) => Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never > - , AEff, Args extends Array, A>( + , AEff, Args extends Array, A>( body: (this: unassigned, ...args: Args) => Generator | (Eff & Effect), a: ( _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args ) => A ): (...args: Args) => A - , AEff, Args extends Array, A>( + , AEff, Args extends Array, A>( body: (this: Self, ...args: Args) => Generator | (Eff & Effect), a: ( _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args ) => A ): (this: Self, ...args: Args) => A - , AEff, Args extends Array, A>( + , AEff, Args extends Array, A>( options: { readonly self: Self }, body: (this: Self, ...args: Args) => Generator | (Eff & Effect), a: ( _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args ) => A ): (...args: Args) => A - , AEff, Args extends Array, A, B>( + , AEff, Args extends Array, A, B>( body: (this: unassigned, ...args: Args) => Generator | (Eff & Effect), a: ( _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args ) => A, b: (_: A, ...args: Args) => B ): (...args: Args) => B - , AEff, Args extends Array, A, B>( + , AEff, Args extends Array, A, B>( body: (this: Self, ...args: Args) => Generator | (Eff & Effect), a: ( _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args ) => A, b: (_: A, ...args: Args) => B ): (this: Self, ...args: Args) => B - , AEff, Args extends Array, A, B>( + , AEff, Args extends Array, A, B>( options: { readonly self: Self }, body: (this: Self, ...args: Args) => Generator | (Eff & Effect), a: ( _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18339,7 +19594,7 @@ export namespace fn { ): (...args: Args) => B < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18351,10 +19606,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18364,7 +19619,7 @@ export namespace fn { ): (...args: Args) => C < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18376,10 +19631,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18389,7 +19644,7 @@ export namespace fn { ): (this: Self, ...args: Args) => C < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18402,10 +19657,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18415,7 +19670,7 @@ export namespace fn { ): (...args: Args) => C < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18428,10 +19683,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18442,7 +19697,7 @@ export namespace fn { ): (...args: Args) => D < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18455,10 +19710,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18470,7 +19725,7 @@ export namespace fn { < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18484,10 +19739,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18498,7 +19753,7 @@ export namespace fn { ): (...args: Args) => D < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18512,10 +19767,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18527,7 +19782,7 @@ export namespace fn { ): (...args: Args) => E < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18541,10 +19796,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18557,7 +19812,7 @@ export namespace fn { < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18572,10 +19827,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18587,7 +19842,7 @@ export namespace fn { ): (...args: Args) => E < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18602,10 +19857,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18618,7 +19873,7 @@ export namespace fn { ): (...args: Args) => F < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18633,10 +19888,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18650,7 +19905,7 @@ export namespace fn { < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18666,10 +19921,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18682,7 +19937,7 @@ export namespace fn { ): (...args: Args) => F < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18698,10 +19953,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18715,7 +19970,7 @@ export namespace fn { ): (...args: Args) => G < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18731,10 +19986,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18749,7 +20004,7 @@ export namespace fn { < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18766,10 +20021,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18783,7 +20038,7 @@ export namespace fn { ): (...args: Args) => G < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18800,10 +20055,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18818,7 +20073,7 @@ export namespace fn { ): (...args: Args) => H < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18835,10 +20090,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18854,7 +20109,7 @@ export namespace fn { < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18872,10 +20127,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18890,7 +20145,7 @@ export namespace fn { ): (...args: Args) => H < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18908,10 +20163,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18927,7 +20182,7 @@ export namespace fn { ): (...args: Args) => I < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18945,10 +20200,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -18965,7 +20220,7 @@ export namespace fn { < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -18984,10 +20239,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19003,7 +20258,7 @@ export namespace fn { ): (...args: Args) => I < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19022,10 +20277,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19042,7 +20297,7 @@ export namespace fn { ): (...args: Args) => J < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19061,10 +20316,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19082,7 +20337,7 @@ export namespace fn { < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19102,10 +20357,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19122,7 +20377,7 @@ export namespace fn { ): (...args: Args) => J < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19142,10 +20397,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19163,7 +20418,7 @@ export namespace fn { ): (...args: Args) => K < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19183,10 +20438,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19205,7 +20460,7 @@ export namespace fn { < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19226,10 +20481,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19247,7 +20502,7 @@ export namespace fn { ): (...args: Args) => K < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19268,10 +20523,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19290,7 +20545,7 @@ export namespace fn { ): (...args: Args) => L < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19311,10 +20566,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19334,7 +20589,7 @@ export namespace fn { < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19356,10 +20611,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19378,7 +20633,7 @@ export namespace fn { ): (...args: Args) => L < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19400,10 +20655,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19423,7 +20678,7 @@ export namespace fn { ): (...args: Args) => M < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19445,10 +20700,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19469,7 +20724,7 @@ export namespace fn { < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19492,10 +20747,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19515,7 +20770,7 @@ export namespace fn { ): (...args: Args) => M < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19538,10 +20793,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19562,7 +20817,7 @@ export namespace fn { ): (...args: Args) => N < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19585,10 +20840,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19610,7 +20865,7 @@ export namespace fn { < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19634,10 +20889,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19658,7 +20913,7 @@ export namespace fn { ): (...args: Args) => N < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19682,10 +20937,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19707,7 +20962,7 @@ export namespace fn { ): (...args: Args) => O < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19731,10 +20986,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19757,7 +21012,7 @@ export namespace fn { < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19782,10 +21037,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19807,7 +21062,7 @@ export namespace fn { ): (...args: Args) => O < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19832,10 +21087,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19858,7 +21113,7 @@ export namespace fn { ): (...args: Args) => P < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19883,10 +21138,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19910,7 +21165,7 @@ export namespace fn { < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19936,10 +21191,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -19962,7 +21217,7 @@ export namespace fn { ): (...args: Args) => P < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -19988,10 +21243,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -20015,7 +21270,7 @@ export namespace fn { ): (...args: Args) => Q < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -20041,10 +21296,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -20069,7 +21324,7 @@ export namespace fn { < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -20096,10 +21351,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -20123,7 +21378,7 @@ export namespace fn { ): (...args: Args) => Q < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -20150,10 +21405,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -20178,7 +21433,7 @@ export namespace fn { ): (...args: Args) => R < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -20205,10 +21460,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -20234,7 +21489,7 @@ export namespace fn { < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -20262,10 +21517,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -20290,7 +21545,7 @@ export namespace fn { ): (...args: Args) => R < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -20318,10 +21573,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -20347,7 +21602,7 @@ export namespace fn { ): (...args: Args) => S < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -20375,10 +21630,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -20405,7 +21660,7 @@ export namespace fn { < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -20434,10 +21689,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -20463,7 +21718,7 @@ export namespace fn { ): (...args: Args) => S < - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -20492,10 +21747,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -20522,7 +21777,7 @@ export namespace fn { ): (...args: Args) => T < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -20551,10 +21806,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -20582,7 +21837,7 @@ export namespace fn { < Self, - Eff extends Yieldable, + Eff extends Effect, AEff, Args extends Array, A, @@ -20612,10 +21867,10 @@ export namespace fn { _: Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? E + : [Eff] extends [Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Yieldable] ? R + : [Eff] extends [Effect] ? R : never >, ...args: Args @@ -20646,51 +21901,211 @@ export namespace fn { /** * Creates an Effect-returning function without tracing. * - * `Effect.fnUntraced` also acts as a `pipe` function, so you can append transforms after the body. + * **When to use** + * + * Use when you are defining a reusable Effect function whose implementation + * would otherwise be a normal function returning {@link gen}, especially when + * tracing spans or stack-frame capture are not needed. + * + * **Details** + * + * Compared to a plain function that returns {@link gen}, `Effect.fnUntraced` + * reuses the generator body instead of allocating a fresh generator closure + * around the arguments on every call. It does not record an Effect stack-frame + * boundary and does not create tracing spans. Use {@link fn} when you need + * those stack frames or spans. Additional arguments after the generator body + * act like `pipe` transforms: each transform receives the previous result and + * the original function arguments. Annotate the generator return type with + * `Effect.fn.Return` when the produced `Effect` type needs to be + * stated explicitly. + * + * **Example** (Defining untraced effect functions) * - * @example * ```ts - * import { Console, Effect } from "effect" + * import { Effect } from "effect" + * + * const f = Effect.fnUntraced(function*( + * value: string + * ) { + * return yield* Effect.succeed(value.length) + * }) + * + * // ┌─── Effect.Effect + * // ▼ + * const program = f("hello") + * ``` + * + * **Example** (Transforming the returned Effect) + * + * ```ts + * import { Effect } from "effect" + * + * const f = Effect.fnUntraced( + * function*(value: string) { + * return yield* Effect.succeed(value.length) + * }, + * (effect, value) => + * effect.pipe(Effect.map((length) => `${value}: ${length}`)) + * ) + * + * // ┌─── Effect.Effect + * // ▼ + * const program = f("hello") + * ``` + * + * **Example** (Annotating an untraced non-parametric function) + * + * ```ts + * import { Effect } from "effect" + * + * const f = Effect.fnUntraced(function*( + * value: string + * ): Effect.fn.Return { + * return yield* Effect.succeed(value.length) + * }) + * + * // ┌─── Effect.Effect + * // ▼ + * const program = f("hello") + * ``` + * + * **Example** (Annotating an untraced parametric function) + * + * ```ts + * import { Effect } from "effect" + * + * const f = Effect.fnUntraced(function*( + * value: A + * ): Effect.fn.Return { + * return yield* Effect.succeed(value) + * }) + * + * // ┌─── Effect.Effect + * // ▼ + * const program = f("hello") + * ``` + * + * @category functions + * @since 3.12.0 + */ +export const fnUntraced: fn.Untraced = internal.fnUntraced + +/** + * Creates a reusable traced function from an Effect body. + * + * **When to use** + * + * Use when you are defining a reusable Effect function whose implementation + * would otherwise be a normal function returning {@link gen}, and you want + * tracing spans or stack-frame capture. + * + * **Details** + * + * Compared to a plain function that returns {@link gen}, `Effect.fn` reuses the + * generator body instead of allocating a fresh generator closure around the + * arguments on every call. Call `Effect.fn(body, ...)` for a generic + * stack-frame boundary without creating a span. Call + * `Effect.fn("operationName", options?)(body, ...)` when that boundary should + * have a readable operation name and the returned `Effect` should create a + * tracing span when run. {@link SpanOptionsNoTrace} configures span metadata + * such as attributes, links, parent or root selection, kind, sampling, and log + * level. Additional arguments after the generator body act like `pipe` + * transforms: each transform receives the previous result and the original + * function arguments. When those transforms return an `Effect`, the returned + * effect includes stack-frame metadata and, for the named form, a tracing span. + * Generator bodies may declare a `this` parameter; pass `{ self }` before the + * body to bind `this` when the function is created. + * + * **Example** (Defining traced effect functions) + * + * ```ts + * import { Effect } from "effect" + * + * const f = Effect.fn("calculateLength")(function*(value: string) { + * return yield* Effect.succeed(value.length) + * }) + * + * // ┌─── Effect.Effect + * // ▼ + * const program = f("hello") + * ``` + * + * **Example** (Transforming the returned Effect) + * + * ```ts + * import { Effect } from "effect" + * + * const f = Effect.fn("formatLength")( + * function*(value: string) { + * return yield* Effect.succeed(value.length) + * }, + * (effect, value) => + * effect.pipe(Effect.map((length) => `${value}: ${length}`)) + * ) + * + * // ┌─── Effect.Effect + * // ▼ + * const program = f("hello") + * ``` + * + * **Example** (Binding this) + * + * ```ts + * import { Effect } from "effect" + * + * class Counter { + * count = 0 + * + * increment = Effect.fn("Counter.increment")( + * { self: this }, + * function*(this: Counter, by: number) { + * this.count += by + * return yield* Effect.succeed(this.count) + * } + * ) + * } + * + * const counter = new Counter() + * + * // ┌─── Effect.Effect + * // ▼ + * const program = counter.increment(1) + * ``` + * + * **Example** (Annotating a traced non-parametric function) + * + * ```ts + * import { Effect } from "effect" * - * const greet = Effect.fnUntraced(function* (name: string) { - * yield* Console.log(`Hello, ${name}`) - * return name.length + * const f = Effect.fn("calculateLength")(function*( + * value: string + * ): Effect.fn.Return { + * return yield* Effect.succeed(value.length) * }) * - * Effect.runFork(greet("Ada")) + * // ┌─── Effect.Effect + * // ▼ + * const program = f("hello") * ``` * - * @since 3.12.0 - * @category Function - */ -export const fnUntraced: fn.Untraced = internal.fnUntraced - -/** - * Creates a traced function with an optional span name and `SpanOptionsNoTrace` that adds spans and stack frames, plus pipeable post-processing that receives the Effect and the original arguments. - * - * Pipeable functions run after the body and can transform the resulting Effect. + * **Example** (Annotating a traced parametric function) * - * @example * ```ts - * import { Console, Effect } from "effect" - * - * // Create a named span and post-process the returned Effect. - * const greet = Effect.fn("greet")( - * function*(name: string) { - * yield* Console.log(`Hello, ${name}`) - * return name.length - * }, - * Effect.map((length) => length + 1) - * ) + * import { Effect } from "effect" * - * const program = Effect.gen(function*() { - * const result = yield* greet("Ada") - * yield* Console.log(`Length: ${result}`) + * const f = Effect.fn("succeed")(function*( + * value: A + * ): Effect.fn.Return { + * return yield* Effect.succeed(value) * }) + * + * // ┌─── Effect.Effect + * // ▼ + * const program = f("hello") * ``` * - * @since 3.12.0 - * @category Function + * @category functions + * @since 3.11.0 */ export const fn: fn.Traced & { (name: string, options?: SpanOptionsNoTrace): fn.Traced @@ -20704,7 +22119,8 @@ export const fn: fn.Traced & { * Retrieves the `Clock` service from the context and provides it to the * specified effectful function. * - * @example + * **Example** (Accessing the Clock service) + * * ```ts * import { Console, Effect } from "effect" * @@ -20720,8 +22136,8 @@ export const fn: fn.Traced & { * // Current time is: 1735484929744 * ``` * + * @category clock * @since 2.0.0 - * @category Clock */ export const clockWith: ( f: (clock: Clock) => Effect @@ -20734,10 +22150,13 @@ export const clockWith: ( /** * Creates a logger function that logs at the specified level. * + * **Details** + * * If no level is provided, the logger uses the fiber's current log level and * extracts any `Cause` values from the message list. * - * @example + * **Example** (Logging at a dynamic level) + * * ```ts * import { Effect } from "effect" * @@ -20748,8 +22167,8 @@ export const clockWith: ( * }) * ``` * + * @category logging * @since 2.0.0 - * @category Logging */ export const logWithLevel: (level?: Severity) => (...message: ReadonlyArray) => Effect = internal.logWithLevel @@ -20757,7 +22176,8 @@ export const logWithLevel: (level?: Severity) => (...message: ReadonlyArray /** * Logs one or more messages using the default log level. * - * @example + * **Example** (Logging at the default level) + * * ```ts * import { Effect } from "effect" * @@ -20777,15 +22197,16 @@ export const logWithLevel: (level?: Severity) => (...message: ReadonlyArray * // 4 * ``` * + * @category logging * @since 2.0.0 - * @category Logging */ export const log: (...message: ReadonlyArray) => Effect = internal.logWithLevel() /** * Logs one or more messages at the FATAL level. * - * @example + * **Example** (Logging fatal messages) + * * ```ts * import { Effect } from "effect" * @@ -20806,15 +22227,16 @@ export const log: (...message: ReadonlyArray) => Effect = internal.lo * // timestamp=2023-... level=FATAL message="System shutting down" * ``` * + * @category logging * @since 2.0.0 - * @category Logging */ export const logFatal: (...message: ReadonlyArray) => Effect = internal.logWithLevel("Fatal") /** * Logs one or more messages at the WARNING level. * - * @example + * **Example** (Logging warnings) + * * ```ts * import { Effect } from "effect" * @@ -20836,15 +22258,16 @@ export const logFatal: (...message: ReadonlyArray) => Effect = intern * // timestamp=2023-... level=WARN message="Using deprecated API endpoint" * ``` * + * @category logging * @since 2.0.0 - * @category Logging */ export const logWarning: (...message: ReadonlyArray) => Effect = internal.logWithLevel("Warn") /** * Logs one or more messages at the ERROR level. * - * @example + * **Example** (Logging errors) + * * ```ts * import { Effect } from "effect" * @@ -20869,15 +22292,16 @@ export const logWarning: (...message: ReadonlyArray) => Effect = inte * // timestamp=2023-... level=ERROR message="Caught error: Something went wrong" * ``` * + * @category logging * @since 2.0.0 - * @category Logging */ export const logError: (...message: ReadonlyArray) => Effect = internal.logWithLevel("Error") /** * Logs one or more messages at the INFO level. * - * @example + * **Example** (Logging information) + * * ```ts * import { Effect } from "effect" * @@ -20897,15 +22321,16 @@ export const logError: (...message: ReadonlyArray) => Effect = intern * // timestamp=2023-... level=INFO message="Application version: 1.2.3" * ``` * + * @category logging * @since 2.0.0 - * @category Logging */ export const logInfo: (...message: ReadonlyArray) => Effect = internal.logWithLevel("Info") /** * Logs one or more messages at the DEBUG level. * - * @example + * **Example** (Logging debug messages) + * * ```ts * import { Effect } from "effect" * @@ -20926,15 +22351,16 @@ export const logInfo: (...message: ReadonlyArray) => Effect = interna * // timestamp=2023-... level=DEBUG message="Variable state: x=10 y=20 z=30" * ``` * + * @category logging * @since 2.0.0 - * @category Logging */ export const logDebug: (...message: ReadonlyArray) => Effect = internal.logWithLevel("Debug") /** * Logs one or more messages at the TRACE level. * - * @example + * **Example** (Logging trace messages) + * * ```ts * import { Effect } from "effect" * @@ -20958,15 +22384,16 @@ export const logDebug: (...message: ReadonlyArray) => Effect = intern * // timestamp=2023-... level=TRACE message="Exiting function processData" * ``` * + * @category logging * @since 2.0.0 - * @category Logging */ export const logTrace: (...message: ReadonlyArray) => Effect = internal.logWithLevel("Trace") /** * Adds a logger to the set of loggers which will output logs for this effect. * - * @example + * **Example** (Adding a logger to an effect) + * * ```ts * import { Effect, Logger } from "effect" * @@ -20987,14 +22414,15 @@ export const logTrace: (...message: ReadonlyArray) => Effect = intern * // Output includes both default and custom log outputs * ``` * - * @since 2.0.0 - * @category Logging + * @category logging + * @since 4.0.0 */ export const withLogger = dual< /** * Adds a logger to the set of loggers which will output logs for this effect. * - * @example + * **Example** (Adding a logger to an effect) + * * ```ts * import { Effect, Logger } from "effect" * @@ -21015,14 +22443,15 @@ export const withLogger = dual< * // Output includes both default and custom log outputs * ``` * - * @since 2.0.0 - * @category Logging + * @category logging + * @since 4.0.0 */ (logger: Logger) => (effect: Effect) => Effect, /** * Adds a logger to the set of loggers which will output logs for this effect. * - * @example + * **Example** (Adding a logger to an effect) + * * ```ts * import { Effect, Logger } from "effect" * @@ -21043,8 +22472,8 @@ export const withLogger = dual< * // Output includes both default and custom log outputs * ``` * - * @since 2.0.0 - * @category Logging + * @category logging + * @since 4.0.0 */ (effect: Effect, logger: Logger) => Effect >(2, (effect, logger) => @@ -21057,7 +22486,8 @@ export const withLogger = dual< /** * Adds an annotation to each log line in this effect. * - * @example + * **Example** (Adding log annotations) + * * ```ts * import { Effect } from "effect" * @@ -21080,14 +22510,15 @@ export const withLogger = dual< * // All log messages will include the userId and operation annotations * ``` * + * @category logging * @since 2.0.0 - * @category Logging */ export const annotateLogs = dual< /** * Adds an annotation to each log line in this effect. * - * @example + * **Example** (Adding log annotations) + * * ```ts * import { Effect } from "effect" * @@ -21110,8 +22541,8 @@ export const annotateLogs = dual< * // All log messages will include the userId and operation annotations * ``` * + * @category logging * @since 2.0.0 - * @category Logging */ { ( @@ -21125,7 +22556,8 @@ export const annotateLogs = dual< /** * Adds an annotation to each log line in this effect. * - * @example + * **Example** (Adding log annotations) + * * ```ts * import { Effect } from "effect" * @@ -21148,8 +22580,8 @@ export const annotateLogs = dual< * // All log messages will include the userId and operation annotations * ``` * + * @category logging * @since 2.0.0 - * @category Logging */ { ( @@ -21182,11 +22614,18 @@ export const annotateLogs = dual< /** * Adds log annotations to the current scope. * + * **When to use** + * + * Use to attach log annotations that last until the current scope closes. + * + * **Details** + * * This differs from `annotateLogs`, which only annotates a specific effect. * `annotateLogsScoped` updates annotations for the entire current `Scope` and * restores the previous annotations when the scope closes. * - * @example + * **Example** (Adding scoped log annotations) + * * ```ts * import { Effect } from "effect" * @@ -21201,18 +22640,27 @@ export const annotateLogs = dual< * Effect.runPromise(program) * ``` * - * @since 4.0.0 - * @category Logging + * @see {@link annotateLogs} for annotating one effect + * + * @category logging + * @since 3.1.0 */ export const annotateLogsScoped: { /** * Adds log annotations to the current scope. * + * **When to use** + * + * Use to attach log annotations that last until the current scope closes. + * + * **Details** + * * This differs from `annotateLogs`, which only annotates a specific effect. * `annotateLogsScoped` updates annotations for the entire current `Scope` and * restores the previous annotations when the scope closes. * - * @example + * **Example** (Adding scoped log annotations) + * * ```ts * import { Effect } from "effect" * @@ -21227,18 +22675,27 @@ export const annotateLogsScoped: { * Effect.runPromise(program) * ``` * - * @since 4.0.0 - * @category Logging + * @see {@link annotateLogs} for annotating one effect + * + * @category logging + * @since 3.1.0 */ (key: string, value: unknown): Effect /** * Adds log annotations to the current scope. * + * **When to use** + * + * Use to attach log annotations that last until the current scope closes. + * + * **Details** + * * This differs from `annotateLogs`, which only annotates a specific effect. * `annotateLogsScoped` updates annotations for the entire current `Scope` and * restores the previous annotations when the scope closes. * - * @example + * **Example** (Adding scoped log annotations) + * * ```ts * import { Effect } from "effect" * @@ -21253,8 +22710,10 @@ export const annotateLogsScoped: { * Effect.runPromise(program) * ``` * - * @since 4.0.0 - * @category Logging + * @see {@link annotateLogs} for annotating one effect + * + * @category logging + * @since 3.1.0 */ (values: Record): Effect } = internal.annotateLogsScoped @@ -21262,7 +22721,8 @@ export const annotateLogsScoped: { /** * Adds a span to each log line in this effect. * - * @example + * **Example** (Adding a log span) + * * ```ts * import { Effect } from "effect" * @@ -21286,14 +22746,15 @@ export const annotateLogsScoped: { * // All log messages will include span information showing the nested operation context * ``` * + * @category logging * @since 2.0.0 - * @category Logging */ export const withLogSpan = dual< /** * Adds a span to each log line in this effect. * - * @example + * **Example** (Adding a log span) + * * ```ts * import { Effect } from "effect" * @@ -21317,14 +22778,15 @@ export const withLogSpan = dual< * // All log messages will include span information showing the nested operation context * ``` * + * @category logging * @since 2.0.0 - * @category Logging */ (label: string) => (effect: Effect) => Effect, /** * Adds a span to each log line in this effect. * - * @example + * **Example** (Adding a log span) + * * ```ts * import { Effect } from "effect" * @@ -21348,8 +22810,8 @@ export const withLogSpan = dual< * // All log messages will include span information showing the nested operation context * ``` * + * @category logging * @since 2.0.0 - * @category Logging */ (effect: Effect, label: string) => Effect >( @@ -21369,10 +22831,13 @@ export const withLogSpan = dual< /** * Updates the `Metric` every time the `Effect` is executed. * + * **Details** + * * Also accepts an optional function which can be used to map the `Exit` value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Incrementing a metric for each execution) + * * ```ts * import { Effect, Metric } from "effect" * @@ -21391,7 +22856,8 @@ export const withLogSpan = dual< * ) * ``` * - * @example + * **Example** (Mapping exits before updating a metric) + * * ```ts * import { Effect, Exit, Metric } from "effect" * @@ -21411,8 +22877,8 @@ export const withLogSpan = dual< * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ export const track: { // ----------------------------------------------------------------------------- @@ -21422,10 +22888,13 @@ export const track: { /** * Updates the `Metric` every time the `Effect` is executed. * + * **Details** + * * Also accepts an optional function which can be used to map the `Exit` value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Incrementing a metric for each execution) + * * ```ts * import { Effect, Metric } from "effect" * @@ -21444,7 +22913,8 @@ export const track: { * ) * ``` * - * @example + * **Example** (Mapping exits before updating a metric) + * * ```ts * import { Effect, Exit, Metric } from "effect" * @@ -21464,8 +22934,8 @@ export const track: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ (metric: Metric.Metric, f: (exit: Exit.Exit) => Input): (self: Effect) => Effect // ----------------------------------------------------------------------------- @@ -21475,10 +22945,13 @@ export const track: { /** * Updates the `Metric` every time the `Effect` is executed. * + * **Details** + * * Also accepts an optional function which can be used to map the `Exit` value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Incrementing a metric for each execution) + * * ```ts * import { Effect, Metric } from "effect" * @@ -21497,7 +22970,8 @@ export const track: { * ) * ``` * - * @example + * **Example** (Mapping exits before updating a metric) + * * ```ts * import { Effect, Exit, Metric } from "effect" * @@ -21517,8 +22991,8 @@ export const track: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ (metric: Metric.Metric, NoInfer>, State>): (self: Effect) => Effect // ----------------------------------------------------------------------------- @@ -21528,10 +23002,13 @@ export const track: { /** * Updates the `Metric` every time the `Effect` is executed. * + * **Details** + * * Also accepts an optional function which can be used to map the `Exit` value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Incrementing a metric for each execution) + * * ```ts * import { Effect, Metric } from "effect" * @@ -21550,7 +23027,8 @@ export const track: { * ) * ``` * - * @example + * **Example** (Mapping exits before updating a metric) + * * ```ts * import { Effect, Exit, Metric } from "effect" * @@ -21570,8 +23048,8 @@ export const track: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ ( self: Effect, @@ -21585,10 +23063,13 @@ export const track: { /** * Updates the `Metric` every time the `Effect` is executed. * + * **Details** + * * Also accepts an optional function which can be used to map the `Exit` value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Incrementing a metric for each execution) + * * ```ts * import { Effect, Metric } from "effect" * @@ -21607,7 +23088,8 @@ export const track: { * ) * ``` * - * @example + * **Example** (Mapping exits before updating a metric) + * * ```ts * import { Effect, Exit, Metric } from "effect" * @@ -21627,8 +23109,8 @@ export const track: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ ( self: Effect, @@ -21651,10 +23133,13 @@ export const track: { * Updates the provided `Metric` every time the wrapped `Effect` succeeds with * a value. * + * **Details** + * * Also accepts an optional function which can be used to map the success value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Counting successful results) + * * ```ts * import { Effect, Metric } from "effect" * @@ -21672,7 +23157,8 @@ export const track: { * ) * ``` * - * @example + * **Example** (Mapping successes before tracking) + * * ```ts * import { Effect, Metric } from "effect" * @@ -21689,18 +23175,21 @@ export const track: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ export const trackSuccesses: { /** * Updates the provided `Metric` every time the wrapped `Effect` succeeds with * a value. * + * **Details** + * * Also accepts an optional function which can be used to map the success value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Counting successful results) + * * ```ts * import { Effect, Metric } from "effect" * @@ -21718,7 +23207,8 @@ export const trackSuccesses: { * ) * ``` * - * @example + * **Example** (Mapping successes before tracking) + * * ```ts * import { Effect, Metric } from "effect" * @@ -21735,18 +23225,21 @@ export const trackSuccesses: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ (metric: Metric.Metric, f: (value: A) => Input): (self: Effect) => Effect /** * Updates the provided `Metric` every time the wrapped `Effect` succeeds with * a value. * + * **Details** + * * Also accepts an optional function which can be used to map the success value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Counting successful results) + * * ```ts * import { Effect, Metric } from "effect" * @@ -21764,7 +23257,8 @@ export const trackSuccesses: { * ) * ``` * - * @example + * **Example** (Mapping successes before tracking) + * * ```ts * import { Effect, Metric } from "effect" * @@ -21781,18 +23275,21 @@ export const trackSuccesses: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ (metric: Metric.Metric, State>): (self: Effect) => Effect /** * Updates the provided `Metric` every time the wrapped `Effect` succeeds with * a value. * + * **Details** + * * Also accepts an optional function which can be used to map the success value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Counting successful results) + * * ```ts * import { Effect, Metric } from "effect" * @@ -21810,7 +23307,8 @@ export const trackSuccesses: { * ) * ``` * - * @example + * **Example** (Mapping successes before tracking) + * * ```ts * import { Effect, Metric } from "effect" * @@ -21827,8 +23325,8 @@ export const trackSuccesses: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ ( self: Effect, @@ -21839,10 +23337,13 @@ export const trackSuccesses: { * Updates the provided `Metric` every time the wrapped `Effect` succeeds with * a value. * + * **Details** + * * Also accepts an optional function which can be used to map the success value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Counting successful results) + * * ```ts * import { Effect, Metric } from "effect" * @@ -21860,7 +23361,8 @@ export const trackSuccesses: { * ) * ``` * - * @example + * **Example** (Mapping successes before tracking) + * * ```ts * import { Effect, Metric } from "effect" * @@ -21877,8 +23379,8 @@ export const trackSuccesses: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ (self: Effect, metric: Metric.Metric, State>): Effect } = dual( @@ -21898,10 +23400,13 @@ export const trackSuccesses: { * Updates the provided `Metric` every time the wrapped `Effect` fails with an * **expected** error. * + * **Details** + * * Also accepts an optional function which can be used to map the error value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Counting expected failures) + * * ```ts * import { Effect, Metric } from "effect" * @@ -21919,7 +23424,8 @@ export const trackSuccesses: { * ) * ``` * - * @example + * **Example** (Mapping errors before tracking) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -21938,18 +23444,21 @@ export const trackSuccesses: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ export const trackErrors: { /** * Updates the provided `Metric` every time the wrapped `Effect` fails with an * **expected** error. * + * **Details** + * * Also accepts an optional function which can be used to map the error value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Counting expected failures) + * * ```ts * import { Effect, Metric } from "effect" * @@ -21967,7 +23476,8 @@ export const trackErrors: { * ) * ``` * - * @example + * **Example** (Mapping errors before tracking) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -21986,18 +23496,21 @@ export const trackErrors: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ (metric: Metric.Metric, f: (error: E) => Input): (self: Effect) => Effect /** * Updates the provided `Metric` every time the wrapped `Effect` fails with an * **expected** error. * + * **Details** + * * Also accepts an optional function which can be used to map the error value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Counting expected failures) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22015,7 +23528,8 @@ export const trackErrors: { * ) * ``` * - * @example + * **Example** (Mapping errors before tracking) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -22034,18 +23548,21 @@ export const trackErrors: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ (metric: Metric.Metric, State>): (self: Effect) => Effect /** * Updates the provided `Metric` every time the wrapped `Effect` fails with an * **expected** error. * + * **Details** + * * Also accepts an optional function which can be used to map the error value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Counting expected failures) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22063,7 +23580,8 @@ export const trackErrors: { * ) * ``` * - * @example + * **Example** (Mapping errors before tracking) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -22082,8 +23600,8 @@ export const trackErrors: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ ( self: Effect, @@ -22094,10 +23612,13 @@ export const trackErrors: { * Updates the provided `Metric` every time the wrapped `Effect` fails with an * **expected** error. * + * **Details** + * * Also accepts an optional function which can be used to map the error value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Counting expected failures) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22115,7 +23636,8 @@ export const trackErrors: { * ) * ``` * - * @example + * **Example** (Mapping errors before tracking) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -22134,8 +23656,8 @@ export const trackErrors: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ (self: Effect, metric: Metric.Metric, State>): Effect } = dual( @@ -22155,10 +23677,13 @@ export const trackErrors: { * Updates the provided `Metric` every time the wrapped `Effect` fails with an * **unexpected** error (i.e. a defect). * + * **Details** + * * Also accepts an optional function which can be used to map the defect value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Counting defects) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22176,7 +23701,8 @@ export const trackErrors: { * ) * ``` * - * @example + * **Example** (Mapping defects before tracking) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22196,18 +23722,21 @@ export const trackErrors: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ export const trackDefects: { /** * Updates the provided `Metric` every time the wrapped `Effect` fails with an * **unexpected** error (i.e. a defect). * + * **Details** + * * Also accepts an optional function which can be used to map the defect value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Counting defects) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22225,7 +23754,8 @@ export const trackDefects: { * ) * ``` * - * @example + * **Example** (Mapping defects before tracking) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22245,18 +23775,21 @@ export const trackDefects: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ (metric: Metric.Metric, f: (defect: unknown) => Input): (self: Effect) => Effect /** * Updates the provided `Metric` every time the wrapped `Effect` fails with an * **unexpected** error (i.e. a defect). * + * **Details** + * * Also accepts an optional function which can be used to map the defect value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Counting defects) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22274,7 +23807,8 @@ export const trackDefects: { * ) * ``` * - * @example + * **Example** (Mapping defects before tracking) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22294,18 +23828,21 @@ export const trackDefects: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ (metric: Metric.Metric): (self: Effect) => Effect /** * Updates the provided `Metric` every time the wrapped `Effect` fails with an * **unexpected** error (i.e. a defect). * + * **Details** + * * Also accepts an optional function which can be used to map the defect value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Counting defects) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22323,7 +23860,8 @@ export const trackDefects: { * ) * ``` * - * @example + * **Example** (Mapping defects before tracking) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22343,8 +23881,8 @@ export const trackDefects: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ ( self: Effect, @@ -22355,10 +23893,13 @@ export const trackDefects: { * Updates the provided `Metric` every time the wrapped `Effect` fails with an * **unexpected** error (i.e. a defect). * + * **Details** + * * Also accepts an optional function which can be used to map the defect value * of the `Effect` into a valid `Input` for the `Metric`. * - * @example + * **Example** (Counting defects) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22376,7 +23917,8 @@ export const trackDefects: { * ) * ``` * - * @example + * **Example** (Mapping defects before tracking) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22396,8 +23938,8 @@ export const trackDefects: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ (self: Effect, metric: Metric.Metric): Effect } = dual( @@ -22413,11 +23955,14 @@ export const trackDefects: { * Updates the provided `Metric` with the `Duration` of time (in nanoseconds) * that the wrapped `Effect` took to complete. * + * **Details** + * * Also accepts an optional function which can be used to map the `Duration` * that the wrapped `Effect` took to complete into a valid `Input` for the * `Metric`. * - * @example + * **Example** (Recording execution duration) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22433,7 +23978,8 @@ export const trackDefects: { * ) * ``` * - * @example + * **Example** (Mapping duration before tracking) + * * ```ts * import { Duration, Effect, Metric } from "effect" * @@ -22450,19 +23996,22 @@ export const trackDefects: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ export const trackDuration: { /** * Updates the provided `Metric` with the `Duration` of time (in nanoseconds) * that the wrapped `Effect` took to complete. * + * **Details** + * * Also accepts an optional function which can be used to map the `Duration` * that the wrapped `Effect` took to complete into a valid `Input` for the * `Metric`. * - * @example + * **Example** (Recording execution duration) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22478,7 +24027,8 @@ export const trackDuration: { * ) * ``` * - * @example + * **Example** (Mapping duration before tracking) + * * ```ts * import { Duration, Effect, Metric } from "effect" * @@ -22495,8 +24045,8 @@ export const trackDuration: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ ( metric: Metric.Metric, @@ -22506,11 +24056,14 @@ export const trackDuration: { * Updates the provided `Metric` with the `Duration` of time (in nanoseconds) * that the wrapped `Effect` took to complete. * + * **Details** + * * Also accepts an optional function which can be used to map the `Duration` * that the wrapped `Effect` took to complete into a valid `Input` for the * `Metric`. * - * @example + * **Example** (Recording execution duration) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22526,7 +24079,8 @@ export const trackDuration: { * ) * ``` * - * @example + * **Example** (Mapping duration before tracking) + * * ```ts * import { Duration, Effect, Metric } from "effect" * @@ -22543,19 +24097,22 @@ export const trackDuration: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ (metric: Metric.Metric): (self: Effect) => Effect /** * Updates the provided `Metric` with the `Duration` of time (in nanoseconds) * that the wrapped `Effect` took to complete. * + * **Details** + * * Also accepts an optional function which can be used to map the `Duration` * that the wrapped `Effect` took to complete into a valid `Input` for the * `Metric`. * - * @example + * **Example** (Recording execution duration) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22571,7 +24128,8 @@ export const trackDuration: { * ) * ``` * - * @example + * **Example** (Mapping duration before tracking) + * * ```ts * import { Duration, Effect, Metric } from "effect" * @@ -22588,8 +24146,8 @@ export const trackDuration: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ ( self: Effect, @@ -22600,11 +24158,14 @@ export const trackDuration: { * Updates the provided `Metric` with the `Duration` of time (in nanoseconds) * that the wrapped `Effect` took to complete. * + * **Details** + * * Also accepts an optional function which can be used to map the `Duration` * that the wrapped `Effect` took to complete into a valid `Input` for the * `Metric`. * - * @example + * **Example** (Recording execution duration) + * * ```ts * import { Effect, Metric } from "effect" * @@ -22620,7 +24181,8 @@ export const trackDuration: { * ) * ``` * - * @example + * **Example** (Mapping duration before tracking) + * * ```ts * import { Duration, Effect, Metric } from "effect" * @@ -22637,8 +24199,8 @@ export const trackDuration: { * ) * ``` * + * @category tracking * @since 4.0.0 - * @category Tracking */ (self: Effect, metric: Metric.Metric): Effect } = dual( @@ -22667,12 +24229,15 @@ export const trackDuration: { // ----------------------------------------------------------------------------- /** - * Service that holds the current transaction state, it includes + * Service that holds the current transaction state. + * + * **Details** * - * - a journal that stores any non committed change to TxRef values - * - a retry flag to know if the transaction should be retried + * It includes a journal that stores non-committed changes to `TxRef` values and + * a retry flag that records whether the transaction should be retried. + * + * **Example** (Building transactions) * - * @example * ```ts * import { Effect } from "effect" * @@ -22684,8 +24249,8 @@ export const trackDuration: { * }) * ``` * + * @category transactions * @since 4.0.0 - * @category Transactions */ export class Transaction extends Context.Service< Transaction, @@ -22705,21 +24270,21 @@ export class Transaction extends Context.Service< * Defines a transaction boundary. Transactions are "all or nothing" with respect to changes * made to transactional values (i.e. TxRef) that occur within the transaction body. * + * **Details** + * * If called inside an active transaction, `tx` composes with the current transaction and reuses * its journal and retry state instead of creating a nested boundary. * - * In Effect transactions are optimistic with retry, that means transactions are retried when: - * - * - the body of the transaction explicitely calls to `Effect.txRetry` and any of the - * accessed transactional values changes. - * - * - any of the accessed transactional values change during the execution of the transaction - * due to a different transaction committing before the current. + * Effect transactions are optimistic with retry. A transaction is retried when + * its body explicitly calls `Effect.txRetry` and any accessed transactional + * value changes, or when any accessed transactional value changes because a + * different transaction commits before the current one. * * The outermost `tx` call creates the transaction boundary and commits or rolls back the full * composed transaction. * - * @example + * **Example** (Running a transaction) + * * ```ts * import { Effect, TxRef } from "effect" * @@ -22740,8 +24305,8 @@ export class Transaction extends Context.Service< * }) * ``` * + * @category transactions * @since 4.0.0 - * @category Transactions */ export const tx = ( effect: Effect @@ -22833,14 +24398,13 @@ function clearTransaction(state: Transaction["Service"]) { } /** - * Signals that the current transaction needs to be retried. + * Retries the current transaction by signaling that it must be retried. * - * NOTE: the transaction retries on any change to transactional values (i.e. TxRef) accessed in its body. + * **Details** * - * @since 4.0.0 - * @category Transactions + * NOTE: the transaction retries on any change to transactional values (i.e. TxRef) accessed in its body. * - * @example + * **Example** (Retrying transactions) * * ```ts * import { Effect, TxRef } from "effect" @@ -22868,29 +24432,21 @@ function clearTransaction(state: Transaction["Service"]) { * * Effect.runPromise(program).catch(console.error) * ``` + * + * @category transactions + * @since 4.0.0 */ export const txRetry: Effect = flatMap( - Transaction.asEffect(), + Transaction, (state) => { state.retry = true return interrupt } ) /** - * @since 4.0.0 - * @category Effectify - * @example - * ```ts - * import { Effect } from "effect" + * Type helpers for converting callback-based functions into `Effect` functions. * - * // Effectify namespace contains utilities for converting callback-based APIs - * declare function readFile( - * path: string, - * cb: (err: Error | null, data?: string) => void - * ): void - * const effectReadFile = Effect.effectify(readFile) - * // Converts callback-based functions to Effect-based functions - * ``` + * @since 4.0.0 */ export declare namespace Effectify { interface Callback { @@ -22902,20 +24458,10 @@ export declare namespace Effectify { type WithoutNull = unknown extends A ? void : Exclude /** - * @since 4.0.0 - * @category Effectify - * @example - * ```ts - * import type { Effect } from "effect" + * Converts a callback-based function type into an `Effect`-returning function type. * - * // Effectify type converts callback-based function types to Effect-based types - * type CallbackFn = ( - * x: number, - * cb: (err: Error | null, result?: string) => void - * ) => void - * type EffectFn = Effect.Effectify.Effectify - * // Result: (x: number) => Effect - * ``` + * @category effectify + * @since 4.0.0 */ export type Effectify = T extends { (...args: ArgsWithCallback): infer _R1 @@ -23060,20 +24606,10 @@ export declare namespace Effectify { : never /** - * @category Util - * @since 4.0.0 - * @example - * ```ts - * import type { Effect } from "effect" + * Extracts the callback error type from a callback-based function type. * - * // EffectifyError extracts error types from callback-based function types - * type CallbackFn = ( - * x: number, - * cb: (err: Error | null, result?: string) => void - * ) => void - * type ErrorType = Effect.Effectify.EffectifyError - * // Result: Error | null - * ``` + * @category effectify + * @since 4.0.0 */ export type EffectifyError = T extends { (...args: ArgsWithCallback): infer _R1 @@ -23154,9 +24690,19 @@ export declare namespace Effectify { } /** - * Converts a callback-based function to a function that returns an `Effect`. + * Converts an error-first callback API into a function that returns an + * `Effect`. + * + * **Details** + * + * The original function is called with the supplied arguments plus a final + * callback. A non-null callback error fails the returned effect, while a + * successful callback value becomes the effect success. Use `onError` to map + * callback errors and `onSyncError` to turn synchronous throws into typed + * failures; otherwise synchronous throws become defects. + * + * **Example** (Converting callbacks to effects) * - * @example Basic Usage * ```ts * import { Effect } from "effect" * import * as fs from "fs" @@ -23171,7 +24717,8 @@ export declare namespace Effectify { * // Output: contents of package.json * ``` * - * @example Custom Error Handling + * **Example** (Mapping callback errors to typed failures) + * * ```ts * import { Effect } from "effect" * import * as fs from "fs" @@ -23187,14 +24734,24 @@ export declare namespace Effectify { * // Output: Exit.failure with custom error message * ``` * + * @category effectify * @since 4.0.0 - * @category Effectify */ export const effectify: { /** - * Converts a callback-based function to a function that returns an `Effect`. + * Converts an error-first callback API into a function that returns an + * `Effect`. + * + * **Details** + * + * The original function is called with the supplied arguments plus a final + * callback. A non-null callback error fails the returned effect, while a + * successful callback value becomes the effect success. Use `onError` to map + * callback errors and `onSyncError` to turn synchronous throws into typed + * failures; otherwise synchronous throws become defects. + * + * **Example** (Converting callbacks to effects) * - * @example Basic Usage * ```ts * import { Effect } from "effect" * import * as fs from "fs" @@ -23209,7 +24766,8 @@ export const effectify: { * // Output: contents of package.json * ``` * - * @example Custom Error Handling + * **Example** (Mapping callback errors to typed failures) + * * ```ts * import { Effect } from "effect" * import * as fs from "fs" @@ -23225,14 +24783,24 @@ export const effectify: { * // Output: Exit.failure with custom error message * ``` * + * @category effectify * @since 4.0.0 - * @category Effectify */ ) => any>(fn: F): Effectify.Effectify> /** - * Converts a callback-based function to a function that returns an `Effect`. + * Converts an error-first callback API into a function that returns an + * `Effect`. + * + * **Details** + * + * The original function is called with the supplied arguments plus a final + * callback. A non-null callback error fails the returned effect, while a + * successful callback value becomes the effect success. Use `onError` to map + * callback errors and `onSyncError` to turn synchronous throws into typed + * failures; otherwise synchronous throws become defects. + * + * **Example** (Converting callbacks to effects) * - * @example Basic Usage * ```ts * import { Effect } from "effect" * import * as fs from "fs" @@ -23247,7 +24815,8 @@ export const effectify: { * // Output: contents of package.json * ``` * - * @example Custom Error Handling + * **Example** (Mapping callback errors to typed failures) + * * ```ts * import { Effect } from "effect" * import * as fs from "fs" @@ -23263,17 +24832,27 @@ export const effectify: { * // Output: Exit.failure with custom error message * ``` * + * @category effectify * @since 4.0.0 - * @category Effectify */ ) => any, E>( fn: F, onError: (error: Effectify.EffectifyError, args: Parameters) => E ): Effectify.Effectify /** - * Converts a callback-based function to a function that returns an `Effect`. + * Converts an error-first callback API into a function that returns an + * `Effect`. + * + * **Details** + * + * The original function is called with the supplied arguments plus a final + * callback. A non-null callback error fails the returned effect, while a + * successful callback value becomes the effect success. Use `onError` to map + * callback errors and `onSyncError` to turn synchronous throws into typed + * failures; otherwise synchronous throws become defects. + * + * **Example** (Converting callbacks to effects) * - * @example Basic Usage * ```ts * import { Effect } from "effect" * import * as fs from "fs" @@ -23288,7 +24867,8 @@ export const effectify: { * // Output: contents of package.json * ``` * - * @example Custom Error Handling + * **Example** (Mapping callback errors to typed failures) + * * ```ts * import { Effect } from "effect" * import * as fs from "fs" @@ -23304,8 +24884,8 @@ export const effectify: { * // Output: Exit.failure with custom error message * ``` * + * @category effectify * @since 4.0.0 - * @category Effectify */ ) => any, E, E2>( fn: F, @@ -23336,10 +24916,13 @@ export const effectify: { /** * Ensures that an effect's success type extends a given type `A`. * - * This function provides compile-time type checking to ensure that the success - * value of an effect conforms to a specific type constraint. + * **Details** + * + * This helper is checked at compile time and does not change the effect's + * runtime behavior. + * + * **Example** (Constraining the success type) * - * @example * ```ts * import { Effect } from "effect" * @@ -23355,18 +24938,21 @@ export const effectify: { * // Type 'string' is not assignable to type 'number' * ``` * + * @category utility types * @since 4.0.0 - * @category Type Constraints */ export const satisfiesSuccessType = () => (effect: Effect): Effect => effect /** * Ensures that an effect's error type extends a given type `E`. * - * This function provides compile-time type checking to ensure that the error - * type of an effect conforms to a specific type constraint. + * **Details** + * + * This helper is checked at compile time and does not change the effect's + * runtime behavior. + * + * **Example** (Constraining the error type) * - * @example * ```ts * import { Data, Effect } from "effect" * @@ -23384,18 +24970,21 @@ export const satisfiesSuccessType = () => (effect: Effect * // Type 'string' is not assignable to type 'ValidationError' * ``` * + * @category utility types * @since 4.0.0 - * @category Type Constraints */ export const satisfiesErrorType = () => (effect: Effect): Effect => effect /** * Ensures that an effect's requirements type extends a given type `R`. * - * This function provides compile-time type checking to ensure that the - * requirements (context) type of an effect conforms to a specific type constraint. + * **Details** + * + * This helper is checked at compile time and does not change the effect's + * runtime behavior. + * + * **Example** (Constraining the services type) * - * @example * ```ts * import { Effect } from "effect" * @@ -23411,28 +25000,26 @@ export const satisfiesErrorType = () => (effect: Effect() => (effect: Effect): Effect => effect /** - * An optimized version of `map` that checks if an effect is already resolved - * and applies the mapping function eagerly when possible. + * Applies `map` eagerly when an effect is already resolved. + * + * **When to use** * - * **When to Use** + * Use when an already-resolved effect should apply a success transformation + * immediately while pending effects still use regular mapping. * - * `mapEager` provides better performance for effects that are already resolved - * by applying the transformation immediately instead of deferring it through - * the effect pipeline. + * **Details** * - * **Behavior** + * Success effects apply the mapping function immediately. Failure effects pass + * through unchanged, and pending effects fall back to regular `map` behavior. * - * - For **Success effects**: Applies the mapping function immediately to the value - * - For **Failure effects**: Returns the failure as-is without applying the mapping - * - For **Pending effects**: Falls back to the regular `map` behavior + * **Example** (Mapping already completed effects) * - * @example * ```ts * import { Effect } from "effect" * @@ -23445,27 +25032,25 @@ export const satisfiesServicesType = () => (effect: Effec * const mappedPending = Effect.mapEager(pending, (n) => n * 2) // Uses regular map * ``` * + * @category eager * @since 4.0.0 - * @category Eager */ export const mapEager: { /** - * An optimized version of `map` that checks if an effect is already resolved - * and applies the mapping function eagerly when possible. + * Applies `map` eagerly when an effect is already resolved. + * + * **When to use** * - * **When to Use** + * Use when an already-resolved effect should apply a success transformation + * immediately while pending effects still use regular mapping. * - * `mapEager` provides better performance for effects that are already resolved - * by applying the transformation immediately instead of deferring it through - * the effect pipeline. + * **Details** * - * **Behavior** + * Success effects apply the mapping function immediately. Failure effects pass + * through unchanged, and pending effects fall back to regular `map` behavior. * - * - For **Success effects**: Applies the mapping function immediately to the value - * - For **Failure effects**: Returns the failure as-is without applying the mapping - * - For **Pending effects**: Falls back to the regular `map` behavior + * **Example** (Mapping already completed effects) * - * @example * ```ts * import { Effect } from "effect" * @@ -23478,27 +25063,25 @@ export const mapEager: { * const mappedPending = Effect.mapEager(pending, (n) => n * 2) // Uses regular map * ``` * + * @category eager * @since 4.0.0 - * @category Eager */ (f: (a: A) => B): (self: Effect) => Effect /** - * An optimized version of `map` that checks if an effect is already resolved - * and applies the mapping function eagerly when possible. + * Applies `map` eagerly when an effect is already resolved. + * + * **When to use** * - * **When to Use** + * Use when an already-resolved effect should apply a success transformation + * immediately while pending effects still use regular mapping. * - * `mapEager` provides better performance for effects that are already resolved - * by applying the transformation immediately instead of deferring it through - * the effect pipeline. + * **Details** * - * **Behavior** + * Success effects apply the mapping function immediately. Failure effects pass + * through unchanged, and pending effects fall back to regular `map` behavior. * - * - For **Success effects**: Applies the mapping function immediately to the value - * - For **Failure effects**: Returns the failure as-is without applying the mapping - * - For **Pending effects**: Falls back to the regular `map` behavior + * **Example** (Mapping already completed effects) * - * @example * ```ts * import { Effect } from "effect" * @@ -23511,29 +25094,29 @@ export const mapEager: { * const mappedPending = Effect.mapEager(pending, (n) => n * 2) // Uses regular map * ``` * + * @category eager * @since 4.0.0 - * @category Eager */ (self: Effect, f: (a: A) => B): Effect } = internal.mapEager /** - * An optimized version of `mapError` that checks if an effect is already resolved - * and applies the error mapping function eagerly when possible. + * Applies `mapError` eagerly when an effect is already resolved. + * + * **When to use** * - * **When to Use** + * Use when an already-resolved failed effect should apply an error + * transformation immediately while pending effects still use regular error + * mapping. * - * `mapErrorEager` provides better performance for effects that are already resolved - * by applying the error transformation immediately instead of deferring it through - * the effect pipeline. + * **Details** * - * **Behavior** + * Success effects pass through unchanged because there is no error to + * transform. Failure effects apply the mapping function immediately, and + * pending effects fall back to regular `mapError` behavior. * - * - For **Success effects**: Returns the success as-is (no error to transform) - * - For **Failure effects**: Applies the mapping function immediately to the error - * - For **Pending effects**: Falls back to the regular `mapError` behavior + * **Example** (Mapping errors eagerly when possible) * - * @example * ```ts * import { Effect } from "effect" * @@ -23549,27 +25132,27 @@ export const mapEager: { * ) // Uses regular mapError * ``` * + * @category eager * @since 4.0.0 - * @category Eager */ export const mapErrorEager: { /** - * An optimized version of `mapError` that checks if an effect is already resolved - * and applies the error mapping function eagerly when possible. + * Applies `mapError` eagerly when an effect is already resolved. + * + * **When to use** * - * **When to Use** + * Use when an already-resolved failed effect should apply an error + * transformation immediately while pending effects still use regular error + * mapping. * - * `mapErrorEager` provides better performance for effects that are already resolved - * by applying the error transformation immediately instead of deferring it through - * the effect pipeline. + * **Details** * - * **Behavior** + * Success effects pass through unchanged because there is no error to + * transform. Failure effects apply the mapping function immediately, and + * pending effects fall back to regular `mapError` behavior. * - * - For **Success effects**: Returns the success as-is (no error to transform) - * - For **Failure effects**: Applies the mapping function immediately to the error - * - For **Pending effects**: Falls back to the regular `mapError` behavior + * **Example** (Mapping errors eagerly when possible) * - * @example * ```ts * import { Effect } from "effect" * @@ -23585,27 +25168,27 @@ export const mapErrorEager: { * ) // Uses regular mapError * ``` * + * @category eager * @since 4.0.0 - * @category Eager */ (f: (e: E) => E2): (self: Effect) => Effect /** - * An optimized version of `mapError` that checks if an effect is already resolved - * and applies the error mapping function eagerly when possible. + * Applies `mapError` eagerly when an effect is already resolved. + * + * **When to use** * - * **When to Use** + * Use when an already-resolved failed effect should apply an error + * transformation immediately while pending effects still use regular error + * mapping. * - * `mapErrorEager` provides better performance for effects that are already resolved - * by applying the error transformation immediately instead of deferring it through - * the effect pipeline. + * **Details** * - * **Behavior** + * Success effects pass through unchanged because there is no error to + * transform. Failure effects apply the mapping function immediately, and + * pending effects fall back to regular `mapError` behavior. * - * - For **Success effects**: Returns the success as-is (no error to transform) - * - For **Failure effects**: Applies the mapping function immediately to the error - * - For **Pending effects**: Falls back to the regular `mapError` behavior + * **Example** (Mapping errors eagerly when possible) * - * @example * ```ts * import { Effect } from "effect" * @@ -23621,29 +25204,28 @@ export const mapErrorEager: { * ) // Uses regular mapError * ``` * + * @category eager * @since 4.0.0 - * @category Eager */ (self: Effect, f: (e: E) => E2): Effect } = internal.mapErrorEager /** - * An optimized version of `mapBoth` that checks if an effect is already resolved - * and applies the appropriate mapping function eagerly when possible. + * Applies `mapBoth` eagerly when an effect is already resolved. + * + * **When to use** * - * **When to Use** + * Use when an already-resolved effect should transform either success or + * failure immediately while pending effects still use regular channel mapping. * - * `mapBothEager` provides better performance for effects that are already resolved - * by applying the transformation immediately instead of deferring it through - * the effect pipeline. + * **Details** * - * **Behavior** + * Success effects apply `onSuccess` immediately, and failure effects apply + * `onFailure` immediately. Pending effects fall back to regular `mapBoth` + * behavior. * - * - For **Success effects**: Applies the `onSuccess` function immediately to the value - * - For **Failure effects**: Applies the `onFailure` function immediately to the error - * - For **Pending effects**: Falls back to the regular `mapBoth` behavior + * **Example** (Mapping both channels eagerly when possible) * - * @example * ```ts * import { Effect } from "effect" * @@ -23661,27 +25243,26 @@ export const mapErrorEager: { * }) // onFailure applied eagerly * ``` * + * @category eager * @since 4.0.0 - * @category Eager */ export const mapBothEager: { /** - * An optimized version of `mapBoth` that checks if an effect is already resolved - * and applies the appropriate mapping function eagerly when possible. + * Applies `mapBoth` eagerly when an effect is already resolved. + * + * **When to use** * - * **When to Use** + * Use when an already-resolved effect should transform either success or + * failure immediately while pending effects still use regular channel mapping. * - * `mapBothEager` provides better performance for effects that are already resolved - * by applying the transformation immediately instead of deferring it through - * the effect pipeline. + * **Details** * - * **Behavior** + * Success effects apply `onSuccess` immediately, and failure effects apply + * `onFailure` immediately. Pending effects fall back to regular `mapBoth` + * behavior. * - * - For **Success effects**: Applies the `onSuccess` function immediately to the value - * - For **Failure effects**: Applies the `onFailure` function immediately to the error - * - For **Pending effects**: Falls back to the regular `mapBoth` behavior + * **Example** (Mapping both channels eagerly when possible) * - * @example * ```ts * import { Effect } from "effect" * @@ -23699,29 +25280,28 @@ export const mapBothEager: { * }) // onFailure applied eagerly * ``` * + * @category eager * @since 4.0.0 - * @category Eager */ ( options: { readonly onFailure: (e: E) => E2; readonly onSuccess: (a: A) => A2 } ): (self: Effect) => Effect /** - * An optimized version of `mapBoth` that checks if an effect is already resolved - * and applies the appropriate mapping function eagerly when possible. + * Applies `mapBoth` eagerly when an effect is already resolved. + * + * **When to use** * - * **When to Use** + * Use when an already-resolved effect should transform either success or + * failure immediately while pending effects still use regular channel mapping. * - * `mapBothEager` provides better performance for effects that are already resolved - * by applying the transformation immediately instead of deferring it through - * the effect pipeline. + * **Details** * - * **Behavior** + * Success effects apply `onSuccess` immediately, and failure effects apply + * `onFailure` immediately. Pending effects fall back to regular `mapBoth` + * behavior. * - * - For **Success effects**: Applies the `onSuccess` function immediately to the value - * - For **Failure effects**: Applies the `onFailure` function immediately to the error - * - For **Pending effects**: Falls back to the regular `mapBoth` behavior + * **Example** (Mapping both channels eagerly when possible) * - * @example * ```ts * import { Effect } from "effect" * @@ -23739,8 +25319,8 @@ export const mapBothEager: { * }) // onFailure applied eagerly * ``` * + * @category eager * @since 4.0.0 - * @category Eager */ ( self: Effect, @@ -23749,22 +25329,21 @@ export const mapBothEager: { } = internal.mapBothEager /** - * An optimized version of `flatMap` that checks if an effect is already resolved - * and applies the flatMap function eagerly when possible. + * Applies `flatMap` eagerly when an effect is already resolved. + * + * **When to use** * - * **When to Use** + * Use when an already-resolved successful effect should bind immediately to the + * next effect while pending effects still use regular flat mapping. * - * `flatMapEager` provides better performance for effects that are already resolved - * by applying the transformation immediately instead of deferring it through - * the effect pipeline. + * **Details** * - * **Behavior** + * Success effects apply the flatMap function immediately. Failure effects pass + * through unchanged, and pending effects fall back to regular `flatMap` + * behavior. * - * - For **Success effects**: Applies the flatMap function immediately to the value - * - For **Failure effects**: Returns the failure as-is without applying the flatMap - * - For **Pending effects**: Falls back to the regular `flatMap` behavior + * **Example** (Flat mapping eagerly when possible) * - * @example * ```ts * import { Effect } from "effect" * @@ -23780,27 +25359,26 @@ export const mapBothEager: { * ) // Uses regular flatMap * ``` * + * @category eager * @since 4.0.0 - * @category Eager */ export const flatMapEager: { /** - * An optimized version of `flatMap` that checks if an effect is already resolved - * and applies the flatMap function eagerly when possible. + * Applies `flatMap` eagerly when an effect is already resolved. + * + * **When to use** * - * **When to Use** + * Use when an already-resolved successful effect should bind immediately to the + * next effect while pending effects still use regular flat mapping. * - * `flatMapEager` provides better performance for effects that are already resolved - * by applying the transformation immediately instead of deferring it through - * the effect pipeline. + * **Details** * - * **Behavior** + * Success effects apply the flatMap function immediately. Failure effects pass + * through unchanged, and pending effects fall back to regular `flatMap` + * behavior. * - * - For **Success effects**: Applies the flatMap function immediately to the value - * - For **Failure effects**: Returns the failure as-is without applying the flatMap - * - For **Pending effects**: Falls back to the regular `flatMap` behavior + * **Example** (Flat mapping eagerly when possible) * - * @example * ```ts * import { Effect } from "effect" * @@ -23816,27 +25394,26 @@ export const flatMapEager: { * ) // Uses regular flatMap * ``` * + * @category eager * @since 4.0.0 - * @category Eager */ (f: (a: A) => Effect): (self: Effect) => Effect /** - * An optimized version of `flatMap` that checks if an effect is already resolved - * and applies the flatMap function eagerly when possible. + * Applies `flatMap` eagerly when an effect is already resolved. + * + * **When to use** * - * **When to Use** + * Use when an already-resolved successful effect should bind immediately to the + * next effect while pending effects still use regular flat mapping. * - * `flatMapEager` provides better performance for effects that are already resolved - * by applying the transformation immediately instead of deferring it through - * the effect pipeline. + * **Details** * - * **Behavior** + * Success effects apply the flatMap function immediately. Failure effects pass + * through unchanged, and pending effects fall back to regular `flatMap` + * behavior. * - * - For **Success effects**: Applies the flatMap function immediately to the value - * - For **Failure effects**: Returns the failure as-is without applying the flatMap - * - For **Pending effects**: Falls back to the regular `flatMap` behavior + * **Example** (Flat mapping eagerly when possible) * - * @example * ```ts * import { Effect } from "effect" * @@ -23852,29 +25429,28 @@ export const flatMapEager: { * ) // Uses regular flatMap * ``` * + * @category eager * @since 4.0.0 - * @category Eager */ (self: Effect, f: (a: A) => Effect): Effect } = internal.flatMapEager /** - * An optimized version of `catch` that checks if an effect is already resolved - * and applies the catch function eagerly when possible. + * Applies `catch` eagerly when an effect is already resolved. + * + * **When to use** * - * **When to Use** + * Use when an already-resolved failed effect should recover immediately while + * pending effects still use regular error recovery. * - * `catchEager` provides better performance for effects that are already resolved - * by applying the error recovery immediately instead of deferring it through - * the effect pipeline. + * **Details** * - * **Behavior** + * Success effects pass through unchanged because there is no error to catch. + * Failure effects apply the catch function immediately, and pending effects + * fall back to regular `catch` behavior. * - * - For **Success effects**: Returns the success as-is (no error to catch) - * - For **Failure effects**: Applies the catch function immediately to the error - * - For **Pending effects**: Falls back to the regular `catch` behavior + * **Example** (Catching failures eagerly when possible) * - * @example * ```ts * import { Effect } from "effect" * @@ -23900,27 +25476,26 @@ export const flatMapEager: { * ) // Uses regular catch * ``` * + * @category eager * @since 4.0.0 - * @category Eager */ export const catchEager: { /** - * An optimized version of `catch` that checks if an effect is already resolved - * and applies the catch function eagerly when possible. + * Applies `catch` eagerly when an effect is already resolved. + * + * **When to use** * - * **When to Use** + * Use when an already-resolved failed effect should recover immediately while + * pending effects still use regular error recovery. * - * `catchEager` provides better performance for effects that are already resolved - * by applying the error recovery immediately instead of deferring it through - * the effect pipeline. + * **Details** * - * **Behavior** + * Success effects pass through unchanged because there is no error to catch. + * Failure effects apply the catch function immediately, and pending effects + * fall back to regular `catch` behavior. * - * - For **Success effects**: Returns the success as-is (no error to catch) - * - For **Failure effects**: Applies the catch function immediately to the error - * - For **Pending effects**: Falls back to the regular `catch` behavior + * **Example** (Catching failures eagerly when possible) * - * @example * ```ts * import { Effect } from "effect" * @@ -23946,27 +25521,26 @@ export const catchEager: { * ) // Uses regular catch * ``` * + * @category eager * @since 4.0.0 - * @category Eager */ (f: (e: NoInfer) => Effect): (self: Effect) => Effect /** - * An optimized version of `catch` that checks if an effect is already resolved - * and applies the catch function eagerly when possible. + * Applies `catch` eagerly when an effect is already resolved. + * + * **When to use** * - * **When to Use** + * Use when an already-resolved failed effect should recover immediately while + * pending effects still use regular error recovery. * - * `catchEager` provides better performance for effects that are already resolved - * by applying the error recovery immediately instead of deferring it through - * the effect pipeline. + * **Details** * - * **Behavior** + * Success effects pass through unchanged because there is no error to catch. + * Failure effects apply the catch function immediately, and pending effects + * fall back to regular `catch` behavior. * - * - For **Success effects**: Returns the success as-is (no error to catch) - * - For **Failure effects**: Applies the catch function immediately to the error - * - For **Pending effects**: Falls back to the regular `catch` behavior + * **Example** (Catching failures eagerly when possible) * - * @example * ```ts * import { Effect } from "effect" * @@ -23992,8 +25566,8 @@ export const catchEager: { * ) // Uses regular catch * ``` * + * @category eager * @since 4.0.0 - * @category Eager */ (self: Effect, f: (e: NoInfer) => Effect): Effect } = internal.catchEager @@ -24001,10 +25575,13 @@ export const catchEager: { /** * Creates untraced function effects with eager evaluation optimization. * + * **Details** + * * Executes generator functions eagerly when all yielded effects are synchronous, * stopping at the first async effect and deferring to normal execution. * - * @example + * **Example** (Defining eager untraced effect functions) + * * ```ts * import { Effect } from "effect" * @@ -24017,7 +25594,7 @@ export const catchEager: { * const effect = computation() // Executed immediately if all effects are sync * ``` * + * @category eager * @since 4.0.0 - * @category Eager */ export const fnUntracedEager: fn.Untraced = internal.fnUntracedEager diff --git a/.opencode/node_modules/effect/src/Effectable.ts b/.opencode/node_modules/effect/src/Effectable.ts index a47c982a4b60515f4b1cfc621abde21b6e850092..f4a114ad8d64cc4e1e5a7c6bd94ab637690e27ed 100644 --- a/.opencode/node_modules/effect/src/Effectable.ts +++ b/.opencode/node_modules/effect/src/Effectable.ts @@ -1,4 +1,9 @@ /** + * Low-level helpers for making custom values behave like Effects. The module + * exposes a prototype builder and an abstract base class that let + * domain-specific values, such as service keys or configuration descriptions, + * be evaluated by Effect and yielded inside `Effect.gen`. + * * @since 4.0.0 */ import type * as Effect from "./Effect.ts" @@ -8,10 +13,20 @@ import { evaluate, makePrimitiveProto } from "./internal/core.ts" /** * Create a low-level `Effect` prototype. * - * When the effect is evaluated, it will call `evaluate` with the current fiber. + * **When to use** + * + * Use when you need to create a custom Effect-like value without extending a + * class, by providing a label and an evaluate function that receives the + * current fiber. + * + * **Details** + * + * When the effect is evaluated, it calls `evaluate` with the current fiber. * + * @see {@link Class} for a class-based approach to defining custom Effect values + * + * @category prototypes * @since 4.0.0 - * @category Prototypes */ export const Prototype = >(options: { readonly label: string @@ -30,18 +45,24 @@ const Base: new() => Effect.Effect = (() => { Base.prototype = Prototype({ label: "Effectable", evaluate(_) { - return this.asEffect() + return this } }) return Base as any })() /** - * An abstract class that can be extended to create an `Effect`. + * Provides an abstract class that can be extended to create an `Effect`. * - * @since 4.0.0 - * @category Constructors + * **When to use** + * + * Use as an abstract base class to define custom classes whose instances behave + * as `Effect` values. + * + * @see {@link Prototype} for a lower-level primitive approach to creating custom Effect-like values without a class + * @category constructors + * @since 2.0.0 */ export abstract class Class extends Base { - abstract override asEffect(): Effect.Effect + abstract override: Effect.Effect } diff --git a/.opencode/node_modules/effect/src/Encoding.ts b/.opencode/node_modules/effect/src/Encoding.ts index cc2ef804f254668a7f68439c19af76e1ef4cf04d..11885fb90d73d0762720ff79710271716ada78d5 100644 --- a/.opencode/node_modules/effect/src/Encoding.ts +++ b/.opencode/node_modules/effect/src/Encoding.ts @@ -1,5 +1,9 @@ /** - * Encoding & decoding for Base64 (RFC4648), Base64Url, and Hex. + * Encoding and decoding helpers for Base64, Base64Url, and hexadecimal text. + * The functions convert between strings, UTF-8 text, and `Uint8Array` bytes. + * Encode functions return strings directly, while decode functions return + * `Result.Result` so invalid input is reported as an `EncodingError` instead of + * being thrown. * * @since 4.0.0 */ @@ -12,20 +16,56 @@ import * as Result from "./Result.ts" // ------------------------------------------------------------------------------------- /** + * Type identifier stored on `EncodingError` values and used by + * `isEncodingError`. + * + * **When to use** + * + * Use when implementing low-level `EncodingError`-compatible values that need + * to carry the runtime marker. + * + * **Details** + * + * This marker is part of the runtime representation of `EncodingError`. Prefer + * `isEncodingError` when narrowing unknown values. + * + * @see {@link isEncodingError} for the public guard that checks this marker + * + * @category type IDs * @since 4.0.0 - * @category symbols */ export const EncodingErrorTypeId = "~effect/encoding/EncodingError" as const /** + * Literal type of the `EncodingErrorTypeId` marker. + * + * **When to use** + * + * Use to type the marker carried by `EncodingError` values. + * + * @category type IDs * @since 4.0.0 - * @category symbols */ export type EncodingErrorTypeId = typeof EncodingErrorTypeId /** - * @since 4.0.0 + * Error returned when an encoding or decoding operation cannot process its + * input. + * + * **When to use** + * + * Use when you need to handle or inspect failures from encoding or decoding + * operations. + * + * **Details** + * + * The error records whether the failure happened during encoding or decoding, + * which encoding module reported it, the original input, and a human-readable + * message. + * + * @see {@link isEncodingError} for checking whether a value is an EncodingError * @category constructors + * @since 4.0.0 */ export class EncodingError extends Data.TaggedError("EncodingError")<{ kind: "Decode" | "Encode" @@ -34,14 +74,35 @@ export class EncodingError extends Data.TaggedError("EncodingError")<{ message: string }> { /** + * Marks this value as an encoding or decoding error for runtime guards. + * + * **When to use** + * + * Use to identify `EncodingError` instances through `isEncodingError`. + * * @since 4.0.0 */ readonly [EncodingErrorTypeId]: EncodingErrorTypeId = EncodingErrorTypeId } /** - * @since 4.0.0 + * Checks whether a value is an `EncodingError`. + * + * **When to use** + * + * Use to narrow an unknown value before handling it as an `EncodingError` from + * encoding or decoding code. + * + * **Details** + * + * Returns `true` when the value carries the `EncodingErrorTypeId` marker and + * narrows the value to `EncodingError`. + * + * @see {@link EncodingError} for the structured error produced by failed + * encoding and decoding operations + * * @category guards + * @since 4.0.0 */ export const isEncodingError = (u: unknown): u is EncodingError => hasProperty(u, EncodingErrorTypeId) @@ -52,7 +113,19 @@ export const isEncodingError = (u: unknown): u is EncodingError => hasProperty(u /** * Encodes the given value into a base64 (RFC4648) `string`. * - * @example + * **When to use** + * + * Use to encode text or bytes as a standard padded Base64 string for storage or + * transport. + * + * **Details** + * + * String inputs are encoded as UTF-8 bytes before Base64 encoding. + * `Uint8Array` inputs are encoded directly. The output uses the standard + * RFC4648 alphabet with `=` padding. + * + * **Example** (Encoding Base64 strings and bytes) + * * ```ts * import { Encoding } from "effect" * @@ -64,16 +137,31 @@ export const isEncodingError = (u: unknown): u is EncodingError => hasProperty(u * console.log(Encoding.encodeBase64(bytes)) // "SGVsbG8=" * ``` * - * @since 4.0.0 + * @see {@link decodeBase64} for decoding standard Base64 to bytes + * @see {@link decodeBase64String} for decoding standard Base64 to UTF-8 text + * @see {@link encodeBase64Url} for URL-safe unpadded Base64 output + * * @category encoding + * @since 2.0.0 */ export const encodeBase64: (input: Uint8Array | string) => string = (input) => typeof input === "string" ? base64EncodeUint8Array(encoder.encode(input)) : base64EncodeUint8Array(input) /** - * Decodes a base64 (RFC4648) encoded `string` into a `Uint8Array`. + * Decodes a base64 (RFC4648) string into bytes safely. + * + * **When to use** + * + * Use to decode a standard padded Base64 string into bytes without throwing on + * invalid input. + * + * **Details** + * + * Returns `Result.succeed` with a `Uint8Array` when decoding succeeds, or + * `Result.fail` with an `EncodingError` when the input is not valid base64. + * + * **Example** (Decoding Base64 bytes) * - * @example * ```ts * import { Encoding, Result } from "effect" * @@ -83,8 +171,8 @@ export const encodeBase64: (input: Uint8Array | string) => string = (input) => * } * ``` * - * @since 4.0.0 * @category decoding + * @since 2.0.0 */ export const decodeBase64 = (str: string): Result.Result => { const stripped = stripCrlf(str) @@ -140,9 +228,20 @@ export const decodeBase64 = (str: string): Result.Result Result.map(decodeBase64(str), (_) => decoder.decode(_)) @@ -164,7 +263,19 @@ export const decodeBase64String = (str: string) => Result.map(decodeBase64(str), /** * Encodes the given value into a base64 (URL) `string`. * - * @example + * **When to use** + * + * Use to encode text or bytes as an unpadded Base64Url string for contexts that + * require the URL-safe alphabet. + * + * **Details** + * + * String inputs are encoded as UTF-8 bytes before Base64Url encoding. + * `Uint8Array` inputs are encoded directly. The output removes `=` padding and + * replaces `+` with `-` and `/` with `_`. + * + * **Example** (Encoding URL-safe Base64) + * * ```ts * import { Encoding } from "effect" * @@ -175,16 +286,33 @@ export const decodeBase64String = (str: string) => Result.map(decodeBase64(str), * console.log(Encoding.encodeBase64Url(bytes)) // "SGVsbG8_" * ``` * - * @since 4.0.0 + * @see {@link decodeBase64Url} for decoding URL-safe Base64 to bytes + * @see {@link decodeBase64UrlString} for decoding URL-safe Base64 to UTF-8 text + * @see {@link encodeBase64} for standard padded Base64 output + * * @category encoding + * @since 2.0.0 */ export const encodeBase64Url: (input: Uint8Array | string) => string = (input) => typeof input === "string" ? base64UrlEncodeUint8Array(encoder.encode(input)) : base64UrlEncodeUint8Array(input) /** - * Decodes a base64 (URL) encoded `string` into a `Uint8Array`. + * Decodes a URL-safe base64 string into bytes safely. + * + * **When to use** + * + * Use to decode padded or unpadded Base64Url text into bytes without throwing + * on invalid input. + * + * **Details** + * + * Returns `Result.succeed` with a `Uint8Array` when decoding succeeds, or + * `Result.fail` with an `EncodingError` when the input is not valid URL-safe + * base64. Both padded and unpadded URL-safe base64 forms are accepted when + * otherwise valid. + * + * **Example** (Decoding URL-safe Base64 bytes) * - * @example * ```ts * import { Encoding, Result } from "effect" * @@ -194,8 +322,8 @@ export const encodeBase64Url: (input: Uint8Array | string) => string = (input) = * } * ``` * - * @since 4.0.0 * @category decoding + * @since 2.0.0 */ export const decodeBase64Url = (str: string): Result.Result => { const stripped = stripCrlf(str) @@ -230,9 +358,21 @@ export const decodeBase64Url = (str: string): Result.Result Result.map(decodeBase64Url(str), (_) => decoder.decode(_)) @@ -254,7 +394,12 @@ export const decodeBase64UrlString = (str: string) => Result.map(decodeBase64Url /** * Encodes the given value into a hex `string`. * - * @example + * **When to use** + * + * Use to encode text or bytes as lowercase hexadecimal text. + * + * **Example** (Encoding hex strings and bytes) + * * ```ts * import { Encoding } from "effect" * @@ -266,16 +411,27 @@ export const decodeBase64UrlString = (str: string) => Result.map(decodeBase64Url * console.log(Encoding.encodeHex(bytes)) // "48656c6c6f" * ``` * - * @since 4.0.0 * @category encoding + * @since 2.0.0 */ export const encodeHex: (input: Uint8Array | string) => string = (input) => typeof input === "string" ? hexEncodeUint8Array(encoder.encode(input)) : hexEncodeUint8Array(input) /** - * Decodes a hex encoded `string` into a `Uint8Array`. + * Decodes a hexadecimal string into bytes safely. + * + * **When to use** + * + * Use to decode hexadecimal text into bytes without throwing on invalid input. + * + * **Details** + * + * Returns `Result.succeed` with a `Uint8Array` when decoding succeeds, or + * `Result.fail` with an `EncodingError` when the input has an odd length or + * contains invalid hex characters. + * + * **Example** (Decoding hex bytes) * - * @example * ```ts * import { Encoding, Result } from "effect" * @@ -285,8 +441,8 @@ export const encodeHex: (input: Uint8Array | string) => string = (input) => * } * ``` * - * @since 4.0.0 * @category decoding + * @since 2.0.0 */ export const decodeHex = (str: string): Result.Result => { const bytes = new TextEncoder().encode(str) @@ -324,9 +480,20 @@ export const decodeHex = (str: string): Result.Result } /** - * Decodes a hex encoded `string` into a UTF-8 `string`. + * Decodes a hexadecimal string into a UTF-8 string safely. + * + * **When to use** + * + * Use to decode hexadecimal text into UTF-8 text without throwing on invalid + * input. + * + * **Details** + * + * Returns `Result.succeed` with the decoded text when decoding succeeds, or + * `Result.fail` with an `EncodingError` when the input is not valid hex. + * + * **Example** (Decoding hex strings) * - * @example * ```ts * import { Encoding, Result } from "effect" * @@ -336,8 +503,8 @@ export const decodeHex = (str: string): Result.Result * } * ``` * - * @since 4.0.0 * @category decoding + * @since 2.0.0 */ export const decodeHexString = (str: string) => Result.map(decodeHex(str), (_) => decoder.decode(_)) diff --git a/.opencode/node_modules/effect/src/Equal.ts b/.opencode/node_modules/effect/src/Equal.ts index 8535301e4cf32f932b3cb2058e5133e3e3356394..b9c9b5ccf35ce8a3f1a0b9a028d4b0f49cdc3478 100644 --- a/.opencode/node_modules/effect/src/Equal.ts +++ b/.opencode/node_modules/effect/src/Equal.ts @@ -1,71 +1,11 @@ /** - * Structural and custom equality for Effect values. - * - * The `Equal` module provides deep structural comparison for primitives, plain - * objects, arrays, Maps, Sets, Dates, and RegExps. Types that implement the - * {@link Equal} interface can supply their own comparison logic while staying - * compatible with the rest of the ecosystem (HashMap, HashSet, etc.). - * - * ## Mental model - * - * - **Structural equality** — two values are equal when their contents match, - * not when they share the same reference. - * - **Hash-first shortcut** — before comparing fields, the module checks - * {@link Hash.hash}. If the hashes differ the objects are unequal without - * further traversal. - * - **Equal interface** — any object that implements both {@link symbol} (the - * equality method) and `Hash.symbol` (the hash method) can define custom - * comparison logic. - * - **Caching** — comparison results for object pairs are cached in a WeakMap. - * This makes repeated checks fast but **requires immutability** after the - * first comparison. - * - **By-reference opt-out** — {@link byReference} and {@link byReferenceUnsafe} - * let you switch individual objects back to reference equality when you need - * mutable identity semantics. - * - * ## Common tasks - * - * - Compare two values → {@link equals} - * - Check if a value implements `Equal` → {@link isEqual} - * - Use `equals` where an `Equivalence` is expected → {@link asEquivalence} - * - Implement custom equality on a class → implement {@link Equal} (see - * example on the interface) - * - Opt an object out of structural equality → {@link byReference} / - * {@link byReferenceUnsafe} - * - * ## Gotchas - * - * - Objects **must be treated as immutable** after their first equality check. - * Results are cached; mutating an object afterwards yields stale results. - * - `NaN` is considered equal to `NaN` (unlike `===`). - * - Functions without an `Equal` implementation are compared by reference. - * - Map and Set comparisons are order-independent but O(n²) in size. - * - If only one of two objects implements `Equal`, they are never equal. - * - * ## Quickstart - * - * **Example** (basic structural comparison) + * Compares values with Effect's structural equality rules. * - * ```ts - * import { Equal } from "effect" - * - * // Primitives - * console.log(Equal.equals(1, 1)) // true - * console.log(Equal.equals("a", "b")) // false - * - * // Objects and arrays - * console.log(Equal.equals({ x: 1 }, { x: 1 })) // true - * console.log(Equal.equals([1, 2], [1, 2])) // true - * - * // Curried form - * const is42 = Equal.equals(42) - * console.log(is42(42)) // true - * console.log(is42(0)) // false - * ``` - * - * @see {@link equals} — the main comparison function - * @see {@link Equal} — the interface for custom equality - * @see {@link Hash} — the companion hashing module + * `equals` compares primitives, arrays, plain objects, maps, sets, dates, + * regular expressions, and values that implement the `Equal` interface. This + * module also defines the equality symbol, guards, adapters, map and set + * comparison builders, and helpers for marking objects that should compare only + * by reference. * * @since 2.0.0 */ @@ -75,20 +15,18 @@ import { byReferenceInstances, getAllObjectKeys } from "./internal/equal.ts" import { hasProperty } from "./Predicate.ts" /** - * The unique string identifier for the {@link Equal} interface. + * Defines the unique string identifier for the `Equal` interface. * - * Use this as a computed property key when implementing custom equality on a - * class or object literal. + * **When to use** * - * When to use: - * - As the method name when implementing the {@link Equal} interface. - * - To check manually whether an object carries an equality method (prefer - * {@link isEqual} instead). + * Use when you implement custom equality and need the computed property key for + * the equality method. * - * Behavior: - * - Pure constant — no allocation or side effects. + * **Details** * - * **Example** (implementing Equal on a class) + * This is a pure constant with no allocation or side effects. + * + * **Example** (Implementing Equal on a Class) * * ```ts * import { Equal, Hash } from "effect" @@ -108,7 +46,7 @@ import { hasProperty } from "./Predicate.ts" * * @see {@link Equal} — the interface that uses this symbol * @see {@link isEqual} — type guard for `Equal` implementors - * + * @category symbols * @since 2.0.0 */ export const symbol = "~effect/interfaces/Equal" @@ -116,25 +54,27 @@ export const symbol = "~effect/interfaces/Equal" /** * The interface for types that define their own equality logic. * - * Any object that implements both `[Equal.symbol]` (equality) and - * `[Hash.symbol]` (hashing) is recognized by {@link equals} and by - * hash-based collections such as `HashMap` and `HashSet`. + * **When to use** * - * When to use: - * - When you need value-based equality for a class (e.g. domain IDs, + * Use when you need value-based equality for a class (e.g. domain IDs, * coordinates, money values). * - When your type will be stored in `HashMap` or `HashSet`. * - When the default structural comparison is too broad or too narrow for * your type. * - * Behavior: + * **Details** + * + * Any object that implements both `[Equal.symbol]` (equality) and + * `[Hash.symbol]` (hashing) is recognized by {@link equals} and by hash-based + * collections such as `HashMap` and `HashSet`. + * * - Extends `Hash.Hash`, so implementors **must** also provide `[Hash.symbol]`. * - The hash contract: if `a[Equal.symbol](b)` returns `true`, then * `Hash.hash(a)` must equal `Hash.hash(b)`. * - {@link equals} delegates to this method when both operands implement it. * If only one operand implements `Equal`, they are considered unequal. * - * **Example** (coordinate with value equality) + * **Example** (Coordinate with Value Equality) * * ```ts * import { Equal, Hash } from "effect" @@ -160,7 +100,6 @@ export const symbol = "~effect/interfaces/Equal" * @see {@link symbol} — the property key used by the equality method * @see {@link equals} — the main comparison function * @see {@link isEqual} — type guard for `Equal` implementors - * * @category models * @since 2.0.0 */ @@ -169,36 +108,36 @@ export interface Equal extends Hash.Hash { } /** - * Compares two values for deep structural equality. - * - * When to use: - * - As the default equality check throughout Effect code. - * - In data-level assertions or conditional logic where structural comparison - * is needed. - * - In its curried (single-argument) form to build reusable predicates. - * - * Behavior: - * - Returns a `boolean`; never throws. - * - Primitives: compared by value. `NaN` equals `NaN`. - * - Objects implementing {@link Equal}: delegates to their - * `[Equal.symbol]` method. If only one operand implements `Equal`, the - * result is `false`. - * - Dates: compared by ISO string representation. - * - RegExps: compared by string representation. - * - Arrays: element-by-element recursive comparison (order matters). - * - Maps / Sets: structural comparison of entries (order-independent, O(n²)). - * - Plain objects: all own and inherited enumerable keys are compared - * recursively. - * - Functions without an `Equal` implementation are compared by reference. - * - Circular references are handled; two structures that are circular at the - * same depth are considered equal. - * - Hash values are checked first as a fast-path rejection. + * Checks whether two values are deeply structurally equal. + * + * **When to use** + * + * Use when you need Effect's default structural equality check. + * + * **Details** + * + * Returns a `boolean` and never throws. Primitives are compared by value, and + * `NaN` equals `NaN`. Objects implementing `Equal` delegate to their + * `[Equal.symbol]` method; if only one operand implements `Equal`, the result + * is `false`. + * + * Dates compare by ISO string, RegExps compare by string representation, + * arrays compare element-by-element, Maps and Sets compare entries + * order-independently, and plain objects compare enumerable keys recursively. + * Functions without an `Equal` implementation compare by reference. Circular + * references are handled when both structures are circular at the same depth. + * + * Hash values are checked first as a fast-path rejection. The function also + * supports dual data-last usage: call it with one argument to get a curried + * predicate. + * + * **Gotchas** + * * - Results are cached per object pair in a WeakMap. **Objects must not be * mutated after their first comparison.** - * - Supports dual (data-last) usage: call with one argument to get a curried - * predicate. + * - Map and Set comparisons are O(n²) in size. * - * **Example** (comparing values) + * **Example** (Comparing Values) * * ```ts * import { Equal } from "effect" @@ -229,7 +168,6 @@ export interface Equal extends Hash.Hash { * @see {@link Equal} — the interface for custom equality * @see {@link isEqual} — check whether a value implements `Equal` * @see {@link asEquivalence} — wrap `equals` as an `Equivalence` - * * @category equality * @since 2.0.0 */ @@ -454,19 +392,19 @@ const compareSets = makeCompareSet(compareBoth) /** * Checks whether a value implements the {@link Equal} interface. * - * When to use: - * - To branch on whether a value supports custom equality before calling - * its `[Equal.symbol]` method directly. - * - In generic utility code that needs to distinguish `Equal` implementors - * from plain values. + * **When to use** + * + * Use when you need generic utility code to distinguish `Equal` implementors + * from plain values before calling `[Equal.symbol]` directly. + * + * **Details** * - * Behavior: * - Pure function, no side effects. * - Returns `true` if and only if `u` has a property keyed by * {@link symbol}. * - Acts as a TypeScript type guard, narrowing the input to {@link Equal}. * - * **Example** (type guard) + * **Example** (Type Guard) * * ```ts * import { Equal, Hash } from "effect" @@ -488,7 +426,6 @@ const compareSets = makeCompareSet(compareBoth) * * @see {@link Equal} — the interface being checked * @see {@link symbol} — the property key that signals `Equal` support - * * @category guards * @since 2.0.0 */ @@ -497,16 +434,18 @@ export const isEqual = (u: unknown): u is Equal => hasProperty(u, symbol) /** * Wraps {@link equals} as an `Equivalence`. * - * When to use: - * - When an API (e.g. `Array.dedupeWith`, `Equivalence.mapInput`) requires an - * `Equivalence` and you want to reuse `Equal.equals`. + * **When to use** + * + * Use when you want to pass `Equal.equals` to APIs that require an + * `Equivalence`. + * + * **Details** * - * Behavior: * - Returns a function `(a: A, b: A) => boolean` that delegates to * {@link equals}. * - Pure; allocates a thin wrapper on each call. * - * **Example** (deduplicating with Equal semantics) + * **Example** (Deduplicating with Equal Semantics) * * ```ts * import { Array, Equal } from "effect" @@ -517,22 +456,21 @@ export const isEqual = (u: unknown): u is Equal => hasProperty(u, symbol) * ``` * * @see {@link equals} — the underlying comparison function - * * @category instances - * @since 2.0.0 + * @since 4.0.0 */ export const asEquivalence: () => Equivalence = () => equals /** * Creates a proxy that uses reference equality instead of structural equality. * - * When to use: - * - When you have a plain object or array that should be compared by identity - * (reference), not by contents. - * - When you want to preserve the original object unchanged and get a new - * reference-equal handle. + * **When to use** + * + * Use when you need to compare a plain object or array by identity without + * mutating the original value. + * + * **Details** * - * Behavior: * - Returns a `Proxy` wrapping `obj`. The proxy reads through to the * original, so property access is unchanged. * - The proxy is registered in an internal WeakSet; {@link equals} returns @@ -541,7 +479,7 @@ export const asEquivalence: () => Equivalence = () => equals * - Each call creates a **new** proxy, so `byReference(x) !== byReference(x)`. * - Does **not** mutate the original object (unlike {@link byReferenceUnsafe}). * - * **Example** (opting out of structural equality) + * **Example** (Opting Out of Structural Equality) * * ```ts * import { Equal } from "effect" @@ -560,31 +498,33 @@ export const asEquivalence: () => Equivalence = () => equals * @see {@link byReferenceUnsafe} — same effect without a proxy (mutates the * original) * @see {@link equals} — the comparison function affected by this opt-out - * - * @category utility - * @since 2.0.0 + * @category equality + * @since 4.0.0 */ export const byReference = (obj: T): T => byReferenceUnsafe(new Proxy(obj, {})) /** - * Permanently marks an object to use reference equality, without creating a - * proxy. + * Marks an object permanently to use reference equality, without creating a proxy. + * + * **When to use** * - * When to use: - * - When you want reference equality semantics and can accept that the - * original object is **permanently** modified. - * - When proxy overhead is unacceptable (hot paths, large collections). + * Use when you need reference equality without proxy allocation and accept + * permanently marking the original object for reference-only equality. + * + * **Details** * - * Behavior: * - Adds `obj` to an internal WeakSet. From that point on, {@link equals} * treats it as reference-only. * - Returns the **same** object (not a copy or proxy), so * `byReferenceUnsafe(x) === x`. - * - The marking is irreversible for the lifetime of the object. * - Does **not** affect the object's prototype, properties, or behavior * beyond equality checks. * - * **Example** (marking an object for reference equality) + * **Gotchas** + * + * The marking is irreversible for the lifetime of the object. + * + * **Example** (Marking an Object for Reference Equality) * * ```ts * import { Equal } from "effect" @@ -601,9 +541,8 @@ export const byReference = (obj: T): T => byReferenceUnsafe(ne * * @see {@link byReference} — safer alternative that creates a proxy * @see {@link equals} — the comparison function affected by this opt-out - * - * @category utility - * @since 2.0.0 + * @category unsafe + * @since 4.0.0 */ export const byReferenceUnsafe = (obj: T): T => { byReferenceInstances.add(obj) diff --git a/.opencode/node_modules/effect/src/Equivalence.ts b/.opencode/node_modules/effect/src/Equivalence.ts index 712b0c2caced63ed37abfc6a26b516f8032fe509..9d8c85162b448590fccc672f1c635ed57df97cc4 100644 --- a/.opencode/node_modules/effect/src/Equivalence.ts +++ b/.opencode/node_modules/effect/src/Equivalence.ts @@ -1,53 +1,11 @@ /** - * Utilities for defining equivalence relations - binary relations that determine when two values - * should be considered equivalent. Equivalence relations are used for comparing, deduplicating, - * and organizing data in collections and data structures. + * Defines reusable equality functions for values of the same type. * - * ## Mental model - * - * - **Equivalence relation**: A function `(a: A, b: A) => boolean` that returns `true` when values are equivalent - * - **Reflexive property**: Every value is equivalent to itself (`eq(a, a) === true`) - * - **Symmetric property**: If `a` is equivalent to `b`, then `b` is equivalent to `a` (`eq(a, b) === eq(b, a)`) - * - **Transitive property**: If `a` is equivalent to `b` and `b` is equivalent to `c`, then `a` is equivalent to `c` - * - **Reference equality optimization**: {@link make} checks `===` first for performance before calling the custom function - * - **Composition**: Equivalences can be combined using {@link combine} and {@link combineAll} to create more complex relations - * - * ## Common tasks - * - * - Creating custom equivalences → {@link make} - * - Using strict equality (`===`) → {@link strictEqual} - * - Combining multiple equivalences (AND logic) → {@link combine}, {@link combineAll} - * - Transforming input before comparison → {@link mapInput} - * - Creating equivalences for structured types → {@link Struct}, {@link Tuple}, {@link Array_}, {@link Record} - * - * ## Gotchas - * - * - `strictEqual` uses `===`, so `NaN !== NaN` and objects are compared by reference, not structure - * - `make` optimizes with a reference equality check, so identical references return `true` without calling the function - * - `combineAll` with an empty collection returns an equivalence that always returns `true` - * - `Tuple` and `Array` require matching lengths; different lengths are never equivalent - * - * ## Quickstart - * - * **Example** (Case-insensitive string equivalence) - * - * ```ts - * import { Array, Equivalence } from "effect" - * - * const caseInsensitive = Equivalence.make((a, b) => - * a.toLowerCase() === b.toLowerCase() - * ) - * - * const strings = ["Hello", "world", "HELLO", "World"] - * const deduplicated = Array.dedupeWith(strings, caseInsensitive) - * console.log(deduplicated) // ["Hello", "world"] - * ``` - * - * ## See also - * - * - {@link Equal} - For structural equality (can convert to Equivalence) - * - {@link Array_.dedupeWith} - Remove duplicates using an equivalence - * - {@link Chunk} - Collections that use equivalences for operations + * An `Equivalence` returns `true` when two `A` values should be treated as + * the same for a particular purpose. This module includes strict equality + * instances for primitive types, constructors for custom comparisons, and + * helpers for tuples, arrays, structs, records, dates, and values compared + * through a derived field. * * @since 2.0.0 */ @@ -58,13 +16,12 @@ import * as Reducer from "./Reducer.ts" /** * Represents an equivalence relation over type `A`. * - * When to use this: - * - As a type annotation for equivalence functions - * - When implementing custom equivalence logic - * - When working with collection operations that require equivalence relations + * **When to use** + * + * Use as a type annotation when you accept or return an equivalence function. + * + * **Details** * - * Behavior: - * - Pure function: does not mutate inputs or have side effects * - Returns `boolean`: `true` if values are equivalent, `false` otherwise * - Must satisfy reflexive, symmetric, and transitive properties * @@ -95,8 +52,8 @@ import * as Reducer from "./Reducer.ts" * console.log(pointEq({ x: 1, y: 2 }, { x: 1, y: 2 })) // true * ``` * - * See also: {@link make}, {@link strictEqual} - * + * @see {@link make} + * @see {@link strictEqual} * @category type class * @since 2.0.0 */ @@ -105,23 +62,22 @@ export type Equivalence = (self: A, that: A) => boolean /** * Type lambda for `Equivalence`, used for higher-kinded type operations. * - * When to use this: - * - Rarely needed in application code - * - Primarily for internal type system operations and HKT (Higher-Kinded Types) abstractions - * - When working with generic type constructors that require type lambdas + * **When to use** + * + * Use when you need to abstract over `Equivalence` in higher-kinded type code. + * + * **Details** * - * Behavior: * - Enables `Equivalence` to work with the Effect type system's HKT infrastructure * - Used internally for type-level computations and generic abstractions * * **Example** (Type-level usage) * * ```ts - * import type { Equivalence } from "effect" - * import type { Kind } from "effect/HKT" + * import type { Equivalence, HKT } from "effect" * * // Used internally for type-level computations - * type NumberEquivalence = Kind< + * type NumberEquivalence = HKT.Kind< * Equivalence.EquivalenceTypeLambda, * never, * never, @@ -131,8 +87,8 @@ export type Equivalence = (self: A, that: A) => boolean * // Equivalent to: Equivalence.Equivalence * ``` * - * See also: {@link Equivalence}, {@link TypeLambda} - * + * @see {@link Equivalence} + * @see {@link TypeLambda} * @category type lambdas * @since 2.0.0 */ @@ -143,16 +99,17 @@ export interface EquivalenceTypeLambda extends TypeLambda { /** * Creates a custom equivalence relation with an optimized reference equality check. * - * When to use this: - * - When you need a custom equivalence that isn't just strict equality - * - When creating equivalences for complex types with custom comparison logic - * - When you want the performance benefit of reference equality optimization + * **When to use** * - * Behavior: - * - Does not mutate inputs - * - First checks reference equality (`===`) for performance; if values are identical, returns `true` without calling the function - * - Falls back to the provided equivalence function if values are not the same reference - * - The provided function must satisfy reflexive, symmetric, and transitive properties + * Use when you need an equality rule that the built-in instances and input + * mapping helpers cannot express, and you can provide a law-abiding comparison. + * + * **Details** + * + * The returned equivalence first checks reference equality (`===`) for + * performance. If the values are not the same reference, it falls back to the + * provided equivalence function, which must satisfy reflexive, symmetric, and + * transitive properties. * * **Example** (Case-insensitive string equivalence) * @@ -178,12 +135,12 @@ export interface EquivalenceTypeLambda extends TypeLambda { * * const tolerance = Equivalence.make((a, b) => Math.abs(a - b) < 0.0001) * - * console.log(tolerance(1.0, 1.0001)) // false + * console.log(tolerance(1.0, 1.001)) // false * console.log(tolerance(1.0, 1.00001)) // true * ``` * - * See also: {@link strictEqual}, {@link mapInput} - * + * @see {@link strictEqual} + * @see {@link mapInput} * @category constructors * @since 2.0.0 */ @@ -195,18 +152,20 @@ const isStrictEquivalent = (x: unknown, y: unknown) => x === y /** * Creates an equivalence relation that uses strict equality (`===`) to compare values. * - * When to use this: - * - For primitive types (numbers, strings, booleans) where `===` is appropriate - * - When you need reference equality for objects (same object instance) - * - As a building block for more complex equivalences via {@link mapInput} or {@link combine} - * - When performance is critical and you don't need structural equality + * **When to use** * - * Behavior: - * - Does not mutate inputs - * - Uses JavaScript's strict equality operator (`===`) - * - For primitives: compares values directly - * - For objects: compares by reference (same object instance) - * - Note: `NaN !== NaN`, so `NaN` values are never considered equivalent + * Use when you need strict equality (`===`) as the comparison. + * + * **Details** + * + * Uses JavaScript's strict equality operator (`===`). Primitives compare by + * value. Objects compare by reference, so only the same object instance is + * equivalent. Use this as a building block for more complex equivalences via + * `mapInput` or `combine`. + * + * **Gotchas** + * + * `NaN !== NaN`, so `NaN` values are never considered equivalent. * * **Example** (Primitive types) * @@ -232,17 +191,22 @@ const isStrictEquivalent = (x: unknown, y: unknown) => x === y * console.log(strictObjEq(obj, { value: 42 })) // false (different references) * ``` * - * See also: {@link make}, {@link Equal} (for structural equality) - * + * @see {@link make} + * @see `Equal` for structural equality * @category constructors * @since 4.0.0 */ export const strictEqual: () => Equivalence = () => isStrictEquivalent /** - * An `Equivalence` instance for strings using strict equality (`===`). + * Equivalence instance for strings using strict equality (`===`). + * + * **When to use** + * + * Use when you need to supply case-sensitive string equality. + * + * **Example** (Comparing strings) * - * @example * ```ts * import { Equivalence } from "effect" * @@ -256,11 +220,14 @@ export const strictEqual: () => Equivalence = () => isStrictEquivalent export const String: Equivalence = isStrictEquivalent /** - * An `Equivalence` instance for numbers. + * Equivalence instance for numbers. + * + * **When to use** + * + * Use when you need numeric equality that treats NaN as equal to itself. * - * `NaN` is considered equal to `NaN`. + * **Example** (Comparing numbers) * - * @example * ```ts * import { Equivalence } from "effect" * @@ -277,9 +244,14 @@ export const Number: Equivalence = make((self, that) => ) /** - * An `Equivalence` instance for booleans using strict equality (`===`). + * Equivalence instance for booleans using strict equality (`===`). + * + * **When to use** + * + * Use when you need to supply boolean equality. + * + * **Example** (Comparing booleans) * - * @example * ```ts * import { Equivalence } from "effect" * @@ -293,9 +265,14 @@ export const Number: Equivalence = make((self, that) => export const Boolean: Equivalence = isStrictEquivalent /** - * An `Equivalence` instance for bigints using strict equality (`===`). + * Equivalence instance for bigints using strict equality (`===`). + * + * **When to use** + * + * Use when you need to supply bigint equality. + * + * **Example** (Comparing bigints) * - * @example * ```ts * import { Equivalence } from "effect" * @@ -311,16 +288,16 @@ export const BigInt: Equivalence = isStrictEquivalent /** * Combines two equivalence relations using logical AND. * - * When to use this: - * - When you need to combine exactly two equivalences - * - When building complex equivalences from simpler ones - * - When you want both conditions to be satisfied (AND logic) + * **When to use** + * + * Use when you need to combine exactly two equivalences with AND semantics. + * + * **Details** * - * Behavior: - * - Does not mutate inputs - * - Returns `true` only if both equivalences return `true` - * - Short-circuits: if the first equivalence returns `false`, the second is not called - * - The result is also an equivalence (satisfies reflexive, symmetric, transitive properties) + * Returns `true` only if both equivalences return `true`. The comparison + * short-circuits when the first equivalence returns `false`. The result is also + * an equivalence that satisfies reflexive, symmetric, and transitive + * properties. * * **Example** (Combining name and age equivalences) * @@ -352,8 +329,8 @@ export const BigInt: Equivalence = isStrictEquivalent * console.log(personEquivalence(person1, person3)) // false (different age) * ``` * - * See also: {@link combineAll}, {@link mapInput} - * + * @see {@link combineAll} + * @see {@link mapInput} * @category combining * @since 2.0.0 */ @@ -361,16 +338,16 @@ export const combine: { /** * Combines two equivalence relations using logical AND. * - * When to use this: - * - When you need to combine exactly two equivalences - * - When building complex equivalences from simpler ones - * - When you want both conditions to be satisfied (AND logic) + * **When to use** + * + * Use when you need to combine exactly two equivalences with AND semantics. + * + * **Details** * - * Behavior: - * - Does not mutate inputs - * - Returns `true` only if both equivalences return `true` - * - Short-circuits: if the first equivalence returns `false`, the second is not called - * - The result is also an equivalence (satisfies reflexive, symmetric, transitive properties) + * Returns `true` only if both equivalences return `true`. The comparison + * short-circuits when the first equivalence returns `false`. The result is also + * an equivalence that satisfies reflexive, symmetric, and transitive + * properties. * * **Example** (Combining name and age equivalences) * @@ -402,8 +379,8 @@ export const combine: { * console.log(personEquivalence(person1, person3)) // false (different age) * ``` * - * See also: {@link combineAll}, {@link mapInput} - * + * @see {@link combineAll} + * @see {@link mapInput} * @category combining * @since 2.0.0 */ @@ -411,16 +388,16 @@ export const combine: { /** * Combines two equivalence relations using logical AND. * - * When to use this: - * - When you need to combine exactly two equivalences - * - When building complex equivalences from simpler ones - * - When you want both conditions to be satisfied (AND logic) + * **When to use** + * + * Use when you need to combine exactly two equivalences with AND semantics. + * + * **Details** * - * Behavior: - * - Does not mutate inputs - * - Returns `true` only if both equivalences return `true` - * - Short-circuits: if the first equivalence returns `false`, the second is not called - * - The result is also an equivalence (satisfies reflexive, symmetric, transitive properties) + * Returns `true` only if both equivalences return `true`. The comparison + * short-circuits when the first equivalence returns `false`. The result is also + * an equivalence that satisfies reflexive, symmetric, and transitive + * properties. * * **Example** (Combining name and age equivalences) * @@ -452,8 +429,8 @@ export const combine: { * console.log(personEquivalence(person1, person3)) // false (different age) * ``` * - * See also: {@link combineAll}, {@link mapInput} - * + * @see {@link combineAll} + * @see {@link mapInput} * @category combining * @since 2.0.0 */ @@ -463,18 +440,17 @@ export const combine: { /** * Combines multiple equivalence relations into a single equivalence using logical AND. * - * When to use this: - * - When you need to combine three or more equivalences - * - When you have a dynamic collection of equivalences to combine - * - When building equivalences from arrays or iterables - * - Prefer over multiple `combine` calls when you have many equivalences + * **When to use** + * + * Use when you need to combine many `Equivalence` instances from an iterable. * - * Behavior: - * - Does not mutate inputs - * - Returns `true` only if all equivalences in the collection return `true` - * - Short-circuits: stops at the first equivalence that returns `false` - * - Empty collection edge case: returns an equivalence that always returns `true` - * - The result is also an equivalence (satisfies reflexive, symmetric, transitive properties) + * **Details** + * + * Returns `true` only if all equivalences in the collection return `true`. The + * comparison stops at the first equivalence that returns `false`. Empty + * collections return an equivalence that always returns `true`. The result is + * also an equivalence that satisfies reflexive, symmetric, and transitive + * properties. * * **Example** (Combining multiple field equivalences) * @@ -520,8 +496,8 @@ export const combine: { * console.log(alwaysEq("anything", "else")) // true * ``` * - * See also: {@link combine}, {@link mapInput} - * + * @see {@link combine} + * @see {@link mapInput} * @category combining * @since 2.0.0 */ @@ -538,18 +514,18 @@ export const combineAll = (collection: Iterable>): Equivalence /** * Transforms an equivalence relation by mapping the input values before comparison. * - * When to use this: - * - When you need an equivalence for a complex type based on a single property - * - When you want to normalize values before comparison (e.g., case-insensitive strings) - * - When creating equivalences that focus on specific fields of objects - * - As a building block for creating equivalences via {@link combine} or {@link combineAll} + * **When to use** + * + * Use when you need an equivalence for one type by comparing a derived value. + * + * **Details** * - * Behavior: - * - Does not mutate inputs * - Applies the transformation function to both values before comparing - * - The transformation function should be pure (no side effects) + * - The transformation function should be pure and have no side effects * - The resulting equivalence compares the transformed values using the provided equivalence - * - The result is also an equivalence (satisfies reflexive, symmetric, transitive properties) + * - The result is also an equivalence that satisfies reflexive, symmetric, and transitive properties + * - Useful for comparing by one property or normalizing values before + * comparison, such as case-insensitive strings * * **Example** (Equivalence based on object property) * @@ -590,8 +566,8 @@ export const combineAll = (collection: Iterable>): Equivalence * console.log(caseInsensitiveEq("Hello", "World")) // false * ``` * - * See also: {@link combine}, {@link Struct} - * + * @see {@link combine} + * @see {@link Struct} * @category mapping * @since 2.0.0 */ @@ -599,18 +575,18 @@ export const mapInput: { /** * Transforms an equivalence relation by mapping the input values before comparison. * - * When to use this: - * - When you need an equivalence for a complex type based on a single property - * - When you want to normalize values before comparison (e.g., case-insensitive strings) - * - When creating equivalences that focus on specific fields of objects - * - As a building block for creating equivalences via {@link combine} or {@link combineAll} + * **When to use** + * + * Use when you need an equivalence for one type by comparing a derived value. + * + * **Details** * - * Behavior: - * - Does not mutate inputs * - Applies the transformation function to both values before comparing - * - The transformation function should be pure (no side effects) + * - The transformation function should be pure and have no side effects * - The resulting equivalence compares the transformed values using the provided equivalence - * - The result is also an equivalence (satisfies reflexive, symmetric, transitive properties) + * - The result is also an equivalence that satisfies reflexive, symmetric, and transitive properties + * - Useful for comparing by one property or normalizing values before + * comparison, such as case-insensitive strings * * **Example** (Equivalence based on object property) * @@ -651,8 +627,8 @@ export const mapInput: { * console.log(caseInsensitiveEq("Hello", "World")) // false * ``` * - * See also: {@link combine}, {@link Struct} - * + * @see {@link combine} + * @see {@link Struct} * @category mapping * @since 2.0.0 */ @@ -660,18 +636,18 @@ export const mapInput: { /** * Transforms an equivalence relation by mapping the input values before comparison. * - * When to use this: - * - When you need an equivalence for a complex type based on a single property - * - When you want to normalize values before comparison (e.g., case-insensitive strings) - * - When creating equivalences that focus on specific fields of objects - * - As a building block for creating equivalences via {@link combine} or {@link combineAll} + * **When to use** + * + * Use when you need an equivalence for one type by comparing a derived value. + * + * **Details** * - * Behavior: - * - Does not mutate inputs * - Applies the transformation function to both values before comparing - * - The transformation function should be pure (no side effects) + * - The transformation function should be pure and have no side effects * - The resulting equivalence compares the transformed values using the provided equivalence - * - The result is also an equivalence (satisfies reflexive, symmetric, transitive properties) + * - The result is also an equivalence that satisfies reflexive, symmetric, and transitive properties + * - Useful for comparing by one property or normalizing values before + * comparison, such as case-insensitive strings * * **Example** (Equivalence based on object property) * @@ -712,8 +688,8 @@ export const mapInput: { * console.log(caseInsensitiveEq("Hello", "World")) // false * ``` * - * See also: {@link combine}, {@link Struct} - * + * @see {@link combine} + * @see {@link Struct} * @category mapping * @since 2.0.0 */ @@ -726,18 +702,18 @@ export const mapInput: { /** * Creates an equivalence for tuples with heterogeneous element types. * - * When to use this: - * - When comparing tuples with different types at each position - * - When you need different equivalence logic for each tuple element - * - When working with fixed-length tuples (not arrays) - * - Prefer over `Array` when you have a known tuple structure with different types + * **When to use** + * + * Use when you need an `Equivalence` for fixed-length tuples with per-position + * equivalences. + * + * **Details** * - * Behavior: - * - Does not mutate inputs - * - Requires tuples to have the same length; different lengths are never equivalent - * - Applies each equivalence to the corresponding element position - * - Returns `true` only if all elements are equivalent according to their respective equivalences - * - The result is also an equivalence (satisfies reflexive, symmetric, transitive properties) + * Tuples must have the same length; different lengths are never equivalent. + * Each equivalence is applied to the corresponding element position. The result + * returns `true` only if all elements are equivalent according to their + * respective equivalences, and it also satisfies reflexive, symmetric, and + * transitive properties. * * **Example** (Homogeneous tuple equivalence) * @@ -758,7 +734,7 @@ export const mapInput: { * console.log(stringTupleEq(tuple1, tuple3)) // false (different third element) * ``` * - * **Example** (Heterogeneous tuple with custom equivalences) + * **Example** (Tuple with custom equivalences) * * ```ts * import { Equivalence } from "effect" @@ -779,8 +755,6 @@ export const mapInput: { * ) // true * ``` * - * See also: {@link Array_}, {@link Struct} - * * @category combinators * @since 4.0.0 */ @@ -818,19 +792,17 @@ export { /** * Creates an equivalence for arrays where all elements are compared using the same equivalence. * - * When to use this: - * - When comparing arrays with homogeneous element types - * - When all elements should use the same equivalence logic - * - When working with variable-length arrays (not fixed tuples) - * - Prefer over `Tuple` when you have arrays of the same type + * **When to use** + * + * Use when you need to compare arrays with one equivalence for every element. + * + * **Details** * - * Behavior: - * - Does not mutate inputs * - Requires arrays to have the same length; different lengths are never equivalent - * - Compares elements positionally (index 0 with index 0, etc.) + * - Compares elements positionally, such as index `0` with index `0` * - Returns `true` only if all corresponding elements are equivalent * - Empty arrays are considered equivalent - * - The result is also an equivalence (satisfies reflexive, symmetric, transitive properties) + * - The result is also an equivalence that satisfies reflexive, symmetric, and transitive properties * * **Example** (Number array equivalence) * @@ -860,8 +832,8 @@ export { * console.log(stringArrayEq([], [])) // true (empty arrays) * ``` * - * See also: {@link Tuple}, {@link Record} - * + * @see {@link Tuple} + * @see {@link Record} * @category combinators * @since 4.0.0 */ @@ -871,19 +843,18 @@ export { /** * Creates an equivalence for objects by comparing their properties using provided equivalences. * - * When to use this: - * - When comparing objects with known, fixed property names - * - When you need different equivalence logic for different properties - * - When working with struct/interface types with specific fields - * - Prefer over `Record` when you have a fixed set of known properties + * **When to use** + * + * Use when you need an `Equivalence` for objects with known, fixed property + * names. + * + * **Details** * - * Behavior: - * - Does not mutate inputs - * - Compares only the properties specified in the struct definition - * - Properties not in the struct are ignored - * - Returns `true` only if all specified properties are equivalent according to their equivalences - * - Supports both string and symbol keys (via `Reflect.ownKeys`) - * - The result is also an equivalence (satisfies reflexive, symmetric, transitive properties) + * Compares only the properties specified in the struct definition; other + * properties are ignored. String and symbol keys are supported via + * `Reflect.ownKeys`. The result returns `true` only if all specified properties + * are equivalent according to their equivalences, and it also satisfies + * reflexive, symmetric, and transitive properties. * * **Example** (Struct with different equivalences per field) * @@ -931,8 +902,9 @@ export { * console.log(nameAgeEq(obj1, obj2)) // true * ``` * - * See also: {@link Record}, {@link mapInput}, {@link combine} - * + * @see {@link Record} + * @see {@link mapInput} + * @see {@link combine} * @category combinators * @since 4.0.0 */ @@ -951,20 +923,19 @@ export function Struct>>( /** * Creates an equivalence for objects by comparing all properties using the same equivalence. * - * When to use this: - * - When comparing objects with dynamic or unknown property names - * - When all property values should use the same equivalence logic - * - When working with record/dictionary types (key-value maps) - * - Prefer over `Struct` when you have variable properties or need to compare all properties uniformly + * **When to use** + * + * Use when you need to compare records with the same equivalence for every + * property value. + * + * **Details** * - * Behavior: - * - Does not mutate inputs * - Compares all properties present in both objects * - Requires both objects to have the same set of keys; different keys result in `false` * - All property values must be equivalent according to the provided equivalence - * - Supports both string and symbol keys (via `Reflect.ownKeys`) + * - Supports both string and symbol keys via `Reflect.ownKeys` * - Empty objects are considered equivalent - * - The result is also an equivalence (satisfies reflexive, symmetric, transitive properties) + * - The result is also an equivalence that satisfies reflexive, symmetric, and transitive properties * * **Example** (Record with string values) * @@ -998,8 +969,6 @@ export function Struct>>( * console.log(numberRecordEq(scores1, scores3)) // false * ``` * - * See also: {@link Struct}, {@link Array_} - * * @category combinators * @since 4.0.0 */ @@ -1023,16 +992,16 @@ export function Record(value: Equivalence): Equivalence(value: Equivalence): Equivalence() { @@ -1068,23 +1035,19 @@ export function makeReducer() { } /** - * An `Equivalence` instance for `Date` objects. + * Equivalence instance for `Date` objects that compares their `getTime()` values using `Equivalence.Number`. + * + * **When to use** * - * Dates are compared by their time value (milliseconds since the Unix epoch), - * using {@link Date.prototype.getTime}. + * Use when you need an `Equivalence` for JavaScript date objects by their + * millisecond timestamp. * - * When to use this: - * - When comparing `Date` objects by their exact point in time - * - When you need value-based equality instead of reference equality - * - When working with collections that contain `Date` values + * **Details** * - * Behavior: - * - Does not mutate inputs - * - Two dates are equivalent if `self.getTime() === that.getTime()` - * - Internally uses {@link Number} equivalence - * - Different `Date` instances representing the same time are considered equivalent + * Different `Date` instances that represent the same millisecond timestamp are equivalent. Because `Equivalence.Number` + * treats `NaN` as equal to `NaN`, two invalid `Date` values are also considered equivalent. * - * **Example** + * **Example** (Comparing Date values) * * ```ts * import { Equivalence } from "effect" @@ -1113,10 +1076,11 @@ export function makeReducer() { * console.log(Equivalence.Date(d1, d2)) // true (same time value) * ``` * - * See also: {@link Number}, {@link mapInput}, {@link strictEqual} - * + * @see {@link Number} for the numeric equivalence applied to each `Date#getTime()` result + * @see {@link mapInput} for deriving an equivalence by mapping inputs before comparison + * @see {@link strictEqual} for reference equality when two values must be the same object * @category instances - * @since 4.0.0 + * @since 2.0.0 */ export const Date: Equivalence = mapInput( Number, diff --git a/.opencode/node_modules/effect/src/ErrorReporter.ts b/.opencode/node_modules/effect/src/ErrorReporter.ts index 8c34ad181c70bfe6e0967f07790d392e0fc0d03c..1fbc6ccc813b9bf30f33e96710f276dceecf7dfb 100644 --- a/.opencode/node_modules/effect/src/ErrorReporter.ts +++ b/.opencode/node_modules/effect/src/ErrorReporter.ts @@ -1,50 +1,12 @@ /** - * Pluggable error reporting for Effect programs. + * Reports Effect failures to external code. * - * Reporting is triggered by `Effect.withErrorReporting`, - * `ErrorReporter.report`, or built-in reporting boundaries in the HTTP and - * RPC server modules. - * - * Each reporter receives a structured callback with the failing `Cause`, a - * pretty-printed `Error`, severity, and any extra attributes attached to the - * original error — making it straightforward to forward failures to Sentry, - * Datadog, or a custom logging backend. - * - * Use the annotation symbols (`ignore`, `severity`, `attributes`) on your - * error classes to control reporting behavior per-error. - * - * @example - * ```ts - * import { Data, Effect, ErrorReporter } from "effect" - * - * // A reporter that logs to the console - * const consoleReporter = ErrorReporter.make(({ error, severity }) => { - * console.error(`[${severity}]`, error.message) - * }) - * - * // An error that should be ignored by reporters - * class NotFoundError extends Data.TaggedError("NotFoundError")<{}> { - * readonly [ErrorReporter.ignore] = true - * } - * - * // An error with custom severity and attributes - * class RateLimitError extends Data.TaggedError("RateLimitError")<{ - * readonly retryAfter: number - * }> { - * readonly [ErrorReporter.severity] = "Warn" as const - * readonly [ErrorReporter.attributes] = { - * retryAfter: this.retryAfter - * } - * } - * - * // Opt in to error reporting with Effect.withErrorReporting - * const program = Effect.gen(function*() { - * return yield* new RateLimitError({ retryAfter: 60 }) - * }).pipe( - * Effect.withErrorReporting, - * Effect.provide(ErrorReporter.layer([consoleReporter])) - * ) - * ``` + * An `ErrorReporter` receives `Cause` values from `Effect.withErrorReporting`, + * manual `report` calls, or built-in reporting boundaries. It forwards each + * non-interruption error to a callback, so applications can send failures to + * logging, monitoring, or error-tracking systems. This module also includes + * layers for installing reporters and symbols for marking errors as ignored or + * attaching severity and attributes. * * @since 4.0.0 */ @@ -61,28 +23,55 @@ import type { ReadonlyRecord } from "./Record.ts" import type * as Scope from "./Scope.ts" /** + * String literal type used as the runtime type identifier for + * `ErrorReporter` values. + * + * **When to use** + * + * Use to refer to the runtime type identifier type in low-level integrations. + * + * @category type IDs * @since 4.0.0 - * @category Type Identifiers */ export type TypeId = "~effect/ErrorReporter" /** + * Runtime type identifier attached to `ErrorReporter` values. + * + * **Details** + * + * This marker is part of the runtime representation of `ErrorReporter` + * implementations. Most code should create reporters with `make` and register + * them with `layer`. + * + * @category type IDs * @since 4.0.0 - * @category Type Identifiers */ export const TypeId: TypeId = "~effect/ErrorReporter" /** * An `ErrorReporter` receives reported failures and forwards them to an - * external system (logging service, error tracker, etc.). + * external system such as a logging service or error tracker. + * + * **When to use** + * + * Use as the interface for custom reporters that forward reported Effect + * failures to logging, monitoring, or error-tracking systems. + * + * **Details** * * Reporting is triggered by `Effect.withErrorReporting`, * `ErrorReporter.report`, or built-in boundaries in the HTTP and RPC server - * modules. Use {@link make} to create a reporter — it handles deduplication + * modules. Use {@link make} to create a reporter; it handles deduplication * and per-error annotation extraction automatically. * + * @see {@link make} for creating an `ErrorReporter` from a callback + * @see {@link layer} for registering reporters in the environment + * @see {@link report} for manually reporting a `Cause` + * @see {@link Effect.withErrorReporting} for reporting failures from an effect + * + * @category models * @since 4.0.0 - * @category Models */ export interface ErrorReporter { readonly [TypeId]: TypeId @@ -96,12 +85,20 @@ export interface ErrorReporter { /** * Creates an `ErrorReporter` from a callback. * + * **When to use** + * + * Use to define how reported failures are forwarded to a logging, monitoring, + * or error-tracking backend. + * + * **Details** + * * The returned reporter automatically deduplicates causes and individual * errors (the same object is never reported twice), skips interruptions, * and resolves the `ignore`, `severity`, and `attributes` annotations on * each error before invoking your callback. * - * @example + * **Example** (Forwarding errors to the console) + * * ```ts * import { ErrorReporter } from "effect" * @@ -113,8 +110,11 @@ export interface ErrorReporter { * ) * ``` * + * @see {@link layer} for registering reporters in the environment + * @see {@link report} for manually reporting a `Cause` + * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const make = ( report: (options: { @@ -155,29 +155,36 @@ export const make = ( } /** - * A `Context.Reference` holding the set of active `ErrorReporter`s for the + * Context reference that holds the set of active error reporters for the * current fiber. Defaults to an empty set (no reporting). * - * Prefer {@link layer} to configure reporters via the `Layer` API. Use this - * reference directly only when you need low-level control (e.g. reading the - * current reporters or swapping them inside a `FiberRef`). + * **When to use** + * + * Use when you need to read or replace the current set of error reporters + * directly. * + * @category references * @since 4.0.0 - * @category References */ export const CurrentErrorReporters: Context.Reference> = references.CurrentErrorReporters /** * Creates a `Layer` that registers one or more `ErrorReporter`s. * + * **When to use** + * + * Use to provide one or more error reporters to effects that perform error + * reporting. + * + * **Details** + * * Reporters can be plain `ErrorReporter` values or effectful - * `Effect` values that are resolved when the layer is built. + * `Effect` values that are resolved when the layer is built. By + * default the provided reporters **replace** any previously registered + * reporters. Set `mergeWithExisting: true` to add them alongside existing ones. * - * By default the provided reporters **replace** any previously registered - * reporters. Set `mergeWithExisting: true` to add them alongside existing - * ones. + * **Example** (Providing error reporters) * - * @example * ```ts * import { Effect, ErrorReporter } from "effect" * @@ -207,8 +214,11 @@ export const CurrentErrorReporters: Context.Reference * ) * ``` * + * @see {@link make} for creating an `ErrorReporter` from a callback + * @see {@link CurrentErrorReporters} for low-level access to the current reporters + * + * @category layers * @since 4.0.0 - * @category Layers */ export const layer = < const Reporters extends ReadonlyArray> @@ -237,13 +247,14 @@ export const layer = < ) /** - * Manually report a `Cause` to all registered `ErrorReporter`s on the - * current fiber. + * Runs all registered error reporters on the current fiber for a `Cause`. + * + * **When to use** * - * This is useful when you want to report an error for observability without - * actually failing the fiber. + * Use to report a failure for observability without failing the current fiber. + * + * **Example** (Reporting a cause manually) * - * @example * ```ts * import { Cause, Effect, ErrorReporter } from "effect" * @@ -255,8 +266,8 @@ export const layer = < * }) * ``` * - * @since 4.0.0 * @category Reporting + * @since 4.0.0 */ export const report = (cause: Cause.Cause): Effect.Effect => Effect.withFiber((fiber) => { @@ -265,18 +276,29 @@ export const report = (cause: Cause.Cause): Effect.Effect => }) /** - * Interface that errors can implement to control reporting behavior. + * Interface that object errors can implement to control reporting behavior. * - * All three annotation properties are optional: - * - `[ErrorReporter.ignore]` — when `true`, the error is never reported - * - `[ErrorReporter.severity]` — overrides the default `"Error"` severity - * - `[ErrorReporter.attributes]` — extra key/value pairs forwarded to reporters + * **When to use** * - * The global `Error` interface is augmented with `Reportable`, so these - * properties are available on all `Error` instances. + * Use as the annotation contract for object errors that customize how error + * reporting handles them. * + * **Details** + * + * All three annotation properties are optional: `[ErrorReporter.ignore]` + * prevents reporting when set to `true`, `[ErrorReporter.severity]` overrides + * the default `"Info"` severity, and `[ErrorReporter.attributes]` adds extra + * key/value pairs forwarded to reporters. The global `Error` interface is + * augmented with `Reportable`, so these properties are available on `Error` + * instances at the type level. + * + * @see {@link ignore} for the runtime annotation key that suppresses reports + * @see {@link severity} for the runtime annotation key that overrides severity + * @see {@link attributes} for the runtime annotation key that attaches reporter + * metadata + * + * @category annotations * @since 4.0.0 - * @category Annotations */ export interface Reportable { readonly [ignore]?: boolean @@ -289,32 +311,42 @@ declare global { } /** - * Symbol key used to mark an error as unreportable. + * Defines the string property key used to mark an object error as ignored by error + * reporting. * - * Set this property to `true` on any error class to prevent it from being - * forwarded to reporters. Useful for expected errors such as HTTP 404s. + * **When to use** * - * @example - * ```ts - * import { Data, ErrorReporter } from "effect" + * Use to type the property key that suppresses reporting for expected object + * errors. * - * class NotFoundError extends Data.TaggedError("NotFoundError")<{}> { - * readonly [ErrorReporter.ignore] = true - * } - * ``` + * **Details** + * + * Set this property to `true` on an error class or object error to prevent it + * from being forwarded to reporters. This is useful for expected failures such + * as HTTP 404 responses. * + * @category annotations * @since 4.0.0 - * @category Annotations */ export type ignore = "~effect/ErrorReporter/ignore" /** - * Symbol key used to mark an error as unreportable. + * Defines the runtime property key used to mark an object error as ignored by error + * reporting. + * + * **When to use** + * + * Use to suppress reporting for expected object errors, such as HTTP 404 + * responses. + * + * **Details** * - * Set this property to `true` on any error class to prevent it from being - * forwarded to reporters. Useful for expected errors such as HTTP 404s. + * Set `error[ErrorReporter.ignore]` to `true` to prevent the error from being + * forwarded to reporters. This is useful for expected failures such as HTTP 404 + * responses. + * + * **Example** (Marking errors as ignored) * - * @example * ```ts * import { Data, ErrorReporter } from "effect" * @@ -323,8 +355,12 @@ export type ignore = "~effect/ErrorReporter/ignore" * } * ``` * + * @see {@link isIgnored} for checking whether a value carries this annotation + * @see {@link Reportable} for the annotation contract recognized on object + * errors + * + * @category annotations * @since 4.0.0 - * @category Annotations */ export const ignore: ignore = "~effect/ErrorReporter/ignore" @@ -332,41 +368,52 @@ export const ignore: ignore = "~effect/ErrorReporter/ignore" * Returns `true` if the given value has the `ErrorReporter.ignore` annotation * set to `true`. * + * **When to use** + * + * Use to check whether an error value is annotated to be skipped before + * forwarding it to error reporting code. + * + * @see {@link ignore} for the annotation key this predicate reads + * + * @category annotations * @since 4.0.0 - * @category Annotations */ export const isIgnored = (u: unknown): boolean => typeof u === "object" && u !== null && ignore in u && u[ignore] === true /** - * Symbol key used to override the severity level of an error. + * Defines the string property key used to override the severity level of an object error. * - * When set, the reporter callback receives this value as `severity` instead - * of the default `"Error"`. Accepted values are the `LogLevel.Severity` - * literals: `"Trace"`, `"Debug"`, `"Info"`, `"Warn"`, `"Error"`, `"Fatal"`. + * **When to use** * - * @example - * ```ts - * import { Data, ErrorReporter } from "effect" + * Use to type the property key that overrides the reporting severity for object + * errors. * - * class DeprecationWarning extends Data.TaggedError("DeprecationWarning")<{}> { - * readonly [ErrorReporter.severity] = "Warn" as const - * } - * ``` + * **Details** * + * When set to a valid `LogLevel.Severity`, the reporter callback receives this + * value as `severity`. Missing or invalid values fall back to `"Info"`. + * + * @category annotations * @since 4.0.0 - * @category Annotations */ export type severity = "~effect/ErrorReporter/severity" /** - * Symbol key used to override the severity level of an error. + * Defines the runtime property key used to override the severity level of an object error. + * + * **When to use** + * + * Use to annotate object errors with the severity reporter callbacks should + * receive. * - * When set, the reporter callback receives this value as `severity` instead - * of the default `"Error"`. Accepted values are the `LogLevel.Severity` - * literals: `"Trace"`, `"Debug"`, `"Info"`, `"Warn"`, `"Error"`, `"Fatal"`. + * **Details** + * + * Set `error[ErrorReporter.severity]` to a valid `LogLevel.Severity` value. + * Missing or invalid values fall back to `"Info"`. + * + * **Example** (Setting error severity annotations) * - * @example * ```ts * import { Data, ErrorReporter } from "effect" * @@ -375,17 +422,29 @@ export type severity = "~effect/ErrorReporter/severity" * } * ``` * + * @see {@link getSeverity} for reading the severity stored under this key + * @see {@link Reportable} for the annotation contract recognized on object + * errors + * + * @category annotations * @since 4.0.0 - * @category Annotations */ export const severity: severity = "~effect/ErrorReporter/severity" /** * Reads the `ErrorReporter.severity` annotation from an error object, - * falling back to `"Error"` when unset or invalid. + * falling back to `"Info"` when the annotation is unset or invalid. + * + * **When to use** + * + * Use to inspect the severity that reporter callbacks will receive for an + * object error. + * + * @see {@link severity} for the annotation key used to override severity + * @see {@link Reportable} for the annotation properties recognized on object errors * + * @category annotations * @since 4.0.0 - * @category Annotations */ export const getSeverity = (error: object): Severity => { if (severity in error && LogLevel.values.includes(error[severity] as Severity)) { @@ -395,38 +454,40 @@ export const getSeverity = (error: object): Severity => { } /** - * Symbol key used to attach extra key/value metadata to an error report. + * Defines the string property key used to attach extra key/value metadata to an object + * error report. * - * Reporters receive these attributes alongside the error, making it easy to - * include contextual information such as user IDs, request IDs, or any - * domain-specific data useful for debugging. + * **When to use** * - * @example - * ```ts - * import { Data, ErrorReporter } from "effect" + * Use to type the property key that attaches metadata to object error reports. * - * class PaymentError extends Data.TaggedError("PaymentError")<{ - * readonly orderId: string - * }> { - * readonly [ErrorReporter.attributes] = { - * orderId: this.orderId - * } - * } - * ``` + * **Details** + * + * Reporters receive these attributes alongside the error, making it easy to + * include contextual information such as user IDs, request IDs, or other + * domain-specific debugging data. * + * @category annotations * @since 4.0.0 - * @category Annotations */ export type attributes = "~effect/ErrorReporter/attributes" /** - * Symbol key used to attach extra key/value metadata to an error report. + * Defines the runtime property key used to attach extra key/value metadata to an object + * error report. * - * Reporters receive these attributes alongside the error, making it easy to - * include contextual information such as user IDs, request IDs, or any - * domain-specific data useful for debugging. + * **When to use** + * + * Use to attach domain metadata to object errors so reporter callbacks receive + * it with the reported failure. + * + * **Details** + * + * Set `error[ErrorReporter.attributes]` to a record of metadata that should be + * forwarded to reporters alongside the error. + * + * **Example** (Setting error attributes) * - * @example * ```ts * import { Data, ErrorReporter } from "effect" * @@ -439,8 +500,14 @@ export type attributes = "~effect/ErrorReporter/attributes" * } * ``` * + * @see {@link ignore} for suppressing reports for expected object errors + * @see {@link severity} for overriding reporter severity + * @see {@link getAttributes} for reading the metadata stored under this key + * @see {@link Reportable} for the annotation contract recognized on object + * errors + * + * @category annotations * @since 4.0.0 - * @category Annotations */ export const attributes: attributes = "~effect/ErrorReporter/attributes" @@ -448,8 +515,26 @@ export const attributes: attributes = "~effect/ErrorReporter/attributes" * Reads the `ErrorReporter.attributes` annotation from an error object, * returning an empty record when unset. * + * **When to use** + * + * Use to inspect the attributes that reporter callbacks will receive for an + * object error. + * + * **Details** + * + * Returns the value stored under `ErrorReporter.attributes`, or the module's + * shared empty record when the annotation is absent. + * + * **Gotchas** + * + * The annotation value is returned as-is; this helper does not validate or + * clone it. + * + * @see {@link attributes} for the annotation key used to attach metadata + * @see {@link Reportable} for the annotation properties recognized on object errors + * + * @category annotations * @since 4.0.0 - * @category Annotations */ export const getAttributes = (error: object): ReadonlyRecord => { return attributes in error ? error[attributes] as any : emptyAttributes diff --git a/.opencode/node_modules/effect/src/ExecutionPlan.ts b/.opencode/node_modules/effect/src/ExecutionPlan.ts index 49fd6834df9a4ef4ca01e38bf46aa2c8ad9e3f2a..fd00503b59cf8ba186f158252c5cf41a2a9b011c 100644 --- a/.opencode/node_modules/effect/src/ExecutionPlan.ts +++ b/.opencode/node_modules/effect/src/ExecutionPlan.ts @@ -1,4 +1,12 @@ /** + * Describes ordered fallback steps for running effects or streams. + * + * An `ExecutionPlan` contains one or more steps. Each step provides a `Context` + * or `Layer`, and may also define attempt limits, retry schedules, or + * predicates that decide whether to keep trying. The runtime tries steps in + * order until the workflow succeeds or the plan is exhausted. This module also + * supports merging plans and reading metadata for the active step and attempt. + * * @since 3.16.0 */ import type { NonEmptyReadonlyArray } from "./Array.ts" @@ -13,29 +21,54 @@ import * as Predicate from "./Predicate.ts" import type * as Schedule from "./Schedule.ts" /** + * String literal type used as the runtime type identifier for `ExecutionPlan` + * values. + * + * @category type IDs * @since 3.16.0 - * @category Type IDs */ export type TypeId = "~effect/ExecutionPlan" /** + * Runtime type identifier attached to `ExecutionPlan` values and used by + * `isExecutionPlan`. + * + * @category type IDs * @since 3.16.0 - * @category Type IDs */ export const TypeId: TypeId = "~effect/ExecutionPlan" /** + * Returns `true` if a value is an `ExecutionPlan` by checking for the + * `ExecutionPlan.TypeId` marker. + * + * **When to use** + * + * Use when accepting an unknown value and you need to narrow it to an + * `ExecutionPlan` before reading plan fields or passing it to plan-consuming + * APIs. + * + * **Gotchas** + * + * This is a structural marker check; it does not validate the marker value or + * the shape of the plan steps. + * + * @see {@link make} for constructing execution plans that satisfy this guard + * @see {@link TypeId} for the runtime marker checked by this guard + * + * @category guards * @since 3.16.0 - * @category Guards */ export const isExecutionPlan = (u: unknown): u is ExecutionPlan => Predicate.hasProperty(u, TypeId) /** * 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. * + * **Example** (Defining fallback execution steps) + * * ```ts - * import type { Layer } from "effect" * import { Effect, ExecutionPlan, Schedule } from "effect" + * import type { Layer } from "effect" * import type { LanguageModel } from "effect/unstable/ai" * * declare const layerBad: Layer.Layer @@ -70,8 +103,8 @@ export const isExecutionPlan = (u: unknown): u is ExecutionPlan => Predicat * const withPlan: Effect.Effect = Effect.withExecutionPlan(effect, ThePlan) * ``` * + * @category models * @since 3.16.0 - * @category Models */ export interface ExecutionPlan< Config extends { @@ -94,10 +127,9 @@ export interface ExecutionPlan< }> /** - * Returns an equivalent `ExecutionPlan` with the requirements satisfied, - * using the current context. + * Returns an equivalent `ExecutionPlan` with the requirements satisfied, using the current context. */ - readonly withRequirements: Effect.Effect< + readonly captureRequirements: Effect.Effect< ExecutionPlan<{ provides: Config["provides"] input: Config["input"] @@ -110,8 +142,17 @@ export interface ExecutionPlan< } /** - * @since 3.16.0 - * @category Models + * Base type-level configuration carried by an `ExecutionPlan`. + * + * **Details** + * + * `provides` tracks services supplied by plan steps, `input` tracks the error + * input consumed by schedules and `while` predicates, `error` tracks failures + * from plan layers or predicates, and `requirements` tracks services needed to + * build or run the plan. + * + * @category models + * @since 4.0.0 */ export type ConfigBase = { provides: any @@ -123,9 +164,11 @@ export type ConfigBase = { /** * 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. * + * **Example** (Creating an execution plan) + * * ```ts - * import type { Layer } from "effect" * import { Effect, ExecutionPlan, Schedule } from "effect" + * import type { Layer } from "effect" * import type { LanguageModel } from "effect/unstable/ai" * * declare const layerBad: Layer.Layer @@ -160,8 +203,8 @@ export type ConfigBase = { * const withPlan: Effect.Effect = Effect.withExecutionPlan(effect, ThePlan) * ``` * + * @category constructors * @since 3.16.0 - * @category Constructors */ export const make = >( ...steps: Steps & { [K in keyof Steps]: make.Step } @@ -196,10 +239,21 @@ export const make = >( }) as any) /** + * Namespace containing type helpers used by `ExecutionPlan.make`. + * * @since 3.16.0 */ export declare namespace make { /** + * Input shape for a single execution-plan step. + * + * **Details** + * + * Each step provides a `Context` or `Layer` and may limit attempts, add a + * `while` predicate for retry decisions, or attach a `Schedule` for retry + * timing. + * + * @category models * @since 3.16.0 */ export type Step = { @@ -210,6 +264,10 @@ export declare namespace make { } /** + * Computes the intersection of services provided by a list of execution-plan + * steps. + * + * @category utility types * @since 3.16.1 */ export type StepProvides, Out = unknown> = Steps extends @@ -224,6 +282,9 @@ export declare namespace make { Out /** + * Computes the intersection of services provided by a list of execution plans. + * + * @category utility types * @since 3.16.1 */ export type PlanProvides, Out = unknown> = Plans extends @@ -232,6 +293,10 @@ export declare namespace make { Out /** + * Computes the input type consumed by the `while` predicates and schedules in + * a list of execution-plan steps. + * + * @category utility types * @since 3.16.0 */ export type StepInput, Out = unknown> = Steps extends @@ -246,6 +311,9 @@ export declare namespace make { Out /** + * Computes the combined input type consumed by a list of execution plans. + * + * @category utility types * @since 3.16.0 */ export type PlanInput, Out = unknown> = Plans extends @@ -256,7 +324,7 @@ export declare namespace make { const Proto: Omit, "steps"> = { [TypeId]: TypeId, - get withRequirements() { + get captureRequirements() { const self = this as any as ExecutionPlan return effect.contextWith((context: Context.Context) => effect.succeed(makeProto(self.steps.map((step) => ({ @@ -286,8 +354,22 @@ const makeProto = ( } /** + * Combines multiple execution plans by concatenating their steps in order. + * + * **When to use** + * + * Use to combine separately defined fallback plans into one ordered plan before + * applying it to an effect or stream. + * + * **Details** + * + * The resulting plan tries every step from the first plan, then every step from + * the next plan, and so on. + * + * @see {@link make} for building a plan from individual steps instead of combining existing plans + * + * @category combining * @since 3.16.0 - * @category Combining */ export const merge = >>( ...plans: Plans @@ -299,8 +381,15 @@ export const merge = => makeProto(plans.flatMap((plan) => plan.steps) as any) /** + * Metadata describing the currently running execution-plan attempt. + * + * **Details** + * + * `attempt` is the current 1-based attempt number, and `stepIndex` is the + * 0-based index of the plan step currently being evaluated. + * + * @category metadata * @since 4.0.0 - * @category Metadata */ export interface Metadata { readonly attempt: number @@ -308,8 +397,16 @@ export interface Metadata { } /** + * Context reference containing metadata for the currently running + * execution-plan attempt. + * + * **When to use** + * + * Use to read the active plan step and attempt while code is running under an + * execution plan. + * + * @category metadata * @since 4.0.0 - * @category Metadata */ export const CurrentMetadata = Context.Reference("effect/ExecutionPlan/CurrentMetadata", { defaultValue: constant({ diff --git a/.opencode/node_modules/effect/src/Exit.ts b/.opencode/node_modules/effect/src/Exit.ts index 6a8185d9b7f8873ae1372ee36346c162d8f66a6b..1996c7a6d12e90d115f16cd2eaf61feb3b237ee2 100644 --- a/.opencode/node_modules/effect/src/Exit.ts +++ b/.opencode/node_modules/effect/src/Exit.ts @@ -1,58 +1,11 @@ /** - * Represents the outcome of an Effect computation as a plain, synchronously - * inspectable value. + * Represents the result of an Effect computation as a plain value. * - * ## Mental model - * - * - `Exit` is a union of two cases: `Success` and `Failure` - * - A `Success` wraps a value of type `A` - * - A `Failure` wraps a `Cause`, which may contain typed errors, defects, or interruptions - * - `Exit` is also an `Effect`, so you can yield it directly inside `Effect.gen` - * - Constructors mirror the failure modes: {@link fail} for typed errors, {@link die} for defects, {@link interrupt} for fiber interruptions - * - Use `Exit` when you need to inspect an Effect result without running further effects - * - * ## Common tasks - * - * - Create a success: {@link succeed} - * - Create a typed failure: {@link fail} - * - Create a failure from a Cause: {@link failCause} - * - Create a defect: {@link die} - * - Create an interruption: {@link interrupt} - * - Check the outcome: {@link isSuccess}, {@link isFailure}, {@link match} - * - Extract values optionally: {@link getSuccess}, {@link getCause}, {@link findErrorOption} - * - Transform the result: {@link map}, {@link mapError}, {@link mapBoth} - * - Combine multiple exits: {@link asVoidAll} - * - Inspect failure categories: {@link hasFails}, {@link hasDies}, {@link hasInterrupts} - * - * ## Gotchas - * - * - A `Failure` wraps a `Cause`, not a bare `E`. Use Cause utilities to drill into it. - * - {@link mapError} and {@link mapBoth} only transform typed errors (Fail reasons in the Cause). If the Cause contains only defects or interruptions, the original failure passes through unchanged. - * - Filter-based APIs ({@link filterSuccess}, {@link filterValue}, etc.) return `Filter.fail` markers for pipeline composition. They are not `Option` values or Effect failures. - * - {@link findError} and {@link findDefect} return only the first matching reason from the Cause. - * - * ## Quickstart - * - * **Example** (Creating and inspecting exits) - * - * ```ts - * import { Exit } from "effect" - * - * const success = Exit.succeed(42) - * const failure = Exit.fail("not found") - * - * const message = Exit.match(success, { - * onSuccess: (value) => `Got: ${value}`, - * onFailure: () => "Failed" - * }) - * console.log(message) // "Got: 42" - * ``` - * - * ## See also - * - * - {@link Exit} the core union type - * - {@link succeed} and {@link fail} the most common constructors - * - {@link match} for pattern matching on an Exit + * An `Exit` is either a success with an `A` or a failure with a + * `Cause`. The failure cause preserves typed errors, defects, and + * interruptions after a workflow has finished. Use this module when completed + * Effect results need to be inspected, transformed, filtered, or matched + * synchronously as data. * * @since 2.0.0 */ @@ -69,12 +22,16 @@ const TypeId = core.ExitTypeId /** * Represents the result of an Effect computation. * - * - Use when you need to synchronously inspect whether a computation succeeded or failed - * - Use as an alternative to try/catch for Effect-based code + * **When to use** + * + * Use when you need to synchronously inspect whether an Effect computation + * succeeded or failed. * - * An `Exit` is either: - * - `Success` containing a value of type `A` - * - `Failure` containing a `Cause` describing why the computation failed + * **Details** + * + * An `Exit` is either `Success` containing a value of type `A`, or + * `Failure` containing a `Cause` describing why the computation + * failed. * * Since `Exit` is also an `Effect`, you can yield it inside `Effect.gen`. * @@ -96,23 +53,35 @@ const TypeId = core.ExitTypeId * @see {@link Failure} for the failure case * @see {@link match} for pattern matching * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export type Exit = Success | Failure /** + * Namespace containing helper types shared by `Exit` values. + * + * **When to use** + * + * Use to reference helper types that describe the shared structure of `Exit` + * values. + * * @since 2.0.0 - * @category models */ export declare namespace Exit { /** * Base interface shared by both Success and Failure. * + * **When to use** + * + * Use to describe the common protocol implemented by every `Exit` value. + * + * **Details** + * * Every Exit is also an Effect, so you can yield it in `Effect.gen`. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface Proto extends Effect.Effect { readonly [TypeId]: typeof TypeId @@ -122,8 +91,11 @@ export declare namespace Exit { /** * A successful Exit containing a value. * - * - Use {@link isSuccess} to narrow an `Exit` to `Success` - * - Access the value via the `value` property after narrowing + * **When to use** + * + * Use when working with the successful branch of an `Exit` after narrowing + * with {@link isSuccess}. Access the value via the `value` property after + * narrowing. * * **Example** (Accessing the success value) * @@ -141,8 +113,8 @@ export declare namespace Exit { * @see {@link isSuccess} to narrow an Exit to Success * @see {@link Failure} for the failure counterpart * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface Success extends Exit.Proto { readonly _tag: "Success" @@ -152,9 +124,15 @@ export interface Success extends Exit.Proto { /** * A failed Exit containing a Cause. * - * - Use {@link isFailure} to narrow an `Exit` to `Failure` - * - Access the cause via the `cause` property after narrowing - * - The `Cause` may contain typed errors, defects, or interruptions + * **When to use** + * + * Use when working with the failed branch of an `Exit` after narrowing with + * {@link isFailure}. Access the cause via the `cause` property after + * narrowing. + * + * **Details** + * + * The `Cause` may contain typed errors, defects, or interruptions. * * **Example** (Accessing the failure cause) * @@ -172,8 +150,8 @@ export interface Success extends Exit.Proto { * @see {@link isFailure} to narrow an Exit to Failure * @see {@link Success} for the success counterpart * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface Failure extends Exit.Proto { readonly _tag: "Failure" @@ -181,10 +159,14 @@ export interface Failure extends Exit.Proto { } /** - * Tests whether an unknown value is an Exit. + * Checks whether an unknown value is an Exit. + * + * **When to use** + * + * Use to validate unknown values at system boundaries and narrow them to + * `Exit`. * - * - Use to validate unknown values at system boundaries - * - Works as a type guard, narrowing to `Exit` + * **Details** * * Does not inspect the contents of the Exit. Returns `true` for both Success * and Failure exits. @@ -210,8 +192,11 @@ export const isExit: (u: unknown) => u is Exit = core.isExit /** * Creates a successful Exit containing the given value. * - * - Use to wrap a known success value into an Exit - * - Use when constructing test data or returning explicit results + * **When to use** + * + * Use when you need an Exit that contains a known success value. + * + * **Details** * * Returns a `Success` with the provided value. Does not perform any * computation. @@ -226,7 +211,7 @@ export const isExit: (u: unknown) => u is Exit = core.isExit * ``` * * @see {@link fail} to create a failed Exit - * @see {@link void} for a pre-allocated success with no value + * @see {@link void_ void} for a pre-allocated success with no value * * @category constructors * @since 2.0.0 @@ -236,8 +221,13 @@ export const succeed: (a: A) => Exit = core.exitSucceed /** * Creates a failed Exit from a Cause. * - * - Use when you already have a `Cause` and want to wrap it in an Exit - * - Use for advanced error handling where you need full control over the Cause structure + * **When to use** + * + * Use when you already have a `Cause` and want to wrap it in an Exit + * for advanced error handling where you need full control over the Cause + * structure. + * + * **Details** * * Returns a `Failure`. If you only have an error value, use * {@link fail} instead. @@ -263,8 +253,13 @@ export const failCause: (cause: Cause.Cause) => Exit = core.exit /** * Creates a failed Exit from a typed error value. * - * - Use for expected, recoverable failures - * - The error is wrapped in a `Cause.Fail` internally + * **When to use** + * + * Use when you need to represent an expected typed failure as an `Exit`. + * + * **Details** + * + * The error is wrapped in a `Cause.Fail` internally. * * Returns a `Failure`. * @@ -289,8 +284,14 @@ export const fail: (e: E) => Exit = core.exitFail /** * Creates a failed Exit from a defect (unexpected error). * - * - Use for unexpected, unrecoverable errors that should not appear in the typed error channel - * - The defect is wrapped in a `Cause.Die` internally + * **When to use** + * + * Use when you need unexpected, unrecoverable errors that should not appear in + * the typed error channel. + * + * **Details** + * + * The defect is wrapped in a `Cause.Die` internally. * * Returns a `Failure` with `E = never`, since defects do not appear in * the typed error channel. @@ -315,10 +316,14 @@ export const die: (defect: unknown) => Exit = core.exitDie /** * Creates a failed Exit representing fiber interruption. * - * - Use to signal that a fiber was interrupted - * - Optionally pass a fiber ID to identify which fiber was interrupted + * **When to use** + * + * Use to signal that a fiber was interrupted. * - * Returns a `Failure` with an `Interrupt` cause. + * **Details** + * + * Optionally pass a fiber ID to identify which fiber was interrupted. Returns + * a `Failure` with an `Interrupt` cause. * * **Example** (Creating an interruption Exit) * @@ -340,12 +345,16 @@ export const interrupt: (fiberId?: number | undefined) => Exit = effect.e const void_: Exit = effect.exitVoid export { /** - * A pre-allocated successful Exit with a `void` value. + * Provides a pre-allocated successful Exit with a `void` value. + * + * **When to use** + * + * Use when you need a shared successful `Exit` with no meaningful value. * - * - Use when you need a success Exit but do not care about the value - * - Avoids allocating a new Exit for a common case + * **Details** * - * Equivalent to `Exit.succeed(undefined)` but shared as a single instance. + * Equivalent to `Exit.succeed(undefined)` but shared as a single instance, + * avoiding allocation for a common case. * * **Example** (Using the void Exit) * @@ -366,10 +375,12 @@ export { } /** - * Tests whether an Exit is a Success. + * Checks whether an Exit is a Success. * - * - Use as a type guard to narrow `Exit` to `Success` - * - After narrowing, the `value` property becomes accessible + * **When to use** + * + * Use as a type guard to narrow `Exit` to `Success` and access the + * `value` property. * * **Example** (Narrowing to Success) * @@ -392,10 +403,12 @@ export { export const isSuccess: (self: Exit) => self is Success = effect.exitIsSuccess /** - * Tests whether an Exit is a Failure. + * Checks whether an Exit is a Failure. + * + * **When to use** * - * - Use as a type guard to narrow `Exit` to `Failure` - * - After narrowing, the `cause` property becomes accessible + * Use as a type guard to narrow `Exit` to `Failure` and access the + * `cause` property. * * **Example** (Narrowing to Failure) * @@ -418,13 +431,16 @@ export const isSuccess: (self: Exit) => self is Success = effe export const isFailure: (self: Exit) => self is Failure = effect.exitIsFailure /** - * Tests whether a failed Exit contains typed errors (Fail reasons). + * Checks whether a failed Exit contains typed errors (Fail reasons). * - * - Use to distinguish typed failures from defects or interruptions - * - Returns `false` for successful exits + * **When to use** * - * Only checks for `Fail` reasons in the Cause. A Cause with only `Die` or - * `Interrupt` reasons returns `false`. + * Use to distinguish typed failures from defects or interruptions. + * + * **Details** + * + * Returns `false` for successful exits. Only checks for `Fail` reasons in the + * Cause. A Cause with only `Die` or `Interrupt` reasons returns `false`. * * **Example** (Checking for typed errors) * @@ -445,13 +461,16 @@ export const isFailure: (self: Exit) => self is Failure = effe export const hasFails: (self: Exit) => self is Failure = effect.exitHasFails /** - * Tests whether a failed Exit contains defects (Die reasons). + * Checks whether a failed Exit contains defects (Die reasons). + * + * **When to use** * - * - Use to check for unexpected errors - * - Returns `false` for successful exits + * Use to check whether an `Exit` failure cause contains unexpected errors. * - * Only checks for `Die` reasons in the Cause. A Cause with only `Fail` or - * `Interrupt` reasons returns `false`. + * **Details** + * + * Returns `false` for successful exits. Only checks for `Die` reasons in the + * Cause. A Cause with only `Fail` or `Interrupt` reasons returns `false`. * * **Example** (Checking for defects) * @@ -472,13 +491,16 @@ export const hasFails: (self: Exit) => self is Failure = effec export const hasDies: (self: Exit) => self is Failure = effect.exitHasDies /** - * Tests whether a failed Exit contains interruptions (Interrupt reasons). + * Checks whether a failed Exit contains interruptions (Interrupt reasons). + * + * **When to use** * - * - Use to check if a fiber was interrupted - * - Returns `false` for successful exits + * Use to check whether an `Exit` contains fiber interruption. * - * Only checks for `Interrupt` reasons in the Cause. A Cause with only `Fail` - * or `Die` reasons returns `false`. + * **Details** + * + * Returns `false` for successful exits. Only checks for `Interrupt` reasons in + * the Cause. A Cause with only `Fail` or `Die` reasons returns `false`. * * **Example** (Checking for interruptions) * @@ -499,26 +521,38 @@ export const hasDies: (self: Exit) => self is Failure = effect export const hasInterrupts: (self: Exit) => self is Failure = effect.exitHasInterrupts /** - * Extracts the Success variant from an Exit for use in filter pipelines. + * Extracts the Success variant from an Exit as a Result. + * + * **When to use** + * + * Use when composing Exit checks with `Filter` or other `Result`-based + * filtering APIs and you want the full Success wrapper. + * + * **Details** + * + * Returns `Result.succeed(success)` when the Exit is a Success, or + * `Result.fail(failure)` with the original Failure otherwise. * - * - Use with Filter-based composition - * - Returns the `Success` if the Exit succeeded, or a `Filter.fail` wrapping the Failure otherwise + * **Gotchas** + * + * This is not an `Option` accessor or an Effect failure. A failed extraction is + * represented as data in the `Result` failure channel. * * **Example** (Filtering for success) * * ```ts - * import { Exit, Filter } from "effect" + * import { Exit, Result } from "effect" * * const exit = Exit.succeed(42) * const result = Exit.filterSuccess(exit) - * // If exit is a success, result is the Success object - * // If exit is a failure, result is a Filter.fail marker + * + * console.log(Result.isSuccess(result)) // true * ``` * * @see {@link filterFailure} for the inverse * @see {@link filterValue} to extract the raw value instead of the Success object * - * @category filters + * @category filtering * @since 4.0.0 */ export const filterSuccess: ( @@ -526,87 +560,132 @@ export const filterSuccess: ( ) => Result.Result, Failure> = effect.exitFilterSuccess /** - * Extracts the success value from an Exit for use in filter pipelines. + * Extracts the success value from an Exit as a Result. + * + * **When to use** + * + * Use when composing Exit checks with `Filter` or other `Result`-based + * filtering APIs and you want the raw success value rather than the Success + * wrapper. + * + * **Details** * - * - Use with Filter-based composition when you want the raw value, not the Success wrapper - * - Returns the value `A` if the Exit succeeded, or a `Filter.fail` wrapping the Failure otherwise + * Returns `Result.succeed(value)` when the Exit is a Success, or + * `Result.fail(failure)` with the original Failure otherwise. + * + * **Gotchas** + * + * This is not an `Option` accessor or an Effect failure. A failed extraction is + * represented as data in the `Result` failure channel. * * **Example** (Filtering for the value) * * ```ts - * import { Exit, Filter } from "effect" + * import { Exit, Result } from "effect" * * const exit = Exit.succeed(42) * const result = Exit.filterValue(exit) - * // If exit is a success, result is 42 - * // If exit is a failure, result is a Filter.fail marker + * + * console.log(Result.isSuccess(result) && result.success) // 42 * ``` * * @see {@link filterSuccess} to get the full Success object * @see {@link getSuccess} to get the value as an Option instead * - * @category filters + * @category filtering * @since 4.0.0 */ export const filterValue: (self: Exit) => Result.Result> = effect.exitFilterValue /** - * Extracts the Failure variant from an Exit for use in filter pipelines. + * Extracts the Failure variant from an Exit as a Result. + * + * **When to use** * - * - Use with Filter-based composition - * - Returns the `Failure` if the Exit failed, or a `Filter.fail` wrapping the Success otherwise + * Use when composing Exit checks with `Filter` or other `Result`-based + * filtering APIs and you want the full Failure wrapper. + * + * **Details** + * + * Returns `Result.succeed(failure)` when the Exit is a Failure, or + * `Result.fail(success)` with the original Success otherwise. + * + * **Gotchas** + * + * This is not an `Option` accessor or an Effect failure. A failed extraction is + * represented as data in the `Result` failure channel. * * **Example** (Filtering for failure) * * ```ts - * import { Exit, Filter } from "effect" + * import { Exit, Result } from "effect" * * const exit = Exit.fail("err") * const result = Exit.filterFailure(exit) - * // If exit is a failure, result is the Failure object - * // If exit is a success, result is a Filter.fail marker + * + * console.log(Result.isSuccess(result)) // true * ``` * * @see {@link filterSuccess} for the inverse * @see {@link filterCause} to extract the Cause directly * - * @category filters + * @category filtering * @since 4.0.0 */ export const filterFailure: (self: Exit) => Result.Result, Success> = effect.exitFilterFailure /** - * Extracts the Cause from a failed Exit for use in filter pipelines. + * Extracts the Cause from a failed Exit as a Result. + * + * **When to use** + * + * Use when composing Exit checks with `Filter` or other `Result`-based + * filtering APIs and you want the raw Cause rather than the Failure wrapper. + * + * **Details** + * + * Returns `Result.succeed(cause)` when the Exit is a Failure, or + * `Result.fail(success)` with the original Success otherwise. + * + * **Gotchas** * - * - Use with Filter-based composition when you want the raw Cause, not the Failure wrapper - * - Returns the `Cause` if the Exit failed, or a `Filter.fail` wrapping the Success otherwise + * This is not an `Option` accessor or an Effect failure. A failed extraction is + * represented as data in the `Result` failure channel. * * **Example** (Filtering for the cause) * * ```ts - * import { Exit, Filter } from "effect" + * import { Exit, Result } from "effect" * * const exit = Exit.fail("err") * const result = Exit.filterCause(exit) - * // If exit is a failure, result is the Cause - * // If exit is a success, result is a Filter.fail marker + * + * console.log(Result.isSuccess(result)) // true * ``` * * @see {@link filterFailure} to get the full Failure object * @see {@link getCause} to get the Cause as an Option instead * - * @category filters + * @category filtering * @since 4.0.0 */ export const filterCause: (self: Exit) => Result.Result, Success> = effect.exitFilterCause /** - * Extracts the first typed error value from a failed Exit for use in filter - * pipelines. + * Extracts the first typed error value from a failed Exit as a Result. + * + * **When to use** + * + * Use when you need the first typed error from an `Exit` as a `Result` for + * `Filter` or other `Result`-based filtering APIs. + * + * **Details** + * + * Returns `Result.succeed(error)` when the Cause contains a Fail reason, or + * `Result.fail(exit)` with the original Exit otherwise. * - * - Use when you need just the first `E` from the Cause - * - Returns the error `E` if one exists, or `Filter.fail` wrapping the original Exit if the Exit has no typed errors + * **Gotchas** * * Only finds the first Fail reason. If the Cause has multiple errors, the rest * are ignored. @@ -614,30 +693,39 @@ export const filterCause: (self: Exit) => Result.Result(input: Exit) => Result.Result> = effect.exitFindError /** - * Extracts the first defect from a failed Exit for use in filter pipelines. + * Extracts the first defect from a failed Exit as a Result. * - * - Use when you need to inspect unexpected errors - * - Returns the defect value if one exists, or `Filter.fail` wrapping the original Exit if the Exit has no defects + * **When to use** + * + * Use when you need the first defect from an `Exit` as a `Result` for + * `Filter` or other `Result`-based filtering APIs. + * + * **Details** + * + * Returns `Result.succeed(defect)` when the Cause contains a Die reason, or + * `Result.fail(exit)` with the original Exit otherwise. + * + * **Gotchas** * * Only finds the first Die reason. If the Cause has multiple defects, the rest * are ignored. @@ -645,21 +733,21 @@ export const findError: (input: Exit) => Result.Result * **Example** (Finding the first defect) * * ```ts - * import { Exit, Filter } from "effect" + * import { Exit, Result } from "effect" * * const exit = Exit.die("boom") * const result = Exit.findDefect(exit) - * // result is "boom" + * console.log(Result.isSuccess(result) && result.success) // "boom" * * const typed = Exit.fail("err") * const noDefect = Exit.findDefect(typed) - * // noDefect is a Filter.fail marker + * console.log(Result.isFailure(noDefect)) // true * ``` * * @see {@link findError} to find typed errors instead * @see {@link hasDies} to check for defects without extracting them * - * @category filters + * @category filtering * @since 4.0.0 */ export const findDefect: (input: Exit) => Result.Result> = effect.exitFindDefect @@ -667,11 +755,15 @@ export const findDefect: (input: Exit) => Result.Result(self: Exit) => Exit = effect.exitAsVo /** * Combines multiple Exit values into a single `Exit`. * - * - Use to validate that all exits in a collection succeeded - * - If all exits are successful, returns a void success - * - If any exit is a failure, returns a single failure with all error causes combined + * **When to use** + * + * Use to validate that all exits in a collection succeeded + * + * **Details** + * + * If all exits are successful, this returns a void success. If any exit is a + * failure, this returns a single failure with all error causes combined. * * Iterates over the entire collection. Collects all failure causes, not just * the first. @@ -1099,8 +1267,14 @@ export const asVoidAll: >>( /** * Returns the success value of an Exit as an Option. * - * - Use when you want to optionally extract the value without pattern matching - * - Returns `Option.some(value)` for a Success, `Option.none()` for a Failure + * **When to use** + * + * Use when you need the success value from an `Exit` as an `Option` instead of + * pattern matching. + * + * **Details** + * + * Returns `Option.some(value)` for a Success and `Option.none()` for a Failure. * * **Example** (Getting the success value) * @@ -1114,7 +1288,7 @@ export const asVoidAll: >>( * @see {@link getCause} to extract the Cause of a failure * @see {@link filterValue} for filter-pipeline usage * - * @category Accessors + * @category accessors * @since 4.0.0 */ export const getSuccess: (self: Exit) => Option = effect.exitGetSuccess @@ -1122,8 +1296,14 @@ export const getSuccess: (self: Exit) => Option = effect.exitGetS /** * Returns the Cause of a failed Exit as an Option. * - * - Use when you want to optionally inspect the failure cause - * - Returns `Option.some(cause)` for a Failure, `Option.none()` for a Success + * **When to use** + * + * Use when you need the failure `Cause` from an `Exit` as an `Option` instead + * of pattern matching. + * + * **Details** + * + * Returns `Option.some(cause)` for a Failure and `Option.none()` for a Success. * * **Example** (Getting the failure cause) * @@ -1137,7 +1317,7 @@ export const getSuccess: (self: Exit) => Option = effect.exitGetS * @see {@link getSuccess} to extract the success value * @see {@link filterCause} for filter-pipeline usage * - * @category Accessors + * @category accessors * @since 4.0.0 */ export const getCause: (self: Exit) => Option> = effect.exitGetCause @@ -1145,9 +1325,20 @@ export const getCause: (self: Exit) => Option> = effe /** * Returns the first typed error from a failed Exit as an Option. * - * - Use when you want to optionally extract a typed error without dealing with the full Cause - * - Returns `Option.some(error)` if the Cause contains a Fail reason, `Option.none()` otherwise - * - Returns `Option.none()` for successes, defect-only failures, and interrupt-only failures + * **When to use** + * + * Use when you need the first typed error from an `Exit` as an `Option`, + * ignoring successes and non-typed failures. + * + * **Details** + * + * Returns `Option.some(error)` if the Cause contains a Fail reason. Successes, + * defect-only failures, and interrupt-only failures return `Option.none()`. + * + * **Gotchas** + * + * Only finds the first Fail reason. If the Cause has multiple typed errors, + * the rest are ignored. * * **Example** (Getting the first error) * @@ -1162,7 +1353,7 @@ export const getCause: (self: Exit) => Option> = effe * @see {@link findError} for filter-pipeline usage * @see {@link getCause} to get the full Cause as an Option * - * @category Accessors + * @category accessors * @since 4.0.0 */ export const findErrorOption: (self: Exit) => Option = effect.exitFindErrorOption diff --git a/.opencode/node_modules/effect/src/Fiber.ts b/.opencode/node_modules/effect/src/Fiber.ts index 4ac717f6716a2cb530f796d3c99ee3d29f760fac..3d4a8e3dccd1dccfefe2e4211360506744f3742d 100644 --- a/.opencode/node_modules/effect/src/Fiber.ts +++ b/.opencode/node_modules/effect/src/Fiber.ts @@ -1,74 +1,9 @@ /** - * This module provides utilities for working with `Fiber`, the fundamental unit of - * concurrency in Effect. Fibers are lightweight, user-space threads that allow - * multiple Effects to run concurrently with structured concurrency guarantees. - * - * Key characteristics of Fibers: - * - **Lightweight**: Much lighter than OS threads, you can create millions - * - **Structured concurrency**: Parent fibers manage child fiber lifecycles - * - **Cancellation safety**: Proper resource cleanup when interrupted - * - **Cooperative**: Fibers yield control at effect boundaries - * - **Traceable**: Each fiber has an ID for debugging and monitoring - * - * Common patterns: - * - **Fork and join**: Start concurrent work and wait for results - * - **Race conditions**: Run multiple effects, take the first to complete - * - **Supervision**: Monitor and restart failed fibers - * - **Resource management**: Ensure proper cleanup on interruption - * - * @example - * ```ts - * import { Console, Effect, Fiber } from "effect" - * - * // Basic fiber operations - * const basicExample = Effect.gen(function*() { - * // Fork an effect to run concurrently - * const fiber = yield* Effect.forkChild( - * Effect.gen(function*() { - * yield* Effect.sleep("2 seconds") - * yield* Console.log("Background task completed") - * return "background result" - * }) - * ) - * - * // Do other work while the fiber runs - * yield* Console.log("Doing other work...") - * yield* Effect.sleep("1 second") - * - * // Wait for the fiber to complete - * const result = yield* Fiber.join(fiber) - * yield* Console.log(`Fiber result: ${result}`) - * }) - * - * // Joining multiple fibers - * const joinExample = Effect.gen(function*() { - * const task1 = Effect.delay(Effect.succeed("task1"), "1 second") - * const task2 = Effect.delay(Effect.succeed("task2"), "2 seconds") - * - * // Start both effects as fibers - * const fiber1 = yield* Effect.forkChild(task1) - * const fiber2 = yield* Effect.forkChild(task2) - * - * // Wait for both to complete - * const result1 = yield* Fiber.join(fiber1) - * const result2 = yield* Fiber.join(fiber2) - * return [result1, result2] // ["task1", "task2"] - * }) - * - * // Parallel execution with structured concurrency - * const parallelExample = Effect.gen(function*() { - * const tasks = [1, 2, 3, 4, 5].map((n) => - * Effect.gen(function*() { - * yield* Effect.sleep(`${n * 100} millis`) - * return n * n - * }) - * ) - * - * // Run all tasks in parallel, wait for all to complete - * const results = yield* Effect.all(tasks, { concurrency: "unbounded" }) - * return results // [1, 4, 9, 16, 25] - * }) - * ``` + * Operations for handles returned by forking effects. A `Fiber` is a + * lightweight execution of an `Effect` that may still be running or may already + * have completed. This module lets callers await or join fiber results, + * interrupt one or many fibers, check unknown values, access the current fiber, + * and attach manually managed fibers to a `Scope` for cleanup. * * @since 2.0.0 */ @@ -95,7 +30,25 @@ const TypeId = `~effect/Fiber/${version}` * Effects concurrently while maintaining structured concurrency and * cancellation safety. * - * @example + * **When to use** + * + * Use to observe, join, interrupt, or coordinate work that has already been + * forked. + * + * **Details** + * + * A fiber exposes both safe Effect-based operations, such as {@link await_ await}, + * {@link join}, and {@link interrupt}, and low-level runtime fields used by + * the scheduler and runtime internals. + * + * **Gotchas** + * + * Prefer the exported functions in this module over calling `interruptUnsafe` + * or `pollUnsafe` directly. The unsafe methods are immediate runtime hooks and + * do not provide the same Effect-based sequencing guarantees. + * + * **Example** (Awaiting a forked fiber) + * * ```ts * import { Effect, Fiber } from "effect" * @@ -111,8 +64,8 @@ const TypeId = `~effect/Fiber/${version}` * }) * ``` * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface Fiber extends Pipeable { readonly [TypeId]: Fiber.Variance @@ -142,7 +95,17 @@ export interface Fiber extends Pipeable { * The Fiber namespace contains utility types and functions for working with fibers. * It provides type-level utilities for fiber operations and variance encoding. * - * @example + * **When to use** + * + * Use to reference type-level helpers associated with `Fiber`. + * + * **Details** + * + * The namespace currently exposes type-level support used by the `Fiber` + * interface. Runtime operations are exported as module-level functions. + * + * **Example** (Working with fiber types) + * * ```ts * import { Effect, Fiber } from "effect" * @@ -163,14 +126,19 @@ export interface Fiber extends Pipeable { * ``` * * @since 2.0.0 - * @category models */ export declare namespace Fiber { /** * Variance encoding for the Fiber type, specifying covariance in both the * success type `A` and the error type `E`. * - * @example + * **When to use** + * + * Use to carry the success and error type parameters for `Fiber` in Effect's + * type machinery. + * + * **Example** (Upcasting fibers safely) + * * ```ts * import type { Fiber } from "effect" * @@ -179,8 +147,8 @@ export declare namespace Fiber { * const upcast: Fiber.Fiber = fiber * ``` * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface Variance { readonly _A: Covariant @@ -193,7 +161,23 @@ export { /** * Waits for a fiber to complete and returns its exit value. * - * @example + * **When to use** + * + * Use when you need to inspect whether the fiber succeeded, + * failed, died, or was interrupted without propagating the failure. + * + * **Details** + * + * The returned Effect always succeeds with an `Exit` describing the fiber's + * outcome. + * + * **Gotchas** + * + * This does not flatten the fiber result into the current Effect. Use + * {@link join} when you want fiber failures to fail the current Effect. + * + * **Example** (Awaiting a fiber exit) + * * ```ts * import { Effect, Fiber } from "effect" * @@ -204,8 +188,8 @@ export { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ await_ as await } @@ -213,7 +197,22 @@ export { * Waits for all fibers in the provided iterable to complete and returns * an array of their exit values. * - * @example + * **When to use** + * + * Use when you need every fiber outcome as data, including failures and + * interruptions. + * + * **Details** + * + * The returned array is ordered like the input iterable. + * + * **Gotchas** + * + * Failures are captured as `Exit.Failure` values. Use {@link joinAll} when you + * want the first failed fiber to fail the returned Effect. + * + * **Example** (Awaiting multiple fiber exits) + * * ```ts * import { Effect, Fiber } from "effect" * @@ -225,8 +224,8 @@ export { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const awaitAll: >( self: Iterable @@ -243,7 +242,18 @@ export const awaitAll: >( * Joins a fiber, blocking until it completes. If the fiber succeeds, * returns its value. If it fails, the error is propagated. * - * @example + * **When to use** + * + * Use when you need a forked fiber's failure to fail the current Effect because + * that fiber is part of the current workflow. + * + * **Gotchas** + * + * Joining a failed fiber propagates the fiber's Cause. Use {@link await_ await} when + * you need to inspect the `Exit` instead of failing. + * + * **Example** (Joining a fiber) + * * ```ts * import { Effect, Fiber } from "effect" * @@ -254,14 +264,36 @@ export const awaitAll: >( * }) * ``` * - * @since 2.0.0 + * @see {@link await_ await} for inspecting the fiber outcome as an Exit + * * @category combinators + * @since 2.0.0 */ export const join: (self: Fiber) => Effect = effect.fiberJoin /** - * @since 2.0.0 + * Waits for all fibers to succeed and returns their values in input order. + * + * **When to use** + * + * Use when you need every fiber to succeed and want the successful values + * rather than the `Exit` values. + * + * **Details** + * + * If any fiber fails, the returned `Effect` fails with that fiber's cause and + * stops waiting for additional results. This does not interrupt the remaining + * fibers. + * + * **Gotchas** + * + * A failure stops waiting, but it does not interrupt any other fibers. Use + * {@link interruptAll} separately when remaining fibers should be stopped. + * + * @see {@link awaitAll} for collecting every fiber outcome as an Exit + * * @category combinators + * @since 2.0.0 */ export const joinAll: >>( self: A @@ -277,7 +309,22 @@ export const joinAll: >>( * Interrupts a fiber, causing it to stop executing and clean up any * acquired resources. * - * @example + * **When to use** + * + * Use when you need to cancel a forked fiber and wait for its cleanup to + * complete. + * + * **Details** + * + * The returned Effect completes only after the interrupted fiber has completed. + * + * **Gotchas** + * + * Interruption is cooperative. A fiber can continue running while it is inside + * uninterruptible work or finalizers. + * + * **Example** (Interrupting a fiber) + * * ```ts * import { Effect, Fiber } from "effect" * @@ -290,8 +337,11 @@ export const joinAll: >>( * }) * ``` * - * @since 2.0.0 + * @see {@link interruptAs} for specifying the interrupting fiber ID + * @see {@link await_ await} for observing the interrupted fiber's Exit + * * @category interruption + * @since 2.0.0 */ export const interrupt: (self: Fiber) => Effect = effect.fiberInterrupt @@ -299,7 +349,22 @@ export const interrupt: (self: Fiber) => Effect = effect.fiber * Interrupts a fiber with a specific fiber ID as the interruptor. This allows * tracking which fiber initiated the interruption. * - * @example + * **When to use** + * + * Use when runtime diagnostics or tracing should attribute the interruption to + * a specific fiber ID. + * + * **Details** + * + * The returned Effect completes only after the interrupted fiber has completed. + * + * **Gotchas** + * + * The supplied ID affects the recorded interruptor. It does not make + * interruption synchronous or force uninterruptible regions to stop early. + * + * **Example** (Interrupting a fiber as another fiber) + * * ```ts * import { Effect, Fiber } from "effect" * @@ -314,15 +379,32 @@ export const interrupt: (self: Fiber) => Effect = effect.fiber * }) * ``` * - * @since 2.0.0 + * @see {@link interrupt} for using the current fiber as the interruptor + * * @category interruption + * @since 2.0.0 */ export const interruptAs: { /** * Interrupts a fiber with a specific fiber ID as the interruptor. This allows * tracking which fiber initiated the interruption. * - * @example + * **When to use** + * + * Use when runtime diagnostics or tracing should attribute the interruption to + * a specific fiber ID. + * + * **Details** + * + * The returned Effect completes only after the interrupted fiber has completed. + * + * **Gotchas** + * + * The supplied ID affects the recorded interruptor. It does not make + * interruption synchronous or force uninterruptible regions to stop early. + * + * **Example** (Interrupting a fiber as another fiber) + * * ```ts * import { Effect, Fiber } from "effect" * @@ -337,8 +419,10 @@ export const interruptAs: { * }) * ``` * - * @since 2.0.0 + * @see {@link interrupt} for using the current fiber as the interruptor + * * @category interruption + * @since 2.0.0 */ ( fiberId: number | undefined, @@ -348,7 +432,22 @@ export const interruptAs: { * Interrupts a fiber with a specific fiber ID as the interruptor. This allows * tracking which fiber initiated the interruption. * - * @example + * **When to use** + * + * Use when runtime diagnostics or tracing should attribute the interruption to + * a specific fiber ID. + * + * **Details** + * + * The returned Effect completes only after the interrupted fiber has completed. + * + * **Gotchas** + * + * The supplied ID affects the recorded interruptor. It does not make + * interruption synchronous or force uninterruptible regions to stop early. + * + * **Example** (Interrupting a fiber as another fiber) + * * ```ts * import { Effect, Fiber } from "effect" * @@ -363,8 +462,10 @@ export const interruptAs: { * }) * ``` * - * @since 2.0.0 + * @see {@link interrupt} for using the current fiber as the interruptor + * * @category interruption + * @since 2.0.0 */ ( self: Fiber, @@ -377,7 +478,23 @@ export const interruptAs: { * Interrupts all fibers in the provided iterable, causing them to stop executing * and clean up any acquired resources. * - * @example + * **When to use** + * + * Use when you need to cancel several forked fibers and wait for their cleanup + * to complete. + * + * **Details** + * + * The current fiber is recorded as the interruptor. The returned Effect + * completes only after all interrupted fibers have completed. + * + * **Gotchas** + * + * Interruption is cooperative for each fiber. The returned Effect can wait for + * uninterruptible work and finalizers in any interrupted fiber. + * + * **Example** (Interrupting multiple fibers) + * * ```ts * import { Console, Effect, Fiber } from "effect" * @@ -415,8 +532,10 @@ export const interruptAs: { * }) * ``` * - * @since 2.0.0 + * @see {@link interruptAllAs} for specifying the interrupting fiber ID + * * @category interruption + * @since 2.0.0 */ export const interruptAll: >>( fibers: A @@ -427,7 +546,23 @@ export const interruptAll: >>( * interrupting fiber. This allows you to control which fiber is considered the source * of the interruption, which can be useful for debugging and tracing. * - * @example + * **When to use** + * + * Use to interrupt several fibers while recording a specific fiber ID as the + * interruptor. + * + * **Details** + * + * The returned Effect completes only after all interrupted fibers have + * completed. + * + * **Gotchas** + * + * The supplied ID affects the recorded interruptor. It does not make + * interruption synchronous or force uninterruptible regions to stop early. + * + * **Example** (Interrupting multiple fibers as another fiber) + * * ```ts * import { Console, Effect, Fiber } from "effect" * @@ -460,8 +595,10 @@ export const interruptAll: >>( * }) * ``` * - * @since 2.0.0 + * @see {@link interruptAll} for using the current fiber as the interruptor + * * @category interruption + * @since 2.0.0 */ export const interruptAllAs: { /** @@ -469,7 +606,23 @@ export const interruptAllAs: { * interrupting fiber. This allows you to control which fiber is considered the source * of the interruption, which can be useful for debugging and tracing. * - * @example + * **When to use** + * + * Use to interrupt several fibers while recording a specific fiber ID as the + * interruptor. + * + * **Details** + * + * The returned Effect completes only after all interrupted fibers have + * completed. + * + * **Gotchas** + * + * The supplied ID affects the recorded interruptor. It does not make + * interruption synchronous or force uninterruptible regions to stop early. + * + * **Example** (Interrupting multiple fibers as another fiber) + * * ```ts * import { Console, Effect, Fiber } from "effect" * @@ -502,8 +655,10 @@ export const interruptAllAs: { * }) * ``` * - * @since 2.0.0 + * @see {@link interruptAll} for using the current fiber as the interruptor + * * @category interruption + * @since 2.0.0 */ (fiberId: number): >>(fibers: A) => Effect /** @@ -511,7 +666,23 @@ export const interruptAllAs: { * interrupting fiber. This allows you to control which fiber is considered the source * of the interruption, which can be useful for debugging and tracing. * - * @example + * **When to use** + * + * Use to interrupt several fibers while recording a specific fiber ID as the + * interruptor. + * + * **Details** + * + * The returned Effect completes only after all interrupted fibers have + * completed. + * + * **Gotchas** + * + * The supplied ID affects the recorded interruptor. It does not make + * interruption synchronous or force uninterruptible regions to stop early. + * + * **Example** (Interrupting multiple fibers as another fiber) + * * ```ts * import { Console, Effect, Fiber } from "effect" * @@ -544,17 +715,30 @@ export const interruptAllAs: { * }) * ``` * - * @since 2.0.0 + * @see {@link interruptAll} for using the current fiber as the interruptor + * * @category interruption + * @since 2.0.0 */ >>(fibers: A, fiberId: number): Effect } = effect.fiberInterruptAllAs /** - * Tests if a value is a Fiber. This is a type guard that can be used to + * Checks whether a value is a Fiber. This is a type guard that can be used to * determine if an unknown value is a Fiber instance. * - * @example + * **When to use** + * + * Use when checking values at boundaries where an unknown value may be a + * runtime fiber. + * + * **Details** + * + * The check looks for the internal Fiber type ID marker and does not inspect + * the fiber's current state. + * + * **Example** (Checking for fibers) + * * ```ts * import { Effect, Fiber } from "effect" * @@ -577,8 +761,8 @@ export const interruptAllAs: { * }) * ``` * - * @since 2.0.0 * @category guards + * @since 2.0.0 */ export const isFiber = ( u: unknown @@ -588,7 +772,18 @@ export const isFiber = ( * Returns the current fiber if called from within a fiber context, * otherwise returns `undefined`. * - * @example + * **When to use** + * + * Use when you need low-level runtime integrations that need access to the currently + * executing fiber. + * + * **Gotchas** + * + * This is a synchronous accessor, not an Effect. It returns `undefined` outside + * an active fiber runtime context. + * + * **Example** (Getting the current fiber) + * * ```ts * import { Effect, Fiber } from "effect" * @@ -600,30 +795,78 @@ export const isFiber = ( * }) * ``` * - * @since 2.0.0 * @category accessors + * @since 4.0.0 */ export const getCurrent: () => Fiber | undefined = effect.getCurrentFiber /** - * Links the lifetime of a fiber to the provided scope. + * Adds a fiber to a `Scope` and returns the same fiber. + * + * **When to use** + * + * Use when a manually managed fiber should be interrupted when a Scope closes. + * + * **Details** * + * When the scope is closed, the fiber is interrupted. If the scope is already + * closed, the fiber is interrupted immediately. + * + * **Gotchas** + * + * This does not wait for the fiber to complete. It only registers the + * interruption finalizer and returns the same fiber. + * + * @see {@link interrupt} for interrupting and waiting for completion + * + * @category resource management * @since 4.0.0 - * @category Scope */ export const runIn: { /** - * Links the lifetime of a fiber to the provided scope. + * Adds a fiber to a `Scope` and returns the same fiber. + * + * **When to use** + * + * Use when a manually managed fiber should be interrupted when a Scope closes. * + * **Details** + * + * When the scope is closed, the fiber is interrupted. If the scope is already + * closed, the fiber is interrupted immediately. + * + * **Gotchas** + * + * This does not wait for the fiber to complete. It only registers the + * interruption finalizer and returns the same fiber. + * + * @see {@link interrupt} for interrupting and waiting for completion + * + * @category resource management * @since 4.0.0 - * @category Scope */ (scope: Scope): (self: Fiber) => Fiber /** - * Links the lifetime of a fiber to the provided scope. + * Adds a fiber to a `Scope` and returns the same fiber. + * + * **When to use** + * + * Use when a manually managed fiber should be interrupted when a Scope closes. + * + * **Details** + * + * When the scope is closed, the fiber is interrupted. If the scope is already + * closed, the fiber is interrupted immediately. + * + * **Gotchas** + * + * This does not wait for the fiber to complete. It only registers the + * interruption finalizer and returns the same fiber. + * + * @see {@link interrupt} for interrupting and waiting for completion * + * @category resource management * @since 4.0.0 - * @category Scope */ (self: Fiber, scope: Scope): Fiber } = effect.fiberRunIn diff --git a/.opencode/node_modules/effect/src/FiberHandle.ts b/.opencode/node_modules/effect/src/FiberHandle.ts index 7d47f1de15d354994cbab91a50cf238b3650d485..7ce2c3056c59b6bffae6ebf309757d986048fdfd 100644 --- a/.opencode/node_modules/effect/src/FiberHandle.ts +++ b/.opencode/node_modules/effect/src/FiberHandle.ts @@ -1,4 +1,13 @@ /** + * Manages at most one fiber inside a scope. + * + * A `FiberHandle` can hold one `Fiber`. Installing a new fiber + * interrupts the previous one unless the operation is configured with + * `onlyIfMissing`, and closing the owning scope interrupts the current fiber. + * This module includes constructors for handles and scoped runtimes, helpers + * for setting, reading, clearing, and running fibers, and operations for joining + * the current fiber or waiting until the handle is empty. + * * @since 2.0.0 */ import * as Cause from "./Cause.ts" @@ -20,7 +29,12 @@ import type * as Scope from "./Scope.ts" const TypeId = "~effect/FiberHandle" /** - * @example + * Scoped handle that manages at most one fiber, interrupts the current fiber + * when the handle's scope closes, and removes managed fibers from the handle + * when they complete. + * + * **Example** (Managing a single fiber) + * * ```ts * import { Effect, Fiber, FiberHandle } from "effect" * @@ -35,8 +49,8 @@ const TypeId = "~effect/FiberHandle" * }) * ``` * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface FiberHandle extends Pipeable, Inspectable.Inspectable { readonly [TypeId]: typeof TypeId @@ -50,7 +64,11 @@ export interface FiberHandle extends Pipeable, } /** - * @example + * Returns `true` if a value is a `FiberHandle` by checking for the + * `FiberHandle` runtime marker. + * + * **Example** (Checking fiber handles) + * * ```ts * import { Effect, FiberHandle } from "effect" * @@ -62,8 +80,8 @@ export interface FiberHandle extends Pipeable, * }) * ``` * - * @since 2.0.0 * @category refinements + * @since 2.0.0 */ export const isFiberHandle = (u: unknown): u is FiberHandle => Predicate.hasProperty(u, TypeId) @@ -86,13 +104,17 @@ const makeUnsafe = (): FiberHandle => { } /** - * A FiberHandle can be used to store a single fiber. - * When the associated Scope is closed, the contained fiber will be interrupted. + * Creates a scoped `FiberHandle` that can store a single fiber. + * + * **Details** + * + * 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. * - * 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** (Creating a scoped fiber handle) * - * @example * ```ts * import { Effect, FiberHandle } from "effect" * @@ -110,8 +132,8 @@ const makeUnsafe = (): FiberHandle => { * ) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const make = (): Effect.Effect, never, Scope.Scope> => Effect.acquireRelease( @@ -130,9 +152,16 @@ export const make = (): Effect.Effect(): Effect.Effect(): Effect.Effect< ( @@ -173,9 +202,22 @@ export const makeRuntime = (): Effect.Effect< ) /** - * Create an Effect run function that is backed by a FiberHandle. + * Creates a scoped run function that forks effects into a new `FiberHandle` + * and returns a `Promise` for each effect result. + * + * **When to use** + * + * Use when integrating a scoped `FiberHandle` runner with Promise-based APIs + * and Promise rejection from squashed failures is the desired boundary. + * + * **Details** + * + * Each call stores the fiber in the handle and interrupts the previous fiber + * unless `onlyIfMissing` is set. The returned Promise resolves with the + * effect's success value or rejects with the squashed failure cause. + * + * **Example** (Running effects as promises) * - * @example * ```ts * import { Effect, FiberHandle } from "effect" * @@ -189,8 +231,8 @@ export const makeRuntime = (): Effect.Effect< * }).pipe(Effect.scoped) * ``` * - * @since 3.13.0 * @category constructors + * @since 3.13.0 */ export const makeRuntimePromise = (): Effect.Effect< ( @@ -217,10 +259,16 @@ const isInternalInterruption = Filter.toPredicate(Filter.compose( )) /** - * Set the fiber in a FiberHandle. When the fiber completes, it will be removed from the FiberHandle. + * Sets 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. * - * @example + * **When to use** + * + * Use when an existing forked fiber must be installed synchronously into a + * handle and immediate interruption of replaced or closed fibers is acceptable. + * + * **Example** (Setting a fiber unsafely) + * * ```ts * import { Effect, Fiber, FiberHandle } from "effect" * @@ -237,15 +285,21 @@ const isInternalInterruption = Filter.toPredicate(Filter.compose( * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ export const setUnsafe: { /** - * Set the fiber in a FiberHandle. When the fiber completes, it will be removed from the FiberHandle. + * Sets 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. * - * @example + * **When to use** + * + * Use when an existing forked fiber must be installed synchronously into a + * handle and immediate interruption of replaced or closed fibers is acceptable. + * + * **Example** (Setting a fiber unsafely) + * * ```ts * import { Effect, Fiber, FiberHandle } from "effect" * @@ -262,8 +316,8 @@ export const setUnsafe: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ ( fiber: Fiber.Fiber, @@ -273,10 +327,16 @@ export const setUnsafe: { } ): (self: FiberHandle) => void /** - * Set the fiber in a FiberHandle. When the fiber completes, it will be removed from the FiberHandle. + * Sets 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. * - * @example + * **When to use** + * + * Use when an existing forked fiber must be installed synchronously into a + * handle and immediate interruption of replaced or closed fibers is acceptable. + * + * **Example** (Setting a fiber unsafely) + * * ```ts * import { Effect, Fiber, FiberHandle } from "effect" * @@ -293,8 +353,8 @@ export const setUnsafe: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ ( self: FiberHandle, @@ -345,13 +405,16 @@ export const setUnsafe: { }) /** - * Set the fiber in the `FiberHandle`. When the fiber completes, it will be - * removed from the `FiberHandle`. + * Sets the fiber in the `FiberHandle`. + * + * **Details** * - * If a fiber already exists in the `FiberHandle`, it will be interrupted - * unless `options.onlyIfMissing` is set. + * 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. + * + * **Example** (Setting a fiber safely) * - * @example * ```ts * import { Effect, Fiber, FiberHandle } from "effect" * @@ -368,18 +431,21 @@ export const setUnsafe: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const set: { /** - * Set the fiber in the `FiberHandle`. When the fiber completes, it will be - * removed from the `FiberHandle`. + * Sets the fiber in the `FiberHandle`. * - * If a fiber already exists in the `FiberHandle`, it will be interrupted - * unless `options.onlyIfMissing` is set. + * **Details** + * + * 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. + * + * **Example** (Setting a fiber safely) * - * @example * ```ts * import { Effect, Fiber, FiberHandle } from "effect" * @@ -396,8 +462,8 @@ export const set: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ ( fiber: Fiber.Fiber, @@ -407,13 +473,16 @@ export const set: { } ): (self: FiberHandle) => Effect.Effect /** - * Set the fiber in the `FiberHandle`. When the fiber completes, it will be - * removed from the `FiberHandle`. + * Sets the fiber in the `FiberHandle`. + * + * **Details** * - * If a fiber already exists in the `FiberHandle`, it will be interrupted - * unless `options.onlyIfMissing` is set. + * 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. + * + * **Example** (Setting a fiber safely) * - * @example * ```ts * import { Effect, Fiber, FiberHandle } from "effect" * @@ -430,8 +499,8 @@ export const set: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ ( self: FiberHandle, @@ -457,9 +526,15 @@ export const set: { )) /** - * Retrieve the fiber from the FiberHandle. + * Retrieves the fiber from the FiberHandle synchronously. + * + * **When to use** + * + * Use when synchronous inspection of the current fiber is needed and an + * `Option` result is enough outside the Effect workflow. + * + * **Example** (Reading the current fiber unsafely) * - * @example * ```ts * import { Effect, FiberHandle } from "effect" * @@ -477,17 +552,18 @@ export const set: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ export function getUnsafe(self: FiberHandle): Option.Option> { return self.state._tag === "Closed" ? Option.none() : Option.fromUndefinedOr(self.state.fiber) } /** - * Retrieve the fiber from the FiberHandle. + * Retrieves the fiber from the FiberHandle effectfully. + * + * **Example** (Reading the current fiber) * - * @example * ```ts * import { Effect, Fiber, FiberHandle } from "effect" * @@ -506,15 +582,19 @@ export function getUnsafe(self: FiberHandle): Option.Option(self: FiberHandle): Effect.Effect>> { return Effect.suspend(() => Effect.succeed(getUnsafe(self))) } /** - * @example + * Interrupts the fiber currently stored in the `FiberHandle`, if any, and + * leaves the handle empty. + * + * **Example** (Clearing a fiber handle) + * * ```ts * import { Effect, FiberHandle } from "effect" * @@ -533,8 +613,8 @@ export function get(self: FiberHandle): Effect.Effect(self: FiberHandle): Effect.Effect => Effect.uninterruptibleMask((restore) => { @@ -562,10 +642,16 @@ const constInterruptedFiber = (function() { })() /** - * Run an Effect and add the forked fiber to the FiberHandle. - * When the fiber completes, it will be removed from the FiberHandle. + * Forks an Effect and stores the resulting fiber in the `FiberHandle`. + * + * **Details** + * + * The handle manages only one fiber: running a new effect interrupts the + * previous fiber unless `onlyIfMissing` is set. When the managed fiber + * completes, it is removed from the handle. + * + * **Example** (Running an effect in a fiber handle) * - * @example * ```ts * import { Effect, Fiber, FiberHandle } from "effect" * @@ -584,15 +670,21 @@ const constInterruptedFiber = (function() { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ 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. + * Forks an Effect and stores the resulting fiber in the `FiberHandle`. + * + * **Details** + * + * The handle manages only one fiber: running a new effect interrupts the + * previous fiber unless `onlyIfMissing` is set. When the managed fiber + * completes, it is removed from the handle. + * + * **Example** (Running an effect in a fiber handle) * - * @example * ```ts * import { Effect, Fiber, FiberHandle } from "effect" * @@ -611,8 +703,8 @@ export const run: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ ( self: FiberHandle, @@ -625,10 +717,16 @@ export const run: { effect: Effect.Effect ) => Effect.Effect, never, R> /** - * Run an Effect and add the forked fiber to the FiberHandle. - * When the fiber completes, it will be removed from the FiberHandle. + * Forks an Effect and stores the resulting fiber in the `FiberHandle`. + * + * **Details** + * + * The handle manages only one fiber: running a new effect interrupts the + * previous fiber unless `onlyIfMissing` is set. When the managed fiber + * completes, it is removed from the handle. + * + * **Example** (Running an effect in a fiber handle) * - * @example * ```ts * import { Effect, Fiber, FiberHandle } from "effect" * @@ -647,8 +745,8 @@ export const run: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ ( self: FiberHandle, @@ -687,11 +785,18 @@ const runImpl = ( }) /** - * Capture a Runtime and use it to fork Effect's, adding the forked fibers to the FiberHandle. + * Captures the current runtime and returns a function for forking effects into + * an existing `FiberHandle`. + * + * **Details** + * + * Each call returns the forked fiber, stores it in the handle, and interrupts + * the previous fiber unless `onlyIfMissing` is set. + * + * **Example** (Capturing a runtime for fiber handles) * - * @example * ```ts - * import { Effect, FiberHandle, Context } from "effect" + * import { Context, Effect, FiberHandle } from "effect" * * interface Users { * readonly _: unique symbol @@ -705,17 +810,17 @@ const runImpl = ( * const run = yield* FiberHandle.runtime(handle)() * * // run an effect and set the fiber in the handle - * run(Effect.andThen(Users.asEffect(), (_) => _.getAll)) + * run(Effect.andThen(Users, (_) => _.getAll)) * * // this will interrupt the previous fiber - * run(Effect.andThen(Users.asEffect(), (_) => _.getAll)) + * run(Effect.andThen(Users, (_) => _.getAll)) * }).pipe( * Effect.scoped // The fiber will be interrupted when the scope is closed * ) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const runtime: ( self: FiberHandle @@ -762,12 +867,17 @@ export const runtime: ( ) /** - * Capture a Runtime and use it to fork Effect's, adding the forked fibers to the FiberHandle. + * Captures the current runtime and returns a function for running effects in + * an existing `FiberHandle` as Promises. + * + * **Details** * - * The returned run function will return Promise's that will resolve when the - * fiber completes. + * Each call stores the forked fiber in the handle and interrupts the previous + * fiber unless `onlyIfMissing` is set. The Promise resolves with the effect's + * success value or rejects with the squashed failure cause. + * + * **Example** (Capturing a runtime for promises) * - * @example * ```ts * import { Effect, FiberHandle } from "effect" * @@ -782,8 +892,8 @@ export const runtime: ( * }) * ``` * - * @since 3.13.0 * @category combinators + * @since 3.13.0 */ export const runtimePromise = (self: FiberHandle): () => Effect.Effect< ( @@ -827,10 +937,17 @@ export const runtimePromise = (self: FiberHandle): () => ) /** - * If any of the Fiber's in the handle terminate with a failure, - * the returned Effect will terminate with the first failure that occurred. + * Waits for the `FiberHandle` to fail or close. + * + * **Details** + * + * The returned Effect fails with the first managed fiber failure that is not + * ignored by the handle's interruption rules. Normal successful completion of + * a managed fiber only removes it from the handle; use `awaitEmpty` to wait + * for the current fiber to finish. + * + * **Example** (Propagating fiber failures) * - * @example * ```ts * import { Effect, FiberHandle } from "effect" * @@ -843,16 +960,17 @@ export const runtimePromise = (self: FiberHandle): () => * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const join = (self: FiberHandle): Effect.Effect => Deferred.await(self.deferred as Deferred.Deferred) /** - * Wait for the fiber in the FiberHandle to complete. + * Waits for the fiber in the FiberHandle to complete. + * + * **Example** (Waiting for a fiber to complete) * - * @example * ```ts * import { Effect, FiberHandle } from "effect" * @@ -869,8 +987,8 @@ export const join = (self: FiberHandle): Effect.Effect => * }) * ``` * - * @since 3.13.0 * @category combinators + * @since 3.13.0 */ export const awaitEmpty = (self: FiberHandle): Effect.Effect => Effect.suspend(() => { diff --git a/.opencode/node_modules/effect/src/FiberMap.ts b/.opencode/node_modules/effect/src/FiberMap.ts index c14ea4e1b59b17070d91ae52729743fc5e83870a..6941d6428443ecb2d563b75557a6303a2d673905 100644 --- a/.opencode/node_modules/effect/src/FiberMap.ts +++ b/.opencode/node_modules/effect/src/FiberMap.ts @@ -1,4 +1,12 @@ /** + * Manages fibers by key inside a scope. + * + * A `FiberMap` owns a map of running fibers, interrupts them when its + * scope closes, and automatically removes each entry when the corresponding + * fiber completes. Use it when a program needs to start, replace, join, or + * interrupt background work by a stable key while keeping all fibers tied to + * one scope. + * * @since 2.0.0 */ import * as Cause from "./Cause.ts" @@ -25,7 +33,8 @@ const TypeId = "~effect/FiberMap" * Scope is closed, all fibers in the map will be interrupted. Fibers are * automatically removed from the map when they complete. * - * @example + * **Example** (Managing fibers in a map) + * * ```ts * import { Effect, FiberMap } from "effect" * @@ -34,8 +43,8 @@ const TypeId = "~effect/FiberMap" * const map = yield* FiberMap.make() * * // Add some fibers to the map - * yield* FiberMap.run(map, "task1", Effect.succeed("Hello")) - * yield* FiberMap.run(map, "task2", Effect.succeed("World")) + * yield* FiberMap.run(map, "task1", Effect.never) + * yield* FiberMap.run(map, "task2", Effect.never) * * // Get the size of the map * const size = yield* FiberMap.size(map) @@ -43,8 +52,8 @@ const TypeId = "~effect/FiberMap" * }) * ``` * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface FiberMap extends Pipeable, Inspectable.Inspectable, Iterable<[K, Fiber.Fiber]> @@ -60,7 +69,14 @@ export interface FiberMap } /** - * @example + * Returns `true` if a value is a `FiberMap`. + * + * **Details** + * + * This is a type guard that checks for the `FiberMap` runtime marker. + * + * **Example** (Checking if a value is a FiberMap) + * * ```ts * import { Effect, FiberMap } from "effect" * @@ -73,8 +89,8 @@ export interface FiberMap * }) * ``` * - * @since 2.0.0 * @category refinements + * @since 2.0.0 */ export const isFiberMap = (u: unknown): u is FiberMap => Predicate.hasProperty(u, TypeId) @@ -106,13 +122,17 @@ const makeUnsafe = ( } /** - * 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. + * Creates a scoped `FiberMap` for storing fibers by key. + * + * **Details** + * + * 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. * - * 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** (Creating a scoped FiberMap) * - * @example * ```ts * import { Effect, FiberMap } from "effect" * @@ -129,8 +149,8 @@ const makeUnsafe = ( * ) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const make = (): Effect.Effect, never, Scope.Scope> => Effect.acquireRelease( @@ -152,9 +172,17 @@ export const make = (): Effect.Effect(): Effect.Effect(): Effect.Effect< ( @@ -195,10 +223,23 @@ export const makeRuntime = (): Effect.Effect< ) /** - * Create an Effect run function that is backed by a FiberMap. - * Returns a Promise instead of a Fiber for more convenient use with async/await. + * Creates a scoped run function that forks effects into a new `FiberMap` and + * returns a `Promise` for each effect result. + * + * **When to use** + * + * Use when keyed fibers must be managed in a scoped map while exposing their + * results through Promise-based APIs. + * + * **Details** + * + * Each call stores the fiber under the supplied key, interrupting any previous + * fiber for that key unless `onlyIfMissing` is set. The returned Promise + * resolves with the effect's success value or rejects with the squashed failure + * cause. + * + * **Example** (Creating a promise runtime) * - * @example * ```ts * import { Effect, FiberMap } from "effect" * @@ -217,8 +258,8 @@ export const makeRuntime = (): Effect.Effect< * }) * ``` * - * @since 3.13.0 * @category constructors + * @since 3.13.0 */ export const makeRuntimePromise = (): Effect.Effect< ( @@ -245,53 +286,83 @@ const isInternalInterruption = Filter.toPredicate(Filter.compose( )) /** - * 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. + * Adds a fiber to the `FiberMap` under a key using a synchronous, unsafe + * mutation. + * + * **When to use** + * + * Use when an existing forked fiber must be installed under a key immediately + * and synchronous interruption of the replaced fiber is acceptable. + * + * **Details** + * + * When the fiber completes, it is removed from the map. If the key already has + * a fiber, that previous fiber is interrupted unless `onlyIfMissing` is set; + * in that case the new fiber is interrupted and the existing entry is kept. + * + * **Example** (Adding a fiber unsafely) * - * @example * ```ts - * import { Effect, Fiber, FiberMap } from "effect" + * import { Deferred, Effect, Fiber, FiberMap } from "effect" * * const program = Effect.gen(function*() { * const map = yield* FiberMap.make() + * const deferred = yield* Deferred.make() * * // Create a fiber and add it to the map - * const fiber = yield* Effect.forkChild(Effect.succeed("Hello")) + * const fiber = yield* Effect.forkChild(Deferred.await(deferred)) * FiberMap.setUnsafe(map, "greeting", fiber) * - * // The fiber will be automatically removed when it completes - * const result = yield* Fiber.await(fiber) + * yield* Deferred.succeed(deferred, "Hello") + * + * // Join the fiber to get its successful value + * const result = yield* Fiber.join(fiber) * console.log(result) // "Hello" * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ export const setUnsafe: { /** - * 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. + * Adds a fiber to the `FiberMap` under a key using a synchronous, unsafe + * mutation. + * + * **When to use** + * + * Use when an existing forked fiber must be installed under a key immediately + * and synchronous interruption of the replaced fiber is acceptable. + * + * **Details** + * + * When the fiber completes, it is removed from the map. If the key already has + * a fiber, that previous fiber is interrupted unless `onlyIfMissing` is set; + * in that case the new fiber is interrupted and the existing entry is kept. + * + * **Example** (Adding a fiber unsafely) * - * @example * ```ts - * import { Effect, Fiber, FiberMap } from "effect" + * import { Deferred, Effect, Fiber, FiberMap } from "effect" * * const program = Effect.gen(function*() { * const map = yield* FiberMap.make() + * const deferred = yield* Deferred.make() * * // Create a fiber and add it to the map - * const fiber = yield* Effect.forkChild(Effect.succeed("Hello")) + * const fiber = yield* Effect.forkChild(Deferred.await(deferred)) * FiberMap.setUnsafe(map, "greeting", fiber) * - * // The fiber will be automatically removed when it completes - * const result = yield* Fiber.await(fiber) + * yield* Deferred.succeed(deferred, "Hello") + * + * // Join the fiber to get its successful value + * const result = yield* Fiber.join(fiber) * console.log(result) // "Hello" * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ ( key: K, @@ -302,28 +373,43 @@ export const setUnsafe: { } | undefined ): (self: FiberMap) => 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. + * Adds a fiber to the `FiberMap` under a key using a synchronous, unsafe + * mutation. + * + * **When to use** + * + * Use when an existing forked fiber must be installed under a key immediately + * and synchronous interruption of the replaced fiber is acceptable. + * + * **Details** + * + * When the fiber completes, it is removed from the map. If the key already has + * a fiber, that previous fiber is interrupted unless `onlyIfMissing` is set; + * in that case the new fiber is interrupted and the existing entry is kept. + * + * **Example** (Adding a fiber unsafely) * - * @example * ```ts - * import { Effect, Fiber, FiberMap } from "effect" + * import { Deferred, Effect, Fiber, FiberMap } from "effect" * * const program = Effect.gen(function*() { * const map = yield* FiberMap.make() + * const deferred = yield* Deferred.make() * * // Create a fiber and add it to the map - * const fiber = yield* Effect.forkChild(Effect.succeed("Hello")) + * const fiber = yield* Effect.forkChild(Deferred.await(deferred)) * FiberMap.setUnsafe(map, "greeting", fiber) * - * // The fiber will be automatically removed when it completes - * const result = yield* Fiber.await(fiber) + * yield* Deferred.succeed(deferred, "Hello") + * + * // Join the fiber to get its successful value + * const result = yield* Fiber.join(fiber) * console.log(result) // "Hello" * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ ( self: FiberMap, @@ -382,55 +468,75 @@ export const setUnsafe: { }) /** - * 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. + * Adds a fiber to the `FiberMap` under a key. + * + * **Details** + * + * When the fiber completes, it is removed from the map. If the key already has + * a fiber, that previous fiber is interrupted unless `onlyIfMissing` is set; + * in that case the new fiber is interrupted and the existing entry is kept. + * * This is the Effect-wrapped version of `setUnsafe`. * - * @example + * **Example** (Adding a fiber) + * * ```ts - * import { Effect, Fiber, FiberMap } from "effect" + * import { Deferred, Effect, Fiber, FiberMap } from "effect" * * const program = Effect.gen(function*() { * const map = yield* FiberMap.make() + * const deferred = yield* Deferred.make() * * // Create a fiber and add it to the map using Effect - * const fiber = yield* Effect.forkChild(Effect.succeed("Hello")) + * const fiber = yield* Effect.forkChild(Deferred.await(deferred)) * yield* FiberMap.set(map, "greeting", fiber) * - * // The fiber will be automatically removed when it completes - * const result = yield* Fiber.await(fiber) + * yield* Deferred.succeed(deferred, "Hello") + * + * // Join the fiber to get its successful value + * const result = yield* Fiber.join(fiber) * console.log(result) // "Hello" * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ 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. + * Adds a fiber to the `FiberMap` under a key. + * + * **Details** + * + * When the fiber completes, it is removed from the map. If the key already has + * a fiber, that previous fiber is interrupted unless `onlyIfMissing` is set; + * in that case the new fiber is interrupted and the existing entry is kept. + * * This is the Effect-wrapped version of `setUnsafe`. * - * @example + * **Example** (Adding a fiber) + * * ```ts - * import { Effect, Fiber, FiberMap } from "effect" + * import { Deferred, Effect, Fiber, FiberMap } from "effect" * * const program = Effect.gen(function*() { * const map = yield* FiberMap.make() + * const deferred = yield* Deferred.make() * * // Create a fiber and add it to the map using Effect - * const fiber = yield* Effect.forkChild(Effect.succeed("Hello")) + * const fiber = yield* Effect.forkChild(Deferred.await(deferred)) * yield* FiberMap.set(map, "greeting", fiber) * - * // The fiber will be automatically removed when it completes - * const result = yield* Fiber.await(fiber) + * yield* Deferred.succeed(deferred, "Hello") + * + * // Join the fiber to get its successful value + * const result = yield* Fiber.join(fiber) * console.log(result) // "Hello" * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ ( key: K, @@ -441,29 +547,39 @@ export const set: { } | undefined ): (self: FiberMap) => Effect.Effect /** - * 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. + * Adds a fiber to the `FiberMap` under a key. + * + * **Details** + * + * When the fiber completes, it is removed from the map. If the key already has + * a fiber, that previous fiber is interrupted unless `onlyIfMissing` is set; + * in that case the new fiber is interrupted and the existing entry is kept. + * * This is the Effect-wrapped version of `setUnsafe`. * - * @example + * **Example** (Adding a fiber) + * * ```ts - * import { Effect, Fiber, FiberMap } from "effect" + * import { Deferred, Effect, Fiber, FiberMap } from "effect" * * const program = Effect.gen(function*() { * const map = yield* FiberMap.make() + * const deferred = yield* Deferred.make() * * // Create a fiber and add it to the map using Effect - * const fiber = yield* Effect.forkChild(Effect.succeed("Hello")) + * const fiber = yield* Effect.forkChild(Deferred.await(deferred)) * yield* FiberMap.set(map, "greeting", fiber) * - * // The fiber will be automatically removed when it completes - * const result = yield* Fiber.await(fiber) + * yield* Deferred.succeed(deferred, "Hello") + * + * // Join the fiber to get its successful value + * const result = yield* Fiber.join(fiber) * console.log(result) // "Hello" * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ ( self: FiberMap, @@ -485,84 +601,111 @@ export const set: { ): Effect.Effect => Effect.sync(() => setUnsafe(self, key, fiber, options))) /** - * Retrieve a fiber from the FiberMap. + * Retrieves a fiber from the FiberMap synchronously. + * + * **When to use** + * + * Use when synchronous keyed lookup of a fiber in a `FiberMap` is needed and an + * `Option` result is enough outside the Effect workflow. + * + * **Example** (Retrieving a fiber unsafely) * - * @example * ```ts - * import { Effect, Fiber, FiberMap } from "effect" + * import { Deferred, Effect, Fiber, FiberMap } from "effect" * * const program = Effect.gen(function*() { * const map = yield* FiberMap.make() + * const deferred = yield* Deferred.make() * * // Add a fiber to the map - * const fiber = yield* Effect.forkChild(Effect.succeed("Hello")) + * const fiber = yield* Effect.forkChild(Deferred.await(deferred)) * FiberMap.setUnsafe(map, "greeting", fiber) * * // Retrieve the fiber * const retrieved = FiberMap.getUnsafe(map, "greeting") * if (retrieved._tag === "Some") { - * const result = yield* Fiber.await(retrieved.value) + * yield* Deferred.succeed(deferred, "Hello") + * + * const result = yield* Fiber.join(retrieved.value) * console.log(result) // "Hello" * } * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ export const getUnsafe: { /** - * Retrieve a fiber from the FiberMap. + * Retrieves a fiber from the FiberMap synchronously. + * + * **When to use** + * + * Use when synchronous keyed lookup of a fiber in a `FiberMap` is needed and an + * `Option` result is enough outside the Effect workflow. + * + * **Example** (Retrieving a fiber unsafely) * - * @example * ```ts - * import { Effect, Fiber, FiberMap } from "effect" + * import { Deferred, Effect, Fiber, FiberMap } from "effect" * * const program = Effect.gen(function*() { * const map = yield* FiberMap.make() + * const deferred = yield* Deferred.make() * * // Add a fiber to the map - * const fiber = yield* Effect.forkChild(Effect.succeed("Hello")) + * const fiber = yield* Effect.forkChild(Deferred.await(deferred)) * FiberMap.setUnsafe(map, "greeting", fiber) * * // Retrieve the fiber * const retrieved = FiberMap.getUnsafe(map, "greeting") * if (retrieved._tag === "Some") { - * const result = yield* Fiber.await(retrieved.value) + * yield* Deferred.succeed(deferred, "Hello") + * + * const result = yield* Fiber.join(retrieved.value) * console.log(result) // "Hello" * } * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ (key: K): (self: FiberMap) => Option.Option> /** - * Retrieve a fiber from the FiberMap. + * Retrieves a fiber from the FiberMap synchronously. + * + * **When to use** + * + * Use when synchronous keyed lookup of a fiber in a `FiberMap` is needed and an + * `Option` result is enough outside the Effect workflow. + * + * **Example** (Retrieving a fiber unsafely) * - * @example * ```ts - * import { Effect, Fiber, FiberMap } from "effect" + * import { Deferred, Effect, Fiber, FiberMap } from "effect" * * const program = Effect.gen(function*() { * const map = yield* FiberMap.make() + * const deferred = yield* Deferred.make() * * // Add a fiber to the map - * const fiber = yield* Effect.forkChild(Effect.succeed("Hello")) + * const fiber = yield* Effect.forkChild(Deferred.await(deferred)) * FiberMap.setUnsafe(map, "greeting", fiber) * * // Retrieve the fiber * const retrieved = FiberMap.getUnsafe(map, "greeting") * if (retrieved._tag === "Some") { - * const result = yield* Fiber.await(retrieved.value) + * yield* Deferred.succeed(deferred, "Hello") + * + * const result = yield* Fiber.join(retrieved.value) * console.log(result) // "Hello" * } * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ (self: FiberMap, key: K): Option.Option> } = dual( @@ -573,90 +716,108 @@ export const getUnsafe: { ) /** - * Retrieve a fiber from the FiberMap. + * Retrieves a fiber from the FiberMap effectfully. + * + * **Details** * * Returns an `Option` wrapped in `Effect`. * - * @example + * **Example** (Retrieving a fiber) + * * ```ts - * import { Effect, Fiber, FiberMap } from "effect" + * import { Deferred, Effect, Fiber, FiberMap } from "effect" * * const program = Effect.gen(function*() { * const map = yield* FiberMap.make() + * const deferred = yield* Deferred.make() * * // Add a fiber to the map - * const fiber = yield* Effect.forkChild(Effect.succeed("Hello")) + * const fiber = yield* Effect.forkChild(Deferred.await(deferred)) * yield* FiberMap.set(map, "greeting", fiber) * * // Retrieve the fiber with error handling * const retrieved = yield* FiberMap.get(map, "greeting") * if (retrieved._tag === "Some") { - * const result = yield* Fiber.await(retrieved.value) + * yield* Deferred.succeed(deferred, "Hello") + * + * const result = yield* Fiber.join(retrieved.value) * console.log(result) // "Hello" * } * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const get: { /** - * Retrieve a fiber from the FiberMap. + * Retrieves a fiber from the FiberMap effectfully. + * + * **Details** * * Returns an `Option` wrapped in `Effect`. * - * @example + * **Example** (Retrieving a fiber) + * * ```ts - * import { Effect, Fiber, FiberMap } from "effect" + * import { Deferred, Effect, Fiber, FiberMap } from "effect" * * const program = Effect.gen(function*() { * const map = yield* FiberMap.make() + * const deferred = yield* Deferred.make() * * // Add a fiber to the map - * const fiber = yield* Effect.forkChild(Effect.succeed("Hello")) + * const fiber = yield* Effect.forkChild(Deferred.await(deferred)) * yield* FiberMap.set(map, "greeting", fiber) * * // Retrieve the fiber with error handling * const retrieved = yield* FiberMap.get(map, "greeting") * if (retrieved._tag === "Some") { - * const result = yield* Fiber.await(retrieved.value) + * yield* Deferred.succeed(deferred, "Hello") + * + * const result = yield* Fiber.join(retrieved.value) * console.log(result) // "Hello" * } * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (key: K): (self: FiberMap) => Effect.Effect>> /** - * Retrieve a fiber from the FiberMap. + * Retrieves a fiber from the FiberMap effectfully. + * + * **Details** * * Returns an `Option` wrapped in `Effect`. * - * @example + * **Example** (Retrieving a fiber) + * * ```ts - * import { Effect, Fiber, FiberMap } from "effect" + * import { Deferred, Effect, Fiber, FiberMap } from "effect" * * const program = Effect.gen(function*() { * const map = yield* FiberMap.make() + * const deferred = yield* Deferred.make() * * // Add a fiber to the map - * const fiber = yield* Effect.forkChild(Effect.succeed("Hello")) + * const fiber = yield* Effect.forkChild(Deferred.await(deferred)) * yield* FiberMap.set(map, "greeting", fiber) * * // Retrieve the fiber with error handling * const retrieved = yield* FiberMap.get(map, "greeting") * if (retrieved._tag === "Some") { - * const result = yield* Fiber.await(retrieved.value) + * yield* Deferred.succeed(deferred, "Hello") + * + * const result = yield* Fiber.join(retrieved.value) * console.log(result) // "Hello" * } * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (self: FiberMap, key: K): Effect.Effect>> } = dual( @@ -666,9 +827,10 @@ export const get: { ) /** - * Check if a key exists in the FiberMap. + * Checks whether a key exists in the FiberMap. + * + * **Example** (Checking if a key exists unsafely) * - * @example * ```ts * import { Effect, FiberMap } from "effect" * @@ -676,7 +838,7 @@ export const get: { * const map = yield* FiberMap.make() * * // Add a fiber to the map - * yield* FiberMap.run(map, "task1", Effect.succeed("Hello")) + * yield* FiberMap.run(map, "task1", Effect.never) * * // Check if keys exist * console.log(FiberMap.hasUnsafe(map, "task1")) // true @@ -684,14 +846,15 @@ export const get: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ export const hasUnsafe: { /** - * Check if a key exists in the FiberMap. + * Checks whether a key exists in the FiberMap. + * + * **Example** (Checking if a key exists unsafely) * - * @example * ```ts * import { Effect, FiberMap } from "effect" * @@ -699,7 +862,7 @@ export const hasUnsafe: { * const map = yield* FiberMap.make() * * // Add a fiber to the map - * yield* FiberMap.run(map, "task1", Effect.succeed("Hello")) + * yield* FiberMap.run(map, "task1", Effect.never) * * // Check if keys exist * console.log(FiberMap.hasUnsafe(map, "task1")) // true @@ -707,14 +870,15 @@ export const hasUnsafe: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ (key: K): (self: FiberMap) => boolean /** - * Check if a key exists in the FiberMap. + * Checks whether a key exists in the FiberMap. + * + * **Example** (Checking if a key exists unsafely) * - * @example * ```ts * import { Effect, FiberMap } from "effect" * @@ -722,7 +886,7 @@ export const hasUnsafe: { * const map = yield* FiberMap.make() * * // Add a fiber to the map - * yield* FiberMap.run(map, "task1", Effect.succeed("Hello")) + * yield* FiberMap.run(map, "task1", Effect.never) * * // Check if keys exist * console.log(FiberMap.hasUnsafe(map, "task1")) // true @@ -730,8 +894,8 @@ export const hasUnsafe: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ (self: FiberMap, key: K): boolean } = dual( @@ -741,10 +905,11 @@ export const hasUnsafe: { ) /** - * Check if a key exists in the FiberMap. + * Checks whether a key exists in the FiberMap. * This is the Effect-wrapped version of `hasUnsafe`. * - * @example + * **Example** (Checking if a key exists) + * * ```ts * import { Effect, FiberMap } from "effect" * @@ -752,7 +917,7 @@ export const hasUnsafe: { * const map = yield* FiberMap.make() * * // Add a fiber to the map - * yield* FiberMap.run(map, "task1", Effect.succeed("Hello")) + * yield* FiberMap.run(map, "task1", Effect.never) * * // Check if keys exist using Effect * const exists1 = yield* FiberMap.has(map, "task1") @@ -763,15 +928,16 @@ export const hasUnsafe: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const has: { /** - * Check if a key exists in the FiberMap. + * Checks whether a key exists in the FiberMap. * This is the Effect-wrapped version of `hasUnsafe`. * - * @example + * **Example** (Checking if a key exists) + * * ```ts * import { Effect, FiberMap } from "effect" * @@ -779,7 +945,7 @@ export const has: { * const map = yield* FiberMap.make() * * // Add a fiber to the map - * yield* FiberMap.run(map, "task1", Effect.succeed("Hello")) + * yield* FiberMap.run(map, "task1", Effect.never) * * // Check if keys exist using Effect * const exists1 = yield* FiberMap.has(map, "task1") @@ -790,15 +956,16 @@ export const has: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (key: K): (self: FiberMap) => Effect.Effect /** - * Check if a key exists in the FiberMap. + * Checks whether a key exists in the FiberMap. * This is the Effect-wrapped version of `hasUnsafe`. * - * @example + * **Example** (Checking if a key exists) + * * ```ts * import { Effect, FiberMap } from "effect" * @@ -806,7 +973,7 @@ export const has: { * const map = yield* FiberMap.make() * * // Add a fiber to the map - * yield* FiberMap.run(map, "task1", Effect.succeed("Hello")) + * yield* FiberMap.run(map, "task1", Effect.never) * * // Check if keys exist using Effect * const exists1 = yield* FiberMap.has(map, "task1") @@ -817,8 +984,8 @@ export const has: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (self: FiberMap, key: K): Effect.Effect } = dual( @@ -827,9 +994,10 @@ export const has: { ) /** - * Remove a fiber from the FiberMap, interrupting it if it exists. + * Removes a fiber from the FiberMap, interrupting it if it exists. + * + * **Example** (Removing a fiber) * - * @example * ```ts * import { Effect, FiberMap } from "effect" * @@ -849,14 +1017,15 @@ export const has: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const remove: { /** - * Remove a fiber from the FiberMap, interrupting it if it exists. + * Removes a fiber from the FiberMap, interrupting it if it exists. + * + * **Example** (Removing a fiber) * - * @example * ```ts * import { Effect, FiberMap } from "effect" * @@ -876,14 +1045,15 @@ export const remove: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (key: K): (self: FiberMap) => Effect.Effect /** - * Remove a fiber from the FiberMap, interrupting it if it exists. + * Removes a fiber from the FiberMap, interrupting it if it exists. + * + * **Example** (Removing a fiber) * - * @example * ```ts * import { Effect, FiberMap } from "effect" * @@ -903,15 +1073,16 @@ export const remove: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (self: FiberMap, key: K): Effect.Effect } = dual< /** - * Remove a fiber from the FiberMap, interrupting it if it exists. + * Removes a fiber from the FiberMap, interrupting it if it exists. + * + * **Example** (Removing a fiber) * - * @example * ```ts * import { Effect, FiberMap } from "effect" * @@ -931,14 +1102,15 @@ export const remove: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (key: K) => (self: FiberMap) => Effect.Effect, /** - * Remove a fiber from the FiberMap, interrupting it if it exists. + * Removes a fiber from the FiberMap, interrupting it if it exists. + * + * **Example** (Removing a fiber) * - * @example * ```ts * import { Effect, FiberMap } from "effect" * @@ -958,8 +1130,8 @@ export const remove: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (self: FiberMap, key: K) => Effect.Effect >(2, (self, key) => @@ -975,9 +1147,10 @@ export const remove: { })) /** - * Remove all fibers from the FiberMap, interrupting them. + * Removes all fibers from the FiberMap, interrupting them. + * + * **Example** (Clearing all fibers) * - * @example * ```ts * import { Effect, FiberMap } from "effect" * @@ -998,8 +1171,8 @@ export const remove: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const clear = (self: FiberMap): Effect.Effect => Effect.suspend(() => { @@ -1020,10 +1193,15 @@ const constInterruptedFiber = (function() { })() /** - * Run an Effect and add the forked fiber to the FiberMap. - * When the fiber completes, it will be removed from the FiberMap. + * Forks an Effect and stores the resulting fiber in the `FiberMap` under a key. + * + * **Details** + * + * When the fiber completes, it is removed from the map. If the key already has + * a fiber, the previous fiber is interrupted unless `onlyIfMissing` is set. + * + * **Example** (Forking effects into a map) * - * @example * ```ts * import { Effect, Fiber, FiberMap } from "effect" * @@ -1034,24 +1212,29 @@ const constInterruptedFiber = (function() { * const fiber1 = yield* FiberMap.run(map, "task1", Effect.succeed("Hello")) * const fiber2 = yield* FiberMap.run(map, "task2", Effect.succeed("World")) * - * // Wait for the results - * const result1 = yield* Fiber.await(fiber1) - * const result2 = yield* Fiber.await(fiber2) + * // Join the fibers to get their successful values + * const result1 = yield* Fiber.join(fiber1) + * const result2 = yield* Fiber.join(fiber2) * * console.log(result1, result2) // "Hello", "World" * console.log(yield* FiberMap.size(map)) // 0 (fibers are removed after completion) * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ 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. + * Forks an Effect and stores the resulting fiber in the `FiberMap` under a key. + * + * **Details** + * + * When the fiber completes, it is removed from the map. If the key already has + * a fiber, the previous fiber is interrupted unless `onlyIfMissing` is set. + * + * **Example** (Forking effects into a map) * - * @example * ```ts * import { Effect, Fiber, FiberMap } from "effect" * @@ -1062,17 +1245,17 @@ export const run: { * const fiber1 = yield* FiberMap.run(map, "task1", Effect.succeed("Hello")) * const fiber2 = yield* FiberMap.run(map, "task2", Effect.succeed("World")) * - * // Wait for the results - * const result1 = yield* Fiber.await(fiber1) - * const result2 = yield* Fiber.await(fiber2) + * // Join the fibers to get their successful values + * const result1 = yield* Fiber.join(fiber1) + * const result2 = yield* Fiber.join(fiber2) * * console.log(result1, result2) // "Hello", "World" * console.log(yield* FiberMap.size(map)) // 0 (fibers are removed after completion) * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ ( self: FiberMap, @@ -1086,10 +1269,15 @@ export const run: { effect: Effect.Effect ) => Effect.Effect, never, R> /** - * Run an Effect and add the forked fiber to the FiberMap. - * When the fiber completes, it will be removed from the FiberMap. + * Forks an Effect and stores the resulting fiber in the `FiberMap` under a key. + * + * **Details** + * + * When the fiber completes, it is removed from the map. If the key already has + * a fiber, the previous fiber is interrupted unless `onlyIfMissing` is set. + * + * **Example** (Forking effects into a map) * - * @example * ```ts * import { Effect, Fiber, FiberMap } from "effect" * @@ -1100,17 +1288,17 @@ export const run: { * const fiber1 = yield* FiberMap.run(map, "task1", Effect.succeed("Hello")) * const fiber2 = yield* FiberMap.run(map, "task2", Effect.succeed("World")) * - * // Wait for the results - * const result1 = yield* Fiber.await(fiber1) - * const result2 = yield* Fiber.await(fiber2) + * // Join the fibers to get their successful values + * const result1 = yield* Fiber.join(fiber1) + * const result2 = yield* Fiber.join(fiber2) * * console.log(result1, result2) // "Hello", "World" * console.log(yield* FiberMap.size(map)) // 0 (fibers are removed after completion) * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ ( self: FiberMap, @@ -1153,11 +1341,18 @@ const runImpl = ( }) /** - * Capture a Runtime and use it to fork Effect's, adding the forked fibers to the FiberMap. + * Captures the current runtime and returns a function for forking effects into + * an existing `FiberMap`. + * + * **Details** + * + * Each call stores the forked fiber under the supplied key. If that key already + * has a fiber, the previous fiber is interrupted unless `onlyIfMissing` is set. + * + * **Example** (Capturing a runtime) * - * @example * ```ts - * import { Effect, FiberMap, Context } from "effect" + * import { Context, Effect, FiberMap } from "effect" * * interface Users { * readonly _: unique symbol @@ -1171,15 +1366,15 @@ const runImpl = ( * const run = yield* FiberMap.runtime(map)() * * // run some effects and add the fibers to the map - * run("effect-a", Effect.andThen(Users.asEffect(), (_) => _.getAll)) - * run("effect-b", Effect.andThen(Users.asEffect(), (_) => _.getAll)) + * 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 * @category combinators + * @since 2.0.0 */ export const runtime: ( self: FiberMap @@ -1224,10 +1419,18 @@ export const runtime: ( ) /** - * Capture a Runtime and use it to fork Effect's, adding the forked fibers to the FiberMap. - * Returns a Promise instead of a Fiber for convenience. + * Captures the current runtime and returns a function for running effects in + * an existing `FiberMap` as Promises. + * + * **Details** + * + * Each call stores the forked fiber under the supplied key, interrupting any + * previous fiber for that key unless `onlyIfMissing` is set. The Promise + * resolves with the effect's success value or rejects with the squashed failure + * cause. + * + * **Example** (Running effects as promises) * - * @example * ```ts * import { Effect, FiberMap } from "effect" * @@ -1247,8 +1450,8 @@ export const runtime: ( * }) * ``` * - * @since 3.13.0 * @category combinators + * @since 3.13.0 */ export const runtimePromise = (self: FiberMap): () => Effect.Effect< ( @@ -1287,9 +1490,10 @@ export const runtimePromise = (self: FiberMap): () ) /** - * Get the number of fibers currently in the FiberMap. + * Gets the number of fibers currently in the FiberMap. + * + * **Example** (Checking the map size) * - * @example * ```ts * import { Effect, FiberMap } from "effect" * @@ -1306,17 +1510,24 @@ export const runtimePromise = (self: FiberMap): () * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const size = (self: FiberMap): Effect.Effect => 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. + * Waits for the `FiberMap` to fail or close. + * + * **Details** + * + * The returned Effect fails with the first managed fiber failure that is not + * ignored by the map's interruption rules. Normal successful completion + * removes fibers from the map; use `awaitEmpty` to wait until the map has no + * fibers. + * + * **Example** (Joining failing fibers) * - * @example * ```ts * import { Effect, FiberMap } from "effect" * @@ -1329,17 +1540,18 @@ export const size = (self: FiberMap): Effect.Effect => * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const join = (self: FiberMap): Effect.Effect => Deferred.await(self.deferred as Deferred.Deferred) /** - * Wait for the FiberMap to be empty. + * Waits for the FiberMap to be empty. * This will wait for all currently running fibers to complete. * - * @example + * **Example** (Waiting for an empty map) + * * ```ts * import { Effect, FiberMap } from "effect" * @@ -1360,8 +1572,8 @@ export const join = (self: FiberMap): Effect.Effect = * }) * ``` * - * @since 3.13.0 * @category combinators + * @since 3.13.0 */ export const awaitEmpty = (self: FiberMap): Effect.Effect => Effect.whileLoop({ diff --git a/.opencode/node_modules/effect/src/FiberSet.ts b/.opencode/node_modules/effect/src/FiberSet.ts index 65b885e7bd13c9b4c74098c05d4f0892c29ec01f..4a20ebccc1258c939510ab335e749ea09b59b565 100644 --- a/.opencode/node_modules/effect/src/FiberSet.ts +++ b/.opencode/node_modules/effect/src/FiberSet.ts @@ -1,4 +1,11 @@ /** + * Manages many fibers together inside one scope. + * + * A `FiberSet` tracks running fibers, removes each fiber when it + * completes, and interrupts all still-running fibers when the owning scope + * closes. This module includes scoped runtime constructors plus helpers for + * adding, clearing, running, counting, joining, and waiting for managed fibers. + * * @since 2.0.0 */ import * as Cause from "./Cause.ts" @@ -22,7 +29,8 @@ const TypeId = "~effect/FiberSet" * A FiberSet is a collection of fibers that can be managed together. * When the associated Scope is closed, all fibers in the set will be interrupted. * - * @example + * **Example** (Managing fibers in a set) + * * ```ts * import { Effect, FiberSet } from "effect" * @@ -38,8 +46,8 @@ const TypeId = "~effect/FiberSet" * }) * ``` * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface FiberSet extends Pipeable, Inspectable.Inspectable, Iterable> @@ -55,11 +63,10 @@ export interface FiberSet } /** - * Checks if a value is a FiberSet. + * Checks whether a value is a FiberSet. + * + * **Example** (Checking if a value is a FiberSet) * - * @since 2.0.0 - * @category refinements - * @example * ```ts * import { Effect, FiberSet } from "effect" * @@ -70,6 +77,9 @@ export interface FiberSet * console.log(FiberSet.isFiberSet({})) // false * }) * ``` + * + * @category refinements + * @since 2.0.0 */ export const isFiberSet = (u: unknown): u is FiberSet => Predicate.hasProperty(u, TypeId) @@ -101,13 +111,17 @@ const makeUnsafe = ( } /** - * A FiberSet can be used to store a collection of fibers. - * When the associated Scope is closed, all fibers in the set will be interrupted. + * Creates a scoped `FiberSet` for storing fibers. * - * You can add fibers to the set using `FiberSet.add` or `FiberSet.run`, and the fibers will - * be automatically removed from the FiberSet when they complete. + * **Details** + * + * When the associated Scope is closed, all fibers in the set will be + * interrupted. You can add fibers to the set using `FiberSet.add` or + * `FiberSet.run`, and the fibers will be automatically removed from the + * FiberSet when they complete. + * + * **Example** (Creating a scoped FiberSet) * - * @example * ```ts * import { Effect, FiberSet } from "effect" * @@ -124,8 +138,8 @@ const makeUnsafe = ( * ) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const make = (): Effect.Effect, never, Scope.Scope> => Effect.acquireRelease( @@ -143,11 +157,15 @@ export const make = (): Effect.Effect, ) /** - * Create an Effect run function that is backed by a FiberSet. + * Creates a scoped run function that forks effects into a new `FiberSet`. + * + * **Details** + * + * Each call returns the forked fiber and adds it to the set. Managed fibers are + * removed when they complete and are interrupted when the set's scope closes. + * + * **Example** (Creating a scoped runtime) * - * @since 2.0.0 - * @category constructors - * @example * ```ts * import { Effect, Fiber, FiberSet } from "effect" * @@ -164,6 +182,9 @@ export const make = (): Effect.Effect, * console.log(result1, result2) // "hello" "world" * }) * ``` + * + * @category constructors + * @since 2.0.0 */ export const makeRuntime = (): Effect.Effect< (( @@ -179,10 +200,22 @@ export const makeRuntime = (): Effect.Effec ) /** - * Create an Effect run function that is backed by a FiberSet. - * The returned run function will return Promise's. + * Creates a scoped run function that forks effects into a new `FiberSet` and + * returns a `Promise` for each effect result. + * + * **When to use** + * + * Use when many scoped fibers should be tracked as a set while exposing each + * result through Promise-based APIs. + * + * **Details** + * + * Managed fibers are removed when they complete and are interrupted when the + * set's scope closes. Each Promise resolves with the effect's success value or + * rejects with the squashed failure cause. + * + * **Example** (Creating a promise runtime) * - * @example * ```ts * import { Effect, FiberSet } from "effect" * @@ -200,8 +233,8 @@ export const makeRuntime = (): Effect.Effec * }) * ``` * - * @since 3.13.0 * @category constructors + * @since 3.13.0 */ export const makeRuntimePromise = (): Effect.Effect< (( @@ -223,10 +256,22 @@ const isInternalInterruption = Filter.toPredicate(Filter.compose( )) /** - * Add a fiber to the FiberSet. When the fiber completes, it will be removed. - * This is the unsafe version that doesn't return an Effect. + * Adds an existing fiber to the `FiberSet` using a synchronous, unsafe + * mutation. + * + * **When to use** + * + * Use when an already forked fiber must be registered immediately and + * synchronous interruption on a closed set is acceptable. + * + * **Details** + * + * When the fiber completes, it is removed from the set. If the set is already + * closed, the supplied fiber is interrupted immediately. Non-interruption + * failures are recorded for `FiberSet.join`. + * + * **Example** (Adding a fiber unsafely) * - * @example * ```ts * import { Effect, FiberSet } from "effect" * @@ -242,15 +287,27 @@ const isInternalInterruption = Filter.toPredicate(Filter.compose( * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ export const addUnsafe: { /** - * Add a fiber to the FiberSet. When the fiber completes, it will be removed. - * This is the unsafe version that doesn't return an Effect. + * Adds an existing fiber to the `FiberSet` using a synchronous, unsafe + * mutation. + * + * **When to use** + * + * Use when an already forked fiber must be registered immediately and + * synchronous interruption on a closed set is acceptable. + * + * **Details** + * + * When the fiber completes, it is removed from the set. If the set is already + * closed, the supplied fiber is interrupted immediately. Non-interruption + * failures are recorded for `FiberSet.join`. + * + * **Example** (Adding a fiber unsafely) * - * @example * ```ts * import { Effect, FiberSet } from "effect" * @@ -266,8 +323,8 @@ export const addUnsafe: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ ( fiber: Fiber.Fiber, @@ -276,10 +333,22 @@ export const addUnsafe: { } | undefined ): (self: FiberSet) => void /** - * Add a fiber to the FiberSet. When the fiber completes, it will be removed. - * This is the unsafe version that doesn't return an Effect. + * Adds an existing fiber to the `FiberSet` using a synchronous, unsafe + * mutation. + * + * **When to use** + * + * Use when an already forked fiber must be registered immediately and + * synchronous interruption on a closed set is acceptable. + * + * **Details** + * + * When the fiber completes, it is removed from the set. If the set is already + * closed, the supplied fiber is interrupted immediately. Non-interruption + * failures are recorded for `FiberSet.join`. + * + * **Example** (Adding a fiber unsafely) * - * @example * ```ts * import { Effect, FiberSet } from "effect" * @@ -295,8 +364,8 @@ export const addUnsafe: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ ( self: FiberSet, @@ -338,9 +407,10 @@ export const addUnsafe: { }) /** - * Add a fiber to the FiberSet. When the fiber completes, it will be removed. + * Adds a fiber to the FiberSet. When the fiber completes, it will be removed. + * + * **Example** (Adding a fiber) * - * @example * ```ts * import { Effect, FiberSet } from "effect" * @@ -356,14 +426,15 @@ export const addUnsafe: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const add: { /** - * Add a fiber to the FiberSet. When the fiber completes, it will be removed. + * Adds a fiber to the FiberSet. When the fiber completes, it will be removed. + * + * **Example** (Adding a fiber) * - * @example * ```ts * import { Effect, FiberSet } from "effect" * @@ -379,8 +450,8 @@ export const add: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ ( fiber: Fiber.Fiber, @@ -389,9 +460,10 @@ export const add: { } | undefined ): (self: FiberSet) => Effect.Effect /** - * Add a fiber to the FiberSet. When the fiber completes, it will be removed. + * Adds a fiber to the FiberSet. When the fiber completes, it will be removed. + * + * **Example** (Adding a fiber) * - * @example * ```ts * import { Effect, FiberSet } from "effect" * @@ -407,8 +479,8 @@ export const add: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ ( self: FiberSet, @@ -429,9 +501,10 @@ export const add: { ) /** - * Interrupt all fibers in the FiberSet and clear the set. + * Interrupts all fibers in the `FiberSet` and clears the set. + * + * **Example** (Clearing all fibers) * - * @example * ```ts * import { Effect, FiberSet } from "effect" * @@ -451,8 +524,8 @@ export const add: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const clear = (self: FiberSet): Effect.Effect => Effect.suspend(() => { @@ -473,10 +546,11 @@ const constInterruptedFiber = (function() { })() /** - * Fork an Effect and add the forked fiber to the FiberSet. + * Forks an Effect and add the forked fiber to the FiberSet. * When the fiber completes, it will be removed from the FiberSet. * - * @example + * **Example** (Forking effects into a set) + * * ```ts * import { Effect, Fiber, FiberSet } from "effect" * @@ -495,15 +569,16 @@ const constInterruptedFiber = (function() { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const run: { /** - * Fork an Effect and add the forked fiber to the FiberSet. + * Forks an Effect and add the forked fiber to the FiberSet. * When the fiber completes, it will be removed from the FiberSet. * - * @example + * **Example** (Forking effects into a set) + * * ```ts * import { Effect, Fiber, FiberSet } from "effect" * @@ -522,8 +597,8 @@ export const run: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ ( self: FiberSet, @@ -535,10 +610,11 @@ export const run: { effect: Effect.Effect ) => Effect.Effect, never, R> /** - * Fork an Effect and add the forked fiber to the FiberSet. + * Forks an Effect and add the forked fiber to the FiberSet. * When the fiber completes, it will be removed from the FiberSet. * - * @example + * **Example** (Forking effects into a set) + * * ```ts * import { Effect, Fiber, FiberSet } from "effect" * @@ -557,8 +633,8 @@ export const run: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ ( self: FiberSet, @@ -594,11 +670,12 @@ const runImpl = ( }) /** - * Capture a Runtime and use it to fork Effect's, adding the forked fibers to the FiberSet. + * Captures a `Runtime` and uses it to fork effects into the `FiberSet`. + * + * **Example** (Capturing a runtime) * - * @example * ```ts - * import { Effect, FiberSet, Context } from "effect" + * import { Context, Effect, FiberSet } from "effect" * * interface Users { * readonly _: unique symbol @@ -612,14 +689,14 @@ const runImpl = ( * const run = yield* FiberSet.runtime(set)() * * // run some effects and add the fibers to the set - * run(Effect.andThen(Users.asEffect(), (_) => _.getAll)) + * run(Effect.andThen(Users, (_) => _.getAll)) * }).pipe( * Effect.scoped // The fibers will be interrupted when the scope is closed * ) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const runtime: ( self: FiberSet @@ -654,11 +731,20 @@ export const runtime: ( ) /** - * Capture a Runtime and use it to fork Effect's, adding the forked fibers to the FiberSet. + * Captures a `Runtime` and returns a Promise-based runner that forks effects + * into the `FiberSet`. * - * The returned run function will return Promise's. + * **When to use** + * + * Use when you need to bridge effects to `Promise` values while still tracking + * their fibers in a `FiberSet`. + * + * **Details** + * + * The returned run function returns a `Promise` for each effect result. + * + * **Example** (Running effects as promises) * - * @example * ```ts * import { Effect, FiberSet } from "effect" * @@ -677,8 +763,10 @@ export const runtime: ( * }) * ``` * - * @since 3.13.0 + * @see {@link runtime} for a runner that returns the forked `Fiber` + * * @category combinators + * @since 3.13.0 */ export const runtimePromise = (self: FiberSet): () => Effect.Effect< ( @@ -712,9 +800,10 @@ export const runtimePromise = (self: FiberSet): () => Eff ) /** - * Get the number of fibers currently in the FiberSet. + * Gets the number of fibers currently in the FiberSet. + * + * **Example** (Checking the set size) * - * @example * ```ts * import { Effect, FiberSet } from "effect" * @@ -731,17 +820,18 @@ export const runtimePromise = (self: FiberSet): () => Eff * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const size = (self: FiberSet): Effect.Effect => Effect.sync(() => self.state._tag === "Closed" ? 0 : self.state.backing.size) /** - * Join all fibers in the FiberSet. If any of the Fiber's in the set terminate with a failure, + * Joins all fibers in the FiberSet. If any fiber in the set terminates with a failure, * the returned Effect will terminate with the first failure that occurred. * - * @example + * **Example** (Joining failing fibers) + * * ```ts * import { Effect, FiberSet } from "effect" * @@ -754,16 +844,17 @@ export const size = (self: FiberSet): Effect.Effect => * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const join = (self: FiberSet): Effect.Effect => Deferred.await(self.deferred as Deferred.Deferred) /** - * Wait until the fiber set is empty. + * Waits until the fiber set is empty. + * + * **Example** (Waiting for an empty set) * - * @example * ```ts * import { Effect, FiberSet } from "effect" * @@ -781,8 +872,8 @@ export const join = (self: FiberSet): Effect.Effect => * }) * ``` * - * @since 3.13.0 * @category combinators + * @since 3.13.0 */ export const awaitEmpty = (self: FiberSet): Effect.Effect => Effect.whileLoop({ diff --git a/.opencode/node_modules/effect/src/FileSystem.ts b/.opencode/node_modules/effect/src/FileSystem.ts index a777e3a45a393e0a1299c4b94c24cee351c22691..0b4b191e5dab15429bb6072c3a48fa73fc0429c2 100644 --- a/.opencode/node_modules/effect/src/FileSystem.ts +++ b/.opencode/node_modules/effect/src/FileSystem.ts @@ -1,37 +1,12 @@ /** - * This module provides a comprehensive file system abstraction that supports both synchronous - * and asynchronous file operations through Effect. It includes utilities for file I/O, directory - * management, permissions, timestamps, and file watching with proper error handling. + * Defines the portable file system service for Effect programs. * - * The `FileSystem` interface provides a cross-platform abstraction over file system operations, - * allowing you to work with files and directories in a functional, composable way. All operations - * return `Effect` values that can be composed, transformed, and executed safely. - * - * @example - * ```ts - * import { Console, Effect, FileSystem } from "effect" - * - * const program = Effect.gen(function*() { - * const fs = yield* FileSystem.FileSystem - * - * // Create a directory - * yield* fs.makeDirectory("./temp", { recursive: true }) - * - * // Write a file - * yield* fs.writeFileString("./temp/hello.txt", "Hello, World!") - * - * // Read the file back - * const content = yield* fs.readFileString("./temp/hello.txt") - * yield* Console.log("File content:", content) - * - * // Get file information - * const stats = yield* fs.stat("./temp/hello.txt") - * yield* Console.log("File size:", stats.size) - * - * // Clean up - * yield* fs.remove("./temp", { recursive: true }) - * }) - * ``` + * `FileSystem` is the boundary between Effect code and the host file system. + * Platform packages provide concrete layers, while this module defines the + * operations for reading, writing, inspecting, streaming, and watching files. + * Operations return `Effect`, `Stream`, or `Sink` values and fail with + * `PlatformError`. The module also includes file handles, size helpers, open + * flags, watch events, and the watch backend service. * * @since 4.0.0 */ @@ -55,11 +30,14 @@ const TypeId = "~effect/platform/FileSystem" /** * Core interface for file system operations in Effect. * + * **Details** + * * The FileSystem interface provides a comprehensive set of file and directory operations * that work cross-platform. All operations return Effect values that can be composed, * transformed, and executed safely with proper error handling. * - * @example + * **Example** (Accessing file system operations) + * * ```ts * import { Console, Effect, FileSystem } from "effect" * @@ -85,14 +63,14 @@ const TypeId = "~effect/platform/FileSystem" * }) * ``` * + * @category models * @since 4.0.0 - * @category model */ export interface FileSystem { readonly [TypeId]: typeof TypeId /** - * Check if a file can be accessed. + * Checks whether a file can be accessed. * You can optionally specify the level of access to check for. */ readonly access: ( @@ -106,6 +84,8 @@ export interface FileSystem { /** * Copy a file or directory from `fromPath` to `toPath`. * + * **Details** + * * Equivalent to `cp -r`. */ readonly copy: ( @@ -139,7 +119,7 @@ export interface FileSystem { gid: number ) => Effect.Effect /** - * Check if a path exists. + * Checks whether a path exists. */ readonly exists: ( path: string @@ -165,6 +145,8 @@ export interface FileSystem { /** * Create a temporary directory. * + * **Details** + * * By default the directory will be created inside the system's default * temporary directory, but you can specify a different location by setting * the `directory` option. @@ -179,6 +161,8 @@ export interface FileSystem { /** * Create a temporary directory inside a scope. * + * **Details** + * * Functionally equivalent to `makeTempDirectory`, but the directory will be * automatically deleted when the scope is closed. */ @@ -199,6 +183,8 @@ export interface FileSystem { /** * Create a temporary file inside a scope. * + * **Details** + * * Functionally equivalent to `makeTempFile`, but the file will be * automatically deleted when the scope is closed. */ @@ -210,6 +196,8 @@ export interface FileSystem { /** * Open a file at `path` with the specified `options`. * + * **Details** + * * The file handle will be automatically closed when the scope is closed. */ readonly open: ( @@ -222,6 +210,8 @@ export interface FileSystem { /** * List the contents of a directory. * + * **Details** + * * You can recursively list the contents of nested directories by setting the * `recursive` option. */ @@ -298,6 +288,8 @@ export interface FileSystem { /** * Create a readable `Stream` for the specified `path`. * + * **Details** + * * Changing the `bufferSize` option will change the internal buffer size of * the stream. It defaults to `4`. * @@ -369,12 +361,15 @@ export interface FileSystem { /** * Represents a file size in bytes using a branded bigint. * + * **Details** + * * This type ensures type safety when working with file sizes, preventing * accidental mixing of regular numbers with size values. The underlying * bigint allows for handling very large file sizes beyond JavaScript's * number precision limits. * - * @example + * **Example** (Creating branded file sizes) + * * ```ts * import { Effect, FileSystem } from "effect" * @@ -383,26 +378,28 @@ export interface FileSystem { * const largeFile = FileSystem.Size(BigInt("9007199254740992")) // Very large * * // Use with file operations - * const truncateToSize = (path: string, size: FileSystem.Size) => - * Effect.gen(function*() { - * const fs = yield* FileSystem.FileSystem - * return fs.truncate(path, size) - * }) + * const truncateToSize = Effect.fnUntraced(function*(path: string, size: FileSystem.Size) { + * const fs = yield* FileSystem.FileSystem + * return yield* fs.truncate(path, size) + * }) * ``` * - * @since 4.0.0 * @category sizes + * @since 4.0.0 */ export type Size = Brand.Branded /** * Input type for size parameters that accepts multiple numeric types. * + * **Details** + * * This union type allows file system operations to accept size values in * different formats for convenience, which are then normalized to the * branded `Size` type internally. * - * @example + * **Example** (Using size inputs) + * * ```ts * import { Effect, FileSystem } from "effect" * @@ -416,19 +413,22 @@ export type Size = Brand.Branded * }) * ``` * - * @since 4.0.0 * @category sizes + * @since 4.0.0 */ export type SizeInput = bigint | number | Size /** * Creates a `Size` from various numeric input types. * + * **Details** + * * Converts numbers, bigints, or existing Size values into a properly * branded Size type. This function handles the conversion and ensures * type safety for file size operations. * - * @example + * **Example** (Converting size inputs) + * * ```ts * import { Effect, FileSystem } from "effect" * @@ -452,18 +452,21 @@ export type SizeInput = bigint | number | Size * }) * ``` * - * @since 4.0.0 * @category sizes + * @since 4.0.0 */ export const Size = (bytes: SizeInput): Size => typeof bytes === "bigint" ? bytes as Size : BigInt(bytes) as Size /** * Creates a `Size` representing kilobytes (1024 bytes). * + * **Details** + * * Converts a number of kilobytes to the equivalent size in bytes. * Uses binary kilobytes (1024 bytes) rather than decimal (1000 bytes). * - * @example + * **Example** (Creating kibibyte sizes) + * * ```ts * import { Effect, FileSystem } from "effect" * @@ -482,18 +485,21 @@ export const Size = (bytes: SizeInput): Size => typeof bytes === "bigint" ? byte * }) * ``` * - * @since 4.0.0 * @category sizes + * @since 4.0.0 */ export const KiB = (n: number): Size => Size(n * 1024) /** * Creates a `Size` representing mebibytes (1024² bytes). * + * **Details** + * * Converts a number of mebibytes to the equivalent size in bytes. * Uses binary mebibytes (1,048,576 bytes) rather than decimal megabytes. * - * @example + * **Example** (Creating mebibyte sizes) + * * ```ts * import { Effect, FileSystem } from "effect" * @@ -516,48 +522,56 @@ export const KiB = (n: number): Size => Size(n * 1024) * }) * ``` * - * @since 4.0.0 * @category sizes + * @since 4.0.0 */ export const MiB = (n: number): Size => Size(n * 1024 * 1024) /** * Creates a `Size` representing gibibytes (1024³ bytes). * + * **Details** + * * Converts a number of gibibytes to the equivalent size in bytes. * Uses binary gibibytes (1,073,741,824 bytes) rather than decimal gigabytes. * - * @example + * **Example** (Creating gibibyte sizes) + * * ```ts - * import { Console, Effect, FileSystem } from "effect" + * import { Effect, FileSystem } from "effect" * * const program = Effect.gen(function*() { * const fs = yield* FileSystem.FileSystem * - * // Check available space before creating large files - * const stats = yield* fs.stat(".") - * const requiredSpace = FileSystem.GiB(5) + * // Use GiB values as size thresholds + * const maxArchiveSize = FileSystem.GiB(1) + * console.log(maxArchiveSize.toString()) // "1073741824" + * + * const tempFile = yield* fs.makeTempFile({ prefix: "archive-" }) + * yield* fs.writeFileString(tempFile, "backup data") * - * // Create a large temporary file - * const tempFile = yield* fs.makeTempFile({ prefix: "large-" }) - * yield* fs.truncate(tempFile, FileSystem.GiB(1)) // 1 GiB file + * const info = yield* fs.stat(tempFile) + * console.log(info.size < maxArchiveSize) // true * - * yield* Console.log(`Created ${tempFile} with 1 GiB size`) + * yield* fs.remove(tempFile) * }) * ``` * - * @since 4.0.0 * @category sizes + * @since 4.0.0 */ export const GiB = (n: number): Size => Size(n * 1024 * 1024 * 1024) /** * Creates a `Size` representing tebibytes (1024⁴ bytes). * + * **Details** + * * Converts a number of tebibytes to the equivalent size in bytes. * Uses binary tebibytes (1,099,511,627,776 bytes) rather than decimal terabytes. * - * @example + * **Example** (Creating tebibyte sizes) + * * ```ts * import { Console, Effect, FileSystem } from "effect" * @@ -579,8 +593,8 @@ export const GiB = (n: number): Size => Size(n * 1024 * 1024 * 1024) * }) * ``` * - * @since 4.0.0 * @category sizes + * @since 4.0.0 */ export const TiB = (n: number): Size => Size(n * 1024 * 1024 * 1024 * 1024) @@ -590,11 +604,14 @@ const bigintPiB = bigint1024 * bigint1024 * bigint1024 * bigint1024 * bigint1024 /** * Creates a `Size` representing pebibytes (1024⁵ bytes). * + * **Details** + * * Converts a number of pebibytes to the equivalent size in bytes. * Uses binary pebibytes (1,125,899,906,842,624 bytes) rather than decimal petabytes. * This function uses BigInt arithmetic to handle the very large numbers involved. * - * @example + * **Example** (Creating pebibyte sizes) + * * ```ts * import { Console, Effect, FileSystem } from "effect" * @@ -615,14 +632,16 @@ const bigintPiB = bigint1024 * bigint1024 * bigint1024 * bigint1024 * bigint1024 * }) * ``` * - * @since 4.0.0 * @category sizes + * @since 4.0.0 */ export const PiB = (n: number): Size => Size(BigInt(n) * bigintPiB) /** * File open flags that determine how a file is opened and what operations are allowed. * + * **Details** + * * These flags correspond to standard POSIX file open modes and control the file access * permissions and behavior when opening files. * @@ -637,7 +656,8 @@ export const PiB = (n: number): Size => Size(BigInt(n) * bigintPiB) * - `"a+"` - Read/write. Appends to file or creates new file. * - `"ax+"` - Like 'a+' but fails if file exists. * - * @example + * **Example** (Opening files with flags) + * * ```ts * import { Effect, FileSystem } from "effect" * @@ -658,8 +678,8 @@ export const PiB = (n: number): Size => Size(BigInt(n) * bigintPiB) * }) * ``` * + * @category models * @since 4.0.0 - * @category model */ export type OpenFlag = | "r" @@ -674,12 +694,19 @@ export type OpenFlag = | "ax+" /** - * The service identifier for the FileSystem service. + * Service tag for platform file-system operations. + * + * **When to use** + * + * Use to access or provide operations for files, directories, permissions, + * streams, and sinks through the Effect context. + * + * **Details** * * This key is used to provide and access the FileSystem service in the Effect context. - * Use this to inject file system implementations or access file system operations. * - * @example + * **Example** (Accessing and providing FileSystem) + * * ```ts * import { Effect, FileSystem } from "effect" * @@ -708,20 +735,31 @@ export type OpenFlag = * ) * ``` * + * @category services * @since 4.0.0 - * @category tag */ export const FileSystem: Context.Service = Context.Service("effect/platform/FileSystem") /** * Creates a FileSystem implementation from a partial implementation. * + * **When to use** + * + * Use to build a concrete `FileSystem` service from platform-specific core + * operations while deriving the convenience methods that can be implemented + * from them. + * + * **Details** + * * This function takes a partial FileSystem implementation and automatically provides * default implementations for `exists`, `readFileString`, `stream`, `sink`, and * `writeFileString` methods based on the provided core methods. * + * @see {@link makeNoop} for a testing stub that accepts method overrides without requiring a complete implementation + * @see {@link layerNoop} for providing a no-op `FileSystem` as a `Layer` in tests + * + * @category constructors * @since 4.0.0 - * @category constructor */ export const make = ( impl: Omit @@ -811,16 +849,17 @@ const notFound = (method: string, path: string) => }) /** - * Creates a no-op FileSystem implementation for testing purposes. + * Creates a stub `FileSystem` implementation for tests. + * + * **Details** * - * This function creates a FileSystem where most operations fail with "NotFound" errors, - * except for operations that can be safely stubbed. You can override specific methods - * by providing them in the `fileSystem` parameter. + * By default, `exists` returns `false`, `remove` succeeds, many file operations + * fail with `PlatformError` `NotFound`, and temporary-directory/file operations + * die as not implemented. Pass method overrides to provide the behavior needed + * by a specific test without touching the real file system. * - * This is useful for testing scenarios where you want to control specific file system - * behaviors without affecting the actual file system. + * **Example** (Creating a no-op FileSystem) * - * @example * ```ts * import { Effect, FileSystem, PlatformError } from "effect" * @@ -857,8 +896,8 @@ const notFound = (method: string, path: string) => * ) * ``` * + * @category constructors * @since 4.0.0 - * @category constructor */ export const makeNoop = (fileSystem: Partial): FileSystem => FileSystem.of({ @@ -956,10 +995,13 @@ export const makeNoop = (fileSystem: Partial): FileSystem => /** * Creates a Layer that provides a no-op FileSystem implementation for testing. * + * **Details** + * * This is a convenience function that wraps `makeNoop` in a Layer, making it easy * to provide the test filesystem to your Effect programs. * - * @example + * **Example** (Providing a no-op FileSystem layer) + * * ```ts * import { Effect, FileSystem } from "effect" * @@ -979,37 +1021,62 @@ export const makeNoop = (fileSystem: Partial): FileSystem => * const testProgram = Effect.provide(program, testLayer) * ``` * - * @since 4.0.0 * @category layers + * @since 4.0.0 */ export const layerNoop = (fileSystem: Partial): Layer.Layer => Layer.succeed(FileSystem)(makeNoop(fileSystem)) /** + * Runtime type identifier attached to `FileSystem.File` handles and used by + * `isFile` to recognize them. + * + * **Details** + * + * This marker is part of the runtime representation of file handles. Prefer + * `isFile` when narrowing unknown values. + * + * @see {@link File} for the open file handle shape that carries this marker + * @see {@link isFile} for the public guard that checks this marker + * + * @category type IDs * @since 4.0.0 - * @category File */ export const FileTypeId = "~effect/platform/FileSystem/File" /** - * Type guard to check if a value is a File instance. + * Returns `true` if a value is a `File` handle by checking for the + * `FileTypeId` marker. * - * This function determines whether the provided value is a valid File - * instance by checking for the presence of the File type identifier. + * **When to use** * + * Use when accepting an unknown value and you need to narrow it to a `File` + * before calling file-handle operations. + * + * **Details** + * + * This is a structural marker check. It does not validate the marker value or + * the shape of the file handle. + * + * @see {@link File} for the file-handle interface narrowed by this guard + * @see {@link FileTypeId} for the runtime marker checked by this guard + * + * @category file * @since 4.0.0 - * @category File */ export const isFile = (u: unknown): u is File => hasProperty(u, FileTypeId) /** * Interface representing an open file handle. * + * **Details** + * * Provides low-level file operations including reading, writing, seeking, * and retrieving file information. File handles are automatically managed * within scoped operations to ensure proper cleanup. * - * @example + * **Example** (Working with file handles) + * * ```ts * import { Console, Effect, FileSystem } from "effect" * @@ -1040,8 +1107,8 @@ export const isFile = (u: unknown): u is File => hasProperty(u, FileTypeId) * }) * ``` * + * @category file * @since 4.0.0 - * @category File */ export interface File { readonly [FileTypeId]: typeof FileTypeId @@ -1057,29 +1124,35 @@ export interface File { } /** + * Namespace containing types associated with open file handles, including file + * descriptors, entry kinds, and stat information. + * * @since 4.0.0 - * @category File */ export declare namespace File { /** * Branded type for file descriptors. * + * **Details** + * * File descriptors are numeric handles used by the operating system * to identify open files. The branded type ensures type safety. * + * @category file * @since 4.0.0 - * @category File */ export type Descriptor = Brand.Branded /** * Enumeration of possible file system entry types. * + * **Details** + * * Represents the different types of entries that can exist in a file system, * from regular files to special device files and symbolic links. * + * @category file * @since 4.0.0 - * @category File */ export type Type = | "File" @@ -1094,36 +1167,47 @@ export declare namespace File { /** * Comprehensive file information structure. * + * **Details** + * * Contains metadata about a file or directory including type, timestamps, * permissions, and size information. This structure is returned by file * stat operations. * - * @example + * **Example** (Inspecting file information) + * * ```ts - * import { Console, Effect, FileSystem, Option } from "effect" + * import { Effect, FileSystem, Option } from "effect" * * const program = Effect.gen(function*() { * const fs = yield* FileSystem.FileSystem * - * const info: FileSystem.File.Info = yield* fs.stat("./data.txt") + * const path = yield* fs.makeTempFile({ prefix: "info-" }) + * yield* fs.writeFileString(path, "hello") * - * yield* Console.log(`File type: ${info.type}`) - * yield* Console.log(`File size: ${info.size} bytes`) - * yield* Console.log(`Mode: ${info.mode.toString(8)}`) // Octal permissions + * const info: FileSystem.File.Info = yield* fs.stat(path) * - * // Handle optional timestamps - * const mtime = Option.getOrElse(info.mtime, () => new Date(0)) - * yield* Console.log(`Modified: ${mtime.toISOString()}`) + * console.log(`File type: ${info.type}`) // "File type: File" + * console.log(`File size: ${info.size} bytes`) // "File size: 5 bytes" + * console.log(`Mode: ${info.mode.toString(8)}`) // Octal permissions + * + * // Handle optional timestamps without inventing a fallback date + * const modified = Option.match(info.mtime, { + * onNone: () => "unavailable", + * onSome: (mtime) => mtime.toISOString() + * }) + * console.log(`Modified: ${modified}`) * * // Check if it's a regular file * if (info.type === "File") { - * yield* Console.log("Processing regular file...") + * console.log("Processing regular file...") // "Processing regular file..." * } + * + * yield* fs.remove(path) * }) * ``` * + * @category file * @since 4.0.0 - * @category File */ export interface Info { readonly type: Type @@ -1144,48 +1228,88 @@ export declare namespace File { } /** - * Creates a branded file descriptor. + * Creates a `File.Descriptor` from a number. + * + * **When to use** + * + * Use to brand an operating-system file descriptor number when implementing a + * `FileSystem` that returns custom `File` handles. * - * File descriptors are integer handles that the operating system uses to identify - * open files. This branded type ensures type safety when working with file descriptors. + * **Details** * + * `File.Descriptor` is a branded integer handle used by operating systems to + * identify open files. + * + * **Gotchas** + * + * This constructor is nominal and does not check that the number is an integer + * or that it refers to an open file descriptor. + * + * @see {@link File.Descriptor} for the branded descriptor type produced by this constructor + * @see {@link File} for file handles that expose a descriptor through `fd` + * + * @category constructors * @since 4.0.0 - * @category constructor */ export const FileDescriptor = Brand.nominal() /** - * Specifies the reference point for seeking within a file. + * Specifies the reference point for seeking within an open file. + * + * **When to use** + * + * Use with `File` handles when positioning the cursor before a read or write + * and the offset must be interpreted from either the start of the file or the + * current cursor. + * + * **Details** * - * - `"start"` - Seek from the beginning of the file - * - `"current"` - Seek from the current position + * - `"start"` seeks from the beginning of the file. + * - `"current"` seeks from the current cursor position. * + * @see {@link File} for the open file handle API whose `seek` method consumes this mode + * + * @category models * @since 4.0.0 - * @category model */ export type SeekMode = "start" | "current" /** - * Represents file system events that can be observed when watching files or directories. + * Represents file system events emitted when watching files or directories. + * + * **When to use** + * + * Use when consuming file system watch streams and pattern matching on `_tag` + * to handle created, updated, or removed paths. + * + * **Details** * + * The union covers create, update, and remove events. Each event carries the + * reported `path`. + * + * @see {@link FileSystem} for the service interface whose `watch` operation emits these events + * + * @category models * @since 4.0.0 - * @category model */ export type WatchEvent = WatchEvent.Create | WatchEvent.Update | WatchEvent.Remove /** + * Namespace containing the concrete event shapes emitted by `FileSystem.watch`. + * * @since 4.0.0 - * @category model */ export declare namespace WatchEvent { /** * Event representing the creation of a new file or directory. * + * **Details** + * * This event is triggered when a new file or directory is created * in the watched location. * + * @category models * @since 4.0.0 - * @category model */ export interface Create { readonly _tag: "Create" @@ -1195,11 +1319,13 @@ export declare namespace WatchEvent { /** * Event representing the modification of an existing file or directory. * + * **Details** + * * This event is triggered when an existing file or directory is * modified in the watched location. * + * @category models * @since 4.0.0 - * @category model */ export interface Update { readonly _tag: "Update" @@ -1209,11 +1335,13 @@ export declare namespace WatchEvent { /** * Event representing the deletion of a file or directory. * + * **Details** + * * This event is triggered when a file or directory is deleted * from the watched location. * + * @category models * @since 4.0.0 - * @category model */ export interface Remove { readonly _tag: "Remove" @@ -1224,11 +1352,14 @@ export declare namespace WatchEvent { /** * Service key for file system watch backend implementations. * + * **Details** + * * This service provides the low-level file watching capabilities that can be * implemented differently on various platforms (e.g., inotify on Linux, * FSEvents on macOS, etc.). * - * @example + * **Example** (Providing a custom watch backend) + * * ```ts * import { Effect, FileSystem, Option, Stream } from "effect" * @@ -1255,8 +1386,8 @@ export declare namespace WatchEvent { * ) * ``` * - * @since 4.0.0 * @category file watcher + * @since 4.0.0 */ export class WatchBackend extends Context.Service Option.Option> diff --git a/.opencode/node_modules/effect/src/Filter.ts b/.opencode/node_modules/effect/src/Filter.ts index 8f12853acbf0843e49b4f11b3adb8cdff3c8bafa..fab9e9e8a8bfaee6cf677f6ba2e5e421a419a691 100644 --- a/.opencode/node_modules/effect/src/Filter.ts +++ b/.opencode/node_modules/effect/src/Filter.ts @@ -1,4 +1,13 @@ /** + * Defines composable checks that can also transform values. + * + * A `Filter` receives an input and returns a `Result`. + * Success means the value passed the filter, and failure means the value was + * filtered out. Filters may also narrow or transform the passing value. This + * module includes constructors from predicates, options, and effects, built-in + * filters for common JavaScript values and tags, helpers for combining filters, + * and conversions to predicates, options, and results. + * * @since 4.0.0 */ import type { Effect } from "./Effect.ts" @@ -12,10 +21,13 @@ import type { EqualsWith, ExcludeTag, ExtractReason, ExtractTag, ReasonTags, Tag /** * Represents a filter function that can transform inputs to outputs or filter them out. * - * A filter takes an input value and either returns a boxed pass value or - * the special `fail` type to indicate the value should be filtered out. + * **Details** + * + * A filter takes an input value and either returns a boxed pass value or the + * special `fail` type to indicate the value should be filtered out. + * + * **Example** (Defining a positive number filter) * - * @example * ```ts * import { Filter, Result } from "effect" * @@ -26,8 +38,8 @@ import type { EqualsWith, ExcludeTag, ExtractReason, ExtractTag, ReasonTags, Tag * console.log(positiveFilter(-3)) // Result.fail(-3) * ``` * + * @category models * @since 4.0.0 - * @category Models */ export interface Filter { (input: Input): Result.Result @@ -36,10 +48,14 @@ export interface Filter { /** * Represents an effectful filter function that can produce Effects. * - * Similar to a regular Filter, but the filtering operation itself can be effectful, - * allowing for asynchronous operations, error handling, and dependency injection. + * **Details** + * + * Similar to a regular `Filter`, but the filtering operation itself can be + * effectful, allowing for asynchronous operations, error handling, and + * dependency injection. + * + * **Example** (Defining an effectful user filter) * - * @example * ```ts * import { Effect, Filter, Result } from "effect" * @@ -60,8 +76,8 @@ export interface Filter { * }) * ``` * + * @category models * @since 4.0.0 - * @category Models */ export interface FilterEffect< in Input, @@ -80,10 +96,13 @@ export interface FilterEffect< /** * Creates a Filter from a function that returns either a `pass` or `fail` value. * + * **Details** + * * This is the primary constructor for creating custom filters. The function * should return either `Result.succeed(value)` or `Result.fail(value)`. * - * @example + * **Example** (Creating custom filters) + * * ```ts * import { Filter, Result } from "effect" * @@ -96,8 +115,8 @@ export interface FilterEffect< * ) * ``` * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const make = ( f: (input: Input) => Result.Result @@ -106,11 +125,14 @@ export const make = ( /** * Creates an effectful Filter from a function that returns an Effect. * + * **Details** + * * This constructor is used when the filtering operation needs to perform - * effectful computations, such as async operations, error handling, or - * accessing services from the environment. + * effectful computations, such as async operations, error handling, or accessing + * services from the environment. + * + * **Example** (Creating effectful filters) * - * @example * ```ts * import { Effect, Filter, Result } from "effect" * @@ -123,26 +145,35 @@ export const make = ( * ) * ``` * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const makeEffect = ( f: (input: Input) => Effect, E, R> ): FilterEffect => f as any /** + * Transforms the failure value produced by a `Filter`, leaving successful + * results unchanged. + * + * @category mapping * @since 4.0.0 - * @category Mapping */ export const mapFail: { /** + * Transforms the failure value produced by a `Filter`, leaving successful + * results unchanged. + * + * @category mapping * @since 4.0.0 - * @category Mapping */ (f: (fail: Fail) => Fail2): (self: Filter) => Filter /** + * Transforms the failure value produced by a `Filter`, leaving successful + * results unchanged. + * + * @category mapping * @since 4.0.0 - * @category Mapping */ (self: Filter, f: (fail: Fail) => Fail2): Filter } = dual(2, ( @@ -164,8 +195,8 @@ export { * Creates a Filter that tries to apply a function and returns `fail` on * error. * + * @category constructors * @since 4.0.0 - * @category Constructors */ try_ as try } @@ -173,11 +204,14 @@ export { /** * Creates a Filter from a predicate or refinement function. * + * **Details** + * * This is a convenient way to create filters from boolean-returning functions. * When the predicate returns true, the input value is passed through unchanged. * When it returns false, the `fail` type is returned. * - * @example + * **Example** (Creating filters from predicates) + * * ```ts * import { Filter, Result } from "effect" * @@ -191,18 +225,21 @@ export { * ) * ``` * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const fromPredicate: { /** * Creates a Filter from a predicate or refinement function. * + * **Details** + * * This is a convenient way to create filters from boolean-returning functions. * When the predicate returns true, the input value is passed through unchanged. * When it returns false, the `fail` type is returned. * - * @example + * **Example** (Creating filters from predicates) + * * ```ts * import { Filter, Result } from "effect" * @@ -216,18 +253,21 @@ export const fromPredicate: { * ) * ``` * + * @category constructors * @since 4.0.0 - * @category Constructors */ (refinement: Predicate.Refinement): Filter>> /** * Creates a Filter from a predicate or refinement function. * + * **Details** + * * This is a convenient way to create filters from boolean-returning functions. * When the predicate returns true, the input value is passed through unchanged. * When it returns false, the `fail` type is returned. * - * @example + * **Example** (Creating filters from predicates) + * * ```ts * import { Filter, Result } from "effect" * @@ -241,18 +281,19 @@ export const fromPredicate: { * ) * ``` * + * @category constructors * @since 4.0.0 - * @category Constructors */ (predicate: Predicate.Predicate): Filter } = (predicate: Predicate.Predicate | Predicate.Refinement): Filter => (input: A) => predicate(input) ? Result.succeed(input as B) : Result.fail(input) /** - * Creates a Filter from a function that returns an Option. + * Creates a `Filter` from a function that returns an `Option`; `Some(value)` + * passes with `value`, and `None` fails with the original input. * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const fromPredicateOption = (predicate: (a: A) => Option.Option): Filter => (input) => { const o = predicate(input) @@ -262,8 +303,16 @@ export const fromPredicateOption = (predicate: (a: A) => Option.Option) /** * Converts a Filter into a predicate function. * + * **When to use** + * + * Use to reuse a `Filter` with APIs that accept only boolean predicates when + * the pass and fail payloads are not needed. + * + * @see {@link toOption} for keeping passed values and discarding failure values + * @see {@link toResult} for preserving both pass and failure values + * + * @category converting * @since 4.0.0 - * @category Constructors */ export const toPredicate = ( self: Filter @@ -273,7 +322,8 @@ export const toPredicate = ( /** * A predefined filter that only passes through string values. * - * @example + * **Example** (Filtering strings) + * * ```ts * import { Filter, Result } from "effect" * @@ -281,22 +331,52 @@ export const toPredicate = ( * console.log(Filter.string(42)) // fail * ``` * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const string: Filter = fromPredicate(Predicate.isString) /** + * Creates a `Filter` that passes only values strictly equal to the specified + * value using JavaScript `===` comparison. + * + * **When to use** + * + * Use when you need a `Filter` that accepts only the exact primitive value or + * object reference using JavaScript strict equality in a `Filter` / `Result` + * pipeline. + * + * **Gotchas** + * + * `NaN` never passes, even when the expected value is `NaN`, and objects pass + * only when they are the same reference. + * + * @see {@link equals} for structural equality when distinct values with equal + * contents should pass + * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const equalsStrict = (value: A): Filter>> => (u) => (u as unknown) === value ? Result.succeed(value) : Result.fail(u as any) /** + * Creates a `Filter` that passes inputs whose `has(key)` method returns + * `true` for the specified key. + * + * **When to use** + * + * Use to keep inputs that expose a `has` method, such as `Set` or `Map`, when + * they contain a required key. + * + * @see {@link fromPredicate} for custom predicate filters or inputs without a + * `has` method + * @see {@link Predicate.hasProperty} for guarding property presence instead of + * calling an input's `has` method + * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const has = (key: K) => boolean }>(input: Input): Result.Result => @@ -305,8 +385,25 @@ export const has = /** * Creates a filter that only passes instances of the given constructor. * + * **When to use** + * + * Use to narrow unknown input to values created by a specific JavaScript + * constructor while keeping the result in the `Filter` / `Result` pipeline. + * + * **Details** + * + * The filter succeeds when the input satisfies `instanceof constructor`. + * Otherwise it fails with the original input. + * + * **Gotchas** + * + * This uses JavaScript `instanceof` semantics, including prototype-chain and + * realm behavior. + * + * @see {@link fromPredicate} for custom predicate-based narrowing + * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const instanceOf = any>(constructor: K) => @@ -316,7 +413,8 @@ export const instanceOf = /** * A predefined filter that only passes through number values. * - * @example + * **Example** (Filtering numbers) + * * ```ts * import { Filter, Result } from "effect" * @@ -324,69 +422,191 @@ export const instanceOf = * console.log(Filter.number("42")) // fail * ``` * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const number: Filter = fromPredicate(Predicate.isNumber) /** * A predefined filter that only passes through boolean values. * + * **When to use** + * + * Use when accepting an unknown input only if it is already a boolean and you + * want a `Filter` result rather than a plain predicate result. + * + * **Details** + * + * Implemented with `fromPredicate(Predicate.isBoolean)`, so `true` and `false` + * succeed and non-booleans fail with the original input. + * + * @see {@link Predicate.isBoolean} for the underlying guard + * @see {@link fromPredicate} for custom predicate-based filters + * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const boolean: Filter = fromPredicate(Predicate.isBoolean) /** - * A predefined filter that only passes through BigInt values. + * A predefined filter that only passes through `bigint` primitive values. + * + * **When to use** + * + * Use to keep primitive big integer values from unknown input while staying in + * the composable `Filter` / `Result` pipeline. + * + * **Details** + * + * Implemented with `fromPredicate(Predicate.isBigInt)`, so values where + * `typeof input === "bigint"` succeed and all other inputs fail with the + * original input. * + * **Gotchas** + * + * This filter does not coerce numbers or strings; `1n` passes while `1` fails. + * + * @see {@link number} for JavaScript `number` values + * @see {@link Predicate.isBigInt} for the underlying guard + * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const bigint: Filter = fromPredicate(Predicate.isBigInt) /** * A predefined filter that only passes through Symbol values. * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const symbol: Filter = fromPredicate(Predicate.isSymbol) /** * A predefined filter that only passes through Date objects. * + * **When to use** + * + * Use when you need to narrow unknown input to JavaScript `Date` instances with + * a reusable `Filter`. + * + * **Details** + * + * Implemented with `fromPredicate(Predicate.isDate)`, so passing values return + * `Result.succeed(input)` and failing values return `Result.fail(input)`. + * + * **Gotchas** + * + * The check uses `instanceof Date`, so invalid `Date` objects still pass; the + * filter does not validate the timestamp. + * + * @see {@link Predicate.isDate} for the underlying guard + * @see {@link instanceOf} for constructor-based filtering + * @see {@link fromPredicate} for custom date checks + * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const date: Filter = fromPredicate(Predicate.isDate) /** * Creates a filter that checks if an input is tagged with a specific tag. * + * **When to use** + * + * Use to keep only the matching member of a `_tag`-discriminated union while + * staying in a composable `Filter` / `Result` pipeline. + * + * **Details** + * + * The filter succeeds when `Predicate.isTagged(input, tag)` returns `true`. + * Otherwise it fails with the original input. + * + * **Gotchas** + * + * This only checks `_tag`; it does not validate the rest of the variant fields. + * + * @see {@link Predicate.isTagged} for the underlying boolean guard when a + * `Filter` result is not needed + * @see {@link reason} for extracting a nested reason variant from tagged errors + * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const tagged: { /** * Creates a filter that checks if an input is tagged with a specific tag. * + * **When to use** + * + * Use to keep only the matching member of a `_tag`-discriminated union while + * staying in a composable `Filter` / `Result` pipeline. + * + * **Details** + * + * The filter succeeds when `Predicate.isTagged(input, tag)` returns `true`. + * Otherwise it fails with the original input. + * + * **Gotchas** + * + * This only checks `_tag`; it does not validate the rest of the variant fields. + * + * @see {@link Predicate.isTagged} for the underlying boolean guard when a + * `Filter` result is not needed + * @see {@link reason} for extracting a nested reason variant from tagged errors + * + * @category constructors * @since 4.0.0 - * @category Constructors */ (): >(tag: Tag) => Filter, ExcludeTag> /** * Creates a filter that checks if an input is tagged with a specific tag. * + * **When to use** + * + * Use to keep only the matching member of a `_tag`-discriminated union while + * staying in a composable `Filter` / `Result` pipeline. + * + * **Details** + * + * The filter succeeds when `Predicate.isTagged(input, tag)` returns `true`. + * Otherwise it fails with the original input. + * + * **Gotchas** + * + * This only checks `_tag`; it does not validate the rest of the variant fields. + * + * @see {@link Predicate.isTagged} for the underlying boolean guard when a + * `Filter` result is not needed + * @see {@link reason} for extracting a nested reason variant from tagged errors + * + * @category constructors * @since 4.0.0 - * @category Constructors */ >(tag: Tag): Filter, ExcludeTag> /** * Creates a filter that checks if an input is tagged with a specific tag. * + * **When to use** + * + * Use to keep only the matching member of a `_tag`-discriminated union while + * staying in a composable `Filter` / `Result` pipeline. + * + * **Details** + * + * The filter succeeds when `Predicate.isTagged(input, tag)` returns `true`. + * Otherwise it fails with the original input. + * + * **Gotchas** + * + * This only checks `_tag`; it does not validate the rest of the variant fields. + * + * @see {@link Predicate.isTagged} for the underlying boolean guard when a + * `Filter` result is not needed + * @see {@link reason} for extracting a nested reason variant from tagged errors + * + * @category constructors * @since 4.0.0 - * @category Constructors */ (tag: Tag): (input: Input) => Result.Result, ExcludeTag> } = function() { @@ -401,15 +621,15 @@ const taggedImpl = /** * Creates a filter that extracts a reason from a tagged error. * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const reason: { /** * Creates a filter that extracts a reason from a tagged error. * + * @category constructors * @since 4.0.0 - * @category Constructors */ (): , const ReasonTag extends ReasonTags>>( tag: Tag, @@ -418,15 +638,15 @@ export const reason: { /** * Creates a filter that extracts a reason from a tagged error. * + * @category constructors * @since 4.0.0 - * @category Constructors */ , const ReasonTag extends ReasonTags>>(tag: Tag, reasonTag: ReasonTag): Filter, ReasonTag>, Input> /** * Creates a filter that extracts a reason from a tagged error. * + * @category constructors * @since 4.0.0 - * @category Constructors */ (tag: Tag, reasonTag: ReasonTag): (input: Input) => Result.Result, ReasonTag>, Input> } = function() { @@ -448,8 +668,22 @@ const reasonImpl = /** * Creates a filter that only passes values equal to the specified value using structural equality. * + * **When to use** + * + * Use to accept inputs that are structurally equal to a known expected value + * while staying in a composable `Filter` / `Result` pipeline. + * + * **Details** + * + * Delegates to `Equal.equals`. On success it returns `Result.succeed(value)`; + * on failure it returns `Result.fail(input)`. + * + * @see {@link equalsStrict} for JavaScript `===` matching instead of structural + * equality + * @see {@link Equal.equals} for the underlying structural equality semantics + * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const equals = (value: A): Filter>> => (u) => @@ -458,22 +692,22 @@ export const equals = /** * Combines two filters with logical OR semantics. * + * @category combinators * @since 4.0.0 - * @category Combinators */ export const or: { /** * Combines two filters with logical OR semantics. * + * @category combinators * @since 4.0.0 - * @category Combinators */ (that: Filter): (self: Filter) => Filter /** * Combines two filters with logical OR semantics. * + * @category combinators * @since 4.0.0 - * @category Combinators */ (self: Filter, that: Filter): Filter } = dual(2, ( @@ -488,31 +722,55 @@ export const or: { /** * Combines two filters and applies a function to their results. * + * **When to use** + * + * Use to combine two filters with a custom function to merge their outputs. + * + * **Details** + * * Both filters must succeed (not return `fail`) for the combination to succeed. * If both filters pass, their outputs are combined using the provided function. * + * @see {@link zip} for combining two filters into a tuple + * + * @category combinators * @since 4.0.0 - * @category Combinators */ export const zipWith: { /** * Combines two filters and applies a function to their results. * + * **When to use** + * + * Use to combine two filters with a custom function to merge their outputs. + * + * **Details** + * * Both filters must succeed (not return `fail`) for the combination to succeed. * If both filters pass, their outputs are combined using the provided function. * + * @see {@link zip} for combining two filters into a tuple + * + * @category combinators * @since 4.0.0 - * @category Combinators */ (right: Filter, f: (left: PassL, right: PassR) => A): (left: Filter) => Filter /** * Combines two filters and applies a function to their results. * + * **When to use** + * + * Use to combine two filters with a custom function to merge their outputs. + * + * **Details** + * * Both filters must succeed (not return `fail`) for the combination to succeed. * If both filters pass, their outputs are combined using the provided function. * + * @see {@link zip} for combining two filters into a tuple + * + * @category combinators * @since 4.0.0 - * @category Combinators */ ( left: Filter, @@ -535,10 +793,13 @@ export const zipWith: { /** * Combines two filters into a tuple of their results. * - * Both filters must succeed for the combination to succeed. If both pass, - * their outputs are combined into a tuple. + * **Details** + * + * Both filters must succeed for the combination to succeed. If both pass, their + * outputs are combined into a tuple. + * + * **Example** (Zipping filters) * - * @example * ```ts * import { Filter } from "effect" * @@ -548,17 +809,20 @@ export const zipWith: { * const positiveAndEven = Filter.zip(positiveNumbers, evenNumbers) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ export const zip: { /** * Combines two filters into a tuple of their results. * - * Both filters must succeed for the combination to succeed. If both pass, - * their outputs are combined into a tuple. + * **Details** + * + * Both filters must succeed for the combination to succeed. If both pass, their + * outputs are combined into a tuple. + * + * **Example** (Zipping filters) * - * @example * ```ts * import { Filter } from "effect" * @@ -568,8 +832,8 @@ export const zip: { * const positiveAndEven = Filter.zip(positiveNumbers, evenNumbers) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ (right: Filter): ( left: Filter @@ -577,10 +841,13 @@ export const zip: { /** * Combines two filters into a tuple of their results. * - * Both filters must succeed for the combination to succeed. If both pass, - * their outputs are combined into a tuple. + * **Details** + * + * Both filters must succeed for the combination to succeed. If both pass, their + * outputs are combined into a tuple. + * + * **Example** (Zipping filters) * - * @example * ```ts * import { Filter } from "effect" * @@ -590,8 +857,8 @@ export const zip: { * const positiveAndEven = Filter.zip(positiveNumbers, evenNumbers) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ (left: Filter, right: Filter): Filter } = dual(2, ( @@ -603,7 +870,8 @@ export const zip: { /** * Combines two filters but only returns the result of the left filter. * - * @example + * **Example** (Keeping the left filter result) + * * ```ts * import { Filter } from "effect" * @@ -613,14 +881,15 @@ export const zip: { * const positiveEven = Filter.andLeft(positiveNumbers, evenNumbers) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ export const andLeft: { /** * Combines two filters but only returns the result of the left filter. * - * @example + * **Example** (Keeping the left filter result) + * * ```ts * import { Filter } from "effect" * @@ -630,8 +899,8 @@ export const andLeft: { * const positiveEven = Filter.andLeft(positiveNumbers, evenNumbers) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ (right: Filter): ( left: Filter @@ -639,7 +908,8 @@ export const andLeft: { /** * Combines two filters but only returns the result of the left filter. * - * @example + * **Example** (Keeping the left filter result) + * * ```ts * import { Filter } from "effect" * @@ -649,8 +919,8 @@ export const andLeft: { * const positiveEven = Filter.andLeft(positiveNumbers, evenNumbers) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ (left: Filter, right: Filter): Filter } = dual(2, ( @@ -661,7 +931,8 @@ export const andLeft: { /** * Combines two filters but only returns the result of the right filter. * - * @example + * **Example** (Keeping the right filter result) + * * ```ts * import { Filter, Result } from "effect" * @@ -673,14 +944,15 @@ export const andLeft: { * const positiveDoubled = Filter.andRight(positiveNumbers, doubleNumbers) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ export const andRight: { /** * Combines two filters but only returns the result of the right filter. * - * @example + * **Example** (Keeping the right filter result) + * * ```ts * import { Filter, Result } from "effect" * @@ -692,8 +964,8 @@ export const andRight: { * const positiveDoubled = Filter.andRight(positiveNumbers, doubleNumbers) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ (right: Filter): ( left: Filter @@ -701,7 +973,8 @@ export const andRight: { /** * Combines two filters but only returns the result of the right filter. * - * @example + * **Example** (Keeping the right filter result) + * * ```ts * import { Filter, Result } from "effect" * @@ -713,8 +986,8 @@ export const andRight: { * const positiveDoubled = Filter.andRight(positiveNumbers, doubleNumbers) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ (left: Filter, right: Filter): Filter } = dual(2, ( @@ -725,7 +998,8 @@ export const andRight: { /** * Composes two filters sequentially, feeding the output of the first into the second. * - * @example + * **Example** (Composing filters) + * * ```ts * import { Filter, Result } from "effect" * @@ -737,14 +1011,15 @@ export const andRight: { * const stringToUpper = Filter.compose(stringFilter, nonEmptyUpper) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ export const compose: { /** * Composes two filters sequentially, feeding the output of the first into the second. * - * @example + * **Example** (Composing filters) + * * ```ts * import { Filter, Result } from "effect" * @@ -756,14 +1031,15 @@ export const compose: { * const stringToUpper = Filter.compose(stringFilter, nonEmptyUpper) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ (right: Filter): (left: Filter) => Filter /** * Composes two filters sequentially, feeding the output of the first into the second. * - * @example + * **Example** (Composing filters) + * * ```ts * import { Filter, Result } from "effect" * @@ -775,8 +1051,8 @@ export const compose: { * const stringToUpper = Filter.compose(stringFilter, nonEmptyUpper) * ``` * + * @category combinators * @since 4.0.0 - * @category Combinators */ (left: Filter, right: Filter): Filter } = dual(2, ( @@ -790,36 +1066,42 @@ export const compose: { }) /** - * Composes two filters sequentially, allowing the output of the first to be - * passed to the second. + * Composes two filters sequentially, passing the successful output of the first + * filter to the second. + * + * **Details** * - * This is similar to `compose`, but it will always fail with the original - * input. + * If either filter fails, the returned filter fails with the original input + * instead of the intermediate failure value. * + * @category combinators * @since 4.0.0 - * @category Combinators */ export const composePassthrough: { /** - * Composes two filters sequentially, allowing the output of the first to be - * passed to the second. + * Composes two filters sequentially, passing the successful output of the first + * filter to the second. * - * This is similar to `compose`, but it will always fail with the original - * input. + * **Details** * + * If either filter fails, the returned filter fails with the original input + * instead of the intermediate failure value. + * + * @category combinators * @since 4.0.0 - * @category Combinators */ (right: Filter): (left: Filter) => Filter /** - * Composes two filters sequentially, allowing the output of the first to be - * passed to the second. + * Composes two filters sequentially, passing the successful output of the first + * filter to the second. + * + * **Details** * - * This is similar to `compose`, but it will always fail with the original - * input. + * If either filter fails, the returned filter fails with the original input + * instead of the intermediate failure value. * + * @category combinators * @since 4.0.0 - * @category Combinators */ (left: Filter, right: Filter): Filter } = dual(2, ( @@ -835,8 +1117,19 @@ export const composePassthrough: { }) /** + * Converts a `Filter` into a function that returns `Some` for passed values + * and `None` for filtered-out values. + * + * **When to use** + * + * Use when adapting a `Filter` to `Option`-based code where passed values + * become `Some` and filtered-out inputs become `None`. + * + * @see {@link toResult} for keeping the filter failure value + * @see {@link toPredicate} for plain boolean pass/fail checks + * + * @category converting * @since 4.0.0 - * @category Conversions */ export const toOption = ( self: Filter @@ -847,8 +1140,19 @@ export const toOption = ( } /** + * Converts a `Filter` into a function that returns the underlying + * `Result.Result` for each input. + * + * **When to use** + * + * Use to adapt a `Filter` to APIs that expect a plain function returning + * `Result`, while preserving both the pass value and the failure value. + * + * @see {@link toOption} for keeping only passed values + * @see {@link toPredicate} for plain boolean pass/fail checks + * + * @category converting * @since 4.0.0 - * @category Conversions */ export const toResult = ( self: Filter diff --git a/.opencode/node_modules/effect/src/Formatter.ts b/.opencode/node_modules/effect/src/Formatter.ts index cfde8a6454838f06f50ed7aa93dc4a426eac13b3..b2fa5a95d4c3008417b0c0fe0e518417c3cb36d5 100644 --- a/.opencode/node_modules/effect/src/Formatter.ts +++ b/.opencode/node_modules/effect/src/Formatter.ts @@ -1,54 +1,11 @@ /** - * Utilities for converting arbitrary JavaScript values into human-readable - * strings, with support for circular references, redaction, and common JS - * types that `JSON.stringify` handles poorly. - * - * Mental model: - * - A `Formatter` is a callable `(value: Value) => Format`. - * - {@link format} is the general-purpose pretty-printer: it handles - * primitives, arrays, objects, `BigInt`, `Symbol`, `Date`, `RegExp`, - * `Set`, `Map`, class instances, and circular references. - * - {@link formatJson} is a safe `JSON.stringify` wrapper that silently - * drops circular references and applies redaction. - * - Both functions accept a `space` option for indentation control. - * - * Common tasks: - * - Pretty-print any value for debugging / logging -> {@link format} - * - Serialize to JSON safely (no circular throws) -> {@link formatJson} - * - Format a single object property key -> {@link formatPropertyKey} - * - Format a property path like `["a"]["b"]` -> {@link formatPath} - * - Format a `Date` to ISO string safely -> {@link formatDate} - * - * Gotchas: - * - {@link format} output is **not** valid JSON; use {@link formatJson} when - * you need parseable JSON. - * - {@link format} calls `toString()` on objects by default; pass - * `ignoreToString: true` to disable. - * - {@link formatJson} silently omits circular references (the key is - * dropped from the output). - * - Values implementing the `Redactable` protocol are automatically - * redacted by both {@link format} and {@link formatJson}. - * - * **Example** (Pretty-print a value) + * Formats JavaScript values into readable strings. * - * ```ts - * import { Formatter } from "effect" - * - * const obj = { name: "Alice", scores: [100, 97] } - * console.log(Formatter.format(obj)) - * // {"name":"Alice","scores":[100,97]} - * - * console.log(Formatter.format(obj, { space: 2 })) - * // { - * // "name": "Alice", - * // "scores": [ - * // 100, - * // 97 - * // ] - * // } - * ``` - * - * See also: {@link Formatter}, {@link format}, {@link formatJson} + * `format` is intended for logs, diagnostics, and error messages. It handles + * primitives, objects, arrays, dates, regular expressions, maps, sets, class + * instances, errors, circular references, and redactable values. `formatJson` + * wraps JSON formatting with redaction and circular-reference handling, and the + * module also includes helpers for property keys, paths, and dates. * * @since 4.0.0 */ @@ -56,16 +13,15 @@ import * as Predicate from "./Predicate.ts" import { getRedacted, redact, symbolRedactable } from "./Redactable.ts" /** - * A callable interface representing a function that converts a `Value` into a - * `Format` (defaults to `string`). + * A callable interface representing a function that converts a `Value` into a `Format`, which defaults to `string`. * - * When to use: - * - You want to type a formatting / rendering function generically. - * - You are building a pipeline that accepts pluggable formatters. + * **When to use** * - * Behavior: - * - Pure callable type; carries no runtime implementation. - * - Contravariant in `Value`, covariant in `Format`. + * Use when you want to type a formatting or rendering function generically, or when you are building a pipeline that accepts pluggable formatters. + * + * **Details** + * + * This is a pure callable type and carries no runtime implementation. It is contravariant in `Value` and covariant in `Format`. * * **Example** (Define a custom formatter) * @@ -78,9 +34,9 @@ import { getRedacted, redact, symbolRedactable } from "./Redactable.ts" * // HELLO * ``` * - * See also: {@link format}, {@link formatJson} - * - * @category Model + * @see {@link format} + * @see {@link formatJson} + * @category models * @since 4.0.0 */ export interface Formatter { @@ -90,17 +46,18 @@ export interface Formatter { /** * Converts any JavaScript value into a human-readable string. * - * When to use: - * - Pretty-printing values for debugging, logging, or error messages. - * - You need to handle `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, - * or class instances that `JSON.stringify` cannot represent. - * - You want circular references shown as `"[Circular]"` instead of - * throwing. + * **When to use** + * + * Use when you need to format arbitrary JavaScript values for debugging, + * logging, or error messages. + * + * **Details** * - * Behavior: - * - Does not mutate input. * - Output is **not** valid JSON; use {@link formatJson} when you need * parseable JSON. + * - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class + * instances that `JSON.stringify` cannot represent. + * - Circular references are shown as `"[Circular]"` instead of throwing. * - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`). * Strings are JSON-quoted. * - Objects with a custom `toString` (not `Object.prototype.toString`): @@ -112,9 +69,6 @@ export interface Formatter { * - `Redactable` values are automatically redacted. * - Arrays/objects with 0–1 entries are inline; larger ones are * pretty-printed when `space` is set. - * - Circular references are replaced with `"[Circular]"`. - * - * Options: * - `space` — indentation unit (number of spaces, or a string like * `"\t"`). Defaults to `0` (compact). * - `ignoreToString` — skip calling `toString()`. Defaults to `false`. @@ -154,9 +108,10 @@ export interface Formatter { * // {"name":"loop","self":[Circular]} * ``` * - * See also: {@link formatJson}, {@link Formatter} - * - * @since 4.0.0 + * @see {@link formatJson} + * @see {@link Formatter} + * @category formatting + * @since 2.0.0 */ export function format(input: unknown, options?: { readonly space?: number | string | undefined @@ -246,30 +201,6 @@ export function format(input: unknown, options?: { const CIRCULAR = "[Circular]" /** - * Formats a single property key for display. - * - * When to use: - * - You are building a custom formatter that needs to render object keys. - * - * Behavior: - * - String keys are JSON-quoted (e.g. `"foo"`). - * - Symbol and number keys are converted with `String()`. - * - Pure function; does not mutate input. - * - * **Example** (Format property keys) - * - * ```ts - * import { Formatter } from "effect" - * - * console.log(Formatter.formatPropertyKey("name")) - * // "name" - * - * console.log(Formatter.formatPropertyKey(Symbol.for("id"))) - * // Symbol(id) - * ``` - * - * See also: {@link formatPath}, {@link format} - * * @internal */ export function formatPropertyKey(name: PropertyKey): string { @@ -279,27 +210,6 @@ export function formatPropertyKey(name: PropertyKey): string { /** * Formats an array of property keys as a bracket-notation path string. * - * When to use: - * - You need to display a path through a nested object (e.g. in error - * messages or schema validation output). - * - * Behavior: - * - Each key is wrapped in brackets and formatted via - * {@link formatPropertyKey}. - * - Returns an empty string for an empty path. - * - Pure function; does not mutate input. - * - * **Example** (Render a property path) - * - * ```ts - * import { Formatter } from "effect" - * - * console.log(Formatter.formatPath(["users", 0, "name"])) - * // ["users"][0]["name"] - * ``` - * - * See also: {@link formatPropertyKey}, {@link format} - * * @internal */ export function formatPath(path: ReadonlyArray): string { @@ -310,29 +220,6 @@ export function formatPath(path: ReadonlyArray): string { * Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for * invalid dates instead of throwing. * - * When to use: - * - You want a safe `toISOString()` that never throws. - * - * Behavior: - * - Returns `date.toISOString()` on success. - * - Returns `"Invalid Date"` if `toISOString()` throws (e.g. for - * `new Date(NaN)`). - * - Pure function; does not mutate input. - * - * **Example** (Safe date formatting) - * - * ```ts - * import { Formatter } from "effect" - * - * console.log(Formatter.formatDate(new Date("2024-01-15T10:30:00Z"))) - * // 2024-01-15T10:30:00.000Z - * - * console.log(Formatter.formatDate(new Date("invalid"))) - * // Invalid Date - * ``` - * - * See also: {@link format} - * * @internal */ export function formatDate(date: Date): string { @@ -353,27 +240,22 @@ function safeToString(input: any): string { } /** - * Safely stringifies a value to JSON, silently dropping circular references. - * - * When to use: - * - You need valid JSON output (unlike {@link format}). - * - The input may contain circular references and you want them silently - * omitted rather than throwing a `TypeError`. - * - * Behavior: - * - Does not mutate input. - * - Uses `JSON.stringify` internally with a replacer that tracks the - * current object ancestry. - * - Circular references are replaced with `undefined` (omitted from - * output). - * - `Redactable` values are automatically redacted before serialization. - * - Types not supported by JSON (`BigInt`, `Symbol`, `undefined`, - * functions) follow standard `JSON.stringify` behavior (omitted or - * `null` in arrays). - * - * Options: - * - `space` — indentation unit (number of spaces, or a string like - * `"\t"`). Defaults to `0` (compact). + * Stringifies a value to JSON safely, silently dropping circular references. + * + * **When to use** + * + * Use when you need valid JSON output, unlike `format`, and the input may + * contain circular references that should be silently omitted rather than + * throwing a `TypeError`. + * + * **Details** + * + * Uses `JSON.stringify` internally with a replacer that tracks the current + * object ancestry. Circular references are replaced with `undefined`, which + * omits them from object output. `Redactable` values are automatically redacted + * before serialization. Values not supported by JSON, such as `BigInt`, + * `Symbol`, `undefined`, and functions, follow standard `JSON.stringify` + * behavior. The `space` parameter controls indentation and defaults to `0`. * * **Example** (Compact JSON) * @@ -407,8 +289,9 @@ function safeToString(input: any): string { * // } * ``` * - * See also: {@link format}, {@link Formatter} - * + * @see {@link format} + * @see {@link Formatter} + * @category serialization * @since 4.0.0 */ export function formatJson(input: unknown, options?: { diff --git a/.opencode/node_modules/effect/src/Function.ts b/.opencode/node_modules/effect/src/Function.ts index f75bd8239bfd3c5112fda0a949c8c8c0fa920eec..ed15ce5f5ecbcfe468459a15ad70a951e604983c 100644 --- a/.opencode/node_modules/effect/src/Function.ts +++ b/.opencode/node_modules/effect/src/Function.ts @@ -1,4 +1,11 @@ /** + * Provides small helpers for defining and reusing TypeScript functions. + * + * The main helpers are `pipe` and `flow` for left-to-right composition and + * `dual` for APIs that support both direct and pipe-friendly call styles. The + * module also contains small identity, constant, tuple, type-level, and + * memoization helpers used across the library. + * * @since 2.0.0 */ import type { TypeLambda } from "./HKT.ts" @@ -7,13 +14,18 @@ import { pipeArguments } from "./Pipeable.ts" /** * Type lambda for function types, used for higher-kinded type operations. * - * @example + * **When to use** + * + * Use when defining higher-kinded abstractions that must accept function types + * as one of their type-lambda inputs. + * + * **Example** (Creating a function type with a type lambda) + * * ```ts - * import type { FunctionTypeLambda } from "effect/Function" - * import type { Kind } from "effect/HKT" + * import type { Function, HKT } from "effect" * * // Create a function type using the type lambda - * type StringToNumber = Kind + * type StringToNumber = HKT.Kind * // Equivalent to: (a: string) => number * ``` * @@ -25,42 +37,26 @@ export interface FunctionTypeLambda extends TypeLambda { } /** - * Creates a function that can be used in a data-last (aka `pipe`able) or - * data-first style. + * Creates a function that can be called in data-first style or data-last + * (`pipe`-friendly) style. * - * The first parameter to `dual` is either the arity of the uncurried function - * or a predicate that determines if the function is being used in a data-first - * or data-last style. + * **When to use** * - * Using the arity is the most common use case, but there are some cases where - * you may want to use a predicate. For example, if you have a function that - * takes an optional argument, you can use a predicate to determine if the - * function is being used in a data-first or data-last style. + * Use to expose one implementation through both direct and `pipe`-friendly + * call styles. * - * You can pass either the arity of the uncurried function or a predicate - * which determines if the function is being used in a data-first or - * data-last style. - * - * @example - * ```ts - * import { dual, pipe } from "effect/Function" - * - * // Using arity to determine data-first or data-last style - * const sum = dual< - * (that: number) => (self: number) => number, - * (self: number, that: number) => number - * >(2, (self, that) => self + that) + * **Details** * - * console.log(sum(2, 3)) // 5 (data-first) - * console.log(pipe(2, sum(3))) // 5 (data-last) - * ``` + * Pass either the arity of the uncurried function or a predicate that decides + * whether the current call is data-first. Arity is the common case. Use a + * predicate when optional arguments make arity ambiguous. * * **Example** (Using arity to determine data-first or data-last style) * * ```ts - * import { dual, pipe } from "effect/Function" + * import { Function, pipe } from "effect" * - * const sum = dual< + * const sum = Function.dual< * (that: number) => (self: number) => number, * (self: number, that: number) => number * >(2, (self, that) => self + that) @@ -72,12 +68,12 @@ export interface FunctionTypeLambda extends TypeLambda { * **Example** (Using call signatures to define the overloads) * * ```ts - * import { dual, pipe } from "effect/Function" + * import { Function, pipe } from "effect" * * const sum: { * (that: number): (self: number) => number * (self: number, that: number): number - * } = dual(2, (self: number, that: number): number => self + that) + * } = Function.dual(2, (self: number, that: number): number => self + that) * * console.log(sum(2, 3)) // 5 * console.log(pipe(2, sum(3))) // 5 @@ -86,9 +82,9 @@ export interface FunctionTypeLambda extends TypeLambda { * **Example** (Using a predicate to determine data-first or data-last style) * * ```ts - * import { dual, pipe } from "effect/Function" + * import { Function, pipe } from "effect" * - * const sum = dual< + * const sum = Function.dual< * (that: number) => (self: number) => number, * (self: number, that: number) => number * >( @@ -105,42 +101,26 @@ export interface FunctionTypeLambda extends TypeLambda { */ export const dual: { /** - * Creates a function that can be used in a data-last (aka `pipe`able) or - * data-first style. + * Creates a function that can be called in data-first style or data-last + * (`pipe`-friendly) style. * - * The first parameter to `dual` is either the arity of the uncurried function - * or a predicate that determines if the function is being used in a data-first - * or data-last style. + * **When to use** * - * Using the arity is the most common use case, but there are some cases where - * you may want to use a predicate. For example, if you have a function that - * takes an optional argument, you can use a predicate to determine if the - * function is being used in a data-first or data-last style. + * Use to expose one implementation through both direct and `pipe`-friendly + * call styles. * - * You can pass either the arity of the uncurried function or a predicate - * which determines if the function is being used in a data-first or - * data-last style. + * **Details** * - * @example - * ```ts - * import { dual, pipe } from "effect/Function" - * - * // Using arity to determine data-first or data-last style - * const sum = dual< - * (that: number) => (self: number) => number, - * (self: number, that: number) => number - * >(2, (self, that) => self + that) - * - * console.log(sum(2, 3)) // 5 (data-first) - * console.log(pipe(2, sum(3))) // 5 (data-last) - * ``` + * Pass either the arity of the uncurried function or a predicate that decides + * whether the current call is data-first. Arity is the common case. Use a + * predicate when optional arguments make arity ambiguous. * * **Example** (Using arity to determine data-first or data-last style) * * ```ts - * import { dual, pipe } from "effect/Function" + * import { Function, pipe } from "effect" * - * const sum = dual< + * const sum = Function.dual< * (that: number) => (self: number) => number, * (self: number, that: number) => number * >(2, (self, that) => self + that) @@ -152,12 +132,12 @@ export const dual: { * **Example** (Using call signatures to define the overloads) * * ```ts - * import { dual, pipe } from "effect/Function" + * import { Function, pipe } from "effect" * * const sum: { * (that: number): (self: number) => number * (self: number, that: number): number - * } = dual(2, (self: number, that: number): number => self + that) + * } = Function.dual(2, (self: number, that: number): number => self + that) * * console.log(sum(2, 3)) // 5 * console.log(pipe(2, sum(3))) // 5 @@ -166,9 +146,9 @@ export const dual: { * **Example** (Using a predicate to determine data-first or data-last style) * * ```ts - * import { dual, pipe } from "effect/Function" + * import { Function, pipe } from "effect" * - * const sum = dual< + * const sum = Function.dual< * (that: number) => (self: number) => number, * (self: number, that: number) => number * >( @@ -185,42 +165,26 @@ export const dual: { */ ) => any, DataFirst extends (...args: Array) => any>(arity: Parameters["length"], body: DataFirst): DataLast & DataFirst /** - * Creates a function that can be used in a data-last (aka `pipe`able) or - * data-first style. + * Creates a function that can be called in data-first style or data-last + * (`pipe`-friendly) style. * - * The first parameter to `dual` is either the arity of the uncurried function - * or a predicate that determines if the function is being used in a data-first - * or data-last style. + * **When to use** * - * Using the arity is the most common use case, but there are some cases where - * you may want to use a predicate. For example, if you have a function that - * takes an optional argument, you can use a predicate to determine if the - * function is being used in a data-first or data-last style. + * Use to expose one implementation through both direct and `pipe`-friendly + * call styles. * - * You can pass either the arity of the uncurried function or a predicate - * which determines if the function is being used in a data-first or - * data-last style. + * **Details** * - * @example - * ```ts - * import { dual, pipe } from "effect/Function" - * - * // Using arity to determine data-first or data-last style - * const sum = dual< - * (that: number) => (self: number) => number, - * (self: number, that: number) => number - * >(2, (self, that) => self + that) - * - * console.log(sum(2, 3)) // 5 (data-first) - * console.log(pipe(2, sum(3))) // 5 (data-last) - * ``` + * Pass either the arity of the uncurried function or a predicate that decides + * whether the current call is data-first. Arity is the common case. Use a + * predicate when optional arguments make arity ambiguous. * * **Example** (Using arity to determine data-first or data-last style) * * ```ts - * import { dual, pipe } from "effect/Function" + * import { Function, pipe } from "effect" * - * const sum = dual< + * const sum = Function.dual< * (that: number) => (self: number) => number, * (self: number, that: number) => number * >(2, (self, that) => self + that) @@ -232,12 +196,12 @@ export const dual: { * **Example** (Using call signatures to define the overloads) * * ```ts - * import { dual, pipe } from "effect/Function" + * import { Function, pipe } from "effect" * * const sum: { * (that: number): (self: number) => number * (self: number, that: number): number - * } = dual(2, (self: number, that: number): number => self + that) + * } = Function.dual(2, (self: number, that: number): number => self + that) * * console.log(sum(2, 3)) // 5 * console.log(pipe(2, sum(3))) // 5 @@ -246,9 +210,9 @@ export const dual: { * **Example** (Using a predicate to determine data-first or data-last style) * * ```ts - * import { dual, pipe } from "effect/Function" + * import { Function, pipe } from "effect" * - * const sum = dual< + * const sum = Function.dual< * (that: number) => (self: number) => number, * (self: number, that: number) => number * >( @@ -312,30 +276,46 @@ export const dual: { } } /** - * Apply a function to a given value. + * Applies a function to a given value. + * + * **When to use** + * + * Use to pass a fixed value into a unary function, especially when the function + * is the value flowing through `pipe`. + * + * **Details** + * + * `apply(a)(f)` is equivalent to `f(a)`. + * + * **Example** (Applying an argument to a function) * - * @example * ```ts - * import { apply, pipe } from "effect/Function" - * import { length } from "effect/String" + * import { Function, pipe, String } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(pipe(length, apply("hello")), 5) + * assert.deepStrictEqual(pipe(String.length, Function.apply("hello")), 5) * ``` * + * @see {@link pipe} for building left-to-right pipelines + * * @category combinators * @since 2.0.0 */ export const apply = (a: A) => (self: (a: A) => B): B => self(a) /** - * A lazy argument. + * A zero-argument function that produces a value when invoked. + * + * **When to use** + * + * Use to type a lazy value provider that should not run until called. + * + * **Example** (Creating a lazy argument) * - * @example * ```ts - * import { constant, type LazyArg } from "effect/Function" + * import { Function } from "effect" * - * const constNull: LazyArg = constant(null) + * const constNull: Function.LazyArg = Function.constant(null) * ``` * * @category models @@ -346,12 +326,18 @@ export type LazyArg = () => A /** * Represents a function with multiple arguments. * - * @example + * **When to use** + * + * Use to describe a function whose argument list is represented as a tuple + * type. + * + * **Example** (Typing a variadic function) + * * ```ts - * import type { FunctionN } from "effect/Function" + * import type { Function } from "effect" * import * as assert from "node:assert" * - * const sum: FunctionN<[number, number], number> = (a, b) => a + b + * const sum: Function.FunctionN<[number, number], number> = (a, b) => a + b * assert.deepStrictEqual(sum(2, 3), 5) * ``` * @@ -361,11 +347,16 @@ export type LazyArg = () => A export type FunctionN, B> = (...args: A) => B /** - * The identity function, i.e. A function that returns its input argument. + * Returns its input argument unchanged. + * + * **When to use** + * + * Use to return a value unchanged where a function is required. + * + * **Example** (Returning the same value) * - * @example * ```ts - * import { identity } from "effect/Function" + * import { identity } from "effect" * import * as assert from "node:assert" * * assert.deepStrictEqual(identity(5), 5) @@ -377,48 +368,71 @@ export type FunctionN, B> = (...args: A) => B export const identity = (a: A): A => a /** - * A function that ensures that the type of an expression matches some type, + * Ensures that the type of an expression matches some type, * without changing the resulting type of that expression. * - * @example + * **When to use** + * + * Use to check assignability while preserving the expression's precise inferred + * type. + * + * **Example** (Checking an expression against a type) + * * ```ts - * import { satisfies } from "effect/Function" + * import { Function } from "effect" * import * as assert from "node:assert" * - * const test1 = satisfies()(5 as const) + * const test1 = Function.satisfies()(5 as const) * // ^? const test: 5 * // @ts-expect-error - * const test2 = satisfies()(5) + * const test2 = Function.satisfies()(5) * // ^? Argument of type 'number' is not assignable to parameter of type 'string' * - * assert.deepStrictEqual(satisfies()(5), 5) + * assert.deepStrictEqual(Function.satisfies()(5), 5) * ``` * - * @category type utils + * @see {@link cast} for changing only the static TypeScript type + * + * @category utility types * @since 2.0.0 */ export const satisfies = () => (b: B) => b /** - * Casts the result to the specified type. + * Returns the input value with a different static type. * - * @category type utils - * @since 2.0.0 + * **When to use** + * + * Use when you need an explicit type-level cast and accept that the value is + * returned unchanged at runtime. + * + * **Gotchas** + * + * This is a type-level cast only; it performs no runtime validation or + * conversion. + * + * @see {@link satisfies} for checking assignability without changing the resulting type + * + * @category utility types + * @since 4.0.0 */ export const cast: (a: A) => B = identity as any /** - * Creates a constant value that never changes. + * Creates a zero-argument function that always returns the provided value. + * + * **When to use** + * + * Use when you need a thunk or callback that returns the same value on every + * invocation. * - * This is useful when you want to pass a value to a higher-order function (a function that takes another function as its argument) - * and want that inner function to always use the same value, no matter how many times it is called. + * **Example** (Creating a constant thunk) * - * @example * ```ts - * import { constant } from "effect/Function" + * import { Function } from "effect" * import * as assert from "node:assert" * - * const constNull = constant(null) + * const constNull = Function.constant(null) * * assert.deepStrictEqual(constNull(), null) * assert.deepStrictEqual(constNull(), null) @@ -430,14 +444,19 @@ export const cast: (a: A) => B = identity as any export const constant = (value: A): LazyArg => () => value /** - * A thunk that returns always `true`. + * Returns `true` when called. + * + * **When to use** + * + * Use when you need a thunk that returns `true` on every invocation. + * + * **Example** (Returning true from a thunk) * - * @example * ```ts - * import { constTrue } from "effect/Function" + * import { Function } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(constTrue(), true) + * assert.deepStrictEqual(Function.constTrue(), true) * ``` * * @category constants @@ -446,14 +465,19 @@ export const constant = (value: A): LazyArg => () => value export const constTrue: LazyArg = constant(true) /** - * A thunk that returns always `false`. + * Returns `false` when called. + * + * **When to use** + * + * Use when you need a thunk that returns `false` on every invocation. + * + * **Example** (Returning false from a thunk) * - * @example * ```ts - * import { constFalse } from "effect/Function" + * import { Function } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(constFalse(), false) + * assert.deepStrictEqual(Function.constFalse(), false) * ``` * * @category constants @@ -462,14 +486,19 @@ export const constTrue: LazyArg = constant(true) export const constFalse: LazyArg = constant(false) /** - * A thunk that returns always `null`. + * Returns `null` when called. + * + * **When to use** + * + * Use when you need a thunk that returns `null` on every invocation. + * + * **Example** (Returning null from a thunk) * - * @example * ```ts - * import { constNull } from "effect/Function" + * import { Function } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(constNull(), null) + * assert.deepStrictEqual(Function.constNull(), null) * ``` * * @category constants @@ -478,14 +507,19 @@ export const constFalse: LazyArg = constant(false) export const constNull: LazyArg = constant(null) /** - * A thunk that returns always `undefined`. + * Returns `undefined` when called. + * + * **When to use** + * + * Use when you need a thunk that returns `undefined` on every invocation. + * + * **Example** (Returning undefined from a thunk) * - * @example * ```ts - * import { constUndefined } from "effect/Function" + * import { Function } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(constUndefined(), undefined) + * assert.deepStrictEqual(Function.constUndefined(), undefined) * ``` * * @category constants @@ -494,14 +528,20 @@ export const constNull: LazyArg = constant(null) export const constUndefined: LazyArg = constant(undefined) /** - * A thunk that returns always `void`. + * Returns no meaningful value when called. + * + * **When to use** + * + * Use when you need a thunk that is called only for its effect and has no + * meaningful return value. + * + * **Example** (Returning void from a thunk) * - * @example * ```ts - * import { constVoid } from "effect/Function" + * import { Function } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(constVoid(), undefined) + * assert.deepStrictEqual(Function.constVoid(), undefined) * ``` * * @category constants @@ -512,14 +552,20 @@ export const constVoid: LazyArg = constUndefined /** * Reverses the order of arguments for a curried function. * - * @example + * **When to use** + * + * Use to adapt a curried function when its argument groups need to be supplied + * in the opposite order. + * + * **Example** (Flipping curried arguments) + * * ```ts - * import { flip } from "effect/Function" + * import { Function } from "effect" * import * as assert from "node:assert" * * const f = (a: number) => (b: string) => a - b.length * - * assert.deepStrictEqual(flip(f)("aaa")(2), -1) + * assert.deepStrictEqual(Function.flip(f)("aaa")(2), -1) * ``` * * @category combinators @@ -535,17 +581,25 @@ export const flip = , B extends Array, C>( * Composes two functions, `ab` and `bc` into a single function that takes in an argument `a` of type `A` and returns a result of type `C`. * The result is obtained by first applying the `ab` function to `a` and then applying the `bc` function to the result of `ab`. * - * @example + * **When to use** + * + * Use to compose exactly two unary functions into a reusable unary function. + * + * **Example** (Composing two functions) + * * ```ts - * import { compose } from "effect/Function" + * import { Function } from "effect" * import * as assert from "node:assert" * * const increment = (n: number) => n + 1 * const square = (n: number) => n * n * - * assert.strictEqual(compose(increment, square)(2), 9) + * assert.strictEqual(Function.compose(increment, square)(2), 9) * ``` * + * @see {@link flow} for composing a left-to-right sequence of functions + * @see {@link pipe} for applying a value through a left-to-right sequence immediately + * * @category combinators * @since 2.0.0 */ @@ -554,17 +608,25 @@ export const compose: { * Composes two functions, `ab` and `bc` into a single function that takes in an argument `a` of type `A` and returns a result of type `C`. * The result is obtained by first applying the `ab` function to `a` and then applying the `bc` function to the result of `ab`. * - * @example + * **When to use** + * + * Use to compose exactly two unary functions into a reusable unary function. + * + * **Example** (Composing two functions) + * * ```ts - * import { compose } from "effect/Function" + * import { Function } from "effect" * import * as assert from "node:assert" * * const increment = (n: number) => n + 1 * const square = (n: number) => n * n * - * assert.strictEqual(compose(increment, square)(2), 9) + * assert.strictEqual(Function.compose(increment, square)(2), 9) * ``` * + * @see {@link flow} for composing a left-to-right sequence of functions + * @see {@link pipe} for applying a value through a left-to-right sequence immediately + * * @category combinators * @since 2.0.0 */ @@ -573,17 +635,25 @@ export const compose: { * Composes two functions, `ab` and `bc` into a single function that takes in an argument `a` of type `A` and returns a result of type `C`. * The result is obtained by first applying the `ab` function to `a` and then applying the `bc` function to the result of `ab`. * - * @example + * **When to use** + * + * Use to compose exactly two unary functions into a reusable unary function. + * + * **Example** (Composing two functions) + * * ```ts - * import { compose } from "effect/Function" + * import { Function } from "effect" * import * as assert from "node:assert" * * const increment = (n: number) => n + 1 * const square = (n: number) => n * n * - * assert.strictEqual(compose(increment, square)(2), 9) + * assert.strictEqual(Function.compose(increment, square)(2), 9) * ``` * + * @see {@link flow} for composing a left-to-right sequence of functions + * @see {@link pipe} for applying a value through a left-to-right sequence immediately + * * @category combinators * @since 2.0.0 */ @@ -591,21 +661,30 @@ export const compose: { } = dual(2, (ab: (a: A) => B, bc: (b: B) => C): (a: A) => C => (a) => bc(ab(a))) /** - * The `absurd` function is a stub for cases where a value of type `never` is encountered in your code, - * meaning that it should be impossible for this code to be executed. + * Marks an impossible branch by accepting a `never` value and returning any + * type. + * + * **When to use** * - * This function is particularly useful when it's necessary to specify that certain cases are impossible. + * Use when you need a return value in a branch that exhaustive checks prove + * cannot be reached. + * + * **Gotchas** + * + * Calling `absurd` throws, because a value of type `never` should be + * impossible at runtime. + * + * **Example** (Handling impossible values) * - * @example * ```ts - * import { absurd } from "effect/Function" + * import { absurd } from "effect" * * const handleNever = (value: never) => { * return absurd(value) // This will throw an error if called * } * ``` * - * @category utilities + * @category utility types * @since 2.0.0 */ export const absurd = (_: never): A => { @@ -615,89 +694,123 @@ export const absurd = (_: never): A => { /** * Creates a tupled version of this function: instead of `n` arguments, it accepts a single tuple argument. * - * @example + * **When to use** + * + * Use to adapt a multi-argument function so it accepts one tuple argument. + * + * **Example** (Converting arguments to a tuple) + * * ```ts - * import { tupled } from "effect/Function" + * import { Function } from "effect" * import * as assert from "node:assert" * - * const sumTupled = tupled((x: number, y: number): number => x + y) + * const sumTupled = Function.tupled((x: number, y: number): number => x + y) * * assert.deepStrictEqual(sumTupled([1, 2]), 3) * ``` * + * @see {@link untupled} for adapting a tuple-argument function back to multiple arguments + * * @category combinators * @since 2.0.0 */ export const tupled = , B>(f: (...a: A) => B): (a: A) => B => (a) => f(...a) /** - * Inverse function of `tupled` + * Converts a tupled function back to an uncurried function. + * + * **When to use** + * + * Use to adapt a tuple-argument function so it accepts multiple arguments. + * + * **Example** (Converting a tuple to arguments) * - * @example * ```ts - * import { untupled } from "effect/Function" + * import { Function } from "effect" * import * as assert from "node:assert" * - * const getFirst = untupled((tuple: [A, B]): A => tuple[0]) + * const getFirst = Function.untupled((tuple: [A, B]): A => tuple[0]) * * assert.deepStrictEqual(getFirst(1, 2), 1) * ``` * + * @see {@link tupled} for adapting a multi-argument function to one tuple argument + * * @category combinators * @since 2.0.0 */ export const untupled = , B>(f: (a: A) => B): (...a: A) => B => (...a) => f(a) /** - * Pipes the value of an expression into a pipeline of functions. + * Pipes the value of an expression through a left-to-right sequence of + * functions. + * + * **When to use** + * + * Use when you need to compose data-last functions into readable + * transformation pipelines instead of method-style chains. * * **Details** * - * The `pipe` function is a utility that allows us to compose functions in a - * readable and sequential manner. It takes the output of one function and - * passes it as the input to the next function in the pipeline. This enables us - * to build complex transformations by chaining multiple functions together. + * Takes an initial value, passes it to the first function, then passes each + * result to the next function in order. The final function result is returned. * - * ```ts skip-type-checking - * import { pipe } from "effect" + * **Gotchas** * - * const result = pipe(input, func1, func2, ..., funcN) - * ``` + * Each function passed after the initial value must accept a single argument, + * because `pipe` calls each step with only the previous result. * - * In this syntax, `input` is the initial value, and `func1`, `func2`, ..., - * `funcN` are the functions to be applied in sequence. The result of each - * function becomes the input for the next function, and the final result is - * returned. + * **Example** (Using pipeline syntax) * - * Here's an illustration of how `pipe` works: + * In this example, `1` is passed to the first function, and each result becomes + * the input for the next function. * - * ``` - * ┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐ ┌───────┐ ┌────────┐ - * │ input │───►│ func1 │───►│ func2 │───►│ ... │───►│ funcN │───►│ result │ - * └───────┘ └───────┘ └───────┘ └───────┘ └───────┘ └────────┘ + * ```ts + * import { pipe } from "effect" + * + * const result = pipe( + * 1, + * (n) => n + 1, + * (n) => n * 2, + * (n) => `result: ${n}` + * ) + * + * console.log(result) // "result: 4" * ``` * - * It's important to note that functions passed to `pipe` must have a **single - * argument** because they are only called with a single argument. + * **Example** (Chaining methods before conversion) * - * **When to Use** + * ```ts + * const numbers = [1, 2, 3, 4] + * const double = (n: number) => n * 2 + * const greaterThanFour = (n: number) => n > 4 * - * This is useful in combination with data-last functions as a simulation of - * methods: + * const result = numbers.map(double).filter(greaterThanFour) * - * ```ts skip-type-checking - * as.map(f).filter(g) + * console.log(result) // [6, 8] * ``` * - * becomes: + * **Example** (Rewriting method chains with pipe) + * + * The same transformation can be written with data-last functions. * - * ```ts skip-type-checking + * ```ts * import { Array, pipe } from "effect" * - * pipe(as, Array.map(f), Array.filter(g)) + * const numbers = [1, 2, 3, 4] + * const double = (n: number) => n * 2 + * const greaterThanFour = (n: number) => n > 4 + * + * const result = pipe( + * numbers, + * Array.map(double), + * Array.filter(greaterThanFour) + * ) + * + * console.log(result) // [6, 8] * ``` * - * **Example** (Chaining Arithmetic Operations) + * **Example** (Chaining arithmetic operations) * * ```ts * import { pipe } from "effect" @@ -714,7 +827,8 @@ export const untupled = , B>(f: (a: A) => B): ( * // Output: 2 * ``` * - * @example + * **Example** (Building a simple transformation pipeline) + * * ```ts * import { pipe } from "effect" * @@ -1185,13 +1299,22 @@ export function pipe(a: unknown, ...args: Array): unknown { } /** - * Performs left-to-right function composition. The first argument may have any arity, the remaining arguments must be unary. + * Performs left-to-right function composition. + * + * **When to use** + * + * Use to build a reusable function from a left-to-right sequence of + * transformations. + * + * **Details** + * + * The first function may have any arity. Every following function must be + * unary. * - * See also [`pipe`](#pipe). + * **Example** (Composing functions left to right) * - * @example * ```ts - * import { flow } from "effect/Function" + * import { flow } from "effect" * import * as assert from "node:assert" * * const len = (s: string): number => s.length @@ -1202,6 +1325,9 @@ export function pipe(a: unknown, ...args: Array): unknown { * assert.strictEqual(f("aaa"), 6) * ``` * + * @see {@link pipe} for applying a value through a left-to-right sequence immediately + * @see {@link compose} for composing exactly two functions + * * @category combinators * @since 2.0.0 */ @@ -1371,33 +1497,52 @@ export function flow( } /** - * Type hole simulation. Creates a placeholder for any type, primarily used during development. + * Creates a compile-time placeholder for a value of any type. + * + * **When to use** + * + * Use as a temporary typed placeholder while developing incomplete code. + * + * **Gotchas** + * + * `hole` is intended for temporary development use. If the placeholder is + * evaluated at runtime, it throws. + * + * **Example** (Creating a development placeholder) * - * @example * ```ts - * import { hole } from "effect/Function" + * import { hole } from "effect" + * + * // Intentionally not called: `hole` throws if the placeholder is evaluated. + * const buildUser = (id: number): { readonly id: number; readonly name: string } => ({ + * id, + * name: hole() + * }) * - * // Use during development as a placeholder - * const placeholder: string = hole() + * console.log(typeof buildUser) // "function" * ``` * - * @category utilities + * @category utility types * @since 2.0.0 */ export const hole: () => T = cast(absurd) /** - * The SK combinator, also known as the "S-K combinator" or "S-combinator", is a fundamental combinator in the - * lambda calculus and the SKI combinator calculus. + * Returns the second argument and discards the first. The SK combinator is + * a fundamental combinator in the lambda calculus and the SKI combinator + * calculus. + * + * **When to use** + * + * Use to discard the first argument and return the second argument. * - * This function is useful for discarding the first argument passed to it and returning the second argument. + * **Example** (Discarding the first argument) * - * @example * ```ts - * import { SK } from "effect/Function" + * import { Function } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(SK(0, "hello"), "hello") + * assert.deepStrictEqual(Function.SK(0, "hello"), "hello") * ``` * * @category combinators @@ -1406,6 +1551,27 @@ export const hole: () => T = cast(absurd) export const SK = (_: A, b: B): B => b /** + * Creates a memoized function whose input is an object, caching results by + * object identity. + * + * **When to use** + * + * Use to reuse the result of a synchronous computation whose output is stable + * for a given object reference. + * + * **Details** + * + * Each memoized wrapper owns a private `WeakMap` keyed by object identity. + * Cached `undefined` results are still returned because the cache is checked + * with `WeakMap.has`. + * + * **Gotchas** + * + * Structurally equal objects do not share cache entries. If the same object is + * mutated after its first call, later calls still return the cached result for + * that reference. + * + * @category caching * @since 4.0.0 */ export function memoize(f: (a: A) => O): (ast: A) => O { diff --git a/.opencode/node_modules/effect/src/Graph.ts b/.opencode/node_modules/effect/src/Graph.ts index 93fa0a5dd09a1de3a385b4f435bb3045c83f1597..cc9f89fd750581891720254273e99fda18d6adc6 100644 --- a/.opencode/node_modules/effect/src/Graph.ts +++ b/.opencode/node_modules/effect/src/Graph.ts @@ -1,4 +1,11 @@ /** + * Models relationships between indexed nodes and edges. + * + * This module provides immutable and scoped-mutable graph data structures. A + * graph can be directed or undirected, and it can store user-defined data on + * both nodes and edges. The module includes traversal, analysis, path-finding, + * transformation, and diagram export utilities. + * * @since 4.0.0 */ @@ -19,24 +26,65 @@ const TypeId = "~effect/collections/Graph" /** * Node index for node identification using plain numbers. * - * @since 4.0.0 + * **When to use** + * + * Use when storing or passing the stable identifier of a graph node between + * `Graph` operations. + * + * **Details** + * + * `addNode` allocates node identifiers from the graph's next node index. + * + * **Gotchas** + * + * A `NodeIndex` is an identifier, not an array offset. Removed node identifiers + * are not reused. + * + * @see {@link EdgeIndex} for edge identifiers instead of node identifiers + * @see {@link addNode} for creating node identifiers + * * @category models + * @since 3.18.0 */ export type NodeIndex = number /** * Edge index for edge identification using plain numbers. * - * @since 4.0.0 + * **When to use** + * + * Use when you need to keep the identifier for a graph edge so you can later + * read, update, remove, or compare that edge. + * + * **Gotchas** + * + * An `EdgeIndex` is an identifier, not an array offset. Removed edge + * identifiers are not reused. + * + * @see {@link NodeIndex} for node identifiers instead of edge identifiers + * @see {@link Edge} for the edge value addressed by this identifier + * @see {@link addEdge} for creating edge identifiers + * @see {@link getEdge} for reading edges by identifier + * * @category models + * @since 3.18.0 */ export type EdgeIndex = number /** - * Edge data containing source, target, and user data. + * Represents edge data containing source, target, and user data. + * + * **When to use** + * + * Use as the graph edge value that carries source node, target node, and stored + * edge data together. + * + * @see {@link getEdge} for reading a single edge by identifier + * @see {@link addEdge} for adding edges to a graph + * @see {@link edges} for iterating graph edges * - * @since 4.0.0 * @category models + * @since 3.18.0 */ export class Edge extends Data.Class<{ readonly source: NodeIndex @@ -47,16 +95,29 @@ export class Edge extends Data.Class<{ /** * Graph type for distinguishing directed and undirected graphs. * - * @since 4.0.0 + * **When to use** + * + * Use when writing graph-polymorphic types or helpers that need to preserve + * whether a graph is directed or undirected. + * + * @see {@link Graph} for immutable graphs parameterized by kind + * @see {@link MutableGraph} for mutable graphs parameterized by kind + * * @category models + * @since 3.18.0 */ export type Kind = "directed" | "undirected" /** - * Graph prototype interface. + * Common structural interface shared by immutable and mutable graphs. + * + * **Details** + * + * Contains the node and edge maps, adjacency indexes, allocation counters, and + * shared protocols used by both `Graph` and `MutableGraph`. * - * @since 4.0.0 * @category models + * @since 3.18.0 */ export interface Proto extends Iterable, Equal.Equal, Pipeable, Inspectable { readonly [TypeId]: typeof TypeId @@ -72,8 +133,17 @@ export interface Proto extends Iterable, /** * Immutable graph interface. * - * @since 4.0.0 + * **When to use** + * + * Use as the immutable graph model for code that queries, traverses, + * transforms, or analyzes graph structure without mutating it. + * + * @see {@link MutableGraph} for the mutable counterpart used inside mutation scopes + * @see {@link DirectedGraph} for a `Graph` fixed to directed edges + * @see {@link UndirectedGraph} for a `Graph` fixed to undirected edges + * * @category models + * @since 3.18.0 */ export interface Graph extends Proto { readonly type: T @@ -83,8 +153,18 @@ export interface Graph extends Proto< /** * Mutable graph interface. * - * @since 4.0.0 + * **When to use** + * + * Use when adding, removing, or updating nodes and edges inside a graph + * mutation scope. + * + * @see {@link Graph} for the immutable graph interface + * @see {@link mutate} for scoped mutation of an immutable graph + * @see {@link beginMutation} for opening a mutable graph manually + * @see {@link endMutation} for returning to an immutable graph + * * @category models + * @since 3.18.0 */ export interface MutableGraph extends Proto { readonly type: T @@ -92,34 +172,80 @@ export interface MutableGraph extends } /** - * Directed graph type alias. + * Immutable graph type for source-to-target relationships. + * + * **When to use** + * + * Use as the immutable graph type when edge direction is part of the model and + * traversal or neighbor queries should follow source-to-target edges. + * + * **Details** + * + * `DirectedGraph` is a `Graph` with node data of type + * `N` and edge data of type `E`. + * + * @see {@link directed} for constructing directed graphs + * @see {@link Graph} for the generic immutable graph type + * @see {@link UndirectedGraph} for graphs whose edges connect both endpoints + * @see {@link MutableDirectedGraph} for the mutable directed graph type * - * @since 4.0.0 * @category models + * @since 3.18.0 */ export type DirectedGraph = Graph /** - * Undirected graph type alias. + * Immutable graph type for relationships without source-to-target direction. + * + * **When to use** + * + * Use when modeling relationships where each edge connects both endpoints + * without a source-to-target direction. + * + * **Details** + * + * `UndirectedGraph` is a `Graph`. + * + * @see {@link undirected} for constructing undirected graphs + * @see {@link DirectedGraph} for graphs whose edges have source-to-target direction + * @see {@link MutableUndirectedGraph} for the mutable undirected graph type * - * @since 4.0.0 * @category models + * @since 3.18.0 */ export type UndirectedGraph = Graph /** * Mutable directed graph type alias. * - * @since 4.0.0 + * **When to use** + * + * Use when annotating a temporary graph value that can be changed in place and + * whose edges have source-to-target direction. + * + * @see {@link MutableGraph} for the generic mutable graph type + * @see {@link DirectedGraph} for the immutable directed graph type + * @see {@link MutableUndirectedGraph} for mutable graphs without edge direction + * * @category models + * @since 3.18.0 */ export type MutableDirectedGraph = MutableGraph /** * Mutable undirected graph type alias. * - * @since 4.0.0 + * **When to use** + * + * Use when annotating a temporary graph value that can be changed in place and + * whose edges connect both endpoints without direction. + * + * @see {@link MutableDirectedGraph} for mutable graphs with directed edges + * @see {@link UndirectedGraph} for the immutable undirected graph type + * @see {@link MutableGraph} for the generic mutable graph type + * * @category models + * @since 3.18.0 */ export type MutableUndirectedGraph = MutableGraph @@ -205,8 +331,17 @@ const ProtoGraph = { // TODO: Do we need safe variants for these? /** - * @since 4.0.0 + * Error thrown by graph operations when the requested graph structure is + * invalid, such as referencing a missing node or using unsupported edge + * weights. + * + * **When to use** + * + * Use when handling failures thrown by graph operations that reject invalid + * graph structure or unsupported algorithm inputs. + * * @category errors + * @since 3.18.0 */ export class GraphError extends Data.TaggedError("GraphError")<{ readonly message: string @@ -220,15 +355,28 @@ const missingNode = (node: number) => new GraphError({ message: `Node ${node} do // ============================================================================= /** + * Returns `true` if a value has the graph runtime type identifier, narrowing + * it to a `Graph`. + * + * **When to use** + * + * Use to narrow an unknown value before treating it as a graph value. + * + * **Gotchas** + * + * This guard checks the shared graph runtime type identifier and does not + * distinguish immutable graphs from mutable graphs. + * + * @category guards * @since 4.0.0 - * @category Guards */ export const isGraph = (u: unknown): u is Graph => hasProperty(u, TypeId) /** * Creates a directed graph, optionally with initial mutations. * - * @example + * **Example** (Creating a directed graph) + * * ```ts * import { Graph } from "effect" * @@ -242,8 +390,8 @@ export const isGraph = (u: unknown): u is Graph => hasProperty * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 3.18.0 */ export const directed = (mutate?: (mutable: MutableDirectedGraph) => void): DirectedGraph => { const graph: Mutable> = Object.create(ProtoGraph) @@ -269,7 +417,8 @@ export const directed = (mutate?: (mutable: MutableDirectedGraph) => /** * Creates an undirected graph, optionally with initial mutations. * - * @example + * **Example** (Creating an undirected graph) + * * ```ts * import { Graph } from "effect" * @@ -283,8 +432,8 @@ export const directed = (mutate?: (mutable: MutableDirectedGraph) => * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 3.18.0 */ export const undirected = (mutate?: (mutable: MutableUndirectedGraph) => void): UndirectedGraph => { const graph: Mutable> = Object.create(ProtoGraph) @@ -314,7 +463,8 @@ export const undirected = (mutate?: (mutable: MutableUndirectedGraph /** * Creates a mutable scope for safe graph mutations by copying the data structure. * - * @example + * **Example** (Beginning a mutation scope) + * * ```ts * import { Graph } from "effect" * @@ -323,8 +473,8 @@ export const undirected = (mutate?: (mutable: MutableUndirectedGraph * // Now mutable can be safely modified without affecting original graph * ``` * - * @since 4.0.0 * @category mutations + * @since 3.18.0 */ export const beginMutation = ( graph: Graph @@ -358,7 +508,8 @@ export const beginMutation = ( /** * Converts a mutable graph back to an immutable graph, ending the mutation scope. * - * @example + * **Example** (Ending a mutation scope) + * * ```ts * import { Graph } from "effect" * @@ -368,8 +519,8 @@ export const beginMutation = ( * const newGraph = Graph.endMutation(mutable) * ``` * - * @since 4.0.0 * @category mutations + * @since 3.18.0 */ export const endMutation = ( mutable: MutableGraph @@ -391,55 +542,70 @@ export const endMutation = ( /** * Performs scoped mutations on a graph, automatically managing the mutation lifecycle. * - * @example + * **Example** (Applying scoped mutations) + * * ```ts * import { Graph } from "effect" * * const graph = Graph.directed() * const newGraph = Graph.mutate(graph, (mutable) => { - * // Safe mutations go here - * // mutable gets automatically converted back to immutable + * const nodeA = Graph.addNode(mutable, "A") + * const nodeB = Graph.addNode(mutable, "B") + * Graph.addEdge(mutable, nodeA, nodeB, 1) * }) + * + * console.log(Graph.nodeCount(newGraph)) // 2 + * console.log(Graph.edgeCount(newGraph)) // 1 * ``` * - * @since 4.0.0 * @category mutations + * @since 3.18.0 */ export const mutate: { /** * Performs scoped mutations on a graph, automatically managing the mutation lifecycle. * - * @example + * **Example** (Applying scoped mutations) + * * ```ts * import { Graph } from "effect" * * const graph = Graph.directed() * const newGraph = Graph.mutate(graph, (mutable) => { - * // Safe mutations go here - * // mutable gets automatically converted back to immutable + * const nodeA = Graph.addNode(mutable, "A") + * const nodeB = Graph.addNode(mutable, "B") + * Graph.addEdge(mutable, nodeA, nodeB, 1) * }) + * + * console.log(Graph.nodeCount(newGraph)) // 2 + * console.log(Graph.edgeCount(newGraph)) // 1 * ``` * - * @since 4.0.0 * @category mutations + * @since 3.18.0 */ (f: (mutable: MutableGraph) => void): (graph: Graph) => Graph /** * Performs scoped mutations on a graph, automatically managing the mutation lifecycle. * - * @example + * **Example** (Applying scoped mutations) + * * ```ts * import { Graph } from "effect" * * const graph = Graph.directed() * const newGraph = Graph.mutate(graph, (mutable) => { - * // Safe mutations go here - * // mutable gets automatically converted back to immutable + * const nodeA = Graph.addNode(mutable, "A") + * const nodeB = Graph.addNode(mutable, "B") + * Graph.addEdge(mutable, nodeA, nodeB, 1) * }) + * + * console.log(Graph.nodeCount(newGraph)) // 2 + * console.log(Graph.edgeCount(newGraph)) // 1 * ``` * - * @since 4.0.0 * @category mutations + * @since 3.18.0 */ (graph: Graph, f: (mutable: MutableGraph) => void): Graph } = dual(2, ( @@ -458,7 +624,23 @@ export const mutate: { /** * Adds a new node to a mutable graph and returns its index. * - * @example + * **When to use** + * + * Use to allocate a new node in a mutable graph before storing edges or + * querying it by index. + * + * **Details** + * + * The returned index is allocated from the graph's next node index. The mutable + * graph stores the node data and initializes empty incoming and outgoing edge + * indexes for the new node. + * + * **Gotchas** + * + * `NodeIndex` values are identifiers and are not reused after removals. + * + * **Example** (Adding nodes) + * * ```ts * import { Graph } from "effect" * @@ -470,8 +652,12 @@ export const mutate: { * }) * ``` * - * @since 4.0.0 + * @see {@link mutate} for obtaining a mutable graph from an immutable graph + * @see {@link addEdge} for connecting existing nodes + * @see {@link removeNode} for removing nodes from a mutable graph + * * @category mutations + * @since 3.18.0 */ export const addNode = ( mutable: MutableGraph, @@ -493,12 +679,12 @@ export const addNode = ( } /** - * Gets the data associated with a node index, if it exists. + * Gets the data associated with a node index safely, if it exists. + * + * **Example** (Getting node data) * - * @example * ```ts - * import { Graph } from "effect" - * import * as Option from "effect/Option" + * import { Graph, Option } from "effect" * * const graph = Graph.mutate(Graph.directed(), (mutable) => { * Graph.addNode(mutable, "Node A") @@ -512,17 +698,17 @@ export const addNode = ( * } * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ export const getNode: { /** - * Gets the data associated with a node index, if it exists. + * Gets the data associated with a node index safely, if it exists. + * + * **Example** (Getting node data) * - * @example * ```ts - * import { Graph } from "effect" - * import * as Option from "effect/Option" + * import { Graph, Option } from "effect" * * const graph = Graph.mutate(Graph.directed(), (mutable) => { * Graph.addNode(mutable, "Node A") @@ -536,17 +722,17 @@ export const getNode: { * } * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ (nodeIndex: NodeIndex): (graph: Graph | MutableGraph) => Option.Option /** - * Gets the data associated with a node index, if it exists. + * Gets the data associated with a node index safely, if it exists. + * + * **Example** (Getting node data) * - * @example * ```ts - * import { Graph } from "effect" - * import * as Option from "effect/Option" + * import { Graph, Option } from "effect" * * const graph = Graph.mutate(Graph.directed(), (mutable) => { * Graph.addNode(mutable, "Node A") @@ -560,8 +746,8 @@ export const getNode: { * } * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ (graph: Graph | MutableGraph, nodeIndex: NodeIndex): Option.Option } = dual(2, ( @@ -570,9 +756,10 @@ export const getNode: { ): Option.Option => graph.nodes.has(nodeIndex) ? Option.some(graph.nodes.get(nodeIndex)!) : Option.none()) /** - * Checks if a node with the given index exists in the graph. + * Checks whether a node with the given index exists in the graph. + * + * **Example** (Checking node existence) * - * @example * ```ts * import { Graph } from "effect" * @@ -589,14 +776,15 @@ export const getNode: { * console.log(notExists) // false * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ export const hasNode: { /** - * Checks if a node with the given index exists in the graph. + * Checks whether a node with the given index exists in the graph. + * + * **Example** (Checking node existence) * - * @example * ```ts * import { Graph } from "effect" * @@ -613,14 +801,15 @@ export const hasNode: { * console.log(notExists) // false * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ (nodeIndex: NodeIndex): (graph: Graph | MutableGraph) => boolean /** - * Checks if a node with the given index exists in the graph. + * Checks whether a node with the given index exists in the graph. + * + * **Example** (Checking node existence) * - * @example * ```ts * import { Graph } from "effect" * @@ -637,8 +826,8 @@ export const hasNode: { * console.log(notExists) // false * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ (graph: Graph | MutableGraph, nodeIndex: NodeIndex): boolean } = dual(2, ( @@ -649,7 +838,8 @@ export const hasNode: { /** * Returns the number of nodes in the graph. * - * @example + * **Example** (Counting nodes) + * * ```ts * import { Graph } from "effect" * @@ -665,8 +855,8 @@ export const hasNode: { * console.log(Graph.nodeCount(graphWithNodes)) // 3 * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ export const nodeCount = ( graph: Graph | MutableGraph @@ -675,7 +865,8 @@ export const nodeCount = ( /** * Finds the first node that matches the given predicate. * - * @example + * **Example** (Finding the first matching node) + * * ```ts * import { Graph } from "effect" * @@ -692,14 +883,15 @@ export const nodeCount = ( * console.log(notFound) // Option.none() * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ export const findNode: { /** * Finds the first node that matches the given predicate. * - * @example + * **Example** (Finding the first matching node) + * * ```ts * import { Graph } from "effect" * @@ -716,14 +908,15 @@ export const findNode: { * console.log(notFound) // Option.none() * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ (predicate: (data: N) => boolean): (graph: Graph | MutableGraph) => Option.Option /** * Finds the first node that matches the given predicate. * - * @example + * **Example** (Finding the first matching node) + * * ```ts * import { Graph } from "effect" * @@ -740,8 +933,8 @@ export const findNode: { * console.log(notFound) // Option.none() * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ ( graph: Graph | MutableGraph, @@ -762,7 +955,8 @@ export const findNode: { /** * Finds all nodes that match the given predicate. * - * @example + * **Example** (Finding matching nodes) + * * ```ts * import { Graph } from "effect" * @@ -779,14 +973,15 @@ export const findNode: { * console.log(empty) // [] * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ export const findNodes: { /** * Finds all nodes that match the given predicate. * - * @example + * **Example** (Finding matching nodes) + * * ```ts * import { Graph } from "effect" * @@ -803,14 +998,15 @@ export const findNodes: { * console.log(empty) // [] * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ (predicate: (data: N) => boolean): (graph: Graph | MutableGraph) => Array /** * Finds all nodes that match the given predicate. * - * @example + * **Example** (Finding matching nodes) + * * ```ts * import { Graph } from "effect" * @@ -827,8 +1023,8 @@ export const findNodes: { * console.log(empty) // [] * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ ( graph: Graph | MutableGraph, @@ -850,7 +1046,8 @@ export const findNodes: { /** * Finds the first edge that matches the given predicate. * - * @example + * **Example** (Finding the first matching edge) + * * ```ts * import { Graph } from "effect" * @@ -869,14 +1066,15 @@ export const findNodes: { * console.log(notFound) // Option.none() * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ export const findEdge: { /** * Finds the first edge that matches the given predicate. * - * @example + * **Example** (Finding the first matching edge) + * * ```ts * import { Graph } from "effect" * @@ -895,14 +1093,15 @@ export const findEdge: { * console.log(notFound) // Option.none() * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ (predicate: (data: E, source: NodeIndex, target: NodeIndex) => boolean): (graph: Graph | MutableGraph) => Option.Option /** * Finds the first edge that matches the given predicate. * - * @example + * **Example** (Finding the first matching edge) + * * ```ts * import { Graph } from "effect" * @@ -921,8 +1120,8 @@ export const findEdge: { * console.log(notFound) // Option.none() * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ ( graph: Graph | MutableGraph, @@ -943,7 +1142,8 @@ export const findEdge: { /** * Finds all edges that match the given predicate. * - * @example + * **Example** (Finding matching edges) + * * ```ts * import { Graph } from "effect" * @@ -963,14 +1163,15 @@ export const findEdge: { * console.log(empty) // [] * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ export const findEdges: { /** * Finds all edges that match the given predicate. * - * @example + * **Example** (Finding matching edges) + * * ```ts * import { Graph } from "effect" * @@ -990,14 +1191,15 @@ export const findEdges: { * console.log(empty) // [] * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ (predicate: (data: E, source: NodeIndex, target: NodeIndex) => boolean): (graph: Graph | MutableGraph) => Array /** * Finds all edges that match the given predicate. * - * @example + * **Example** (Finding matching edges) + * * ```ts * import { Graph } from "effect" * @@ -1017,8 +1219,8 @@ export const findEdges: { * console.log(empty) // [] * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ ( graph: Graph | MutableGraph, @@ -1040,7 +1242,8 @@ export const findEdges: { /** * Updates a single node's data by applying a transformation function. * - * @example + * **Example** (Updating node data) + * * ```ts * import { Graph } from "effect" * @@ -1054,8 +1257,8 @@ export const findEdges: { * console.log(nodeData) // Option.some("NODE A") * ``` * - * @since 4.0.0 - * @category transformations + * @category transforming + * @since 3.18.0 */ export const updateNode = ( mutable: MutableGraph, @@ -1074,7 +1277,8 @@ export const updateNode = ( /** * Updates a single edge's data by applying a transformation function. * - * @example + * **Example** (Updating edge data) + * * ```ts * import { Graph } from "effect" * @@ -1086,11 +1290,11 @@ export const updateNode = ( * }) * * const edgeData = Graph.getEdge(result, 0) - * console.log(edgeData) // new Graph.Edge({ source: 0, target: 1, data: 20 }) + * console.log(edgeData) // Option.some(new Graph.Edge({ source: 0, target: 1, data: 20 })) * ``` * - * @since 4.0.0 * @category mutations + * @since 3.18.0 */ export const updateEdge = ( mutable: MutableGraph, @@ -1107,9 +1311,15 @@ export const updateEdge = ( } /** - * Creates a new graph with transformed node data using the provided mapping function. + * Transforms every node's data in a mutable graph in place using the provided + * mapping function. + * + * **Details** + * + * Node indices and edges are preserved; only the stored node data is replaced. + * + * **Example** (Mapping node data) * - * @example * ```ts * import { Graph } from "effect" * @@ -1121,11 +1331,11 @@ export const updateEdge = ( * }) * * const nodeData = Graph.getNode(graph, 0) - * console.log(nodeData) // new Graph.Node("NODE A") + * console.log(nodeData) // Option.some("NODE A") * ``` * - * @since 4.0.0 - * @category transformations + * @category transforming + * @since 3.18.0 */ export const mapNodes = ( mutable: MutableGraph, @@ -1141,7 +1351,8 @@ export const mapNodes = ( /** * Transforms all edge data in a mutable graph using the provided mapping function. * - * @example + * **Example** (Mapping edge data) + * * ```ts * import { Graph } from "effect" * @@ -1155,11 +1366,11 @@ export const mapNodes = ( * }) * * const edgeData = Graph.getEdge(graph, 0) - * console.log(edgeData) // new Graph.Edge({ source: 0, target: 1, data: 20 }) + * console.log(edgeData) // Option.some(new Graph.Edge({ source: 0, target: 1, data: 20 })) * ``` * - * @since 4.0.0 - * @category transformations + * @category transforming + * @since 3.18.0 */ export const mapEdges = ( mutable: MutableGraph, @@ -1176,9 +1387,35 @@ export const mapEdges = ( } /** - * Reverses all edge directions in a mutable graph by swapping source and target nodes. + * @internal + */ +const rebuildAdjacency = ( + mutable: MutableGraph +): void => { + mutable.adjacency.clear() + mutable.reverseAdjacency.clear() + + for (const nodeIndex of mutable.nodes.keys()) { + mutable.adjacency.set(nodeIndex, []) + mutable.reverseAdjacency.set(nodeIndex, []) + } + + for (const [edgeIndex, edgeData] of mutable.edges) { + mutable.adjacency.get(edgeData.source)!.push(edgeIndex) + mutable.reverseAdjacency.get(edgeData.target)!.push(edgeIndex) + + if (mutable.type === "undirected") { + mutable.adjacency.get(edgeData.target)!.push(edgeIndex) + mutable.reverseAdjacency.get(edgeData.source)!.push(edgeIndex) + } + } +} + +/** + * Swaps source and target nodes for every edge in a mutable graph. + * + * **Example** (Reversing edge directions) * - * @example * ```ts * import { Graph } from "effect" * @@ -1192,15 +1429,19 @@ export const mapEdges = ( * }) * * const edge0 = Graph.getEdge(graph, 0) - * console.log(edge0) // new Graph.Edge({ source: 1, target: 0, data: 1 }) - B -> A + * console.log(edge0) // Option.some(new Graph.Edge({ source: 1, target: 0, data: 1 })) * ``` * - * @since 4.0.0 - * @category transformations + * @category transforming + * @since 3.18.0 */ export const reverse = ( mutable: MutableGraph ): void => { + if (mutable.type === "undirected") { + return + } + // Reverse all edges by swapping source and target for (const [index, edgeData] of mutable.edges) { mutable.edges.set( @@ -1213,22 +1454,7 @@ export const reverse = ( ) } - // Clear and rebuild adjacency lists with reversed directions - mutable.adjacency.clear() - mutable.reverseAdjacency.clear() - - // Rebuild adjacency lists with reversed directions - for (const [edgeIndex, edgeData] of mutable.edges) { - // Add to forward adjacency (source -> target) - const sourceEdges = mutable.adjacency.get(edgeData.source) || [] - sourceEdges.push(edgeIndex) - mutable.adjacency.set(edgeData.source, sourceEdges) - - // Add to reverse adjacency (target <- source) - const targetEdges = mutable.reverseAdjacency.get(edgeData.target) || [] - targetEdges.push(edgeIndex) - mutable.reverseAdjacency.set(edgeData.target, targetEdges) - } + rebuildAdjacency(mutable) // Invalidate cycle flag since edge directions changed mutable.acyclic = Option.none() @@ -1238,10 +1464,10 @@ export const reverse = ( * Filters and optionally transforms nodes in a mutable graph using a predicate function. * Nodes that return Option.none are removed along with all their connected edges. * - * @example + * **Example** (Filtering and mapping nodes) + * * ```ts - * import { Graph } from "effect" - * import * as Option from "effect/Option" + * import { Graph, Option } from "effect" * * const graph = Graph.directed((mutable) => { * const a = Graph.addNode(mutable, "active") @@ -1261,8 +1487,8 @@ export const reverse = ( * console.log(Graph.nodeCount(graph)) // 2 (only "active" nodes remain) * ``` * - * @since 4.0.0 - * @category transformations + * @category transforming + * @since 3.18.0 */ export const filterMapNodes = ( mutable: MutableGraph, @@ -1292,10 +1518,10 @@ export const filterMapNodes = ( * Filters and optionally transforms edges in a mutable graph using a predicate function. * Edges that return Option.none are removed from the graph. * - * @example + * **Example** (Filtering and mapping edges) + * * ```ts - * import { Graph } from "effect" - * import * as Option from "effect/Option" + * import { Graph, Option } from "effect" * * const graph = Graph.directed((mutable) => { * const a = Graph.addNode(mutable, "A") @@ -1315,8 +1541,8 @@ export const filterMapNodes = ( * console.log(Graph.edgeCount(graph)) // 2 (edges with weight 5 removed) * ``` * - * @since 4.0.0 - * @category transformations + * @category transforming + * @since 3.18.0 */ export const filterMapEdges = ( mutable: MutableGraph, @@ -1349,7 +1575,8 @@ export const filterMapEdges = ( * Filters nodes by removing those that don't match the predicate. * This function modifies the mutable graph in place. * - * @example + * **Example** (Filtering nodes) + * * ```ts * import { Graph } from "effect" * @@ -1366,8 +1593,8 @@ export const filterMapEdges = ( * console.log(Graph.nodeCount(graph)) // 2 (only "active" nodes remain) * ``` * - * @since 4.0.0 - * @category transformations + * @category transforming + * @since 3.18.0 */ export const filterNodes = ( mutable: MutableGraph, @@ -1392,7 +1619,8 @@ export const filterNodes = ( * Filters edges by removing those that don't match the predicate. * This function modifies the mutable graph in place. * - * @example + * **Example** (Filtering edges) + * * ```ts * import { Graph } from "effect" * @@ -1412,8 +1640,8 @@ export const filterNodes = ( * console.log(Graph.edgeCount(graph)) // 2 (edge with weight 5 removed) * ``` * - * @since 4.0.0 - * @category transformations + * @category transforming + * @since 3.18.0 */ export const filterEdges = ( mutable: MutableGraph, @@ -1465,7 +1693,24 @@ const invalidateCycleFlagOnAddition = ( /** * Adds a new edge to a mutable graph and returns its index. * - * @example + * **When to use** + * + * Use to connect two existing nodes in a mutable graph while storing edge data + * and receiving the new edge identifier. + * + * **Details** + * + * Creates an `Edge` with the source, target, and data at the next edge index, + * updates adjacency indexes, and increments the graph's next edge index. + * Undirected graphs register the same edge for both endpoints. + * + * **Gotchas** + * + * The source and target nodes must already exist in the mutable graph; missing + * endpoints throw a `GraphError`. + * + * **Example** (Adding edges) + * * ```ts * import { Graph } from "effect" * @@ -1477,8 +1722,13 @@ const invalidateCycleFlagOnAddition = ( * }) * ``` * - * @since 4.0.0 + * @see {@link mutate} for obtaining a mutable graph from an immutable graph + * @see {@link addNode} for creating node indexes before connecting them + * @see {@link getEdge} for reading the returned edge + * @see {@link removeEdge} for removing an edge from a mutable graph + * * @category mutations + * @since 3.18.0 */ export const addEdge = ( mutable: MutableGraph, @@ -1537,7 +1787,8 @@ export const addEdge = ( /** * Removes a node and all its incident edges from a mutable graph. * - * @example + * **Example** (Removing a node) + * * ```ts * import { Graph } from "effect" * @@ -1551,8 +1802,8 @@ export const addEdge = ( * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 3.18.0 */ export const removeNode = ( mutable: MutableGraph, @@ -1600,7 +1851,8 @@ export const removeNode = ( /** * Removes an edge from a mutable graph. * - * @example + * **Example** (Removing an edge) + * * ```ts * import { Graph } from "effect" * @@ -1614,8 +1866,8 @@ export const removeNode = ( * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 3.18.0 */ export const removeEdge = ( mutable: MutableGraph, @@ -1690,9 +1942,10 @@ const removeEdgeInternal = ( // ============================================================================= /** - * Gets the edge data associated with an edge index, if it exists. + * Gets the edge data associated with an edge index safely, if it exists. + * + * **Example** (Getting edge data) * - * @example * ```ts * import { Graph } from "effect" * @@ -1707,13 +1960,13 @@ const removeEdgeInternal = ( * * if (edgeData._tag === "Some") { * console.log(edgeData.value.data) // 42 - * console.log(edgeData.value.source) // NodeIndex(0) - * console.log(edgeData.value.target) // NodeIndex(1) + * console.log(edgeData.value.source) // 0 + * console.log(edgeData.value.target) // 1 * } * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ export const getEdge: { // ============================================================================= @@ -1721,9 +1974,10 @@ export const getEdge: { // ============================================================================= /** - * Gets the edge data associated with an edge index, if it exists. + * Gets the edge data associated with an edge index safely, if it exists. + * + * **Example** (Getting edge data) * - * @example * ```ts * import { Graph } from "effect" * @@ -1738,13 +1992,13 @@ export const getEdge: { * * if (edgeData._tag === "Some") { * console.log(edgeData.value.data) // 42 - * console.log(edgeData.value.source) // NodeIndex(0) - * console.log(edgeData.value.target) // NodeIndex(1) + * console.log(edgeData.value.source) // 0 + * console.log(edgeData.value.target) // 1 * } * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ (edgeIndex: EdgeIndex): (graph: Graph | MutableGraph) => Option.Option> // ============================================================================= @@ -1752,9 +2006,10 @@ export const getEdge: { // ============================================================================= /** - * Gets the edge data associated with an edge index, if it exists. + * Gets the edge data associated with an edge index safely, if it exists. + * + * **Example** (Getting edge data) * - * @example * ```ts * import { Graph } from "effect" * @@ -1769,13 +2024,13 @@ export const getEdge: { * * if (edgeData._tag === "Some") { * console.log(edgeData.value.data) // 42 - * console.log(edgeData.value.source) // NodeIndex(0) - * console.log(edgeData.value.target) // NodeIndex(1) + * console.log(edgeData.value.source) // 0 + * console.log(edgeData.value.target) // 1 * } * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ (graph: Graph | MutableGraph, edgeIndex: EdgeIndex): Option.Option> } = dual(2, ( @@ -1784,9 +2039,10 @@ export const getEdge: { ): Option.Option> => Option.fromUndefinedOr(graph.edges.get(edgeIndex))) /** - * Checks if an edge exists between two nodes in the graph. + * Checks whether an edge exists between two nodes in the graph. + * + * **Example** (Checking edge existence) * - * @example * ```ts * import { Graph } from "effect" * @@ -1808,14 +2064,15 @@ export const getEdge: { * console.log(hasAC) // false * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ export const hasEdge: { /** - * Checks if an edge exists between two nodes in the graph. + * Checks whether an edge exists between two nodes in the graph. + * + * **Example** (Checking edge existence) * - * @example * ```ts * import { Graph } from "effect" * @@ -1837,14 +2094,15 @@ export const hasEdge: { * console.log(hasAC) // false * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ (source: NodeIndex, target: NodeIndex): (graph: Graph | MutableGraph) => boolean /** - * Checks if an edge exists between two nodes in the graph. + * Checks whether an edge exists between two nodes in the graph. + * + * **Example** (Checking edge existence) * - * @example * ```ts * import { Graph } from "effect" * @@ -1866,8 +2124,8 @@ export const hasEdge: { * console.log(hasAC) // false * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ ( graph: Graph | MutableGraph, @@ -1887,8 +2145,11 @@ export const hasEdge: { // Check if any edge in the adjacency list connects to the target for (const edgeIndex of adjacencyList) { const edge = graph.edges.get(edgeIndex) - if (edge !== undefined && edge.target === target) { - return true + if (edge !== undefined) { + const neighbor = graph.type === "undirected" && edge.target === source ? edge.source : edge.target + if (neighbor === target) { + return true + } } } @@ -1898,7 +2159,8 @@ export const hasEdge: { /** * Returns the number of edges in the graph. * - * @example + * **Example** (Counting edges) + * * ```ts * import { Graph } from "effect" * @@ -1917,17 +2179,48 @@ export const hasEdge: { * console.log(Graph.edgeCount(graphWithEdges)) // 3 * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ export const edgeCount = ( graph: Graph | MutableGraph ): number => graph.edges.size +const getDirectedNeighbors = ( + graph: Graph | MutableGraph, + nodeIndex: NodeIndex, + direction: Direction +): Array => { + const adjacencyMap = direction === "incoming" + ? graph.reverseAdjacency + : graph.adjacency + + const adjacencyList = adjacencyMap.get(nodeIndex) + if (adjacencyList === undefined) { + return [] + } + + const result: Array = [] + for (const edgeIndex of adjacencyList) { + const edge = graph.edges.get(edgeIndex) + if (edge !== undefined) { + result.push(direction === "incoming" ? edge.source : edge.target) + } + } + + return result +} + /** - * Returns the neighboring nodes (targets of outgoing edges) for a given node. + * Returns the neighboring node indices for a node. + * + * **Details** + * + * For directed graphs, neighbors are the targets of outgoing edges. For + * undirected graphs, neighbors are the other endpoints of incident edges. + * + * **Example** (Getting outgoing neighbors) * - * @example * ```ts * import { Graph } from "effect" * @@ -1944,20 +2237,26 @@ export const edgeCount = ( * const nodeC = 2 * * const neighborsA = Graph.neighbors(graph, nodeA) - * console.log(neighborsA) // [NodeIndex(1), NodeIndex(2)] + * console.log(neighborsA) // [1, 2] * * const neighborsB = Graph.neighbors(graph, nodeB) * console.log(neighborsB) // [] * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ export const neighbors: { /** - * Returns the neighboring nodes (targets of outgoing edges) for a given node. + * Returns the neighboring node indices for a node. + * + * **Details** + * + * For directed graphs, neighbors are the targets of outgoing edges. For + * undirected graphs, neighbors are the other endpoints of incident edges. + * + * **Example** (Getting outgoing neighbors) * - * @example * ```ts * import { Graph } from "effect" * @@ -1974,20 +2273,26 @@ export const neighbors: { * const nodeC = 2 * * const neighborsA = Graph.neighbors(graph, nodeA) - * console.log(neighborsA) // [NodeIndex(1), NodeIndex(2)] + * console.log(neighborsA) // [1, 2] * * const neighborsB = Graph.neighbors(graph, nodeB) * console.log(neighborsB) // [] * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ (nodeIndex: NodeIndex): (graph: Graph | MutableGraph) => Array /** - * Returns the neighboring nodes (targets of outgoing edges) for a given node. + * Returns the neighboring node indices for a node. + * + * **Details** + * + * For directed graphs, neighbors are the targets of outgoing edges. For + * undirected graphs, neighbors are the other endpoints of incident edges. + * + * **Example** (Getting outgoing neighbors) * - * @example * ```ts * import { Graph } from "effect" * @@ -2004,14 +2309,14 @@ export const neighbors: { * const nodeC = 2 * * const neighborsA = Graph.neighbors(graph, nodeA) - * console.log(neighborsA) // [NodeIndex(1), NodeIndex(2)] + * console.log(neighborsA) // [1, 2] * * const neighborsB = Graph.neighbors(graph, nodeB) * console.log(neighborsB) // [] * ``` * - * @since 4.0.0 * @category getters + * @since 3.18.0 */ (graph: Graph | MutableGraph, nodeIndex: NodeIndex): Array } = dual(2, ( @@ -2023,26 +2328,163 @@ export const neighbors: { return getUndirectedNeighbors(graph as any, nodeIndex) } - const adjacencyList = graph.adjacency.get(nodeIndex) - if (adjacencyList === undefined) { - return [] - } + return getDirectedNeighbors(graph as Graph | MutableGraph, nodeIndex, "outgoing") +}) - const result: Array = [] - for (const edgeIndex of adjacencyList) { - const edge = graph.edges.get(edgeIndex) - if (edge !== undefined) { - result.push(edge.target) - } +/** + * Returns the outgoing neighbor node indices for a node in a directed graph. + * + * **When to use** + * + * Use when you need the nodes reached by following outgoing edges from a node in + * a directed graph. + * + * **Gotchas** + * + * Throws a `GraphError` when used with an undirected graph. + * + * @see {@link predecessors} for incoming neighbors in a directed graph + * @see {@link neighbors} for generic neighbor lookup across graph kinds + * + * @category queries + * @since 4.0.0 + */ +export const successors: { + /** + * Returns the outgoing neighbor node indices for a node in a directed graph. + * + * **When to use** + * + * Use when you need the nodes reached by following outgoing edges from a node in + * a directed graph. + * + * **Gotchas** + * + * Throws a `GraphError` when used with an undirected graph. + * + * @see {@link predecessors} for incoming neighbors in a directed graph + * @see {@link neighbors} for generic neighbor lookup across graph kinds + * + * @category queries + * @since 4.0.0 + */ + (nodeIndex: NodeIndex): (graph: Graph | MutableGraph) => Array + /** + * Returns the outgoing neighbor node indices for a node in a directed graph. + * + * **When to use** + * + * Use when you need the nodes reached by following outgoing edges from a node in + * a directed graph. + * + * **Gotchas** + * + * Throws a `GraphError` when used with an undirected graph. + * + * @see {@link predecessors} for incoming neighbors in a directed graph + * @see {@link neighbors} for generic neighbor lookup across graph kinds + * + * @category queries + * @since 4.0.0 + */ + ( + graph: Graph | MutableGraph, + nodeIndex: NodeIndex + ): Array +} = dual(2, ( + graph: Graph | MutableGraph, + nodeIndex: NodeIndex +): Array => { + if (graph.type === "undirected") { + throw new GraphError({ message: "Cannot get successors of undirected graph" }) } + return getDirectedNeighbors(graph as Graph | MutableGraph, nodeIndex, "outgoing") +}) - return result +/** + * Returns the incoming neighbor node indices for a node in a directed graph. + * + * **When to use** + * + * Use when you need the nodes that reach a node by following incoming edges in a + * directed graph. + * + * **Gotchas** + * + * Throws a `GraphError` when used with an undirected graph. + * + * @see {@link successors} for outgoing neighbors in a directed graph + * @see {@link neighbors} for generic neighbor lookup across graph kinds + * + * @category queries + * @since 4.0.0 + */ +export const predecessors: { + /** + * Returns the incoming neighbor node indices for a node in a directed graph. + * + * **When to use** + * + * Use when you need the nodes that reach a node by following incoming edges in a + * directed graph. + * + * **Gotchas** + * + * Throws a `GraphError` when used with an undirected graph. + * + * @see {@link successors} for outgoing neighbors in a directed graph + * @see {@link neighbors} for generic neighbor lookup across graph kinds + * + * @category queries + * @since 4.0.0 + */ + (nodeIndex: NodeIndex): (graph: Graph | MutableGraph) => Array + /** + * Returns the incoming neighbor node indices for a node in a directed graph. + * + * **When to use** + * + * Use when you need the nodes that reach a node by following incoming edges in a + * directed graph. + * + * **Gotchas** + * + * Throws a `GraphError` when used with an undirected graph. + * + * @see {@link successors} for outgoing neighbors in a directed graph + * @see {@link neighbors} for generic neighbor lookup across graph kinds + * + * @category queries + * @since 4.0.0 + */ + ( + graph: Graph | MutableGraph, + nodeIndex: NodeIndex + ): Array +} = dual(2, ( + graph: Graph | MutableGraph, + nodeIndex: NodeIndex +): Array => { + if (graph.type === "undirected") { + throw new GraphError({ message: "Cannot get predecessors of undirected graph" }) + } + return getDirectedNeighbors(graph as Graph | MutableGraph, nodeIndex, "incoming") }) /** - * Get neighbors of a node in a specific direction for bidirectional traversal. + * Gets directed neighbors of a node in a specific direction. + * + * **When to use** + * + * Use when maintaining existing code that already passes an explicit traversal + * direction. New code should prefer `successors` or `predecessors`. + * + * **Gotchas** + * + * Throws a `GraphError` when used with an undirected graph. + * + * **Example** (Traversing directed neighbors) * - * @example * ```ts * import { Graph } from "effect" * @@ -2062,14 +2504,27 @@ export const neighbors: { * const incoming = Graph.neighborsDirected(graph, nodeB, "incoming") * ``` * - * @since 4.0.0 + * @deprecated Use {@link successors} for outgoing neighbors or {@link predecessors} for incoming neighbors. + * @see {@link successors} for outgoing neighbors in a directed graph + * @see {@link predecessors} for incoming neighbors in a directed graph * @category queries + * @since 3.18.0 */ export const neighborsDirected: { /** - * Get neighbors of a node in a specific direction for bidirectional traversal. + * Gets directed neighbors of a node in a specific direction. + * + * **When to use** + * + * Use when maintaining existing code that already passes an explicit traversal + * direction. New code should prefer `successors` or `predecessors`. + * + * **Gotchas** + * + * Throws a `GraphError` when used with an undirected graph. + * + * **Example** (Traversing directed neighbors) * - * @example * ```ts * import { Graph } from "effect" * @@ -2089,14 +2544,27 @@ export const neighborsDirected: { * const incoming = Graph.neighborsDirected(graph, nodeB, "incoming") * ``` * - * @since 4.0.0 + * @deprecated Use {@link successors} for outgoing neighbors or {@link predecessors} for incoming neighbors. + * @see {@link successors} for outgoing neighbors in a directed graph + * @see {@link predecessors} for incoming neighbors in a directed graph * @category queries + * @since 3.18.0 */ - (nodeIndex: NodeIndex, direction: Direction): (graph: Graph | MutableGraph) => Array + (nodeIndex: NodeIndex, direction: Direction): (graph: Graph | MutableGraph) => Array /** - * Get neighbors of a node in a specific direction for bidirectional traversal. + * Gets directed neighbors of a node in a specific direction. + * + * **When to use** + * + * Use when maintaining existing code that already passes an explicit traversal + * direction. New code should prefer `successors` or `predecessors`. + * + * **Gotchas** + * + * Throws a `GraphError` when used with an undirected graph. + * + * **Example** (Traversing directed neighbors) * - * @example * ```ts * import { Graph } from "effect" * @@ -2116,11 +2584,14 @@ export const neighborsDirected: { * const incoming = Graph.neighborsDirected(graph, nodeB, "incoming") * ``` * - * @since 4.0.0 + * @deprecated Use {@link successors} for outgoing neighbors or {@link predecessors} for incoming neighbors. + * @see {@link successors} for outgoing neighbors in a directed graph + * @see {@link predecessors} for incoming neighbors in a directed graph * @category queries + * @since 3.18.0 */ - ( - graph: Graph | MutableGraph, + ( + graph: Graph | MutableGraph, nodeIndex: NodeIndex, direction: Direction ): Array @@ -2129,28 +2600,10 @@ export const neighborsDirected: { nodeIndex: NodeIndex, direction: Direction ): Array => { - const adjacencyMap = direction === "incoming" - ? graph.reverseAdjacency - : graph.adjacency - - const adjacencyList = adjacencyMap.get(nodeIndex) - if (adjacencyList === undefined) { - return [] - } - - const result: Array = [] - for (const edgeIndex of adjacencyList) { - const edge = graph.edges.get(edgeIndex) - if (edge !== undefined) { - // For incoming direction, we want the source node instead of target - const neighborNode = direction === "incoming" - ? edge.source - : edge.target - result.push(neighborNode) - } + if (graph.type === "undirected") { + throw new GraphError({ message: "Cannot get directed neighbors of undirected graph" }) } - - return result + return getDirectedNeighbors(graph as Graph | MutableGraph, nodeIndex, direction) }) // ============================================================================= @@ -2160,12 +2613,15 @@ export const neighborsDirected: { /** * Configuration options for GraphViz DOT format generation from graphs. * - * Provides customization for node labels, edge labels, and graph naming - * in DOT format compatible with GraphViz tools. + * **Details** + * + * These options customize node labels, edge labels, and graph naming in DOT + * format compatible with GraphViz tools. + * + * **Example** (Configuring GraphViz labels) * - * @example * ```ts - * import type * as Graph from "effect/Graph" + * import type { Graph } from "effect" * * // Basic options with custom labels * const basicOptions: Graph.GraphVizOptions = { @@ -2181,8 +2637,8 @@ export const neighborsDirected: { * } * ``` * - * @since 4.0.0 - * @category models + * @category options + * @since 3.18.0 */ export interface GraphVizOptions { /** @@ -2207,7 +2663,8 @@ export interface GraphVizOptions { /** * Exports a graph to GraphViz DOT format for visualization. * - * @example + * **Example** (Exporting GraphViz DOT) + * * ```ts * import { Graph } from "effect" * @@ -2232,14 +2689,15 @@ export interface GraphVizOptions { * // } * ``` * - * @since 4.0.0 - * @category utils + * @category converting + * @since 3.18.0 */ export const toGraphViz: { /** * Exports a graph to GraphViz DOT format for visualization. * - * @example + * **Example** (Exporting GraphViz DOT) + * * ```ts * import { Graph } from "effect" * @@ -2264,14 +2722,15 @@ export const toGraphViz: { * // } * ``` * - * @since 4.0.0 - * @category utils + * @category converting + * @since 3.18.0 */ (options?: GraphVizOptions): (graph: Graph | MutableGraph) => string /** * Exports a graph to GraphViz DOT format for visualization. * - * @example + * **Example** (Exporting GraphViz DOT) + * * ```ts * import { Graph } from "effect" * @@ -2296,8 +2755,8 @@ export const toGraphViz: { * // } * ``` * - * @since 4.0.0 - * @category utils + * @category converting + * @since 3.18.0 */ ( graph: Graph | MutableGraph, @@ -2343,6 +2802,8 @@ export const toGraphViz: { /** * Mermaid node shape types for diagram visualization. * + * **Details** + * * Each shape produces different visual representations in Mermaid diagrams: * - `rectangle`: Standard rectangular nodes `A["label"]` * - `rounded`: Rounded rectangular nodes `A("label")` @@ -2353,9 +2814,10 @@ export const toGraphViz: { * - `subroutine`: Subroutine-style nodes `A[["label"]]` * - `cylindrical`: Cylindrical database-style nodes `A[("label")]` * - * @example + * **Example** (Selecting Mermaid node shapes) + * * ```ts - * import type * as Graph from "effect/Graph" + * import type { Graph } from "effect" * * // Shape selector function for different node types * const shapeSelector = (nodeData: string): Graph.MermaidNodeShape => { @@ -2371,8 +2833,8 @@ export const toGraphViz: { * } * ``` * - * @since 4.0.0 * @category models + * @since 3.18.0 */ export type MermaidNodeShape = | "rectangle" // A["label"] @@ -2387,15 +2849,18 @@ export type MermaidNodeShape = /** * Mermaid diagram direction types for controlling layout orientation. * + * **Details** + * * Determines the flow direction of nodes and edges in the diagram: * - `TB`/`TD`: Top to Bottom (vertical layout, default) * - `BT`: Bottom to Top (reverse vertical) * - `LR`: Left to Right (horizontal layout) * - `RL`: Right to Left (reverse horizontal) * - * @example + * **Example** (Configuring Mermaid directions) + * * ```ts - * import type * as Graph from "effect/Graph" + * import type { Graph } from "effect" * * // Horizontal workflow diagram * const horizontalOptions: Graph.MermaidOptions = { @@ -2413,8 +2878,8 @@ export type MermaidNodeShape = * } * ``` * - * @since 4.0.0 * @category models + * @since 3.18.0 */ export type MermaidDirection = | "TB" // Top to Bottom (default) @@ -2426,6 +2891,8 @@ export type MermaidDirection = /** * Mermaid diagram types for different visualization formats. * + * **Details** + * * Specifies the Mermaid diagram syntax to use: * - `flowchart`: For directed graphs with arrows (`A --> B`) * - `graph`: For undirected graphs with lines (`A --- B`) @@ -2433,9 +2900,10 @@ export type MermaidDirection = * When not specified, automatically selects based on graph type: * directed graphs use "flowchart", undirected graphs use "graph". * - * @example + * **Example** (Selecting Mermaid diagram types) + * * ```ts - * import type * as Graph from "effect/Graph" + * import type { Graph } from "effect" * * // Force flowchart format (even for undirected graphs) * const flowchartOptions: Graph.MermaidOptions = { @@ -2451,8 +2919,8 @@ export type MermaidDirection = * const autoOptions: Graph.MermaidOptions = {} * ``` * - * @since 4.0.0 * @category models + * @since 3.18.0 */ export type MermaidDiagramType = | "flowchart" // For directed graphs @@ -2461,18 +2929,21 @@ export type MermaidDiagramType = /** * Configuration options for Mermaid diagram generation, following GraphViz pattern. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ /** * Configuration options for Mermaid diagram generation from graphs. * - * Provides customization for node labels, edge labels, diagram type, - * layout direction, node shapes, and graph naming in Mermaid format. + * **Details** + * + * These options customize node labels, edge labels, diagram type, layout + * direction, node shapes, and graph naming in Mermaid format. + * + * **Example** (Configuring Mermaid output) * - * @example * ```ts - * import type * as Graph from "effect/Graph" + * import type { Graph } from "effect" * * // Basic options with custom labels * const basicOptions: Graph.MermaidOptions = { @@ -2490,8 +2961,8 @@ export type MermaidDiagramType = * } * ``` * - * @since 4.0.0 - * @category models + * @category options + * @since 3.18.0 */ export interface MermaidOptions { /** @@ -2582,14 +3053,17 @@ const formatMermaidNode = ( /** * Exports a graph to Mermaid diagram format for visualization. * + * **Details** + * * Mermaid is a popular diagram-as-code tool that generates flowcharts and other * visualizations from text-based definitions. This function converts Effect Graph * structures to valid Mermaid syntax for use in documentation, web applications, * and visualization tools. * - * @example + * **Example** (Exporting a directed Mermaid diagram) + * * ```ts - * import * as Graph from "effect/Graph" + * import { Graph } from "effect" * * // Basic directed graph export * const graph = Graph.directed((mutable) => { @@ -2610,9 +3084,10 @@ const formatMermaidNode = ( * // 0 -->|"2"| 2 * ``` * - * @example + * **Example** (Exporting an undirected Mermaid diagram) + * * ```ts - * import * as Graph from "effect/Graph" + * import { Graph } from "effect" * * // Undirected graph with custom labels and direction * const socialGraph = Graph.undirected<{ name: string }, string>((mutable) => { @@ -2637,9 +3112,10 @@ const formatMermaidNode = ( * // 1 ---|"colleagues"| 2 * ``` * - * @example + * **Example** (Customizing Mermaid node shapes) + * * ```ts - * import * as Graph from "effect/Graph" + * import { Graph } from "effect" * * // Advanced styling with node shapes for flowchart * const workflow = Graph.directed<{ type: string; name: string }, string>( @@ -2688,9 +3164,10 @@ const formatMermaidNode = ( * // 2 --> 3 * ``` * - * @example + * **Example** (Visualizing dependency graphs) + * * ```ts - * import * as Graph from "effect/Graph" + * import { Graph } from "effect" * * // Real-world example: Software dependency graph * interface Dependency { @@ -2749,25 +3226,24 @@ const formatMermaidNode = ( * // 0 -->|"builds with"| 3 * ``` * - * @param graph - The graph to export (directed or undirected) - * @param options - Optional configuration for the Mermaid output - * @returns Mermaid diagram syntax as a string - * - * @since 4.0.0 - * @category utils + * @category converting + * @since 3.18.0 */ export const toMermaid: { /** * Exports a graph to Mermaid diagram format for visualization. * + * **Details** + * * Mermaid is a popular diagram-as-code tool that generates flowcharts and other * visualizations from text-based definitions. This function converts Effect Graph * structures to valid Mermaid syntax for use in documentation, web applications, * and visualization tools. * - * @example + * **Example** (Exporting a directed Mermaid diagram) + * * ```ts - * import * as Graph from "effect/Graph" + * import { Graph } from "effect" * * // Basic directed graph export * const graph = Graph.directed((mutable) => { @@ -2788,9 +3264,10 @@ export const toMermaid: { * // 0 -->|"2"| 2 * ``` * - * @example + * **Example** (Exporting an undirected Mermaid diagram) + * * ```ts - * import * as Graph from "effect/Graph" + * import { Graph } from "effect" * * // Undirected graph with custom labels and direction * const socialGraph = Graph.undirected<{ name: string }, string>((mutable) => { @@ -2815,9 +3292,10 @@ export const toMermaid: { * // 1 ---|"colleagues"| 2 * ``` * - * @example + * **Example** (Customizing Mermaid node shapes) + * * ```ts - * import * as Graph from "effect/Graph" + * import { Graph } from "effect" * * // Advanced styling with node shapes for flowchart * const workflow = Graph.directed<{ type: string; name: string }, string>( @@ -2866,9 +3344,10 @@ export const toMermaid: { * // 2 --> 3 * ``` * - * @example + * **Example** (Visualizing dependency graphs) + * * ```ts - * import * as Graph from "effect/Graph" + * import { Graph } from "effect" * * // Real-world example: Software dependency graph * interface Dependency { @@ -2927,25 +3406,24 @@ export const toMermaid: { * // 0 -->|"builds with"| 3 * ``` * - * @param graph - The graph to export (directed or undirected) - * @param options - Optional configuration for the Mermaid output - * @returns Mermaid diagram syntax as a string - * - * @since 4.0.0 - * @category utils + * @category converting + * @since 3.18.0 */ (options?: MermaidOptions): (graph: Graph | MutableGraph) => string /** * Exports a graph to Mermaid diagram format for visualization. * + * **Details** + * * Mermaid is a popular diagram-as-code tool that generates flowcharts and other * visualizations from text-based definitions. This function converts Effect Graph * structures to valid Mermaid syntax for use in documentation, web applications, * and visualization tools. * - * @example + * **Example** (Exporting a directed Mermaid diagram) + * * ```ts - * import * as Graph from "effect/Graph" + * import { Graph } from "effect" * * // Basic directed graph export * const graph = Graph.directed((mutable) => { @@ -2966,9 +3444,10 @@ export const toMermaid: { * // 0 -->|"2"| 2 * ``` * - * @example + * **Example** (Exporting an undirected Mermaid diagram) + * * ```ts - * import * as Graph from "effect/Graph" + * import { Graph } from "effect" * * // Undirected graph with custom labels and direction * const socialGraph = Graph.undirected<{ name: string }, string>((mutable) => { @@ -2993,9 +3472,10 @@ export const toMermaid: { * // 1 ---|"colleagues"| 2 * ``` * - * @example + * **Example** (Customizing Mermaid node shapes) + * * ```ts - * import * as Graph from "effect/Graph" + * import { Graph } from "effect" * * // Advanced styling with node shapes for flowchart * const workflow = Graph.directed<{ type: string; name: string }, string>( @@ -3044,9 +3524,10 @@ export const toMermaid: { * // 2 --> 3 * ``` * - * @example + * **Example** (Visualizing dependency graphs) + * * ```ts - * import * as Graph from "effect/Graph" + * import { Graph } from "effect" * * // Real-world example: Software dependency graph * interface Dependency { @@ -3105,12 +3586,8 @@ export const toMermaid: { * // 0 -->|"builds with"| 3 * ``` * - * @param graph - The graph to export (directed or undirected) - * @param options - Optional configuration for the Mermaid output - * @returns Mermaid diagram syntax as a string - * - * @since 4.0.0 - * @category utils + * @category converting + * @since 3.18.0 */ ( graph: Graph | MutableGraph, @@ -3170,7 +3647,8 @@ export const toMermaid: { /** * Direction for graph traversal, indicating which edges to follow. * - * @example + * **Example** (Traversing by direction) + * * ```ts * import { Graph } from "effect" * @@ -3191,8 +3669,8 @@ export const toMermaid: { * ) * ``` * - * @since 4.0.0 * @category models + * @since 3.18.0 */ export type Direction = "outgoing" | "incoming" @@ -3201,13 +3679,16 @@ export type Direction = "outgoing" | "incoming" // ============================================================================= /** - * Checks if the graph is acyclic (contains no cycles). + * Checks whether the graph is acyclic (contains no cycles). + * + * **Details** * * Uses depth-first search to detect back edges, which indicate cycles. * For directed graphs, any back edge creates a cycle. For undirected graphs, * a back edge that doesn't go to the immediate parent creates a cycle. * - * @example + * **Example** (Checking cycles) + * * ```ts * import { Graph } from "effect" * @@ -3231,8 +3712,8 @@ export type Direction = "outgoing" | "incoming" * console.log(Graph.isAcyclic(cyclic)) // false * ``` * - * @since 4.0.0 * @category algorithms + * @since 3.18.0 */ export const isAcyclic = ( graph: Graph | MutableGraph @@ -3242,6 +3723,37 @@ export const isAcyclic = ( return graph.acyclic.value } + if (graph.type === "undirected") { + const visited = new Set() + + for (const startNode of graph.nodes.keys()) { + if (visited.has(startNode)) { + continue + } + + visited.add(startNode) + const stack: Array<{ node: NodeIndex; parent: NodeIndex | null }> = [{ node: startNode, parent: null }] + + while (stack.length > 0) { + const { node, parent } = stack.pop()! + const nodeNeighbors = getUndirectedNeighbors(graph as any, node) + + for (const neighbor of nodeNeighbors) { + if (!visited.has(neighbor)) { + visited.add(neighbor) + stack.push({ node: neighbor, parent: node }) + } else if (neighbor !== parent) { + graph.acyclic = Option.some(false) + return false + } + } + } + } + + graph.acyclic = Option.some(true) + return true + } + // Stack-safe DFS cycle detection using iterative approach const visited = new Set() const recursionStack = new Set() @@ -3278,7 +3790,11 @@ export const isAcyclic = ( recursionStack.add(node) // Get neighbors for this node - const nodeNeighbors = Array.from(neighborsDirected(graph, node, "outgoing")) + const nodeNeighbors = getDirectedNeighbors( + graph as Graph | MutableGraph, + node, + "outgoing" + ) stack[stack.length - 1] = [node, nodeNeighbors, 0, false] continue } @@ -3311,13 +3827,16 @@ export const isAcyclic = ( } /** - * Checks if an undirected graph is bipartite. + * Checks whether an undirected graph is bipartite. + * + * **Details** * * A bipartite graph is one whose vertices can be divided into two disjoint sets * such that no two vertices within the same set are adjacent. Uses BFS coloring * to determine bipartiteness. * - * @example + * **Example** (Checking bipartite graphs) + * * ```ts * import { Graph } from "effect" * @@ -3345,8 +3864,8 @@ export const isAcyclic = ( * console.log(Graph.isBipartite(triangle)) // false * ``` * - * @since 4.0.0 * @category algorithms + * @since 3.18.0 */ export const isBipartite = ( graph: Graph | MutableGraph @@ -3422,11 +3941,27 @@ const getUndirectedNeighbors = ( return Array.from(neighbors) } +const getTraversalNeighbors = ( + graph: Graph | MutableGraph, + nodeIndex: NodeIndex, + direction: Direction +): Array => + graph.type === "undirected" + ? getUndirectedNeighbors(graph as any, nodeIndex) + : getDirectedNeighbors(graph as Graph | MutableGraph, nodeIndex, direction) + +const getTraversableNeighbor = ( + graph: Graph | MutableGraph, + current: NodeIndex, + edge: Edge +): NodeIndex => graph.type === "undirected" && edge.target === current ? edge.source : edge.target + /** - * Find connected components in an undirected graph. + * Finds connected components in an undirected graph. * Each component is represented as an array of node indices. * - * @example + * **Example** (Finding connected components) + * * ```ts * import { Graph } from "effect" * @@ -3443,8 +3978,8 @@ const getUndirectedNeighbors = ( * console.log(components) // [[0, 1], [2, 3]] * ``` * - * @since 4.0.0 * @category algorithms + * @since 3.18.0 */ export const connectedComponents = ( graph: Graph | MutableGraph @@ -3481,10 +4016,15 @@ export const connectedComponents = ( } /** - * Find strongly connected components in a directed graph using Kosaraju's algorithm. + * Finds strongly connected components in a directed graph using Kosaraju's algorithm. * Each SCC is represented as an array of node indices. * - * @example + * **Gotchas** + * + * Throws a `GraphError` when used with an undirected graph. + * + * **Example** (Finding strongly connected components) + * * ```ts * import { Graph } from "effect" * @@ -3501,12 +4041,16 @@ export const connectedComponents = ( * console.log(sccs) // [[0, 1, 2]] * ``` * - * @since 4.0.0 * @category algorithms + * @since 3.18.0 */ -export const stronglyConnectedComponents = ( - graph: Graph | MutableGraph +export const stronglyConnectedComponents = ( + graph: Graph | MutableGraph ): Array> => { + if ((graph as Graph | MutableGraph).type === "undirected") { + throw new GraphError({ message: "Cannot find strongly connected components of undirected graph" }) + } + const visited = new Set() const finishOrder: Array = [] // Iterate directly over node keys @@ -3532,7 +4076,7 @@ export const stronglyConnectedComponents = ( } visited.add(node) - const nodeNeighborsList = neighbors(graph, node) + const nodeNeighborsList = getDirectedNeighbors(graph, node, "outgoing") stack[stack.length - 1] = [node, nodeNeighborsList, 0, false] continue } @@ -3602,10 +4146,31 @@ export const stronglyConnectedComponents = ( // ============================================================================= /** - * Result of a shortest path computation containing the path and total distance. + * Result of a shortest path computation. + * + * **When to use** + * + * Use to read the successful source-to-target shortest path returned by + * path-finding algorithms, including the ordered node indices, total distance, + * and traversed edge data. + * + * **Details** + * + * Contains the node-index path, the total numeric distance, and the edge data + * encountered along the path. + * + * **Gotchas** + * + * `costs` contains original edge data, not the numeric output of the cost + * function unless the edge data is numeric. + * + * @see {@link dijkstra} for shortest paths with non-negative edge costs + * @see {@link astar} for heuristic shortest-path search + * @see {@link bellmanFord} for shortest paths that may include negative edge weights + * @see {@link AllPairsResult} for the all-pairs shortest-path result shape * - * @since 4.0.0 * @category models + * @since 3.18.0 */ export interface PathResult { readonly path: Array @@ -3614,10 +4179,29 @@ export interface PathResult { } /** - * Configuration for Dijkstra's algorithm. + * Configuration for finding a shortest path with Dijkstra's algorithm. + * + * **When to use** + * + * Use when configuring `dijkstra` to find a shortest path between two existing + * node indices with non-negative edge costs. + * + * **Details** + * + * Specifies the source and target node indices, plus a cost function that maps + * each edge's data to a non-negative numeric weight. + * + * **Gotchas** + * + * `dijkstra` throws a `GraphError` when either endpoint does not exist or when + * the cost function returns a negative weight. + * + * @see {@link dijkstra} for the algorithm that consumes this configuration + * @see {@link AstarConfig} for heuristic shortest-path search + * @see {@link BellmanFordConfig} for shortest paths that may include negative edge weights * - * @since 4.0.0 * @category models + * @since 3.18.0 */ export interface DijkstraConfig { source: NodeIndex @@ -3625,13 +4209,34 @@ export interface DijkstraConfig { cost: (edgeData: E) => number } +const validateNonNegativeEdgeWeights = ( + graph: Graph | MutableGraph, + cost: (edgeData: E) => number, + algorithm: string +): Map => { + const edgeWeights = new Map() + for (const [edgeIndex, edgeData] of graph.edges) { + const weight = cost(edgeData.data) + if (weight < 0 || Number.isNaN(weight)) { + throw new GraphError({ message: `${algorithm} requires non-negative edge weights` }) + } + edgeWeights.set(edgeIndex, weight) + } + return edgeWeights +} + /** - * Find the shortest path between two nodes using Dijkstra's algorithm. + * Finds the shortest path from the configured source node to the target node + * using Dijkstra's algorithm. * - * Dijkstra's algorithm works with non-negative edge weights and finds the shortest - * path from a source node to a target node in O((V + E) log V) time complexity. + * **Details** + * + * Edge costs must be non-negative. Returns `Option.none()` when the target is + * not reachable, and throws a `GraphError` when either endpoint is missing or a + * negative edge cost is encountered. + * + * **Example** (Finding shortest paths with Dijkstra) * - * @example * ```ts * import { Graph } from "effect" * @@ -3656,17 +4261,22 @@ export interface DijkstraConfig { * } * ``` * - * @since 4.0.0 * @category algorithms + * @since 3.18.0 */ export const dijkstra: { /** - * Find the shortest path between two nodes using Dijkstra's algorithm. + * Finds the shortest path from the configured source node to the target node + * using Dijkstra's algorithm. + * + * **Details** * - * Dijkstra's algorithm works with non-negative edge weights and finds the shortest - * path from a source node to a target node in O((V + E) log V) time complexity. + * Edge costs must be non-negative. Returns `Option.none()` when the target is + * not reachable, and throws a `GraphError` when either endpoint is missing or a + * negative edge cost is encountered. + * + * **Example** (Finding shortest paths with Dijkstra) * - * @example * ```ts * import { Graph } from "effect" * @@ -3691,17 +4301,22 @@ export const dijkstra: { * } * ``` * - * @since 4.0.0 * @category algorithms + * @since 3.18.0 */ (config: DijkstraConfig): (graph: Graph | MutableGraph) => Option.Option> /** - * Find the shortest path between two nodes using Dijkstra's algorithm. + * Finds the shortest path from the configured source node to the target node + * using Dijkstra's algorithm. + * + * **Details** + * + * Edge costs must be non-negative. Returns `Option.none()` when the target is + * not reachable, and throws a `GraphError` when either endpoint is missing or a + * negative edge cost is encountered. * - * Dijkstra's algorithm works with non-negative edge weights and finds the shortest - * path from a source node to a target node in O((V + E) log V) time complexity. + * **Example** (Finding shortest paths with Dijkstra) * - * @example * ```ts * import { Graph } from "effect" * @@ -3726,8 +4341,8 @@ export const dijkstra: { * } * ``` * - * @since 4.0.0 * @category algorithms + * @since 3.18.0 */ (graph: Graph | MutableGraph, config: DijkstraConfig): Option.Option> } = dual(2, ( @@ -3742,6 +4357,8 @@ export const dijkstra: { throw missingNode(config.target) } + const edgeWeights = validateNonNegativeEdgeWeights(graph, config.cost, "Dijkstra's algorithm") + // Early return if source equals target if (config.source === config.target) { return Option.some({ @@ -3801,13 +4418,8 @@ export const dijkstra: { for (const edgeIndex of adjacencyList) { const edge = graph.edges.get(edgeIndex) if (edge !== undefined) { - const neighbor = edge.target - const cost = config.cost(edge.data) - - // Validate non-negative weights - if (cost < 0) { - throw new GraphError({ message: "Dijkstra's algorithm requires non-negative edge weights" }) - } + const neighbor = getTraversableNeighbor(graph, currentNode, edge) + const cost = edgeWeights.get(edgeIndex)! const newDistance = currentDistance + cost const neighborDistance = distances.get(neighbor)! @@ -3857,10 +4469,24 @@ export const dijkstra: { }) /** - * Result of all-pairs shortest path computation. + * Result of an all-pairs shortest path computation. + * + * **When to use** + * + * Use when storing or passing around the complete output of `floydWarshall` so + * callers can look up shortest distances, node paths, and edge data for any + * source and target node pair. + * + * **Details** + * + * Contains distance, node-path, and edge-data maps keyed by source and target + * node indices. + * + * @see {@link floydWarshall} for computing an all-pairs shortest path result + * @see {@link PathResult} for the single source-to-target result shape used by path-finding algorithms * - * @since 4.0.0 * @category models + * @since 3.18.0 */ export interface AllPairsResult { readonly distances: Map> @@ -3869,14 +4495,17 @@ export interface AllPairsResult { } /** - * Find shortest paths between all pairs of nodes using Floyd-Warshall algorithm. + * Finds shortest paths between all pairs of nodes using the Floyd-Warshall + * algorithm. * - * Floyd-Warshall algorithm computes shortest paths between all pairs of nodes in O(V³) time. - * It can handle negative edge weights and detect negative cycles. + * **Details** * - * Throws if a negative cycle is detected that affects the path to target. + * Computes distances, reconstructed node paths, and edge-data paths for every + * source and target pair in O(V^3) time. Negative edge weights are allowed, but + * a `GraphError` is thrown if any negative cycle is detected. + * + * **Example** (Finding all-pairs shortest paths) * - * @example * ```ts * import { Graph } from "effect" * @@ -3894,19 +4523,22 @@ export interface AllPairsResult { * const pathAToC = result.paths.get(0)?.get(2) // [0, 1, 2] * ``` * - * @since 4.0.0 * @category algorithms + * @since 3.18.0 */ export const floydWarshall: { /** - * Find shortest paths between all pairs of nodes using Floyd-Warshall algorithm. + * Finds shortest paths between all pairs of nodes using the Floyd-Warshall + * algorithm. * - * Floyd-Warshall algorithm computes shortest paths between all pairs of nodes in O(V³) time. - * It can handle negative edge weights and detect negative cycles. + * **Details** * - * Throws if a negative cycle is detected that affects the path to target. + * Computes distances, reconstructed node paths, and edge-data paths for every + * source and target pair in O(V^3) time. Negative edge weights are allowed, but + * a `GraphError` is thrown if any negative cycle is detected. + * + * **Example** (Finding all-pairs shortest paths) * - * @example * ```ts * import { Graph } from "effect" * @@ -3924,19 +4556,22 @@ export const floydWarshall: { * const pathAToC = result.paths.get(0)?.get(2) // [0, 1, 2] * ``` * - * @since 4.0.0 * @category algorithms + * @since 3.18.0 */ (cost: (edgeData: E) => number): (graph: Graph | MutableGraph) => AllPairsResult /** - * Find shortest paths between all pairs of nodes using Floyd-Warshall algorithm. + * Finds shortest paths between all pairs of nodes using the Floyd-Warshall + * algorithm. * - * Floyd-Warshall algorithm computes shortest paths between all pairs of nodes in O(V³) time. - * It can handle negative edge weights and detect negative cycles. + * **Details** * - * Throws if a negative cycle is detected that affects the path to target. + * Computes distances, reconstructed node paths, and edge-data paths for every + * source and target pair in O(V^3) time. Negative edge weights are allowed, but + * a `GraphError` is thrown if any negative cycle is detected. + * + * **Example** (Finding all-pairs shortest paths) * - * @example * ```ts * import { Graph } from "effect" * @@ -3954,8 +4589,8 @@ export const floydWarshall: { * const pathAToC = result.paths.get(0)?.get(2) // [0, 1, 2] * ``` * - * @since 4.0.0 * @category algorithms + * @since 3.18.0 */ ( graph: Graph | MutableGraph, @@ -3999,6 +4634,15 @@ export const floydWarshall: { next.get(i)!.set(j, j) edgeMatrix.get(i)!.set(j, edgeData.data) } + + if (graph.type === "undirected") { + const reverseWeight = distances.get(j)!.get(i)! + if (weight < reverseWeight) { + distances.get(j)!.set(i, weight) + next.get(j)!.set(i, i) + edgeMatrix.get(j)!.set(i, edgeData.data) + } + } } // Floyd-Warshall main loop @@ -4073,10 +4717,24 @@ export const floydWarshall: { }) /** - * Configuration for A* pathfinding algorithm. + * Configuration for finding a shortest path with the A* algorithm. + * + * **When to use** + * + * Use when configuring `astar` for point-to-point shortest-path searches where + * node data can provide a heuristic estimate toward the target. + * + * **Details** + * + * Specifies the source and target node indices, an edge-cost function, and a + * heuristic that estimates the remaining cost from a node to the target. + * + * @see {@link astar} for the algorithm that consumes this configuration + * @see {@link DijkstraConfig} for shortest paths without a heuristic + * @see {@link BellmanFordConfig} for shortest paths that may include negative edge weights * - * @since 4.0.0 * @category models + * @since 3.18.0 */ export interface AstarConfig { source: NodeIndex @@ -4086,13 +4744,18 @@ export interface AstarConfig { } /** - * Find the shortest path between two nodes using A* pathfinding algorithm. + * Finds the shortest path from the configured source node to the target node + * using the A* pathfinding algorithm. + * + * **Details** * - * A* is an extension of Dijkstra's algorithm that uses a heuristic function to guide - * the search towards the target, potentially finding paths faster than Dijkstra's. - * The heuristic must be admissible (never overestimate the actual cost). + * The edge-cost function must return non-negative weights, and the heuristic + * should be consistent to preserve shortest-path guarantees. Returns + * `Option.none()` when the target is not reachable, and throws a `GraphError` + * when either endpoint is missing or a negative edge cost is encountered. + * + * **Example** (Finding shortest paths with A-star) * - * @example * ```ts * import { Graph } from "effect" * @@ -4123,18 +4786,23 @@ export interface AstarConfig { * } * ``` * - * @since 4.0.0 * @category algorithms + * @since 3.18.0 */ export const astar: { /** - * Find the shortest path between two nodes using A* pathfinding algorithm. + * Finds the shortest path from the configured source node to the target node + * using the A* pathfinding algorithm. * - * A* is an extension of Dijkstra's algorithm that uses a heuristic function to guide - * the search towards the target, potentially finding paths faster than Dijkstra's. - * The heuristic must be admissible (never overestimate the actual cost). + * **Details** + * + * The edge-cost function must return non-negative weights, and the heuristic + * should be consistent to preserve shortest-path guarantees. Returns + * `Option.none()` when the target is not reachable, and throws a `GraphError` + * when either endpoint is missing or a negative edge cost is encountered. + * + * **Example** (Finding shortest paths with A-star) * - * @example * ```ts * import { Graph } from "effect" * @@ -4165,18 +4833,23 @@ export const astar: { * } * ``` * - * @since 4.0.0 * @category algorithms + * @since 3.18.0 */ (config: AstarConfig): (graph: Graph | MutableGraph) => Option.Option> /** - * Find the shortest path between two nodes using A* pathfinding algorithm. + * Finds the shortest path from the configured source node to the target node + * using the A* pathfinding algorithm. + * + * **Details** * - * A* is an extension of Dijkstra's algorithm that uses a heuristic function to guide - * the search towards the target, potentially finding paths faster than Dijkstra's. - * The heuristic must be admissible (never overestimate the actual cost). + * The edge-cost function must return non-negative weights, and the heuristic + * should be consistent to preserve shortest-path guarantees. Returns + * `Option.none()` when the target is not reachable, and throws a `GraphError` + * when either endpoint is missing or a negative edge cost is encountered. + * + * **Example** (Finding shortest paths with A-star) * - * @example * ```ts * import { Graph } from "effect" * @@ -4207,8 +4880,8 @@ export const astar: { * } * ``` * - * @since 4.0.0 * @category algorithms + * @since 3.18.0 */ (graph: Graph | MutableGraph, config: AstarConfig): Option.Option> } = dual(2, ( @@ -4223,6 +4896,8 @@ export const astar: { throw missingNode(config.target) } + const edgeWeights = validateNonNegativeEdgeWeights(graph, config.cost, "A* algorithm") + // Early return if source equals target if (config.source === config.target) { return Option.some({ @@ -4297,13 +4972,8 @@ export const astar: { for (const edgeIndex of adjacencyList) { const edge = graph.edges.get(edgeIndex) if (edge !== undefined) { - const neighbor = edge.target - const weight = config.cost(edge.data) - - // Validate non-negative weights - if (weight < 0) { - throw new GraphError({ message: "A* algorithm requires non-negative edge weights" }) - } + const neighbor = getTraversableNeighbor(graph, currentNode, edge) + const weight = edgeWeights.get(edgeIndex)! const tentativeGScore = currentGScore + weight const neighborGScore = gScore.get(neighbor)! @@ -4362,10 +5032,24 @@ export const astar: { }) /** - * Configuration for Bellman-Ford algorithm. + * Configuration for finding a shortest path with the Bellman-Ford algorithm. + * + * **When to use** + * + * Use when configuring `bellmanFord` to find a shortest path where edge + * weights may be negative. + * + * **Details** + * + * Specifies the source and target node indices, plus a cost function that maps + * each edge's data to a numeric weight. + * + * @see {@link bellmanFord} for the algorithm that consumes this configuration + * @see {@link DijkstraConfig} for non-negative edge costs + * @see {@link AstarConfig} for heuristic shortest-path search * - * @since 4.0.0 * @category models + * @since 3.18.0 */ export interface BellmanFordConfig { source: NodeIndex @@ -4374,13 +5058,17 @@ export interface BellmanFordConfig { } /** - * Find the shortest path between two nodes using Bellman-Ford algorithm. + * Finds the shortest path from the configured source node to the target node + * using the Bellman-Ford algorithm. + * + * **Details** * - * Bellman-Ford algorithm can handle negative edge weights and detects negative cycles. - * It has O(VE) time complexity, slower than Dijkstra's but more versatile. - * Returns Option.none() if a negative cycle is detected that affects the path. + * Negative edge weights are allowed. Returns `Option.none()` when the target is + * unreachable or when a negative cycle affects the path to the target. Throws a + * `GraphError` when either endpoint is missing. + * + * **Example** (Finding shortest paths with Bellman-Ford) * - * @example * ```ts * import { Graph } from "effect" * @@ -4405,18 +5093,22 @@ export interface BellmanFordConfig { * } * ``` * - * @since 4.0.0 * @category algorithms + * @since 3.18.0 */ export const bellmanFord: { /** - * Find the shortest path between two nodes using Bellman-Ford algorithm. + * Finds the shortest path from the configured source node to the target node + * using the Bellman-Ford algorithm. + * + * **Details** + * + * Negative edge weights are allowed. Returns `Option.none()` when the target is + * unreachable or when a negative cycle affects the path to the target. Throws a + * `GraphError` when either endpoint is missing. * - * Bellman-Ford algorithm can handle negative edge weights and detects negative cycles. - * It has O(VE) time complexity, slower than Dijkstra's but more versatile. - * Returns Option.none() if a negative cycle is detected that affects the path. + * **Example** (Finding shortest paths with Bellman-Ford) * - * @example * ```ts * import { Graph } from "effect" * @@ -4441,18 +5133,22 @@ export const bellmanFord: { * } * ``` * - * @since 4.0.0 * @category algorithms + * @since 3.18.0 */ (config: BellmanFordConfig): (graph: Graph | MutableGraph) => Option.Option> /** - * Find the shortest path between two nodes using Bellman-Ford algorithm. + * Finds the shortest path from the configured source node to the target node + * using the Bellman-Ford algorithm. + * + * **Details** * - * Bellman-Ford algorithm can handle negative edge weights and detects negative cycles. - * It has O(VE) time complexity, slower than Dijkstra's but more versatile. - * Returns Option.none() if a negative cycle is detected that affects the path. + * Negative edge weights are allowed. Returns `Option.none()` when the target is + * unreachable or when a negative cycle affects the path to the target. Throws a + * `GraphError` when either endpoint is missing. + * + * **Example** (Finding shortest paths with Bellman-Ford) * - * @example * ```ts * import { Graph } from "effect" * @@ -4477,8 +5173,8 @@ export const bellmanFord: { * } * ``` * - * @since 4.0.0 * @category algorithms + * @since 3.18.0 */ ( graph: Graph | MutableGraph, @@ -4525,6 +5221,14 @@ export const bellmanFord: { weight, edgeData: edgeData.data }) + if (graph.type === "undirected" && edgeData.source !== edgeData.target) { + edges.push({ + source: edgeData.target, + target: edgeData.source, + weight, + edgeData: edgeData.data + }) + } } // Relax edges up to V-1 times @@ -4566,14 +5270,8 @@ export const bellmanFord: { affectedNodes.add(node) // Add all nodes reachable from this node - const adjacencyList = graph.adjacency.get(node) - if (adjacencyList !== undefined) { - for (const edgeIndex of adjacencyList) { - const edge = graph.edges.get(edgeIndex) - if (edge !== undefined) { - queue.push(edge.target) - } - } + for (const neighbor of getTraversalNeighbors(graph, node, "outgoing")) { + queue.push(neighbor) } } @@ -4614,13 +5312,16 @@ export const bellmanFord: { }) /** - * Concrete class for iterables that produce [NodeIndex, NodeData] tuples. + * Represents an iterable wrapper used by graph traversal and listing APIs. + * + * **Details** + * + * A `Walker` yields `[index, data]` pairs lazily and can be viewed as just the + * indices, just the values, or mapped entries with `indices`, `values`, + * `entries`, and `visit`. * - * This class provides a common abstraction for all iterables that return node data, - * including traversal iterators (DFS, BFS, etc.) and element iterators (nodes, externals). - * It uses a mapEntry function pattern for flexible iteration and transformation. + * **Example** (Working with node walkers) * - * @example * ```ts * import { Graph } from "effect" * @@ -4644,8 +5345,8 @@ export const bellmanFord: { * const nodeEntries = Array.from(Graph.entries(allNodes)) // [[0, "A"], [1, "B"]] * ``` * - * @since 4.0.0 * @category models + * @since 3.18.0 */ export class Walker implements Iterable<[T, N]> { // @ts-ignore @@ -4654,11 +5355,14 @@ export class Walker implements Iterable<[T, N]> { /** * Visits each element and maps it to a value using the provided function. * + * **Details** + * * Takes a function that receives the index and data, * and returns an iterable of the mapped values. Skips elements that * no longer exist in the graph. * - * @example + * **Example** (Visiting walker elements) + * * ```ts * import { Graph } from "effect" * @@ -4682,7 +5386,6 @@ export class Walker implements Iterable<[T, N]> { * ``` * * @since 4.0.0 - * @category iterators */ readonly visit: (f: (index: T, data: N) => U) => Iterable @@ -4694,7 +5397,8 @@ export class Walker implements Iterable<[T, N]> { * and returns an iterable of the mapped values. Skips elements that * no longer exist in the graph. * - * @example + * **Example** (Visiting walker elements) + * * ```ts * import { Graph } from "effect" * @@ -4717,8 +5421,8 @@ export class Walker implements Iterable<[T, N]> { * console.log(custom) // [{ id: 0, name: "A" }, { id: 1, name: "B" }] * ``` * - * @since 4.0.0 * @category iterators + * @since 4.0.0 */ visit: (f: (index: T, data: N) => U) => Iterable ) { @@ -4731,8 +5435,16 @@ export class Walker implements Iterable<[T, N]> { * Type alias for node iteration using Walker. * NodeWalker is represented as Walker. * - * @since 4.0.0 + * **When to use** + * + * Use as the shared node walker type returned by graph traversal and node + * listing APIs. + * + * @see {@link Walker} for the generic lazy iterator wrapper + * @see {@link EdgeWalker} for edge iterators + * * @category models + * @since 3.18.0 */ export type NodeWalker = Walker @@ -4740,15 +5452,26 @@ export type NodeWalker = Walker * Type alias for edge iteration using Walker. * EdgeWalker is represented as Walker>. * - * @since 4.0.0 + * **When to use** + * + * Use to type helpers or parameters that consume edge iterators returned by + * `Graph` APIs, where each item is keyed by an `EdgeIndex` and carries the + * full `Edge`. + * + * @see {@link Walker} for the generic lazy iterator wrapper + * @see {@link NodeWalker} for node iterators + * @see {@link edges} for creating edge walkers + * * @category models + * @since 3.18.0 */ export type EdgeWalker = Walker> /** * Returns an iterator over the indices in the walker. * - * @example + * **Example** (Iterating walker indices) + * * ```ts * import { Graph } from "effect" * @@ -4763,15 +5486,16 @@ export type EdgeWalker = Walker> * console.log(indices) // [0, 1] * ``` * - * @since 4.0.0 - * @category utilities + * @category iterators + * @since 3.18.0 */ export const indices = (walker: Walker): Iterable => walker.visit((index, _) => index) /** * Returns an iterator over the values (data) in the walker. * - * @example + * **Example** (Iterating walker values) + * * ```ts * import { Graph } from "effect" * @@ -4786,15 +5510,16 @@ export const indices = (walker: Walker): Iterable => walker.visit * console.log(values) // ["A", "B"] * ``` * - * @since 4.0.0 - * @category utilities + * @category iterators + * @since 3.18.0 */ export const values = (walker: Walker): Iterable => walker.visit((_, data) => data) /** * Returns an iterator over [index, data] entries in the walker. * - * @example + * **Example** (Iterating walker entries) + * * ```ts * import { Graph } from "effect" * @@ -4809,17 +5534,37 @@ export const values = (walker: Walker): Iterable => walker.visit( * console.log(entries) // [[0, "A"], [1, "B"]] * ``` * - * @since 4.0.0 - * @category utilities + * @category iterators + * @since 3.18.0 */ export const entries = (walker: Walker): Iterable<[T, N]> => walker.visit((index, data) => [index, data] as [T, N]) /** - * Configuration options for search iterators. + * Configuration for DFS, BFS, and postorder graph traversals. + * + * **When to use** + * + * Use to configure the starting node indices and edge-following direction for + * lazy graph traversals. + * + * **Details** + * + * `start` supplies the node indices where traversal begins. If it is omitted, + * the iterator is empty. `direction` chooses whether traversal follows + * outgoing or incoming edges. + * + * **Gotchas** + * + * Traversal creation throws a `GraphError` when any configured `start` node + * does not exist. + * + * @see {@link dfs} for depth-first traversal + * @see {@link bfs} for breadth-first traversal + * @see {@link dfsPostOrder} for depth-first postorder traversal * - * @since 4.0.0 * @category models + * @since 3.18.0 */ export interface SearchConfig { readonly start?: Array @@ -4827,12 +5572,17 @@ export interface SearchConfig { } /** - * Creates a new DFS iterator with optional configuration. + * Creates a lazy depth-first traversal iterator from the configured start + * nodes. * - * The iterator maintains a stack of nodes to visit and tracks discovered nodes. - * It provides lazy evaluation of the depth-first search. + * **Details** + * + * If no start nodes are supplied, the iterator is empty. The `direction` option + * chooses whether to follow outgoing or incoming edges. Throws a `GraphError` + * if any configured start node does not exist. + * + * **Example** (Traversing depth-first) * - * @example * ```ts * import { Graph } from "effect" * @@ -4855,17 +5605,22 @@ export interface SearchConfig { * // Can be used programmatically * ``` * - * @since 4.0.0 * @category iterators + * @since 3.18.0 */ export const dfs: { /** - * Creates a new DFS iterator with optional configuration. + * Creates a lazy depth-first traversal iterator from the configured start + * nodes. + * + * **Details** * - * The iterator maintains a stack of nodes to visit and tracks discovered nodes. - * It provides lazy evaluation of the depth-first search. + * If no start nodes are supplied, the iterator is empty. The `direction` option + * chooses whether to follow outgoing or incoming edges. Throws a `GraphError` + * if any configured start node does not exist. + * + * **Example** (Traversing depth-first) * - * @example * ```ts * import { Graph } from "effect" * @@ -4888,17 +5643,22 @@ export const dfs: { * // Can be used programmatically * ``` * - * @since 4.0.0 * @category iterators + * @since 3.18.0 */ (config?: SearchConfig): (graph: Graph | MutableGraph) => NodeWalker /** - * Creates a new DFS iterator with optional configuration. + * Creates a lazy depth-first traversal iterator from the configured start + * nodes. + * + * **Details** + * + * If no start nodes are supplied, the iterator is empty. The `direction` option + * chooses whether to follow outgoing or incoming edges. Throws a `GraphError` + * if any configured start node does not exist. * - * The iterator maintains a stack of nodes to visit and tracks discovered nodes. - * It provides lazy evaluation of the depth-first search. + * **Example** (Traversing depth-first) * - * @example * ```ts * import { Graph } from "effect" * @@ -4921,8 +5681,8 @@ export const dfs: { * // Can be used programmatically * ``` * - * @since 4.0.0 * @category iterators + * @since 3.18.0 */ (graph: Graph | MutableGraph, config?: SearchConfig): NodeWalker } = dual((args) => isGraph(args[0]), ( @@ -4959,7 +5719,7 @@ export const dfs: { continue } - const neighbors = neighborsDirected(graph, current, direction) + const neighbors = getTraversalNeighbors(graph, current, direction) for (let i = neighbors.length - 1; i >= 0; i--) { const neighbor = neighbors[i] if (!discovered.has(neighbor)) { @@ -4979,12 +5739,17 @@ export const dfs: { }) /** - * Creates a new BFS iterator with optional configuration. + * Creates a lazy breadth-first traversal iterator from the configured start + * nodes. + * + * **Details** * - * The iterator maintains a queue of nodes to visit and tracks discovered nodes. - * It provides lazy evaluation of the breadth-first search. + * If no start nodes are supplied, the iterator is empty. The `direction` option + * chooses whether to follow outgoing or incoming edges. Throws a `GraphError` + * if any configured start node does not exist. + * + * **Example** (Traversing breadth-first) * - * @example * ```ts * import { Graph } from "effect" * @@ -5007,17 +5772,22 @@ export const dfs: { * // Can be used programmatically * ``` * - * @since 4.0.0 * @category iterators + * @since 3.18.0 */ export const bfs: { /** - * Creates a new BFS iterator with optional configuration. + * Creates a lazy breadth-first traversal iterator from the configured start + * nodes. * - * The iterator maintains a queue of nodes to visit and tracks discovered nodes. - * It provides lazy evaluation of the breadth-first search. + * **Details** + * + * If no start nodes are supplied, the iterator is empty. The `direction` option + * chooses whether to follow outgoing or incoming edges. Throws a `GraphError` + * if any configured start node does not exist. + * + * **Example** (Traversing breadth-first) * - * @example * ```ts * import { Graph } from "effect" * @@ -5040,17 +5810,22 @@ export const bfs: { * // Can be used programmatically * ``` * - * @since 4.0.0 * @category iterators + * @since 3.18.0 */ (config?: SearchConfig): (graph: Graph | MutableGraph) => NodeWalker /** - * Creates a new BFS iterator with optional configuration. + * Creates a lazy breadth-first traversal iterator from the configured start + * nodes. + * + * **Details** * - * The iterator maintains a queue of nodes to visit and tracks discovered nodes. - * It provides lazy evaluation of the breadth-first search. + * If no start nodes are supplied, the iterator is empty. The `direction` option + * chooses whether to follow outgoing or incoming edges. Throws a `GraphError` + * if any configured start node does not exist. + * + * **Example** (Traversing breadth-first) * - * @example * ```ts * import { Graph } from "effect" * @@ -5073,8 +5848,8 @@ export const bfs: { * // Can be used programmatically * ``` * - * @since 4.0.0 * @category iterators + * @since 3.18.0 */ (graph: Graph | MutableGraph, config?: SearchConfig): NodeWalker } = dual((args) => isGraph(args[0]), ( @@ -5103,7 +5878,7 @@ export const bfs: { if (!discovered.has(current)) { discovered.add(current) - const neighbors = neighborsDirected(graph, current, direction) + const neighbors = getTraversalNeighbors(graph, current, direction) for (const neighbor of neighbors) { if (!discovered.has(neighbor)) { queue.push(neighbor) @@ -5127,10 +5902,26 @@ export const bfs: { }) /** - * Configuration options for topological sort iterator. + * Configuration for the topological sort iterator. + * + * **When to use** + * + * Use to prioritize specific zero in-degree nodes in a topological sort. + * + * **Details** + * + * `initials` optionally supplies zero in-degree node indices used as + * prioritized initial queue entries. Topological sorting still includes the + * other zero in-degree nodes and produces a complete topological order. + * + * **Gotchas** + * + * Throws a `GraphError` when any initial node has incoming edges. + * + * @see {@link topo} for the iterator that consumes this configuration * - * @since 4.0.0 * @category models + * @since 3.18.0 */ export interface TopoConfig { readonly initials?: Array @@ -5139,10 +5930,13 @@ export interface TopoConfig { /** * Creates a new topological sort iterator with optional configuration. * + * **Details** + * * The iterator uses Kahn's algorithm to lazily produce nodes in topological order. * Throws an error if the graph contains cycles. * - * @example + * **Example** (Sorting topologically) + * * ```ts * import { Graph } from "effect" * @@ -5163,7 +5957,7 @@ export interface TopoConfig { * // With initial nodes * const topo2 = Graph.topo(graph, { initials: [0] }) * - * // Throws error for cyclic graph + * // Check before sorting a cyclic graph * const cyclicGraph = Graph.directed((mutable) => { * const a = Graph.addNode(mutable, "A") * const b = Graph.addNode(mutable, "B") @@ -5171,24 +5965,25 @@ export interface TopoConfig { * Graph.addEdge(mutable, b, a, 2) // Creates cycle * }) * - * try { - * Graph.topo(cyclicGraph) // Throws: "Cannot perform topological sort on cyclic graph" - * } catch (error) { - * console.log((error as Error).message) + * if (!Graph.isAcyclic(cyclicGraph)) { + * console.log("cyclic graph") // cyclic graph * } * ``` * - * @since 4.0.0 * @category iterators + * @since 3.18.0 */ export const topo: { /** * Creates a new topological sort iterator with optional configuration. * + * **Details** + * * The iterator uses Kahn's algorithm to lazily produce nodes in topological order. * Throws an error if the graph contains cycles. * - * @example + * **Example** (Sorting topologically) + * * ```ts * import { Graph } from "effect" * @@ -5209,7 +6004,7 @@ export const topo: { * // With initial nodes * const topo2 = Graph.topo(graph, { initials: [0] }) * - * // Throws error for cyclic graph + * // Check before sorting a cyclic graph * const cyclicGraph = Graph.directed((mutable) => { * const a = Graph.addNode(mutable, "A") * const b = Graph.addNode(mutable, "B") @@ -5217,24 +6012,25 @@ export const topo: { * Graph.addEdge(mutable, b, a, 2) // Creates cycle * }) * - * try { - * Graph.topo(cyclicGraph) // Throws: "Cannot perform topological sort on cyclic graph" - * } catch (error) { - * console.log((error as Error).message) + * if (!Graph.isAcyclic(cyclicGraph)) { + * console.log("cyclic graph") // cyclic graph * } * ``` * - * @since 4.0.0 * @category iterators + * @since 3.18.0 */ (config?: TopoConfig): (graph: Graph | MutableGraph) => NodeWalker /** * Creates a new topological sort iterator with optional configuration. * + * **Details** + * * The iterator uses Kahn's algorithm to lazily produce nodes in topological order. * Throws an error if the graph contains cycles. * - * @example + * **Example** (Sorting topologically) + * * ```ts * import { Graph } from "effect" * @@ -5255,7 +6051,7 @@ export const topo: { * // With initial nodes * const topo2 = Graph.topo(graph, { initials: [0] }) * - * // Throws error for cyclic graph + * // Check before sorting a cyclic graph * const cyclicGraph = Graph.directed((mutable) => { * const a = Graph.addNode(mutable, "A") * const b = Graph.addNode(mutable, "B") @@ -5263,21 +6059,23 @@ export const topo: { * Graph.addEdge(mutable, b, a, 2) // Creates cycle * }) * - * try { - * Graph.topo(cyclicGraph) // Throws: "Cannot perform topological sort on cyclic graph" - * } catch (error) { - * console.log((error as Error).message) + * if (!Graph.isAcyclic(cyclicGraph)) { + * console.log("cyclic graph") // cyclic graph * } * ``` * - * @since 4.0.0 * @category iterators + * @since 3.18.0 */ (graph: Graph | MutableGraph, config?: TopoConfig): NodeWalker } = dual((args) => isGraph(args[0]), ( graph: Graph | MutableGraph, config: TopoConfig = {} ): NodeWalker => { + if (graph.type === "undirected") { + throw new GraphError({ message: "Cannot perform topological sort on undirected graph" }) + } + // Check if graph is acyclic first if (!isAcyclic(graph)) { throw new GraphError({ message: "Cannot perform topological sort on cyclic graph" }) @@ -5296,6 +6094,7 @@ export const topo: { [Symbol.iterator]: () => { const inDegree = new Map() const remaining = new Set() + const initialSet = new Set(initials) const queue = [...initials] // Initialize in-degree counts @@ -5310,12 +6109,16 @@ export const topo: { inDegree.set(edgeData.target, currentInDegree + 1) } - // Add nodes with zero in-degree to queue if no initials provided - if (initials.length === 0) { - for (const [nodeIndex, degree] of inDegree) { - if (degree === 0) { - queue.push(nodeIndex) - } + for (const nodeIndex of initials) { + if (inDegree.get(nodeIndex)! !== 0) { + throw new GraphError({ message: `Initial node ${nodeIndex} has incoming edges` }) + } + } + + // Add remaining zero in-degree nodes after prioritized initials. + for (const [nodeIndex, degree] of inDegree) { + if (degree === 0 && !initialSet.has(nodeIndex)) { + queue.push(nodeIndex) } } @@ -5327,7 +6130,11 @@ export const topo: { remaining.delete(current) // Process outgoing edges, reducing in-degree of targets - const neighbors = neighborsDirected(graph, current, "outgoing") + const neighbors = getDirectedNeighbors( + graph as Graph | MutableGraph, + current, + "outgoing" + ) for (const neighbor of neighbors) { if (remaining.has(neighbor)) { const currentInDegree = inDegree.get(neighbor) || 0 @@ -5358,13 +6165,17 @@ export const topo: { }) /** - * Creates a new DFS postorder iterator with optional configuration. + * Creates a lazy depth-first postorder traversal iterator from the configured + * start nodes. + * + * **Details** + * + * Nodes are emitted after their reachable descendants have been processed. If + * no start nodes are supplied, the iterator is empty. The `direction` option + * chooses whether to follow outgoing or incoming edges. * - * The iterator maintains a stack with visit state tracking and emits nodes - * in postorder (after all descendants have been processed). Essential for - * dependency resolution and tree destruction algorithms. + * **Example** (Traversing in postorder) * - * @example * ```ts * import { Graph } from "effect" * @@ -5383,18 +6194,22 @@ export const topo: { * } * ``` * - * @since 4.0.0 * @category iterators + * @since 3.18.0 */ export const dfsPostOrder: { /** - * Creates a new DFS postorder iterator with optional configuration. + * Creates a lazy depth-first postorder traversal iterator from the configured + * start nodes. + * + * **Details** * - * The iterator maintains a stack with visit state tracking and emits nodes - * in postorder (after all descendants have been processed). Essential for - * dependency resolution and tree destruction algorithms. + * Nodes are emitted after their reachable descendants have been processed. If + * no start nodes are supplied, the iterator is empty. The `direction` option + * chooses whether to follow outgoing or incoming edges. + * + * **Example** (Traversing in postorder) * - * @example * ```ts * import { Graph } from "effect" * @@ -5413,18 +6228,22 @@ export const dfsPostOrder: { * } * ``` * - * @since 4.0.0 * @category iterators + * @since 3.18.0 */ (config?: SearchConfig): (graph: Graph | MutableGraph) => NodeWalker /** - * Creates a new DFS postorder iterator with optional configuration. + * Creates a lazy depth-first postorder traversal iterator from the configured + * start nodes. * - * The iterator maintains a stack with visit state tracking and emits nodes - * in postorder (after all descendants have been processed). Essential for - * dependency resolution and tree destruction algorithms. + * **Details** + * + * Nodes are emitted after their reachable descendants have been processed. If + * no start nodes are supplied, the iterator is empty. The `direction` option + * chooses whether to follow outgoing or incoming edges. + * + * **Example** (Traversing in postorder) * - * @example * ```ts * import { Graph } from "effect" * @@ -5443,8 +6262,8 @@ export const dfsPostOrder: { * } * ``` * - * @since 4.0.0 * @category iterators + * @since 3.18.0 */ (graph: Graph | MutableGraph, config?: SearchConfig): NodeWalker } = dual((args) => isGraph(args[0]), ( @@ -5483,7 +6302,7 @@ export const dfsPostOrder: { if (!current.visitedChildren) { current.visitedChildren = true - const neighbors = neighborsDirected(graph, current.node, direction) + const neighbors = getTraversalNeighbors(graph, current.node, direction) for (let i = neighbors.length - 1; i >= 0; i--) { const neighbor = neighbors[i] @@ -5517,10 +6336,13 @@ export const dfsPostOrder: { /** * Creates an iterator over all node indices in the graph. * + * **Details** + * * The iterator produces node indices in the order they were added to the graph. * This provides access to all nodes regardless of connectivity. * - * @example + * **Example** (Iterating all nodes) + * * ```ts * import { Graph } from "effect" * @@ -5535,8 +6357,8 @@ export const dfsPostOrder: { * console.log(indices) // [0, 1, 2] * ``` * - * @since 4.0.0 * @category iterators + * @since 3.18.0 */ export const nodes = ( graph: Graph | MutableGraph @@ -5562,10 +6384,13 @@ export const nodes = ( /** * Creates an iterator over all edge indices in the graph. * + * **Details** + * * The iterator produces edge indices in the order they were added to the graph. * This provides access to all edges regardless of connectivity. * - * @example + * **Example** (Iterating all edges) + * * ```ts * import { Graph } from "effect" * @@ -5581,8 +6406,8 @@ export const nodes = ( * console.log(indices) // [0, 1] * ``` * - * @since 4.0.0 * @category iterators + * @since 3.18.0 */ export const edges = ( graph: Graph | MutableGraph @@ -5606,23 +6431,40 @@ export const edges = ( })) /** - * Configuration for externals iterator. + * Configuration for selecting external nodes. + * + * **When to use** + * + * Use to configure how `externals` identifies graph boundary nodes when you + * need sinks with no outgoing edges or sources with no incoming edges. + * + * **Details** + * + * `direction` chooses which missing edge direction makes a node external: + * `"outgoing"` selects nodes with no outgoing edges, and `"incoming"` selects + * nodes with no incoming edges. If omitted, `direction` defaults to + * `"outgoing"`. + * + * @see {@link externals} for the iterator that consumes this configuration * - * @since 4.0.0 * @category models + * @since 3.18.0 */ export interface ExternalsConfig { readonly direction?: Direction } /** - * Creates an iterator over external nodes (nodes without edges in specified direction). + * Creates an iterator over external nodes (nodes without edges in the specified direction). + * + * **Details** * - * External nodes are nodes that have no outgoing edges (direction="outgoing") or - * no incoming edges (direction="incoming"). These are useful for finding + * External nodes have no outgoing edges (`direction: "outgoing"`) or no + * incoming edges (`direction: "incoming"`). These are useful for finding * sources, sinks, or isolated nodes. * - * @example + * **Example** (Iterating external nodes) + * * ```ts * import { Graph } from "effect" * @@ -5649,18 +6491,21 @@ export interface ExternalsConfig { * console.log(sources) // [0, 3] * ``` * - * @since 4.0.0 * @category iterators + * @since 3.18.0 */ export const externals: { /** - * Creates an iterator over external nodes (nodes without edges in specified direction). + * Creates an iterator over external nodes (nodes without edges in the specified direction). * - * External nodes are nodes that have no outgoing edges (direction="outgoing") or - * no incoming edges (direction="incoming"). These are useful for finding + * **Details** + * + * External nodes have no outgoing edges (`direction: "outgoing"`) or no + * incoming edges (`direction: "incoming"`). These are useful for finding * sources, sinks, or isolated nodes. * - * @example + * **Example** (Iterating external nodes) + * * ```ts * import { Graph } from "effect" * @@ -5687,18 +6532,21 @@ export const externals: { * console.log(sources) // [0, 3] * ``` * - * @since 4.0.0 * @category iterators + * @since 3.18.0 */ (config?: ExternalsConfig): (graph: Graph | MutableGraph) => NodeWalker /** - * Creates an iterator over external nodes (nodes without edges in specified direction). + * Creates an iterator over external nodes (nodes without edges in the specified direction). + * + * **Details** * - * External nodes are nodes that have no outgoing edges (direction="outgoing") or - * no incoming edges (direction="incoming"). These are useful for finding + * External nodes have no outgoing edges (`direction: "outgoing"`) or no + * incoming edges (`direction: "incoming"`). These are useful for finding * sources, sinks, or isolated nodes. * - * @example + * **Example** (Iterating external nodes) + * * ```ts * import { Graph } from "effect" * @@ -5725,8 +6573,8 @@ export const externals: { * console.log(sources) // [0, 3] * ``` * - * @since 4.0.0 * @category iterators + * @since 3.18.0 */ (graph: Graph | MutableGraph, config?: ExternalsConfig): NodeWalker } = dual((args) => isGraph(args[0]), ( diff --git a/.opencode/node_modules/effect/src/HKT.ts b/.opencode/node_modules/effect/src/HKT.ts index 3876ccb199221427478745e2f1b3439cd00142e1..4cbbfead470b3c2b93575fed8de6a7c39edf7719 100644 --- a/.opencode/node_modules/effect/src/HKT.ts +++ b/.opencode/node_modules/effect/src/HKT.ts @@ -1,73 +1,73 @@ /** - * This module provides utilities for Higher-Kinded Types (HKT) in TypeScript. + * Provides type-level helpers for generic code over container-like types. * - * Higher-Kinded Types are types that take other types as parameters, similar to how - * functions take values as parameters. They enable generic programming over type - * constructors, allowing you to write code that works with any container type - * (like Array, Option, Effect, etc.) in a uniform way. - * - * The HKT system in Effect uses TypeLambdas to encode type-level functions that - * can represent complex type relationships with multiple type parameters, including - * contravariant, covariant, and invariant positions. - * - * @example - * ```ts - * import type { HKT } from "effect" - * - * // Define a TypeLambda for Array - * interface ArrayTypeLambda extends HKT.TypeLambda { - * readonly type: Array - * } - * - * // Use Kind to get the concrete type - * type MyArray = HKT.Kind - * // MyArray is Array - * - * // Define a TypeClass that works with any HKT - * interface Functor extends HKT.TypeClass { - * map( - * fa: HKT.Kind, - * f: (a: A) => B - * ): HKT.Kind - * } - * ``` + * TypeScript cannot directly abstract over shapes such as `Option`, + * `ReadonlyArray`, or `Effect`. This module represents those shapes + * with `TypeLambda` and applies concrete type arguments with `Kind`. It is + * mostly useful when defining generic helpers or type classes that should work + * across several data types. * * @since 2.0.0 */ import type * as Types from "./Types.ts" /** - * A unique symbol used to identify TypeClass implementations. + * Defines the unique symbol used to associate `TypeClass` implementations with their `TypeLambda`. + * + * **When to use** + * + * Use when you need to define a custom type class that exposes the `TypeLambda` + * it operates on. + * + * **Details** + * + * This symbol links a type class shape with its compile-time type lambda. It is + * intended for type-class definitions and has no runtime behavior. * - * This symbol is used internally by the HKT system to associate type classes - * with their corresponding TypeLambda. It provides a way to link runtime - * type class instances with their compile-time type information. + * **Example** (Linking a type class to a type lambda) * - * @example * ```ts * import type { HKT } from "effect" * - * interface MyTypeClass extends HKT.TypeClass { - * // TypeClass methods here + * interface IdentityTypeLambda extends HKT.TypeLambda { + * readonly type: this["Target"] * } * - * // The URI symbol helps TypeScript understand the relationship - * // between the type class and its type lambda + * interface IdentityTypeClass extends HKT.TypeClass { + * readonly [HKT.URI]?: IdentityTypeLambda + * readonly of: (value: A) => HKT.Kind + * } + * + * const identity: IdentityTypeClass = { + * of: (value) => value + * } + * + * type LinkedTypeLambda = typeof identity[typeof HKT.URI] + * + * const value: HKT.Kind, never, never, never, string> = identity.of("ok") + * console.log(value) // "ok" * ``` * - * @since 2.0.0 * @category symbols + * @since 2.0.0 */ export declare const URI: unique symbol /** * Base interface for type classes that work with Higher-Kinded Types. * - * A TypeClass defines operations that can be performed on any type constructor - * that matches the given TypeLambda. This enables writing generic code that + * **When to use** + * + * Use to define type class interfaces parameterized by a `TypeLambda`. + * + * **Details** + * + * A `TypeClass` defines operations that can be performed on any type constructor + * that matches the given `TypeLambda`. This enables writing generic code that * works across different container types like Array, Option, Effect, etc. * - * @example + * **Example** (Defining higher-kinded type classes) + * * ```ts * import type { HKT } from "effect" * @@ -88,8 +88,8 @@ export declare const URI: unique symbol * } * ``` * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface TypeClass { readonly [URI]?: F @@ -98,17 +98,20 @@ export interface TypeClass { /** * Base interface for defining Higher-Kinded Type parameters. * - * A TypeLambda encodes the "shape" of a type constructor, specifying how many - * type parameters it takes and their variance (contravariant, covariant, or invariant). - * This allows representing complex types like `Effect` in a uniform way. + * **When to use** + * + * Use to encode a type constructor for higher-kinded generic programming. + * + * **Details** + * + * A `TypeLambda` encodes the "shape" of a type constructor, specifying how many + * type parameters it takes and their variance (contravariant, covariant, or + * invariant). The four parameters are `In` for contravariant input, `Out2` for + * covariant output often used for errors, `Out1` for covariant output often used + * for context or environment, and `Target` for the invariant main type. * - * The four parameters represent: - * - `In`: Contravariant input parameter - * - `Out2`: Covariant output parameter (often used for errors) - * - `Out1`: Covariant output parameter (often used for context/environment) - * - `Target`: Invariant target parameter (the main type) + * **Example** (Defining type lambdas) * - * @example * ```ts * import type { Effect, HKT } from "effect" * @@ -128,8 +131,8 @@ export interface TypeClass { * } * ``` * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface TypeLambda { readonly In: unknown @@ -139,17 +142,22 @@ export interface TypeLambda { } /** - * Applies type parameters to a TypeLambda to get the concrete type. + * Applies type parameters to a `TypeLambda` to get the concrete type. + * + * **When to use** + * + * Use to apply a `TypeLambda` to type parameters and obtain its concrete type. + * + * **Details** * - * This type-level function takes a TypeLambda and four type parameters, - * then "applies" them to get the actual type. It handles the variance - * correctly, ensuring contravariant parameters are used as inputs and - * covariant parameters as outputs. + * This type-level function takes a `TypeLambda` and four type parameters, then + * "applies" them to get the actual type. It handles variance correctly, ensuring + * contravariant parameters are used as inputs and covariant parameters as + * outputs. This is the core mechanism that allows HKT to transform abstract type + * constructors into concrete types by applying arguments. * - * This is the core mechanism that allows HKT to work - it transforms - * abstract type constructors into concrete types by applying arguments. + * **Example** (Applying type lambdas) * - * @example * ```ts * import type { Effect, HKT, Option } from "effect" * @@ -185,8 +193,8 @@ export interface TypeLambda { * > * ``` * + * @category utility types * @since 2.0.0 - * @category type utils */ export type Kind = F extends { readonly type: unknown diff --git a/.opencode/node_modules/effect/src/Hash.ts b/.opencode/node_modules/effect/src/Hash.ts index 7c7fa27ff9595a1b56b0106a67c104635a647d5e..2fb1532c9e968da1cbb272621bca0e9e4399ffd6 100644 --- a/.opencode/node_modules/effect/src/Hash.ts +++ b/.opencode/node_modules/effect/src/Hash.ts @@ -1,9 +1,11 @@ /** - * This module provides utilities for hashing values in TypeScript. - * - * Hashing is the process of converting data into a fixed-size numeric value, - * typically used for data structures like hash tables, equality comparisons, - * and efficient data storage. + * Computes Effect hash values and defines the interface for objects that want + * to provide their own hash implementation. Hashes are small numeric + * fingerprints used by Effect data structures to bucket values quickly; they + * are not cryptographic digests and they are not proof that two values are + * equal. The module also includes helpers for primitive, structure, array, and + * reference-based hashes, plus functions for combining and optimizing numeric + * hash values. * * @since 2.0.0 */ @@ -12,8 +14,18 @@ import { byReferenceInstances, getAllObjectKeys } from "./internal/equal.ts" import { hasProperty } from "./Predicate.ts" /** - * The unique identifier used to identify objects that implement the Hash interface. + * Defines the unique identifier used to identify objects that implement the Hash interface. + * + * **When to use** + * + * Use as the computed property key for the method that supplies a custom hash + * value on a `Hash` implementor. + * + * @see {@link Hash} for the interface implemented with this symbol + * @see {@link isHash} for checking whether a value implements `Hash` + * @see {@link hash} for computing hash values * + * @category symbols * @since 2.0.0 */ export const symbol = "~effect/interfaces/Hash" @@ -21,10 +33,17 @@ export const symbol = "~effect/interfaces/Hash" /** * A type that represents an object that can be hashed. * + * **When to use** + * + * Use to let a custom type provide its own stable hash value. + * + * **Details** + * * Objects implementing this interface provide a method to compute their hash value, * which is used for efficient comparison and storage operations. * - * @example + * **Example** (Implementing Hash) + * * ```ts * import { Hash } from "effect" * @@ -50,21 +69,27 @@ export interface Hash { /** * Computes a hash value for any given value. * + * **When to use** + * + * Use to compute an Effect hash for primitives, collections, and hashable + * objects. + * + * **Details** + * * This function can hash primitives (numbers, strings, booleans, etc.) as well as * objects, arrays, and other complex data structures. It automatically handles * different types and provides a consistent hash value for equivalent inputs. * - * **⚠️ CRITICAL IMMUTABILITY REQUIREMENT**: Objects being hashed must be treated as - * immutable after their first hash computation. Hash results are cached, so mutating - * an object after hashing will lead to stale cached values and broken hash-based - * operations. For mutable objects, use referential equality by implementing custom - * `Hash` interface that hashes the object reference, not its content. + * **Gotchas** + * + * Objects being hashed must be treated as immutable after their first hash + * computation. Hash results are cached, so mutating an object after hashing will + * lead to stale cached values and broken hash-based operations. For mutable + * objects, implement a custom `Hash` interface that hashes the object reference + * rather than its content. * - * **FORBIDDEN**: Modifying objects after `Hash.hash()` has been called on them - * **ALLOWED**: Using immutable objects, or mutable objects with custom `Hash` interface - * that uses referential equality (hashes the object reference, not content) + * **Example** (Hashing different values) * - * @example * ```ts * import { Hash } from "effect" * @@ -76,7 +101,7 @@ export interface Hash { * // Hash objects and arrays * console.log(Hash.hash({ name: "John", age: 30 })) * console.log(Hash.hash([1, 2, 3])) - * console.log(Hash.hash(new Date("2023-01-01"))) + * console.log(Hash.hash({ id: "user-1", roles: ["admin", "editor"] })) * ``` * * @category hashing @@ -139,11 +164,18 @@ export const hash: (self: A) => number = (self: A) => { /** * Generates a random hash value for an object and caches it. * + * **When to use** + * + * Use to hash an object by reference identity instead of structural content. + * + * **Details** + * * This function creates a random hash value for objects that don't have their own * hash implementation. The hash value is cached using a WeakMap, so the same object * will always return the same hash value during its lifetime. * - * @example + * **Example** (Hashing objects by reference) + * * ```ts * import { Hash } from "effect" * @@ -170,16 +202,22 @@ export const random: (self: A) => number = (self) => { /** * Combines two hash values into a single hash value. * - * This function takes two hash values and combines them using a mathematical - * operation to produce a new hash value. It's useful for creating hash values - * of composite structures. + * **When to use** + * + * Use to build a hash for a composite value by folding together hash values for + * its parts. + * + * **Details** + * + * Supports both direct and pipeable usage. The implementation combines two + * hash values with `(self * 53) ^ b`. + * + * **Example** (Combining hash values) * - * @example * ```ts - * import { Hash } from "effect" // combined hash value + * import { Hash, pipe } from "effect" * * // Can also be used with pipe - * import { pipe } from "effect" * * const hash1 = Hash.hash("hello") * const hash2 = Hash.hash("world") @@ -190,6 +228,9 @@ export const random: (self: A) => number = (self) => { * const result = pipe(hash1, Hash.combine(hash2)) * ``` * + * @see {@link hash} for computing hash values from arbitrary inputs + * @see {@link structureKeys} for hashing selected object fields without manual combination + * * @category hashing * @since 2.0.0 */ @@ -197,16 +238,22 @@ export const combine: { /** * Combines two hash values into a single hash value. * - * This function takes two hash values and combines them using a mathematical - * operation to produce a new hash value. It's useful for creating hash values - * of composite structures. + * **When to use** + * + * Use to build a hash for a composite value by folding together hash values for + * its parts. + * + * **Details** + * + * Supports both direct and pipeable usage. The implementation combines two + * hash values with `(self * 53) ^ b`. + * + * **Example** (Combining hash values) * - * @example * ```ts - * import { Hash } from "effect" // combined hash value + * import { Hash, pipe } from "effect" * * // Can also be used with pipe - * import { pipe } from "effect" * * const hash1 = Hash.hash("hello") * const hash2 = Hash.hash("world") @@ -217,6 +264,9 @@ export const combine: { * const result = pipe(hash1, Hash.combine(hash2)) * ``` * + * @see {@link hash} for computing hash values from arbitrary inputs + * @see {@link structureKeys} for hashing selected object fields without manual combination + * * @category hashing * @since 2.0.0 */ @@ -224,16 +274,22 @@ export const combine: { /** * Combines two hash values into a single hash value. * - * This function takes two hash values and combines them using a mathematical - * operation to produce a new hash value. It's useful for creating hash values - * of composite structures. + * **When to use** + * + * Use to build a hash for a composite value by folding together hash values for + * its parts. + * + * **Details** + * + * Supports both direct and pipeable usage. The implementation combines two + * hash values with `(self * 53) ^ b`. + * + * **Example** (Combining hash values) * - * @example * ```ts - * import { Hash } from "effect" // combined hash value + * import { Hash, pipe } from "effect" * * // Can also be used with pipe - * import { pipe } from "effect" * * const hash1 = Hash.hash("hello") * const hash2 = Hash.hash("world") @@ -244,6 +300,9 @@ export const combine: { * const result = pipe(hash1, Hash.combine(hash2)) * ``` * + * @see {@link hash} for computing hash values from arbitrary inputs + * @see {@link structureKeys} for hashing selected object fields without manual combination + * * @category hashing * @since 2.0.0 */ @@ -251,12 +310,19 @@ export const combine: { } = dual(2, (self: number, b: number): number => (self * 53) ^ b) /** - * Optimizes a hash value by applying bit manipulation techniques. + * Applies bit manipulation techniques to optimize a hash value. + * + * **When to use** + * + * Use to improve the bit distribution of a raw numeric hash value. + * + * **Details** * * This function takes a hash value and applies bitwise operations to improve * the distribution of hash values, reducing the likelihood of collisions. * - * @example + * **Example** (Optimizing a hash value) + * * ```ts * import { Hash } from "effect" * @@ -274,12 +340,19 @@ export const combine: { export const optimize = (n: number): number => (n & 0xbfffffff) | ((n >>> 1) & 0x40000000) /** - * Checks if a value implements the Hash interface. + * Checks whether a value implements the Hash interface. + * + * **When to use** + * + * Use to detect whether an unknown value provides a custom hash implementation. + * + * **Details** * * This function determines whether a given value has the Hash symbol property, * indicating that it can provide its own hash value implementation. * - * @example + * **Example** (Checking for Hash support) + * * ```ts * import { Hash } from "effect" * @@ -303,11 +376,18 @@ export const isHash = (u: unknown): u is Hash => hasProperty(u, symbol) /** * Computes a hash value for a number. * + * **When to use** + * + * Use to hash a JavaScript number with Effect's numeric hash semantics. + * + * **Details** + * * This function creates a hash value for numeric inputs, handling special cases * like NaN, Infinity, and -Infinity with distinct hash values. It uses bitwise operations to ensure good distribution * of hash values across different numeric inputs. * - * @example + * **Example** (Hashing numbers) + * * ```ts * import { Hash } from "effect" * @@ -346,11 +426,19 @@ export const number = (n: number) => { /** * Computes a hash value for a string using the djb2 algorithm. * + * **When to use** + * + * Use when you need a string field to contribute to a custom structural hash + * implementation. + * + * **Details** + * * This function implements a variation of the djb2 hash algorithm, which is * known for its good distribution properties and speed. It processes each * character of the string to produce a consistent hash value. * - * @example + * **Example** (Hashing strings) + * * ```ts * import { Hash } from "effect" * @@ -376,11 +464,18 @@ export const string = (str: string) => { /** * Computes a hash value for an object using only the specified keys. * + * **When to use** + * + * Use to hash an object by a selected set of property keys. + * + * **Details** + * * This function allows you to hash an object by considering only specific keys, * which is useful when you want to create a hash based on a subset of an object's * properties. * - * @example + * **Example** (Hashing selected object keys) + * * ```ts * import { Hash } from "effect" * @@ -411,13 +506,19 @@ export const structureKeys = (o: object, keys: Iterable) => { } /** - * Computes a hash value for an object using all of its enumerable keys. + * Computes a structural hash for an object using Effect's object key collection. + * + * **When to use** + * + * Use to hash an object from all structural keys collected by Effect. + * + * **Details** + * + * The hash is based on the object's structural keys and their values, including + * symbol keys and relevant prototype keys for non-plain objects. * - * This function creates a hash value based on all enumerable properties of an object. - * It's a convenient way to hash an entire object structure when you want to consider - * all its properties. + * **Example** (Hashing object structures) * - * @example * ```ts * import { Hash } from "effect" * @@ -447,13 +548,24 @@ const iterableWith = (seed: number, f: (el: any) => number) => (iter: Iterable number) => (iter: Iterable` hashes keys and resolves matches with Effect's + * structural equality rules. Lookup, insertion, removal, and transformation + * operations return new maps, while temporary mutation helpers support efficient + * batch updates. This module also includes constructors, iteration, conversion, + * mapping, filtering, and reducing helpers. + * * @since 2.0.0 */ @@ -17,9 +25,10 @@ const TypeId = internal.HashMapTypeId * insertion, and deletion operations. It uses a Hash Array Mapped Trie (HAMT) internally * for structural sharing and optimal performance. * - * @example + * **Example** (Using basic HashMap operations) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * // Create a HashMap * const map = HashMap.make(["a", 1], ["b", 2], ["c", 3]) @@ -36,8 +45,8 @@ const TypeId = internal.HashMapTypeId * console.log(HashMap.size(updated)) // 4 * ``` * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface HashMap extends Iterable<[Key, Value]>, Equal, Pipeable, Inspectable { readonly [TypeId]: typeof TypeId @@ -47,9 +56,10 @@ export interface HashMap extends Iterable<[Key, Value]>, Equ * The HashMap namespace contains type-level utilities and helper types * for working with HashMap instances. * - * @example + * **Example** (Extracting HashMap types) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * // Create a concrete HashMap for type extraction * const inventory = HashMap.make( @@ -75,7 +85,6 @@ export interface HashMap extends Iterable<[Key, Value]>, Equ * ``` * * @since 2.0.0 - * @category models */ export declare namespace HashMap { /** @@ -83,10 +92,10 @@ export declare namespace HashMap { * Takes an Option representing the current value and returns an Option * representing the new value. * - * @example + * **Example** (Updating values from Options) + * * ```ts - * import * as HashMap from "effect/HashMap" - * import * as Option from "effect/Option" + * import { HashMap, Option } from "effect" * * const map = HashMap.make(["a", 1], ["b", 2]) * @@ -98,17 +107,18 @@ export declare namespace HashMap { * console.log(HashMap.get(updated, "a")) // Option.some(2) * ``` * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export type UpdateFn = (option: Option) => Option /** * This type-level utility extracts the key type `K` from a `HashMap` type. * - * @example + * **Example** (Extracting key types) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * // Create a HashMap to extract key type from * const userMap = HashMap.make( @@ -123,17 +133,19 @@ export declare namespace HashMap { * const getUserById = (id: UserKey) => HashMap.get(userMap, id) * console.log(getUserById("alice")) // Option.some({ name: "Alice", age: 30 }) * ``` + * + * @category utility types * @since 2.0.0 - * @category type-level */ export type Key> = [T] extends [HashMap] ? _K : never /** * This type-level utility extracts the value type `V` from a `HashMap` type. * - * @example + * **Example** (Extracting value types) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * // Create a HashMap with user data * const userMap = HashMap.make( @@ -152,17 +164,19 @@ export declare namespace HashMap { * const alice = HashMap.get(userMap, "alice") * // alice has type Option thanks to type extraction * ``` + * + * @category utility types * @since 2.0.0 - * @category type-level */ export type Value> = [T] extends [HashMap] ? _V : never /** * This type-level utility extracts the entry type `[K, V]` from a `HashMap` type. * - * @example + * **Example** (Extracting entry types) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * // Create a product catalog HashMap * const catalog = HashMap.make( @@ -178,22 +192,24 @@ export declare namespace HashMap { * return `${productId}: $${product.price} (${product.category})` * } * - * // Convert to entries and process - * const descriptions = HashMap.toEntries(catalog).map(processEntry) - * console.log(descriptions) // ["laptop: $999 (electronics)", "book: $29 (education)"] + * // Convert to entries, process, and sort for deterministic output + * const descriptions = HashMap.toEntries(catalog).map(processEntry).sort() + * console.log(descriptions) // ["book: $29 (education)", "laptop: $999 (electronics)"] * ``` + * + * @category utility types * @since 3.9.0 - * @category type-level */ export type Entry> = [Key, Value] } /** - * Checks if a value is a HashMap. + * Checks whether a value is a HashMap. + * + * **Example** (Checking HashMap values) * - * @example * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map = HashMap.make(["a", 1], ["b", 2]) * const notMap = { a: 1 } @@ -203,16 +219,17 @@ export declare namespace HashMap { * console.log(HashMap.isHashMap(null)) // false * ``` * - * @since 2.0.0 * @category refinements + * @since 2.0.0 */ export const isHashMap: { /** - * Checks if a value is a HashMap. + * Checks whether a value is a HashMap. + * + * **Example** (Checking HashMap values) * - * @example * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map = HashMap.make(["a", 1], ["b", 2]) * const notMap = { a: 1 } @@ -222,16 +239,17 @@ export const isHashMap: { * console.log(HashMap.isHashMap(null)) // false * ``` * - * @since 2.0.0 * @category refinements + * @since 2.0.0 */ (u: Iterable): u is HashMap /** - * Checks if a value is a HashMap. + * Checks whether a value is a HashMap. + * + * **Example** (Checking HashMap values) * - * @example * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map = HashMap.make(["a", 1], ["b", 2]) * const notMap = { a: 1 } @@ -241,8 +259,8 @@ export const isHashMap: { * console.log(HashMap.isHashMap(null)) // false * ``` * - * @since 2.0.0 * @category refinements + * @since 2.0.0 */ (u: unknown): u is HashMap } = internal.isHashMap @@ -250,34 +268,36 @@ export const isHashMap: { /** * Creates a new empty `HashMap`. * - * @example + * **Example** (Creating an empty HashMap) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map = HashMap.empty() * console.log(HashMap.isEmpty(map)) // true * console.log(HashMap.size(map)) // 0 * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const empty: () => HashMap = internal.empty /** * Constructs a new `HashMap` from an array of key/value pairs. * - * @example + * **Example** (Creating a HashMap from entries) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map = HashMap.make(["a", 1], ["b", 2], ["c", 3]) * console.log(HashMap.size(map)) // 3 * console.log(HashMap.get(map, "b")) // Option.some(2) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const make: >( ...entries: Entries @@ -289,9 +309,10 @@ export const make: >( /** * Creates a new `HashMap` from an iterable collection of key/value pairs. * - * @example + * **Example** (Creating a HashMap from an iterable) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const entries = [["a", 1], ["b", 2], ["c", 3]] as const * const map = HashMap.fromIterable(entries) @@ -299,17 +320,18 @@ export const make: >( * console.log(HashMap.get(map, "a")) // Option.some(1) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const fromIterable: (entries: Iterable) => HashMap = internal.fromIterable /** - * Checks if the `HashMap` contains any entries. + * Checks whether the `HashMap` contains no entries. + * + * **Example** (Checking for empty HashMaps) * - * @example * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const emptyMap = HashMap.empty() * const nonEmptyMap = HashMap.make(["a", 1]) @@ -318,18 +340,19 @@ export const fromIterable: (entries: Iterable) => HashMap * console.log(HashMap.isEmpty(nonEmptyMap)) // false * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ export const isEmpty: (self: HashMap) => boolean = internal.isEmpty /** - * Safely lookup the value for the specified key in the `HashMap` using the + * Looks up the value for the specified key in the `HashMap` safely using the * internal hashing function. * - * @example + * **Example** (Looking up values) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map = HashMap.make(["a", 1], ["b", 2]) * @@ -341,17 +364,18 @@ export const isEmpty: (self: HashMap) => boolean = internal.isEmpty * console.log(value) // Option.some(2) * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ export const get: { /** - * Safely lookup the value for the specified key in the `HashMap` using the + * Looks up the value for the specified key in the `HashMap` safely using the * internal hashing function. * - * @example + * **Example** (Looking up values) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map = HashMap.make(["a", 1], ["b", 2]) * @@ -363,17 +387,18 @@ export const get: { * console.log(value) // Option.some(2) * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (key: K1): (self: HashMap) => Option /** - * Safely lookup the value for the specified key in the `HashMap` using the + * Looks up the value for the specified key in the `HashMap` safely using the * internal hashing function. * - * @example + * **Example** (Looking up values) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map = HashMap.make(["a", 1], ["b", 2]) * @@ -385,19 +410,19 @@ export const get: { * console.log(value) // Option.some(2) * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (self: HashMap, key: K1): Option } = internal.get /** - * Lookup the value for the specified key in the `HashMap` using a custom hash. + * Looks up the value for the specified key in the `HashMap` safely using a custom hash. + * + * **Example** (Looking up values with a hash) * - * @example * ```ts - * import { Hash } from "effect" - * import * as HashMap from "effect/HashMap" + * import { Hash, HashMap } from "effect" * * // Useful when implementing custom equality for complex keys * const userMap = HashMap.make( @@ -418,17 +443,17 @@ export const get: { * console.log(notFound) // Option.none() * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ export const getHash: { /** - * Lookup the value for the specified key in the `HashMap` using a custom hash. + * Looks up the value for the specified key in the `HashMap` safely using a custom hash. + * + * **Example** (Looking up values with a hash) * - * @example * ```ts - * import { Hash } from "effect" - * import * as HashMap from "effect/HashMap" + * import { Hash, HashMap } from "effect" * * // Useful when implementing custom equality for complex keys * const userMap = HashMap.make( @@ -449,17 +474,17 @@ export const getHash: { * console.log(notFound) // Option.none() * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (key: K1, hash: number): (self: HashMap) => Option /** - * Lookup the value for the specified key in the `HashMap` using a custom hash. + * Looks up the value for the specified key in the `HashMap` safely using a custom hash. + * + * **Example** (Looking up values with a hash) * - * @example * ```ts - * import { Hash } from "effect" - * import * as HashMap from "effect/HashMap" + * import { Hash, HashMap } from "effect" * * // Useful when implementing custom equality for complex keys * const userMap = HashMap.make( @@ -480,23 +505,30 @@ export const getHash: { * console.log(notFound) // Option.none() * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (self: HashMap, key: K1, hash: number): Option } = internal.getHash /** - * Unsafely lookup the value for the specified key in the `HashMap` using the + * Looks up the value for the specified key in the `HashMap` unsafely using the * internal hashing function. * - * ⚠️ **Warning**: This function throws an error if the key is not found. - * Use `HashMap.get` for safe access that returns `Option`. + * **When to use** + * + * Use when reading from a `HashMap` by a key known to exist, and throwing is an + * acceptable programming error for a missing key. + * + * **Gotchas** + * + * This function throws an error if the key is not found. Use `HashMap.get` for + * safe access that returns `Option`. + * + * **Example** (Unsafely looking up values) * - * @example * ```ts - * import * as HashMap from "effect/HashMap" - * import * as Option from "effect/Option" + * import { HashMap, Option } from "effect" * * const config = HashMap.make( * ["api_url", "https://api.example.com"], @@ -518,21 +550,28 @@ export const getHash: { * // Error: "HashMap.getUnsafe: key not found" * ``` * - * @since 2.0.0 * @category unsafe + * @since 4.0.0 */ export const getUnsafe: { /** - * Unsafely lookup the value for the specified key in the `HashMap` using the + * Looks up the value for the specified key in the `HashMap` unsafely using the * internal hashing function. * - * ⚠️ **Warning**: This function throws an error if the key is not found. - * Use `HashMap.get` for safe access that returns `Option`. + * **When to use** + * + * Use when reading from a `HashMap` by a key known to exist, and throwing is an + * acceptable programming error for a missing key. + * + * **Gotchas** + * + * This function throws an error if the key is not found. Use `HashMap.get` for + * safe access that returns `Option`. + * + * **Example** (Unsafely looking up values) * - * @example * ```ts - * import * as HashMap from "effect/HashMap" - * import * as Option from "effect/Option" + * import { HashMap, Option } from "effect" * * const config = HashMap.make( * ["api_url", "https://api.example.com"], @@ -554,21 +593,28 @@ export const getUnsafe: { * // Error: "HashMap.getUnsafe: key not found" * ``` * - * @since 2.0.0 * @category unsafe + * @since 4.0.0 */ (key: K1): (self: HashMap) => V /** - * Unsafely lookup the value for the specified key in the `HashMap` using the + * Looks up the value for the specified key in the `HashMap` unsafely using the * internal hashing function. * - * ⚠️ **Warning**: This function throws an error if the key is not found. - * Use `HashMap.get` for safe access that returns `Option`. + * **When to use** + * + * Use when reading from a `HashMap` by a key known to exist, and throwing is an + * acceptable programming error for a missing key. + * + * **Gotchas** + * + * This function throws an error if the key is not found. Use `HashMap.get` for + * safe access that returns `Option`. + * + * **Example** (Unsafely looking up values) * - * @example * ```ts - * import * as HashMap from "effect/HashMap" - * import * as Option from "effect/Option" + * import { HashMap, Option } from "effect" * * const config = HashMap.make( * ["api_url", "https://api.example.com"], @@ -590,18 +636,19 @@ export const getUnsafe: { * // Error: "HashMap.getUnsafe: key not found" * ``` * - * @since 2.0.0 * @category unsafe + * @since 4.0.0 */ (self: HashMap, key: K1): V } = internal.getUnsafe /** - * Checks if the specified key has an entry in the `HashMap`. + * Checks whether the specified key has an entry in the `HashMap`. + * + * **Example** (Checking for keys) * - * @example * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map = HashMap.make(["a", 1], ["b", 2]) * @@ -613,16 +660,17 @@ export const getUnsafe: { * console.log(hasB) // true * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ export const has: { /** - * Checks if the specified key has an entry in the `HashMap`. + * Checks whether the specified key has an entry in the `HashMap`. + * + * **Example** (Checking for keys) * - * @example * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map = HashMap.make(["a", 1], ["b", 2]) * @@ -634,16 +682,17 @@ export const has: { * console.log(hasB) // true * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (key: K1): (self: HashMap) => boolean /** - * Checks if the specified key has an entry in the `HashMap`. + * Checks whether the specified key has an entry in the `HashMap`. + * + * **Example** (Checking for keys) * - * @example * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map = HashMap.make(["a", 1], ["b", 2]) * @@ -655,20 +704,20 @@ export const has: { * console.log(hasB) // true * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (self: HashMap, key: K1): boolean } = internal.has /** - * Checks if the specified key has an entry in the `HashMap` using a custom + * Checks whether the specified key has an entry in the `HashMap` using a custom * hash. * - * @example + * **Example** (Checking keys with a hash) + * * ```ts - * import { Hash } from "effect" - * import * as HashMap from "effect/HashMap" + * import { Hash, HashMap } from "effect" * * // Create a map with case-sensitive keys * const userMap = HashMap.make( @@ -680,23 +729,26 @@ export const has: { * const exactHash = Hash.string("Admin") * console.log(HashMap.hasHash(userMap, "Admin", exactHash)) // true * - * // Check case-insensitive by using custom hash - * const caseInsensitiveHash = Hash.string("admin".toLowerCase()) - * console.log(HashMap.hasHash(userMap, "admin", caseInsensitiveHash)) // false (different hash) + * // A matching hash does not override key equality + * console.log(HashMap.hasHash(userMap, "admin", exactHash)) // false + * + * // A different hash also cannot find the existing key + * const lowercaseHash = Hash.string("admin") + * console.log(HashMap.hasHash(userMap, "Admin", lowercaseHash)) // false * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ export const hasHash: { /** - * Checks if the specified key has an entry in the `HashMap` using a custom + * Checks whether the specified key has an entry in the `HashMap` using a custom * hash. * - * @example + * **Example** (Checking keys with a hash) + * * ```ts - * import { Hash } from "effect" - * import * as HashMap from "effect/HashMap" + * import { Hash, HashMap } from "effect" * * // Create a map with case-sensitive keys * const userMap = HashMap.make( @@ -708,23 +760,26 @@ export const hasHash: { * const exactHash = Hash.string("Admin") * console.log(HashMap.hasHash(userMap, "Admin", exactHash)) // true * - * // Check case-insensitive by using custom hash - * const caseInsensitiveHash = Hash.string("admin".toLowerCase()) - * console.log(HashMap.hasHash(userMap, "admin", caseInsensitiveHash)) // false (different hash) + * // A matching hash does not override key equality + * console.log(HashMap.hasHash(userMap, "admin", exactHash)) // false + * + * // A different hash also cannot find the existing key + * const lowercaseHash = Hash.string("admin") + * console.log(HashMap.hasHash(userMap, "Admin", lowercaseHash)) // false * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (key: K1, hash: number): (self: HashMap) => boolean /** - * Checks if the specified key has an entry in the `HashMap` using a custom + * Checks whether the specified key has an entry in the `HashMap` using a custom * hash. * - * @example + * **Example** (Checking keys with a hash) + * * ```ts - * import { Hash } from "effect" - * import * as HashMap from "effect/HashMap" + * import { Hash, HashMap } from "effect" * * // Create a map with case-sensitive keys * const userMap = HashMap.make( @@ -736,63 +791,69 @@ export const hasHash: { * const exactHash = Hash.string("Admin") * console.log(HashMap.hasHash(userMap, "Admin", exactHash)) // true * - * // Check case-insensitive by using custom hash - * const caseInsensitiveHash = Hash.string("admin".toLowerCase()) - * console.log(HashMap.hasHash(userMap, "admin", caseInsensitiveHash)) // false (different hash) + * // A matching hash does not override key equality + * console.log(HashMap.hasHash(userMap, "admin", exactHash)) // false + * + * // A different hash also cannot find the existing key + * const lowercaseHash = Hash.string("admin") + * console.log(HashMap.hasHash(userMap, "Admin", lowercaseHash)) // false * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (self: HashMap, key: K1, hash: number): boolean } = internal.hasHash /** - * Checks if an element matching the given predicate exists in the given `HashMap`. + * Checks whether an element matching the given predicate exists in the given `HashMap`. + * + * **Example** (Checking entries by predicate) * - * @example * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const hm = HashMap.make([1, "a"]) * HashMap.hasBy(hm, (value, key) => value === "a" && key === 1) // -> true * HashMap.hasBy(hm, (value) => value === "b") // -> false * ``` * - * @since 3.16.0 * @category elements + * @since 3.16.0 */ export const hasBy: { /** - * Checks if an element matching the given predicate exists in the given `HashMap`. + * Checks whether an element matching the given predicate exists in the given `HashMap`. + * + * **Example** (Checking entries by predicate) * - * @example * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const hm = HashMap.make([1, "a"]) * HashMap.hasBy(hm, (value, key) => value === "a" && key === 1) // -> true * HashMap.hasBy(hm, (value) => value === "b") // -> false * ``` * - * @since 3.16.0 * @category elements + * @since 3.16.0 */ (predicate: (value: NoInfer, key: NoInfer) => boolean): (self: HashMap) => boolean /** - * Checks if an element matching the given predicate exists in the given `HashMap`. + * Checks whether an element matching the given predicate exists in the given `HashMap`. + * + * **Example** (Checking entries by predicate) * - * @example * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const hm = HashMap.make([1, "a"]) * HashMap.hasBy(hm, (value, key) => value === "a" && key === 1) // -> true * HashMap.hasBy(hm, (value) => value === "b") // -> false * ``` * - * @since 3.16.0 * @category elements + * @since 3.16.0 */ ( self: HashMap, @@ -804,9 +865,10 @@ export const hasBy: { * Sets the specified key to the specified value using the internal hashing * function. * - * @example + * **Example** (Setting a value) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map1 = HashMap.make(["a", 1]) * const map2 = HashMap.set(map1, "b", 2) @@ -818,17 +880,18 @@ export const hasBy: { * console.log(HashMap.size(map1)) // 1 * ``` * + * @category transforming * @since 2.0.0 - * @category transformations */ export const set: { /** * Sets the specified key to the specified value using the internal hashing * function. * - * @example + * **Example** (Setting a value) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map1 = HashMap.make(["a", 1]) * const map2 = HashMap.set(map1, "b", 2) @@ -840,17 +903,18 @@ export const set: { * console.log(HashMap.size(map1)) // 1 * ``` * + * @category transforming * @since 2.0.0 - * @category transformations */ (key: K, value: V): (self: HashMap) => HashMap /** * Sets the specified key to the specified value using the internal hashing * function. * - * @example + * **Example** (Setting a value) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map1 = HashMap.make(["a", 1]) * const map2 = HashMap.set(map1, "b", 2) @@ -862,8 +926,8 @@ export const set: { * console.log(HashMap.size(map1)) // 1 * ``` * + * @category transforming * @since 2.0.0 - * @category transformations */ (self: HashMap, key: K, value: V): HashMap } = internal.set @@ -871,43 +935,46 @@ export const set: { /** * Returns an `IterableIterator` of the keys within the `HashMap`. * - * @example + * **Example** (Iterating keys) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map = HashMap.make(["a", 1], ["b", 2], ["c", 3]) * const keys = Array.from(HashMap.keys(map)) * console.log(keys.sort()) // ["a", "b", "c"] * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export const keys: (self: HashMap) => IterableIterator = internal.keys /** * Returns an `IterableIterator` of the values within the `HashMap`. * - * @example + * **Example** (Iterating values) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map = HashMap.make(["a", 1], ["b", 2], ["c", 3]) * const values = Array.from(HashMap.values(map)) * console.log(values.sort()) // [1, 2, 3] * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export const values: (self: HashMap) => IterableIterator = internal.values /** * Returns an `Array` of the values within the `HashMap`. * - * @example + * **Example** (Converting values to an array) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const employees = HashMap.make( * ["alice", { department: "engineering", salary: 90000 }], @@ -928,17 +995,18 @@ export const values: (self: HashMap) => IterableIterator = intern * console.log(engineers.length) // 2 * ``` * - * @since 3.13.0 * @category getters + * @since 3.13.0 */ export const toValues = (self: HashMap): Array => Array.from(values(self)) /** * Returns an `IterableIterator` of the entries within the `HashMap`. * - * @example + * **Example** (Iterating entries) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * // Create a configuration map * const config = HashMap.make( @@ -947,33 +1015,31 @@ export const toValues = (self: HashMap): Array => Array.from(valu * ["cache.enabled", "true"] * ) * - * // Get entries iterator for processing - * const entries = HashMap.entries(config) + * // Sort the derived array for deterministic output + * const settings = Array.from(HashMap.entries(config)) + * .sort(([left], [right]) => left.localeCompare(right)) + * .map(([key, value]) => `Setting ${key} = ${value}`) * - * // Process each configuration entry - * for (const [key, value] of entries) { - * console.log(`Setting ${key} = ${value}`) - * } - * // Setting database.host = localhost - * // Setting database.port = 5432 - * // Setting cache.enabled = true + * console.log(settings) + * // ["Setting cache.enabled = true", "Setting database.host = localhost", "Setting database.port = 5432"] * * // Convert to array when you need all entries at once * const allEntries = Array.from(HashMap.entries(config)) * console.log(allEntries.length) // 3 * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export const entries: (self: HashMap) => IterableIterator<[K, V]> = internal.entries /** * Returns an `Array<[K, V]>` of the entries within the `HashMap`. * - * @example + * **Example** (Converting entries to an array) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const gameScores = HashMap.make( * ["alice", 1250], @@ -996,17 +1062,18 @@ export const entries: (self: HashMap) => IterableIterator<[K, V]> = * const sortedMap = HashMap.fromIterable(scoreEntries) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export const toEntries = (self: HashMap): Array<[K, V]> => Array.from(entries(self)) /** * Returns the number of entries within the `HashMap`. * - * @example + * **Example** (Getting the size) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const emptyMap = HashMap.empty() * const map = HashMap.make(["a", 1], ["b", 2], ["c", 3]) @@ -1015,17 +1082,23 @@ export const toEntries = (self: HashMap): Array<[K, V]> => Array.fro * console.log(HashMap.size(map)) // 3 * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export const size: (self: HashMap) => number = internal.size /** - * Marks the `HashMap` as mutable for performance optimization during batch operations. + * Creates a transient mutable `HashMap` for efficient batched updates. + * + * **Details** + * + * Apply updates to the returned map, then call `endMutation` to finish the + * mutation window and use the result as an immutable `HashMap`. + * + * **Example** (Beginning batch mutation) * - * @example * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map = HashMap.make(["a", 1]) * @@ -1042,17 +1115,18 @@ export const size: (self: HashMap) => number = internal.size * console.log(HashMap.size(result)) // 2 * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ export const beginMutation: (self: HashMap) => HashMap = internal.beginMutation /** * Marks the `HashMap` as immutable, completing the mutation cycle. * - * @example + * **Example** (Ending batch mutation) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * // Start with an existing map * const original = HashMap.make(["x", 10], ["y", 20]) @@ -1073,17 +1147,24 @@ export const beginMutation: (self: HashMap) => HashMap = inter * console.log(HashMap.get(final, "z")) // Option.some(30) * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ export const endMutation: (self: HashMap) => HashMap = internal.endMutation /** - * Mutates the `HashMap` within the context of the provided function. + * Runs a batch of updates against a transient mutable copy of the `HashMap` + * and returns the finalized immutable result. + * + * **Details** + * + * The callback may call mutation-oriented helpers such as `set` and `remove` + * on the transient map. + * + * **Example** (Applying batched mutations) * - * @example * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map1 = HashMap.make(["a", 1]) * const map2 = HashMap.mutate(map1, (mutable) => { @@ -1093,16 +1174,23 @@ export const endMutation: (self: HashMap) => HashMap = interna * // Returns a new HashMap with mutations applied * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ export const mutate: { /** - * Mutates the `HashMap` within the context of the provided function. + * Runs a batch of updates against a transient mutable copy of the `HashMap` + * and returns the finalized immutable result. + * + * **Details** + * + * The callback may call mutation-oriented helpers such as `set` and `remove` + * on the transient map. + * + * **Example** (Applying batched mutations) * - * @example * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map1 = HashMap.make(["a", 1]) * const map2 = HashMap.mutate(map1, (mutable) => { @@ -1112,16 +1200,23 @@ export const mutate: { * // Returns a new HashMap with mutations applied * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ (f: (self: HashMap) => void): (self: HashMap) => HashMap /** - * Mutates the `HashMap` within the context of the provided function. + * Runs a batch of updates against a transient mutable copy of the `HashMap` + * and returns the finalized immutable result. + * + * **Details** + * + * The callback may call mutation-oriented helpers such as `set` and `remove` + * on the transient map. + * + * **Example** (Applying batched mutations) * - * @example * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map1 = HashMap.make(["a", 1]) * const map2 = HashMap.mutate(map1, (mutable) => { @@ -1131,24 +1226,25 @@ export const mutate: { * // Returns a new HashMap with mutations applied * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ (self: HashMap, f: (self: HashMap) => void): HashMap } = internal.mutate /** - * Set or remove the specified key in the `HashMap` using the specified - * update function. The value of the specified key will be computed using the - * provided hash. + * Sets or removes the specified key using an update function. * - * The update function will be invoked with the current value of the key if it - * exists, or `None` if no such value exists. + * **Details** + * + * The update function receives `Some(value)` when the key exists or `None` + * when it does not. Returning `Some(newValue)` stores the value, and returning + * `None` removes the key or leaves it absent. + * + * **Example** (Updating values with Options) * - * @example * ```ts - * import * as HashMap from "effect/HashMap" - * import * as Option from "effect/Option" + * import { HashMap, Option } from "effect" * * const map = HashMap.make(["a", 1], ["b", 2]) * @@ -1160,22 +1256,23 @@ export const mutate: { * console.log(HashMap.get(updated, "a")) // Option.some(2) * ``` * + * @category transforming * @since 2.0.0 - * @category transformations */ export const modifyAt: { /** - * Set or remove the specified key in the `HashMap` using the specified - * update function. The value of the specified key will be computed using the - * provided hash. + * Sets or removes the specified key using an update function. + * + * **Details** + * + * The update function receives `Some(value)` when the key exists or `None` + * when it does not. Returning `Some(newValue)` stores the value, and returning + * `None` removes the key or leaves it absent. * - * The update function will be invoked with the current value of the key if it - * exists, or `None` if no such value exists. + * **Example** (Updating values with Options) * - * @example * ```ts - * import * as HashMap from "effect/HashMap" - * import * as Option from "effect/Option" + * import { HashMap, Option } from "effect" * * const map = HashMap.make(["a", 1], ["b", 2]) * @@ -1187,22 +1284,23 @@ export const modifyAt: { * console.log(HashMap.get(updated, "a")) // Option.some(2) * ``` * + * @category transforming * @since 2.0.0 - * @category transformations */ (key: K, f: HashMap.UpdateFn): (self: HashMap) => HashMap /** - * Set or remove the specified key in the `HashMap` using the specified - * update function. The value of the specified key will be computed using the - * provided hash. + * Sets or removes the specified key using an update function. * - * The update function will be invoked with the current value of the key if it - * exists, or `None` if no such value exists. + * **Details** + * + * The update function receives `Some(value)` when the key exists or `None` + * when it does not. Returning `Some(newValue)` stores the value, and returning + * `None` removes the key or leaves it absent. + * + * **Example** (Updating values with Options) * - * @example * ```ts - * import * as HashMap from "effect/HashMap" - * import * as Option from "effect/Option" + * import { HashMap, Option } from "effect" * * const map = HashMap.make(["a", 1], ["b", 2]) * @@ -1214,27 +1312,26 @@ export const modifyAt: { * console.log(HashMap.get(updated, "a")) // Option.some(2) * ``` * + * @category transforming * @since 2.0.0 - * @category transformations */ (self: HashMap, key: K, f: HashMap.UpdateFn): HashMap } = internal.modifyAt /** - * Alter the value of the specified key in the `HashMap` using the specified - * update function. The value of the specified key will be computed using the - * provided hash. + * Sets or removes the specified key using a precomputed hash and an update + * function. + * + * **Details** * - * The update function will be invoked with the current value of the key if it - * exists, or `None` if no such value exists. + * The update function receives `Some(value)` when the key exists or `None` + * when it does not. Returning `Some(newValue)` stores the value, and returning + * `None` removes the key or leaves it absent. * - * This function will always either update or insert a value into the `HashMap`. + * **Example** (Updating values with a hash) * - * @example * ```ts - * import { Hash } from "effect" - * import * as HashMap from "effect/HashMap" - * import * as Option from "effect/Option" + * import { Hash, HashMap, Option } from "effect" * * // Useful when working with precomputed hashes for performance * const counters = HashMap.make(["downloads", 100], ["views", 250]) @@ -1268,25 +1365,24 @@ export const modifyAt: { * console.log(HashMap.get(withClicks, "clicks")) // Option.some(1) * ``` * + * @category transforming * @since 2.0.0 - * @category transformations */ export const modifyHash: { /** - * Alter the value of the specified key in the `HashMap` using the specified - * update function. The value of the specified key will be computed using the - * provided hash. + * Sets or removes the specified key using a precomputed hash and an update + * function. + * + * **Details** * - * The update function will be invoked with the current value of the key if it - * exists, or `None` if no such value exists. + * The update function receives `Some(value)` when the key exists or `None` + * when it does not. Returning `Some(newValue)` stores the value, and returning + * `None` removes the key or leaves it absent. * - * This function will always either update or insert a value into the `HashMap`. + * **Example** (Updating values with a hash) * - * @example * ```ts - * import { Hash } from "effect" - * import * as HashMap from "effect/HashMap" - * import * as Option from "effect/Option" + * import { Hash, HashMap, Option } from "effect" * * // Useful when working with precomputed hashes for performance * const counters = HashMap.make(["downloads", 100], ["views", 250]) @@ -1320,25 +1416,24 @@ export const modifyHash: { * console.log(HashMap.get(withClicks, "clicks")) // Option.some(1) * ``` * + * @category transforming * @since 2.0.0 - * @category transformations */ (key: K, hash: number, f: HashMap.UpdateFn): (self: HashMap) => HashMap /** - * Alter the value of the specified key in the `HashMap` using the specified - * update function. The value of the specified key will be computed using the - * provided hash. + * Sets or removes the specified key using a precomputed hash and an update + * function. * - * The update function will be invoked with the current value of the key if it - * exists, or `None` if no such value exists. + * **Details** * - * This function will always either update or insert a value into the `HashMap`. + * The update function receives `Some(value)` when the key exists or `None` + * when it does not. Returning `Some(newValue)` stores the value, and returning + * `None` removes the key or leaves it absent. + * + * **Example** (Updating values with a hash) * - * @example * ```ts - * import { Hash } from "effect" - * import * as HashMap from "effect/HashMap" - * import * as Option from "effect/Option" + * import { Hash, HashMap, Option } from "effect" * * // Useful when working with precomputed hashes for performance * const counters = HashMap.make(["downloads", 100], ["views", 250]) @@ -1372,8 +1467,8 @@ export const modifyHash: { * console.log(HashMap.get(withClicks, "clicks")) // Option.some(1) * ``` * + * @category transforming * @since 2.0.0 - * @category transformations */ (self: HashMap, key: K, hash: number, f: HashMap.UpdateFn): HashMap } = internal.modifyHash @@ -1381,9 +1476,10 @@ export const modifyHash: { /** * Updates the value of the specified key within the `HashMap` if it exists. * - * @example + * **Example** (Modifying existing values) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map1 = HashMap.make(["a", 1], ["b", 2]) * const map2 = HashMap.modify(map1, "a", (value) => value * 3) @@ -1392,16 +1488,17 @@ export const modifyHash: { * console.log(HashMap.get(map2, "b")) // Option.some(2) * ``` * + * @category transforming * @since 2.0.0 - * @category transformations */ export const modify: { /** * Updates the value of the specified key within the `HashMap` if it exists. * - * @example + * **Example** (Modifying existing values) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map1 = HashMap.make(["a", 1], ["b", 2]) * const map2 = HashMap.modify(map1, "a", (value) => value * 3) @@ -1410,16 +1507,17 @@ export const modify: { * console.log(HashMap.get(map2, "b")) // Option.some(2) * ``` * + * @category transforming * @since 2.0.0 - * @category transformations */ (key: K, f: (v: V) => V): (self: HashMap) => HashMap /** * Updates the value of the specified key within the `HashMap` if it exists. * - * @example + * **Example** (Modifying existing values) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map1 = HashMap.make(["a", 1], ["b", 2]) * const map2 = HashMap.modify(map1, "a", (value) => value * 3) @@ -1428,18 +1526,24 @@ export const modify: { * console.log(HashMap.get(map2, "b")) // Option.some(2) * ``` * + * @category transforming * @since 2.0.0 - * @category transformations */ (self: HashMap, key: K, f: (v: V) => V): HashMap } = internal.modify /** - * Performs a union of this `HashMap` and that `HashMap`. + * Combines two `HashMap`s into one. + * + * **Details** + * + * Entries from `that` are inserted into `self`; when both maps contain an + * equal key, the value from `that` replaces the value from `self`. + * + * **Example** (Combining HashMaps) * - * @example * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map1 = HashMap.make(["a", 1], ["b", 2]) * const map2 = HashMap.make(["b", 20], ["c", 3]) @@ -1449,16 +1553,22 @@ export const modify: { * console.log(HashMap.get(union, "b")) // Option.some(20) - map2 wins * ``` * - * @since 2.0.0 * @category combining + * @since 2.0.0 */ export const union: { /** - * Performs a union of this `HashMap` and that `HashMap`. + * Combines two `HashMap`s into one. + * + * **Details** + * + * Entries from `that` are inserted into `self`; when both maps contain an + * equal key, the value from `that` replaces the value from `self`. + * + * **Example** (Combining HashMaps) * - * @example * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map1 = HashMap.make(["a", 1], ["b", 2]) * const map2 = HashMap.make(["b", 20], ["c", 3]) @@ -1468,16 +1578,22 @@ export const union: { * console.log(HashMap.get(union, "b")) // Option.some(20) - map2 wins * ``` * - * @since 2.0.0 * @category combining + * @since 2.0.0 */ (that: HashMap): (self: HashMap) => HashMap /** - * Performs a union of this `HashMap` and that `HashMap`. + * Combines two `HashMap`s into one. + * + * **Details** + * + * Entries from `that` are inserted into `self`; when both maps contain an + * equal key, the value from `that` replaces the value from `self`. + * + * **Example** (Combining HashMaps) * - * @example * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map1 = HashMap.make(["a", 1], ["b", 2]) * const map2 = HashMap.make(["b", 20], ["c", 3]) @@ -1487,19 +1603,20 @@ export const union: { * console.log(HashMap.get(union, "b")) // Option.some(20) - map2 wins * ``` * - * @since 2.0.0 * @category combining + * @since 2.0.0 */ (self: HashMap, that: HashMap): HashMap } = internal.union /** - * Remove the entry for the specified key in the `HashMap` using the internal + * Removes the entry for the specified key in the `HashMap` using the internal * hashing function. * - * @example + * **Example** (Removing a key) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map1 = HashMap.make(["a", 1], ["b", 2], ["c", 3]) * const map2 = HashMap.remove(map1, "b") @@ -1509,17 +1626,18 @@ export const union: { * console.log(HashMap.has(map2, "a")) // true * ``` * + * @category transforming * @since 2.0.0 - * @category transformations */ export const remove: { /** - * Remove the entry for the specified key in the `HashMap` using the internal + * Removes the entry for the specified key in the `HashMap` using the internal * hashing function. * - * @example + * **Example** (Removing a key) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map1 = HashMap.make(["a", 1], ["b", 2], ["c", 3]) * const map2 = HashMap.remove(map1, "b") @@ -1529,17 +1647,18 @@ export const remove: { * console.log(HashMap.has(map2, "a")) // true * ``` * + * @category transforming * @since 2.0.0 - * @category transformations */ (key: K): (self: HashMap) => HashMap /** - * Remove the entry for the specified key in the `HashMap` using the internal + * Removes the entry for the specified key in the `HashMap` using the internal * hashing function. * - * @example + * **Example** (Removing a key) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map1 = HashMap.make(["a", 1], ["b", 2], ["c", 3]) * const map2 = HashMap.remove(map1, "b") @@ -1549,8 +1668,8 @@ export const remove: { * console.log(HashMap.has(map2, "a")) // true * ``` * + * @category transforming * @since 2.0.0 - * @category transformations */ (self: HashMap, key: K): HashMap } = internal.remove @@ -1558,9 +1677,10 @@ export const remove: { /** * Removes all entries in the `HashMap` which have the specified keys. * - * @example + * **Example** (Removing multiple keys) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map1 = HashMap.make(["a", 1], ["b", 2], ["c", 3], ["d", 4]) * const map2 = HashMap.removeMany(map1, ["b", "d"]) @@ -1570,16 +1690,17 @@ export const remove: { * console.log(HashMap.has(map2, "c")) // true * ``` * + * @category transforming * @since 2.0.0 - * @category transformations */ export const removeMany: { /** * Removes all entries in the `HashMap` which have the specified keys. * - * @example + * **Example** (Removing multiple keys) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map1 = HashMap.make(["a", 1], ["b", 2], ["c", 3], ["d", 4]) * const map2 = HashMap.removeMany(map1, ["b", "d"]) @@ -1589,16 +1710,17 @@ export const removeMany: { * console.log(HashMap.has(map2, "c")) // true * ``` * + * @category transforming * @since 2.0.0 - * @category transformations */ (keys: Iterable): (self: HashMap) => HashMap /** * Removes all entries in the `HashMap` which have the specified keys. * - * @example + * **Example** (Removing multiple keys) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map1 = HashMap.make(["a", 1], ["b", 2], ["c", 3], ["d", 4]) * const map2 = HashMap.removeMany(map1, ["b", "d"]) @@ -1608,8 +1730,8 @@ export const removeMany: { * console.log(HashMap.has(map2, "c")) // true * ``` * + * @category transforming * @since 2.0.0 - * @category transformations */ (self: HashMap, keys: Iterable): HashMap } = internal.removeMany @@ -1617,9 +1739,10 @@ export const removeMany: { /** * Sets multiple key-value pairs in the `HashMap`. * - * @example + * **Example** (Setting multiple entries) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map1 = HashMap.make(["a", 1], ["b", 2]) * const newEntries = [["c", 3], ["d", 4], ["a", 10]] as const // "a" will be overwritten @@ -1630,16 +1753,17 @@ export const removeMany: { * console.log(HashMap.get(map2, "c")) // Option.some(3) * ``` * - * @since 2.0.0 - * @category transformations + * @category transforming + * @since 4.0.0 */ export const setMany: { /** * Sets multiple key-value pairs in the `HashMap`. * - * @example + * **Example** (Setting multiple entries) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map1 = HashMap.make(["a", 1], ["b", 2]) * const newEntries = [["c", 3], ["d", 4], ["a", 10]] as const // "a" will be overwritten @@ -1650,16 +1774,17 @@ export const setMany: { * console.log(HashMap.get(map2, "c")) // Option.some(3) * ``` * - * @since 2.0.0 - * @category transformations + * @category transforming + * @since 4.0.0 */ (entries: Iterable): (self: HashMap) => HashMap /** * Sets multiple key-value pairs in the `HashMap`. * - * @example + * **Example** (Setting multiple entries) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map1 = HashMap.make(["a", 1], ["b", 2]) * const newEntries = [["c", 3], ["d", 4], ["a", 10]] as const // "a" will be overwritten @@ -1670,8 +1795,8 @@ export const setMany: { * console.log(HashMap.get(map2, "c")) // Option.some(3) * ``` * - * @since 2.0.0 - * @category transformations + * @category transforming + * @since 4.0.0 */ (self: HashMap, entries: Iterable): HashMap } = internal.setMany @@ -1679,9 +1804,10 @@ export const setMany: { /** * Maps over the entries of the `HashMap` using the specified function. * - * @example + * **Example** (Mapping values) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map1 = HashMap.make(["a", 1], ["b", 2], ["c", 3]) * const map2 = HashMap.map(map1, (value, key) => `${key}:${value * 2}`) @@ -1690,16 +1816,17 @@ export const setMany: { * console.log(HashMap.get(map2, "b")) // Option.some("b:4") * ``` * - * @since 2.0.0 * @category mapping + * @since 2.0.0 */ export const map: { /** * Maps over the entries of the `HashMap` using the specified function. * - * @example + * **Example** (Mapping values) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map1 = HashMap.make(["a", 1], ["b", 2], ["c", 3]) * const map2 = HashMap.map(map1, (value, key) => `${key}:${value * 2}`) @@ -1708,16 +1835,17 @@ export const map: { * console.log(HashMap.get(map2, "b")) // Option.some("b:4") * ``` * - * @since 2.0.0 * @category mapping + * @since 2.0.0 */ (f: (value: V, key: K) => A): (self: HashMap) => HashMap /** * Maps over the entries of the `HashMap` using the specified function. * - * @example + * **Example** (Mapping values) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map1 = HashMap.make(["a", 1], ["b", 2], ["c", 3]) * const map2 = HashMap.map(map1, (value, key) => `${key}:${value * 2}`) @@ -1726,20 +1854,23 @@ export const map: { * console.log(HashMap.get(map2, "b")) // Option.some("b:4") * ``` * - * @since 2.0.0 * @category mapping + * @since 2.0.0 */ (self: HashMap, f: (value: V, key: K) => A): HashMap } = internal.map /** - * Chains over the entries of the `HashMap` using the specified function. + * Maps each entry to a `HashMap` and flattens the results. * - * **NOTE**: the hash and equal of both maps have to be the same. + * **Gotchas** + * + * The hash and equality behavior of both maps have to be the same. + * + * **Example** (FlatMapping values) * - * @example * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map1 = HashMap.make(["a", 1], ["b", 2]) * const map2 = HashMap.flatMap( @@ -1752,18 +1883,21 @@ export const map: { * console.log(HashMap.get(map2, "b2")) // Option.some(4) * ``` * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ export const flatMap: { /** - * Chains over the entries of the `HashMap` using the specified function. + * Maps each entry to a `HashMap` and flattens the results. * - * **NOTE**: the hash and equal of both maps have to be the same. + * **Gotchas** + * + * The hash and equality behavior of both maps have to be the same. + * + * **Example** (FlatMapping values) * - * @example * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map1 = HashMap.make(["a", 1], ["b", 2]) * const map2 = HashMap.flatMap( @@ -1776,18 +1910,21 @@ export const flatMap: { * console.log(HashMap.get(map2, "b2")) // Option.some(4) * ``` * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ (f: (value: A, key: K) => HashMap): (self: HashMap) => HashMap /** - * Chains over the entries of the `HashMap` using the specified function. + * Maps each entry to a `HashMap` and flattens the results. * - * **NOTE**: the hash and equal of both maps have to be the same. + * **Gotchas** + * + * The hash and equality behavior of both maps have to be the same. + * + * **Example** (FlatMapping values) * - * @example * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map1 = HashMap.make(["a", 1], ["b", 2]) * const map2 = HashMap.flatMap( @@ -1800,8 +1937,8 @@ export const flatMap: { * console.log(HashMap.get(map2, "b2")) // Option.some(4) * ``` * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ (self: HashMap, f: (value: A, key: K) => HashMap): HashMap } = internal.flatMap @@ -1809,9 +1946,10 @@ export const flatMap: { /** * Applies the specified function to the entries of the `HashMap`. * - * @example + * **Example** (Iterating with side effects) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map = HashMap.make(["a", 1], ["b", 2]) * const collected: Array<[string, number]> = [] @@ -1823,16 +1961,17 @@ export const flatMap: { * console.log(collected.sort()) // [["a", 1], ["b", 2]] * ``` * - * @since 2.0.0 * @category traversing + * @since 2.0.0 */ export const forEach: { /** * Applies the specified function to the entries of the `HashMap`. * - * @example + * **Example** (Iterating with side effects) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map = HashMap.make(["a", 1], ["b", 2]) * const collected: Array<[string, number]> = [] @@ -1844,16 +1983,17 @@ export const forEach: { * console.log(collected.sort()) // [["a", 1], ["b", 2]] * ``` * - * @since 2.0.0 * @category traversing + * @since 2.0.0 */ (f: (value: V, key: K) => void): (self: HashMap) => void /** * Applies the specified function to the entries of the `HashMap`. * - * @example + * **Example** (Iterating with side effects) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map = HashMap.make(["a", 1], ["b", 2]) * const collected: Array<[string, number]> = [] @@ -1865,8 +2005,8 @@ export const forEach: { * console.log(collected.sort()) // [["a", 1], ["b", 2]] * ``` * - * @since 2.0.0 * @category traversing + * @since 2.0.0 */ (self: HashMap, f: (value: V, key: K) => void): void } = internal.forEach @@ -1874,9 +2014,10 @@ export const forEach: { /** * Reduces the specified state over the entries of the `HashMap`. * - * @example + * **Example** (Reducing values) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map = HashMap.make(["a", 1], ["b", 2], ["c", 3]) * const sum = HashMap.reduce(map, 0, (acc, value) => acc + value) @@ -1884,16 +2025,17 @@ export const forEach: { * console.log(sum) // 6 * ``` * - * @since 2.0.0 * @category folding + * @since 2.0.0 */ export const reduce: { /** * Reduces the specified state over the entries of the `HashMap`. * - * @example + * **Example** (Reducing values) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map = HashMap.make(["a", 1], ["b", 2], ["c", 3]) * const sum = HashMap.reduce(map, 0, (acc, value) => acc + value) @@ -1901,16 +2043,17 @@ export const reduce: { * console.log(sum) // 6 * ``` * - * @since 2.0.0 * @category folding + * @since 2.0.0 */ (zero: Z, f: (accumulator: Z, value: V, key: K) => Z): (self: HashMap) => Z /** * Reduces the specified state over the entries of the `HashMap`. * - * @example + * **Example** (Reducing values) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map = HashMap.make(["a", 1], ["b", 2], ["c", 3]) * const sum = HashMap.reduce(map, 0, (acc, value) => acc + value) @@ -1918,8 +2061,8 @@ export const reduce: { * console.log(sum) // 6 * ``` * - * @since 2.0.0 * @category folding + * @since 2.0.0 */ (self: HashMap, zero: Z, f: (accumulator: Z, value: V, key: K) => Z): Z } = internal.reduce @@ -1927,9 +2070,10 @@ export const reduce: { /** * Filters entries out of a `HashMap` using the specified predicate. * - * @example + * **Example** (Filtering entries) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map1 = HashMap.make(["a", 1], ["b", 2], ["c", 3], ["d", 4]) * const map2 = HashMap.filter(map1, (value) => value % 2 === 0) @@ -1940,16 +2084,17 @@ export const reduce: { * console.log(HashMap.has(map2, "a")) // false * ``` * - * @since 2.0.0 * @category filtering + * @since 2.0.0 */ export const filter: { /** * Filters entries out of a `HashMap` using the specified predicate. * - * @example + * **Example** (Filtering entries) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map1 = HashMap.make(["a", 1], ["b", 2], ["c", 3], ["d", 4]) * const map2 = HashMap.filter(map1, (value) => value % 2 === 0) @@ -1960,16 +2105,17 @@ export const filter: { * console.log(HashMap.has(map2, "a")) // false * ``` * - * @since 2.0.0 * @category filtering + * @since 2.0.0 */ (f: (a: NoInfer, k: K) => boolean): (self: HashMap) => HashMap /** * Filters entries out of a `HashMap` using the specified predicate. * - * @example + * **Example** (Filtering entries) + * * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map1 = HashMap.make(["a", 1], ["b", 2], ["c", 3], ["d", 4]) * const map2 = HashMap.filter(map1, (value) => value % 2 === 0) @@ -1980,8 +2126,8 @@ export const filter: { * console.log(HashMap.has(map2, "a")) // false * ``` * - * @since 2.0.0 * @category filtering + * @since 2.0.0 */ (self: HashMap, f: (a: A, k: K) => boolean): HashMap } = internal.filter @@ -1989,10 +2135,10 @@ export const filter: { /** * Filters out `None` values from a `HashMap` of `Options`s. * - * @example + * **Example** (Compacting Option values) + * * ```ts - * import * as HashMap from "effect/HashMap" - * import * as Option from "effect/Option" + * import { HashMap, Option } from "effect" * * const map1 = HashMap.make( * ["a", Option.some(1)], @@ -2006,8 +2152,8 @@ export const filter: { * console.log(HashMap.has(map2, "b")) // false * ``` * - * @since 2.0.0 * @category filtering + * @since 2.0.0 */ export const compact: (self: HashMap>) => HashMap = internal.compact @@ -2015,10 +2161,10 @@ export const compact: (self: HashMap>) => HashMap = int * Maps over the entries of the `HashMap` using the specified filter and keeps * only successful results. * - * @example + * **Example** (Filtering and mapping Results) + * * ```ts - * import * as HashMap from "effect/HashMap" - * import * as Result from "effect/Result" + * import { HashMap, Result } from "effect" * * const map1 = HashMap.make(["a", 1], ["b", 2], ["c", 3], ["d", 4]) * const map2 = HashMap.filterMap( @@ -2031,18 +2177,18 @@ export const compact: (self: HashMap>) => HashMap = int * console.log(HashMap.get(map2, "d")) // Option.some(8) * ``` * - * @since 2.0.0 * @category filtering + * @since 2.0.0 */ export const filterMap: { /** * Maps over the entries of the `HashMap` using the specified filter and keeps * only successful results. * - * @example + * **Example** (Filtering and mapping Results) + * * ```ts - * import * as HashMap from "effect/HashMap" - * import * as Result from "effect/Result" + * import { HashMap, Result } from "effect" * * const map1 = HashMap.make(["a", 1], ["b", 2], ["c", 3], ["d", 4]) * const map2 = HashMap.filterMap( @@ -2055,18 +2201,18 @@ export const filterMap: { * console.log(HashMap.get(map2, "d")) // Option.some(8) * ``` * - * @since 2.0.0 * @category filtering + * @since 2.0.0 */ (f: (input: A, key: K) => Result): (self: HashMap) => HashMap /** * Maps over the entries of the `HashMap` using the specified filter and keeps * only successful results. * - * @example + * **Example** (Filtering and mapping Results) + * * ```ts - * import * as HashMap from "effect/HashMap" - * import * as Result from "effect/Result" + * import { HashMap, Result } from "effect" * * const map1 = HashMap.make(["a", 1], ["b", 2], ["c", 3], ["d", 4]) * const map2 = HashMap.filterMap( @@ -2079,8 +2225,8 @@ export const filterMap: { * console.log(HashMap.get(map2, "d")) // Option.some(8) * ``` * - * @since 2.0.0 * @category filtering + * @since 2.0.0 */ (self: HashMap, f: (input: A, key: K) => Result): HashMap } = internal.filterMap @@ -2089,15 +2235,15 @@ export const filterMap: { * Returns the first element that satisfies the specified * predicate, or `None` if no such element exists. * - * @example + * **Example** (Finding the first matching entry) + * * ```ts - * import * as HashMap from "effect/HashMap" - * import * as Option from "effect/Option" + * import { HashMap, Option } from "effect" * * const map = HashMap.make(["a", 1], ["b", 2], ["c", 3]) - * const result = HashMap.findFirst(map, (value) => value > 1) - * console.log(result) // Option.some(["c", 3]) - * console.log(Option.getOrElse(result, () => ["", 0])) // ["c", 3] + * const result = HashMap.findFirst(map, (value, key) => key === "b" && value > 1) + * console.log(result) // Option.some(["b", 2]) + * console.log(Option.getOrElse(result, () => ["", 0])) // ["b", 2] * ``` * * @category elements @@ -2108,15 +2254,15 @@ export const findFirst: { * Returns the first element that satisfies the specified * predicate, or `None` if no such element exists. * - * @example + * **Example** (Finding the first matching entry) + * * ```ts - * import * as HashMap from "effect/HashMap" - * import * as Option from "effect/Option" + * import { HashMap, Option } from "effect" * * const map = HashMap.make(["a", 1], ["b", 2], ["c", 3]) - * const result = HashMap.findFirst(map, (value) => value > 1) - * console.log(result) // Option.some(["c", 3]) - * console.log(Option.getOrElse(result, () => ["", 0])) // ["c", 3] + * const result = HashMap.findFirst(map, (value, key) => key === "b" && value > 1) + * console.log(result) // Option.some(["b", 2]) + * console.log(Option.getOrElse(result, () => ["", 0])) // ["b", 2] * ``` * * @category elements @@ -2127,15 +2273,15 @@ export const findFirst: { * Returns the first element that satisfies the specified * predicate, or `None` if no such element exists. * - * @example + * **Example** (Finding the first matching entry) + * * ```ts - * import * as HashMap from "effect/HashMap" - * import * as Option from "effect/Option" + * import { HashMap, Option } from "effect" * * const map = HashMap.make(["a", 1], ["b", 2], ["c", 3]) - * const result = HashMap.findFirst(map, (value) => value > 1) - * console.log(result) // Option.some(["c", 3]) - * console.log(Option.getOrElse(result, () => ["", 0])) // ["c", 3] + * const result = HashMap.findFirst(map, (value, key) => key === "b" && value > 1) + * console.log(result) // Option.some(["b", 2]) + * console.log(Option.getOrElse(result, () => ["", 0])) // ["b", 2] * ``` * * @category elements @@ -2145,11 +2291,12 @@ export const findFirst: { } = internal.findFirst /** - * Checks if any entry in a hashmap meets a specific condition. + * Checks whether any entry in a hashmap meets a specific condition. + * + * **Example** (Checking for any matching entry) * - * @example * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map = HashMap.make(["a", 1], ["b", 2], ["c", 3]) * @@ -2157,16 +2304,17 @@ export const findFirst: { * console.log(HashMap.some(map, (value) => value > 5)) // false * ``` * - * @since 3.13.0 * @category elements + * @since 3.13.0 */ export const some: { /** - * Checks if any entry in a hashmap meets a specific condition. + * Checks whether any entry in a hashmap meets a specific condition. + * + * **Example** (Checking for any matching entry) * - * @example * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map = HashMap.make(["a", 1], ["b", 2], ["c", 3]) * @@ -2174,16 +2322,17 @@ export const some: { * console.log(HashMap.some(map, (value) => value > 5)) // false * ``` * - * @since 3.13.0 * @category elements + * @since 3.13.0 */ (predicate: (a: NoInfer, k: K) => boolean): (self: HashMap) => boolean /** - * Checks if any entry in a hashmap meets a specific condition. + * Checks whether any entry in a hashmap meets a specific condition. + * + * **Example** (Checking for any matching entry) * - * @example * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map = HashMap.make(["a", 1], ["b", 2], ["c", 3]) * @@ -2191,18 +2340,19 @@ export const some: { * console.log(HashMap.some(map, (value) => value > 5)) // false * ``` * - * @since 3.13.0 * @category elements + * @since 3.13.0 */ (self: HashMap, predicate: (a: A, k: K) => boolean): boolean } = internal.some /** - * Checks if all entries in a hashmap meets a specific condition. + * Checks whether all entries in a hashmap meets a specific condition. + * + * **Example** (Checking all entries) * - * @example * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map = HashMap.make(["a", 1], ["b", 2], ["c", 3]) * @@ -2210,19 +2360,17 @@ export const some: { * console.log(HashMap.every(map, (value) => value > 1)) // false * ``` * - * @param self - The hashmap to check. - * @param predicate - The condition to test entries (value, key). - * - * @since 3.14.0 * @category elements + * @since 3.14.0 */ export const every: { /** - * Checks if all entries in a hashmap meets a specific condition. + * Checks whether all entries in a hashmap meets a specific condition. + * + * **Example** (Checking all entries) * - * @example * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map = HashMap.make(["a", 1], ["b", 2], ["c", 3]) * @@ -2230,19 +2378,17 @@ export const every: { * console.log(HashMap.every(map, (value) => value > 1)) // false * ``` * - * @param self - The hashmap to check. - * @param predicate - The condition to test entries (value, key). - * - * @since 3.14.0 * @category elements + * @since 3.14.0 */ (predicate: (a: NoInfer, k: K) => boolean): (self: HashMap) => boolean /** - * Checks if all entries in a hashmap meets a specific condition. + * Checks whether all entries in a hashmap meets a specific condition. + * + * **Example** (Checking all entries) * - * @example * ```ts - * import * as HashMap from "effect/HashMap" + * import { HashMap } from "effect" * * const map = HashMap.make(["a", 1], ["b", 2], ["c", 3]) * @@ -2250,11 +2396,8 @@ export const every: { * console.log(HashMap.every(map, (value) => value > 1)) // false * ``` * - * @param self - The hashmap to check. - * @param predicate - The condition to test entries (value, key). - * - * @since 3.14.0 * @category elements + * @since 3.14.0 */ (self: HashMap, predicate: (a: A, k: K) => boolean): boolean } = internal.every diff --git a/.opencode/node_modules/effect/src/HashRing.ts b/.opencode/node_modules/effect/src/HashRing.ts index ec2ac5e337cec5cfee26e0f646775088aefb23ba..8416ea5745d848293db0efc4d6df60cf44d2c959 100644 --- a/.opencode/node_modules/effect/src/HashRing.ts +++ b/.opencode/node_modules/effect/src/HashRing.ts @@ -1,4 +1,12 @@ /** + * Assigns string inputs to nodes with weighted consistent hashing. + * + * A hash ring minimizes remapping when nodes are added, removed, or reweighted. + * This makes it useful for routing requests, partitioning keys, and + * distributing shards across service instances or storage backends. This module + * can create rings, add or remove nodes by `PrimaryKey`, route an input string + * to a node, and compute shard assignments. + * * @since 4.0.0 */ import { dual } from "./Function.ts" @@ -12,8 +20,21 @@ import * as PrimaryKey from "./PrimaryKey.ts" const TypeId = "~effect/cluster/HashRing" as const /** - * @since 4.0.0 - * @category Models + * A weighted consistent-hashing ring for assigning inputs to nodes with stable + * remapping as nodes are added or removed. + * + * **When to use** + * + * Use to maintain a mutable weighted hash ring for routing keys or shards to + * nodes identified by `PrimaryKey`. + * + * **Details** + * + * Nodes are identified by their `PrimaryKey` value and can be iterated from the + * ring. + * + * @category models + * @since 3.19.0 */ export interface HashRing extends Pipeable, Iterable { readonly [TypeId]: typeof TypeId @@ -24,14 +45,49 @@ export interface HashRing extends Pipeable, Ite } /** - * @since 4.0.0 - * @category Guards + * Checks whether a value is a `HashRing`. + * + * **When to use** + * + * Use to narrow an `unknown` value before treating it as a `HashRing`, such as + * values crossing an untyped boundary. + * + * **Details** + * + * The guard checks for the module's internal `TypeId` property and narrows to + * `HashRing`. + * + * **Gotchas** + * + * This is a structural type-id check; it does not validate the ring's `nodes`, + * `ring`, or weight state. + * + * @see {@link HashRing} for the type narrowed by this guard + * @see {@link make} for creating an empty `HashRing` + * + * @category guards + * @since 3.19.0 */ export const isHashRing = (u: unknown): u is HashRing => hasProperty(u, TypeId) /** - * @since 4.0.0 - * @category Constructors + * Creates an empty `HashRing`. + * + * **When to use** + * + * Use to create an empty weighted consistent-hashing ring with the default or + * custom virtual-point density. + * + * **Details** + * + * `baseWeight` controls how many virtual points are added for a node with + * weight `1`; it defaults to `128` and is clamped to at least `1`. + * + * @see {@link add} for registering one node after creation + * @see {@link addMany} for registering several nodes after creation + * + * @category constructors + * @since 3.19.0 */ export const make = (options?: { readonly baseWeight?: number | undefined @@ -60,19 +116,27 @@ const Proto = { } /** - * Add new nodes to the ring. If a node already exists in the ring, it + * Adds 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 4.0.0 - * @category Combinators + * **When to use** + * + * Use to register or update several nodes in a `HashRing` at the same weight. + * + * @category combinators + * @since 3.19.0 */ export const addMany: { /** - * Add new nodes to the ring. If a node already exists in the ring, it + * Adds 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 4.0.0 - * @category Combinators + * **When to use** + * + * Use to register or update several nodes in a `HashRing` at the same weight. + * + * @category combinators + * @since 3.19.0 */ ( nodes: Iterable, @@ -81,11 +145,15 @@ export const addMany: { } ): (self: HashRing) => HashRing /** - * Add new nodes to the ring. If a node already exists in the ring, it + * Adds 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 4.0.0 - * @category Combinators + * **When to use** + * + * Use to register or update several nodes in a `HashRing` at the same weight. + * + * @category combinators + * @since 3.19.0 */ ( self: HashRing, @@ -140,19 +208,55 @@ function addNodesToRing(self: HashRing, keys } /** - * Add a new node to the ring. If the node already exists in the ring, it + * Adds 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 4.0.0 - * @category Combinators + * **When to use** + * + * Use to register one node in a `HashRing` so lookups and shard assignments can + * return it, or update that node's weight. + * + * **Details** + * + * Nodes are matched by `PrimaryKey.value`. The weight defaults to `1` and is + * clamped to at least `0.1`. + * + * **Gotchas** + * + * This mutates and returns the same ring instance. + * + * @see {@link addMany} for adding or updating several nodes + * @see {@link remove} for unregistering a node + * @see {@link has} for checking primary-key membership + * + * @category combinators + * @since 3.19.0 */ export const add: { /** - * Add a new node to the ring. If the node already exists in the ring, it + * Adds 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 4.0.0 - * @category Combinators + * **When to use** + * + * Use to register one node in a `HashRing` so lookups and shard assignments can + * return it, or update that node's weight. + * + * **Details** + * + * Nodes are matched by `PrimaryKey.value`. The weight defaults to `1` and is + * clamped to at least `0.1`. + * + * **Gotchas** + * + * This mutates and returns the same ring instance. + * + * @see {@link addMany} for adding or updating several nodes + * @see {@link remove} for unregistering a node + * @see {@link has} for checking primary-key membership + * + * @category combinators + * @since 3.19.0 */ ( node: A, @@ -161,11 +265,29 @@ export const add: { } ): (self: HashRing) => HashRing /** - * Add a new node to the ring. If the node already exists in the ring, it + * Adds 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 4.0.0 - * @category Combinators + * **When to use** + * + * Use to register one node in a `HashRing` so lookups and shard assignments can + * return it, or update that node's weight. + * + * **Details** + * + * Nodes are matched by `PrimaryKey.value`. The weight defaults to `1` and is + * clamped to at least `0.1`. + * + * **Gotchas** + * + * This mutates and returns the same ring instance. + * + * @see {@link addMany} for adding or updating several nodes + * @see {@link remove} for unregistering a node + * @see {@link has} for checking primary-key membership + * + * @category combinators + * @since 3.19.0 */ ( self: HashRing, @@ -181,22 +303,73 @@ export const add: { /** * Removes the node from the ring. No-op's if the node does not exist. * - * @since 4.0.0 - * @category Combinators + * **When to use** + * + * Use to remove a node that has left the pool so future lookups and shard + * assignments stop returning it. + * + * **Details** + * + * Removal matches by `PrimaryKey.value`, so any value with the same primary key + * removes the same ring member. + * + * **Gotchas** + * + * This mutates and returns the same ring instance. + * + * @see {@link add} for registering or updating a node + * @see {@link has} for checking membership by primary key + * + * @category combinators + * @since 3.19.0 */ export const remove: { /** * Removes the node from the ring. No-op's if the node does not exist. * - * @since 4.0.0 - * @category Combinators + * **When to use** + * + * Use to remove a node that has left the pool so future lookups and shard + * assignments stop returning it. + * + * **Details** + * + * Removal matches by `PrimaryKey.value`, so any value with the same primary key + * removes the same ring member. + * + * **Gotchas** + * + * This mutates and returns the same ring instance. + * + * @see {@link add} for registering or updating a node + * @see {@link has} for checking membership by primary key + * + * @category combinators + * @since 3.19.0 */ (node: A): (self: HashRing) => HashRing /** * Removes the node from the ring. No-op's if the node does not exist. * - * @since 4.0.0 - * @category Combinators + * **When to use** + * + * Use to remove a node that has left the pool so future lookups and shard + * assignments stop returning it. + * + * **Details** + * + * Removal matches by `PrimaryKey.value`, so any value with the same primary key + * removes the same ring member. + * + * **Gotchas** + * + * This mutates and returns the same ring instance. + * + * @see {@link add} for registering or updating a node + * @see {@link has} for checking membership by primary key + * + * @category combinators + * @since 3.19.0 */ (self: HashRing, node: A): HashRing } = dual(2, (self: HashRing, node: A): HashRing => { @@ -211,18 +384,66 @@ export const remove: { }) /** - * @since 4.0.0 - * @category Combinators + * Checks whether the ring contains a node with the same `PrimaryKey` value. + * + * **When to use** + * + * Use when you need to know whether registering a node would update an existing + * ring member because another node already has the same primary-key identity. + * + * **Details** + * + * Membership is checked with `self.nodes.has(PrimaryKey.value(node))`, so + * matching is by primary key, not object identity or weight. + * + * @see {@link add} for registering or updating nodes + * @see {@link remove} for removing nodes by the same primary-key identity + * @see {@link get} for routing an input string to a node + * + * @category combinators + * @since 3.19.0 */ export const has: { /** - * @since 4.0.0 - * @category Combinators + * Checks whether the ring contains a node with the same `PrimaryKey` value. + * + * **When to use** + * + * Use when you need to know whether registering a node would update an existing + * ring member because another node already has the same primary-key identity. + * + * **Details** + * + * Membership is checked with `self.nodes.has(PrimaryKey.value(node))`, so + * matching is by primary key, not object identity or weight. + * + * @see {@link add} for registering or updating nodes + * @see {@link remove} for removing nodes by the same primary-key identity + * @see {@link get} for routing an input string to a node + * + * @category combinators + * @since 3.19.0 */ (node: A): (self: HashRing) => boolean /** - * @since 4.0.0 - * @category Combinators + * Checks whether the ring contains a node with the same `PrimaryKey` value. + * + * **When to use** + * + * Use when you need to know whether registering a node would update an existing + * ring member because another node already has the same primary-key identity. + * + * **Details** + * + * Membership is checked with `self.nodes.has(PrimaryKey.value(node))`, so + * matching is by primary key, not object identity or weight. + * + * @see {@link add} for registering or updating nodes + * @see {@link remove} for removing nodes by the same primary-key identity + * @see {@link get} for routing an input string to a node + * + * @category combinators + * @since 3.19.0 */ (self: HashRing, node: A): boolean } = dual( @@ -234,8 +455,16 @@ export const has: { * Gets the node which should handle the given input. Returns undefined if * the hashring has no elements with weight. * - * @since 4.0.0 - * @category Combinators + * **When to use** + * + * Use to route a single string input key to the current ring member responsible + * for that key. + * + * @see {@link getShards} for assigning fixed shard indexes instead of routing + * one input string at a time + * + * @category combinators + * @since 3.19.0 */ export const get = (self: HashRing, input: string): A | undefined => { if (self.ring.length === 0) { @@ -247,12 +476,15 @@ export const get = (self: HashRing, input: s } /** - * 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. + * Computes a balanced shard distribution across the nodes in the ring. * - * @since 4.0.0 - * @category Combinators + * **When to use** + * + * Use to precompute ownership for a fixed number of shard indexes across the + * current ring members. + * + * @category combinators + * @since 3.19.0 */ export const getShards = (self: HashRing, count: number): Array | undefined => { if (self.ring.length === 0) { diff --git a/.opencode/node_modules/effect/src/HashSet.ts b/.opencode/node_modules/effect/src/HashSet.ts index 598b889d8dd0140c0310cd0f7bef3fa289d5e34b..1a5388404ecc2decf9c91bdf91677f508e9b2d87 100644 --- a/.opencode/node_modules/effect/src/HashSet.ts +++ b/.opencode/node_modules/effect/src/HashSet.ts @@ -1,4 +1,12 @@ /** + * Stores unique values in an immutable hash set. + * + * A `HashSet` contains at most one value for each equality class according + * to Effect's `Equal` and `Hash` rules. Membership checks, additions, removals, + * and set operations return new sets. This module also includes constructors, + * union, intersection, difference, subset checks, mapping, filtering, and + * reducing helpers. + * * @since 2.0.0 */ @@ -16,9 +24,10 @@ const TypeId = internal.HashSetTypeId * A HashSet is an immutable set data structure that provides efficient storage * and retrieval of unique values. It uses a HashMap internally for optimal performance. * - * @example + * **Example** (Creating and updating a HashSet) + * * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * // Create a HashSet * const set = HashSet.make("apple", "banana", "cherry") @@ -36,8 +45,8 @@ const TypeId = internal.HashSetTypeId * console.log(HashSet.size(smaller)) // 2 * ``` * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface HashSet extends Iterable, Equal, Pipeable, Inspectable { readonly [TypeId]: typeof TypeId @@ -47,9 +56,10 @@ export interface HashSet extends Iterable, Equal, Pipeable, In * The HashSet namespace contains type-level utilities and helper types * for working with HashSet instances. * - * @example + * **Example** (Extracting value types from a HashSet) + * * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * // Create a concrete HashSet for type extraction * const fruits = HashSet.make("apple", "banana", "cherry") @@ -64,13 +74,19 @@ export interface HashSet extends Iterable, Equal, Pipeable, In * ``` * * @since 2.0.0 - * @category namespace */ export declare namespace HashSet { /** - * @example + * Extracts the element type from a `HashSet`. + * + * **Details** + * + * For `HashSet.HashSet`, `HashSet.Value<...>` resolves to `A`. + * + * **Example** (Extracting a HashSet value type) + * * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const numbers = HashSet.make(1, 2, 3, 4, 5) * @@ -80,8 +96,8 @@ export declare namespace HashSet { * const processNumber = (n: NumberType) => n * 2 * ``` * - * @since 2.0.0 - * @category type-level + * @category utility types + * @since 4.0.0 */ export type Value = T extends HashSet ? V : never } @@ -89,9 +105,10 @@ export declare namespace HashSet { /** * Creates an empty HashSet. * - * @example + * **Example** (Creating an empty HashSet) + * * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const set = HashSet.empty() * @@ -103,17 +120,18 @@ export declare namespace HashSet { * console.log(HashSet.size(withValues)) // 2 * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const empty: () => HashSet = internal.empty /** * Creates a HashSet from a variable number of values. * - * @example + * **Example** (Creating a HashSet from values) + * * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const fruits = HashSet.make("apple", "banana", "cherry") * console.log(HashSet.size(fruits)) // 3 @@ -125,8 +143,8 @@ export const empty: () => HashSet = internal.empty * console.log(HashSet.size(mixed)) // 3 * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const make: >( ...values: Values @@ -135,9 +153,10 @@ export const make: >( /** * Creates a HashSet from an iterable collection of values. * - * @example + * **Example** (Creating a HashSet from an iterable) + * * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const fromArray = HashSet.fromIterable(["a", "b", "c", "b", "a"]) * console.log(HashSet.size(fromArray)) // 3 @@ -149,17 +168,18 @@ export const make: >( * console.log(Array.from(fromString)) // ["h", "e", "l", "o"] * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const fromIterable: (values: Iterable) => HashSet = internal.fromIterable /** - * Checks if a value is a HashSet. + * Checks whether a value is a HashSet. + * + * **Example** (Checking for a HashSet) * - * @example * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const set = HashSet.make(1, 2, 3) * const array = [1, 2, 3] @@ -169,16 +189,17 @@ export const fromIterable: (values: Iterable) => HashSet = internal.fro * console.log(HashSet.isHashSet(null)) // false * ``` * - * @since 2.0.0 * @category guards + * @since 2.0.0 */ export const isHashSet: { /** - * Checks if a value is a HashSet. + * Checks whether a value is a HashSet. + * + * **Example** (Checking for a HashSet) * - * @example * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const set = HashSet.make(1, 2, 3) * const array = [1, 2, 3] @@ -188,16 +209,17 @@ export const isHashSet: { * console.log(HashSet.isHashSet(null)) // false * ``` * - * @since 2.0.0 * @category guards + * @since 2.0.0 */ (u: Iterable): u is HashSet /** - * Checks if a value is a HashSet. + * Checks whether a value is a HashSet. + * + * **Example** (Checking for a HashSet) * - * @example * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const set = HashSet.make(1, 2, 3) * const array = [1, 2, 3] @@ -207,8 +229,8 @@ export const isHashSet: { * console.log(HashSet.isHashSet(null)) // false * ``` * - * @since 2.0.0 * @category guards + * @since 2.0.0 */ (u: unknown): u is HashSet } = internal.isHashSet @@ -216,9 +238,10 @@ export const isHashSet: { /** * Adds a value to the HashSet, returning a new HashSet. * - * @example + * **Example** (Adding values to a HashSet) + * * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const set = HashSet.make("a", "b") * const withC = HashSet.add(set, "c") @@ -232,16 +255,17 @@ export const isHashSet: { * console.log(HashSet.size(same)) // 2 * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ export const add: { /** * Adds a value to the HashSet, returning a new HashSet. * - * @example + * **Example** (Adding values to a HashSet) + * * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const set = HashSet.make("a", "b") * const withC = HashSet.add(set, "c") @@ -255,16 +279,17 @@ export const add: { * console.log(HashSet.size(same)) // 2 * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ (value: V): (self: HashSet) => HashSet /** * Adds a value to the HashSet, returning a new HashSet. * - * @example + * **Example** (Adding values to a HashSet) + * * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const set = HashSet.make("a", "b") * const withC = HashSet.add(set, "c") @@ -278,8 +303,8 @@ export const add: { * console.log(HashSet.size(same)) // 2 * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ (self: HashSet, value: V): HashSet } = Dual.dual< @@ -288,19 +313,19 @@ export const add: { >(2, internal.add) /** - * Checks if the HashSet contains the specified value. + * Checks whether the HashSet contains the specified value. + * + * **Example** (Checking HashSet membership) * - * @example * ```ts - * import * as HashSet from "effect/HashSet" // false + * import { Equal, Hash, HashSet } from "effect" * * // Works with any type that implements Equal - * import { Equal, Hash } from "effect" * * const set = HashSet.make("apple", "banana", "cherry") * * console.log(HashSet.has(set, "apple")) // true - * console.log(HashSet.has(set, "grape")) + * console.log(HashSet.has(set, "grape")) // false * * class Person implements Equal.Equal { * constructor(readonly name: string) {} @@ -318,24 +343,24 @@ export const add: { * console.log(HashSet.has(people, new Person("Alice"))) // true * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ export const has: { /** - * Checks if the HashSet contains the specified value. + * Checks whether the HashSet contains the specified value. + * + * **Example** (Checking HashSet membership) * - * @example * ```ts - * import * as HashSet from "effect/HashSet" // false + * import { Equal, Hash, HashSet } from "effect" * * // Works with any type that implements Equal - * import { Equal, Hash } from "effect" * * const set = HashSet.make("apple", "banana", "cherry") * * console.log(HashSet.has(set, "apple")) // true - * console.log(HashSet.has(set, "grape")) + * console.log(HashSet.has(set, "grape")) // false * * class Person implements Equal.Equal { * constructor(readonly name: string) {} @@ -353,24 +378,24 @@ export const has: { * console.log(HashSet.has(people, new Person("Alice"))) // true * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (value: V): (self: HashSet) => boolean /** - * Checks if the HashSet contains the specified value. + * Checks whether the HashSet contains the specified value. + * + * **Example** (Checking HashSet membership) * - * @example * ```ts - * import * as HashSet from "effect/HashSet" // false + * import { Equal, Hash, HashSet } from "effect" * * // Works with any type that implements Equal - * import { Equal, Hash } from "effect" * * const set = HashSet.make("apple", "banana", "cherry") * * console.log(HashSet.has(set, "apple")) // true - * console.log(HashSet.has(set, "grape")) + * console.log(HashSet.has(set, "grape")) // false * * class Person implements Equal.Equal { * constructor(readonly name: string) {} @@ -388,8 +413,8 @@ export const has: { * console.log(HashSet.has(people, new Person("Alice"))) // true * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (self: HashSet, value: V): boolean } = Dual.dual< @@ -400,9 +425,10 @@ export const has: { /** * Removes a value from the HashSet, returning a new HashSet. * - * @example + * **Example** (Removing values from a HashSet) + * * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const set = HashSet.make("a", "b", "c") * const withoutB = HashSet.remove(set, "b") @@ -416,16 +442,17 @@ export const has: { * console.log(HashSet.size(same)) // 3 * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ export const remove: { /** * Removes a value from the HashSet, returning a new HashSet. * - * @example + * **Example** (Removing values from a HashSet) + * * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const set = HashSet.make("a", "b", "c") * const withoutB = HashSet.remove(set, "b") @@ -439,16 +466,17 @@ export const remove: { * console.log(HashSet.size(same)) // 3 * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ (value: V): (self: HashSet) => HashSet /** * Removes a value from the HashSet, returning a new HashSet. * - * @example + * **Example** (Removing values from a HashSet) + * * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const set = HashSet.make("a", "b", "c") * const withoutB = HashSet.remove(set, "b") @@ -462,8 +490,8 @@ export const remove: { * console.log(HashSet.size(same)) // 3 * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ (self: HashSet, value: V): HashSet } = Dual.dual< @@ -474,9 +502,10 @@ export const remove: { /** * Returns the number of values in the HashSet. * - * @example + * **Example** (Getting the HashSet size) + * * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const empty = HashSet.empty() * console.log(HashSet.size(empty)) // 0 @@ -488,17 +517,18 @@ export const remove: { * console.log(HashSet.size(withDuplicates)) // 3 * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export const size: (self: HashSet) => number = internal.size /** - * Checks if the HashSet is empty. + * Checks whether the HashSet is empty. + * + * **Example** (Checking whether a HashSet is empty) * - * @example * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const empty = HashSet.empty() * console.log(HashSet.isEmpty(empty)) // true @@ -507,17 +537,18 @@ export const size: (self: HashSet) => number = internal.size * console.log(HashSet.isEmpty(nonEmpty)) // false * ``` * - * @since 2.0.0 * @category getters + * @since 4.0.0 */ export const isEmpty: (self: HashSet) => boolean = internal.isEmpty /** * Creates the union of two HashSets. * - * @example + * **Example** (Combining HashSets) + * * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const set1 = HashSet.make("a", "b") * const set2 = HashSet.make("b", "c") @@ -527,16 +558,17 @@ export const isEmpty: (self: HashSet) => boolean = internal.isEmpty * console.log(HashSet.size(combined)) // 3 * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const union: { /** * Creates the union of two HashSets. * - * @example + * **Example** (Combining HashSets) + * * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const set1 = HashSet.make("a", "b") * const set2 = HashSet.make("b", "c") @@ -546,16 +578,17 @@ export const union: { * console.log(HashSet.size(combined)) // 3 * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (that: HashSet): (self: HashSet) => HashSet /** * Creates the union of two HashSets. * - * @example + * **Example** (Combining HashSets) + * * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const set1 = HashSet.make("a", "b") * const set2 = HashSet.make("b", "c") @@ -565,8 +598,8 @@ export const union: { * console.log(HashSet.size(combined)) // 3 * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (self: HashSet, that: HashSet): HashSet } = Dual.dual< @@ -577,9 +610,10 @@ export const union: { /** * Creates the intersection of two HashSets. * - * @example + * **Example** (Finding common HashSet values) + * * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const set1 = HashSet.make("a", "b", "c") * const set2 = HashSet.make("b", "c", "d") @@ -589,16 +623,17 @@ export const union: { * console.log(HashSet.size(common)) // 2 * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const intersection: { /** * Creates the intersection of two HashSets. * - * @example + * **Example** (Finding common HashSet values) + * * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const set1 = HashSet.make("a", "b", "c") * const set2 = HashSet.make("b", "c", "d") @@ -608,16 +643,17 @@ export const intersection: { * console.log(HashSet.size(common)) // 2 * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (that: HashSet): (self: HashSet) => HashSet /** * Creates the intersection of two HashSets. * - * @example + * **Example** (Finding common HashSet values) + * * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const set1 = HashSet.make("a", "b", "c") * const set2 = HashSet.make("b", "c", "d") @@ -627,8 +663,8 @@ export const intersection: { * console.log(HashSet.size(common)) // 2 * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (self: HashSet, that: HashSet): HashSet } = Dual.dual< @@ -639,9 +675,10 @@ export const intersection: { /** * Creates the difference of two HashSets (elements in the first set that are not in the second). * - * @example + * **Example** (Finding HashSet differences) + * * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const set1 = HashSet.make("a", "b", "c") * const set2 = HashSet.make("b", "d") @@ -651,16 +688,17 @@ export const intersection: { * console.log(HashSet.size(diff)) // 2 * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const difference: { /** * Creates the difference of two HashSets (elements in the first set that are not in the second). * - * @example + * **Example** (Finding HashSet differences) + * * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const set1 = HashSet.make("a", "b", "c") * const set2 = HashSet.make("b", "d") @@ -670,16 +708,17 @@ export const difference: { * console.log(HashSet.size(diff)) // 2 * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (that: HashSet): (self: HashSet) => HashSet /** * Creates the difference of two HashSets (elements in the first set that are not in the second). * - * @example + * **Example** (Finding HashSet differences) + * * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const set1 = HashSet.make("a", "b", "c") * const set2 = HashSet.make("b", "d") @@ -689,8 +728,8 @@ export const difference: { * console.log(HashSet.size(diff)) // 2 * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (self: HashSet, that: HashSet): HashSet } = Dual.dual< @@ -699,11 +738,12 @@ export const difference: { >(2, internal.difference) /** - * Checks if a HashSet is a subset of another HashSet. + * Checks whether a HashSet is a subset of another HashSet. + * + * **Example** (Checking subset relationships) * - * @example * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const small = HashSet.make("a", "b") * const large = HashSet.make("a", "b", "c", "d") @@ -715,16 +755,17 @@ export const difference: { * console.log(HashSet.isSubset(small, small)) // true * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ export const isSubset: { /** - * Checks if a HashSet is a subset of another HashSet. + * Checks whether a HashSet is a subset of another HashSet. + * + * **Example** (Checking subset relationships) * - * @example * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const small = HashSet.make("a", "b") * const large = HashSet.make("a", "b", "c", "d") @@ -736,16 +777,17 @@ export const isSubset: { * console.log(HashSet.isSubset(small, small)) // true * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (that: HashSet): (self: HashSet) => boolean /** - * Checks if a HashSet is a subset of another HashSet. + * Checks whether a HashSet is a subset of another HashSet. + * + * **Example** (Checking subset relationships) * - * @example * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const small = HashSet.make("a", "b") * const large = HashSet.make("a", "b", "c", "d") @@ -757,8 +799,8 @@ export const isSubset: { * console.log(HashSet.isSubset(small, small)) // true * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (self: HashSet, that: HashSet): boolean } = Dual.dual< @@ -769,9 +811,10 @@ export const isSubset: { /** * Maps each value in the HashSet using the provided function. * - * @example + * **Example** (Mapping HashSet values) + * * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const numbers = HashSet.make(1, 2, 3) * const doubled = HashSet.map(numbers, (n) => n * 2) @@ -785,16 +828,17 @@ export const isSubset: { * console.log(Array.from(lengths).sort()) // [5, 6] (apple=5, banana=6, cherry=6) * ``` * - * @since 2.0.0 * @category mapping + * @since 2.0.0 */ export const map: { /** * Maps each value in the HashSet using the provided function. * - * @example + * **Example** (Mapping HashSet values) + * * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const numbers = HashSet.make(1, 2, 3) * const doubled = HashSet.map(numbers, (n) => n * 2) @@ -808,16 +852,17 @@ export const map: { * console.log(Array.from(lengths).sort()) // [5, 6] (apple=5, banana=6, cherry=6) * ``` * - * @since 2.0.0 * @category mapping + * @since 2.0.0 */ (f: (value: V) => U): (self: HashSet) => HashSet /** * Maps each value in the HashSet using the provided function. * - * @example + * **Example** (Mapping HashSet values) + * * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const numbers = HashSet.make(1, 2, 3) * const doubled = HashSet.map(numbers, (n) => n * 2) @@ -831,8 +876,8 @@ export const map: { * console.log(Array.from(lengths).sort()) // [5, 6] (apple=5, banana=6, cherry=6) * ``` * - * @since 2.0.0 * @category mapping + * @since 2.0.0 */ (self: HashSet, f: (value: V) => U): HashSet } = Dual.dual< @@ -843,9 +888,10 @@ export const map: { /** * Filters the HashSet keeping only values that satisfy the predicate. * - * @example + * **Example** (Filtering HashSet values) + * * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const numbers = HashSet.make(1, 2, 3, 4, 5, 6) * const evens = HashSet.filter(numbers, (n) => n % 2 === 0) @@ -854,16 +900,17 @@ export const map: { * console.log(HashSet.size(evens)) // 3 * ``` * - * @since 2.0.0 * @category filtering + * @since 2.0.0 */ export const filter: { /** * Filters the HashSet keeping only values that satisfy the predicate. * - * @example + * **Example** (Filtering HashSet values) + * * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const numbers = HashSet.make(1, 2, 3, 4, 5, 6) * const evens = HashSet.filter(numbers, (n) => n % 2 === 0) @@ -872,16 +919,17 @@ export const filter: { * console.log(HashSet.size(evens)) // 3 * ``` * - * @since 2.0.0 * @category filtering + * @since 2.0.0 */ (refinement: Refinement, U>): (self: HashSet) => HashSet /** * Filters the HashSet keeping only values that satisfy the predicate. * - * @example + * **Example** (Filtering HashSet values) + * * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const numbers = HashSet.make(1, 2, 3, 4, 5, 6) * const evens = HashSet.filter(numbers, (n) => n % 2 === 0) @@ -890,16 +938,17 @@ export const filter: { * console.log(HashSet.size(evens)) // 3 * ``` * - * @since 2.0.0 * @category filtering + * @since 2.0.0 */ (predicate: Predicate>): (self: HashSet) => HashSet /** * Filters the HashSet keeping only values that satisfy the predicate. * - * @example + * **Example** (Filtering HashSet values) + * * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const numbers = HashSet.make(1, 2, 3, 4, 5, 6) * const evens = HashSet.filter(numbers, (n) => n % 2 === 0) @@ -908,16 +957,17 @@ export const filter: { * console.log(HashSet.size(evens)) // 3 * ``` * - * @since 2.0.0 * @category filtering + * @since 2.0.0 */ (self: HashSet, refinement: Refinement): HashSet /** * Filters the HashSet keeping only values that satisfy the predicate. * - * @example + * **Example** (Filtering HashSet values) + * * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const numbers = HashSet.make(1, 2, 3, 4, 5, 6) * const evens = HashSet.filter(numbers, (n) => n % 2 === 0) @@ -926,8 +976,8 @@ export const filter: { * console.log(HashSet.size(evens)) // 3 * ``` * - * @since 2.0.0 * @category filtering + * @since 2.0.0 */ (self: HashSet, predicate: Predicate): HashSet } = Dual.dual< @@ -942,11 +992,12 @@ export const filter: { >(2, internal.filter) /** - * Tests whether at least one value in the HashSet satisfies the predicate. + * Checks whether at least one value in the HashSet satisfies the predicate. + * + * **Example** (Testing whether some values match) * - * @example * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const numbers = HashSet.make(1, 2, 3, 4, 5) * @@ -957,16 +1008,17 @@ export const filter: { * console.log(HashSet.some(empty, (n) => n > 0)) // false * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ export const some: { /** - * Tests whether at least one value in the HashSet satisfies the predicate. + * Checks whether at least one value in the HashSet satisfies the predicate. + * + * **Example** (Testing whether some values match) * - * @example * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const numbers = HashSet.make(1, 2, 3, 4, 5) * @@ -977,16 +1029,17 @@ export const some: { * console.log(HashSet.some(empty, (n) => n > 0)) // false * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (predicate: Predicate): (self: HashSet) => boolean /** - * Tests whether at least one value in the HashSet satisfies the predicate. + * Checks whether at least one value in the HashSet satisfies the predicate. + * + * **Example** (Testing whether some values match) * - * @example * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const numbers = HashSet.make(1, 2, 3, 4, 5) * @@ -997,8 +1050,8 @@ export const some: { * console.log(HashSet.some(empty, (n) => n > 0)) // false * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (self: HashSet, predicate: Predicate): boolean } = Dual.dual< @@ -1007,11 +1060,12 @@ export const some: { >(2, internal.some) /** - * Tests whether all values in the HashSet satisfy the predicate. + * Checks whether all values in the HashSet satisfy the predicate. + * + * **Example** (Testing whether every value matches) * - * @example * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const numbers = HashSet.make(2, 4, 6, 8) * @@ -1022,16 +1076,17 @@ export const some: { * console.log(HashSet.every(empty, (n) => n > 0)) // true (vacuously true) * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ export const every: { /** - * Tests whether all values in the HashSet satisfy the predicate. + * Checks whether all values in the HashSet satisfy the predicate. + * + * **Example** (Testing whether every value matches) * - * @example * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const numbers = HashSet.make(2, 4, 6, 8) * @@ -1042,16 +1097,17 @@ export const every: { * console.log(HashSet.every(empty, (n) => n > 0)) // true (vacuously true) * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (predicate: Predicate): (self: HashSet) => boolean /** - * Tests whether all values in the HashSet satisfy the predicate. + * Checks whether all values in the HashSet satisfy the predicate. + * + * **Example** (Testing whether every value matches) * - * @example * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const numbers = HashSet.make(2, 4, 6, 8) * @@ -1062,8 +1118,8 @@ export const every: { * console.log(HashSet.every(empty, (n) => n > 0)) // true (vacuously true) * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (self: HashSet, predicate: Predicate): boolean } = Dual.dual< @@ -1074,9 +1130,10 @@ export const every: { /** * Reduces the HashSet to a single value by iterating through the values and applying an accumulator function. * - * @example + * **Example** (Reducing HashSet values) + * * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const numbers = HashSet.make(1, 2, 3, 4, 5) * const sum = HashSet.reduce(numbers, 0, (acc, n) => acc + n) @@ -1088,16 +1145,17 @@ export const every: { * console.log(concatenated) // Order may vary: "abc", "bac", etc. * ``` * - * @since 2.0.0 * @category folding + * @since 2.0.0 */ export const reduce: { /** * Reduces the HashSet to a single value by iterating through the values and applying an accumulator function. * - * @example + * **Example** (Reducing HashSet values) + * * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const numbers = HashSet.make(1, 2, 3, 4, 5) * const sum = HashSet.reduce(numbers, 0, (acc, n) => acc + n) @@ -1109,16 +1167,17 @@ export const reduce: { * console.log(concatenated) // Order may vary: "abc", "bac", etc. * ``` * - * @since 2.0.0 * @category folding + * @since 2.0.0 */ (zero: U, f: (accumulator: U, value: V) => U): (self: HashSet) => U /** * Reduces the HashSet to a single value by iterating through the values and applying an accumulator function. * - * @example + * **Example** (Reducing HashSet values) + * * ```ts - * import * as HashSet from "effect/HashSet" + * import { HashSet } from "effect" * * const numbers = HashSet.make(1, 2, 3, 4, 5) * const sum = HashSet.reduce(numbers, 0, (acc, n) => acc + n) @@ -1130,8 +1189,8 @@ export const reduce: { * console.log(concatenated) // Order may vary: "abc", "bac", etc. * ``` * - * @since 2.0.0 * @category folding + * @since 2.0.0 */ (self: HashSet, zero: U, f: (accumulator: U, value: V) => U): U } = Dual.dual< diff --git a/.opencode/node_modules/effect/src/Inspectable.ts b/.opencode/node_modules/effect/src/Inspectable.ts index ba5cef5f1fa9520d47047f52c9411775bdf625c2..05fed12bff79b9cd9a5c7ede218c249b75e8e9ee 100644 --- a/.opencode/node_modules/effect/src/Inspectable.ts +++ b/.opencode/node_modules/effect/src/Inspectable.ts @@ -1,39 +1,11 @@ /** - * This module provides utilities for making values inspectable and debuggable in TypeScript. + * Controls how values appear in logs and debugging output. * - * The Inspectable interface provides a standard way to implement custom string representations - * for objects, making them easier to debug and inspect. It includes support for JSON - * serialization, Node.js inspection, and safe circular reference handling. - * - * The module also includes redaction capabilities for sensitive data, allowing objects - * to provide different representations based on the current execution context. - * - * @example - * ```ts - * import { Inspectable } from "effect" - * import { format } from "effect/Formatter" - * - * class User extends Inspectable.Class { - * constructor( - * public readonly name: string, - * public readonly email: string - * ) { - * super() - * } - * - * toJSON() { - * return { - * _tag: "User", - * name: this.name, - * email: this.email - * } - * } - * } - * - * const user = new User("Alice", "alice@example.com") - * console.log(user.toString()) // Pretty printed JSON - * console.log(format(user)) // Same as toString() - * ``` + * Effect data types use `Inspectable` to provide stable string, JSON, and + * Node.js inspection output. This keeps custom values readable in logs, REPLs, + * test failures, and diagnostics. This module defines the Node inspect symbol, + * the `Inspectable` interface, safe conversion helpers, and shared prototype or + * class implementations for custom values. * * @since 2.0.0 */ @@ -42,13 +14,20 @@ import * as Predicate from "./Predicate.ts" import { redact } from "./Redactable.ts" /** - * Symbol used by Node.js for custom object inspection. + * Defines the symbol used by Node.js for custom object inspection. + * + * **When to use** + * + * Use to implement Node.js custom inspection for a value. + * + * **Details** * * This symbol is recognized by Node.js's `util.inspect()` function and the REPL * for custom object representation. When an object has a method with this symbol, * it will be called to determine how the object should be displayed. * - * @example + * **Example** (Defining custom Node inspection) + * * ```ts * import { Inspectable } from "effect" * @@ -64,8 +43,8 @@ import { redact } from "./Redactable.ts" * console.log(obj) // Displays: CustomObject(hello) * ``` * - * @since 2.0.0 * @category symbols + * @since 2.0.0 */ export const NodeInspectSymbol = Symbol.for("nodejs.util.inspect.custom") @@ -74,7 +53,12 @@ export const NodeInspectSymbol = Symbol.for("nodejs.util.inspect.custom") * This symbol type is used to implement custom inspection behavior in Node.js * environments. * - * @example + * **When to use** + * + * Use to type methods keyed by the Node.js custom inspection symbol. + * + * **Example** (Typing custom Node inspection) + * * ```ts * import { Inspectable } from "effect" * @@ -90,22 +74,28 @@ export const NodeInspectSymbol = Symbol.for("nodejs.util.inspect.custom") * console.log(obj) // CustomObject(test) * ``` * - * @since 2.0.0 * @category symbols + * @since 2.0.0 */ export type NodeInspectSymbol = typeof NodeInspectSymbol /** * Interface for objects that can be inspected and provide custom string representations. * + * **When to use** + * + * Use to define values with custom string, JSON, and Node.js inspection output. + * + * **Details** + * * Objects implementing this interface can control how they appear in debugging contexts, * JSON serialization, and Node.js inspection. This is particularly useful for creating * custom data types that display meaningful information during development. * - * @example + * **Example** (Implementing inspectable objects) + * * ```ts - * import { Inspectable } from "effect" - * import { format } from "effect/Formatter" + * import { Formatter, Inspectable } from "effect" * * class Result implements Inspectable.Inspectable { * constructor( @@ -114,7 +104,7 @@ export type NodeInspectSymbol = typeof NodeInspectSymbol * ) {} * * toString(): string { - * return format(this.toJSON()) + * return Formatter.format(this.toJSON()) * } * * toJSON() { @@ -130,8 +120,8 @@ export type NodeInspectSymbol = typeof NodeInspectSymbol * console.log(success.toString()) // Pretty formatted JSON * ``` * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface Inspectable { toString(): string @@ -140,15 +130,24 @@ export interface Inspectable { } /** - * Safely converts a value to a JSON-serializable representation, useful for - * implementing the `toJSON` method of the {@link Inspectable} interface. + * Converts a value to a JSON-serializable representation safely. + * + * **When to use** + * + * Use when you need a safe, JSON-serializable representation of a value + * without risking unhandled errors. + * + * **Details** * * This function attempts to extract JSON data from objects that implement the * `toJSON` method, recursively processes arrays, and handles errors gracefully. * For objects that don't have a `toJSON` method, it applies redaction to * protect sensitive information. * - * @since 2.0.0 + * @see {@link toStringUnknown} for converting unknown values to strings + * + * @category converting + * @since 4.0.0 */ export const toJson = (input: unknown): unknown => { try { @@ -168,6 +167,19 @@ export const toJson = (input: unknown): unknown => { } /** + * Converts an unknown value to a string for diagnostics. + * + * **When to use** + * + * Use to produce a diagnostic string from a value whose runtime type is unknown. + * + * **Details** + * + * Strings are returned unchanged. Objects are formatted as JSON using the + * provided whitespace setting when possible, and values that cannot be + * formatted are converted with `String`. + * + * @category converting * @since 2.0.0 */ export const toStringUnknown = (u: unknown, whitespace: number | string | undefined = 2): string => { @@ -184,11 +196,18 @@ export const toStringUnknown = (u: unknown, whitespace: number | string | undefi /** * A base prototype object that implements the {@link Inspectable} interface. * + * **When to use** + * + * Use as a prototype for plain objects that should share standard inspectable behavior. + * + * **Details** + * * This object provides default implementations for the {@link Inspectable} methods. * It can be used as a prototype for objects that want to be inspectable, * or as a mixin to add inspection capabilities to existing objects. * - * @example + * **Example** (Using the base inspectable prototype) + * * ```ts * import { Inspectable } from "effect" * @@ -207,6 +226,7 @@ export const toStringUnknown = (u: unknown, whitespace: number | string | undefi * MyClass.prototype.constructor = MyClass * ``` * + * @category prototypes * @since 2.0.0 */ export const BaseProto: Inspectable = { @@ -222,13 +242,20 @@ export const BaseProto: Inspectable = { } /** - * Abstract base class that implements the Inspectable interface. + * Provides an abstract base class that implements the Inspectable interface. + * + * **When to use** + * + * Use as a base class for inspectable objects that define their own JSON representation. + * + * **Details** * * This class provides a convenient way to create inspectable objects by extending it. * Subclasses only need to implement the `toJSON()` method, and they automatically * get proper `toString()` and Node.js inspection support. * - * @example + * **Example** (Extending the inspectable base class) + * * ```ts * import { Inspectable } from "effect" * @@ -256,13 +283,19 @@ export const BaseProto: Inspectable = { * console.log(user) // In Node.js, shows the same formatted output * ``` * - * @since 2.0.0 * @category classes + * @since 2.0.0 */ export abstract class Class { /** * Returns a JSON representation of this object. * + * **When to use** + * + * Use to provide the JSON representation consumed by inherited inspection methods. + * + * **Details** + * * Subclasses must implement this method to define how the object * should be serialized for debugging and inspection purposes. * @@ -272,6 +305,10 @@ export abstract class Class { /** * Node.js custom inspection method. * + * **When to use** + * + * Use to expose the class JSON representation to Node.js inspection. + * * @since 2.0.0 */ [NodeInspectSymbol]() { @@ -280,6 +317,10 @@ export abstract class Class { /** * Returns a formatted string representation of this object. * + * **When to use** + * + * Use to format the class JSON representation as a string. + * * @since 2.0.0 */ toString() { diff --git a/.opencode/node_modules/effect/src/Iterable.ts b/.opencode/node_modules/effect/src/Iterable.ts index 119fb33eddca7d5f867b000fa6a782a7639c5096..e30935076d8c90122803ead1c7dfceaf80b0aa76 100644 --- a/.opencode/node_modules/effect/src/Iterable.ts +++ b/.opencode/node_modules/effect/src/Iterable.ts @@ -1,31 +1,10 @@ /** - * This module provides utility functions for working with Iterables in TypeScript. + * Works with JavaScript values that implement `[Symbol.iterator]`. * - * Iterables are objects that implement the iterator protocol, allowing them to be - * consumed with `for...of` loops, spread syntax, and other iteration constructs. - * This module provides a comprehensive set of functions for creating, transforming, - * and working with iterables in a functional programming style. - * - * Unlike arrays, iterables can be lazy and potentially infinite, making them suitable - * for stream processing and memory-efficient data manipulation. All functions in this - * module preserve the lazy nature of iterables where possible. - * - * @example - * ```ts - * import { Iterable, Option } from "effect" - * - * // Create iterables - * const numbers = Iterable.range(1, 5) - * const doubled = Iterable.map(numbers, (x) => x * 2) - * const filtered = Iterable.filter(doubled, (x) => x > 5) - * - * console.log(Array.from(filtered)) // [6, 8, 10] - * - * // Infinite iterables - * const fibonacci = Iterable.unfold([0, 1], ([a, b]) => Option.some([a, [b, a + b]])) - * const first10 = Iterable.take(fibonacci, 10) - * console.log(Array.from(first10)) // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] - * ``` + * Iterables include arrays, strings, generators, sets, and custom lazy + * sequences. The helpers in this module let code transform, search, group, and + * fold iterable values while preserving the input as an iterable instead of + * forcing an array first. * * @since 2.0.0 */ @@ -45,14 +24,14 @@ import type { NoInfer } from "./Types.ts" /** * Creates an iterable by applying a function to consecutive integers. * - * This is a fundamental constructor that generates iterables by calling a function - * with each index starting from 0. If no length is specified, the iterable will - * be infinite. This is useful for generating sequences, patterns, or any indexed data. + * **Details** + * + * The function is called with each index starting from `0`. If no length is + * specified, the iterable is infinite. This is useful for generating + * sequences, patterns, or any indexed data. * - * @param f - Function that receives the index and returns the element - * @param options - Configuration object with optional length + * **Example** (Generating values by index) * - * @example * ```ts * import { Iterable } from "effect" * @@ -93,16 +72,21 @@ export const makeBy = (f: (i: number) => A, options?: { } /** - * Return a `Iterable` containing a range of integers, including both endpoints. + * Returns an iterable of integers starting at `start` and increasing by `1`. * - * If `end` is omitted, the range will not have an upper bound. + * **Details** + * + * When `end` is provided and `start <= end`, both endpoints are included. When + * `end` is omitted, the iterable is unbounded. When `start > end`, the + * iterable contains only `start`. + * + * **Example** (Creating a range) * - * @example * ```ts - * import { range } from "effect/Iterable" + * import { Iterable } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(Array.from(range(1, 3)), [1, 2, 3]) + * assert.deepStrictEqual(Array.from(Iterable.range(1, 3)), [1, 2, 3]) * ``` * * @category constructors @@ -118,16 +102,19 @@ export const range = (start: number, end?: number): Iterable => { } /** - * Return a `Iterable` containing a value repeated the specified number of times. + * Returns a `Iterable` containing a value repeated the specified number of times. + * + * **Details** + * + * `n` is normalized to an integer greater than or equal to `1`. * - * **Note**. `n` is normalized to an integer >= 1. + * **Example** (Repeating a value) * - * @example * ```ts - * import { replicate } from "effect/Iterable" + * import { Iterable } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(Array.from(replicate("a", 3)), ["a", "a", "a"]) + * assert.deepStrictEqual(Array.from(Iterable.replicate("a", 3)), ["a", "a", "a"]) * ``` * * @category constructors @@ -135,16 +122,19 @@ export const range = (start: number, end?: number): Iterable => { */ export const replicate: { /** - * Return a `Iterable` containing a value repeated the specified number of times. + * Returns a `Iterable` containing a value repeated the specified number of times. + * + * **Details** * - * **Note**. `n` is normalized to an integer >= 1. + * `n` is normalized to an integer greater than or equal to `1`. + * + * **Example** (Repeating a value) * - * @example * ```ts - * import { replicate } from "effect/Iterable" + * import { Iterable } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(Array.from(replicate("a", 3)), ["a", "a", "a"]) + * assert.deepStrictEqual(Array.from(Iterable.replicate("a", 3)), ["a", "a", "a"]) * ``` * * @category constructors @@ -152,16 +142,19 @@ export const replicate: { */ (n: number): (a: A) => Iterable /** - * Return a `Iterable` containing a value repeated the specified number of times. + * Returns a `Iterable` containing a value repeated the specified number of times. * - * **Note**. `n` is normalized to an integer >= 1. + * **Details** + * + * `n` is normalized to an integer greater than or equal to `1`. + * + * **Example** (Repeating a value) * - * @example * ```ts - * import { replicate } from "effect/Iterable" + * import { Iterable } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(Array.from(replicate("a", 3)), ["a", "a", "a"]) + * assert.deepStrictEqual(Array.from(Iterable.replicate("a", 3)), ["a", "a", "a"]) * ``` * * @category constructors @@ -171,16 +164,55 @@ export const replicate: { } = dual(2, (a: A, n: number): Iterable => makeBy(() => a, { length: n })) /** + * Repeats an iterable `n` times, yielding the full contents of `self` for each + * repetition. + * + * **When to use** + * + * Use to repeat an iterable's contents a specific number of times. + * + * **Details** + * + * The result is lazy. Each repetition obtains a new iterator from `self`. + * + * @see {@link forever} for repeating without an upper bound + * @see {@link replicate} for repeating a single value * @category constructors * @since 4.0.0 */ export const repeat: { /** + * Repeats an iterable `n` times, yielding the full contents of `self` for each + * repetition. + * + * **When to use** + * + * Use to repeat an iterable's contents a specific number of times. + * + * **Details** + * + * The result is lazy. Each repetition obtains a new iterator from `self`. + * + * @see {@link forever} for repeating without an upper bound + * @see {@link replicate} for repeating a single value * @category constructors * @since 4.0.0 */ (n: number): (self: Iterable) => Iterable /** + * Repeats an iterable `n` times, yielding the full contents of `self` for each + * repetition. + * + * **When to use** + * + * Use to repeat an iterable's contents a specific number of times. + * + * **Details** + * + * The result is lazy. Each repetition obtains a new iterator from `self`. + * + * @see {@link forever} for repeating without an upper bound + * @see {@link replicate} for repeating a single value * @category constructors * @since 4.0.0 */ @@ -188,6 +220,21 @@ export const repeat: { } = dual(2, (self: Iterable, n: number): Iterable => flatten(makeBy(() => self, { length: n }))) /** + * Repeats an iterable without an upper bound. + * + * **When to use** + * + * Use to cycle a reusable iterable without an upper bound when a downstream + * consumer controls how many values are taken. + * + * **Gotchas** + * + * The returned iterable is lazy and should usually be bounded with `take` or + * another terminating consumer before materializing it. + * + * @see {@link repeat} for repeating an iterable a specific number of times + * @see {@link take} for bounding the unbounded result before materializing it + * * @category constructors * @since 4.0.0 */ @@ -196,19 +243,20 @@ export const forever = (self: Iterable): Iterable => repeat(self, Infin /** * Takes a record and returns an Iterable of tuples containing its keys and values. * - * @example + * **Example** (Converting a record to entries) + * * ```ts - * import { fromRecord } from "effect/Iterable" + * import { Iterable } from "effect" * import * as assert from "node:assert" * * const x = { a: 1, b: 2, c: 3 } - * assert.deepStrictEqual(Array.from(fromRecord(x)), [["a", 1], ["b", 2], [ + * assert.deepStrictEqual(Array.from(Iterable.fromRecord(x)), [["a", 1], ["b", 2], [ * "c", * 3 * ]]) * ``` * - * @category conversions + * @category converting * @since 2.0.0 */ export const fromRecord = (self: Readonly>): Iterable<[K, A]> => ({ @@ -222,9 +270,10 @@ export const fromRecord = (self: Readonly>): I }) /** - * Prepend an element to the front of an `Iterable`, creating a new `Iterable`. + * Prepends an element to the front of an `Iterable`, creating a new `Iterable`. + * + * **Example** (Prepending an element) * - * @example * ```ts * import { Iterable } from "effect" * @@ -238,14 +287,15 @@ export const fromRecord = (self: Readonly>): I * console.log(Array.from(withZ)) // ["z", "a", "b", "c"] * ``` * - * @category concatenating + * @category combining * @since 2.0.0 */ export const prepend: { /** - * Prepend an element to the front of an `Iterable`, creating a new `Iterable`. + * Prepends an element to the front of an `Iterable`, creating a new `Iterable`. + * + * **Example** (Prepending an element) * - * @example * ```ts * import { Iterable } from "effect" * @@ -259,14 +309,15 @@ export const prepend: { * console.log(Array.from(withZ)) // ["z", "a", "b", "c"] * ``` * - * @category concatenating + * @category combining * @since 2.0.0 */ (head: B): (self: Iterable) => Iterable /** - * Prepend an element to the front of an `Iterable`, creating a new `Iterable`. + * Prepends an element to the front of an `Iterable`, creating a new `Iterable`. + * + * **Example** (Prepending an element) * - * @example * ```ts * import { Iterable } from "effect" * @@ -280,7 +331,7 @@ export const prepend: { * console.log(Array.from(withZ)) // ["z", "a", "b", "c"] * ``` * - * @category concatenating + * @category combining * @since 2.0.0 */ (self: Iterable, head: B): Iterable @@ -289,7 +340,8 @@ export const prepend: { /** * Prepends the specified prefix iterable to the beginning of the specified iterable. * - * @example + * **Example** (Prepending another iterable) + * * ```ts * import { Iterable } from "effect" * import * as assert from "node:assert" @@ -300,14 +352,15 @@ export const prepend: { * ) * ``` * - * @category concatenating + * @category combining * @since 2.0.0 */ export const prependAll: { /** * Prepends the specified prefix iterable to the beginning of the specified iterable. * - * @example + * **Example** (Prepending another iterable) + * * ```ts * import { Iterable } from "effect" * import * as assert from "node:assert" @@ -318,14 +371,15 @@ export const prependAll: { * ) * ``` * - * @category concatenating + * @category combining * @since 2.0.0 */ (that: Iterable): (self: Iterable) => Iterable /** * Prepends the specified prefix iterable to the beginning of the specified iterable. * - * @example + * **Example** (Prepending another iterable) + * * ```ts * import { Iterable } from "effect" * import * as assert from "node:assert" @@ -336,7 +390,7 @@ export const prependAll: { * ) * ``` * - * @category concatenating + * @category combining * @since 2.0.0 */ (self: Iterable, that: Iterable): Iterable @@ -346,9 +400,25 @@ export const prependAll: { ) /** - * Append an element to the end of an `Iterable`, creating a new `Iterable`. + * Appends an element to the end of an `Iterable`, creating a new `Iterable`. + * + * **When to use** + * + * Use to add one element after all elements of an iterable while keeping the + * result as a lazy `Iterable`. + * + * **Details** + * + * The result yields every element from `self` first, then yields `last` after + * `self` is exhausted. + * + * **Gotchas** + * + * If `self` is infinite or never completes, the appended element is never + * reached. + * + * **Example** (Appending an element) * - * @example * ```ts * import { Iterable } from "effect" * @@ -364,14 +434,33 @@ export const prependAll: { * console.log(Array.from(result)) // [1, 2, 3, 4] * ``` * - * @category concatenating + * @see {@link prepend} for adding one element before the existing elements + * @see {@link appendAll} for appending all elements from another iterable + * + * @category combining * @since 2.0.0 */ export const append: { /** - * Append an element to the end of an `Iterable`, creating a new `Iterable`. + * Appends an element to the end of an `Iterable`, creating a new `Iterable`. + * + * **When to use** + * + * Use to add one element after all elements of an iterable while keeping the + * result as a lazy `Iterable`. + * + * **Details** + * + * The result yields every element from `self` first, then yields `last` after + * `self` is exhausted. + * + * **Gotchas** + * + * If `self` is infinite or never completes, the appended element is never + * reached. + * + * **Example** (Appending an element) * - * @example * ```ts * import { Iterable } from "effect" * @@ -387,14 +476,33 @@ export const append: { * console.log(Array.from(result)) // [1, 2, 3, 4] * ``` * - * @category concatenating + * @see {@link prepend} for adding one element before the existing elements + * @see {@link appendAll} for appending all elements from another iterable + * + * @category combining * @since 2.0.0 */ (last: B): (self: Iterable) => Iterable /** - * Append an element to the end of an `Iterable`, creating a new `Iterable`. + * Appends an element to the end of an `Iterable`, creating a new `Iterable`. + * + * **When to use** + * + * Use to add one element after all elements of an iterable while keeping the + * result as a lazy `Iterable`. + * + * **Details** + * + * The result yields every element from `self` first, then yields `last` after + * `self` is exhausted. + * + * **Gotchas** + * + * If `self` is infinite or never completes, the appended element is never + * reached. + * + * **Example** (Appending an element) * - * @example * ```ts * import { Iterable } from "effect" * @@ -410,7 +518,10 @@ export const append: { * console.log(Array.from(result)) // [1, 2, 3, 4] * ``` * - * @category concatenating + * @see {@link prepend} for adding one element before the existing elements + * @see {@link appendAll} for appending all elements from another iterable + * + * @category combining * @since 2.0.0 */ (self: Iterable, last: B): Iterable @@ -419,7 +530,22 @@ export const append: { /** * Concatenates two iterables, combining their elements. * - * @example + * **When to use** + * + * Use to lazily concatenate two iterables while preserving order, yielding all + * elements from `self` before `that`. + * + * **Details** + * + * The result is lazy. The iterator for `that` is not created or read until + * `self` is exhausted. + * + * **Gotchas** + * + * If `self` is infinite or never completes, `that` is never reached. + * + * **Example** (Concatenating iterables) + * * ```ts * import { Iterable } from "effect" * @@ -441,14 +567,32 @@ export const append: { * console.log(Array.from(result)) // [0, -1, -2, 1, 2] * ``` * - * @category concatenating + * @see {@link append} for appending one value instead of another iterable + * @see {@link prependAll} for yielding another iterable before `self` + * + * @category combining * @since 2.0.0 */ export const appendAll: { /** * Concatenates two iterables, combining their elements. * - * @example + * **When to use** + * + * Use to lazily concatenate two iterables while preserving order, yielding all + * elements from `self` before `that`. + * + * **Details** + * + * The result is lazy. The iterator for `that` is not created or read until + * `self` is exhausted. + * + * **Gotchas** + * + * If `self` is infinite or never completes, `that` is never reached. + * + * **Example** (Concatenating iterables) + * * ```ts * import { Iterable } from "effect" * @@ -470,14 +614,32 @@ export const appendAll: { * console.log(Array.from(result)) // [0, -1, -2, 1, 2] * ``` * - * @category concatenating + * @see {@link append} for appending one value instead of another iterable + * @see {@link prependAll} for yielding another iterable before `self` + * + * @category combining * @since 2.0.0 */ (that: Iterable): (self: Iterable) => Iterable /** * Concatenates two iterables, combining their elements. * - * @example + * **When to use** + * + * Use to lazily concatenate two iterables while preserving order, yielding all + * elements from `self` before `that`. + * + * **Details** + * + * The result is lazy. The iterator for `that` is not created or read until + * `self` is exhausted. + * + * **Gotchas** + * + * If `self` is infinite or never completes, `that` is never reached. + * + * **Example** (Concatenating iterables) + * * ```ts * import { Iterable } from "effect" * @@ -499,7 +661,10 @@ export const appendAll: { * console.log(Array.from(result)) // [0, -1, -2, 1, 2] * ``` * - * @category concatenating + * @see {@link append} for appending one value instead of another iterable + * @see {@link prependAll} for yielding another iterable before `self` + * + * @category combining * @since 2.0.0 */ (self: Iterable, that: Iterable): Iterable @@ -529,9 +694,10 @@ export const appendAll: { ) /** - * Reduce an `Iterable` from the left, keeping all intermediate results instead of only the final result. + * Reduces an `Iterable` from the left, keeping all intermediate results instead of only the final result. + * + * **Example** (Tracking running results) * - * @example * ```ts * import { Iterable } from "effect" * @@ -556,9 +722,10 @@ export const appendAll: { */ export const scan: { /** - * Reduce an `Iterable` from the left, keeping all intermediate results instead of only the final result. + * Reduces an `Iterable` from the left, keeping all intermediate results instead of only the final result. + * + * **Example** (Tracking running results) * - * @example * ```ts * import { Iterable } from "effect" * @@ -583,9 +750,10 @@ export const scan: { */ (b: B, f: (b: B, a: A) => B): (self: Iterable) => Iterable /** - * Reduce an `Iterable` from the left, keeping all intermediate results instead of only the final result. + * Reduces an `Iterable` from the left, keeping all intermediate results instead of only the final result. + * + * **Example** (Tracking running results) * - * @example * ```ts * import { Iterable } from "effect" * @@ -630,15 +798,16 @@ export const scan: { })) /** - * Determine if an `Iterable` is empty + * Checks whether an `Iterable` is empty. + * + * **Example** (Checking for emptiness) * - * @example * ```ts - * import { isEmpty } from "effect/Iterable" + * import { Iterable } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(isEmpty([]), true) - * assert.deepStrictEqual(isEmpty([1, 2, 3]), false) + * assert.deepStrictEqual(Iterable.isEmpty([]), true) + * assert.deepStrictEqual(Iterable.isEmpty([1, 2, 3]), false) * ``` * * @category guards @@ -650,9 +819,10 @@ export const isEmpty = (self: Iterable): self is Iterable => { } /** - * Return the number of elements in a `Iterable`. + * Returns the number of elements in a `Iterable`. + * + * **Example** (Counting iterable elements) * - * @example * ```ts * import { Iterable } from "effect" * @@ -684,12 +854,12 @@ export const size = (self: Iterable): number => { } /** - * Get the first element of a `Iterable`, or `None` if the `Iterable` is empty. + * Gets the first element of a `Iterable` safely, or `None` if the `Iterable` is empty. + * + * **Example** (Getting the first element) * - * @example * ```ts - * import { Iterable } from "effect" - * import * as Option from "effect/Option" + * import { Iterable, Option } from "effect" * * const numbers = [1, 2, 3] * console.log(Iterable.head(numbers)) // Option.some(1) @@ -718,9 +888,19 @@ export const head = (self: Iterable): Option => { } /** - * Get the first element of a `Iterable`, or throw an error if the `Iterable` is empty. + * Gets the first element of an `Iterable` without returning an `Option`. + * + * **When to use** + * + * Use when the `Iterable` is known to be non-empty and direct access to the + * first element is preferred over handling `Option.none`. + * + * **Gotchas** + * + * Throws if the `Iterable` is empty. + * + * **Example** (Getting the first element unsafely) * - * @example * ```ts * import { Iterable } from "effect" * @@ -730,13 +910,8 @@ export const head = (self: Iterable): Option => { * const letters = "hello" * console.log(Iterable.headUnsafe(letters)) // "h" * - * // This will throw an error! - * try { - * const empty = Iterable.empty() - * Iterable.headUnsafe(empty) // throws Error: "headUnsafe: empty iterable" - * } catch (error) { - * console.log((error as Error).message) // "headUnsafe: empty iterable" - * } + * // Iterable.headUnsafe(Iterable.empty()) + * // throws Error: "headUnsafe: empty iterable" * * // Use only when you're certain the iterable is non-empty * const nonEmpty = Iterable.range(1, 10) @@ -744,7 +919,7 @@ export const head = (self: Iterable): Option => { * ``` * * @category getters - * @since 3.3.0 + * @since 4.0.0 */ export const headUnsafe = (self: Iterable): A => { const iterator = self[Symbol.iterator]() @@ -754,11 +929,14 @@ export const headUnsafe = (self: Iterable): A => { } /** - * Keep only a max number of elements from the start of an `Iterable`, creating a new `Iterable`. + * Keeps only a max number of elements from the start of an `Iterable`, creating a new `Iterable`. * - * **Note**. `n` is normalized to a non negative integer. + * **Details** + * + * `n` is normalized to a non-negative integer. + * + * **Example** (Taking from the start) * - * @example * ```ts * import { Iterable } from "effect" * @@ -785,11 +963,14 @@ export const headUnsafe = (self: Iterable): A => { */ export const take: { /** - * Keep only a max number of elements from the start of an `Iterable`, creating a new `Iterable`. + * Keeps only a max number of elements from the start of an `Iterable`, creating a new `Iterable`. + * + * **Details** + * + * `n` is normalized to a non-negative integer. * - * **Note**. `n` is normalized to a non negative integer. + * **Example** (Taking from the start) * - * @example * ```ts * import { Iterable } from "effect" * @@ -816,11 +997,14 @@ export const take: { */ (n: number): (self: Iterable) => Iterable /** - * Keep only a max number of elements from the start of an `Iterable`, creating a new `Iterable`. + * Keeps only a max number of elements from the start of an `Iterable`, creating a new `Iterable`. * - * **Note**. `n` is normalized to a non negative integer. + * **Details** + * + * `n` is normalized to a non-negative integer. + * + * **Example** (Taking from the start) * - * @example * ```ts * import { Iterable } from "effect" * @@ -863,9 +1047,11 @@ export const take: { })) /** - * Calculate the longest initial Iterable for which all element satisfy the specified predicate, creating a new `Iterable`. + * Takes the longest initial `Iterable` prefix for which all elements satisfy the + * specified predicate. + * + * **Example** (Taking while a predicate holds) * - * @example * ```ts * import { Iterable } from "effect" * @@ -897,9 +1083,11 @@ export const take: { */ export const takeWhile: { /** - * Calculate the longest initial Iterable for which all element satisfy the specified predicate, creating a new `Iterable`. + * Takes the longest initial `Iterable` prefix for which all elements satisfy the + * specified predicate. + * + * **Example** (Taking while a predicate holds) * - * @example * ```ts * import { Iterable } from "effect" * @@ -931,9 +1119,11 @@ export const takeWhile: { */ (refinement: (a: NoInfer, i: number) => a is B): (self: Iterable) => Iterable /** - * Calculate the longest initial Iterable for which all element satisfy the specified predicate, creating a new `Iterable`. + * Takes the longest initial `Iterable` prefix for which all elements satisfy the + * specified predicate. + * + * **Example** (Taking while a predicate holds) * - * @example * ```ts * import { Iterable } from "effect" * @@ -965,9 +1155,11 @@ export const takeWhile: { */ (predicate: (a: NoInfer, i: number) => boolean): (self: Iterable) => Iterable /** - * Calculate the longest initial Iterable for which all element satisfy the specified predicate, creating a new `Iterable`. + * Takes the longest initial `Iterable` prefix for which all elements satisfy the + * specified predicate. + * + * **Example** (Taking while a predicate holds) * - * @example * ```ts * import { Iterable } from "effect" * @@ -999,9 +1191,11 @@ export const takeWhile: { */ (self: Iterable, refinement: (a: A, i: number) => a is B): Iterable /** - * Calculate the longest initial Iterable for which all element satisfy the specified predicate, creating a new `Iterable`. + * Takes the longest initial `Iterable` prefix for which all elements satisfy the + * specified predicate. + * + * **Example** (Taking while a predicate holds) * - * @example * ```ts * import { Iterable } from "effect" * @@ -1049,11 +1243,14 @@ export const takeWhile: { })) /** - * Drop a max number of elements from the start of an `Iterable` + * Drops a max number of elements from the start of an `Iterable` + * + * **Details** + * + * `n` is normalized to a non-negative integer. * - * **Note**. `n` is normalized to a non negative integer. + * **Example** (Dropping from the start) * - * @example * ```ts * import { Iterable } from "effect" * @@ -1079,11 +1276,14 @@ export const takeWhile: { */ export const drop: { /** - * Drop a max number of elements from the start of an `Iterable` + * Drops a max number of elements from the start of an `Iterable` * - * **Note**. `n` is normalized to a non negative integer. + * **Details** + * + * `n` is normalized to a non-negative integer. + * + * **Example** (Dropping from the start) * - * @example * ```ts * import { Iterable } from "effect" * @@ -1109,11 +1309,14 @@ export const drop: { */ (n: number): (self: Iterable) => Iterable /** - * Drop a max number of elements from the start of an `Iterable` + * Drops a max number of elements from the start of an `Iterable` + * + * **Details** * - * **Note**. `n` is normalized to a non negative integer. + * `n` is normalized to a non-negative integer. + * + * **Example** (Dropping from the start) * - * @example * ```ts * import { Iterable } from "effect" * @@ -1161,10 +1364,10 @@ export const drop: { * Returns the first element that satisfies the specified * predicate, or `None` if no such element exists. * - * @example + * **Example** (Finding the first match) + * * ```ts - * import { Iterable } from "effect" - * import * as Option from "effect/Option" + * import { Iterable, Option } from "effect" * * const numbers = [1, 3, 4, 6, 8] * const firstEven = Iterable.findFirst(numbers, (x) => x % 2 === 0) @@ -1202,10 +1405,10 @@ export const findFirst: { * Returns the first element that satisfies the specified * predicate, or `None` if no such element exists. * - * @example + * **Example** (Finding the first match) + * * ```ts - * import { Iterable } from "effect" - * import * as Option from "effect/Option" + * import { Iterable, Option } from "effect" * * const numbers = [1, 3, 4, 6, 8] * const firstEven = Iterable.findFirst(numbers, (x) => x % 2 === 0) @@ -1243,10 +1446,10 @@ export const findFirst: { * Returns the first element that satisfies the specified * predicate, or `None` if no such element exists. * - * @example + * **Example** (Finding the first match) + * * ```ts - * import { Iterable } from "effect" - * import * as Option from "effect/Option" + * import { Iterable, Option } from "effect" * * const numbers = [1, 3, 4, 6, 8] * const firstEven = Iterable.findFirst(numbers, (x) => x % 2 === 0) @@ -1284,10 +1487,10 @@ export const findFirst: { * Returns the first element that satisfies the specified * predicate, or `None` if no such element exists. * - * @example + * **Example** (Finding the first match) + * * ```ts - * import { Iterable } from "effect" - * import * as Option from "effect/Option" + * import { Iterable, Option } from "effect" * * const numbers = [1, 3, 4, 6, 8] * const firstEven = Iterable.findFirst(numbers, (x) => x % 2 === 0) @@ -1325,10 +1528,10 @@ export const findFirst: { * Returns the first element that satisfies the specified * predicate, or `None` if no such element exists. * - * @example + * **Example** (Finding the first match) + * * ```ts - * import { Iterable } from "effect" - * import * as Option from "effect/Option" + * import { Iterable, Option } from "effect" * * const numbers = [1, 3, 4, 6, 8] * const firstEven = Iterable.findFirst(numbers, (x) => x % 2 === 0) @@ -1366,10 +1569,10 @@ export const findFirst: { * Returns the first element that satisfies the specified * predicate, or `None` if no such element exists. * - * @example + * **Example** (Finding the first match) + * * ```ts - * import { Iterable } from "effect" - * import * as Option from "effect/Option" + * import { Iterable, Option } from "effect" * * const numbers = [1, 3, 4, 6, 8] * const firstEven = Iterable.findFirst(numbers, (x) => x % 2 === 0) @@ -1407,10 +1610,10 @@ export const findFirst: { * Returns the first element that satisfies the specified * predicate, or `None` if no such element exists. * - * @example + * **Example** (Finding the first match) + * * ```ts - * import { Iterable } from "effect" - * import * as Option from "effect/Option" + * import { Iterable, Option } from "effect" * * const numbers = [1, 3, 4, 6, 8] * const firstEven = Iterable.findFirst(numbers, (x) => x % 2 === 0) @@ -1466,9 +1669,10 @@ export const findFirst: { ) /** - * Find the last element for which a predicate holds. + * Finds the last element for which a predicate holds. + * + * **Example** (Finding the last match) * - * @example * ```ts * import { Iterable } from "effect" * @@ -1498,9 +1702,10 @@ export const findFirst: { */ export const findLast: { /** - * Find the last element for which a predicate holds. + * Finds the last element for which a predicate holds. + * + * **Example** (Finding the last match) * - * @example * ```ts * import { Iterable } from "effect" * @@ -1530,9 +1735,10 @@ export const findLast: { */ (f: (a: NoInfer, i: number) => Option): (self: Iterable) => Option /** - * Find the last element for which a predicate holds. + * Finds the last element for which a predicate holds. + * + * **Example** (Finding the last match) * - * @example * ```ts * import { Iterable } from "effect" * @@ -1562,9 +1768,10 @@ export const findLast: { */ (refinement: (a: NoInfer, i: number) => a is B): (self: Iterable) => Option /** - * Find the last element for which a predicate holds. + * Finds the last element for which a predicate holds. + * + * **Example** (Finding the last match) * - * @example * ```ts * import { Iterable } from "effect" * @@ -1594,9 +1801,10 @@ export const findLast: { */ (predicate: (a: NoInfer, i: number) => boolean): (self: Iterable) => Option /** - * Find the last element for which a predicate holds. + * Finds the last element for which a predicate holds. + * + * **Example** (Finding the last match) * - * @example * ```ts * import { Iterable } from "effect" * @@ -1626,9 +1834,10 @@ export const findLast: { */ (self: Iterable, f: (a: A, i: number) => Option): Option /** - * Find the last element for which a predicate holds. + * Finds the last element for which a predicate holds. + * + * **Example** (Finding the last match) * - * @example * ```ts * import { Iterable } from "effect" * @@ -1658,9 +1867,10 @@ export const findLast: { */ (self: Iterable, refinement: (a: A, i: number) => a is B): Option /** - * Find the last element for which a predicate holds. + * Finds the last element for which a predicate holds. + * + * **Example** (Finding the last match) * - * @example * ```ts * import { Iterable } from "effect" * @@ -1714,7 +1924,8 @@ export const findLast: { /** * Takes two `Iterable`s and returns an `Iterable` of corresponding pairs. * - * @example + * **Example** (Zipping iterables) + * * ```ts * import { Iterable } from "effect" * @@ -1749,7 +1960,8 @@ export const zip: { /** * Takes two `Iterable`s and returns an `Iterable` of corresponding pairs. * - * @example + * **Example** (Zipping iterables) + * * ```ts * import { Iterable } from "effect" * @@ -1784,7 +1996,8 @@ export const zip: { /** * Takes two `Iterable`s and returns an `Iterable` of corresponding pairs. * - * @example + * **Example** (Zipping iterables) + * * ```ts * import { Iterable } from "effect" * @@ -1822,10 +2035,11 @@ export const zip: { ) /** - * Apply a function to pairs of elements at the same index in two `Iterable`s, collecting the results. If one + * Applies a function to pairs of elements at the same index in two `Iterable`s, collecting the results. If one * input `Iterable` is short, excess elements of the longer `Iterable` are discarded. * - * @example + * **Example** (Zipping with a combining function) + * * ```ts * import { Iterable } from "effect" * @@ -1869,10 +2083,11 @@ export const zip: { */ export const zipWith: { /** - * Apply a function to pairs of elements at the same index in two `Iterable`s, collecting the results. If one + * Applies a function to pairs of elements at the same index in two `Iterable`s, collecting the results. If one * input `Iterable` is short, excess elements of the longer `Iterable` are discarded. * - * @example + * **Example** (Zipping with a combining function) + * * ```ts * import { Iterable } from "effect" * @@ -1916,10 +2131,11 @@ export const zipWith: { */ (that: Iterable, f: (a: A, b: B) => C): (self: Iterable) => Iterable /** - * Apply a function to pairs of elements at the same index in two `Iterable`s, collecting the results. If one + * Applies a function to pairs of elements at the same index in two `Iterable`s, collecting the results. If one * input `Iterable` is short, excess elements of the longer `Iterable` are discarded. * - * @example + * **Example** (Zipping with a combining function) + * * ```ts * import { Iterable } from "effect" * @@ -1980,10 +2196,18 @@ export const zipWith: { })) /** - * Places an element in between members of an `Iterable`. + * Places a separator between members of an `Iterable`. + * + * **When to use** + * + * Use to lazily insert a separator between adjacent values. + * + * **Details** + * * If the input is a non-empty array, the result is also a non-empty array. * - * @example + * **Example** (Interspersing separators) + * * ```ts * import { Iterable } from "effect" * @@ -2013,15 +2237,23 @@ export const zipWith: { * console.log(Array.from(css).join("")) // "color: red; font-size: 14px; margin: 10px" * ``` * - * @category concatenating + * @category combining * @since 2.0.0 */ export const intersperse: { /** - * Places an element in between members of an `Iterable`. + * Places a separator between members of an `Iterable`. + * + * **When to use** + * + * Use to lazily insert a separator between adjacent values. + * + * **Details** + * * If the input is a non-empty array, the result is also a non-empty array. * - * @example + * **Example** (Interspersing separators) + * * ```ts * import { Iterable } from "effect" * @@ -2051,15 +2283,23 @@ export const intersperse: { * console.log(Array.from(css).join("")) // "color: red; font-size: 14px; margin: 10px" * ``` * - * @category concatenating + * @category combining * @since 2.0.0 */ (middle: B): (self: Iterable) => Iterable /** - * Places an element in between members of an `Iterable`. + * Places a separator between members of an `Iterable`. + * + * **When to use** + * + * Use to lazily insert a separator between adjacent values. + * + * **Details** + * * If the input is a non-empty array, the result is also a non-empty array. * - * @example + * **Example** (Interspersing separators) + * * ```ts * import { Iterable } from "effect" * @@ -2089,7 +2329,7 @@ export const intersperse: { * console.log(Array.from(css).join("")) // "color: red; font-size: 14px; margin: 10px" * ``` * - * @category concatenating + * @category combining * @since 2.0.0 */ (self: Iterable, middle: B): Iterable @@ -2118,7 +2358,8 @@ export const intersperse: { /** * Returns a function that checks if an `Iterable` contains a given value using a provided `isEquivalent` function. * - * @example + * **Example** (Checking membership with custom equivalence) + * * ```ts * import { Iterable } from "effect" * @@ -2165,9 +2406,16 @@ export const containsWith = (isEquivalent: (self: A, that: A) => boolean): { }) /** - * Returns a function that checks if a `Iterable` contains a given value using the default `Equivalence`. + * Checks whether an iterable contains a value using Effect's default `Equal` + * equivalence. + * + * **Details** + * + * Can be called as `contains(self, value)` or curried as + * `contains(value)(self)`. + * + * **Example** (Checking membership) * - * @example * ```ts * import { Iterable } from "effect" * @@ -2195,9 +2443,16 @@ export const containsWith = (isEquivalent: (self: A, that: A) => boolean): { */ export const contains: { /** - * Returns a function that checks if a `Iterable` contains a given value using the default `Equivalence`. + * Checks whether an iterable contains a value using Effect's default `Equal` + * equivalence. + * + * **Details** + * + * Can be called as `contains(self, value)` or curried as + * `contains(value)(self)`. + * + * **Example** (Checking membership) * - * @example * ```ts * import { Iterable } from "effect" * @@ -2225,9 +2480,16 @@ export const contains: { */ (a: A): (self: Iterable) => boolean /** - * Returns a function that checks if a `Iterable` contains a given value using the default `Equivalence`. + * Checks whether an iterable contains a value using Effect's default `Equal` + * equivalence. + * + * **Details** + * + * Can be called as `contains(self, value)` or curried as + * `contains(value)(self)`. + * + * **Example** (Checking membership) * - * @example * ```ts * import { Iterable } from "effect" * @@ -2260,7 +2522,8 @@ export const contains: { * Splits an `Iterable` into length-`n` pieces. The last piece will be shorter if `n` does not evenly divide the length of * the `Iterable`. * - * @example + * **Example** (Chunking an iterable) + * * ```ts * import { Iterable } from "effect" * @@ -2299,7 +2562,8 @@ export const chunksOf: { * Splits an `Iterable` into length-`n` pieces. The last piece will be shorter if `n` does not evenly divide the length of * the `Iterable`. * - * @example + * **Example** (Chunking an iterable) + * * ```ts * import { Iterable } from "effect" * @@ -2338,7 +2602,8 @@ export const chunksOf: { * Splits an `Iterable` into length-`n` pieces. The last piece will be shorter if `n` does not evenly divide the length of * the `Iterable`. * - * @example + * **Example** (Chunking an iterable) + * * ```ts * import { Iterable } from "effect" * @@ -2402,9 +2667,10 @@ export const chunksOf: { }) /** - * Group equal, consecutive elements of an `Iterable` into `NonEmptyArray`s using the provided `isEquivalent` function. + * Groups equal, consecutive elements of an `Iterable` into `NonEmptyArray`s using the provided `isEquivalent` function. + * + * **Example** (Grouping consecutive elements with custom equivalence) * - * @example * ```ts * import { Iterable } from "effect" * @@ -2441,9 +2707,10 @@ export const chunksOf: { */ export const groupWith: { /** - * Group equal, consecutive elements of an `Iterable` into `NonEmptyArray`s using the provided `isEquivalent` function. + * Groups equal, consecutive elements of an `Iterable` into `NonEmptyArray`s using the provided `isEquivalent` function. + * + * **Example** (Grouping consecutive elements with custom equivalence) * - * @example * ```ts * import { Iterable } from "effect" * @@ -2480,9 +2747,10 @@ export const groupWith: { */ (isEquivalent: (self: A, that: A) => boolean): (self: Iterable) => Iterable> /** - * Group equal, consecutive elements of an `Iterable` into `NonEmptyArray`s using the provided `isEquivalent` function. + * Groups equal, consecutive elements of an `Iterable` into `NonEmptyArray`s using the provided `isEquivalent` function. + * + * **Example** (Grouping consecutive elements with custom equivalence) * - * @example * ```ts * import { Iterable } from "effect" * @@ -2556,9 +2824,10 @@ export const groupWith: { ) /** - * Group equal, consecutive elements of an `Iterable` into `NonEmptyArray`s. + * Groups equal, consecutive elements of an `Iterable` into `NonEmptyArray`s. + * + * **Example** (Grouping consecutive elements) * - * @example * ```ts * import { Iterable } from "effect" * @@ -2592,10 +2861,16 @@ export const group: (self: Iterable) => Iterable> = group ) /** - * Splits an `Iterable` into sub-non-empty-arrays stored in an object, based on the result of calling a `string`-returning - * function on each element, and grouping the results according to values returned + * Groups all elements by the string or symbol key returned by `f`. + * + * **Details** + * + * Each property in the returned record contains a non-empty array of elements + * that produced that key. Unlike `group`, matching elements do not need to be + * consecutive. + * + * **Example** (Grouping by a key) * - * @example * ```ts * import { Iterable } from "effect" * @@ -2637,10 +2912,16 @@ export const group: (self: Iterable) => Iterable> = group */ export const groupBy: { /** - * Splits an `Iterable` into sub-non-empty-arrays stored in an object, based on the result of calling a `string`-returning - * function on each element, and grouping the results according to values returned + * Groups all elements by the string or symbol key returned by `f`. + * + * **Details** + * + * Each property in the returned record contains a non-empty array of elements + * that produced that key. Unlike `group`, matching elements do not need to be + * consecutive. + * + * **Example** (Grouping by a key) * - * @example * ```ts * import { Iterable } from "effect" * @@ -2682,10 +2963,16 @@ export const groupBy: { */ (f: (a: A) => K): (self: Iterable) => Record, NonEmptyArray> /** - * Splits an `Iterable` into sub-non-empty-arrays stored in an object, based on the result of calling a `string`-returning - * function on each element, and grouping the results according to values returned + * Groups all elements by the string or symbol key returned by `f`. + * + * **Details** + * + * Each property in the returned record contains a non-empty array of elements + * that produced that key. Unlike `group`, matching elements do not need to be + * consecutive. + * + * **Example** (Grouping by a key) * - * @example * ```ts * import { Iterable } from "effect" * @@ -2756,10 +3043,13 @@ const constEmptyIterator: Iterator = { /** * Creates an empty iterable that yields no elements. * - * This function returns a reusable empty iterable that can be used as a base case - * for operations or when you need to represent "no data" in a type-safe way. + * **When to use** + * + * Use when you need an empty iterable as a typed "no data" value or a base + * case for iterable operations. + * + * **Example** (Creating an empty iterable) * - * @example * ```ts * import { Iterable } from "effect" * @@ -2782,12 +3072,13 @@ export const empty = (): Iterable => constEmpty /** * Creates an iterable containing a single element. * - * This is useful for wrapping a single value in an iterable context, - * allowing it to be used with other iterable operations. + * **When to use** * - * @param a - The single element to wrap in an iterable + * Use to wrap a single value in an iterable context so it can be combined + * with other iterable operations. + * + * **Example** (Wrapping a single value) * - * @example * ```ts * import { Iterable } from "effect" * @@ -2818,15 +3109,15 @@ export const of = (a: A): Iterable => [a] /** * Transforms each element of an iterable using a function. * + * **Details** + * * This is one of the most fundamental operations for working with iterables. * It applies a transformation function to each element, creating a new iterable - * with the transformed values. The operation is lazy - elements are only + * with the transformed values. The operation is lazy, so elements are only * transformed when the iterable is consumed. * - * @param self - The source iterable to transform - * @param f - Function that transforms each element (receives value and index) + * **Example** (Mapping elements) * - * @example * ```ts * import { Iterable } from "effect" * @@ -2854,15 +3145,15 @@ export const map: { /** * Transforms each element of an iterable using a function. * + * **Details** + * * This is one of the most fundamental operations for working with iterables. * It applies a transformation function to each element, creating a new iterable - * with the transformed values. The operation is lazy - elements are only + * with the transformed values. The operation is lazy, so elements are only * transformed when the iterable is consumed. * - * @param self - The source iterable to transform - * @param f - Function that transforms each element (receives value and index) + * **Example** (Mapping elements) * - * @example * ```ts * import { Iterable } from "effect" * @@ -2890,15 +3181,15 @@ export const map: { /** * Transforms each element of an iterable using a function. * + * **Details** + * * This is one of the most fundamental operations for working with iterables. * It applies a transformation function to each element, creating a new iterable - * with the transformed values. The operation is lazy - elements are only + * with the transformed values. The operation is lazy, so elements are only * transformed when the iterable is consumed. * - * @param self - The source iterable to transform - * @param f - Function that transforms each element (receives value and index) + * **Example** (Mapping elements) * - * @example * ```ts * import { Iterable } from "effect" * @@ -2942,7 +3233,8 @@ export const map: { /** * Applies a function to each element in an Iterable and returns a new Iterable containing the concatenated mapped elements. * - * @example + * **Example** (FlatMapping iterables) + * * ```ts * import { Iterable } from "effect" * @@ -2980,7 +3272,8 @@ export const flatMap: { /** * Applies a function to each element in an Iterable and returns a new Iterable containing the concatenated mapped elements. * - * @example + * **Example** (FlatMapping iterables) + * * ```ts * import { Iterable } from "effect" * @@ -3018,7 +3311,8 @@ export const flatMap: { /** * Applies a function to each element in an Iterable and returns a new Iterable containing the concatenated mapped elements. * - * @example + * **Example** (FlatMapping iterables) + * * ```ts * import { Iterable } from "effect" * @@ -3061,7 +3355,8 @@ export const flatMap: { /** * Flattens an Iterable of Iterables into a single Iterable * - * @example + * **Example** (Flattening nested iterables) + * * ```ts * import { Iterable } from "effect" * @@ -3116,13 +3411,16 @@ export const flatten = (self: Iterable>): Iterable => ({ /** * Transforms elements of an iterable using a function that returns a `Result`, keeping only successful values. * - * This combines mapping and filtering in a single operation - the function is applied to each element, - * and only elements that result in `Result.succeed` are included in the result. + * **Details** + * + * This combines mapping and filtering in a single operation. The function is + * applied to each element, and only elements that result in `Result.succeed` + * are included in the result. + * + * **Example** (Filtering and transforming Result values) * - * @example * ```ts - * import { Iterable } from "effect" - * import * as Result from "effect/Result" + * import { Iterable, Result } from "effect" * * // Parse strings to numbers, keeping only valid ones * const strings = ["1", "2", "invalid", "4", "not-a-number"] @@ -3162,13 +3460,16 @@ export const filterMap: { /** * Transforms elements of an iterable using a function that returns a `Result`, keeping only successful values. * - * This combines mapping and filtering in a single operation - the function is applied to each element, - * and only elements that result in `Result.succeed` are included in the result. + * **Details** + * + * This combines mapping and filtering in a single operation. The function is + * applied to each element, and only elements that result in `Result.succeed` + * are included in the result. + * + * **Example** (Filtering and transforming Result values) * - * @example * ```ts - * import { Iterable } from "effect" - * import * as Result from "effect/Result" + * import { Iterable, Result } from "effect" * * // Parse strings to numbers, keeping only valid ones * const strings = ["1", "2", "invalid", "4", "not-a-number"] @@ -3208,13 +3509,16 @@ export const filterMap: { /** * Transforms elements of an iterable using a function that returns a `Result`, keeping only successful values. * - * This combines mapping and filtering in a single operation - the function is applied to each element, - * and only elements that result in `Result.succeed` are included in the result. + * **Details** + * + * This combines mapping and filtering in a single operation. The function is + * applied to each element, and only elements that result in `Result.succeed` + * are included in the result. + * + * **Example** (Filtering and transforming Result values) * - * @example * ```ts - * import { Iterable } from "effect" - * import * as Result from "effect/Result" + * import { Iterable, Result } from "effect" * * // Parse strings to numbers, keeping only valid ones * const strings = ["1", "2", "invalid", "4", "not-a-number"] @@ -3277,10 +3581,10 @@ export const filterMap: { /** * Transforms all elements of the `Iterable` for as long as the specified function succeeds. * - * @example + * **Example** (Filtering and transforming until failure) + * * ```ts - * import { Iterable } from "effect" - * import * as Result from "effect/Result" + * import { Iterable, Result } from "effect" * * // Parse numbers until we hit an invalid one * const strings = ["1", "2", "3", "invalid", "4", "5"] @@ -3314,10 +3618,10 @@ export const filterMapWhile: { /** * Transforms all elements of the `Iterable` for as long as the specified function succeeds. * - * @example + * **Example** (Filtering and transforming until failure) + * * ```ts - * import { Iterable } from "effect" - * import * as Result from "effect/Result" + * import { Iterable, Result } from "effect" * * // Parse numbers until we hit an invalid one * const strings = ["1", "2", "3", "invalid", "4", "5"] @@ -3351,10 +3655,10 @@ export const filterMapWhile: { /** * Transforms all elements of the `Iterable` for as long as the specified function succeeds. * - * @example + * **Example** (Filtering and transforming until failure) + * * ```ts - * import { Iterable } from "effect" - * import * as Result from "effect/Result" + * import { Iterable, Result } from "effect" * * // Parse numbers until we hit an invalid one * const strings = ["1", "2", "3", "invalid", "4", "5"] @@ -3408,10 +3712,10 @@ export const filterMapWhile: { /** * Retrieves the `Some` values from an `Iterable` of `Option`s. * - * @example + * **Example** (Extracting Some values) + * * ```ts - * import { Iterable } from "effect" - * import * as Option from "effect/Option" + * import { Iterable, Option } from "effect" * import * as assert from "node:assert" * * assert.deepStrictEqual( @@ -3446,12 +3750,13 @@ export const getSomes = (self: Iterable>): Iterable => { } /** - * Retrieves the `Err` values from an `Iterable` of `Result`s. + * Returns a lazy iterable containing the failure values from an iterable of + * `Result`s, skipping successful results. + * + * **Example** (Extracting failures) * - * @example * ```ts - * import { Iterable } from "effect" - * import * as Result from "effect/Result" + * import { Iterable, Result } from "effect" * import * as assert from "node:assert" * * assert.deepStrictEqual( @@ -3467,7 +3772,7 @@ export const getSomes = (self: Iterable>): Iterable => { * ``` * * @category filtering - * @since 2.0.0 + * @since 4.0.0 */ export const getFailures = (self: Iterable>): Iterable => { return { @@ -3490,12 +3795,13 @@ export const getFailures = (self: Iterable>): Iterable = } /** - * Retrieves the `Ok` values from an `Iterable` of `Result`s. + * Returns a lazy iterable containing the success values from an iterable of + * `Result`s, skipping failed results. + * + * **Example** (Extracting successes) * - * @example * ```ts - * import { Iterable } from "effect" - * import * as Result from "effect/Result" + * import { Iterable, Result } from "effect" * import * as assert from "node:assert" * * assert.deepStrictEqual( @@ -3511,7 +3817,7 @@ export const getFailures = (self: Iterable>): Iterable = * ``` * * @category filtering - * @since 2.0.0 + * @since 4.0.0 */ export const getSuccesses = (self: Iterable>): Iterable => { return { @@ -3536,14 +3842,14 @@ export const getSuccesses = (self: Iterable>): Iterable /** * Filters an iterable to only include elements that match a predicate. * + * **Details** + * * This function creates a new iterable containing only the elements for which * the predicate function returns true. Like map, this operation is lazy and * elements are only tested when the iterable is consumed. * - * @param self - The source iterable to filter - * @param predicate - Function that tests each element (receives value and index) + * **Example** (Filtering elements) * - * @example * ```ts * import { Iterable } from "effect" * @@ -3580,14 +3886,14 @@ export const filter: { /** * Filters an iterable to only include elements that match a predicate. * + * **Details** + * * This function creates a new iterable containing only the elements for which * the predicate function returns true. Like map, this operation is lazy and * elements are only tested when the iterable is consumed. * - * @param self - The source iterable to filter - * @param predicate - Function that tests each element (receives value and index) + * **Example** (Filtering elements) * - * @example * ```ts * import { Iterable } from "effect" * @@ -3624,14 +3930,14 @@ export const filter: { /** * Filters an iterable to only include elements that match a predicate. * + * **Details** + * * This function creates a new iterable containing only the elements for which * the predicate function returns true. Like map, this operation is lazy and * elements are only tested when the iterable is consumed. * - * @param self - The source iterable to filter - * @param predicate - Function that tests each element (receives value and index) + * **Example** (Filtering elements) * - * @example * ```ts * import { Iterable } from "effect" * @@ -3668,14 +3974,14 @@ export const filter: { /** * Filters an iterable to only include elements that match a predicate. * + * **Details** + * * This function creates a new iterable containing only the elements for which * the predicate function returns true. Like map, this operation is lazy and * elements are only tested when the iterable is consumed. * - * @param self - The source iterable to filter - * @param predicate - Function that tests each element (receives value and index) + * **Example** (Filtering elements) * - * @example * ```ts * import { Iterable } from "effect" * @@ -3712,14 +4018,14 @@ export const filter: { /** * Filters an iterable to only include elements that match a predicate. * + * **Details** + * * This function creates a new iterable containing only the elements for which * the predicate function returns true. Like map, this operation is lazy and * elements are only tested when the iterable is consumed. * - * @param self - The source iterable to filter - * @param predicate - Function that tests each element (receives value and index) + * **Example** (Filtering elements) * - * @example * ```ts * import { Iterable } from "effect" * @@ -3778,10 +4084,13 @@ export const filter: { /** * Transforms elements using a function that may return null or undefined, filtering out the null/undefined results. * - * This is useful when working with APIs or functions that return nullable values, - * providing a clean way to filter out null/undefined while transforming. + * **When to use** + * + * Use when working with APIs or functions that return nullable values, + * providing a clean way to filter out null or undefined while transforming. + * + * **Example** (FlatMapping nullable results) * - * @example * ```ts * import { Iterable } from "effect" * @@ -3815,16 +4124,19 @@ export const filter: { * ``` * * @category sequencing - * @since 2.0.0 + * @since 4.0.0 */ export const flatMapNullishOr: { /** * Transforms elements using a function that may return null or undefined, filtering out the null/undefined results. * - * This is useful when working with APIs or functions that return nullable values, - * providing a clean way to filter out null/undefined while transforming. + * **When to use** + * + * Use when working with APIs or functions that return nullable values, + * providing a clean way to filter out null or undefined while transforming. + * + * **Example** (FlatMapping nullable results) * - * @example * ```ts * import { Iterable } from "effect" * @@ -3858,16 +4170,19 @@ export const flatMapNullishOr: { * ``` * * @category sequencing - * @since 2.0.0 + * @since 4.0.0 */ (f: (a: A) => B): (self: Iterable) => Iterable> /** * Transforms elements using a function that may return null or undefined, filtering out the null/undefined results. * - * This is useful when working with APIs or functions that return nullable values, - * providing a clean way to filter out null/undefined while transforming. + * **When to use** + * + * Use when working with APIs or functions that return nullable values, + * providing a clean way to filter out null or undefined while transforming. + * + * **Example** (FlatMapping nullable results) * - * @example * ```ts * import { Iterable } from "effect" * @@ -3901,7 +4216,7 @@ export const flatMapNullishOr: { * ``` * * @category sequencing - * @since 2.0.0 + * @since 4.0.0 */ (self: Iterable, f: (a: A) => B): Iterable> } = dual( @@ -3914,9 +4229,10 @@ export const flatMapNullishOr: { ) /** - * Check if a predicate holds true for some `Iterable` element. + * Checks whether a predicate holds true for some `Iterable` element. + * + * **Example** (Checking whether some element matches) * - * @example * ```ts * import { Iterable } from "effect" * @@ -3955,9 +4271,10 @@ export const flatMapNullishOr: { */ export const some: { /** - * Check if a predicate holds true for some `Iterable` element. + * Checks whether a predicate holds true for some `Iterable` element. + * + * **Example** (Checking whether some element matches) * - * @example * ```ts * import { Iterable } from "effect" * @@ -3996,9 +4313,10 @@ export const some: { */ (predicate: (a: A, i: number) => boolean): (self: Iterable) => boolean /** - * Check if a predicate holds true for some `Iterable` element. + * Checks whether a predicate holds true for some `Iterable` element. + * + * **Example** (Checking whether some element matches) * - * @example * ```ts * import { Iterable } from "effect" * @@ -4053,11 +4371,14 @@ export const some: { * Generates an iterable by repeatedly applying a function that produces the * next element and state. * + * **Details** + * * This is useful for creating iterables from a generating function that * maintains state. The function should return `Option.some([value, nextState])` * to continue or `Option.none()` to stop. * - * @example + * **Example** (Unfolding state into values) + * * ```ts * import { Iterable, Option } from "effect" * @@ -4104,9 +4425,10 @@ export const unfold = (b: B, f: (b: B) => Option): Iterab }) /** - * Iterate over the `Iterable` applying `f`. + * Iterates over the `Iterable`, applying `f` to each element. + * + * **Example** (Iterating with side effects) * - * @example * ```ts * import { Iterable } from "effect" * @@ -4142,9 +4464,10 @@ export const unfold = (b: B, f: (b: B) => Option): Iterab */ export const forEach: { /** - * Iterate over the `Iterable` applying `f`. + * Iterates over the `Iterable`, applying `f` to each element. + * + * **Example** (Iterating with side effects) * - * @example * ```ts * import { Iterable } from "effect" * @@ -4180,9 +4503,10 @@ export const forEach: { */ (f: (a: A, i: number) => void): (self: Iterable) => void /** - * Iterate over the `Iterable` applying `f`. + * Iterates over the `Iterable`, applying `f` to each element. + * + * **Example** (Iterating with side effects) * - * @example * ```ts * import { Iterable } from "effect" * @@ -4225,12 +4549,15 @@ export const forEach: { }) /** - * Reduce an iterable to a single value by applying a function to each element and accumulating the result. + * Reduces an iterable to a single value by applying a function to each element and accumulating the result. + * + * **Details** * * This function applies a reducing function against an accumulator and each element * of the iterable (from left to right) to reduce it to a single value. * - * @example + * **Example** (Reducing an iterable) + * * ```ts * import { Iterable } from "effect" * @@ -4274,12 +4601,15 @@ export const forEach: { */ export const reduce: { /** - * Reduce an iterable to a single value by applying a function to each element and accumulating the result. + * Reduces an iterable to a single value by applying a function to each element and accumulating the result. + * + * **Details** * * This function applies a reducing function against an accumulator and each element * of the iterable (from left to right) to reduce it to a single value. * - * @example + * **Example** (Reducing an iterable) + * * ```ts * import { Iterable } from "effect" * @@ -4323,12 +4653,15 @@ export const reduce: { */ (b: B, f: (b: B, a: A, i: number) => B): (self: Iterable) => B /** - * Reduce an iterable to a single value by applying a function to each element and accumulating the result. + * Reduces an iterable to a single value by applying a function to each element and accumulating the result. + * + * **Details** * * This function applies a reducing function against an accumulator and each element * of the iterable (from left to right) to reduce it to a single value. * - * @example + * **Example** (Reducing an iterable) + * * ```ts * import { Iterable } from "effect" * @@ -4386,7 +4719,8 @@ export const reduce: { /** * Deduplicates adjacent elements that are identical using the provided `isEquivalent` function. * - * @example + * **Example** (Deduplicating adjacent elements with custom equivalence) + * * ```ts * import { Iterable } from "effect" * @@ -4428,7 +4762,8 @@ export const dedupeAdjacentWith: { /** * Deduplicates adjacent elements that are identical using the provided `isEquivalent` function. * - * @example + * **Example** (Deduplicating adjacent elements with custom equivalence) + * * ```ts * import { Iterable } from "effect" * @@ -4470,7 +4805,8 @@ export const dedupeAdjacentWith: { /** * Deduplicates adjacent elements that are identical using the provided `isEquivalent` function. * - * @example + * **Example** (Deduplicating adjacent elements with custom equivalence) + * * ```ts * import { Iterable } from "effect" * @@ -4538,7 +4874,8 @@ export const dedupeAdjacentWith: { /** * Deduplicates adjacent elements that are identical. * - * @example + * **Example** (Deduplicating adjacent elements) + * * ```ts * import { Iterable } from "effect" * @@ -4577,7 +4914,8 @@ export const dedupeAdjacent: (self: Iterable) => Iterable = dedupeAdjac /** * Zips this Iterable crosswise with the specified Iterable using the specified combiner. * - * @example + * **Example** (Combining cartesian products) + * * ```ts * import { Iterable } from "effect" * @@ -4620,14 +4958,15 @@ export const dedupeAdjacent: (self: Iterable) => Iterable = dedupeAdjac * // ["admin_can_read", "admin_can_write", "admin_can_delete", "user_can_read", "user_can_write", "user_can_delete"] * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ export const cartesianWith: { /** * Zips this Iterable crosswise with the specified Iterable using the specified combiner. * - * @example + * **Example** (Combining cartesian products) + * * ```ts * import { Iterable } from "effect" * @@ -4670,14 +5009,15 @@ export const cartesianWith: { * // ["admin_can_read", "admin_can_write", "admin_can_delete", "user_can_read", "user_can_write", "user_can_delete"] * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (that: Iterable, f: (a: A, b: B) => C): (self: Iterable) => Iterable /** * Zips this Iterable crosswise with the specified Iterable using the specified combiner. * - * @example + * **Example** (Combining cartesian products) + * * ```ts * import { Iterable } from "effect" * @@ -4720,8 +5060,8 @@ export const cartesianWith: { * // ["admin_can_read", "admin_can_write", "admin_can_delete", "user_can_read", "user_can_write", "user_can_delete"] * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (self: Iterable, that: Iterable, f: (a: A, b: B) => C): Iterable } = dual( @@ -4733,7 +5073,8 @@ export const cartesianWith: { /** * Zips this Iterable crosswise with the specified Iterable. * - * @example + * **Example** (Generating cartesian pairs) + * * ```ts * import { Iterable } from "effect" * @@ -4767,14 +5108,15 @@ export const cartesianWith: { * console.log(Array.from(withEmpty)) // [] * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ export const cartesian: { /** * Zips this Iterable crosswise with the specified Iterable. * - * @example + * **Example** (Generating cartesian pairs) + * * ```ts * import { Iterable } from "effect" * @@ -4808,14 +5150,15 @@ export const cartesian: { * console.log(Array.from(withEmpty)) // [] * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (that: Iterable): (self: Iterable) => Iterable<[A, B]> /** * Zips this Iterable crosswise with the specified Iterable. * - * @example + * **Example** (Generating cartesian pairs) + * * ```ts * import { Iterable } from "effect" * @@ -4849,8 +5192,8 @@ export const cartesian: { * console.log(Array.from(withEmpty)) // [] * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (self: Iterable, that: Iterable): Iterable<[A, B]> } = dual( @@ -4859,9 +5202,9 @@ export const cartesian: { ) /** - * Counts all the element of the given iterable that pass the given predicate + * Computes how many elements of the iterable pass the given predicate. * - * **Example** + * **Example** (Counting matching elements) * * ```ts * import { Iterable } from "effect" @@ -4875,9 +5218,9 @@ export const cartesian: { */ export const countBy: { /** - * Counts all the element of the given iterable that pass the given predicate + * Computes how many elements of the iterable pass the given predicate. * - * **Example** + * **Example** (Counting matching elements) * * ```ts * import { Iterable } from "effect" @@ -4891,9 +5234,9 @@ export const countBy: { */ (predicate: (a: NoInfer, i: number) => boolean): (self: Iterable) => number /** - * Counts all the element of the given iterable that pass the given predicate + * Computes how many elements of the iterable pass the given predicate. * - * **Example** + * **Example** (Counting matching elements) * * ```ts * import { Iterable } from "effect" diff --git a/.opencode/node_modules/effect/src/JsonPatch.ts b/.opencode/node_modules/effect/src/JsonPatch.ts index de410daf6c3e0905eaf48721c3ab7aea062307ba..5194b444c55c868f5ac38d0f2f70fbf1d836ba15 100644 --- a/.opencode/node_modules/effect/src/JsonPatch.ts +++ b/.opencode/node_modules/effect/src/JsonPatch.ts @@ -1,54 +1,9 @@ /** - * JSON Patch operations for transforming JSON documents. - * - * This module implements a subset of RFC 6902, providing operations that can be applied deterministically without additional context. It supports computing structural diffs between JSON values and applying patches to transform documents. - * - * ## Mental model - * - * - **JSON Patch**: An ordered sequence of operations that transform a document from one state to another - * - **JSON Pointer**: Path syntax for targeting specific locations in a JSON document (e.g., `/users/0/name`) - * - **Operations**: Three types - `add` (insert value), `remove` (delete value), `replace` (update value) - * - **Immutable transformations**: All operations return new values; inputs are never mutated - * - **Sequential application**: Operations are applied in order, with later operations observing changes from earlier ones - * - **Structural diff**: The `get` function computes differences by comparing structure, not content semantics - * - * ## Common tasks - * - * - Computing diffs between JSON values → {@link get} - * - Applying patches to transform documents → {@link apply} - * - Creating patches manually → {@link JsonPatchOperation} - * - Storing and validating patch documents → {@link JsonPatch} - * - * ## Gotchas - * - * - Array removals are emitted from highest index to lowest to avoid index shifting during application - * - Root operations use an empty string path `""` to target the entire document - * - Array append operations use `-` as the last token in the path (e.g., `/items/-`) - * - Generated patches are deterministic but not guaranteed to be minimal - * - Empty patches return the original document reference (no allocation) - * - Invalid paths or operations throw errors rather than returning a result type - * - * ## Quickstart - * - * **Example** (Computing and applying a patch) - * - * ```ts - * import * as JsonPatch from "effect/JsonPatch" - * - * const oldValue = { name: "Alice", age: 30 } - * const newValue = { name: "Alice", age: 31, city: "NYC" } - * - * const patch = JsonPatch.get(oldValue, newValue) - * // [{ op: "replace", path: "/age", value: 31 }, { op: "add", path: "/city", value: "NYC" }] - * - * const result = JsonPatch.apply(patch, oldValue) - * // { name: "Alice", age: 31, city: "NYC" } - * ``` - * - * ## See also - * - * - {@link JsonPointer} - Utilities for working with JSON Pointer paths - * - {@link Schema.Json} - The JSON value type used by this module + * The `JsonPatch` module computes and applies deterministic patch documents for + * JSON values. A patch is an ordered list of `add`, `remove`, and `replace` + * operations addressed by JSON Pointer paths. Use it to describe the structural + * difference between two JSON documents, serialize that difference, and replay + * it without mutating the original input. * * @since 4.0.0 */ @@ -60,25 +15,24 @@ import type * as Schema from "./Schema.ts" /** * A single JSON Patch operation. * - * Represents one transformation step in a JSON Patch document. This is a subset of RFC 6902, restricted to operations that can be applied deterministically without additional context. - * - * ## When to use this + * **When to use** * - * - Defining patch operation types in your code - * - Manually constructing patch operations - * - Type-checking patch operation structures + * Use to manually construct patch operations, accept patch operations from + * callers, or type-check patch operation structures. * - * ## Behavior + * **Details** * - * - All fields are readonly; operations are immutable value objects - * - Paths use JSON Pointer syntax; empty string `""` refers to the root document - * - The `description` field is optional and can be used for documentation - * - Operations are discriminated unions based on the `op` field + * Represents one transformation step in a JSON Patch document. This is a subset + * of RFC 6902, restricted to operations that can be applied deterministically + * without additional context. All fields are readonly, paths use JSON Pointer + * syntax, and the empty string `""` refers to the root document. Operations are + * discriminated by the `op` field, and the optional `description` field can be + * used for documentation. * * **Example** (All operation types) * * ```ts - * import * as JsonPatch from "effect/JsonPatch" + * import { JsonPatch } from "effect" * * const addOp: JsonPatch.JsonPatchOperation = { * op: "add", @@ -98,22 +52,22 @@ import type * as Schema from "./Schema.ts" * } * ``` * - * ## See also - * - * - {@link JsonPatch} - Array of operations forming a complete patch - * - {@link get} - Computes operations automatically from value differences - * - {@link apply} - Applies operations to transform documents - * - * @category Model + * @see {@link JsonPatch} for the array of operations forming a complete patch + * @see {@link get} to compute operations automatically from value differences + * @see {@link apply} to apply operations to transform documents + * @category models * @since 4.0.0 */ export type JsonPatchOperation = | { readonly op: "add" /** - * JSON Pointer to the target location. + * JSON Pointer to the target location. For arrays, the last token may be `-` + * to append. + * + * **When to use** * - * For arrays, the last token may be `-` to append. + * Use to identify where the `add` operation inserts its value. */ readonly path: string readonly value: Schema.Json @@ -121,13 +75,25 @@ export type JsonPatchOperation = } | { readonly op: "remove" - /** JSON Pointer to the target location. */ + /** + * JSON Pointer to the target location. + * + * **When to use** + * + * Use to identify which location the `remove` operation deletes. + */ readonly path: string readonly description?: string } | { readonly op: "replace" - /** JSON Pointer to the target location. Use `""` to replace the root document. */ + /** + * JSON Pointer to the target location. Use `""` to replace the root document. + * + * **When to use** + * + * Use to identify which location the `replace` operation overwrites. + */ readonly path: string readonly value: Schema.Json readonly description?: string @@ -136,26 +102,21 @@ export type JsonPatchOperation = /** * A JSON Patch document (an ordered list of operations). * - * Represents a complete transformation as a sequence of operations. Operations are applied in order, and later operations observe the changes made by earlier ones. - * - * ## When to use this + * **When to use** * - * - Storing or serializing patch documents - * - Passing patches between functions or systems - * - Type-checking patch arrays - * - Validating patch structure + * Use to store, serialize, pass, or validate complete patch documents. * - * ## Behavior + * **Details** * - * - Operations are applied sequentially from first to last - * - Empty arrays represent no-op patches (return original document) - * - Later operations see the document state after earlier operations - * - The array is readonly; individual operations are immutable + * Represents a complete transformation as a readonly sequence of immutable + * operations. Operations are applied sequentially from first to last, and later + * operations observe the document state produced by earlier operations. An empty + * array represents a no-op patch and returns the original document. * * **Example** (Multi-operation patch) * * ```ts - * import * as JsonPatch from "effect/JsonPatch" + * import { JsonPatch } from "effect" * * const patch: JsonPatch.JsonPatch = [ * { op: "add", path: "/items/-", value: "apple" }, @@ -167,44 +128,40 @@ export type JsonPatchOperation = * // { count: 5, items: ["apple"] } * ``` * - * ## See also - * - * - {@link JsonPatchOperation} - Individual operation types - * - {@link get} - Generates patches from value differences - * - {@link apply} - Executes patches to transform documents - * - * @category Model + * @see {@link JsonPatchOperation} for individual operation types + * @see {@link get} to generate patches from value differences + * @see {@link apply} to execute patches to transform documents + * @category models * @since 4.0.0 */ export type JsonPatch = ReadonlyArray /** - * Compute a patch that transforms `oldValue` into `newValue`. + * Computes a structural patch that transforms `oldValue` into `newValue`. + * + * **When to use** * - * Generates a structural diff between two JSON values, producing a patch that when applied to `oldValue` yields `newValue`. + * Use to compute a JSON Patch from before and after JSON documents, detect + * structural changes, or create deterministic update operations. * - * ## When to use this + * **Details** * - * - Computing differences between JSON documents - * - Detecting changes in data structures - * - Generating patches for synchronization or version control - * - Creating minimal update operations from before/after states + * Generates a structural diff between two JSON values, producing a patch that + * yields `newValue` when applied to `oldValue`. It returns an empty array when + * values are identical, recursively diffs nested structures, emits root + * `replace` operations for primitive changes, and processes object keys in + * sorted order for stable output. * - * ## Behavior + * **Gotchas** * - * - Returns an empty array if values are identical (same reference or deep equal) - * - Does not mutate inputs; returns a new patch array - * - Primitives (numbers, strings, booleans, null) result in a root `replace` operation - * - Arrays are compared by index position; no move or copy detection - * - Objects are compared by key; keys processed in sorted order for stable output - * - Array removals emitted from highest to lowest index to prevent index shifting - * - Output is deterministic but not guaranteed to be minimal - * - Nested structures are recursively diffed + * Arrays are compared by index position, with no move or copy detection. Array + * removals are emitted from highest to lowest index to prevent index shifting. + * The output is deterministic but not guaranteed to be minimal. * * **Example** (Computing object diff) * * ```ts - * import * as JsonPatch from "effect/JsonPatch" + * import { JsonPatch } from "effect" * * const oldValue = { users: [{ id: 1, name: "Alice" }], count: 1 } * const newValue = { users: [{ id: 1, name: "Bob" }, { id: 2, name: "Charlie" }], count: 2 } @@ -217,11 +174,9 @@ export type JsonPatch = ReadonlyArray * // ] * ``` * - * ## See also - * - * - {@link apply} - Applies the generated patch to a document - * - {@link JsonPatchOperation} - The operation types in the patch - * + * @see {@link apply} to apply the generated patch to a document + * @see {@link JsonPatchOperation} for the operation types in the patch + * @category transforming * @since 4.0.0 */ export function get(oldValue: Schema.Json, newValue: Schema.Json): JsonPatch { @@ -288,31 +243,31 @@ export function get(oldValue: Schema.Json, newValue: Schema.Json): JsonPatch { } /** - * Apply a JSON Patch to a document. + * Applies a JSON Patch to a JSON document. + * + * **When to use** * - * Executes a sequence of patch operations on a JSON document, returning a new document with all transformations applied. + * Use to execute patches generated by {@link get}, transform documents + * with manually constructed patches, or process patch operations from external + * sources. * - * ## When to use this + * **Details** * - * - Applying patches generated by {@link get} - * - Transforming documents with manually constructed patches - * - Implementing patch-based update mechanisms - * - Processing patch operations from external sources + * Executes patch operations sequentially, so later operations see changes made + * by earlier operations. It never mutates the input document; array and object + * operations copy the affected containers. An empty patch returns the original + * reference, and a root replace (`path: ""`) returns the provided value + * directly. * - * ## Behavior + * **Gotchas** * - * - Never mutates the input document; returns a new value - * - Returns the original reference if patch is empty (no allocation) - * - Operations applied sequentially; later operations see earlier changes - * - Root replace (`path: ""`) returns the provided value directly - * - Throws errors for invalid paths, missing properties, or out-of-bounds array indices - * - Array operations preserve immutability by copying affected arrays - * - Object operations preserve immutability by copying affected objects + * Invalid paths, missing properties, and out-of-bounds array indices throw + * errors. * * **Example** (Applying a patch) * * ```ts - * import * as JsonPatch from "effect/JsonPatch" + * import { JsonPatch } from "effect" * * const document = { items: [1, 2, 3], total: 6 } * const patch: JsonPatch.JsonPatch = [ @@ -324,11 +279,9 @@ export function get(oldValue: Schema.Json, newValue: Schema.Json): JsonPatch { * // { items: [1, 2, 3, 4], total: 10 } * ``` * - * ## See also - * - * - {@link get} - Generates patches from value differences - * - {@link JsonPatchOperation} - The operation types being applied - * + * @see {@link get} to generate patches from value differences + * @see {@link JsonPatchOperation} for the operation types being applied + * @category transforming * @since 4.0.0 */ export function apply(patch: JsonPatch, oldValue: Schema.Json): Schema.Json { diff --git a/.opencode/node_modules/effect/src/JsonPointer.ts b/.opencode/node_modules/effect/src/JsonPointer.ts index cd17e5f2b98442806be2b279c84938e2c5fe5b41..ab12f5daaf97aa6339691a701d9350d9d9b5d984 100644 --- a/.opencode/node_modules/effect/src/JsonPointer.ts +++ b/.opencode/node_modules/effect/src/JsonPointer.ts @@ -1,90 +1,42 @@ /** - * Utilities for escaping and unescaping JSON Pointer reference tokens according to RFC 6901. - * - * JSON Pointer (RFC 6901) defines a string syntax for identifying a specific value within a JSON document. - * A JSON Pointer is a sequence of reference tokens separated by forward slashes (`/`). Each reference token - * must be escaped when it contains special characters (`~` or `/`). - * - * ## Mental model - * - * - **Reference token**: A single segment of a JSON Pointer path (e.g., `"foo"`, `"bar/baz"`, `"key~with~tilde"`) - * - **Escaping**: Encoding special characters in a token so it can be safely used in a JSON Pointer (`~` → `~0`, `/` → `~1`) - * - **Unescaping**: Decoding escaped characters back to their original form (`~0` → `~`, `~1` → `/`) - * - **RFC 6901 compliance**: These functions implement the standard escaping rules for JSON Pointer reference tokens - * - **Pure functions**: Both operations are pure, immutable, and have no side effects - * - * ## Common tasks - * - * - Building JSON Pointers from path segments → {@link escapeToken} - * - Parsing JSON Pointers to extract original token values → {@link unescapeToken} - * - Escaping object keys or path segments before constructing JSON Pointers → {@link escapeToken} - * - Extracting unescaped identifiers from JSON Pointer strings → {@link unescapeToken} - * - * ## Gotchas - * - * - These functions operate on **reference tokens**, not full JSON Pointers. A full JSON Pointer like `/foo/bar` must be split into tokens (`["foo", "bar"]`) before escaping/unescaping - * - The order of replacement operations matters: `escapeToken` replaces `~` before `/` to avoid double-escaping - * - Empty strings are valid tokens and are returned unchanged - * - These functions do not validate JSON Pointer syntax; they only handle token-level escaping - * - * ## Quickstart - * - * **Example** (Building and parsing a JSON Pointer) - * - * ```ts - * import { escapeToken, unescapeToken } from "effect/JsonPointer" - * - * // Build a JSON Pointer from path segments - * const segments = ["users", "name/alias", "value"] - * const pointer = "/" + segments.map(escapeToken).join("/") - * // "/users/name~1alias/value" - * - * // Parse a JSON Pointer back to segments - * const tokens = pointer.split("/").slice(1).map(unescapeToken) - * // ["users", "name/alias", "value"] - * ``` - * - * ## See also - * - * - {@link JsonPatch} - Uses these utilities for JSON Patch operations - * - {@link JsonSchema} - Uses these utilities for schema reference resolution + * Helpers for escaping and unescaping JSON Pointer path segments. JSON Pointer + * uses `/` to separate path tokens inside a JSON document, so token text must + * encode literal `~` and `/` characters. This module provides the two RFC 6901 + * token conversions used by JSON Patch and related path handling. * * @since 4.0.0 */ /** - * Escapes a JSON Pointer reference token according to RFC 6901. - * - * Encodes special characters in a reference token so it can be safely used as a segment in a JSON Pointer. + * Escapes a JSON Pointer reference token according to RFC 6901 by encoding special characters so the token can be safely used as a segment in a JSON Pointer. * - * ## When to use this + * **When to use** * - * - Building JSON Pointers from object keys or path segments that may contain special characters - * - Escaping tokens before joining them with `/` to form a complete JSON Pointer - * - Preparing reference tokens for use in JSON Patch operations or schema references + * Use when you need to escape a single JSON Pointer path segment. * - * ## Behavior + * **Details** * - * - Does not mutate the input string; returns a new escaped string + * - Returns a new escaped string * - Replaces `~` (tilde) with `~0` and `/` (forward slash) with `~1` - * - Replacement order matters: `~` is replaced before `/` to prevent double-escaping * - Returns the input unchanged if it contains no special characters * - Empty strings are valid and returned unchanged * + * **Gotchas** + * + * The replacement order matters: `~` is replaced before `/` to prevent double-escaping. + * * **Example** (Escaping special characters) * * ```ts - * import { escapeToken } from "effect/JsonPointer" + * import { JsonPointer } from "effect" * - * escapeToken("a/b") // "a~1b" - * escapeToken("c~d") // "c~0d" - * escapeToken("path/to~key") // "path~1to~0key" + * JsonPointer.escapeToken("a/b") // "a~1b" + * JsonPointer.escapeToken("c~d") // "c~0d" + * JsonPointer.escapeToken("path/to~key") // "path~1to~0key" * ``` * - * ## See also - * - * - {@link unescapeToken} - The inverse operation for decoding escaped tokens - * + * @see {@link unescapeToken} The inverse operation for decoding escaped tokens + * @category encoding * @since 4.0.0 */ export function escapeToken(token: string): string { @@ -92,38 +44,35 @@ export function escapeToken(token: string): string { } /** - * Unescapes a JSON Pointer reference token according to RFC 6901. - * - * Decodes escaped characters in a reference token to recover the original token value. + * Decodes a JSON Pointer reference token according to RFC 6901 escaping rules. * - * ## When to use this + * **When to use** * - * - Parsing JSON Pointers to extract the original token values from escaped segments - * - Converting escaped tokens back to their original form for use as object keys or identifiers - * - Resolving schema references or JSON Patch paths that use escaped tokens + * Use when you need to decode a single escaped JSON Pointer path segment. * - * ## Behavior + * **Details** * - * - Does not mutate the input string; returns a new unescaped string + * - Returns a new unescaped string * - Replaces `~1` with `/` (forward slash) and `~0` with `~` (tilde) - * - Replacement order matters: `~1` is replaced before `~0` to prevent incorrect decoding * - Returns the input unchanged if it contains no escaped sequences * - Empty strings are valid and returned unchanged * + * **Gotchas** + * + * The replacement order matters: `~1` is replaced before `~0` to prevent incorrect decoding. + * * **Example** (Unescaping special characters) * * ```ts - * import { unescapeToken } from "effect/JsonPointer" + * import { JsonPointer } from "effect" * - * unescapeToken("a~1b") // "a/b" - * unescapeToken("c~0d") // "c~d" - * unescapeToken("path~1to~0key") // "path/to~key" + * JsonPointer.unescapeToken("a~1b") // "a/b" + * JsonPointer.unescapeToken("c~0d") // "c~d" + * JsonPointer.unescapeToken("path~1to~0key") // "path/to~key" * ``` * - * ## See also - * - * - {@link escapeToken} - The inverse operation for encoding tokens - * + * @see {@link escapeToken} The inverse operation for encoding tokens + * @category decoding * @since 4.0.0 */ export function unescapeToken(token: string): string { diff --git a/.opencode/node_modules/effect/src/JsonSchema.ts b/.opencode/node_modules/effect/src/JsonSchema.ts index abfe51bc87c196d066a67bc633b5c2502348054b..7def9d323cea4c2d747aebd59164e311bf3a0a94 100644 --- a/.opencode/node_modules/effect/src/JsonSchema.ts +++ b/.opencode/node_modules/effect/src/JsonSchema.ts @@ -1,86 +1,10 @@ /** - * Convert JSON Schema documents between dialects (Draft-07, Draft-2020-12, - * OpenAPI 3.0, OpenAPI 3.1). All dialects are normalized to an internal - * `Document<"draft-2020-12">` representation before optional conversion to - * an output dialect. - * - * ## Mental model - * - * - **JsonSchema** — a plain object with string keys; represents any single - * JSON Schema node. - * - **Dialect** — one of `"draft-07"`, `"draft-2020-12"`, `"openapi-3.1"`, - * or `"openapi-3.0"`. - * - **Document** — a structured container holding a root `schema`, its - * companion `definitions`, and the target `dialect`. Definitions are - * stored separately from the root schema so they can be relocated when - * converting between dialects. - * - **MultiDocument** — same as `Document` but carries multiple root - * schemas (at least one). Useful when generating several schemas that - * share a single definitions pool. - * - **Definitions** — a `Record` keyed by definition - * name. The ref pointer prefix depends on the dialect. - * - **`from*` functions** — parse a raw JSON Schema object into the - * canonical `Document<"draft-2020-12">`. - * - **`to*` functions** — convert from the canonical representation to a - * specific output dialect. - * - * ## Common tasks - * - * - Parse a Draft-07 schema → {@link fromSchemaDraft07} - * - Parse a Draft-2020-12 schema → {@link fromSchemaDraft2020_12} - * - Parse an OpenAPI 3.1 schema → {@link fromSchemaOpenApi3_1} - * - Parse an OpenAPI 3.0 schema → {@link fromSchemaOpenApi3_0} - * - Convert to Draft-07 output → {@link toDocumentDraft07} - * - Convert to OpenAPI 3.1 output → {@link toMultiDocumentOpenApi3_1} - * - Resolve a `$ref` against definitions → {@link resolve$ref} - * - Inline the root `$ref` of a document → {@link resolveTopLevel$ref} - * - * ## Gotchas - * - * - All `from*` functions normalize to `Document<"draft-2020-12">` - * regardless of the input dialect. - * - Unsupported or unrecognized JSON Schema keywords are silently dropped - * during conversion. - * - Draft-07 tuple syntax (`items` as array + `additionalItems`) is - * converted to 2020-12 form (`prefixItems` + `items`), and vice-versa. - * - OpenAPI 3.0 `nullable: true` is expanded into `type` arrays or - * `anyOf` unions. The `nullable` keyword is removed. - * - OpenAPI 3.0 singular `example` is converted to `examples` (array). - * - {@link resolve$ref} only looks up the last segment of the ref path in - * the definitions map; it does not follow arbitrary JSON Pointer paths. - * - * ## Quickstart - * - * **Example** (Parse a Draft-07 schema and convert to Draft-07 output) - * - * ```ts - * import { JsonSchema } from "effect" - * - * const raw: JsonSchema.JsonSchema = { - * type: "object", - * properties: { - * name: { type: "string" } - * }, - * required: ["name"] - * } - * - * // Parse into canonical form - * const doc = JsonSchema.fromSchemaDraft07(raw) - * - * // Convert back to Draft-07 - * const draft07 = JsonSchema.toDocumentDraft07(doc) - * - * console.log(draft07.dialect) // "draft-07" - * console.log(draft07.schema) // { type: "object", properties: { name: { type: "string" } }, required: ["name"] } - * ``` - * - * ## See also - * - * - {@link Document} - * - {@link MultiDocument} - * - {@link fromSchemaDraft07} - * - {@link toDocumentDraft07} - * - {@link resolve$ref} + * Helpers for normalizing and converting JSON Schema and OpenAPI schema + * documents. Supported inputs include JSON Schema Draft-07, Draft 2020-12, + * OpenAPI 3.0, and OpenAPI 3.1; conversions normalize through + * `Document<"draft-2020-12">` before emitting another dialect. The module also + * defines document types, meta-schema constants, OpenAPI component-key helpers, + * and `$ref` resolution utilities. * * @since 4.0.0 */ @@ -92,10 +16,16 @@ import * as Rec from "./Record.ts" /** * A plain object representing a single JSON Schema node. * - * This is an open record type (`[x: string]: unknown`) so it can hold any - * JSON Schema keyword. Most functions in this module accept or return this - * type. + * **When to use** + * + * Use to represent an arbitrary JSON Schema object regardless of dialect. * + * **Details** + * + * This is an open record type (`[x: string]: unknown`) so it can hold any JSON + * Schema keyword. Most functions in this module accept or return this type. + * + * @category models * @since 4.0.0 */ export interface JsonSchema { @@ -105,11 +35,21 @@ export interface JsonSchema { /** * The set of JSON Schema dialects supported by this module. * - * - `"draft-07"` — JSON Schema Draft-07 - * - `"draft-2020-12"` — JSON Schema Draft 2020-12 (canonical internal form) - * - `"openapi-3.1"` — OpenAPI 3.1 (uses Draft 2020-12 as its schema dialect) - * - `"openapi-3.0"` — OpenAPI 3.0 (uses a Draft-04/07 subset with extensions) + * **When to use** + * + * Use as the dialect marker for `JsonSchema` documents when parsing, + * converting, or emitting schemas across the supported formats. + * + * **Details** + * + * Supported values are `"draft-07"` for JSON Schema Draft-07, + * `"draft-2020-12"` for JSON Schema Draft 2020-12 and the canonical internal + * form, `"openapi-3.1"` for OpenAPI 3.1, and `"openapi-3.0"` for OpenAPI 3.0. * + * @see {@link Document} for a single root schema tagged with a dialect + * @see {@link MultiDocument} for multiple root schemas tagged with a dialect + * + * @category models * @since 4.0.0 */ export type Dialect = "draft-07" | "draft-2020-12" | "openapi-3.1" | "openapi-3.0" @@ -117,6 +57,11 @@ export type Dialect = "draft-07" | "draft-2020-12" | "openapi-3.1" | "openapi-3. /** * The JSON Schema primitive type names. * + * **When to use** + * + * Use to restrict a JSON Schema `type` keyword to the supported primitive names. + * + * @category models * @since 4.0.0 */ export type Type = "string" | "number" | "boolean" | "array" | "object" | "null" | "integer" @@ -124,6 +69,21 @@ export type Type = "string" | "number" | "boolean" | "array" | "object" | "null" /** * A record of named JSON Schema definitions, keyed by definition name. * + * **When to use** + * + * Use as the shared lookup table for named JSON Schema nodes that are + * referenced from JSON Schema documents. + * + * **Details** + * + * The map is dialect-neutral. Conversion APIs emit it as `$defs`, + * `definitions`, or `components.schemas` depending on the target format. + * + * @see {@link Document} for a single root schema with definitions + * @see {@link MultiDocument} for multiple root schemas sharing definitions + * @see {@link resolve$ref} for resolving a `$ref` against definitions + * + * @category models * @since 4.0.0 */ export interface Definitions extends Record {} @@ -132,16 +92,19 @@ export interface Definitions extends Record {} * A structured container for a single JSON Schema and its associated * definitions. * - * - Use when you need to carry a root schema together with its - * shared definitions. - * - Use when converting between dialects via the `from*` / `to*` functions. + * **When to use** + * + * Use when you need to carry a root schema together with its shared + * definitions, or when converting between dialects with the `from*` and `to*` + * functions. + * + * **Details** * * The `schema` field holds the root schema *without* the definitions * collection. Root definitions are stored separately in `definitions` and - * referenced via: - * - `#/$defs/` for Draft-2020-12 - * - `#/definitions/` for Draft-07 - * - `#/components/schemas/` for OpenAPI 3.1 and OpenAPI 3.0 + * referenced via `#/$defs/` for Draft-2020-12, `#/definitions/` + * for Draft-07, and `#/components/schemas/` for OpenAPI 3.1 and + * OpenAPI 3.0. * * **Example** (Inspecting a parsed document) * @@ -162,7 +125,7 @@ export interface Definitions extends Record {} * * @see {@link MultiDocument} * @see {@link fromSchemaDraft2020_12} - * + * @category models * @since 4.0.0 */ export interface Document { @@ -173,15 +136,20 @@ export interface Document { /** * Like {@link Document}, but carries multiple root schemas that share a - * single definitions pool. The `schemas` tuple is non-empty (at least one - * element). + * single definitions pool. * - * - Use when generating several schemas (e.g. request body + response body) - * that reference the same set of definitions. + * **When to use** + * + * Use when generating several schemas, such as a request body + * and a response body, that reference the same set of definitions. + * + * **Details** + * + * The `schemas` tuple is non-empty and contains at least one element. * * @see {@link Document} * @see {@link toMultiDocumentOpenApi3_1} - * + * @category models * @since 4.0.0 */ export interface MultiDocument { @@ -191,15 +159,41 @@ export interface MultiDocument { } /** - * The `$schema` meta-schema URI for JSON Schema Draft-07. + * Represents the `$schema` meta-schema URI for JSON Schema Draft-07. + * + * **When to use** * + * Use when constructing a Draft-07 JSON Schema document and you need a stable + * value for the root `$schema` field. + * + * **Details** + * + * The exported value is the literal string + * `http://json-schema.org/draft-07/schema`. + * + * @see {@link META_SCHEMA_URI_DRAFT_2020_12} for the Draft 2020-12 `$schema` URI + * + * @category constants * @since 4.0.0 */ export const META_SCHEMA_URI_DRAFT_07 = "http://json-schema.org/draft-07/schema" /** - * The `$schema` meta-schema URI for JSON Schema Draft 2020-12. + * Represents the `$schema` meta-schema URI for JSON Schema Draft 2020-12. + * + * **When to use** * + * Use when you need to populate the `$schema` field while emitting a JSON + * Schema document that should declare JSON Schema Draft 2020-12. + * + * **Details** + * + * The exported value is the literal string + * `https://json-schema.org/draft/2020-12/schema`. + * + * @see {@link META_SCHEMA_URI_DRAFT_07} for the Draft-07 `$schema` URI + * + * @category constants * @since 4.0.0 */ export const META_SCHEMA_URI_DRAFT_2020_12 = "https://json-schema.org/draft/2020-12/schema" @@ -211,13 +205,21 @@ const RE_COMPONENTS_SCHEMAS = /^#\/components\/schemas(?=\/|$)/ /** * Parses a raw Draft-07 JSON Schema into a `Document<"draft-2020-12">`. * - * - Use when you have a JSON Schema that follows Draft-07 conventions. - * - Converts Draft-07 tuple syntax (`items` as array + `additionalItems`) - * to Draft-2020-12 form (`prefixItems` + `items`). - * - Rewrites `#/definitions/...` refs to `#/$defs/...`. - * - Extracts root-level `definitions` into the `definitions` field. - * - Does not mutate the input. Allocates a new `Document`. - * - Unsupported keywords (e.g. `if`/`then`/`else`, `$id`) are dropped. + * **When to use** + * + * Use when you have a raw JSON Schema object that follows Draft-07 conventions + * and need the canonical Draft-2020-12 document representation. + * + * **Details** + * + * This converts Draft-07 tuple syntax (`items` as array plus + * `additionalItems`) to Draft-2020-12 form (`prefixItems` plus `items`), + * rewrites `#/definitions/...` refs to `#/$defs/...`, and extracts root-level + * `definitions` into the `definitions` field. + * + * **Gotchas** + * + * Unsupported keywords, such as `if`/`then`/`else` and `$id`, are dropped. * * **Example** (Parsing a Draft-07 schema) * @@ -242,7 +244,7 @@ const RE_COMPONENTS_SCHEMAS = /^#\/components\/schemas(?=\/|$)/ * @see {@link fromSchemaDraft2020_12} * @see {@link fromSchemaOpenApi3_0} * @see {@link toDocumentDraft07} - * + * @category decoding * @since 4.0.0 */ export function fromSchemaDraft07(js: JsonSchema): Document<"draft-2020-12"> { @@ -356,10 +358,14 @@ export function fromSchemaDraft07(js: JsonSchema): Document<"draft-2020-12"> { /** * Parses a raw Draft-2020-12 JSON Schema into a `Document<"draft-2020-12">`. * - * - Use when you already have a schema in Draft-2020-12 format. - * - Separates `$defs` from the root schema into the `definitions` field. - * - Does not mutate the input. Allocates a new `Document`. - * - Unlike {@link fromSchemaDraft07}, this performs no keyword rewriting. + * **When to use** + * + * Use when you already have a raw JSON Schema object in Draft-2020-12 format. + * + * **Details** + * + * This separates `$defs` from the root schema into the `definitions` field. + * Unlike {@link fromSchemaDraft07}, this performs no keyword rewriting. * * **Example** (Parsing a Draft-2020-12 schema) * @@ -379,7 +385,7 @@ export function fromSchemaDraft07(js: JsonSchema): Document<"draft-2020-12"> { * * @see {@link fromSchemaDraft07} * @see {@link fromSchemaOpenApi3_1} - * + * @category decoding * @since 4.0.0 */ export function fromSchemaDraft2020_12(js: JsonSchema): Document<"draft-2020-12"> { @@ -394,10 +400,15 @@ export function fromSchemaDraft2020_12(js: JsonSchema): Document<"draft-2020-12" /** * Parses a raw OpenAPI 3.1 JSON Schema into a `Document<"draft-2020-12">`. * - * - Use when consuming schemas from an OpenAPI 3.1 specification. - * - Rewrites `#/components/schemas/...` refs to `#/$defs/...`. - * - Delegates to {@link fromSchemaDraft2020_12} after rewriting refs. - * - Does not mutate the input. Allocates a new `Document`. + * **When to use** + * + * Use when you need to consume raw JSON Schema objects from an OpenAPI 3.1 + * specification. + * + * **Details** + * + * This rewrites `#/components/schemas/...` refs to `#/$defs/...`, then delegates + * to {@link fromSchemaDraft2020_12}. * * **Example** (Parsing an OpenAPI 3.1 schema) * @@ -418,7 +429,7 @@ export function fromSchemaDraft2020_12(js: JsonSchema): Document<"draft-2020-12" * * @see {@link fromSchemaOpenApi3_0} * @see {@link toMultiDocumentOpenApi3_1} - * + * @category decoding * @since 4.0.0 */ export function fromSchemaOpenApi3_1(js: JsonSchema): Document<"draft-2020-12"> { @@ -429,12 +440,17 @@ export function fromSchemaOpenApi3_1(js: JsonSchema): Document<"draft-2020-12"> /** * Parses a raw OpenAPI 3.0 JSON Schema into a `Document<"draft-2020-12">`. * - * - Use when consuming schemas from an OpenAPI 3.0 specification. - * - Handles OpenAPI 3.0 extensions: `nullable`, singular `example`, - * boolean `exclusiveMinimum`/`exclusiveMaximum`. - * - Normalizes the schema to Draft-07 first, then converts to - * Draft-2020-12 via {@link fromSchemaDraft07}. - * - Does not mutate the input. Allocates a new `Document`. + * **When to use** + * + * Use when you need to consume raw JSON Schema objects from an OpenAPI 3.0 + * specification. + * + * **Details** + * + * This handles OpenAPI 3.0 extensions, including `nullable`, singular + * `example`, and boolean `exclusiveMinimum` or `exclusiveMaximum`. It + * normalizes the schema to Draft-07 first, then converts to Draft-2020-12 via + * {@link fromSchemaDraft07}. * * **Example** (Parsing an OpenAPI 3.0 nullable schema) * @@ -453,7 +469,7 @@ export function fromSchemaOpenApi3_1(js: JsonSchema): Document<"draft-2020-12"> * * @see {@link fromSchemaOpenApi3_1} * @see {@link fromSchemaDraft07} - * + * @category decoding * @since 4.0.0 */ export function fromSchemaOpenApi3_0(schema: JsonSchema): Document<"draft-2020-12"> { @@ -464,13 +480,21 @@ export function fromSchemaOpenApi3_0(schema: JsonSchema): Document<"draft-2020-1 /** * Converts a `Document<"draft-2020-12">` to a `Document<"draft-07">`. * - * - Use when you need to output a schema in Draft-07 format. - * - Rewrites `#/$defs/...` refs to `#/definitions/...`. - * - Converts Draft-2020-12 tuple syntax (`prefixItems` + `items`) to - * Draft-07 form (`items` as array + `additionalItems`). - * - Converts both the root schema and all definitions. - * - Does not mutate the input. Allocates a new `Document`. - * - Unsupported Draft-2020-12 keywords are dropped. + * **When to use** + * + * Use when you need to output a canonical JSON Schema document in Draft-07 + * format. + * + * **Details** + * + * This rewrites `#/$defs/...` refs to `#/definitions/...`, converts + * Draft-2020-12 tuple syntax (`prefixItems` plus `items`) to Draft-07 form + * (`items` as array plus `additionalItems`), and converts both the root schema + * and all definitions. + * + * **Gotchas** + * + * Unsupported Draft-2020-12 keywords are dropped. * * **Example** (Converting to Draft-07) * @@ -491,7 +515,7 @@ export function fromSchemaOpenApi3_0(schema: JsonSchema): Document<"draft-2020-1 * * @see {@link fromSchemaDraft07} * @see {@link toMultiDocumentOpenApi3_1} - * + * @category encoding * @since 4.0.0 */ export function toDocumentDraft07(document: Document<"draft-2020-12">): Document<"draft-07"> { @@ -607,13 +631,18 @@ function toSchemaDraft07(schema: JsonSchema): JsonSchema { * Converts a `MultiDocument<"draft-2020-12">` to a * `MultiDocument<"openapi-3.1">`. * - * - Use when generating an OpenAPI 3.1 specification from internal schemas. - * - Rewrites `#/$defs/...` refs to `#/components/schemas/...`. - * - Sanitizes definition keys to match the OpenAPI component key pattern - * (`^[a-zA-Z0-9.\-_]+$`), replacing invalid characters with `_`. - * - Updates all `$ref` pointers to use the sanitized keys. - * - Converts all schemas and definitions in the multi-document. - * - Does not mutate the input. Allocates a new `MultiDocument`. + * **When to use** + * + * Use when you need to emit an OpenAPI 3.1 multi-document from canonical JSON + * Schema documents. + * + * **Details** + * + * This rewrites `#/$defs/...` refs to `#/components/schemas/...`, sanitizes + * definition keys to match the OpenAPI component key pattern + * (`^[a-zA-Z0-9.\-_]+$`) by replacing invalid characters with `_`, updates all + * `$ref` pointers to use the sanitized keys, and converts all schemas and + * definitions in the multi-document. * * **Example** (Converting to OpenAPI 3.1) * @@ -635,7 +664,7 @@ function toSchemaDraft07(schema: JsonSchema): JsonSchema { * * @see {@link toDocumentDraft07} * @see {@link MultiDocument} - * + * @category encoding * @since 4.0.0 */ export function toMultiDocumentOpenApi3_1(multiDocument: MultiDocument<"draft-2020-12">): MultiDocument<"openapi-3.1"> { @@ -827,12 +856,19 @@ function widen_type(node: Record): Record { * Resolves a `$ref` string by looking up the last path segment in a * definitions map. * - * - Use when you need to dereference a `$ref` pointer to get the - * actual schema it points to. - * - Only resolves the final segment of the ref path (e.g. `"User"` from - * `"#/$defs/User"`); does not follow arbitrary JSON Pointer paths. - * - Returns `undefined` if the definition is not found. - * - Does not mutate anything. Pure function. + * **When to use** + * + * Use when you need to dereference a `$ref` pointer to get the JSON Schema + * object it points to. + * + * **Details** + * + * This only resolves the final segment of the ref path, such as `"User"` from + * `"#/$defs/User"`. It returns `undefined` if the definition is not found. + * + * **Gotchas** + * + * This function does not follow arbitrary JSON Pointer paths. * * **Example** (Resolving a $ref) * @@ -852,7 +888,7 @@ function widen_type(node: Record): Record { * * @see {@link resolveTopLevel$ref} * @see {@link Definitions} - * + * @category getters * @since 4.0.0 */ export function resolve$ref($ref: string, definitions: Definitions): JsonSchema | undefined { @@ -867,15 +903,17 @@ export function resolve$ref($ref: string, definitions: Definitions): JsonSchema } /** - * If the root schema of a document is a `$ref`, resolves it against the - * document's definitions and returns a new document with the inlined - * schema. Returns the original document unchanged if the root schema is - * not a `$ref` or if the referenced definition is not found. + * Resolves a document whose root schema is a top-level `$ref`. + * + * **When to use** + * + * Use when you need to dereference a top-level `$ref` before inspecting the + * root JSON Schema object's properties directly. * - * - Use to dereference a top-level `$ref` before inspecting the root - * schema's properties directly. - * - Does not mutate the input. Returns the same object if no change is - * needed, or a shallow copy with the resolved schema. + * **Details** + * + * This returns the same object if no change is needed, or a shallow copy with + * the resolved schema. * * **Example** (Resolving a top-level $ref) * @@ -896,7 +934,7 @@ export function resolve$ref($ref: string, definitions: Definitions): JsonSchema * * @see {@link resolve$ref} * @see {@link Document} - * + * @category transforming * @since 4.0.0 */ export function resolveTopLevel$ref(document: Document<"draft-2020-12">): Document<"draft-2020-12"> { diff --git a/.opencode/node_modules/effect/src/Latch.ts b/.opencode/node_modules/effect/src/Latch.ts index fba0b77134578831656f0e41ed0cf27ac4ea798d..4392a9e1b532abc69c89dbebe0358d97f47d637a 100644 --- a/.opencode/node_modules/effect/src/Latch.ts +++ b/.opencode/node_modules/effect/src/Latch.ts @@ -1,13 +1,33 @@ /** - * @since 3.8.0 + * Reusable synchronization primitives for coordinating fibers. A `Latch` is + * either open or closed: when it is closed, `await` and `whenOpen` suspend + * until the latch opens or the current waiters are released. The module + * includes effectful and synchronous constructors plus helpers to open, release, + * close, wait, and gate effects behind the latch. + * + * @since 4.0.0 */ import type * as Effect from "./Effect.ts" import * as internal from "./internal/effect.ts" /** - * @category models - * @since 3.8.0 - * @example + * A reusable coordination primitive that lets fibers wait until they are + * released by the latch. + * + * **When to use** + * + * Use to coordinate fibers that must wait for an explicit open or release + * signal before continuing. + * + * **Details** + * + * A closed latch causes `await` and `whenOpen` to suspend. `open` opens the + * latch and releases current and future waiters, `release` releases only + * current waiters without opening it, and `close` makes future waiters suspend + * again. + * + * **Example** (Coordinating fibers with a latch) + * * ```ts * import { Effect, Latch } from "effect" * @@ -21,34 +41,94 @@ import * as internal from "./internal/effect.ts" * return "Latch was opened!" * }) * ``` + * + * @see {@link make} for creating a latch inside Effect code + * @see {@link open} for releasing current and future waiters + * @see {@link release} for releasing only the current waiters + * + * @category models + * @since 4.0.0 */ export interface Latch { - /** open the latch, releasing all fibers waiting on it */ + /** + * Opens the latch, releasing all fibers waiting on it. + * + * **When to use** + * + * Use to let current and future waiters continue. + */ readonly open: Effect.Effect - /** open the latch, releasing all fibers waiting on it */ + + /** + * Opens the latch synchronously, releasing all fibers waiting on it. + * + * **When to use** + * + * Use when synchronous code must open the latch immediately. + */ openUnsafe(this: Latch): boolean - /** release all fibers waiting on the latch, without opening it */ + + /** + * Releases all fibers currently waiting on the latch without opening it. + * + * **When to use** + * + * Use to let current waiters continue while future waiters still suspend. + */ readonly release: Effect.Effect - /** wait for the latch to be opened */ + + /** + * Waits for the latch to be opened or released. + * + * **When to use** + * + * Use to suspend until the latch allows the current fiber to continue. + */ readonly await: Effect.Effect - /** close the latch */ + + /** + * Closes the latch so future waiters suspend again. + * + * **When to use** + * + * Use to re-enable waiting after a latch has been opened. + */ readonly close: Effect.Effect - /** close the latch */ + + /** + * Closes the latch synchronously so future waiters suspend again. + * + * **When to use** + * + * Use when synchronous code must close the latch immediately. + */ closeUnsafe(this: Latch): boolean - /** only run the given effect when the latch is open */ + + /** + * Runs the given effect only after the latch allows waiting fibers to + * continue. + * + * **When to use** + * + * Use to gate an effect behind the latch signal. + */ whenOpen(self: Effect.Effect): Effect.Effect } /** - * Creates a new Latch unsafely. + * Creates a `Latch` synchronously, outside of `Effect`. + * + * **When to use** * - * **Previously Known As** + * Use when you need to allocate a `Latch` synchronously outside an Effect + * workflow. * - * This API replaces the following from Effect 3.x: + * **Details** * - * - `Effect.makeLatchUnsafe` + * The latch starts closed by default; pass `true` to create it open. + * + * **Example** (Creating a latch unsafely) * - * @example * ```ts * import { Effect, Latch } from "effect" * @@ -69,21 +149,26 @@ export interface Latch { * const program = Effect.all([waiter, opener]) * ``` * + * @see {@link make} for creating a latch inside Effect code + * * @category constructors - * @since 3.8.0 + * @since 4.0.0 */ export const makeUnsafe: (open?: boolean | undefined) => Latch = internal.makeLatchUnsafe /** - * Creates a new Latch. + * Creates a `Latch` inside `Effect`. * - * **Previously Known As** + * **When to use** * - * This API replaces the following from Effect 3.x: + * Use to create a latch for coordinating fibers inside Effect code. * - * - `Effect.makeLatch` + * **Details** + * + * The latch starts closed by default; pass `true` to create it open. + * + * **Example** (Creating a latch) * - * @example * ```ts * import { Effect, Latch } from "effect" * @@ -106,13 +191,27 @@ export const makeUnsafe: (open?: boolean | undefined) => Latch = internal.makeLa * }) * ``` * + * @see {@link makeUnsafe} for synchronous allocation outside Effect code + * * @category constructors - * @since 3.8.0 + * @since 4.0.0 */ export const make: (open?: boolean | undefined) => Effect.Effect = internal.makeLatch /** - * Opens the latch, releasing all fibers waiting on it. + * Opens the latch and releases fibers waiting on it. + * + * **When to use** + * + * Use to open a latch and release all fibers that are waiting on it. + * + * **Details** + * + * The returned effect succeeds with `true` when this call changed the latch + * from closed to open, or `false` if it was already open. + * + * @see {@link openUnsafe} for a synchronous variant + * @see {@link release} to release waiting fibers without opening the latch * * @category combinators * @since 4.0.0 @@ -120,7 +219,22 @@ export const make: (open?: boolean | undefined) => Effect.Effect = intern export const open = (self: Latch): Effect.Effect => self.open /** - * Opens the latch, releasing all fibers waiting on it. + * Opens the latch synchronously and releases fibers waiting on it. + * + * **When to use** + * + * Use when you need synchronous code to open a latch immediately and release + * the fibers waiting on it. + * + * **Details** + * + * Returns `true` when this call changed the latch from closed to open, or + * `false` if it was already open. This unsafe variant performs the state + * change immediately instead of returning an `Effect`. + * + * @see {@link open} for the effectful variant + * @see {@link release} to release waiting fibers without opening the latch + * @see {@link closeUnsafe} for the synchronous inverse operation * * @category unsafe * @since 4.0.0 @@ -128,7 +242,20 @@ export const open = (self: Latch): Effect.Effect => self.open export const openUnsafe = (self: Latch): boolean => self.openUnsafe() /** - * Releases all fibers waiting on the latch, without opening it. + * Releases the fibers currently waiting on a closed latch without opening it. + * + * **When to use** + * + * Use to let the fibers currently waiting on a latch proceed while keeping the + * latch closed for future waiters. + * + * **Details** + * + * The returned effect succeeds with `true` when release was requested while + * the latch was closed, or `false` if the latch was already open. Future + * waiters still suspend until the latch is opened or released again. + * + * @see {@link open} for opening the latch for current and future waiters * * @category combinators * @since 4.0.0 @@ -141,6 +268,25 @@ export { /** * Waits for the latch to be opened. * + * **When to use** + * + * Use to suspend the current fiber until the latch is opened or the current + * set of waiters is released. + * + * **Details** + * + * Awaiting an already open latch completes immediately. Awaiting a closed + * latch suspends until `open` or `release` resumes the waiters. + * + * **Gotchas** + * + * `release` can resume current waiters without opening the latch, so later + * waiters may still suspend. + * + * @see {@link open} for opening the latch for current and future waiters + * @see {@link release} for resuming current waiters without opening the latch + * @see {@link whenOpen} for waiting before running another effect + * * @category getters * @since 4.0.0 */ @@ -148,7 +294,20 @@ export { } /** - * Closes the latch. + * Closes the latch so future `await` and `whenOpen` calls suspend. + * + * **When to use** + * + * Use to re-enable waiting on a latch after it was opened, so later `await` + * and `whenOpen` calls suspend again. + * + * **Details** + * + * The returned effect succeeds with `true` when this call changed the latch + * from open to closed, or `false` if it was already closed. + * + * @see {@link closeUnsafe} for a synchronous variant + * @see {@link open} for opening the latch for current and future waiters * * @category combinators * @since 4.0.0 @@ -156,7 +315,23 @@ export { export const close = (self: Latch): Effect.Effect => self.close /** - * Closes the latch. + * Closes the latch synchronously so future `await` and `whenOpen` calls + * suspend. + * + * **When to use** + * + * Use to close a latch synchronously when the state change must happen outside + * an `Effect`. + * + * **Details** + * + * Returns `true` when this call changed the latch from open to closed, or + * `false` if it was already closed. This unsafe variant performs the state + * change immediately instead of returning an `Effect`. + * + * @see {@link close} for the effectful variant + * @see {@link openUnsafe} to synchronously open the latch and release waiting + * fibers * * @category unsafe * @since 4.0.0 @@ -164,21 +339,69 @@ export const close = (self: Latch): Effect.Effect => self.close export const closeUnsafe = (self: Latch): boolean => self.closeUnsafe() /** - * Runs the given effect only when the latch is open. + * Waits on the latch, then runs the provided effect. + * + * **When to use** + * + * Use to gate another effect so it starts only after the latch is opened or + * the current waiters are released. + * + * **Details** + * + * If the latch is open, the effect runs immediately. If it is closed, the + * returned effect suspends until the latch is opened or the current waiters are + * released. The provided effect's success, failure, and requirements are + * preserved. + * + * @see `await` for waiting without running another effect + * @see {@link open} for opening the latch for current and future waiters + * @see {@link release} for resuming current waiters without opening the latch * * @category combinators * @since 4.0.0 */ export const whenOpen: { /** - * Runs the given effect only when the latch is open. + * Waits on the latch, then runs the provided effect. + * + * **When to use** + * + * Use to gate another effect so it starts only after the latch is opened or + * the current waiters are released. + * + * **Details** + * + * If the latch is open, the effect runs immediately. If it is closed, the + * returned effect suspends until the latch is opened or the current waiters are + * released. The provided effect's success, failure, and requirements are + * preserved. + * + * @see `await` for waiting without running another effect + * @see {@link open} for opening the latch for current and future waiters + * @see {@link release} for resuming current waiters without opening the latch * * @category combinators * @since 4.0.0 */ (self: Latch): (effect: Effect.Effect) => Effect.Effect /** - * Runs the given effect only when the latch is open. + * Waits on the latch, then runs the provided effect. + * + * **When to use** + * + * Use to gate another effect so it starts only after the latch is opened or + * the current waiters are released. + * + * **Details** + * + * If the latch is open, the effect runs immediately. If it is closed, the + * returned effect suspends until the latch is opened or the current waiters are + * released. The provided effect's success, failure, and requirements are + * preserved. + * + * @see `await` for waiting without running another effect + * @see {@link open} for opening the latch for current and future waiters + * @see {@link release} for resuming current waiters without opening the latch * * @category combinators * @since 4.0.0 diff --git a/.opencode/node_modules/effect/src/Layer.ts b/.opencode/node_modules/effect/src/Layer.ts index 228c906267ec1ba416b89d8dd68879875fda9013..8b3934f3dd38cd2fb9d1f7a2d709406d2286d1a4 100644 --- a/.opencode/node_modules/effect/src/Layer.ts +++ b/.opencode/node_modules/effect/src/Layer.ts @@ -1,19 +1,11 @@ /** - * A `Layer` 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`. + * Builds and wires services for Effect applications. * - * 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. + * A `Layer` describes how to acquire one or more services, which + * services are required to build them, and which errors can occur during + * acquisition. Layers can manage scoped resources, memoize shared services, + * combine with other layers, provide services to effects or streams, and attach + * error handling, tracing, or lifecycle hooks. * * @since 2.0.0 */ @@ -42,15 +34,22 @@ import type * as Unify from "./Unify.ts" const TypeId = "~effect/Layer" /** - * A Layer describes how to build one or more services for dependency injection. + * A `Layer` describes how to build one or more services for dependency injection. * - * A Layer represents: - * - ROut: The services this layer provides - * - E: The possible errors during layer construction - * - RIn: The services this layer requires as dependencies + * **When to use** + * + * Use to model construction of application services for dependency injection, + * especially when services have dependencies, can fail during construction, or + * need scoped setup and release. + * + * **Details** + * + * A `Layer` represents `ROut` as the services this layer + * provides, `E` as the possible errors during layer construction, and `RIn` as + * the services this layer requires as dependencies. * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface Layer extends Variance, Pipeable { /** @internal */ @@ -61,8 +60,16 @@ export interface Layer extends Variance } /** - * @since 4.0.0 + * Type-level hook that allows `Layer` values to participate in `Unify` + * inference. + * + * **Details** + * + * This is used by Effect's pipe and unification machinery to preserve the + * provided services, error, and requirements of a `Layer`. + * * @category models + * @since 4.0.0 */ export interface LayerUnify { Layer?: () => A[Unify.typeSymbol] extends Layer | infer _ ? Layer< @@ -74,16 +81,19 @@ export interface LayerUnify { } /** - * @since 4.0.0 + * Type-level marker used by `Unify` for `Layer` types that should be ignored + * during unification. + * * @category models + * @since 4.0.0 */ export interface LayerUnifyIgnore {} /** * The variance interface for Layer type parameters. * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface Variance { readonly [TypeId]: { @@ -93,13 +103,26 @@ export interface Variance { } } /** - * A constraint interface for working with any Layer type. + * A type-level constraint for working with any `Layer` type. + * + * **When to use** + * + * Use to constrain generic parameters or layer collections to any `Layer` + * value while preserving its provided, error, and required service types for + * inference. + * + * **Details** * - * This interface is used to constrain generic types to Layer types - * without specifying exact type parameters. + * This interface is used to constrain generic types to `Layer` values without + * specifying exact type parameters. * + * @see {@link Layer} for the concrete layer interface + * @see {@link Services} for extracting required services from a layer type + * @see {@link Error} for extracting construction errors from a layer type + * @see {@link Success} for extracting provided services from a layer type + * + * @category utility types * @since 3.9.0 - * @category type-level */ export interface Any { readonly [TypeId]: { @@ -109,40 +132,68 @@ export interface Any { } } /** - * Extracts the service dependencies (RIn) from a Layer type. + * Extracts the service requirements (`RIn`) from a `Layer` type. * - * @since 2.0.0 - * @category type-level + * **When to use** + * + * Use to derive the dependency requirements of a generic or inferred `Layer` + * without restating its `RIn` type parameter. + * + * @see {@link Success} for extracting the services provided by the same `Layer` + * @see {@link Error} for extracting the construction failure type from the same `Layer` + * + * @category utility types + * @since 4.0.0 */ export type Services = T extends infer L ? L extends Layer ? _RIn : never : never /** - * Extracts the error type (E) from a Layer type. + * Extracts the error type (`E`) from a `Layer` type. + * + * **When to use** + * + * Use to derive a layer construction error type for helper types, wrappers, or + * APIs that preserve a layer failure channel. * + * @see {@link Success} for extracting the services provided by the same `Layer` + * @see {@link Services} for extracting the dependency requirements of the same `Layer` + * + * @category utility types * @since 2.0.0 - * @category type-level */ export type Error = T extends Layer ? _E : never /** - * Extracts the service output type (ROut) from a Layer type. + * Extracts the service output type (`ROut`) from a `Layer` type. + * + * **When to use** + * + * Use to derive the services provided by an existing or generic `Layer` without + * restating its `ROut` type parameter. + * + * @see {@link Error} for extracting the layer construction error type instead + * @see {@link Services} for extracting the layer input service requirements instead * + * @category utility types * @since 2.0.0 - * @category type-level */ export type Success = T extends Layer ? _ROut : never const MemoMapTypeId = "~effect/Layer/MemoMap" /** - * A MemoMap is used to memoize layer construction and ensure sharing of layers. + * A `MemoMap` is used to memoize layer construction and ensure sharing of + * layers. * - * The MemoMap prevents duplicate construction of the same layer instance, + * **Details** + * + * The `MemoMap` prevents duplicate construction of the same layer instance, * enabling efficient resource sharing across layer dependencies. * - * @example + * **Example** (Sharing layer construction with a memo map) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -153,7 +204,7 @@ const MemoMapTypeId = "~effect/Layer/MemoMap" * const memoMap = yield* Layer.makeMemoMap * const scope = yield* Effect.scope * - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) * const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) @@ -162,11 +213,15 @@ const MemoMapTypeId = "~effect/Layer/MemoMap" * }) * ``` * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface MemoMap { readonly [MemoMapTypeId]: typeof MemoMapTypeId + readonly get: ( + layer: Layer, + scope: Scope.Scope + ) => Effect, E, RIn> | undefined readonly getOrElseMemoize: ( layer: Layer, scope: Scope.Scope, @@ -174,18 +229,36 @@ export interface MemoMap { ) => Effect, E, RIn> } +type MemoMapEntry = { + observers: number + effect: Effect, any> + readonly finalizer: (exit: Exit.Exit) => Effect +} + +const memoMapReuse = ( + entry: MemoMapEntry, + scope: Scope.Scope +): Effect, E, RIn> => { + entry.observers++ + return internalEffect.andThen( + internalEffect.scopeAddFinalizerExit(scope, (exit) => entry.finalizer(exit)), + entry.effect + ) +} + /** * Returns `true` if the specified value is a `Layer`, `false` otherwise. * - * @example + * **Example** (Checking whether a value is a layer) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) * const notALayer = { someProperty: "value" } @@ -194,8 +267,8 @@ export interface MemoMap { * console.log(Layer.isLayer(notALayer)) // false * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export const isLayer = (u: unknown): u is Layer => hasProperty(u, TypeId) @@ -222,14 +295,18 @@ const fromBuildUnsafe = ( } /** - * Constructs a Layer from a function that uses a `MemoMap` and `Scope` to build the layer. + * Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to + * build the layer. + * + * **Details** * * The function receives a `MemoMap` for memoization and a `Scope` for resource management. * A child scope is created, and if the build fails, the child scope is closed. * - * @example + * **Example** (Constructing a layer from a build function) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -244,8 +321,8 @@ const fromBuildUnsafe = ( * ) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fromBuild = ( build: ( @@ -262,15 +339,18 @@ export const fromBuild = ( }) /** - * Constructs a Layer from a function that uses a `MemoMap` and `Scope` to build the layer, - * with automatic memoization. + * Constructs a `Layer` from a function that uses a `MemoMap` and `Scope` to + * build the layer, with automatic memoization. + * + * **Details** * * This is similar to `fromBuild` but provides automatic memoization of the layer construction. * The layer will be memoized based on the provided `MemoMap`. * - * @example + * **Example** (Memoizing layer construction) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -285,8 +365,8 @@ export const fromBuild = ( * ) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fromBuildMemo = ( build: ( @@ -298,62 +378,81 @@ export const fromBuildMemo = ( return self } +const memoMapBuild = ( + memoMap: MemoMapImpl, + layer: Layer, + scope: Scope.Scope, + build: (memoMap: MemoMap, scope: Scope.Scope) => Effect, E, RIn> +): Effect, E, RIn> => { + const layerScope = Scope.makeUnsafe() + const deferred = Deferred.makeUnsafe, E>() + const entry: MemoMapEntry = { + observers: 1, + effect: Deferred.await(deferred), + finalizer: (exit: Exit.Exit) => + internalEffect.suspend(() => { + entry.observers-- + if (entry.observers === 0) { + memoMap.map.delete(layer) + return Scope.close(layerScope, exit) + } + return internalEffect.void + }) + } + memoMap.map.set(layer, entry) + return internalEffect.scopeAddFinalizerExit(scope, entry.finalizer).pipe( + internalEffect.flatMap(() => build(memoMap, layerScope)), + internalEffect.onExit((exit) => { + entry.effect = exit + return Deferred.done(deferred, exit) + }) + ) +} + class MemoMapImpl implements MemoMap { get [MemoMapTypeId](): typeof MemoMapTypeId { return MemoMapTypeId } - readonly map = new Map, { - observers: number - effect: Effect, any> - readonly finalizer: (exit: Exit.Exit) => Effect - }>() + readonly parent: MemoMap | undefined + + constructor(parent?: MemoMap) { + this.parent = parent + } + + readonly map = new Map, MemoMapEntry>() + + get( + layer: Layer, + scope: Scope.Scope + ): Effect, E, RIn> | undefined { + const local = this.map.get(layer) + if (local) { + return memoMapReuse(local, scope) + } + return this.parent?.get(layer, scope) + } getOrElseMemoize( layer: Layer, scope: Scope.Scope, build: (memoMap: MemoMap, scope: Scope.Scope) => Effect, E, RIn> ): Effect, E, RIn> { - if (this.map.has(layer)) { - const entry = this.map.get(layer)! - entry.observers++ - return internalEffect.andThen( - internalEffect.scopeAddFinalizerExit(scope, (exit) => entry.finalizer(exit)), - entry.effect - ) - } - const layerScope = Scope.makeUnsafe() - const deferred = Deferred.makeUnsafe, E>() - const entry = { - observers: 1, - effect: Deferred.await(deferred), - finalizer: (exit: Exit.Exit) => - internalEffect.suspend(() => { - entry.observers-- - if (entry.observers === 0) { - this.map.delete(layer) - return Scope.close(layerScope, exit) - } - return internalEffect.void - }) + const existing = this.get(layer, scope) + if (existing) { + return existing } - this.map.set(layer, entry) - return internalEffect.scopeAddFinalizerExit(scope, entry.finalizer).pipe( - internalEffect.flatMap(() => build(this, layerScope)), - internalEffect.onExit((exit) => { - entry.effect = exit - return Deferred.done(deferred, exit) - }) - ) + return memoMapBuild(this, layer, scope, build) } } /** - * Constructs a `MemoMap` that can be used to build additional layers. + * Constructs a `MemoMap` synchronously so it can be used to build additional layers. + * + * **Example** (Creating a memo map unsafely) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -364,7 +463,7 @@ class MemoMapImpl implements MemoMap { * const memoMap = Layer.makeMemoMapUnsafe() * const scope = yield* Effect.scope * - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) * const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) @@ -373,17 +472,37 @@ class MemoMapImpl implements MemoMap { * }) * ``` * - * @since 4.0.0 * @category memo map + * @since 4.0.0 */ export const makeMemoMapUnsafe = (): MemoMap => new MemoMapImpl() /** - * Constructs a `MemoMap` that can be used to build additional layers. + * Constructs a child `MemoMap` synchronously, allowing it to reuse layers + * already memoized in the parent while isolating any new layer allocations to + * the child map. + * + * **When to use** + * + * Use to synchronously fork a memo map for manual layer building when child + * builds should see parent memoized layers without writing newly built layers + * back to the parent. + * + * @see {@link forkMemoMap} for allocating the child memo map inside `Effect` + * @see {@link makeMemoMapUnsafe} for creating a root memo map without a parent + * + * @category memo map + * @since 4.0.0 + */ +export const forkMemoMapUnsafe = (parent: MemoMap): MemoMap => new MemoMapImpl(parent) + +/** + * Constructs a `MemoMap` effectfully so it can be used to build additional layers. + * + * **Example** (Creating a memo map in an effect) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -394,7 +513,7 @@ export const makeMemoMapUnsafe = (): MemoMap => new MemoMapImpl() * const memoMap = yield* Layer.makeMemoMap * const scope = yield* Effect.scope * - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) * const context = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) @@ -403,19 +522,47 @@ export const makeMemoMapUnsafe = (): MemoMap => new MemoMapImpl() * }) * ``` * - * @since 2.0.0 * @category memo map + * @since 2.0.0 */ export const makeMemoMap: Effect = internalEffect.sync(makeMemoMapUnsafe) /** - * A service reference for the current `MemoMap` used in layer construction. + * Constructs a child `MemoMap` effectfully, allowing it to reuse layers already + * memoized in the parent while isolating any new layer allocations to the child + * map. * - * This service provides access to the current memoization map during layer building, - * allowing layers to share memoized results. + * **When to use** + * + * Use when a layer build should inherit already memoized layers from an + * existing `MemoMap` while keeping newly memoized layers out of the parent map. + * + * @see {@link makeMemoMap} for creating a root memo map in an `Effect` + * @see {@link forkMemoMapUnsafe} for the synchronous constructor variant + * @see {@link buildWithMemoMap} for building layers with an explicit memo map + * + * @category memo map + * @since 4.0.0 + */ +export const forkMemoMap = (parent: MemoMap): Effect => internalEffect.sync(() => forkMemoMapUnsafe(parent)) + +/** + * Context service for the current `MemoMap` used in layer construction. + * + * **When to use** + * + * Use when building custom layer operations that need to access the current + * memoization map from the fiber context. + * + * **Details** + * + * This service wraps a `MemoMap` as a `Context.Service`, making it available + * for dependency injection during layer construction. + * + * @see {@link MemoMap} the memoization map type wrapped by this service * - * @since 3.13.0 * @category models + * @since 3.13.0 */ export class CurrentMemoMap extends Context.Service()("effect/Layer/CurrentMemoMap") { static getOrCreate: (self: Context.Context) => MemoMap = Context.getOrElse( @@ -428,9 +575,10 @@ export class CurrentMemoMap extends Context.Service()(" * Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize * the layer construction. * - * @example + * **Example** (Building layers with an explicit memo map) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -446,13 +594,13 @@ export class CurrentMemoMap extends Context.Service()(" * const scope = yield* Effect.scope * * // Build database layer with memoization - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) * const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) * * // Build logger layer with same memoization (reuses memo if same layer) - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(msg))) * }) * const loggerContext = yield* Layer.buildWithMemoMap( @@ -468,17 +616,18 @@ export class CurrentMemoMap extends Context.Service()(" * }) * ``` * - * @since 2.0.0 * @category memo map + * @since 2.0.0 */ export const buildWithMemoMap: { /** * Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize * the layer construction. * - * @example + * **Example** (Building layers with an explicit memo map) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -494,13 +643,13 @@ export const buildWithMemoMap: { * const scope = yield* Effect.scope * * // Build database layer with memoization - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) * const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) * * // Build logger layer with same memoization (reuses memo if same layer) - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(msg))) * }) * const loggerContext = yield* Layer.buildWithMemoMap( @@ -516,17 +665,18 @@ export const buildWithMemoMap: { * }) * ``` * - * @since 2.0.0 * @category memo map + * @since 2.0.0 */ (memoMap: MemoMap, scope: Scope.Scope): (self: Layer) => Effect, E, RIn> /** * Builds a layer into an `Effect` value, using the specified `MemoMap` to memoize * the layer construction. * - * @example + * **Example** (Building layers with an explicit memo map) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -542,13 +692,13 @@ export const buildWithMemoMap: { * const scope = yield* Effect.scope * * // Build database layer with memoization - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) * const dbContext = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) * * // Build logger layer with same memoization (reuses memo if same layer) - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(msg))) * }) * const loggerContext = yield* Layer.buildWithMemoMap( @@ -564,8 +714,8 @@ export const buildWithMemoMap: { * }) * ``` * - * @since 2.0.0 * @category memo map + * @since 2.0.0 */ (self: Layer, memoMap: MemoMap, scope: Scope.Scope): Effect, E, RIn> } = dual(3, ( @@ -582,9 +732,10 @@ export const buildWithMemoMap: { /** * Builds a layer into a scoped value. * - * @example + * **Example** (Building a layer into a context) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -592,7 +743,7 @@ export const buildWithMemoMap: { * * // Build a layer to get its services * const program = Effect.gen(function*() { - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) * @@ -606,8 +757,8 @@ export const buildWithMemoMap: { * }) * ``` * - * @since 2.0.0 * @category destructors + * @since 2.0.0 */ export const build = ( self: Layer @@ -621,15 +772,22 @@ export const 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. + * Builds a layer using an explicit scope. + * + * **When to use** + * + * Use to control the lifetime of layer resources with a scope supplied by the + * caller. + * + * **Details** + * + * Resources created by the layer are released when the supplied scope is + * closed, unless a resource extends its own scope. + * + * **Example** (Building a layer with an explicit scope) * - * @example * ```ts - * import { Effect, Layer, Scope, Context } from "effect" + * import { Context, Effect, Layer, Scope } from "effect" * * class Database extends Context.Service Effect.Effect @@ -639,7 +797,7 @@ export const build = ( * const program = Effect.gen(function*() { * const scope = yield* Effect.scope * - * const dbLayer = Layer.effect(Database)(Effect.gen(function*() { + * const dbLayer = Layer.effect(Database, Effect.gen(function*() { * console.log("Initializing database...") * yield* Scope.addFinalizer( * scope, @@ -657,20 +815,27 @@ export const build = ( * }) * ``` * - * @since 2.0.0 * @category destructors + * @since 2.0.0 */ 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. + * Builds a layer using an explicit scope. + * + * **When to use** + * + * Use to control the lifetime of layer resources with a scope supplied by the + * caller. + * + * **Details** + * + * Resources created by the layer are released when the supplied scope is + * closed, unless a resource extends its own scope. + * + * **Example** (Building a layer with an explicit scope) * - * @example * ```ts - * import { Effect, Layer, Scope, Context } from "effect" + * import { Context, Effect, Layer, Scope } from "effect" * * class Database extends Context.Service Effect.Effect @@ -680,7 +845,7 @@ export const buildWithScope: { * const program = Effect.gen(function*() { * const scope = yield* Effect.scope * - * const dbLayer = Layer.effect(Database)(Effect.gen(function*() { + * const dbLayer = Layer.effect(Database, Effect.gen(function*() { * console.log("Initializing database...") * yield* Scope.addFinalizer( * scope, @@ -698,20 +863,27 @@ export const buildWithScope: { * }) * ``` * - * @since 2.0.0 * @category destructors + * @since 2.0.0 */ (scope: Scope.Scope): (self: Layer) => Effect, 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. + * Builds a layer using an explicit scope. + * + * **When to use** + * + * Use to control the lifetime of layer resources with a scope supplied by the + * caller. + * + * **Details** + * + * Resources created by the layer are released when the supplied scope is + * closed, unless a resource extends its own scope. + * + * **Example** (Building a layer with an explicit scope) * - * @example * ```ts - * import { Effect, Layer, Scope, Context } from "effect" + * import { Context, Effect, Layer, Scope } from "effect" * * class Database extends Context.Service Effect.Effect @@ -721,7 +893,7 @@ export const buildWithScope: { * const program = Effect.gen(function*() { * const scope = yield* Effect.scope * - * const dbLayer = Layer.effect(Database)(Effect.gen(function*() { + * const dbLayer = Layer.effect(Database, Effect.gen(function*() { * console.log("Initializing database...") * yield* Scope.addFinalizer( * scope, @@ -739,8 +911,8 @@ export const buildWithScope: { * }) * ``` * - * @since 2.0.0 * @category destructors + * @since 2.0.0 */ (self: Layer, scope: Scope.Scope): Effect, E, RIn> } = dual(2, ( @@ -756,132 +928,90 @@ export const buildWithScope: { )) /** - * Constructs a layer from the specified value. + * Constructs a layer that provides a single service from an already available + * value. + * + * **When to use** + * + * Use when you need a `Layer` that provides a service from an already + * constructed implementation without effectful acquisition. + * + * **Example** (Creating a layer from a service implementation) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * class Logger extends Context.Service Effect.Effect - * }>()("Logger") {} - * - * // Create layers from concrete service implementations - * const databaseLayer = Layer.succeed(Database)({ + * const DatabaseLive = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Query result: ${sql}`)) * }) - * - * const loggerLayer = Layer.succeed(Logger)({ - * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) - * }) - * - * // Use the layers in a program - * const program = Effect.gen(function*() { - * const database = yield* Database - * const logger = yield* Logger - * - * yield* logger.log("Starting database query") - * const result = yield* database.query("SELECT * FROM users") - * yield* logger.log(`Query completed: ${result}`) - * - * return result - * }).pipe( - * Effect.provide(Layer.mergeAll(databaseLayer, loggerLayer)) - * ) * ``` * - * @since 2.0.0 + * @see {@link sync} for constructing layers from lazy values + * * @category constructors + * @since 2.0.0 */ export const succeed: { /** - * Constructs a layer from the specified value. + * Constructs a layer that provides a single service from an already available + * value. + * + * **When to use** + * + * Use when you need a `Layer` that provides a service from an already + * constructed implementation without effectful acquisition. + * + * **Example** (Creating a layer from a service implementation) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * class Logger extends Context.Service Effect.Effect - * }>()("Logger") {} - * - * // Create layers from concrete service implementations - * const databaseLayer = Layer.succeed(Database)({ + * const DatabaseLive = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Query result: ${sql}`)) * }) - * - * const loggerLayer = Layer.succeed(Logger)({ - * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) - * }) - * - * // Use the layers in a program - * const program = Effect.gen(function*() { - * const database = yield* Database - * const logger = yield* Logger - * - * yield* logger.log("Starting database query") - * const result = yield* database.query("SELECT * FROM users") - * yield* logger.log(`Query completed: ${result}`) - * - * return result - * }).pipe( - * Effect.provide(Layer.mergeAll(databaseLayer, loggerLayer)) - * ) * ``` * - * @since 2.0.0 + * @see {@link sync} for constructing layers from lazy values + * * @category constructors + * @since 2.0.0 */ (service: Context.Key): (resource: S) => Layer /** - * Constructs a layer from the specified value. + * Constructs a layer that provides a single service from an already available + * value. + * + * **When to use** + * + * Use when you need a `Layer` that provides a service from an already + * constructed implementation without effectful acquisition. + * + * **Example** (Creating a layer from a service implementation) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * class Logger extends Context.Service Effect.Effect - * }>()("Logger") {} - * - * // Create layers from concrete service implementations - * const databaseLayer = Layer.succeed(Database)({ + * const DatabaseLive = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Query result: ${sql}`)) * }) - * - * const loggerLayer = Layer.succeed(Logger)({ - * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) - * }) - * - * // Use the layers in a program - * const program = Effect.gen(function*() { - * const database = yield* Database - * const logger = yield* Logger - * - * yield* logger.log("Starting database query") - * const result = yield* database.query("SELECT * FROM users") - * yield* logger.log(`Query completed: ${result}`) - * - * return result - * }).pipe( - * Effect.provide(Layer.mergeAll(databaseLayer, loggerLayer)) - * ) * ``` * - * @since 2.0.0 + * @see {@link sync} for constructing layers from lazy values + * * @category constructors + * @since 2.0.0 */ (service: Context.Key, resource: Types.NoInfer): Layer } = function() { @@ -892,15 +1022,23 @@ export const succeed: { } as any /** - * Constructs a layer from the specified value, which must return one or more - * services. + * Constructs a layer that provides all services in an already available + * `Context`. * - * This is a more general version of `succeed` that allows you to provide multiple - * services at once through a `Context`. + * **When to use** + * + * Use when you need a `Layer` built from an existing `Context`, including when + * you need to provide multiple services at once. + * + * **Details** + * + * This is a more general version of `succeed` that allows you to provide + * multiple services at once through a `Context`. + * + * **Example** (Providing multiple services from a context) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -921,97 +1059,138 @@ export const succeed: { * const layer = Layer.succeedContext(context) * ``` * - * @since 2.0.0 + * @see {@link succeed} for providing a single service from a value + * * @category constructors + * @since 2.0.0 */ export const succeedContext = (context: Context.Context): Layer => fromBuildUnsafe(constant(internalEffect.succeed(context))) /** - * A Layer that constructs an empty Context. + * An empty layer that provides no services, cannot fail, has no requirements, + * and performs no construction or finalization work. * - * This layer provides no services and can be used as a neutral element - * in layer composition or as a starting point for building layers. + * **When to use** + * + * Use as the no-op branch when conditionally composing layers. + * + * **Example** (Disabling optional lifecycle work) * - * @example * ```ts - * import { Layer } from "effect" + * import { Console, Layer } from "effect" + * + * declare const flag: boolean * - * const emptyLayer = Layer.empty + * const StartupLogLive = flag + * ? Layer.effectDiscard(Console.log("application starting")) + * : Layer.empty * ``` * - * @since 2.0.0 + * @see {@link effectDiscard} for running an effect while providing no services + * * @category constructors + * @since 2.0.0 */ export const empty: Layer = succeedContext(Context.empty()) /** - * Lazily constructs a layer from the specified value. + * Constructs a layer lazily that provides a single service. + * + * **When to use** + * + * Use when you need a `Layer` that provides one service whose value is created + * synchronously, but creation should be deferred until the layer is built. + * + * **Details** * * This is a lazy version of `succeed` where the service value is computed * synchronously only when the layer is built. * - * @example + * **Example** (Lazily providing a service) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * const layer = Layer.sync(Database)(() => ({ + * const layer = Layer.sync(Database, () => ({ * query: (sql: string) => Effect.succeed(`Query: ${sql}`) * })) * ``` * - * @since 2.0.0 + * @see {@link succeed} for constructing layers from static values + * * @category constructors + * @since 2.0.0 */ export const sync: { /** - * Lazily constructs a layer from the specified value. + * Constructs a layer lazily that provides a single service. + * + * **When to use** + * + * Use when you need a `Layer` that provides one service whose value is created + * synchronously, but creation should be deferred until the layer is built. + * + * **Details** * * This is a lazy version of `succeed` where the service value is computed * synchronously only when the layer is built. * - * @example + * **Example** (Lazily providing a service) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * const layer = Layer.sync(Database)(() => ({ + * const layer = Layer.sync(Database, () => ({ * query: (sql: string) => Effect.succeed(`Query: ${sql}`) * })) * ``` * - * @since 2.0.0 + * @see {@link succeed} for constructing layers from static values + * * @category constructors + * @since 2.0.0 */ (service: Context.Key): (evaluate: LazyArg) => Layer /** - * Lazily constructs a layer from the specified value. + * Constructs a layer lazily that provides a single service. + * + * **When to use** + * + * Use when you need a `Layer` that provides one service whose value is created + * synchronously, but creation should be deferred until the layer is built. + * + * **Details** * * This is a lazy version of `succeed` where the service value is computed * synchronously only when the layer is built. * - * @example + * **Example** (Lazily providing a service) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * const layer = Layer.sync(Database)(() => ({ + * const layer = Layer.sync(Database, () => ({ * query: (sql: string) => Effect.succeed(`Query: ${sql}`) * })) * ``` * - * @since 2.0.0 + * @see {@link succeed} for constructing layers from static values + * * @category constructors + * @since 2.0.0 */ (service: Context.Key, evaluate: LazyArg>): Layer } = function() { @@ -1022,15 +1201,22 @@ export const sync: { } as any /** - * Lazily constructs a layer from the specified value, which must return one or more - * services. + * Constructs a layer lazily that provides all services in a `Context`. + * + * **When to use** + * + * Use when you need a `Layer` that creates multiple services synchronously but + * defers that work until the layer is built. + * + * **Details** * - * This is a lazy version of `succeedContext` where the Context is computed + * This is a lazy version of `succeedContext` where the `Context` is computed * synchronously only when the layer is built. * - * @example + * **Example** (Lazily providing a context) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1043,108 +1229,126 @@ export const sync: { * ) * ``` * - * @since 2.0.0 + * @see {@link sync} for lazily providing a single service + * @see {@link succeedContext} for providing an already available context + * * @category constructors + * @since 2.0.0 */ export const syncContext = (evaluate: LazyArg>): Layer => fromBuildMemo(constant(internalEffect.sync(evaluate))) /** - * Constructs a layer from the specified scoped effect. + * Constructs a layer from an effect that produces a single service. * - * This allows you to create a Layer from an Effect that produces a service. - * The Effect is executed in the scope of the layer, allowing for proper - * resource management. + * **When to use** * - * **Previously Known As** + * Use when you need to construct a `Layer`-provided service with an `Effect`, + * dependencies, or scoped resource acquisition. + * + * **Details** * - * This API replaces the following from Effect 3.x: + * This allows you to create a `Layer` from an `Effect` that produces a service. + * The `Effect` is executed in the scope of the layer, allowing for proper + * resource management. * - * - `Layer.scoped` + * **Example** (Creating a layer from an effect) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * const layer = Layer.effect(Database)( + * const layer = Layer.effect(Database, * Effect.sync(() => ({ * query: (sql: string) => Effect.succeed(`Query: ${sql}`) * })) * ) * ``` * - * @since 2.0.0 + * @see {@link effectContext} for effectfully providing multiple services + * @see {@link effectDiscard} for running construction work without providing services + * * @category constructors + * @since 2.0.0 */ export const effect: { /** - * Constructs a layer from the specified scoped effect. + * Constructs a layer from an effect that produces a single service. * - * This allows you to create a Layer from an Effect that produces a service. - * The Effect is executed in the scope of the layer, allowing for proper - * resource management. + * **When to use** + * + * Use when you need to construct a `Layer`-provided service with an `Effect`, + * dependencies, or scoped resource acquisition. * - * **Previously Known As** + * **Details** * - * This API replaces the following from Effect 3.x: + * This allows you to create a `Layer` from an `Effect` that produces a service. + * The `Effect` is executed in the scope of the layer, allowing for proper + * resource management. * - * - `Layer.scoped` + * **Example** (Creating a layer from an effect) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * const layer = Layer.effect(Database)( + * const layer = Layer.effect(Database, * Effect.sync(() => ({ * query: (sql: string) => Effect.succeed(`Query: ${sql}`) * })) * ) * ``` * - * @since 2.0.0 + * @see {@link effectContext} for effectfully providing multiple services + * @see {@link effectDiscard} for running construction work without providing services + * * @category constructors + * @since 2.0.0 */ (service: Context.Key): ( effect: Effect ) => Layer> /** - * Constructs a layer from the specified scoped effect. + * Constructs a layer from an effect that produces a single service. * - * This allows you to create a Layer from an Effect that produces a service. - * The Effect is executed in the scope of the layer, allowing for proper - * resource management. + * **When to use** * - * **Previously Known As** + * Use when you need to construct a `Layer`-provided service with an `Effect`, + * dependencies, or scoped resource acquisition. * - * This API replaces the following from Effect 3.x: + * **Details** + * + * This allows you to create a `Layer` from an `Effect` that produces a service. + * The `Effect` is executed in the scope of the layer, allowing for proper + * resource management. * - * - `Layer.scoped` + * **Example** (Creating a layer from an effect) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * const layer = Layer.effect(Database)( + * const layer = Layer.effect(Database, * Effect.sync(() => ({ * query: (sql: string) => Effect.succeed(`Query: ${sql}`) * })) * ) * ``` * - * @since 2.0.0 + * @see {@link effectContext} for effectfully providing multiple services + * @see {@link effectDiscard} for running construction work without providing services + * * @category constructors + * @since 2.0.0 */ (service: Context.Key, effect: Effect, E, R>): Layer> } = function() { @@ -1161,15 +1365,23 @@ const effectImpl = ( effectContext(internalEffect.map(effect, (value) => Context.make(service, value))) /** - * Constructs a layer from the specified scoped effect, which must return one - * or more services. + * Constructs a layer from an effect that produces all services in a `Context`. + * + * **When to use** + * + * Use when you need a `Layer` that effectfully constructs a `Context` with + * multiple services. * - * This allows you to create a Layer from an effectful computation that returns - * multiple services. The Effect is executed in the scope of the layer. + * **Details** + * + * This allows you to create a `Layer` from an effectful computation that + * returns multiple services. The `Effect` is executed in the scope of the + * layer. + * + * **Example** (Creating a layer from an effectful context) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service< * Database, @@ -1183,26 +1395,26 @@ const effectImpl = ( * ) * ``` * - * @since 2.0.0 + * @see {@link effect} for effectfully providing a single service + * * @category constructors + * @since 2.0.0 */ export const effectContext = ( effect: Effect, E, R> ): Layer> => fromBuildMemo((_, scope) => Scope.provide(effect, scope)) /** - * Constructs a layer from the specified scoped effect. - * - * This is useful when you want to run an Effect for its side effects during - * layer construction, but don't need to provide any services. + * Constructs a layer from an effect, discarding its value and providing no + * services. * - * **Previously Known As** + * **When to use** * - * This API replaces the following from Effect 3.x: + * Use when layer construction should run an Effect for its side effects while providing no + * services. * - * - `Layer.scopedDiscard` + * **Example** (Running an effect during layer construction) * - * @example * ```ts * import { Effect, Layer } from "effect" * @@ -1213,21 +1425,26 @@ export const effectContext = ( * ) * ``` * - * @since 2.0.0 + * @see {@link empty} for a no-op layer that performs no construction work + * * @category constructors + * @since 2.0.0 */ export const effectDiscard = (effect: Effect): Layer> => effectContext(internalEffect.as(effect, Context.empty())) /** - * Lazily constructs a layer using the specified factory. + * Constructs a layer lazily using the specified factory. + * + * **Details** * * The factory is evaluated only when the suspended layer is first built, and * the result is memoized with normal layer sharing semantics. * - * @example + * **Example** (Choosing a layer lazily) + * * ```ts - * import { Layer, Context } from "effect" + * import { Context, Layer } from "effect" * * class Config extends Context.Service()("Config") {} * @@ -1235,41 +1452,48 @@ export const effectDiscard = (effect: Effect): Layer * useProd - * ? Layer.succeed(Config)("https://api.example.com") - * : Layer.succeed(Config)("http://localhost:3000") + * ? Layer.succeed(Config, "https://api.example.com") + * : Layer.succeed(Config, "http://localhost:3000") * ) * ``` * - * @since 4.0.0 * @category constructors + * @since 2.0.0 */ export const suspend = (evaluate: LazyArg>): Layer => fromBuildMemo((memoMap, scope) => internalEffect.suspend(() => evaluate().build(memoMap, scope))) /** - * Unwraps a Layer from an Effect, flattening the nested structure. + * Unwraps a `Layer` from an `Effect`, flattening the nested structure. + * + * **When to use** * - * This is useful when you have an Effect that produces a Layer, and you want to - * use that Layer directly. The resulting Layer will have the combined error and - * dependency types from both the outer Effect and the inner Layer. + * Use when you have an `Effect` that produces a `Layer` and you want to + * use that layer directly. + * + * **Details** + * + * The resulting Layer will have the combined error and dependency types from + * both the outer Effect and the inner Layer. + * + * **Example** (Unwrapping an effectful layer) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * * const layerEffect = Effect.succeed( - * Layer.succeed(Database)({ query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) }) + * Layer.succeed(Database, { query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) }) * ) * * const unwrappedLayer = Layer.unwrap(layerEffect) * ``` * + * @category converting * @since 4.0.0 - * @category utils */ export const unwrap = ( self: Effect, E, R> @@ -1296,14 +1520,25 @@ const mergeAllEffect = , ...Array Effect.Effect @@ -1313,18 +1548,20 @@ const mergeAllEffect = , ...Array Effect.Effect * }>()("Logger") {} * - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(msg))) * }) * * const mergedLayer = Layer.mergeAll(dbLayer, loggerLayer) * ``` * - * @since 2.0.0 + * @see {@link merge} for merging one layer with another layer or array + * * @category zipping + * @since 2.0.0 */ export const mergeAll = , ...Array>]>( ...layers: Layers @@ -1335,14 +1572,24 @@ export const mergeAll = , ...Array => fromBuild((memoMap, scope) => mergeAllEffect(layers, memoMap, scope)) /** - * Merges this layer with the specified layer concurrently, producing a new layer with combined input and output types. + * Merges this layer with another layer concurrently, producing a new layer with + * combined input, error, and output types. + * + * **When to use** + * + * Use to combine an existing `Layer` with another `Layer` or an array of + * layers while preserving pipeline style. + * + * **Details** + * + * This is a binary version of `mergeAll` that merges exactly two layers or one + * layer with an array of layers. The layers are built concurrently and their + * outputs are combined. * - * This is a binary version of `mergeAll` that merges exactly two layers or one layer with an array of layers. - * The layers are built concurrently and their outputs are combined. + * **Example** (Merging two layers) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1352,29 +1599,41 @@ export const mergeAll = , ...Array Effect.Effect * }>()("Logger") {} * - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(msg))) * }) * * const mergedLayer = Layer.merge(dbLayer, loggerLayer) * ``` * - * @since 2.0.0 + * @see {@link mergeAll} for merging several layers at once + * * @category zipping + * @since 2.0.0 */ export const merge: { /** - * Merges this layer with the specified layer concurrently, producing a new layer with combined input and output types. + * Merges this layer with another layer concurrently, producing a new layer with + * combined input, error, and output types. + * + * **When to use** + * + * Use to combine an existing `Layer` with another `Layer` or an array of + * layers while preserving pipeline style. * - * This is a binary version of `mergeAll` that merges exactly two layers or one layer with an array of layers. - * The layers are built concurrently and their outputs are combined. + * **Details** + * + * This is a binary version of `mergeAll` that merges exactly two layers or one + * layer with an array of layers. The layers are built concurrently and their + * outputs are combined. + * + * **Example** (Merging two layers) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1384,29 +1643,41 @@ export const merge: { * readonly log: (msg: string) => Effect.Effect * }>()("Logger") {} * - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(msg))) * }) * * const mergedLayer = Layer.merge(dbLayer, loggerLayer) * ``` * - * @since 2.0.0 + * @see {@link mergeAll} for merging several layers at once + * * @category zipping + * @since 2.0.0 */ (that: Layer): (self: Layer) => Layer /** - * Merges this layer with the specified layer concurrently, producing a new layer with combined input and output types. + * Merges this layer with another layer concurrently, producing a new layer with + * combined input, error, and output types. + * + * **When to use** + * + * Use to combine an existing `Layer` with another `Layer` or an array of + * layers while preserving pipeline style. + * + * **Details** + * + * This is a binary version of `mergeAll` that merges exactly two layers or one + * layer with an array of layers. The layers are built concurrently and their + * outputs are combined. * - * This is a binary version of `mergeAll` that merges exactly two layers or one layer with an array of layers. - * The layers are built concurrently and their outputs are combined. + * **Example** (Merging two layers) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1416,18 +1687,20 @@ export const merge: { * readonly log: (msg: string) => Effect.Effect * }>()("Logger") {} * - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(msg))) * }) * * const mergedLayer = Layer.merge(dbLayer, loggerLayer) * ``` * - * @since 2.0.0 + * @see {@link mergeAll} for merging several layers at once + * * @category zipping + * @since 2.0.0 */ ]>(that: Layers): ( self: Layer @@ -1438,14 +1711,24 @@ export const merge: { | R > /** - * Merges this layer with the specified layer concurrently, producing a new layer with combined input and output types. + * Merges this layer with another layer concurrently, producing a new layer with + * combined input, error, and output types. + * + * **When to use** + * + * Use to combine an existing `Layer` with another `Layer` or an array of + * layers while preserving pipeline style. + * + * **Details** * - * This is a binary version of `mergeAll` that merges exactly two layers or one layer with an array of layers. - * The layers are built concurrently and their outputs are combined. + * This is a binary version of `mergeAll` that merges exactly two layers or one + * layer with an array of layers. The layers are built concurrently and their + * outputs are combined. + * + * **Example** (Merging two layers) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1455,29 +1738,41 @@ export const merge: { * readonly log: (msg: string) => Effect.Effect * }>()("Logger") {} * - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(msg))) * }) * * const mergedLayer = Layer.merge(dbLayer, loggerLayer) * ``` * - * @since 2.0.0 + * @see {@link mergeAll} for merging several layers at once + * * @category zipping + * @since 2.0.0 */ (self: Layer, that: Layer): Layer /** - * Merges this layer with the specified layer concurrently, producing a new layer with combined input and output types. + * Merges this layer with another layer concurrently, producing a new layer with + * combined input, error, and output types. + * + * **When to use** * - * This is a binary version of `mergeAll` that merges exactly two layers or one layer with an array of layers. - * The layers are built concurrently and their outputs are combined. + * Use to combine an existing `Layer` with another `Layer` or an array of + * layers while preserving pipeline style. + * + * **Details** + * + * This is a binary version of `mergeAll` that merges exactly two layers or one + * layer with an array of layers. The layers are built concurrently and their + * outputs are combined. + * + * **Example** (Merging two layers) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1487,18 +1782,20 @@ export const merge: { * readonly log: (msg: string) => Effect.Effect * }>()("Logger") {} * - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed("result")) * }) - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(msg))) * }) * * const mergedLayer = Layer.merge(dbLayer, loggerLayer) * ``` * - * @since 2.0.0 + * @see {@link mergeAll} for merging several layers at once + * * @category zipping + * @since 2.0.0 */ ]>(self: Layer, that: Layers): Layer< A | Success, @@ -1533,13 +1830,22 @@ const provideWith = ( ) /** - * 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. + * Feeds the output services of the dependency layer into the requirements of + * this layer, returning a layer that only provides the services from this layer. + * + * **When to use** + * + * Use when you need to hide an implementation dependency layer from callers. + * + * **Details** + * + * In `serviceLayer.pipe(Layer.provide(dependencyLayer))`, the dependency layer is + * built first and is used to satisfy the requirements of `serviceLayer`. + * + * **Example** (Providing layer dependencies) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1557,16 +1863,16 @@ const provideWith = ( * }>()("Logger") {} * * // Create dependency layers - * const databaseLayer = Layer.succeed(Database)({ + * const databaseLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`DB: ${sql}`)) * }) * - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) * }) * * // UserService depends on Database and Logger - * const userServiceLayer = Layer.effect(UserService)(Effect.gen(function*() { + * const userServiceLayer = Layer.effect(UserService, Effect.gen(function*() { * const database = yield* Database * const logger = yield* Logger * @@ -1595,18 +1901,29 @@ const provideWith = ( * ) * ``` * + * @see {@link provideMerge} for retaining the dependency services + * + * @category providing services * @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. + * Feeds the output services of the dependency layer into the requirements of + * this layer, returning a layer that only provides the services from this layer. + * + * **When to use** + * + * Use when you need to hide an implementation dependency layer from callers. + * + * **Details** + * + * In `serviceLayer.pipe(Layer.provide(dependencyLayer))`, the dependency layer is + * built first and is used to satisfy the requirements of `serviceLayer`. + * + * **Example** (Providing layer dependencies) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1624,16 +1941,16 @@ export const provide: { * }>()("Logger") {} * * // Create dependency layers - * const databaseLayer = Layer.succeed(Database)({ + * const databaseLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`DB: ${sql}`)) * }) * - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) * }) * * // UserService depends on Database and Logger - * const userServiceLayer = Layer.effect(UserService)(Effect.gen(function*() { + * const userServiceLayer = Layer.effect(UserService, Effect.gen(function*() { * const database = yield* Database * const logger = yield* Logger * @@ -1662,18 +1979,29 @@ export const provide: { * ) * ``` * + * @see {@link provideMerge} for retaining the dependency services + * + * @category providing services * @since 2.0.0 - * @category utils */ (that: Layer): (self: Layer) => Layer> /** - * 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. + * Feeds the output services of the dependency layer into the requirements of + * this layer, returning a layer that only provides the services from this layer. + * + * **When to use** + * + * Use when you need to hide an implementation dependency layer from callers. + * + * **Details** + * + * In `serviceLayer.pipe(Layer.provide(dependencyLayer))`, the dependency layer is + * built first and is used to satisfy the requirements of `serviceLayer`. + * + * **Example** (Providing layer dependencies) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1691,16 +2019,16 @@ export const provide: { * }>()("Logger") {} * * // Create dependency layers - * const databaseLayer = Layer.succeed(Database)({ + * const databaseLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`DB: ${sql}`)) * }) * - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) * }) * * // UserService depends on Database and Logger - * const userServiceLayer = Layer.effect(UserService)(Effect.gen(function*() { + * const userServiceLayer = Layer.effect(UserService, Effect.gen(function*() { * const database = yield* Database * const logger = yield* Logger * @@ -1729,8 +2057,10 @@ export const provide: { * ) * ``` * + * @see {@link provideMerge} for retaining the dependency services + * + * @category providing services * @since 2.0.0 - * @category utils */ ]>(that: Layers): ( self: Layer @@ -1741,13 +2071,22 @@ export const provide: { | Exclude> > /** - * 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. + * Feeds the output services of the dependency layer into the requirements of + * this layer, returning a layer that only provides the services from this layer. + * + * **When to use** + * + * Use when you need to hide an implementation dependency layer from callers. + * + * **Details** + * + * In `serviceLayer.pipe(Layer.provide(dependencyLayer))`, the dependency layer is + * built first and is used to satisfy the requirements of `serviceLayer`. + * + * **Example** (Providing layer dependencies) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1765,16 +2104,16 @@ export const provide: { * }>()("Logger") {} * * // Create dependency layers - * const databaseLayer = Layer.succeed(Database)({ + * const databaseLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`DB: ${sql}`)) * }) * - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) * }) * * // UserService depends on Database and Logger - * const userServiceLayer = Layer.effect(UserService)(Effect.gen(function*() { + * const userServiceLayer = Layer.effect(UserService, Effect.gen(function*() { * const database = yield* Database * const logger = yield* Logger * @@ -1803,18 +2142,29 @@ export const provide: { * ) * ``` * + * @see {@link provideMerge} for retaining the dependency services + * + * @category providing services * @since 2.0.0 - * @category utils */ (self: Layer, that: Layer): Layer> /** - * 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. + * Feeds the output services of the dependency layer into the requirements of + * this layer, returning a layer that only provides the services from this layer. + * + * **When to use** + * + * Use when you need to hide an implementation dependency layer from callers. + * + * **Details** + * + * In `serviceLayer.pipe(Layer.provide(dependencyLayer))`, the dependency layer is + * built first and is used to satisfy the requirements of `serviceLayer`. + * + * **Example** (Providing layer dependencies) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1832,16 +2182,16 @@ export const provide: { * }>()("Logger") {} * * // Create dependency layers - * const databaseLayer = Layer.succeed(Database)({ + * const databaseLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`DB: ${sql}`)) * }) * - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) * }) * * // UserService depends on Database and Logger - * const userServiceLayer = Layer.effect(UserService)(Effect.gen(function*() { + * const userServiceLayer = Layer.effect(UserService, Effect.gen(function*() { * const database = yield* Database * const logger = yield* Logger * @@ -1870,8 +2220,10 @@ export const provide: { * ) * ``` * + * @see {@link provideMerge} for retaining the dependency services + * + * @category providing services * @since 2.0.0 - * @category utils */ ]>(self: Layer, that: Layers): Layer< A, @@ -1885,13 +2237,22 @@ export const provide: { ) => provideWith(self, that, identity)) /** - * 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. + * Feeds the output services of the dependency layer into the requirements of + * this layer, returning a layer that provides both sets of services. + * + * **When to use** + * + * Use when you need to compose `Layer`s while keeping both the constructed + * service and the dependency used to build it available. + * + * **Details** + * + * Prefer {@link provide} when the dependency should stay private. + * + * **Example** (Providing dependencies while retaining services) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1909,16 +2270,16 @@ export const provide: { * }>()("UserService") {} * * // Create dependency layers - * const databaseLayer = Layer.succeed(Database)({ + * const databaseLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`DB: ${sql}`)) * }) * - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) * }) * * // UserService depends on Database and Logger - * const userServiceLayer = Layer.effect(UserService)(Effect.gen(function*() { + * const userServiceLayer = Layer.effect(UserService, Effect.gen(function*() { * const database = yield* Database * const logger = yield* Logger * @@ -1953,18 +2314,29 @@ export const provide: { * ) * ``` * + * @see {@link provide} for keeping dependency services private + * + * @category providing services * @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. + * Feeds the output services of the dependency layer into the requirements of + * this layer, returning a layer that provides both sets of services. + * + * **When to use** + * + * Use when you need to compose `Layer`s while keeping both the constructed + * service and the dependency used to build it available. + * + * **Details** + * + * Prefer {@link provide} when the dependency should stay private. + * + * **Example** (Providing dependencies while retaining services) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -1982,16 +2354,16 @@ export const provideMerge: { * }>()("UserService") {} * * // Create dependency layers - * const databaseLayer = Layer.succeed(Database)({ + * const databaseLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`DB: ${sql}`)) * }) * - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) * }) * * // UserService depends on Database and Logger - * const userServiceLayer = Layer.effect(UserService)(Effect.gen(function*() { + * const userServiceLayer = Layer.effect(UserService, Effect.gen(function*() { * const database = yield* Database * const logger = yield* Logger * @@ -2026,18 +2398,29 @@ export const provideMerge: { * ) * ``` * + * @see {@link provide} for keeping dependency services private + * + * @category providing services * @since 2.0.0 - * @category utils */ (that: Layer): (self: Layer) => Layer> /** - * 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. + * Feeds the output services of the dependency layer into the requirements of + * this layer, returning a layer that provides both sets of services. + * + * **When to use** + * + * Use when you need to compose `Layer`s while keeping both the constructed + * service and the dependency used to build it available. + * + * **Details** + * + * Prefer {@link provide} when the dependency should stay private. + * + * **Example** (Providing dependencies while retaining services) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -2055,16 +2438,16 @@ export const provideMerge: { * }>()("UserService") {} * * // Create dependency layers - * const databaseLayer = Layer.succeed(Database)({ + * const databaseLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`DB: ${sql}`)) * }) * - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) * }) * * // UserService depends on Database and Logger - * const userServiceLayer = Layer.effect(UserService)(Effect.gen(function*() { + * const userServiceLayer = Layer.effect(UserService, Effect.gen(function*() { * const database = yield* Database * const logger = yield* Logger * @@ -2099,8 +2482,10 @@ export const provideMerge: { * ) * ``` * + * @see {@link provide} for keeping dependency services private + * + * @category providing services * @since 2.0.0 - * @category utils */ ]>(that: Layers): ( self: Layer @@ -2111,13 +2496,22 @@ export const provideMerge: { | Exclude> > /** - * 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. + * Feeds the output services of the dependency layer into the requirements of + * this layer, returning a layer that provides both sets of services. + * + * **When to use** + * + * Use when you need to compose `Layer`s while keeping both the constructed + * service and the dependency used to build it available. + * + * **Details** + * + * Prefer {@link provide} when the dependency should stay private. + * + * **Example** (Providing dependencies while retaining services) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -2135,16 +2529,16 @@ export const provideMerge: { * }>()("UserService") {} * * // Create dependency layers - * const databaseLayer = Layer.succeed(Database)({ + * const databaseLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`DB: ${sql}`)) * }) * - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) * }) * * // UserService depends on Database and Logger - * const userServiceLayer = Layer.effect(UserService)(Effect.gen(function*() { + * const userServiceLayer = Layer.effect(UserService, Effect.gen(function*() { * const database = yield* Database * const logger = yield* Logger * @@ -2179,18 +2573,29 @@ export const provideMerge: { * ) * ``` * + * @see {@link provide} for keeping dependency services private + * + * @category providing services * @since 2.0.0 - * @category utils */ (self: Layer, that: Layer): Layer> /** - * 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. + * Feeds the output services of the dependency layer into the requirements of + * this layer, returning a layer that provides both sets of services. + * + * **When to use** + * + * Use when you need to compose `Layer`s while keeping both the constructed + * service and the dependency used to build it available. + * + * **Details** + * + * Prefer {@link provide} when the dependency should stay private. + * + * **Example** (Providing dependencies while retaining services) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -2208,16 +2613,16 @@ export const provideMerge: { * }>()("UserService") {} * * // Create dependency layers - * const databaseLayer = Layer.succeed(Database)({ + * const databaseLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`DB: ${sql}`)) * }) * - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Effect.sync(() => console.log(`[LOG] ${msg}`))) * }) * * // UserService depends on Database and Logger - * const userServiceLayer = Layer.effect(UserService)(Effect.gen(function*() { + * const userServiceLayer = Layer.effect(UserService, Effect.gen(function*() { * const database = yield* Database * const logger = yield* Logger * @@ -2252,8 +2657,10 @@ export const provideMerge: { * ) * ``` * + * @see {@link provide} for keeping dependency services private + * + * @category providing services * @since 2.0.0 - * @category utils */ ]>(self: Layer, that: Layers): Layer< A | Success, @@ -2274,9 +2681,10 @@ export const provideMerge: { /** * Constructs a layer dynamically based on the output of this layer. * - * @example + * **Example** (Creating services from layer output) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Config extends Context.Service()("Logger") {} * * // Base config layer - * const configLayer = Layer.succeed(Config)({ + * const configLayer = Layer.succeed(Config, { * dbUrl: "postgres://localhost:5432/mydb", * logLevel: "debug" * }) @@ -2303,7 +2711,7 @@ export const provideMerge: { * const config = Context.get(context, Config) * * // Create database layer based on config - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => * Effect.succeed( * `Querying ${config.dbUrl}: ${sql}` @@ -2311,7 +2719,7 @@ export const provideMerge: { * }) * * // Create logger layer based on config - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => * config.logLevel === "debug" * ? Effect.sync(() => console.log(`[DEBUG] ${msg}`)) @@ -2338,16 +2746,17 @@ export const provideMerge: { * ) * ``` * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ export const flatMap: { /** * Constructs a layer dynamically based on the output of this layer. * - * @example + * **Example** (Creating services from layer output) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Config extends Context.Service()("Logger") {} * * // Base config layer - * const configLayer = Layer.succeed(Config)({ + * const configLayer = Layer.succeed(Config, { * dbUrl: "postgres://localhost:5432/mydb", * logLevel: "debug" * }) @@ -2374,7 +2783,7 @@ export const flatMap: { * const config = Context.get(context, Config) * * // Create database layer based on config - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => * Effect.succeed( * `Querying ${config.dbUrl}: ${sql}` @@ -2382,7 +2791,7 @@ export const flatMap: { * }) * * // Create logger layer based on config - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => * config.logLevel === "debug" * ? Effect.sync(() => console.log(`[DEBUG] ${msg}`)) @@ -2409,16 +2818,17 @@ export const flatMap: { * ) * ``` * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ (f: (context: Context.Context) => Layer): (self: Layer) => Layer /** * Constructs a layer dynamically based on the output of this layer. * - * @example + * **Example** (Creating services from layer output) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Config extends Context.Service()("Logger") {} * * // Base config layer - * const configLayer = Layer.succeed(Config)({ + * const configLayer = Layer.succeed(Config, { * dbUrl: "postgres://localhost:5432/mydb", * logLevel: "debug" * }) @@ -2445,7 +2855,7 @@ export const flatMap: { * const config = Context.get(context, Config) * * // Create database layer based on config - * const dbLayer = Layer.succeed(Database)({ + * const dbLayer = Layer.succeed(Database, { * query: Effect.fn("Database.query")((sql: string) => * Effect.succeed( * `Querying ${config.dbUrl}: ${sql}` @@ -2453,7 +2863,7 @@ export const flatMap: { * }) * * // Create logger layer based on config - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => * config.logLevel === "debug" * ? Effect.sync(() => console.log(`[DEBUG] ${msg}`)) @@ -2480,8 +2890,8 @@ export const flatMap: { * ) * ``` * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ ( self: Layer, @@ -2501,22 +2911,64 @@ export const flatMap: { /** * Performs the specified effect if this layer succeeds. * - * @since 4.0.0 + * **When to use** + * + * Use to run an effectful observation after a layer has been built + * successfully, such as logging or metrics, without changing the services the + * layer provides. + * + * **Details** + * + * The callback receives the services produced by this layer. Its result is + * discarded, and the original layer output is preserved. + * + * @see {@link tapError} for running an effect when layer construction fails with a typed error + * @see {@link tapCause} for running an effect when layer construction fails with any cause + * * @category sequencing + * @since 2.0.0 */ export const tap: { /** * Performs the specified effect if this layer succeeds. * - * @since 4.0.0 + * **When to use** + * + * Use to run an effectful observation after a layer has been built + * successfully, such as logging or metrics, without changing the services the + * layer provides. + * + * **Details** + * + * The callback receives the services produced by this layer. Its result is + * discarded, and the original layer output is preserved. + * + * @see {@link tapError} for running an effect when layer construction fails with a typed error + * @see {@link tapCause} for running an effect when layer construction fails with any cause + * * @category sequencing + * @since 2.0.0 */ (f: (context: Context.Context) => Effect): (self: Layer) => Layer> /** * Performs the specified effect if this layer succeeds. * - * @since 4.0.0 + * **When to use** + * + * Use to run an effectful observation after a layer has been built + * successfully, such as logging or metrics, without changing the services the + * layer provides. + * + * **Details** + * + * The callback receives the services produced by this layer. Its result is + * discarded, and the original layer output is preserved. + * + * @see {@link tapError} for running an effect when layer construction fails with a typed error + * @see {@link tapCause} for running an effect when layer construction fails with any cause + * * @category sequencing + * @since 2.0.0 */ ( self: Layer, @@ -2536,22 +2988,64 @@ export const tap: { /** * Performs the specified effect if this layer fails. * - * @since 4.0.0 + * **When to use** + * + * Use to run logging, metrics, or other effects when layer construction fails + * while preserving the original typed error. + * + * **Details** + * + * The callback receives the typed error. If the callback succeeds, the layer + * still fails with the original error; if the callback fails, that failure is + * added to the layer's error type. + * + * @see {@link tap} for running an effect when layer construction succeeds + * @see {@link tapCause} for inspecting the full failure cause, including defects and interruption + * * @category sequencing + * @since 2.0.0 */ export const tapError: { /** * Performs the specified effect if this layer fails. * - * @since 4.0.0 + * **When to use** + * + * Use to run logging, metrics, or other effects when layer construction fails + * while preserving the original typed error. + * + * **Details** + * + * The callback receives the typed error. If the callback succeeds, the layer + * still fails with the original error; if the callback fails, that failure is + * added to the layer's error type. + * + * @see {@link tap} for running an effect when layer construction succeeds + * @see {@link tapCause} for inspecting the full failure cause, including defects and interruption + * * @category sequencing + * @since 2.0.0 */ (f: (e: XE) => Effect): (self: Layer) => Layer> /** * Performs the specified effect if this layer fails. * - * @since 4.0.0 + * **When to use** + * + * Use to run logging, metrics, or other effects when layer construction fails + * while preserving the original typed error. + * + * **Details** + * + * The callback receives the typed error. If the callback succeeds, the layer + * still fails with the original error; if the callback fails, that failure is + * added to the layer's error type. + * + * @see {@link tap} for running an effect when layer construction succeeds + * @see {@link tapCause} for inspecting the full failure cause, including defects and interruption + * * @category sequencing + * @since 2.0.0 */ (self: Layer, f: (e: XE) => Effect): Layer> } = dual(2, ( @@ -2566,42 +3060,69 @@ export const tapError: { )) /** - * Performs the specified effect if this layer fails. + * Performs the specified effect when this layer fails with any cause. + * + * **When to use** * - * **Previously Known As** + * Use to run diagnostics or reporting when layer construction fails and the + * full `Cause` is needed. * - * This API replaces the following from Effect 3.x: + * **Details** * - * - `Layer.tapErrorCause` + * The callback receives the layer's `Cause`, so it can inspect typed errors, + * defects, and interruption information. If the callback succeeds, the layer + * fails again with the original cause; if the callback fails, that failure is + * added to the layer's error type. + * + * @see {@link tapError} for observing only typed layer construction errors + * @see {@link catchCause} for recovering from a layer construction failure by switching to another layer * - * @since 4.0.0 * @category sequencing + * @since 4.0.0 */ export const tapCause: { /** - * Performs the specified effect if this layer fails. + * Performs the specified effect when this layer fails with any cause. + * + * **When to use** * - * **Previously Known As** + * Use to run diagnostics or reporting when layer construction fails and the + * full `Cause` is needed. * - * This API replaces the following from Effect 3.x: + * **Details** * - * - `Layer.tapErrorCause` + * The callback receives the layer's `Cause`, so it can inspect typed errors, + * defects, and interruption information. If the callback succeeds, the layer + * fails again with the original cause; if the callback fails, that failure is + * added to the layer's error type. + * + * @see {@link tapError} for observing only typed layer construction errors + * @see {@link catchCause} for recovering from a layer construction failure by switching to another layer * - * @since 4.0.0 * @category sequencing + * @since 4.0.0 */ (f: (cause: Cause.Cause) => Effect): (self: Layer) => Layer> /** - * Performs the specified effect if this layer fails. + * Performs the specified effect when this layer fails with any cause. + * + * **When to use** * - * **Previously Known As** + * Use to run diagnostics or reporting when layer construction fails and the + * full `Cause` is needed. * - * This API replaces the following from Effect 3.x: + * **Details** * - * - `Layer.tapErrorCause` + * The callback receives the layer's `Cause`, so it can inspect typed errors, + * defects, and interruption information. If the callback succeeds, the layer + * fails again with the original cause; if the callback fails, that failure is + * added to the layer's error type. + * + * @see {@link tapError} for observing only typed layer construction errors + * @see {@link catchCause} for recovering from a layer construction failure by switching to another layer * - * @since 4.0.0 * @category sequencing + * @since 4.0.0 */ ( self: Layer, @@ -2620,12 +3141,18 @@ export const tapCause: { )) /** - * Translates effect failure into death of the fiber, making all failures - * unchecked and not a part of the type of the layer. + * Converts layer construction failures into defects, removing them from the + * layer's error type. + * + * **Details** + * + * Use this only when failures should be treated as unrecoverable defects rather + * than typed errors that callers can handle. + * + * **Example** (Converting layer failures to defects) * - * @example * ```ts - * import { Data, Effect, Layer, Context } from "effect" + * import { Context, Data, Effect, Layer } from "effect" * * class DatabaseError extends Data.TaggedError("DatabaseError")<{ * message: string @@ -2636,14 +3163,9 @@ export const tapCause: { * }>()("Database") {} * * // Layer that can fail during construction - * const flakyDatabaseLayer = Layer.effect(Database)(Effect.gen(function*() { - * // Simulate a database connection that might fail - * const shouldFail = Math.random() > 0.5 - * if (shouldFail) { - * return yield* new DatabaseError({ message: "Connection failed" }) - * } - * - * return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Result: ${sql}`)) } + * const flakyDatabaseLayer = Layer.effect(Database, Effect.gen(function*() { + * console.log("connecting") + * return yield* new DatabaseError({ message: "Connection failed" }) * })) * * // Convert failures to fiber death - removes error from type @@ -2657,12 +3179,12 @@ export const tapCause: { * Effect.provide(reliableDatabaseLayer) * ) * - * // If the database layer fails, the entire fiber will die - * // instead of the effect failing with DatabaseError + * // Running the program prints "connecting", then the DatabaseError is + * // converted into a fiber defect instead of remaining a typed error. * ``` * - * @since 2.0.0 * @category error handling + * @since 2.0.0 */ export const orDie = (self: Layer): Layer => fromBuildUnsafe((memoMap, scope) => internalEffect.orDie(self.build(memoMap, scope))) @@ -2688,10 +3210,18 @@ const catch_: { export { /** - * Recovers from all errors. + * Recovers from all typed errors by switching to another layer. + * + * **When to use** + * + * Use when every typed `Layer` construction error should use the same + * recovery path. + * + * @see {@link catchTag} for recovering from specific tagged errors + * @see {@link catchCause} for recovering with access to the full cause * - * @since 4.0.0 * @category error handling + * @since 4.0.0 */ catch_ as catch } @@ -2699,9 +3229,14 @@ export { /** * Recovers from specific tagged errors. * - * @example + * **When to use** + * + * Use when only some tagged `Layer` construction errors should be recovered. + * + * **Example** (Recovering from tagged layer errors) + * * ```ts - * import { Data, Effect, Layer, Context } from "effect" + * import { Context, Data, Effect, Layer } from "effect" * * class ConfigError extends Data.TaggedError("ConfigError") {} * @@ -2709,25 +3244,32 @@ export { * readonly apiUrl: string * }>()("Config") {} * - * const configLayer = Layer.effect(Config)(Effect.fail(new ConfigError())) + * const configLayer = Layer.effect(Config, Effect.fail(new ConfigError())) * - * const fallbackLayer = Layer.succeed(Config)({ apiUrl: "http://localhost" }) + * const fallbackLayer = Layer.succeed(Config, { apiUrl: "http://localhost" }) * * const recovered = configLayer.pipe( * Layer.catchTag("ConfigError", () => fallbackLayer) * ) * ``` * - * @since 4.0.0 + * @see {@link catchCause} for recovering with access to the full cause + * * @category error handling + * @since 4.0.0 */ export const catchTag: { /** * Recovers from specific tagged errors. * - * @example + * **When to use** + * + * Use when only some tagged `Layer` construction errors should be recovered. + * + * **Example** (Recovering from tagged layer errors) + * * ```ts - * import { Data, Effect, Layer, Context } from "effect" + * import { Context, Data, Effect, Layer } from "effect" * * class ConfigError extends Data.TaggedError("ConfigError") {} * @@ -2735,17 +3277,19 @@ export const catchTag: { * readonly apiUrl: string * }>()("Config") {} * - * const configLayer = Layer.effect(Config)(Effect.fail(new ConfigError())) + * const configLayer = Layer.effect(Config, Effect.fail(new ConfigError())) * - * const fallbackLayer = Layer.succeed(Config)({ apiUrl: "http://localhost" }) + * const fallbackLayer = Layer.succeed(Config, { apiUrl: "http://localhost" }) * * const recovered = configLayer.pipe( * Layer.catchTag("ConfigError", () => fallbackLayer) * ) * ``` * - * @since 4.0.0 + * @see {@link catchCause} for recovering with access to the full cause + * * @category error handling + * @since 4.0.0 */ | NonEmptyReadonlyArray>, E, RIn2, E2, ROut2>( k: K, @@ -2762,9 +3306,14 @@ export const catchTag: { /** * Recovers from specific tagged errors. * - * @example + * **When to use** + * + * Use when only some tagged `Layer` construction errors should be recovered. + * + * **Example** (Recovering from tagged layer errors) + * * ```ts - * import { Data, Effect, Layer, Context } from "effect" + * import { Context, Data, Effect, Layer } from "effect" * * class ConfigError extends Data.TaggedError("ConfigError") {} * @@ -2772,17 +3321,19 @@ export const catchTag: { * readonly apiUrl: string * }>()("Config") {} * - * const configLayer = Layer.effect(Config)(Effect.fail(new ConfigError())) + * const configLayer = Layer.effect(Config, Effect.fail(new ConfigError())) * - * const fallbackLayer = Layer.succeed(Config)({ apiUrl: "http://localhost" }) + * const fallbackLayer = Layer.succeed(Config, { apiUrl: "http://localhost" }) * * const recovered = configLayer.pipe( * Layer.catchTag("ConfigError", () => fallbackLayer) * ) * ``` * - * @since 4.0.0 + * @see {@link catchCause} for recovering with access to the full cause + * * @category error handling + * @since 4.0.0 */ < RIn, @@ -2823,177 +3374,177 @@ export const catchTag: { )) /** - * Recovers from all errors. + * Recovers from any failure cause by switching to another layer. + * + * **When to use** + * + * Use when you need `Layer` recovery to inspect more than the typed error, + * such as defects or interruption information. + * + * **Details** + * + * The handler receives the full `Cause` of the failed layer, including typed + * errors, unexpected defects, and interruption information, and returns the + * fallback layer to build instead. Finalizers for resources acquired by the + * failed layer are still run before the fallback layer is acquired. + * + * **Example** (Recovering from layer failures by cause) * - * @example * ```ts - * import { Data, Effect, Layer, Context } from "effect" + * import { Context, Data, Effect, Layer } from "effect" * * class DatabaseError extends Data.TaggedError("DatabaseError")<{ * message: string * }> {} * - * class NetworkError extends Data.TaggedError("NetworkError")<{ - * reason: string - * }> {} - * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * class Logger extends Context.Service Effect.Effect - * }>()("Logger") {} - * - * // Primary database layer that might fail - * const primaryDatabaseLayer = Layer.effect(Database)(Effect.gen(function*() { - * return yield* new DatabaseError({ message: "Primary DB unreachable" }) - * return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Primary: ${sql}`)) } - * })) + * const primaryDatabaseLayer = Layer.effect(Database, + * Effect.fail(new DatabaseError({ message: "Primary DB unreachable" })) + * ) * - * // Fallback layers for different error causes * const databaseWithFallback = primaryDatabaseLayer.pipe( * Layer.catchCause(() => { - * // For any cause/error, fallback to in-memory database - * return Layer.mergeAll( - * Layer.succeed(Database)({ - * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Memory: ${sql}`)) - * }), - * Layer.succeed(Logger)({ - * log: Effect.fn("Logger.log")((msg: string) => - * Effect.sync(() => console.log(`[FALLBACK] ${msg}`)) - * ) - * }) - * ) + * return Layer.succeed(Database, { + * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Memory: ${sql}`)) + * }) * }) * ) * * const program = Effect.gen(function*() { * const database = yield* Database - * return yield* database.query("SELECT * FROM users") + * const result = yield* database.query("SELECT * FROM users") + * console.log(result) * }).pipe( * Effect.provide(databaseWithFallback) * ) + * + * Effect.runPromise(program) + * // Memory: SELECT * FROM users * ``` * - * @since 2.0.0 + * @see {@link catchTag} for recovering from specific tagged errors + * * @category error handling + * @since 4.0.0 */ export const catchCause: { /** - * Recovers from all errors. + * Recovers from any failure cause by switching to another layer. + * + * **When to use** + * + * Use when you need `Layer` recovery to inspect more than the typed error, + * such as defects or interruption information. + * + * **Details** + * + * The handler receives the full `Cause` of the failed layer, including typed + * errors, unexpected defects, and interruption information, and returns the + * fallback layer to build instead. Finalizers for resources acquired by the + * failed layer are still run before the fallback layer is acquired. + * + * **Example** (Recovering from layer failures by cause) * - * @example * ```ts - * import { Data, Effect, Layer, Context } from "effect" + * import { Context, Data, Effect, Layer } from "effect" * * class DatabaseError extends Data.TaggedError("DatabaseError")<{ * message: string * }> {} * - * class NetworkError extends Data.TaggedError("NetworkError")<{ - * reason: string - * }> {} - * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * class Logger extends Context.Service Effect.Effect - * }>()("Logger") {} - * - * // Primary database layer that might fail - * const primaryDatabaseLayer = Layer.effect(Database)(Effect.gen(function*() { - * return yield* new DatabaseError({ message: "Primary DB unreachable" }) - * return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Primary: ${sql}`)) } - * })) + * const primaryDatabaseLayer = Layer.effect(Database, + * Effect.fail(new DatabaseError({ message: "Primary DB unreachable" })) + * ) * - * // Fallback layers for different error causes * const databaseWithFallback = primaryDatabaseLayer.pipe( * Layer.catchCause(() => { - * // For any cause/error, fallback to in-memory database - * return Layer.mergeAll( - * Layer.succeed(Database)({ - * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Memory: ${sql}`)) - * }), - * Layer.succeed(Logger)({ - * log: Effect.fn("Logger.log")((msg: string) => - * Effect.sync(() => console.log(`[FALLBACK] ${msg}`)) - * ) - * }) - * ) + * return Layer.succeed(Database, { + * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Memory: ${sql}`)) + * }) * }) * ) * * const program = Effect.gen(function*() { * const database = yield* Database - * return yield* database.query("SELECT * FROM users") + * const result = yield* database.query("SELECT * FROM users") + * console.log(result) * }).pipe( * Effect.provide(databaseWithFallback) * ) + * + * Effect.runPromise(program) + * // Memory: SELECT * FROM users * ``` * - * @since 2.0.0 + * @see {@link catchTag} for recovering from specific tagged errors + * * @category error handling + * @since 4.0.0 */ (onError: (cause: Cause.Cause) => Layer): (self: Layer) => Layer /** - * Recovers from all errors. + * Recovers from any failure cause by switching to another layer. + * + * **When to use** + * + * Use when you need `Layer` recovery to inspect more than the typed error, + * such as defects or interruption information. + * + * **Details** + * + * The handler receives the full `Cause` of the failed layer, including typed + * errors, unexpected defects, and interruption information, and returns the + * fallback layer to build instead. Finalizers for resources acquired by the + * failed layer are still run before the fallback layer is acquired. + * + * **Example** (Recovering from layer failures by cause) * - * @example * ```ts - * import { Data, Effect, Layer, Context } from "effect" + * import { Context, Data, Effect, Layer } from "effect" * * class DatabaseError extends Data.TaggedError("DatabaseError")<{ * message: string * }> {} * - * class NetworkError extends Data.TaggedError("NetworkError")<{ - * reason: string - * }> {} - * * class Database extends Context.Service Effect.Effect * }>()("Database") {} * - * class Logger extends Context.Service Effect.Effect - * }>()("Logger") {} - * - * // Primary database layer that might fail - * const primaryDatabaseLayer = Layer.effect(Database)(Effect.gen(function*() { - * return yield* new DatabaseError({ message: "Primary DB unreachable" }) - * return { query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Primary: ${sql}`)) } - * })) + * const primaryDatabaseLayer = Layer.effect(Database, + * Effect.fail(new DatabaseError({ message: "Primary DB unreachable" })) + * ) * - * // Fallback layers for different error causes * const databaseWithFallback = primaryDatabaseLayer.pipe( * Layer.catchCause(() => { - * // For any cause/error, fallback to in-memory database - * return Layer.mergeAll( - * Layer.succeed(Database)({ - * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Memory: ${sql}`)) - * }), - * Layer.succeed(Logger)({ - * log: Effect.fn("Logger.log")((msg: string) => - * Effect.sync(() => console.log(`[FALLBACK] ${msg}`)) - * ) - * }) - * ) + * return Layer.succeed(Database, { + * query: Effect.fn("Database.query")((sql: string) => Effect.succeed(`Memory: ${sql}`)) + * }) * }) * ) * * const program = Effect.gen(function*() { * const database = yield* Database - * return yield* database.query("SELECT * FROM users") + * const result = yield* database.query("SELECT * FROM users") + * console.log(result) * }).pipe( * Effect.provide(databaseWithFallback) * ) + * + * Effect.runPromise(program) + * // Memory: SELECT * FROM users * ``` * - * @since 2.0.0 + * @see {@link catchTag} for recovering from specific tagged errors + * * @category error handling + * @since 4.0.0 */ ( self: Layer, @@ -3013,6 +3564,11 @@ export const catchCause: { /** * Updates a service in the context with a new implementation. * + * **When to use** + * + * Use to adapt or extend a service's behavior during the creation of a + * layer. + * * **Details** * * This function modifies the existing implementation of a service in the @@ -3020,18 +3576,18 @@ export const catchCause: { * 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. - * + * @category providing services * @since 3.13.0 - * @category utils */ export const updateService: { /** * Updates a service in the context with a new implementation. * + * **When to use** + * + * Use to adapt or extend a service's behavior during the creation of a + * layer. + * * **Details** * * This function modifies the existing implementation of a service in the @@ -3039,18 +3595,18 @@ export const updateService: { * 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. - * + * @category providing services * @since 3.13.0 - * @category utils */ (service: Context.Key, f: (a: Types.NoInfer) => A): (layer: Layer) => Layer /** * Updates a service in the context with a new implementation. * + * **When to use** + * + * Use to adapt or extend a service's behavior during the creation of a + * layer. + * * **Details** * * This function modifies the existing implementation of a service in the @@ -3058,13 +3614,8 @@ export const updateService: { * 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. - * + * @category providing services * @since 3.13.0 - * @category utils */ ( layer: Layer, @@ -3077,70 +3628,111 @@ export const updateService: { layer: Layer, service: Context.Key, f: (a: Types.NoInfer) => A - ): Layer => provide(layer, effect(service, internalEffect.map(service.asEffect(), f))) + ): Layer => provide(layer, effect(service, internalEffect.map(service, f))) ) /** * Creates a fresh version of this layer that will not be shared. * - * @example + * **When to use** + * + * Use when you need two parts of an application to receive separate instances + * of a resource, such as two independent client sessions. + * + * **Gotchas** + * + * Do not use it just to work around confusing composition. By default, sharing + * the same layer value is usually the desired behavior. + * + * **Example** (Creating non-shared layer instances) + * * ```ts - * import { Effect, Layer, Ref, Context } from "effect" + * import { Context, Effect, Layer, Ref } from "effect" * * class Counter extends Context.Service Effect.Effect + * readonly id: number * }>()("Counter") {} * - * // Layer that creates a counter with shared state - * const counterLayer = Layer.effect(Counter)(Effect.gen(function*() { - * const ref = yield* Ref.make(0) - * return { - * count: 0, - * increment: Effect.fn("Counter.increment")(() => - * Ref.update(ref, (n) => n + 1).pipe( - * Effect.flatMap(() => Ref.get(ref)) - * ) - * ) - * } + * class Left extends Context.Service()("Left") {} + * + * class Right extends Context.Service()("Right") {} + * + * const leftLayer = Layer.effect(Left, Effect.gen(function*() { + * const counter = yield* Counter + * return { counterId: counter.id } + * })) + * + * const rightLayer = Layer.effect(Right, Effect.gen(function*() { + * const counter = yield* Counter + * return { counterId: counter.id } * })) * - * // By default, layers are shared - same instance used everywhere - * const sharedProgram = Effect.gen(function*() { - * const counter1 = yield* Counter - * const counter2 = yield* Counter + * const showIds = Effect.gen(function*() { + * const left = yield* Left + * const right = yield* Right + * console.log(`same Counter: ${left.counterId === right.counterId}`) + * }) * - * // Both counter1 and counter2 refer to the same instance - * console.log("Shared layer - same instance") - * }).pipe( - * Effect.provide(counterLayer) - * ) + * const program = Effect.gen(function*() { + * const nextId = yield* Ref.make(0) * - * // Fresh layer creates a new instance each time - * const freshProgram = Effect.gen(function*() { - * const counter1 = yield* Counter - * const counter2 = yield* Counter + * const counterLayer = Layer.effect(Counter, Effect.gen(function*() { + * const id = yield* Ref.updateAndGet(nextId, (n) => n + 1) + * console.log("constructed Counter") + * return { id } + * })) * - * // counter1 and counter2 are different instances - * console.log("Fresh layer - different instances") - * }).pipe( - * Effect.provide(Layer.fresh(counterLayer)) - * ) + * const shared = Layer.merge( + * Layer.provide(leftLayer, counterLayer), + * Layer.provide(rightLayer, counterLayer) + * ) + * + * yield* Effect.provide(showIds, shared) + * + * const freshCounterLayer = Layer.fresh(counterLayer) + * const fresh = Layer.merge( + * Layer.provide(leftLayer, freshCounterLayer), + * Layer.provide(rightLayer, freshCounterLayer) + * ) + * + * yield* Effect.provide(showIds, fresh) + * }) + * + * Effect.runPromise(program) + * // constructed Counter + * // same Counter: true + * // constructed Counter + * // constructed Counter + * // same Counter: false * ``` * + * @category layers * @since 2.0.0 - * @category utils */ export const fresh = (self: Layer): Layer => fromBuildUnsafe((_, scope) => self.build(makeMemoMapUnsafe(), scope)) /** - * 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. + * Builds this layer and keeps it alive until the returned effect is interrupted. + * + * **When to use** + * + * Use when you model your entire application as a layer, such as an HTTP + * server. + * + * **Details** + * + * When the returned effect is interrupted, the layer scope is closed and all + * finalizers registered during layer acquisition are run. + * + * **Example** (Launching an application layer) * - * @example * ```ts - * import { Console, Effect, Layer, Context } from "effect" + * import { Console, Context, Effect, Layer } from "effect" * * class HttpServer extends Context.Service Effect.Effect @@ -3152,7 +3744,7 @@ export const fresh = (self: Layer): Layer => * }>()("Logger") {} * * // Server layer that starts an HTTP server - * const serverLayer = Layer.effect(HttpServer)(Effect.gen(function*() { + * const serverLayer = Layer.effect(HttpServer, Effect.gen(function*() { * yield* Console.log("Starting HTTP server...") * * return { @@ -3167,7 +3759,7 @@ export const fresh = (self: Layer): Layer => * } * })) * - * const loggerLayer = Layer.succeed(Logger)({ + * const loggerLayer = Layer.succeed(Logger, { * log: Effect.fn("Logger.log")((msg: string) => Console.log(`[LOG] ${msg}`)) * }) * @@ -3185,8 +3777,8 @@ export const fresh = (self: Layer): Layer => * // Effect.runFork(application) * ``` * + * @category converting * @since 2.0.0 - * @category conversions */ export const launch = (self: Layer): Effect => internalEffect.scoped(internalEffect.andThen(build(self), internalEffect.never)) @@ -3194,12 +3786,22 @@ export const launch = (self: Layer): Effect = Types.Simplify< & { @@ -3220,12 +3822,21 @@ type AnyEffectOrStream = /** * Creates a mock layer for testing purposes. You can provide a partial - * implementation of the service, and any methods not provided will - * throw an unimplemented defect when called. + * implementation of the service. Any missing members that are `Effect`s, + * `Stream`s, `Channel`s, or functions returning them will fail with an + * unimplemented defect when used. + * + * **Details** + * + * Missing members are represented by a value that can be used as an `Effect`, + * `Stream`, `Channel`, or as a function returning an `Effect`. This lets the + * mock preserve the shape of common service methods while still failing loudly + * when an unimplemented member is exercised. + * + * **Example** (Mocking services for tests) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class UserService extends Context.Service(service: Context.Key): (implementation: PartialEffectful) => Layer /** * Creates a mock layer for testing purposes. You can provide a partial - * implementation of the service, and any methods not provided will - * throw an unimplemented defect when called. + * implementation of the service. Any missing members that are `Effect`s, + * `Stream`s, `Channel`s, or functions returning them will fail with an + * unimplemented defect when used. + * + * **Details** + * + * Missing members are represented by a value that can be used as an `Effect`, + * `Stream`, `Channel`, or as a function returning an `Effect`. This lets the + * mock preserve the shape of common service methods while still failing loudly + * when an unimplemented member is exercised. + * + * **Example** (Mocking services for tests) * - * @example * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class UserService extends Context.Service( service: Context.Key, @@ -3417,12 +4046,15 @@ const ChannelTypeId: Channel.TypeId = "~effect/Channel" // ----------------------------------------------------------------------------- /** - * Ensures that an layer's success type extends a given type `ROut`. + * Ensures that a layer's success type extends a given type `ROut`. + * + * **Details** * * This function provides compile-time type checking to ensure that the success - * value of an layer conforms to a specific type constraint. + * value of a layer conforms to a specific type constraint. + * + * **Example** (Constraining layer success types) * - * @example * ```ts * import { Layer } from "effect" * @@ -3438,22 +4070,25 @@ const ChannelTypeId: Channel.TypeId = "~effect/Channel" * // This would cause a TypeScript compilation error: * // const invalidLayer = satisfiesNumber(StringLayer) * // ^^^^^^^^^^^ - * // Type 'number' is not assignable to type 'string' + * // Type 'string' is not assignable to type 'number' * ``` * + * @category utility types * @since 4.0.0 - * @category Type constraints */ export const satisfiesSuccessType = () => (layer: Layer): Layer => layer /** - * Ensures that an layer's error type extends a given type `E`. + * Ensures that a layer's error type extends a given type `E`. + * + * **Details** * * This function provides compile-time type checking to ensure that the error - * type of an layer conforms to a specific type constraint. + * type of a layer conforms to a specific type constraint. + * + * **Example** (Constraining layer error types) * - * @example * ```ts * import { Layer } from "effect" * @@ -3473,26 +4108,29 @@ export const satisfiesSuccessType = * // Type 'string' is not assignable to type 'Error' * ``` * + * @category utility types * @since 4.0.0 - * @category Type constraints */ export const satisfiesErrorType = () => (layer: Layer): Layer => layer /** - * Ensures that an layer's requirements type extends a given type `R`. + * Ensures that a layer's requirements type extends a given type `R`. + * + * **Details** * * This function provides compile-time type checking to ensure that the - * requirements (context) type of an layer conforms to a specific type constraint. + * requirements type of a layer conforms to a specific type constraint. + * + * **Example** (Constraining layer service requirements) * - * @example * ```ts * import { Layer } from "effect" * * declare const FortyTwoLayer: Layer.Layer * declare const StringLayer: Layer.Layer * - * // Define a constraint that the success type must be a number + * // Define a constraint that the service requirements must be numbers * const satisfiesNumber = Layer.satisfiesServicesType() * * // This works - Layer extends Layer @@ -3504,8 +4142,8 @@ export const satisfiesErrorType = * // Type 'string' is not assignable to type 'number' * ``` * + * @category utility types * @since 4.0.0 - * @category Type constraints */ export const satisfiesServicesType = () => (layer: Layer): Layer => layer @@ -3518,13 +4156,27 @@ export const satisfiesServicesType = * Represents options that can be used to control the behavior of spans created * for layers. * + * **When to use** + * + * Use to configure tracing metadata, stack trace capture, and `onEnd` + * finalization for spans created by `Layer.span` and `Layer.withSpan` during + * layer construction. + * + * **Details** + * + * Extends `Tracer.SpanOptions` with `onEnd`, which runs when the layer span + * ends as the layer scope closes. + * + * @see {@link span} for creating a layer span + * @see {@link withSpan} for wrapping layer construction in a span + * + * @category options * @since 4.0.0 - * @category Models */ export interface SpanOptions extends Tracer.SpanOptions { /** - * A function that will be called when the span associated with the layer is - * ending (i.e. when the `Scope` that the span is associated with is closed). + * Runs when the span associated with the layer ends, which happens when the + * layer scope is closed. */ readonly onEnd?: | ((span: Tracer.Span, exit: Exit.Exit) => Effect) @@ -3535,13 +4187,19 @@ export interface SpanOptions extends Tracer.SpanOptions { * Constructs a new `Layer` which creates a span and registers it as the current * parent span. * + * **Details** + * * This allows you to create a traced scope for layer construction, making all * operations within the layer constructor part of the same trace span. The span - * is automatically closed when the layer's scope is closed. + * is automatically ended when the layer's scope is closed. If `onEnd` is + * provided, it receives the span and the layer scope's exit value when the span + * ends. + * + * **Example** (Tracing layer construction with a span) * - * @example * ```ts - * import { Console, Effect, Layer, Context, type Tracer } from "effect" + * import { Console, Context, Effect, Layer } from "effect" + * import type { Tracer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -3573,8 +4231,8 @@ export interface SpanOptions extends Tracer.SpanOptions { * }) * ``` * - * @since 4.0.0 * @category tracing + * @since 2.0.0 */ export const span = ( name: string, @@ -3593,16 +4251,18 @@ export const span = ( } /** - * Constructs a new `Layer` which takes an existing span and registers it as the - * current parent span. + * Constructs a layer that provides an existing span as the current parent span. * - * This allows you to create a traced scope for layer construction, making all - * operations within the layer constructor part of the same trace span. The span - * is automatically closed when the layer's scope is closed. + * **Details** + * + * The supplied span is made available through `Tracer.ParentSpan` for layers + * that are built with this layer. This API does not create, end, or close the + * span; the caller remains responsible for the span's lifetime. + * + * **Example** (Using an existing parent span) * - * @example * ```ts - * import { Console, Effect, Layer, Context, Tracer } from "effect" + * import { Console, Context, Effect, Layer, Tracer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -3627,23 +4287,26 @@ export const span = ( * })))) * ``` * - * @since 4.0.0 * @category tracing + * @since 2.0.0 */ export const parentSpan = (span: Tracer.AnySpan): Layer => succeedContext(Tracer.ParentSpan.context(span)) /** - * Wraps a Layer with a new tracing span, making all operations in the layer + * Wraps a `Layer` with a new tracing span, making all operations in the layer * constructor part of the named trace span. * + * **Details** + * * This creates a new span for the layer's construction and execution. The span * is automatically ended when the layer's scope is closed. This is useful for * tracking the lifecycle and performance of layer initialization. * - * @example + * **Example** (Wrapping a layer with a span) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -3684,25 +4347,27 @@ export const parentSpan = (span: Tracer.AnySpan): Layer => * * yield* logger.log("Application ready") * return yield* database.query("SELECT * FROM users") - * }).pipe(Effect.provide(appLayer) - * ) + * }).pipe(Effect.provide(appLayer)) * ``` * - * @since 4.0.0 * @category tracing + * @since 2.0.0 */ export const withSpan: { /** - * Wraps a Layer with a new tracing span, making all operations in the layer + * Wraps a `Layer` with a new tracing span, making all operations in the layer * constructor part of the named trace span. * + * **Details** + * * This creates a new span for the layer's construction and execution. The span * is automatically ended when the layer's scope is closed. This is useful for * tracking the lifecycle and performance of layer initialization. * - * @example + * **Example** (Wrapping a layer with a span) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -3743,27 +4408,29 @@ export const withSpan: { * * yield* logger.log("Application ready") * return yield* database.query("SELECT * FROM users") - * }).pipe(Effect.provide(appLayer) - * ) + * }).pipe(Effect.provide(appLayer)) * ``` * - * @since 4.0.0 * @category tracing + * @since 2.0.0 */ (name: string, options?: SpanOptions): ( self: Layer ) => Layer> /** - * Wraps a Layer with a new tracing span, making all operations in the layer + * Wraps a `Layer` with a new tracing span, making all operations in the layer * constructor part of the named trace span. * + * **Details** + * * This creates a new span for the layer's construction and execution. The span * is automatically ended when the layer's scope is closed. This is useful for * tracking the lifecycle and performance of layer initialization. * - * @example + * **Example** (Wrapping a layer with a span) + * * ```ts - * import { Effect, Layer, Context } from "effect" + * import { Context, Effect, Layer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -3804,12 +4471,11 @@ export const withSpan: { * * yield* logger.log("Application ready") * return yield* database.query("SELECT * FROM users") - * }).pipe(Effect.provide(appLayer) - * ) + * }).pipe(Effect.provide(appLayer)) * ``` * - * @since 4.0.0 * @category tracing + * @since 2.0.0 */ (self: Layer, name: string, options?: SpanOptions): Layer> } = function() { @@ -3845,15 +4511,23 @@ export const withSpan: { } as any /** - * Wraps a `Layer` with a new tracing span and sets the span as the parent span. + * Wraps a layer so spans created during its construction use the supplied span + * as their parent. + * + * **Details** * - * This attaches a layer to an existing trace span, making all operations within - * the layer children of the provided parent span. This is useful for integrating - * layer construction into an existing trace hierarchy. + * Use this to attach layer construction to an existing trace hierarchy. This API + * does not create or end the supplied parent span. + * + * When the supplied span is a native `Span`, layer construction also receives + * diagnostic information that helps associate failures with the layer call site. + * External spans are only installed as the parent span and do not add this + * diagnostic call-site information. + * + * **Example** (Attaching layers to an existing parent span) * - * @example * ```ts - * import { Effect, Layer, Context, Tracer } from "effect" + * import { Context, Effect, Layer, Tracer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -3900,20 +4574,28 @@ export const withSpan: { * ) * ``` * - * @since 4.0.0 * @category tracing + * @since 2.0.0 */ export const withParentSpan: { /** - * Wraps a `Layer` with a new tracing span and sets the span as the parent span. + * Wraps a layer so spans created during its construction use the supplied span + * as their parent. + * + * **Details** + * + * Use this to attach layer construction to an existing trace hierarchy. This API + * does not create or end the supplied parent span. + * + * When the supplied span is a native `Span`, layer construction also receives + * diagnostic information that helps associate failures with the layer call site. + * External spans are only installed as the parent span and do not add this + * diagnostic call-site information. * - * This attaches a layer to an existing trace span, making all operations within - * the layer children of the provided parent span. This is useful for integrating - * layer construction into an existing trace hierarchy. + * **Example** (Attaching layers to an existing parent span) * - * @example * ```ts - * import { Effect, Layer, Context, Tracer } from "effect" + * import { Context, Effect, Layer, Tracer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -3960,22 +4642,30 @@ export const withParentSpan: { * ) * ``` * - * @since 4.0.0 * @category tracing + * @since 2.0.0 */ (span: Tracer.AnySpan, options?: Tracer.TraceOptions): ( self: Layer ) => Layer> /** - * Wraps a `Layer` with a new tracing span and sets the span as the parent span. + * Wraps a layer so spans created during its construction use the supplied span + * as their parent. + * + * **Details** * - * This attaches a layer to an existing trace span, making all operations within - * the layer children of the provided parent span. This is useful for integrating - * layer construction into an existing trace hierarchy. + * Use this to attach layer construction to an existing trace hierarchy. This API + * does not create or end the supplied parent span. + * + * When the supplied span is a native `Span`, layer construction also receives + * diagnostic information that helps associate failures with the layer call site. + * External spans are only installed as the parent span and do not add this + * diagnostic call-site information. + * + * **Example** (Attaching layers to an existing parent span) * - * @example * ```ts - * import { Effect, Layer, Context, Tracer } from "effect" + * import { Context, Effect, Layer, Tracer } from "effect" * * class Database extends Context.Service Effect.Effect @@ -4022,8 +4712,8 @@ export const withParentSpan: { * ) * ``` * - * @since 4.0.0 * @category tracing + * @since 2.0.0 */ (self: Layer, span: Tracer.AnySpan, options?: Tracer.TraceOptions): Layer> } = function() { diff --git a/.opencode/node_modules/effect/src/LayerMap.ts b/.opencode/node_modules/effect/src/LayerMap.ts index fb3c71c34079102cff9184e931d5e66fd5783b4e..410c04c43eaecdfad9bb1aabc22139a07187844b 100644 --- a/.opencode/node_modules/effect/src/LayerMap.ts +++ b/.opencode/node_modules/effect/src/LayerMap.ts @@ -1,4 +1,12 @@ /** + * Caches scoped services selected by key and built from layers. + * + * A `LayerMap` turns a key into a cached service `Context` and + * exposes that context as either a `Layer` or a scoped effect. Entries can be + * invalidated explicitly or released after they sit unused. This is useful for + * keyed resource families such as tenant clients, regional connections, or + * environment-specific services. + * * @since 3.14.0 */ import * as Context from "./Context.ts" @@ -15,11 +23,17 @@ const TypeId = "~effect/LayerMap" type IdleTimeToLiveInput = Duration.Input | ((key: K) => Duration.Input) /** - * @since 3.14.0 - * @category Models - * @example + * A scoped, keyed map of layer-built service contexts. + * + * **Details** + * + * A `LayerMap` builds resources for a key on demand, exposes them as a `Layer` + * or scoped `Context`, and can invalidate cached resources for a key. + * + * **Example** (Managing keyed layers) + * * ```ts - * import { Effect, Layer, LayerMap, Context } from "effect" + * import { Context, Effect, Layer, LayerMap } from "effect" * * // Define a service key * const DatabaseService = Context.Service<{ @@ -47,6 +61,9 @@ type IdleTimeToLiveInput = Duration.Input | ((key: K) => Duration.Input) * yield* layerMap.invalidate("development") * }) * ``` + * + * @category models + * @since 3.14.0 */ export interface LayerMap { readonly [TypeId]: typeof TypeId @@ -73,15 +90,12 @@ export interface LayerMap { } /** - * @since 3.14.0 - * @category Constructors + * Creates a `LayerMap` that dynamically provides resources based on a key. * - * A `LayerMap` allows you to create a map of Layer's that can be used to - * dynamically access resources based on a key. + * **Example** (Creating a layer map) * - * @example * ```ts - * import { Effect, Layer, LayerMap, Context } from "effect" + * import { Context, Effect, Layer, LayerMap } from "effect" * * // Define a service key * const DatabaseService = Context.Service<{ @@ -113,6 +127,9 @@ export interface LayerMap { * console.log(result) // "development: SELECT * FROM users" * }) * ``` + * + * @category constructors + * @since 3.14.0 */ export const make: < K, @@ -155,11 +172,17 @@ export const make: < }) /** - * @since 3.14.0 - * @category Constructors - * @example + * Creates a `LayerMap` from a record of predefined layers. + * + * **Details** + * + * The record keys become the keys accepted by the returned `LayerMap`, and the + * record values are the layers built for those keys. + * + * **Example** (Creating a layer map from a record) + * * ```ts - * import { Effect, Layer, LayerMap, Context } from "effect" + * import { Context, Effect, Layer, LayerMap } from "effect" * * // Define service keys * const DevDatabase = Context.Service<{ @@ -193,6 +216,9 @@ export const make: < * console.log("LayerMap created from record") * }) * ``` + * + * @category constructors + * @since 3.14.0 */ export const fromRecord = < const Layers extends Record>, @@ -218,8 +244,23 @@ export const fromRecord = < }) as any /** + * Service class shape produced by `LayerMap.Service`. + * + * **When to use** + * + * Use as the public type for classes returned by `LayerMap.Service` when an API + * needs to accept, return, or alias the generated service class and its static + * helpers. + * + * **Details** + * + * It combines a `Context.Service` tag for the `LayerMap` with default layers + * and helper accessors for retrieving, using, and invalidating keyed resources. + * + * @see {@link Service} for creating concrete `LayerMap` service classes + * + * @category services * @since 3.14.0 - * @category Service */ export interface TagClass< in out Self, @@ -263,15 +304,13 @@ export interface TagClass< } /** - * @since 3.14.0 - * @category Service - * * Create a `LayerMap` service that provides a dynamic set of resources based on * a key. * - * @example + * **Example** (Defining a layer map service) + * * ```ts - * import { Console, Effect, Layer, LayerMap, Context } from "effect" + * import { Console, Context, Effect, Layer, LayerMap } from "effect" * * // Define a service key * const Greeter = Context.Service<{ @@ -303,6 +342,9 @@ export interface TagClass< * Effect.provide(GreeterMap.layer) * ) * ``` + * + * @category services + * @since 3.14.0 */ export const Service = () => < @@ -365,50 +407,62 @@ export const Service = () => Layer.provide(TagClass_.layerNoDeps, options.dependencies as any) : TagClass_.layerNoDeps - TagClass_.get = (key: string) => Layer.unwrap(Effect.map(TagClass_.asEffect(), (layerMap) => layerMap.get(key))) - TagClass_.contextEffect = (key: string) => - Effect.flatMap(TagClass_.asEffect(), (layerMap) => layerMap.contextEffect(key)) - TagClass_.invalidate = (key: string) => Effect.flatMap(TagClass_.asEffect(), (layerMap) => layerMap.invalidate(key)) + TagClass_.get = (key: string) => Layer.unwrap(Effect.map(TagClass_, (layerMap) => layerMap.get(key))) + TagClass_.contextEffect = (key: string) => Effect.flatMap(TagClass_, (layerMap) => layerMap.contextEffect(key)) + TagClass_.invalidate = (key: string) => Effect.flatMap(TagClass_, (layerMap) => layerMap.invalidate(key)) return TagClass as any } /** + * Type helpers for values created with `LayerMap.Service`. + * * @since 3.14.0 - * @category Service */ export declare namespace Service { /** + * Extracts the key type accepted by a `LayerMap.Service` definition. + * + * @category services * @since 3.14.0 - * @category Service */ export type Key = Options extends { readonly lookup: (key: infer K) => any } ? K : Options extends { readonly layers: infer Layers } ? keyof Layers : never /** + * Extracts the layer type produced by a `LayerMap.Service` definition. + * + * @category services * @since 3.14.0 - * @category Service */ export type Layers = Options extends { readonly lookup: (key: infer _K) => infer Layers } ? Layers : Options extends { readonly layers: infer Layers } ? Layers[keyof Layers] : never /** + * Extracts the services provided by the layers in a `LayerMap.Service` + * definition. + * + * @category services * @since 3.14.0 - * @category Service */ export type Success = Layers extends Layer.Layer ? _A : never /** + * Extracts the error type of the layers in a `LayerMap.Service` definition. + * + * @category services * @since 3.14.0 - * @category Service */ export type Error = Layers extends Layer.Layer ? _E : never /** - * @since 3.14.0 - * @category Service + * Extracts the service requirements of the layers in a `LayerMap.Service` + * definition. + * + * @category services + * @since 4.0.0 */ export type Services = Layers extends Layer.Layer ? _R : never } diff --git a/.opencode/node_modules/effect/src/LogLevel.ts b/.opencode/node_modules/effect/src/LogLevel.ts index 8c8449ba10e0087992f4972140acce0976534c73..128305399c40c28db9663b1dace199f4b0ea7e93 100644 --- a/.opencode/node_modules/effect/src/LogLevel.ts +++ b/.opencode/node_modules/effect/src/LogLevel.ts @@ -1,102 +1,10 @@ /** - * @since 2.0.0 - * - * The `LogLevel` module provides utilities for managing log levels in Effect applications. - * It defines a hierarchy of log levels and provides functions for comparing and filtering logs - * based on their severity. - * - * ## Log Level Hierarchy - * - * The log levels are ordered from most severe to least severe: - * - * 1. **All** - Special level that allows all messages - * 2. **Fatal** - System is unusable, immediate attention required - * 3. **Error** - Error conditions that should be investigated - * 4. **Warn** - Warning conditions that may indicate problems - * 5. **Info** - Informational messages about normal operation - * 6. **Debug** - Debug information useful during development - * 7. **Trace** - Very detailed trace information - * 8. **None** - Special level that suppresses all messages - * - * ## Basic Usage - * - * ```ts - * import { Effect } from "effect" - * - * // Basic log level usage - * const program = Effect.gen(function*() { - * yield* Effect.logFatal("System is shutting down") - * yield* Effect.logError("Database connection failed") - * yield* Effect.logWarning("Memory usage is high") - * yield* Effect.logInfo("User logged in") - * yield* Effect.logDebug("Processing request") - * yield* Effect.logTrace("Variable value: xyz") - * }) - * ``` - * - * ## Level Comparison - * - * ```ts - * import { LogLevel } from "effect" - * - * // Check if one level is more severe than another - * console.log(LogLevel.isGreaterThan("Error", "Info")) // true - * console.log(LogLevel.isGreaterThan("Debug", "Error")) // false - * - * // Check if level meets minimum threshold - * console.log(LogLevel.isGreaterThanOrEqualTo("Info", "Debug")) // true - * console.log(LogLevel.isLessThan("Trace", "Info")) // true - * ``` - * - * ## Filtering by Level - * - * ```ts - * import { Logger, LogLevel } from "effect" - * - * // Create a logger that only logs Error and above - * const errorLogger = Logger.make((options) => { - * if (LogLevel.isGreaterThanOrEqualTo(options.logLevel, "Error")) { - * console.log(`[${options.logLevel}] ${options.message}`) - * } - * }) - * - * // Production logger - Info and above - * const productionLogger = Logger.make((options) => { - * if (LogLevel.isGreaterThanOrEqualTo(options.logLevel, "Info")) { - * console.log( - * `${options.date.toISOString()} [${options.logLevel}] ${options.message}` - * ) - * } - * }) + * Log-level types and helpers used by Effect logging. The module defines all + * accepted log levels, the concrete emitted severities, the ordered level list, + * equality and ordering instances, threshold comparison helpers, and an effect + * for checking whether a level is enabled by the current logging settings. * - * // Development logger - Debug and above - * const devLogger = Logger.make((options) => { - * if (LogLevel.isGreaterThanOrEqualTo(options.logLevel, "Debug")) { - * console.log(`[${options.logLevel}] ${options.message}`) - * } - * }) - * ``` - * - * ## Runtime Configuration - * - * ```ts - * import { Config, Effect, Logger, LogLevel } from "effect" - * - * // Configure log level from environment - * const logLevelConfig = Config.string("LOG_LEVEL").pipe( - * Config.withDefault("Info") - * ) - * - * const configurableLogger = Effect.gen(function*() { - * const minLevel = yield* logLevelConfig - * - * return Logger.make((options) => { - * if (LogLevel.isGreaterThanOrEqualTo(options.logLevel, minLevel)) { - * console.log(`[${options.logLevel}] ${options.message}`) - * } - * }) - * }) - * ``` + * @since 2.0.0 */ import type * as Effect from "./Effect.ts" import * as Equ from "./Equivalence.ts" @@ -106,7 +14,15 @@ import * as Ord from "./Order.ts" import * as References from "./References.ts" /** - * Represents the severity level of a log message. + * Represents every level used by Effect logging, including concrete message + * severities and the `All` and `None` sentinel levels. + * + * **When to use** + * + * Use to type values that may be either concrete log message severities or + * logging configuration sentinels. + * + * **Details** * * The levels are ordered from most severe to least severe: * - `All` - Special level that allows all messages @@ -118,7 +34,8 @@ import * as References from "./References.ts" * - `Trace` - Very detailed trace information * - `None` - Special level that suppresses all messages * - * @example + * **Example** (Using log levels) + * * ```ts * import { Effect } from "effect" * @@ -137,30 +54,72 @@ import * as References from "./References.ts" * const debugLevel = "Debug" // LogLevel * ``` * - * @since 4.0.0 * @category models + * @since 2.0.0 */ export type LogLevel = "All" | "Fatal" | "Error" | "Warn" | "Info" | "Debug" | "Trace" | "None" /** - * @since 4.0.0 + * Log levels that represent actual message severities, excluding the `All` and + * `None` sentinel levels. + * + * **When to use** + * + * Use when typing emitted log message severities, such as explicit log calls, + * current log level references, or error-report severity annotations, where + * `All` and `None` are not valid values. + * + * @see {@link LogLevel} for the wider log-level type that also accepts the + * `All` and `None` sentinel levels + * @see {@link values} for the runtime list of all accepted `LogLevel` values, + * including sentinels + * * @category models + * @since 4.0.0 */ export type Severity = "Fatal" | "Error" | "Warn" | "Info" | "Debug" | "Trace" /** - * @since 4.0.0 + * Returns all `LogLevel` values in order from `All` through the concrete severities to + * `None`. + * + * **When to use** + * + * Use to enumerate or validate all accepted `LogLevel` string values, including + * the `All` and `None` sentinel levels. + * + * **Details** + * + * The array order matches the module severity order: `All`, concrete + * severities from `Fatal` to `Trace`, then `None`. + * + * **Gotchas** + * + * This list includes `All` and `None`, so it is not limited to concrete emitted + * severities. + * + * @see {@link Severity} for the concrete message severity type that excludes `All` and `None` + * @see {@link Order} for comparing these levels by severity order + * * @category models + * @since 4.0.0 */ export const values: ReadonlyArray = ["All", "Fatal", "Error", "Warn", "Info", "Debug", "Trace", "None"] /** - * An `Order` instance for `LogLevel` that defines the severity ordering. + * Order instance for `LogLevel` that defines the severity ordering. + * + * **When to use** + * + * Use to sort or compare log levels according to Effect's severity order. + * + * **Details** * * This order treats "All" as the least restrictive level and "None" as the most restrictive, * with Fatal being the most severe actual log level. * - * @example + * **Example** (Ordering log levels) + * * ```ts * import { LogLevel } from "effect" * @@ -170,15 +129,25 @@ export const values: ReadonlyArray = ["All", "Fatal", "Error", "Warn", * console.log(LogLevel.Order("Info", "Info")) // 0 (Info == Info) * ``` * - * @since 2.0.0 * @category ordering + * @since 2.0.0 */ export const Order: Ord.Order = effect.LogLevelOrder /** - * An `Equivalence` instance for log levels using strict equality (`===`). + * Equivalence instance for log levels using strict equality (`===`). + * + * **When to use** + * + * Use to compare two `LogLevel` values when only the exact same level should + * match. + * + * **Details** + * + * Each log level string, including `All` and `None`, only matches itself. + * + * **Example** (Comparing log levels) * - * @example * ```ts * import { LogLevel } from "effect" * @@ -186,6 +155,9 @@ export const Order: Ord.Order = effect.LogLevelOrder * console.log(LogLevel.Equivalence("Error", "Info")) // false * ``` * + * @see {@link Order} for severity ordering rather than exact level equality + * @see {@link isGreaterThanOrEqualTo} for minimum-threshold checks + * * @category instances * @since 4.0.0 */ @@ -194,18 +166,44 @@ export const Equivalence: Equ.Equivalence = Equ.strictEqual( /** * Returns the ordinal value of the log level. * - * @since 4.0.0 + * **When to use** + * + * Use to project a `LogLevel` into the numeric sort key used by + * `LogLevel.Order` when custom ordering code or an integration needs a number + * instead of an `Order` comparison. + * + * **Details** + * + * The mapping is `All` to `Number.MIN_SAFE_INTEGER`, `Trace` to `0`, `Debug` to + * `10000`, `Info` to `20000`, `Warn` to `30000`, `Error` to `40000`, `Fatal` to + * `50000`, and `None` to `Number.MAX_SAFE_INTEGER`. + * + * **Gotchas** + * + * These ordinals are internal sort keys; do not treat them as external severity + * numbers. + * + * @see {@link Order} for comparing log levels without exposing numeric keys + * @see {@link isGreaterThanOrEqualTo} for minimum-threshold filtering + * * @category ordering + * @since 4.0.0 */ export const getOrdinal = (self: LogLevel): number => effect.logLevelToOrder(self) /** * Determines if the first log level is more severe than the second. * + * **When to use** + * + * Use to check whether one log level is strictly more severe than another. + * + * **Details** + * * Returns `true` if `self` represents a more severe level than `that`. - * This is useful for filtering logs based on minimum severity requirements. * - * @example + * **Example** (Checking higher severity) + * * ```ts * import { LogLevel } from "effect" * @@ -227,17 +225,23 @@ export const getOrdinal = (self: LogLevel): number => effect.logLevelToOrder(sel * console.log(isMoreSevereThanInfo("Debug")) // false * ``` * - * @since 2.0.0 * @category ordering + * @since 4.0.0 */ export const isGreaterThan: { /** * Determines if the first log level is more severe than the second. * + * **When to use** + * + * Use to check whether one log level is strictly more severe than another. + * + * **Details** + * * Returns `true` if `self` represents a more severe level than `that`. - * This is useful for filtering logs based on minimum severity requirements. * - * @example + * **Example** (Checking higher severity) + * * ```ts * import { LogLevel } from "effect" * @@ -259,17 +263,23 @@ export const isGreaterThan: { * console.log(isMoreSevereThanInfo("Debug")) // false * ``` * - * @since 2.0.0 * @category ordering + * @since 4.0.0 */ (that: LogLevel): (self: LogLevel) => boolean /** * Determines if the first log level is more severe than the second. * + * **When to use** + * + * Use to check whether one log level is strictly more severe than another. + * + * **Details** + * * Returns `true` if `self` represents a more severe level than `that`. - * This is useful for filtering logs based on minimum severity requirements. * - * @example + * **Example** (Checking higher severity) + * * ```ts * import { LogLevel } from "effect" * @@ -291,8 +301,8 @@ export const isGreaterThan: { * console.log(isMoreSevereThanInfo("Debug")) // false * ``` * - * @since 2.0.0 * @category ordering + * @since 4.0.0 */ (self: LogLevel, that: LogLevel): boolean } = effect.isLogLevelGreaterThan @@ -300,10 +310,17 @@ export const isGreaterThan: { /** * Determines if the first log level is more severe than or equal to the second. * + * **When to use** + * + * Use to implement minimum log-level filtering by checking whether a message + * level meets a threshold. + * + * **Details** + * * Returns `true` if `self` represents a level that is more severe than or equal to `that`. - * This is the most common function for implementing minimum log level filtering. * - * @example + * **Example** (Filtering by minimum log level) + * * ```ts * import { Logger, LogLevel } from "effect" * @@ -333,17 +350,24 @@ export const isGreaterThan: { * const shouldLog = isInfoOrAbove("Error") // true * ``` * - * @since 2.0.0 * @category ordering + * @since 4.0.0 */ export const isGreaterThanOrEqualTo: { /** * Determines if the first log level is more severe than or equal to the second. * + * **When to use** + * + * Use to implement minimum log-level filtering by checking whether a message + * level meets a threshold. + * + * **Details** + * * Returns `true` if `self` represents a level that is more severe than or equal to `that`. - * This is the most common function for implementing minimum log level filtering. * - * @example + * **Example** (Filtering by minimum log level) + * * ```ts * import { Logger, LogLevel } from "effect" * @@ -373,17 +397,24 @@ export const isGreaterThanOrEqualTo: { * const shouldLog = isInfoOrAbove("Error") // true * ``` * - * @since 2.0.0 * @category ordering + * @since 4.0.0 */ (that: LogLevel): (self: LogLevel) => boolean /** * Determines if the first log level is more severe than or equal to the second. * + * **When to use** + * + * Use to implement minimum log-level filtering by checking whether a message + * level meets a threshold. + * + * **Details** + * * Returns `true` if `self` represents a level that is more severe than or equal to `that`. - * This is the most common function for implementing minimum log level filtering. * - * @example + * **Example** (Filtering by minimum log level) + * * ```ts * import { Logger, LogLevel } from "effect" * @@ -413,8 +444,8 @@ export const isGreaterThanOrEqualTo: { * const shouldLog = isInfoOrAbove("Error") // true * ``` * - * @since 2.0.0 * @category ordering + * @since 4.0.0 */ (self: LogLevel, that: LogLevel): boolean } = Ord.isGreaterThanOrEqualTo(Order) @@ -422,10 +453,16 @@ export const isGreaterThanOrEqualTo: { /** * Determines if the first log level is less severe than the second. * + * **When to use** + * + * Use to check whether one log level is strictly less severe than another. + * + * **Details** + * * Returns `true` if `self` represents a less severe level than `that`. - * This is useful for filtering out logs that are too verbose. * - * @example + * **Example** (Checking lower severity) + * * ```ts * import { LogLevel } from "effect" * @@ -447,17 +484,23 @@ export const isGreaterThanOrEqualTo: { * console.log(isLessSevereThanError("Fatal")) // false * ``` * - * @since 2.0.0 * @category ordering + * @since 4.0.0 */ export const isLessThan: { /** * Determines if the first log level is less severe than the second. * + * **When to use** + * + * Use to check whether one log level is strictly less severe than another. + * + * **Details** + * * Returns `true` if `self` represents a less severe level than `that`. - * This is useful for filtering out logs that are too verbose. * - * @example + * **Example** (Checking lower severity) + * * ```ts * import { LogLevel } from "effect" * @@ -479,17 +522,23 @@ export const isLessThan: { * console.log(isLessSevereThanError("Fatal")) // false * ``` * - * @since 2.0.0 * @category ordering + * @since 4.0.0 */ (that: LogLevel): (self: LogLevel) => boolean /** * Determines if the first log level is less severe than the second. * + * **When to use** + * + * Use to check whether one log level is strictly less severe than another. + * + * **Details** + * * Returns `true` if `self` represents a less severe level than `that`. - * This is useful for filtering out logs that are too verbose. * - * @example + * **Example** (Checking lower severity) + * * ```ts * import { LogLevel } from "effect" * @@ -511,8 +560,8 @@ export const isLessThan: { * console.log(isLessSevereThanError("Fatal")) // false * ``` * - * @since 2.0.0 * @category ordering + * @since 4.0.0 */ (self: LogLevel, that: LogLevel): boolean } = Ord.isLessThan(Order) @@ -520,10 +569,17 @@ export const isLessThan: { /** * Determines if the first log level is less severe than or equal to the second. * + * **When to use** + * + * Use to implement maximum log-level filtering by checking whether a level is + * at or below a threshold. + * + * **Details** + * * Returns `true` if `self` represents a level that is less severe than or equal to `that`. - * This is useful for implementing maximum log level filtering. * - * @example + * **Example** (Filtering by maximum log level) + * * ```ts * import { Logger, LogLevel } from "effect" * @@ -551,17 +607,24 @@ export const isLessThan: { * const shouldLog = isInfoOrBelow("Debug") // true * ``` * - * @since 2.0.0 * @category ordering + * @since 4.0.0 */ export const isLessThanOrEqualTo: { /** * Determines if the first log level is less severe than or equal to the second. * + * **When to use** + * + * Use to implement maximum log-level filtering by checking whether a level is + * at or below a threshold. + * + * **Details** + * * Returns `true` if `self` represents a level that is less severe than or equal to `that`. - * This is useful for implementing maximum log level filtering. * - * @example + * **Example** (Filtering by maximum log level) + * * ```ts * import { Logger, LogLevel } from "effect" * @@ -589,17 +652,24 @@ export const isLessThanOrEqualTo: { * const shouldLog = isInfoOrBelow("Debug") // true * ``` * - * @since 2.0.0 * @category ordering + * @since 4.0.0 */ (that: LogLevel): (self: LogLevel) => boolean /** * Determines if the first log level is less severe than or equal to the second. * + * **When to use** + * + * Use to implement maximum log-level filtering by checking whether a level is + * at or below a threshold. + * + * **Details** + * * Returns `true` if `self` represents a level that is less severe than or equal to `that`. - * This is useful for implementing maximum log level filtering. * - * @example + * **Example** (Filtering by maximum log level) + * * ```ts * import { Logger, LogLevel } from "effect" * @@ -627,8 +697,8 @@ export const isLessThanOrEqualTo: { * const shouldLog = isInfoOrBelow("Debug") // true * ``` * - * @since 2.0.0 * @category ordering + * @since 4.0.0 */ (self: LogLevel, that: LogLevel): boolean } = Ord.isLessThanOrEqualTo(Order) @@ -636,10 +706,18 @@ export const isLessThanOrEqualTo: { /** * Checks whether a given log level is enabled for the current fiber. * + * **When to use** + * + * Use to check whether a log level would be emitted under the current fiber's + * minimum log level. + * + * **Details** + * * A log level is enabled when it is greater than or equal to * `References.MinimumLogLevel`. * - * @example + * **Example** (Checking current fiber log level) + * * ```ts * import { Effect, LogLevel, References } from "effect" * @@ -655,8 +733,8 @@ export const isLessThanOrEqualTo: { * ) * ``` * - * @since 4.0.0 * @category filtering + * @since 4.0.0 */ export const isEnabled = (self: LogLevel): Effect.Effect => core.withFiber((fiber) => effect.succeed(!isGreaterThan(fiber.getRef(References.MinimumLogLevel), self))) diff --git a/.opencode/node_modules/effect/src/Logger.ts b/.opencode/node_modules/effect/src/Logger.ts index f7feb82650d250fe2524978dff79e62c0366ccd0..4195216027bededf127dc513e1cdcc1e7b21cd79 100644 --- a/.opencode/node_modules/effect/src/Logger.ts +++ b/.opencode/node_modules/effect/src/Logger.ts @@ -1,102 +1,13 @@ /** - * @since 2.0.0 - * - * The `Logger` module provides a robust and flexible logging system for Effect applications. - * It offers structured logging, multiple output formats, and seamless integration with the - * Effect runtime's tracing and context management. - * - * ## Key Features - * - * - **Structured Logging**: Built-in support for structured log messages with metadata - * - **Multiple Formats**: JSON, LogFmt, Pretty, and custom formatting options - * - **Context Integration**: Automatic capture of fiber context, spans, and annotations - * - **Batching**: Efficient log aggregation and batch processing - * - **File Output**: Direct file writing with configurable batch windows - * - **Composable**: Transform and compose loggers using functional patterns - * - * ## Basic Usage - * - * ```ts - * import { Effect } from "effect" - * - * // Basic logging - * const program = Effect.gen(function*() { - * yield* Effect.log("Application started") - * yield* Effect.logInfo("Processing user request") - * yield* Effect.logWarning("Resource limit approaching") - * yield* Effect.logError("Database connection failed") - * }) - * - * // With structured data - * const structuredLog = Effect.gen(function*() { - * yield* Effect.log("User action", { userId: 123, action: "login" }) - * yield* Effect.logInfo("Request processed", { duration: 150, statusCode: 200 }) - * }) - * ``` - * - * ## Custom Loggers - * - * ```ts - * import { Effect, Logger } from "effect" - * - * // Create a custom logger - * const customLogger = Logger.make((options) => { - * console.log(`[${options.logLevel}] ${options.message}`) - * }) - * - * // Use JSON format for production - * const jsonLogger = Logger.consoleJson + * Defines loggers and log-event data for Effect programs. * - * // Pretty format for development - * const prettyLogger = Logger.consolePretty() - * - * const program = Effect.log("Hello World").pipe( - * Effect.provide(Logger.layer([jsonLogger])) - * ) - * ``` - * - * ## Multiple Loggers + * A `Logger` receives each log event as `Options` and turns it + * into output such as a formatted string, structured object, console write, + * file write, JSON line, or trace span event. This module also includes active + * logger references, console routing helpers, built-in formatters, batching, + * file logging, and layers for installing loggers. * - * ```ts - * import { Effect, Logger } from "effect" - * - * // Combine multiple loggers - * const CombinedLoggerLive = Logger.layer([ - * Logger.consoleJson, - * Logger.consolePretty() - * ]) - * - * const program = Effect.log("Application event").pipe( - * Effect.provide(CombinedLoggerLive) - * ) - * ``` - * - * ## Batched Logging - * - * ```ts - * import { Duration, Effect, Logger } from "effect" - * - * const batchedLogger = Logger.batched(Logger.formatJson, { - * window: Duration.seconds(5), - * flush: (messages) => - * Effect.sync(() => { - * // Process batch of log messages - * console.log("Flushing", messages.length, "log entries") - * }) - * }) - * - * const program = Effect.gen(function*() { - * const logger = yield* batchedLogger - * yield* Effect.provide( - * Effect.all([ - * Effect.log("Event 1"), - * Effect.log("Event 2"), - * Effect.log("Event 3") - * ]), - * Logger.layer([logger]) - * ) - * }) - * ``` + * @since 2.0.0 */ import * as Array from "./Array.ts" import type * as Cause from "./Cause.ts" @@ -120,7 +31,16 @@ import type * as Scope from "./Scope.ts" const TypeId = "~effect/Logger" /** - * @example + * A logger that transforms a runtime log event into an output value. + * + * **Details** + * + * The runtime calls `log` with the message, level, cause, fiber, and timestamp + * for each log event. Use `Logger.layer` to install one or more loggers for an + * effect. + * + * **Example** (Creating custom loggers) + * * ```ts * import { Effect, Logger } from "effect" * @@ -140,8 +60,8 @@ const TypeId = "~effect/Logger" * ) * ``` * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface Logger extends Pipeable { readonly [TypeId]: typeof TypeId @@ -149,7 +69,14 @@ export interface Logger extends Pipeable { } /** - * @example + * Information supplied to a `Logger` for a single log event. + * + * **Details** + * + * Includes the logged message, log level, cause, current fiber, and timestamp. + * + * **Example** (Accessing logger options) + * * ```ts * import { Effect, Logger } from "effect" * @@ -170,8 +97,8 @@ export interface Logger extends Pipeable { * ) * ``` * + * @category options * @since 2.0.0 - * @category models */ export interface Options { readonly message: Message @@ -184,7 +111,8 @@ export interface Options { /** * Returns `true` if the specified value is a `Logger`, otherwise returns `false`. * - * @example + * **Example** (Checking logger values) + * * ```ts * import { Logger } from "effect" * @@ -197,13 +125,22 @@ export interface Options { * console.log(Logger.isLogger({ log: () => {} })) // false * ``` * - * @since 2.0.0 * @category guards + * @since 4.0.0 */ export const isLogger = (u: unknown): u is Logger => Predicate.hasProperty(u, TypeId) /** - * @example + * Context reference containing the active loggers for the current fiber. + * + * **Details** + * + * By default this set includes the default logger and the tracer logger. + * Providing `Logger.layer` replaces or merges with this set depending on its + * options. + * + * **Example** (Accessing current loggers) + * * ```ts * import { Effect, Logger } from "effect" * @@ -223,24 +160,44 @@ export const isLogger = (u: unknown): u is Logger => Predicate * }) * ``` * - * @since 4.0.0 * @category references + * @since 4.0.0 */ export const CurrentLoggers: Context.Reference>> = effect.CurrentLoggers /** - * @since 4.0.0 + * Context reference that routes the built-in default logger and TTY pretty + * console logger to stderr. + * + * **When to use** + * + * Use to route built-in logger output to stderr while keeping stdout reserved + * for protocol messages or data output. + * + * **Details** + * + * The reference defaults to `false`. Providing `true` makes the affected + * loggers call `console.error` instead of `console.log`. + * + * @see {@link defaultLogger} for the runtime logger affected by this reference + * @see {@link consolePretty} for the TTY-mode pretty console logger affected by this reference + * @see {@link withConsoleError} for routing a specific formatter logger to `console.error` + * * @category references + * @since 4.0.0 */ export const LogToStderr: Context.Reference = effect.LogToStderr /** * Transforms the output of a `Logger` using the provided function. * - * This allows you to modify, enhance, or completely change the output format - * of an existing logger without recreating the entire logging logic. + * **When to use** + * + * Use when an existing logger's output should be transformed without recreating the + * logging logic. + * + * **Example** (Transforming logger output) * - * @example * ```ts * import { Logger } from "effect" * @@ -264,17 +221,20 @@ export const LogToStderr: Context.Reference = effect.LogToStderr * ) * ``` * + * @category mapping * @since 2.0.0 - * @category utils */ export const map = dual< /** * Transforms the output of a `Logger` using the provided function. * - * This allows you to modify, enhance, or completely change the output format - * of an existing logger without recreating the entire logging logic. + * **When to use** + * + * Use when an existing logger's output should be transformed without recreating the + * logging logic. + * + * **Example** (Transforming logger output) * - * @example * ```ts * import { Logger } from "effect" * @@ -298,8 +258,8 @@ export const map = dual< * ) * ``` * + * @category mapping * @since 2.0.0 - * @category utils */ (f: (output: Output) => Output2) => ( self: Logger @@ -307,10 +267,13 @@ export const map = dual< /** * Transforms the output of a `Logger` using the provided function. * - * This allows you to modify, enhance, or completely change the output format - * of an existing logger without recreating the entire logging logic. + * **When to use** + * + * Use when an existing logger's output should be transformed without recreating the + * logging logic. + * + * **Example** (Transforming logger output) * - * @example * ```ts * import { Logger } from "effect" * @@ -334,8 +297,8 @@ export const map = dual< * ) * ``` * + * @category mapping * @since 2.0.0 - * @category utils */ (self: Logger, f: (output: Output) => Output2) => Logger >(2, (self, f) => effect.loggerMake((options) => f(self.log(options)))) @@ -344,10 +307,13 @@ export const map = dual< * Returns a new `Logger` that writes all output of the specified `Logger` to * the console using `console.log`. * - * This is useful for taking any logger that produces string or object output - * and routing it to the console for development or debugging purposes. + * **When to use** + * + * Use when a logger's string or object output should be routed to `console.log` for + * development or debugging. + * + * **Example** (Writing logger output with console.log) * - * @example * ```ts * import { Effect, Logger } from "effect" * @@ -364,8 +330,8 @@ export const map = dual< * ) * ``` * + * @category logging * @since 2.0.0 - * @category utils */ export const withConsoleLog = ( self: Logger @@ -378,10 +344,13 @@ export const withConsoleLog = ( * Returns a new `Logger` that writes all output of the specified `Logger` to * the console using `console.error`. * - * This is particularly useful for error logging where you want to ensure - * log messages appear in the error stream (stderr) rather than standard output. + * **When to use** + * + * Use when logger output should be routed to `console.error`, such as error logs that + * should appear on stderr instead of stdout. + * + * **Example** (Writing logger output with console.error) * - * @example * ```ts * import { Effect, Logger } from "effect" * @@ -398,8 +367,8 @@ export const withConsoleLog = ( * ) * ``` * + * @category logging * @since 2.0.0 - * @category utils */ export const withConsoleError = ( self: Logger @@ -412,17 +381,17 @@ export const withConsoleError = ( * Returns a new `Logger` that writes all output of the specified `Logger` to * the console. * + * **Details** + * * Will use the appropriate console method (i.e. `console.log`, `console.error`, * etc.) based upon the current `LogLevel`. * - * - `Debug` -> `console.debug` - * - `Info` -> `console.info` - * - `Trace` -> `console.trace` - * - `Warn` -> `console.warn` - * - `Error` and `Fatal` -> `console.error` - * - Others -> `console.log` + * `Debug` uses `console.debug`, `Info` uses `console.info`, `Trace` uses + * `console.trace`, `Warn` uses `console.warn`, `Error` and `Fatal` use + * `console.error`, and all other levels use `console.log`. + * + * **Example** (Writing logs with level-based console methods) * - * @example * ```ts * import { Effect, Logger } from "effect" * @@ -442,8 +411,8 @@ export const withConsoleError = ( * ) * ``` * - * @since 2.0.0 - * @category utils + * @category logging + * @since 3.8.0 */ export const withLeveledConsole = ( self: Logger @@ -495,6 +464,8 @@ const format = ( space?: number | string | undefined ) => ({ cause, date, fiber, logLevel, message }: Options): string => { + const formatUnknown = (value: unknown): string => + typeof value === "string" ? value : Formatter.format(value, { space }) const formatValue = (value: string): string => value.match(textOnly) ? value : quoteValue(value) const format = (label: string, value: string): string => `${effect.formatLabel(label)}=${formatValue(value)}` const append = (label: string, value: string): string => " " + format(label, value) @@ -505,7 +476,7 @@ const format = ( const messages = Array.ensure(message) for (let i = 0; i < messages.length; i++) { - out += append("message", Formatter.format(messages[i], { space })) + out += append("message", formatUnknown(messages[i])) } if (cause.reasons.length > 0) { @@ -520,7 +491,7 @@ const format = ( const annotations = fiber.getRef(CurrentLogAnnotations) for (const [label, value] of Object.entries(annotations)) { - out += append(label, Formatter.format(value, { space })) + out += append(label, formatUnknown(value)) } return out @@ -529,13 +500,15 @@ const format = ( /** * Creates a new `Logger` from a log function. * + * **Details** + * * The log function receives an options object containing the message, log level, * cause, fiber information, and timestamp, and should return the desired output. * - * @example + * **Example** (Creating loggers from functions) + * * ```ts - * import { Effect, Logger } from "effect" - * import { CurrentLogAnnotations } from "effect/References" + * import { Effect, Logger, References } from "effect" * * // Simple text logger * const textLogger = Logger.make((options) => @@ -548,7 +521,7 @@ const format = ( * level: options.logLevel, * message: options.message, * fiberId: options.fiber.id, - * annotations: options.fiber.getRef(CurrentLogAnnotations) + * annotations: options.fiber.getRef(References.CurrentLogAnnotations) * })) * * // Custom filtering logger @@ -564,8 +537,8 @@ const format = ( * ) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const make: ( log: (options: Options) => Output @@ -574,7 +547,8 @@ export const make: ( /** * The default logging implementation used by the Effect runtime. * - * @example + * **Example** (Using the default logger) + * * ```ts * import { Effect, Logger } from "effect" * @@ -596,20 +570,21 @@ export const make: ( * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 2.0.0 */ export const defaultLogger: Logger = effect.defaultLogger /** * A `Logger` which outputs logs as a string. * - * For example: - * ``` - * timestamp=2025-01-03T14:22:47.570Z level=INFO fiber=#1 message=hello - * ``` + * **Details** + * + * For example, a simple log entry is rendered as + * `timestamp=2025-01-03T14:22:47.570Z level=INFO fiber=#1 message=hello`. + * + * **Example** (Formatting logs as simple strings) * - * @example * ```ts * import { Effect, Logger } from "effect" * @@ -630,8 +605,8 @@ export const defaultLogger: Logger = effect.defaultLogger * ) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const formatSimple = effect.loggerMake(format(escapeDoubleQuotes)) @@ -639,12 +614,13 @@ export const formatSimple = effect.loggerMake(format(escapeDoubleQuotes)) * A `Logger` which outputs logs using the [logfmt](https://brandur.org/logfmt) * style. * - * For example: - * ``` - * timestamp=2025-01-03T14:22:47.570Z level=INFO fiber=#1 message=hello - * ``` + * **Details** + * + * For example, a logfmt entry is rendered as + * `timestamp=2025-01-03T14:22:47.570Z level=INFO fiber=#1 message=hello`. + * + * **Example** (Formatting logs as logfmt) * - * @example * ```ts * import { Effect, Logger } from "effect" * @@ -668,27 +644,23 @@ export const formatSimple = effect.loggerMake(format(escapeDoubleQuotes)) * const productionLogger = Logger.formatLogFmt * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const formatLogFmt = effect.loggerMake(format(JSON.stringify, 0)) /** * A `Logger` which outputs logs using a structured format. * - * For example: - * ``` - * { - * message: [ 'hello' ], - * level: 'INFO', - * timestamp: '2025-01-03T14:25:39.666Z', - * annotations: { key: 'value' }, - * spans: { label: 0 }, - * fiberId: '#1' - * } - * ``` + * **Details** + * + * For example, a structured entry can contain `message: [ "hello" ]`, + * `level: "INFO"`, `timestamp: "2025-01-03T14:25:39.666Z"`, + * `annotations: { key: "value" }`, `spans: { label: 0 }`, and + * `fiberId: "#1"`. + * + * **Example** (Formatting logs as structured objects) * - * @example * ```ts * import { Effect, Logger } from "effect" * @@ -715,8 +687,8 @@ export const formatLogFmt = effect.loggerMake(format(JSON.stringify, 0)) * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const formatStructured: Logger { - * // Send to Elasticsearch, CloudWatch, etc. - * console.log("Sending to external service:", jsonString) - * return jsonString - * }) + * // Adapt the JSON string before giving it to an output sink + * const envelopedJsonLogger = Logger.map( + * Logger.formatJson, + * (jsonString) => `{"service":"api-server","entry":${jsonString}}` + * ) + * + * const envelopedConsoleLogger = Logger.withConsoleLog(envelopedJsonLogger) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const formatJson = map(formatStructured, Formatter.formatJson) /** - * Returns a new `Logger` which will aggregate logs output by the specified - * `Logger` over the provided `window`. After the `window` has elapsed, the - * provided `flush` function will be called with the logs aggregated during - * the last `window`. + * Creates a scoped logger that batches the output of another logger. + * + * **Details** * - * This is useful for implementing efficient batch processing of logs, such as - * writing multiple log entries to a database or file in a single operation. + * The returned effect starts a scoped background process that periodically + * passes buffered outputs to `flush`. When the scope closes, the background + * process is interrupted and any remaining buffered entries are flushed. + * + * **Example** (Batching logger output) * - * @example * ```ts * import { Duration, Effect, Logger } from "effect" * @@ -849,20 +825,21 @@ export const formatJson = map(formatStructured, Formatter.formatJson) * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 2.0.0 */ export const batched = dual< /** - * Returns a new `Logger` which will aggregate logs output by the specified - * `Logger` over the provided `window`. After the `window` has elapsed, the - * provided `flush` function will be called with the logs aggregated during - * the last `window`. + * Creates a scoped logger that batches the output of another logger. + * + * **Details** * - * This is useful for implementing efficient batch processing of logs, such as - * writing multiple log entries to a database or file in a single operation. + * The returned effect starts a scoped background process that periodically + * passes buffered outputs to `flush`. When the scope closes, the background + * process is interrupted and any remaining buffered entries are flushed. + * + * **Example** (Batching logger output) * - * @example * ```ts * import { Duration, Effect, Logger } from "effect" * @@ -902,8 +879,8 @@ export const batched = dual< * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 2.0.0 */ ( options: { @@ -914,15 +891,16 @@ export const batched = dual< self: Logger ) => Effect.Effect, never, Scope.Scope>, /** - * Returns a new `Logger` which will aggregate logs output by the specified - * `Logger` over the provided `window`. After the `window` has elapsed, the - * provided `flush` function will be called with the logs aggregated during - * the last `window`. + * Creates a scoped logger that batches the output of another logger. + * + * **Details** * - * This is useful for implementing efficient batch processing of logs, such as - * writing multiple log entries to a database or file in a single operation. + * The returned effect starts a scoped background process that periodically + * passes buffered outputs to `flush`. When the scope closes, the background + * process is interrupted and any remaining buffered entries are flushed. + * + * **Example** (Batching logger output) * - * @example * ```ts * import { Duration, Effect, Logger } from "effect" * @@ -962,8 +940,8 @@ export const batched = dual< * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 2.0.0 */ ( self: Logger, @@ -1013,13 +991,14 @@ export const batched = dual< * A `Logger` which outputs logs in a "pretty" format and writes them to the * console. * - * For example: - * ``` - * [09:37:17.579] INFO (#1) label=0ms: hello - * key: value - * ``` + * **Details** + * + * For example, pretty output can render as + * `[09:37:17.579] INFO (#1) label=0ms: hello` followed by an annotation line + * such as `key: value`. + * + * **Example** (Logging with pretty console output) * - * @example * ```ts * import { Effect, Logger } from "effect" * @@ -1051,8 +1030,8 @@ export const batched = dual< * const ciLogger = Logger.consolePretty({ colors: false }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const consolePretty: ( options?: { @@ -1067,12 +1046,13 @@ export const consolePretty: ( * A `Logger` which outputs logs using the [logfmt](https://brandur.org/logfmt) * style and writes them to the console. * - * For example: - * ``` - * timestamp=2025-01-03T14:22:47.570Z level=INFO fiber=#1 message=info - * ``` + * **Details** + * + * For example, a console logfmt entry is rendered as + * `timestamp=2025-01-03T14:22:47.570Z level=INFO fiber=#1 message=info`. + * + * **Example** (Logging logfmt output to the console) * - * @example * ```ts * import { Effect, Logger } from "effect" * @@ -1102,28 +1082,25 @@ export const consolePretty: ( * ]) * ``` * - * @since 2.0.0 * @category constructors + * @since 4.0.0 */ export const consoleLogFmt: Logger = withConsoleLog(formatLogFmt) /** - * A `Logger` which outputs logs using a strctured format and writes them to + * A `Logger` which outputs logs using a structured format and writes them to * the console. * - * For example: - * ``` - * { - * message: [ 'info', 'message' ], - * level: 'INFO', - * timestamp: '2025-01-03T14:25:39.666Z', - * annotations: { key: 'value' }, - * spans: { label: 0 }, - * fiberId: '#1' - * } - * ``` + * **Details** + * + * For example, console structured output can contain + * `message: [ "info", "message" ]`, `level: "INFO"`, + * `timestamp: "2025-01-03T14:25:39.666Z"`, + * `annotations: { key: "value" }`, `spans: { label: 0 }`, and + * `fiberId: "#1"`. + * + * **Example** (Logging structured output to the console) * - * @example * ```ts * import { Effect, Logger } from "effect" * @@ -1161,8 +1138,8 @@ export const consoleLogFmt: Logger = withConsoleLog(formatLogFmt) * ) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const consoleStructured: Logger = withConsoleLog(formatStructured) @@ -1170,12 +1147,14 @@ export const consoleStructured: Logger = withConsoleLog(formatStr * A `Logger` which outputs logs using a structured format serialized as JSON * on a single line and writes them to the console. * - * For example: - * ``` - * {"message":["hello"],"level":"INFO","timestamp":"2025-01-03T14:28:57.508Z","annotations":{"key":"value"},"spans":{"label":0},"fiberId":"#1"} - * ``` + * **Details** + * + * For example, console JSON output can render as + * `{"message":["hello"],"level":"INFO","timestamp":"2025-01-03T14:28:57.508Z", + * "annotations":{"key":"value"},"spans":{"label":0},"fiberId":"#1"}`. + * + * **Example** (Logging JSON output to the console) * - * @example * ```ts * import { Effect, Logger } from "effect" * @@ -1218,23 +1197,26 @@ export const consoleStructured: Logger = withConsoleLog(formatStr * ) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const consoleJson: Logger = withConsoleLog(formatJson) /** * A `Logger` which includes log messages as tracer span events. * + * **Details** + * * This logger integrates logging with distributed tracing by recording * all log messages as events on the current trace span, making them visible * in tracing tools like OpenTelemetry, Jaeger, or Zipkin. * - * **Note**: This logger is included in the default set of loggers for all - * Effect programs, so log messages automatically appear as span events unless - * you override the default loggers. + * This logger is included in the default set of loggers for all Effect programs, + * so log messages automatically appear as span events unless you override the + * default loggers. + * + * **Example** (Recording logs as trace span events) * - * @example * ```ts * import { Effect, Logger } from "effect" * @@ -1271,8 +1253,8 @@ export const consoleJson: Logger = withConsoleLog(formatJson) * ) * ``` * - * @since 4.0.0 * @category constructors + * @since 2.0.0 */ export const tracerLogger: Logger = effect.tracerLogger @@ -1280,10 +1262,13 @@ export const tracerLogger: Logger = effect.tracerLogger * Creates a `Layer` which will overwrite the current set of loggers with the * specified array of `loggers`. * + * **Details** + * * If the specified array of `loggers` should be _merged_ with the current set * of loggers (instead of overwriting them), set `mergeWithExisting` to `true`. * - * @example + * **Example** (Providing logger layers) + * * ```ts * import { Effect, Logger } from "effect" * @@ -1314,8 +1299,8 @@ export const tracerLogger: Logger = effect.tracerLogger * ) * ``` * - * @since 4.0.0 * @category context + * @since 4.0.0 */ export const layer = < const Loggers extends ReadonlyArray | Effect.Effect, any, any>> @@ -1342,13 +1327,19 @@ export const layer = < ) /** - * Create a Logger from another string Logger that writes to the specified file. + * Creates a scoped logger that writes string logger output to a file. * - * **Example** + * **Details** + * + * The returned effect requires `FileSystem` and `Scope`. The file logger batches + * string output, writes each batch to the specified path, and flushes remaining + * entries when the scope closes. + * + * **Example** (Writing JSON logs to a file) * * ```ts - * import { NodeFileSystem, NodeRuntime } from "@effect/platform-node" * import { Effect, Layer, Logger } from "effect" + * import { NodeFileSystem, NodeRuntime } from "@effect/platform-node" * * const fileLogger = Logger.formatJson.pipe( * Logger.toFile("/tmp/log.txt") @@ -1365,75 +1356,89 @@ export const layer = < * ) * ``` * - * @example + * **Example** (Writing logs to files) + * * ```ts - * import { NodeFileSystem } from "@effect/platform-node" * import { Duration, Effect, Logger } from "effect" + * import { NodeFileSystem } from "@effect/platform-node" * - * // Basic file logging - * const basicFileLogger = Effect.gen(function*() { - * const fileLogger = yield* Logger.formatJson.pipe( - * Logger.toFile("/tmp/app.log") - * ) - * - * yield* Effect.log("Application started").pipe( - * Effect.provide(Logger.layer([fileLogger])) - * ) - * }).pipe( + * // Basic file logging. The scope keeps the file open while logs are emitted + * // and flushes pending entries when it closes. + * const basicFileLogger = Effect.scoped( + * Effect.gen(function*() { + * const fileLogger = yield* Logger.formatJson.pipe( + * Logger.toFile("/tmp/app.log") + * ) + * + * yield* Effect.log("Application started").pipe( + * Effect.provide(Logger.layer([fileLogger])) + * ) + * }) + * ).pipe( * Effect.provide(NodeFileSystem.layer) * ) * * // File logger with custom batch window - * const batchedFileLogger = Effect.gen(function*() { - * const fileLogger = yield* Logger.formatLogFmt.pipe( - * Logger.toFile("/var/log/myapp.log", { - * flag: "a", - * batchWindow: Duration.seconds(5) - * }) - * ) - * - * yield* Effect.all([ - * Effect.log("Event 1"), - * Effect.log("Event 2"), - * Effect.log("Event 3") - * ]).pipe( - * Effect.provide(Logger.layer([fileLogger])) - * ) - * }).pipe( + * const batchedFileLogger = Effect.scoped( + * Effect.gen(function*() { + * const fileLogger = yield* Logger.formatLogFmt.pipe( + * Logger.toFile("/var/log/myapp.log", { + * flag: "a", + * batchWindow: Duration.seconds(5) + * }) + * ) + * + * yield* Effect.all([ + * Effect.log("Event 1"), + * Effect.log("Event 2"), + * Effect.log("Event 3") + * ]).pipe( + * Effect.provide(Logger.layer([fileLogger])) + * ) + * }) + * ).pipe( * Effect.provide(NodeFileSystem.layer) * ) * * // Multiple loggers: console + file - * const multiLogger = Effect.gen(function*() { - * const fileLogger = yield* Logger.formatJson.pipe( - * Logger.toFile("/tmp/production.log") - * ) - * - * const loggerLive = Logger.layer([ - * Logger.consolePretty(), - * fileLogger - * ]) - * - * yield* Effect.log("Production event").pipe( - * Effect.provide(loggerLive) - * ) - * }).pipe( + * const multiLogger = Effect.scoped( + * Effect.gen(function*() { + * const fileLogger = yield* Logger.formatJson.pipe( + * Logger.toFile("/tmp/production.log") + * ) + * + * const loggerLive = Logger.layer([ + * Logger.consolePretty(), + * fileLogger + * ]) + * + * yield* Effect.log("Production event").pipe( + * Effect.provide(loggerLive) + * ) + * }) + * ).pipe( * Effect.provide(NodeFileSystem.layer) * ) * ``` * - * @since 4.0.0 * @category file + * @since 4.0.0 */ export const toFile = dual< /** - * Create a Logger from another string Logger that writes to the specified file. + * Creates a scoped logger that writes string logger output to a file. + * + * **Details** + * + * The returned effect requires `FileSystem` and `Scope`. The file logger batches + * string output, writes each batch to the specified path, and flushes remaining + * entries when the scope closes. * - * **Example** + * **Example** (Writing JSON logs to a file) * * ```ts - * import { NodeFileSystem, NodeRuntime } from "@effect/platform-node" * import { Effect, Layer, Logger } from "effect" + * import { NodeFileSystem, NodeRuntime } from "@effect/platform-node" * * const fileLogger = Logger.formatJson.pipe( * Logger.toFile("/tmp/log.txt") @@ -1450,65 +1455,73 @@ export const toFile = dual< * ) * ``` * - * @example + * **Example** (Writing logs to files) + * * ```ts - * import { NodeFileSystem } from "@effect/platform-node" * import { Duration, Effect, Logger } from "effect" + * import { NodeFileSystem } from "@effect/platform-node" * - * // Basic file logging - * const basicFileLogger = Effect.gen(function*() { - * const fileLogger = yield* Logger.formatJson.pipe( - * Logger.toFile("/tmp/app.log") - * ) + * // Basic file logging. The scope keeps the file open while logs are emitted + * // and flushes pending entries when it closes. + * const basicFileLogger = Effect.scoped( + * Effect.gen(function*() { + * const fileLogger = yield* Logger.formatJson.pipe( + * Logger.toFile("/tmp/app.log") + * ) * - * yield* Effect.log("Application started").pipe( - * Effect.provide(Logger.layer([fileLogger])) - * ) - * }).pipe( + * yield* Effect.log("Application started").pipe( + * Effect.provide(Logger.layer([fileLogger])) + * ) + * }) + * ).pipe( * Effect.provide(NodeFileSystem.layer) * ) * * // File logger with custom batch window - * const batchedFileLogger = Effect.gen(function*() { - * const fileLogger = yield* Logger.formatLogFmt.pipe( - * Logger.toFile("/var/log/myapp.log", { - * flag: "a", - * batchWindow: Duration.seconds(5) - * }) - * ) + * const batchedFileLogger = Effect.scoped( + * Effect.gen(function*() { + * const fileLogger = yield* Logger.formatLogFmt.pipe( + * Logger.toFile("/var/log/myapp.log", { + * flag: "a", + * batchWindow: Duration.seconds(5) + * }) + * ) * - * yield* Effect.all([ - * Effect.log("Event 1"), - * Effect.log("Event 2"), - * Effect.log("Event 3") - * ]).pipe( - * Effect.provide(Logger.layer([fileLogger])) - * ) - * }).pipe( + * yield* Effect.all([ + * Effect.log("Event 1"), + * Effect.log("Event 2"), + * Effect.log("Event 3") + * ]).pipe( + * Effect.provide(Logger.layer([fileLogger])) + * ) + * }) + * ).pipe( * Effect.provide(NodeFileSystem.layer) * ) * * // Multiple loggers: console + file - * const multiLogger = Effect.gen(function*() { - * const fileLogger = yield* Logger.formatJson.pipe( - * Logger.toFile("/tmp/production.log") - * ) + * const multiLogger = Effect.scoped( + * Effect.gen(function*() { + * const fileLogger = yield* Logger.formatJson.pipe( + * Logger.toFile("/tmp/production.log") + * ) * - * const loggerLive = Logger.layer([ - * Logger.consolePretty(), - * fileLogger - * ]) + * const loggerLive = Logger.layer([ + * Logger.consolePretty(), + * fileLogger + * ]) * - * yield* Effect.log("Production event").pipe( - * Effect.provide(loggerLive) - * ) - * }).pipe( + * yield* Effect.log("Production event").pipe( + * Effect.provide(loggerLive) + * ) + * }) + * ).pipe( * Effect.provide(NodeFileSystem.layer) * ) * ``` * - * @since 4.0.0 * @category file + * @since 4.0.0 */ ( path: string, @@ -1521,13 +1534,19 @@ export const toFile = dual< self: Logger ) => Effect.Effect, PlatformError, Scope.Scope | FileSystem.FileSystem>, /** - * Create a Logger from another string Logger that writes to the specified file. + * Creates a scoped logger that writes string logger output to a file. + * + * **Details** * - * **Example** + * The returned effect requires `FileSystem` and `Scope`. The file logger batches + * string output, writes each batch to the specified path, and flushes remaining + * entries when the scope closes. + * + * **Example** (Writing JSON logs to a file) * * ```ts - * import { NodeFileSystem, NodeRuntime } from "@effect/platform-node" * import { Effect, Layer, Logger } from "effect" + * import { NodeFileSystem, NodeRuntime } from "@effect/platform-node" * * const fileLogger = Logger.formatJson.pipe( * Logger.toFile("/tmp/log.txt") @@ -1544,65 +1563,73 @@ export const toFile = dual< * ) * ``` * - * @example + * **Example** (Writing logs to files) + * * ```ts - * import { NodeFileSystem } from "@effect/platform-node" * import { Duration, Effect, Logger } from "effect" + * import { NodeFileSystem } from "@effect/platform-node" * - * // Basic file logging - * const basicFileLogger = Effect.gen(function*() { - * const fileLogger = yield* Logger.formatJson.pipe( - * Logger.toFile("/tmp/app.log") - * ) + * // Basic file logging. The scope keeps the file open while logs are emitted + * // and flushes pending entries when it closes. + * const basicFileLogger = Effect.scoped( + * Effect.gen(function*() { + * const fileLogger = yield* Logger.formatJson.pipe( + * Logger.toFile("/tmp/app.log") + * ) * - * yield* Effect.log("Application started").pipe( - * Effect.provide(Logger.layer([fileLogger])) - * ) - * }).pipe( + * yield* Effect.log("Application started").pipe( + * Effect.provide(Logger.layer([fileLogger])) + * ) + * }) + * ).pipe( * Effect.provide(NodeFileSystem.layer) * ) * * // File logger with custom batch window - * const batchedFileLogger = Effect.gen(function*() { - * const fileLogger = yield* Logger.formatLogFmt.pipe( - * Logger.toFile("/var/log/myapp.log", { - * flag: "a", - * batchWindow: Duration.seconds(5) - * }) - * ) + * const batchedFileLogger = Effect.scoped( + * Effect.gen(function*() { + * const fileLogger = yield* Logger.formatLogFmt.pipe( + * Logger.toFile("/var/log/myapp.log", { + * flag: "a", + * batchWindow: Duration.seconds(5) + * }) + * ) * - * yield* Effect.all([ - * Effect.log("Event 1"), - * Effect.log("Event 2"), - * Effect.log("Event 3") - * ]).pipe( - * Effect.provide(Logger.layer([fileLogger])) - * ) - * }).pipe( + * yield* Effect.all([ + * Effect.log("Event 1"), + * Effect.log("Event 2"), + * Effect.log("Event 3") + * ]).pipe( + * Effect.provide(Logger.layer([fileLogger])) + * ) + * }) + * ).pipe( * Effect.provide(NodeFileSystem.layer) * ) * * // Multiple loggers: console + file - * const multiLogger = Effect.gen(function*() { - * const fileLogger = yield* Logger.formatJson.pipe( - * Logger.toFile("/tmp/production.log") - * ) + * const multiLogger = Effect.scoped( + * Effect.gen(function*() { + * const fileLogger = yield* Logger.formatJson.pipe( + * Logger.toFile("/tmp/production.log") + * ) * - * const loggerLive = Logger.layer([ - * Logger.consolePretty(), - * fileLogger - * ]) + * const loggerLive = Logger.layer([ + * Logger.consolePretty(), + * fileLogger + * ]) * - * yield* Effect.log("Production event").pipe( - * Effect.provide(loggerLive) - * ) - * }).pipe( + * yield* Effect.log("Production event").pipe( + * Effect.provide(loggerLive) + * ) + * }) + * ).pipe( * Effect.provide(NodeFileSystem.layer) * ) * ``` * - * @since 4.0.0 * @category file + * @since 4.0.0 */ ( self: Logger, diff --git a/.opencode/node_modules/effect/src/ManagedRuntime.ts b/.opencode/node_modules/effect/src/ManagedRuntime.ts index 7ba87fe2fa612e6d76ff9d442108a0caeb7d651b..f3252b7802b706884a3b87568c0f26351ff52e8f 100644 --- a/.opencode/node_modules/effect/src/ManagedRuntime.ts +++ b/.opencode/node_modules/effect/src/ManagedRuntime.ts @@ -1,4 +1,12 @@ /** + * Runs many effects against services built once from a `Layer`. + * + * A `ManagedRuntime` builds the services from a layer, keeps those services + * available for repeated effect runs, and releases acquired resources when it + * is disposed. This module includes the runtime type, a constructor, a guard, + * and runners for connecting Effect programs to JavaScript entry points such as + * promises, callbacks, and synchronous code. + * * @since 2.0.0 */ import type * as Context from "./Context.ts" @@ -13,34 +21,93 @@ import type { Mutable } from "./Types.ts" const TypeId = "~effect/ManagedRuntime" /** - * Checks if the provided argument is a `ManagedRuntime`. + * Checks whether the provided argument is a `ManagedRuntime`. + * + * **When to use** + * + * Use to narrow an unknown value before treating it as a `ManagedRuntime`. + * + * **Details** + * + * The guard checks the internal `ManagedRuntime` marker property. It does not + * build the layer or inspect the runtime's services. + * + * **Gotchas** + * + * Disposed runtimes still carry the marker, so this guard does not prove the + * runtime is still usable. + * + * @see {@link make} for creating managed runtimes this guard recognizes * - * @since 3.9.0 * @category guards + * @since 3.9.0 */ export const isManagedRuntime = (input: unknown): input is ManagedRuntime => hasProperty(input, TypeId) /** + * Type helpers associated with `ManagedRuntime`. + * + * **When to use** + * + * Use to reference type-level helpers for extracting managed runtime services + * and layer errors. + * * @since 3.4.0 */ export declare namespace ManagedRuntime { /** - * @category type-level - * @since 4.0.0 + * Extracts the services available from a `ManagedRuntime`. + * + * **When to use** + * + * Use to derive the service requirements provided by an existing + * `ManagedRuntime` type. + * + * @category utility types + * @since 3.4.0 */ export type Services> = [T] extends [ManagedRuntime] ? R : never /** - * @category type-level + * Extracts the layer construction error type of a `ManagedRuntime`. + * + * **When to use** + * + * Use to derive the layer construction error type from an existing + * `ManagedRuntime` type. + * + * @category utility types * @since 3.4.0 */ export type Error> = [T] extends [ManagedRuntime] ? E : never } /** - * @since 2.0.0 + * A runtime built from a layer that can execute effects requiring that layer's + * services. + * + * **When to use** + * + * Use as the reusable runtime value returned by `make` when application entry + * points or integration code need to run many effects against the same + * layer-built services. + * + * **Details** + * + * The runtime builds and caches its service context and owns the scope for + * resources acquired by the layer. + * + * **Gotchas** + * + * Dispose the runtime with `dispose` or `disposeEffect` when it is no longer + * needed. + * + * @see {@link make} for constructing a managed runtime from a layer + * @see {@link Layer.build} for lower-level scoped layer construction + * * @category models + * @since 2.0.0 */ export interface ManagedRuntime { readonly [TypeId]: typeof TypeId @@ -56,6 +123,11 @@ export interface ManagedRuntime { /** * Executes the effect using the provided Scheduler or using the global * Scheduler if not provided + * + * **When to use** + * + * Use to fork an effect against this runtime's services and get the running + * fiber. */ readonly runFork: ( self: Effect.Effect, @@ -65,7 +137,9 @@ export interface ManagedRuntime { /** * Executes the effect synchronously returning the exit. * - * This method is effectful and should only be invoked at the edges of your + * **When to use** + * + * Use when invoking this effectful method at the edges of your * program. */ readonly runSyncExit: (effect: Effect.Effect) => Exit.Exit @@ -73,7 +147,9 @@ export interface ManagedRuntime { /** * 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 + * **When to use** + * + * Use when invoking this effectful method at the edges of your * program. */ readonly runSync: (effect: Effect.Effect) => A @@ -82,7 +158,9 @@ export interface ManagedRuntime { * 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 + * **When to use** + * + * Use when invoking this effectful method at the edges of your * program. */ readonly runCallback: ( @@ -99,7 +177,9 @@ export interface ManagedRuntime { * 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 + * **When to use** + * + * Use when invoking this effectful method at the edges of your * program. */ readonly runPromise: (effect: Effect.Effect, options?: Effect.RunOptions) => Promise @@ -108,7 +188,9 @@ export interface ManagedRuntime { * 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 + * **When to use** + * + * Use when invoking this effectful method at the edges of your * program. */ readonly runPromiseExit: ( @@ -118,44 +200,75 @@ export interface ManagedRuntime { /** * Dispose of the resources associated with the runtime. + * + * **When to use** + * + * Use to release this runtime's layer resources from Promise-based code. */ readonly dispose: () => Promise /** * Dispose of the resources associated with the runtime. + * + * **When to use** + * + * Use to release this runtime's layer resources from an `Effect` workflow. */ readonly disposeEffect: Effect.Effect } /** - * Convert a Layer into an ManagedRuntime, that can be used to run Effect's using - * your services. + * Creates a `ManagedRuntime` from a layer. + * + * **When to use** + * + * Use to create a reusable runtime from a `Layer` for application entry points + * or integration code that runs many effects without rebuilding services. + * + * **Details** + * + * The layer is built lazily on first use and its context is cached for + * subsequent runs. Resources acquired by the layer are owned by the runtime and + * are released when `dispose` or `disposeEffect` is run. `options.memoMap` can + * be used to share layer memoization with other layer builds. + * + * **Gotchas** + * + * Dispose the runtime when it is no longer needed. A runtime cannot be reused + * after disposal. + * + * **Example** (Creating a managed runtime) * - * @since 2.0.0 - * @category runtime class - * @example * ```ts - * import { Console, Effect, Layer, ManagedRuntime, Context } from "effect" + * import { Context, Effect, Layer, ManagedRuntime } from "effect" * * class Notifications extends Context.Service Effect.Effect * }>()("Notifications") { * static readonly layer = Layer.succeed(this)({ - * notify: Effect.fn("Notifications.notify")((message) => Console.log(message)) + * notify: Effect.fn("Notifications.notify")((message) => + * Effect.sync(() => console.log(message)) + * ) * }) * } * - * async function main() { - * const runtime = ManagedRuntime.make(Notifications.layer) - * await runtime.runPromise(Effect.flatMap( - * Notifications.asEffect(), - * (_) => _.notify("Hello, world!") - * )) - * await runtime.dispose() - * } + * const runtime = ManagedRuntime.make(Notifications.layer) * - * main() + * const program = Effect.flatMap( + * Notifications, + * (_) => _.notify("Hello, world!") + * ).pipe(Effect.ensuring(runtime.disposeEffect)) + * + * runtime.runPromise(program) + * // Hello, world! * ``` + * + * @see {@link ManagedRuntime} for the returned runtime interface + * @see {@link Layer.MemoMap} for shared layer memoization + * @see {@link Layer.build} for lower-level scoped layer construction + * + * @category runtime class + * @since 2.0.0 */ export const make = ( layer: Layer.Layer, diff --git a/.opencode/node_modules/effect/src/Match.ts b/.opencode/node_modules/effect/src/Match.ts index a1d3c322c1b3d568fb6a17a023b5e242fd828c3a..baf5c61f82b25f7c965da577ca2ebc0161786161 100644 --- a/.opencode/node_modules/effect/src/Match.ts +++ b/.opencode/node_modules/effect/src/Match.ts @@ -1,28 +1,12 @@ /** - * The `effect/match` module provides a type-safe pattern matching system for - * TypeScript. Inspired by functional programming, it simplifies conditional - * logic by replacing verbose if/else or switch statements with a structured and - * expressive API. + * Builds pattern matchers for TypeScript values. * - * This module supports matching against types, values, and discriminated unions - * while enforcing exhaustiveness checking to ensure all cases are handled. - * - * Although pattern matching is not yet a native JavaScript feature, - * `effect/match` offers a reliable implementation that is available today. - * - * **How Pattern Matching Works** - * - * Pattern matching follows a structured process: - * - * - **Creating a matcher**: Define a `Matcher` that operates on either a - * specific `Match.type` or `Match.value`. - * - * - **Defining patterns**: Use combinators such as `Match.when`, `Match.not`, - * and `Match.tag` to specify matching conditions. - * - * - **Completing the match**: Apply a finalizer such as `Match.exhaustive`, - * `Match.orElse`, or `Match.option` to determine how unmatched cases should - * be handled. + * `Match` lets you add ordered cases and then finish them with a result, + * fallback, `Option`, or exhaustive check. Use `Match.type` to define a + * reusable matcher for a type, or `Match.value` to match one value immediately. + * Cases can match literal values, predicates, object shapes, tags, negated + * patterns, and common checks such as strings, numbers, records, and class + * instances. * * @since 4.0.0 */ @@ -37,19 +21,15 @@ import type { Unify } from "./Unify.ts" const TypeId = internal.TypeId /** - * Pattern matching follows a structured process: + * Union type for matchers created by `Match.type` and `Match.value`. * - * - **Creating a matcher**: Define a `Matcher` that operates on either a - * specific `Match.type` or `Match.value`. + * **Details** * - * - **Defining patterns**: Use combinators such as `Match.when`, `Match.not`, - * and `Match.tag` to specify matching conditions. + * A `Matcher` carries the input type, accumulated filters, remaining cases, + * result type, and, for value matchers, the provided value being matched. * - * - **Completing the match**: Apply a finalizer such as `Match.exhaustive`, - * `Match.orElse`, or `Match.option` to determine how unmatched cases should - * be handled. + * **Example** (Matching string and number values) * - * @example * ```ts * import { Match } from "effect" * @@ -71,7 +51,7 @@ const TypeId = internal.TypeId * // Output: "string: some input" * ``` * - * @category Model + * @category models * @since 4.0.0 */ export type Matcher = @@ -81,12 +61,15 @@ export type Matcher()` and allows you to define * patterns that will be applied to values of the specified type. It maintains * type-level information about the input type, applied filters, remaining cases, * and expected results. * - * @example + * **Example** (Creating a type matcher) + * * ```ts * import { Match } from "effect" * @@ -120,11 +103,14 @@ export interface TypeMatcher() => Matcher, I, never, never> = internal.type @@ -292,6 +283,10 @@ export const type: () => Matcher, I, never, never> = /** * Creates a matcher from a specific value. * + * **When to use** + * + * Use to match one concrete input immediately. + * * **Details** * * This function allows you to define a `Matcher` directly from a given value, @@ -302,7 +297,7 @@ export const type: () => Matcher, I, never, never> = * Once the matcher is created, you can use pattern-matching functions like * {@link when} to define how different cases should be handled. * - * @example (Matching an Object by Property) + * **Example** (Matching an Object by Property) * * ```ts * import { Match } from "effect" @@ -326,7 +321,7 @@ export const type: () => Matcher, I, never, never> = * * @see {@link type} for creating a matcher from a specific type. * - * @category Creating a matcher + * @category constructors * @since 4.0.0 */ export const value: ( @@ -336,11 +331,14 @@ export const value: ( /** * Creates a match function for a specific value with discriminated union handling. * + * **Details** + * * This function provides a convenient way to pattern match on discriminated unions * by providing an object that maps each `_tag` value to its corresponding handler. * It's similar to a switch statement but with better type safety and exhaustiveness checking. * - * @example + * **Example** (Matching value tags) + * * ```ts * import { Match } from "effect" * @@ -356,18 +354,21 @@ export const value: ( * console.log(message) // "Success: Hello" * ``` * - * @category Creating a matcher + * @category constructors * @since 4.0.0 */ export const valueTags: { /** * Creates a match function for a specific value with discriminated union handling. * + * **Details** + * * This function provides a convenient way to pattern match on discriminated unions * by providing an object that maps each `_tag` value to its corresponding handler. * It's similar to a switch statement but with better type safety and exhaustiveness checking. * - * @example + * **Example** (Matching value tags) + * * ```ts * import { Match } from "effect" * @@ -383,7 +384,7 @@ export const valueTags: { * console.log(message) // "Success: Hello" * ``` * - * @category Creating a matcher + * @category constructors * @since 4.0.0 */ < @@ -395,11 +396,14 @@ export const valueTags: { /** * Creates a match function for a specific value with discriminated union handling. * + * **Details** + * * This function provides a convenient way to pattern match on discriminated unions * by providing an object that maps each `_tag` value to its corresponding handler. * It's similar to a switch statement but with better type safety and exhaustiveness checking. * - * @example + * **Example** (Matching value tags) + * * ```ts * import { Match } from "effect" * @@ -415,7 +419,7 @@ export const valueTags: { * console.log(message) // "Success: Hello" * ``` * - * @category Creating a matcher + * @category constructors * @since 4.0.0 */ < @@ -429,11 +433,14 @@ export const valueTags: { /** * Creates a type-safe match function for discriminated unions based on `_tag` field. * + * **Details** + * * This function allows you to define exhaustive pattern matching for discriminated unions * by providing handlers for each possible `_tag` value. It ensures type safety and * can optionally enforce a specific return type across all branches. * - * @example + * **Example** (Matching type tags) + * * ```ts * import { Match } from "effect" * @@ -466,18 +473,21 @@ export const valueTags: { * // Output: { type: "pending" } * ``` * - * @category Creating a matcher + * @category constructors * @since 4.0.0 */ export const typeTags: { /** * Creates a type-safe match function for discriminated unions based on `_tag` field. * + * **Details** + * * This function allows you to define exhaustive pattern matching for discriminated unions * by providing handlers for each possible `_tag` value. It ensures type safety and * can optionally enforce a specific return type across all branches. * - * @example + * **Example** (Matching type tags) + * * ```ts * import { Match } from "effect" * @@ -510,7 +520,7 @@ export const typeTags: { * // Output: { type: "pending" } * ``` * - * @category Creating a matcher + * @category constructors * @since 4.0.0 */ (): < @@ -525,11 +535,14 @@ export const typeTags: { /** * Creates a type-safe match function for discriminated unions based on `_tag` field. * + * **Details** + * * This function allows you to define exhaustive pattern matching for discriminated unions * by providing handlers for each possible `_tag` value. It ensures type safety and * can optionally enforce a specific return type across all branches. * - * @example + * **Example** (Matching type tags) + * * ```ts * import { Match } from "effect" * @@ -562,7 +575,7 @@ export const typeTags: { * // Output: { type: "pending" } * ``` * - * @category Creating a matcher + * @category constructors * @since 4.0.0 */ (): < @@ -588,7 +601,7 @@ export const typeTags: { * **Important:** This function must be the first step in the matcher pipeline. * If used later, TypeScript will not enforce type consistency correctly. * - * @example (Validating Return Type Consistency) + * **Example** (Validating Return Type Consistency) * * ```ts * import { Match } from "effect" @@ -605,7 +618,7 @@ export const typeTags: { * ) * ``` * - * @category utils + * @category utility types * @since 4.0.0 */ export const withReturnType: () => ( @@ -616,18 +629,19 @@ export const withReturnType: () => ( /** * Defines a condition for matching values. * - * **Details** + * **When to use** * - * This function enables pattern matching by checking whether a given value - * satisfies a condition. It supports both direct value comparisons and - * predicate functions. If the condition is met, the associated function is - * executed. + * Use to add one positive pattern case to a `Match.type` or `Match.value` + * pipeline when a direct value, predicate, or structured object pattern should + * run a handler for matching input. + * + * **Details** * - * This function is useful when defining matchers that need to check for - * specific values or apply logical conditions to determine a match. It works - * well with structured objects and primitive types. + * Supports both direct value comparisons and predicate functions. If the + * pattern matches, the associated function is executed and the matched input is + * removed from the remaining cases tracked by the matcher. * - * @example (Matching with Values and Predicates) + * **Example** (Matching with Values and Predicates) * * ```ts * import { Match } from "effect" @@ -655,10 +669,10 @@ export const withReturnType: () => ( * // Output: "4 is too young" * ``` * - * @see {@link whenOr} Use this when multiple patterns should match in a single - * condition. - * @see {@link whenAnd} Use this when a value must match all provided patterns. - * @see {@link orElse} Provides a fallback when no patterns match. + * @see {@link whenOr} for handling any one of several patterns with the same handler + * @see {@link whenAnd} for requiring all provided patterns to match before running a handler + * @see {@link not} for handling inputs that do not match a pattern + * @see {@link orElse} for providing a fallback when no pattern case matches * * @category Defining patterns * @since 4.0.0 @@ -695,7 +709,8 @@ export const when: < * this function enables combining them into a single statement, making the * matcher more concise. * - * @example + * **Example** (Matching one of several patterns) + * * ```ts * import { Match } from "effect" * @@ -756,7 +771,8 @@ export const whenOr: < * useful when checking for values that need to fulfill multiple criteria at * once. * - * @example + * **Example** (Matching all provided patterns) + * * ```ts * import { Match } from "effect" * @@ -801,6 +817,10 @@ export const whenAnd: < /** * Matches values based on a specified discriminant field. * + * **When to use** + * + * Use to match one or more exact values of a discriminator field. + * * **Details** * * This function is used to define pattern matching on objects that follow a @@ -809,7 +829,8 @@ export const whenAnd: < * multiple values of the discriminant and provides a function to handle the * matched cases. * - * @example + * **Example** (Matching on a discriminator field) + * * ```ts * import { Match, pipe } from "effect" * @@ -826,6 +847,9 @@ export const whenAnd: < * ) * ``` * + * @see {@link discriminators} for defining several discriminator handlers at once + * @see {@link discriminatorStartsWith} for matching string discriminator values by prefix + * * @category Defining patterns * @since 4.0.0 */ @@ -847,19 +871,19 @@ export const discriminator: ( /** * Matches values where a specified field starts with a given prefix. * + * **When to use** + * + * Use to match string discriminator values by prefix instead of exact value. + * * **Details** * - * This function is useful for working with discriminated unions where the - * discriminant field follows a hierarchical or namespaced structure. It allows - * you to match values based on whether the specified field starts with a given - * prefix, making it easier to handle grouped cases. + * Instead of checking for exact matches, this helper matches values that share + * a common prefix. For example, if the discriminant field contains hierarchical + * names like `"A"`, `"A.A"`, and `"B"`, a single `"A"` rule can match both + * `"A"` and `"A.A"`. * - * Instead of checking for exact matches, this function lets you match values - * that share a common prefix. For example, if your discriminant field contains - * hierarchical names like `"A"`, `"A.A"`, and `"B"`, you can match all values - * starting with `"A"` using a single rule. + * **Example** (Matching discriminator prefixes) * - * @example * ```ts * import { Match, pipe } from "effect" * @@ -875,6 +899,8 @@ export const discriminator: ( * console.log(match({ type: "A.A" })) // 1 * ``` * + * @see {@link discriminator} for matching exact discriminator values + * * @category Defining patterns * @since 4.0.0 */ @@ -898,6 +924,11 @@ export const discriminatorStartsWith: ( * Matches values based on a field that serves as a discriminator, mapping each * possible value to a corresponding handler. * + * **When to use** + * + * Use to define several discriminator handlers at once without finalizing the + * matcher. + * * **Details** * * This function simplifies working with discriminated unions by letting you @@ -907,7 +938,8 @@ export const discriminatorStartsWith: ( * possible values of the field, and the values are the corresponding handler * functions. * - * @example + * **Example** (Mapping discriminator handlers) + * * ```ts * import { Match, pipe } from "effect" * @@ -927,6 +959,9 @@ export const discriminatorStartsWith: ( * ) * ``` * + * @see {@link discriminator} for adding one discriminator case to a matcher pipeline + * @see {@link discriminatorsExhaustive} for handling every discriminator value and finalizing the matcher + * * @category Defining patterns * @since 4.0.0 */ @@ -952,21 +987,23 @@ export const discriminators: ( > = internal.discriminators /** - * Matches values based on a discriminator field and **ensures all cases are - * handled**. + * Matches values by a discriminator field and requires every possible case to + * be handled. + * + * **When to use** + * + * Use to define an exhaustive discriminator handler map that finalizes the + * matcher. * - * **Details*+ + * **Details** * - * This function is similar to {@link discriminators}, but **requires that all - * possible cases** are explicitly handled. It is useful when working with - * discriminated unions, where a specific field (e.g., `"type"`) determines the - * shape of an object. Each possible value of the field must have a - * corresponding handler, ensuring **exhaustiveness checking** at compile time. + * This is the exhaustive variant of {@link discriminators}. Each possible + * discriminator value must have a corresponding handler, so the matcher is + * finalized directly and does not require `Match.exhaustive` at the end of the + * pipeline. * - * This function **does not require** `Match.exhaustive` at the end of the - * pipeline because it enforces exhaustiveness by design. + * **Example** (Handling all discriminator cases) * - * @example * ```ts * import { Match, pipe } from "effect" * @@ -985,6 +1022,8 @@ export const discriminators: ( * ) * ``` * + * @see {@link discriminators} for defining discriminator handlers without finalizing the matcher + * * @category Defining patterns * @since 4.0.0 */ @@ -1004,17 +1043,19 @@ export const discriminatorsExhaustive: ( internal.discriminatorsExhaustive /** - * The `Match.tag` function allows pattern matching based on the `_tag` field in - * a [Discriminated Union](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-func.html#discriminated-unions). - * You can specify multiple tags to match within a single pattern. + * Matches discriminated union members by their `_tag` field. * - * **Note** + * **When to use** * - * The `Match.tag` function relies on the convention within the Effect ecosystem - * of naming the tag field as `"_tag"`. Ensure that your discriminated unions - * follow this naming convention for proper functionality. + * Use to handle one or more `_tag` cases with the same matcher branch. + * + * **Details** * - * @example (Matching a Discriminated Union by Tag) + * This helper follows the Effect convention that discriminated unions use + * `"_tag"` as their discriminator field. Use {@link discriminator} for a + * different discriminator field. + * + * **Example** (Matching a Discriminated Union by Tag) * * ```ts * import { Match } from "effect" @@ -1073,10 +1114,10 @@ export const tag: < * useful for handling hierarchical or namespaced tags, where multiple related * cases share a common prefix. * - * @example - ```ts - * import { pipe } from "effect" - * import { Match } from "effect" + * **Example** (Matching tag prefixes) + * + * ```ts + * import { Match, pipe } from "effect" * * const match = pipe( * Match.type<{ _tag: "A" } | { _tag: "B" } | { _tag: "A.A" } | {}>(), @@ -1123,7 +1164,8 @@ export const tagStartsWith: < * returns a transformed result. If all possible tags are handled, you can * enforce exhaustiveness using `Match.exhaustive` to ensure no case is missed. * - * @example + * **Example** (Mapping tag handlers) + * * ```ts * import { Match, pipe } from "effect" * @@ -1177,7 +1219,8 @@ export const tags: < * handled. If a `_tag` value is missing from the mapping, TypeScript will * report an error. * - * @example + * **Example** (Handling all tag cases) + * * ```ts * import { Match, pipe } from "effect" * @@ -1213,17 +1256,19 @@ export const tagsExhaustive: < internal.tagsExhaustive /** - * Excludes a specific value from matching while allowing all others. + * Creates a pattern that excludes a specific value while allowing all others. + * + * **When to use** + * + * Use to add a negative pattern case for inputs that should match when another + * pattern does not. * * **Details** * - * This function is useful when you need to **handle all values except one or - * more specific cases**. Instead of listing all possible matches manually, this - * function simplifies the logic by allowing you to specify values to exclude. - * Any excluded value will bypass the provided function and continue matching - * through other cases. + * Any excluded value bypasses the provided function and continues matching + * through later cases. * - * @example (Ignoring a Specific Value) + * **Example** (Ignoring a Specific Value) * * ```ts * import { Match } from "effect" @@ -1243,6 +1288,8 @@ export const tagsExhaustive: < * // Output: "fallback" * ``` * + * @see {@link when} for adding a positive pattern case + * * @category Defining patterns * @since 4.0.0 */ @@ -1268,10 +1315,17 @@ export const not: < /** * Matches non-empty strings. * + * **When to use** + * + * Use to match strings whose length is greater than zero. + * + * **Details** + * * This predicate matches any string that contains at least one character, * effectively filtering out empty strings (""). * - * @example + * **Example** (Matching non-empty strings) + * * ```ts * import { Match } from "effect" * @@ -1291,7 +1345,9 @@ export const not: < * // Output: "Valid input: " (whitespace-only strings are considered non-empty) * ``` * - * @category Predicates + * @see {@link string} for matching any string + * + * @category predicates * @since 4.0.0 */ export const nonEmptyString: SafeRefinement = internal.nonEmptyString @@ -1299,10 +1355,17 @@ export const nonEmptyString: SafeRefinement = internal.nonEmptySt /** * Matches a specific set of literal values (e.g., `Match.is("a", 42, true)`). * + * **When to use** + * + * Use to match one of several literal primitive or null values. + * + * **Details** + * * This function creates a predicate that matches any of the provided literal values. * It's useful for matching against multiple specific values in a single pattern. * - * @example + * **Example** (Matching literal values) + * * ```ts * import { Match } from "effect" * @@ -1330,7 +1393,7 @@ export const nonEmptyString: SafeRefinement = internal.nonEmptySt * // Output: "Unknown status: pending" * ``` * - * @category Predicates + * @category predicates * @since 4.0.0 */ export const is: < @@ -1340,10 +1403,13 @@ export const is: < /** * Matches values of type `string`. * + * **Details** + * * This predicate refines unknown values to strings, allowing pattern matching * on string types. It's commonly used in type-based matchers to handle string cases. * - * @example + * **Example** (Matching string values) + * * ```ts * import { Match } from "effect" * @@ -1367,11 +1433,18 @@ export const string: Predicate.Refinement = Predicate.isString /** * Matches values of type `number`. * + * **When to use** + * + * Use to match primitive number values, including `NaN` and infinities. + * + * **Details** + * * This predicate refines unknown values to numbers, allowing pattern matching * on numeric types. It matches all number values including integers, floats, * `Infinity`, `-Infinity`, and `NaN`. * - * @example + * **Example** (Matching number values) + * * ```ts * import { Match } from "effect" * @@ -1391,6 +1464,8 @@ export const string: Predicate.Refinement = Predicate.isString * console.log(categorizeNumber("hello")) // "Not a number type" * ``` * + * @see {@link bigint} for matching primitive bigint values + * * @category predicates * @since 4.0.0 */ @@ -1399,11 +1474,23 @@ export const number: Predicate.Refinement = Predicate.isNumber /** * Matches any value without restrictions. * - * This predicate matches absolutely any value, including `undefined`, `null`, - * objects, primitives, functions, etc. It's useful as a catch-all pattern - * or when you need to match any remaining cases. + * **When to use** + * + * Use to define an explicit catch-all pattern when the handler should receive + * the unmatched value. + * + * **Details** + * + * This predicate matches every input, including `undefined`, `null`, objects, + * primitives, and functions. + * + * **Gotchas** + * + * `Match.any` should usually be last because cases are checked in order and + * the first matching case wins. + * + * **Example** (Matching any remaining value) * - * @example * ```ts * import { Match } from "effect" * @@ -1429,7 +1516,10 @@ export const number: Predicate.Refinement = Predicate.isNumber * // Output: "Other: object" * ``` * - * @category Predicates + * @see {@link defined} for matching only non-nullish values + * @see {@link orElse} for providing a fallback after earlier cases + * + * @category predicates * @since 4.0.0 */ export const any: SafeRefinement = internal.any @@ -1437,10 +1527,17 @@ export const any: SafeRefinement = internal.any /** * Matches any defined (non-null and non-undefined) value. * + * **When to use** + * + * Use to exclude only `null` and `undefined` from a match branch. + * + * **Details** + * * This predicate matches values that are neither `null` nor `undefined`, * effectively filtering out nullish values while preserving all other types. * - * @example + * **Example** (Matching defined values) + * * ```ts * import { Match } from "effect" * @@ -1469,7 +1566,9 @@ export const any: SafeRefinement = internal.any * // Output: "Value is null or undefined" * ``` * - * @category Predicates + * @see {@link any} for matching every value without excluding nullish inputs + * + * @category predicates * @since 4.0.0 */ export const defined: (u: A) => u is A & {} = internal.defined @@ -1477,10 +1576,17 @@ export const defined: (u: A) => u is A & {} = internal.defined /** * Matches values of type `boolean`. * + * **When to use** + * + * Use to match primitive boolean values. + * + * **Details** + * * This predicate refines unknown values to booleans, allowing pattern matching * on boolean types. It only matches the primitive boolean values `true` and `false`. * - * @example + * **Example** (Matching boolean values) + * * ```ts * import { Match } from "effect" * @@ -1501,6 +1607,8 @@ export const defined: (u: A) => u is A & {} = internal.defined * console.log(describeTruthiness(1)) // "Some other truthy value" * ``` * + * @see {@link is} for matching specific literal boolean values + * * @category predicates * @since 4.0.0 */ @@ -1511,7 +1619,19 @@ export { /** * Matches the value `undefined`. * - * @category Predicates + * **When to use** + * + * Use when a matcher should handle only inputs with no defined value. + * + * **Details** + * + * This refinement is backed by `Predicate.isUndefined`, which checks + * `input === undefined`. + * + * @see {@link defined} for matching non-nullish values + * @see {@link is} for matching literal values + * + * @category predicates * @since 4.0.0 */ _undefined as undefined @@ -1522,7 +1642,19 @@ export { /** * Matches the value `null`. * - * @category Predicates + * **When to use** + * + * Use to handle only the `null` literal in a match branch. + * + * **Details** + * + * This refinement is backed by `Predicate.isNull`, which checks + * `input === null`. + * + * @see {@link defined} for matching non-nullish values + * @see {@link is} for matching literal values + * + * @category predicates * @since 4.0.0 */ _null as null @@ -1531,10 +1663,17 @@ export { /** * Matches values of type `bigint`. * + * **When to use** + * + * Use to match primitive bigint values. + * + * **Details** + * * This predicate refines unknown values to bigints, allowing pattern matching * on bigint types. BigInts are used for representing integers with arbitrary precision. * - * @example + * **Example** (Matching bigint values) + * * ```ts * import { Match } from "effect" * @@ -1555,6 +1694,8 @@ export { * console.log(processLargeNumber("123")) // "Not a numeric type" * ``` * + * @see {@link number} for matching primitive number values + * * @category predicates * @since 4.0.0 */ @@ -1563,11 +1704,14 @@ export const bigint: Predicate.Refinement = Predicate.isBigInt /** * Matches values of type `symbol`. * + * **Details** + * * This predicate refines unknown values to symbols, allowing pattern matching * on symbol types. Symbols are unique identifiers that are often used as * object keys or for creating private properties. * - * @example + * **Example** (Matching symbol values) + * * ```ts * import { Match } from "effect" * @@ -1598,11 +1742,18 @@ export const symbol: Predicate.Refinement = Predicate.isSymbol /** * Matches values that are instances of `Date`. * + * **When to use** + * + * Use to match `Date` instances. + * + * **Details** + * * This predicate refines unknown values to Date instances, allowing pattern * matching on Date objects. It only matches actual Date instances, not * date strings or timestamps. * - * @example + * **Example** (Matching Date instances) + * * ```ts * import { Match } from "effect" * @@ -1614,32 +1765,38 @@ export const symbol: Predicate.Refinement = Predicate.isSymbol * return `Date: ${date.toISOString().split("T")[0]}` * }), * Match.when(Match.string, (str) => `Date string: ${str}`), - * Match.when( - * Match.number, - * (num) => `Timestamp: ${new Date(num).toISOString()}` - * ), * Match.orElse(() => "Not a date-related value") * ) * * console.log(processDateValue(new Date("2024-01-01"))) // "Date: 2024-01-01" * console.log(processDateValue(new Date("invalid"))) // "Invalid date" * console.log(processDateValue("2024-01-01")) // "Date string: 2024-01-01" - * console.log(processDateValue(1704067200000)) // "Timestamp: 2024-01-01T00:00:00.000Z" + * console.log(processDateValue(1704067200000)) // "Not a date-related value" * ``` * + * @see {@link instanceOf} for matching instances of any constructor + * * @category predicates * @since 4.0.0 */ export const date: Predicate.Refinement = Predicate.isDate /** - * Matches objects where keys are `string` or `symbol` and values are `unknown`. + * Matches non-null objects other than arrays. + * + * **When to use** * - * This predicate refines unknown values to record objects, allowing pattern - * matching on plain objects. It excludes arrays, functions, dates, and other - * special object types, matching only plain objects and object literals. + * Use to match broad non-null, non-array object values. + * + * **Details** + * + * This predicate uses `Predicate.isObject`: it returns `true` for values whose + * runtime type is `"object"`, are not `null`, and are not arrays. It can match + * `Date`, `RegExp`, and class instances; use `instanceOf` or a more specific + * pattern when those cases need to be distinguished. + * + * **Example** (Matching record objects) * - * @example * ```ts * import { Match } from "effect" * @@ -1653,20 +1810,17 @@ export const date: Predicate.Refinement = Predicate.isDate * Match.instanceOf(Array), * (arr) => `Array with ${arr.length} items` * ), - * Match.when(Match.date, () => "Date object"), * Match.orElse(() => "Not an object") * ) * - * console.log(analyzeValue({ name: "Alice", age: 30 })) - * // "Object with 2 properties: [name, age]" - * console.log(analyzeValue([1, 2, 3])) - * // "Array with 3 items" - * console.log(analyzeValue(new Date())) - * // "Date object" - * console.log(analyzeValue("hello")) - * // "Not an object" + * console.log(analyzeValue({ name: "Alice", age: 30 })) // "Object with 2 properties: [name, age]" + * console.log(analyzeValue([1, 2, 3])) // "Array with 3 items" + * console.log(analyzeValue(null)) // "Not an object" + * console.log(analyzeValue("hello")) // "Not an object" * ``` * + * @see {@link instanceOf} for matching a specific constructor + * * @category predicates * @since 4.0.0 */ @@ -1675,10 +1829,18 @@ export const record: Predicate.Refinement `Standard error: ${err.message}` * ), - * Match.when(Match.instanceOf(Date), (date) => `Date: ${date.toISOString()}`), * Match.when( * Match.instanceOf(Array), * (arr) => `Array with ${arr.length} items` * ), + * Match.when( + * Match.instanceOf(Map), + * (map) => `Map with ${map.size} entries` + * ), * Match.orElse((value) => `Other: ${typeof value}`) * ) * - * console.log(handleValue(new CustomError("Failed", 404))) - * // Output: "Custom error: Failed (code: 404)" - * - * console.log(handleValue(new Error("Generic error"))) - * // Output: "Standard error: Generic error" - * - * console.log(handleValue(new Date())) - * // Output: "Date: 2024-01-01T00:00:00.000Z" - * - * console.log(handleValue([1, 2, 3])) - * // Output: "Array with 3 items" + * console.log(handleValue(new CustomError("Failed", 404))) // "Custom error: Failed (code: 404)" + * console.log(handleValue(new Error("Generic error"))) // "Standard error: Generic error" + * console.log(handleValue([1, 2, 3])) // "Array with 3 items" + * console.log(handleValue(new Map([["count", 1]]))) // "Map with 1 entries" * ``` * - * @category Predicates + * @see {@link instanceOfUnsafe} for constructor matching without the same type-safety guarantee + * @see {@link record} for matching broad non-null, non-array objects + * + * @category predicates * @since 4.0.0 */ export const instanceOf: any>( @@ -1727,13 +1888,20 @@ export const instanceOf: any>( ) => SafeRefinement, never> = internal.instanceOf /** - * Unsafe variant of `instanceOf` that allows matching without type narrowing. + * Checks whether a value is an instance of a constructor without type-safe narrowing. + * + * **When to use** + * + * Use when you need constructor matching to use the unsafe refinement type. + * + * **Details** * * This predicate checks if a value is an instance of the specified constructor * but doesn't provide the same type safety guarantees as the regular `instanceOf`. * Use this when you need more flexibility but understand the type safety implications. * - * @example + * **Example** (Matching class instances unsafely) + * * ```ts * import { Match } from "effect" * @@ -1754,6 +1922,8 @@ export const instanceOf: any>( * ) * ``` * + * @see {@link instanceOf} for type-safe constructor matching + * * @category predicates * @since 4.0.0 */ @@ -1764,6 +1934,10 @@ export const instanceOfUnsafe: any>( /** * Provides a fallback value when no patterns match. * + * **When to use** + * + * Use to finalize a matcher with a fallback for unmatched input. + * * **Details** * * This function ensures that a matcher always returns a valid result, even if @@ -1771,7 +1945,7 @@ export const instanceOfUnsafe: any>( * `default` clause in a `switch` statement or the final `else` in an `if-else` * chain. * - * @example (Providing a Default Value When No Patterns Match) + * **Example** (Providing a Default Value When No Patterns Match) * * ```ts * import { Match } from "effect" @@ -1791,7 +1965,11 @@ export const instanceOfUnsafe: any>( * // Output: "fallback" * ``` * - * @category Completion + * @see {@link option} for finalizing unmatched input as `Option.none` + * @see {@link result} for returning unmatched input as a `Result` failure + * @see {@link orElseAbsurd} for finalizing when unmatched input should be impossible + * + * @category completion * @since 4.0.0 */ export const orElse: Ret>( @@ -1802,7 +1980,12 @@ export const orElse: Ret>( // TODO(4.0): Rename to "orThrow"? Like Result.getOrThrow /** - * Throws an error if no pattern matches. + * Returns a matcher that throws an error if no pattern matches. + * + * **When to use** + * + * Use to finalize a matcher when every remaining unmatched case should be + * impossible. * * **Details** * @@ -1814,7 +1997,8 @@ export const orElse: Ret>( * When used, this function removes the need for an explicit fallback case and * ensures that an unmatched value is never silently ignored. * - * @example + * **Example** (Throwing on unmatched input) + * * ```ts * import { Match } from "effect" * @@ -1832,6 +2016,9 @@ export const orElse: Ret>( * // strictMatcher("c" as any) // throws * ``` * + * @see {@link exhaustive} for compile-time exhaustive matcher finalization + * @see {@link orElse} for providing a fallback for unmatched input + * * @category completion * @since 4.0.0 */ @@ -1854,7 +2041,7 @@ export const orElseAbsurd: ( * unmatched case should be explicitly handled rather than returning a default * value or throwing an error. * - * @example (Extracting a User Role with `Match.result`) + * **Example** (Extracting a User Role with `Match.result`) * * ```ts * import { Match } from "effect" @@ -1875,7 +2062,7 @@ export const orElseAbsurd: ( * // Output: { _id: 'Result', _tag: 'Err', err: { role: 'viewer' } } * ``` * - * @category Completion + * @category completion * @since 4.0.0 */ export const result: ( @@ -1885,6 +2072,11 @@ export const result: ( /** * Wraps the match result in an `Option`, representing an optional match. * + * **When to use** + * + * Use to finalize a matcher when unmatched input is expected and should become + * `Option.none`. + * * **Details** * * This function ensures that the result of a matcher is wrapped in an `Option`, @@ -1895,7 +2087,7 @@ export const result: ( * handled explicitly rather than throwing an error or returning a default * value. * - * @example (Extracting a User Role with `Match.option`) + * **Example** (Extracting a User Role with `Match.option`) * * ```ts * import { Match } from "effect" @@ -1916,7 +2108,10 @@ export const result: ( * // Output: { _id: 'Option', _tag: 'None' } * ``` * - * @category Completion + * @see {@link result} for preserving unmatched input as a `Result` failure + * @see {@link orElse} for replacing unmatched input with a fallback value + * + * @category completion * @since 4.0.0 */ export const option: ( @@ -1924,12 +2119,19 @@ export const option: ( ) => [Pr] extends [never] ? (input: I) => Option.Option> : Option.Option> = internal.option /** - * The `Match.exhaustive` method finalizes the pattern matching process by - * ensuring that all possible cases are accounted for. If any case is missing, - * TypeScript will produce a type error. This is particularly useful when - * working with unions, as it helps prevent unintended gaps in pattern matching. + * Completes a matcher that handles every remaining input case. + * + * **When to use** * - * @example (Ensuring All Cases Are Covered) + * Use to require TypeScript to reject incomplete matcher definitions before the + * matcher is turned into a function. + * + * **Details** + * + * If any case is still unmatched, the matcher does not type-check as + * exhaustive. + * + * **Example** (Ensuring All Cases Are Covered) * * ```ts * import { Match } from "effect" @@ -1945,7 +2147,7 @@ export const option: ( * ) * ``` * - * @category Completion + * @category completion * @since 4.0.0 */ export const exhaustive: ( @@ -1957,11 +2159,14 @@ const SafeRefinementId = "~effect/match/Match/SafeRefinement" /** * A safe refinement that narrows types without runtime errors. * + * **Details** + * * `SafeRefinement` provides a way to refine types in pattern matching while * maintaining type safety. Unlike regular predicates, safe refinements can * transform the matched value's type without throwing runtime errors. * - * @example + * **Example** (Using safe refinements) + * * ```ts * import { Match } from "effect" * @@ -1992,39 +2197,27 @@ type Fail = typeof Fail /** * A namespace containing utility types for Match operations. * + * **Details** + * * This namespace provides advanced type-level utilities used internally by the * Match module to perform complex pattern matching, type narrowing, and filter * application. These types enable the sophisticated type inference that makes * pattern matching both type-safe and ergonomic. * - * @example - * ```ts - * import { Match } from "effect" - * - * // Most users won't need to use Types directly, but it powers the type system: - * type MyPattern = Match.Types.PatternBase<{ name: string; age: number }> - * type MyWhenMatch = Match.Types.WhenMatch - * - * // These types are used internally to provide accurate type inference - * const matcher = Match.type().pipe( - * Match.when(Match.string, (s) => s.length), // s is correctly typed as string - * Match.when(Match.number, (n) => n * 2), // n is correctly typed as number - * Match.exhaustive - * ) - * ``` - * - * @category types * @since 4.0.0 */ export declare namespace Types { /** * Computes the matched type when a pattern P is applied to type R. * + * **Details** + * * This utility type determines what type a value will have after successfully * matching against a pattern. It handles refinements, predicates, and complex * object patterns to provide accurate type narrowing. * - * @example + * **Example** (Computing matched types) + * * ```ts * import type { Match } from "effect" * @@ -2062,11 +2255,14 @@ export declare namespace Types { /** * Computes the remaining type when a pattern P is excluded from type R. * + * **Details** + * * This utility type determines what type remains after a `Match.not` pattern * excludes certain values. It's the complement of `WhenMatch`, calculating * what's left after removing the matched portion. * - * @example + * **Example** (Computing unmatched types) + * * ```ts * import type { Match } from "effect" * @@ -2092,11 +2288,14 @@ export declare namespace Types { /** * Resolves a pattern to its matched type for use in type computations. * + * **Details** + * * This utility type processes patterns (predicates, refinements, objects) * and resolves them to their corresponding matched types. It's used internally * to compute type transformations during pattern matching. * - * @example + * **Example** (Resolving match patterns) + * * ```ts * import type { Match } from "effect" * @@ -2117,11 +2316,14 @@ export declare namespace Types { /** * Computes the excluded type when a pattern P is used for exclusion. * + * **Details** + * * This utility type determines what should be excluded from a union type * when a pattern is used in filtering operations. It transforms patterns * into their exclusion-safe representations. * - * @example + * **Example** (Computing excluded patterns) + * * ```ts * import type { Match } from "effect" * @@ -2179,11 +2381,14 @@ export declare namespace Types { /** * Defines the structure for complex object and array patterns. * + * **Details** + * * This type represents patterns that can match against complex data structures * like objects and arrays. It supports nested pattern matching and partial * object matching, enabling sophisticated pattern compositions. * - * @example + * **Example** (Describing complex object patterns) + * * ```ts * import { Match } from "effect" * @@ -2218,28 +2423,12 @@ export declare namespace Types { /** * Defines primitive patterns that can match simple values. * + * **Details** + * * This type represents the building blocks of pattern matching: predicates, * literal values, and safe refinements. These are the atomic patterns that * can be composed into more complex matching logic. * - * @example - * ```ts - * import { Match } from "effect" - * - * // PatternPrimitive includes various pattern types: - * - * // Literal values - * Match.when("exact", () => "matched exact") - * Match.when(42, () => "matched number") - * - * // Predicates - * Match.when(Match.string, (s) => `string: ${s}`) - * Match.when((x: number) => x > 10, (n: number) => `large number: ${n}`) - * - * // Custom refinements - * Match.when(Match.defined, (value) => `defined: ${value}`) - * ``` - * * @category types * @since 4.0.0 */ @@ -2248,11 +2437,14 @@ export declare namespace Types { /** * Represents a filter that excludes specific types from a union. * + * **Details** + * * `Without` is used internally to track which types should be excluded * from consideration during pattern matching. It helps implement the * type-level logic for `Match.not` and other exclusion operations. * - * @example + * **Example** (Tracking excluded types) + * * ```ts * import { Match } from "effect" * @@ -2275,11 +2467,14 @@ export declare namespace Types { /** * Represents a filter that includes only specific types from a union. * + * **Details** + * * `Only` is used internally to track which types should be exclusively * considered during pattern matching. It helps implement the type-level * logic for positive matches and type narrowing. * - * @example + * **Example** (Tracking included types) + * * ```ts * import { Match } from "effect" * @@ -2302,11 +2497,14 @@ export declare namespace Types { /** * Adds a type to the exclusion filter, expanding what should be filtered out. * + * **Details** + * * This utility type manages the accumulation of excluded types during * pattern matching. When multiple exclusions are applied, it combines * them into a single filter representation. * - * @example + * **Example** (Accumulating excluded types) + * * ```ts * import { Match } from "effect" * @@ -2329,11 +2527,14 @@ export declare namespace Types { /** * Adds a type to the inclusion filter, refining what should be included. * + * **Details** + * * This utility type manages the refinement of included types during * pattern matching. It ensures that only the most specific type * constraints are maintained when multiple positive matches are applied. * - * @example + * **Example** (Refining included types) + * * ```ts * import { Match } from "effect" * @@ -2357,11 +2558,14 @@ export declare namespace Types { /** * Applies accumulated filters to an input type, producing the final narrowed type. * + * **Details** + * * This utility type takes the collected inclusion/exclusion filters and * applies them to the input type to compute the final narrowed result. * It's the culmination of the type-level filtering process. * - * @example + * **Example** (Applying accumulated filters) + * * ```ts * import type { Match } from "effect" * @@ -2389,11 +2593,14 @@ export declare namespace Types { /** * Extracts tag values from a discriminated union based on a discriminant field. * + * **Details** + * * This utility type extracts the possible values of a discriminant field * from a union type. It's used internally to implement tag-based pattern * matching for discriminated unions. * - * @example + * **Example** (Extracting discriminator tags) + * * ```ts * import type { Match } from "effect" * @@ -2421,11 +2628,14 @@ export declare namespace Types { /** * Converts an array type to an intersection of its element types. * + * **Details** + * * This utility type takes an array of types and converts them into a single * intersection type. It's used internally when multiple patterns need to * be satisfied simultaneously (like in `Match.whenAnd`). * - * @example + * **Example** (Converting arrays to intersections) + * * ```ts * import type { Match } from "effect" * @@ -2452,11 +2662,14 @@ export declare namespace Types { /** * Extracts and narrows the matched type from an input type given a pattern. * + * **Details** + * * This is the core type utility that performs the actual type extraction * and narrowing logic. It handles the complex type-level computation that * determines what type results from applying a pattern to an input type. * - * @example + * **Example** (Extracting matched types) + * * ```ts * import { Match } from "effect" * diff --git a/.opencode/node_modules/effect/src/Metric.ts b/.opencode/node_modules/effect/src/Metric.ts index bd5447e51e519603e87398ebb432f5a3e6f413b2..1072578e715b64782bca72a203353647a74ce6b5 100644 --- a/.opencode/node_modules/effect/src/Metric.ts +++ b/.opencode/node_modules/effect/src/Metric.ts @@ -1,140 +1,14 @@ /** - * @since 2.0.0 - * - * The `Metric` module provides a comprehensive system for collecting, aggregating, and observing - * application metrics in Effect applications. It offers type-safe, concurrent metrics that can - * be used to monitor performance, track business metrics, and gain insights into application behavior. - * - * ## Key Features - * - * - **Five Metric Types**: Counters, Gauges, Frequencies, Histograms, and Summaries - * - **Type Safety**: Fully typed metrics with compile-time guarantees - * - **Concurrency Safe**: Thread-safe metrics that work with Effect's concurrency model - * - **Attributes**: Tag metrics with key-value attributes for filtering and grouping - * - **Snapshots**: Take point-in-time snapshots of all metrics for reporting - * - **Runtime Integration**: Automatic fiber runtime metrics collection - * - * ## Metric Types - * - * ### Counter - * Tracks cumulative values that only increase or can be reset to zero. - * Perfect for counting events, requests, errors, etc. - * - * ### Gauge - * Represents a single numerical value that can go up or down. - * Ideal for current resource usage, temperature, queue sizes, etc. - * - * ### Frequency - * Counts occurrences of discrete string values. - * Useful for tracking categorical data like HTTP status codes, user actions, etc. - * - * ### Histogram - * Records observations in configurable buckets to analyze distribution. - * Great for response times, request sizes, and other measured values. - * - * ### Summary - * Calculates quantiles over a sliding time window. - * Provides statistical insights into value distributions over time. - * - * ## Basic Usage - * - * ```ts - * import { Effect, Metric } from "effect" - * - * // Create metrics - * const requestCount = Metric.counter("http_requests_total", { - * description: "Total number of HTTP requests" - * }) - * - * const responseTime = Metric.histogram("http_response_time", { - * description: "HTTP response time in milliseconds", - * boundaries: Metric.linearBoundaries({ start: 0, width: 50, count: 20 }) - * }) - * - * // Use metrics in your application - * const handleRequest = Effect.gen(function*() { - * yield* Metric.update(requestCount, 1) - * - * const startTime = yield* Effect.clockWith((clock) => clock.currentTimeMillis) + * Records and reads measurements from Effect programs. * - * // Process request... - * yield* Effect.sleep("100 millis") + * A `Metric` accepts typed update values and stores an aggregated + * state that can be read directly or included in a snapshot. Metrics are used + * for counters, gauges, frequencies, histograms, summaries, and timers. This + * module includes metric constructors, update and read helpers, attributes, + * histogram boundaries, registry snapshots, text dumps, and controls for + * enabling runtime metrics. * - * const endTime = yield* Effect.clockWith((clock) => clock.currentTimeMillis) - * yield* Metric.update(responseTime, endTime - startTime) - * }) - * ``` - * - * ## Attributes and Tagging - * - * ```ts - * import { Effect, Metric } from "effect" - * - * const requestCount = Metric.counter("requests", { - * description: "Number of requests by endpoint and method" - * }) - * - * const program = Effect.gen(function*() { - * // Add attributes to metrics - * yield* Metric.update( - * Metric.withAttributes(requestCount, { - * endpoint: "/api/users", - * method: "GET" - * }), - * 1 - * ) - * - * // Or use withAttributes for compile-time attributes - * const taggedCounter = Metric.withAttributes(requestCount, { - * endpoint: "/api/posts", - * method: "POST" - * }) - * yield* Metric.update(taggedCounter, 1) - * }) - * ``` - * - * ## Advanced Examples - * - * ```ts - * import { Effect, Metric } from "effect" - * - * // Business metrics - * const userSignups = Metric.counter("user_signups_total") - * const activeUsers = Metric.gauge("active_users_current") - * const featureUsage = Metric.frequency("feature_usage") - * - * // Performance metrics - * const dbQueryTime = Metric.summary("db_query_duration", { - * maxAge: "5 minutes", - * maxSize: 1000, - * quantiles: [0.5, 0.9, 0.95, 0.99] - * }) - * - * const program = Effect.gen(function*() { - * // Track user signup - * yield* Metric.update(userSignups, 1) - * - * // Update active user count - * yield* Metric.update(activeUsers, 1250) - * - * // Record feature usage - * yield* Metric.update(featureUsage, "dashboard_view") - * - * // Measure database query time - * yield* Effect.timed(performDatabaseQuery).pipe( - * Effect.tap(([duration]) => Metric.update(dbQueryTime, duration)) - * ) - * }) - * - * // Get metric snapshots - * const getMetrics = Effect.gen(function*() { - * const snapshots = yield* Metric.snapshot - * - * for (const metric of snapshots) { - * console.log(`${metric.id}: ${JSON.stringify(metric.state)}`) - * } - * }) - * ``` + * @since 2.0.0 */ import * as Arr from "./Array.ts" @@ -157,6 +31,8 @@ import type { Contravariant, Covariant } from "./Types.ts" * A `Metric` represents a concurrent metric which accepts update * values of type `Input` and are aggregated to a value of type `State`. * + * **Details** + * * For example, a counter metric would have type `Metric`, * 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 @@ -170,7 +46,8 @@ import type { Contravariant, Covariant } from "./Types.ts" * - Histograms * - Summaries * - * @example + * **Example** (Using multiple metric types) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -224,8 +101,8 @@ import type { Contravariant, Covariant } from "./Types.ts" * }) * ``` * + * @category models * @since 2.0.0 - * @category Models */ export interface Metric extends Pipeable { readonly [TypeId]: typeof TypeId @@ -243,10 +120,13 @@ export interface Metric extends Pipeable { /** * A Counter metric that tracks cumulative values that typically only increase. * - * Counters are useful for tracking monotonically increasing values like request counts, + * **When to use** + * + * Use when counters are useful for tracking monotonically increasing values like request counts, * bytes processed, errors encountered, or any value that accumulates over time. * - * @example + * **Example** (Using counter metrics) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -300,15 +180,16 @@ export interface Metric extends Pipeable { * }) * ``` * + * @category metrics * @since 2.0.0 - * @category Metrics */ export interface Counter extends Metric> {} /** * State interface for Counter metrics containing the current count and increment mode. * - * @example + * **Example** (Reading counter state) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -361,8 +242,8 @@ export interface Counter extends Metric { readonly count: Input extends bigint ? bigint : number @@ -372,11 +253,14 @@ export interface CounterState { /** * A Frequency metric interface that counts occurrences of discrete string values. * - * Frequency metrics are ideal for tracking categorical data where you want to count + * **When to use** + * + * Use when frequency metrics are ideal for tracking categorical data where you want to count * how many times specific string values occur, such as HTTP status codes, user actions, * error types, or any discrete string-based events. * - * @example + * **Example** (Using frequency metrics) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -446,15 +330,16 @@ export interface CounterState { * }) * ``` * + * @category metrics * @since 2.0.0 - * @category Metrics */ export interface Frequency extends Metric {} /** * State interface for Frequency metrics containing occurrence counts for discrete string values. * - * @example + * **Example** (Reading frequency state) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -530,8 +415,8 @@ export interface Frequency extends Metric {} * }) * ``` * - * @since 2.0.0 - * @category Metrics + * @category metrics + * @since 4.0.0 */ export interface FrequencyState { readonly occurrences: ReadonlyMap @@ -540,10 +425,13 @@ export interface FrequencyState { /** * A Gauge metric that tracks instantaneous values that can go up or down. * - * Gauges are useful for tracking current state values like memory usage, CPU load, + * **When to use** + * + * Use when gauges are useful for tracking current state values like memory usage, CPU load, * active connections, queue sizes, or any value that represents a current level. * - * @example + * **Example** (Using gauge metrics) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -590,15 +478,16 @@ export interface FrequencyState { * }) * ``` * + * @category metrics * @since 2.0.0 - * @category Metrics */ export interface Gauge extends Metric> {} /** * State interface for Gauge metrics containing the current instantaneous value. * - * @example + * **Example** (Reading gauge state) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -658,8 +547,8 @@ export interface Gauge extends Metric { readonly value: Input extends bigint ? bigint : number @@ -668,10 +557,13 @@ export interface GaugeState { /** * A Histogram metric that records observations in configurable buckets to analyze value distributions. * - * Histograms are ideal for measuring request durations, response sizes, and other continuous values + * **When to use** + * + * Use when histograms are ideal for measuring request durations, response sizes, and other continuous values * where you need to understand the distribution of values rather than just aggregates. * - * @example + * **Example** (Using histogram metrics) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -746,15 +638,16 @@ export interface GaugeState { * }) * ``` * + * @category metrics * @since 2.0.0 - * @category Metrics */ export interface Histogram extends Metric {} /** * State interface for Histogram metrics containing bucket distributions and aggregate statistics. * - * @example + * **Example** (Reading histogram state) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -832,8 +725,8 @@ export interface Histogram extends Metric {} * }) * ``` * - * @since 2.0.0 - * @category Metrics + * @category metrics + * @since 4.0.0 */ export interface HistogramState { readonly buckets: ReadonlyArray<[number, number]> @@ -846,11 +739,14 @@ export interface HistogramState { /** * A Summary metric that calculates quantiles over a sliding time window of observations. * - * Summaries provide statistical insights into value distributions by tracking specific quantiles + * **When to use** + * + * Use when summaries provide statistical insights into value distributions by tracking specific quantiles * (percentiles) such as median (50th), 95th percentile, 99th percentile, etc. They're ideal for * understanding performance characteristics like response time distributions. * - * @example + * **Example** (Using summary metrics) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -935,15 +831,16 @@ export interface HistogramState { * }) * ``` * + * @category metrics * @since 2.0.0 - * @category Metrics */ export interface Summary extends Metric {} /** * State interface for Summary metrics containing quantile calculations and aggregate statistics. * - * @example + * **Example** (Reading summary state) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -1016,8 +913,8 @@ export interface Summary extends Metric {} * }) * ``` * - * @since 2.0.0 - * @category Metrics + * @category metrics + * @since 4.0.0 */ export interface SummaryState { readonly quantiles: ReadonlyArray @@ -1031,7 +928,8 @@ export interface SummaryState { * The `Metric` namespace provides a comprehensive system for collecting, aggregating, and observing * application metrics in Effect applications. * - * @example + * **Example** (Collecting application metrics) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -1070,13 +968,13 @@ export interface SummaryState { * ``` * * @since 2.0.0 - * @category models */ export declare namespace Metric { /** * Union type representing all available metric types in the Effect metrics system. * - * @example + * **Example** (Inspecting metric types) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -1148,15 +1046,16 @@ export declare namespace Metric { * }) * ``` * - * @since 2.0.0 * @category types + * @since 4.0.0 */ export type Type = "Counter" | "Frequency" | "Gauge" | "Histogram" | "Summary" /** * Union type for metric attributes that can be provided as either an object or array of tuples. * - * @example + * **Example** (Providing attributes in different formats) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -1223,15 +1122,16 @@ export declare namespace Metric { * }) * ``` * - * @since 2.0.0 * @category types + * @since 4.0.0 */ export type Attributes = AttributeSet | ReadonlyArray<[string, string]> /** * Type for metric attributes as a readonly record of string key-value pairs. * - * @example + * **Example** (Combining metric attribute sets) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -1300,15 +1200,16 @@ export declare namespace Metric { * }) * ``` * - * @since 2.0.0 * @category types + * @since 4.0.0 */ export type AttributeSet = Readonly> /** * Utility type to extract the Input type from a Metric type. * - * @example + * **Example** (Extracting metric input types) + * * ```ts * import { Metric } from "effect" * @@ -1349,8 +1250,8 @@ export declare namespace Metric { * // Metric.update(stringFrequency, 404) // ✗ Type error * ``` * - * @since 2.0.0 * @category types + * @since 4.0.0 */ export type Input = A extends Metric ? _Input : never @@ -1358,7 +1259,8 @@ export declare namespace Metric { /** * Utility type to extract the State type from a Metric type. * - * @example + * **Example** (Extracting metric state types) + * * ```ts * import { Effect, Metric } from "effect" * @@ -1408,8 +1310,8 @@ export declare namespace Metric { * }) * ``` * - * @since 2.0.0 * @category types + * @since 4.0.0 */ export type State = A extends Metric ? _State : never @@ -1417,7 +1319,8 @@ export declare namespace Metric { /** * Interface defining the core hooks for metric operations: get, update, and modify. * - * @example + * **Example** (Using metric hooks) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -1453,8 +1356,8 @@ export declare namespace Metric { * }) * ``` * - * @since 2.0.0 * @category interfaces + * @since 4.0.0 */ export interface Hooks { readonly get: (context: Context.Context) => State @@ -1465,7 +1368,8 @@ export declare namespace Metric { /** * Interface containing complete metadata information about a metric. * - * @example + * **Example** (Inspecting metric metadata) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -1518,8 +1422,8 @@ export declare namespace Metric { * }) * ``` * - * @since 4.0.0 * @category interfaces + * @since 4.0.0 */ export interface Metadata { readonly id: string @@ -1532,7 +1436,8 @@ export declare namespace Metric { /** * Protocol interface for metric snapshots containing metadata and current state. * - * @example + * **Example** (Inspecting metric snapshot protocols) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -1590,8 +1495,8 @@ export declare namespace Metric { * }) * ``` * - * @since 4.0.0 * @category interfaces + * @since 4.0.0 */ export interface SnapshotProto { readonly id: string @@ -1604,7 +1509,8 @@ export declare namespace Metric { /** * Union type representing all possible metric snapshot types with their corresponding states. * - * @example + * **Example** (Analyzing metric snapshots) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -1666,8 +1572,8 @@ export declare namespace Metric { * }) * ``` * - * @since 4.0.0 * @category types + * @since 4.0.0 */ export type Snapshot = | SnapshotProto<"Counter", CounterState> @@ -1680,7 +1586,8 @@ export declare namespace Metric { /** * Service key for the current metric attributes context. * - * @example + * **Example** (Using the current attributes key) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -1722,15 +1629,28 @@ export declare namespace Metric { * }) * ``` * + * @category references * @since 4.0.0 - * @category References */ export const CurrentMetricAttributesKey = "effect/Metric/CurrentMetricAttributes" as const /** - * Service class for managing the current metric attributes context. + * Context reference for metric attributes applied from the current Effect + * context. + * + * **When to use** + * + * Use to provide default attributes that should be merged into metric updates + * and reads in a scoped part of a program. + * + * **Details** + * + * The default value is an empty attribute set. Metric reads and updates merge + * these contextual attributes with the metric's own attributes to select the + * metric series being accessed. + * + * **Example** (Providing current metric attributes) * - * @example * ```ts * import { Data, Effect, Metric } from "effect" * @@ -1758,8 +1678,8 @@ export const CurrentMetricAttributesKey = "effect/Metric/CurrentMetricAttributes * }) * ``` * + * @category references * @since 4.0.0 - * @category References */ export const CurrentMetricAttributes = Context.Reference(CurrentMetricAttributesKey, { defaultValue: () => ({}) @@ -1768,10 +1688,30 @@ export const CurrentMetricAttributes = Context.Reference(Cu const MetricRegistryKey = "~effect/observability/Metric/MetricRegistryKey" /** - * Service class for accessing the current metric registry. + * Context reference for the metric registry in the current context. + * + * **When to use** + * + * Use when you need a custom metric registry for an isolated program or test + * instead of the default registry. + * + * **Details** + * + * By default, the reference creates an empty `Map` the first time it is + * resolved. Metrics register their metadata and hooks lazily in this map when + * they are read or updated. * + * **Gotchas** + * + * Because `Context.Reference` caches default values, the default `Map` is + * shared by contexts that do not provide an override. Provide `MetricRegistry` + * with a fresh `Map` when isolation matters. + * + * @see {@link snapshot} for reading all registered metrics from the current `Effect` context + * @see {@link snapshotUnsafe} for reading all registered metrics from an explicit `Context` + * + * @category references * @since 4.0.0 - * @category References */ export const MetricRegistry = Context.Reference>>( MetricRegistryKey, @@ -2147,10 +2087,13 @@ class MetricTransform extends Metric$ extends Metric$ => Predicate.hasProperty(u, "~effect/Metric") && u["~effect/Metric"] === "~effect/Metric" @@ -2175,15 +2118,15 @@ export const isMetric = (u: unknown): u is Metric => * time. Counters can be incremented and decremented and provide a running total * of changes. * - * **Options** + * **Details** + * + * The optional `description` describes the counter, and `attributes` attach + * dimensions to it. Set `bigint` to create a counter that accepts `bigint` + * inputs. Set `incremental` to `true` to create a counter that can only ever be + * incremented. * - * - `description` - A description of the `Counter`. - * - `attributes` - The attributes to associate with the `Counter`. - * - `bigint` - Indicates if the `Counter` should use the `bigint` type. - * - `incremental` - Set to `true` to create a `Counter` that can only ever be - * incremented. + * **Example** (Creating counter metrics) * - * @example * ```ts * import { Data, Effect, Metric } from "effect" * @@ -2225,8 +2168,8 @@ export const isMetric = (u: unknown): u is Metric => * }) * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const counter: { /** @@ -2234,15 +2177,15 @@ export const counter: { * time. Counters can be incremented and decremented and provide a running total * of changes. * - * **Options** + * **Details** * - * - `description` - A description of the `Counter`. - * - `attributes` - The attributes to associate with the `Counter`. - * - `bigint` - Indicates if the `Counter` should use the `bigint` type. - * - `incremental` - Set to `true` to create a `Counter` that can only ever be - * incremented. + * The optional `description` describes the counter, and `attributes` attach + * dimensions to it. Set `bigint` to create a counter that accepts `bigint` + * inputs. Set `incremental` to `true` to create a counter that can only ever be + * incremented. + * + * **Example** (Creating counter metrics) * - * @example * ```ts * import { Data, Effect, Metric } from "effect" * @@ -2284,8 +2227,8 @@ export const counter: { * }) * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ ( name: string, @@ -2301,15 +2244,15 @@ export const counter: { * time. Counters can be incremented and decremented and provide a running total * of changes. * - * **Options** + * **Details** + * + * The optional `description` describes the counter, and `attributes` attach + * dimensions to it. Set `bigint` to create a counter that accepts `bigint` + * inputs. Set `incremental` to `true` to create a counter that can only ever be + * incremented. * - * - `description` - A description of the `Counter`. - * - `attributes` - The attributes to associate with the `Counter`. - * - `bigint` - Indicates if the `Counter` should use the `bigint` type. - * - `incremental` - Set to `true` to create a `Counter` that can only ever be - * incremented. + * **Example** (Creating counter metrics) * - * @example * ```ts * import { Data, Effect, Metric } from "effect" * @@ -2351,8 +2294,8 @@ export const counter: { * }) * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ ( name: string, @@ -2369,16 +2312,19 @@ export const counter: { * Represents a `Gauge` metric that tracks and reports a single numerical value * at a specific moment. * - * Gauges are most suitable for metrics that represent instantaneous values, - * such as memory usage or CPU load. + * **When to use** * - * **Options** + * Use when you need a metric for instantaneous values, such as memory usage or + * CPU load. * - * - `description` - A description of the `Gauge`. - * - `attributes` - The attributes to associate with the `Gauge`. - * - `bigint` - Indicates if the `Gauge` should use the `bigint` type. + * **Details** + * + * The optional `description` describes the gauge, and `attributes` attach + * dimensions to it. Set `bigint` to create a gauge that accepts `bigint` + * inputs. + * + * **Example** (Creating gauge metrics) * - * @example * ```ts * import { Data, Effect, Metric } from "effect" * @@ -2425,24 +2371,27 @@ export const counter: { * }) * ``` * + * @category constructors * @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 most suitable for metrics that represent instantaneous values, - * such as memory usage or CPU load. + * **When to use** + * + * Use when you need a metric for instantaneous values, such as memory usage or + * CPU load. * - * **Options** + * **Details** * - * - `description` - A description of the `Gauge`. - * - `attributes` - The attributes to associate with the `Gauge`. - * - `bigint` - Indicates if the `Gauge` should use the `bigint` type. + * The optional `description` describes the gauge, and `attributes` attach + * dimensions to it. Set `bigint` to create a gauge that accepts `bigint` + * inputs. + * + * **Example** (Creating gauge metrics) * - * @example * ```ts * import { Data, Effect, Metric } from "effect" * @@ -2489,8 +2438,8 @@ export const gauge: { * }) * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ ( name: string, @@ -2504,16 +2453,19 @@ export const gauge: { * Represents a `Gauge` metric that tracks and reports a single numerical value * at a specific moment. * - * Gauges are most suitable for metrics that represent instantaneous values, - * such as memory usage or CPU load. + * **When to use** + * + * Use when you need a metric for instantaneous values, such as memory usage or + * CPU load. * - * **Options** + * **Details** * - * - `description` - A description of the `Gauge`. - * - `attributes` - The attributes to associate with the `Gauge`. - * - `bigint` - Indicates if the `Gauge` should use the `bigint` type. + * The optional `description` describes the gauge, and `attributes` attach + * dimensions to it. Set `bigint` to create a gauge that accepts `bigint` + * inputs. + * + * **Example** (Creating gauge metrics) * - * @example * ```ts * import { Data, Effect, Metric } from "effect" * @@ -2560,8 +2512,8 @@ export const gauge: { * }) * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ ( name: string, @@ -2577,17 +2529,19 @@ export const gauge: { * Creates a `Frequency` metric which can be used to count the number of * occurrences of a string. * - * Frequency metrics are most suitable for counting the number of times a - * specific event or incident occurs. + * **When to use** + * + * Use when you need a metric for counting how often a specific event or + * incident occurs. * - * **Options** + * **Details** * - * - `description` - A description of the `Frequency`. - * - `attributes` - The attributes to associate with the `Frequency`. - * - `preregisteredWords` - Occurrences which are pre-registered with the - * `Frequency` metric occurrences. + * The optional `description` describes the frequency, and `attributes` attach + * dimensions to it. Use `preregisteredWords` to initialize occurrence counts + * for known string values before updates arrive. + * + * **Example** (Creating frequency metrics) * - * @example * ```ts * import { Data, Effect, Metric } from "effect" * @@ -2645,8 +2599,8 @@ export const gauge: { * }) * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const frequency = (name: string, options?: { readonly description?: string | undefined @@ -2657,16 +2611,19 @@ export const frequency = (name: string, options?: { /** * Represents a `Histogram` metric that records observations into buckets. * - * Histogram metrics are most suitable for measuring the distribution of values - * within a range. + * **When to use** + * + * Use when you need a metric for measuring the distribution of values within a + * range. * - * **Options** + * **Details** * - * - `description` - A description of the `Histogram`. - * - `attributes` - The attributes to associate with the `Histogram`. - * - `boundaries` - The bucket boundaries of the `Histogram` + * The optional `description` describes the histogram, and `attributes` attach + * dimensions to it. The required `boundaries` option defines the histogram + * bucket boundaries. + * + * **Example** (Creating histogram metrics) * - * @example * ```ts * import { Data, Effect, Metric } from "effect" * @@ -2721,8 +2678,8 @@ export const frequency = (name: string, options?: { * }) * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const histogram = (name: string, options: { readonly description?: string | undefined @@ -2734,18 +2691,20 @@ export const histogram = (name: string, options: { * Creates a `Summary` metric that records observations and calculates quantiles * which takes a value as input and uses the current time. * - * Summary metrics are most suitable for providing statistical information about - * a set of values, including quantiles. + * **When to use** + * + * Use when you need a metric that records statistical information about a set + * of values, including quantiles. * - * **Options** + * **Details** * - * - `description` - An description of the `Summary`. - * - `attributes` - The attributes to associate with the `Summary`. - * - `maxAge` - The maximum age of observations to retain. - * - `maxSize` - The maximum number of observations to keep. - * - `quantiles` - An array of quantiles to calculate (e.g., [0.5, 0.9]). + * The optional `description` describes the summary, and `attributes` attach + * dimensions to it. `maxAge` controls how long observations are retained, + * `maxSize` controls how many observations are kept, and `quantiles` lists the + * quantiles to calculate, such as `[0.5, 0.9]`. + * + * **Example** (Creating summary metrics) * - * @example * ```ts * import { Data, Duration, Effect, Metric } from "effect" * @@ -2771,13 +2730,10 @@ export const histogram = (name: string, options: { * attributes: { service: "upload-service" } * }) * - * // Simulate recording various response times over time - * for (let i = 0; i < 20; i++) { - * const responseTime = 50 + Math.random() * 200 // 50-250ms + * // Record deterministic response times + * const responseTimes = [82, 96, 104, 118, 135, 170, 210, 240] + * for (const responseTime of responseTimes) { * yield* Metric.update(responseTimeSummary, responseTime) - * - * // Wait a bit to simulate different timestamps - * yield* Effect.sleep(Duration.millis(100)) * } * * // Record some payload sizes @@ -2790,20 +2746,28 @@ export const histogram = (name: string, options: { * const responseStats = yield* Metric.value(responseTimeSummary) * const payloadStats = yield* Metric.value(payloadSizeSummary) * - * // responseStats will contain: - * // - quantiles: [[0.5, Some(125)], [0.9, Some(220)], [0.95, Some(235)], [0.99, Some(245)]] - * // - count: 20, min: ~50, max: ~250, sum: ~2500 - * // - Only observations from the last 5 minutes are included + * console.log({ + * count: responseStats.count, + * min: responseStats.min, + * max: responseStats.max, + * sum: responseStats.sum + * }) // { count: 8, min: 82, max: 240, sum: 1155 } * - * // payloadStats will contain quantile information for recent payload sizes - * // Older observations automatically age out based on maxAge setting + * console.log({ + * count: payloadStats.count, + * min: payloadStats.min, + * max: payloadStats.max, + * sum: payloadStats.sum + * }) // { count: 4, min: 1.2, max: 15.6, sum: 26 } + * + * // Both summaries include quantile information for their configured windows. * * return { responseStats, payloadStats } * }) * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const summary = (name: string, options: { readonly description?: string | undefined @@ -2819,21 +2783,26 @@ export const summary = (name: string, options: { ] as [number, number]) /** - * Creates a `Summary` metric that records observations and calculates quantiles - * which takes a value and the current timestamp as input. + * Creates a `Summary` metric that records observations with explicit + * timestamps and calculates quantiles. + * + * **When to use** + * + * Use when you need a metric that records statistical information about a set + * of values together with timestamps. * - * Summary metrics are most suitable for providing statistical information about - * a set of values, including quantiles. + * **Details** * - * **Options** + * Inputs to this metric are `[value, timestamp]` pairs; the current clock is + * used when reading quantiles against the configured `maxAge`. * - * - `description` - An description of the `Summary`. - * - `attributes` - The attributes to associate with the `Summary`. - * - `maxAge` - The maximum age of observations to retain. - * - `maxSize` - The maximum number of observations to keep. - * - `quantiles` - An array of quantiles to calculate (e.g., [0.5, 0.9]). + * The optional `description` describes the summary, and `attributes` attach + * dimensions to it. `maxAge` controls how long observations are retained, + * `maxSize` controls how many observations are kept, and `quantiles` lists the + * quantiles to calculate, such as `[0.5, 0.9]`. + * + * **Example** (Creating summaries with explicit timestamps) * - * @example * ```ts * import { Metric } from "effect" * @@ -2848,8 +2817,8 @@ export const summary = (name: string, options: { * ) * ``` * - * @since 2.0.0 - * @category Constructors + * @category constructors + * @since 4.0.0 */ export const summaryWithTimestamp = (name: string, options: { readonly description?: string | undefined @@ -2863,13 +2832,16 @@ export const summaryWithTimestamp = (name: string, options: { * Creates a timer metric, based on a `Histogram`, which keeps track of * durations in milliseconds. * + * **Details** + * * The unit of time will automatically be added to the metric as a tag (i.e. * `"time_unit: milliseconds"`). * * If `options.boundaries` is not provided, the boundaries will be computed * using `Metric.exponentialBoundaries({ start: 0.5, factor: 2, count: 35 })`. * - * @example + * **Example** (Recording durations with a timer) + * * ```ts * import { Data, Duration, Effect, Metric } from "effect" * @@ -2883,19 +2855,23 @@ export const summaryWithTimestamp = (name: string, options: { * attributes: { service: "user-api" } * }) * - * // Simulate an API operation and measure its duration + * // Record a measured API operation duration * const apiOperation = Effect.gen(function*() { - * const start = Date.now() - * yield* Effect.sleep(Duration.millis(100)) // Simulate work - * const duration = Duration.millis(Date.now() - start) - * - * // Update the timer with the measured duration + * const duration = Duration.millis(120) * yield* Metric.update(apiRequestTimer, duration) + * + * const state = yield* Metric.value(apiRequestTimer) + * console.log({ + * count: state.count, + * min: state.min, + * max: state.max, + * sum: state.sum + * }) // { count: 1, min: 120, max: 120, sum: 120 } * }) * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const timer = (name: string, options?: { readonly description?: string | undefined @@ -2913,15 +2889,17 @@ export const timer = (name: string, options?: { /** * Retrieves the current state of the specified `Metric`. * - * This function returns an Effect that, when executed, will provide the current - * aggregated state of the metric. The state type depends on the metric type: - * - Counter: `{ count: number | bigint }` - * - Gauge: `{ value: number | bigint }` - * - Frequency: `{ occurrences: Map }` - * - Histogram: `{ buckets: Array<[number, number]>, count: number, min: number, max: number, sum: number }` - * - Summary: `{ quantiles: Array<[number, number | undefined]>, count: number, min: number, max: number, sum: number }` + * **Details** + * + * The returned state depends on the metric type. Counters return + * `CounterState` with `count` and `incremental`, gauges return + * `GaugeState` with `value`, frequencies return + * `FrequencyState` with `occurrences`, histograms return `HistogramState` with + * buckets, count, min, max, and sum, and summaries return `SummaryState` with + * quantiles, count, min, max, and sum. + * + * **Example** (Reading metric state) * - * @example * ```ts * import { Effect, Metric } from "effect" * @@ -2949,8 +2927,8 @@ export const timer = (name: string, options?: { * }) * ``` * + * @category getters * @since 2.0.0 - * @category Utilities */ export const value = ( self: Metric @@ -2963,14 +2941,16 @@ export const value = ( /** * Modifies the metric with the specified input. * - * The behavior of `modify` depends on the metric type: - * - **Counter**: Adds the input value to the current count - * - **Gauge**: Adds the input value to the current gauge value - * - **Frequency**: Same as `update` - increments the occurrence count for the input string - * - **Histogram**: Same as `update` - records the input value in the appropriate bucket - * - **Summary**: Same as `update` - records the input observation + * **Details** + * + * The behavior of `modify` depends on the metric type. Counters add the input + * value to the current count, gauges add the input value to the current gauge + * value, frequencies increment the occurrence count for the input string, + * histograms record the input value in the appropriate bucket, and summaries + * record the input observation. + * + * **Example** (Modifying metric values) * - * @example * ```ts * import { Effect, Metric } from "effect" * @@ -2997,21 +2977,23 @@ export const value = ( * }) * ``` * - * @since 2.0.0 - * @category Utilities + * @category mutations + * @since 3.6.5 */ export const modify: { /** * Modifies the metric with the specified input. * - * The behavior of `modify` depends on the metric type: - * - **Counter**: Adds the input value to the current count - * - **Gauge**: Adds the input value to the current gauge value - * - **Frequency**: Same as `update` - increments the occurrence count for the input string - * - **Histogram**: Same as `update` - records the input value in the appropriate bucket - * - **Summary**: Same as `update` - records the input observation + * **Details** + * + * The behavior of `modify` depends on the metric type. Counters add the input + * value to the current count, gauges add the input value to the current gauge + * value, frequencies increment the occurrence count for the input string, + * histograms record the input value in the appropriate bucket, and summaries + * record the input observation. + * + * **Example** (Modifying metric values) * - * @example * ```ts * import { Effect, Metric } from "effect" * @@ -3038,21 +3020,23 @@ export const modify: { * }) * ``` * - * @since 2.0.0 - * @category Utilities + * @category mutations + * @since 3.6.5 */ (input: Input): (self: Metric) => Effect /** * Modifies the metric with the specified input. * - * The behavior of `modify` depends on the metric type: - * - **Counter**: Adds the input value to the current count - * - **Gauge**: Adds the input value to the current gauge value - * - **Frequency**: Same as `update` - increments the occurrence count for the input string - * - **Histogram**: Same as `update` - records the input value in the appropriate bucket - * - **Summary**: Same as `update` - records the input observation + * **Details** + * + * The behavior of `modify` depends on the metric type. Counters add the input + * value to the current count, gauges add the input value to the current gauge + * value, frequencies increment the occurrence count for the input string, + * histograms record the input value in the appropriate bucket, and summaries + * record the input observation. + * + * **Example** (Modifying metric values) * - * @example * ```ts * import { Effect, Metric } from "effect" * @@ -3079,22 +3063,24 @@ export const modify: { * }) * ``` * - * @since 2.0.0 - * @category Utilities + * @category mutations + * @since 3.6.5 */ (self: Metric, input: Input): Effect } = dual< /** * Modifies the metric with the specified input. * - * The behavior of `modify` depends on the metric type: - * - **Counter**: Adds the input value to the current count - * - **Gauge**: Adds the input value to the current gauge value - * - **Frequency**: Same as `update` - increments the occurrence count for the input string - * - **Histogram**: Same as `update` - records the input value in the appropriate bucket - * - **Summary**: Same as `update` - records the input observation + * **Details** + * + * The behavior of `modify` depends on the metric type. Counters add the input + * value to the current count, gauges add the input value to the current gauge + * value, frequencies increment the occurrence count for the input string, + * histograms record the input value in the appropriate bucket, and summaries + * record the input observation. + * + * **Example** (Modifying metric values) * - * @example * ```ts * import { Effect, Metric } from "effect" * @@ -3121,21 +3107,23 @@ export const modify: { * }) * ``` * - * @since 2.0.0 - * @category Utilities + * @category mutations + * @since 3.6.5 */ (input: Input) => (self: Metric) => Effect, /** * Modifies the metric with the specified input. * - * The behavior of `modify` depends on the metric type: - * - **Counter**: Adds the input value to the current count - * - **Gauge**: Adds the input value to the current gauge value - * - **Frequency**: Same as `update` - increments the occurrence count for the input string - * - **Histogram**: Same as `update` - records the input value in the appropriate bucket - * - **Summary**: Same as `update` - records the input observation + * **Details** + * + * The behavior of `modify` depends on the metric type. Counters add the input + * value to the current count, gauges add the input value to the current gauge + * value, frequencies increment the occurrence count for the input string, + * histograms record the input value in the appropriate bucket, and summaries + * record the input observation. + * + * **Example** (Modifying metric values) * - * @example * ```ts * import { Effect, Metric } from "effect" * @@ -3162,8 +3150,8 @@ export const modify: { * }) * ``` * - * @since 2.0.0 - * @category Utilities + * @category mutations + * @since 3.6.5 */ (self: Metric, input: Input) => Effect >(2, (self, input) => @@ -3175,14 +3163,16 @@ export const modify: { /** * Updates the metric with the specified input. * - * The behavior of `update` depends on the metric type: - * - **Counter**: Adds the input value to the current count (same as `modify`) - * - **Gauge**: Sets the gauge to the specified value (replaces current value) - * - **Frequency**: Increments the occurrence count for the input string by 1 - * - **Histogram**: Records the input value in the appropriate bucket - * - **Summary**: Records the input value as a new observation + * **Details** + * + * The behavior of `update` depends on the metric type. Counters add the input + * value to the current count, gauges replace the current value with the input + * value, frequencies increment the occurrence count for the input string, + * histograms record the input value in the appropriate bucket, and summaries + * record the input value as a new observation. + * + * **Example** (Updating metric values) * - * @example * ```ts * import { Effect, Metric } from "effect" * @@ -3218,21 +3208,23 @@ export const modify: { * }) * ``` * + * @category mutations * @since 2.0.0 - * @category Utilities */ export const update: { /** * Updates the metric with the specified input. * - * The behavior of `update` depends on the metric type: - * - **Counter**: Adds the input value to the current count (same as `modify`) - * - **Gauge**: Sets the gauge to the specified value (replaces current value) - * - **Frequency**: Increments the occurrence count for the input string by 1 - * - **Histogram**: Records the input value in the appropriate bucket - * - **Summary**: Records the input value as a new observation + * **Details** + * + * The behavior of `update` depends on the metric type. Counters add the input + * value to the current count, gauges replace the current value with the input + * value, frequencies increment the occurrence count for the input string, + * histograms record the input value in the appropriate bucket, and summaries + * record the input value as a new observation. + * + * **Example** (Updating metric values) * - * @example * ```ts * import { Effect, Metric } from "effect" * @@ -3268,21 +3260,23 @@ export const update: { * }) * ``` * + * @category mutations * @since 2.0.0 - * @category Utilities */ (input: Input): (self: Metric) => Effect /** * Updates the metric with the specified input. * - * The behavior of `update` depends on the metric type: - * - **Counter**: Adds the input value to the current count (same as `modify`) - * - **Gauge**: Sets the gauge to the specified value (replaces current value) - * - **Frequency**: Increments the occurrence count for the input string by 1 - * - **Histogram**: Records the input value in the appropriate bucket - * - **Summary**: Records the input value as a new observation + * **Details** + * + * The behavior of `update` depends on the metric type. Counters add the input + * value to the current count, gauges replace the current value with the input + * value, frequencies increment the occurrence count for the input string, + * histograms record the input value in the appropriate bucket, and summaries + * record the input value as a new observation. + * + * **Example** (Updating metric values) * - * @example * ```ts * import { Effect, Metric } from "effect" * @@ -3318,22 +3312,24 @@ export const update: { * }) * ``` * + * @category mutations * @since 2.0.0 - * @category Utilities */ (self: Metric, input: Input): Effect } = dual< /** * Updates the metric with the specified input. * - * The behavior of `update` depends on the metric type: - * - **Counter**: Adds the input value to the current count (same as `modify`) - * - **Gauge**: Sets the gauge to the specified value (replaces current value) - * - **Frequency**: Increments the occurrence count for the input string by 1 - * - **Histogram**: Records the input value in the appropriate bucket - * - **Summary**: Records the input value as a new observation + * **Details** + * + * The behavior of `update` depends on the metric type. Counters add the input + * value to the current count, gauges replace the current value with the input + * value, frequencies increment the occurrence count for the input string, + * histograms record the input value in the appropriate bucket, and summaries + * record the input value as a new observation. + * + * **Example** (Updating metric values) * - * @example * ```ts * import { Effect, Metric } from "effect" * @@ -3369,21 +3365,23 @@ export const update: { * }) * ``` * + * @category mutations * @since 2.0.0 - * @category Utilities */ (input: Input) => (self: Metric) => Effect, /** * Updates the metric with the specified input. * - * The behavior of `update` depends on the metric type: - * - **Counter**: Adds the input value to the current count (same as `modify`) - * - **Gauge**: Sets the gauge to the specified value (replaces current value) - * - **Frequency**: Increments the occurrence count for the input string by 1 - * - **Histogram**: Records the input value in the appropriate bucket - * - **Summary**: Records the input value as a new observation + * **Details** + * + * The behavior of `update` depends on the metric type. Counters add the input + * value to the current count, gauges replace the current value with the input + * value, frequencies increment the occurrence count for the input string, + * histograms record the input value in the appropriate bucket, and summaries + * record the input value as a new observation. + * + * **Example** (Updating metric values) * - * @example * ```ts * import { Effect, Metric } from "effect" * @@ -3419,8 +3417,8 @@ export const update: { * }) * ``` * + * @category mutations * @since 2.0.0 - * @category Utilities */ (self: Metric, input: Input) => Effect >( @@ -3434,7 +3432,8 @@ export const update: { * of the specified new type, which must be transformable to the input type of * this metric. * - * @example + * **Example** (Mapping metric inputs) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -3464,8 +3463,8 @@ export const update: { * }) * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ export const mapInput: { /** @@ -3473,7 +3472,8 @@ export const mapInput: { * of the specified new type, which must be transformable to the input type of * this metric. * - * @example + * **Example** (Mapping metric inputs) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -3503,8 +3503,8 @@ export const mapInput: { * }) * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ (f: (input: Input2, context: Context.Context) => Input): (self: Metric) => Metric /** @@ -3512,7 +3512,8 @@ export const mapInput: { * of the specified new type, which must be transformable to the input type of * this metric. * - * @example + * **Example** (Mapping metric inputs) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -3542,8 +3543,8 @@ export const mapInput: { * }) * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ ( self: Metric, @@ -3555,7 +3556,8 @@ export const mapInput: { * of the specified new type, which must be transformable to the input type of * this metric. * - * @example + * **Example** (Mapping metric inputs) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -3585,8 +3587,8 @@ export const mapInput: { * }) * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ (f: (input: Input2, context: Context.Context) => Input) => (self: Metric) => Metric, /** @@ -3594,7 +3596,8 @@ export const mapInput: { * of the specified new type, which must be transformable to the input type of * this metric. * - * @example + * **Example** (Mapping metric inputs) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -3624,8 +3627,8 @@ export const mapInput: { * }) * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ ( self: Metric, @@ -3647,7 +3650,8 @@ export const mapInput: { * of any type, and translates them to updates with the specified constant * update value. * - * @example + * **Example** (Ignoring inputs with a constant value) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -3674,8 +3678,8 @@ export const mapInput: { * }) * ``` * - * @since 2.0.0 * @category Input + * @since 2.0.0 */ export const withConstantInput: { /** @@ -3683,7 +3687,8 @@ export const withConstantInput: { * of any type, and translates them to updates with the specified constant * update value. * - * @example + * **Example** (Ignoring inputs with a constant value) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -3710,8 +3715,8 @@ export const withConstantInput: { * }) * ``` * - * @since 2.0.0 * @category Input + * @since 2.0.0 */ (input: Input): (self: Metric) => Metric /** @@ -3719,7 +3724,8 @@ export const withConstantInput: { * of any type, and translates them to updates with the specified constant * update value. * - * @example + * **Example** (Ignoring inputs with a constant value) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -3746,8 +3752,8 @@ export const withConstantInput: { * }) * ``` * - * @since 2.0.0 * @category Input + * @since 2.0.0 */ (self: Metric, input: Input): Metric } = dual< @@ -3756,7 +3762,8 @@ export const withConstantInput: { * of any type, and translates them to updates with the specified constant * update value. * - * @example + * **Example** (Ignoring inputs with a constant value) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -3783,8 +3790,8 @@ export const withConstantInput: { * }) * ``` * - * @since 2.0.0 * @category Input + * @since 2.0.0 */ (input: Input) => (self: Metric) => Metric, /** @@ -3792,7 +3799,8 @@ export const withConstantInput: { * of any type, and translates them to updates with the specified constant * update value. * - * @example + * **Example** (Ignoring inputs with a constant value) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -3819,8 +3827,8 @@ export const withConstantInput: { * }) * ``` * - * @since 2.0.0 * @category Input + * @since 2.0.0 */ (self: Metric, input: Input) => Metric >(2, (self, input) => mapInput(self, () => input)) @@ -3828,11 +3836,14 @@ export const withConstantInput: { /** * Returns a new metric that applies the specified attributes to all operations. * + * **Details** + * * Attributes are key-value pairs that provide additional context for metrics, * enabling filtering, grouping, and more detailed analysis. Each combination * of attribute values creates a separate metric series. * - * @example + * **Example** (Applying metric attributes) + * * ```ts * import { Effect, Metric } from "effect" * @@ -3877,18 +3888,21 @@ export const withConstantInput: { * }) * ``` * - * @since 4.0.0 * @category Attributes + * @since 4.0.0 */ export const withAttributes: { /** * Returns a new metric that applies the specified attributes to all operations. * + * **Details** + * * Attributes are key-value pairs that provide additional context for metrics, * enabling filtering, grouping, and more detailed analysis. Each combination * of attribute values creates a separate metric series. * - * @example + * **Example** (Applying metric attributes) + * * ```ts * import { Effect, Metric } from "effect" * @@ -3933,18 +3947,21 @@ export const withAttributes: { * }) * ``` * - * @since 4.0.0 * @category Attributes + * @since 4.0.0 */ (attributes: Metric.Attributes): (self: Metric) => Metric /** * Returns a new metric that applies the specified attributes to all operations. * + * **Details** + * * Attributes are key-value pairs that provide additional context for metrics, * enabling filtering, grouping, and more detailed analysis. Each combination * of attribute values creates a separate metric series. * - * @example + * **Example** (Applying metric attributes) + * * ```ts * import { Effect, Metric } from "effect" * @@ -3989,19 +4006,22 @@ export const withAttributes: { * }) * ``` * - * @since 4.0.0 * @category Attributes + * @since 4.0.0 */ (self: Metric, attributes: Metric.Attributes): Metric } = dual< /** * Returns a new metric that applies the specified attributes to all operations. * + * **Details** + * * Attributes are key-value pairs that provide additional context for metrics, * enabling filtering, grouping, and more detailed analysis. Each combination * of attribute values creates a separate metric series. * - * @example + * **Example** (Applying metric attributes) + * * ```ts * import { Effect, Metric } from "effect" * @@ -4046,18 +4066,21 @@ export const withAttributes: { * }) * ``` * - * @since 4.0.0 * @category Attributes + * @since 4.0.0 */ (attributes: Metric.Attributes) => (self: Metric) => Metric, /** * Returns a new metric that applies the specified attributes to all operations. * + * **Details** + * * Attributes are key-value pairs that provide additional context for metrics, * enabling filtering, grouping, and more detailed analysis. Each combination * of attribute values creates a separate metric series. * - * @example + * **Example** (Applying metric attributes) + * * ```ts * import { Effect, Metric } from "effect" * @@ -4102,8 +4125,8 @@ export const withAttributes: { * }) * ``` * - * @since 4.0.0 * @category Attributes + * @since 4.0.0 */ (self: Metric, attributes: Metric.Attributes) => Metric >(2, ( @@ -4122,10 +4145,13 @@ export const withAttributes: { /** * Captures a snapshot of all registered metrics in the current context. * + * **Details** + * * Returns an array of metric snapshots, each containing the metric's metadata * (name, description, type) and current state (values, counts, etc.). * - * @example + * **Example** (Capturing metric snapshots) + * * ```ts * import { Console, Data, Effect, Metric } from "effect" * @@ -4164,8 +4190,8 @@ export const withAttributes: { * }) * ``` * - * @since 2.0.0 * @category Snapshotting + * @since 2.0.0 */ export const snapshot: Effect> = InternalEffect.map( InternalEffect.context(), @@ -4176,11 +4202,14 @@ export const snapshot: Effect> = InternalEffect.m * Returns a human-readable string representation of all currently registered * metrics in a tabular format. * + * **Details** + * * This debugging utility captures a snapshot of all metrics and formats them * in an easy-to-read table showing names, descriptions, types, attributes, * and current state values. * - * @example + * **Example** (Dumping metrics as text) + * * ```ts * import { Console, Data, Effect, Metric } from "effect" * @@ -4223,8 +4252,8 @@ export const snapshot: Effect> = InternalEffect.m * }) * ``` * - * @since 2.0.0 * @category Debugging + * @since 4.0.0 */ export const dump: Effect = InternalEffect.flatMap(InternalEffect.context(), (context) => { const metrics = snapshotUnsafe(context) @@ -4262,14 +4291,22 @@ export const dump: Effect = InternalEffect.flatMap(InternalEffect.contex }) /** - * Synchronously captures a snapshot of all registered metrics using the provided + * Captures a snapshot of all registered metrics synchronously using the provided * service context. * + * **When to use** + * + * Use to read metric snapshots from an explicit `Context` in low-level + * integrations, exporters, or debugging tools that already have the context. + * + * **Details** + * * This is the "unsafe" version that bypasses Effect's safety guarantees and requires * manual handling of the services context. Use the safe `snapshot` function for normal * application code. * - * @example + * **Example** (Capturing snapshots from a context) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -4296,13 +4333,14 @@ export const dump: Effect = InternalEffect.flatMap(InternalEffect.contex * * // Use snapshotUnsafe for direct, synchronous access * const snapshots = Metric.snapshotUnsafe(services) + * const exportBatchCreatedAt = 1_700_000_000_000 * * // Process snapshots immediately (useful for exporters, debugging tools) * const exportData = snapshots.map((snapshot) => ({ * name: snapshot.id, * type: snapshot.type, * value: snapshot.state, - * timestamp: Date.now() + * timestamp: exportBatchCreatedAt * })) * * // This is synchronous and doesn't involve Effect overhead @@ -4318,8 +4356,8 @@ export const dump: Effect = InternalEffect.flatMap(InternalEffect.contex * }) * ``` * - * @since 2.0.0 * @category Snapshotting + * @since 4.0.0 */ export const snapshotUnsafe = (context: Context.Context): ReadonlyArray => { const registry = Context.get(context, MetricRegistry) @@ -4391,14 +4429,16 @@ const attributesToString = (attributes: Metric.AttributeSet): string => { // Metric Boundaries /** - * A helper method to create histogram bucket boundaries from an iterable set - * of values. + * Creates histogram bucket boundaries from an iterable set of values. + * + * **Details** * * Processes any iterable of numbers by removing duplicates, filtering out * non-positive values, and automatically appending positive infinity as the * final boundary. * - * @example + * **Example** (Creating boundaries from values) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -4452,20 +4492,25 @@ const attributesToString = (attributes: Metric.AttributeSet): string => { * }) * ``` * - * @since 2.0.0 - * @category Boundaries + * @category boundaries + * @since 4.0.0 */ export const boundariesFromIterable = (iterable: Iterable): ReadonlyArray => Arr.append(Arr.filter(new Set(iterable), (n) => n > 0), Number.POSITIVE_INFINITY) /** - * A helper method to create histogram bucket boundaries with linearly - * increasing values. + * Creates histogram bucket boundaries from a linear sequence and appends + * positive infinity. + * + * **Details** * - * Creates evenly-spaced boundaries starting from a base value and incrementing - * by a fixed width. Automatically adds positive infinity as the final boundary. + * Generates `count - 1` finite boundaries using `start + width + index` for + * each zero-based index, then applies the same normalization as + * `boundariesFromIterable`: non-positive values are removed, duplicates are + * collapsed, and `Infinity` is appended. + * + * **Example** (Creating linear boundaries) * - * @example * ```ts * import { Data, Effect, Metric } from "effect" * @@ -4474,13 +4519,12 @@ export const boundariesFromIterable = (iterable: Iterable): ReadonlyArra * }> {} * * // Create boundaries for response time histogram - * // Buckets: 0-100ms, 100-200ms, 200-300ms, 300-400ms, 400ms+ * const responseBoundaries = Metric.linearBoundaries({ * start: 0, // Starting point - * width: 100, // 100ms intervals + * width: 100, // Offset used for the first boundary * count: 5 // Creates 4 boundaries + infinity * }) - * console.log(responseBoundaries) // [100, 200, 300, 400, Infinity] + * console.log(responseBoundaries) // [100, 101, 102, 103, Infinity] * * // Create a histogram using these boundaries * const responseTimeHistogram = Metric.histogram("api_response_time", { @@ -4490,17 +4534,17 @@ export const boundariesFromIterable = (iterable: Iterable): ReadonlyArra * * const program = Effect.gen(function*() { * // Record some response times - * yield* Metric.update(responseTimeHistogram, 85) // Goes in 0-100ms bucket - * yield* Metric.update(responseTimeHistogram, 250) // Goes in 200-300ms bucket - * yield* Metric.update(responseTimeHistogram, 450) // Goes in 400ms+ bucket + * yield* Metric.update(responseTimeHistogram, 85) + * yield* Metric.update(responseTimeHistogram, 101) + * yield* Metric.update(responseTimeHistogram, 450) * * const value = yield* Metric.value(responseTimeHistogram) * return value * }) * ``` * - * @since 2.0.0 - * @category Boundaries + * @category boundaries + * @since 4.0.0 */ export const linearBoundaries = (options: { readonly start: number @@ -4510,13 +4554,15 @@ export const linearBoundaries = (options: { boundariesFromIterable(Arr.makeBy(options.count - 1, (n) => options.start + n + options.width)) /** - * A helper method to create histogram bucket boundaries with exponentially - * increasing values. + * Creates histogram bucket boundaries with exponentially increasing values. + * + * **Details** * * Creates boundaries that grow exponentially, useful for metrics that span * multiple orders of magnitude. Each boundary is calculated as start * factor^i. * - * @example + * **Example** (Creating exponential boundaries) + * * ```ts * import { Data, Effect, Metric } from "effect" * @@ -4557,8 +4603,8 @@ export const linearBoundaries = (options: { * }) * ``` * - * @since 2.0.0 - * @category Boundaries + * @category boundaries + * @since 4.0.0 */ export const exponentialBoundaries = (options: { readonly start: number @@ -4588,7 +4634,8 @@ const fiberFailures = counter("child_fiber_failures", { /** * Service key for the fiber runtime metrics service. * - * @example + * **Example** (Using the fiber runtime metrics key) + * * ```ts * import { Data, Effect, Layer, Metric } from "effect" * @@ -4618,8 +4665,8 @@ const fiberFailures = counter("child_fiber_failures", { * }) * ``` * + * @category metrics * @since 4.0.0 - * @category Runtime Metrics */ export const FiberRuntimeMetricsKey: "effect/observability/Metric/FiberRuntimeMetricsKey" = InternalMetric.FiberRuntimeMetricsKey @@ -4627,11 +4674,11 @@ export const FiberRuntimeMetricsKey: "effect/observability/Metric/FiberRuntimeMe /** * Interface for the fiber runtime metrics service that tracks fiber lifecycle events. * - * @example + * **Example** (Providing a custom fiber metrics service) + * * ```ts - * import type { Context } from "effect" * import { Data, Effect, Layer, Metric } from "effect" - * import type { Exit } from "effect/Exit" + * import type { Context, Exit } from "effect" * * class MetricsError extends Data.TaggedError("MetricsError")<{ * readonly operation: string @@ -4645,7 +4692,7 @@ export const FiberRuntimeMetricsKey: "effect/observability/Metric/FiberRuntimeMe * }, * recordFiberEnd: ( * context: Context.Context, - * exit: Exit + * exit: Exit.Exit * ) => { * console.log("Fiber completed with exit:", exit) * // Custom logic for tracking fiber completion based on exit status @@ -4660,8 +4707,8 @@ export const FiberRuntimeMetricsKey: "effect/observability/Metric/FiberRuntimeMe * }) * ``` * + * @category metrics * @since 4.0.0 - * @category Runtime Metrics */ export interface FiberRuntimeMetricsService { readonly recordFiberStart: (context: Context.Context) => void @@ -4669,9 +4716,22 @@ export interface FiberRuntimeMetricsService { } /** - * Service class for managing fiber runtime metrics collection. + * Context reference for the optional service that records fiber runtime + * metrics. + * + * **When to use** + * + * Use to provide or inspect the service that receives fiber start and end + * notifications for automatic runtime metrics. + * + * **Details** + * + * When provided, the runtime can notify the service about child-fiber start and + * end events. When the reference is `undefined`, automatic fiber runtime metric + * collection is disabled. + * + * **Example** (Accessing the fiber runtime metrics service) * - * @example * ```ts * import { Data, Effect, Metric } from "effect" * @@ -4710,8 +4770,8 @@ export interface FiberRuntimeMetricsService { * }) * ``` * + * @category runtime metrics * @since 4.0.0 - * @category Runtime Metrics */ export const FiberRuntimeMetrics = Context.Reference( InternalMetric.FiberRuntimeMetricsKey, @@ -4721,7 +4781,8 @@ export const FiberRuntimeMetrics = Context.Reference) { @@ -4778,15 +4839,16 @@ export const FiberRuntimeMetricsImpl: FiberRuntimeMetricsService = { } /** - * A Layer that enables automatic collection of fiber runtime metrics across + * Layer that enables automatic collection of fiber runtime metrics across * an entire Effect application. * - * Unlike the function version which wraps individual Effects, this layer provides - * runtime metrics collection to all Effects in the application context. This is - * the recommended approach for production applications that need comprehensive - * fiber monitoring. + * **When to use** + * + * Use when you need runtime metrics collection for all Effects in the + * application context rather than wrapping individual Effects. + * + * **Example** (Enabling runtime metrics with a layer) * - * @example * ```ts * import { Console, Data, Effect, Layer, Metric } from "effect" * @@ -4871,15 +4933,16 @@ export const FiberRuntimeMetricsImpl: FiberRuntimeMetricsService = { * ) * ``` * + * @category metrics * @since 4.0.0 - * @category Runtime Metrics */ export const enableRuntimeMetricsLayer = Layer.succeed(FiberRuntimeMetrics)(FiberRuntimeMetricsImpl) /** - * A Layer that disables automatic collection of fiber runtime metrics. + * Layer that disables automatic collection of fiber runtime metrics. + * + * **Example** (Disabling runtime metrics with a layer) * - * @example * ```ts * import { Data, Effect, Metric } from "effect" * @@ -4911,19 +4974,22 @@ export const enableRuntimeMetricsLayer = Layer.succeed(FiberRuntimeMetrics)(Fibe * }) * ``` * + * @category metrics * @since 4.0.0 - * @category Runtime Metrics */ export const disableRuntimeMetricsLayer = Layer.succeed(FiberRuntimeMetrics)(undefined) /** * Enables automatic collection of fiber runtime metrics for the provided Effect. * + * **Details** + * * When enabled, automatically tracks fiber lifecycle metrics including active fibers, * started fibers, successful completions, and failures. These metrics provide valuable * insights into the concurrency patterns and health of your Effect application. * - * @example + * **Example** (Enabling runtime metrics for an effect) + * * ```ts * import { Console, Data, Effect, Layer, Metric } from "effect" * @@ -4992,8 +5058,8 @@ export const disableRuntimeMetricsLayer = Layer.succeed(FiberRuntimeMetrics)(und * ) * ``` * + * @category metrics * @since 4.0.0 - * @category Runtime Metrics */ export const enableRuntimeMetrics: (self: Effect) => Effect = InternalEffect.provideService( FiberRuntimeMetrics, @@ -5003,11 +5069,13 @@ export const enableRuntimeMetrics: (self: Effect) => Effect(self: Effect) => Effect * Effect.gen(function*() { * // Simulate intensive computation - * const result = i * i + Math.random() + * const result = i * i + (i % 10) / 10 * return result * }) * ) @@ -5077,8 +5145,8 @@ export const enableRuntimeMetrics: (self: Effect) => Effect(self: Effect) => Effect = InternalEffect.provideService( FiberRuntimeMetrics, diff --git a/.opencode/node_modules/effect/src/MutableHashMap.ts b/.opencode/node_modules/effect/src/MutableHashMap.ts index 75dd9d5ce164676029917de90a146dc09d3de3a3..d5034ac363514d1772704092770685f282aff451 100644 --- a/.opencode/node_modules/effect/src/MutableHashMap.ts +++ b/.opencode/node_modules/effect/src/MutableHashMap.ts @@ -1,28 +1,13 @@ /** - * MutableHashMap is a high-performance, mutable hash map implementation designed for efficient key-value storage - * with support for both structural and referential equality. It provides O(1) average-case performance for - * basic operations and integrates seamlessly with Effect's Equal and Hash interfaces. - * - * The implementation uses a hybrid approach: - * - Referential keys (without Equal implementation) are stored in a native Map - * - Structural keys (with Equal implementation) are stored in hash buckets with collision handling - * - * Key Features: - * - Mutable operations for performance-critical scenarios - * - Supports both structural and referential equality - * - Efficient collision handling through bucketing - * - Iterable interface for easy traversal - * - Memory-efficient storage with automatic bucket management - * - * Performance Characteristics: - * - Get/Set/Has: O(1) average, O(n) worst case (hash collisions) - * - Remove: O(1) average, O(n) worst case - * - Clear: O(1) - * - Size: O(1) - * - Iteration: O(n) + * Stores key/value entries in a mutable hash map. + * + * `MutableHashMap` updates the same collection in place and supports fast + * lookup, insertion, removal, clearing, and iteration. It combines a native + * `Map` for ordinary JavaScript keys with hash buckets for keys that implement + * Effect `Equal` and `Hash`, so callers can mix reference-based and structural + * lookup in the same collection. * * @since 2.0.0 - * @category data-structures */ import type { NonEmptyArray } from "./Array.ts" import * as Equal from "./Equal.ts" @@ -38,9 +23,24 @@ import { hasProperty } from "./Predicate.ts" const TypeId = "~effect/collections/MutableHashMap" /** - * @example + * A mutable hash map that stores key-value pairs and supports both referential + * and Effect structural equality. + * + * **When to use** + * + * Use as a mutable key-value map when in-place updates are acceptable and keys + * may rely on Effect structural equality. + * + * **Details** + * + * Operations mutate the map in place. Keys that implement `Equal` / `Hash` can + * be looked up structurally; other keys use normal JavaScript reference or + * primitive equality. + * + * **Example** (Using a mutable hash map) + * * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" + * import { MutableHashMap } from "effect" * * // Create a mutable hash map with string keys and number values * const map: MutableHashMap.MutableHashMap = MutableHashMap @@ -63,8 +63,12 @@ const TypeId = "~effect/collections/MutableHashMap" * console.log(entries) // [["count", 42], ["total", 100]] * ``` * - * @since 2.0.0 + * @see {@link empty} for creating an empty mutable hash map + * @see {@link get} for reading values by key + * @see {@link set} for mutating entries by key + * * @category models + * @since 2.0.0 */ export interface MutableHashMap extends Iterable<[K, V]>, Pipeable, Inspectable { readonly [TypeId]: typeof TypeId @@ -73,7 +77,21 @@ export interface MutableHashMap extends Iterable<[K, V]>, Pipeable } /** - * Checks if the specified value is a `MutableHashMap`, `false` otherwise. + * Checks whether the specified value is a `MutableHashMap`, `false` otherwise. + * + * **When to use** + * + * Use to narrow an unknown value before treating it as a mutable hash map. + * + * **Details** + * + * The check looks for the `MutableHashMap` runtime marker. + * + * **Gotchas** + * + * The check does not validate the key or value types carried by the map. + * + * @see {@link MutableHashMap} for the mutable hash map interface * * @category refinements * @since 4.0.0 @@ -105,9 +123,18 @@ const MutableHashMapProto: Omit, "backing" | "b /** * Creates an empty MutableHashMap. * - * @example + * **When to use** + * + * Use to create a fresh mutable map before adding entries over time. + * + * **Details** + * + * Each call returns a new empty map instance. + * + * **Example** (Creating an empty map) + * * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" + * import { MutableHashMap } from "effect" * * const map = MutableHashMap.empty() * @@ -118,8 +145,11 @@ const MutableHashMapProto: Omit, "backing" | "b * console.log(MutableHashMap.size(map)) // 2 * ``` * - * @since 2.0.0 + * @see {@link make} for creating a map from explicit entries + * @see {@link fromIterable} for creating a map from an iterable of entries + * * @category constructors + * @since 2.0.0 */ export const empty = (): MutableHashMap => { const self = Object.create(MutableHashMapProto) @@ -131,9 +161,14 @@ export const empty = (): MutableHashMap => { /** * Creates a MutableHashMap from a variable number of key-value pairs. * - * @example + * **When to use** + * + * Use to create a mutable hash map from explicit entries known at the call site. + * + * **Example** (Creating a map from entries) + * * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" + * import { MutableHashMap } from "effect" * * const map = MutableHashMap.make( * ["key1", 42], @@ -145,8 +180,11 @@ export const empty = (): MutableHashMap => { * console.log(MutableHashMap.size(map)) // 3 * ``` * - * @since 2.0.0 + * @see {@link empty} for creating an empty map + * @see {@link fromIterable} for creating a map from an iterable of entries + * * @category constructors + * @since 2.0.0 */ export const make: >( ...entries: Entries @@ -158,9 +196,14 @@ export const make: >( /** * Creates a MutableHashMap from an iterable collection of key-value pairs. * - * @example + * **When to use** + * + * Use to create a mutable hash map from an existing iterable of entries. + * + * **Example** (Creating a map from an iterable) + * * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" + * import { MutableHashMap } from "effect" * * const entries = [ * ["apple", 1], @@ -178,8 +221,11 @@ export const make: >( * console.log(MutableHashMap.get(fromMap, "x")) // Some(10) * ``` * - * @since 2.0.0 + * @see {@link make} for creating a map from explicit entries + * @see {@link empty} for creating an empty map + * * @category constructors + * @since 2.0.0 */ export const fromIterable = (entries: Iterable): MutableHashMap => { const self = empty() @@ -190,11 +236,21 @@ export const fromIterable = (entries: Iterable): MutableH } /** - * Retrieves the value associated with the specified key from the MutableHashMap. + * Looks up a key in the `MutableHashMap` safely. + * + * **When to use** + * + * Use to safely read a `MutableHashMap` value for a key as an `Option`. + * + * **Details** + * + * Returns `Some(value)` when an equal key is present and `None` when the key is + * absent. + * + * **Example** (Getting a value) * - * @example * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" + * import { MutableHashMap } from "effect" * * const map = MutableHashMap.make(["key1", 42], ["key2", 100]) * @@ -206,16 +262,29 @@ export const fromIterable = (entries: Iterable): MutableH * console.log(getValue(map)) // Some(42) * ``` * - * @since 2.0.0 + * @see {@link has} for checking only whether a key is present + * @see {@link set} for inserting or replacing a value by key + * * @category elements + * @since 2.0.0 */ export const get: { /** - * Retrieves the value associated with the specified key from the MutableHashMap. + * Looks up a key in the `MutableHashMap` safely. + * + * **When to use** + * + * Use to safely read a `MutableHashMap` value for a key as an `Option`. + * + * **Details** + * + * Returns `Some(value)` when an equal key is present and `None` when the key is + * absent. + * + * **Example** (Getting a value) * - * @example * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" + * import { MutableHashMap } from "effect" * * const map = MutableHashMap.make(["key1", 42], ["key2", 100]) * @@ -227,16 +296,29 @@ export const get: { * console.log(getValue(map)) // Some(42) * ``` * - * @since 2.0.0 + * @see {@link has} for checking only whether a key is present + * @see {@link set} for inserting or replacing a value by key + * * @category elements + * @since 2.0.0 */ (key: K): (self: MutableHashMap) => Option.Option /** - * Retrieves the value associated with the specified key from the MutableHashMap. + * Looks up a key in the `MutableHashMap` safely. + * + * **When to use** + * + * Use to safely read a `MutableHashMap` value for a key as an `Option`. + * + * **Details** + * + * Returns `Some(value)` when an equal key is present and `None` when the key is + * absent. + * + * **Example** (Getting a value) * - * @example * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" + * import { MutableHashMap } from "effect" * * const map = MutableHashMap.make(["key1", 42], ["key2", 100]) * @@ -248,17 +330,30 @@ export const get: { * console.log(getValue(map)) // Some(42) * ``` * - * @since 2.0.0 + * @see {@link has} for checking only whether a key is present + * @see {@link set} for inserting or replacing a value by key + * * @category elements + * @since 2.0.0 */ (self: MutableHashMap, key: K): Option.Option } = dual< /** - * Retrieves the value associated with the specified key from the MutableHashMap. + * Looks up a key in the `MutableHashMap` safely. + * + * **When to use** + * + * Use to safely read a `MutableHashMap` value for a key as an `Option`. + * + * **Details** + * + * Returns `Some(value)` when an equal key is present and `None` when the key is + * absent. + * + * **Example** (Getting a value) * - * @example * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" + * import { MutableHashMap } from "effect" * * const map = MutableHashMap.make(["key1", 42], ["key2", 100]) * @@ -270,16 +365,29 @@ export const get: { * console.log(getValue(map)) // Some(42) * ``` * - * @since 2.0.0 + * @see {@link has} for checking only whether a key is present + * @see {@link set} for inserting or replacing a value by key + * * @category elements + * @since 2.0.0 */ (key: K) => (self: MutableHashMap) => Option.Option, /** - * Retrieves the value associated with the specified key from the MutableHashMap. + * Looks up a key in the `MutableHashMap` safely. + * + * **When to use** + * + * Use to safely read a `MutableHashMap` value for a key as an `Option`. + * + * **Details** + * + * Returns `Some(value)` when an equal key is present and `None` when the key is + * absent. + * + * **Example** (Getting a value) * - * @example * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" + * import { MutableHashMap } from "effect" * * const map = MutableHashMap.make(["key1", 42], ["key2", 100]) * @@ -291,8 +399,11 @@ export const get: { * console.log(getValue(map)) // Some(42) * ``` * - * @since 2.0.0 + * @see {@link has} for checking only whether a key is present + * @see {@link set} for inserting or replacing a value by key + * * @category elements + * @since 2.0.0 */ (self: MutableHashMap, key: K) => Option.Option >(2, (self: MutableHashMap, key: K): Option.Option => { @@ -317,11 +428,16 @@ const referentialKeysCache = new WeakMap() const isSimpleKey = (u: unknown): boolean => typeof u !== "object" && typeof u !== "function" /** - * Extracts all keys from the MutableHashMap into an array. + * Returns an iterable over the keys in the `MutableHashMap`. + * + * **When to use** + * + * Use to iterate over the keys currently stored in a mutable hash map. + * + * **Example** (Reading keys) * - * @example * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" + * import { MutableHashMap } from "effect" * * const map = MutableHashMap.make( * ["apple", 1], @@ -336,17 +452,25 @@ const isSimpleKey = (u: unknown): boolean => typeof u !== "object" && typeof u ! * const hasRequiredKeys = allKeys.includes("apple") && allKeys.includes("banana") * ``` * - * @since 3.8.0 + * @see {@link values} for iterating over stored values + * @see {@link has} for checking one key without iterating + * * @category elements + * @since 3.8.0 */ export const keys = (self: MutableHashMap): Iterable => self.backing.keys() /** - * Extracts all values from the MutableHashMap into an array. + * Returns an iterable over the values in the `MutableHashMap`. + * + * **When to use** + * + * Use to iterate over the values currently stored in a mutable hash map. + * + * **Example** (Reading values) * - * @example * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" + * import { MutableHashMap } from "effect" * * const map = MutableHashMap.make( * ["apple", 1], @@ -366,8 +490,10 @@ export const keys = (self: MutableHashMap): Iterable => self.back * console.log(largeValues) // [2, 3] * ``` * - * @since 3.8.0 + * @see {@link keys} for iterating over stored keys + * * @category elements + * @since 3.8.0 */ export const values = (self: MutableHashMap): Iterable => self.backing.values() @@ -387,11 +513,17 @@ const getFromBucket = ( } /** - * Checks if the MutableHashMap contains the specified key. + * Checks whether the MutableHashMap contains the specified key. + * + * **When to use** + * + * Use to test whether a key is present in a `MutableHashMap` without reading + * its value. + * + * **Example** (Checking for a key) * - * @example * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" + * import { MutableHashMap } from "effect" * * const map = MutableHashMap.make(["key1", 42], ["key2", 100]) * @@ -403,16 +535,24 @@ const getFromBucket = ( * console.log(hasKey(map)) // true * ``` * - * @since 2.0.0 + * @see {@link get} for reading the value as an `Option` + * * @category elements + * @since 2.0.0 */ export const has: { /** - * Checks if the MutableHashMap contains the specified key. + * Checks whether the MutableHashMap contains the specified key. + * + * **When to use** + * + * Use to test whether a key is present in a `MutableHashMap` without reading + * its value. + * + * **Example** (Checking for a key) * - * @example * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" + * import { MutableHashMap } from "effect" * * const map = MutableHashMap.make(["key1", 42], ["key2", 100]) * @@ -424,16 +564,24 @@ export const has: { * console.log(hasKey(map)) // true * ``` * - * @since 2.0.0 + * @see {@link get} for reading the value as an `Option` + * * @category elements + * @since 2.0.0 */ (key: K): (self: MutableHashMap) => boolean /** - * Checks if the MutableHashMap contains the specified key. + * Checks whether the MutableHashMap contains the specified key. + * + * **When to use** + * + * Use to test whether a key is present in a `MutableHashMap` without reading + * its value. + * + * **Example** (Checking for a key) * - * @example * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" + * import { MutableHashMap } from "effect" * * const map = MutableHashMap.make(["key1", 42], ["key2", 100]) * @@ -445,17 +593,25 @@ export const has: { * console.log(hasKey(map)) // true * ``` * - * @since 2.0.0 + * @see {@link get} for reading the value as an `Option` + * * @category elements + * @since 2.0.0 */ (self: MutableHashMap, key: K): boolean } = dual< /** - * Checks if the MutableHashMap contains the specified key. + * Checks whether the MutableHashMap contains the specified key. + * + * **When to use** + * + * Use to test whether a key is present in a `MutableHashMap` without reading + * its value. + * + * **Example** (Checking for a key) * - * @example * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" + * import { MutableHashMap } from "effect" * * const map = MutableHashMap.make(["key1", 42], ["key2", 100]) * @@ -467,16 +623,24 @@ export const has: { * console.log(hasKey(map)) // true * ``` * - * @since 2.0.0 + * @see {@link get} for reading the value as an `Option` + * * @category elements + * @since 2.0.0 */ (key: K) => (self: MutableHashMap) => boolean, /** - * Checks if the MutableHashMap contains the specified key. + * Checks whether the MutableHashMap contains the specified key. + * + * **When to use** + * + * Use to test whether a key is present in a `MutableHashMap` without reading + * its value. + * + * **Example** (Checking for a key) * - * @example * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" + * import { MutableHashMap } from "effect" * * const map = MutableHashMap.make(["key1", 42], ["key2", 100]) * @@ -488,8 +652,10 @@ export const has: { * console.log(hasKey(map)) // true * ``` * - * @since 2.0.0 + * @see {@link get} for reading the value as an `Option` + * * @category elements + * @since 2.0.0 */ (self: MutableHashMap, key: K) => boolean >(2, (self, key) => Option.isSome(get(self, key))) @@ -498,9 +664,15 @@ export const has: { * Sets a key-value pair in the MutableHashMap, mutating the map in place. * If the key already exists, its value is updated. * - * @example + * **When to use** + * + * Use to insert a new `MutableHashMap` entry or replace an existing entry in + * place. + * + * **Example** (Setting key-value pairs) + * * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" + * import { MutableHashMap } from "effect" * * const map = MutableHashMap.empty() * @@ -521,17 +693,27 @@ export const has: { * console.log(MutableHashMap.size(map)) // 3 * ``` * - * @since 2.0.0 + * @see {@link modify} for updating an existing value with a function + * @see {@link modifyAt} for setting or removing based on the current optional value + * @see {@link remove} for deleting an entry by key + * * @category mutations + * @since 2.0.0 */ export const set: { /** * Sets a key-value pair in the MutableHashMap, mutating the map in place. * If the key already exists, its value is updated. * - * @example + * **When to use** + * + * Use to insert a new `MutableHashMap` entry or replace an existing entry in + * place. + * + * **Example** (Setting key-value pairs) + * * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" + * import { MutableHashMap } from "effect" * * const map = MutableHashMap.empty() * @@ -552,17 +734,27 @@ export const set: { * console.log(MutableHashMap.size(map)) // 3 * ``` * - * @since 2.0.0 + * @see {@link modify} for updating an existing value with a function + * @see {@link modifyAt} for setting or removing based on the current optional value + * @see {@link remove} for deleting an entry by key + * * @category mutations + * @since 2.0.0 */ (key: K, value: V): (self: MutableHashMap) => MutableHashMap /** * Sets a key-value pair in the MutableHashMap, mutating the map in place. * If the key already exists, its value is updated. * - * @example + * **When to use** + * + * Use to insert a new `MutableHashMap` entry or replace an existing entry in + * place. + * + * **Example** (Setting key-value pairs) + * * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" + * import { MutableHashMap } from "effect" * * const map = MutableHashMap.empty() * @@ -583,8 +775,12 @@ export const set: { * console.log(MutableHashMap.size(map)) // 3 * ``` * - * @since 2.0.0 + * @see {@link modify} for updating an existing value with a function + * @see {@link modifyAt} for setting or removing based on the current optional value + * @see {@link remove} for deleting an entry by key + * * @category mutations + * @since 2.0.0 */ (self: MutableHashMap, key: K, value: V): MutableHashMap } = dual< @@ -592,9 +788,15 @@ export const set: { * Sets a key-value pair in the MutableHashMap, mutating the map in place. * If the key already exists, its value is updated. * - * @example + * **When to use** + * + * Use to insert a new `MutableHashMap` entry or replace an existing entry in + * place. + * + * **Example** (Setting key-value pairs) + * * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" + * import { MutableHashMap } from "effect" * * const map = MutableHashMap.empty() * @@ -615,17 +817,27 @@ export const set: { * console.log(MutableHashMap.size(map)) // 3 * ``` * - * @since 2.0.0 + * @see {@link modify} for updating an existing value with a function + * @see {@link modifyAt} for setting or removing based on the current optional value + * @see {@link remove} for deleting an entry by key + * * @category mutations + * @since 2.0.0 */ (key: K, value: V) => (self: MutableHashMap) => MutableHashMap, /** * Sets a key-value pair in the MutableHashMap, mutating the map in place. * If the key already exists, its value is updated. * - * @example + * **When to use** + * + * Use to insert a new `MutableHashMap` entry or replace an existing entry in + * place. + * + * **Example** (Setting key-value pairs) + * * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" + * import { MutableHashMap } from "effect" * * const map = MutableHashMap.empty() * @@ -646,8 +858,12 @@ export const set: { * console.log(MutableHashMap.size(map)) // 3 * ``` * - * @since 2.0.0 + * @see {@link modify} for updating an existing value with a function + * @see {@link modifyAt} for setting or removing based on the current optional value + * @see {@link remove} for deleting an entry by key + * * @category mutations + * @since 2.0.0 */ (self: MutableHashMap, key: K, value: V) => MutableHashMap >(3, (self: MutableHashMap, key: K, value: V) => { @@ -694,9 +910,15 @@ const getRefKey = ( * Updates the value of the specified key within the MutableHashMap if it exists. * If the key doesn't exist, the map remains unchanged. * - * @example + * **When to use** + * + * Use to transform an existing `MutableHashMap` value in place without + * inserting missing keys. + * + * **Example** (Modifying existing values) + * * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" + * import { MutableHashMap } from "effect" * * const map = MutableHashMap.make(["count", 5], ["total", 100]) * @@ -717,17 +939,26 @@ const getRefKey = ( * increment(map) * ``` * - * @since 2.0.0 + * @see {@link set} for inserting or replacing a value directly + * @see {@link modifyAt} for handling both missing and existing keys + * * @category mutations + * @since 2.0.0 */ export const modify: { /** * Updates the value of the specified key within the MutableHashMap if it exists. * If the key doesn't exist, the map remains unchanged. * - * @example + * **When to use** + * + * Use to transform an existing `MutableHashMap` value in place without + * inserting missing keys. + * + * **Example** (Modifying existing values) + * * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" + * import { MutableHashMap } from "effect" * * const map = MutableHashMap.make(["count", 5], ["total", 100]) * @@ -748,17 +979,26 @@ export const modify: { * increment(map) * ``` * - * @since 2.0.0 + * @see {@link set} for inserting or replacing a value directly + * @see {@link modifyAt} for handling both missing and existing keys + * * @category mutations + * @since 2.0.0 */ (key: K, f: (v: V) => V): (self: MutableHashMap) => MutableHashMap /** * Updates the value of the specified key within the MutableHashMap if it exists. * If the key doesn't exist, the map remains unchanged. * - * @example + * **When to use** + * + * Use to transform an existing `MutableHashMap` value in place without + * inserting missing keys. + * + * **Example** (Modifying existing values) + * * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" + * import { MutableHashMap } from "effect" * * const map = MutableHashMap.make(["count", 5], ["total", 100]) * @@ -779,8 +1019,11 @@ export const modify: { * increment(map) * ``` * - * @since 2.0.0 + * @see {@link set} for inserting or replacing a value directly + * @see {@link modifyAt} for handling both missing and existing keys + * * @category mutations + * @since 2.0.0 */ (self: MutableHashMap, key: K, f: (v: V) => V): MutableHashMap } = dual< @@ -788,9 +1031,15 @@ export const modify: { * Updates the value of the specified key within the MutableHashMap if it exists. * If the key doesn't exist, the map remains unchanged. * - * @example + * **When to use** + * + * Use to transform an existing `MutableHashMap` value in place without + * inserting missing keys. + * + * **Example** (Modifying existing values) + * * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" + * import { MutableHashMap } from "effect" * * const map = MutableHashMap.make(["count", 5], ["total", 100]) * @@ -811,17 +1060,26 @@ export const modify: { * increment(map) * ``` * - * @since 2.0.0 + * @see {@link set} for inserting or replacing a value directly + * @see {@link modifyAt} for handling both missing and existing keys + * * @category mutations + * @since 2.0.0 */ (key: K, f: (v: V) => V) => (self: MutableHashMap) => MutableHashMap, /** * Updates the value of the specified key within the MutableHashMap if it exists. * If the key doesn't exist, the map remains unchanged. * - * @example + * **When to use** + * + * Use to transform an existing `MutableHashMap` value in place without + * inserting missing keys. + * + * **Example** (Modifying existing values) + * * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" + * import { MutableHashMap } from "effect" * * const map = MutableHashMap.make(["count", 5], ["total", 100]) * @@ -842,8 +1100,11 @@ export const modify: { * increment(map) * ``` * - * @since 2.0.0 + * @see {@link set} for inserting or replacing a value directly + * @see {@link modifyAt} for handling both missing and existing keys + * * @category mutations + * @since 2.0.0 */ (self: MutableHashMap, key: K, f: (v: V) => V) => MutableHashMap >(3, (self: MutableHashMap, key: K, f: (v: V) => V) => { @@ -875,15 +1136,18 @@ export const modify: { }) /** - * Sets or removes the specified key in the MutableHashMap using an update function. - * The function receives the current value as an Option and returns an Option. - * If the function returns Some, the key is set to that value. - * If the function returns None, the key is removed. + * Updates or removes the specified key using a function from the current + * optional value to the next optional value. + * + * **When to use** + * + * Use to decide whether to insert, update, or remove a key based on its current + * optional value. + * + * **Example** (Updating or removing a key) * - * @example * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" - * import * as Option from "effect/Option" + * import { MutableHashMap, Option } from "effect" * * const map = MutableHashMap.make(["count", 5]) * @@ -916,20 +1180,27 @@ export const modify: { * console.log(MutableHashMap.has(map, "new")) // false (42 <= 50) * ``` * - * @since 2.0.0 + * @see {@link modify} for updating only when the key already exists + * @see {@link set} for inserting or replacing directly + * @see {@link remove} for deleting directly + * * @category mutations + * @since 2.0.0 */ export const modifyAt: { /** - * Sets or removes the specified key in the MutableHashMap using an update function. - * The function receives the current value as an Option and returns an Option. - * If the function returns Some, the key is set to that value. - * If the function returns None, the key is removed. + * Updates or removes the specified key using a function from the current + * optional value to the next optional value. + * + * **When to use** + * + * Use to decide whether to insert, update, or remove a key based on its current + * optional value. + * + * **Example** (Updating or removing a key) * - * @example * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" - * import * as Option from "effect/Option" + * import { MutableHashMap, Option } from "effect" * * const map = MutableHashMap.make(["count", 5]) * @@ -962,20 +1233,27 @@ export const modifyAt: { * console.log(MutableHashMap.has(map, "new")) // false (42 <= 50) * ``` * - * @since 2.0.0 + * @see {@link modify} for updating only when the key already exists + * @see {@link set} for inserting or replacing directly + * @see {@link remove} for deleting directly + * * @category mutations + * @since 2.0.0 */ (key: K, f: (value: Option.Option) => Option.Option): (self: MutableHashMap) => MutableHashMap /** - * Sets or removes the specified key in the MutableHashMap using an update function. - * The function receives the current value as an Option and returns an Option. - * If the function returns Some, the key is set to that value. - * If the function returns None, the key is removed. + * Updates or removes the specified key using a function from the current + * optional value to the next optional value. + * + * **When to use** + * + * Use to decide whether to insert, update, or remove a key based on its current + * optional value. + * + * **Example** (Updating or removing a key) * - * @example * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" - * import * as Option from "effect/Option" + * import { MutableHashMap, Option } from "effect" * * const map = MutableHashMap.make(["count", 5]) * @@ -1008,8 +1286,12 @@ export const modifyAt: { * console.log(MutableHashMap.has(map, "new")) // false (42 <= 50) * ``` * - * @since 2.0.0 + * @see {@link modify} for updating only when the key already exists + * @see {@link set} for inserting or replacing directly + * @see {@link remove} for deleting directly + * * @category mutations + * @since 2.0.0 */ ( self: MutableHashMap, @@ -1018,15 +1300,18 @@ export const modifyAt: { ): MutableHashMap } = dual< /** - * Sets or removes the specified key in the MutableHashMap using an update function. - * The function receives the current value as an Option and returns an Option. - * If the function returns Some, the key is set to that value. - * If the function returns None, the key is removed. + * Updates or removes the specified key using a function from the current + * optional value to the next optional value. + * + * **When to use** + * + * Use to decide whether to insert, update, or remove a key based on its current + * optional value. + * + * **Example** (Updating or removing a key) * - * @example * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" - * import * as Option from "effect/Option" + * import { MutableHashMap, Option } from "effect" * * const map = MutableHashMap.make(["count", 5]) * @@ -1059,20 +1344,27 @@ export const modifyAt: { * console.log(MutableHashMap.has(map, "new")) // false (42 <= 50) * ``` * - * @since 2.0.0 + * @see {@link modify} for updating only when the key already exists + * @see {@link set} for inserting or replacing directly + * @see {@link remove} for deleting directly + * * @category mutations + * @since 2.0.0 */ (key: K, f: (value: Option.Option) => Option.Option) => (self: MutableHashMap) => MutableHashMap, /** - * Sets or removes the specified key in the MutableHashMap using an update function. - * The function receives the current value as an Option and returns an Option. - * If the function returns Some, the key is set to that value. - * If the function returns None, the key is removed. + * Updates or removes the specified key using a function from the current + * optional value to the next optional value. + * + * **When to use** + * + * Use to decide whether to insert, update, or remove a key based on its current + * optional value. + * + * **Example** (Updating or removing a key) * - * @example * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" - * import * as Option from "effect/Option" + * import { MutableHashMap, Option } from "effect" * * const map = MutableHashMap.make(["count", 5]) * @@ -1105,8 +1397,12 @@ export const modifyAt: { * console.log(MutableHashMap.has(map, "new")) // false (42 <= 50) * ``` * - * @since 2.0.0 + * @see {@link modify} for updating only when the key already exists + * @see {@link set} for inserting or replacing directly + * @see {@link remove} for deleting directly + * * @category mutations + * @since 2.0.0 */ ( self: MutableHashMap, @@ -1130,9 +1426,14 @@ export const modifyAt: { * Removes the specified key from the MutableHashMap, mutating the map in place. * If the key doesn't exist, the map remains unchanged. * - * @example + * **When to use** + * + * Use to delete one key from a mutable hash map in place. + * + * **Example** (Removing a key) + * * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" + * import { MutableHashMap } from "effect" * * const map = MutableHashMap.make( * ["key1", 42], @@ -1157,17 +1458,25 @@ export const modifyAt: { * console.log(MutableHashMap.size(map)) // 1 * ``` * - * @since 2.0.0 + * @see {@link clear} for removing all entries + * @see {@link modifyAt} for conditionally removing based on the current value + * * @category mutations + * @since 2.0.0 */ export const remove: { /** * Removes the specified key from the MutableHashMap, mutating the map in place. * If the key doesn't exist, the map remains unchanged. * - * @example + * **When to use** + * + * Use to delete one key from a mutable hash map in place. + * + * **Example** (Removing a key) + * * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" + * import { MutableHashMap } from "effect" * * const map = MutableHashMap.make( * ["key1", 42], @@ -1192,17 +1501,25 @@ export const remove: { * console.log(MutableHashMap.size(map)) // 1 * ``` * - * @since 2.0.0 + * @see {@link clear} for removing all entries + * @see {@link modifyAt} for conditionally removing based on the current value + * * @category mutations + * @since 2.0.0 */ (key: K): (self: MutableHashMap) => MutableHashMap /** * Removes the specified key from the MutableHashMap, mutating the map in place. * If the key doesn't exist, the map remains unchanged. * - * @example + * **When to use** + * + * Use to delete one key from a mutable hash map in place. + * + * **Example** (Removing a key) + * * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" + * import { MutableHashMap } from "effect" * * const map = MutableHashMap.make( * ["key1", 42], @@ -1227,8 +1544,11 @@ export const remove: { * console.log(MutableHashMap.size(map)) // 1 * ``` * - * @since 2.0.0 + * @see {@link clear} for removing all entries + * @see {@link modifyAt} for conditionally removing based on the current value + * * @category mutations + * @since 2.0.0 */ (self: MutableHashMap, key: K): MutableHashMap } = dual< @@ -1236,9 +1556,14 @@ export const remove: { * Removes the specified key from the MutableHashMap, mutating the map in place. * If the key doesn't exist, the map remains unchanged. * - * @example + * **When to use** + * + * Use to delete one key from a mutable hash map in place. + * + * **Example** (Removing a key) + * * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" + * import { MutableHashMap } from "effect" * * const map = MutableHashMap.make( * ["key1", 42], @@ -1263,17 +1588,25 @@ export const remove: { * console.log(MutableHashMap.size(map)) // 1 * ``` * - * @since 2.0.0 + * @see {@link clear} for removing all entries + * @see {@link modifyAt} for conditionally removing based on the current value + * * @category mutations + * @since 2.0.0 */ (key: K) => (self: MutableHashMap) => MutableHashMap, /** * Removes the specified key from the MutableHashMap, mutating the map in place. * If the key doesn't exist, the map remains unchanged. * - * @example + * **When to use** + * + * Use to delete one key from a mutable hash map in place. + * + * **Example** (Removing a key) + * * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" + * import { MutableHashMap } from "effect" * * const map = MutableHashMap.make( * ["key1", 42], @@ -1298,8 +1631,11 @@ export const remove: { * console.log(MutableHashMap.size(map)) // 1 * ``` * - * @since 2.0.0 + * @see {@link clear} for removing all entries + * @see {@link modifyAt} for conditionally removing based on the current value + * * @category mutations + * @since 2.0.0 */ (self: MutableHashMap, key: K) => MutableHashMap >(2, (self: MutableHashMap, key_: K) => { @@ -1332,9 +1668,14 @@ export const remove: { * Removes all key-value pairs from the MutableHashMap, mutating the map in place. * The map becomes empty after this operation. * - * @example + * **When to use** + * + * Use to empty a mutable hash map while keeping the same map instance. + * + * **Example** (Clearing all entries) + * * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" + * import { MutableHashMap } from "effect" * * const map = MutableHashMap.make( * ["key1", 42], @@ -1355,8 +1696,11 @@ export const remove: { * console.log(MutableHashMap.size(map)) // 1 * ``` * - * @since 2.0.0 + * @see {@link remove} for deleting one key + * @see {@link empty} for creating a fresh empty map + * * @category mutations + * @since 2.0.0 */ export const clear = (self: MutableHashMap) => { self.backing.clear() @@ -1367,9 +1711,14 @@ export const clear = (self: MutableHashMap) => { /** * Returns the number of key-value pairs in the MutableHashMap. * - * @example + * **When to use** + * + * Use to read how many entries are currently stored in the mutable hash map. + * + * **Example** (Checking map size) + * * ```ts - * import * as MutableHashMap from "effect/MutableHashMap" + * import { MutableHashMap } from "effect" * * const map = MutableHashMap.empty() * console.log(MutableHashMap.size(map)) // 0 @@ -1385,25 +1734,84 @@ export const clear = (self: MutableHashMap) => { * console.log(MutableHashMap.size(map)) // 0 * ``` * - * @since 2.0.0 + * @see {@link isEmpty} for checking whether the map has no entries + * * @category elements + * @since 2.0.0 */ export const size = (self: MutableHashMap): number => self.backing.size /** + * Returns `true` when the `MutableHashMap` contains no key-value pairs. + * + * **When to use** + * + * Use to branch on whether a mutable map currently has any entries. + * + * @see {@link size} for reading the exact number of entries + * + * @category predicates * @since 2.0.0 */ export const isEmpty = (self: MutableHashMap): boolean => self.backing.size === 0 /** + * Runs a callback for each key-value pair in the `MutableHashMap`. + * + * **When to use** + * + * Use to run a synchronous side-effecting callback for every key-value pair in + * an existing mutable map. + * + * **Details** + * + * Iteration follows the backing map's order. The callback receives the value + * first and the key second, matching `Map.prototype.forEach`. + * + * @see {@link keys} for iterating only keys + * @see {@link values} for iterating only values + * + * @category traversing * @since 2.0.0 */ export const forEach: { /** + * Runs a callback for each key-value pair in the `MutableHashMap`. + * + * **When to use** + * + * Use to run a synchronous side-effecting callback for every key-value pair in + * an existing mutable map. + * + * **Details** + * + * Iteration follows the backing map's order. The callback receives the value + * first and the key second, matching `Map.prototype.forEach`. + * + * @see {@link keys} for iterating only keys + * @see {@link values} for iterating only values + * + * @category traversing * @since 2.0.0 */ (f: (value: V, key: K) => void): (self: MutableHashMap) => void /** + * Runs a callback for each key-value pair in the `MutableHashMap`. + * + * **When to use** + * + * Use to run a synchronous side-effecting callback for every key-value pair in + * an existing mutable map. + * + * **Details** + * + * Iteration follows the backing map's order. The callback receives the value + * first and the key second, matching `Map.prototype.forEach`. + * + * @see {@link keys} for iterating only keys + * @see {@link values} for iterating only values + * + * @category traversing * @since 2.0.0 */ (self: MutableHashMap, f: (value: V, key: K) => void): void diff --git a/.opencode/node_modules/effect/src/MutableHashSet.ts b/.opencode/node_modules/effect/src/MutableHashSet.ts index 58e48c804c558edef314d8953218ce6b775969ce..73ee943c594888f30c93b800c273b77cc01b75b0 100644 --- a/.opencode/node_modules/effect/src/MutableHashSet.ts +++ b/.opencode/node_modules/effect/src/MutableHashSet.ts @@ -1,28 +1,13 @@ /** - * @fileoverview - * MutableHashSet is a high-performance, mutable set implementation that provides efficient storage - * and retrieval of unique values. Built on top of MutableHashMap, it inherits the same performance - * characteristics and support for both structural and referential equality. - * - * The implementation uses a MutableHashMap internally where each value is stored as a key with a - * boolean flag, providing O(1) average-case performance for all operations. - * - * Key Features: - * - Mutable operations for performance-critical scenarios - * - Supports both structural and referential equality - * - Efficient duplicate detection and removal - * - Iterable interface for easy traversal - * - Memory-efficient storage with automatic deduplication - * - Seamless integration with Effect's Equal and Hash interfaces - * - * Performance Characteristics: - * - Add/Has/Remove: O(1) average, O(n) worst case (hash collisions) - * - Clear: O(1) - * - Size: O(1) - * - Iteration: O(n) + * Stores unique values in a mutable hash set. + * + * `MutableHashSet` updates the same collection in place and supports fast + * membership checks, insertion, removal, clearing, and iteration. It is built + * on `MutableHashMap`: each set value is stored as a map key, so uniqueness + * follows the same hashing and equality rules as the underlying mutable hash + * map. * * @since 2.0.0 - * @category data-structures */ import { format } from "./Formatter.ts" import * as Dual from "./Function.ts" @@ -35,7 +20,22 @@ import { hasProperty } from "./Predicate.ts" const TypeId = "~effect/collections/MutableHashSet" /** - * @example + * A mutable hash set for storing unique values with Effect structural equality + * support. + * + * **When to use** + * + * Use to store and mutate a collection of unique values with Effect hashing and + * equality semantics. + * + * **Details** + * + * Operations mutate the set in place. Values that implement `Equal` / `Hash` + * can be de-duplicated structurally; other values use normal JavaScript + * reference or primitive equality. + * + * **Example** (Using a mutable hash set) + * * ```ts * import { MutableHashSet } from "effect" * @@ -61,8 +61,8 @@ const TypeId = "~effect/collections/MutableHashSet" * console.log(MutableHashSet.size(set)) // 3 * ``` * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface MutableHashSet extends Iterable, Pipeable, Inspectable { readonly [TypeId]: typeof TypeId @@ -70,7 +70,21 @@ export interface MutableHashSet extends Iterable, Pipeable, Inspectabl } /** - * Checks if the specified value is a `MutableHashSet`, `false` otherwise. + * Checks whether the specified value is a `MutableHashSet`, `false` otherwise. + * + * **When to use** + * + * Use to narrow an unknown value before treating it as a mutable hash set. + * + * **Details** + * + * The check looks for the `MutableHashSet` runtime marker. + * + * **Gotchas** + * + * Native `Set` values do not satisfy this check. + * + * @see {@link MutableHashSet} for the mutable hash set interface * * @category refinements * @since 4.0.0 @@ -108,7 +122,16 @@ const fromHashMap = (keyMap: MutableHashMap.MutableHashMap): Muta /** * Creates an empty MutableHashSet. * - * @example + * **When to use** + * + * Use to create a fresh mutable set before adding values over time. + * + * **Details** + * + * Each call returns a new empty set backed by an empty `MutableHashMap`. + * + * **Example** (Creating an empty set) + * * ```ts * import { MutableHashSet } from "effect" * @@ -123,8 +146,12 @@ const fromHashMap = (keyMap: MutableHashMap.MutableHashMap): Muta * console.log(Array.from(set)) // ["apple", "banana"] * ``` * - * @since 2.0.0 + * @see {@link make} for creating a set from explicit values + * @see {@link fromIterable} for creating a set from an iterable of values + * @see {@link clear} for emptying an existing mutable set + * * @category constructors + * @since 2.0.0 */ export const empty = (): MutableHashSet => fromHashMap(MutableHashMap.empty()) @@ -132,7 +159,12 @@ export const empty = (): MutableHashSet => fromHashMap(MutableHash * Creates a MutableHashSet from an iterable collection of values. * Duplicates are automatically removed. * - * @example + * **When to use** + * + * Use to build a mutable hash set from any iterable of values. + * + * **Example** (Creating a set from an iterable) + * * ```ts * import { MutableHashSet } from "effect" * @@ -151,8 +183,8 @@ export const empty = (): MutableHashSet => fromHashMap(MutableHash * console.log(Array.from(fromString)) // ["h", "e", "l", "o"] * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const fromIterable = (keys: Iterable): MutableHashSet => fromHashMap(MutableHashMap.fromIterable(Array.from(keys).map((k) => [k, true]))) @@ -161,7 +193,12 @@ export const fromIterable = (keys: Iterable): MutableHashSet => * Creates a MutableHashSet from a variable number of values. * Duplicates are automatically removed. * - * @example + * **When to use** + * + * Use to build a mutable hash set from explicit values. + * + * **Example** (Creating a set from values) + * * ```ts * import { MutableHashSet } from "effect" * @@ -180,8 +217,8 @@ export const fromIterable = (keys: Iterable): MutableHashSet => * console.log(MutableHashSet.size(mixed)) // 3 * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const make = >( ...keys: Keys @@ -191,7 +228,12 @@ export const make = >( * Adds a value to the MutableHashSet, mutating the set in place. * If the value already exists, the set remains unchanged. * - * @example + * **When to use** + * + * Use to insert a value into a mutable set while keeping uniqueness. + * + * **Example** (Adding values) + * * ```ts * import { MutableHashSet } from "effect" * @@ -214,15 +256,20 @@ export const make = >( * console.log(MutableHashSet.size(set)) // 3 * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ export const add: { /** * Adds a value to the MutableHashSet, mutating the set in place. * If the value already exists, the set remains unchanged. * - * @example + * **When to use** + * + * Use to insert a value into a mutable set while keeping uniqueness. + * + * **Example** (Adding values) + * * ```ts * import { MutableHashSet } from "effect" * @@ -245,15 +292,20 @@ export const add: { * console.log(MutableHashSet.size(set)) // 3 * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ (key: V): (self: MutableHashSet) => MutableHashSet /** * Adds a value to the MutableHashSet, mutating the set in place. * If the value already exists, the set remains unchanged. * - * @example + * **When to use** + * + * Use to insert a value into a mutable set while keeping uniqueness. + * + * **Example** (Adding values) + * * ```ts * import { MutableHashSet } from "effect" * @@ -276,8 +328,8 @@ export const add: { * console.log(MutableHashSet.size(set)) // 3 * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ (self: MutableHashSet, key: V): MutableHashSet } = Dual.dual< @@ -286,9 +338,19 @@ export const add: { >(2, (self, key) => (MutableHashMap.set(self.keyMap, key, true), self)) /** - * Checks if the MutableHashSet contains the specified value. + * Checks whether the MutableHashSet contains the specified value. + * + * **When to use** + * + * Use to test whether a mutable set currently contains a value. + * + * **Details** + * + * Membership follows the same hashing and equality rules as the underlying + * `MutableHashMap`. + * + * **Example** (Checking for a value) * - * @example * ```ts * import { MutableHashSet } from "effect" * @@ -306,14 +368,27 @@ export const add: { * console.log(MutableHashSet.has(set, "grape")) // true * ``` * - * @since 2.0.0 + * @see {@link add} for adding a value to the set + * @see {@link remove} for removing a value from the set + * * @category elements + * @since 2.0.0 */ export const has: { /** - * Checks if the MutableHashSet contains the specified value. + * Checks whether the MutableHashSet contains the specified value. + * + * **When to use** + * + * Use to test whether a mutable set currently contains a value. + * + * **Details** + * + * Membership follows the same hashing and equality rules as the underlying + * `MutableHashMap`. + * + * **Example** (Checking for a value) * - * @example * ```ts * import { MutableHashSet } from "effect" * @@ -331,14 +406,27 @@ export const has: { * console.log(MutableHashSet.has(set, "grape")) // true * ``` * - * @since 2.0.0 + * @see {@link add} for adding a value to the set + * @see {@link remove} for removing a value from the set + * * @category elements + * @since 2.0.0 */ (key: V): (self: MutableHashSet) => boolean /** - * Checks if the MutableHashSet contains the specified value. + * Checks whether the MutableHashSet contains the specified value. + * + * **When to use** + * + * Use to test whether a mutable set currently contains a value. + * + * **Details** + * + * Membership follows the same hashing and equality rules as the underlying + * `MutableHashMap`. + * + * **Example** (Checking for a value) * - * @example * ```ts * import { MutableHashSet } from "effect" * @@ -356,8 +444,11 @@ export const has: { * console.log(MutableHashSet.has(set, "grape")) // true * ``` * - * @since 2.0.0 + * @see {@link add} for adding a value to the set + * @see {@link remove} for removing a value from the set + * * @category elements + * @since 2.0.0 */ (self: MutableHashSet, key: V): boolean } = Dual.dual< @@ -369,7 +460,12 @@ export const has: { * Removes the specified value from the MutableHashSet, mutating the set in place. * If the value doesn't exist, the set remains unchanged. * - * @example + * **When to use** + * + * Use to delete a value from a mutable set if it is present. + * + * **Example** (Removing a value) + * * ```ts * import { MutableHashSet } from "effect" * @@ -392,15 +488,20 @@ export const has: { * console.log(MutableHashSet.size(set)) // 1 * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ export const remove: { /** * Removes the specified value from the MutableHashSet, mutating the set in place. * If the value doesn't exist, the set remains unchanged. * - * @example + * **When to use** + * + * Use to delete a value from a mutable set if it is present. + * + * **Example** (Removing a value) + * * ```ts * import { MutableHashSet } from "effect" * @@ -423,15 +524,20 @@ export const remove: { * console.log(MutableHashSet.size(set)) // 1 * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ (key: V): (self: MutableHashSet) => MutableHashSet /** * Removes the specified value from the MutableHashSet, mutating the set in place. * If the value doesn't exist, the set remains unchanged. * - * @example + * **When to use** + * + * Use to delete a value from a mutable set if it is present. + * + * **Example** (Removing a value) + * * ```ts * import { MutableHashSet } from "effect" * @@ -454,8 +560,8 @@ export const remove: { * console.log(MutableHashSet.size(set)) // 1 * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ (self: MutableHashSet, key: V): MutableHashSet } = Dual.dual< @@ -466,7 +572,12 @@ export const remove: { /** * Returns the number of unique values in the MutableHashSet. * - * @example + * **When to use** + * + * Use to read how many unique values are currently stored in the set. + * + * **Example** (Checking set size) + * * ```ts * import { MutableHashSet } from "effect" * @@ -485,8 +596,8 @@ export const remove: { * console.log(MutableHashSet.size(set)) // 0 * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ export const size = (self: MutableHashSet): number => MutableHashMap.size(self.keyMap) @@ -494,7 +605,12 @@ export const size = (self: MutableHashSet): number => MutableHashMap.size( * Removes all values from the MutableHashSet, mutating the set in place. * The set becomes empty after this operation. * - * @example + * **When to use** + * + * Use to empty a mutable set while keeping the same set instance. + * + * **Example** (Clearing all values) + * * ```ts * import { MutableHashSet } from "effect" * @@ -514,7 +630,7 @@ export const size = (self: MutableHashSet): number => MutableHashMap.size( * console.log(MutableHashSet.size(set)) // 1 * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ export const clear = (self: MutableHashSet): MutableHashSet => (MutableHashMap.clear(self.keyMap), self) diff --git a/.opencode/node_modules/effect/src/MutableList.ts b/.opencode/node_modules/effect/src/MutableList.ts index cbe3e0a0cc29686f1ef0eb377ad5027087617af4..7dbe56f27c76841154f3aa415f7077ec0226d801 100644 --- a/.opencode/node_modules/effect/src/MutableList.ts +++ b/.opencode/node_modules/effect/src/MutableList.ts @@ -1,38 +1,12 @@ /** - * @fileoverview - * MutableList is an efficient, mutable linked list implementation optimized for high-throughput - * scenarios like logging, queuing, and streaming. It uses a bucket-based architecture where - * elements are stored in arrays (buckets) linked together, providing optimal performance for - * both append and prepend operations. - * - * The implementation uses a sophisticated bucket system: - * - Each bucket contains an array of elements with an offset pointer - * - Buckets can be marked as mutable or immutable for optimization - * - Elements are taken from the head and added to the tail - * - Memory is efficiently managed through bucket reuse and cleanup - * - * Key Features: - * - Highly optimized for high-frequency append/prepend operations - * - Memory efficient with automatic cleanup of consumed elements - * - Support for bulk operations (appendAll, prependAll, takeN) - * - Filtering and removal operations - * - Zero-copy optimizations for certain scenarios - * - * Performance Characteristics: - * - Append/Prepend: O(1) amortized - * - Take/TakeN: O(1) per element taken - * - Length: O(1) - * - Clear: O(1) - * - Filter: O(n) - * - * Ideal Use Cases: - * - High-throughput logging systems - * - Producer-consumer queues - * - Streaming data buffers - * - Real-time data processing pipelines + * Mutable lists for collecting ordered values and draining them from the front. + * A `MutableList` can append values to the end, prepend values to the + * beginning, take one or more values from the front, inspect its contents as an + * array, filter values, remove values, and clear itself. All operations update + * the same list object in place and keep its `length` field current. Taking + * from an empty list returns the `Empty` symbol. * * @since 4.0.0 - * @category data-structures */ import * as Arr from "./Array.ts" @@ -41,9 +15,10 @@ import * as Arr from "./Array.ts" * MutableList provides efficient append/prepend operations and is ideal for * producer-consumer patterns, queues, and streaming scenarios. * - * @example + * **Example** (Creating and consuming a mutable list) + * * ```ts - * import * as MutableList from "effect/MutableList" + * import { MutableList } from "effect" * * // Create a mutable list * const list: MutableList.MutableList = MutableList.make() @@ -64,8 +39,8 @@ import * as Arr from "./Array.ts" * console.log(MutableList.take(list)) // 2 * ``` * - * @since 4.0.0 * @category models + * @since 2.0.0 */ export interface MutableList { head: MutableList.Bucket | undefined @@ -77,9 +52,10 @@ export interface MutableList { * The MutableList namespace contains type definitions and utilities for working * with mutable linked lists. * - * @example + * **Example** (Typing queue processors) + * * ```ts - * import * as MutableList from "effect/MutableList" + * import { MutableList } from "effect" * * // Type annotation using the namespace * const processQueue = (queue: MutableList.MutableList) => { @@ -106,17 +82,23 @@ export interface MutableList { * } * ``` * - * @since 4.0.0 - * @category models + * @since 2.0.0 */ export declare namespace MutableList { /** - * Internal bucket structure used by MutableList to store elements efficiently. - * Buckets are linked together to form the list structure. + * Storage node used by the exposed `head` and `tail` fields of a + * `MutableList`. + * + * **Details** + * + * Most code should treat buckets as an implementation detail and use + * `MutableList` operations such as `append`, `prepend`, and `take` instead + * of constructing or mutating buckets directly. + * + * **Example** (Inspecting buckets) * - * @example * ```ts - * import * as MutableList from "effect/MutableList" + * import { MutableList } from "effect" * * const list = MutableList.make() * MutableList.append(list, 1) @@ -138,8 +120,8 @@ export declare namespace MutableList { * inspectBucket(list.tail) * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface Bucket { readonly array: Array @@ -150,12 +132,18 @@ export declare namespace MutableList { } /** - * A unique symbol used to represent an empty result when taking elements from a MutableList. + * Defines the unique symbol used to represent an empty result when taking elements from a MutableList. * This symbol is returned by `take` when the list is empty, allowing for safe type checking. * - * @example + * **When to use** + * + * Use to detect that `take` returned no element before handling the result as a + * list item. + * + * **Example** (Checking for empty results) + * * ```ts - * import * as MutableList from "effect/MutableList" + * import { MutableList } from "effect" * * const list = MutableList.make() * @@ -182,8 +170,8 @@ export declare namespace MutableList { * console.log(empty === MutableList.Empty) // true, list is empty * ``` * + * @category symbols * @since 4.0.0 - * @category Symbols */ export const Empty: unique symbol = Symbol.for("effect/MutableList/Empty") @@ -191,9 +179,10 @@ export const Empty: unique symbol = Symbol.for("effect/MutableList/Empty") * The type of the Empty symbol, used for type checking when taking elements from a MutableList. * This provides compile-time safety when checking for empty results. * - * @example + * **Example** (Handling empty results type-safely) + * * ```ts - * import * as MutableList from "effect/MutableList" + * import { MutableList } from "effect" * * const list = MutableList.make() * @@ -231,17 +220,18 @@ export const Empty: unique symbol = Symbol.for("effect/MutableList/Empty") * } * ``` * + * @category symbols * @since 4.0.0 - * @category Symbols */ export type Empty = typeof Empty /** * Creates an empty MutableList. * - * @example + * **Example** (Creating an empty mutable list) + * * ```ts - * import * as MutableList from "effect/MutableList" + * import { MutableList } from "effect" * * const list = MutableList.make() * @@ -258,8 +248,8 @@ export type Empty = typeof Empty * console.log(MutableList.take(list)) // "second" * ``` * - * @since 4.0.0 * @category constructors + * @since 2.0.0 */ export const make = (): MutableList => ({ head: undefined, @@ -278,9 +268,10 @@ const emptyBucket = (): MutableList.Bucket => ({ * Appends an element to the end of the MutableList. * This operation is optimized for high-frequency usage. * - * @example + * **Example** (Appending elements) + * * ```ts - * import * as MutableList from "effect/MutableList" + * import { MutableList } from "effect" * * const list = MutableList.make() * @@ -302,8 +293,8 @@ const emptyBucket = (): MutableList.Bucket => ({ * } * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ export const append = (self: MutableList, message: A): void => { if (!self.tail) { @@ -320,9 +311,10 @@ export const append = (self: MutableList, message: A): void => { * Prepends an element to the beginning of the MutableList. * This operation is optimized for high-frequency usage. * - * @example + * **Example** (Prepending elements) + * * ```ts - * import * as MutableList from "effect/MutableList" + * import { MutableList } from "effect" * * const list = MutableList.make() * @@ -344,8 +336,8 @@ export const append = (self: MutableList, message: A): void => { * console.log(MutableList.take(list)) // "priority" * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ export const prepend = (self: MutableList, message: A): void => { self.head = { @@ -362,9 +354,10 @@ export const prepend = (self: MutableList, message: A): void => { * The elements are added in order, so the first element in the iterable becomes * the new head of the list. * - * @example + * **Example** (Prepending multiple elements) + * * ```ts - * import * as MutableList from "effect/MutableList" + * import { MutableList } from "effect" * * const list = MutableList.make() * MutableList.append(list, 4) @@ -384,8 +377,8 @@ export const prepend = (self: MutableList, message: A): void => { * console.log(MutableList.takeAll(newList)) // ["h", "e", "l", "l", "o"] * ``` * - * @since 4.0.0 * @category mutations + * @since 4.0.0 */ export const prependAll = (self: MutableList, messages: Iterable): void => prependAllUnsafe(self, Arr.fromIterable(messages), !Array.isArray(messages)) @@ -394,12 +387,20 @@ export const prependAll = (self: MutableList, messages: Iterable): void * Prepends all elements from a ReadonlyArray to the beginning of the MutableList. * This is an optimized version that can reuse the array when mutable=true. * - * ⚠️ **Warning**: When mutable=true, the input array may be modified internally. - * Only use mutable=true when you control the array lifecycle. + * **When to use** + * + * Use when prepending a trusted array directly is worth the optimized path and + * you control whether the input may be reused. + * + * **Gotchas** + * + * When mutable=true, the input array may be modified internally. Only use + * mutable=true when you control the array lifecycle. + * + * **Example** (Prepending arrays with optional mutation) * - * @example * ```ts - * import * as MutableList from "effect/MutableList" + * import { MutableList } from "effect" * * const list = MutableList.make() * MutableList.append(list, 4) @@ -417,8 +418,8 @@ export const prependAll = (self: MutableList, messages: Iterable): void * console.log(MutableList.takeAll(list)) // [10, 20, 30, 1, 2, 3, 4] * ``` * - * @since 4.0.0 * @category mutations + * @since 4.0.0 */ export const prependAllUnsafe = (self: MutableList, messages: ReadonlyArray, mutable = false): void => { self.head = { @@ -434,9 +435,10 @@ export const prependAllUnsafe = (self: MutableList, messages: ReadonlyArra * Appends all elements from an iterable to the end of the MutableList. * Returns the number of elements added. * - * @example + * **Example** (Appending multiple elements) + * * ```ts - * import * as MutableList from "effect/MutableList" + * import { MutableList } from "effect" * * const list = MutableList.make() * MutableList.append(list, 1) @@ -464,8 +466,8 @@ export const prependAllUnsafe = (self: MutableList, messages: ReadonlyArra * console.log(count) // 1000 * ``` * - * @since 4.0.0 * @category mutations + * @since 4.0.0 */ export const appendAll = (self: MutableList, messages: Iterable): number => appendAllUnsafe(self, Arr.fromIterable(messages), !Array.isArray(messages)) @@ -475,12 +477,20 @@ export const appendAll = (self: MutableList, messages: Iterable): numbe * This is an optimized version that can reuse the array when mutable=true. * Returns the number of elements added. * - * ⚠️ **Warning**: When mutable=true, the input array may be modified internally. - * Only use mutable=true when you control the array lifecycle. + * **When to use** + * + * Use when appending a trusted array directly is worth the optimized path and + * you control whether the input may be reused. + * + * **Gotchas** + * + * When mutable=true, the input array may be modified internally. Only use + * mutable=true when you control the array lifecycle. + * + * **Example** (Appending arrays with optional mutation) * - * @example * ```ts - * import * as MutableList from "effect/MutableList" + * import { MutableList } from "effect" * * const list = MutableList.make() * MutableList.append(list, 1) @@ -503,8 +513,8 @@ export const appendAll = (self: MutableList, messages: Iterable): numbe * MutableList.appendAllUnsafe(list, bigArray, true) // Very efficient * ``` * - * @since 4.0.0 * @category mutations + * @since 4.0.0 */ export const appendAllUnsafe = (self: MutableList, messages: ReadonlyArray, mutable = false): number => { if (messages.length === 0) { @@ -529,9 +539,10 @@ export const appendAllUnsafe = (self: MutableList, messages: ReadonlyArray * Removes all elements from the MutableList, resetting it to an empty state. * This operation is highly optimized and releases all internal memory. * - * @example + * **Example** (Clearing a mutable list) + * * ```ts - * import * as MutableList from "effect/MutableList" + * import { MutableList } from "effect" * * const list = MutableList.make() * MutableList.appendAll(list, [1, 2, 3, 4, 5]) @@ -555,8 +566,8 @@ export const appendAllUnsafe = (self: MutableList, messages: ReadonlyArray * } * ``` * - * @since 4.0.0 * @category mutations + * @since 4.0.0 */ export const clear = (self: MutableList): void => { self.head = self.tail = undefined @@ -568,9 +579,10 @@ export const clear = (self: MutableList): void => { * The taken elements are removed from the list. This operation is optimized for performance * and includes zero-copy optimizations when possible. * - * @example + * **Example** (Taking batches) + * * ```ts - * import * as MutableList from "effect/MutableList" + * import { MutableList } from "effect" * * const list = MutableList.make() * MutableList.appendAll(list, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) @@ -601,8 +613,8 @@ export const clear = (self: MutableList): void => { * } * ``` * - * @since 4.0.0 * @category elements + * @since 4.0.0 */ export const takeN = (self: MutableList, n: number): Array => { if (n <= 0 || !self.head) return [] @@ -634,8 +646,25 @@ export const takeN = (self: MutableList, n: number): Array => { } /** - * @since 4.0.0 + * Removes up to `n` elements from the beginning of the `MutableList` without + * returning them. + * + * **When to use** + * + * Use to discard a bounded number of values from the head of a `MutableList` + * when the removed values are not needed. + * + * **Details** + * + * If `n` is less than or equal to zero, or the list is empty, the list is left + * unchanged. If `n` is greater than or equal to the current length, the list is + * cleared. + * + * @see {@link takeN} for removing up to `n` values and returning them as an array + * @see {@link clear} for removing every value from the list + * * @category elements + * @since 4.0.0 */ export const takeNVoid = (self: MutableList, n: number): void => { if (n <= 0 || !self.head) return @@ -665,9 +694,10 @@ export const takeNVoid = (self: MutableList, n: number): void => { * Takes all elements from the MutableList and returns them as an array. * The list becomes empty after this operation. This is equivalent to takeN(list, list.length). * - * @example + * **Example** (Draining all elements) + * * ```ts - * import * as MutableList from "effect/MutableList" + * import { MutableList } from "effect" * * const list = MutableList.make() * MutableList.appendAll(list, ["apple", "banana", "cherry"]) @@ -699,8 +729,8 @@ export const takeNVoid = (self: MutableList, n: number): void => { * } * ``` * - * @since 4.0.0 * @category elements + * @since 4.0.0 */ export const takeAll = (self: MutableList): Array => takeN(self, self.length) @@ -709,9 +739,10 @@ export const takeAll = (self: MutableList): Array => takeN(self, self.l * Returns the element if available, or the Empty symbol if the list is empty. * The taken element is removed from the list. * - * @example + * **Example** (Taking one element) + * * ```ts - * import * as MutableList from "effect/MutableList" + * import { MutableList } from "effect" * * const list = MutableList.make() * MutableList.appendAll(list, ["first", "second", "third"]) @@ -749,8 +780,8 @@ export const takeAll = (self: MutableList): Array => takeN(self, self.l * } * ``` * - * @since 4.0.0 * @category elements + * @since 4.0.0 */ export const take = (self: MutableList): Empty | A => { if (!self.head) return Empty @@ -769,8 +800,18 @@ export const take = (self: MutableList): Empty | A => { } /** - * @since 4.0.0 + * Copies up to `n` elements from the beginning of the `MutableList` into a new + * array without modifying the list. + * + * **When to use** + * + * Use when you need to inspect or snapshot a bounded prefix of the list without + * consuming it. + * + * @see {@link takeN} for removing up to `n` values and returning them as an array + * * @category elements + * @since 4.0.0 */ export const toArrayN = (self: MutableList, n: number): Array => { const length = Math.min(n, self.length) @@ -788,8 +829,18 @@ export const toArrayN = (self: MutableList, n: number): Array => { } /** - * @since 4.0.0 + * Copies all current elements of the `MutableList` into a new array without + * modifying the list. + * + * **When to use** + * + * Use when you need a snapshot of all current elements while keeping the list + * unchanged. + * + * @see {@link takeAll} for converting all elements to an array and clearing the list + * * @category elements + * @since 4.0.0 */ export const toArray = (self: MutableList): Array => toArrayN(self, self.length) @@ -797,9 +848,10 @@ export const toArray = (self: MutableList): Array => toArrayN(self, sel * Filters the MutableList in place, keeping only elements that satisfy the predicate. * This operation modifies the list and rebuilds its internal structure for efficiency. * - * @example + * **Example** (Filtering in place) + * * ```ts - * import * as MutableList from "effect/MutableList" + * import { MutableList } from "effect" * * const list = MutableList.make() * MutableList.appendAll(list, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) @@ -809,7 +861,6 @@ export const toArray = (self: MutableList): Array => toArrayN(self, sel * // Keep only even numbers * MutableList.filter(list, (n) => n % 2 === 0) * - * console.log(list.length) // 5 * console.log(MutableList.takeAll(list)) // [2, 4, 6, 8, 10] * * // Filter with index @@ -831,11 +882,11 @@ export const toArray = (self: MutableList): Array => toArrayN(self, sel * * // Keep only errors * MutableList.filter(logs, (log) => log.level === "ERROR") - * console.log(MutableList.takeAll(logs)) // Only error logs + * console.log(MutableList.takeAll(logs).map((log) => log.message)) // ["Connection failed", "Timeout"] * ``` * - * @since 4.0.0 * @category mutations + * @since 4.0.0 */ export const filter = (self: MutableList, f: (value: A, i: number) => boolean): void => { const array: Array = [] @@ -854,15 +905,31 @@ export const filter = (self: MutableList, f: (value: A, i: number) => bool offset: 0, next: undefined } + self.length = array.length } /** - * Removes all occurrences of a specific value from the MutableList. - * This operation modifies the list in place. + * Removes all occurrences of a value from the `MutableList` using JavaScript + * strict equality semantics. + * + * **When to use** + * + * Use when in-place removal should use JavaScript identity/strict equality + * rather than Effect structural equality. + * + * **Details** + * + * The list is modified in place. + * + * **Gotchas** + * + * Values are compared with `!==`, so this does not use Effect structural + * equality. + * + * **Example** (Removing matching values) * - * @example * ```ts - * import * as MutableList from "effect/MutableList" + * import { MutableList } from "effect" * * const list = MutableList.make() * MutableList.appendAll(list, ["apple", "banana", "apple", "cherry", "apple"]) @@ -872,12 +939,13 @@ export const filter = (self: MutableList, f: (value: A, i: number) => bool * // Remove all occurrences of "apple" * MutableList.remove(list, "apple") * - * console.log(list.length) // 2 * console.log(MutableList.takeAll(list)) // ["banana", "cherry"] * * // Remove non-existent value (no effect) - * MutableList.remove(list, "grape") - * console.log(list.length) // 2 + * const colors = MutableList.make() + * MutableList.appendAll(colors, ["red", "blue"]) + * MutableList.remove(colors, "green") + * console.log(MutableList.takeAll(colors)) // ["red", "blue"] * * // Real-world example: removing completed tasks * const tasks = MutableList.make<{ id: number; status: string }>() @@ -890,10 +958,10 @@ export const filter = (self: MutableList, f: (value: A, i: number) => bool * * // Remove completed tasks by filtering status * MutableList.filter(tasks, (task) => task.status !== "completed") - * console.log(MutableList.takeAll(tasks)) // Only pending tasks + * console.log(MutableList.takeAll(tasks).map((task) => task.id)) // [1, 3] * ``` * - * @since 4.0.0 * @category mutations + * @since 4.0.0 */ export const remove = (self: MutableList, value: A): void => filter(self, (v) => v !== value) diff --git a/.opencode/node_modules/effect/src/MutableRef.ts b/.opencode/node_modules/effect/src/MutableRef.ts index ec2f958707d8d6229f91b70101440e6ff6bfc3f1..71f5fdb0de472c5bd3c9244d8ff07859d4db8062 100644 --- a/.opencode/node_modules/effect/src/MutableRef.ts +++ b/.opencode/node_modules/effect/src/MutableRef.ts @@ -1,34 +1,13 @@ /** - * @fileoverview - * MutableRef provides a mutable reference container that allows safe mutation of values - * in functional programming contexts. It serves as a bridge between functional and imperative - * programming paradigms, offering atomic operations for state management. - * - * Unlike regular variables, MutableRef encapsulates mutable state and provides controlled - * access through a standardized API. It supports atomic compare-and-set operations for - * thread-safe updates and integrates seamlessly with Effect's ecosystem. - * - * Key Features: - * - Mutable reference semantics with functional API - * - Atomic compare-and-set operations for safe concurrent updates - * - Specialized operations for numeric and boolean values - * - Chainable operations that return the reference or the value - * - Integration with Effect's Equal interface for value comparison - * - * Common Use Cases: - * - State containers in functional applications - * - Counters and accumulators - * - Configuration that needs to be updated at runtime - * - Caching and memoization scenarios - * - Inter-module communication via shared references - * - * Performance Characteristics: - * - Get/Set: O(1) - * - Compare-and-set: O(1) - * - All operations: O(1) + * Stores synchronous mutable state in a small reference object. + * + * A `MutableRef` stores one current value and exposes it through `.current`. + * Unlike `Ref`, its operations are synchronous and update the same object in + * place. This module includes pipeable helpers for reading, setting, comparing, + * and updating the value, plus numeric increment/decrement helpers and a + * boolean toggle helper. * * @since 2.0.0 - * @category data-structures */ import * as Equal from "./Equal.ts" import * as Dual from "./Function.ts" @@ -39,7 +18,20 @@ import type { Pipeable } from "./Pipeable.ts" const TypeId = "~effect/MutableRef" /** - * @example + * A synchronous mutable reference that stores a current value. + * + * **When to use** + * + * Use to keep local mutable state in a stable, pipeable reference. + * + * **Details** + * + * Read or write the value directly through `.current`, or use the `MutableRef` + * helpers for pipeable updates such as `get`, `set`, `update`, and + * `compareAndSet`. All operations mutate the same reference in place. + * + * **Example** (Creating and updating refs) + * * ```ts * import { MutableRef } from "effect" * @@ -70,8 +62,8 @@ const TypeId = "~effect/MutableRef" * console.log(config.current.timeout) // 10000 * ``` * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface MutableRef extends Pipeable, Inspectable { readonly [TypeId]: typeof TypeId @@ -92,7 +84,12 @@ const MutableRefProto: Omit, "current"> = { /** * Creates a new MutableRef with the specified initial value. * - * @example + * **When to use** + * + * Use to create a synchronous `MutableRef` initialized with a value. + * + * **Example** (Creating mutable refs) + * * ```ts * import { MutableRef } from "effect" * @@ -110,8 +107,8 @@ const MutableRefProto: Omit, "current"> = { * console.log(MutableRef.get(status)) // "running" * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const make = (value: T): MutableRef => { const ref = Object.create(MutableRefProto) @@ -120,11 +117,17 @@ export const make = (value: T): MutableRef => { } /** - * Atomically sets the value to newValue if the current value equals oldValue. + * Sets the value to newValue atomically if the current value equals oldValue. * Returns true if the value was updated, false otherwise. * Uses Effect's Equal interface for value comparison. * - * @example + * **When to use** + * + * Use to replace a `MutableRef` value only when the current value still matches + * an expected value. + * + * **Example** (Comparing and setting values) + * * ```ts * import { MutableRef } from "effect" * @@ -152,16 +155,22 @@ export const make = (value: T): MutableRef => { * console.log(casUpdate(ref)) // true * ``` * - * @since 2.0.0 * @category general + * @since 2.0.0 */ export const compareAndSet: { /** - * Atomically sets the value to newValue if the current value equals oldValue. + * Sets the value to newValue atomically if the current value equals oldValue. * Returns true if the value was updated, false otherwise. * Uses Effect's Equal interface for value comparison. * - * @example + * **When to use** + * + * Use to replace a `MutableRef` value only when the current value still matches + * an expected value. + * + * **Example** (Comparing and setting values) + * * ```ts * import { MutableRef } from "effect" * @@ -189,16 +198,22 @@ export const compareAndSet: { * console.log(casUpdate(ref)) // true * ``` * - * @since 2.0.0 * @category general + * @since 2.0.0 */ (oldValue: T, newValue: T): (self: MutableRef) => boolean /** - * Atomically sets the value to newValue if the current value equals oldValue. + * Sets the value to newValue atomically if the current value equals oldValue. * Returns true if the value was updated, false otherwise. * Uses Effect's Equal interface for value comparison. * - * @example + * **When to use** + * + * Use to replace a `MutableRef` value only when the current value still matches + * an expected value. + * + * **Example** (Comparing and setting values) + * * ```ts * import { MutableRef } from "effect" * @@ -226,8 +241,8 @@ export const compareAndSet: { * console.log(casUpdate(ref)) // true * ``` * - * @since 2.0.0 * @category general + * @since 2.0.0 */ (self: MutableRef, oldValue: T, newValue: T): boolean } = Dual.dual< @@ -244,7 +259,13 @@ export const compareAndSet: { /** * Decrements a numeric MutableRef by 1 and returns the reference. * - * @example + * **When to use** + * + * Use when you need an in-place `MutableRef` decrement that returns the same + * `MutableRef`. + * + * **Example** (Decrementing numeric refs) + * * ```ts * import { MutableRef } from "effect" * @@ -267,15 +288,21 @@ export const compareAndSet: { * } * ``` * - * @since 2.0.0 * @category numeric + * @since 2.0.0 */ export const decrement = (self: MutableRef): MutableRef => update(self, (n) => n - 1) /** * Decrements a numeric MutableRef by 1 and returns the new value. * - * @example + * **When to use** + * + * Use to decrement a numeric `MutableRef` and immediately read the updated + * value. + * + * **Example** (Decrementing and reading refs) + * * ```ts * import { MutableRef } from "effect" * @@ -298,15 +325,20 @@ export const decrement = (self: MutableRef): MutableRef => updat * } * ``` * - * @since 2.0.0 * @category numeric + * @since 2.0.0 */ export const decrementAndGet = (self: MutableRef): number => updateAndGet(self, (n) => n - 1) /** * Gets the current value of the MutableRef. * - * @example + * **When to use** + * + * Use to read the current `MutableRef` value without mutating it. + * + * **Example** (Reading current values) + * * ```ts * import { MutableRef } from "effect" * @@ -327,15 +359,20 @@ export const decrementAndGet = (self: MutableRef): number => updateAndGe * console.log(value1 === value2) // true * ``` * - * @since 2.0.0 * @category general + * @since 2.0.0 */ export const get = (self: MutableRef): T => self.current /** * Decrements a numeric MutableRef by 1 and returns the previous value. * - * @example + * **When to use** + * + * Use to read the current numeric `MutableRef` value before decrementing it. + * + * **Example** (Reading before decrementing) + * * ```ts * import { MutableRef } from "effect" * @@ -359,15 +396,20 @@ export const get = (self: MutableRef): T => self.current * console.log(`Current: ${currentIndex}, Next: ${MutableRef.get(index)}`) // "Current: 3, Next: 2" * ``` * - * @since 2.0.0 * @category numeric + * @since 2.0.0 */ export const getAndDecrement = (self: MutableRef): number => getAndUpdate(self, (n) => n - 1) /** * Increments a numeric MutableRef by 1 and returns the previous value. * - * @example + * **When to use** + * + * Use to read the current numeric `MutableRef` value before incrementing it. + * + * **Example** (Reading before incrementing) + * * ```ts * import { MutableRef } from "effect" * @@ -399,15 +441,21 @@ export const getAndDecrement = (self: MutableRef): number => getAndUpdat * } * ``` * - * @since 2.0.0 * @category numeric + * @since 2.0.0 */ export const getAndIncrement = (self: MutableRef): number => getAndUpdate(self, (n) => n + 1) /** * Sets the MutableRef to a new value and returns the previous value. * - * @example + * **When to use** + * + * Use to replace the current `MutableRef` value while keeping the previous + * value. + * + * **Example** (Reading before setting) + * * ```ts * import { MutableRef } from "effect" * @@ -435,14 +483,20 @@ export const getAndIncrement = (self: MutableRef): number => getAndUpdat * console.log(MutableRef.get(buffer)) // [] * ``` * - * @since 2.0.0 * @category general + * @since 2.0.0 */ export const getAndSet: { /** * Sets the MutableRef to a new value and returns the previous value. * - * @example + * **When to use** + * + * Use to replace the current `MutableRef` value while keeping the previous + * value. + * + * **Example** (Reading before setting) + * * ```ts * import { MutableRef } from "effect" * @@ -470,14 +524,20 @@ export const getAndSet: { * console.log(MutableRef.get(buffer)) // [] * ``` * - * @since 2.0.0 * @category general + * @since 2.0.0 */ (value: T): (self: MutableRef) => T /** * Sets the MutableRef to a new value and returns the previous value. * - * @example + * **When to use** + * + * Use to replace the current `MutableRef` value while keeping the previous + * value. + * + * **Example** (Reading before setting) + * * ```ts * import { MutableRef } from "effect" * @@ -505,8 +565,8 @@ export const getAndSet: { * console.log(MutableRef.get(buffer)) // [] * ``` * - * @since 2.0.0 * @category general + * @since 2.0.0 */ (self: MutableRef, value: T): T } = Dual.dual< @@ -522,7 +582,13 @@ export const getAndSet: { * Updates the MutableRef with the result of applying a function to its current value, * and returns the previous value. * - * @example + * **When to use** + * + * Use to transform the current `MutableRef` value while keeping the previous + * value. + * + * **Example** (Reading before updating) + * * ```ts * import { MutableRef } from "effect" * @@ -556,15 +622,21 @@ export const getAndSet: { * console.log(MutableRef.get(list)) // [1, 2, 3, 4] * ``` * - * @since 2.0.0 * @category general + * @since 2.0.0 */ export const getAndUpdate: { /** * Updates the MutableRef with the result of applying a function to its current value, * and returns the previous value. * - * @example + * **When to use** + * + * Use to transform the current `MutableRef` value while keeping the previous + * value. + * + * **Example** (Reading before updating) + * * ```ts * import { MutableRef } from "effect" * @@ -598,15 +670,21 @@ export const getAndUpdate: { * console.log(MutableRef.get(list)) // [1, 2, 3, 4] * ``` * - * @since 2.0.0 * @category general + * @since 2.0.0 */ (f: (value: T) => T): (self: MutableRef) => T /** * Updates the MutableRef with the result of applying a function to its current value, * and returns the previous value. * - * @example + * **When to use** + * + * Use to transform the current `MutableRef` value while keeping the previous + * value. + * + * **Example** (Reading before updating) + * * ```ts * import { MutableRef } from "effect" * @@ -640,8 +718,8 @@ export const getAndUpdate: { * console.log(MutableRef.get(list)) // [1, 2, 3, 4] * ``` * - * @since 2.0.0 * @category general + * @since 2.0.0 */ (self: MutableRef, f: (value: T) => T): T } = Dual.dual< @@ -652,7 +730,13 @@ export const getAndUpdate: { /** * Increments a numeric MutableRef by 1 and returns the reference. * - * @example + * **When to use** + * + * Use when you need an in-place `MutableRef` increment that returns the same + * `MutableRef`. + * + * **Example** (Incrementing numeric refs) + * * ```ts * import { MutableRef } from "effect" * @@ -678,15 +762,21 @@ export const getAndUpdate: { * console.log(result === counter) // true * ``` * - * @since 2.0.0 * @category numeric + * @since 2.0.0 */ export const increment = (self: MutableRef): MutableRef => update(self, (n) => n + 1) /** * Increments a numeric MutableRef by 1 and returns the new value. * - * @example + * **When to use** + * + * Use to increment a numeric `MutableRef` and immediately read the updated + * value. + * + * **Example** (Incrementing and reading refs) + * * ```ts * import { MutableRef } from "effect" * @@ -713,15 +803,21 @@ export const increment = (self: MutableRef): MutableRef => updat * } * ``` * - * @since 2.0.0 * @category numeric + * @since 2.0.0 */ export const incrementAndGet = (self: MutableRef): number => updateAndGet(self, (n) => n + 1) /** * Sets the MutableRef to a new value and returns the reference. * - * @example + * **When to use** + * + * Use when you need an in-place `MutableRef` replacement that returns the same + * `MutableRef`. + * + * **Example** (Setting values) + * * ```ts * import { MutableRef } from "effect" * @@ -753,14 +849,20 @@ export const incrementAndGet = (self: MutableRef): number => updateAndGe * MutableRef.set(state, "success") * ``` * - * @since 2.0.0 * @category general + * @since 2.0.0 */ export const set: { /** * Sets the MutableRef to a new value and returns the reference. * - * @example + * **When to use** + * + * Use when you need an in-place `MutableRef` replacement that returns the same + * `MutableRef`. + * + * **Example** (Setting values) + * * ```ts * import { MutableRef } from "effect" * @@ -792,14 +894,20 @@ export const set: { * MutableRef.set(state, "success") * ``` * - * @since 2.0.0 * @category general + * @since 2.0.0 */ (value: T): (self: MutableRef) => MutableRef /** * Sets the MutableRef to a new value and returns the reference. * - * @example + * **When to use** + * + * Use when you need an in-place `MutableRef` replacement that returns the same + * `MutableRef`. + * + * **Example** (Setting values) + * * ```ts * import { MutableRef } from "effect" * @@ -831,8 +939,8 @@ export const set: { * MutableRef.set(state, "success") * ``` * - * @since 2.0.0 * @category general + * @since 2.0.0 */ (self: MutableRef, value: T): MutableRef } = Dual.dual< @@ -846,7 +954,13 @@ export const set: { /** * Sets the MutableRef to a new value and returns the new value. * - * @example + * **When to use** + * + * Use to replace the current `MutableRef` value and immediately read the + * replacement. + * + * **Example** (Setting and reading values) + * * ```ts * import { MutableRef } from "effect" * @@ -874,14 +988,20 @@ export const set: { * console.log(returnedValue) // 3 * ``` * - * @since 2.0.0 * @category general + * @since 2.0.0 */ export const setAndGet: { /** * Sets the MutableRef to a new value and returns the new value. * - * @example + * **When to use** + * + * Use to replace the current `MutableRef` value and immediately read the + * replacement. + * + * **Example** (Setting and reading values) + * * ```ts * import { MutableRef } from "effect" * @@ -909,14 +1029,20 @@ export const setAndGet: { * console.log(returnedValue) // 3 * ``` * - * @since 2.0.0 * @category general + * @since 2.0.0 */ (value: T): (self: MutableRef) => T /** * Sets the MutableRef to a new value and returns the new value. * - * @example + * **When to use** + * + * Use to replace the current `MutableRef` value and immediately read the + * replacement. + * + * **Example** (Setting and reading values) + * * ```ts * import { MutableRef } from "effect" * @@ -944,8 +1070,8 @@ export const setAndGet: { * console.log(returnedValue) // 3 * ``` * - * @since 2.0.0 * @category general + * @since 2.0.0 */ (self: MutableRef, value: T): T } = Dual.dual< @@ -960,7 +1086,13 @@ export const setAndGet: { * Updates the MutableRef with the result of applying a function to its current value, * and returns the reference. * - * @example + * **When to use** + * + * Use when you need an in-place `MutableRef` value transformation that returns + * the same `MutableRef`. + * + * **Example** (Updating values) + * * ```ts * import { MutableRef } from "effect" * @@ -996,15 +1128,21 @@ export const setAndGet: { * console.log(MutableRef.get(list)) // [1, 2, 3, 4] * ``` * - * @since 2.0.0 * @category general + * @since 2.0.0 */ export const update: { /** * Updates the MutableRef with the result of applying a function to its current value, * and returns the reference. * - * @example + * **When to use** + * + * Use when you need an in-place `MutableRef` value transformation that returns + * the same `MutableRef`. + * + * **Example** (Updating values) + * * ```ts * import { MutableRef } from "effect" * @@ -1040,15 +1178,21 @@ export const update: { * console.log(MutableRef.get(list)) // [1, 2, 3, 4] * ``` * - * @since 2.0.0 * @category general + * @since 2.0.0 */ (f: (value: T) => T): (self: MutableRef) => MutableRef /** * Updates the MutableRef with the result of applying a function to its current value, * and returns the reference. * - * @example + * **When to use** + * + * Use when you need an in-place `MutableRef` value transformation that returns + * the same `MutableRef`. + * + * **Example** (Updating values) + * * ```ts * import { MutableRef } from "effect" * @@ -1084,8 +1228,8 @@ export const update: { * console.log(MutableRef.get(list)) // [1, 2, 3, 4] * ``` * - * @since 2.0.0 * @category general + * @since 2.0.0 */ (self: MutableRef, f: (value: T) => T): MutableRef } = Dual.dual< @@ -1097,7 +1241,13 @@ export const update: { * Updates the MutableRef with the result of applying a function to its current value, * and returns the new value. * - * @example + * **When to use** + * + * Use to transform the current `MutableRef` value and immediately read the + * updated value. + * + * **Example** (Updating and reading values) + * * ```ts * import { MutableRef } from "effect" * @@ -1135,15 +1285,21 @@ export const update: { * console.log(MutableRef.get(list)) // [2, 4, 6] * ``` * - * @since 2.0.0 * @category general + * @since 2.0.0 */ export const updateAndGet: { /** * Updates the MutableRef with the result of applying a function to its current value, * and returns the new value. * - * @example + * **When to use** + * + * Use to transform the current `MutableRef` value and immediately read the + * updated value. + * + * **Example** (Updating and reading values) + * * ```ts * import { MutableRef } from "effect" * @@ -1181,15 +1337,21 @@ export const updateAndGet: { * console.log(MutableRef.get(list)) // [2, 4, 6] * ``` * - * @since 2.0.0 * @category general + * @since 2.0.0 */ (f: (value: T) => T): (self: MutableRef) => T /** * Updates the MutableRef with the result of applying a function to its current value, * and returns the new value. * - * @example + * **When to use** + * + * Use to transform the current `MutableRef` value and immediately read the + * updated value. + * + * **Example** (Updating and reading values) + * * ```ts * import { MutableRef } from "effect" * @@ -1227,8 +1389,8 @@ export const updateAndGet: { * console.log(MutableRef.get(list)) // [2, 4, 6] * ``` * - * @since 2.0.0 * @category general + * @since 2.0.0 */ (self: MutableRef, f: (value: T) => T): T } = Dual.dual< @@ -1237,9 +1399,16 @@ export const updateAndGet: { >(2, (self, f) => setAndGet(self, f(get(self)))) /** - * Toggles a boolean MutableRef (true becomes false, false becomes true) and returns the reference. + * Switches a boolean `MutableRef` between `true` and `false`, then returns the + * reference. + * + * **When to use** + * + * Use when you need an in-place boolean `MutableRef` toggle that returns the + * same `MutableRef`. + * + * **Example** (Toggling boolean refs) * - * @example * ```ts * import { MutableRef } from "effect" * @@ -1273,7 +1442,7 @@ export const updateAndGet: { * console.log(result === flag) // true * ``` * - * @since 2.0.0 * @category boolean + * @since 2.0.0 */ export const toggle = (self: MutableRef): MutableRef => update(self, (_) => !_) diff --git a/.opencode/node_modules/effect/src/Newtype.ts b/.opencode/node_modules/effect/src/Newtype.ts index 596e7a12f999beaf5f1212389b4e570a6de91de9..ea64786d9626fcd2db97c1c665d7c43d5b5b90c0 100644 --- a/.opencode/node_modules/effect/src/Newtype.ts +++ b/.opencode/node_modules/effect/src/Newtype.ts @@ -1,65 +1,12 @@ /** - * Lightweight wrapper types that prevent accidental mixing of structurally - * identical values (e.g. `UserId` vs `OrderId`, both `string` at runtime). - * - * **Mental model** - * - * - **Newtype** — a compile-time wrapper around a **carrier** type (the - * underlying primitive or object). At runtime the value is unchanged; the - * tag exists only in the type system. - * - **Key** — a unique string literal that distinguishes one newtype from - * another (e.g. `"Label"`, `"UserId"`). - * - **Carrier** — the underlying type the newtype wraps (e.g. `string`, - * `number`). - * - **Iso** — a lossless two-way conversion between a newtype and its carrier, - * created with {@link makeIso}. Use `iso.set(carrier)` to wrap and - * `iso.get(newtype)` to unwrap. - * - * **Common tasks** - * - * - Define a newtype → declare an `interface` extending - * `Newtype.Newtype` - * - Wrap / unwrap values → {@link makeIso} (returns an `Optic.Iso`) - * - Unwrap only → {@link value} - * - Lift an `Equivalence` → {@link makeEquivalence} - * - Lift an `Order` → {@link makeOrder} - * - Lift a `Combiner` → {@link makeCombiner} - * - Lift a `Reducer` → {@link makeReducer} - * - * **Gotchas** - * - * - Newtypes are **purely compile-time**. There is zero runtime overhead; - * `value` and `makeIso` use identity casts. - * - Two newtypes sharing the same key string will be assignable to each other. - * Choose unique key strings. - * - A newtype value is **not** assignable to its carrier type without - * explicitly unwrapping via {@link value} or an iso. - * - * **Quickstart** - * - * **Example** (defining and using a newtype) + * Creates compile-time-only wrappers around existing value types. * - * ```ts - * import { Newtype } from "effect" - * - * // 1. Define a newtype - * interface Label extends Newtype.Newtype<"Label", string> {} - * - * // 2. Create an iso for wrapping/unwrapping - * const labelIso = Newtype.makeIso(data: NonEmptyIterable.NonEmptyIterable): A { - * // Safe to get the first element - guaranteed to exist - * const [first] = NonEmptyIterable.unprepend(data) - * return first - * } - * - * // Using Array.make to create non-empty arrays - * const numbers = Array.make( - * 1, - * 2, - * 3, - * 4, - * 5 - * ) as unknown as NonEmptyIterable.NonEmptyIterable - * const firstNumber = processNonEmpty(numbers) // number - * - * // Regular arrays can be asserted as NonEmptyIterable when known to be non-empty - * const values = [1, 2, 3] as unknown as NonEmptyIterable.NonEmptyIterable - * const firstValue = processNonEmpty(values) // number - * - * // Custom iterables that are guaranteed non-empty - * function* generateNumbers(): NonEmptyIterable.NonEmptyIterable { - * yield 1 - * yield 2 - * yield 3 - * } - * - * const firstGenerated = processNonEmpty(generateNumbers()) // number - * ``` - * - * ## Working with Different Iterable Types - * - * ```ts - * import { Array } from "effect" - * - * // Creating non-empty arrays - * const nonEmptyArray = Array.make( - * 1, - * 2, - * 3 - * ) as unknown as NonEmptyIterable.NonEmptyIterable + * The `NonEmptyIterable` module provides a type-level representation of any + * JavaScript `Iterable` that is known to contain at least one element. A + * `NonEmptyIterable` can be consumed anywhere an `Iterable` is expected, + * while also carrying the guarantee that reading the first element is safe. * - * // Working with strings (assert as NonEmptyIterable when known to be non-empty) - * const nonEmptyString = "hello" as unknown as NonEmptyIterable.NonEmptyIterable< - * string - * > - * const [firstChar] = NonEmptyIterable.unprepend(nonEmptyString) - * console.log(firstChar) // "h" - * - * // Working with Maps (assert when known to be non-empty) - * const nonEmptyMap = new Map([ - * ["key1", "value1"], - * ["key2", "value2"] - * ]) as unknown as NonEmptyIterable.NonEmptyIterable<[string, string]> - * const [firstEntry] = NonEmptyIterable.unprepend(nonEmptyMap) - * console.log(firstEntry) // ["key1", "value1"] - * - * // Custom generator functions - * function* fibonacci(): NonEmptyIterable.NonEmptyIterable { - * let a = 1, b = 1 - * yield a - * while (true) { - * yield b - * const next = a + b - * a = b - * b = next - * } - * } - * - * const [firstFib, restFib] = NonEmptyIterable.unprepend( - * fibonacci() as unknown as NonEmptyIterable.NonEmptyIterable - * ) - * console.log(firstFib) // 1 - * ``` - * - * ## Integration with Effect Arrays - * - * ```ts - * import { Array, pipe } from "effect" - * import type * as NonEmptyIterable from "effect/NonEmptyIterable" - * import type * as NonEmptyIterable from "effect/NonEmptyIterable" - * - * // Many Array functions work with NonEmptyIterable - * declare const nonEmptyData: NonEmptyIterable.NonEmptyIterable - * - * const processData = pipe( - * nonEmptyData, - * Array.fromIterable, - * Array.map((x) => x * 2), - * Array.filter((x) => x > 5) - * // Result is a regular array since filtering might make it empty - * ) - * - * // Safe operations that preserve non-emptiness - * const doubledData = pipe( - * nonEmptyData, - * Array.fromIterable, - * Array.map((x) => x * 2) - * // This would still be non-empty if the source was non-empty - * ) - * ``` + * @since 2.0.0 */ /** - * A unique symbol used to brand the `NonEmptyIterable` type. + * Defines the type-level symbol used to brand the `NonEmptyIterable` type. * - * This symbol ensures that `NonEmptyIterable` is a distinct type from regular - * `Iterable`, providing compile-time guarantees about non-emptiness while - * maintaining full compatibility with the JavaScript iteration protocol. + * **When to use** * - * @example - * ```ts - * import type * as NonEmptyIterable from "effect/NonEmptyIterable" + * Use as the property key for the type-level brand that marks an `Iterable` as + * non-empty. * - * // The symbol is used internally for type branding - * declare const data: NonEmptyIterable.NonEmptyIterable + * **Details** * - * // This has the nonEmpty symbol property (not accessible at runtime) - * // but is still a regular Iterable for all practical purposes - * for (const item of data) { - * console.log(item) // Works normally - * } + * `NonEmptyIterable` includes `readonly [nonEmpty]: A`, which makes it + * distinct from a plain `Iterable` at compile time while preserving the + * normal iteration shape. * - * // Can be used with any function expecting an Iterable - * const array = Array.from(data) - * const set = new Set(data) - * ``` + * @see {@link NonEmptyIterable} for the branded iterable type that uses this symbol * - * @category symbol + * @category symbols * @since 2.0.0 */ export declare const nonEmpty: unique symbol @@ -162,6 +31,12 @@ export declare const nonEmpty: unique symbol /** * Represents an iterable that is guaranteed to contain at least one element. * + * **When to use** + * + * Use to require an iterable input that must provide at least one element. + * + * **Details** + * * `NonEmptyIterable` extends the standard `Iterable` interface with a type-level * guarantee of non-emptiness. This allows for safe operations that would otherwise * require runtime checks or could throw exceptions. @@ -169,11 +44,10 @@ export declare const nonEmpty: unique symbol * The type is branded with a unique symbol to ensure type safety while maintaining * full compatibility with JavaScript's iteration protocol. * - * @example + * **Example** (Working with non-empty iterables) + * * ```ts - * import { Array } from "effect" - * import * as Chunk from "effect/Chunk" - * import * as NonEmptyIterable from "effect/NonEmptyIterable" + * import { Array, Chunk, NonEmptyIterable } from "effect" * * // Function that requires non-empty data * function getFirst(data: NonEmptyIterable.NonEmptyIterable): A { @@ -212,7 +86,7 @@ export declare const nonEmpty: unique symbol * ) // 3 * ``` * - * @category model + * @category models * @since 2.0.0 */ export interface NonEmptyIterable extends Iterable { @@ -220,20 +94,23 @@ export interface NonEmptyIterable extends Iterable { } /** - * Safely extracts the first element and remaining elements from a non-empty iterable. + * Extracts the first element and remaining elements from a non-empty iterable safely. + * + * **When to use** + * + * Use to split a non-empty iterable into its first element and an iterator for + * the remaining elements. + * + * **Details** * * This function provides a safe way to deconstruct a `NonEmptyIterable` into its * head (first element) and tail (remaining elements as an iterator). Since the * iterable is guaranteed to be non-empty, the first element is always available. * - * @param self - The non-empty iterable to deconstruct - * @returns A tuple containing the first element and an iterator for the remaining elements + * **Example** (Extracting first and remaining elements) * - * @example * ```ts - * import { Array } from "effect" - * import * as Chunk from "effect/Chunk" - * import * as NonEmptyIterable from "effect/NonEmptyIterable" + * import { Array, Chunk, NonEmptyIterable } from "effect" * * // Helper to make iterator iterable for Array.from * const iteratorToIterable = (iterator: Iterator): Iterable => ({ diff --git a/.opencode/node_modules/effect/src/Number.ts b/.opencode/node_modules/effect/src/Number.ts index 0a9f0b4999567c4f402e5272aa316479db96f60c..f3054077aad74dabc78f7cfc0ff318c5ead2a733 100644 --- a/.opencode/node_modules/effect/src/Number.ts +++ b/.opencode/node_modules/effect/src/Number.ts @@ -1,6 +1,9 @@ /** - * This module provides utility functions and type class instances for working with the `number` type in TypeScript. - * It includes functions for basic arithmetic operations. + * Works with TypeScript `number` values. + * + * This module exposes the native `Number` constructor together with helpers for + * checking, parsing, arithmetic, safe division, comparison, range checks, + * clamping, rounding, ordering, equivalence, and numeric aggregation. * * @since 2.0.0 */ @@ -13,11 +16,24 @@ import * as predicate from "./Predicate.ts" import * as Reducer from "./Reducer.ts" /** - * The global `Number` constructor. + * Exposes the global number constructor. + * + * **When to use** + * + * Use to access native JavaScript numeric coercion from the Effect module + * namespace. + * + * **Gotchas** + * + * This follows native `Number` coercion rules, including empty strings + * becoming `0` and invalid numeric strings becoming `NaN`. + * + * @see {@link parse} for parsing strings into an `Option` + * + * **Example** (Coercing values to numbers) * - * @example * ```ts - * import * as N from "effect/Number" + * import { Number as N } from "effect" * * const num = N.Number("42") * console.log(num) // 42 @@ -32,15 +48,20 @@ import * as Reducer from "./Reducer.ts" export const Number = globalThis.Number /** - * Tests if a value is a `number`. + * Checks whether a value is a `number`. + * + * **When to use** + * + * Use to validate unknown input and narrow it to `number`. + * + * **Example** (Checking for numbers) * - * @example * ```ts - * import { isNumber } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(isNumber(2), true) - * assert.deepStrictEqual(isNumber("2"), false) + * assert.deepStrictEqual(Number.isNumber(2), true) + * assert.deepStrictEqual(Number.isNumber("2"), false) * ``` * * @category guards @@ -51,14 +72,21 @@ export const isNumber: (input: unknown) => input is number = predicate.isNumber /** * Provides an addition operation on `number`s. * - * @example + * **When to use** + * + * Use to add two numbers. + * + * **Example** (Adding numbers) + * * ```ts - * import { sum } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(sum(2, 3), 5) + * assert.deepStrictEqual(Number.sum(2, 3), 5) * ``` * + * @see {@link sumAll} for summing an iterable of numbers + * * @category math * @since 2.0.0 */ @@ -66,14 +94,21 @@ export const sum: { /** * Provides an addition operation on `number`s. * - * @example + * **When to use** + * + * Use to add two numbers. + * + * **Example** (Adding numbers) + * * ```ts - * import { sum } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(sum(2, 3), 5) + * assert.deepStrictEqual(Number.sum(2, 3), 5) * ``` * + * @see {@link sumAll} for summing an iterable of numbers + * * @category math * @since 2.0.0 */ @@ -81,14 +116,21 @@ export const sum: { /** * Provides an addition operation on `number`s. * - * @example + * **When to use** + * + * Use to add two numbers. + * + * **Example** (Adding numbers) + * * ```ts - * import { sum } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(sum(2, 3), 5) + * assert.deepStrictEqual(Number.sum(2, 3), 5) * ``` * + * @see {@link sumAll} for summing an iterable of numbers + * * @category math * @since 2.0.0 */ @@ -98,14 +140,21 @@ export const sum: { /** * Provides a multiplication operation on `number`s. * - * @example + * **When to use** + * + * Use to multiply two numbers. + * + * **Example** (Multiplying numbers) + * * ```ts - * import { multiply } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(multiply(2, 3), 6) + * assert.deepStrictEqual(Number.multiply(2, 3), 6) * ``` * + * @see {@link multiplyAll} for multiplying an iterable of numbers + * * @category math * @since 2.0.0 */ @@ -113,14 +162,21 @@ export const multiply: { /** * Provides a multiplication operation on `number`s. * - * @example + * **When to use** + * + * Use to multiply two numbers. + * + * **Example** (Multiplying numbers) + * * ```ts - * import { multiply } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(multiply(2, 3), 6) + * assert.deepStrictEqual(Number.multiply(2, 3), 6) * ``` * + * @see {@link multiplyAll} for multiplying an iterable of numbers + * * @category math * @since 2.0.0 */ @@ -128,14 +184,21 @@ export const multiply: { /** * Provides a multiplication operation on `number`s. * - * @example + * **When to use** + * + * Use to multiply two numbers. + * + * **Example** (Multiplying numbers) + * * ```ts - * import { multiply } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(multiply(2, 3), 6) + * assert.deepStrictEqual(Number.multiply(2, 3), 6) * ``` * + * @see {@link multiplyAll} for multiplying an iterable of numbers + * * @category math * @since 2.0.0 */ @@ -145,12 +208,17 @@ export const multiply: { /** * Provides a subtraction operation on `number`s. * - * @example + * **When to use** + * + * Use to subtract one number from another. + * + * **Example** (Subtracting numbers) + * * ```ts - * import { subtract } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(subtract(2, 3), -1) + * assert.deepStrictEqual(Number.subtract(2, 3), -1) * ``` * * @category math @@ -160,12 +228,17 @@ export const subtract: { /** * Provides a subtraction operation on `number`s. * - * @example + * **When to use** + * + * Use to subtract one number from another. + * + * **Example** (Subtracting numbers) + * * ```ts - * import { subtract } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(subtract(2, 3), -1) + * assert.deepStrictEqual(Number.subtract(2, 3), -1) * ``` * * @category math @@ -175,12 +248,17 @@ export const subtract: { /** * Provides a subtraction operation on `number`s. * - * @example + * **When to use** + * + * Use to subtract one number from another. + * + * **Example** (Subtracting numbers) + * * ```ts - * import { subtract } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(subtract(2, 3), -1) + * assert.deepStrictEqual(Number.subtract(2, 3), -1) * ``` * * @category math @@ -190,11 +268,13 @@ export const subtract: { } = dual(2, (self: number, that: number): number => self - that) /** - * Provides a division operation on `number`s. + * Divides `number`s safely, returning `Option.none()` if the divisor is `0`. + * + * **When to use** * - * Returns `Option.none()` if the divisor is `0`. + * Use to divide numbers while representing division by zero as `Option.none`. * - * **Example** + * **Example** (Dividing numbers safely) * * ```ts * import { Number } from "effect" @@ -203,16 +283,21 @@ export const subtract: { * Number.divide(6, 0) // Option.none() * ``` * + * @see {@link divideUnsafe} for division that throws when the divisor is zero + * @see {@link remainder} for the numeric remainder operation + * * @category math * @since 2.0.0 */ export const divide: { /** - * Provides a division operation on `number`s. + * Divides `number`s safely, returning `Option.none()` if the divisor is `0`. + * + * **When to use** * - * Returns `Option.none()` if the divisor is `0`. + * Use to divide numbers while representing division by zero as `Option.none`. * - * **Example** + * **Example** (Dividing numbers safely) * * ```ts * import { Number } from "effect" @@ -221,16 +306,21 @@ export const divide: { * Number.divide(6, 0) // Option.none() * ``` * + * @see {@link divideUnsafe} for division that throws when the divisor is zero + * @see {@link remainder} for the numeric remainder operation + * * @category math * @since 2.0.0 */ (that: number): (self: number) => Option.Option /** - * Provides a division operation on `number`s. + * Divides `number`s safely, returning `Option.none()` if the divisor is `0`. + * + * **When to use** * - * Returns `Option.none()` if the divisor is `0`. + * Use to divide numbers while representing division by zero as `Option.none`. * - * **Example** + * **Example** (Dividing numbers safely) * * ```ts * import { Number } from "effect" @@ -239,6 +329,9 @@ export const divide: { * Number.divide(6, 0) // Option.none() * ``` * + * @see {@link divideUnsafe} for division that throws when the divisor is zero + * @see {@link remainder} for the numeric remainder operation + * * @category math * @since 2.0.0 */ @@ -249,57 +342,87 @@ export const divide: { ) /** - * Provides an unsafe division operation on `number`s. + * Divides two `number` values without returning an `Option`. + * + * **When to use** + * + * Use to divide `number` values where the divisor is known to be non-zero and + * a plain `number` result is preferred over handling `Option.none`. + * + * **Gotchas** * * Throws a `RangeError` if the divisor is `0`. * - * **Example** + * **Example** (Dividing numbers unsafely) * * ```ts * import { Number } from "effect" * - * Number.divideUnsafe(6, 3) // 2 - * Number.divideUnsafe(6, 0) // throws RangeError("Division by zero") + * console.log(Number.divideUnsafe(6, 3)) // 2 + * + * // Passing 0 as the divisor throws a RangeError("Division by zero"). * ``` * + * @see {@link divide} for division that returns `Option.none` when the divisor is zero + * * @category math - * @since 2.0.0 + * @since 4.0.0 */ export const divideUnsafe: { /** - * Provides an unsafe division operation on `number`s. + * Divides two `number` values without returning an `Option`. + * + * **When to use** + * + * Use to divide `number` values where the divisor is known to be non-zero and + * a plain `number` result is preferred over handling `Option.none`. + * + * **Gotchas** * * Throws a `RangeError` if the divisor is `0`. * - * **Example** + * **Example** (Dividing numbers unsafely) * * ```ts * import { Number } from "effect" * - * Number.divideUnsafe(6, 3) // 2 - * Number.divideUnsafe(6, 0) // throws RangeError("Division by zero") + * console.log(Number.divideUnsafe(6, 3)) // 2 + * + * // Passing 0 as the divisor throws a RangeError("Division by zero"). * ``` * + * @see {@link divide} for division that returns `Option.none` when the divisor is zero + * * @category math - * @since 2.0.0 + * @since 4.0.0 */ (that: number): (self: number) => number /** - * Provides an unsafe division operation on `number`s. + * Divides two `number` values without returning an `Option`. + * + * **When to use** + * + * Use to divide `number` values where the divisor is known to be non-zero and + * a plain `number` result is preferred over handling `Option.none`. + * + * **Gotchas** * * Throws a `RangeError` if the divisor is `0`. * - * **Example** + * **Example** (Dividing numbers unsafely) * * ```ts * import { Number } from "effect" * - * Number.divideUnsafe(6, 3) // 2 - * Number.divideUnsafe(6, 0) // throws RangeError("Division by zero") + * console.log(Number.divideUnsafe(6, 3)) // 2 + * + * // Passing 0 as the divisor throws a RangeError("Division by zero"). * ``` * + * @see {@link divide} for division that returns `Option.none` when the divisor is zero + * * @category math - * @since 2.0.0 + * @since 4.0.0 */ (self: number, that: number): number } = dual( @@ -311,12 +434,17 @@ export const divideUnsafe: { /** * Returns the result of adding `1` to a given number. * - * @example + * **When to use** + * + * Use to increment a numeric counter by one. + * + * **Example** (Incrementing a number) + * * ```ts - * import { increment } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(increment(2), 3) + * assert.deepStrictEqual(Number.increment(2), 3) * ``` * * @category math @@ -327,12 +455,17 @@ export const increment = (n: number): number => n + 1 /** * Decrements a number by `1`. * - * @example + * **When to use** + * + * Use to decrement a numeric counter by one. + * + * **Example** (Decrementing a number) + * * ```ts - * import { decrement } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(decrement(3), 2) + * assert.deepStrictEqual(Number.decrement(3), 2) * ``` * * @category math @@ -341,11 +474,17 @@ export const increment = (n: number): number => n + 1 export const decrement = (n: number): number => n - 1 /** - * An `Order` instance for `number` values. + * Order instance for `number` values. + * + * **When to use** + * + * Use when you need to sort or compare numbers through APIs that accept an + * ordering instance. + * + * **Example** (Comparing numbers) * - * @example * ```ts - * import * as Number from "effect/Number" + * import { Number } from "effect" * * console.log(Number.Order(1, 2)) // -1 * console.log(Number.Order(2, 1)) // 1 @@ -358,11 +497,15 @@ export const decrement = (n: number): number => n - 1 export const Order: order.Order = order.Number /** - * An `Equivalence` instance for numbers. + * Equivalence instance for numbers where `NaN` is considered equal to `NaN`. + * + * **When to use** * - * `NaN` is considered equal to `NaN`. + * Use when checking numeric equality through APIs that accept an equivalence + * relation. + * + * **Example** (Comparing numbers for equivalence) * - * @example * ```ts * import { Number } from "effect" * @@ -372,59 +515,74 @@ export const Order: order.Order = order.Number * ``` * * @category instances - * @since 4.0.0 + * @since 2.0.0 */ export const Equivalence: Equ.Equivalence = Equ.Number /** * Returns `true` if the first argument is less than the second, otherwise `false`. * - * @example + * **When to use** + * + * Use to test whether one number is strictly less than another. + * + * **Example** (Checking less-than comparisons) + * * ```ts - * import { isLessThan } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(isLessThan(2, 3), true) - * assert.deepStrictEqual(isLessThan(3, 3), false) - * assert.deepStrictEqual(isLessThan(4, 3), false) + * assert.deepStrictEqual(Number.isLessThan(2, 3), true) + * assert.deepStrictEqual(Number.isLessThan(3, 3), false) + * assert.deepStrictEqual(Number.isLessThan(4, 3), false) * ``` * * @category predicates - * @since 2.0.0 + * @since 4.0.0 */ export const isLessThan: { /** * Returns `true` if the first argument is less than the second, otherwise `false`. * - * @example + * **When to use** + * + * Use to test whether one number is strictly less than another. + * + * **Example** (Checking less-than comparisons) + * * ```ts - * import { isLessThan } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(isLessThan(2, 3), true) - * assert.deepStrictEqual(isLessThan(3, 3), false) - * assert.deepStrictEqual(isLessThan(4, 3), false) + * assert.deepStrictEqual(Number.isLessThan(2, 3), true) + * assert.deepStrictEqual(Number.isLessThan(3, 3), false) + * assert.deepStrictEqual(Number.isLessThan(4, 3), false) * ``` * * @category predicates - * @since 2.0.0 + * @since 4.0.0 */ (that: number): (self: number) => boolean /** * Returns `true` if the first argument is less than the second, otherwise `false`. * - * @example + * **When to use** + * + * Use to test whether one number is strictly less than another. + * + * **Example** (Checking less-than comparisons) + * * ```ts - * import { isLessThan } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(isLessThan(2, 3), true) - * assert.deepStrictEqual(isLessThan(3, 3), false) - * assert.deepStrictEqual(isLessThan(4, 3), false) + * assert.deepStrictEqual(Number.isLessThan(2, 3), true) + * assert.deepStrictEqual(Number.isLessThan(3, 3), false) + * assert.deepStrictEqual(Number.isLessThan(4, 3), false) * ``` * * @category predicates - * @since 2.0.0 + * @since 4.0.0 */ (self: number, that: number): boolean } = order.isLessThan(Order) @@ -432,52 +590,67 @@ export const isLessThan: { /** * Returns a function that checks if a given `number` is less than or equal to the provided one. * - * @example + * **When to use** + * + * Use to test whether one number is less than or equal to another. + * + * **Example** (Checking less-than-or-equal comparisons) + * * ```ts - * import { isLessThanOrEqualTo } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(isLessThanOrEqualTo(2, 3), true) - * assert.deepStrictEqual(isLessThanOrEqualTo(3, 3), true) - * assert.deepStrictEqual(isLessThanOrEqualTo(4, 3), false) + * assert.deepStrictEqual(Number.isLessThanOrEqualTo(2, 3), true) + * assert.deepStrictEqual(Number.isLessThanOrEqualTo(3, 3), true) + * assert.deepStrictEqual(Number.isLessThanOrEqualTo(4, 3), false) * ``` * * @category predicates - * @since 2.0.0 + * @since 4.0.0 */ export const isLessThanOrEqualTo: { /** * Returns a function that checks if a given `number` is less than or equal to the provided one. * - * @example + * **When to use** + * + * Use to test whether one number is less than or equal to another. + * + * **Example** (Checking less-than-or-equal comparisons) + * * ```ts - * import { isLessThanOrEqualTo } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(isLessThanOrEqualTo(2, 3), true) - * assert.deepStrictEqual(isLessThanOrEqualTo(3, 3), true) - * assert.deepStrictEqual(isLessThanOrEqualTo(4, 3), false) + * assert.deepStrictEqual(Number.isLessThanOrEqualTo(2, 3), true) + * assert.deepStrictEqual(Number.isLessThanOrEqualTo(3, 3), true) + * assert.deepStrictEqual(Number.isLessThanOrEqualTo(4, 3), false) * ``` * * @category predicates - * @since 2.0.0 + * @since 4.0.0 */ (that: number): (self: number) => boolean /** * Returns a function that checks if a given `number` is less than or equal to the provided one. * - * @example + * **When to use** + * + * Use to test whether one number is less than or equal to another. + * + * **Example** (Checking less-than-or-equal comparisons) + * * ```ts - * import { isLessThanOrEqualTo } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(isLessThanOrEqualTo(2, 3), true) - * assert.deepStrictEqual(isLessThanOrEqualTo(3, 3), true) - * assert.deepStrictEqual(isLessThanOrEqualTo(4, 3), false) + * assert.deepStrictEqual(Number.isLessThanOrEqualTo(2, 3), true) + * assert.deepStrictEqual(Number.isLessThanOrEqualTo(3, 3), true) + * assert.deepStrictEqual(Number.isLessThanOrEqualTo(4, 3), false) * ``` * * @category predicates - * @since 2.0.0 + * @since 4.0.0 */ (self: number, that: number): boolean } = order.isLessThanOrEqualTo(Order) @@ -485,52 +658,67 @@ export const isLessThanOrEqualTo: { /** * Returns `true` if the first argument is greater than the second, otherwise `false`. * - * @example + * **When to use** + * + * Use to test whether one number is strictly greater than another. + * + * **Example** (Checking greater-than comparisons) + * * ```ts - * import { isGreaterThan } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(isGreaterThan(2, 3), false) - * assert.deepStrictEqual(isGreaterThan(3, 3), false) - * assert.deepStrictEqual(isGreaterThan(4, 3), true) + * assert.deepStrictEqual(Number.isGreaterThan(2, 3), false) + * assert.deepStrictEqual(Number.isGreaterThan(3, 3), false) + * assert.deepStrictEqual(Number.isGreaterThan(4, 3), true) * ``` * * @category predicates - * @since 2.0.0 + * @since 4.0.0 */ export const isGreaterThan: { /** * Returns `true` if the first argument is greater than the second, otherwise `false`. * - * @example + * **When to use** + * + * Use to test whether one number is strictly greater than another. + * + * **Example** (Checking greater-than comparisons) + * * ```ts - * import { isGreaterThan } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(isGreaterThan(2, 3), false) - * assert.deepStrictEqual(isGreaterThan(3, 3), false) - * assert.deepStrictEqual(isGreaterThan(4, 3), true) + * assert.deepStrictEqual(Number.isGreaterThan(2, 3), false) + * assert.deepStrictEqual(Number.isGreaterThan(3, 3), false) + * assert.deepStrictEqual(Number.isGreaterThan(4, 3), true) * ``` * * @category predicates - * @since 2.0.0 + * @since 4.0.0 */ (that: number): (self: number) => boolean /** * Returns `true` if the first argument is greater than the second, otherwise `false`. * - * @example + * **When to use** + * + * Use to test whether one number is strictly greater than another. + * + * **Example** (Checking greater-than comparisons) + * * ```ts - * import { isGreaterThan } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(isGreaterThan(2, 3), false) - * assert.deepStrictEqual(isGreaterThan(3, 3), false) - * assert.deepStrictEqual(isGreaterThan(4, 3), true) + * assert.deepStrictEqual(Number.isGreaterThan(2, 3), false) + * assert.deepStrictEqual(Number.isGreaterThan(3, 3), false) + * assert.deepStrictEqual(Number.isGreaterThan(4, 3), true) * ``` * * @category predicates - * @since 2.0.0 + * @since 4.0.0 */ (self: number, that: number): boolean } = order.isGreaterThan(Order) @@ -538,62 +726,82 @@ export const isGreaterThan: { /** * Returns a function that checks if a given `number` is greater than or equal to the provided one. * - * @example + * **When to use** + * + * Use to test whether one number is greater than or equal to another. + * + * **Example** (Checking greater-than-or-equal comparisons) + * * ```ts - * import { isGreaterThanOrEqualTo } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(isGreaterThanOrEqualTo(2, 3), false) - * assert.deepStrictEqual(isGreaterThanOrEqualTo(3, 3), true) - * assert.deepStrictEqual(isGreaterThanOrEqualTo(4, 3), true) + * assert.deepStrictEqual(Number.isGreaterThanOrEqualTo(2, 3), false) + * assert.deepStrictEqual(Number.isGreaterThanOrEqualTo(3, 3), true) + * assert.deepStrictEqual(Number.isGreaterThanOrEqualTo(4, 3), true) * ``` * * @category predicates - * @since 2.0.0 + * @since 4.0.0 */ export const isGreaterThanOrEqualTo: { /** * Returns a function that checks if a given `number` is greater than or equal to the provided one. * - * @example + * **When to use** + * + * Use to test whether one number is greater than or equal to another. + * + * **Example** (Checking greater-than-or-equal comparisons) + * * ```ts - * import { isGreaterThanOrEqualTo } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(isGreaterThanOrEqualTo(2, 3), false) - * assert.deepStrictEqual(isGreaterThanOrEqualTo(3, 3), true) - * assert.deepStrictEqual(isGreaterThanOrEqualTo(4, 3), true) + * assert.deepStrictEqual(Number.isGreaterThanOrEqualTo(2, 3), false) + * assert.deepStrictEqual(Number.isGreaterThanOrEqualTo(3, 3), true) + * assert.deepStrictEqual(Number.isGreaterThanOrEqualTo(4, 3), true) * ``` * * @category predicates - * @since 2.0.0 + * @since 4.0.0 */ (that: number): (self: number) => boolean /** * Returns a function that checks if a given `number` is greater than or equal to the provided one. * - * @example + * **When to use** + * + * Use to test whether one number is greater than or equal to another. + * + * **Example** (Checking greater-than-or-equal comparisons) + * * ```ts - * import { isGreaterThanOrEqualTo } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(isGreaterThanOrEqualTo(2, 3), false) - * assert.deepStrictEqual(isGreaterThanOrEqualTo(3, 3), true) - * assert.deepStrictEqual(isGreaterThanOrEqualTo(4, 3), true) + * assert.deepStrictEqual(Number.isGreaterThanOrEqualTo(2, 3), false) + * assert.deepStrictEqual(Number.isGreaterThanOrEqualTo(3, 3), true) + * assert.deepStrictEqual(Number.isGreaterThanOrEqualTo(4, 3), true) * ``` * * @category predicates - * @since 2.0.0 + * @since 4.0.0 */ (self: number, that: number): boolean } = order.isGreaterThanOrEqualTo(Order) /** - * Checks if a `number` is between a `minimum` and `maximum` value (inclusive). + * Checks whether a `number` is between a `minimum` and `maximum` value (inclusive). + * + * **When to use** + * + * Use to test whether a number falls inside an inclusive range. + * + * **Example** (Checking inclusive ranges) * - * @example * ```ts - * import * as Number from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * * const between = Number.between({ minimum: 0, maximum: 5 }) @@ -603,16 +811,23 @@ export const isGreaterThanOrEqualTo: { * assert.deepStrictEqual(between(6), false) * ``` * + * @see {@link clamp} for forcing a number into an inclusive range + * * @category predicates * @since 2.0.0 */ export const between: { /** - * Checks if a `number` is between a `minimum` and `maximum` value (inclusive). + * Checks whether a `number` is between a `minimum` and `maximum` value (inclusive). + * + * **When to use** + * + * Use to test whether a number falls inside an inclusive range. + * + * **Example** (Checking inclusive ranges) * - * @example * ```ts - * import * as Number from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * * const between = Number.between({ minimum: 0, maximum: 5 }) @@ -622,6 +837,8 @@ export const between: { * assert.deepStrictEqual(between(6), false) * ``` * + * @see {@link clamp} for forcing a number into an inclusive range + * * @category predicates * @since 2.0.0 */ @@ -632,11 +849,16 @@ export const between: { } ): (self: number) => boolean /** - * Checks if a `number` is between a `minimum` and `maximum` value (inclusive). + * Checks whether a `number` is between a `minimum` and `maximum` value (inclusive). + * + * **When to use** + * + * Use to test whether a number falls inside an inclusive range. + * + * **Example** (Checking inclusive ranges) * - * @example * ```ts - * import * as Number from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * * const between = Number.between({ minimum: 0, maximum: 5 }) @@ -646,6 +868,8 @@ export const between: { * assert.deepStrictEqual(between(6), false) * ``` * + * @see {@link clamp} for forcing a number into an inclusive range + * * @category predicates * @since 2.0.0 */ @@ -661,13 +885,20 @@ export const between: { /** * Restricts the given `number` to be within the range specified by the `minimum` and `maximum` values. * + * **When to use** + * + * Use to force a number into an inclusive range. + * + * **Details** + * * - If the `number` is less than the `minimum` value, the function returns the `minimum` value. * - If the `number` is greater than the `maximum` value, the function returns the `maximum` value. * - Otherwise, it returns the original `number`. * - * @example + * **Example** (Clamping to a range) + * * ```ts - * import * as Number from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * * const clamp = Number.clamp({ minimum: 1, maximum: 5 }) @@ -677,6 +908,8 @@ export const between: { * assert.equal(clamp(6), 5) * ``` * + * @see {@link between} for checking whether a number is already inside a range + * * @category math * @since 2.0.0 */ @@ -684,13 +917,20 @@ export const clamp: { /** * Restricts the given `number` to be within the range specified by the `minimum` and `maximum` values. * + * **When to use** + * + * Use to force a number into an inclusive range. + * + * **Details** + * * - If the `number` is less than the `minimum` value, the function returns the `minimum` value. * - If the `number` is greater than the `maximum` value, the function returns the `maximum` value. * - Otherwise, it returns the original `number`. * - * @example + * **Example** (Clamping to a range) + * * ```ts - * import * as Number from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * * const clamp = Number.clamp({ minimum: 1, maximum: 5 }) @@ -700,6 +940,8 @@ export const clamp: { * assert.equal(clamp(6), 5) * ``` * + * @see {@link between} for checking whether a number is already inside a range + * * @category math * @since 2.0.0 */ @@ -712,13 +954,20 @@ export const clamp: { /** * Restricts the given `number` to be within the range specified by the `minimum` and `maximum` values. * + * **When to use** + * + * Use to force a number into an inclusive range. + * + * **Details** + * * - If the `number` is less than the `minimum` value, the function returns the `minimum` value. * - If the `number` is greater than the `maximum` value, the function returns the `maximum` value. * - Otherwise, it returns the original `number`. * - * @example + * **Example** (Clamping to a range) + * * ```ts - * import * as Number from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * * const clamp = Number.clamp({ minimum: 1, maximum: 5 }) @@ -728,6 +977,8 @@ export const clamp: { * assert.equal(clamp(6), 5) * ``` * + * @see {@link between} for checking whether a number is already inside a range + * * @category math * @since 2.0.0 */ @@ -743,14 +994,21 @@ export const clamp: { /** * Returns the minimum between two `number`s. * - * @example + * **When to use** + * + * Use to select the smaller of two numbers. + * + * **Example** (Finding the minimum) + * * ```ts - * import { min } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(min(2, 3), 2) + * assert.deepStrictEqual(Number.min(2, 3), 2) * ``` * + * @see {@link max} for selecting the larger value + * * @category math * @since 2.0.0 */ @@ -758,14 +1016,21 @@ export const min: { /** * Returns the minimum between two `number`s. * - * @example + * **When to use** + * + * Use to select the smaller of two numbers. + * + * **Example** (Finding the minimum) + * * ```ts - * import { min } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(min(2, 3), 2) + * assert.deepStrictEqual(Number.min(2, 3), 2) * ``` * + * @see {@link max} for selecting the larger value + * * @category math * @since 2.0.0 */ @@ -773,14 +1038,21 @@ export const min: { /** * Returns the minimum between two `number`s. * - * @example + * **When to use** + * + * Use to select the smaller of two numbers. + * + * **Example** (Finding the minimum) + * * ```ts - * import { min } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(min(2, 3), 2) + * assert.deepStrictEqual(Number.min(2, 3), 2) * ``` * + * @see {@link max} for selecting the larger value + * * @category math * @since 2.0.0 */ @@ -790,14 +1062,21 @@ export const min: { /** * Returns the maximum between two `number`s. * - * @example + * **When to use** + * + * Use to select the larger of two numbers. + * + * **Example** (Finding the maximum) + * * ```ts - * import { max } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(max(2, 3), 3) + * assert.deepStrictEqual(Number.max(2, 3), 3) * ``` * + * @see {@link min} for selecting the smaller value + * * @category math * @since 2.0.0 */ @@ -805,14 +1084,21 @@ export const max: { /** * Returns the maximum between two `number`s. * - * @example + * **When to use** + * + * Use to select the larger of two numbers. + * + * **Example** (Finding the maximum) + * * ```ts - * import { max } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(max(2, 3), 3) + * assert.deepStrictEqual(Number.max(2, 3), 3) * ``` * + * @see {@link min} for selecting the smaller value + * * @category math * @since 2.0.0 */ @@ -820,14 +1106,21 @@ export const max: { /** * Returns the maximum between two `number`s. * - * @example + * **When to use** + * + * Use to select the larger of two numbers. + * + * **Example** (Finding the maximum) + * * ```ts - * import { max } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(max(2, 3), 3) + * assert.deepStrictEqual(Number.max(2, 3), 3) * ``` * + * @see {@link min} for selecting the smaller value + * * @category math * @since 2.0.0 */ @@ -837,14 +1130,19 @@ export const max: { /** * Determines the sign of a given `number`. * - * @example + * **When to use** + * + * Use to classify a number as negative, zero, or positive. + * + * **Example** (Determining the sign) + * * ```ts - * import { sign } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(sign(-5), -1) - * assert.deepStrictEqual(sign(0), 0) - * assert.deepStrictEqual(sign(5), 1) + * assert.deepStrictEqual(Number.sign(-5), -1) + * assert.deepStrictEqual(Number.sign(0), 0) + * assert.deepStrictEqual(Number.sign(5), 1) * ``` * * @category math @@ -855,14 +1153,22 @@ export const sign = (n: number): Ordering => Order(n, 0) /** * Takes an `Iterable` of `number`s and returns their sum as a single `number`. * - * @example + * **When to use** + * + * Use to sum all numbers in an iterable. + * + * **Example** (Summing an iterable) + * * ```ts - * import { sumAll } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(sumAll([2, 3, 4]), 9) + * assert.deepStrictEqual(Number.sumAll([2, 3, 4]), 9) * ``` * + * @see {@link sum} for adding two numbers + * @see {@link ReducerSum} for summing through APIs that consume a `Reducer` + * * @category math * @since 2.0.0 */ @@ -877,14 +1183,22 @@ export const sumAll = (collection: Iterable): number => { /** * Takes an `Iterable` of `number`s and returns their multiplication as a single `number`. * - * @example + * **When to use** + * + * Use to multiply all numbers in an iterable. + * + * **Example** (Multiplying an iterable) + * * ```ts - * import { multiplyAll } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(multiplyAll([2, 3, 4]), 24) + * assert.deepStrictEqual(Number.multiplyAll([2, 3, 4]), 24) * ``` * + * @see {@link multiply} for multiplying two numbers + * @see {@link ReducerMultiply} for multiplying through APIs that consume a `Reducer` + * * @category math * @since 2.0.0 */ @@ -900,58 +1214,76 @@ export const multiplyAll = (collection: Iterable): number => { } /** - * Returns the remainder left over when one operand is divided by a second operand. + * Returns the remainder left over when one operand is divided by a second operand, always taking the sign of the dividend. + * + * **When to use** + * + * Use to compute a numeric remainder while preserving decimal precision better + * than direct JavaScript `%` for decimal operands. * - * It always takes the sign of the dividend. + * **Example** (Calculating remainders) * - * @example * ```ts - * import { remainder } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(remainder(2, 2), 0) - * assert.deepStrictEqual(remainder(3, 2), 1) - * assert.deepStrictEqual(remainder(-4, 2), -0) + * assert.deepStrictEqual(Number.remainder(2, 2), 0) + * assert.deepStrictEqual(Number.remainder(3, 2), 1) + * assert.deepStrictEqual(Number.remainder(-4, 2), -0) * ``` * + * @see {@link divide} for quotient calculation with division-by-zero represented as `Option.none` + * * @category math * @since 2.0.0 */ export const remainder: { /** - * Returns the remainder left over when one operand is divided by a second operand. + * Returns the remainder left over when one operand is divided by a second operand, always taking the sign of the dividend. + * + * **When to use** + * + * Use to compute a numeric remainder while preserving decimal precision better + * than direct JavaScript `%` for decimal operands. * - * It always takes the sign of the dividend. + * **Example** (Calculating remainders) * - * @example * ```ts - * import { remainder } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(remainder(2, 2), 0) - * assert.deepStrictEqual(remainder(3, 2), 1) - * assert.deepStrictEqual(remainder(-4, 2), -0) + * assert.deepStrictEqual(Number.remainder(2, 2), 0) + * assert.deepStrictEqual(Number.remainder(3, 2), 1) + * assert.deepStrictEqual(Number.remainder(-4, 2), -0) * ``` * + * @see {@link divide} for quotient calculation with division-by-zero represented as `Option.none` + * * @category math * @since 2.0.0 */ (divisor: number): (self: number) => number /** - * Returns the remainder left over when one operand is divided by a second operand. + * Returns the remainder left over when one operand is divided by a second operand, always taking the sign of the dividend. + * + * **When to use** * - * It always takes the sign of the dividend. + * Use to compute a numeric remainder while preserving decimal precision better + * than direct JavaScript `%` for decimal operands. + * + * **Example** (Calculating remainders) * - * @example * ```ts - * import { remainder } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(remainder(2, 2), 0) - * assert.deepStrictEqual(remainder(3, 2), 1) - * assert.deepStrictEqual(remainder(-4, 2), -0) + * assert.deepStrictEqual(Number.remainder(2, 2), 0) + * assert.deepStrictEqual(Number.remainder(3, 2), 1) + * assert.deepStrictEqual(Number.remainder(-4, 2), -0) * ``` * + * @see {@link divide} for quotient calculation with division-by-zero represented as `Option.none` + * * @category math * @since 2.0.0 */ @@ -979,13 +1311,18 @@ function decimalCount(n: number): number { /** * Returns the next power of 2 from the given number. * - * @example + * **When to use** + * + * Use to round a number up to the next power of two. + * + * **Example** (Finding the next power of two) + * * ```ts - * import { nextPow2 } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(nextPow2(5), 8) - * assert.deepStrictEqual(nextPow2(17), 32) + * assert.deepStrictEqual(Number.nextPow2(5), 8) + * assert.deepStrictEqual(Number.nextPow2(17), 32) * ``` * * @category math @@ -997,10 +1334,14 @@ export const nextPow2 = (n: number): number => { } /** - * Tries to parse a `number` from a `string` using the `Number()` function. + * Parses a `number` from a `string` safely using the `Number()` function. * The following special string values are supported: "NaN", "Infinity", "-Infinity". * - * **Example** + * **When to use** + * + * Use to parse numeric text without throwing on invalid input. + * + * **Example** (Parsing numbers from strings) * * ```ts * import { Number } from "effect" @@ -1013,6 +1354,8 @@ export const nextPow2 = (n: number): number => { * Number.parse("not a number") // Option.none() * ``` * + * @see {@link Number} for native constructor coercion + * * @category constructors * @since 2.0.0 */ @@ -1036,13 +1379,18 @@ export const parse = (s: string): Option.Option => { /** * Returns the number rounded with the given precision. * - * @example + * **When to use** + * + * Use to round a number to a fixed number of decimal places. + * + * **Example** (Rounding with precision) + * * ```ts - * import { round } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(round(1.1234, 2), 1.12) - * assert.deepStrictEqual(round(1.567, 2), 1.57) + * assert.deepStrictEqual(Number.round(1.1234, 2), 1.12) + * assert.deepStrictEqual(Number.round(1.567, 2), 1.57) * ``` * * @category math @@ -1052,13 +1400,18 @@ export const round: { /** * Returns the number rounded with the given precision. * - * @example + * **When to use** + * + * Use to round a number to a fixed number of decimal places. + * + * **Example** (Rounding with precision) + * * ```ts - * import { round } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(round(1.1234, 2), 1.12) - * assert.deepStrictEqual(round(1.567, 2), 1.57) + * assert.deepStrictEqual(Number.round(1.1234, 2), 1.12) + * assert.deepStrictEqual(Number.round(1.567, 2), 1.57) * ``` * * @category math @@ -1068,13 +1421,18 @@ export const round: { /** * Returns the number rounded with the given precision. * - * @example + * **When to use** + * + * Use to round a number to a fixed number of decimal places. + * + * **Example** (Rounding with precision) + * * ```ts - * import { round } from "effect/Number" + * import { Number } from "effect" * import * as assert from "node:assert" * - * assert.deepStrictEqual(round(1.1234, 2), 1.12) - * assert.deepStrictEqual(round(1.567, 2), 1.57) + * assert.deepStrictEqual(Number.round(1.1234, 2), 1.12) + * assert.deepStrictEqual(Number.round(1.567, 2), 1.57) * ``` * * @category math @@ -1087,15 +1445,43 @@ export const round: { }) /** - * A `Reducer` for combining `number`s using addition. + * Reducer for combining `number`s using addition. + * + * **When to use** + * + * Use to sum many numbers through APIs that consume a `Reducer`. + * + * **Details** * + * The reducer starts from `0`, so `combineAll([])` returns `0`. + * + * @see {@link sumAll} for summing an iterable directly + * @see {@link ReducerMultiply} for multiplying number values + * + * @category math * @since 4.0.0 */ export const ReducerSum: Reducer.Reducer = Reducer.make((a, b) => a + b, 0) /** - * A `Reducer` for combining `number`s using multiplication. + * Reducer for combining `number`s using multiplication. + * + * **When to use** + * + * Use to multiply many numbers through APIs that consume a `Reducer`. + * + * **Details** + * + * The reducer starts from `1`, so reducing an empty collection returns `1`. + * + * **Gotchas** + * + * Reducing an iterable short-circuits when it sees `0`, so later elements are + * not consumed. * + * @see {@link multiplyAll} for multiplying an iterable directly + * + * @category math * @since 4.0.0 */ export const ReducerMultiply: Reducer.Reducer = Reducer.make((a, b) => a * b, 1, (collection) => { @@ -1108,15 +1494,49 @@ export const ReducerMultiply: Reducer.Reducer = Reducer.make((a, b) => a }) /** - * A `Combiner` that returns the maximum `number`. + * Reducer for reducing `number`s by keeping the maximum value. + * + * **When to use** + * + * Use to keep the largest number through APIs that consume a `Reducer`. + * + * **Details** + * + * The reducer starts from `-Infinity`, so reducing an empty collection returns + * `-Infinity`. + * + * **Gotchas** + * + * `NaN` values propagate through `Math.max`. + * + * @see {@link ReducerMin} for keeping the smallest number + * @see {@link max} for comparing two numbers directly * + * @category math * @since 4.0.0 */ export const ReducerMax: Reducer.Reducer = Reducer.make((a, b) => Math.max(a, b), -Infinity) /** - * A `Combiner` that returns the minimum `number`. + * Reducer for reducing `number`s by keeping the minimum value. + * + * **When to use** + * + * Use to keep the smallest number through APIs that consume a `Reducer`. + * + * **Details** + * + * The reducer starts from `Infinity`, so reducing an empty collection returns + * `Infinity`. * + * **Gotchas** + * + * `NaN` values propagate through `Math.min`. + * + * @see {@link ReducerMax} for keeping the largest number + * @see {@link min} for comparing two numbers directly + * + * @category math * @since 4.0.0 */ export const ReducerMin: Reducer.Reducer = Reducer.make((a, b) => Math.min(a, b), Infinity) diff --git a/.opencode/node_modules/effect/src/Optic.ts b/.opencode/node_modules/effect/src/Optic.ts index 8dedf66f312f5421598df5e7d590114e8be25f77..b13d83074400fe649b551f7f92e545bf65ccc515 100644 --- a/.opencode/node_modules/effect/src/Optic.ts +++ b/.opencode/node_modules/effect/src/Optic.ts @@ -1,98 +1,15 @@ /** - * Composable, immutable accessors for reading and updating nested data - * structures without mutation. - * - * **Mental model** - * - * - **Optic** — a first-class reference to a piece inside a larger structure. - * Compose optics to reach deeply nested values. - * - **Iso** — lossless two-way conversion (`get`/`set`) between `S` and `A`. - * Extends both {@link Lens} and {@link Prism}. - * - **Lens** — focuses on exactly one part of `S`. `get` always succeeds; - * `replace` needs the original `S` to produce the updated whole. - * - **Prism** — focuses on a part that may not be present (e.g. a union - * variant). `getResult` can fail; `set` builds a new `S` from `A` alone. - * - **Optional** — the most general optic: both reading and writing can fail. - * - **Traversal** — focuses on zero or more elements of an array-like - * structure. Technically `Optional>`. - * - **Hierarchy** (strongest → weakest): - * `Iso > Lens | Prism > Optional`. Composing a weaker optic with any other - * produces the weaker kind. - * - * **Common tasks** - * - * - Start a chain → {@link id} (identity iso) - * - Drill into a struct key → `.key("name")` / `.optionalKey("name")` - * - Drill into a key that may not exist → `.at("name")` - * - Narrow a tagged union → `.tag("MyVariant")` - * - Narrow by type guard → `.refine(guard)` - * - Add validation → `.check(Schema.isGreaterThan(0))` - * - Filter out `undefined` → `.notUndefined()` - * - Pick/omit struct keys → `.pick(["a","b"])` / `.omit(["c"])` - * - Traverse array elements → `.forEach(el => el.key("field"))` - * - Build an iso → {@link makeIso} - * - Build a lens → {@link makeLens} - * - Build a prism → {@link makePrism}, {@link fromChecks} - * - Build an optional → {@link makeOptional} - * - Focus into `Option.Some` → {@link some} - * - Focus into `Result.Success`/`Failure` → {@link success}, {@link failure} - * - Convert record ↔ entries → {@link entries} - * - Extract all traversal elements → {@link getAll} - * - * **Gotchas** - * - * - Updates are structurally persistent: only nodes on the path are cloned. - * Unrelated branches keep referential identity. However, **no-op updates - * may still allocate** a new root — do not rely on reference identity to - * detect no-ops. - * - `replace` silently returns the original `S` when the optic cannot focus - * (e.g. wrong tag). Use `replaceResult` for explicit failure. - * - `modify` also returns the original `S` on focus failure — it never throws. - * - `.key()` and `.optionalKey()` do not work on union types (compile error). - * - Only plain objects (`Object.prototype` or `null` prototype) and arrays can - * be cloned. Class instances cause a runtime error on `replace`/`modify`. - * - * **Quickstart** - * - * **Example** (reading and updating nested state) + * Reads and updates focused parts of values without mutating the original + * value. * - * ```ts - * import { Optic } from "effect" - * - * type State = { user: { name: string; age: number } } - * - * const _age = Optic.id().key("user").key("age") - * - * const s1: State = { user: { name: "Alice", age: 30 } } - * - * // Read - * console.log(_age.get(s1)) - * // Output: 30 - * - * // Update immutably - * const s2 = _age.replace(31, s1) - * console.log(s2) - * // Output: { user: { name: "Alice", age: 31 } } - * - * // Modify with a function - * const s3 = _age.modify((n) => n + 1)(s1) - * console.log(s3) - * // Output: { user: { name: "Alice", age: 31 } } - * - * // Referential identity is preserved for unrelated branches - * console.log(s2.user !== s1.user) - * // Output: true (on the path) - * ``` - * - * **See also** - * - * - {@link id} — entry point for optic chains - * - {@link Lens} / {@link Prism} / {@link Optional} — core optic types - * - {@link Traversal} / {@link getAll} — multi-focus optics - * - {@link some} / {@link success} / {@link failure} — built-in prisms + * An optic describes where to look inside a value, such as a record field, a + * union variant, an optional value, or several values in a collection. Different + * optic types describe different kinds of focus: some always find a value, + * some may not, and some can find many. This module includes the optic types, + * constructors, focusing helpers, and operations for replacing, modifying, or + * collecting focused values. * * @since 4.0.0 - * @module */ import { format } from "./Formatter.ts" @@ -101,20 +18,22 @@ import * as Option from "./Option.ts" import * as Predicate from "./Predicate.ts" import * as Result from "./Result.ts" import type * as Schema from "./Schema.ts" -import * as AST from "./SchemaAST.ts" -import type * as Issue from "./SchemaIssue.ts" +import * as SchemaAST from "./SchemaAST.ts" +import type * as SchemaIssue from "./SchemaIssue.ts" import * as Struct from "./Struct.ts" import type { IsUnion } from "./Types.ts" /** * A lossless, reversible conversion between types `S` and `A`. * - * When to use: - * - You have a pair of functions that convert back and forth without losing + * **When to use** + * + * Use when you have a pair of functions that convert back and forth without losing * information (e.g. `Record ↔ entries`, `Celsius ↔ Fahrenheit`). * - You want the strongest optic that can be composed with any other. * - * Behavior: + * **Details** + * * - `get(s)` always succeeds and returns an `A`. * - `set(a)` always succeeds and returns an `S`. * - `get(set(a)) === a` and `set(get(s))` equals `s` (round-trip laws). @@ -149,13 +68,14 @@ export interface Iso extends Lens, Prism {} /** * Creates an {@link Iso} from a pair of conversion functions. * - * When to use: - * - You have two pure functions that form a lossless round-trip between `S` - * and `A`. + * **When to use** + * + * Use when you have two pure conversion functions that preserve all information + * between `S` and `A`. + * + * **Details** * - * Behavior: - * - Does not mutate inputs. - * - The returned optic can be composed with any other optic. + * The returned optic can be composed with any other optic. * * **Example** (wrapping/unwrapping a branded type) * @@ -178,7 +98,7 @@ export interface Iso extends Lens, Prism {} * @see {@link Iso} — the type this function returns * @see {@link id} — identity iso (no conversion) * - * @category Constructors + * @category constructors * @since 4.0.0 */ export function makeIso(get: (s: S) => A, set: (a: A) => S): Iso { @@ -188,12 +108,13 @@ export function makeIso(get: (s: S) => A, set: (a: A) => S): Iso { /** * Focuses on exactly one part `A` inside a whole `S`. * - * When to use: - * - You always have a value to read (the part exists unconditionally). - * - You need the original `S` to produce the updated whole (unlike - * {@link Iso}). + * **When to use** + * + * Use when you always have a value to read and need the original `S` to produce + * the updated whole, unlike `Iso`. + * + * **Details** * - * Behavior: * - `get(s)` always succeeds and returns `A`. * - `replace(a, s)` returns a new `S` with the focused part replaced. * - Extends {@link Optional}. @@ -227,12 +148,13 @@ export interface Lens extends Optional { /** * Creates a {@link Lens} from a getter and a replacer. * - * When to use: - * - You can always extract `A` from `S` and produce a new `S` by + * **When to use** + * + * Use when you can always extract `A` from `S` and produce a new `S` by * substituting a new `A`. * - * Behavior: - * - Does not mutate inputs. + * **Details** + * * - `replace(a, s)` should return a structurally new `S` with `a` in place * of the old focus. * @@ -256,7 +178,7 @@ export interface Lens extends Optional { * @see {@link Lens} — the type this function returns * @see {@link makeIso} — when no original `S` is needed for `set` * - * @category Constructors + * @category constructors * @since 4.0.0 */ export function makeLens(get: (s: S) => A, replace: (a: A, s: S) => S): Lens { @@ -267,12 +189,14 @@ export function makeLens(get: (s: S) => A, replace: (a: A, s: S) => S): Le * Focuses on a part `A` of `S` that may not be present (e.g. a union * variant or a validated subset). * - * When to use: - * - The focus is conditional — reading can fail (wrong variant, failed + * **When to use** + * + * Use when the focus is conditional — reading can fail (wrong variant, failed * validation). * - Building a new `S` from `A` does **not** require the original `S`. * - * Behavior: + * **Details** + * * - `getResult(s)` returns `Result.Success` when the focus matches, or * `Result.Failure` with an error message. * - `set(a)` always succeeds and returns a new `S`. @@ -312,12 +236,13 @@ export interface Prism extends Optional { /** * Creates a {@link Prism} from a fallible getter and an infallible setter. * - * When to use: - * - Reading can fail (the part may not exist in `S`), but building `S` + * **When to use** + * + * Use when reading can fail (the part may not exist in `S`), but building `S` * from `A` always succeeds. * - * Behavior: - * - Does not mutate inputs. + * **Details** + * * - `getResult` should return `Result.fail(message)` on mismatch. * * **Example** (parsing a string to a number) @@ -343,7 +268,7 @@ export interface Prism extends Optional { * @see {@link Prism} — the type this function returns * @see {@link fromChecks} — build from `Schema` checks instead * - * @category Constructors + * @category constructors * @since 4.0.0 */ export function makePrism(getResult: (s: S) => Result.Result, set: (a: A) => S): Prism { @@ -353,16 +278,17 @@ export function makePrism(getResult: (s: S) => Result.Result, s /** * Creates a {@link Prism} from one or more `Schema` validation checks. * - * When to use: - * - You want to narrow `T` to the subset that passes certain validation + * **When to use** + * + * Use when you want to narrow `T` to the subset that passes certain validation * rules (e.g. positive integer). * - You already have `Schema.isGreaterThan`, `Schema.isInt`, etc. * - * Behavior: + * **Details** + * * - `getResult` runs all checks; fails with a combined error message when * any check fails. * - `set` is identity — the value passes through unchanged. - * - Does not mutate inputs. * * **Example** (positive integer prism) * @@ -384,10 +310,10 @@ export function makePrism(getResult: (s: S) => Result.Result, s * @see {@link makePrism} — constructor with custom getter/setter * @see {@link Prism} — the type this function returns * - * @category Constructors + * @category constructors * @since 4.0.0 */ -export function fromChecks(...checks: readonly [AST.Check, ...Array>]): Prism { +export function fromChecks(...checks: readonly [SchemaAST.Check, ...Array>]): Prism { return make(new CheckNode(checks)) } @@ -471,9 +397,9 @@ class PathNode { class CheckNode { readonly _tag = "CheckNode" - readonly checks: readonly [AST.Check, ...Array>] + readonly checks: readonly [SchemaAST.Check, ...Array>] - constructor(checks: readonly [AST.Check, ...Array>]) { + constructor(checks: readonly [SchemaAST.Check, ...Array>]) { this.checks = checks } } @@ -531,13 +457,15 @@ type ForbidUnion = IsUnion extends true ? [Message /** * The most general optic — both reading and writing can fail. * - * When to use: - * - The focus may not exist in `S` **and** writing a new `A` back may also - * fail (e.g. the source no longer matches the expected shape). - * - As the base type: every optic ({@link Iso}, {@link Lens}, {@link Prism}, - * {@link Traversal}) extends `Optional`. + * **When to use** + * + * Use when the focus may not exist in `S` and writing a new `A` back may also + * fail, for example when the source no longer matches the expected shape. This + * is the base type extended by {@link Iso}, {@link Lens}, {@link Prism}, and + * {@link Traversal}. + * + * **Details** * - * Behavior: * - `getResult(s)` returns `Result.Success` or `Result.Failure`. * - `replaceResult(a, s)` returns `Result.Success` or * `Result.Failure`. @@ -574,9 +502,8 @@ type ForbidUnion = IsUnion extends true ? [Message export interface Optional { readonly node: Node /** - * Attempts to read the focus `A` from the whole `S`. - * - * Returns `Result.Success` when the focus exists, or + * Attempts to read the focus `A` from the whole `S`. Returns + * `Result.Success` when the focus exists, or * `Result.Failure` with a descriptive error otherwise. */ readonly getResult: (s: S) => Result.Result @@ -634,6 +561,8 @@ export interface Optional { /** * Focuses on a property of the current struct/tuple focus. * + * **Details** + * * - On a {@link Lens}, returns a Lens. * - On an {@link Optional}, returns an Optional. * - Does **not** work on union types (compile error). @@ -665,6 +594,8 @@ export interface Optional { * Focuses on a key where setting `undefined` **removes** the key from the * struct (or splices the element from an array/tuple). * + * **Details** + * * - The focus type becomes `A[Key] | undefined`. * - Does **not** work on union types (compile error). * @@ -698,6 +629,8 @@ export interface Optional { * Adds one or more `Schema` validation checks to the optic chain. * `getResult` fails when any check fails; `set` passes through unchanged. * + * **Details** + * * - On a {@link Prism}, returns a Prism. * - On an {@link Optional}, returns an Optional. * @@ -717,12 +650,17 @@ export interface Optional { * * @see {@link fromChecks} — standalone prism from checks */ - check(this: Prism, ...checks: readonly [AST.Check, ...Array>]): Prism - check(this: Optional, ...checks: readonly [AST.Check, ...Array>]): Optional + check(this: Prism, ...checks: readonly [SchemaAST.Check, ...Array>]): Prism + check( + this: Optional, + ...checks: readonly [SchemaAST.Check, ...Array>] + ): Optional /** * Narrows the focus to a subtype `B` using a type guard. * + * **Details** + * * - On a {@link Prism}, returns a Prism. * - On an {@link Optional}, returns an Optional. * - Pass optional `annotations` to customize the error message. @@ -761,6 +699,8 @@ export interface Optional { * Narrows the focus to the variant of a tagged union with the given * `_tag` value. * + * **Details** + * * - On a {@link Prism}, returns a Prism. * - On an {@link Optional}, returns an Optional. * - Shorthand for `.refine(s => s._tag === tag)`. @@ -785,11 +725,11 @@ export interface Optional { * * @see `.refine()` — for arbitrary type guards */ - tag( + tag( this: Prism, tag: Tag ): Prism> - tag( + tag( this: Optional, tag: Tag ): Optional> @@ -798,6 +738,8 @@ export interface Optional { * Focuses on a key only if it exists (`Object.hasOwn`). Both * `getResult` and `replaceResult` fail when the key is absent. * + * **Details** + * * Unlike `.key()`, which always succeeds on the read side, `.at()` is * useful for Records or arrays where the key/index may not be present. * @@ -830,6 +772,8 @@ export interface Optional { /** * Focuses on a subset of keys of the current struct focus. * + * **Details** + * * - On a {@link Lens}, returns a Lens. * - On an {@link Optional}, returns an Optional. * - Does **not** work on union types (compile error). @@ -863,6 +807,8 @@ export interface Optional { /** * Focuses on all keys **except** the specified ones. * + * **Details** + * * - On a {@link Lens}, returns a Lens. * - On an {@link Optional}, returns an Optional. * - Does **not** work on union types (compile error). @@ -882,7 +828,7 @@ export interface Optional { * * @see `.pick()` — the inverse operation * - * @since 1.0.0 + * @since 4.0.0 */ omit>( this: Lens, @@ -897,7 +843,6 @@ export interface Optional { /** * Filters out `undefined` from the focus, producing a {@link Prism}. - * * `getResult` fails when the focus is `undefined`. * * **Example** (filtering undefined) @@ -922,12 +867,12 @@ export interface Optional { /** * Focuses **all elements** of an array-like focus and optionally narrows * to a subset using an element-level optic. - * * Available only on {@link Traversal} (i.e. when `A` is * `ReadonlyArray`). Returns a new Traversal focused on the * selected elements. * - * Behavior: + * **Details** + * * - **getResult** collects the values focused by `f(id())` for each * element. Non-focusable elements are skipped. * - **replaceResult** expects exactly as many values as were collected by @@ -965,6 +910,8 @@ export interface Optional { /** * Applies a function to **every** element focused by the traversal. * + * **Details** + * * Available only on {@link Traversal}. Returns a function `(s: S) => S`. * If the traversal cannot focus, the original `s` is returned unchanged. * @@ -997,11 +944,13 @@ export interface Optional { /** * Creates an {@link Optional} from a fallible getter and a fallible setter. * - * When to use: - * - Both reading and writing can fail. + * **When to use** + * + * Use when you need an optic for a focus that may be missing on read and may + * reject updates on write. + * + * **Details** * - * Behavior: - * - Does not mutate inputs. * - `getResult` should return `Result.fail(message)` on mismatch. * - `set` should return `Result.fail(message)` when the update cannot be * applied. @@ -1031,7 +980,7 @@ export interface Optional { * @see {@link makeLens} — when reading always succeeds * @see {@link makePrism} — when writing always succeeds * - * @category Constructors + * @category constructors * @since 4.0.0 */ export function makeOptional( @@ -1044,11 +993,13 @@ export function makeOptional( /** * An optic that focuses on **zero or more** elements of type `A` inside `S`. * - * When to use: - * - You want to read/update multiple elements at once (e.g. all items in + * **When to use** + * + * Use when you want to read/update multiple elements at once (e.g. all items in * an array, or a filtered subset). * - * Behavior: + * **Details** + * * - Technically `Optional>` — the focused value is an * array of all matched elements. * - Use `.forEach()` to add per-element sub-optics (filtering, drilling @@ -1129,11 +1080,11 @@ class OptionalImpl implements Optional { ) ) } - check(...checks: readonly [AST.Check, ...Array>]): any { + check(...checks: readonly [SchemaAST.Check, ...Array>]): any { return make(compose(this.node, new CheckNode(checks))) } refine(refinement: (a: A) => a is B, annotations?: Schema.Annotations.Filter): any { - return make(compose(this.node, new CheckNode([AST.makeFilterByGuard(refinement, annotations)]))) + return make(compose(this.node, new CheckNode([SchemaAST.makeFilterByGuard(refinement, annotations)]))) } tag(tag: string): any { return make( @@ -1346,7 +1297,7 @@ const recur = memoize((node: Node): Op => { case "CheckNode": return { _tag: "PrismNode", - get: (s: any) => Result.mapError(AST.runChecks(node.checks, s), String), + get: (s: any) => Result.mapError(SchemaAST.runChecks(node.checks, s), String), set: identity } case "CompositionNode": { @@ -1436,14 +1387,15 @@ function getCompositionTag(a: Op["_tag"], b: Op["_tag"]): Op["_tag"] { * Returns a function that extracts all elements focused by a * {@link Traversal} as a plain mutable array. * - * When to use: - * - You need the focused values as a simple `Array` for further + * **When to use** + * + * Use when you need the focused values as a simple `Array` for further * processing. * - * Behavior: + * **Details** + * * - Returns an empty array when the traversal cannot focus. * - Always returns a fresh array (safe to mutate). - * - Does not mutate the source. * * **Example** (collecting positive numbers) * @@ -1485,13 +1437,14 @@ export function getAll(traversal: Traversal): (s: S) => Array { const identityIso = make(identityNode) /** - * The identity {@link Iso}. Focuses on the whole value unchanged. + * Iso that focuses on the whole value unchanged. + * + * **When to use** * - * When to use: - * - As the starting point of an optic chain: `Optic.id().key("x")...` - * - Anywhere an `Iso` is needed. + * Use when you need to start an optic chain with a focus on the whole value. + * + * **Details** * - * Behavior: * - `get(s)` returns `s`. * - `set(a)` returns `a`. * - Singleton — every call returns the same instance. @@ -1519,14 +1472,16 @@ export function id(): Iso { } /** - * An {@link Iso} that converts a `Record` to an array of + * Iso that converts a `Record` to an array of * `[key, value]` entries and back. * - * When to use: - * - You want to traverse or manipulate record entries as an array (e.g. + * **When to use** + * + * Use when you want to traverse or manipulate record entries as an array (e.g. * with `.forEach()`). * - * Behavior: + * **Details** + * * - `get` uses `Object.entries`. * - `set` uses `Object.fromEntries`. * - Round-trip is lossless for `Record`. @@ -1556,13 +1511,15 @@ export function entries(): Iso, ReadonlyArray` and want to read/update the inner value only + * Use when you have an `Option` and want to read/update the inner value only * when it is `Some`. * - * Behavior: + * **Details** + * * - `getResult` fails with an error message when the option is `None`. * - `set(a)` wraps `a` in `Option.some(a)`. * @@ -1602,12 +1559,14 @@ export function some(): Prism, A> { } /** - * A {@link Prism} that focuses on `Option.None`, exposing `undefined`. + * Prism that focuses on `Option.None`, exposing `undefined`. + * + * **When to use** * - * When to use: - * - You want to match or construct `None` values within an optic chain. + * Use when you want to match or construct `None` values within an optic chain. + * + * **Details** * - * Behavior: * - `getResult` succeeds with `undefined` when the option is `None`. * - `getResult` fails when the option is `Some`. * - `set(undefined)` produces `Option.none()`. @@ -1645,13 +1604,15 @@ export function none(): Prism, undefined> { } /** - * A {@link Prism} that focuses on the success value of a `Result`. + * Prism that focuses on the success value of a `Result`. + * + * **When to use** * - * When to use: - * - You have a `Result` and want to read/update `A` only when it + * Use when you have a `Result` and want to read/update `A` only when it * is a `Success`. * - * Behavior: + * **Details** + * * - `getResult` fails when the result is a `Failure`. * - `set(a)` produces `Result.succeed(a)`. * @@ -1688,13 +1649,15 @@ export function success(): Prism, A> { } /** - * A {@link Prism} that focuses on the failure value of a `Result`. + * Prism that focuses on the failure value of a `Result`. + * + * **When to use** * - * When to use: - * - You have a `Result` and want to read/update `E` only when it + * Use when you have a `Result` and want to read/update `E` only when it * is a `Failure`. * - * Behavior: + * **Details** + * * - `getResult` fails when the result is a `Success`. * - `set(e)` produces `Result.fail(e)`. * @@ -1733,6 +1696,6 @@ export function failure(): Prism, E> { function runRefinement( refinement: (e: E) => e is T, annotations?: Schema.Annotations.Filter -): (e: E) => Result.Result { - return (e) => AST.runChecks([AST.makeFilterByGuard(refinement, annotations)], e) as any +): (e: E) => Result.Result { + return (e) => SchemaAST.runChecks([SchemaAST.makeFilterByGuard(refinement, annotations)], e) as any } diff --git a/.opencode/node_modules/effect/src/Option.ts b/.opencode/node_modules/effect/src/Option.ts index 90c49c64541c996562a26ebc8343c09783969822..9f867e2081b6752983899df32ebd06a3dea8f753 100644 --- a/.opencode/node_modules/effect/src/Option.ts +++ b/.opencode/node_modules/effect/src/Option.ts @@ -1,80 +1,16 @@ /** - * The `Option` module provides a type-safe way to represent values that may or - * may not exist. An `Option` is either `Some` (containing a value) or - * `None` (representing absence). - * - * **Mental model** - * - * - `Option` is a discriminated union: `None | Some` - * - `None` represents the absence of a value (like `null`/`undefined`, but type-safe) - * - `Some` wraps a present value of type `A`, accessed via `.value` - * - `Option` is a monad: chain operations with {@link flatMap}, compose pipelines with `pipe` - * - All operations are pure and return new `Option` values; the input is never mutated - * - `Option` is yieldable in `Effect.gen`, producing the inner value or short-circuiting with `NoSuchElementError` - * - * **Common tasks** - * - * - Create from a value: {@link some}, {@link none} - * - Create from nullable: {@link fromNullishOr}, {@link fromNullOr}, {@link fromUndefinedOr} - * - Create from iterable: {@link fromIterable} - * - Create from Result: {@link getSuccess}, {@link getFailure} - * - Transform: {@link map}, {@link flatMap}, {@link andThen} - * - Unwrap: {@link getOrElse}, {@link getOrNull}, {@link getOrUndefined}, {@link getOrThrow} - * - Pattern match: {@link match} - * - Fallbacks: {@link orElse}, {@link orElseSome}, {@link firstSomeOf} - * - Filter: {@link filter}, {@link filterMap} - * - Combine multiple: {@link all}, {@link zipWith}, {@link product} - * - Generator syntax: {@link gen} - * - Do notation: {@link Do}, {@link bind}, {@link let_ let} - * - Check contents: {@link isSome}, {@link isNone}, {@link contains}, {@link exists} - * - * **Gotchas** - * - * - `Option.some(null)` is a valid `Some`; use {@link fromNullishOr} to treat `null`/`undefined` as `None` - * - {@link filterMap} uses a `Filter` callback that returns `Result` - * - {@link getOrThrow} throws a generic `Error`; prefer {@link getOrThrowWith} for custom errors - * - `None` is a singleton; compare with {@link isNone}, not `===` - * - When yielded in `Effect.gen`, a `None` becomes a `NoSuchElementError` defect - * - * **Quickstart** - * - * **Example** (Working with optional values) + * Models a value that may be present or absent. * - * ```ts - * import { Option } from "effect" - * - * const name = Option.some("Alice") - * const age = Option.none() - * - * // Transform - * const upper = Option.map(name, (s) => s.toUpperCase()) - * - * // Unwrap with fallback - * console.log(Option.getOrElse(upper, () => "unknown")) - * // Output: "ALICE" - * - * console.log(Option.getOrElse(age, () => 0)) - * // Output: 0 - * - * // Combine multiple options - * const both = Option.all({ name, age }) - * console.log(Option.isNone(both)) - * // Output: true - * ``` - * - * **See also** - * - * - {@link some} / {@link none} for creating values - * - {@link map} / {@link flatMap} for transforming values - * - {@link match} for pattern matching - * - {@link gen} for generator-based syntax + * An `Option` is `Some` when a value is available and `None` when it is + * not. This lets code handle missing values explicitly instead of relying on + * `null` or `undefined`. The module includes helpers for creating, checking, + * transforming, combining, and extracting optional values, plus conversions to + * and from common nullable or result-like shapes. It also includes `Option.gen` + * for writing small generator-based computations that stop at the first `None`. * * @since 2.0.0 - * @module */ -import type { NoSuchElementError } from "./Cause.ts" import * as Combiner from "./Combiner.ts" -import type { EffectIterator, Yieldable } from "./Effect.ts" import * as Equal from "./Equal.ts" import * as Equivalence from "./Equivalence.ts" import type * as Filter from "./Filter.ts" @@ -104,32 +40,15 @@ const TypeId = "~effect/data/Option" * * **When to use** * - * - Representing initial values that may not yet exist + * Use to represent initial values that may not yet exist * - Returning from partial functions (not defined for all inputs) * - Managing optional fields in data structures * - * **Example** (Creating and matching Options) - * - * ```ts - * import { Option } from "effect" - * - * const someValue: Option.Option = Option.some(42) - * const noneValue: Option.Option = Option.none() - * - * const result = Option.match(someValue, { - * onNone: () => "No value", - * onSome: (value) => `Value is ${value}` - * }) - * - * console.log(result) - * // Output: "Value is 42" - * ``` - * * @see {@link some} for creating a `Some` * @see {@link none} for creating a `None` * @see {@link match} for pattern matching * - * @category Models + * @category models * @since 2.0.0 */ export type Option = None | Some @@ -139,54 +58,73 @@ export type Option = None | Some * * **When to use** * - * - Use as a type guard target when narrowing via {@link isNone} + * Use as a type guard target when narrowing via {@link isNone} * - * **Behavior** + * **Details** * * - `_tag` is always `"None"` - * - Yieldable in `Effect.gen` — yields `NoSuchElementError` * - Implements `Pipeable`, `Inspectable`, and structural equality * * @see {@link isNone} to check if an `Option` is `None` * @see {@link none} to construct a `None` * - * @category Models + * @category models * @since 2.0.0 */ -export interface None extends Pipeable, Inspectable, Yieldable, A, NoSuchElementError> { +export interface None extends Pipeable, Inspectable { readonly _tag: "None" readonly _op: "None" readonly valueOrUndefined: undefined readonly [TypeId]: { readonly _A: Covariant } + [Symbol.iterator](): OptionIterator> [Unify.typeSymbol]?: unknown [Unify.unifySymbol]?: OptionUnify [Unify.ignoreSymbol]?: OptionUnifyIgnore } +/** + * Iterator protocol used to yield an `Option` inside {@link gen}, returning the + * contained value type back to the generator. + * + * **When to use** + * + * Use when defining or typing `[Symbol.iterator]()` for `Option` values so + * `yield*` can pass the contained value type back into `Option.gen`. + * + * @see {@link gen} for writing generator-based `Option` code that consumes this iterator protocol + * + * @category generators + * @since 4.0.0 + */ +export interface OptionIterator> { + next( + ...args: ReadonlyArray + ): IteratorResult> +} + /** * Represents the presence of a value within an {@link Option}. * * **When to use** * - * - Use as a type guard target when narrowing via {@link isSome} + * Use as a type guard target when narrowing via {@link isSome} * - Access the inner value via `.value` * - * **Behavior** + * **Details** * * - `_tag` is always `"Some"` * - `.value` holds the contained value of type `A` - * - Yieldable in `Effect.gen` — yields the inner value * - Implements `Pipeable`, `Inspectable`, and structural equality * * @see {@link isSome} to check if an `Option` is `Some` * @see {@link some} to construct a `Some` * - * @category Models + * @category models * @since 2.0.0 */ -export interface Some extends Pipeable, Inspectable, Yieldable, A, NoSuchElementError> { +export interface Some extends Pipeable, Inspectable { readonly _tag: "Some" readonly _op: "Some" readonly value: A @@ -194,17 +132,26 @@ export interface Some extends Pipeable, Inspectable, Yieldable, readonly [TypeId]: { readonly _A: Covariant } - [Symbol.iterator](): EffectIterator> + [Symbol.iterator](): OptionIterator> [Unify.typeSymbol]?: unknown [Unify.unifySymbol]?: OptionUnify [Unify.ignoreSymbol]?: OptionUnifyIgnore } /** - * Internal unification interface for `Option` types. Used by the Effect - * library's type system for type-level operations. + * Type-level unification support for `Option` values. + * + * **When to use** + * + * Use when extending Effect's type-level unification support for `Option`. * - * @category Models + * **Details** + * + * This is used by Effect's `Unify` machinery to preserve the contained value + * type when generic code returns or combines `Option` values. Users normally + * do not need to reference this interface directly. + * + * @category models * @since 2.0.0 */ export interface OptionUnify { @@ -214,25 +161,20 @@ export interface OptionUnify { /** * Namespace containing utility types for `Option`. * - * **Example** (Extracting the value type) - * - * ```ts - * import type { Option } from "effect" - * - * declare const myOption: Option.Option + * **When to use** * - * // ┌─── string - * // ▼ - * type MyType = Option.Option.Value - * ``` + * Use to access type-level helpers associated with `Option`. * - * @category Namespaces * @since 2.0.0 */ export declare namespace Option { /** * Extracts the type of the value contained in an `Option`. * + * **When to use** + * + * Use to infer the inner value type from an existing `Option` type. + * * **Example** (Extracting the value type) * * ```ts @@ -245,16 +187,25 @@ export declare namespace Option { * type MyType = Option.Option.Value * ``` * - * @since 2.0.0 * @category Type-level Utils + * @since 2.0.0 */ export type Value> = [T] extends [Option] ? _A : never } /** - * Internal interface for type unification ignore behavior. + * Marker interface used by Effect's `Unify` machinery for `Option` values. * - * @category Models + * **When to use** + * + * Use when marking generic code so `Option` unification should be ignored. + * + * **Details** + * + * This supports type-level unification behavior for `Option`. Users normally + * do not need to reference this interface directly. + * + * @category models * @since 2.0.0 */ export interface OptionUnifyIgnore {} @@ -262,7 +213,12 @@ export interface OptionUnifyIgnore {} /** * Type lambda interface for higher-kinded type encodings with `Option`. * - * @category Type Lambdas + * **When to use** + * + * Use when defining higher-kinded abstractions that must accept optional-value + * types as one of their type-lambda inputs. + * + * @category type lambdas * @since 2.0.0 */ export interface OptionTypeLambda extends TypeLambda { @@ -274,10 +230,10 @@ export interface OptionTypeLambda extends TypeLambda { * * **When to use** * - * - Representing a missing or uninitialized value - * - Returning "no result" from a function + * Use to represent a missing or uninitialized value, such as returning "no + * result" from a function. * - * **Behavior** + * **Details** * * - Returns `Option`, which is a subtype of `Option` for any `A` * - Always returns the same singleton instance @@ -297,7 +253,7 @@ export interface OptionTypeLambda extends TypeLambda { * * @see {@link some} for the opposite operation. * - * @category Constructors + * @category constructors * @since 2.0.0 */ export const none = (): Option => option.none @@ -307,10 +263,10 @@ export const none = (): Option => option.none * * **When to use** * - * - Wrapping a known-present value as `Option` + * Use to wrap a known present value as `Option` * - Returning a successful result from a partial function * - * **Behavior** + * **Details** * * - Always returns `Some` * - Does not filter `null` or `undefined`; use {@link fromNullishOr} for that @@ -330,7 +286,7 @@ export const none = (): Option => option.none * * @see {@link none} for the opposite operation. * - * @category Constructors + * @category constructors * @since 2.0.0 */ export const some: (value: A) => Option = option.some @@ -340,10 +296,10 @@ export const some: (value: A) => Option = option.some * * **When to use** * - * - Validating unknown values at runtime boundaries - * - Type-narrowing in union types + * Use to validate unknown values at runtime boundaries, such as type-narrowing + * in union types. * - * **Behavior** + * **Details** * * - Returns `true` for both `Some` and `None` instances * - Acts as a type guard, narrowing the input to `Option` @@ -366,7 +322,7 @@ export const some: (value: A) => Option = option.some * @see {@link isNone} to check for `None` specifically * @see {@link isSome} to check for `Some` specifically * - * @category Guards + * @category guards * @since 2.0.0 */ export const isOption: (input: unknown) => input is Option = option.isOption @@ -376,9 +332,9 @@ export const isOption: (input: unknown) => input is Option = option.isO * * **When to use** * - * - Branching on absence before accessing `.value` + * Use when you need to branch on an absent `Option` before accessing `.value`. * - * **Behavior** + * **Details** * * - Acts as a type guard, narrowing to `None` * @@ -396,7 +352,7 @@ export const isOption: (input: unknown) => input is Option = option.isO * * @see {@link isSome} for the opposite check. * - * @category Guards + * @category guards * @since 2.0.0 */ export const isNone: (self: Option) => self is None = option.isNone @@ -406,9 +362,9 @@ export const isNone: (self: Option) => self is None = option.isNone * * **When to use** * - * - Branching on presence before accessing `.value` + * Use when you need to branch on a present `Option` before accessing `.value`. * - * **Behavior** + * **Details** * * - Acts as a type guard, narrowing to `Some` * @@ -426,7 +382,7 @@ export const isNone: (self: Option) => self is None = option.isNone * * @see {@link isNone} for the opposite check. * - * @category Guards + * @category guards * @since 2.0.0 */ export const isSome: (self: Option) => self is Some = option.isSome @@ -436,10 +392,10 @@ export const isSome: (self: Option) => self is Some = option.isSome * * **When to use** * - * - Exhaustively handling both branches in one expression - * - Transforming an `Option` into a plain value + * Use when you need to handle both `Some` and `None` in one expression and + * transform an `Option` into a plain value. * - * **Behavior** + * **Details** * * - If `None`, calls `onNone` and returns its result * - If `Some`, calls `onSome` with the value and returns its result @@ -461,7 +417,7 @@ export const isSome: (self: Option) => self is Some = option.isSome * * @see {@link getOrElse} for unwrapping with a default * - * @category Pattern matching + * @category pattern matching * @since 2.0.0 */ export const match: { @@ -470,10 +426,10 @@ export const match: { * * **When to use** * - * - Exhaustively handling both branches in one expression - * - Transforming an `Option` into a plain value + * Use when you need to handle both `Some` and `None` in one expression and + * transform an `Option` into a plain value. * - * **Behavior** + * **Details** * * - If `None`, calls `onNone` and returns its result * - If `Some`, calls `onSome` with the value and returns its result @@ -495,7 +451,7 @@ export const match: { * * @see {@link getOrElse} for unwrapping with a default * - * @category Pattern matching + * @category pattern matching * @since 2.0.0 */ ( @@ -509,10 +465,10 @@ export const match: { * * **When to use** * - * - Exhaustively handling both branches in one expression - * - Transforming an `Option` into a plain value + * Use when you need to handle both `Some` and `None` in one expression and + * transform an `Option` into a plain value. * - * **Behavior** + * **Details** * * - If `None`, calls `onNone` and returns its result * - If `Some`, calls `onSome` with the value and returns its result @@ -534,7 +490,7 @@ export const match: { * * @see {@link getOrElse} for unwrapping with a default * - * @category Pattern matching + * @category pattern matching * @since 2.0.0 */ ( @@ -557,10 +513,10 @@ export const match: { * * **When to use** * - * - Turning a parsing function into a type-narrowing predicate - * - Filtering arrays with `Array.prototype.filter` + * Use when you need to turn an `Option`-returning parser into a type-narrowing + * predicate, such as for `Array.prototype.filter`. * - * **Behavior** + * **Details** * * - Returns `true` when the original function returns `Some` * - Returns `false` when the original function returns `None` @@ -589,7 +545,7 @@ export const match: { * * @see {@link liftPredicate} for the reverse direction * - * @category Conversions + * @category converting * @since 2.0.0 */ export const toRefinement = (f: (a: A) => Option): (a: A) => a is B => (a: A): a is B => isSome(f(a)) @@ -600,10 +556,10 @@ export const toRefinement = (f: (a: A) => Option): (a: A) => * * **When to use** * - * - Safely extracting the head of a collection - * - Working with generators or lazy iterables + * Use when you need to safely extract the head of a collection, including + * generators or lazy iterables. * - * **Behavior** + * **Details** * * - Only consumes the first element; does not iterate the rest * - Returns `None` for empty iterables @@ -622,7 +578,7 @@ export const toRefinement = (f: (a: A) => Option): (a: A) => * * @see {@link toArray} for the inverse direction * - * @category Constructors + * @category constructors * @since 2.0.0 */ export const fromIterable = (collection: Iterable): Option => { @@ -637,12 +593,13 @@ export const fromIterable = (collection: Iterable): Option => { * * **When to use** * - * - Discarding the error channel when you only care about success + * Use when you need to discard a `Result` failure and keep only the success + * value as an `Option`. * - * **Behavior** + * **Details** * - * - `Ok` → `Some` with the success value - * - `Err` → `None` (error is discarded) + * - `Success` becomes `Some` with the success value + * - `Failure` becomes `None` and the failure value is discarded * * **Example** (Extracting the success side) * @@ -658,22 +615,23 @@ export const fromIterable = (collection: Iterable): Option => { * * @see {@link getFailure} for the opposite operation. * - * @category Conversions - * @since 2.0.0 + * @category converting + * @since 4.0.0 */ export const getSuccess: (self: Result) => Option = result.getSuccess /** - * Converts a `Result` into an `Option`, keeping only the error value. + * Converts a `Result` into an `Option`, keeping only the failure value. * * **When to use** * - * - Extracting the error when you don't need the success channel + * Use when you need to discard a `Result` success and keep only the failure + * value as an `Option`. * - * **Behavior** + * **Details** * - * - `Err` → `Some` with the error value - * - `Ok` → `None` (success value is discarded) + * - `Failure` becomes `Some` with the failure value + * - `Success` becomes `None` and the success value is discarded * * **Example** (Extracting the failure side) * @@ -689,8 +647,8 @@ export const getSuccess: (self: Result) => Option = result.getSuc * * @see {@link getSuccess} for the opposite operation. * - * @category Conversions - * @since 2.0.0 + * @category converting + * @since 4.0.0 */ export const getFailure: (self: Result) => Option = result.getFailure @@ -699,10 +657,10 @@ export const getFailure: (self: Result) => Option = result.getFai * * **When to use** * - * - Providing a default value for an absent `Option` + * Use when providing a default value for an absent `Option` * - Unwrapping with lazy evaluation of the fallback * - * **Behavior** + * **Details** * * - `Some` → returns the inner value * - `None` → calls `onNone()` and returns its result @@ -724,7 +682,7 @@ export const getFailure: (self: Result) => Option = result.getFai * @see {@link getOrUndefined} to fall back to `undefined` * @see {@link getOrThrow} to throw on `None` * - * @category Getters + * @category getters * @since 2.0.0 */ export const getOrElse: { @@ -733,10 +691,10 @@ export const getOrElse: { * * **When to use** * - * - Providing a default value for an absent `Option` + * Use when providing a default value for an absent `Option` * - Unwrapping with lazy evaluation of the fallback * - * **Behavior** + * **Details** * * - `Some` → returns the inner value * - `None` → calls `onNone()` and returns its result @@ -758,7 +716,7 @@ export const getOrElse: { * @see {@link getOrUndefined} to fall back to `undefined` * @see {@link getOrThrow} to throw on `None` * - * @category Getters + * @category getters * @since 2.0.0 */ (onNone: LazyArg): (self: Option) => B | A @@ -767,10 +725,10 @@ export const getOrElse: { * * **When to use** * - * - Providing a default value for an absent `Option` + * Use when providing a default value for an absent `Option` * - Unwrapping with lazy evaluation of the fallback * - * **Behavior** + * **Details** * * - `Some` → returns the inner value * - `None` → calls `onNone()` and returns its result @@ -792,7 +750,7 @@ export const getOrElse: { * @see {@link getOrUndefined} to fall back to `undefined` * @see {@link getOrThrow} to throw on `None` * - * @category Getters + * @category getters * @since 2.0.0 */ (self: Option, onNone: LazyArg): A | B @@ -806,10 +764,10 @@ export const getOrElse: { * * **When to use** * - * - Chaining fallback `Option` computations - * - Building priority chains of optional values + * Use when you need a lazy fallback `Option`, such as when building priority + * chains of optional values. * - * **Behavior** + * **Details** * * - `Some` → returns `self` unchanged * - `None` → evaluates and returns `that()` @@ -830,7 +788,7 @@ export const getOrElse: { * @see {@link orElseSome} to wrap the fallback value in `Some` automatically * @see {@link firstSomeOf} to pick the first `Some` from a collection * - * @category Error handling + * @category error handling * @since 2.0.0 */ export const orElse: { @@ -839,10 +797,10 @@ export const orElse: { * * **When to use** * - * - Chaining fallback `Option` computations - * - Building priority chains of optional values + * Use when you need a lazy fallback `Option`, such as when building priority + * chains of optional values. * - * **Behavior** + * **Details** * * - `Some` → returns `self` unchanged * - `None` → evaluates and returns `that()` @@ -863,7 +821,7 @@ export const orElse: { * @see {@link orElseSome} to wrap the fallback value in `Some` automatically * @see {@link firstSomeOf} to pick the first `Some` from a collection * - * @category Error handling + * @category error handling * @since 2.0.0 */ (that: LazyArg>): (self: Option) => Option @@ -872,10 +830,10 @@ export const orElse: { * * **When to use** * - * - Chaining fallback `Option` computations - * - Building priority chains of optional values + * Use when you need a lazy fallback `Option`, such as when building priority + * chains of optional values. * - * **Behavior** + * **Details** * * - `Some` → returns `self` unchanged * - `None` → evaluates and returns `that()` @@ -896,7 +854,7 @@ export const orElse: { * @see {@link orElseSome} to wrap the fallback value in `Some` automatically * @see {@link firstSomeOf} to pick the first `Some` from a collection * - * @category Error handling + * @category error handling * @since 2.0.0 */ (self: Option, that: LazyArg>): Option @@ -911,9 +869,9 @@ export const orElse: { * * **When to use** * - * - Providing a default plain value (not an `Option`) as fallback + * Use when providing a default plain value (not an `Option`) as fallback * - * **Behavior** + * **Details** * * - `Some` → returns `self` unchanged * - `None` → calls `onNone()`, wraps result in `Some`, and returns it @@ -932,7 +890,7 @@ export const orElse: { * * @see {@link orElse} when the fallback is itself an `Option` * - * @category Error handling + * @category error handling * @since 2.0.0 */ export const orElseSome: { @@ -942,9 +900,9 @@ export const orElseSome: { * * **When to use** * - * - Providing a default plain value (not an `Option`) as fallback + * Use when providing a default plain value (not an `Option`) as fallback * - * **Behavior** + * **Details** * * - `Some` → returns `self` unchanged * - `None` → calls `onNone()`, wraps result in `Some`, and returns it @@ -963,7 +921,7 @@ export const orElseSome: { * * @see {@link orElse} when the fallback is itself an `Option` * - * @category Error handling + * @category error handling * @since 2.0.0 */ (onNone: LazyArg): (self: Option) => Option @@ -973,9 +931,9 @@ export const orElseSome: { * * **When to use** * - * - Providing a default plain value (not an `Option`) as fallback + * Use when providing a default plain value (not an `Option`) as fallback * - * **Behavior** + * **Details** * * - `Some` → returns `self` unchanged * - `None` → calls `onNone()`, wraps result in `Some`, and returns it @@ -994,7 +952,7 @@ export const orElseSome: { * * @see {@link orElse} when the fallback is itself an `Option` * - * @category Error handling + * @category error handling * @since 2.0.0 */ (self: Option, onNone: LazyArg): Option @@ -1004,14 +962,14 @@ export const orElseSome: { ) /** - * Like {@link orElse}, but wraps the result in a `Result` to indicate the - * source of the value. + * Returns the first available value and marks whether it came from the fallback. * * **When to use** * - * - Distinguishing whether a value came from the primary or fallback `Option` + * Use when you need to know whether a present value came from the primary or + * fallback `Option`. * - * **Behavior** + * **Details** * * - `self` is `Some` → `Some(Result.fail(value))` (value from primary) * - `self` is `None`, `that()` is `Some` → `Some(Result.succeed(value))` (value from fallback) @@ -1031,19 +989,19 @@ export const orElseSome: { * * @see {@link orElse} for the simpler variant without source tracking * - * @category Error handling - * @since 2.0.0 + * @category error handling + * @since 4.0.0 */ export const orElseResult: { /** - * Like {@link orElse}, but wraps the result in a `Result` to indicate the - * source of the value. + * Returns the first available value and marks whether it came from the fallback. * * **When to use** * - * - Distinguishing whether a value came from the primary or fallback `Option` + * Use when you need to know whether a present value came from the primary or + * fallback `Option`. * - * **Behavior** + * **Details** * * - `self` is `Some` → `Some(Result.fail(value))` (value from primary) * - `self` is `None`, `that()` is `Some` → `Some(Result.succeed(value))` (value from fallback) @@ -1063,19 +1021,19 @@ export const orElseResult: { * * @see {@link orElse} for the simpler variant without source tracking * - * @category Error handling - * @since 2.0.0 + * @category error handling + * @since 4.0.0 */ (that: LazyArg>): (self: Option) => Option> /** - * Like {@link orElse}, but wraps the result in a `Result` to indicate the - * source of the value. + * Returns the first available value and marks whether it came from the fallback. * * **When to use** * - * - Distinguishing whether a value came from the primary or fallback `Option` + * Use when you need to know whether a present value came from the primary or + * fallback `Option`. * - * **Behavior** + * **Details** * * - `self` is `Some` → `Some(Result.fail(value))` (value from primary) * - `self` is `None`, `that()` is `Some` → `Some(Result.succeed(value))` (value from fallback) @@ -1095,8 +1053,8 @@ export const orElseResult: { * * @see {@link orElse} for the simpler variant without source tracking * - * @category Error handling - * @since 2.0.0 + * @category error handling + * @since 4.0.0 */ (self: Option, that: LazyArg>): Option> } = dual( @@ -1111,9 +1069,9 @@ export const orElseResult: { * * **When to use** * - * - Searching for the first available value in a priority list + * Use when you need the first available `Some` value from a priority list. * - * **Behavior** + * **Details** * * - Short-circuits on the first `Some` * - Returns `None` only when every element is `None` @@ -1133,7 +1091,7 @@ export const orElseResult: { * * @see {@link orElse} for a two-option fallback * - * @category Error handling + * @category error handling * @since 2.0.0 */ export const firstSomeOf = > = Iterable>>( @@ -1153,10 +1111,10 @@ export const firstSomeOf = > = Iterable`) @@ -1180,8 +1138,8 @@ export const firstSomeOf = > = Iterable( a: A @@ -1193,9 +1151,10 @@ export const fromNullishOr = ( * * **When to use** * - * - When `null` is a meaningful value but `undefined` means absent + * Use when you want to treat only `undefined` as absent while preserving `null` + * as a meaningful value. * - * **Behavior** + * **Details** * * - `undefined` → `None` * - Any other value (including `null`) → `Some` @@ -1218,7 +1177,7 @@ export const fromNullishOr = ( * @see {@link fromNullishOr} to treat both `null` and `undefined` as absent * @see {@link fromNullOr} to only treat `null` as absent * - * @category Conversions + * @category converting * @since 4.0.0 */ export const fromUndefinedOr = ( @@ -1231,9 +1190,10 @@ export const fromUndefinedOr = ( * * **When to use** * - * - When `undefined` is a meaningful value but `null` means absent + * Use when you want to treat only `null` as absent while preserving + * `undefined` as a meaningful value. * - * **Behavior** + * **Details** * * - `null` → `None` * - Any other value (including `undefined`) → `Some` @@ -1256,7 +1216,7 @@ export const fromUndefinedOr = ( * @see {@link fromNullishOr} to treat both `null` and `undefined` as absent * @see {@link fromUndefinedOr} to only treat `undefined` as absent * - * @category Conversions + * @category converting * @since 4.0.0 */ export const fromNullOr = ( @@ -1269,9 +1229,9 @@ export const fromNullOr = ( * * **When to use** * - * - Wrapping existing nullable-returning functions for use in `Option` pipelines + * Use to wrap existing nullable-returning functions for use in `Option` pipelines * - * **Behavior** + * **Details** * * - Calls the original function with the given arguments * - Wraps the result via {@link fromNullishOr} @@ -1298,8 +1258,8 @@ export const fromNullOr = ( * @see {@link fromNullishOr} for converting a single value * @see {@link liftThrowable} for functions that throw instead * - * @category Conversions - * @since 2.0.0 + * @category converting + * @since 4.0.0 */ export const liftNullishOr = , B>( f: (...a: A) => B @@ -1311,9 +1271,9 @@ export const liftNullishOr = , B>( * * **When to use** * - * - Interoping with APIs that use `null` for missing values + * Use when you need to pass absent `Option` values to APIs that expect `null`. * - * **Behavior** + * **Details** * * - `Some` → the inner value * - `None` → `null` @@ -1333,7 +1293,7 @@ export const liftNullishOr = , B>( * @see {@link getOrUndefined} to return `undefined` instead * @see {@link getOrElse} for a custom fallback * - * @category Getters + * @category getters * @since 2.0.0 */ export const getOrNull: (self: Option) => A | null = getOrElse(constNull) @@ -1343,9 +1303,10 @@ export const getOrNull: (self: Option) => A | null = getOrElse(constNull) * * **When to use** * - * - Interoping with APIs that use `undefined` for missing values + * Use when you need to pass absent `Option` values to APIs that expect + * `undefined`. * - * **Behavior** + * **Details** * * - `Some` → the inner value * - `None` → `undefined` @@ -1365,7 +1326,7 @@ export const getOrNull: (self: Option) => A | null = getOrElse(constNull) * @see {@link getOrNull} to return `null` instead * @see {@link getOrElse} for a custom fallback * - * @category Getters + * @category getters * @since 2.0.0 */ export const getOrUndefined: (self: Option) => A | undefined = getOrElse(constUndefined) @@ -1375,9 +1336,9 @@ export const getOrUndefined: (self: Option) => A | undefined = getOrElse(c * * **When to use** * - * - Wrapping exception-throwing APIs (e.g. `JSON.parse`) for safe usage + * Use to wrap exception-throwing APIs (e.g. `JSON.parse`) for safe usage * - * **Behavior** + * **Details** * * - If the function returns normally → `Some` with the result * - If the function throws → `None` (exception is swallowed) @@ -1398,7 +1359,7 @@ export const getOrUndefined: (self: Option) => A | undefined = getOrElse(c * * @see {@link liftNullishOr} for nullable-returning functions * - * @category Conversions + * @category converting * @since 2.0.0 */ export const liftThrowable = , B>( @@ -1417,10 +1378,10 @@ export const liftThrowable = , B>( * * **When to use** * - * - Fail-fast unwrapping when absence is unexpected - * - Providing a descriptive error for debugging + * Use when you need fail-fast unwrapping of an `Option` for unexpected absence + * and want to provide a descriptive debugging error. * - * **Behavior** + * **Details** * * - `Some` → returns the inner value * - `None` → throws the value returned by `onNone()` @@ -1440,7 +1401,7 @@ export const liftThrowable = , B>( * @see {@link getOrThrow} for a version with a default error * @see {@link getOrElse} for a non-throwing alternative * - * @category Conversions + * @category converting * @since 2.0.0 */ export const getOrThrowWith: { @@ -1449,10 +1410,10 @@ export const getOrThrowWith: { * * **When to use** * - * - Fail-fast unwrapping when absence is unexpected - * - Providing a descriptive error for debugging + * Use when you need fail-fast unwrapping of an `Option` for unexpected absence + * and want to provide a descriptive debugging error. * - * **Behavior** + * **Details** * * - `Some` → returns the inner value * - `None` → throws the value returned by `onNone()` @@ -1472,7 +1433,7 @@ export const getOrThrowWith: { * @see {@link getOrThrow} for a version with a default error * @see {@link getOrElse} for a non-throwing alternative * - * @category Conversions + * @category converting * @since 2.0.0 */ (onNone: () => unknown): (self: Option) => A @@ -1481,10 +1442,10 @@ export const getOrThrowWith: { * * **When to use** * - * - Fail-fast unwrapping when absence is unexpected - * - Providing a descriptive error for debugging + * Use when you need fail-fast unwrapping of an `Option` for unexpected absence + * and want to provide a descriptive debugging error. * - * **Behavior** + * **Details** * * - `Some` → returns the inner value * - `None` → throws the value returned by `onNone()` @@ -1504,7 +1465,7 @@ export const getOrThrowWith: { * @see {@link getOrThrow} for a version with a default error * @see {@link getOrElse} for a non-throwing alternative * - * @category Conversions + * @category converting * @since 2.0.0 */ (self: Option, onNone: () => unknown): A @@ -1520,9 +1481,10 @@ export const getOrThrowWith: { * * **When to use** * - * - Quick fail-fast unwrapping when a generic error is acceptable + * Use when you need quick fail-fast unwrapping of an `Option` and a generic + * error is acceptable. * - * **Behavior** + * **Details** * * - `Some` → returns the inner value * - `None` → throws `new Error("getOrThrow called on a None")` @@ -1542,7 +1504,7 @@ export const getOrThrowWith: { * @see {@link getOrThrowWith} for a custom error * @see {@link getOrElse} for a non-throwing alternative * - * @category Conversions + * @category converting * @since 2.0.0 */ export const getOrThrow: (self: Option) => A = getOrThrowWith(() => new Error("getOrThrow called on a None")) @@ -1553,14 +1515,13 @@ export const getOrThrow: (self: Option) => A = getOrThrowWith(() => new Er * * **When to use** * - * - Applying a pure transformation to an optional value - * - Chaining transformations in a pipeline + * Use to apply a pure transformation to an `Option`'s present value, especially + * when chaining transformations in a pipeline. * - * **Behavior** + * **Details** * * - `Some` → applies `f` and wraps the result in a new `Some` * - `None` → returns `None` unchanged - * - Does not mutate the input * * **Example** (Mapping over an Option) * @@ -1577,7 +1538,7 @@ export const getOrThrow: (self: Option) => A = getOrThrowWith(() => new Er * @see {@link flatMap} when `f` returns an `Option` * @see {@link as} to replace the value with a constant * - * @category Mapping + * @category mapping * @since 2.0.0 */ export const map: { @@ -1587,14 +1548,13 @@ export const map: { * * **When to use** * - * - Applying a pure transformation to an optional value - * - Chaining transformations in a pipeline + * Use to apply a pure transformation to an `Option`'s present value, especially + * when chaining transformations in a pipeline. * - * **Behavior** + * **Details** * * - `Some` → applies `f` and wraps the result in a new `Some` * - `None` → returns `None` unchanged - * - Does not mutate the input * * **Example** (Mapping over an Option) * @@ -1611,7 +1571,7 @@ export const map: { * @see {@link flatMap} when `f` returns an `Option` * @see {@link as} to replace the value with a constant * - * @category Mapping + * @category mapping * @since 2.0.0 */ (f: (a: A) => B): (self: Option) => Option @@ -1621,14 +1581,13 @@ export const map: { * * **When to use** * - * - Applying a pure transformation to an optional value - * - Chaining transformations in a pipeline + * Use to apply a pure transformation to an `Option`'s present value, especially + * when chaining transformations in a pipeline. * - * **Behavior** + * **Details** * * - `Some` → applies `f` and wraps the result in a new `Some` * - `None` → returns `None` unchanged - * - Does not mutate the input * * **Example** (Mapping over an Option) * @@ -1645,7 +1604,7 @@ export const map: { * @see {@link flatMap} when `f` returns an `Option` * @see {@link as} to replace the value with a constant * - * @category Mapping + * @category mapping * @since 2.0.0 */ (self: Option, f: (a: A) => B): Option @@ -1659,12 +1618,8 @@ export const map: { * * **When to use** * - * - Preserving presence/absence while discarding the original value - * - * **Behavior** - * - * - `Some` → `Some(b)` - * - `None` → `None` + * Use when you need to replace a present `Option` value while preserving + * whether it was `Some` or `None`. * * **Example** (Replacing a value) * @@ -1681,7 +1636,7 @@ export const map: { * @see {@link asVoid} to replace with `undefined` * @see {@link map} for a general transformation * - * @category Mapping + * @category mapping * @since 2.0.0 */ export const as: { @@ -1690,12 +1645,8 @@ export const as: { * * **When to use** * - * - Preserving presence/absence while discarding the original value - * - * **Behavior** - * - * - `Some` → `Some(b)` - * - `None` → `None` + * Use when you need to replace a present `Option` value while preserving + * whether it was `Some` or `None`. * * **Example** (Replacing a value) * @@ -1712,7 +1663,7 @@ export const as: { * @see {@link asVoid} to replace with `undefined` * @see {@link map} for a general transformation * - * @category Mapping + * @category mapping * @since 2.0.0 */ (b: B): (self: Option) => Option @@ -1721,12 +1672,8 @@ export const as: { * * **When to use** * - * - Preserving presence/absence while discarding the original value - * - * **Behavior** - * - * - `Some` → `Some(b)` - * - `None` → `None` + * Use when you need to replace a present `Option` value while preserving + * whether it was `Some` or `None`. * * **Example** (Replacing a value) * @@ -1743,7 +1690,7 @@ export const as: { * @see {@link asVoid} to replace with `undefined` * @see {@link map} for a general transformation * - * @category Mapping + * @category mapping * @since 2.0.0 */ (self: Option, b: B): Option @@ -1755,12 +1702,8 @@ export const as: { * * **When to use** * - * - Discarding the value while preserving presence/absence - * - * **Behavior** - * - * - `Some` → `Some(undefined)` - * - `None` → `None` + * Use when you need to discard a present `Option` value while preserving + * whether it was `Some` or `None`. * * **Example** (Voiding the value) * @@ -1776,7 +1719,7 @@ export const as: { * * @see {@link as} to replace with a specific constant * - * @category Mapping + * @category mapping * @since 2.0.0 */ export const asVoid: <_>(self: Option<_>) => Option = as(undefined) @@ -1784,11 +1727,11 @@ export const asVoid: <_>(self: Option<_>) => Option = as(undefined) const void_: Option = some(undefined) export { /** - * A pre-built `Some(undefined)` constant. + * Provides a pre-built `Some(undefined)` constant. * * **When to use** * - * - Returning a "success with no meaningful value" from an `Option`-returning function + * Use to return a "success with no meaningful value" from an `Option`-returning function * * **Example** (Using Option.void) * @@ -1801,7 +1744,7 @@ export { * * @see {@link asVoid} to convert an existing `Option` to `Option` * - * @category Constructors + * @category constructors * @since 2.0.0 */ void_ as void @@ -1813,10 +1756,10 @@ export { * * **When to use** * - * - Chaining computations that each may fail (return `None`) - * - Sequencing dependent optional operations + * Use when you need to chain dependent `Option` computations where each step + * may return `None`. * - * **Behavior** + * **Details** * * - `Some` → applies `f` to the value and returns its `Option` result * - `None` → returns `None` without calling `f` @@ -1849,7 +1792,7 @@ export { * @see {@link andThen} for a more flexible variant * @see {@link flatten} to unwrap a nested `Option>` * - * @category Sequencing + * @category sequencing * @since 2.0.0 */ export const flatMap: { @@ -1859,10 +1802,10 @@ export const flatMap: { * * **When to use** * - * - Chaining computations that each may fail (return `None`) - * - Sequencing dependent optional operations + * Use when you need to chain dependent `Option` computations where each step + * may return `None`. * - * **Behavior** + * **Details** * * - `Some` → applies `f` to the value and returns its `Option` result * - `None` → returns `None` without calling `f` @@ -1895,7 +1838,7 @@ export const flatMap: { * @see {@link andThen} for a more flexible variant * @see {@link flatten} to unwrap a nested `Option>` * - * @category Sequencing + * @category sequencing * @since 2.0.0 */ (f: (a: A) => Option): (self: Option) => Option @@ -1905,10 +1848,10 @@ export const flatMap: { * * **When to use** * - * - Chaining computations that each may fail (return `None`) - * - Sequencing dependent optional operations + * Use when you need to chain dependent `Option` computations where each step + * may return `None`. * - * **Behavior** + * **Details** * * - `Some` → applies `f` to the value and returns its `Option` result * - `None` → returns `None` without calling `f` @@ -1941,7 +1884,7 @@ export const flatMap: { * @see {@link andThen} for a more flexible variant * @see {@link flatten} to unwrap a nested `Option>` * - * @category Sequencing + * @category sequencing * @since 2.0.0 */ (self: Option, f: (a: A) => Option): Option @@ -1956,10 +1899,10 @@ export const flatMap: { * * **When to use** * - * - Flexible chaining where the next step may return `Option`, a plain value, - * or a function + * Use when you need to chain an `Option` with a next step that may be another + * `Option`, a plain value, or a function. * - * **Behavior** + * **Details** * * - If `self` is `None`, returns `None` immediately * - If `f` is a function, calls it with the `Some` value @@ -1987,7 +1930,7 @@ export const flatMap: { * @see {@link flatMap} for the standard monadic bind * @see {@link map} when you always return a plain value * - * @category Sequencing + * @category sequencing * @since 2.0.0 */ export const andThen: { @@ -1997,10 +1940,10 @@ export const andThen: { * * **When to use** * - * - Flexible chaining where the next step may return `Option`, a plain value, - * or a function + * Use when you need to chain an `Option` with a next step that may be another + * `Option`, a plain value, or a function. * - * **Behavior** + * **Details** * * - If `self` is `None`, returns `None` immediately * - If `f` is a function, calls it with the `Some` value @@ -2028,7 +1971,7 @@ export const andThen: { * @see {@link flatMap} for the standard monadic bind * @see {@link map} when you always return a plain value * - * @category Sequencing + * @category sequencing * @since 2.0.0 */ (f: (a: A) => Option): (self: Option) => Option @@ -2038,10 +1981,10 @@ export const andThen: { * * **When to use** * - * - Flexible chaining where the next step may return `Option`, a plain value, - * or a function + * Use when you need to chain an `Option` with a next step that may be another + * `Option`, a plain value, or a function. * - * **Behavior** + * **Details** * * - If `self` is `None`, returns `None` immediately * - If `f` is a function, calls it with the `Some` value @@ -2069,7 +2012,7 @@ export const andThen: { * @see {@link flatMap} for the standard monadic bind * @see {@link map} when you always return a plain value * - * @category Sequencing + * @category sequencing * @since 2.0.0 */ (f: Option): (self: Option) => Option @@ -2079,10 +2022,10 @@ export const andThen: { * * **When to use** * - * - Flexible chaining where the next step may return `Option`, a plain value, - * or a function + * Use when you need to chain an `Option` with a next step that may be another + * `Option`, a plain value, or a function. * - * **Behavior** + * **Details** * * - If `self` is `None`, returns `None` immediately * - If `f` is a function, calls it with the `Some` value @@ -2110,7 +2053,7 @@ export const andThen: { * @see {@link flatMap} for the standard monadic bind * @see {@link map} when you always return a plain value * - * @category Sequencing + * @category sequencing * @since 2.0.0 */ (f: (a: A) => B): (self: Option) => Option @@ -2120,10 +2063,10 @@ export const andThen: { * * **When to use** * - * - Flexible chaining where the next step may return `Option`, a plain value, - * or a function + * Use when you need to chain an `Option` with a next step that may be another + * `Option`, a plain value, or a function. * - * **Behavior** + * **Details** * * - If `self` is `None`, returns `None` immediately * - If `f` is a function, calls it with the `Some` value @@ -2151,7 +2094,7 @@ export const andThen: { * @see {@link flatMap} for the standard monadic bind * @see {@link map} when you always return a plain value * - * @category Sequencing + * @category sequencing * @since 2.0.0 */ (f: NotFunction): (self: Option) => Option @@ -2161,10 +2104,10 @@ export const andThen: { * * **When to use** * - * - Flexible chaining where the next step may return `Option`, a plain value, - * or a function + * Use when you need to chain an `Option` with a next step that may be another + * `Option`, a plain value, or a function. * - * **Behavior** + * **Details** * * - If `self` is `None`, returns `None` immediately * - If `f` is a function, calls it with the `Some` value @@ -2192,7 +2135,7 @@ export const andThen: { * @see {@link flatMap} for the standard monadic bind * @see {@link map} when you always return a plain value * - * @category Sequencing + * @category sequencing * @since 2.0.0 */ (self: Option, f: (a: A) => Option): Option @@ -2202,10 +2145,10 @@ export const andThen: { * * **When to use** * - * - Flexible chaining where the next step may return `Option`, a plain value, - * or a function + * Use when you need to chain an `Option` with a next step that may be another + * `Option`, a plain value, or a function. * - * **Behavior** + * **Details** * * - If `self` is `None`, returns `None` immediately * - If `f` is a function, calls it with the `Some` value @@ -2233,7 +2176,7 @@ export const andThen: { * @see {@link flatMap} for the standard monadic bind * @see {@link map} when you always return a plain value * - * @category Sequencing + * @category sequencing * @since 2.0.0 */ (self: Option, f: Option): Option @@ -2243,10 +2186,10 @@ export const andThen: { * * **When to use** * - * - Flexible chaining where the next step may return `Option`, a plain value, - * or a function + * Use when you need to chain an `Option` with a next step that may be another + * `Option`, a plain value, or a function. * - * **Behavior** + * **Details** * * - If `self` is `None`, returns `None` immediately * - If `f` is a function, calls it with the `Some` value @@ -2274,7 +2217,7 @@ export const andThen: { * @see {@link flatMap} for the standard monadic bind * @see {@link map} when you always return a plain value * - * @category Sequencing + * @category sequencing * @since 2.0.0 */ (self: Option, f: (a: A) => B): Option @@ -2284,10 +2227,10 @@ export const andThen: { * * **When to use** * - * - Flexible chaining where the next step may return `Option`, a plain value, - * or a function + * Use when you need to chain an `Option` with a next step that may be another + * `Option`, a plain value, or a function. * - * **Behavior** + * **Details** * * - If `self` is `None`, returns `None` immediately * - If `f` is a function, calls it with the `Some` value @@ -2315,7 +2258,7 @@ export const andThen: { * @see {@link flatMap} for the standard monadic bind * @see {@link map} when you always return a plain value * - * @category Sequencing + * @category sequencing * @since 2.0.0 */ (self: Option, f: NotFunction): Option @@ -2334,10 +2277,10 @@ export const andThen: { * * **When to use** * - * - Chaining with functions that use `null`/`undefined` instead of `Option` - * - Navigating deeply nested optional properties + * Use when you need to chain optional computations that use `null` or + * `undefined` instead of `Option`, such as nested property access. * - * **Behavior** + * **Details** * * - `None` → `None` * - `Some` → applies `f`, then wraps via {@link fromNullishOr} @@ -2366,8 +2309,8 @@ export const andThen: { * @see {@link flatMap} when the function already returns `Option` * @see {@link fromNullishOr} for single-value conversion * - * @category Sequencing - * @since 2.0.0 + * @category sequencing + * @since 4.0.0 */ export const flatMapNullishOr: { /** @@ -2376,10 +2319,10 @@ export const flatMapNullishOr: { * * **When to use** * - * - Chaining with functions that use `null`/`undefined` instead of `Option` - * - Navigating deeply nested optional properties + * Use when you need to chain optional computations that use `null` or + * `undefined` instead of `Option`, such as nested property access. * - * **Behavior** + * **Details** * * - `None` → `None` * - `Some` → applies `f`, then wraps via {@link fromNullishOr} @@ -2408,8 +2351,8 @@ export const flatMapNullishOr: { * @see {@link flatMap} when the function already returns `Option` * @see {@link fromNullishOr} for single-value conversion * - * @category Sequencing - * @since 2.0.0 + * @category sequencing + * @since 4.0.0 */ (f: (a: A) => B): (self: Option) => Option> /** @@ -2418,10 +2361,10 @@ export const flatMapNullishOr: { * * **When to use** * - * - Chaining with functions that use `null`/`undefined` instead of `Option` - * - Navigating deeply nested optional properties + * Use when you need to chain optional computations that use `null` or + * `undefined` instead of `Option`, such as nested property access. * - * **Behavior** + * **Details** * * - `None` → `None` * - `Some` → applies `f`, then wraps via {@link fromNullishOr} @@ -2450,8 +2393,8 @@ export const flatMapNullishOr: { * @see {@link flatMap} when the function already returns `Option` * @see {@link fromNullishOr} for single-value conversion * - * @category Sequencing - * @since 2.0.0 + * @category sequencing + * @since 4.0.0 */ (self: Option, f: (a: A) => B): Option> } = dual( @@ -2465,9 +2408,9 @@ export const flatMapNullishOr: { * * **When to use** * - * - Removing one layer of `Option` nesting + * Use when you need to remove one layer of nested `Option`. * - * **Behavior** + * **Details** * * - `Some(Some(value))` → `Some(value)` * - `Some(None)` → `None` @@ -2487,7 +2430,7 @@ export const flatMapNullishOr: { * * @see {@link flatMap} which is `map` + `flatten` * - * @category Sequencing + * @category sequencing * @since 2.0.0 */ export const flatten: (self: Option>) => Option = flatMap(identity) @@ -2497,9 +2440,10 @@ export const flatten: (self: Option>) => Option = flatMap(identi * * **When to use** * - * - Running a side-condition that must succeed, then using the second value + * Use when you need two `Option` values to both be `Some`, then keep only the + * second value. * - * **Behavior** + * **Details** * * - Both `Some` → returns `that` * - Either `None` → returns `None` @@ -2519,7 +2463,7 @@ export const flatten: (self: Option>) => Option = flatMap(identi * @see {@link zipLeft} to keep the first value instead * @see {@link zipWith} to combine both values * - * @category Zipping + * @category zipping * @since 2.0.0 */ export const zipRight: { @@ -2528,9 +2472,10 @@ export const zipRight: { * * **When to use** * - * - Running a side-condition that must succeed, then using the second value + * Use when you need two `Option` values to both be `Some`, then keep only the + * second value. * - * **Behavior** + * **Details** * * - Both `Some` → returns `that` * - Either `None` → returns `None` @@ -2550,7 +2495,7 @@ export const zipRight: { * @see {@link zipLeft} to keep the first value instead * @see {@link zipWith} to combine both values * - * @category Zipping + * @category zipping * @since 2.0.0 */ (that: Option): <_>(self: Option<_>) => Option @@ -2559,9 +2504,10 @@ export const zipRight: { * * **When to use** * - * - Running a side-condition that must succeed, then using the second value + * Use when you need two `Option` values to both be `Some`, then keep only the + * second value. * - * **Behavior** + * **Details** * * - Both `Some` → returns `that` * - Either `None` → returns `None` @@ -2581,7 +2527,7 @@ export const zipRight: { * @see {@link zipLeft} to keep the first value instead * @see {@link zipWith} to combine both values * - * @category Zipping + * @category zipping * @since 2.0.0 */ (self: Option, that: Option): Option @@ -2592,9 +2538,10 @@ export const zipRight: { * * **When to use** * - * - Running a validation that must succeed, but keeping the original value + * Use when you need two `Option` values to both be `Some`, then keep only the + * first value. * - * **Behavior** + * **Details** * * - Both `Some` → returns `self` * - Either `None` → returns `None` @@ -2614,7 +2561,7 @@ export const zipRight: { * @see {@link zipRight} to keep the second value instead * @see {@link zipWith} to combine both values * - * @category Zipping + * @category zipping * @since 2.0.0 */ export const zipLeft: { @@ -2623,9 +2570,10 @@ export const zipLeft: { * * **When to use** * - * - Running a validation that must succeed, but keeping the original value + * Use when you need two `Option` values to both be `Some`, then keep only the + * first value. * - * **Behavior** + * **Details** * * - Both `Some` → returns `self` * - Either `None` → returns `None` @@ -2645,7 +2593,7 @@ export const zipLeft: { * @see {@link zipRight} to keep the second value instead * @see {@link zipWith} to combine both values * - * @category Zipping + * @category zipping * @since 2.0.0 */ <_>(that: Option<_>): (self: Option) => Option @@ -2654,9 +2602,10 @@ export const zipLeft: { * * **When to use** * - * - Running a validation that must succeed, but keeping the original value + * Use when you need two `Option` values to both be `Some`, then keep only the + * first value. * - * **Behavior** + * **Details** * * - Both `Some` → returns `self` * - Either `None` → returns `None` @@ -2676,7 +2625,7 @@ export const zipLeft: { * @see {@link zipRight} to keep the second value instead * @see {@link zipWith} to combine both values * - * @category Zipping + * @category zipping * @since 2.0.0 */ (self: Option, that: Option): Option @@ -2688,9 +2637,10 @@ export const zipLeft: { * * **When to use** * - * - Building pipelines of partial functions (Kleisli composition) + * Use when you need to compose two functions that each return an `Option`, so + * `None` short-circuits without calling the next function. * - * **Behavior** + * **Details** * * - Calls `afb(a)`, then if `Some`, calls `bfc` with its value * - Short-circuits to `None` if either function returns `None` @@ -2717,7 +2667,7 @@ export const zipLeft: { * * @see {@link flatMap} for single-step chaining * - * @category Sequencing + * @category sequencing * @since 2.0.0 */ export const composeK: { @@ -2727,9 +2677,10 @@ export const composeK: { * * **When to use** * - * - Building pipelines of partial functions (Kleisli composition) + * Use when you need to compose two functions that each return an `Option`, so + * `None` short-circuits without calling the next function. * - * **Behavior** + * **Details** * * - Calls `afb(a)`, then if `Some`, calls `bfc` with its value * - Short-circuits to `None` if either function returns `None` @@ -2756,7 +2707,7 @@ export const composeK: { * * @see {@link flatMap} for single-step chaining * - * @category Sequencing + * @category sequencing * @since 2.0.0 */ (bfc: (b: B) => Option): (afb: (a: A) => Option) => (a: A) => Option @@ -2766,9 +2717,10 @@ export const composeK: { * * **When to use** * - * - Building pipelines of partial functions (Kleisli composition) + * Use when you need to compose two functions that each return an `Option`, so + * `None` short-circuits without calling the next function. * - * **Behavior** + * **Details** * * - Calls `afb(a)`, then if `Some`, calls `bfc` with its value * - Short-circuits to `None` if either function returns `None` @@ -2795,7 +2747,7 @@ export const composeK: { * * @see {@link flatMap} for single-step chaining * - * @category Sequencing + * @category sequencing * @since 2.0.0 */ (afb: (a: A) => Option, bfc: (b: B) => Option): (a: A) => Option @@ -2808,10 +2760,10 @@ export const composeK: { * * **When to use** * - * - Validating a value without transforming it - * - Adding a side-condition check in a pipeline + * Use to validate an `Option`'s present value without transforming it, such as + * adding a side-condition check in a pipeline. * - * **Behavior** + * **Details** * * - `None` → `None` * - `Some` → calls `f(value)`; if result is `Some`, returns original `self`; if `None`, returns `None` @@ -2834,7 +2786,7 @@ export const composeK: { * @see {@link flatMap} when you want to transform the value * @see {@link filter} for predicate-based filtering * - * @category Sequencing + * @category sequencing * @since 2.0.0 */ export const tap: { @@ -2845,10 +2797,10 @@ export const tap: { * * **When to use** * - * - Validating a value without transforming it - * - Adding a side-condition check in a pipeline + * Use to validate an `Option`'s present value without transforming it, such as + * adding a side-condition check in a pipeline. * - * **Behavior** + * **Details** * * - `None` → `None` * - `Some` → calls `f(value)`; if result is `Some`, returns original `self`; if `None`, returns `None` @@ -2871,7 +2823,7 @@ export const tap: { * @see {@link flatMap} when you want to transform the value * @see {@link filter} for predicate-based filtering * - * @category Sequencing + * @category sequencing * @since 2.0.0 */ (f: (a: A) => Option): (self: Option) => Option @@ -2882,10 +2834,10 @@ export const tap: { * * **When to use** * - * - Validating a value without transforming it - * - Adding a side-condition check in a pipeline + * Use to validate an `Option`'s present value without transforming it, such as + * adding a side-condition check in a pipeline. * - * **Behavior** + * **Details** * * - `None` → `None` * - `Some` → calls `f(value)`; if result is `Some`, returns original `self`; if `None`, returns `None` @@ -2908,7 +2860,7 @@ export const tap: { * @see {@link flatMap} when you want to transform the value * @see {@link filter} for predicate-based filtering * - * @category Sequencing + * @category sequencing * @since 2.0.0 */ (self: Option, f: (a: A) => Option): Option @@ -2920,9 +2872,10 @@ export const tap: { * * **When to use** * - * - Pairing two optional values together + * Use when you need to require two `Option` values to both be `Some` and keep + * both values as a tuple. * - * **Behavior** + * **Details** * * - Both `Some` → `Some([a, b])` * - Either `None` → `None` @@ -2942,7 +2895,7 @@ export const tap: { * @see {@link zipWith} to combine with a function instead of a tuple * @see {@link all} to combine many `Option`s * - * @category Combining + * @category combining * @since 2.0.0 */ export const product = (self: Option, that: Option): Option<[A, B]> => @@ -2954,9 +2907,10 @@ export const product = (self: Option, that: Option): Option<[A, B]> * * **When to use** * - * - Collecting several `Option`s of the same type into a non-empty tuple + * Use when you need several `Option` values of the same type to all be `Some` + * and return them as a non-empty tuple. * - * **Behavior** + * **Details** * * - All `Some` → `Some([self.value, ...rest])` * - Any `None` → `None` @@ -2979,7 +2933,7 @@ export const product = (self: Option, that: Option): Option<[A, B]> * @see {@link product} for combining exactly two * @see {@link all} for tuples, structs, and iterables * - * @category Combining + * @category combining * @since 2.0.0 */ export const productMany = ( @@ -3005,10 +2959,10 @@ export const productMany = ( * * **When to use** * - * - Collecting multiple `Option`s into one, preserving the input shape - * - "All or nothing" combination — any `None` makes the result `None` + * Use when you need to combine multiple `Option` values into one while + * preserving the input shape, with any `None` making the result `None`. * - * **Behavior** + * **Details** * * - Tuple input → `Option` of a tuple with the same length * - Struct input → `Option` of a struct with the same keys @@ -3041,7 +2995,7 @@ export const productMany = ( * @see {@link product} for combining exactly two * @see {@link productMany} for a homogeneous collection * - * @category Combining + * @category combining * @since 2.0.0 */ // @ts-expect-error @@ -3081,9 +3035,10 @@ export const all: > | Record> | Record(that: Option, f: (a: A, b: B) => C): (self: Option) => Option @@ -3151,9 +3107,10 @@ export const zipWith: { * * **When to use** * - * - Merging two optional values into a computed result + * Use when you need to combine two present `Option` values into a computed + * result. * - * **Behavior** + * **Details** * * - Both `Some` → applies `f(a, b)` and wraps in `Some` * - Either `None` → `None` @@ -3177,7 +3134,7 @@ export const zipWith: { * @see {@link product} to combine into a tuple instead * @see {@link lift2} to lift a binary function * - * @category Zipping + * @category zipping * @since 2.0.0 */ (self: Option, that: Option, f: (a: A, b: B) => C): Option @@ -3192,9 +3149,10 @@ export const zipWith: { * * **When to use** * - * - Aggregating values from a collection where some may be absent + * Use when you need to aggregate values from a collection where some may be + * absent. * - * **Behavior** + * **Details** * * - Iterates through the collection, applying `f` only to `Some` values * - `None` values are skipped entirely @@ -3211,7 +3169,7 @@ export const zipWith: { * // Output: 3 * ``` * - * @category Reducing + * @category reducing * @since 2.0.0 */ export const reduceCompact: { @@ -3220,9 +3178,10 @@ export const reduceCompact: { * * **When to use** * - * - Aggregating values from a collection where some may be absent + * Use when you need to aggregate values from a collection where some may be + * absent. * - * **Behavior** + * **Details** * * - Iterates through the collection, applying `f` only to `Some` values * - `None` values are skipped entirely @@ -3239,7 +3198,7 @@ export const reduceCompact: { * // Output: 3 * ``` * - * @category Reducing + * @category reducing * @since 2.0.0 */ (b: B, f: (b: B, a: A) => B): (self: Iterable>) => B @@ -3248,9 +3207,10 @@ export const reduceCompact: { * * **When to use** * - * - Aggregating values from a collection where some may be absent + * Use when you need to aggregate values from a collection where some may be + * absent. * - * **Behavior** + * **Details** * * - Iterates through the collection, applying `f` only to `Some` values * - `None` values are skipped entirely @@ -3267,7 +3227,7 @@ export const reduceCompact: { * // Output: 3 * ``` * - * @category Reducing + * @category reducing * @since 2.0.0 */ (self: Iterable>, b: B, f: (b: B, a: A) => B): B @@ -3289,10 +3249,10 @@ export const reduceCompact: { * * **When to use** * - * - Interfacing with array-based APIs - * - Spreading optional values into collections + * Use when you need to pass an `Option` to array-based APIs or spread optional + * values into collections. * - * **Behavior** + * **Details** * * - `Some` → single-element array `[value]` * - `None` → empty array `[]` @@ -3311,7 +3271,7 @@ export const reduceCompact: { * * @see {@link fromIterable} for the inverse direction * - * @category Conversions + * @category converting * @since 2.0.0 */ export const toArray = (self: Option): Array => isNone(self) ? [] : [self.value] @@ -3321,9 +3281,10 @@ export const toArray = (self: Option): Array => isNone(self) ? [] : [se * * **When to use** * - * - Categorizing an optional value into "left" (failure) and "right" (success) channels + * Use when you need to split an optional value into "left" and "right" + * channels using a `Result`-returning function. * - * **Behavior** + * **Details** * * - `None` → `[None, None]` * - `Some` where `f` returns `Err` → `[Some(error), None]` @@ -3351,7 +3312,7 @@ export const toArray = (self: Option): Array => isNone(self) ? [] : [se * * @see {@link filter} for simple predicate-based filtering * - * @category Filtering + * @category filtering * @since 2.0.0 */ export const partitionMap: { @@ -3360,9 +3321,10 @@ export const partitionMap: { * * **When to use** * - * - Categorizing an optional value into "left" (failure) and "right" (success) channels + * Use when you need to split an optional value into "left" and "right" + * channels using a `Result`-returning function. * - * **Behavior** + * **Details** * * - `None` → `[None, None]` * - `Some` where `f` returns `Err` → `[Some(error), None]` @@ -3390,7 +3352,7 @@ export const partitionMap: { * * @see {@link filter} for simple predicate-based filtering * - * @category Filtering + * @category filtering * @since 2.0.0 */ (f: (a: A) => Result): (self: Option) => [left: Option, right: Option] @@ -3399,9 +3361,10 @@ export const partitionMap: { * * **When to use** * - * - Categorizing an optional value into "left" (failure) and "right" (success) channels + * Use when you need to split an optional value into "left" and "right" + * channels using a `Result`-returning function. * - * **Behavior** + * **Details** * * - `None` → `[None, None]` * - `Some` where `f` returns `Err` → `[Some(error), None]` @@ -3429,7 +3392,7 @@ export const partitionMap: { * * @see {@link filter} for simple predicate-based filtering * - * @category Filtering + * @category filtering * @since 2.0.0 */ (self: Option, f: (a: A) => Result): [left: Option, right: Option] @@ -3447,14 +3410,20 @@ export const partitionMap: { /** * Transforms and filters an `Option` using a `Filter` callback. * + * **When to use** + * + * Use to transform an `Option`'s present value and discard it when the `Filter` + * fails. + * + * **Details** + * * The callback returns a `Result`: `Result.succeed` keeps and transforms the * value, while `Result.fail` discards it. * * **Example** (Filtering and transforming) * * ```ts - * import { Option } from "effect" - * import * as Result from "effect/Result" + * import { Option, Result } from "effect" * * console.log(Option.filterMap( * Option.some(2), @@ -3465,21 +3434,27 @@ export const partitionMap: { * * @see {@link filter} for predicate-based filtering * - * @category Filtering + * @category filtering * @since 2.0.0 */ export const filterMap: { /** * Transforms and filters an `Option` using a `Filter` callback. * + * **When to use** + * + * Use to transform an `Option`'s present value and discard it when the `Filter` + * fails. + * + * **Details** + * * The callback returns a `Result`: `Result.succeed` keeps and transforms the * value, while `Result.fail` discards it. * * **Example** (Filtering and transforming) * * ```ts - * import { Option } from "effect" - * import * as Result from "effect/Result" + * import { Option, Result } from "effect" * * console.log(Option.filterMap( * Option.some(2), @@ -3490,21 +3465,27 @@ export const filterMap: { * * @see {@link filter} for predicate-based filtering * - * @category Filtering + * @category filtering * @since 2.0.0 */ (f: Filter.Filter): (self: Option) => Option /** * Transforms and filters an `Option` using a `Filter` callback. * + * **When to use** + * + * Use to transform an `Option`'s present value and discard it when the `Filter` + * fails. + * + * **Details** + * * The callback returns a `Result`: `Result.succeed` keeps and transforms the * value, while `Result.fail` discards it. * * **Example** (Filtering and transforming) * * ```ts - * import { Option } from "effect" - * import * as Result from "effect/Result" + * import { Option, Result } from "effect" * * console.log(Option.filterMap( * Option.some(2), @@ -3515,7 +3496,7 @@ export const filterMap: { * * @see {@link filter} for predicate-based filtering * - * @category Filtering + * @category filtering * @since 2.0.0 */ (self: Option, f: Filter.Filter): Option @@ -3533,10 +3514,10 @@ export const filterMap: { * * **When to use** * - * - Discarding values that don't meet a condition - * - Narrowing the type via a refinement predicate + * Use when you need to discard an `Option`'s present value when it does not + * meet a condition, while narrowing the type via a refinement predicate. * - * **Behavior** + * **Details** * * - `None` → `None` * - `Some` where `predicate(value)` is `true` → `Some(value)` @@ -3564,7 +3545,7 @@ export const filterMap: { * @see {@link filterMap} to transform and filter simultaneously * @see {@link exists} to test without filtering * - * @category Filtering + * @category filtering * @since 2.0.0 */ export const filter: { @@ -3574,10 +3555,10 @@ export const filter: { * * **When to use** * - * - Discarding values that don't meet a condition - * - Narrowing the type via a refinement predicate + * Use when you need to discard an `Option`'s present value when it does not + * meet a condition, while narrowing the type via a refinement predicate. * - * **Behavior** + * **Details** * * - `None` → `None` * - `Some` where `predicate(value)` is `true` → `Some(value)` @@ -3605,7 +3586,7 @@ export const filter: { * @see {@link filterMap} to transform and filter simultaneously * @see {@link exists} to test without filtering * - * @category Filtering + * @category filtering * @since 2.0.0 */ (refinement: Refinement): (self: Option) => Option @@ -3615,10 +3596,10 @@ export const filter: { * * **When to use** * - * - Discarding values that don't meet a condition - * - Narrowing the type via a refinement predicate + * Use when you need to discard an `Option`'s present value when it does not + * meet a condition, while narrowing the type via a refinement predicate. * - * **Behavior** + * **Details** * * - `None` → `None` * - `Some` where `predicate(value)` is `true` → `Some(value)` @@ -3646,7 +3627,7 @@ export const filter: { * @see {@link filterMap} to transform and filter simultaneously * @see {@link exists} to test without filtering * - * @category Filtering + * @category filtering * @since 2.0.0 */ (predicate: Predicate): (self: Option) => Option @@ -3656,10 +3637,10 @@ export const filter: { * * **When to use** * - * - Discarding values that don't meet a condition - * - Narrowing the type via a refinement predicate + * Use when you need to discard an `Option`'s present value when it does not + * meet a condition, while narrowing the type via a refinement predicate. * - * **Behavior** + * **Details** * * - `None` → `None` * - `Some` where `predicate(value)` is `true` → `Some(value)` @@ -3687,7 +3668,7 @@ export const filter: { * @see {@link filterMap} to transform and filter simultaneously * @see {@link exists} to test without filtering * - * @category Filtering + * @category filtering * @since 2.0.0 */ (self: Option, refinement: Refinement): Option @@ -3697,10 +3678,10 @@ export const filter: { * * **When to use** * - * - Discarding values that don't meet a condition - * - Narrowing the type via a refinement predicate + * Use when you need to discard an `Option`'s present value when it does not + * meet a condition, while narrowing the type via a refinement predicate. * - * **Behavior** + * **Details** * * - `None` → `None` * - `Some` where `predicate(value)` is `true` → `Some(value)` @@ -3728,7 +3709,7 @@ export const filter: { * @see {@link filterMap} to transform and filter simultaneously * @see {@link exists} to test without filtering * - * @category Filtering + * @category filtering * @since 2.0.0 */ (self: Option, predicate: Predicate): Option @@ -3743,9 +3724,10 @@ export const filter: { * * **When to use** * - * - Comparing two `Option` values for structural equality + * Use when you need equality to treat two `None` values as equal and compare + * two `Some` values with a supplied equality rule. * - * **Behavior** + * **Details** * * - `None` vs `None` → `true` * - `Some` vs `None` (or vice versa) → `false` @@ -3768,8 +3750,8 @@ export const filter: { * // Output: true * ``` * - * @category Equivalence - * @since 2.0.0 + * @category instances + * @since 4.0.0 */ export const makeEquivalence = (isEquivalent: Equivalence.Equivalence): Equivalence.Equivalence> => Equivalence.make((x, y) => isNone(x) ? isNone(y) : isNone(y) ? false : isEquivalent(x.value, y.value)) @@ -3779,9 +3761,11 @@ export const makeEquivalence = (isEquivalent: Equivalence.Equivalence): Eq * * **When to use** * - * - Sorting collections of `Option` values + * Use when you need to sort `Some` and `None` values, with `None` ordered + * before present values and present values compared by a supplied ordering + * rule. * - * **Behavior** + * **Details** * * - `None` is considered less than any `Some` * - Two `Some` values are compared using the provided `Order` @@ -3790,8 +3774,7 @@ export const makeEquivalence = (isEquivalent: Equivalence.Equivalence): Eq * **Example** (Ordering Options) * * ```ts - * import { Option } from "effect" - * import * as N from "effect/Number" + * import { Number as N, Option } from "effect" * * const ord = Option.makeOrder(N.Order) * @@ -3805,8 +3788,8 @@ export const makeEquivalence = (isEquivalent: Equivalence.Equivalence): Eq * // Output: -1 * ``` * - * @category Sorting - * @since 2.0.0 + * @category sorting + * @since 4.0.0 */ export const makeOrder = (O: Order): Order> => order.make((self, that) => isSome(self) ? (isSome(that) ? O(self.value, that.value) : 1) : -1) @@ -3816,9 +3799,10 @@ export const makeOrder = (O: Order): Order> => * * **When to use** * - * - Reusing an existing binary function in an `Option` context + * Use when you need to reuse an existing binary function with two `Option` + * values. * - * **Behavior** + * **Details** * * - Both `Some` → applies `f` and wraps in `Some` * - Either `None` → `None` @@ -3839,7 +3823,7 @@ export const makeOrder = (O: Order): Order> => * * @see {@link zipWith} for a non-lifted variant * - * @category Lifting + * @category lifting * @since 2.0.0 */ export const lift2 = (f: (a: A, b: B) => C): { @@ -3853,10 +3837,10 @@ export const lift2 = (f: (a: A, b: B) => C): { * * **When to use** * - * - Converting a boolean check into an `Option`-returning function + * Use to convert a boolean check into an `Option`-returning function * - Validating input and wrapping it in `Option` * - * **Behavior** + * **Details** * * - `predicate(value)` is `true` → `Some(value)` * - `predicate(value)` is `false` → `None` @@ -3879,7 +3863,7 @@ export const lift2 = (f: (a: A, b: B) => C): { * @see {@link filter} to apply a predicate to an existing `Option` * @see {@link toRefinement} for the inverse direction * - * @category Lifting + * @category lifting * @since 2.0.0 */ export const liftPredicate: { // Note: I intentionally avoid using the NoInfer pattern here. @@ -3890,10 +3874,10 @@ export const liftPredicate: { // Note: I intentionally avoid using the NoInfer p * * **When to use** * - * - Converting a boolean check into an `Option`-returning function + * Use to convert a boolean check into an `Option`-returning function * - Validating input and wrapping it in `Option` * - * **Behavior** + * **Details** * * - `predicate(value)` is `true` → `Some(value)` * - `predicate(value)` is `false` → `None` @@ -3916,7 +3900,7 @@ export const liftPredicate: { // Note: I intentionally avoid using the NoInfer p * @see {@link filter} to apply a predicate to an existing `Option` * @see {@link toRefinement} for the inverse direction * - * @category Lifting + * @category lifting * @since 2.0.0 */ (predicate: Predicate): (b: B) => Option @@ -3926,10 +3910,10 @@ export const liftPredicate: { // Note: I intentionally avoid using the NoInfer p * * **When to use** * - * - Converting a boolean check into an `Option`-returning function + * Use to convert a boolean check into an `Option`-returning function * - Validating input and wrapping it in `Option` * - * **Behavior** + * **Details** * * - `predicate(value)` is `true` → `Some(value)` * - `predicate(value)` is `false` → `None` @@ -3952,7 +3936,7 @@ export const liftPredicate: { // Note: I intentionally avoid using the NoInfer p * @see {@link filter} to apply a predicate to an existing `Option` * @see {@link toRefinement} for the inverse direction * - * @category Lifting + * @category lifting * @since 2.0.0 */ (self: A, refinement: Refinement): Option @@ -3962,10 +3946,10 @@ export const liftPredicate: { // Note: I intentionally avoid using the NoInfer p * * **When to use** * - * - Converting a boolean check into an `Option`-returning function + * Use to convert a boolean check into an `Option`-returning function * - Validating input and wrapping it in `Option` * - * **Behavior** + * **Details** * * - `predicate(value)` is `true` → `Some(value)` * - `predicate(value)` is `false` → `None` @@ -3988,7 +3972,7 @@ export const liftPredicate: { // Note: I intentionally avoid using the NoInfer p * @see {@link filter} to apply a predicate to an existing `Option` * @see {@link toRefinement} for the inverse direction * - * @category Lifting + * @category lifting * @since 2.0.0 */ (self: B, predicate: Predicate): Option @@ -3998,14 +3982,15 @@ export const liftPredicate: { // Note: I intentionally avoid using the NoInfer p ) /** - * Checks if an `Option` contains a value equivalent to the given one, using a + * Checks whether an `Option` contains a value equivalent to the given one, using a * custom `Equivalence`. * * **When to use** * - * - Testing membership with a custom equality check + * Use when you need to test whether an `Option` contains a value using a + * custom equality check. * - * **Behavior** + * **Details** * * - `Some` where `isEquivalent(value, a)` is `true` → `true` * - `Some` where not equivalent, or `None` → `false` @@ -4029,7 +4014,7 @@ export const liftPredicate: { // Note: I intentionally avoid using the NoInfer p * * @see {@link contains} for a version using default equality * - * @category Elements + * @category elements * @since 2.0.0 */ export const containsWith = (isEquivalent: (self: A, that: A) => boolean): { @@ -4038,14 +4023,15 @@ export const containsWith = (isEquivalent: (self: A, that: A) => boolean): { } => dual(2, (self: Option, a: A): boolean => isNone(self) ? false : isEquivalent(self.value, a)) /** - * Checks if an `Option` contains a value equal to the given one, using default + * Checks whether an `Option` contains a value equal to the given one, using default * structural equality. * * **When to use** * - * - Quick membership test with standard equality + * Use when you need a quick membership test for an `Option` value using + * standard equality. * - * **Behavior** + * **Details** * * - `Some` where `Equal.equals(value, a)` is `true` → `true` * - `Some` where not equal, or `None` → `false` @@ -4068,19 +4054,20 @@ export const containsWith = (isEquivalent: (self: A, that: A) => boolean): { * @see {@link containsWith} for custom equality * @see {@link exists} to test with a predicate * - * @category Elements + * @category elements * @since 2.0.0 */ export const contains: { /** - * Checks if an `Option` contains a value equal to the given one, using default + * Checks whether an `Option` contains a value equal to the given one, using default * structural equality. * * **When to use** * - * - Quick membership test with standard equality + * Use when you need a quick membership test for an `Option` value using + * standard equality. * - * **Behavior** + * **Details** * * - `Some` where `Equal.equals(value, a)` is `true` → `true` * - `Some` where not equal, or `None` → `false` @@ -4103,19 +4090,20 @@ export const contains: { * @see {@link containsWith} for custom equality * @see {@link exists} to test with a predicate * - * @category Elements + * @category elements * @since 2.0.0 */ (a: A): (self: Option) => boolean /** - * Checks if an `Option` contains a value equal to the given one, using default + * Checks whether an `Option` contains a value equal to the given one, using default * structural equality. * * **When to use** * - * - Quick membership test with standard equality + * Use when you need a quick membership test for an `Option` value using + * standard equality. * - * **Behavior** + * **Details** * * - `Some` where `Equal.equals(value, a)` is `true` → `true` * - `Some` where not equal, or `None` → `false` @@ -4138,20 +4126,20 @@ export const contains: { * @see {@link containsWith} for custom equality * @see {@link exists} to test with a predicate * - * @category Elements + * @category elements * @since 2.0.0 */ (self: Option, a: A): boolean } = containsWith(Equal.asEquivalence()) /** - * Tests if the value in a `Some` satisfies a predicate or refinement. + * Checks whether the value in a `Some` satisfies a predicate or refinement. * * **When to use** * - * - Checking a condition on an optional value without unwrapping + * Use to check a condition on an optional value without unwrapping * - * **Behavior** + * **Details** * * - `None` → `false` * - `Some` where `predicate(value)` is `true` → `true` @@ -4178,18 +4166,18 @@ export const contains: { * @see {@link filter} to keep or discard based on a predicate * @see {@link contains} to test for a specific value * - * @category Elements + * @category elements * @since 2.0.0 */ export const exists: { /** - * Tests if the value in a `Some` satisfies a predicate or refinement. + * Checks whether the value in a `Some` satisfies a predicate or refinement. * * **When to use** * - * - Checking a condition on an optional value without unwrapping + * Use to check a condition on an optional value without unwrapping * - * **Behavior** + * **Details** * * - `None` → `false` * - `Some` where `predicate(value)` is `true` → `true` @@ -4216,18 +4204,18 @@ export const exists: { * @see {@link filter} to keep or discard based on a predicate * @see {@link contains} to test for a specific value * - * @category Elements + * @category elements * @since 2.0.0 */ (refinement: Refinement, B>): (self: Option) => self is Option /** - * Tests if the value in a `Some` satisfies a predicate or refinement. + * Checks whether the value in a `Some` satisfies a predicate or refinement. * * **When to use** * - * - Checking a condition on an optional value without unwrapping + * Use to check a condition on an optional value without unwrapping * - * **Behavior** + * **Details** * * - `None` → `false` * - `Some` where `predicate(value)` is `true` → `true` @@ -4254,18 +4242,18 @@ export const exists: { * @see {@link filter} to keep or discard based on a predicate * @see {@link contains} to test for a specific value * - * @category Elements + * @category elements * @since 2.0.0 */ (predicate: Predicate>): (self: Option) => boolean /** - * Tests if the value in a `Some` satisfies a predicate or refinement. + * Checks whether the value in a `Some` satisfies a predicate or refinement. * * **When to use** * - * - Checking a condition on an optional value without unwrapping + * Use to check a condition on an optional value without unwrapping * - * **Behavior** + * **Details** * * - `None` → `false` * - `Some` where `predicate(value)` is `true` → `true` @@ -4292,18 +4280,18 @@ export const exists: { * @see {@link filter} to keep or discard based on a predicate * @see {@link contains} to test for a specific value * - * @category Elements + * @category elements * @since 2.0.0 */ (self: Option, refinement: Refinement): self is Option /** - * Tests if the value in a `Some` satisfies a predicate or refinement. + * Checks whether the value in a `Some` satisfies a predicate or refinement. * * **When to use** * - * - Checking a condition on an optional value without unwrapping + * Use to check a condition on an optional value without unwrapping * - * **Behavior** + * **Details** * * - `None` → `false` * - `Some` where `predicate(value)` is `true` → `true` @@ -4330,7 +4318,7 @@ export const exists: { * @see {@link filter} to keep or discard based on a predicate * @see {@link contains} to test for a specific value * - * @category Elements + * @category elements * @since 2.0.0 */ (self: Option, predicate: Predicate): boolean @@ -4350,7 +4338,8 @@ export const exists: { * * **When to use** * - * - Beginning a do notation chain by naming the first value + * Use when you need to start an `Option` do notation chain by naming the first + * value. * * **Example** (Starting do notation) * @@ -4371,7 +4360,7 @@ export const exists: { * @see {@link bind} to add `Option` values * @see {@link let_ let} to add plain values * - * @category Do notation + * @category do notation * @since 2.0.0 */ export const bindTo: { @@ -4385,7 +4374,8 @@ export const bindTo: { * * **When to use** * - * - Beginning a do notation chain by naming the first value + * Use when you need to start an `Option` do notation chain by naming the first + * value. * * **Example** (Starting do notation) * @@ -4406,7 +4396,7 @@ export const bindTo: { * @see {@link bind} to add `Option` values * @see {@link let_ let} to add plain values * - * @category Do notation + * @category do notation * @since 2.0.0 */ (name: N): (self: Option) => Option<{ [K in N]: A }> @@ -4420,7 +4410,8 @@ export const bindTo: { * * **When to use** * - * - Beginning a do notation chain by naming the first value + * Use when you need to start an `Option` do notation chain by naming the first + * value. * * **Example** (Starting do notation) * @@ -4441,7 +4432,7 @@ export const bindTo: { * @see {@link bind} to add `Option` values * @see {@link let_ let} to add plain values * - * @category Do notation + * @category do notation * @since 2.0.0 */ (self: Option, name: N): Option<{ [K in N]: A }> @@ -4465,7 +4456,8 @@ export { * * **When to use** * - * - Binding a derived (non-`Option`) value in a do notation pipeline + * Use when you need to bind a derived non-`Option` value in an `Option` do + * notation pipeline. * * **Example** (Adding a computed value) * @@ -4486,7 +4478,7 @@ export { * @see {@link bind} to add `Option` values * @see {@link bindTo} to start by naming an existing `Option` * - * @category Do notation + * @category do notation * @since 2.0.0 */ let_ as let @@ -4498,7 +4490,7 @@ export { * * **When to use** * - * - Sequencing `Option` computations in do notation + * Use when you need to sequence `Option` computations in do notation. * * **Example** (Binding Option values) * @@ -4520,7 +4512,7 @@ export { * @see {@link let_ let} to add plain values * @see {@link bindTo} to start by naming an existing `Option` * - * @category Do notation + * @category do notation * @since 2.0.0 */ export const bind: { @@ -4530,7 +4522,7 @@ export const bind: { * * **When to use** * - * - Sequencing `Option` computations in do notation + * Use when you need to sequence `Option` computations in do notation. * * **Example** (Binding Option values) * @@ -4552,7 +4544,7 @@ export const bind: { * @see {@link let_ let} to add plain values * @see {@link bindTo} to start by naming an existing `Option` * - * @category Do notation + * @category do notation * @since 2.0.0 */ (name: Exclude, f: (a: NoInfer) => Option): (self: Option) => Option<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }> @@ -4562,7 +4554,7 @@ export const bind: { * * **When to use** * - * - Sequencing `Option` computations in do notation + * Use when you need to sequence `Option` computations in do notation. * * **Example** (Binding Option values) * @@ -4584,7 +4576,7 @@ export const bind: { * @see {@link let_ let} to add plain values * @see {@link bindTo} to start by naming an existing `Option` * - * @category Do notation + * @category do notation * @since 2.0.0 */ ( @@ -4595,12 +4587,13 @@ export const bind: { } = doNotation.bind(map, flatMap) /** - * An `Option` containing an empty record `{}`, used as the starting point for + * Provides an `Option` containing an empty record `{}`, used as the starting point for * do notation chains. * * **When to use** * - * - Starting a do notation pipeline before adding bindings + * Use when you need to start an `Option` do notation pipeline before adding + * bindings. * * **Example** (Do notation pipeline) * @@ -4622,21 +4615,21 @@ export const bind: { * @see {@link let_ let} to add plain values * @see {@link bindTo} to start by naming an existing `Option` * - * @category Do notation + * @category do notation * @since 2.0.0 */ export const Do: Option<{}> = some({}) /** - * Generator-based syntax for `Option`, similar to `async`/`await` but for + * Provides generator-based syntax for `Option`, similar to `async`/`await` but for * optional values. Yielding a `None` short-circuits the generator to `None`. * * **When to use** * - * - Writing imperative-style code that chains multiple `Option`s - * - Readability when many sequential optional steps are involved + * Use when you need generator syntax for a sequence of `Option` steps that + * should short-circuit on `None`. * - * **Behavior** + * **Details** * * - Each `yield*` unwraps a `Some` value or short-circuits to `None` * - The return value is wrapped in `Some` @@ -4663,7 +4656,7 @@ export const Do: Option<{}> = some({}) * * @see {@link Do} / {@link bind} for the do notation alternative * - * @category Generators + * @category generators * @since 2.0.0 */ export const gen: Gen.Gen = (...args) => { @@ -4686,10 +4679,10 @@ export const gen: Gen.Gen = (...args) => { * * **When to use** * - * - Building a reducer that falls back to the first available value - * - Combining optional values where either side may be absent + * Use to build an `Option` reducer that falls back to the first available value + * when either side may be absent. * - * **Behavior** + * **Details** * * - `None` + `None` → `None` * - `Some(a)` + `None` → `Some(a)` @@ -4709,6 +4702,7 @@ export const gen: Gen.Gen = (...args) => { * * @see {@link makeReducerFailFast} for fail-fast semantics * + * @category Reducer * @since 4.0.0 */ export function makeReducer(combiner: Combiner.Combiner): Reducer.Reducer> { @@ -4725,9 +4719,10 @@ export function makeReducer(combiner: Combiner.Combiner): Reducer.Reducer< * * **When to use** * - * - Operations that require both values to be present + * Use when you need an `Option` combiner that returns `None` unless both + * operands are `Some`. * - * **Behavior** + * **Details** * * - `None` + anything → `None` * - anything + `None` → `None` @@ -4748,6 +4743,7 @@ export function makeReducer(combiner: Combiner.Combiner): Reducer.Reducer< * * @see {@link makeReducerFailFast} to get a full `Reducer` * + * @category Combiner * @since 4.0.0 */ export function makeCombinerFailFast(combiner: Combiner.Combiner): Combiner.Combiner> { @@ -4763,10 +4759,10 @@ export function makeCombinerFailFast(combiner: Combiner.Combiner): Combine * * **When to use** * - * - Wrapping an existing `Reducer` to work with `Option` values - * - Reductions where any `None` should abort the entire result + * Use when you need to reduce `Option` values with fail-fast semantics, where + * any `None` aborts the entire result instead of being skipped. * - * **Behavior** + * **Details** * * - Initial value is `Some(reducer.initialValue)` * - Combines only when both operands are `Some` @@ -4788,6 +4784,7 @@ export function makeCombinerFailFast(combiner: Combiner.Combiner): Combine * @see {@link makeCombinerFailFast} for just the combiner * @see {@link makeReducer} for non-fail-fast semantics * + * @category Reducer * @since 4.0.0 */ export function makeReducerFailFast(reducer: Reducer.Reducer): Reducer.Reducer> { diff --git a/.opencode/node_modules/effect/src/Order.ts b/.opencode/node_modules/effect/src/Order.ts index 8fdcbf32a966917c7dbd72db7075db79b6b20abf..8c6549d278fdb6f18ad8c0b30a87d6f83419f99d 100644 --- a/.opencode/node_modules/effect/src/Order.ts +++ b/.opencode/node_modules/effect/src/Order.ts @@ -1,51 +1,12 @@ /** - * This module provides the `Order` type class for defining total orderings on types. - * An `Order` is a comparison function that returns `-1` (less than), `0` (equal), or `1` (greater than). - * - * Mental model: - * - An `Order` is a pure function `(a: A, b: A) => Ordering` that compares two values - * - The result `-1` means the first value is less than the second - * - The result `0` means the values are equal according to this ordering - * - The result `1` means the first value is greater than the second - * - Orders must satisfy total ordering laws: totality (either `x <= y` or `y <= x`), antisymmetry (if `x <= y` and `y <= x` then `x == y`), and transitivity (if `x <= y` and `y <= z` then `x <= z`) - * - Orders can be composed using {@link combine} and {@link combineAll} to create multi-criteria comparisons - * - Orders can be transformed using {@link mapInput} to compare values by extracting a comparable property - * - Built-in orders exist for common types: {@link Number}, {@link String}, {@link Boolean}, {@link BigInt}, {@link Date} - * - * Common tasks: - * - Creating custom orders → {@link make} - * - Using built-in orders → {@link Number}, {@link String}, {@link Boolean}, {@link BigInt}, {@link Date} - * - Combining multiple orders → {@link combine}, {@link combineAll} - * - Transforming orders → {@link mapInput} - * - Comparing values → {@link isLessThan}, {@link isGreaterThan}, {@link isLessThanOrEqualTo}, {@link isGreaterThanOrEqualTo} - * - Finding min/max → {@link min}, {@link max} - * - Clamping values → {@link clamp}, {@link isBetween} - * - Ordering collections → {@link Array}, {@link Tuple}, {@link Struct} - * - * Gotchas: - * - `Order.Number` treats all `NaN` values as equal and less than any other number - * - `Order.make` uses reference equality (`===`) as a shortcut: if `self === that`, it returns `0` without calling the comparison function - * - `Order.Array` compares arrays element-by-element, then by length if all elements are equal; `Order.all` only compares elements up to the shorter array's length - * - `Order.Tuple` requires a fixed-length tuple with matching order types; `Order.Array` works with variable-length arrays - * - `Order.min` and `Order.max` return the first argument when values are equal - * - * Quickstart: - * - * **Example** (Basic Usage) + * Defines comparison functions for ordered values. * - * ```ts - * import { Order } from "effect" - * - * const result = Order.Number(5, 10) - * console.log(result) // -1 (5 is less than 10) - * - * const isLessThan = Order.isLessThan(Order.Number)(5, 10) - * console.log(isLessThan) // true - * ``` - * - * See also: - * - {@link Ordering} - The result type of comparisons - * - {@link Reducer} - For combining orders in collections + * An `Order` compares two `A` values and returns whether the first is less + * than, equal to, or greater than the second. Orders are used for sorting, + * choosing minimum or maximum values, checking ranges, and building ordered data + * structures. This module includes built-in orders, constructors for custom + * orders, tools for reversing and combining comparisons, tuple and struct + * helpers, comparison predicates, clamping, and reducer support. * * @since 2.0.0 */ @@ -57,17 +18,16 @@ import * as Reducer from "./Reducer.ts" /** * Represents a total ordering for values of type `A`. * - * When to use this: - * - When you need to define how values of a type should be compared - * - When implementing sorting, searching, or ordered data structures - * - When composing multiple comparison criteria + * **When to use** + * + * Use when you need to define how values of a type are compared. * - * Behavior: - * - Pure function: does not mutate inputs or have side effects - * - Returns `-1` if the first value is less than the second - * - Returns `0` if the values are equal according to this ordering - * - Returns `1` if the first value is greater than the second - * - Must satisfy total ordering laws (totality, antisymmetry, transitivity) + * **Details** + * + * An order returns `-1` when the first value is less than the second, `0` when + * the values are equal according to this ordering, and `1` when the first value + * is greater than the second. It must satisfy total ordering laws: totality, + * antisymmetry, and transitivity. * * **Example** (Custom Order) * @@ -85,10 +45,8 @@ import * as Reducer from "./Reducer.ts" * console.log(byAge(person1, person2)) // 1 * ``` * - * See also: - * - {@link make} - Create an order from a comparison function - * - {@link Ordering} - The result type of comparisons - * + * @see {@link make} to create an order from a comparison function + * @see {@link Ordering} for the result type of comparisons * @category type class * @since 2.0.0 */ @@ -99,13 +57,14 @@ export interface Order { /** * Type lambda for the `Order` type class, used internally for higher-kinded type operations. * - * When to use this: - * - When working with type-level operations that require higher-kinded types - * - When implementing generic type classes that work with orders + * **When to use** + * + * Use when you need to abstract over `Order` in higher-kinded type code. * - * Behavior: - * - Type-level only: no runtime representation - * - Used internally by the Effect type system + * **Details** + * + * This is type-level only, has no runtime representation, and is used + * internally by the Effect type system. * * @category type lambdas * @since 2.0.0 @@ -117,16 +76,17 @@ export interface OrderTypeLambda extends TypeLambda { /** * Creates a new `Order` instance from a comparison function. * - * When to use this: - * - When creating a custom order for a type that doesn't have a built-in order - * - When you need fine-grained control over comparison logic - * - When implementing orders for complex types + * **When to use** + * + * Use when you need a sorting rule not covered by the built-in orders or input + * mapping helpers, and you can provide a total comparison. + * + * **Details** * - * Behavior: - * - Pure function: does not mutate inputs - * - Uses reference equality (`===`) as a shortcut: if `self === that`, returns `0` without calling the comparison function - * - The comparison function should return `-1`, `0`, or `1` based on the comparison result - * - The returned order satisfies total ordering laws if the comparison function does + * Uses reference equality (`===`) as a shortcut: if `self === that`, it returns + * `0` without calling the comparison function. The comparison function should + * return `-1`, `0`, or `1`, and the returned order satisfies total ordering + * laws when the comparison function does. * * **Example** (Creating an Order) * @@ -143,10 +103,8 @@ export interface OrderTypeLambda extends TypeLambda { * console.log(byAge({ name: "Alice", age: 25 }, { name: "Bob", age: 30 })) // -1 * ``` * - * See also: - * - {@link mapInput} - Transform an order by mapping the input type - * - {@link combine} - Combine multiple orders - * + * @see {@link mapInput} to transform an order by mapping the input type + * @see {@link combine} to combine multiple orders * @category constructors * @since 2.0.0 */ @@ -157,18 +115,16 @@ export function make( } /** - * An `Order` instance for strings that compares them lexicographically using JavaScript's `<` operator. + * Order instance for strings that compares them lexicographically using JavaScript's `<` operator. + * + * **When to use** * - * When to use this: - * - When comparing strings alphabetically - * - When sorting string collections - * - As a base for creating orders on types containing strings + * Use when you need lexicographic string ordering. * - * Behavior: - * - Pure function: does not mutate inputs - * - Uses lexicographic (dictionary) ordering - * - Empty string is less than any non-empty string - * - Comparison is case-sensitive + * **Details** + * + * Uses lexicographic dictionary ordering. The empty string is less than any + * non-empty string, and comparisons are case-sensitive. * * **Example** (String Ordering) * @@ -180,29 +136,25 @@ export function make( * console.log(Order.String("apple", "apple")) // 0 * ``` * - * See also: - * - {@link mapInput} - Use this order to compare objects by a string property - * - {@link Struct} - Combine with other orders for struct comparison - * + * @see {@link mapInput} to compare objects by a string property + * @see {@link Struct} to combine with other orders for struct comparison * @category instances * @since 4.0.0 */ export const String: Order = make((self, that) => self < that ? -1 : 1) /** - * An `Order` instance for numbers that compares them numerically. + * Order instance for numbers that compares them numerically. * - * When to use this: - * - When comparing numbers for sorting or searching - * - As a base for creating orders on types containing numbers - * - When implementing numeric comparisons in data structures + * **When to use** * - * Behavior: - * - Pure function: does not mutate inputs - * - `0` is considered equal to `-0` - * - All `NaN` values are considered equal to each other - * - Any `NaN` is considered less than any non-NaN number - * - Uses standard numeric comparison for all other values + * Use when you need numeric ordering for numbers. + * + * **Details** + * + * `0` is considered equal to `-0`. All `NaN` values are considered equal to + * each other, and any `NaN` is considered less than any non-`NaN` number. All + * other values use standard numeric comparison. * * **Example** (Number Ordering) * @@ -217,10 +169,8 @@ export const String: Order = make((self, that) => self < that ? -1 : 1) * console.log(Order.Number(NaN, 1)) // -1 * ``` * - * See also: - * - {@link mapInput} - Use this order to compare objects by a number property - * - {@link BigInt} - For bigint comparisons - * + * @see {@link mapInput} to compare objects by a number property + * @see {@link BigInt} for bigint comparisons * @category instances * @since 4.0.0 */ @@ -232,17 +182,15 @@ export const Number: Order = make((self, that) => { }) /** - * An `Order` instance for booleans where `false` is considered less than `true`. + * Order instance for booleans where `false` is considered less than `true`. * - * When to use this: - * - When comparing booleans for sorting or searching - * - As a base for creating orders on types containing booleans - * - When implementing boolean-based comparisons + * **When to use** * - * Behavior: - * - Pure function: does not mutate inputs - * - `false` is less than `true` - * - Equal values return `0` + * Use when you need boolean ordering where `false` comes before `true`. + * + * **Details** + * + * `false` is less than `true`, and equal values return `0`. * * **Example** (Boolean Ordering) * @@ -254,26 +202,23 @@ export const Number: Order = make((self, that) => { * console.log(Order.Boolean(true, true)) // 0 * ``` * - * See also: - * - {@link mapInput} - Use this order to compare objects by a boolean property - * + * @see {@link mapInput} to compare objects by a boolean property * @category instances * @since 4.0.0 */ export const Boolean: Order = make((self, that) => self < that ? -1 : 1) /** - * An `Order` instance for bigints that compares them numerically. + * Order instance for bigints that compares them numerically. * - * When to use this: - * - When comparing bigint values for sorting or searching - * - As a base for creating orders on types containing bigints - * - When working with large integers that exceed number precision + * **When to use** * - * Behavior: - * - Pure function: does not mutate inputs - * - Uses standard numeric comparison for bigint values - * - Handles arbitrarily large integers + * Use when you need numeric ordering for `bigint` values. + * + * **Details** + * + * Uses standard numeric comparison for bigint values and handles arbitrarily + * large integers. * * **Example** (BigInt Ordering) * @@ -285,10 +230,8 @@ export const Boolean: Order = make((self, that) => self < that ? -1 : 1 * console.log(Order.BigInt(1n, 1n)) // 0 * ``` * - * See also: - * - {@link Number} - For regular number comparisons - * - {@link mapInput} - Use this order to compare objects by a bigint property - * + * @see {@link Number} for regular number comparisons + * @see {@link mapInput} to compare objects by a bigint property * @category instances * @since 4.0.0 */ @@ -297,16 +240,15 @@ export const BigInt: Order = make((self, that) => self < that ? -1 : 1) /** * Creates a new `Order` that reverses the comparison order of the input `Order`. * - * When to use this: - * - When you need descending order instead of ascending - * - When reversing an existing order without modifying the original - * - When creating orders that compare in the opposite direction + * **When to use** * - * Behavior: - * - Pure function: does not mutate inputs - * - Returns a new order that swaps the arguments before comparison - * - If the original order returns `-1`, the flipped order returns `1`, and vice versa - * - Equal comparisons remain `0` + * Use when you need the reverse of an existing order. + * + * **Details** + * + * Returns a new order that swaps the arguments before comparison. If the + * original order returns `-1`, the flipped order returns `1`, and vice versa. + * Equal comparisons remain `0`. * * **Example** (Reversing Order) * @@ -320,11 +262,9 @@ export const BigInt: Order = make((self, that) => self < that ? -1 : 1) * console.log(flip(1, 1)) // 0 * ``` * - * See also: - * - {@link combine} - Combine orders for multi-criteria comparison - * + * @see {@link combine} to combine orders for multi-criteria comparison * @category combinators - * @since 2.0.0 + * @since 4.0.0 */ export function flip(O: Order): Order { return make((self, that) => O(that, self)) @@ -334,16 +274,15 @@ export function flip(O: Order): Order { * Combines two `Order` instances to create a new `Order` that first compares using the first `Order`, * and if the values are equal, then compares using the second `Order`. * - * When to use this: - * - When you need multi-criteria comparison (e.g., sort by age, then by name) - * - When creating composite orders from simpler orders - * - When implementing lexicographic ordering + * **When to use** + * + * Use when you need tie-breaking with exactly two orders. + * + * **Details** * - * Behavior: - * - Pure function: does not mutate inputs - * - First applies the first order; if the result is non-zero, returns that result - * - If the first order returns `0` (equal), applies the second order - * - Returns the first non-zero result, or `0` if both orders return `0` + * First applies the first order. If the result is non-zero, that result is + * returned; otherwise, the second order is applied. The result is the first + * non-zero comparison result, or `0` if both orders return `0`. * * **Example** (Combining Orders) * @@ -368,10 +307,8 @@ export function flip(O: Order): Order { * console.log(byAgeAndName(person1, person3)) // 1 (Alice (30) > Charlie (25)) * ``` * - * See also: - * - {@link combineAll} - Combine multiple orders from a collection - * - {@link mapInput} - Transform orders to work with different types - * + * @see {@link combineAll} to combine multiple orders from a collection + * @see {@link mapInput} to transform orders to work with different types * @category combining * @since 2.0.0 */ @@ -380,16 +317,15 @@ export const combine: { * Combines two `Order` instances to create a new `Order` that first compares using the first `Order`, * and if the values are equal, then compares using the second `Order`. * - * When to use this: - * - When you need multi-criteria comparison (e.g., sort by age, then by name) - * - When creating composite orders from simpler orders - * - When implementing lexicographic ordering + * **When to use** + * + * Use when you need tie-breaking with exactly two orders. + * + * **Details** * - * Behavior: - * - Pure function: does not mutate inputs - * - First applies the first order; if the result is non-zero, returns that result - * - If the first order returns `0` (equal), applies the second order - * - Returns the first non-zero result, or `0` if both orders return `0` + * First applies the first order. If the result is non-zero, that result is + * returned; otherwise, the second order is applied. The result is the first + * non-zero comparison result, or `0` if both orders return `0`. * * **Example** (Combining Orders) * @@ -414,10 +350,8 @@ export const combine: { * console.log(byAgeAndName(person1, person3)) // 1 (Alice (30) > Charlie (25)) * ``` * - * See also: - * - {@link combineAll} - Combine multiple orders from a collection - * - {@link mapInput} - Transform orders to work with different types - * + * @see {@link combineAll} to combine multiple orders from a collection + * @see {@link mapInput} to transform orders to work with different types * @category combining * @since 2.0.0 */ @@ -426,16 +360,15 @@ export const combine: { * Combines two `Order` instances to create a new `Order` that first compares using the first `Order`, * and if the values are equal, then compares using the second `Order`. * - * When to use this: - * - When you need multi-criteria comparison (e.g., sort by age, then by name) - * - When creating composite orders from simpler orders - * - When implementing lexicographic ordering + * **When to use** + * + * Use when you need tie-breaking with exactly two orders. + * + * **Details** * - * Behavior: - * - Pure function: does not mutate inputs - * - First applies the first order; if the result is non-zero, returns that result - * - If the first order returns `0` (equal), applies the second order - * - Returns the first non-zero result, or `0` if both orders return `0` + * First applies the first order. If the result is non-zero, that result is + * returned; otherwise, the second order is applied. The result is the first + * non-zero comparison result, or `0` if both orders return `0`. * * **Example** (Combining Orders) * @@ -460,10 +393,8 @@ export const combine: { * console.log(byAgeAndName(person1, person3)) // 1 (Alice (30) > Charlie (25)) * ``` * - * See also: - * - {@link combineAll} - Combine multiple orders from a collection - * - {@link mapInput} - Transform orders to work with different types - * + * @see {@link combineAll} to combine multiple orders from a collection + * @see {@link mapInput} to transform orders to work with different types * @category combining * @since 2.0.0 */ @@ -480,15 +411,14 @@ export const combine: { /** * Creates an `Order` that considers all values as equal. * - * When to use this: - * - When you need an order that doesn't distinguish between values - * - As a default or fallback order when no meaningful comparison exists - * - When implementing optional ordering where equality is sufficient + * **When to use** + * + * Use when you need an order that treats all values as equal. * - * Behavior: - * - Pure function: does not mutate inputs - * - Always returns `0` regardless of input values - * - Useful as a neutral element in order composition + * **Details** + * + * Always returns `0` regardless of input values, making it useful as a neutral + * element in order composition. * * **Example** (Always Equal Order) * @@ -502,9 +432,7 @@ export const combine: { * console.log(alwaysEqualOrder(1, 1)) // 0 * ``` * - * See also: - * - {@link combine} - Combine with other orders - * + * @see {@link combine} to combine with other orders * @category constructors * @since 4.0.0 */ @@ -516,17 +444,14 @@ export function alwaysEqual(): Order { * Combines all `Order` instances in the provided collection into a single `Order`. * The resulting `Order` compares using each `Order` in sequence until a non-zero result is found. * - * When to use this: - * - When you have a variable number of orders to combine - * - When combining orders from a collection or array - * - When implementing dynamic multi-criteria sorting + * **When to use** * - * Behavior: - * - Pure function: does not mutate inputs - * - Applies orders in iteration order - * - Returns the first non-zero result from any order - * - Returns `0` only if all orders return `0` - * - Short-circuits on the first non-zero result + * Use when you need tie-breaking across a variable number of orders. + * + * **Details** + * + * Applies orders in iteration order and short-circuits on the first non-zero + * result. It returns `0` only if all orders return `0`. * * **Example** (Combining Multiple Orders) * @@ -550,10 +475,8 @@ export function alwaysEqual(): Order { * console.log(combinedOrder(person1, person2)) // -1 (Same age, Alice < Bob) * ``` * - * See also: - * - {@link combine} - Combine two orders - * - {@link makeReducer} - Create a reducer for combining orders - * + * @see {@link combine} to combine two orders + * @see {@link makeReducer} to create a reducer for combining orders * @category combining * @since 2.0.0 */ @@ -574,16 +497,16 @@ export function combineAll(collection: Iterable>): Order { * Transforms an `Order` on type `A` into an `Order` on type `B` by providing a function that * maps values of type `B` to values of type `A`. * - * When to use this: - * - When you have an order for a property type and want to compare objects by that property - * - When extracting a comparable value from a complex type - * - When creating orders for types that contain comparable values + * **When to use** * - * Behavior: - * - Pure function: does not mutate inputs - * - Applies the mapping function to both values before comparison - * - The mapping function should be pure and not have side effects - * - Preserves the ordering properties of the original order + * Use when you need to adapt an `Order` to compare a larger value by one + * derived property. + * + * **Details** + * + * Applies the mapping function to both values before comparison. The mapping + * function should be pure and not have side effects so the ordering properties + * of the original order are preserved. * * **Example** (Mapping Input) * @@ -597,10 +520,8 @@ export function combineAll(collection: Iterable>): Order { * console.log(byLength("aa", "bb")) // 0 * ``` * - * See also: - * - {@link combine} - Combine mapped orders for multi-criteria comparison - * - {@link Struct} - Create orders for structs with multiple fields - * + * @see {@link combine} to combine mapped orders for multi-criteria comparison + * @see {@link Struct} to create orders for structs with multiple fields * @category mapping * @since 2.0.0 */ @@ -609,16 +530,16 @@ export const mapInput: { * Transforms an `Order` on type `A` into an `Order` on type `B` by providing a function that * maps values of type `B` to values of type `A`. * - * When to use this: - * - When you have an order for a property type and want to compare objects by that property - * - When extracting a comparable value from a complex type - * - When creating orders for types that contain comparable values + * **When to use** * - * Behavior: - * - Pure function: does not mutate inputs - * - Applies the mapping function to both values before comparison - * - The mapping function should be pure and not have side effects - * - Preserves the ordering properties of the original order + * Use when you need to adapt an `Order` to compare a larger value by one + * derived property. + * + * **Details** + * + * Applies the mapping function to both values before comparison. The mapping + * function should be pure and not have side effects so the ordering properties + * of the original order are preserved. * * **Example** (Mapping Input) * @@ -632,10 +553,8 @@ export const mapInput: { * console.log(byLength("aa", "bb")) // 0 * ``` * - * See also: - * - {@link combine} - Combine mapped orders for multi-criteria comparison - * - {@link Struct} - Create orders for structs with multiple fields - * + * @see {@link combine} to combine mapped orders for multi-criteria comparison + * @see {@link Struct} to create orders for structs with multiple fields * @category mapping * @since 2.0.0 */ @@ -644,16 +563,16 @@ export const mapInput: { * Transforms an `Order` on type `A` into an `Order` on type `B` by providing a function that * maps values of type `B` to values of type `A`. * - * When to use this: - * - When you have an order for a property type and want to compare objects by that property - * - When extracting a comparable value from a complex type - * - When creating orders for types that contain comparable values + * **When to use** * - * Behavior: - * - Pure function: does not mutate inputs - * - Applies the mapping function to both values before comparison - * - The mapping function should be pure and not have side effects - * - Preserves the ordering properties of the original order + * Use when you need to adapt an `Order` to compare a larger value by one + * derived property. + * + * **Details** + * + * Applies the mapping function to both values before comparison. The mapping + * function should be pure and not have side effects so the ordering properties + * of the original order are preserved. * * **Example** (Mapping Input) * @@ -667,10 +586,8 @@ export const mapInput: { * console.log(byLength("aa", "bb")) // 0 * ``` * - * See also: - * - {@link combine} - Combine mapped orders for multi-criteria comparison - * - {@link Struct} - Create orders for structs with multiple fields - * + * @see {@link combine} to combine mapped orders for multi-criteria comparison + * @see {@link Struct} to create orders for structs with multiple fields * @category mapping * @since 2.0.0 */ @@ -681,18 +598,17 @@ export const mapInput: { ) /** - * An `Order` instance for `Date` objects that compares them chronologically by their timestamp. + * Order instance for `Date` objects that compares them chronologically by their timestamp. + * + * **When to use** * - * When to use this: - * - When comparing dates for sorting or searching - * - As a base for creating orders on types containing dates - * - When implementing time-based comparisons + * Use when you need chronological ordering for JavaScript date values. * - * Behavior: - * - Pure function: does not mutate inputs - * - Compares dates by their underlying timestamp (milliseconds since epoch) - * - Earlier dates are less than later dates - * - Invalid dates are compared as if they were valid (uses `getTime()` result) + * **Details** + * + * Compares dates by their underlying timestamp in milliseconds since the epoch. + * Earlier dates are less than later dates. Invalid dates are compared through + * their `getTime()` result. * * **Example** (Date Ordering) * @@ -707,9 +623,7 @@ export const mapInput: { * console.log(Order.Date(date1, date1)) // 0 * ``` * - * See also: - * - {@link mapInput} - Use this order to compare objects by a date property - * + * @see {@link mapInput} to compare objects by a date property * @category instances * @since 2.0.0 */ @@ -718,17 +632,15 @@ export const Date: Order = mapInput(Number, (date) => date.getTime()) /** * Creates an `Order` for a tuple type based on orders for each element. * - * When to use this: - * - When comparing tuples with different types for each position - * - When you need type-safe tuple ordering - * - When working with fixed-length heterogeneous collections + * **When to use** + * + * Use when you need fixed-length tuple ordering with per-position orders. * - * Behavior: - * - Pure function: does not mutate inputs - * - Compares tuples element-by-element using the corresponding order - * - Stops at the first non-zero comparison result - * - Requires tuples to have the same length as the order collection - * - Returns `0` if all elements are equal + * **Details** + * + * Compares tuples element-by-element using the corresponding order and stops at + * the first non-zero comparison result. Tuples must have the same length as the + * order collection, and the result is `0` only if all elements are equal. * * **Example** (Tuple Ordering) * @@ -742,9 +654,7 @@ export const Date: Order = mapInput(Number, (date) => date.getTime()) * console.log(tupleOrder([1, "a"], [1, "a"])) // 0 * ``` * - * See also: - * - {@link Array} - Compare arrays with length consideration - * + * @see {@link Array} to compare arrays with length consideration * @category combinators * @since 4.0.0 */ @@ -785,17 +695,16 @@ export { /** * Creates an `Order` for arrays by applying the given `Order` to each element, then comparing by length if all elements are equal. * - * When to use this: - * - When comparing arrays of the same element type - * - When you want shorter arrays to be considered less than longer arrays - * - When sorting collections of arrays + * **When to use** + * + * Use when you need lexicographic ordering for arrays of one element type. * - * Behavior: - * - Pure function: does not mutate inputs - * - Compares arrays element-by-element using the provided order - * - Stops at the first non-zero comparison result - * - If all elements are equal, shorter arrays are less than longer arrays - * - Returns `0` only if arrays have the same length and all elements are equal + * **Details** + * + * Compares arrays element-by-element using the provided order and stops at the + * first non-zero comparison result. If all elements are equal, shorter arrays + * are less than longer arrays. The result is `0` only if arrays have the same + * length and all elements are equal. * * **Example** (Array Element Ordering) * @@ -810,9 +719,7 @@ export { * console.log(arrayOrder([1, 2], [1, 2])) // 0 * ``` * - * See also: - * - {@link Tuple} - Type-safe tuple ordering - * + * @see {@link Tuple} for type-safe tuple ordering * @category combinators * @since 4.0.0 */ @@ -822,17 +729,15 @@ export { /** * Creates an `Order` for structs by applying the given `Order`s to each property in sequence. * - * When to use this: - * - When comparing objects with multiple properties - * - When you need multi-field comparison for structs - * - When creating orders for complex data types + * **When to use** + * + * Use when you need multi-field ordering for objects with known properties. * - * Behavior: - * - Pure function: does not mutate inputs - * - Compares structs field-by-field in the order of keys in the fields object - * - Stops at the first non-zero comparison result - * - Returns `0` only if all fields are equal - * - Field order matters: earlier fields take precedence + * **Details** + * + * Compares structs field-by-field in the key order of the fields object and + * stops at the first non-zero comparison result. Field order matters: earlier + * fields take precedence. The result is `0` only if all fields are equal. * * **Example** (Struct Ordering) * @@ -853,10 +758,8 @@ export { * console.log(personOrder(person1, person1)) // 0 * ``` * - * See also: - * - {@link combine} - Combine orders manually - * - {@link mapInput} - Extract and compare by a single property - * + * @see {@link combine} to combine orders manually + * @see {@link mapInput} to extract and compare by a single property * @category combinators * @since 4.0.0 */ @@ -876,18 +779,16 @@ export function Struct }>( } /** - * Tests whether one value is strictly less than another according to the given order. + * Checks whether one value is strictly less than another according to the given order. + * + * **When to use** + * + * Use when you need a boolean less-than predicate using an `Order`. * - * When to use this: - * - When you need a boolean predicate instead of an ordering result - * - When checking if a value is less than another in conditional logic - * - When implementing range checks or comparisons + * **Details** * - * Behavior: - * - Pure function: does not mutate inputs - * - Returns `true` if the order returns `-1` (first value is less than second) - * - Returns `false` for equal or greater values - * - Supports curried and uncurried call styles + * Returns `true` if the order returns `-1`, meaning the first value is less + * than the second. Equal or greater values return `false`. * * **Example** (Less Than) * @@ -901,12 +802,10 @@ export function Struct }>( * console.log(isLessThanNumber(1, 1)) // false * ``` * - * See also: - * - {@link isLessThanOrEqualTo} - Non-strict less than or equal - * - {@link isGreaterThan} - Strict greater than - * + * @see {@link isLessThanOrEqualTo} for non-strict less than or equal + * @see {@link isGreaterThan} for strict greater than * @category predicates - * @since 2.0.0 + * @since 4.0.0 */ export const isLessThan = (O: Order): { (that: A): (self: A) => boolean @@ -914,18 +813,16 @@ export const isLessThan = (O: Order): { } => dual(2, (self: A, that: A) => O(self, that) === -1) /** - * Tests whether one value is strictly greater than another according to the given order. + * Checks whether one value is strictly greater than another according to the given order. * - * When to use this: - * - When you need a boolean predicate instead of an ordering result - * - When checking if a value is greater than another in conditional logic - * - When implementing range checks or comparisons + * **When to use** * - * Behavior: - * - Pure function: does not mutate inputs - * - Returns `true` if the order returns `1` (first value is greater than second) - * - Returns `false` for equal or lesser values - * - Supports curried and uncurried call styles + * Use when you need a boolean greater-than predicate using an `Order`. + * + * **Details** + * + * Returns `true` if the order returns `1`, meaning the first value is greater + * than the second. Equal or lesser values return `false`. * * **Example** (Greater Than) * @@ -939,12 +836,10 @@ export const isLessThan = (O: Order): { * console.log(isGreaterThanNumber(1, 1)) // false * ``` * - * See also: - * - {@link isGreaterThanOrEqualTo} - Non-strict greater than or equal - * - {@link isLessThan} - Strict less than - * + * @see {@link isGreaterThanOrEqualTo} for non-strict greater than or equal + * @see {@link isLessThan} for strict less than * @category predicates - * @since 2.0.0 + * @since 4.0.0 */ export const isGreaterThan = (O: Order): { (that: A): (self: A) => boolean @@ -952,18 +847,16 @@ export const isGreaterThan = (O: Order): { } => dual(2, (self: A, that: A) => O(self, that) === 1) /** - * Tests whether one value is less than or equal to another according to the given order. + * Checks whether one value is less than or equal to another according to the given order. + * + * **When to use** * - * When to use this: - * - When you need a boolean predicate for non-strict comparison - * - When checking if a value is within a range (inclusive lower bound) - * - When implementing inclusive comparisons + * Use when you need a boolean less-than-or-equal predicate using an `Order`. * - * Behavior: - * - Pure function: does not mutate inputs - * - Returns `true` if the order returns `-1` or `0` (less than or equal) - * - Returns `false` only if the order returns `1` (greater than) - * - Supports curried and uncurried call styles + * **Details** + * + * Returns `true` if the order returns `-1` or `0`, and returns `false` only if + * the order returns `1`. * * **Example** (Less Than Or Equal) * @@ -977,12 +870,10 @@ export const isGreaterThan = (O: Order): { * console.log(isLessThanOrEqualToNumber(2, 1)) // false * ``` * - * See also: - * - {@link isLessThan} - Strict less than - * - {@link isGreaterThan} - Strict greater than - * + * @see {@link isLessThan} for strict less than + * @see {@link isGreaterThan} for strict greater than * @category predicates - * @since 2.0.0 + * @since 4.0.0 */ export const isLessThanOrEqualTo = (O: Order): { (that: A): (self: A) => boolean @@ -990,18 +881,17 @@ export const isLessThanOrEqualTo = (O: Order): { } => dual(2, (self: A, that: A) => O(self, that) !== 1) /** - * Tests whether one value is greater than or equal to another according to the given order. + * Checks whether one value is greater than or equal to another according to the given order. * - * When to use this: - * - When you need a boolean predicate for non-strict comparison - * - When checking if a value is within a range (inclusive upper bound) - * - When implementing inclusive comparisons + * **When to use** * - * Behavior: - * - Pure function: does not mutate inputs - * - Returns `true` if the order returns `1` or `0` (greater than or equal) - * - Returns `false` only if the order returns `-1` (less than) - * - Supports curried and uncurried call styles + * Use when you need a boolean greater-than-or-equal predicate using an + * `Order`. + * + * **Details** + * + * Returns `true` if the order returns `1` or `0`, and returns `false` only if + * the order returns `-1`. * * **Example** (Greater Than Or Equal) * @@ -1015,12 +905,10 @@ export const isLessThanOrEqualTo = (O: Order): { * console.log(isGreaterThanOrEqualToNumber(1, 2)) // false * ``` * - * See also: - * - {@link isGreaterThan} - Strict greater than - * - {@link isLessThanOrEqualTo} - Less than or equal - * + * @see {@link isGreaterThan} for strict greater than + * @see {@link isLessThanOrEqualTo} for less than or equal * @category predicates - * @since 2.0.0 + * @since 4.0.0 */ export const isGreaterThanOrEqualTo = (O: Order): { (that: A): (self: A) => boolean @@ -1030,16 +918,15 @@ export const isGreaterThanOrEqualTo = (O: Order): { /** * Returns the minimum of two values according to the given order. If they are equal, returns the first argument. * - * When to use this: - * - When you need to find the smaller of two values - * - When implementing min/max operations - * - When selecting values based on ordering + * **When to use** + * + * Use when you need to select the smaller of two values according to an + * `Order`. * - * Behavior: - * - Pure function: does not mutate inputs - * - Returns the value that compares as less than or equal to the other - * - If values are equal, returns the first argument - * - Supports curried and uncurried call styles + * **Details** + * + * Returns the value that compares as less than or equal to the other value. If + * values are equal, the first argument is returned. * * **Example** (Minimum Value) * @@ -1053,10 +940,8 @@ export const isGreaterThanOrEqualTo = (O: Order): { * console.log(minNumber(1, 1)) // 1 * ``` * - * See also: - * - {@link max} - Maximum of two values - * - {@link clamp} - Clamp a value between min and max - * + * @see {@link max} for the maximum of two values + * @see {@link clamp} to clamp a value between min and max * @category comparisons * @since 2.0.0 */ @@ -1068,16 +953,15 @@ export const min = (O: Order): { /** * Returns the maximum of two values according to the given order. If they are equal, returns the first argument. * - * When to use this: - * - When you need to find the larger of two values - * - When implementing min/max operations - * - When selecting values based on ordering + * **When to use** + * + * Use when you need to select the larger of two values according to an + * `Order`. * - * Behavior: - * - Pure function: does not mutate inputs - * - Returns the value that compares as greater than or equal to the other - * - If values are equal, returns the first argument - * - Supports curried and uncurried call styles + * **Details** + * + * Returns the value that compares as greater than or equal to the other value. + * If values are equal, the first argument is returned. * * **Example** (Maximum Value) * @@ -1091,10 +975,8 @@ export const min = (O: Order): { * console.log(maxNumber(1, 1)) // 1 * ``` * - * See also: - * - {@link min} - Minimum of two values - * - {@link clamp} - Clamp a value between min and max - * + * @see {@link min} for the minimum of two values + * @see {@link clamp} to clamp a value between min and max * @category comparisons * @since 2.0.0 */ @@ -1104,20 +986,19 @@ export const max = (O: Order): { } => dual(2, (self: A, that: A) => self === that || O(self, that) > -1 ? self : that) /** - * Clamps a value between a minimum and a maximum according to the given order. + * Restricts a value between a minimum and a maximum according to the given order. + * + * **When to use** * - * When to use this: - * - When you need to restrict a value to a specific range - * - When implementing bounds checking and normalization - * - When ensuring values stay within valid ranges + * Use when you need to clamp a value to an inclusive range according to an + * `Order`. * - * Behavior: - * - Pure function: does not mutate inputs - * - Returns the value if it's between minimum and maximum (inclusive) - * - Returns minimum if the value is less than minimum - * - Returns maximum if the value is greater than maximum - * - Supports curried and uncurried call styles - * - Requires that minimum <= maximum according to the order + * **Details** + * + * Returns the value itself when it is between minimum and maximum, inclusive. + * Values below the range return minimum, and values above the range return + * maximum. The minimum must be less than or equal to the maximum according to + * the order. * * **Example** (Clamping Values) * @@ -1131,11 +1012,9 @@ export const max = (O: Order): { * console.log(clamp(6)) // 5 * ``` * - * See also: - * - {@link min} - Minimum of two values - * - {@link max} - Maximum of two values - * - {@link isBetween} - Check if a value is within a range - * + * @see {@link min} for the minimum of two values + * @see {@link max} for the maximum of two values + * @see {@link isBetween} to check if a value is within a range * @category comparisons * @since 2.0.0 */ @@ -1158,19 +1037,19 @@ export const clamp = (O: Order): { ) /** - * Tests whether a value is between a minimum and a maximum (inclusive) according to the given order. + * Checks whether a value is between a minimum and a maximum (inclusive) according to the given order. + * + * **When to use** * - * When to use this: - * - When validating that a value is within a valid range - * - When implementing range checks for bounds validation - * - When filtering or selecting values within a range + * Use when you need range checks that respect domain-specific ordering, such as + * dates, versions, or custom priorities, instead of JavaScript numeric + * comparison. * - * Behavior: - * - Pure function: does not mutate inputs - * - Returns `true` if the value is greater than or equal to minimum and less than or equal to maximum - * - Returns `false` if the value is outside the range - * - Supports curried and uncurried call styles - * - Both bounds are inclusive + * **Details** + * + * Returns `true` when the value is greater than or equal to minimum and less + * than or equal to maximum. Values outside the range return `false`. Both + * bounds are inclusive. * * **Example** (Checking Range) * @@ -1186,11 +1065,9 @@ export const clamp = (O: Order): { * console.log(betweenNumber(11, { minimum: 1, maximum: 10 })) // false * ``` * - * See also: - * - {@link clamp} - Clamp a value to a range - * - {@link isLessThanOrEqualTo} - Less than or equal check - * - {@link isGreaterThanOrEqualTo} - Greater than or equal check - * + * @see {@link clamp} to clamp a value to a range + * @see {@link isLessThanOrEqualTo} for less than or equal check + * @see {@link isGreaterThanOrEqualTo} for greater than or equal check * @category predicates * @since 4.0.0 */ @@ -1215,16 +1092,16 @@ export const isBetween = (O: Order): { /** * Creates a `Reducer` for combining `Order` instances, useful for aggregating orders in collections. * - * When to use this: - * - When you need to combine multiple orders from a collection using reducer patterns - * - When implementing fold operations over collections of orders - * - When working with reducers that operate on orders + * **When to use** + * + * Use when you need a reducer that combines orders. * - * Behavior: - * - Returns a reducer that combines orders using {@link combine} - * - Uses {@link alwaysEqual} as the identity element (returns `0` for empty collections) - * - Uses {@link combineAll} for combining collections of orders - * - The reducer can be used with fold operations on collections + * **Details** + * + * Returns a reducer that combines orders using `combine`, uses `alwaysEqual` as + * the identity element for empty collections, and uses `combineAll` for + * combining collections of orders. The reducer can be used with fold operations + * on collections. * * **Example** (Creating a Reducer) * @@ -1238,12 +1115,10 @@ export const isBetween = (O: Order): { * console.log(combined(1, 2)) // -1 (uses first order) * ``` * - * See also: - * - {@link combine} - Combine two orders - * - {@link combineAll} - Combine multiple orders - * - {@link Reducer} - Reducer type for collection operations - * - * @category utilities + * @see {@link combine} to combine two orders + * @see {@link combineAll} to combine multiple orders + * @see {@link Reducer} for reducing orders as a collection operation + * @category constructors * @since 4.0.0 */ export function makeReducer() { diff --git a/.opencode/node_modules/effect/src/Ordering.ts b/.opencode/node_modules/effect/src/Ordering.ts index e182b7714f253fd6b706f0bf9ad6c038def0955c..b2066ed90dd8bc28c4da79cccdc27ca5ca239922 100644 --- a/.opencode/node_modules/effect/src/Ordering.ts +++ b/.opencode/node_modules/effect/src/Ordering.ts @@ -1,29 +1,11 @@ /** - * @fileoverview - * The Ordering module provides utilities for working with comparison results and ordering operations. - * An Ordering represents the result of comparing two values, expressing whether the first value is - * less than (-1), equal to (0), or greater than (1) the second value. - * - * This module is fundamental for building comparison functions, sorting algorithms, and implementing - * ordered data structures. It provides composable operations for combining multiple comparison results - * and pattern matching on ordering outcomes. - * - * Key Features: - * - Type-safe representation of comparison results (-1, 0, 1) - * - Composable operations for combining multiple orderings - * - Pattern matching utilities for handling different ordering cases - * - Ordering reversal and combination functions - * - Integration with Effect's functional programming patterns - * - * Common Use Cases: - * - Implementing custom comparison functions - * - Building complex sorting criteria - * - Combining multiple comparison results - * - Creating ordered data structures - * - Pattern matching on comparison outcomes + * The standard result of comparing two values. An `Ordering` is `-1` when the + * first value is less than the second, `0` when both values compare as equal, + * and `1` when the first value is greater than the second. This module also + * provides helpers for reversing an ordering, matching on the three cases, and + * combining ordered comparison results with a reducer. * * @since 2.0.0 - * @category utilities */ import type { LazyArg } from "./Function.ts" import { dual } from "./Function.ts" @@ -32,11 +14,19 @@ import * as Reducer_ from "./Reducer.ts" /** * Represents the result of comparing two values. * + * **When to use** + * + * Use to model a normalized comparison result that is exactly less than, + * equal to, or greater than. + * + * **Details** + * * - `-1` indicates the first value is less than the second * - `0` indicates the values are equal * - `1` indicates the first value is greater than the second * - * @example + * **Example** (Defining comparison results) + * * ```ts * import type { Ordering } from "effect" * @@ -57,16 +47,22 @@ import * as Reducer_ from "./Reducer.ts" * } * ``` * - * @category model + * @category models * @since 2.0.0 */ export type Ordering = -1 | 0 | 1 /** - * Inverts the ordering of the input Ordering. + * Reverses the ordering of the input Ordering. * This is useful for creating descending sort orders from ascending ones. * - * @example + * **When to use** + * + * Use to flip an ordering result when reversing sort direction or comparison + * priority. + * + * **Example** (Reversing comparison order) + * * ```ts * import { Ordering } from "effect" * @@ -93,24 +89,28 @@ export type Ordering = -1 | 0 | 1 * } * ``` * - * @category transformations + * @category transforming * @since 2.0.0 */ export const reverse = (o: Ordering): Ordering => (o === -1 ? 1 : o === 1 ? -1 : 0) /** - * Depending on the `Ordering` parameter given to it, returns a value produced by one of the 3 functions provided as parameters. + * Matches an `Ordering` value and returns the branch selected by that ordering. + * + * **When to use** + * + * Use to branch on the three possible comparison outcomes in one expression. + * + * **Example** (Pattern matching on orderings) * - * @example * ```ts - * import { Ordering } from "effect" - * import { constant } from "effect/Function" + * import { Function, Ordering } from "effect" * import * as assert from "node:assert" * * const toMessage = Ordering.match({ - * onLessThan: constant("less than"), - * onEqual: constant("equal"), - * onGreaterThan: constant("greater than") + * onLessThan: Function.constant("less than"), + * onEqual: Function.constant("equal"), + * onGreaterThan: Function.constant("greater than") * }) * * assert.deepStrictEqual(toMessage(-1), "less than") @@ -123,18 +123,22 @@ export const reverse = (o: Ordering): Ordering => (o === -1 ? 1 : o === 1 ? -1 : */ export const match: { /** - * Depending on the `Ordering` parameter given to it, returns a value produced by one of the 3 functions provided as parameters. + * Matches an `Ordering` value and returns the branch selected by that ordering. + * + * **When to use** + * + * Use to branch on the three possible comparison outcomes in one expression. + * + * **Example** (Pattern matching on orderings) * - * @example * ```ts - * import { Ordering } from "effect" - * import { constant } from "effect/Function" + * import { Function, Ordering } from "effect" * import * as assert from "node:assert" * * const toMessage = Ordering.match({ - * onLessThan: constant("less than"), - * onEqual: constant("equal"), - * onGreaterThan: constant("greater than") + * onLessThan: Function.constant("less than"), + * onEqual: Function.constant("equal"), + * onGreaterThan: Function.constant("greater than") * }) * * assert.deepStrictEqual(toMessage(-1), "less than") @@ -153,18 +157,22 @@ export const match: { } ): (self: Ordering) => A | B | C /** - * Depending on the `Ordering` parameter given to it, returns a value produced by one of the 3 functions provided as parameters. + * Matches an `Ordering` value and returns the branch selected by that ordering. + * + * **When to use** + * + * Use to branch on the three possible comparison outcomes in one expression. + * + * **Example** (Pattern matching on orderings) * - * @example * ```ts - * import { Ordering } from "effect" - * import { constant } from "effect/Function" + * import { Function, Ordering } from "effect" * import * as assert from "node:assert" * * const toMessage = Ordering.match({ - * onLessThan: constant("less than"), - * onEqual: constant("equal"), - * onGreaterThan: constant("greater than") + * onLessThan: Function.constant("less than"), + * onEqual: Function.constant("equal"), + * onGreaterThan: Function.constant("greater than") * }) * * assert.deepStrictEqual(toMessage(-1), "less than") @@ -193,11 +201,24 @@ export const match: { ): A | B | C => self === -1 ? onLessThan() : self === 0 ? onEqual() : onGreaterThan()) /** - * A `Reducer` for combining `Ordering`s. + * Reducer for combining `Ordering`s. + * + * **When to use** + * + * Use to combine multiple comparison results in priority order, such as + * checking secondary criteria only when earlier criteria compare as equal. + * + * **Details** * * If any of the `Ordering`s is non-zero, the result is the first non-zero `Ordering`. * If all the `Ordering`s are zero, the result is zero. * + * **Gotchas** + * + * `combineAll` stops consuming the iterable as soon as it finds a non-zero + * `Ordering`. + * + * @category ordering * @since 4.0.0 */ export const Reducer: Reducer_.Reducer = Reducer_.make( diff --git a/.opencode/node_modules/effect/src/PartitionedSemaphore.ts b/.opencode/node_modules/effect/src/PartitionedSemaphore.ts index ebb25ecaa40ad9997c487d82f7acc0775a27c778..dd4f4ea0718b360355676828558dd1064007c632 100644 --- a/.opencode/node_modules/effect/src/PartitionedSemaphore.ts +++ b/.opencode/node_modules/effect/src/PartitionedSemaphore.ts @@ -1,4 +1,10 @@ /** + * The `PartitionedSemaphore` module provides a semaphore for limiting + * concurrency across a shared permit pool while keeping waiters grouped by + * partition key. A `PartitionedSemaphore` is useful when many independent + * groups of work compete for the same bounded resource and each group should + * make progress without one busy group monopolizing released permits. + * * @since 4.0.0 */ import * as Effect from "./Effect.ts" @@ -7,14 +13,33 @@ import * as MutableHashMap from "./MutableHashMap.ts" import * as Option from "./Option.ts" /** + * Runtime type identifier used to mark values that implement + * `PartitionedSemaphore`. + * + * **Details** + * + * This marker is part of the runtime representation of partitioned semaphore + * values. + * + * @category type IDs * @since 4.0.0 - * @category models */ export const PartitionedTypeId: PartitionedTypeId = "~effect/PartitionedSemaphore" /** + * Literal type of the `PartitionedSemaphore` runtime type identifier. + * + * **When to use** + * + * Use to type fields that store the exact `PartitionedSemaphore` runtime marker. + * + * **Details** + * + * Use this type when declaring fields that must contain the exact + * `PartitionedTypeId` marker value. + * + * @category type IDs * @since 4.0.0 - * @category models */ export type PartitionedTypeId = "~effect/PartitionedSemaphore" @@ -22,10 +47,17 @@ export type PartitionedTypeId = "~effect/PartitionedSemaphore" * A `PartitionedSemaphore` controls access to a shared permit pool while * tracking waiters by partition key. * + * **When to use** + * + * Use to coordinate shared permits across partition keys so waiting groups make + * progress without one group monopolizing the pool. + * + * **Details** + * * Waiting permits are distributed across partitions in round-robin order. * - * @since 4.0.0 * @category models + * @since 3.19.4 */ export interface PartitionedSemaphore { readonly [PartitionedTypeId]: PartitionedTypeId @@ -44,16 +76,41 @@ export interface PartitionedSemaphore { } /** - * @since 4.0.0 + * Alias interface for a `PartitionedSemaphore` keyed by values of type `K`. + * + * **When to use** + * + * Use as an alternate exported name for a partitioned permit pool keyed by `K`. + * + * **Details** + * + * This interface does not add members beyond `PartitionedSemaphore`; it + * provides an alternate exported name for APIs that refer to a partitioned + * permit pool. + * * @category models + * @since 4.0.0 */ export interface Partitioned extends PartitionedSemaphore {} /** - * Creates a `PartitionedSemaphore` unsafely. + * Constructs a `PartitionedSemaphore` synchronously, outside of `Effect`. + * + * **When to use** + * + * Use when you need to construct a partitioned semaphore synchronously outside + * an `Effect` workflow. + * + * **Details** + * + * Negative permit counts are clamped to `0`. Non-finite permit counts create + * an unbounded semaphore whose acquire and release operations complete + * immediately. + * + * @see {@link make} for creating a partitioned semaphore inside `Effect` * - * @since 4.0.0 * @category constructors + * @since 3.19.4 */ export const makeUnsafe = (options: { readonly permits: number @@ -243,10 +300,27 @@ export const makeUnsafe = (options: { } /** - * Creates a `PartitionedSemaphore`. + * Creates a `PartitionedSemaphore` inside an `Effect`. + * + * **When to use** + * + * Use when semaphore construction should stay inside an `Effect` workflow. + * + * **Details** + * + * The `permits` option sets the shared permit capacity. The resulting + * semaphore tracks waiters by partition key and distributes released permits + * across waiting partitions in round-robin order. + * + * **Gotchas** + * + * Negative permit counts are clamped to `0`. Non-finite permit counts create + * an unbounded semaphore. + * + * @see {@link makeUnsafe} for synchronous construction * - * @since 4.0.0 * @category constructors + * @since 3.19.4 */ export const make = (options: { readonly permits: number @@ -255,84 +329,293 @@ export const make = (options: { /** * Gets the current number of available permits. * - * @since 4.0.0 + * **When to use** + * + * Use to inspect a snapshot of how many permits are currently free. + * + * **Details** + * + * Running the returned effect reads the semaphore's current availability. + * Taking permits decreases availability, and releasing permits can increase it + * up to the semaphore capacity. + * + * **Gotchas** + * + * Reading availability does not reserve permits. + * + * @see {@link capacity} for the fixed total permit capacity + * @see {@link release} for returning permits to the shared pool + * @see {@link withPermitsIfAvailable} for running only when permits are immediately available + * * @category combinators + * @since 4.0.0 */ export const available = (self: PartitionedSemaphore): Effect.Effect => self.available /** * Gets the total capacity. * - * @since 4.0.0 + * **When to use** + * + * Use to inspect the fixed number of permits configured for the semaphore. + * + * **Details** + * + * Capacity is stored when the semaphore is created and does not change as + * permits are acquired or released. + * + * @see {@link available} for the current number of free permits + * * @category getters + * @since 4.0.0 */ export const capacity = (self: PartitionedSemaphore): number => self.capacity /** - * Acquires permits for a partition. + * Returns an effect that acquires the requested number of permits for the + * given partition key. + * + * **When to use** + * + * Use when you need manual permit acquisition for a partition and want to + * control acquisition and release as separate effects. + * + * **Details** + * + * If enough permits are available, the effect completes immediately. Otherwise + * it waits until released permits are assigned to this partition. + * + * **Gotchas** + * + * Requests for more permits than the semaphore capacity never complete. + * Requests for zero or a negative number of permits complete without acquiring + * anything. + * + * @see {@link release} for manually returning permits to the shared pool + * @see {@link withPermits} for automatic acquire and release around an effect + * @see {@link withPermit} for acquiring exactly one permit around an effect * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const take: { /** - * Acquires permits for a partition. + * Returns an effect that acquires the requested number of permits for the + * given partition key. + * + * **When to use** + * + * Use when you need manual permit acquisition for a partition and want to + * control acquisition and release as separate effects. + * + * **Details** + * + * If enough permits are available, the effect completes immediately. Otherwise + * it waits until released permits are assigned to this partition. + * + * **Gotchas** + * + * Requests for more permits than the semaphore capacity never complete. + * Requests for zero or a negative number of permits complete without acquiring + * anything. + * + * @see {@link release} for manually returning permits to the shared pool + * @see {@link withPermits} for automatic acquire and release around an effect + * @see {@link withPermit} for acquiring exactly one permit around an effect * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (key: K, permits: number): (self: PartitionedSemaphore) => Effect.Effect /** - * Acquires permits for a partition. + * Returns an effect that acquires the requested number of permits for the + * given partition key. + * + * **When to use** + * + * Use when you need manual permit acquisition for a partition and want to + * control acquisition and release as separate effects. + * + * **Details** + * + * If enough permits are available, the effect completes immediately. Otherwise + * it waits until released permits are assigned to this partition. + * + * **Gotchas** + * + * Requests for more permits than the semaphore capacity never complete. + * Requests for zero or a negative number of permits complete without acquiring + * anything. + * + * @see {@link release} for manually returning permits to the shared pool + * @see {@link withPermits} for automatic acquire and release around an effect + * @see {@link withPermit} for acquiring exactly one permit around an effect * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: PartitionedSemaphore, key: K, permits: number): Effect.Effect } = dual(3, (self: PartitionedSemaphore, key: K, permits: number): Effect.Effect => self.take(key, permits)) /** - * Releases permits back to the shared pool. + * Returns an effect that releases permits back to the shared pool and returns + * the current available permit count. + * + * **When to use** + * + * Use when you need to return permits acquired with `take` in a lower-level + * partitioned permit protocol with explicit release control. + * + * **Details** + * + * Released permits are first assigned to waiting partitions in round-robin + * order. Only permits not needed by waiters increase the available count, + * which is capped at the semaphore capacity. + * + * @see {@link take} for manual acquisition + * @see {@link withPermits} for automatic acquire and release around an effect + * @see {@link available} for reading the permit count without releasing * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const release: { /** - * Releases permits back to the shared pool. + * Returns an effect that releases permits back to the shared pool and returns + * the current available permit count. + * + * **When to use** + * + * Use when you need to return permits acquired with `take` in a lower-level + * partitioned permit protocol with explicit release control. + * + * **Details** + * + * Released permits are first assigned to waiting partitions in round-robin + * order. Only permits not needed by waiters increase the available count, + * which is capped at the semaphore capacity. + * + * @see {@link take} for manual acquisition + * @see {@link withPermits} for automatic acquire and release around an effect + * @see {@link available} for reading the permit count without releasing * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (permits: number): (self: PartitionedSemaphore) => Effect.Effect /** - * Releases permits back to the shared pool. + * Returns an effect that releases permits back to the shared pool and returns + * the current available permit count. + * + * **When to use** + * + * Use when you need to return permits acquired with `take` in a lower-level + * partitioned permit protocol with explicit release control. + * + * **Details** + * + * Released permits are first assigned to waiting partitions in round-robin + * order. Only permits not needed by waiters increase the available count, + * which is capped at the semaphore capacity. + * + * @see {@link take} for manual acquisition + * @see {@link withPermits} for automatic acquire and release around an effect + * @see {@link available} for reading the permit count without releasing * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: PartitionedSemaphore, permits: number): Effect.Effect } = dual(2, (self: PartitionedSemaphore, permits: number): Effect.Effect => self.release(permits)) /** - * Runs an effect with permits for a partition. + * Runs an effect after acquiring permits for a partition, then releases those + * permits when the effect exits. + * + * **When to use** + * + * Use to guard weighted partitioned work with automatic permit acquisition and + * release around an effect. + * + * **Details** + * + * Permit acquisition may wait according to `take` semantics. Once acquired, + * the permits are released even if the wrapped effect fails or is interrupted. + * + * **Gotchas** + * + * Requests for more permits than the semaphore capacity never complete. + * Requests for zero or a negative number of permits run the effect without + * acquiring anything. + * + * @see {@link withPermit} for the single-permit variant + * @see {@link withPermitsIfAvailable} for running only when permits are + * immediately available + * @see {@link take} for manual acquisition + * @see {@link release} for manual release * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const withPermits: { /** - * Runs an effect with permits for a partition. + * Runs an effect after acquiring permits for a partition, then releases those + * permits when the effect exits. + * + * **When to use** + * + * Use to guard weighted partitioned work with automatic permit acquisition and + * release around an effect. + * + * **Details** + * + * Permit acquisition may wait according to `take` semantics. Once acquired, + * the permits are released even if the wrapped effect fails or is interrupted. + * + * **Gotchas** + * + * Requests for more permits than the semaphore capacity never complete. + * Requests for zero or a negative number of permits run the effect without + * acquiring anything. + * + * @see {@link withPermit} for the single-permit variant + * @see {@link withPermitsIfAvailable} for running only when permits are + * immediately available + * @see {@link take} for manual acquisition + * @see {@link release} for manual release * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: PartitionedSemaphore, key: K, permits: number): (effect: Effect.Effect) => Effect.Effect /** - * Runs an effect with permits for a partition. + * Runs an effect after acquiring permits for a partition, then releases those + * permits when the effect exits. + * + * **When to use** + * + * Use to guard weighted partitioned work with automatic permit acquisition and + * release around an effect. + * + * **Details** + * + * Permit acquisition may wait according to `take` semantics. Once acquired, + * the permits are released even if the wrapped effect fails or is interrupted. + * + * **Gotchas** + * + * Requests for more permits than the semaphore capacity never complete. + * Requests for zero or a negative number of permits run the effect without + * acquiring anything. + * + * @see {@link withPermit} for the single-permit variant + * @see {@link withPermitsIfAvailable} for running only when permits are + * immediately available + * @see {@link take} for manual acquisition + * @see {@link release} for manual release * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ ( self: PartitionedSemaphore, @@ -350,24 +633,75 @@ export const withPermits: { }) as any /** - * Runs an effect with a single permit for a partition. + * Runs an effect after acquiring one permit for a partition, then releases the + * permit when the effect exits. + * + * **When to use** + * + * Use to guard partitioned work with exactly one permit and automatic release + * when the effect exits. + * + * **Details** + * + * This is the single-permit variant of `withPermits`. The permit is released + * even if the wrapped effect fails or is interrupted. + * + * @see {@link withPermits} for acquiring a weighted number of permits + * @see {@link withPermitsIfAvailable} for running only when permits are + * immediately available + * @see {@link take} for manual acquisition + * @see {@link release} for manual release * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const withPermit: { /** - * Runs an effect with a single permit for a partition. + * Runs an effect after acquiring one permit for a partition, then releases the + * permit when the effect exits. + * + * **When to use** + * + * Use to guard partitioned work with exactly one permit and automatic release + * when the effect exits. + * + * **Details** + * + * This is the single-permit variant of `withPermits`. The permit is released + * even if the wrapped effect fails or is interrupted. + * + * @see {@link withPermits} for acquiring a weighted number of permits + * @see {@link withPermitsIfAvailable} for running only when permits are + * immediately available + * @see {@link take} for manual acquisition + * @see {@link release} for manual release * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: PartitionedSemaphore, key: K): (effect: Effect.Effect) => Effect.Effect /** - * Runs an effect with a single permit for a partition. + * Runs an effect after acquiring one permit for a partition, then releases the + * permit when the effect exits. + * + * **When to use** + * + * Use to guard partitioned work with exactly one permit and automatic release + * when the effect exits. + * + * **Details** + * + * This is the single-permit variant of `withPermits`. The permit is released + * even if the wrapped effect fails or is interrupted. + * + * @see {@link withPermits} for acquiring a weighted number of permits + * @see {@link withPermitsIfAvailable} for running only when permits are + * immediately available + * @see {@link take} for manual acquisition + * @see {@link release} for manual release * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: PartitionedSemaphore, key: K, effect: Effect.Effect): Effect.Effect } = ((...args: Array) => { @@ -380,24 +714,72 @@ export const withPermit: { }) as any /** - * Runs an effect only if the permits are immediately available. + * Runs an effect only when the requested permits can be acquired immediately, + * returning the result in `Some`. + * + * **When to use** + * + * Use when guarded work should run only if the shared permit pool can provide + * the requested permits immediately. + * + * **Details** + * + * If the permits are not available, the effect is not run and the result is + * `None`. When permits are acquired, they are released after the wrapped + * effect completes, fails, or is interrupted. Requests for zero or a negative + * number of permits run the effect and return `Some`. + * + * @see {@link withPermits} for the keyed variant that waits until permits are + * available for a partition * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const withPermitsIfAvailable: { /** - * Runs an effect only if the permits are immediately available. + * Runs an effect only when the requested permits can be acquired immediately, + * returning the result in `Some`. + * + * **When to use** + * + * Use when guarded work should run only if the shared permit pool can provide + * the requested permits immediately. + * + * **Details** + * + * If the permits are not available, the effect is not run and the result is + * `None`. When permits are acquired, they are released after the wrapped + * effect completes, fails, or is interrupted. Requests for zero or a negative + * number of permits run the effect and return `Some`. + * + * @see {@link withPermits} for the keyed variant that waits until permits are + * available for a partition * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: PartitionedSemaphore, permits: number): (effect: Effect.Effect) => Effect.Effect, E, R> /** - * Runs an effect only if the permits are immediately available. + * Runs an effect only when the requested permits can be acquired immediately, + * returning the result in `Some`. + * + * **When to use** + * + * Use when guarded work should run only if the shared permit pool can provide + * the requested permits immediately. + * + * **Details** + * + * If the permits are not available, the effect is not run and the result is + * `None`. When permits are acquired, they are released after the wrapped + * effect completes, fails, or is interrupted. Requests for zero or a negative + * number of permits run the effect and return `Some`. + * + * @see {@link withPermits} for the keyed variant that waits until permits are + * available for a partition * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ ( self: PartitionedSemaphore, diff --git a/.opencode/node_modules/effect/src/Path.ts b/.opencode/node_modules/effect/src/Path.ts index b761135d2a081c9576b3ef4356fdfbe88a28aa83..8acb1fdbee40e50b5c366f489a62685d5e6c433d 100644 --- a/.opencode/node_modules/effect/src/Path.ts +++ b/.opencode/node_modules/effect/src/Path.ts @@ -1,4 +1,12 @@ /** + * Provides path operations through the Effect environment. + * + * The `Path` service works with file system paths without tying code to one + * concrete platform module. It exposes common operations such as joining, + * normalizing, parsing, formatting, resolving, and converting paths to or from + * file URLs. This module includes the service interface, parsed path type, + * service tag, runtime marker, and built-in POSIX path layer. + * * @since 4.0.0 */ import * as Context from "./Context.ts" @@ -8,14 +16,37 @@ import * as Layer from "./Layer.ts" import { BadArgument } from "./PlatformError.ts" /** + * Runtime type identifier used to mark implementations of the `Path` service. + * + * **Details** + * + * The marker is the exact string stored on `Path` service implementations. + * Most code should depend on the `Path` service instead of inspecting this + * value directly. + * + * @see {@link layer} for the built-in POSIX `Path` service layer + * + * @category type IDs * @since 4.0.0 */ export const TypeId = "~effect/platform/Path" /** - * @since 4.0.0 - * @category model - * @example + * Defines the service interface for platform-specific path manipulation. + * + * **When to use** + * + * Use to depend on path operations through the Effect environment instead of a + * concrete host path module. + * + * **Details** + * + * The service exposes operations for joining, normalizing, parsing, + * formatting, and converting file system paths. URL conversion methods return + * `Effect`s because invalid file URLs or paths can fail with `BadArgument`. + * + * **Example** (Using path operations) + * * ```ts * import { Effect, Path } from "effect" * @@ -46,6 +77,9 @@ export const TypeId = "~effect/platform/Path" * }) * }) * ``` + * + * @category models + * @since 4.0.0 */ export interface Path { readonly [TypeId]: typeof TypeId @@ -66,9 +100,14 @@ export interface Path { } /** - * @since 4.0.0 - * @category namespace - * @example + * Namespace containing types associated with the `Path` service. + * + * **When to use** + * + * Use to reference types associated with path parsing and formatting. + * + * **Example** (Working with parsed paths) + * * ```ts * import { Effect, Path } from "effect" * @@ -91,12 +130,26 @@ export interface Path { * console.log(parsed, exampleParsed) * }) * ``` + * + * @since 4.0.0 */ export declare namespace Path { /** - * @since 4.0.0 - * @category model - * @example + * Structured representation of a parsed file system path. + * + * **When to use** + * + * Use to model the object form produced by `Path.parse` and consumed by + * `Path.format`. + * + * **Details** + * + * The fields correspond to the path root, directory, base filename, + * extension, and filename without extension, matching the shape consumed by + * `Path.format`. + * + * **Example** (Parsing and formatting paths) + * * ```ts * import { Effect, Path } from "effect" * @@ -123,6 +176,9 @@ export declare namespace Path { * console.log(formatted) // "/home/user/newfile.ts" * }) * ``` + * + * @category models + * @since 4.0.0 */ export interface Parsed { readonly root: string @@ -134,9 +190,14 @@ export declare namespace Path { } /** - * @since 4.0.0 - * @category tag - * @example + * Service tag for accessing the current `Path` implementation. + * + * **When to use** + * + * Use when you need path operations supplied by an effect's environment. + * + * **Example** (Providing a custom Path service) + * * ```ts * import { Effect, Layer, Path } from "effect" * @@ -190,6 +251,9 @@ export declare namespace Path { * // Run with custom path implementation * const result = Effect.provide(program, customPathLayer) * ``` + * + * @category services + * @since 4.0.0 */ export const Path: Context.Service = Context.Service("effect/Path") @@ -786,7 +850,21 @@ const posixImpl = Path.of({ }) /** + * Layer that provides the built-in POSIX `Path` implementation. + * + * **When to use** + * + * Use when you need an effect that requires the `Path` service to run with the + * built-in POSIX path implementation. + * + * **Details** + * + * The layer provides a static service whose separator is `/` and whose + * operations use POSIX path semantics. + * + * @see {@link Path} for accessing the `Path` service from an effect + * + * @category layers * @since 4.0.0 - * @category Layers */ export const layer: Layer.Layer = Layer.succeed(Path)(posixImpl) diff --git a/.opencode/node_modules/effect/src/Pipeable.ts b/.opencode/node_modules/effect/src/Pipeable.ts index 70b2ffede7761592c51250eab9c2b885832adc67..e58dfac8a89128eaa951ddda1fcca8c5c2dd9a2a 100644 --- a/.opencode/node_modules/effect/src/Pipeable.ts +++ b/.opencode/node_modules/effect/src/Pipeable.ts @@ -1,11 +1,31 @@ /** + * The `Pipeable` module defines the shared interface and implementation helpers + * for values that support Effect-style method chaining with `.pipe(...)`. + * + * A `Pipeable` value can pass itself through a sequence of unary functions from + * left to right, so code can be written as `value.pipe(f, g, h)` instead of + * deeply nesting calls. This is the method form used by many Effect data types + * to compose transformations, validations, and effectful operations while + * keeping the original value as the starting point of the pipeline. + * * @since 2.0.0 */ /** - * @since 2.0.0 - * @category models - * @example + * Interface for values that support method-style `pipe` composition. + * + * **When to use** + * + * Use to type values that expose an Effect-style `.pipe(...)` method. + * + * **Details** + * + * Calling `value.pipe(f, g, h)` passes the value through each function from + * left to right, returning the final result. Many Effect data types implement + * this so operations can be chained without nesting function calls. + * + * **Example** (Chaining operations with pipe) + * * ```ts * import { Effect } from "effect" * @@ -16,6 +36,9 @@ * Effect.tap((x) => Effect.log(`Result: ${x}`)) * ) * ``` + * + * @category models + * @since 2.0.0 */ export interface Pipeable { pipe(this: A): A @@ -500,24 +523,42 @@ export interface Pipeable { } /** - * @since 2.0.0 - * @category utilities - * @example + * Applies a `pipe` method's variadic arguments to an initial value from left + * to right. + * + * **When to use** + * + * Use to implement a custom `.pipe(...)` method from JavaScript's `arguments` + * object. + * + * **Details** + * + * This helper is intended for implementing `Pipeable.pipe` methods that + * receive JavaScript's `arguments` object. With no functions it returns the + * original value; otherwise it feeds each result into the next function. + * + * **Example** (Implementing a pipe method) + * * ```ts * import { Pipeable } from "effect" * - * // pipeArguments is used internally to implement efficient piping - * function customPipe(self: A, ...fns: Array<(a: any) => any>): unknown { - * return Pipeable.pipeArguments(self, arguments as any) - * } + * class NumberBox { + * constructor(readonly value: number) {} * - * // Example usage - * const add = (x: number) => (y: number) => x + y - * const multiply = (x: number) => (y: number) => x * y + * pipe(..._fns: ReadonlyArray<(value: number) => number>): number { + * return Pipeable.pipeArguments(this.value, arguments) as number + * } + * } * - * const result = customPipe(5, add(2), multiply(3)) + * const result = new NumberBox(5).pipe( + * (n) => n + 2, + * (n) => n * 3 + * ) * console.log(result) // 21 * ``` + * + * @category combinators + * @since 2.0.0 */ export const pipeArguments = (self: A, args: IArguments): unknown => { switch (args.length) { @@ -552,7 +593,15 @@ export const pipeArguments = (self: A, args: IArguments): unknown => { } /** - * @since 4.0.0 + * Reusable prototype that implements `Pipeable.pipe`. + * + * **When to use** + * + * Use when classes or object prototypes can reuse this value when they need the + * standard pipe implementation backed by `pipeArguments`. + * + * @category prototypes + * @since 3.15.0 */ export const Prototype: Pipeable = { pipe() { @@ -561,8 +610,16 @@ export const Prototype: Pipeable = { } /** - * @since 4.0.0 + * Provides a base constructor whose instances implement the standard `Pipeable.pipe` + * method. + * + * **When to use** + * + * Use when you need to define a class that supports Effect-style method + * chaining through `.pipe(...)`. + * * @category constructors + * @since 3.15.0 */ export const Class: new() => Pipeable = (function() { function PipeableBase() {} @@ -571,22 +628,47 @@ export const Class: new() => Pipeable = (function() { })() /** - * @since 4.0.0 + * Constructor type for classes whose instances implement `Pipeable`. + * + * **When to use** + * + * Use as the constructor-side type when a class value should be known to create + * instances that support Effect-style method chaining with `.pipe(...)`. + * + * @see {@link Pipeable} for the instance-side contract + * @see {@link Class} for the base constructor + * @see {@link Mixin} for wrapping an existing class constructor + * * @category models + * @since 3.15.0 */ export interface PipeableConstructor { new(...args: ReadonlyArray): Pipeable } /** - * @since 4.0.0 + * Returns a subclass of the provided class that adds the standard `pipe` + * method. + * + * **When to use** + * + * Use to add pipe support to an existing class without extending a base class + * or modifying its prototype. + * + * **Details** + * + * The original constructor and instance members are preserved, and the added + * method delegates to `pipeArguments`. + * + * @see {@link Prototype} for a reusable prototype object + * @see {@link Class} for a base constructor to extend * @category constructors + * @since 4.0.0 */ export const Mixin = ) => any>( klass: TBase -): TBase & PipeableConstructor => - (class extends klass { - pipe() { - return pipeArguments(this, arguments) - } - }) +): TBase & PipeableConstructor => (class extends klass { + pipe() { + return pipeArguments(this, arguments) + } +}) diff --git a/.opencode/node_modules/effect/src/PlatformError.ts b/.opencode/node_modules/effect/src/PlatformError.ts index bdd601c59c656be74835b529f4b3a1ed8fefe926..8b3dd7cea40cc74be8f07f0306819c80efc0c3f9 100644 --- a/.opencode/node_modules/effect/src/PlatformError.ts +++ b/.opencode/node_modules/effect/src/PlatformError.ts @@ -1,4 +1,12 @@ /** + * Normalized errors for platform APIs. + * + * Platform services such as file systems, terminals, and sockets use + * `PlatformError` to report host-level failures in a consistent shape. The + * wrapper records whether the problem came from an invalid argument or from the + * operating system, while preserving useful details such as the module, method, + * path, descriptor, description, and original cause when available. + * * @since 4.0.0 */ import * as Data from "./Data.ts" @@ -6,8 +14,24 @@ import * as Data from "./Data.ts" const TypeId = "~effect/platform/PlatformError" /** + * Error data for an invalid argument passed to a platform API. + * + * **When to use** + * + * Use when you need to model caller input rejected before a platform operation + * runs, including invalid-argument reason data. + * + * **Details** + * + * The error records the module and method that rejected the argument, with an + * optional description and cause. It is usually wrapped in `PlatformError`. + * + * @see {@link badArgument} for creating a wrapped `PlatformError` whose reason is `BadArgument` + * @see {@link SystemError} for failures reported by the host platform or operating system + * @see {@link PlatformError} for the wrapper used by most platform APIs + * + * @category models * @since 4.0.0 - * @category Models */ export class BadArgument extends Data.TaggedError("BadArgument")<{ module: string @@ -16,6 +40,12 @@ export class BadArgument extends Data.TaggedError("BadArgument")<{ cause?: unknown }> { /** + * Formats the module, method, and optional description that rejected the argument. + * + * **When to use** + * + * Use to read the formatted error message for a rejected platform argument. + * * @since 4.0.0 */ override get message(): string { @@ -24,8 +54,23 @@ export class BadArgument extends Data.TaggedError("BadArgument")<{ } /** + * Normalized category for failures reported by platform or system operations. + * + * **When to use** + * + * Use to type or match the normalized `_tag` on `SystemError` values reported + * by platform operations. + * + * **Details** + * + * The tags group lower-level platform errors into a stable set such as + * `NotFound`, `PermissionDenied`, `TimedOut`, and `Unknown`. + * + * @see {@link SystemError} for the error data that carries this tag on its `_tag` field + * @see {@link systemError} for creating a `PlatformError` from a system failure with one of these tags + * + * @category models * @since 4.0.0 - * @category Model */ export type SystemErrorTag = | "AlreadyExists" @@ -41,8 +86,25 @@ export type SystemErrorTag = | "WriteZero" /** - * @since 4.0.0 + * Error data for a platform or system operation failure. + * + * **When to use** + * + * Use when you need normalized reason data for a platform or system operation + * failure, including the operation details. + * + * **Details** + * + * The error records a normalized `_tag`, the module and method that failed, + * and optional details such as the syscall, path or descriptor, description, + * and original cause. It is usually wrapped in `PlatformError`. + * + * @see {@link systemError} for creating the usual `PlatformError` wrapper from this reason data + * @see {@link BadArgument} for platform API failures caused by rejected caller input before an operation runs + * @see {@link SystemErrorTag} for the normalized tag values stored in `_tag` + * * @category models + * @since 4.0.0 */ export class SystemError extends Data.Error<{ _tag: SystemErrorTag @@ -54,6 +116,12 @@ export class SystemError extends Data.Error<{ cause?: unknown }> { /** + * Formats the normalized system error tag with operation and path details. + * + * **When to use** + * + * Use to read the formatted error message for a normalized system failure. + * * @since 4.0.0 */ override get message(): string { @@ -64,8 +132,27 @@ export class SystemError extends Data.Error<{ } /** + * Tagged error used by platform APIs to report either invalid arguments or + * system-level failures. + * + * **When to use** + * + * Use as the shared error type for platform APIs that expose invalid arguments + * and host or operating-system failures through a single `Effect` error + * channel. + * + * **Details** + * + * The `reason` field contains the underlying `BadArgument` or `SystemError`. + * When that reason has a cause, the cause is preserved on the wrapper. + * + * @see {@link BadArgument} for invalid inputs rejected before an operation runs + * @see {@link SystemError} for failures reported by the host platform or operating system + * @see {@link badArgument} for creating this wrapper from rejected caller input + * @see {@link systemError} for creating this wrapper from a host or operating-system failure + * + * @category models * @since 4.0.0 - * @category Models */ export class PlatformError extends Data.TaggedError("PlatformError")<{ reason: BadArgument | SystemError @@ -79,6 +166,12 @@ export class PlatformError extends Data.TaggedError("PlatformError")<{ } /** + * Marks this value as a platform error wrapper for runtime guards. + * + * **When to use** + * + * Use to identify `PlatformError` values through their runtime type marker. + * * @since 4.0.0 */ readonly [TypeId]: typeof TypeId = TypeId @@ -89,8 +182,15 @@ export class PlatformError extends Data.TaggedError("PlatformError")<{ } /** - * @since 4.0.0 + * Creates a `PlatformError` whose reason is a `SystemError`. + * + * **When to use** + * + * Use to adapt an operating-system or platform failure into the normalized + * platform error model. + * * @category constructors + * @since 4.0.0 */ export const systemError = (options: { readonly _tag: SystemErrorTag @@ -103,8 +203,15 @@ export const systemError = (options: { }): PlatformError => new PlatformError(new SystemError(options)) /** - * @since 4.0.0 + * Creates a `PlatformError` whose reason is a `BadArgument`. + * + * **When to use** + * + * Use to report a platform API rejecting caller input before performing the + * underlying operation. + * * @category constructors + * @since 4.0.0 */ export const badArgument = (options: { readonly module: string diff --git a/.opencode/node_modules/effect/src/Pool.ts b/.opencode/node_modules/effect/src/Pool.ts index 578299cc3c67a79c6dc74574592940c702f358f0..d7ca646ae3e41cd6be7bf4cfaba2ad8526dd9c95 100644 --- a/.opencode/node_modules/effect/src/Pool.ts +++ b/.opencode/node_modules/effect/src/Pool.ts @@ -1,4 +1,12 @@ /** + * Shares scoped resources across fibers. + * + * A `Pool` acquires resource-backed values with a scoped effect, lets + * fibers borrow them with `get`, can invalidate broken values, and releases all + * acquired values when the pool scope closes. This module includes fixed-size + * pools, pools that resize with a time-to-live policy, custom strategy pools, + * per-item concurrency limits, and runtime state types used by pool strategies. + * * @since 2.0.0 */ import type * as Cause from "./Cause.ts" @@ -25,8 +33,19 @@ const TypeId = "~effect/Pool" * associated with the acquisition and release of resources. An attempt to get * an item `A` from a pool may fail with an error of type `E`. * - * @since 2.0.0 + * **When to use** + * + * Use when you need to share a bounded set of scoped resources across fibers + * while the pool manages acquisition, reuse, and release. + * + * @see {@link make} for creating a pool with size bounds + * @see {@link makeWithTTL} for creating a pool with idle item expiration + * @see {@link makeWithStrategy} for creating a pool with a custom strategy + * @see {@link get} for acquiring an item from a pool + * @see {@link invalidate} for removing a broken item from the pool + * * @category models + * @since 2.0.0 */ export interface Pool extends Pipeable { readonly [TypeId]: typeof TypeId @@ -35,8 +54,24 @@ export interface Pool extends Pipeable { } /** - * @since 4.0.0 + * Normalized configuration used by a `Pool`. + * + * **When to use** + * + * Use as the normalized, read-only description of how a pool acquires, sizes, + * shares, and resizes its items after construction. + * + * **Details** + * + * The config stores the acquire effect, size bounds, per-item concurrency, + * target utilization, and resizing strategy used by the pool implementation. + * + * @see {@link Pool} for the value exposing this configuration + * @see {@link State} for mutable runtime state instead of static configuration + * @see {@link Strategy} for the resizing and reclamation contract stored on the config + * * @category models + * @since 4.0.0 */ export interface Config { readonly acquire: Effect.Effect @@ -48,8 +83,28 @@ export interface Config { } /** - * @since 4.0.0 + * Mutable runtime state maintained by a `Pool`. + * + * **When to use** + * + * Use when you need to inspect or support the runtime state backing a `Pool`, + * including its scope, item sets, semaphores, waiters, invalidation tracking, + * and shutdown flag. + * + * **Details** + * + * This state tracks the pool scope, active and available items, invalidated + * items, semaphores, waiters, and shutdown status. It is exposed for + * inspection and implementation support; user code should prefer the + * high-level pool operations. + * + * @see {@link Pool} for the pool value exposing this state + * @see {@link PoolItem} for the entries stored in the runtime item sets + * @see {@link get} for acquiring items through the high-level API + * @see {@link invalidate} for invalidating items through the high-level API + * * @category models + * @since 4.0.0 */ export interface State { readonly scope: Scope.Scope @@ -64,8 +119,25 @@ export interface State { } /** - * @since 4.0.0 + * Internal record for a value managed by a `Pool`. + * + * **When to use** + * + * Use when implementing a custom pool `Strategy` that needs to inspect + * acquired items, track reference counts, or return reclaimable items to the + * pool. + * + * **Details** + * + * Each item stores the acquisition `Exit`, its finalizer, the current + * reference count, and whether automatic reclaiming has been disabled because + * the item was invalidated. + * + * @see {@link Strategy} for the custom strategy callbacks that receive and return pool items + * @see {@link State} for the runtime sets that store active, available, and invalidated pool items + * * @category models + * @since 4.0.0 */ export interface PoolItem { readonly exit: Exit.Exit @@ -75,8 +147,24 @@ export interface PoolItem { } /** - * @since 4.0.0 + * Strategy used by a `Pool` to manage background resizing and item + * reclamation. + * + * **When to use** + * + * Use when defining a custom pool lifecycle policy that needs to run background + * work, observe acquired items, or choose items for reclamation. + * + * **Details** + * + * `run` starts any strategy-specific background work, `onAcquire` is invoked + * when an item is acquired, and `reclaim` selects an item that can be removed + * or replaced. + * + * @see {@link makeWithStrategy} for constructing a pool from a custom `Strategy` + * * @category models + * @since 4.0.0 */ export interface Strategy { readonly run: (pool: Pool) => Effect.Effect @@ -87,16 +175,32 @@ export interface Strategy { /** * Returns `true` if the specified value is a `Pool`, `false` otherwise. * - * @since 2.0.0 + * **When to use** + * + * Use to validate unknown values at runtime boundaries before treating them as + * `Pool` values. + * + * **Details** + * + * This predicate narrows the input to `Pool`. + * * @category refinements + * @since 2.0.0 */ export const isPool = (u: unknown): u is Pool => hasProperty(u, TypeId) /** - * 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. + * Makes a new pool of the specified fixed size. + * + * **When to use** + * + * Use when you need a fixed-size pool with no growth or shrinkage. + * + * **Details** + * + * 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. * * By setting the `concurrency` parameter, you can control the level of concurrent * access per pool item. By default, the number of permits is set to `1`. @@ -108,8 +212,10 @@ export const isPool = (u: unknown): u is Pool => hasProperty(u * A `targetUtilization` of 0.5 will create new pool items when the existing items are * 50% utilized. * - * @since 2.0.0 + * @see {@link makeWithTTL} for pools with min/max sizes and a TTL-based shrinking policy + * @see {@link makeWithStrategy} for pools with a custom resizing and reclamation strategy * @category constructors + * @since 2.0.0 */ export const make = (options: { readonly acquire: Effect.Effect @@ -120,51 +226,61 @@ export const make = (options: { makeWithStrategy({ ...options, min: options.size, max: options.size, strategy: strategyNoop() }) /** - * 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. + * Creates a scoped pool with minimum and maximum sizes and a time-to-live + * policy for shrinking unused excess items. * - * By setting the `concurrency` parameter, you can control the level of concurrent - * access per pool item. By default, the number of permits is set to `1`. + * **When to use** * - * `targetUtilization` determines when to create new pool items. It is a value - * between 0 and 1, where 1 means only create new pool items when all the existing - * items are fully utilized. + * Use to create an elastic scoped pool that can grow up to a maximum size and + * later reclaim unused excess items. * - * A `targetUtilization` of 0.5 will create new pool items when the existing items are - * 50% utilized. + * **Details** * - * The `timeToLiveStrategy` determines how items are invalidated. If set to - * "creation", then items are invalidated based on their creation time. If set - * to "usage", then items are invalidated based on pool usage. + * The returned pool requires `Scope`; when that scope is closed, allocated + * items are released in an unspecified order. `concurrency` controls how many + * fibers may use each pool item at once and defaults to `1`. * - * By default, the `timeToLiveStrategy` is set to "usage". + * `targetUtilization` controls when new items are created and is clamped by the + * pool implementation. A value of `1` waits until existing items are fully + * utilized before creating more items. * - * ```ts skip-type-checking + * `timeToLiveStrategy` controls when excess items expire: `"creation"` measures + * from item creation, while `"usage"` measures from pool usage. The default is + * `"usage"`. + * + * **Example** (Create a connection pool) + * + * ```ts * import { Duration, Effect, Pool } from "effect" - * import { createConnection } from "mysql2" + * + * interface Connection { + * readonly execute: (sql: string) => Effect.Effect> + * readonly close: Effect.Effect + * } * * const acquireDBConnection = Effect.acquireRelease( - * Effect.sync(() => createConnection("mysql://...")), - * (connection) => Effect.sync(() => connection.end(() => {})) + * Effect.succeed({ + * execute: (sql) => Effect.succeed([`executed: ${sql}`]), + * close: Effect.void + * } satisfies Connection), + * (connection) => connection.close * ) * - * const connectionPool = Effect.flatMap( - * Pool.makeWithTTL({ - * acquire: acquireDBConnection, - * min: 10, - * max: 20, - * timeToLive: Duration.seconds(60) - * }), - * (pool) => pool.get + * const program = Effect.scoped( + * Effect.flatMap( + * Pool.makeWithTTL({ + * acquire: acquireDBConnection, + * min: 10, + * max: 20, + * timeToLive: Duration.seconds(60) + * }), + * (pool) => Effect.flatMap(Pool.get(pool), (connection) => connection.execute("select 1")) + * ) * ) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const makeWithTTL = (options: { readonly acquire: Effect.Effect @@ -183,8 +299,24 @@ export const makeWithTTL = (options: { ) /** - * @since 4.0.0 + * Creates a scoped pool using a custom resizing and reclamation strategy. + * + * **When to use** + * + * Use to build a pool whose item lifecycle is controlled by an explicit + * `Strategy`, such as custom background resizing, replacement, or reclamation. + * + * **Details** + * + * The returned pool requires `Scope`; closing the scope shuts down the pool and + * releases allocated items. + * + * @see {@link make} for fixed-size pools without custom resizing or reclamation + * @see {@link makeWithTTL} for min/max pools that shrink excess items with a TTL policy + * @see {@link Strategy} for the custom strategy contract consumed by this constructor + * * @category constructors + * @since 4.0.0 */ export const makeWithStrategy = (options: { readonly acquire: Effect.Effect @@ -265,12 +397,26 @@ const shutdown = Effect.fnUntraced(function*(self: Pool) { }) /** - * Retrieves an item from the pool 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. + * Retrieves an item from the pool in a scoped effect. + * + * **When to use** + * + * Use to borrow a pooled resource for the lifetime of the current scope so it + * is automatically returned when that scope closes. + * + * **Details** + * + * The returned effect waits for an available item when the pool is at capacity. + * If acquiring a new item fails, the effect fails with the acquisition error. + * + * **Gotchas** + * + * Retrying a failed `get` can repeat the acquisition attempt. + * + * @see {@link invalidate} for removing an unhealthy item from future reuse * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export const get = (self: Pool): Effect.Effect => Effect.suspend(() => { @@ -342,30 +488,63 @@ const getPoolItemInner = Effect.fnUntraced(function*( }) /** - * Invalidates the specified item. This will cause the pool to eventually - * reallocate the item, although this reallocation may occur lazily rather - * than eagerly. + * Invalidates the specified item so the pool can remove it and reallocate the + * item, lazily if needed. + * + * **When to use** + * + * Use to prevent a pooled item from being reused after it becomes unsuitable, + * such as a stale connection or a resource that failed a health check. + * + * **Gotchas** + * + * The item is matched with strict equality. Passing an equivalent but different + * object instance does nothing. + * + * @see {@link get} for retrieving scoped items from the pool * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ 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. + * Invalidates the specified item so the pool can remove it and reallocate the + * item, lazily if needed. + * + * **When to use** + * + * Use to prevent a pooled item from being reused after it becomes unsuitable, + * such as a stale connection or a resource that failed a health check. + * + * **Gotchas** + * + * The item is matched with strict equality. Passing an equivalent but different + * object instance does nothing. + * + * @see {@link get} for retrieving scoped items from the pool * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (item: A): (self: Pool) => Effect.Effect /** - * Invalidates the specified item. This will cause the pool to eventually - * reallocate the item, although this reallocation may occur lazily rather - * than eagerly. + * Invalidates the specified item so the pool can remove it and reallocate the + * item, lazily if needed. + * + * **When to use** + * + * Use to prevent a pooled item from being reused after it becomes unsuitable, + * such as a stale connection or a resource that failed a health check. + * + * **Gotchas** + * + * The item is matched with strict equality. Passing an equivalent but different + * object instance does nothing. + * + * @see {@link get} for retrieving scoped items from the pool * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (self: Pool, item: A): Effect.Effect } = dual(2, (self: Pool, item: A): Effect.Effect => diff --git a/.opencode/node_modules/effect/src/Predicate.ts b/.opencode/node_modules/effect/src/Predicate.ts index 15d8fa4af79e394c29c365d641555b67ab06130f..3afb4d040d51159c752591087e70cfba80447b7b 100644 --- a/.opencode/node_modules/effect/src/Predicate.ts +++ b/.opencode/node_modules/effect/src/Predicate.ts @@ -1,41 +1,11 @@ /** - * Predicate and Refinement helpers for runtime checks, filtering, and type narrowing. - * This module provides small, pure functions you can combine to decide whether a - * value matches a condition and, when using refinements, narrow TypeScript types. - * - * Mental model: - * - A `Predicate` is just `(a: A) => boolean`. - * - A `Refinement` is a predicate that narrows `A` to `B` when true. - * - Guards like `isString` are predicates/refinements for common runtime types. - * - Combinators like `and`/`or` build new predicates from existing ones. - * - `Tuple` and `Struct` lift element/property predicates to compound values. - * - * Common tasks: - * - Reuse an existing predicate on a different input shape -> {@link mapInput} - * - Combine checks -> {@link and}, {@link or}, {@link not}, {@link xor} - * - Build tuple/object checks -> {@link Tuple}, {@link Struct} - * - Narrow `unknown` to a concrete type -> {@link Refinement}, {@link compose} - * - Check runtime types -> {@link isString}, {@link isNumber}, {@link isObject} - * - * Gotchas: - * - `isTruthy` uses JavaScript truthiness; `0`, "", and `false` are false. - * - `isObject` excludes arrays; use {@link isObjectOrArray} for both. - * - `isIterable` treats strings as iterable. - * - `isPromise`/`isPromiseLike` are structural checks (then/catch), not `instanceof`. - * - `isTupleOf` and `isTupleOfAtLeast` only check length, not element types. - * - * **Example** (Filter by a predicate) + * Defines runtime checks for values. * - * ```ts - * import * as Predicate from "effect/Predicate" - * - * const isPositive = (n: number) => n > 0 - * const data = [2, -1, 3] - * - * console.log(data.filter(isPositive)) - * ``` - * - * See also: {@link Predicate}, {@link Refinement}, {@link and}, {@link or}, {@link mapInput} + * A `Predicate` returns `true` or `false` for an `A`. A + * `Refinement` is a predicate that also narrows the TypeScript type when + * it succeeds. This module includes guards for common JavaScript values, + * property and tag checks, tuple and struct checks, boolean combinators, and + * helpers for composing predicates and refinements. * * @since 2.0.0 */ @@ -46,15 +16,16 @@ import type { TupleOf, TupleOfAtLeast } from "./Types.ts" /** * A function that decides whether a value of type `A` satisfies a condition. * - * When to use: - * - You want a reusable boolean check for `A`. - * - You plan to combine checks with {@link and}/{@link or}. - * - You want a simple filter predicate for arrays or iterables. + * **When to use** + * + * Use when you want a reusable boolean check for `A`, especially when you plan + * to combine checks with {@link and}/{@link or} or pass a predicate to arrays + * and iterables. * - * Behavior: - * - Pure function; does not mutate input. - * - Returns `true` or `false`; never throws by itself. - * - Does not narrow types unless you use {@link Refinement}. + * **Details** + * + * A predicate returns `true` or `false` and never throws by itself. It does not + * narrow types unless you use `Refinement`. * * **Example** (Define a predicate) * @@ -66,8 +37,9 @@ import type { TupleOf, TupleOfAtLeast } from "./Types.ts" * console.log(isPositive(1)) * ``` * - * See also: {@link Refinement}, {@link mapInput}, {@link and} - * + * @see {@link Refinement} + * @see {@link mapInput} + * @see {@link and} * @category models * @since 2.0.0 */ @@ -78,13 +50,15 @@ export interface Predicate { /** * Type-level lambda for higher-kinded usage of {@link Predicate}. * - * When to use: - * - You are defining APIs that abstract over predicates with HKTs. - * - You need a `TypeLambda` instance for predicate-based type classes. + * **When to use** * - * Behavior: - * - Type-only; no runtime value is created. - * - Does not affect emitted JavaScript. + * Use when you are defining APIs that abstract over predicates with HKTs and + * need a `TypeLambda` instance for predicate-based type classes. + * + * **Details** + * + * This is type-only, creates no runtime value, and does not affect emitted + * JavaScript. * * **Example** (Type-level usage) * @@ -95,8 +69,7 @@ export interface Predicate { * type TL = Predicate.PredicateTypeLambda * ``` * - * See also: {@link Predicate} - * + * @see {@link Predicate} * @category type lambdas * @since 2.0.0 */ @@ -107,15 +80,16 @@ export interface PredicateTypeLambda extends TypeLambda { /** * A predicate that also narrows the input type when it returns `true`. * - * When to use: - * - You want a runtime check that refines `A` to `B` for TypeScript. - * - You want to compose multiple type guards with {@link compose}. - * - You need to guard `unknown` values safely. + * **When to use** + * + * Use when you want a runtime check that refines `A` to `B` for TypeScript, + * especially when composing type guards with {@link compose} or safely + * checking `unknown` values. + * + * **Details** * - * Behavior: - * - Pure function; does not mutate input. - * - Returns a type predicate (`a is B`). - * - Use with `if`/`filter` to narrow types. + * A refinement returns a type predicate (`a is B`). Use it with `if` or + * `filter` to narrow types. * * **Example** (Narrow unknown) * @@ -130,8 +104,9 @@ export interface PredicateTypeLambda extends TypeLambda { * } * ``` * - * See also: {@link Predicate}, {@link compose}, {@link isString} - * + * @see {@link Predicate} + * @see {@link compose} + * @see {@link isString} * @category models * @since 2.0.0 */ @@ -142,13 +117,15 @@ export interface Refinement { /** * Type-level utilities for working with {@link Predicate} types. * - * When to use: - * - You need to extract input types from predicate signatures. - * - You want to write generic helpers over predicate types. + * **When to use** + * + * Use when you need to extract input types from predicate signatures while + * writing generic helpers over predicate types. * - * Behavior: - * - Type-only; no runtime value is created. - * - The namespace is erased at runtime. + * **Details** + * + * These utilities are type-only, create no runtime values, and the namespace is + * erased at runtime. * * **Example** (Extract predicate input) * @@ -159,22 +136,23 @@ export interface Refinement { * type Input = Predicate.Predicate.In * ``` * - * See also: {@link Predicate}, {@link Refinement} - * + * @see {@link Predicate} + * @see {@link Refinement} * @since 3.6.0 - * @category type-level */ export declare namespace Predicate { /** * Extracts the input type `A` from a `Predicate`. * - * When to use: - * - You want to infer the input type from a predicate type. - * - You are defining generic utilities over predicates. + * **When to use** * - * Behavior: - * - Type-only; no runtime value is created. - * - Resolves to `never` if the type does not match `Predicate`. + * Use when you want to infer the input type from a predicate type while + * defining generic utilities over predicates. + * + * **Details** + * + * This is type-only and creates no runtime value. It resolves to `never` if + * the type does not match `Predicate`. * * **Example** (Infer input) * @@ -185,21 +163,23 @@ export declare namespace Predicate { * type Input = Predicate.Predicate.In

* ``` * - * See also: {@link Predicate.Any}, {@link Refinement.In} - * + * @see {@link Predicate.Any} + * @see {@link Refinement.In} + * @category utility types * @since 3.6.0 - * @category type-level */ export type In = [T] extends [Predicate] ? _A : never /** * A utility type representing any predicate type. * - * When to use: - * - You need a constraint for "any predicate" in generic code. + * **When to use** + * + * Use when you need a constraint for "any predicate" in generic code. + * + * **Details** * - * Behavior: - * - Type-only; no runtime value is created. + * This is type-only and creates no runtime value. * * **Example** (Generic constraint) * @@ -209,10 +189,9 @@ export declare namespace Predicate { * type AnyPredicate = Predicate.Predicate.Any * ``` * - * See also: {@link Predicate.In} - * + * @see {@link Predicate.In} + * @category utility types * @since 3.6.0 - * @category type-level */ export type Any = Predicate } @@ -220,13 +199,15 @@ export declare namespace Predicate { /** * Type-level utilities for working with {@link Refinement} types. * - * When to use: - * - You need to extract input/output types from refinement signatures. - * - You want to write generic helpers over refinements. + * **When to use** + * + * Use when you need to extract input and output types from refinement + * signatures while writing generic helpers over refinements. * - * Behavior: - * - Type-only; no runtime value is created. - * - The namespace is erased at runtime. + * **Details** + * + * These utilities are type-only, create no runtime values, and the namespace is + * erased at runtime. * * **Example** (Extract refinement types) * @@ -238,21 +219,22 @@ export declare namespace Predicate { * type Output = Predicate.Refinement.Out * ``` * - * See also: {@link Refinement}, {@link Predicate} - * + * @see {@link Refinement} + * @see {@link Predicate} * @since 3.6.0 - * @category type-level */ export declare namespace Refinement { /** * Extracts the input type `A` from a `Refinement`. * - * When to use: - * - You want to infer the input type from a refinement type. + * **When to use** * - * Behavior: - * - Type-only; no runtime value is created. - * - Resolves to `never` if the type does not match `Refinement`. + * Use when you want to infer the input type from a refinement type. + * + * **Details** + * + * This is type-only and creates no runtime value. It resolves to `never` if + * the type does not match `Refinement`. * * **Example** (Infer input) * @@ -263,10 +245,10 @@ export declare namespace Refinement { * type Input = Predicate.Refinement.In * ``` * - * See also: {@link Refinement.Out}, {@link Predicate.In} - * + * @see {@link Refinement.Out} + * @see {@link Predicate.In} + * @category utility types * @since 3.6.0 - * @category type-level */ export type In = [T] extends [Refinement] ? _A : never @@ -274,12 +256,14 @@ export declare namespace Refinement { /** * Extracts the output type `B` from a `Refinement`. * - * When to use: - * - You want to infer the narrowed type from a refinement type. + * **When to use** + * + * Use when you want to infer the narrowed type from a refinement type. * - * Behavior: - * - Type-only; no runtime value is created. - * - Resolves to `never` if the type does not match `Refinement`. + * **Details** + * + * This is type-only and creates no runtime value. It resolves to `never` if + * the type does not match `Refinement`. * * **Example** (Infer output) * @@ -290,21 +274,22 @@ export declare namespace Refinement { * type Output = Predicate.Refinement.Out * ``` * - * See also: {@link Refinement.In} - * + * @see {@link Refinement.In} + * @category utility types * @since 3.6.0 - * @category type-level */ export type Out = [T] extends [Refinement] ? _B : never /** * A utility type representing any refinement type. * - * When to use: - * - You need a constraint for "any refinement" in generic code. + * **When to use** + * + * Use when you need a constraint for "any refinement" in generic code. + * + * **Details** * - * Behavior: - * - Type-only; no runtime value is created. + * This is type-only and creates no runtime value. * * **Example** (Generic constraint) * @@ -314,10 +299,10 @@ export declare namespace Refinement { * type AnyRefinement = Predicate.Refinement.Any * ``` * - * See also: {@link Refinement.In}, {@link Refinement.Out} - * + * @see {@link Refinement.In} + * @see {@link Refinement.Out} + * @category utility types * @since 3.6.0 - * @category type-level */ export type Any = Refinement } @@ -325,14 +310,15 @@ export declare namespace Refinement { /** * Transforms the input of a predicate using a mapping function. * - * When to use: - * - You have a predicate on `A` and want one on `B` via `B -> A`. - * - You want to check derived values (lengths, projections, etc.). + * **When to use** + * + * Use when you have a predicate on `A` and want to check `B` values by mapping + * each `B` to an `A`, such as checking lengths or projections. + * + * **Details** * - * Behavior: - * - Pure; does not mutate input. - * - Returns a new predicate that applies `f` before `self`. - * - No short-circuit beyond what `self` does. + * Returns a new predicate that applies `f` before `self`. There is no + * additional short-circuiting beyond what `self` does. * * **Example** (Check string length) * @@ -346,8 +332,9 @@ export declare namespace Refinement { * console.log(isLongerThan2("hello")) * ``` * - * See also: {@link Predicate}, {@link and}, {@link not} - * + * @see {@link Predicate} + * @see {@link and} + * @see {@link not} * @category combinators * @since 2.0.0 */ @@ -355,14 +342,15 @@ export const mapInput: { /** * Transforms the input of a predicate using a mapping function. * - * When to use: - * - You have a predicate on `A` and want one on `B` via `B -> A`. - * - You want to check derived values (lengths, projections, etc.). + * **When to use** + * + * Use when you have a predicate on `A` and want to check `B` values by mapping + * each `B` to an `A`, such as checking lengths or projections. * - * Behavior: - * - Pure; does not mutate input. - * - Returns a new predicate that applies `f` before `self`. - * - No short-circuit beyond what `self` does. + * **Details** + * + * Returns a new predicate that applies `f` before `self`. There is no + * additional short-circuiting beyond what `self` does. * * **Example** (Check string length) * @@ -376,8 +364,9 @@ export const mapInput: { * console.log(isLongerThan2("hello")) * ``` * - * See also: {@link Predicate}, {@link and}, {@link not} - * + * @see {@link Predicate} + * @see {@link and} + * @see {@link not} * @category combinators * @since 2.0.0 */ @@ -385,14 +374,15 @@ export const mapInput: { /** * Transforms the input of a predicate using a mapping function. * - * When to use: - * - You have a predicate on `A` and want one on `B` via `B -> A`. - * - You want to check derived values (lengths, projections, etc.). + * **When to use** + * + * Use when you have a predicate on `A` and want to check `B` values by mapping + * each `B` to an `A`, such as checking lengths or projections. + * + * **Details** * - * Behavior: - * - Pure; does not mutate input. - * - Returns a new predicate that applies `f` before `self`. - * - No short-circuit beyond what `self` does. + * Returns a new predicate that applies `f` before `self`. There is no + * additional short-circuiting beyond what `self` does. * * **Example** (Check string length) * @@ -406,8 +396,9 @@ export const mapInput: { * console.log(isLongerThan2("hello")) * ``` * - * See also: {@link Predicate}, {@link and}, {@link not} - * + * @see {@link Predicate} + * @see {@link and} + * @see {@link not} * @category combinators * @since 2.0.0 */ @@ -417,14 +408,15 @@ export const mapInput: { /** * Checks whether a readonly array has exactly `n` elements. * - * When to use: - * - You need a runtime check for tuple length. - * - You want to narrow `ReadonlyArray` to `TupleOf`. + * **When to use** + * + * Use when you need a `Predicate` guard for exact tuple length that narrows + * `ReadonlyArray` to `TupleOf`. * - * Behavior: - * - Pure; does not mutate input. - * - Only checks length, not element types. - * - Returns a refinement on the array type. + * **Details** + * + * This only checks length, not element types, and returns a refinement on the + * array type. * * **Example** (Exact length) * @@ -436,8 +428,8 @@ export const mapInput: { * console.log(isPair([1, 2])) * ``` * - * See also: {@link isTupleOfAtLeast}, {@link Tuple} - * + * @see {@link isTupleOfAtLeast} + * @see {@link Tuple} * @category guards * @since 3.3.0 */ @@ -445,14 +437,15 @@ export const isTupleOf: { /** * Checks whether a readonly array has exactly `n` elements. * - * When to use: - * - You need a runtime check for tuple length. - * - You want to narrow `ReadonlyArray` to `TupleOf`. + * **When to use** * - * Behavior: - * - Pure; does not mutate input. - * - Only checks length, not element types. - * - Returns a refinement on the array type. + * Use when you need a `Predicate` guard for exact tuple length that narrows + * `ReadonlyArray` to `TupleOf`. + * + * **Details** + * + * This only checks length, not element types, and returns a refinement on the + * array type. * * **Example** (Exact length) * @@ -464,8 +457,8 @@ export const isTupleOf: { * console.log(isPair([1, 2])) * ``` * - * See also: {@link isTupleOfAtLeast}, {@link Tuple} - * + * @see {@link isTupleOfAtLeast} + * @see {@link Tuple} * @category guards * @since 3.3.0 */ @@ -473,14 +466,15 @@ export const isTupleOf: { /** * Checks whether a readonly array has exactly `n` elements. * - * When to use: - * - You need a runtime check for tuple length. - * - You want to narrow `ReadonlyArray` to `TupleOf`. + * **When to use** + * + * Use when you need a `Predicate` guard for exact tuple length that narrows + * `ReadonlyArray` to `TupleOf`. * - * Behavior: - * - Pure; does not mutate input. - * - Only checks length, not element types. - * - Returns a refinement on the array type. + * **Details** + * + * This only checks length, not element types, and returns a refinement on the + * array type. * * **Example** (Exact length) * @@ -492,8 +486,8 @@ export const isTupleOf: { * console.log(isPair([1, 2])) * ``` * - * See also: {@link isTupleOfAtLeast}, {@link Tuple} - * + * @see {@link isTupleOfAtLeast} + * @see {@link Tuple} * @category guards * @since 3.3.0 */ @@ -503,14 +497,15 @@ export const isTupleOf: { /** * Checks whether a readonly array has at least `n` elements. * - * When to use: - * - You need a runtime check for tuple-like minimum length. - * - You want to narrow `ReadonlyArray` to `TupleOfAtLeast`. + * **When to use** + * + * Use when you need a `Predicate` guard for tuple-like minimum length that + * narrows `ReadonlyArray` to `TupleOfAtLeast`. * - * Behavior: - * - Pure; does not mutate input. - * - Only checks length, not element types. - * - Returns a refinement on the array type. + * **Details** + * + * This only checks length, not element types, and returns a refinement on the + * array type. * * **Example** (Minimum length) * @@ -522,8 +517,8 @@ export const isTupleOf: { * console.log(hasAtLeast2([1, 2, 3])) * ``` * - * See also: {@link isTupleOf}, {@link Tuple} - * + * @see {@link isTupleOf} + * @see {@link Tuple} * @category guards * @since 3.3.0 */ @@ -531,14 +526,15 @@ export const isTupleOfAtLeast: { /** * Checks whether a readonly array has at least `n` elements. * - * When to use: - * - You need a runtime check for tuple-like minimum length. - * - You want to narrow `ReadonlyArray` to `TupleOfAtLeast`. + * **When to use** * - * Behavior: - * - Pure; does not mutate input. - * - Only checks length, not element types. - * - Returns a refinement on the array type. + * Use when you need a `Predicate` guard for tuple-like minimum length that + * narrows `ReadonlyArray` to `TupleOfAtLeast`. + * + * **Details** + * + * This only checks length, not element types, and returns a refinement on the + * array type. * * **Example** (Minimum length) * @@ -550,8 +546,8 @@ export const isTupleOfAtLeast: { * console.log(hasAtLeast2([1, 2, 3])) * ``` * - * See also: {@link isTupleOf}, {@link Tuple} - * + * @see {@link isTupleOf} + * @see {@link Tuple} * @category guards * @since 3.3.0 */ @@ -559,14 +555,15 @@ export const isTupleOfAtLeast: { /** * Checks whether a readonly array has at least `n` elements. * - * When to use: - * - You need a runtime check for tuple-like minimum length. - * - You want to narrow `ReadonlyArray` to `TupleOfAtLeast`. + * **When to use** + * + * Use when you need a `Predicate` guard for tuple-like minimum length that + * narrows `ReadonlyArray` to `TupleOfAtLeast`. * - * Behavior: - * - Pure; does not mutate input. - * - Only checks length, not element types. - * - Returns a refinement on the array type. + * **Details** + * + * This only checks length, not element types, and returns a refinement on the + * array type. * * **Example** (Minimum length) * @@ -578,8 +575,8 @@ export const isTupleOfAtLeast: { * console.log(hasAtLeast2([1, 2, 3])) * ``` * - * See also: {@link isTupleOf}, {@link Tuple} - * + * @see {@link isTupleOf} + * @see {@link Tuple} * @category guards * @since 3.3.0 */ @@ -589,14 +586,15 @@ export const isTupleOfAtLeast: { /** * Checks whether a value is truthy. * - * When to use: - * - You want a predicate that mirrors JavaScript truthiness. - * - You need to filter out falsy values like `0`, "", and `false`. + * **When to use** + * + * Use when you want a predicate that mirrors JavaScript truthiness and filters + * out falsy values like `0`, `""`, and `false`. + * + * **Details** * - * Behavior: - * - Pure; does not mutate input. - * - Uses `!!input` under the hood. - * - Treats `0`, "", `false`, `null`, and `undefined` as false. + * This uses `!!input` and treats `0`, `""`, `false`, `null`, and `undefined` + * as false. * * **Example** (Filter truthy) * @@ -609,8 +607,8 @@ export const isTupleOfAtLeast: { * console.log(truthy) * ``` * - * See also: {@link isNullish}, {@link isNotNullish} - * + * @see {@link isNullish} + * @see {@link isNotNullish} * @category guards * @since 2.0.0 */ @@ -621,12 +619,13 @@ export function isTruthy(input: unknown): boolean { /** * Checks whether a value is a `Set`. * - * When to use: - * - You need a runtime guard for `Set` values. + * **When to use** + * + * Use when you need a `Predicate` runtime guard for `Set` values. * - * Behavior: - * - Pure; does not mutate input. - * - Uses `instanceof Set`. + * **Details** + * + * Uses `instanceof Set`. * * **Example** (Guard a Set) * @@ -640,8 +639,8 @@ export function isTruthy(input: unknown): boolean { * } * ``` * - * See also: {@link isMap}, {@link isIterable} - * + * @see {@link isMap} + * @see {@link isIterable} * @category guards * @since 2.0.0 */ @@ -652,12 +651,13 @@ export function isSet(input: unknown): input is Set { /** * Checks whether a value is a `Map`. * - * When to use: - * - You need a runtime guard for `Map` values. + * **When to use** * - * Behavior: - * - Pure; does not mutate input. - * - Uses `instanceof Map`. + * Use when you need a `Predicate` runtime guard for `Map` values. + * + * **Details** + * + * Uses `instanceof Map`. * * **Example** (Guard a Map) * @@ -671,8 +671,8 @@ export function isSet(input: unknown): input is Set { * } * ``` * - * See also: {@link isSet}, {@link isIterable} - * + * @see {@link isSet} + * @see {@link isIterable} * @category guards * @since 2.0.0 */ @@ -683,13 +683,14 @@ export function isMap(input: unknown): input is Map { /** * Checks whether a value is a `string`. * - * When to use: - * - You need to guard an `unknown` value as a string. - * - You want to narrow in `if` statements. + * **When to use** + * + * Use when you need a `Predicate` guard to narrow an `unknown` value to a + * string. + * + * **Details** * - * Behavior: - * - Pure; does not mutate input. - * - Uses `typeof input === "string"`. + * Uses `typeof input === "string"`. * * **Example** (Guard string) * @@ -703,8 +704,9 @@ export function isMap(input: unknown): input is Map { * } * ``` * - * See also: {@link isNumber}, {@link isBoolean}, {@link Refinement} - * + * @see {@link isNumber} + * @see {@link isBoolean} + * @see {@link Refinement} * @category guards * @since 2.0.0 */ @@ -715,13 +717,14 @@ export function isString(input: unknown): input is string { /** * Checks whether a value is a `number`. * - * When to use: - * - You need to guard an `unknown` value as a number. + * **When to use** + * + * Use when you need a `Predicate` guard to narrow an `unknown` value to a + * number. * - * Behavior: - * - Pure; does not mutate input. - * - Uses `typeof input === "number"`. - * - Does not exclude `NaN` or `Infinity`. + * **Details** + * + * Uses `typeof input === "number"` and does not exclude `NaN` or `Infinity`. * * **Example** (Guard number) * @@ -735,8 +738,8 @@ export function isString(input: unknown): input is string { * } * ``` * - * See also: {@link isBigInt}, {@link isString} - * + * @see {@link isBigInt} + * @see {@link isString} * @category guards * @since 2.0.0 */ @@ -747,12 +750,14 @@ export function isNumber(input: unknown): input is number { /** * Checks whether a value is a `boolean`. * - * When to use: - * - You need to guard an `unknown` value as a boolean. + * **When to use** * - * Behavior: - * - Pure; does not mutate input. - * - Uses `typeof input === "boolean"`. + * Use when you need a `Predicate` guard to narrow an `unknown` value to a + * boolean. + * + * **Details** + * + * Uses `typeof input === "boolean"`. * * **Example** (Guard boolean) * @@ -766,8 +771,8 @@ export function isNumber(input: unknown): input is number { * } * ``` * - * See also: {@link isString}, {@link isNumber} - * + * @see {@link isString} + * @see {@link isNumber} * @category guards * @since 2.0.0 */ @@ -778,12 +783,14 @@ export function isBoolean(input: unknown): input is boolean { /** * Checks whether a value is a `bigint`. * - * When to use: - * - You need to guard an `unknown` value as a bigint. + * **When to use** + * + * Use when you need a `Predicate` guard to narrow an `unknown` value to a + * bigint. * - * Behavior: - * - Pure; does not mutate input. - * - Uses `typeof input === "bigint"`. + * **Details** + * + * Uses `typeof input === "bigint"`. * * **Example** (Guard bigint) * @@ -797,8 +804,7 @@ export function isBoolean(input: unknown): input is boolean { * } * ``` * - * See also: {@link isNumber} - * + * @see {@link isNumber} * @category guards * @since 2.0.0 */ @@ -809,12 +815,14 @@ export function isBigInt(input: unknown): input is bigint { /** * Checks whether a value is a `symbol`. * - * When to use: - * - You need to guard an `unknown` value as a symbol. + * **When to use** + * + * Use when you need a `Predicate` guard to narrow an `unknown` value to a + * symbol. + * + * **Details** * - * Behavior: - * - Pure; does not mutate input. - * - Uses `typeof input === "symbol"`. + * Uses `typeof input === "symbol"`. * * **Example** (Guard symbol) * @@ -828,8 +836,7 @@ export function isBigInt(input: unknown): input is bigint { * } * ``` * - * See also: {@link isPropertyKey} - * + * @see {@link isPropertyKey} * @category guards * @since 2.0.0 */ @@ -840,12 +847,14 @@ export function isSymbol(input: unknown): input is symbol { /** * Checks whether a value is a valid `PropertyKey` (string, number, or symbol). * - * When to use: - * - You need to guard unknown keys before indexing. + * **When to use** + * + * Use when you need a `Predicate` guard for unknown property keys before + * indexing. + * + * **Details** * - * Behavior: - * - Pure; does not mutate input. - * - Uses {@link isString}, {@link isNumber}, and {@link isSymbol}. + * Uses `isString`, `isNumber`, and `isSymbol`. * * **Example** (Guard property key) * @@ -860,8 +869,9 @@ export function isSymbol(input: unknown): input is symbol { * } * ``` * - * See also: {@link isString}, {@link isNumber}, {@link isSymbol} - * + * @see {@link isString} + * @see {@link isNumber} + * @see {@link isSymbol} * @category guards * @since 4.0.0 */ @@ -872,12 +882,14 @@ export function isPropertyKey(u: unknown): u is PropertyKey { /** * Checks whether a value is a `function`. * - * When to use: - * - You need to guard an `unknown` value as callable. + * **When to use** + * + * Use when you need a `Predicate` guard to narrow an `unknown` value to a + * callable function. * - * Behavior: - * - Pure; does not mutate input. - * - Uses `typeof input === "function"`. + * **Details** + * + * Uses `typeof input === "function"`. * * **Example** (Guard function) * @@ -891,8 +903,7 @@ export function isPropertyKey(u: unknown): u is PropertyKey { * } * ``` * - * See also: {@link isObjectKeyword} - * + * @see {@link isObjectKeyword} * @category guards * @since 2.0.0 */ @@ -903,12 +914,14 @@ export function isFunction(input: unknown): input is Function { /** * Checks whether a value is `undefined`. * - * When to use: - * - You need a guard for optional values. + * **When to use** + * + * Use when you need a `Predicate` guard for values that are exactly + * `undefined`. + * + * **Details** * - * Behavior: - * - Pure; does not mutate input. - * - Uses `input === undefined`. + * Uses `input === undefined`. * * **Example** (Guard undefined) * @@ -920,8 +933,8 @@ export function isFunction(input: unknown): input is Function { * console.log(Predicate.isUndefined(data)) * ``` * - * See also: {@link isNotUndefined}, {@link isNullish} - * + * @see {@link isNotUndefined} + * @see {@link isNullish} * @category guards * @since 2.0.0 */ @@ -932,12 +945,14 @@ export function isUndefined(input: unknown): input is undefined { /** * Checks whether a value is not `undefined`. * - * When to use: - * - You want to filter out `undefined` while preserving other falsy values. + * **When to use** + * + * Use when you need a `Predicate` refinement that filters out `undefined` + * while preserving other falsy values. * - * Behavior: - * - Pure; does not mutate input. - * - Returns a refinement that excludes `undefined`. + * **Details** + * + * Returns a refinement that excludes `undefined`. * * **Example** (Filter undefined) * @@ -950,8 +965,8 @@ export function isUndefined(input: unknown): input is undefined { * console.log(defined) * ``` * - * See also: {@link isUndefined}, {@link isNotNullish} - * + * @see {@link isUndefined} + * @see {@link isNotNullish} * @category guards * @since 2.0.0 */ @@ -962,12 +977,13 @@ export function isNotUndefined(input: A): input is Exclude { /** * Checks whether a value is `null`. * - * When to use: - * - You need a guard for nullable values. + * **When to use** * - * Behavior: - * - Pure; does not mutate input. - * - Uses `input === null`. + * Use when you need a `Predicate` guard for nullable values. + * + * **Details** + * + * Uses `input === null`. * * **Example** (Guard null) * @@ -979,8 +995,8 @@ export function isNotUndefined(input: A): input is Exclude { * console.log(Predicate.isNull(data)) * ``` * - * See also: {@link isNotNull}, {@link isNullish} - * + * @see {@link isNotNull} + * @see {@link isNullish} * @category guards * @since 2.0.0 */ @@ -991,12 +1007,14 @@ export function isNull(input: unknown): input is null { /** * Checks whether a value is not `null`. * - * When to use: - * - You want to filter out `null` while preserving other falsy values. + * **When to use** + * + * Use when you need a `Predicate` refinement that filters out `null` while + * preserving other falsy values. * - * Behavior: - * - Pure; does not mutate input. - * - Returns a refinement that excludes `null`. + * **Details** + * + * Returns a refinement that excludes `null`. * * **Example** (Filter null) * @@ -1009,8 +1027,8 @@ export function isNull(input: unknown): input is null { * console.log(nonNull) * ``` * - * See also: {@link isNull}, {@link isNotNullish} - * + * @see {@link isNull} + * @see {@link isNotNullish} * @category guards * @since 2.0.0 */ @@ -1021,12 +1039,13 @@ export function isNotNull(input: A): input is Exclude { /** * Checks whether a value is `null` or `undefined`. * - * When to use: - * - You want to guard nullish values explicitly. + * **When to use** + * + * Use when you need a `Predicate` guard for nullish values. * - * Behavior: - * - Pure; does not mutate input. - * - Uses `input === null || input === undefined`. + * **Details** + * + * Uses `input === null || input === undefined`. * * **Example** (Guard nullish) * @@ -1039,8 +1058,9 @@ export function isNotNull(input: A): input is Exclude { * console.log(nullish) * ``` * - * See also: {@link isNotNullish}, {@link isUndefined}, {@link isNull} - * + * @see {@link isNotNullish} + * @see {@link isUndefined} + * @see {@link isNull} * @category guards * @since 4.0.0 */ @@ -1051,12 +1071,14 @@ export function isNullish(input: A): input is A & (null | undefined) { /** * Checks whether a value is not `null` and not `undefined`. * - * When to use: - * - You want to filter out nullish values but keep other falsy ones. + * **When to use** * - * Behavior: - * - Pure; does not mutate input. - * - Uses `input != null`. + * Use when you need a `Predicate` refinement that filters out nullish values + * but keeps other falsy ones. + * + * **Details** + * + * Uses `input != null`. * * **Example** (Filter non-nullish) * @@ -1069,8 +1091,9 @@ export function isNullish(input: A): input is A & (null | undefined) { * console.log(present) * ``` * - * See also: {@link isNullish}, {@link isNotNull}, {@link isNotUndefined} - * + * @see {@link isNullish} + * @see {@link isNotNull} + * @see {@link isNotUndefined} * @category guards * @since 4.0.0 */ @@ -1079,14 +1102,11 @@ export function isNotNullish(input: A): input is NonNullable { } /** - * A guard that always returns `false`. + * Type guard that always returns `false`. * - * When to use: - * - You need a predicate that never accepts, e.g. in default branches. + * **When to use** * - * Behavior: - * - Pure; does not mutate input. - * - Always returns `false`. + * Use when you need a `Predicate` that never accepts, e.g. in default branches. * * **Example** (Never matches) * @@ -1096,8 +1116,7 @@ export function isNotNullish(input: A): input is NonNullable { * console.log(Predicate.isNever("anything")) * ``` * - * See also: {@link isUnknown} - * + * @see {@link isUnknown} * @category guards * @since 2.0.0 */ @@ -1106,14 +1125,11 @@ export function isNever(_: unknown): _ is never { } /** - * A guard that always returns `true`. + * Type guard that always returns `true`. * - * When to use: - * - You need a predicate that always accepts, e.g. as a placeholder. + * **When to use** * - * Behavior: - * - Pure; does not mutate input. - * - Always returns `true`. + * Use when you need a `Predicate` that always accepts, e.g. as a placeholder. * * **Example** (Always matches) * @@ -1123,8 +1139,7 @@ export function isNever(_: unknown): _ is never { * console.log(Predicate.isUnknown(123)) * ``` * - * See also: {@link isNever} - * + * @see {@link isNever} * @category guards * @since 2.0.0 */ @@ -1135,13 +1150,14 @@ export function isUnknown(_: unknown): _ is unknown { /** * Checks whether a value is an object or an array (non-null object). * - * When to use: - * - You want to accept plain objects and arrays, but not `null`. + * **When to use** + * + * Use when you need a `Predicate` guard that accepts plain objects and arrays, + * but not `null`. * - * Behavior: - * - Pure; does not mutate input. - * - Uses `typeof input === "object" && input !== null`. - * - Includes arrays. + * **Details** + * + * Uses `typeof input === "object" && input !== null` and includes arrays. * * **Example** (Object or array) * @@ -1151,8 +1167,8 @@ export function isUnknown(_: unknown): _ is unknown { * console.log(Predicate.isObjectOrArray([])) * ``` * - * See also: {@link isObject}, {@link isObjectKeyword} - * + * @see {@link isObject} + * @see {@link isObjectKeyword} * @category guards * @since 4.0.0 */ @@ -1161,14 +1177,18 @@ export function isObjectOrArray(input: unknown): input is { [x: PropertyKey]: un } /** - * Checks whether a value is a plain object (not an array, not `null`). + * Checks whether a value is a non-null object value that is not an array. * - * When to use: - * - You need to accept objects but exclude arrays. + * **When to use** * - * Behavior: - * - Pure; does not mutate input. - * - Uses `typeof input === "object" && input !== null && !Array.isArray(input)`. + * Use to narrow unknown input to a non-null, non-array object with a + * `Predicate` guard. + * + * **Details** + * + * This is a structural runtime check using `typeof input === "object"`, so it + * also accepts object instances such as `Date`, `Map`, class instances, and + * typed arrays. It excludes `null` and arrays. * * **Example** (Guard object) * @@ -1179,24 +1199,29 @@ export function isObjectOrArray(input: unknown): input is { [x: PropertyKey]: un * console.log(Predicate.isObject([1, 2])) * ``` * - * See also: {@link isObjectOrArray}, {@link isReadonlyObject} - * + * @see {@link isObjectOrArray} + * @see {@link isReadonlyObject} * @category guards - * @since 4.0.0 + * @since 2.0.0 */ export function isObject(input: unknown): input is { [x: PropertyKey]: unknown } { return typeof input === "object" && input !== null && !Array.isArray(input) } /** - * Checks whether a value is a readonly object. + * Checks whether a value is a non-null, non-array object and narrows it to a + * readonly indexable object type. + * + * **When to use** + * + * Use to narrow unknown input to a readonly view of a non-null, non-array + * object with a `Predicate` guard. * - * When to use: - * - You need a guard for object-like values and do not care about mutability. + * **Details** * - * Behavior: - * - Pure; does not mutate input. - * - Delegates to {@link isObject}. + * Readonly-ness is a TypeScript type-level view; it is not observable at + * runtime. This delegates to `isObject`, so class instances and built-in object + * instances are accepted. * * **Example** (Readonly object) * @@ -1208,8 +1233,7 @@ export function isObject(input: unknown): input is { [x: PropertyKey]: unknown } * console.log(Predicate.isReadonlyObject(data)) * ``` * - * See also: {@link isObject} - * + * @see {@link isObject} * @category guards * @since 4.0.0 */ @@ -1220,12 +1244,14 @@ export function isReadonlyObject(input: unknown): input is { readonly [x: Proper /** * Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions). * - * When to use: - * - You want to accept arrays and functions as well as objects. + * **When to use** + * + * Use when you need a `Predicate` guard that accepts arrays and functions as + * well as objects. * - * Behavior: - * - Pure; does not mutate input. - * - Returns `true` for arrays and functions, `false` for `null`. + * **Details** + * + * Returns `true` for arrays and functions, and `false` for `null`. * * **Example** (Object keyword) * @@ -1236,10 +1262,10 @@ export function isReadonlyObject(input: unknown): input is { readonly [x: Proper * console.log(Predicate.isObjectKeyword(null)) * ``` * - * See also: {@link isObject}, {@link isObjectOrArray} - * + * @see {@link isObject} + * @see {@link isObjectOrArray} * @category guards - * @since 2.0.0 + * @since 4.0.0 */ export function isObjectKeyword(input: unknown): input is object { return (typeof input === "object" && input !== null) || isFunction(input) @@ -1248,14 +1274,15 @@ export function isObjectKeyword(input: unknown): input is object { /** * Checks whether a value has a given property key. * - * When to use: - * - You need to guard property access on `unknown` values. - * - You want a simple structural guard for objects. + * **When to use** * - * Behavior: - * - Pure; does not mutate input. - * - Uses the `in` operator and {@link isObjectKeyword}. - * - Does not check property value types. + * Use when you need a `Predicate` guard for property access on `unknown` + * values with a simple structural object check. + * + * **Details** + * + * Uses the `in` operator and `isObjectKeyword`. This does not check property + * value types. * * **Example** (Guard property) * @@ -1270,8 +1297,8 @@ export function isObjectKeyword(input: unknown): input is object { * } * ``` * - * See also: {@link isTagged}, {@link isObjectKeyword} - * + * @see {@link isTagged} + * @see {@link isObjectKeyword} * @category guards * @since 2.0.0 */ @@ -1279,14 +1306,15 @@ export const hasProperty: { /** * Checks whether a value has a given property key. * - * When to use: - * - You need to guard property access on `unknown` values. - * - You want a simple structural guard for objects. + * **When to use** + * + * Use when you need a `Predicate` guard for property access on `unknown` + * values with a simple structural object check. * - * Behavior: - * - Pure; does not mutate input. - * - Uses the `in` operator and {@link isObjectKeyword}. - * - Does not check property value types. + * **Details** + * + * Uses the `in` operator and `isObjectKeyword`. This does not check property + * value types. * * **Example** (Guard property) * @@ -1301,8 +1329,8 @@ export const hasProperty: { * } * ``` * - * See also: {@link isTagged}, {@link isObjectKeyword} - * + * @see {@link isTagged} + * @see {@link isObjectKeyword} * @category guards * @since 2.0.0 */ @@ -1310,14 +1338,15 @@ export const hasProperty: { /** * Checks whether a value has a given property key. * - * When to use: - * - You need to guard property access on `unknown` values. - * - You want a simple structural guard for objects. + * **When to use** + * + * Use when you need a `Predicate` guard for property access on `unknown` + * values with a simple structural object check. + * + * **Details** * - * Behavior: - * - Pure; does not mutate input. - * - Uses the `in` operator and {@link isObjectKeyword}. - * - Does not check property value types. + * Uses the `in` operator and `isObjectKeyword`. This does not check property + * value types. * * **Example** (Guard property) * @@ -1332,8 +1361,8 @@ export const hasProperty: { * } * ``` * - * See also: {@link isTagged}, {@link isObjectKeyword} - * + * @see {@link isTagged} + * @see {@link isObjectKeyword} * @category guards * @since 2.0.0 */ @@ -1347,13 +1376,14 @@ export const hasProperty: { /** * Checks whether a value has a `_tag` property equal to the given tag. * - * When to use: - * - You model tagged unions with a `_tag` field. - * - You want a quick, structural guard for tagged values. + * **When to use** + * + * Use when you model tagged unions with a `_tag` field and want a quick + * `Predicate` guard for tagged values. + * + * **Details** * - * Behavior: - * - Pure; does not mutate input. - * - Uses {@link hasProperty} and strict equality on `_tag`. + * Uses `hasProperty` and strict equality on `_tag`. * * **Example** (Guard tagged) * @@ -1365,8 +1395,7 @@ export const hasProperty: { * console.log(isOk({ _tag: "Ok", value: 1 })) * ``` * - * See also: {@link hasProperty} - * + * @see {@link hasProperty} * @category guards * @since 2.0.0 */ @@ -1374,13 +1403,14 @@ export const isTagged: { /** * Checks whether a value has a `_tag` property equal to the given tag. * - * When to use: - * - You model tagged unions with a `_tag` field. - * - You want a quick, structural guard for tagged values. + * **When to use** + * + * Use when you model tagged unions with a `_tag` field and want a quick + * `Predicate` guard for tagged values. * - * Behavior: - * - Pure; does not mutate input. - * - Uses {@link hasProperty} and strict equality on `_tag`. + * **Details** + * + * Uses `hasProperty` and strict equality on `_tag`. * * **Example** (Guard tagged) * @@ -1392,8 +1422,7 @@ export const isTagged: { * console.log(isOk({ _tag: "Ok", value: 1 })) * ``` * - * See also: {@link hasProperty} - * + * @see {@link hasProperty} * @category guards * @since 2.0.0 */ @@ -1401,13 +1430,14 @@ export const isTagged: { /** * Checks whether a value has a `_tag` property equal to the given tag. * - * When to use: - * - You model tagged unions with a `_tag` field. - * - You want a quick, structural guard for tagged values. + * **When to use** + * + * Use when you model tagged unions with a `_tag` field and want a quick + * `Predicate` guard for tagged values. + * + * **Details** * - * Behavior: - * - Pure; does not mutate input. - * - Uses {@link hasProperty} and strict equality on `_tag`. + * Uses `hasProperty` and strict equality on `_tag`. * * **Example** (Guard tagged) * @@ -1419,8 +1449,7 @@ export const isTagged: { * console.log(isOk({ _tag: "Ok", value: 1 })) * ``` * - * See also: {@link hasProperty} - * + * @see {@link hasProperty} * @category guards * @since 2.0.0 */ @@ -1433,12 +1462,13 @@ export const isTagged: { /** * Checks whether a value is an `Error`. * - * When to use: - * - You need to guard errors caught from unknown sources. + * **When to use** + * + * Use when you need a `Predicate` guard for errors caught from unknown sources. * - * Behavior: - * - Pure; does not mutate input. - * - Uses `instanceof Error`. + * **Details** + * + * Uses `instanceof Error`. * * **Example** (Guard error) * @@ -1450,8 +1480,7 @@ export const isTagged: { * console.log(Predicate.isError(data)) * ``` * - * See also: {@link isUnknown} - * + * @see {@link isUnknown} * @category guards * @since 2.0.0 */ @@ -1462,12 +1491,13 @@ export function isError(input: unknown): input is Error { /** * Checks whether a value is a `Uint8Array`. * - * When to use: - * - You need to guard binary data at runtime. + * **When to use** * - * Behavior: - * - Pure; does not mutate input. - * - Uses `instanceof Uint8Array`. + * Use when you need a `Predicate` runtime guard for binary data. + * + * **Details** + * + * Uses `instanceof Uint8Array`. * * **Example** (Guard Uint8Array) * @@ -1479,8 +1509,8 @@ export function isError(input: unknown): input is Error { * console.log(Predicate.isUint8Array(data)) * ``` * - * See also: {@link isIterable}, {@link isSet} - * + * @see {@link isIterable} + * @see {@link isSet} * @category guards * @since 2.0.0 */ @@ -1491,12 +1521,13 @@ export function isUint8Array(input: unknown): input is Uint8Array { /** * Checks whether a value is a `Date`. * - * When to use: - * - You need to guard dates at runtime. + * **When to use** + * + * Use when you need a `Predicate` runtime guard for dates. * - * Behavior: - * - Pure; does not mutate input. - * - Uses `instanceof Date`. + * **Details** + * + * Uses `instanceof Date`. * * **Example** (Guard Date) * @@ -1508,8 +1539,7 @@ export function isUint8Array(input: unknown): input is Uint8Array { * console.log(Predicate.isDate(data)) * ``` * - * See also: {@link isRegExp} - * + * @see {@link isRegExp} * @category guards * @since 2.0.0 */ @@ -1520,13 +1550,13 @@ export function isDate(input: unknown): input is Date { /** * Checks whether a value is iterable. * - * When to use: - * - You need a guard before iterating an unknown value. + * **When to use** + * + * Use when you need a `Predicate` guard before iterating an unknown value. * - * Behavior: - * - Pure; does not mutate input. - * - Accepts strings as iterable. - * - Uses {@link hasProperty} for `Symbol.iterator`. + * **Details** + * + * Accepts strings as iterable and uses `hasProperty` for `Symbol.iterator`. * * **Example** (Guard iterable) * @@ -1538,8 +1568,8 @@ export function isDate(input: unknown): input is Date { * console.log(Predicate.isIterable(data)) * ``` * - * See also: {@link isSet}, {@link isMap} - * + * @see {@link isSet} + * @see {@link isMap} * @category guards * @since 2.0.0 */ @@ -1550,12 +1580,13 @@ export function isIterable(input: unknown): input is Iterable { /** * Checks whether a value is a `Promise`-like object with `then` and `catch`. * - * When to use: - * - You need to detect promise instances across realms. + * **When to use** * - * Behavior: - * - Pure; does not mutate input. - * - Structural check for `then` and `catch` functions. + * Use when you need a `Predicate` guard for promise instances across realms. + * + * **Details** + * + * Performs a structural check for `then` and `catch` functions. * * **Example** (Guard promise) * @@ -1567,8 +1598,7 @@ export function isIterable(input: unknown): input is Iterable { * console.log(Predicate.isPromise(data)) * ``` * - * See also: {@link isPromiseLike} - * + * @see {@link isPromiseLike} * @category guards * @since 2.0.0 */ @@ -1579,12 +1609,14 @@ export function isPromise(input: unknown): input is Promise { /** * Checks whether a value is `PromiseLike` (has a `then` method). * - * When to use: - * - You only need `then` to interop with promise-like values. + * **When to use** + * + * Use when you need a `Predicate` guard for promise-like values with a + * callable `then` method. * - * Behavior: - * - Pure; does not mutate input. - * - Structural check for a callable `then`. + * **Details** + * + * Performs a structural check for a callable `then`. * * **Example** (Guard promise-like) * @@ -1596,8 +1628,7 @@ export function isPromise(input: unknown): input is Promise { * console.log(Predicate.isPromiseLike(data)) * ``` * - * See also: {@link isPromise} - * + * @see {@link isPromise} * @category guards * @since 2.0.0 */ @@ -1608,12 +1639,13 @@ export function isPromiseLike(input: unknown): input is PromiseLike { /** * Checks whether a value is a `RegExp`. * - * When to use: - * - You need a runtime guard for regular expressions. + * **When to use** + * + * Use when you need a `Predicate` runtime guard for regular expressions. + * + * **Details** * - * Behavior: - * - Pure; does not mutate input. - * - Uses `instanceof RegExp`. + * Uses `instanceof RegExp`. * * **Example** (Guard RegExp) * @@ -1625,8 +1657,7 @@ export function isPromiseLike(input: unknown): input is PromiseLike { * console.log(Predicate.isRegExp(data)) * ``` * - * See also: {@link isDate} - * + * @see {@link isDate} * @category guards * @since 3.9.0 */ @@ -1637,14 +1668,15 @@ export function isRegExp(input: unknown): input is RegExp { /** * Composes two predicates or refinements into one. * - * When to use: - * - You want to chain two refinements for progressive narrowing. - * - You want a predicate that applies two checks in sequence. + * **When to use** + * + * Use when you want to compose two `Predicate` checks in sequence, especially + * when chaining refinements for progressive narrowing. * - * Behavior: - * - Pure; does not mutate input. - * - For refinements, the output type is narrowed by both. - * - Short-circuits on the first `false`. + * **Details** + * + * For refinements, the output type is narrowed by both checks. Evaluation + * short-circuits on the first `false`. * * **Example** (Compose refinements) * @@ -1659,8 +1691,8 @@ export function isRegExp(input: unknown): input is RegExp { * console.log(isIntegerNumber(1)) * ``` * - * See also: {@link and}, {@link Refinement} - * + * @see {@link and} + * @see {@link Refinement} * @category combinators * @since 2.0.0 */ @@ -1668,14 +1700,15 @@ export const compose: { /** * Composes two predicates or refinements into one. * - * When to use: - * - You want to chain two refinements for progressive narrowing. - * - You want a predicate that applies two checks in sequence. + * **When to use** * - * Behavior: - * - Pure; does not mutate input. - * - For refinements, the output type is narrowed by both. - * - Short-circuits on the first `false`. + * Use when you want to compose two `Predicate` checks in sequence, especially + * when chaining refinements for progressive narrowing. + * + * **Details** + * + * For refinements, the output type is narrowed by both checks. Evaluation + * short-circuits on the first `false`. * * **Example** (Compose refinements) * @@ -1690,8 +1723,8 @@ export const compose: { * console.log(isIntegerNumber(1)) * ``` * - * See also: {@link and}, {@link Refinement} - * + * @see {@link and} + * @see {@link Refinement} * @category combinators * @since 2.0.0 */ @@ -1699,14 +1732,15 @@ export const compose: { /** * Composes two predicates or refinements into one. * - * When to use: - * - You want to chain two refinements for progressive narrowing. - * - You want a predicate that applies two checks in sequence. + * **When to use** + * + * Use when you want to compose two `Predicate` checks in sequence, especially + * when chaining refinements for progressive narrowing. + * + * **Details** * - * Behavior: - * - Pure; does not mutate input. - * - For refinements, the output type is narrowed by both. - * - Short-circuits on the first `false`. + * For refinements, the output type is narrowed by both checks. Evaluation + * short-circuits on the first `false`. * * **Example** (Compose refinements) * @@ -1721,8 +1755,8 @@ export const compose: { * console.log(isIntegerNumber(1)) * ``` * - * See also: {@link and}, {@link Refinement} - * + * @see {@link and} + * @see {@link Refinement} * @category combinators * @since 2.0.0 */ @@ -1730,14 +1764,15 @@ export const compose: { /** * Composes two predicates or refinements into one. * - * When to use: - * - You want to chain two refinements for progressive narrowing. - * - You want a predicate that applies two checks in sequence. + * **When to use** + * + * Use when you want to compose two `Predicate` checks in sequence, especially + * when chaining refinements for progressive narrowing. * - * Behavior: - * - Pure; does not mutate input. - * - For refinements, the output type is narrowed by both. - * - Short-circuits on the first `false`. + * **Details** + * + * For refinements, the output type is narrowed by both checks. Evaluation + * short-circuits on the first `false`. * * **Example** (Compose refinements) * @@ -1752,8 +1787,8 @@ export const compose: { * console.log(isIntegerNumber(1)) * ``` * - * See also: {@link and}, {@link Refinement} - * + * @see {@link and} + * @see {@link Refinement} * @category combinators * @since 2.0.0 */ @@ -1761,14 +1796,15 @@ export const compose: { /** * Composes two predicates or refinements into one. * - * When to use: - * - You want to chain two refinements for progressive narrowing. - * - You want a predicate that applies two checks in sequence. + * **When to use** * - * Behavior: - * - Pure; does not mutate input. - * - For refinements, the output type is narrowed by both. - * - Short-circuits on the first `false`. + * Use when you want to compose two `Predicate` checks in sequence, especially + * when chaining refinements for progressive narrowing. + * + * **Details** + * + * For refinements, the output type is narrowed by both checks. Evaluation + * short-circuits on the first `false`. * * **Example** (Compose refinements) * @@ -1783,8 +1819,8 @@ export const compose: { * console.log(isIntegerNumber(1)) * ``` * - * See also: {@link and}, {@link Refinement} - * + * @see {@link and} + * @see {@link Refinement} * @category combinators * @since 2.0.0 */ @@ -1798,14 +1834,15 @@ export const compose: { /** * Creates a predicate for tuples by applying predicates to each element. * - * When to use: - * - You want to validate tuple positions independently. - * - You want to lift element predicates into a tuple predicate. + * **When to use** + * + * Use when you want to validate tuple positions independently by lifting + * element predicates into a tuple predicate. * - * Behavior: - * - Pure; does not mutate input. - * - Returns a refinement if any element predicate is a refinement. - * - Stops at the first failing element. + * **Details** + * + * Returns a refinement if any element predicate is a refinement. Evaluation + * stops at the first failing element. * * **Example** (Tuple predicate) * @@ -1817,8 +1854,8 @@ export const compose: { * console.log(tupleCheck([1, "ok"])) * ``` * - * See also: {@link Struct}, {@link isTupleOf} - * + * @see {@link Struct} + * @see {@link isTupleOf} * @category combinators * @since 4.0.0 */ @@ -1843,14 +1880,15 @@ export function Tuple>( /** * Creates a predicate for objects by applying predicates to named properties. * - * When to use: - * - You want to validate a record shape at runtime. - * - You want to lift property predicates into an object predicate. + * **When to use** + * + * Use when you want to validate a record shape at runtime by lifting property + * predicates into an object predicate. + * + * **Details** * - * Behavior: - * - Pure; does not mutate input. - * - Returns a refinement if any field predicate is a refinement. - * - Checks only the specified keys; extra keys are ignored. + * Returns a refinement if any field predicate is a refinement. Only the + * specified keys are checked, and extra keys are ignored. * * **Example** (Struct predicate) * @@ -1865,8 +1903,8 @@ export function Tuple>( * console.log(userCheck({ id: 1, name: "Ada" })) * ``` * - * See also: {@link Tuple}, {@link hasProperty} - * + * @see {@link Tuple} + * @see {@link hasProperty} * @category combinators * @since 4.0.0 */ @@ -1892,12 +1930,13 @@ export function Struct>( /** * Negates a predicate. * - * When to use: - * - You want the inverse of an existing predicate. + * **When to use** + * + * Use when you want the inverse of an existing predicate. + * + * **Details** * - * Behavior: - * - Pure; does not mutate input. - * - Returns a new predicate that flips the boolean result. + * Returns a new predicate that flips the boolean result. * * **Example** (Negate) * @@ -1909,8 +1948,9 @@ export function Struct>( * console.log(isNotString(1)) * ``` * - * See also: {@link and}, {@link or}, {@link xor} - * + * @see {@link and} + * @see {@link or} + * @see {@link xor} * @category combinators * @since 2.0.0 */ @@ -1921,14 +1961,15 @@ export function not(self: Predicate): Predicate { /** * Creates a predicate that returns `true` if either predicate is `true`. * - * When to use: - * - You want to accept values that satisfy at least one condition. - * - You want to combine refinements with union narrowing. + * **When to use** + * + * Use when you want to combine `Predicate`s with OR, accepting values that + * satisfy at least one condition, including refinements that narrow to a union. * - * Behavior: - * - Pure; does not mutate input. - * - Short-circuits on the first `true`. - * - For refinements, the output type is a union. + * **Details** + * + * Evaluation short-circuits on the first `true`. For refinements, the output + * type is a union. * * **Example** (Either condition) * @@ -1940,8 +1981,8 @@ export function not(self: Predicate): Predicate { * console.log(isStringOrNumber("a")) * ``` * - * See also: {@link and}, {@link xor} - * + * @see {@link and} + * @see {@link xor} * @category combinators * @since 2.0.0 */ @@ -1949,14 +1990,15 @@ export const or: { /** * Creates a predicate that returns `true` if either predicate is `true`. * - * When to use: - * - You want to accept values that satisfy at least one condition. - * - You want to combine refinements with union narrowing. + * **When to use** + * + * Use when you want to combine `Predicate`s with OR, accepting values that + * satisfy at least one condition, including refinements that narrow to a union. + * + * **Details** * - * Behavior: - * - Pure; does not mutate input. - * - Short-circuits on the first `true`. - * - For refinements, the output type is a union. + * Evaluation short-circuits on the first `true`. For refinements, the output + * type is a union. * * **Example** (Either condition) * @@ -1968,8 +2010,8 @@ export const or: { * console.log(isStringOrNumber("a")) * ``` * - * See also: {@link and}, {@link xor} - * + * @see {@link and} + * @see {@link xor} * @category combinators * @since 2.0.0 */ @@ -1977,14 +2019,15 @@ export const or: { /** * Creates a predicate that returns `true` if either predicate is `true`. * - * When to use: - * - You want to accept values that satisfy at least one condition. - * - You want to combine refinements with union narrowing. + * **When to use** + * + * Use when you want to combine `Predicate`s with OR, accepting values that + * satisfy at least one condition, including refinements that narrow to a union. * - * Behavior: - * - Pure; does not mutate input. - * - Short-circuits on the first `true`. - * - For refinements, the output type is a union. + * **Details** + * + * Evaluation short-circuits on the first `true`. For refinements, the output + * type is a union. * * **Example** (Either condition) * @@ -1996,8 +2039,8 @@ export const or: { * console.log(isStringOrNumber("a")) * ``` * - * See also: {@link and}, {@link xor} - * + * @see {@link and} + * @see {@link xor} * @category combinators * @since 2.0.0 */ @@ -2005,14 +2048,15 @@ export const or: { /** * Creates a predicate that returns `true` if either predicate is `true`. * - * When to use: - * - You want to accept values that satisfy at least one condition. - * - You want to combine refinements with union narrowing. + * **When to use** * - * Behavior: - * - Pure; does not mutate input. - * - Short-circuits on the first `true`. - * - For refinements, the output type is a union. + * Use when you want to combine `Predicate`s with OR, accepting values that + * satisfy at least one condition, including refinements that narrow to a union. + * + * **Details** + * + * Evaluation short-circuits on the first `true`. For refinements, the output + * type is a union. * * **Example** (Either condition) * @@ -2024,8 +2068,8 @@ export const or: { * console.log(isStringOrNumber("a")) * ``` * - * See also: {@link and}, {@link xor} - * + * @see {@link and} + * @see {@link xor} * @category combinators * @since 2.0.0 */ @@ -2033,14 +2077,15 @@ export const or: { /** * Creates a predicate that returns `true` if either predicate is `true`. * - * When to use: - * - You want to accept values that satisfy at least one condition. - * - You want to combine refinements with union narrowing. + * **When to use** + * + * Use when you want to combine `Predicate`s with OR, accepting values that + * satisfy at least one condition, including refinements that narrow to a union. * - * Behavior: - * - Pure; does not mutate input. - * - Short-circuits on the first `true`. - * - For refinements, the output type is a union. + * **Details** + * + * Evaluation short-circuits on the first `true`. For refinements, the output + * type is a union. * * **Example** (Either condition) * @@ -2052,8 +2097,8 @@ export const or: { * console.log(isStringOrNumber("a")) * ``` * - * See also: {@link and}, {@link xor} - * + * @see {@link and} + * @see {@link xor} * @category combinators * @since 2.0.0 */ @@ -2063,14 +2108,16 @@ export const or: { /** * Creates a predicate that returns `true` only if both predicates are `true`. * - * When to use: - * - You want to accept values that satisfy multiple conditions. - * - You want to combine refinements with intersection narrowing. + * **When to use** + * + * Use when you want to combine `Predicate`s with AND, accepting values that + * satisfy multiple conditions, including refinements that narrow to an + * intersection. * - * Behavior: - * - Pure; does not mutate input. - * - Short-circuits on the first `false`. - * - For refinements, the output type is an intersection. + * **Details** + * + * Evaluation short-circuits on the first `false`. For refinements, the output + * type is an intersection. * * **Example** (Both conditions) * @@ -2090,8 +2137,8 @@ export const or: { * } * ``` * - * See also: {@link or}, {@link not} - * + * @see {@link or} + * @see {@link not} * @category combinators * @since 2.0.0 */ @@ -2099,14 +2146,16 @@ export const and: { /** * Creates a predicate that returns `true` only if both predicates are `true`. * - * When to use: - * - You want to accept values that satisfy multiple conditions. - * - You want to combine refinements with intersection narrowing. + * **When to use** * - * Behavior: - * - Pure; does not mutate input. - * - Short-circuits on the first `false`. - * - For refinements, the output type is an intersection. + * Use when you want to combine `Predicate`s with AND, accepting values that + * satisfy multiple conditions, including refinements that narrow to an + * intersection. + * + * **Details** + * + * Evaluation short-circuits on the first `false`. For refinements, the output + * type is an intersection. * * **Example** (Both conditions) * @@ -2126,8 +2175,8 @@ export const and: { * } * ``` * - * See also: {@link or}, {@link not} - * + * @see {@link or} + * @see {@link not} * @category combinators * @since 2.0.0 */ @@ -2135,14 +2184,16 @@ export const and: { /** * Creates a predicate that returns `true` only if both predicates are `true`. * - * When to use: - * - You want to accept values that satisfy multiple conditions. - * - You want to combine refinements with intersection narrowing. + * **When to use** + * + * Use when you want to combine `Predicate`s with AND, accepting values that + * satisfy multiple conditions, including refinements that narrow to an + * intersection. * - * Behavior: - * - Pure; does not mutate input. - * - Short-circuits on the first `false`. - * - For refinements, the output type is an intersection. + * **Details** + * + * Evaluation short-circuits on the first `false`. For refinements, the output + * type is an intersection. * * **Example** (Both conditions) * @@ -2162,8 +2213,8 @@ export const and: { * } * ``` * - * See also: {@link or}, {@link not} - * + * @see {@link or} + * @see {@link not} * @category combinators * @since 2.0.0 */ @@ -2171,14 +2222,16 @@ export const and: { /** * Creates a predicate that returns `true` only if both predicates are `true`. * - * When to use: - * - You want to accept values that satisfy multiple conditions. - * - You want to combine refinements with intersection narrowing. + * **When to use** + * + * Use when you want to combine `Predicate`s with AND, accepting values that + * satisfy multiple conditions, including refinements that narrow to an + * intersection. + * + * **Details** * - * Behavior: - * - Pure; does not mutate input. - * - Short-circuits on the first `false`. - * - For refinements, the output type is an intersection. + * Evaluation short-circuits on the first `false`. For refinements, the output + * type is an intersection. * * **Example** (Both conditions) * @@ -2198,8 +2251,8 @@ export const and: { * } * ``` * - * See also: {@link or}, {@link not} - * + * @see {@link or} + * @see {@link not} * @category combinators * @since 2.0.0 */ @@ -2207,14 +2260,16 @@ export const and: { /** * Creates a predicate that returns `true` only if both predicates are `true`. * - * When to use: - * - You want to accept values that satisfy multiple conditions. - * - You want to combine refinements with intersection narrowing. + * **When to use** + * + * Use when you want to combine `Predicate`s with AND, accepting values that + * satisfy multiple conditions, including refinements that narrow to an + * intersection. * - * Behavior: - * - Pure; does not mutate input. - * - Short-circuits on the first `false`. - * - For refinements, the output type is an intersection. + * **Details** + * + * Evaluation short-circuits on the first `false`. For refinements, the output + * type is an intersection. * * **Example** (Both conditions) * @@ -2234,8 +2289,8 @@ export const and: { * } * ``` * - * See also: {@link or}, {@link not} - * + * @see {@link or} + * @see {@link not} * @category combinators * @since 2.0.0 */ @@ -2245,12 +2300,13 @@ export const and: { /** * Creates a predicate that returns `true` if exactly one predicate is `true`. * - * When to use: - * - You want an exclusive-or between two conditions. + * **When to use** * - * Behavior: - * - Pure; does not mutate input. - * - Returns `true` when results differ. + * Use when you want to combine two `Predicate`s with exclusive-or semantics. + * + * **Details** + * + * Returns `true` when results differ. * * **Example** (Exclusive or) * @@ -2264,8 +2320,8 @@ export const and: { * console.log(either(-2)) * ``` * - * See also: {@link or}, {@link and} - * + * @see {@link or} + * @see {@link and} * @category combinators * @since 2.0.0 */ @@ -2273,12 +2329,13 @@ export const xor: { /** * Creates a predicate that returns `true` if exactly one predicate is `true`. * - * When to use: - * - You want an exclusive-or between two conditions. + * **When to use** + * + * Use when you want to combine two `Predicate`s with exclusive-or semantics. + * + * **Details** * - * Behavior: - * - Pure; does not mutate input. - * - Returns `true` when results differ. + * Returns `true` when results differ. * * **Example** (Exclusive or) * @@ -2292,8 +2349,8 @@ export const xor: { * console.log(either(-2)) * ``` * - * See also: {@link or}, {@link and} - * + * @see {@link or} + * @see {@link and} * @category combinators * @since 2.0.0 */ @@ -2301,12 +2358,13 @@ export const xor: { /** * Creates a predicate that returns `true` if exactly one predicate is `true`. * - * When to use: - * - You want an exclusive-or between two conditions. + * **When to use** + * + * Use when you want to combine two `Predicate`s with exclusive-or semantics. * - * Behavior: - * - Pure; does not mutate input. - * - Returns `true` when results differ. + * **Details** + * + * Returns `true` when results differ. * * **Example** (Exclusive or) * @@ -2320,8 +2378,8 @@ export const xor: { * console.log(either(-2)) * ``` * - * See also: {@link or}, {@link and} - * + * @see {@link or} + * @see {@link and} * @category combinators * @since 2.0.0 */ @@ -2331,12 +2389,13 @@ export const xor: { /** * Creates a predicate that returns `true` when both predicates agree. * - * When to use: - * - You want to check equivalence of two predicates. + * **When to use** * - * Behavior: - * - Pure; does not mutate input. - * - Returns `true` when both results are equal. + * Use when you want to check equivalence of two `Predicate`s. + * + * **Details** + * + * Returns `true` when both results are equal. * * **Example** (Equivalence) * @@ -2349,8 +2408,7 @@ export const xor: { * console.log(same(3)) * ``` * - * See also: {@link xor} - * + * @see {@link xor} * @category combinators * @since 2.0.0 */ @@ -2358,12 +2416,13 @@ export const eqv: { /** * Creates a predicate that returns `true` when both predicates agree. * - * When to use: - * - You want to check equivalence of two predicates. + * **When to use** + * + * Use when you want to check equivalence of two `Predicate`s. * - * Behavior: - * - Pure; does not mutate input. - * - Returns `true` when both results are equal. + * **Details** + * + * Returns `true` when both results are equal. * * **Example** (Equivalence) * @@ -2376,8 +2435,7 @@ export const eqv: { * console.log(same(3)) * ``` * - * See also: {@link xor} - * + * @see {@link xor} * @category combinators * @since 2.0.0 */ @@ -2385,12 +2443,13 @@ export const eqv: { /** * Creates a predicate that returns `true` when both predicates agree. * - * When to use: - * - You want to check equivalence of two predicates. + * **When to use** + * + * Use when you want to check equivalence of two `Predicate`s. + * + * **Details** * - * Behavior: - * - Pure; does not mutate input. - * - Returns `true` when both results are equal. + * Returns `true` when both results are equal. * * **Example** (Equivalence) * @@ -2403,8 +2462,7 @@ export const eqv: { * console.log(same(3)) * ``` * - * See also: {@link xor} - * + * @see {@link xor} * @category combinators * @since 2.0.0 */ @@ -2414,13 +2472,15 @@ export const eqv: { /** * Creates a predicate representing logical implication: if `antecedent`, then `consequent`. * - * When to use: - * - You want a rule that only applies when a precondition holds. - * - You model constraints like "if A then B". + * **When to use** + * + * Use when you need to encode logical implication between `Predicate` rules, + * where one rule only applies when a precondition holds. + * + * **Details** * - * Behavior: - * - Pure; does not mutate input. - * - Returns `true` when the antecedent is `false`. + * Models constraints like "if A then B" and returns `true` when the antecedent + * is `false`. * * **Example** (Implication) * @@ -2434,8 +2494,8 @@ export const eqv: { * console.log(implies(16)) * ``` * - * See also: {@link and}, {@link or} - * + * @see {@link and} + * @see {@link or} * @category combinators * @since 2.0.0 */ @@ -2443,13 +2503,15 @@ export const implies: { /** * Creates a predicate representing logical implication: if `antecedent`, then `consequent`. * - * When to use: - * - You want a rule that only applies when a precondition holds. - * - You model constraints like "if A then B". + * **When to use** + * + * Use when you need to encode logical implication between `Predicate` rules, + * where one rule only applies when a precondition holds. * - * Behavior: - * - Pure; does not mutate input. - * - Returns `true` when the antecedent is `false`. + * **Details** + * + * Models constraints like "if A then B" and returns `true` when the antecedent + * is `false`. * * **Example** (Implication) * @@ -2463,8 +2525,8 @@ export const implies: { * console.log(implies(16)) * ``` * - * See also: {@link and}, {@link or} - * + * @see {@link and} + * @see {@link or} * @category combinators * @since 2.0.0 */ @@ -2472,13 +2534,15 @@ export const implies: { /** * Creates a predicate representing logical implication: if `antecedent`, then `consequent`. * - * When to use: - * - You want a rule that only applies when a precondition holds. - * - You model constraints like "if A then B". + * **When to use** + * + * Use when you need to encode logical implication between `Predicate` rules, + * where one rule only applies when a precondition holds. + * + * **Details** * - * Behavior: - * - Pure; does not mutate input. - * - Returns `true` when the antecedent is `false`. + * Models constraints like "if A then B" and returns `true` when the antecedent + * is `false`. * * **Example** (Implication) * @@ -2492,8 +2556,8 @@ export const implies: { * console.log(implies(16)) * ``` * - * See also: {@link and}, {@link or} - * + * @see {@link and} + * @see {@link or} * @category combinators * @since 2.0.0 */ @@ -2506,12 +2570,13 @@ export const implies: { /** * Creates a predicate that returns `true` when neither predicate is `true`. * - * When to use: - * - You want the logical NOR of two conditions. + * **When to use** + * + * Use when you want to combine two `Predicate`s with logical NOR semantics. * - * Behavior: - * - Pure; does not mutate input. - * - Returns the negation of {@link or}. + * **Details** + * + * Returns the negation of `or`. * * **Example** (NOR) * @@ -2523,8 +2588,8 @@ export const implies: { * console.log(neither(true)) * ``` * - * See also: {@link or}, {@link not} - * + * @see {@link or} + * @see {@link not} * @category combinators * @since 2.0.0 */ @@ -2532,12 +2597,13 @@ export const nor: { /** * Creates a predicate that returns `true` when neither predicate is `true`. * - * When to use: - * - You want the logical NOR of two conditions. + * **When to use** * - * Behavior: - * - Pure; does not mutate input. - * - Returns the negation of {@link or}. + * Use when you want to combine two `Predicate`s with logical NOR semantics. + * + * **Details** + * + * Returns the negation of `or`. * * **Example** (NOR) * @@ -2549,8 +2615,8 @@ export const nor: { * console.log(neither(true)) * ``` * - * See also: {@link or}, {@link not} - * + * @see {@link or} + * @see {@link not} * @category combinators * @since 2.0.0 */ @@ -2558,12 +2624,13 @@ export const nor: { /** * Creates a predicate that returns `true` when neither predicate is `true`. * - * When to use: - * - You want the logical NOR of two conditions. + * **When to use** + * + * Use when you want to combine two `Predicate`s with logical NOR semantics. * - * Behavior: - * - Pure; does not mutate input. - * - Returns the negation of {@link or}. + * **Details** + * + * Returns the negation of `or`. * * **Example** (NOR) * @@ -2575,8 +2642,8 @@ export const nor: { * console.log(neither(true)) * ``` * - * See also: {@link or}, {@link not} - * + * @see {@link or} + * @see {@link not} * @category combinators * @since 2.0.0 */ @@ -2589,12 +2656,13 @@ export const nor: { /** * Creates a predicate that returns `true` unless both predicates are `true`. * - * When to use: - * - You want the logical NAND of two conditions. + * **When to use** + * + * Use when you want to combine two `Predicate`s with logical NAND semantics. * - * Behavior: - * - Pure; does not mutate input. - * - Returns the negation of {@link and}. + * **Details** + * + * Returns the negation of `and`. * * **Example** (NAND) * @@ -2606,8 +2674,8 @@ export const nor: { * console.log(notBoth("a")) * ``` * - * See also: {@link and}, {@link not} - * + * @see {@link and} + * @see {@link not} * @category combinators * @since 2.0.0 */ @@ -2615,12 +2683,13 @@ export const nand: { /** * Creates a predicate that returns `true` unless both predicates are `true`. * - * When to use: - * - You want the logical NAND of two conditions. + * **When to use** * - * Behavior: - * - Pure; does not mutate input. - * - Returns the negation of {@link and}. + * Use when you want to combine two `Predicate`s with logical NAND semantics. + * + * **Details** + * + * Returns the negation of `and`. * * **Example** (NAND) * @@ -2632,8 +2701,8 @@ export const nand: { * console.log(notBoth("a")) * ``` * - * See also: {@link and}, {@link not} - * + * @see {@link and} + * @see {@link not} * @category combinators * @since 2.0.0 */ @@ -2641,12 +2710,13 @@ export const nand: { /** * Creates a predicate that returns `true` unless both predicates are `true`. * - * When to use: - * - You want the logical NAND of two conditions. + * **When to use** + * + * Use when you want to combine two `Predicate`s with logical NAND semantics. * - * Behavior: - * - Pure; does not mutate input. - * - Returns the negation of {@link and}. + * **Details** + * + * Returns the negation of `and`. * * **Example** (NAND) * @@ -2658,8 +2728,8 @@ export const nand: { * console.log(notBoth("a")) * ``` * - * See also: {@link and}, {@link not} - * + * @see {@link and} + * @see {@link not} * @category combinators * @since 2.0.0 */ @@ -2672,13 +2742,14 @@ export const nand: { /** * Creates a predicate that returns `true` if all predicates in the collection return `true`. * - * When to use: - * - You have a dynamic list of predicates to apply. + * **When to use** + * + * Use when you have a dynamic list of predicates to apply. + * + * **Details** * - * Behavior: - * - Pure; does not mutate input. - * - Short-circuits on the first `false`. - * - Iterates the collection each time the predicate is called. + * Evaluation short-circuits on the first `false`. The collection is iterated + * each time the predicate is called. * * **Example** (All checks) * @@ -2690,8 +2761,8 @@ export const nand: { * console.log(allChecks(2)) * ``` * - * See also: {@link some}, {@link and} - * + * @see {@link some} + * @see {@link and} * @category elements * @since 2.0.0 */ @@ -2709,13 +2780,14 @@ export function every(collection: Iterable>): Predicate { /** * Creates a predicate that returns `true` if any predicate in the collection returns `true`. * - * When to use: - * - You have a dynamic list of predicates and only need one to pass. + * **When to use** + * + * Use when you have a dynamic list of predicates and only need one to pass. * - * Behavior: - * - Pure; does not mutate input. - * - Short-circuits on the first `true`. - * - Iterates the collection each time the predicate is called. + * **Details** + * + * Evaluation short-circuits on the first `true`. The collection is iterated + * each time the predicate is called. * * **Example** (Any check) * @@ -2727,8 +2799,8 @@ export function every(collection: Iterable>): Predicate { * console.log(anyCheck("ok")) * ``` * - * See also: {@link every}, {@link or} - * + * @see {@link every} + * @see {@link or} * @category elements * @since 2.0.0 */ diff --git a/.opencode/node_modules/effect/src/PrimaryKey.ts b/.opencode/node_modules/effect/src/PrimaryKey.ts index bf0e959e094d040bcb390a2586b0bea96bb3697a..8353ad9dffa770ac2861b69ab50c764882d58521 100644 --- a/.opencode/node_modules/effect/src/PrimaryKey.ts +++ b/.opencode/node_modules/effect/src/PrimaryKey.ts @@ -1,11 +1,8 @@ /** - * This module provides functionality for working with primary keys. - * A `PrimaryKey` is a simple interface that represents a unique identifier - * that can be converted to a string representation. - * - * Primary keys are useful for creating unique identifiers for objects, - * database records, cache keys, or any scenario where you need a - * string-based unique identifier. + * The `PrimaryKey` module defines a small protocol for values that can expose + * a stable, string-based identifier. A value participates by implementing a + * method at {@link symbol}; consumers can check unknown values with + * {@link isPrimaryKey} and read the key with {@link value}. * * @since 2.0.0 */ @@ -13,8 +10,18 @@ import { hasProperty } from "./Predicate.ts" /** - * The unique identifier used to identify objects that implement the `PrimaryKey` interface. + * Defines the unique identifier used to identify objects that implement the `PrimaryKey` interface. + * + * **When to use** + * + * Use to implement the `PrimaryKey` protocol as a computed property key on + * classes or object literals that expose a stable string identifier. * + * @see {@link PrimaryKey} for the protocol interface that declares the method keyed by this symbol + * @see {@link value} for reading the string key from a `PrimaryKey` value + * @see {@link isPrimaryKey} for checking whether an unknown value carries this method + * + * @category symbols * @since 2.0.0 */ export const symbol = "~effect/interfaces/PrimaryKey" @@ -22,10 +29,18 @@ export const symbol = "~effect/interfaces/PrimaryKey" /** * An interface for objects that can provide a string-based primary key. * + * **When to use** + * + * Use to define values that expose a stable string identifier for equality, + * hashing, caching, or persistence. + * + * **Details** + * * Objects implementing this interface must provide a method that returns * a unique string identifier. * - * @example + * **Example** (Implementing a primary key) + * * ```ts * import { PrimaryKey } from "effect" * @@ -49,15 +64,38 @@ export interface PrimaryKey { } /** + * Checks whether a value implements the `PrimaryKey` protocol. + * + * **When to use** + * + * Use to narrow an unknown value before treating it as a `PrimaryKey`. + * + * **Details** + * + * This is a structural guard for the `PrimaryKey.symbol` property. + * + * **Gotchas** + * + * This guard does not call the method or verify that it returns a string. + * + * @see {@link PrimaryKey} for the protocol being checked + * @see {@link value} for extracting the string value after narrowing + * * @category models - * @since 2.0.0 + * @since 4.0.0 */ export const isPrimaryKey = (u: unknown): u is PrimaryKey => hasProperty(u, symbol) /** * Extracts the string value from a `PrimaryKey`. * - * @example + * **When to use** + * + * Use to read the stable string identifier from a value that implements + * `PrimaryKey`. + * + * **Example** (Reading primary key values) + * * ```ts * import { PrimaryKey } from "effect" * diff --git a/.opencode/node_modules/effect/src/PubSub.ts b/.opencode/node_modules/effect/src/PubSub.ts index 4e7c1150a4141928659d8454b13fbeacf7b8cefd..e491162de4446f7ab82efae93531df5050c0841c 100644 --- a/.opencode/node_modules/effect/src/PubSub.ts +++ b/.opencode/node_modules/effect/src/PubSub.ts @@ -1,30 +1,12 @@ /** - * This module provides utilities for working with publish-subscribe (PubSub) systems. + * Broadcasts values from publishers to many subscribers. * - * A PubSub is an asynchronous message hub where publishers can publish messages and subscribers - * can subscribe to receive those messages. PubSub supports various backpressure strategies, - * message replay, and concurrent access from multiple producers and consumers. - * - * @example - * ```ts - * import { Effect, PubSub } from "effect" - * - * const program = Effect.gen(function*() { - * const pubsub = yield* PubSub.bounded(10) - * - * // Publisher - * yield* PubSub.publish(pubsub, "Hello") - * yield* PubSub.publish(pubsub, "World") - * - * // Subscriber - * yield* Effect.scoped(Effect.gen(function*() { - * const subscription = yield* PubSub.subscribe(pubsub) - * const message1 = yield* PubSub.take(subscription) - * const message2 = yield* PubSub.take(subscription) - * console.log(message1, message2) // "Hello", "World" - * })) - * }) - * ``` + * Publishers add messages with `publish` or `publishAll`, and each active + * `Subscription` receives its own copy of every accepted message. Unlike a + * queue, subscribers do not compete for messages. This module includes bounded, + * dropping, sliding, and unbounded hubs, optional replay buffers for late + * subscribers, message-taking helpers, capacity and shutdown operations, and + * low-level types for custom hub strategies. * * @since 2.0.0 */ @@ -51,22 +33,23 @@ const TypeId = "~effect/PubSub" * messages of type `A` and subscribers can subscribe to take messages of type * `A`. * - * @example + * **Example** (Publishing and subscribing to messages) + * * ```ts - * import { Effect } from "effect" - * import * as PubSub from "effect/PubSub" + * import { Effect, PubSub } from "effect" * * const program = Effect.gen(function*() { * // Create a bounded PubSub with capacity 10 * const pubsub = yield* PubSub.bounded(10) * - * // Publish messages - * yield* PubSub.publish(pubsub, "Hello") - * yield* PubSub.publish(pubsub, "World") - * * // Subscribe and consume messages * yield* Effect.scoped(Effect.gen(function*() { * const subscription = yield* PubSub.subscribe(pubsub) + * + * // Publish messages + * yield* PubSub.publish(pubsub, "Hello") + * yield* PubSub.publish(pubsub, "World") + * * const message1 = yield* PubSub.take(subscription) * const message2 = yield* PubSub.take(subscription) * console.log(message1, message2) // "Hello", "World" @@ -74,8 +57,8 @@ const TypeId = "~effect/PubSub" * }) * ``` * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface PubSub extends Pipeable { readonly [TypeId]: { @@ -90,15 +73,18 @@ export interface PubSub extends Pipeable { } /** + * Companion namespace containing the low-level building blocks used by + * `PubSub`, including atomic implementations, backing subscriptions, replay + * windows, and delivery strategies. + * * @since 2.0.0 - * @category models */ -export namespace PubSub { +export declare namespace PubSub { /** * Low-level atomic PubSub interface that handles the core message storage and retrieval. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface Atomic { readonly capacity: number @@ -115,8 +101,8 @@ export namespace PubSub { /** * Low-level subscription interface that handles message polling for individual subscribers. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface BackingSubscription { isEmpty(): boolean @@ -127,10 +113,16 @@ export namespace PubSub { } /** - * Internal type representing the mapping from subscriptions to their pollers. + * Tracks the pollers currently waiting on each backing subscription. + * + * **Details** + * + * This type is part of the low-level `PubSub.Strategy` contract. Most + * application code should use `subscribe`, `take`, and the other `PubSub` + * operations instead of manipulating subscriber maps directly. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type Subscribers = Map< BackingSubscription, @@ -140,8 +132,8 @@ export namespace PubSub { /** * Interface for accessing replay buffer contents for late subscribers. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface ReplayWindow { take(): A | undefined @@ -153,8 +145,8 @@ export namespace PubSub { /** * Strategy interface defining how PubSub handles backpressure and message distribution. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface Strategy { /** @@ -210,10 +202,10 @@ const SubscriptionTypeId = "~effect/PubSub/Subscription" /** * A subscription represents a consumer's connection to a PubSub, allowing them to take messages. * - * @example + * **Example** (Taking messages from a subscription) + * * ```ts - * import { Effect } from "effect" - * import * as PubSub from "effect/PubSub" + * import { Effect, PubSub } from "effect" * * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(10) @@ -224,18 +216,23 @@ const SubscriptionTypeId = "~effect/PubSub/Subscription" * pubsub * ) * + * yield* PubSub.publishAll(pubsub, ["msg1", "msg2", "msg3"]) + * * // Take individual messages * const message = yield* PubSub.take(subscription) + * console.log(message) // "msg1" * * // Take multiple messages - * const messages = yield* PubSub.takeUpTo(subscription, 5) + * const messages = yield* PubSub.takeUpTo(subscription, 1) + * console.log(messages) // ["msg2"] * const allMessages = yield* PubSub.takeAll(subscription) + * console.log(allMessages) // ["msg3"] * })) * }) * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface Subscription extends Pipeable { readonly [SubscriptionTypeId]: { @@ -254,10 +251,10 @@ export interface Subscription extends Pipeable { /** * Creates a PubSub with a custom atomic implementation and strategy. * - * @example + * **Example** (Creating a PubSub with a custom strategy) + * * ```ts - * import { Effect } from "effect" - * import * as PubSub from "effect/PubSub" + * import { Effect, PubSub } from "effect" * * const program = Effect.gen(function*() { * // Create custom PubSub with specific atomic implementation and strategy @@ -271,8 +268,8 @@ export interface Subscription extends Pipeable { * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const make = ( options: { @@ -292,20 +289,20 @@ export const make = ( ) /** - * Creates a bounded PubSub with backpressure strategy. + * Creates a bounded `PubSub` that applies backpressure when it reaches + * capacity. + * + * **Details** * - * The PubSub will retain messages until they have been taken by all subscribers. - * When the PubSub reaches capacity, publishers will be suspended until space becomes available. - * This ensures message delivery guarantees but may slow down fast publishers. + * Published messages are retained until all current subscribers have taken + * them. When the capacity is full, publishers suspend until space is available. + * Pass an options object to configure both `capacity` and an optional replay + * buffer for late subscribers. * - * @param capacity - The maximum number of messages the PubSub can hold, or an options object - * with capacity and optional replay buffer size - * @returns An Effect that creates a bounded PubSub + * **Example** (Creating a bounded PubSub) * - * @example * ```ts - * import { Effect } from "effect" - * import * as PubSub from "effect/PubSub" + * import { Effect, PubSub } from "effect" * * const program = Effect.gen(function*() { * // Create bounded PubSub with capacity 100 @@ -319,8 +316,8 @@ export const make = ( * }) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const bounded = ( capacity: number | { @@ -337,12 +334,14 @@ export const bounded = ( * Creates a bounded `PubSub` with the dropping strategy. The `PubSub` will drop new * messages if the `PubSub` is at capacity. * + * **Details** + * * For best performance use capacities that are powers of two. * - * @example + * **Example** (Dropping messages when full) + * * ```ts - * import { Effect } from "effect" - * import * as PubSub from "effect/PubSub" + * import { Effect, PubSub } from "effect" * * const program = Effect.gen(function*() { * // Create dropping PubSub that drops new messages when full @@ -354,17 +353,24 @@ export const bounded = ( * replay: 5 * }) * - * // Fill the PubSub and see dropping behavior - * yield* PubSub.publish(pubsub, "msg1") // succeeds - * yield* PubSub.publish(pubsub, "msg2") // succeeds - * yield* PubSub.publish(pubsub, "msg3") // succeeds - * const dropped = yield* PubSub.publish(pubsub, "msg4") // returns false (dropped) - * console.log("Message dropped:", !dropped) + * yield* Effect.scoped(Effect.gen(function*() { + * const subscription = yield* PubSub.subscribe(pubsub) + * + * // Fill the PubSub and see dropping behavior + * yield* PubSub.publish(pubsub, "msg1") // succeeds + * yield* PubSub.publish(pubsub, "msg2") // succeeds + * yield* PubSub.publish(pubsub, "msg3") // succeeds + * const dropped = yield* PubSub.publish(pubsub, "msg4") // returns false (dropped) + * console.log("Message dropped:", !dropped) // true + * + * const messages = yield* PubSub.takeAll(subscription) + * console.log(messages) // ["msg1", "msg2", "msg3"] + * })) * }) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const dropping = ( capacity: number | { @@ -381,12 +387,14 @@ export const dropping = ( * Creates a bounded `PubSub` with the sliding strategy. The `PubSub` will add new * messages and drop old messages if the `PubSub` is at capacity. * + * **Details** + * * For best performance use capacities that are powers of two. * - * @example + * **Example** (Sliding old messages when full) + * * ```ts - * import { Effect } from "effect" - * import * as PubSub from "effect/PubSub" + * import { Effect, PubSub } from "effect" * * const program = Effect.gen(function*() { * // Create sliding PubSub that evicts old messages when full @@ -398,22 +406,23 @@ export const dropping = ( * replay: 2 * }) * - * // Fill and overflow the PubSub - * yield* PubSub.publish(pubsub, "msg1") - * yield* PubSub.publish(pubsub, "msg2") - * yield* PubSub.publish(pubsub, "msg3") - * yield* PubSub.publish(pubsub, "msg4") // "msg1" is evicted - * * yield* Effect.scoped(Effect.gen(function*() { * const subscription = yield* PubSub.subscribe(pubsub) + * + * // Fill and overflow the PubSub + * yield* PubSub.publish(pubsub, "msg1") + * yield* PubSub.publish(pubsub, "msg2") + * yield* PubSub.publish(pubsub, "msg3") + * yield* PubSub.publish(pubsub, "msg4") // "msg1" is evicted + * * const messages = yield* PubSub.takeAll(subscription) * console.log(messages) // ["msg2", "msg3", "msg4"] * })) * }) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const sliding = ( capacity: number | { @@ -429,10 +438,10 @@ export const sliding = ( /** * Creates an unbounded `PubSub`. * - * @example + * **Example** (Creating an unbounded PubSub) + * * ```ts - * import { Effect } from "effect" - * import * as PubSub from "effect/PubSub" + * import { Effect, PubSub } from "effect" * * const program = Effect.gen(function*() { * // Create unbounded PubSub @@ -443,21 +452,22 @@ export const sliding = ( * replay: 10 * }) * - * // Can publish unlimited messages - * for (let i = 0; i < 1000; i++) { - * yield* PubSub.publish(pubsub, `message-${i}`) - * } - * * yield* Effect.scoped(Effect.gen(function*() { * const subscription = yield* PubSub.subscribe(pubsub) + * + * // Can publish unlimited messages + * for (let i = 0; i < 3; i++) { + * yield* PubSub.publish(pubsub, `message-${i}`) + * } + * * const message = yield* PubSub.take(subscription) - * console.log("First message:", message) + * console.log("First message:", message) // "message-0" * })) * }) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const unbounded = (options?: { readonly replay?: number | undefined @@ -470,8 +480,30 @@ export const unbounded = (options?: { /** * Creates a bounded atomic PubSub implementation with optional replay buffer. * - * @since 4.0.0 + * **When to use** + * + * Use to provide bounded message storage when building a custom `PubSub` with + * `make` and an explicit delivery strategy. + * + * **Details** + * + * Pass either a capacity number or an options object with `capacity` and + * optional `replay`. A positive `replay` value enables a replay buffer for late + * subscribers, and fractional replay sizes are rounded up. + * + * **Gotchas** + * + * The capacity must be greater than zero; invalid capacities throw + * synchronously before an atomic implementation is created. + * + * @see {@link make} for constructing a `PubSub` from an atomic implementation and delivery strategy + * @see {@link makeAtomicUnbounded} for an atomic implementation without a bounded capacity + * @see {@link bounded} for the higher-level backpressure constructor + * @see {@link dropping} for the higher-level dropping constructor + * @see {@link sliding} for the higher-level sliding constructor + * * @category constructors + * @since 4.0.0 */ export const makeAtomicBounded = ( capacity: number | { @@ -494,8 +526,22 @@ export const makeAtomicBounded = ( /** * Creates an unbounded atomic PubSub implementation with optional replay buffer. * - * @since 4.0.0 + * **When to use** + * + * Use to create the low-level storage layer for a custom `PubSub` whose active + * subscribers may retain an unbounded number of pending messages. + * + * **Gotchas** + * + * Messages published while subscribers are active can be retained without a + * capacity limit until those subscribers take them or unsubscribe. + * + * @see {@link makeAtomicBounded} for a bounded atomic implementation that enforces capacity + * @see {@link make} for wrapping an atomic implementation with a delivery strategy + * @see {@link unbounded} for the high-level effectful constructor for unbounded `PubSub` values + * * @category constructors + * @since 4.0.0 */ export const makeAtomicUnbounded = (options?: { readonly replay?: number | undefined @@ -504,10 +550,10 @@ export const makeAtomicUnbounded = (options?: { /** * Returns the number of elements the queue can hold. * - * @example + * **Example** (Getting PubSub capacity) + * * ```ts - * import { Effect } from "effect" - * import * as PubSub from "effect/PubSub" + * import { Effect, PubSub } from "effect" * * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(100) @@ -520,20 +566,24 @@ export const makeAtomicUnbounded = (options?: { * }) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export const capacity = (self: PubSub): number => self.pubsub.capacity /** - * Retrieves the size of the queue, which is equal to the number of elements - * in the queue. This may be negative if fibers are suspended waiting for - * elements to be added to the queue. + * Returns the current number of messages retained by the `PubSub` for active + * subscribers. + * + * **Details** + * + * If the `PubSub` has been shut down, the returned effect succeeds with `0`. + * The size is not a count of waiting subscribers or suspended publishers. + * + * **Example** (Getting PubSub size) * - * @example * ```ts - * import { Effect } from "effect" - * import * as PubSub from "effect/PubSub" + * import { Effect, PubSub } from "effect" * * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(10) @@ -542,25 +592,41 @@ export const capacity = (self: PubSub): number => self.pubsub.capacity * const initialSize = yield* PubSub.size(pubsub) * console.log("Initial size:", initialSize) // 0 * - * // Publish some messages - * yield* PubSub.publish(pubsub, "msg1") - * yield* PubSub.publish(pubsub, "msg2") + * yield* Effect.scoped(Effect.gen(function*() { + * const subscription = yield* PubSub.subscribe(pubsub) + * + * // Publish some messages for the active subscription + * yield* PubSub.publish(pubsub, "msg1") + * yield* PubSub.publish(pubsub, "msg2") + * + * const afterPublish = yield* PubSub.size(pubsub) + * console.log("After publishing:", afterPublish) // 2 * - * const afterPublish = yield* PubSub.size(pubsub) - * console.log("After publishing:", afterPublish) // 2 + * yield* PubSub.takeAll(subscription) + * })) * }) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export const size = (self: PubSub): Effect.Effect => Effect.sync(() => sizeUnsafe(self)) /** - * Retrieves the size of the queue, which is equal to the number of elements - * in the queue. This may be negative if fibers are suspended waiting for - * elements to be added to the queue. + * Returns the current number of messages retained by the `PubSub` for active + * subscribers synchronously. + * + * **When to use** + * + * Use when an immediate `PubSub` size snapshot is needed outside effectful code + * and concurrent changes between the check and later use are acceptable. + * + * **Details** + * + * Returns `0` after shutdown. Because this is an unsafe synchronous snapshot, + * prefer `size` in effectful code. + * + * **Example** (Reading size synchronously) * - * @example * ```ts * import { PubSub } from "effect" * @@ -571,8 +637,8 @@ export const size = (self: PubSub): Effect.Effect => Effect.sync(( * console.log("Current size:", size) * ``` * - * @since 2.0.0 * @category getters + * @since 4.0.0 */ export const sizeUnsafe = (self: PubSub): number => { if (MutableRef.get(self.shutdownFlag)) { @@ -582,13 +648,16 @@ export const sizeUnsafe = (self: PubSub): number => { } /** - * Returns `true` if the `PubSub` contains at least one element, `false` - * otherwise. + * Returns `true` when the `PubSub` has reached its configured capacity. + * + * **Details** + * + * For unbounded PubSubs this is normally `false`. + * + * **Example** (Checking whether a PubSub is full) * - * @example * ```ts - * import { Effect } from "effect" - * import * as PubSub from "effect/PubSub" + * import { Effect, PubSub } from "effect" * * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(2) @@ -597,17 +666,23 @@ export const sizeUnsafe = (self: PubSub): number => { * const initiallyFull = yield* PubSub.isFull(pubsub) * console.log("Initially full:", initiallyFull) // false * - * // Fill the PubSub - * yield* PubSub.publish(pubsub, "msg1") - * yield* PubSub.publish(pubsub, "msg2") + * yield* Effect.scoped(Effect.gen(function*() { + * const subscription = yield* PubSub.subscribe(pubsub) + * + * // Fill the PubSub for the active subscription + * yield* PubSub.publish(pubsub, "msg1") + * yield* PubSub.publish(pubsub, "msg2") + * + * const nowFull = yield* PubSub.isFull(pubsub) + * console.log("Now full:", nowFull) // true * - * const nowFull = yield* PubSub.isFull(pubsub) - * console.log("Now full:", nowFull) // true + * yield* PubSub.takeAll(subscription) + * })) * }) * ``` * - * @since 2.0.0 * @category predicates + * @since 2.0.0 */ export const isFull = (self: PubSub): Effect.Effect => Effect.map(size(self), (size) => size === self.pubsub.capacity) @@ -615,10 +690,10 @@ export const isFull = (self: PubSub): Effect.Effect => /** * Returns `true` if the `Pubsub` contains zero elements, `false` otherwise. * - * @example + * **Example** (Checking whether a PubSub is empty) + * * ```ts - * import { Effect } from "effect" - * import * as PubSub from "effect/PubSub" + * import { Effect, PubSub } from "effect" * * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(10) @@ -627,49 +702,57 @@ export const isFull = (self: PubSub): Effect.Effect => * const initiallyEmpty = yield* PubSub.isEmpty(pubsub) * console.log("Initially empty:", initiallyEmpty) // true * - * // Publish a message - * yield* PubSub.publish(pubsub, "Hello") + * yield* Effect.scoped(Effect.gen(function*() { + * const subscription = yield* PubSub.subscribe(pubsub) * - * const nowEmpty = yield* PubSub.isEmpty(pubsub) - * console.log("Now empty:", nowEmpty) // false + * // Publish a message for the active subscription + * yield* PubSub.publish(pubsub, "Hello") + * + * const nowEmpty = yield* PubSub.isEmpty(pubsub) + * console.log("Now empty:", nowEmpty) // false + * + * yield* PubSub.take(subscription) + * })) * }) * ``` * - * @since 2.0.0 * @category predicates + * @since 2.0.0 */ export const isEmpty = (self: PubSub): Effect.Effect => Effect.map(size(self), (size) => size === 0) /** - * Interrupts any fibers that are suspended on `offer` or `take`. Future calls - * to `offer*` and `take*` will be interrupted immediately. + * Shuts down the `PubSub`, interrupting suspended publishers and subscribers + * and finalizing active subscriptions. + * + * **Details** + * + * After shutdown, `publish` and `publishAll` succeed with `false`, + * `publishUnsafe` returns `false`, and subscription operations such as `take` + * interrupt. + * + * **Example** (Shutting down a PubSub) * - * @example * ```ts - * import { Effect, Fiber, PubSub } from "effect" + * import { Effect, PubSub } from "effect" * * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(1) * - * // Start a fiber that will be suspended waiting to publish - * const publisherFiber = yield* Effect.forkChild( - * Effect.gen(function*() { - * yield* PubSub.publish(pubsub, "msg1") // fills the buffer - * yield* PubSub.publish(pubsub, "msg2") // will suspend here - * }) - * ) - * * // Shutdown the PubSub * yield* PubSub.shutdown(pubsub) * - * // The suspended publisher will be interrupted - * const result = yield* Fiber.await(publisherFiber) - * console.log("Publisher interrupted:", result._tag === "Failure") + * const isShutdown = yield* PubSub.isShutdown(pubsub) + * console.log("Is shutdown:", isShutdown) // true + * + * // Publishing after shutdown returns false + * const published = yield* PubSub.publish(pubsub, "msg1") + * console.log("Published after shutdown:", published) // false * }) * ``` * - * @since 2.0.0 * @category lifecycle + * @since 2.0.0 */ export const shutdown = (self: PubSub): Effect.Effect => Effect.uninterruptible(Effect.withFiber((fiber) => { @@ -682,12 +765,13 @@ export const shutdown = (self: PubSub): Effect.Effect => })) /** - * Returns `true` if `shutdown` has been called, otherwise returns `false`. + * Checks effectfully whether `shutdown` has been called, returning `true` + * after shutdown and `false` otherwise. + * + * **Example** (Checking whether a PubSub is shutdown) * - * @example * ```ts - * import { Effect } from "effect" - * import * as PubSub from "effect/PubSub" + * import { Effect, PubSub } from "effect" * * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(10) @@ -704,15 +788,22 @@ export const shutdown = (self: PubSub): Effect.Effect => * }) * ``` * - * @since 2.0.0 * @category predicates + * @since 2.0.0 */ export const isShutdown = (self: PubSub): Effect.Effect => Effect.sync(() => isShutdownUnsafe(self)) /** - * Returns `true` if `shutdown` has been called, otherwise returns `false`. + * Checks synchronously whether `shutdown` has been called, returning `true` + * after shutdown and `false` otherwise. + * + * **When to use** + * + * Use when an immediate `PubSub` shutdown-state snapshot is needed outside + * effectful code and racing shutdown changes are acceptable. + * + * **Example** (Checking shutdown synchronously) * - * @example * ```ts * import { PubSub } from "effect" * @@ -727,8 +818,8 @@ export const isShutdown = (self: PubSub): Effect.Effect => Effect * } * ``` * - * @since 4.0.0 * @category predicates + * @since 4.0.0 */ export const isShutdownUnsafe = (self: PubSub): boolean => self.shutdownFlag.current @@ -737,7 +828,8 @@ export const isShutdownUnsafe = (self: PubSub): boolean => self.shutdownFl * not resume until the queue has been shutdown. If the queue is already * shutdown, the `Effect` will resume right away. * - * @example + * **Example** (Waiting for shutdown) + * * ```ts * import { Effect, Fiber, PubSub } from "effect" * @@ -763,19 +855,30 @@ export const isShutdownUnsafe = (self: PubSub): boolean => self.shutdownFl * }) * ``` * - * @since 2.0.0 * @category lifecycle + * @since 2.0.0 */ export const awaitShutdown = (self: PubSub): Effect.Effect => self.shutdownHook.await /** - * Publishes a message to the `PubSub`, returning whether the message was published - * to the `PubSub`. + * Publishes a message to the `PubSub` as an `Effect`, returning whether the + * message was accepted. + * + * **When to use** + * + * Use when you need to publish from effectful code and let the configured + * PubSub strategy handle surplus messages. + * + * **Details** + * + * The effect succeeds with `false` if the `PubSub` is shut down. If the message + * cannot be accepted immediately, the configured strategy decides how surplus + * messages are handled. + * + * **Example** (Publishing a message) * - * @example * ```ts - * import { Effect } from "effect" - * import * as PubSub from "effect/PubSub" + * import { Effect, PubSub } from "effect" * * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(10) @@ -784,35 +887,41 @@ export const awaitShutdown = (self: PubSub): Effect.Effect => self.s * const published = yield* PubSub.publish(pubsub, "Hello World") * console.log("Message published:", published) // true * - * // With a full bounded PubSub using backpressure strategy - * const smallPubsub = yield* PubSub.bounded(1) - * yield* PubSub.publish(smallPubsub, "msg1") // succeeds - * - * // This will suspend until space becomes available - * const publishEffect = PubSub.publish(smallPubsub, "msg2") - * - * // Create a subscriber to free up space * yield* Effect.scoped(Effect.gen(function*() { - * const subscription = yield* PubSub.subscribe(smallPubsub) - * yield* PubSub.take(subscription) // frees space - * const result = yield* publishEffect - * console.log("Second message published:", result) // true + * const subscription = yield* PubSub.subscribe(pubsub) + * + * yield* PubSub.publish(pubsub, "Hello") + * const message = yield* PubSub.take(subscription) + * console.log("Received:", message) // "Hello" * })) * }) * ``` * - * @since 2.0.0 + * @see {@link publishUnsafe} for a synchronous non-blocking attempt that does not run effectful surplus handling + * * @category publishing + * @since 2.0.0 */ export const publish: { /** - * Publishes a message to the `PubSub`, returning whether the message was published - * to the `PubSub`. + * Publishes a message to the `PubSub` as an `Effect`, returning whether the + * message was accepted. + * + * **When to use** + * + * Use when you need to publish from effectful code and let the configured + * PubSub strategy handle surplus messages. + * + * **Details** + * + * The effect succeeds with `false` if the `PubSub` is shut down. If the message + * cannot be accepted immediately, the configured strategy decides how surplus + * messages are handled. + * + * **Example** (Publishing a message) * - * @example * ```ts - * import { Effect } from "effect" - * import * as PubSub from "effect/PubSub" + * import { Effect, PubSub } from "effect" * * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(10) @@ -821,35 +930,41 @@ export const publish: { * const published = yield* PubSub.publish(pubsub, "Hello World") * console.log("Message published:", published) // true * - * // With a full bounded PubSub using backpressure strategy - * const smallPubsub = yield* PubSub.bounded(1) - * yield* PubSub.publish(smallPubsub, "msg1") // succeeds - * - * // This will suspend until space becomes available - * const publishEffect = PubSub.publish(smallPubsub, "msg2") - * - * // Create a subscriber to free up space * yield* Effect.scoped(Effect.gen(function*() { - * const subscription = yield* PubSub.subscribe(smallPubsub) - * yield* PubSub.take(subscription) // frees space - * const result = yield* publishEffect - * console.log("Second message published:", result) // true + * const subscription = yield* PubSub.subscribe(pubsub) + * + * yield* PubSub.publish(pubsub, "Hello") + * const message = yield* PubSub.take(subscription) + * console.log("Received:", message) // "Hello" * })) * }) * ``` * - * @since 2.0.0 + * @see {@link publishUnsafe} for a synchronous non-blocking attempt that does not run effectful surplus handling + * * @category publishing + * @since 2.0.0 */ (value: A): (self: PubSub) => Effect.Effect /** - * Publishes a message to the `PubSub`, returning whether the message was published - * to the `PubSub`. + * Publishes a message to the `PubSub` as an `Effect`, returning whether the + * message was accepted. + * + * **When to use** + * + * Use when you need to publish from effectful code and let the configured + * PubSub strategy handle surplus messages. + * + * **Details** + * + * The effect succeeds with `false` if the `PubSub` is shut down. If the message + * cannot be accepted immediately, the configured strategy decides how surplus + * messages are handled. + * + * **Example** (Publishing a message) * - * @example * ```ts - * import { Effect } from "effect" - * import * as PubSub from "effect/PubSub" + * import { Effect, PubSub } from "effect" * * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(10) @@ -858,25 +973,20 @@ export const publish: { * const published = yield* PubSub.publish(pubsub, "Hello World") * console.log("Message published:", published) // true * - * // With a full bounded PubSub using backpressure strategy - * const smallPubsub = yield* PubSub.bounded(1) - * yield* PubSub.publish(smallPubsub, "msg1") // succeeds - * - * // This will suspend until space becomes available - * const publishEffect = PubSub.publish(smallPubsub, "msg2") - * - * // Create a subscriber to free up space * yield* Effect.scoped(Effect.gen(function*() { - * const subscription = yield* PubSub.subscribe(smallPubsub) - * yield* PubSub.take(subscription) // frees space - * const result = yield* publishEffect - * console.log("Second message published:", result) // true + * const subscription = yield* PubSub.subscribe(pubsub) + * + * yield* PubSub.publish(pubsub, "Hello") + * const message = yield* PubSub.take(subscription) + * console.log("Received:", message) // "Hello" * })) * }) * ``` * - * @since 2.0.0 + * @see {@link publishUnsafe} for a synchronous non-blocking attempt that does not run effectful surplus handling + * * @category publishing + * @since 2.0.0 */ (self: PubSub, value: A): Effect.Effect } = dual(2, (self: PubSub, value: A): Effect.Effect => @@ -899,10 +1009,22 @@ export const publish: { })) /** - * Publishes a message to the `PubSub`, returning whether the message was published - * to the `PubSub`. + * Attempts to publish a message synchronously without applying the PubSub + * strategy's effectful surplus handling. + * + * **When to use** + * + * Use when you need a non-blocking synchronous publish attempt where `false` + * is an acceptable result when the message cannot be accepted immediately. + * + * **Details** + * + * Returns `false` if the `PubSub` is shut down or the message cannot be + * accepted immediately, for example when a bounded PubSub is full. Prefer + * `publish` when backpressure or sliding behavior should be honored. + * + * **Example** (Publishing without suspending) * - * @example * ```ts * import { PubSub } from "effect" * @@ -923,15 +1045,29 @@ export const publish: { * console.log(`Published ${publishedCount} out of ${messages.length} messages`) * ``` * - * @since 4.0.0 + * @see {@link publish} for effectful publishing that honors the configured surplus strategy + * * @category publishing + * @since 4.0.0 */ export const publishUnsafe: { /** - * Publishes a message to the `PubSub`, returning whether the message was published - * to the `PubSub`. + * Attempts to publish a message synchronously without applying the PubSub + * strategy's effectful surplus handling. + * + * **When to use** + * + * Use when you need a non-blocking synchronous publish attempt where `false` + * is an acceptable result when the message cannot be accepted immediately. + * + * **Details** + * + * Returns `false` if the `PubSub` is shut down or the message cannot be + * accepted immediately, for example when a bounded PubSub is full. Prefer + * `publish` when backpressure or sliding behavior should be honored. + * + * **Example** (Publishing without suspending) * - * @example * ```ts * import { PubSub } from "effect" * @@ -952,15 +1088,29 @@ export const publishUnsafe: { * console.log(`Published ${publishedCount} out of ${messages.length} messages`) * ``` * - * @since 4.0.0 + * @see {@link publish} for effectful publishing that honors the configured surplus strategy + * * @category publishing + * @since 4.0.0 */ (value: A): (self: PubSub) => boolean /** - * Publishes a message to the `PubSub`, returning whether the message was published - * to the `PubSub`. + * Attempts to publish a message synchronously without applying the PubSub + * strategy's effectful surplus handling. + * + * **When to use** + * + * Use when you need a non-blocking synchronous publish attempt where `false` + * is an acceptable result when the message cannot be accepted immediately. + * + * **Details** + * + * Returns `false` if the `PubSub` is shut down or the message cannot be + * accepted immediately, for example when a bounded PubSub is full. Prefer + * `publish` when backpressure or sliding behavior should be honored. + * + * **Example** (Publishing without suspending) * - * @example * ```ts * import { PubSub } from "effect" * @@ -981,8 +1131,10 @@ export const publishUnsafe: { * console.log(`Published ${publishedCount} out of ${messages.length} messages`) * ``` * - * @since 4.0.0 + * @see {@link publish} for effectful publishing that honors the configured surplus strategy + * * @category publishing + * @since 4.0.0 */ (self: PubSub, value: A): boolean } = dual(2, (self: PubSub, value: A): boolean => { @@ -998,10 +1150,10 @@ export const publishUnsafe: { * Publishes all of the specified messages to the `PubSub`, returning whether they * were published to the `PubSub`. * - * @example + * **Example** (Publishing multiple messages) + * * ```ts - * import { Effect } from "effect" - * import * as PubSub from "effect/PubSub" + * import { Effect, Fiber, PubSub } from "effect" * * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(10) @@ -1011,35 +1163,40 @@ export const publishUnsafe: { * const allPublished = yield* PubSub.publishAll(pubsub, messages) * console.log("All messages published:", allPublished) // true * - * // With a smaller capacity + * // With a smaller capacity and an active subscription * const smallPubsub = yield* PubSub.bounded(2) * const manyMessages = ["msg1", "msg2", "msg3", "msg4"] * - * // Will suspend until space becomes available for all messages - * const publishAllEffect = PubSub.publishAll(smallPubsub, manyMessages) - * - * // Subscribe to consume messages and free space * yield* Effect.scoped(Effect.gen(function*() { * const subscription = yield* PubSub.subscribe(smallPubsub) - * yield* PubSub.takeAll(subscription) // consume all messages - * const result = yield* publishAllEffect - * console.log("All messages eventually published:", result) + * + * // Will suspend until space becomes available for all messages + * const fiber = yield* Effect.forkChild(PubSub.publishAll(smallPubsub, manyMessages)) + * + * const firstBatch = yield* PubSub.takeBetween(subscription, 2, 2) + * console.log("First batch:", firstBatch) // ["msg1", "msg2"] + * + * const result = yield* Fiber.join(fiber) + * console.log("All messages eventually published:", result) // true + * + * const secondBatch = yield* PubSub.takeAll(subscription) + * console.log("Second batch:", secondBatch) // ["msg3", "msg4"] * })) * }) * ``` * - * @since 2.0.0 * @category publishing + * @since 2.0.0 */ export const publishAll: { /** * Publishes all of the specified messages to the `PubSub`, returning whether they * were published to the `PubSub`. * - * @example + * **Example** (Publishing multiple messages) + * * ```ts - * import { Effect } from "effect" - * import * as PubSub from "effect/PubSub" + * import { Effect, Fiber, PubSub } from "effect" * * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(10) @@ -1049,35 +1206,40 @@ export const publishAll: { * const allPublished = yield* PubSub.publishAll(pubsub, messages) * console.log("All messages published:", allPublished) // true * - * // With a smaller capacity + * // With a smaller capacity and an active subscription * const smallPubsub = yield* PubSub.bounded(2) * const manyMessages = ["msg1", "msg2", "msg3", "msg4"] * - * // Will suspend until space becomes available for all messages - * const publishAllEffect = PubSub.publishAll(smallPubsub, manyMessages) - * - * // Subscribe to consume messages and free space * yield* Effect.scoped(Effect.gen(function*() { * const subscription = yield* PubSub.subscribe(smallPubsub) - * yield* PubSub.takeAll(subscription) // consume all messages - * const result = yield* publishAllEffect - * console.log("All messages eventually published:", result) + * + * // Will suspend until space becomes available for all messages + * const fiber = yield* Effect.forkChild(PubSub.publishAll(smallPubsub, manyMessages)) + * + * const firstBatch = yield* PubSub.takeBetween(subscription, 2, 2) + * console.log("First batch:", firstBatch) // ["msg1", "msg2"] + * + * const result = yield* Fiber.join(fiber) + * console.log("All messages eventually published:", result) // true + * + * const secondBatch = yield* PubSub.takeAll(subscription) + * console.log("Second batch:", secondBatch) // ["msg3", "msg4"] * })) * }) * ``` * - * @since 2.0.0 * @category publishing + * @since 2.0.0 */ (elements: Iterable): (self: PubSub) => Effect.Effect /** * Publishes all of the specified messages to the `PubSub`, returning whether they * were published to the `PubSub`. * - * @example + * **Example** (Publishing multiple messages) + * * ```ts - * import { Effect } from "effect" - * import * as PubSub from "effect/PubSub" + * import { Effect, Fiber, PubSub } from "effect" * * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(10) @@ -1087,25 +1249,30 @@ export const publishAll: { * const allPublished = yield* PubSub.publishAll(pubsub, messages) * console.log("All messages published:", allPublished) // true * - * // With a smaller capacity + * // With a smaller capacity and an active subscription * const smallPubsub = yield* PubSub.bounded(2) * const manyMessages = ["msg1", "msg2", "msg3", "msg4"] * - * // Will suspend until space becomes available for all messages - * const publishAllEffect = PubSub.publishAll(smallPubsub, manyMessages) - * - * // Subscribe to consume messages and free space * yield* Effect.scoped(Effect.gen(function*() { * const subscription = yield* PubSub.subscribe(smallPubsub) - * yield* PubSub.takeAll(subscription) // consume all messages - * const result = yield* publishAllEffect - * console.log("All messages eventually published:", result) + * + * // Will suspend until space becomes available for all messages + * const fiber = yield* Effect.forkChild(PubSub.publishAll(smallPubsub, manyMessages)) + * + * const firstBatch = yield* PubSub.takeBetween(subscription, 2, 2) + * console.log("First batch:", firstBatch) // ["msg1", "msg2"] + * + * const result = yield* Fiber.join(fiber) + * console.log("All messages eventually published:", result) // true + * + * const secondBatch = yield* PubSub.takeAll(subscription) + * console.log("Second batch:", secondBatch) // ["msg3", "msg4"] * })) * }) * ``` * - * @since 2.0.0 * @category publishing + * @since 2.0.0 */ (self: PubSub, elements: Iterable): Effect.Effect } = dual(2, (self: PubSub, elements: Iterable): Effect.Effect => @@ -1131,21 +1298,22 @@ export const publishAll: { * be evaluated multiple times within the scope to take a message from the `PubSub` * each time. * - * @example + * **Example** (Subscribing to messages) + * * ```ts * import { Effect, PubSub } from "effect" * * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(10) * - * // Publish some messages - * yield* PubSub.publish(pubsub, "Hello") - * yield* PubSub.publish(pubsub, "World") - * * // Subscribe within a scope for automatic cleanup * yield* Effect.scoped(Effect.gen(function*() { * const subscription = yield* PubSub.subscribe(pubsub) * + * // Publish some messages + * yield* PubSub.publish(pubsub, "Hello") + * yield* PubSub.publish(pubsub, "World") + * * // Take messages one by one * const msg1 = yield* PubSub.take(subscription) * const msg2 = yield* PubSub.take(subscription) @@ -1154,13 +1322,13 @@ export const publishAll: { * // Subscription is automatically cleaned up when scope exits * })) * - * // Multiple subscribers can receive the same messages - * yield* PubSub.publish(pubsub, "Broadcast") - * * yield* Effect.scoped(Effect.gen(function*() { * const sub1 = yield* PubSub.subscribe(pubsub) * const sub2 = yield* PubSub.subscribe(pubsub) * + * // Multiple subscribers can receive the same messages + * yield* PubSub.publish(pubsub, "Broadcast") + * * const [msg1, msg2] = yield* Effect.all([ * PubSub.take(sub1), * PubSub.take(sub2) @@ -1170,8 +1338,8 @@ export const publishAll: { * }) * ``` * + * @category subscriptions * @since 2.0.0 - * @category subscription */ export const subscribe = (self: PubSub): Effect.Effect, never, Scope.Scope> => Effect.uninterruptible( @@ -1212,7 +1380,8 @@ const unsubscribe = (self: Subscription): Effect.Effect => * Takes a single message from the subscription. If no messages are available, * this will suspend until a message becomes available. * - * @example + * **Example** (Taking a message) + * * ```ts * import { Effect, Fiber, PubSub } from "effect" * @@ -1237,8 +1406,8 @@ const unsubscribe = (self: Subscription): Effect.Effect => * }) * ``` * + * @category subscriptions * @since 4.0.0 - * @category subscription */ export const take = (self: Subscription): Effect.Effect => Effect.suspend(() => { @@ -1264,19 +1433,20 @@ export const take = (self: Subscription): Effect.Effect => * Takes all available messages from the subscription, suspending if no items * are available. * - * @example + * **Example** (Taking all available messages) + * * ```ts * import { Effect, PubSub } from "effect" * * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(10) * - * // Publish multiple messages - * yield* PubSub.publishAll(pubsub, ["msg1", "msg2", "msg3"]) - * * yield* Effect.scoped(Effect.gen(function*() { * const subscription = yield* PubSub.subscribe(pubsub) * + * // Publish multiple messages + * yield* PubSub.publishAll(pubsub, ["msg1", "msg2", "msg3"]) + * * // Take all available messages at once * const allMessages = yield* PubSub.takeAll(subscription) * console.log("All messages:", allMessages) // ["msg1", "msg2", "msg3"] @@ -1284,8 +1454,8 @@ export const take = (self: Subscription): Effect.Effect => * }) * ``` * + * @category subscriptions * @since 4.0.0 - * @category subscription */ export const takeAll = (self: Subscription): Effect.Effect> => Effect.suspend(function loop(value?: [A]): Effect.Effect> { @@ -1334,20 +1504,20 @@ const pollForItem = (self: Subscription) => { /** * Takes up to the specified number of messages from the subscription without suspending. * - * @example + * **Example** (Taking up to a maximum number of messages) + * * ```ts - * import { Effect } from "effect" - * import * as PubSub from "effect/PubSub" + * import { Effect, PubSub } from "effect" * * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(10) * - * // Publish multiple messages - * yield* PubSub.publishAll(pubsub, ["msg1", "msg2", "msg3", "msg4", "msg5"]) - * * yield* Effect.scoped(Effect.gen(function*() { * const subscription = yield* PubSub.subscribe(pubsub) * + * // Publish multiple messages + * yield* PubSub.publishAll(pubsub, ["msg1", "msg2", "msg3", "msg4", "msg5"]) + * * // Take up to 3 messages * const upTo3 = yield* PubSub.takeUpTo(subscription, 3) * console.log("Up to 3:", upTo3) // ["msg1", "msg2", "msg3"] @@ -1363,27 +1533,27 @@ const pollForItem = (self: Subscription) => { * }) * ``` * + * @category subscriptions * @since 4.0.0 - * @category subscription */ export const takeUpTo: { /** * Takes up to the specified number of messages from the subscription without suspending. * - * @example + * **Example** (Taking up to a maximum number of messages) + * * ```ts - * import { Effect } from "effect" - * import * as PubSub from "effect/PubSub" + * import { Effect, PubSub } from "effect" * * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(10) * - * // Publish multiple messages - * yield* PubSub.publishAll(pubsub, ["msg1", "msg2", "msg3", "msg4", "msg5"]) - * * yield* Effect.scoped(Effect.gen(function*() { * const subscription = yield* PubSub.subscribe(pubsub) * + * // Publish multiple messages + * yield* PubSub.publishAll(pubsub, ["msg1", "msg2", "msg3", "msg4", "msg5"]) + * * // Take up to 3 messages * const upTo3 = yield* PubSub.takeUpTo(subscription, 3) * console.log("Up to 3:", upTo3) // ["msg1", "msg2", "msg3"] @@ -1399,27 +1569,27 @@ export const takeUpTo: { * }) * ``` * + * @category subscriptions * @since 4.0.0 - * @category subscription */ (max: number): (self: Subscription) => Effect.Effect> /** * Takes up to the specified number of messages from the subscription without suspending. * - * @example + * **Example** (Taking up to a maximum number of messages) + * * ```ts - * import { Effect } from "effect" - * import * as PubSub from "effect/PubSub" + * import { Effect, PubSub } from "effect" * * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(10) * - * // Publish multiple messages - * yield* PubSub.publishAll(pubsub, ["msg1", "msg2", "msg3", "msg4", "msg5"]) - * * yield* Effect.scoped(Effect.gen(function*() { * const subscription = yield* PubSub.subscribe(pubsub) * + * // Publish multiple messages + * yield* PubSub.publishAll(pubsub, ["msg1", "msg2", "msg3", "msg4", "msg5"]) + * * // Take up to 3 messages * const upTo3 = yield* PubSub.takeUpTo(subscription, 3) * console.log("Up to 3:", upTo3) // ["msg1", "msg2", "msg3"] @@ -1435,8 +1605,8 @@ export const takeUpTo: { * }) * ``` * + * @category subscriptions * @since 4.0.0 - * @category subscription */ (self: Subscription, max: number): Effect.Effect> } = dual(2, (self: Subscription, max: number): Effect.Effect> => @@ -1460,7 +1630,8 @@ export const takeUpTo: { * Takes between the specified minimum and maximum number of messages from the subscription. * Will suspend if the minimum number is not immediately available. * - * @example + * **Example** (Taking between a minimum and maximum) + * * ```ts * import { Effect, Fiber, PubSub } from "effect" * @@ -1485,15 +1656,16 @@ export const takeUpTo: { * }) * ``` * + * @category subscriptions * @since 4.0.0 - * @category subscription */ export const takeBetween: { /** * Takes between the specified minimum and maximum number of messages from the subscription. * Will suspend if the minimum number is not immediately available. * - * @example + * **Example** (Taking between a minimum and maximum) + * * ```ts * import { Effect, Fiber, PubSub } from "effect" * @@ -1518,15 +1690,16 @@ export const takeBetween: { * }) * ``` * + * @category subscriptions * @since 4.0.0 - * @category subscription */ (min: number, max: number): (self: Subscription) => Effect.Effect> /** * Takes between the specified minimum and maximum number of messages from the subscription. * Will suspend if the minimum number is not immediately available. * - * @example + * **Example** (Taking between a minimum and maximum) + * * ```ts * import { Effect, Fiber, PubSub } from "effect" * @@ -1551,8 +1724,8 @@ export const takeBetween: { * }) * ``` * + * @category subscriptions * @since 4.0.0 - * @category subscription */ (self: Subscription, min: number, max: number): Effect.Effect> } = dual( @@ -1595,22 +1768,33 @@ const takeRemainderLoop = ( } /** - * Returns the number of messages currently available in the subscription. + * Returns the number of messages currently available in the subscription as an + * `Effect`. + * + * **When to use** + * + * Use when checking a subscription from effectful code and shutdown should + * interrupt the effect. + * + * **Details** + * + * The count includes replay-buffered messages. If the subscription has been + * shut down, the effect interrupts. + * + * **Example** (Checking remaining messages) * - * @example * ```ts - * import { Effect } from "effect" - * import * as PubSub from "effect/PubSub" + * import { Effect, PubSub } from "effect" * * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(10) * - * // Publish some messages - * yield* PubSub.publishAll(pubsub, ["msg1", "msg2", "msg3"]) - * * yield* Effect.scoped(Effect.gen(function*() { * const subscription = yield* PubSub.subscribe(pubsub) * + * // Publish some messages + * yield* PubSub.publishAll(pubsub, ["msg1", "msg2", "msg3"]) + * * // Check how many messages are available * const count = yield* PubSub.remaining(subscription) * console.log("Messages available:", count) // 3 @@ -1624,8 +1808,10 @@ const takeRemainderLoop = ( * }) * ``` * - * @since 4.0.0 + * @see {@link remainingUnsafe} for a synchronous check that reports shutdown as `Option.none()` + * * @category getters + * @since 4.0.0 */ export const remaining = (self: Subscription): Effect.Effect => Effect.suspend(() => @@ -1635,9 +1821,16 @@ export const remaining = (self: Subscription): Effect.Effect => ) /** - * Returns the number of messages currently available in the subscription. + * Synchronously returns the number of messages currently available in the + * subscription, or `Option.none()` when it is shut down. + * + * **When to use** + * + * Use when you need synchronous polling outside a managed workflow and want + * shutdown observed as data instead of interruption. + * + * **Example** (Checking remaining messages synchronously) * - * @example * ```ts * import { PubSub } from "effect" * @@ -1657,8 +1850,10 @@ export const remaining = (self: Subscription): Effect.Effect => * } * ``` * - * @since 4.0.0 + * @see {@link remaining} for the effectful variant that interrupts on shutdown + * * @category getters + * @since 4.0.0 */ export const remainingUnsafe = (self: Subscription): Option.Option => { if (self.shutdownFlag.current) { @@ -2539,14 +2734,29 @@ const ensureCapacity = (capacity: number): void => { // ----------------------------------------------------------------------------- /** - * A strategy that applies back pressure to publishers when the `PubSub` is at - * capacity. This guarantees that all subscribers will receive all messages - * published to the `PubSub` while they are subscribed. However, it creates the - * risk that a slow subscriber will slow down the rate at which messages - * are published and received by other subscribers. + * Represents the back-pressure strategy for bounded `PubSub` values. + * + * **When to use** + * + * Use to preserve every message for current subscribers when a bounded custom + * `PubSub` should make publishers wait for capacity instead of dropping or + * evicting messages. + * + * **Details** + * + * Publishers wait when the `PubSub` is at capacity, so all current subscribers + * can receive every published message. + * + * **Gotchas** + * + * A slow subscriber can slow down publishers and other subscribers. + * + * @see {@link bounded} for creating bounded PubSubs with back pressure by default + * @see {@link DroppingStrategy} for dropping new messages when capacity is full + * @see {@link SlidingStrategy} for evicting old messages when capacity is full * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export class BackPressureStrategy implements PubSub.Strategy { publishers: MutableList.MutableList< @@ -2641,17 +2851,26 @@ export class BackPressureStrategy implements PubSub.Strategy { } /** - * A strategy that drops new messages when the `PubSub` is at capacity. This - * guarantees that a slow subscriber will not slow down the rate at which - * messages are published. However, it creates the risk that a slow - * subscriber will slow down the rate at which messages are received by - * other subscribers and that subscribers may not receive all messages - * published to the `PubSub` while they are subscribed. - * - * @example + * Represents the dropping strategy for bounded `PubSub` values. + * + * **When to use** + * + * Use to keep publishers fast by dropping new messages when the `PubSub` is at + * capacity. + * + * **Details** + * + * A publish that arrives while the `PubSub` is full is dropped instead of + * waiting for capacity. + * + * **Gotchas** + * + * Subscribers may miss messages published while they are subscribed. + * + * **Example** (Using a dropping strategy) + * * ```ts - * import { Effect } from "effect" - * import * as PubSub from "effect/PubSub" + * import { Effect, PubSub } from "effect" * * const program = Effect.gen(function*() { * // Create PubSub with dropping strategy @@ -2663,24 +2882,25 @@ export class BackPressureStrategy implements PubSub.Strategy { * strategy: () => new PubSub.DroppingStrategy() * }) * - * // Fill the PubSub - * const pub1 = yield* PubSub.publish(pubsub, "msg1") // true - * const pub2 = yield* PubSub.publish(pubsub, "msg2") // true - * const pub3 = yield* PubSub.publish(pubsub, "msg3") // false (dropped) - * - * console.log("Publication results:", [pub1, pub2, pub3]) // [true, true, false] - * - * // Subscribers will only see the first two messages * yield* Effect.scoped(Effect.gen(function*() { * const subscription = yield* PubSub.subscribe(pubsub) + * + * // Fill the PubSub + * const pub1 = yield* PubSub.publish(pubsub, "msg1") // true + * const pub2 = yield* PubSub.publish(pubsub, "msg2") // true + * const pub3 = yield* PubSub.publish(pubsub, "msg3") // false (dropped) + * + * console.log("Publication results:", [pub1, pub2, pub3]) // [true, true, false] + * + * // Subscribers will only see the first two messages * const messages = yield* PubSub.takeAll(subscription) * console.log("Received messages:", messages) // ["msg1", "msg2"] * })) * }) * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export class DroppingStrategy implements PubSub.Strategy { get shutdown(): Effect.Effect { @@ -2718,16 +2938,26 @@ export class DroppingStrategy implements PubSub.Strategy { } /** - * A strategy that adds new messages and drops old messages when the `PubSub` is - * at capacity. This guarantees that a slow subscriber will not slow down - * the rate at which messages are published and received by other - * subscribers. However, it creates the risk that a slow subscriber will - * not receive some messages published to the `PubSub` while it is subscribed. + * Represents the sliding strategy for bounded `PubSub` values. + * + * **When to use** + * + * Use to keep the most recent messages when the `PubSub` is at capacity. + * + * **Details** + * + * New messages are accepted by evicting older messages from the bounded + * `PubSub`. + * + * **Gotchas** + * + * Slow subscribers may miss older messages that are evicted before they are + * consumed. + * + * **Example** (Using a sliding strategy) * - * @example * ```ts - * import { Effect } from "effect" - * import * as PubSub from "effect/PubSub" + * import { Effect, PubSub } from "effect" * * const program = Effect.gen(function*() { * // Create PubSub with sliding strategy @@ -2739,23 +2969,24 @@ export class DroppingStrategy implements PubSub.Strategy { * strategy: () => new PubSub.SlidingStrategy() * }) * - * // Publish messages that exceed capacity - * yield* PubSub.publish(pubsub, "msg1") // stored - * yield* PubSub.publish(pubsub, "msg2") // stored - * yield* PubSub.publish(pubsub, "msg3") // "msg1" evicted, "msg3" stored - * yield* PubSub.publish(pubsub, "msg4") // "msg2" evicted, "msg4" stored - * - * // Subscribers will see the most recent messages * yield* Effect.scoped(Effect.gen(function*() { * const subscription = yield* PubSub.subscribe(pubsub) + * + * // Publish messages that exceed capacity + * yield* PubSub.publish(pubsub, "msg1") // stored + * yield* PubSub.publish(pubsub, "msg2") // stored + * yield* PubSub.publish(pubsub, "msg3") // "msg1" evicted, "msg3" stored + * yield* PubSub.publish(pubsub, "msg4") // "msg2" evicted, "msg4" stored + * + * // Subscribers will see the most recent messages * const messages = yield* PubSub.takeAll(subscription) * console.log("Recent messages:", messages) // ["msg3", "msg4"] * })) * }) * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export class SlidingStrategy implements PubSub.Strategy { get shutdown(): Effect.Effect { diff --git a/.opencode/node_modules/effect/src/Pull.ts b/.opencode/node_modules/effect/src/Pull.ts index abf554f026fe83dd2c92f18f453e16d5209baa2e..86043024854b86762e373ef593c6a9cfb9889dc6 100644 --- a/.opencode/node_modules/effect/src/Pull.ts +++ b/.opencode/node_modules/effect/src/Pull.ts @@ -1,4 +1,13 @@ /** + * Models one low-level pull step for stream-like consumers. + * + * A `Pull` is an `Effect` that can produce one `A`, fail with an + * ordinary error `E`, or signal end-of-input with `Cause.Done`. The + * separate done signal lets low-level consumers distinguish normal completion + * from failure. This module includes type extractors and helpers for detecting, + * filtering, catching, converting, and matching done signals separately from + * ordinary failures. + * * @since 4.0.0 */ import * as Cause from "./Cause.ts" @@ -10,8 +19,23 @@ import * as internalEffect from "./internal/effect.ts" import * as Result from "./Result.ts" /** - * @since 4.0.0 + * An effectful pull step that either produces a value, fails with `E`, or + * signals completion with `Cause.Done`. + * + * **When to use** + * + * Use to model one low-level pull step when a consumer repeatedly evaluates an + * effect that may emit a value, fail normally, or signal normal completion + * through `Cause.Done`. + * + * **Details** + * + * `Pull` represents completion in the error channel so low-level stream + * consumers can distinguish ordinary failures from end-of-input and carry a + * leftover value when needed. + * * @category models + * @since 4.0.0 */ export interface Pull extends Effect, R> @@ -20,16 +44,35 @@ export interface Pull /** * Extracts the success type from a Pull type. * - * @since 4.0.0 + * **When to use** + * + * Use to derive the value produced by an existing `Pull` when declaring + * reusable type aliases, low-level stream helpers, or function signatures. + * + * @see {@link Error} for extracting the ordinary failure type + * @see {@link Leftover} for extracting the completion leftover type + * @see {@link Services} for extracting the required services type instead + * * @category type extractors + * @since 4.0.0 */ export type Success

= P extends Effect ? _A : never /** * Extracts the error type from a Pull type, excluding Done errors. * - * @since 4.0.0 + * **When to use** + * + * Use to derive only the ordinary failure type from a `Pull` when declaring + * wrappers or APIs that handle completion separately. + * + * @see {@link Success} for extracting the pulled value type instead + * @see {@link Leftover} for extracting the completion leftover type + * @see {@link Services} for extracting the required services type instead + * @see {@link ExcludeDone} for excluding `Cause.Done` from an error union + * * @category type extractors + * @since 4.0.0 */ export type Error

= P extends Effect ? _E extends Cause.Done ? never : _E : never @@ -37,8 +80,18 @@ export type Error

= P extends Effect ? _E exten /** * Extracts the leftover type from a Pull type. * - * @since 4.0.0 + * **When to use** + * + * Use to derive the completion leftover type from an existing `Pull` when + * declaring reusable type aliases or helper signatures that preserve a pull's + * done value. + * + * @see {@link Success} for extracting the pulled value type instead + * @see {@link Error} for extracting the ordinary failure type, excluding `Cause.Done` + * @see {@link Services} for extracting the required services type instead + * * @category type extractors + * @since 4.0.0 */ export type Leftover

= P extends Effect ? _E extends Cause.Done ? _L : never : never @@ -46,16 +99,33 @@ export type Leftover

= P extends Effect ? _E ex /** * Extracts the service requirements (context) type from a Pull type. * - * @since 4.0.0 + * **When to use** + * + * Use to derive the context requirements of a generic or inferred `Pull` + * without restating its `R` type parameter. + * + * @see {@link Success} for extracting the pulled value type instead + * @see {@link Error} for extracting the ordinary failure type + * @see {@link Leftover} for extracting the completion leftover type + * * @category type extractors + * @since 4.0.0 */ export type Services

= P extends Effect ? _R : never /** - * Excludes done errors from an error type union. + * Excludes `Cause.Done` completion signals from an error type union. + * + * **When to use** + * + * Use to describe the ordinary error type that remains after `Cause.Done` + * completion signals have been handled or filtered out of an error union. + * + * @see {@link Error} for extracting ordinary failures from a `Pull` + * @see {@link Leftover} for extracting the completion leftover type * - * @since 4.0.0 * @category type extractors + * @since 4.0.0 */ export type ExcludeDone = Exclude> @@ -64,8 +134,25 @@ export type ExcludeDone = Exclude> // ----------------------------------------------------------------------------- /** - * @since 4.0.0 + * Handles `Cause.Done` failures in an effect while leaving ordinary failures + * in the error channel. + * + * **When to use** + * + * Use to recover from a `Cause.Done` completion signal in an effect, such as + * turning a pull leftover value into a successful recovery effect while + * preserving ordinary failures. + * + * **Details** + * + * The handler receives the done leftover value and may recover with a new + * effect. Non-done errors are preserved. + * + * @see {@link matchEffect} for handling success, ordinary failure, and done outcomes explicitly + * @see {@link filterDoneLeftover} for extracting a done leftover from an existing `Cause` + * * @category Done + * @since 4.0.0 */ export const catchDone: { // ----------------------------------------------------------------------------- @@ -73,8 +160,25 @@ export const catchDone: { // ----------------------------------------------------------------------------- /** - * @since 4.0.0 + * Handles `Cause.Done` failures in an effect while leaving ordinary failures + * in the error channel. + * + * **When to use** + * + * Use to recover from a `Cause.Done` completion signal in an effect, such as + * turning a pull leftover value into a successful recovery effect while + * preserving ordinary failures. + * + * **Details** + * + * The handler receives the done leftover value and may recover with a new + * effect. Non-done errors are preserved. + * + * @see {@link matchEffect} for handling success, ordinary failure, and done outcomes explicitly + * @see {@link filterDoneLeftover} for extracting a done leftover from an existing `Cause` + * * @category Done + * @since 4.0.0 */ (f: (leftover: Cause.Done.Extract) => Effect): ( self: Effect @@ -84,8 +188,25 @@ export const catchDone: { // ----------------------------------------------------------------------------- /** - * @since 4.0.0 + * Handles `Cause.Done` failures in an effect while leaving ordinary failures + * in the error channel. + * + * **When to use** + * + * Use to recover from a `Cause.Done` completion signal in an effect, such as + * turning a pull leftover value into a successful recovery effect while + * preserving ordinary failures. + * + * **Details** + * + * The handler receives the done leftover value and may recover with a new + * effect. Non-done errors are preserved. + * + * @see {@link matchEffect} for handling success, ordinary failure, and done outcomes explicitly + * @see {@link filterDoneLeftover} for extracting a done leftover from an existing `Cause` + * * @category Done + * @since 4.0.0 */ ( self: Effect, @@ -98,28 +219,56 @@ export const catchDone: { internalEffect.catchCauseFilter(effect, filterDoneLeftover as any, (l: any) => f(l)) as any) /** - * Checks if a Cause contains any done errors. + * Checks whether a Cause contains any done errors. + * + * **When to use** + * + * Use when you need to test whether a pull failure cause represents normal + * completion and only need a boolean result. + * + * @see {@link isDoneFailure} for checking a single `Cause.Reason` + * @see {@link filterDone} for extracting the `Cause.Done` value from a `Cause` + * @see {@link filterNoDone} for selecting causes with no done failures * - * @since 4.0.0 * @category Done + * @since 4.0.0 */ export const isDoneCause = (cause: Cause.Cause): boolean => cause.reasons.some(isDoneFailure) /** - * Checks if a Cause failure is a done error. + * Checks whether a `Cause.Reason` is a `Fail` reason whose error is a + * `Cause.Done` signal. + * + * **When to use** + * + * Use when you need to identify done completion reasons while traversing + * `cause.reasons`, before handling ordinary failures. + * + * @see {@link isDoneCause} for checking an entire `Cause` for any done reason + * @see {@link filterDone} for extracting the `Cause.Done` value from a `Cause` * - * @since 4.0.0 * @category Done + * @since 4.0.0 */ export const isDoneFailure = ( failure: Cause.Reason ): failure is Cause.Fail> => failure._tag === "Fail" && Cause.isDone(failure.error) /** - * Filters a Cause to extract only halt errors. + * Finds a `Cause.Done` failure in a `Cause`. + * + * **When to use** + * + * Use to separate `Cause.Done` completion from ordinary causes while preserving + * the typed done value. + * + * **Details** + * + * Returns a successful `Result` with the `Cause.Done` value when one is + * present, otherwise returns a failed `Result` containing the non-done cause. * - * @since 4.0.0 * @category Done + * @since 4.0.0 */ export const filterDone: ( input: Cause.Cause @@ -130,10 +279,24 @@ export const filterDone: ( ) as any /** - * Filters a Cause to extract only halt errors. + * Finds a `Cause.Done` failure in a cause whose done value is not used. + * + * **When to use** + * + * Use to detect `Cause.Done` completion in a `Cause` when the completion value + * is not part of the downstream logic. + * + * **Details** + * + * Returns a successful `Result` with the done marker when present, otherwise + * returns a failed `Result` with the non-done cause. + * + * @see {@link filterDone} for preserving the typed `Cause.Done` value when the done payload matters + * @see {@link filterDoneLeftover} for extracting only the done leftover value + * @see {@link filterNoDone} for the inverse filter that succeeds only when no done failure is present * - * @since 4.0.0 * @category Done + * @since 4.0.0 */ export const filterDoneVoid: ( input: Cause.Cause @@ -143,8 +306,23 @@ export const filterDoneVoid: ( ) as any /** - * @since 4.0.0 + * Keeps a `Cause` only when it contains no `Cause.Done` failures. + * + * **When to use** + * + * Use to select ordinary failure causes for handling while leaving `Cause.Done` + * completion causes outside that handler. + * + * **Details** + * + * Returns a successful `Result` with the cause when every failure is non-done; + * otherwise returns a failed `Result` with the original cause. + * + * @see {@link filterDone} for the inverse typed done filter + * @see {@link filterDoneVoid} for done detection when the payload is not needed + * * @category Done + * @since 4.0.0 */ export const filterNoDone: ( input: Cause.Cause @@ -158,8 +336,13 @@ export const filterNoDone: ( /** * Filters a Cause to extract the leftover value from done errors. * - * @since 4.0.0 + * **When to use** + * + * Use to extract only the leftover value carried by a `Cause.Done` completion + * signal. + * * @category Done + * @since 4.0.0 */ export const filterDoneLeftover: ( cause: Cause.Cause @@ -169,10 +352,25 @@ export const filterDoneLeftover: ( ) as any /** - * Converts a Cause into an Exit, extracting halt leftovers as success values. + * Converts a `Cause` into an `Exit`, treating `Cause.Done` as successful + * completion. + * + * **When to use** + * + * Use to produce an `Exit` for finalizing a low-level pull workflow when a + * `Cause.Done` signal should be treated as success and any remaining cause + * should fail. + * + * **Details** + * + * If the cause contains a done value, that leftover becomes the successful + * value. Otherwise the non-done cause becomes the failure cause. + * + * @see {@link filterDone} for extracting the done signal without converting the cause to an `Exit` + * @see {@link matchEffect} for handling `Pull` success, failure, and done outcomes directly * - * @since 4.0.0 * @category Done + * @since 4.0.0 */ export const doneExitFromCause = (cause: Cause.Cause): Exit.Exit, ExcludeDone> => { const halt = filterDone(cause) @@ -182,7 +380,12 @@ export const doneExitFromCause = (cause: Cause.Cause): Exit.Exit(cause: Cause.Cause): Exit.Exit( options: { @@ -228,7 +436,12 @@ export const matchEffect: { /** * Pattern matches on a Pull, handling success, failure, and done cases. * - * @example + * **When to use** + * + * Use to handle all three `Pull` outcomes with effectful handlers. + * + * **Example** (Matching Pull outcomes) + * * ```ts * import { Cause, Effect, Pull } from "effect" * @@ -241,8 +454,8 @@ export const matchEffect: { * }) * ``` * - * @since 4.0.0 * @category pattern matching + * @since 4.0.0 */ ( self: Pull, diff --git a/.opencode/node_modules/effect/src/Queue.ts b/.opencode/node_modules/effect/src/Queue.ts index 4cccce4147f2924a8b1dec8f8e57e2db1d5dea54..30248f7977e2b7d50e38275a184adff05122d288 100644 --- a/.opencode/node_modules/effect/src/Queue.ts +++ b/.opencode/node_modules/effect/src/Queue.ts @@ -1,4 +1,11 @@ /** + * Passes values asynchronously between fibers. + * + * A `Queue` accepts values, hands each value to one consumer in offer + * order, and can complete, fail, interrupt, or shut down. Queues can be bounded + * or unbounded, and bounded queues can suspend, drop, or slide values when + * producers are faster than consumers. + * * @since 3.8.0 */ import * as Arr from "./Array.ts" @@ -24,8 +31,16 @@ const DequeueTypeId = "~effect/Queue/Dequeue" /** * Type guard to check if a value is a Queue. * - * @since 3.8.0 - * @category Guards + * **When to use** + * + * Use to narrow an unknown value to a full `Queue` before passing it to APIs + * that need both offering and taking capabilities. + * + * @see {@link isEnqueue} for checking values that only need write access + * @see {@link isDequeue} for checking values that only need read access + * + * @category guards + * @since 2.0.0 */ export const isQueue = ( u: unknown @@ -34,8 +49,22 @@ export const isQueue = ( /** * Type guard to check if a value is an Enqueue. * - * @since 4.0.0 - * @category Guards + * **When to use** + * + * Use to narrow an unknown value before calling queue operations that require + * write-side access. + * + * **Gotchas** + * + * A full `Queue` also satisfies this guard because every queue includes the + * enqueue side. + * + * @see {@link isQueue} for checking for a full read-write queue handle + * @see {@link isDequeue} for checking for the read side of a queue + * @see {@link asEnqueue} for narrowing an existing `Queue` to its write-only interface + * + * @category guards + * @since 2.0.0 */ export const isEnqueue = ( u: unknown @@ -44,44 +73,83 @@ export const isEnqueue = ( /** * Type guard to check if a value is a Dequeue. * - * @since 4.0.0 - * @category Guards + * **When to use** + * + * Use to narrow an unknown value before passing it to read-side queue + * operations. + * + * @see {@link Dequeue} for the read-side queue handle checked by this guard + * @see {@link isQueue} for checking for a full read-write queue handle + * @see {@link isEnqueue} for checking for the write side of a queue + * @see {@link asDequeue} for narrowing an existing `Queue` to its read-only interface + * + * @category guards + * @since 2.0.0 */ export const isDequeue = ( u: unknown ): u is Dequeue => hasProperty(u, DequeueTypeId) /** - * Converts a Queue to an Enqueue (write-only interface). + * Converts a `Queue` to its write-only `Enqueue` interface. + * + * **When to use** + * + * Use to expose only the producer side of a `Queue` to code that should offer + * values or signal queue lifecycle. + * + * **Gotchas** * + * This is a type-level capability restriction. It returns the same queue + * object, so it does not hide read operations at runtime. + * + * @see {@link asDequeue} for exposing only the read side of a `Queue` + * @see {@link Enqueue} for the write-only queue handle returned by this conversion + * + * @category converting * @since 4.0.0 - * @category Conversions */ export const asEnqueue = (self: Queue): Enqueue => self /** - * Convert a Queue to a Dequeue, allowing only read operations. + * Narrows a `Queue` to a `Dequeue`, exposing the consumer side of the queue. + * + * **When to use** + * + * Use to pass a queue to code that should consume values while keeping + * producer-side operations out of that code's TypeScript type. + * + * **Gotchas** + * + * This is a type-level narrowing operation. It returns the same queue object + * and does not create a runtime wrapper. + * + * @see {@link asEnqueue} for narrowing a queue to its producer side + * @see {@link Dequeue} for the consumer-side queue handle returned by this function * + * @category converting * @since 4.0.0 - * @category Conversions */ export const asDequeue: (self: Queue) => Dequeue = identity /** * An `Enqueue` is a queue that can be offered to. * + * **Details** + * * This interface represents the write-only part of a Queue, allowing you to offer * elements to the queue but not take elements from it. * - * @example + * **Example** (Offering through enqueue handles) + * * ```ts * import { Effect, Queue } from "effect" * * // Function that only needs write access to a queue * const producer = (enqueue: Queue.Enqueue) => * Effect.gen(function*() { - * yield* Queue.offer(enqueue as Queue.Queue, "hello") - * yield* Queue.offerAll(enqueue as Queue.Queue, ["world", "!"]) + * yield* Queue.offer(enqueue, "hello") + * yield* Queue.offerAll(enqueue, ["world", "!"]) * }) * * const program = Effect.gen(function*() { @@ -90,8 +158,8 @@ export const asDequeue: (self: Queue) => Dequeue = identity * }) * ``` * - * @since 4.0.0 - * @category Models + * @category models + * @since 2.0.0 */ export interface Enqueue extends Inspectable { readonly [EnqueueTypeId]: Enqueue.Variance @@ -104,15 +172,23 @@ export interface Enqueue extends Inspectable { } /** - * @since 4.0.0 - * @category Models + * Companion namespace containing type-level metadata for the `Enqueue` + * write-only queue interface. + * + * @since 2.0.0 */ export declare namespace Enqueue { /** - * Variance interface for Enqueue types, defining the type parameter constraints. + * Type-level variance marker for `Enqueue`. * + * **Details** + * + * `Enqueue` is contravariant in both its offered value type `A` and failure + * type `E`, because values and failures flow into the queue through this + * handle. + * + * @category models * @since 4.0.0 - * @category Models */ export interface Variance { _A: Types.Contravariant @@ -123,12 +199,15 @@ export declare namespace Enqueue { /** * A `Dequeue` is a queue that can be taken from. * + * **Details** + * * This interface represents the read-only part of a Queue, allowing you to take * elements from the queue but not offer elements to it. * - * @example + * **Example** (Taking through dequeue handles) + * * ```ts - * import { Cause, Effect, Queue } from "effect" + * import { Effect, Queue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* Queue.bounded(10) @@ -145,8 +224,8 @@ export declare namespace Enqueue { * }) * ``` * - * @since 3.8.0 - * @category Models + * @category models + * @since 2.0.0 */ export interface Dequeue extends Inspectable { readonly [DequeueTypeId]: Dequeue.Variance @@ -159,15 +238,22 @@ export interface Dequeue extends Inspectable { } /** - * @since 4.0.0 - * @category Models + * Companion namespace containing type-level metadata for the `Dequeue` + * read-only queue interface. + * + * @since 2.0.0 */ export declare namespace Dequeue { /** - * Variance interface for Dequeue types, defining the type parameter constraints. + * Type-level variance marker for `Dequeue`. * - * @since 3.8.0 - * @category Models + * **Details** + * + * `Dequeue` is covariant in both the taken value type `A` and failure type + * `E`, because values and failures are observed through this handle. + * + * @category models + * @since 4.0.0 */ export interface Variance { _A: Types.Covariant @@ -178,17 +264,14 @@ export declare namespace Dequeue { /** * A `Queue` is an asynchronous queue that can be offered to and taken from. * - * It also supports signaling that it is done or failed. - * - * **Previously Known As** + * **Details** * - * This API replaces the following from Effect 3.x: + * It also supports signaling that it is done or failed. * - * - `Mailbox` + * **Example** (Offering and taking queue values) * - * @example * ```ts - * import { Cause, Effect, Queue } from "effect" + * import { Effect, Queue } from "effect" * * const program = Effect.gen(function*() { * // Create a bounded queue @@ -207,23 +290,30 @@ export declare namespace Dequeue { * }) * ``` * - * @since 3.8.0 - * @category Models + * @category models + * @since 2.0.0 */ export interface Queue extends Enqueue, Dequeue { readonly [TypeId]: Queue.Variance } /** - * @since 3.8.0 - * @category Models + * Companion namespace containing type-level metadata and low-level state types + * for `Queue`. + * + * @since 2.0.0 */ export declare namespace Queue { /** - * Variance interface for Queue types, defining the type parameter constraints. + * Type-level variance marker for `Queue`. + * + * **Details** * - * @since 3.8.0 - * @category Models + * A full `Queue` is invariant in both `A` and `E` because the same handle can + * both produce and consume values and failures. + * + * @category models + * @since 4.0.0 */ export interface Variance { _A: Types.Invariant @@ -231,10 +321,17 @@ export declare namespace Queue { } /** - * Represents the internal state of a Queue. + * Tagged state of a `Queue`. + * + * **Details** + * + * `Open` queues can accept offers and takers, `Closing` queues are + * completing with a stored failure exit, and `Done` queues have finished. + * This is low-level metadata exposed by the queue model; most users should + * inspect queues through the public operations. * + * @category models * @since 4.0.0 - * @category Models */ export type State = | { @@ -256,10 +353,16 @@ export declare namespace Queue { } /** - * Represents an entry in the queue's offer buffer. + * Represents a suspended offer waiting to be admitted to a bounded queue. * + * **Details** + * + * An entry is either a single message or a batch with an offset into its + * remaining messages, plus a resume callback that completes the suspended + * offer when the queue can accept more input. + * + * @category models * @since 4.0.0 - * @category Models */ export type OfferEntry = | { @@ -294,22 +397,19 @@ const QueueProto = { } /** - * A `Queue` is an asynchronous queue that can be offered to and taken from. + * Creates a `Queue` with optional capacity and overflow strategy. * - * It also supports signaling that it is done or failed. + * **Details** * - * **Previously Known As** + * By default the queue is unbounded and uses the `"suspend"` strategy. Provide + * `capacity` for a bounded queue and choose `"suspend"`, `"dropping"`, or + * `"sliding"` to control what happens when the queue is full. The returned + * queue can be offered to, taken from, failed, ended, interrupted, or shut down. * - * This API replaces the following from Effect 3.x: + * **Example** (Creating queues) * - * - `Mailbox.make` - * - * @since 3.8.0 - * @category Constructors - * @example * ```ts * import { Cause, Effect, Queue } from "effect" - * import * as assert from "node:assert" * * Effect.gen(function*() { * const queue = yield* Queue.make() @@ -321,17 +421,22 @@ const QueueProto = { * * // take messages from the queue * const messages = yield* Queue.takeAll(queue) - * assert.deepStrictEqual(messages, [1, 2, 3, 4, 5]) + * console.log(messages) // [1, 2, 3, 4, 5] * * // signal that the queue is done * yield* Queue.end(queue) - * const done = yield* Effect.flip(Queue.takeAll(queue)) - * assert.deepStrictEqual(done, Cause.Done) + * const done = yield* Effect.flip(Queue.take(queue)) + * console.log(Cause.isDone(done)) // true * - * // signal that the queue has failed - * yield* Queue.fail(queue, "boom") + * // signal that another queue has failed + * const failedQueue = yield* Queue.make() + * const failed = yield* Queue.fail(failedQueue, "boom") + * console.log(failed) // true * }) * ``` + * + * @category constructors + * @since 4.0.0 */ export const make = ( options?: { @@ -358,12 +463,15 @@ export const make = ( /** * Creates a bounded queue with the specified capacity that uses backpressure strategy. * + * **Details** + * * When the queue reaches capacity, producers will be suspended until space becomes available. * This ensures all messages are processed but may slow down producers. * - * @example + * **Example** (Creating bounded queues) + * * ```ts - * import { Cause, Effect, Queue } from "effect" + * import { Effect, Queue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* Queue.bounded(5) @@ -377,8 +485,8 @@ export const make = ( * }) * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const bounded = (capacity: number): Effect> => make({ capacity }) @@ -386,12 +494,15 @@ export const bounded = (capacity: number): Effect> => * Creates a bounded queue with sliding strategy. When the queue reaches capacity, * new elements are added and the oldest elements are dropped. * - * This strategy prevents producers from being blocked but may result in message loss. - * Useful when you want to maintain a rolling window of the most recent messages. + * **When to use** + * + * Use when you need producer offers not to block and can accept dropping the + * oldest messages, such as when maintaining a rolling window of recent values. + * + * **Example** (Creating sliding queues) * - * @example * ```ts - * import { Cause, Effect, Queue } from "effect" + * import { Effect, Queue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* Queue.sliding(3) @@ -409,8 +520,8 @@ export const bounded = (capacity: number): Effect> => * }) * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const sliding = (capacity: number): Effect> => make({ capacity, strategy: "sliding" }) @@ -418,12 +529,15 @@ export const sliding = (capacity: number): Effect> => * Creates a bounded queue with dropping strategy. When the queue reaches capacity, * new elements are dropped and the offer operation returns false. * - * This strategy prevents producers from being blocked and preserves existing messages, - * but new messages may be lost when the queue is full. + * **When to use** + * + * Use when you need producer offers not to block while preserving existing + * queued messages, even if new messages may be dropped when the queue is full. + * + * **Example** (Creating dropping queues) * - * @example * ```ts - * import { Cause, Effect, Queue } from "effect" + * import { Effect, Queue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* Queue.dropping(2) @@ -442,8 +556,8 @@ export const sliding = (capacity: number): Effect> => * }) * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const dropping = (capacity: number): Effect> => make({ capacity, strategy: "dropping" }) @@ -451,13 +565,15 @@ export const dropping = (capacity: number): Effect> => /** * Creates an unbounded queue that can grow to any size without blocking producers. * - * Unlike bounded queues, unbounded queues never apply backpressure - producers - * can always add messages successfully. This is useful when you want to prioritize - * producer throughput over memory usage control. + * **When to use** + * + * Use when you need producers to add messages without backpressure and accept + * unbounded memory growth. + * + * **Example** (Creating unbounded queues) * - * @example * ```ts - * import { Cause, Effect, Queue } from "effect" + * import { Effect, Queue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* Queue.unbounded() @@ -469,7 +585,7 @@ export const dropping = (capacity: number): Effect> => * * // Check current size * const size = yield* Queue.size(queue) - * console.log(size) // Some(5) + * console.log(size) // 5 * * // Take all messages * const messages = yield* Queue.takeAll(queue) @@ -477,21 +593,24 @@ export const dropping = (capacity: number): Effect> => * }) * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const unbounded = (): Effect> => make() /** - * Add a message to the queue. Returns `false` if the queue is done. + * Adds a message to the queue. Returns `false` if the queue is done. + * + * **Details** * * For bounded queues, this operation may suspend if the queue is at capacity, * depending on the backpressure strategy. For dropping/sliding queues, it may * return false or succeed immediately by dropping/sliding existing messages. * - * @example + * **Example** (Offering a value) + * * ```ts - * import { Cause, Effect, Queue } from "effect" + * import { Effect, Queue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* Queue.bounded(3) @@ -508,7 +627,7 @@ export const unbounded = (): Effect> => make() * ``` * * @category Offering - * @since 4.0.0 + * @since 2.0.0 */ export const offer = (self: Enqueue, message: Types.NoInfer): Effect => internalEffect.suspend(() => { @@ -537,12 +656,20 @@ export const offer = (self: Enqueue, message: Types.NoInfer): Eff }) /** - * Add a message to the queue synchronously. Returns `false` if the queue is done. + * Adds a message to the queue synchronously. Returns `false` if the queue is done. + * + * **When to use** + * + * Use when you are already in synchronous queue internals or a performance + * boundary where wrapping the mutation in `Effect` is intentionally avoided. + * + * **Gotchas** * * This is an unsafe operation that directly modifies the queue without Effect wrapping. * Use this only when you're certain about the synchronous nature of the operation. * - * @example + * **Example** (Offering a value synchronously) + * * ```ts * import { Cause, Effect, Queue } from "effect" * @@ -585,28 +712,36 @@ export const offerUnsafe = (self: Enqueue, message: Types.NoInfer } /** - * Add multiple messages to the queue. Returns the remaining messages that + * Adds multiple messages to the queue. Returns the remaining messages that * were not added. * + * **When to use** + * + * Use when producers can submit a batch at once and need to know which messages + * did not fit under the queue's capacity strategy. + * + * **Details** + * * For bounded queues, this operation may suspend if the queue doesn't have * enough capacity. The operation returns an array of messages that couldn't * be added (empty array means all messages were successfully added). * - * @example + * **Example** (Offering multiple values) + * * ```ts - * import { Cause, Effect, Queue } from "effect" + * import { Effect, Queue } from "effect" * * const program = Effect.gen(function*() { - * const queue = yield* Queue.bounded(3) + * const queue = yield* Queue.dropping(3) * - * // Try to add more messages than capacity + * // Try to add more messages than capacity without suspending * const remaining1 = yield* Queue.offerAll(queue, [1, 2, 3, 4, 5]) * console.log(remaining1) // [4, 5] - couldn't fit the last 2 * }) * ``` * * @category Offering - * @since 4.0.0 + * @since 2.0.0 */ export const offerAll = (self: Enqueue, messages: Iterable): Effect> => internalEffect.suspend(() => { @@ -623,12 +758,20 @@ export const offerAll = (self: Enqueue, messages: Iterable): Effe }) /** - * Add multiple messages to the queue synchronously. Returns the remaining messages that + * Adds multiple messages to the queue synchronously. Returns the remaining messages that * were not added. * + * **When to use** + * + * Use when queue internals or a performance boundary need a synchronous batch + * offer and can handle any messages that do not fit. + * + * **Gotchas** + * * This is an unsafe operation that directly modifies the queue without Effect wrapping. * - * @example + * **Example** (Offering multiple values synchronously) + * * ```ts * import { Cause, Effect, Queue } from "effect" * @@ -684,112 +827,107 @@ export const offerAllUnsafe = (self: Enqueue, messages: Iterable) } /** - * Fail the queue with an error. If the queue is already done, `false` is + * Fails the queue with an error. If the queue is already done, `false` is * returned. * - * @example + * **Example** (Failing queues with an error) + * * ```ts - * import { Cause, Effect, Queue } from "effect" + * import { Effect, Queue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* Queue.bounded(10) * - * // Add some messages - * yield* Queue.offer(queue, 1) - * yield* Queue.offer(queue, 2) - * * // Fail the queue with an error * const failed = yield* Queue.fail(queue, "Something went wrong") * console.log(failed) // true * - * // Subsequent operations will reflect the failure - * // Taking from failed queue will fail with the error + * // Taking from the failed queue fails with the error + * const error = yield* Effect.flip(Queue.take(queue)) + * console.log(error) // "Something went wrong" * }) * ``` * - * @category Completion + * @category completion * @since 4.0.0 */ export const fail = (self: Enqueue, error: E) => failCause(self, core.causeFail(error)) /** - * Fail the queue with a cause. If the queue is already done, `false` is + * Fails the queue with a cause. If the queue is already done, `false` is * returned. * - * @example + * **Example** (Failing queues with a cause) + * * ```ts * import { Cause, Effect, Queue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* Queue.bounded(10) * - * // Add some messages - * yield* Queue.offer(queue, 1) - * * // Create a cause and fail the queue * const cause = Cause.fail("Queue processing failed") * const failed = yield* Queue.failCause(queue, cause) * console.log(failed) // true * - * // The queue is now in failed state with the specified cause + * // The queue is now done with the specified failure cause + * console.log(queue.state._tag) // "Done" * }) * ``` * - * @category Completion + * @category completion * @since 4.0.0 */ export const failCause: { /** - * Fail the queue with a cause. If the queue is already done, `false` is + * Fails the queue with a cause. If the queue is already done, `false` is * returned. * - * @example + * **Example** (Failing queues with a cause) + * * ```ts * import { Cause, Effect, Queue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* Queue.bounded(10) * - * // Add some messages - * yield* Queue.offer(queue, 1) - * * // Create a cause and fail the queue * const cause = Cause.fail("Queue processing failed") * const failed = yield* Queue.failCause(queue, cause) * console.log(failed) // true * - * // The queue is now in failed state with the specified cause + * // The queue is now done with the specified failure cause + * console.log(queue.state._tag) // "Done" * }) * ``` * - * @category Completion + * @category completion * @since 4.0.0 */ (cause: Cause): (self: Enqueue) => Effect /** - * Fail the queue with a cause. If the queue is already done, `false` is + * Fails the queue with a cause. If the queue is already done, `false` is * returned. * - * @example + * **Example** (Failing queues with a cause) + * * ```ts * import { Cause, Effect, Queue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* Queue.bounded(10) * - * // Add some messages - * yield* Queue.offer(queue, 1) - * * // Create a cause and fail the queue * const cause = Cause.fail("Queue processing failed") * const failed = yield* Queue.failCause(queue, cause) * console.log(failed) // true * - * // The queue is now in failed state with the specified cause + * // The queue is now done with the specified failure cause + * console.log(queue.state._tag) // "Done" * }) * ``` * - * @category Completion + * @category completion * @since 4.0.0 */ (self: Enqueue, cause: Cause): Effect @@ -800,33 +938,37 @@ export const failCause: { ) /** - * Fail the queue with a cause synchronously. If the queue is already done, `false` is + * Fails the queue with a cause synchronously. If the queue is already done, `false` is * returned. * + * **When to use** + * + * Use when queue completion must be driven from synchronous internals while + * preserving the full failure `Cause`. + * + * **Gotchas** + * * This is an unsafe operation that directly modifies the queue without Effect wrapping. * - * @example + * **Example** (Failing queues with a cause synchronously) + * * ```ts - * import { Effect, Cause } from "effect" - * import { Queue } from "effect" + * import { Cause, Effect, Queue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* Queue.bounded(10) * - * // Add some messages - * Queue.offerUnsafe(queue, 1) - * * // Create a cause and fail the queue synchronously * const cause = Cause.fail("Processing error") * const failed = Queue.failCauseUnsafe(queue, cause) * console.log(failed) // true * - * // The queue is now in failed state + * // The queue is now done with the specified failure cause * console.log(queue.state._tag) // "Done" * }) * ``` * - * @category Completion + * @category completion * @since 4.0.0 */ export const failCauseUnsafe = (self: Enqueue, cause: Cause): boolean => { @@ -847,10 +989,19 @@ export const failCauseUnsafe = (self: Enqueue, cause: Cause): boo } /** - * Signal that the queue is complete. If the queue is already done, `false` is - * returned. + * Signals queue completion. + * + * **When to use** + * + * Use to stop accepting new offers while allowing already queued messages to be + * consumed. + * + * **Details** + * + * Returns `false` if the queue is already done. + * + * **Example** (Ending queues) * - * @example * ```ts * import { Cause, Effect, Queue } from "effect" * @@ -875,18 +1026,29 @@ export const failCauseUnsafe = (self: Enqueue, cause: Cause): boo * }) * ``` * - * @category Completion + * @category completion * @since 4.0.0 */ export const end = (self: Enqueue): Effect => failCause(self, core.causeFail(core.Done())) /** - * Signal that the queue is complete synchronously. If the queue is already done, `false` is - * returned. + * Signals queue completion synchronously. + * + * **When to use** + * + * Use when implementing low-level queue integrations that must complete a queue + * without wrapping the operation in `Effect`. + * + * **Details** + * + * Returns `false` if the queue is already done. + * + * **Gotchas** * * This is an unsafe operation that directly modifies the queue without Effect wrapping. * - * @example + * **Example** (Ending queues synchronously) + * * ```ts * import { Cause, Effect, Queue } from "effect" * @@ -902,12 +1064,18 @@ export const end = (self: Enqueue): Effect => failCa * const ended = Queue.endUnsafe(queue) * console.log(ended) // true * - * // The queue is now done + * // Existing messages can still be consumed while the queue is closing + * console.log(queue.state._tag) // "Closing" + * + * Queue.takeUnsafe(queue) + * Queue.takeUnsafe(queue) + * + * // After buffered messages are consumed, the queue is done * console.log(queue.state._tag) // "Done" * }) * ``` * - * @category Completion + * @category completion * @since 4.0.0 */ export const endUnsafe = (self: Enqueue) => failCauseUnsafe(self, core.causeFail(core.Done())) @@ -915,10 +1083,13 @@ export const endUnsafe = (self: Enqueue) => failCauseUnsafe(s /** * Interrupts the queue gracefully, transitioning it to a closing state. * + * **Details** + * * This operation stops accepting new offers but allows existing messages to be consumed. * Once all messages are drained, the queue transitions to the Done state with an interrupt cause. * - * @example + * **Example** (Interrupting queues gracefully) + * * ```ts * import { Cause, Effect, Queue } from "effect" * @@ -950,19 +1121,25 @@ export const endUnsafe = (self: Enqueue) => failCauseUnsafe(s * }) * ``` * - * @category Completion + * @category completion * @since 4.0.0 */ export const interrupt = (self: Enqueue): Effect => core.withFiber((fiber) => failCause(self, internalEffect.causeInterrupt(fiber.id))) /** - * Shutdown the queue, canceling any pending operations. - * If the queue is already done, `false` is returned. + * Shuts down the queue immediately, discarding buffered messages and resuming + * pending operations. + * + * **Details** + * + * The operation is idempotent and returns `true`, including when the queue has + * already been shut down or completed. + * + * **Example** (Shutting down queues) * - * @example * ```ts - * import { Cause, Effect, Queue } from "effect" + * import { Effect, Queue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* Queue.bounded(2) @@ -971,10 +1148,7 @@ export const interrupt = (self: Enqueue): Effect => * yield* Queue.offer(queue, 1) * yield* Queue.offer(queue, 2) * - * // Try to add more than capacity (will be pending) - * const pendingOffer = Queue.offer(queue, 3) - * - * // Shutdown cancels pending operations and clears the queue + * // Shutdown clears buffered messages and prevents further offers * const wasShutdown = yield* Queue.shutdown(queue) * console.log(wasShutdown) // true * @@ -984,8 +1158,8 @@ export const interrupt = (self: Enqueue): Effect => * }) * ``` * - * @category Completion - * @since 4.0.0 + * @category completion + * @since 2.0.0 */ export const shutdown = (self: Enqueue): Effect => internalEffect.sync(() => { @@ -1009,10 +1183,15 @@ export const shutdown = (self: Enqueue): Effect => }) /** - * Take all messages from the queue, returning an empty array if the queue - * is empty or done. + * Takes and returns all currently buffered messages without waiting for more. + * + * **Details** + * + * Returns an empty array when the queue is empty or has completed normally. If + * the queue has failed, the effect fails with the queue's error. + * + * **Example** (Clearing queued values) * - * @example * ```ts * import { Cause, Effect, Queue } from "effect" * @@ -1036,7 +1215,7 @@ export const shutdown = (self: Enqueue): Effect => * }) * ``` * - * @category Taking + * @category taking * @since 4.0.0 */ export const clear = (self: Dequeue): Effect, Pull.ExcludeDone> => @@ -1053,12 +1232,21 @@ export const clear = (self: Dequeue): Effect, Pull.ExcludeD }) /** - * Take all messages from the queue, or wait for messages to be available. + * Takes all currently available messages, waiting until at least one message + * is available when the queue is empty. + * + * **When to use** + * + * Use when consumers should process the next non-empty batch of buffered + * messages instead of repeatedly taking one message at a time. * - * If the queue is done, the `done` flag will be `true`. If the queue - * fails, the Effect will fail with the error. + * **Details** + * + * Returns a non-empty array. If the queue completes or fails before a message + * can be taken, the effect fails with the queue's terminal error. + * + * **Example** (Taking all available values) * - * @example * ```ts * import { Cause, Effect, Queue } from "effect" * @@ -1074,16 +1262,17 @@ export const clear = (self: Dequeue): Effect, Pull.ExcludeD * }) * ``` * - * @category Taking - * @since 4.0.0 + * @category taking + * @since 2.0.0 */ export const takeAll = (self: Dequeue): Effect, E> => takeBetween(self, 1, Number.POSITIVE_INFINITY) as any /** - * Take all messages from the queue, until the queue has errored or is done. + * Takes all messages from the queue, until the queue has errored or is done. + * + * **Example** (Collecting values until completion) * - * @example * ```ts * import { Cause, Effect, Queue } from "effect" * @@ -1101,7 +1290,7 @@ export const takeAll = (self: Dequeue): Effect, * }) * ``` * - * @category Taking + * @category taking * @since 4.0.0 */ export const collect = (self: Dequeue): Effect, Pull.ExcludeDone> => @@ -1125,13 +1314,17 @@ export const collect = (self: Dequeue): Effect, Pull }) as any /** - * Take a specified number of messages from the queue. It will only take - * up to the capacity of the queue. + * Takes up to `n` messages from the queue. + * + * **Details** + * + * The operation may wait until enough messages are available to satisfy the + * queue's batching rules. If `n` is less than or equal to zero, it succeeds + * with an empty array. If the queue completes or fails before messages can be + * taken, the effect fails with the queue's terminal error. * - * If the queue is done, the `done` flag will be `true`. If the queue - * fails, the Effect will fail with the error. + * **Example** (Taking a fixed number of values) * - * @example * ```ts * import { Cause, Effect, Queue } from "effect" * @@ -1149,17 +1342,14 @@ export const collect = (self: Dequeue): Effect, Pull * const next2 = yield* Queue.takeN(queue, 2) * console.log(next2) // [4, 5] * - * // End the queue before taking; now it can return fewer than requested - * yield* Queue.end(queue) - * - * // Take remaining messages (takes 2, even though we asked for 5) - * const remaining = yield* Queue.takeN(queue, 5) + * // Take remaining messages + * const remaining = yield* Queue.takeN(queue, 2) * console.log(remaining) // [6, 7] * }) * ``` * - * @category Taking - * @since 4.0.0 + * @category taking + * @since 2.0.0 */ export const takeN = ( self: Dequeue, @@ -1167,13 +1357,17 @@ export const takeN = ( ): Effect, E> => takeBetween(self, n, n) /** - * Take a variable number of messages from the queue, between specified min and max. - * It will only take up to the capacity of the queue. + * Takes between `min` and `max` messages from the queue. + * + * **Details** * - * If the queue is done, the `done` flag will be `true`. If the queue - * fails, the Effect will fail with the error. + * The operation waits when fewer than the required minimum messages are + * available. It returns at most `max` messages. If the queue completes or fails + * before the minimum can be satisfied, the effect fails with the queue's + * terminal error. + * + * **Example** (Taking a bounded batch of values) * - * @example * ```ts * import { Cause, Effect, Queue } from "effect" * @@ -1196,8 +1390,8 @@ export const takeN = ( * }) * ``` * - * @category Taking - * @since 4.0.0 + * @category taking + * @since 2.0.0 */ export const takeBetween = ( self: Dequeue, @@ -1209,13 +1403,16 @@ export const takeBetween = ( ) /** - * Take a single message from the queue, or wait for a message to be + * Takes a single message from the queue, or wait for a message to be * available. * + * **Details** + * * If the queue is done, it will fail with `Done`. If the * queue fails, the Effect will fail with the error. * - * @example + * **Example** (Taking one value) + * * ```ts * import { Cause, Effect, Queue } from "effect" * @@ -1234,7 +1431,7 @@ export const takeBetween = ( * // End the queue * yield* Queue.end(queue) * - * // Taking from ended queue fails with None + * // Taking from an ended queue fails with Done * const result = yield* Effect.match(Queue.take(queue), { * onFailure: (error: Cause.Done) => true, * onSuccess: (value: string) => false @@ -1243,8 +1440,8 @@ export const takeBetween = ( * }) * ``` * - * @category Taking - * @since 4.0.0 + * @category taking + * @since 2.0.0 */ export const take = (self: Dequeue): Effect => internalEffect.suspend( @@ -1252,11 +1449,16 @@ export const take = (self: Dequeue): Effect => ) /** - * Tries to take an item from the queue without blocking. + * Attempts to take one item from the queue without waiting. + * + * **Details** + * + * Returns `Option.some` when an item is immediately available. Returns + * `Option.none` when no item is available, when the queue is done, or when the + * immediate take observes a queue failure. * - * Returns `Option.some` with the item if available, or `Option.none` if the queue is empty or done. + * **Example** (Polling without blocking) * - * @example * ```ts * import { Effect, Option, Queue } from "effect" * @@ -1276,8 +1478,8 @@ export const take = (self: Dequeue): Effect => * }) * ``` * - * @category Taking - * @since 4.0.0 + * @category taking + * @since 2.0.0 */ export const poll = (self: Dequeue): Effect> => internalEffect.suspend(() => { @@ -1292,11 +1494,14 @@ export const poll = (self: Dequeue): Effect> => }) /** - * Views the next item without removing it. + * Peeks at the next item without removing it. + * + * **Details** * * Blocks until an item is available. If the queue is done or fails, the error is propagated. * - * @example + * **Example** (Peeking at the next value) + * * ```ts * import { Cause, Effect, Queue } from "effect" * @@ -1310,7 +1515,7 @@ export const poll = (self: Dequeue): Effect> => * }) * ``` * - * @category Taking + * @category taking * @since 4.0.0 */ export const peek = (self: Dequeue): Effect => @@ -1325,16 +1530,21 @@ export const peek = (self: Dequeue): Effect => }) /** - * Take a single message from the queue synchronously, or wait for a message to be - * available. + * Attempts to take one message from the queue synchronously. * - * If the queue is done, it will fail with `Done`. If the - * queue fails, the Effect will fail with the error. - * Returns `undefined` if no message is immediately available. + * **When to use** + * + * Use when polling queue internals must not suspend or register a waiting taker, + * and `undefined` is an acceptable result for an empty queue. + * + * **Details** + * + * Returns an `Exit` for an immediately available message or for the queue's + * terminal state. Returns `undefined` when no message is immediately available. + * This operation does not wait or register a taker. * - * This is an unsafe operation that directly accesses the queue without Effect wrapping. + * **Example** (Taking one value synchronously) * - * @example * ```ts * import { Effect, Queue } from "effect" * @@ -1359,7 +1569,7 @@ export const peek = (self: Dequeue): Effect => * }) * ``` * - * @category Taking + * @category taking * @since 4.0.0 */ export const takeUnsafe = (self: Dequeue): Exit | undefined => { @@ -1399,20 +1609,45 @@ const await_ = (self: Dequeue): Effect> => export { /** - * Wait for the queue to be done. + * Waits until a queue reaches the `Done` state. * - * @category Completion + * **When to use** + * + * Use to suspend a fiber until no further values can be taken from the queue + * and its terminal outcome is known. + * + * **Details** + * + * The effect succeeds with `void` for normal `Done` completion. Other + * terminal causes are preserved, so failures and interruptions complete this + * effect with the same terminal outcome. + * + * **Gotchas** + * + * A queue can be closing before it is done. `await` resumes at `Done`, not at + * the first completion signal, so buffered messages may need to be drained + * first. + * + * @see {@link end} for signaling normal completion while preserving buffered messages for consumers + * @see {@link fail} for signaling an error while preserving buffered messages for consumers + * @see {@link interrupt} for graceful interruption after buffered messages are drained + * @see {@link shutdown} for immediately discarding buffered messages and resuming pending operations + * + * @category completion * @since 4.0.0 */ await_ as await } /** - * Check the size of the queue. + * Returns the current number of buffered messages in the queue. * - * If the queue is complete, it will return `None`. + * **Details** + * + * Completed queues report a size of `0`. + * + * **Example** (Checking queue size) * - * @example * ```ts * import { Cause, Effect, Option, Queue } from "effect" * @@ -1439,15 +1674,16 @@ export { * }) * ``` * - * @category Size - * @since 4.0.0 + * @category sizes + * @since 2.0.0 */ export const size = (self: Dequeue): Effect => internalEffect.sync(() => sizeUnsafe(self)) /** - * Check if the queue is full. + * Checks whether the queue is full. + * + * **Example** (Checking if queues are full) * - * @example * ```ts * import { Cause, Effect, Option, Queue } from "effect" * @@ -1463,18 +1699,26 @@ export const size = (self: Dequeue): Effect => internalEffec * }) * ``` * - * @category Size - * @since 4.0.0 + * @category sizes + * @since 2.0.0 */ export const isFull = (self: Dequeue): Effect => internalEffect.sync(() => isFullUnsafe(self)) /** - * Check the size of the queue synchronously. + * Returns the current number of buffered messages in the queue synchronously. * - * If the queue is complete, it will return `None`. - * This is an unsafe operation that directly accesses the queue without Effect wrapping. + * **When to use** + * + * Use when you need an immediate `Queue` size snapshot for diagnostics or + * internals and do not need the read wrapped in `Effect`. + * + * **Details** + * + * Completed queues report a size of `0`. This unsafe operation reads the queue + * state directly without Effect wrapping. + * + * **Example** (Checking queue size synchronously) * - * @example * ```ts * import { Cause, Effect, Option, Queue } from "effect" * @@ -1503,15 +1747,21 @@ export const isFull = (self: Dequeue): Effect => internalEf * }) * ``` * - * @category Size + * @category sizes * @since 4.0.0 */ export const sizeUnsafe = (self: Dequeue): number => self.state._tag === "Done" ? 0 : self.messages.length /** - * Check if the queue is full synchronously. + * Checks whether the queue is full synchronously. + * + * **When to use** + * + * Use when an immediate `Queue` capacity snapshot is needed outside effectful + * code and racing queue changes are acceptable. + * + * **Example** (Checking fullness synchronously) * - * @example * ```ts * import { Cause, Effect, Option, Queue } from "effect" * @@ -1527,16 +1777,17 @@ export const sizeUnsafe = (self: Dequeue): number => self.state._tag * }) * ``` * - * @category Size + * @category sizes * @since 4.0.0 */ export const isFullUnsafe = (self: Dequeue): boolean => sizeUnsafe(self) === self.capacity /** - * Run an `Effect` into a `Queue`, where success ends the queue and failure + * Runs an `Effect` into a `Queue`, where success ends the queue and failure * fails the queue. * - * @example + * **Example** (Running effects into queues) + * * ```ts * import { Cause, Effect, Queue } from "effect" * @@ -1562,15 +1813,16 @@ export const isFullUnsafe = (self: Dequeue): boolean => sizeUnsafe(s * }) * ``` * - * @since 3.8.0 - * @category Completion + * @category completion + * @since 4.0.0 */ export const into: { /** - * Run an `Effect` into a `Queue`, where success ends the queue and failure + * Runs an `Effect` into a `Queue`, where success ends the queue and failure * fails the queue. * - * @example + * **Example** (Running effects into queues) + * * ```ts * import { Cause, Effect, Queue } from "effect" * @@ -1596,17 +1848,18 @@ export const into: { * }) * ``` * - * @since 3.8.0 - * @category Completion + * @category completion + * @since 4.0.0 */ (self: Enqueue): ( effect: Effect ) => Effect /** - * Run an `Effect` into a `Queue`, where success ends the queue and failure + * Runs an `Effect` into a `Queue`, where success ends the queue and failure * fails the queue. * - * @example + * **Example** (Running effects into queues) + * * ```ts * import { Cause, Effect, Queue } from "effect" * @@ -1632,8 +1885,8 @@ export const into: { * }) * ``` * - * @since 3.8.0 - * @category Completion + * @category completion + * @since 4.0.0 */ (effect: Effect, self: Enqueue): Effect } = dual( diff --git a/.opencode/node_modules/effect/src/Random.ts b/.opencode/node_modules/effect/src/Random.ts index 063210a6da644b92723e7757f99250a56bda81ad..6ab233e79f0f5eabcc616cd53d4b3734662136c3 100644 --- a/.opencode/node_modules/effect/src/Random.ts +++ b/.opencode/node_modules/effect/src/Random.ts @@ -1,23 +1,10 @@ /** - * The Random module provides a service for generating random numbers in Effect - * programs. It offers a testable and composable way to work with randomness, - * supporting integers, floating-point numbers, and range-based generation. + * Provides pseudo-random generation through an Effect service. * - * @example - * ```ts - * import { Effect, Random } from "effect" - * - * const program = Effect.gen(function*() { - * const randomFloat = yield* Random.next - * console.log("Random float:", randomFloat) - * - * const randomInt = yield* Random.nextInt - * console.log("Random integer:", randomInt) - * - * const diceRoll = yield* Random.nextIntBetween(1, 6) - * console.log("Dice roll:", diceRoll) - * }) - * ``` + * This module exposes effectful generators for booleans, doubles, safe + * integers, bounded numbers, shuffling, and deterministic seeded runs. Because + * random generation is a service, tests and applications can replace the + * generator used by Effect programs. * * @since 4.0.0 */ @@ -28,9 +15,21 @@ import * as random from "./internal/random.ts" import * as Predicate from "./Predicate.ts" /** - * Represents a service for generating random numbers. + * Represents a service for generating pseudo-random numbers. + * + * **When to use** + * + * Use to access or provide the random-number generator service used by Effect + * programs. + * + * **Gotchas** + * + * The default implementation is based on `Math.random` and is not + * cryptographically secure. Replace the service with a cryptographically secure + * implementation before using these generators for security-sensitive values. + * + * **Example** (Accessing the random service) * - * @example * ```ts * import { Effect, Random } from "effect" * @@ -38,17 +37,15 @@ import * as Predicate from "./Predicate.ts" * const float = yield* Random.next * const integer = yield* Random.nextInt * const inRange = yield* Random.nextIntBetween(1, 100) - * const uuid = yield* Random.nextUUIDv4 * * console.log("Float:", float) * console.log("Integer:", integer) * console.log("In range:", inRange) - * console.log("UUID:", uuid) * }) * ``` * - * @since 4.0.0 * @category Random Number Generators + * @since 2.0.0 */ export const Random: Context.Reference<{ nextIntUnsafe(): number @@ -59,9 +56,15 @@ const randomWith = (f: (random: typeof Random["Service"]) => A): Effect.Effec Effect.withFiber((fiber) => Effect.succeed(f(fiber.getRef(Random)))) /** - * Generates a random number between 0 (inclusive) and 1 (inclusive). + * Generates a random number between 0 (inclusive) and 1 (exclusive). + * + * **When to use** + * + * Use to generate a pseudo-random floating-point number in the standard + * `[0, 1)` range. + * + * **Example** (Generating a random number) * - * @example * ```ts * import { Effect, Random } from "effect" * @@ -71,15 +74,20 @@ const randomWith = (f: (random: typeof Random["Service"]) => A): Effect.Effec * }) * ``` * - * @since 4.0.0 * @category Random Number Generators + * @since 2.0.0 */ export const next: Effect.Effect = randomWith((r) => r.nextDoubleUnsafe()) /** * Generates a random boolean value. * - * @example + * **When to use** + * + * Use to make a pseudo-random true-or-false choice. + * + * **Example** (Generating a random boolean) + * * ```ts * import { Effect, Random } from "effect" * @@ -89,8 +97,8 @@ export const next: Effect.Effect = randomWith((r) => r.nextDoubleUnsafe( * }) * ``` * - * @since 4.0.0 * @category Random Number Generators + * @since 2.0.0 */ export const nextBoolean: Effect.Effect = randomWith((r) => r.nextDoubleUnsafe() > 0.5) @@ -98,7 +106,13 @@ export const nextBoolean: Effect.Effect = randomWith((r) => r.nextDoubl * Generates a random integer between `Number.MIN_SAFE_INTEGER` (inclusive) * and `Number.MAX_SAFE_INTEGER` (inclusive). * - * @example + * **When to use** + * + * Use to generate a pseudo-random safe integer across the full safe-integer + * range. + * + * **Example** (Generating a random integer) + * * ```ts * import { Effect, Random } from "effect" * @@ -108,15 +122,20 @@ export const nextBoolean: Effect.Effect = randomWith((r) => r.nextDoubl * }) * ``` * - * @since 4.0.0 * @category Random Number Generators + * @since 2.0.0 */ export const nextInt: Effect.Effect = randomWith((r) => r.nextIntUnsafe()) /** - * Generates a random number between `min` (inclusive) and `max` (inclusive). + * Generates a random number between `min` (inclusive) and `max` (exclusive). + * + * **When to use** + * + * Use to generate a pseudo-random floating-point number within a numeric range. + * + * **Example** (Generating a bounded random number) * - * @example * ```ts * import { Effect, Random } from "effect" * @@ -126,19 +145,27 @@ export const nextInt: Effect.Effect = randomWith((r) => r.nextIntUnsafe( * }) * ``` * - * @since 4.0.0 * @category Random Number Generators + * @since 4.0.0 */ export const nextBetween = (min: number, max: number): Effect.Effect => randomWith((r) => r.nextDoubleUnsafe() * (max - min) + min) /** - * Generates a random number between `min` (inclusive) and `max` (inclusive). + * Generates a random integer between `min` and `max`. * - * Set `options.halfOpen: true` to generate in the half-open range - * `[min, max)`. + * **When to use** + * + * Use to generate a pseudo-random integer within a rounded numeric range. + * + * **Details** + * + * The lower bound is rounded up with `Math.ceil` and the upper bound is + * rounded down with `Math.floor`. By default the range is inclusive; set + * `options.halfOpen: true` to exclude the upper bound. + * + * **Example** (Generating a bounded random integer) * - * @example * ```ts * import { Effect, Random } from "effect" * @@ -151,8 +178,8 @@ export const nextBetween = (min: number, max: number): Effect.Effect => * }) * ``` * - * @since 4.0.0 * @category Random Number Generators + * @since 2.0.0 */ export const nextIntBetween = (min: number, max: number, options?: { readonly halfOpen?: boolean @@ -168,7 +195,12 @@ export const nextIntBetween = (min: number, max: number, options?: { /** * Uses the pseudo-random number generator to shuffle the specified iterable. * - * @example + * **When to use** + * + * Use to randomly reorder an iterable using the active `Random` service. + * + * **Example** (Shuffling values) + * * ```ts * import { Effect, Random } from "effect" * @@ -178,8 +210,8 @@ export const nextIntBetween = (min: number, max: number, options?: { * }) * ``` * - * @since 4.0.0 * @category Random Number Generators + * @since 2.0.0 */ export const shuffle = (elements: Iterable): Effect.Effect> => randomWith((r) => { @@ -194,54 +226,23 @@ export const shuffle = (elements: Iterable): Effect.Effect> => }) /** - * Generates a random UUID (v4) string. + * Seeds the pseudo-random number generator with the specified value. * - * @example - * ```ts - * import { Effect, Random } from "effect" + * **When to use** * - * const program = Effect.gen(function*() { - * const uuid = yield* Random.nextUUIDv4 - * console.log("UUID:", uuid) - * }) - * ``` + * Use to run an effect with a deterministic pseudo-random sequence. * - * @since 4.0.0 - * @category Random Number Generators - */ -export const nextUUIDv4: Effect.Effect = randomWith((r) => { - // Generate 16 random bytes (128 bits) for UUID - const bytes: Array = [] - for (let i = 0; i < 16; i++) { - // Get unsigned byte [0, 255] from nextInt (signed 32-bit) - bytes.push((r.nextIntUnsafe() >>> 0) & 0xFF) - } - - // Set version to 4 (bits 12-15 of time_hi_and_version) - bytes[6] = (bytes[6] & 0x0F) | 0x40 - - // Set variant to RFC 4122 (bits 6-7 of clock_seq_hi_and_reserved) - bytes[8] = (bytes[8] & 0x3F) | 0x80 - - // Format as UUID string: xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx - const hex = (n: number) => n.toString(16).padStart(2, "0") - - return [ - bytes.slice(0, 4).map(hex).join(""), - bytes.slice(4, 6).map(hex).join(""), - bytes.slice(6, 8).map(hex).join(""), - bytes.slice(8, 10).map(hex).join(""), - bytes.slice(10, 16).map(hex).join("") - ].join("-") -}) - -/** - * Seeds the pseudorandom number generator with the specified value. + * **Details** + * + * Using the same seed produces the same random sequence, which is useful for + * tests and reproducible simulations. + * + * **Gotchas** * - * Take care to select a seed wit hhigh entropy to avoid issues with the - * quality of random number generation. + * Use an unpredictable seed when uniqueness or unpredictability matters. + * + * **Example** (Seeding random generation) * - * @example * ```ts * import { Effect, Random } from "effect" * @@ -260,17 +261,28 @@ export const nextUUIDv4: Effect.Effect = randomWith((r) => { * Effect.runPromise(seeded2) * ``` * - * @since 4.0.0 * @category Seeding + * @since 4.0.0 */ export const withSeed: { /** - * Seeds the pseudorandom number generator with the specified value. + * Seeds the pseudo-random number generator with the specified value. + * + * **When to use** + * + * Use to run an effect with a deterministic pseudo-random sequence. * - * Take care to select a seed wit hhigh entropy to avoid issues with the - * quality of random number generation. + * **Details** + * + * Using the same seed produces the same random sequence, which is useful for + * tests and reproducible simulations. + * + * **Gotchas** + * + * Use an unpredictable seed when uniqueness or unpredictability matters. + * + * **Example** (Seeding random generation) * - * @example * ```ts * import { Effect, Random } from "effect" * @@ -289,17 +301,28 @@ export const withSeed: { * Effect.runPromise(seeded2) * ``` * - * @since 4.0.0 * @category Seeding + * @since 4.0.0 */ (seed: string | number): (self: Effect.Effect) => Effect.Effect /** - * Seeds the pseudorandom number generator with the specified value. + * Seeds the pseudo-random number generator with the specified value. + * + * **When to use** + * + * Use to run an effect with a deterministic pseudo-random sequence. + * + * **Details** + * + * Using the same seed produces the same random sequence, which is useful for + * tests and reproducible simulations. + * + * **Gotchas** * - * Take care to select a seed wit hhigh entropy to avoid issues with the - * quality of random number generation. + * Use an unpredictable seed when uniqueness or unpredictability matters. + * + * **Example** (Seeding random generation) * - * @example * ```ts * import { Effect, Random } from "effect" * @@ -318,8 +341,8 @@ export const withSeed: { * Effect.runPromise(seeded2) * ``` * - * @since 4.0.0 * @category Seeding + * @since 4.0.0 */ (self: Effect.Effect, seed: string | number): Effect.Effect } = dual(2, ( @@ -531,7 +554,7 @@ function ISAAC_CSPRNG(userSeed?: string | number) { } /** - * Returns a signed, random integer in the range [-2^31, 2^31]. + * Returns a signed, random integer in the range [-2^31, 2^31). */ function nextInt32(): number { if (!generation--) { @@ -542,15 +565,8 @@ function ISAAC_CSPRNG(userSeed?: string | number) { } function nextIntUnsafe(): number { - // Get 32 bits (unsigned) - const low = nextInt32() >>> 0 // [0, 2^32-1] - - // Get 21 more bits for a total of 53 - const high = nextInt32() & 0x1FFFFF // [0, 2^21-1] - - // Combine: high bits * 2^32 + low bits, then shift to signed range - // This gives [0, 2^53-1], subtract 2^52 to center around 0 - return (high * 0x100000000) + low - 0x10000000000000 + return Math.floor(nextDoubleUnsafe() * (Number.MAX_SAFE_INTEGER - Number.MIN_SAFE_INTEGER + 1)) + + Number.MIN_SAFE_INTEGER } /** @@ -563,7 +579,7 @@ function ISAAC_CSPRNG(userSeed?: string | number) { // 53-bit integer const combined = hi * 4294967296 + lo - return combined / 9007199254740991 // [0, 1) + return combined / 0x20000000000000 // [0, 1) } return { nextIntUnsafe, nextDoubleUnsafe } @@ -589,84 +605,22 @@ function add32(x: number, y: number): number { return (msb << 16) | (lsb & 0xffff) } +const seedEncoder = new TextEncoder() + /** - * Convert a UTF-16 strings to UTF-8 encoded 32-bit integers (little-endian). + * Convert a string to UTF-8 encoded 32-bit integers (little-endian). */ function toIntArray(seed: string): Array { - let c1 = 0 // First UTF-16 code unit - let c2 = 0 // Second UTF-16 code unit (for surrogate pairs) - let unicode = 0 // Combined unicode code point from surrogate pair - const result: Array = [] // Result array of 32-bit integers - const buffer: Array = [] // Temporary buffer for the UTF-8 bytes (max 4 bytes) - const length = seed.length - 1 - - let index = 0 - while (index < length) { - c1 = seed.charCodeAt(index++) - c2 = seed.charCodeAt(index + 1) - - // 0x0000 - 0x007f: ASCII, single byte UTF-8: 0xxxxxxxx - // Example: 'A' (0x41) -> [0x41] - if (c1 < 0x0080) { - buffer.push(c1) - } // - // 0x0080 - 0x07ff: Two byte UTF-8: 110xxxxx 10xxxxxx - // Example: '¢' (0xA2) -> [0xC2, 0xA2] - else if (c1 < 0x0800) { - // First byte: upper 5 bits + 110xxxxx marker - // 0xA2 >>> 6 (0x02), & 0x1f = 0x02, | 0xc0 = 0xC2 - buffer.push(((c1 >>> 6) & 0x1f) | 0xc0) - // Second byte: lower 6 bits + 10xxxxxxxx marker - // 0xA2 & 0x3f = 0x22, | 0x80 = 0xA2 - buffer.push(((c1 >>> 0) & 0x3f) | 0x80) - } // - // 0x0800 - 0xffff (non-surrogate): Three byte UTF-8: 1110xxxx 10xxxxxx 10xxxxxx - // Example: '€' (0x20AC) -> [0xE2, 0x82, 0xAC] - else if ((c1 & 0xf800) != 0xd800) { - // First byte: top 4 bits + 1110xxxx marker - // 0x20AC >>> 12 = 0x02, & 0x0f = 0x02, | 0xe0 = 0xE2 - buffer.push(((c1 >>> 12) & 0x0f) | 0xe0) - // Second byte: middle 6 bits + 10xxxxxx marker - // 0x20AC >>> 6 = 0x82, & 0x3f = 0x02, | 0x80 = 0x82 - buffer.push(((c1 >>> 6) & 0x3f) | 0x80) - // Third byte: lower 6 bits + 10xxxxxx marker - // 0x20AC & 0x3f = 0x2C, | 0x80 = 0xAC - buffer.push(((c1 >>> 0) & 0x3f) | 0x80) - } // - // 0xd800 - 0xdfff: Surrogate pairs, four byte UTF-8: 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx - // Example: '𐍈' (U+10348, surrogates 0xD800 0xDF48) -> [0xF0, 0x90, 0x8D, 0x88] - else if (((c1 & 0xfc00) == 0xd800) && ((c2 & 0xfc00) == 0xdc00)) { - // Decode surrogate pair: combine 10 bits from each + 0x10000 - // ((0xDF48 & 0x3f) | ((0xD800 & 0x3f) << 10)) + 0x10000 = 0x10348 - unicode = ((c2 & 0x3f) | ((c1 & 0x3f) << 10)) + 0x10000 - // First byte: top 3 bits + 11110xxx marker - // 0x10348 >>> 18 = 0x00, & 0x07 = 0x00, | 0xf0 = 0xF0 - buffer.push(((unicode >>> 18) & 0x07) | 0xf0) - // Second byte: next 6 bits + 10xxxxxx marker - // 0x10348 >>> 12 = 0x10, & 0x3f = 0x10, | 0x80 = 0x90 - buffer.push(((unicode >>> 12) & 0x3f) | 0x80) - // Third byte: next 6 bits + 10xxxxxx marker - // 0x10348 >>> 6 = 0x40D, & 0x3f = 0x0D, | 0x80 = 0x8D - buffer.push(((unicode >>> 6) & 0x3f) | 0x80) - // Fourth byte: lower 6 bits + 10xxxxxx marker - // 0x10348 & 0x3f = 0x08, | 0x80 = 0x88 - buffer.push(((unicode >>> 0) & 0x3f) | 0x80) - index++ // Skip second surrogate - } else { - // invalid char - } - - // Pack 4 UTF-8 bytes -> 32-bit int (little-endian) - // Example: [0xE2, 0x82, 0xAC, 0x00] -> 0x00ACE2E2 - if (buffer.length > 3) { - result.push( - (buffer.shift()! << 0) | // Byte 0 at bits 0-7: 0xE2 << 0 = 0x000000E2 - (buffer.shift()! << 8) | // Byte 1 at bits 8-15: 0x82 << 8 = 0x00008200 - (buffer.shift()! << 16) | // Byte 2 at bits 16-23: 0xAC << 16 = 0x00AC0000 - (buffer.shift()! << 24) // Byte 3 at bits 24-31: 0x00 << 24 = 0x00000000 - ) - // Result: 0x00AC82E2 - } + const bytes = seedEncoder.encode(seed) + const result: Array = [] + + for (let index = 0; index < bytes.length; index += 4) { + result.push( + ((bytes[index] ?? 0) << 0) | + ((bytes[index + 1] ?? 0) << 8) | + ((bytes[index + 2] ?? 0) << 16) | + ((bytes[index + 3] ?? 0) << 24) + ) } return result diff --git a/.opencode/node_modules/effect/src/RcMap.ts b/.opencode/node_modules/effect/src/RcMap.ts index f022e2571984e6dc03045c44de740dd6dad0632b..80b9515fb4476ab192820963acb14353c5308003 100644 --- a/.opencode/node_modules/effect/src/RcMap.ts +++ b/.opencode/node_modules/effect/src/RcMap.ts @@ -1,4 +1,14 @@ /** + * Shares scoped resources by key and releases them when no one is using them. + * + * An `RcMap` runs a lookup effect the first time a key is requested, shares the + * in-progress or acquired resource with other callers for the same key, and + * tracks each caller through its current `Scope`. When the last scope for a key + * closes, the resource can be released, kept alive for an idle time, or removed + * by capacity limits or explicit invalidation. It is meant for resource + * lifecycles such as clients, sessions, and connections, not as a general + * mutable cache. + * * @since 3.5.0 */ import * as Cause from "./Cause.ts" @@ -22,9 +32,13 @@ const TypeId = "~effect/RcMap" * of resources indexed by keys. Resources are lazily acquired and automatically * released when no longer in use. * - * @since 3.5.0 - * @category models - * @example + * **When to use** + * + * Use to share scoped resources by key while automatically releasing them after + * their last active reference is gone. + * + * **Example** (Inspecting a reference-counted map) + * * ```ts * import { Effect, RcMap } from "effect" * @@ -49,6 +63,12 @@ const TypeId = "~effect/RcMap" * console.log(`Capacity: ${dbConnectionMap.capacity}`) * }).pipe(Effect.scoped) * ``` + * + * @see {@link make} for creating an `RcMap` + * @see {@link get} for acquiring or retaining a resource by key + * + * @category models + * @since 3.5.0 */ export interface RcMap extends Pipeable { readonly [TypeId]: typeof TypeId @@ -64,70 +84,42 @@ export interface RcMap extends Pipeable { * Represents the internal state of an RcMap, which can be either Open (active) * or Closed (shutdown and no longer accepting operations). * + * **When to use** + * + * Use when typing code that inspects an `RcMap`'s `state` field and narrows + * between open and closed lifecycle states. + * + * @see {@link RcMap} for the map value that exposes this state + * @see {@link State.Open} for the active state with entries + * @see {@link State.Closed} for the shutdown state + * + * @category models * @since 4.0.0 - * @category Models - * @example - * ```ts - * import type { RcMap } from "effect" - * - * // State is a union type that can be either: - * declare const openState: RcMap.State.Open - * declare const closedState: RcMap.State.Closed - * - * // Check the state type - * declare const state: RcMap.State - * if (state._tag === "Open") { - * // Access the internal map when open - * console.log("Map is open, contains entries") - * } else { - * // State is closed - * console.log("Map is closed") - * } - * ``` */ export type State = State.Open | State.Closed /** * Namespace containing the internal state types for RcMap. * - * @since 4.0.0 - * @category Models - * @example - * ```ts - * import type { RcMap } from "effect" + * **When to use** * - * // The State namespace contains types for RcMap internal state: - * // - Open: Contains the active resource map - * // - Closed: Indicates the map is shut down - * // - Entry: Individual resource entries with metadata + * Use when referring to the concrete open, closed, and entry state shapes used + * by `RcMap`. * - * declare const openState: RcMap.State.Open - * declare const closedState: RcMap.State.Closed - * declare const entry: RcMap.State.Entry - * ``` + * @since 4.0.0 */ export declare namespace State { /** * Represents the open/active state of an RcMap, containing the actual * resource map that stores entries. * + * **When to use** + * + * Use when handling an `RcMap` that can still accept operations and contains + * stored entries. + * + * @category models * @since 4.0.0 - * @category Models - * @example - * ```ts - * import type { RcMap } from "effect" - * import * as MutableHashMap from "effect/MutableHashMap" - * - * // State.Open contains the active resource map - * declare const openState: RcMap.State.Open - * - * // Access the internal map when state is open - * if (openState._tag === "Open") { - * // The map contains Entry objects indexed by keys - * const hasKey = MutableHashMap.has(openState.map, "someKey") - * console.log(`Map contains key: ${hasKey}`) - * } - * ``` */ export interface Open { readonly _tag: "Open" @@ -138,21 +130,12 @@ export declare namespace State { * Represents the closed state of an RcMap, indicating that the map has been * shut down and will no longer accept new operations. * - * @since 4.0.0 - * @category Models - * @example - * ```ts - * import type { RcMap } from "effect" + * **When to use** * - * // State.Closed indicates the RcMap is shut down - * declare const closedState: RcMap.State.Closed + * Use when handling an `RcMap` after its owning scope has closed. * - * // Check for closed state - * if (closedState._tag === "Closed") { - * console.log("RcMap is closed, no operations allowed") - * // Any attempt to get resources will result in interruption - * } - * ``` + * @category models + * @since 4.0.0 */ export interface Closed { readonly _tag: "Closed" @@ -162,26 +145,13 @@ export declare namespace State { * Represents an individual entry in the RcMap, containing the resource's * metadata including reference count, expiration time, and lifecycle management. * - * @since 4.0.0 - * @category Models - * @example - * ```ts - * import type { RcMap } from "effect" - * - * // Entry contains all metadata for a resource in the map - * declare const entry: RcMap.State.Entry + * **When to use** * - * // Entry properties: - * // - deferred: Promise-like structure for the resource value - * // - scope: Manages the resource's lifecycle - * // - finalizer: Effect to run when cleaning up - * // - fiber: Optional background fiber for expiration - * // - expiresAt: Timestamp when resource expires - * // - refCount: Number of active references + * Use when inspecting the stored resource, reference count, and idle lifecycle + * metadata for a single key. * - * console.log(`Reference count: ${entry.refCount}`) - * console.log(`Expires at: ${entry.expiresAt}`) - * ``` + * @category models + * @since 4.0.0 */ export interface Entry { readonly deferred: Deferred.Deferred @@ -217,20 +187,24 @@ const makeUnsafe = (options: { }) /** - * An `RcMap` can contain multiple reference counted resources that can be indexed + * Creates an `RcMap` that can contain multiple reference counted resources that can be indexed * by a key. The resources are lazily acquired on the first call to `get` and * released when the last reference is released. * - * Complex keys can extend `Equal` and `Hash` to allow lookups by value. + * **When to use** + * + * Use to create a scoped reference-counted map for resources that should be + * acquired once per key and shared while in use. * - * **Options** + * **Details** + * + * Complex keys can extend `Equal` and `Hash` to allow lookups by value. * * - `capacity`: The maximum number of resources that can be held in the map. * - `idleTimeToLive`: When the reference count reaches zero, the resource will be released after this duration. * - * @since 3.5.0 - * @category models - * @example + * **Example** (Creating a reference-counted map) + * * ```ts * import { Effect, RcMap } from "effect" * @@ -251,23 +225,33 @@ const makeUnsafe = (options: { * ) * }) * ``` + * + * @see {@link get} for acquiring or retaining a resource by key + * @see {@link invalidate} for removing a resource from the map + * + * @category models + * @since 3.5.0 */ export const make: { /** - * An `RcMap` can contain multiple reference counted resources that can be indexed + * Creates an `RcMap` that can contain multiple reference counted resources that can be indexed * by a key. The resources are lazily acquired on the first call to `get` and * released when the last reference is released. * - * Complex keys can extend `Equal` and `Hash` to allow lookups by value. + * **When to use** + * + * Use to create a scoped reference-counted map for resources that should be + * acquired once per key and shared while in use. + * + * **Details** * - * **Options** + * Complex keys can extend `Equal` and `Hash` to allow lookups by value. * * - `capacity`: The maximum number of resources that can be held in the map. * - `idleTimeToLive`: When the reference count reaches zero, the resource will be released after this duration. * - * @since 3.5.0 - * @category models - * @example + * **Example** (Creating a reference-counted map) + * * ```ts * import { Effect, RcMap } from "effect" * @@ -288,6 +272,12 @@ export const make: { * ) * }) * ``` + * + * @see {@link get} for acquiring or retaining a resource by key + * @see {@link invalidate} for removing a resource from the map + * + * @category models + * @since 3.5.0 */ ( options: { @@ -297,20 +287,24 @@ export const make: { } ): Effect.Effect, never, Scope.Scope | R> /** - * An `RcMap` can contain multiple reference counted resources that can be indexed + * Creates an `RcMap` that can contain multiple reference counted resources that can be indexed * by a key. The resources are lazily acquired on the first call to `get` and * released when the last reference is released. * - * Complex keys can extend `Equal` and `Hash` to allow lookups by value. + * **When to use** * - * **Options** + * Use to create a scoped reference-counted map for resources that should be + * acquired once per key and shared while in use. + * + * **Details** + * + * Complex keys can extend `Equal` and `Hash` to allow lookups by value. * * - `capacity`: The maximum number of resources that can be held in the map. * - `idleTimeToLive`: When the reference count reaches zero, the resource will be released after this duration. * - * @since 3.5.0 - * @category models - * @example + * **Example** (Creating a reference-counted map) + * * ```ts * import { Effect, RcMap } from "effect" * @@ -331,6 +325,12 @@ export const make: { * ) * }) * ``` + * + * @see {@link get} for acquiring or retaining a resource by key + * @see {@link invalidate} for removing a resource from the map + * + * @category models + * @since 3.5.0 */ ( options: { @@ -379,13 +379,22 @@ export const make: { }) /** - * Retrieves a value from the RcMap by key. If the resource doesn't exist, it will be - * acquired using the lookup function. The resource is reference counted and will be - * released when the scope closes. + * Gets the resource for a key, acquiring it with the map's lookup function when + * the key is not already cached. + * + * **When to use** + * + * Use to acquire or retain the resource for a key within the current scope. + * + * **Details** + * + * The resource's reference count is incremented for the current `Scope`, and a + * release finalizer is added to that scope. When the current scope closes, the + * reference is released; the resource is closed when the last reference is + * released, subject to the map's idle time-to-live setting. + * + * **Example** (Acquiring a resource) * - * @since 3.5.0 - * @category combinators - * @example * ```ts * import { Effect, RcMap } from "effect" * @@ -403,16 +412,31 @@ export const make: { * console.log(resource) // "Resource: database" * }).pipe(Effect.scoped) * ``` + * + * @see {@link make} for creating the reference-counted map + * @see {@link invalidate} for removing a resource by key + * + * @category combinators + * @since 3.5.0 */ export const get: { /** - * Retrieves a value from the RcMap by key. If the resource doesn't exist, it will be - * acquired using the lookup function. The resource is reference counted and will be - * released when the scope closes. + * Gets the resource for a key, acquiring it with the map's lookup function when + * the key is not already cached. + * + * **When to use** + * + * Use to acquire or retain the resource for a key within the current scope. + * + * **Details** + * + * The resource's reference count is incremented for the current `Scope`, and a + * release finalizer is added to that scope. When the current scope closes, the + * reference is released; the resource is closed when the last reference is + * released, subject to the map's idle time-to-live setting. + * + * **Example** (Acquiring a resource) * - * @since 3.5.0 - * @category combinators - * @example * ```ts * import { Effect, RcMap } from "effect" * @@ -430,16 +454,31 @@ export const get: { * console.log(resource) // "Resource: database" * }).pipe(Effect.scoped) * ``` + * + * @see {@link make} for creating the reference-counted map + * @see {@link invalidate} for removing a resource by key + * + * @category combinators + * @since 3.5.0 */ (key: K): (self: RcMap) => Effect.Effect /** - * Retrieves a value from the RcMap by key. If the resource doesn't exist, it will be - * acquired using the lookup function. The resource is reference counted and will be - * released when the scope closes. + * Gets the resource for a key, acquiring it with the map's lookup function when + * the key is not already cached. + * + * **When to use** + * + * Use to acquire or retain the resource for a key within the current scope. + * + * **Details** + * + * The resource's reference count is incremented for the current `Scope`, and a + * release finalizer is added to that scope. When the current scope closes, the + * reference is released; the resource is closed when the last reference is + * released, subject to the map's idle time-to-live setting. + * + * **Example** (Acquiring a resource) * - * @since 3.5.0 - * @category combinators - * @example * ```ts * import { Effect, RcMap } from "effect" * @@ -457,6 +496,12 @@ export const get: { * console.log(resource) // "Resource: database" * }).pipe(Effect.scoped) * ``` + * + * @see {@link make} for creating the reference-counted map + * @see {@link invalidate} for removing a resource by key + * + * @category combinators + * @since 3.5.0 */ (self: RcMap, key: K): Effect.Effect } = dual( @@ -548,11 +593,18 @@ const release = (self: RcMap, key: K, entry: State.Entry }) /** - * Returns an array of all keys currently stored in the RcMap. + * Returns an iterable of all keys currently stored in the `RcMap`. + * + * **When to use** + * + * Use to inspect which keys currently have stored resources in an `RcMap`. + * + * **Details** + * + * If the `RcMap` has been closed, the effect is interrupted. + * + * **Example** (Listing keys) * - * @since 3.5.0 - * @category combinators - * @example * ```ts * import { Effect, RcMap } from "effect" * @@ -571,6 +623,11 @@ const release = (self: RcMap, key: K, entry: State.Entry * console.log(allKeys) // ["foo", "bar", "baz"] * }).pipe(Effect.scoped) * ``` + * + * @see {@link has} for checking one key without enumerating all keys + * + * @category combinators + * @since 3.8.0 */ export const keys = (self: RcMap): Effect.Effect> => { return Effect.suspend(() => @@ -582,9 +639,12 @@ export const keys = (self: RcMap): Effect.Effect> * Invalidates and removes a specific key from the RcMap. If the resource is not * currently in use (reference count is 0), it will be immediately released. * - * @since 3.5.0 - * @category combinators - * @example + * **When to use** + * + * Use to remove a resource by key so the next access performs a fresh lookup. + * + * **Example** (Invalidating a resource) + * * ```ts * import { Effect, RcMap } from "effect" * @@ -608,15 +668,24 @@ export const keys = (self: RcMap): Effect.Effect> * yield* RcMap.get(map, "cache") * }).pipe(Effect.scoped) * ``` + * + * @see {@link get} for acquiring or retaining the resource for a key + * @see {@link touch} for extending the idle lifetime without removing the entry + * + * @category combinators + * @since 3.13.0 */ export const invalidate: { /** * Invalidates and removes a specific key from the RcMap. If the resource is not * currently in use (reference count is 0), it will be immediately released. * - * @since 3.5.0 - * @category combinators - * @example + * **When to use** + * + * Use to remove a resource by key so the next access performs a fresh lookup. + * + * **Example** (Invalidating a resource) + * * ```ts * import { Effect, RcMap } from "effect" * @@ -640,15 +709,24 @@ export const invalidate: { * yield* RcMap.get(map, "cache") * }).pipe(Effect.scoped) * ``` + * + * @see {@link get} for acquiring or retaining the resource for a key + * @see {@link touch} for extending the idle lifetime without removing the entry + * + * @category combinators + * @since 3.13.0 */ (key: K): (self: RcMap) => Effect.Effect /** * Invalidates and removes a specific key from the RcMap. If the resource is not * currently in use (reference count is 0), it will be immediately released. * - * @since 3.5.0 - * @category combinators - * @example + * **When to use** + * + * Use to remove a resource by key so the next access performs a fresh lookup. + * + * **Example** (Invalidating a resource) + * * ```ts * import { Effect, RcMap } from "effect" * @@ -672,6 +750,12 @@ export const invalidate: { * yield* RcMap.get(map, "cache") * }).pipe(Effect.scoped) * ``` + * + * @see {@link get} for acquiring or retaining the resource for a key + * @see {@link touch} for extending the idle lifetime without removing the entry + * + * @category combinators + * @since 3.13.0 */ (self: RcMap, key: K): Effect.Effect } = dual( @@ -689,18 +773,78 @@ export const invalidate: { ) /** - * @since 3.17.7 + * Returns whether the `RcMap` currently contains an entry for the specified + * key. + * + * **When to use** + * + * Use to check whether a key is already present in an `RcMap` without running + * the lookup function or acquiring a missing resource. + * + * **Details** + * + * This operation only checks the current map state. + * + * **Gotchas** + * + * Closed maps return `false`, so `false` does not distinguish a missing key + * from a closed map. + * + * @see {@link get} for acquiring or retaining the resource for a key + * @see {@link keys} for enumerating all currently stored keys + * * @category combinators + * @since 3.17.7 */ export const has: { /** - * @since 3.17.7 + * Returns whether the `RcMap` currently contains an entry for the specified + * key. + * + * **When to use** + * + * Use to check whether a key is already present in an `RcMap` without running + * the lookup function or acquiring a missing resource. + * + * **Details** + * + * This operation only checks the current map state. + * + * **Gotchas** + * + * Closed maps return `false`, so `false` does not distinguish a missing key + * from a closed map. + * + * @see {@link get} for acquiring or retaining the resource for a key + * @see {@link keys} for enumerating all currently stored keys + * * @category combinators + * @since 3.17.7 */ (key: K): (self: RcMap) => Effect.Effect /** - * @since 3.17.7 + * Returns whether the `RcMap` currently contains an entry for the specified + * key. + * + * **When to use** + * + * Use to check whether a key is already present in an `RcMap` without running + * the lookup function or acquiring a missing resource. + * + * **Details** + * + * This operation only checks the current map state. + * + * **Gotchas** + * + * Closed maps return `false`, so `false` does not distinguish a missing key + * from a closed map. + * + * @see {@link get} for acquiring or retaining the resource for a key + * @see {@link keys} for enumerating all currently stored keys + * * @category combinators + * @since 3.17.7 */ (self: RcMap, key: K): Effect.Effect } = dual( @@ -717,9 +861,12 @@ export const has: { * `idleTimeToLive` configured, calling `touch` will reset the expiration * timer for the specified key. * - * @since 3.5.0 - * @category combinators - * @example + * **When to use** + * + * Use to keep an idle resource alive longer without acquiring a new reference. + * + * **Example** (Extending resource idle time) + * * ```ts * import { Effect, RcMap } from "effect" * @@ -744,6 +891,11 @@ export const has: { * // from the time it was touched * }).pipe(Effect.scoped) * ``` + * + * @see {@link invalidate} for removing the resource instead of extending it + * + * @category combinators + * @since 3.13.0 */ export const touch: { /** @@ -751,9 +903,12 @@ export const touch: { * `idleTimeToLive` configured, calling `touch` will reset the expiration * timer for the specified key. * - * @since 3.5.0 - * @category combinators - * @example + * **When to use** + * + * Use to keep an idle resource alive longer without acquiring a new reference. + * + * **Example** (Extending resource idle time) + * * ```ts * import { Effect, RcMap } from "effect" * @@ -778,6 +933,11 @@ export const touch: { * // from the time it was touched * }).pipe(Effect.scoped) * ``` + * + * @see {@link invalidate} for removing the resource instead of extending it + * + * @category combinators + * @since 3.13.0 */ (key: K): (self: RcMap) => Effect.Effect /** @@ -785,9 +945,12 @@ export const touch: { * `idleTimeToLive` configured, calling `touch` will reset the expiration * timer for the specified key. * - * @since 3.5.0 - * @category combinators - * @example + * **When to use** + * + * Use to keep an idle resource alive longer without acquiring a new reference. + * + * **Example** (Extending resource idle time) + * * ```ts * import { Effect, RcMap } from "effect" * @@ -812,6 +975,11 @@ export const touch: { * // from the time it was touched * }).pipe(Effect.scoped) * ``` + * + * @see {@link invalidate} for removing the resource instead of extending it + * + * @category combinators + * @since 3.13.0 */ (self: RcMap, key: K): Effect.Effect } = dual( diff --git a/.opencode/node_modules/effect/src/RcRef.ts b/.opencode/node_modules/effect/src/RcRef.ts index 9c508e6e4a7e796bbcbe6d63aaa8b40a86c11e6d..fab9307eccdb73efbf04353021d08681c7d7c2f6 100644 --- a/.opencode/node_modules/effect/src/RcRef.ts +++ b/.opencode/node_modules/effect/src/RcRef.ts @@ -1,4 +1,11 @@ /** + * Reference-counted handles for sharing one scoped resource across many scoped + * users. An `RcRef` acquires the resource lazily the first time `get` + * needs it, reuses that value while it is borrowed or kept idle, and finalizes + * it when the final borrowing scope closes unless an idle timeout keeps it + * available. The module also provides `invalidate` for forcing the next `get` + * to acquire a fresh resource. + * * @since 3.5.0 */ import type * as Duration from "./Duration.ts" @@ -13,13 +20,19 @@ const TypeId = "~effect/RcRef" /** * A reference counted reference that manages resource lifecycle. * + * **When to use** + * + * Use to share a scoped resource across active users with reference-counted + * acquisition and release. + * + * **Details** + * * An RcRef wraps a resource that can be acquired and released multiple times. * The resource is lazily acquired on the first call to `get` and automatically * released when the last reference is released. * - * @since 3.5.0 - * @category models - * @example + * **Example** (Sharing a lazily acquired resource) + * * ```ts * import { Effect, RcRef } from "effect" * @@ -43,15 +56,19 @@ const TypeId = "~effect/RcRef" * return [connection1, connection2] * }) * ``` + * + * @category models + * @since 3.5.0 */ export interface RcRef extends Pipeable { readonly [TypeId]: RcRef.Variance } /** - * @since 3.5.0 - * @category models - * @example + * Namespace containing type-level members associated with `RcRef`. + * + * **Example** (Referencing namespace types) + * * ```ts * import type { RcRef } from "effect" * @@ -59,21 +76,26 @@ export interface RcRef extends Pipeable { * type MyRcRef = RcRef.RcRef * type MyVariance = RcRef.RcRef.Variance * ``` + * + * @since 3.5.0 */ export declare namespace RcRef { /** - * @since 3.5.0 - * @category models - * @example - * ```ts - * import type { RcRef } from "effect" + * Type-level variance marker for `RcRef`. + * + * **When to use** * - * // Variance interface defines covariance for type parameters - * type StringRcRefVariance = RcRef.RcRef.Variance + * Use to carry the value and error type parameters for `RcRef` in Effect's + * type machinery. * - * // Shows that both A and E are covariant - * declare const variance: StringRcRefVariance - * ``` + * **Details** + * + * This interface records the covariant value and error types carried by an + * `RcRef`. It is used by Effect's type machinery and is not normally + * referenced directly by users. + * + * @category models + * @since 3.5.0 */ export interface Variance { readonly _A: Types.Covariant @@ -82,17 +104,23 @@ export declare namespace RcRef { } /** - * Create an `RcRef` from an acquire `Effect`. + * Creates an `RcRef` from an acquire effect. * - * An RcRef wraps a reference counted resource that can be acquired and released - * multiple times. + * **When to use** * - * The resource is lazily acquired on the first call to `get` and released when - * the last reference is released. + * Use to create a lazily acquired, reference-counted resource from an acquire + * effect. + * + * **Details** + * + * The resource is acquired lazily on the first `get` and shared by subsequent + * gets while it remains cached. Each `get` adds a reference to the current + * `Scope`. When the last reference is released, the resource is closed + * immediately by default, or after `idleTimeToLive` when that option is + * provided. + * + * **Example** (Creating a reference-counted resource) * - * @since 3.5.0 - * @category constructors - * @example * ```ts * import { Effect, RcRef } from "effect" * @@ -112,6 +140,9 @@ export declare namespace RcRef { * ) * }) * ``` + * + * @category constructors + * @since 3.5.0 */ export const make: ( options: { @@ -125,15 +156,22 @@ export const make: ( ) => Effect.Effect, never, R | Scope> = internal.make /** - * Get the value from an RcRef. + * Gets the value from an `RcRef`, acquiring it first if needed. * - * This will acquire the resource if it hasn't been acquired yet, or increment - * the reference count if it has. The resource will be automatically released - * when the returned scope is closed. + * **When to use** + * + * Use to borrow the current resource within a `Scope`, acquiring it first if + * necessary. + * + * **Details** + * + * The reference count is incremented for the current `Scope`, and a release + * finalizer is added to that scope. When the current scope closes, the + * reference is released; the resource is closed when the final reference is + * released, subject to any configured idle time-to-live. + * + * **Example** (Sharing one acquired value) * - * @since 3.5.0 - * @category combinators - * @example * ```ts * import { Effect, RcRef } from "effect" * @@ -156,11 +194,32 @@ export const make: ( * return value1 * }) * ``` + * + * @category combinators + * @since 3.5.0 */ export const get: (self: RcRef) => Effect.Effect = internal.get /** - * @since 3.19.6 + * Invalidates the currently cached resource, if one has been acquired. + * + * **When to use** + * + * Use to force future `RcRef.get` calls to acquire a fresh resource when the + * currently cached resource should no longer be reused. + * + * **Details** + * + * After invalidation, the next `get` acquires a fresh resource. + * + * **Gotchas** + * + * Invalidation does not revoke resources already borrowed by active scopes; + * those remain usable until their scopes close. + * + * @see {@link get} for acquiring the current cached resource or the fresh resource after invalidation + * * @category combinators + * @since 3.19.6 */ export const invalidate: (self: RcRef) => Effect.Effect = internal.invalidate diff --git a/.opencode/node_modules/effect/src/Record.ts b/.opencode/node_modules/effect/src/Record.ts index bbe628b7a71a244cf6511b703616eeef0644b364..b65ec5d2e7e4823fb6dd4ad312cb222d034ab381 100644 --- a/.opencode/node_modules/effect/src/Record.ts +++ b/.opencode/node_modules/effect/src/Record.ts @@ -1,5 +1,11 @@ /** - * This module provides utility functions for working with records in TypeScript. + * Works with plain JavaScript records as immutable key/value dictionaries. + * + * A record is an object whose keys are strings or symbols. This module includes + * helpers for construction, lookup, updates, mapping, filtering, folding, + * set-like combination, and typed conversions between records and iterable + * entries. Helpers that change values return new records instead of mutating the + * input. * * @since 2.0.0 */ @@ -19,7 +25,8 @@ import type { NoInfer } from "./Types.ts" * Represents a readonly record with keys of type `K` and values of type `A`. * This is the foundational type for immutable key-value mappings in Effect. * - * @example + * **Example** (Defining a readonly record type) + * * ```ts * import type { Record } from "effect" * @@ -43,7 +50,8 @@ export type ReadonlyRecord = { * Namespace containing utility types for working with readonly records. * These types help with type-level operations on record keys and values. * - * @example + * **Example** (Using readonly record helper types) + * * ```ts * import type { Record } from "effect" * @@ -54,7 +62,6 @@ export type ReadonlyRecord = { * type CommonKeys = Record.ReadonlyRecord.IntersectKeys<"a" | "b", "b" | "c"> // "b" * ``` * - * @category models * @since 2.0.0 */ export declare namespace ReadonlyRecord { @@ -67,7 +74,8 @@ export declare namespace ReadonlyRecord { * Represents a type that converts literal string keys to generic string type and symbol keys to generic symbol type. * This is useful for maintaining type safety while allowing flexible key types in record operations. * - * @example + * **Example** (Converting literal keys to non-literal keys) + * * ```ts * import type { Record } from "effect" * @@ -88,7 +96,8 @@ export declare namespace ReadonlyRecord { * Represents the intersection of two key types, handling both literal and non-literal string keys. * This type is used in record operations that need to compute overlapping keys. * - * @example + * **Example** (Intersecting record keys) + * * ```ts * import type { Record } from "effect" * @@ -111,15 +120,23 @@ export declare namespace ReadonlyRecord { * Type lambda for readonly records, used in higher-kinded type operations. * This enables records to work with generic type constructors and functors. * - * @example - * ```ts - * import type { Record } from "effect" - * - * // The type lambda allows records to be used as higher-kinded types - * type RecordTypeLambda = Record.ReadonlyRecordTypeLambda<"key1" | "key2"> + * **Example** (Applying a readonly record type lambda) * - * // This enables mapping over the type parameter - * type StringRecord = RecordTypeLambda["type"] // ReadonlyRecord<"key1" | "key2", Target> + * ```ts + * import type { HKT, Record } from "effect" + * + * type Settings = HKT.Kind< + * Record.ReadonlyRecordTypeLambda<"port" | "retries">, + * never, + * never, + * never, + * number + * > + * + * const defaults: Settings = { + * port: 3000, + * retries: 3 + * } * ``` * * @category type lambdas @@ -132,7 +149,8 @@ export interface ReadonlyRecordTypeLambda extends Typ /** * Creates a new, empty record. * - * @example + * **Example** (Creating an empty record) + * * ```ts * import { Record } from "effect" * @@ -154,9 +172,10 @@ export const empty = (): Record< > => ({} as any) /** - * Determine if a record is empty. + * Determines if a mutable record is empty. + * + * **Example** (Checking for an empty record) * - * @example * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -172,9 +191,10 @@ export const isEmptyRecord = (self: Record): self is Object.keys(self).length === 0 /** - * Determine if a record is empty. + * Determines if a readonly record is empty. + * + * **Example** (Checking for an empty readonly record) * - * @example * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -194,7 +214,8 @@ export const isEmptyReadonlyRecord: ( * Takes an iterable and a projection function and returns a record. * The projection function maps each value of the iterable to a tuple of a key and a value, which is then added to the resulting record. * - * @example + * **Example** (Building a record from mapped iterable values) + * * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -215,7 +236,8 @@ export const fromIterableWith: { * Takes an iterable and a projection function and returns a record. * The projection function maps each value of the iterable to a tuple of a key and a value, which is then added to the resulting record. * - * @example + * **Example** (Building a record from mapped iterable values) + * * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -236,7 +258,8 @@ export const fromIterableWith: { * Takes an iterable and a projection function and returns a record. * The projection function maps each value of the iterable to a tuple of a key and a value, which is then added to the resulting record. * - * @example + * **Example** (Building a record from mapped iterable values) + * * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -271,7 +294,8 @@ export const fromIterableWith: { /** * Creates a new record from an iterable, utilizing the provided function to determine the key for each element. * - * @example + * **Example** (Building a record keyed by iterable values) + * * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -301,10 +325,13 @@ export const fromIterableBy = ( /** * Builds a record from an iterable of key-value pairs. * + * **Details** + * * If there are conflicting keys when using `fromEntries`, the last occurrence of the key/value pair will overwrite the * previous ones. So the resulting record will only have the value of the last occurrence of each key. * - * @example + * **Example** (Building a record from entries) + * * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -314,8 +341,8 @@ export const fromIterableBy = ( * assert.deepStrictEqual(Record.fromEntries(input), { a: 1, b: 2 }) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const fromEntries: ( entries: Iterable @@ -324,7 +351,8 @@ export const fromEntries: ( /** * Transforms the values of a record into an `Array` with a custom mapping function. * - * @example + * **Example** (Collecting mapped record values) + * * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -336,14 +364,15 @@ export const fromEntries: ( * ], ["c", 3]]) * ``` * - * @category conversions + * @category converting * @since 2.0.0 */ export const collect: { /** * Transforms the values of a record into an `Array` with a custom mapping function. * - * @example + * **Example** (Collecting mapped record values) + * * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -355,14 +384,15 @@ export const collect: { * ], ["c", 3]]) * ``` * - * @category conversions + * @category converting * @since 2.0.0 */ (f: (key: K, a: A) => B): (self: ReadonlyRecord) => Array /** * Transforms the values of a record into an `Array` with a custom mapping function. * - * @example + * **Example** (Collecting mapped record values) + * * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -374,7 +404,7 @@ export const collect: { * ], ["c", 3]]) * ``` * - * @category conversions + * @category converting * @since 2.0.0 */ (self: ReadonlyRecord, f: (key: K, a: A) => B): Array @@ -392,7 +422,8 @@ export const collect: { /** * Takes a record and returns an array of tuples containing its keys and values. * - * @example + * **Example** (Converting a record to entries) + * * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -401,7 +432,7 @@ export const collect: { * assert.deepStrictEqual(Record.toEntries(x), [["a", 1], ["b", 2], ["c", 3]]) * ``` * - * @category conversions + * @category converting * @since 2.0.0 */ export const toEntries: (self: ReadonlyRecord) => Array<[K, A]> = collect(( @@ -412,7 +443,8 @@ export const toEntries: (self: ReadonlyRecord) => Arr /** * Returns the number of key/value pairs in a record. * - * @example + * **Example** (Getting the record size) + * * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -426,9 +458,10 @@ export const toEntries: (self: ReadonlyRecord) => Arr export const size = (self: ReadonlyRecord): number => keys(self).length /** - * Check if a given `key` exists in a record. + * Checks whether a given `key` exists in a record. + * + * **Example** (Checking key membership) * - * @example * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -442,9 +475,10 @@ export const size = (self: ReadonlyRecord): number => */ export const has: { /** - * Check if a given `key` exists in a record. + * Checks whether a given `key` exists in a record. + * + * **Example** (Checking key membership) * - * @example * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -458,9 +492,10 @@ export const has: { */ (key: NoInfer): (self: ReadonlyRecord) => boolean /** - * Check if a given `key` exists in a record. + * Checks whether a given `key` exists in a record. + * + * **Example** (Checking key membership) * - * @example * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -482,9 +517,10 @@ export const has: { ) /** - * Retrieve a value at a particular key from a record, returning it wrapped in an `Option`. + * Retrieves a value at a particular key from a record safely, returning it wrapped in an `Option`. + * + * **Example** (Getting a value as an Option) * - * @example * ```ts * import { Option, Record as R } from "effect" * import * as assert from "node:assert" @@ -500,9 +536,10 @@ export const has: { */ export const get: { /** - * Retrieve a value at a particular key from a record, returning it wrapped in an `Option`. + * Retrieves a value at a particular key from a record safely, returning it wrapped in an `Option`. + * + * **Example** (Getting a value as an Option) * - * @example * ```ts * import { Option, Record as R } from "effect" * import * as assert from "node:assert" @@ -518,9 +555,10 @@ export const get: { */ (key: NoInfer): (self: ReadonlyRecord) => Option.Option /** - * Retrieve a value at a particular key from a record, returning it wrapped in an `Option`. + * Retrieves a value at a particular key from a record safely, returning it wrapped in an `Option`. + * + * **Example** (Getting a value as an Option) * - * @example * ```ts * import { Option, Record as R } from "effect" * import * as assert from "node:assert" @@ -542,10 +580,11 @@ export const get: { ) /** - * Apply a function to the element at the specified key, creating a new record, + * Applies a function to the element at the specified key safely, creating a new record, * or return `Option.none()` if the key doesn't exist. * - * @example + * **Example** (Modifying a value at a key) + * * ```ts * import { Record } from "effect" * @@ -557,15 +596,16 @@ export const get: { * Record.modify(input, "b", f) // Option.none() * ``` * - * @category utils + * @category mutations * @since 2.0.0 */ export const modify: { /** - * Apply a function to the element at the specified key, creating a new record, + * Applies a function to the element at the specified key safely, creating a new record, * or return `Option.none()` if the key doesn't exist. * - * @example + * **Example** (Modifying a value at a key) + * * ```ts * import { Record } from "effect" * @@ -577,15 +617,16 @@ export const modify: { * Record.modify(input, "b", f) // Option.none() * ``` * - * @category utils + * @category mutations * @since 2.0.0 */ (key: NoInfer, f: (a: A) => B): (self: ReadonlyRecord) => Option.Option> /** - * Apply a function to the element at the specified key, creating a new record, + * Applies a function to the element at the specified key safely, creating a new record, * or return `Option.none()` if the key doesn't exist. * - * @example + * **Example** (Modifying a value at a key) + * * ```ts * import { Record } from "effect" * @@ -597,7 +638,7 @@ export const modify: { * Record.modify(input, "b", f) // Option.none() * ``` * - * @category utils + * @category mutations * @since 2.0.0 */ (self: ReadonlyRecord, key: NoInfer, f: (a: A) => B): Option.Option> @@ -614,9 +655,16 @@ export const modify: { ) /** - * Replaces a value in the record with the new value passed as parameter. + * Replaces the value at an existing key safely and returns the updated record in + * `Option.some`. + * + * **Details** + * + * If the key is not present, returns `Option.none()` and leaves the record + * unchanged. + * + * **Example** (Replacing a value at a key) * - * @example * ```ts * import { Record } from "effect" * @@ -624,14 +672,21 @@ export const modify: { * Record.replace(Record.empty(), "a", 10) // Option.none() * ``` * - * @category utils + * @category mutations * @since 2.0.0 */ export const replace: { /** - * Replaces a value in the record with the new value passed as parameter. + * Replaces the value at an existing key safely and returns the updated record in + * `Option.some`. + * + * **Details** + * + * If the key is not present, returns `Option.none()` and leaves the record + * unchanged. + * + * **Example** (Replacing a value at a key) * - * @example * ```ts * import { Record } from "effect" * @@ -639,14 +694,21 @@ export const replace: { * Record.replace(Record.empty(), "a", 10) // Option.none() * ``` * - * @category utils + * @category mutations * @since 2.0.0 */ (key: NoInfer, b: B): (self: ReadonlyRecord) => Option.Option> /** - * Replaces a value in the record with the new value passed as parameter. + * Replaces the value at an existing key safely and returns the updated record in + * `Option.some`. + * + * **Details** + * + * If the key is not present, returns `Option.none()` and leaves the record + * unchanged. + * + * **Example** (Replacing a value at a key) * - * @example * ```ts * import { Record } from "effect" * @@ -654,7 +716,7 @@ export const replace: { * Record.replace(Record.empty(), "a", 10) // Option.none() * ``` * - * @category utils + * @category mutations * @since 2.0.0 */ (self: ReadonlyRecord, key: NoInfer, b: B): Option.Option> @@ -668,10 +730,19 @@ export const replace: { ) /** - * If the given key exists in the record, returns a new record with the key removed. - * If the key does not exist, returns a shallow copy of the original record. + * Removes a key from a record. + * + * **When to use** + * + * Use to create a shallow copy of a record without one property. + * + * **Details** + * + * If the key is not present, the result is still a shallow copy of the original + * record. + * + * **Example** (Removing a key) * - * @example * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -679,15 +750,24 @@ export const replace: { * assert.deepStrictEqual(Record.remove({ a: 1, b: 2 }, "a"), { b: 2 }) * ``` * - * @category utils + * @category mutations * @since 2.0.0 */ export const remove: { /** - * If the given key exists in the record, returns a new record with the key removed. - * If the key does not exist, returns a shallow copy of the original record. + * Removes a key from a record. + * + * **When to use** + * + * Use to create a shallow copy of a record without one property. + * + * **Details** + * + * If the key is not present, the result is still a shallow copy of the original + * record. + * + * **Example** (Removing a key) * - * @example * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -695,15 +775,24 @@ export const remove: { * assert.deepStrictEqual(Record.remove({ a: 1, b: 2 }, "a"), { b: 2 }) * ``` * - * @category utils + * @category mutations * @since 2.0.0 */ (key: X): (self: ReadonlyRecord) => Record, A> /** - * If the given key exists in the record, returns a new record with the key removed. - * If the key does not exist, returns a shallow copy of the original record. + * Removes a key from a record. + * + * **When to use** + * + * Use to create a shallow copy of a record without one property. + * + * **Details** + * + * If the key is not present, the result is still a shallow copy of the original + * record. + * + * **Example** (Removing a key) * - * @example * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -711,7 +800,7 @@ export const remove: { * assert.deepStrictEqual(Record.remove({ a: 1, b: 2 }, "a"), { b: 2 }) * ``` * - * @category utils + * @category mutations * @since 2.0.0 */ (self: ReadonlyRecord, key: X): Record, A> @@ -728,11 +817,12 @@ export const remove: { ) /** - * Retrieves the value of the property with the given `key` from a record and returns an `Option` + * Retrieves the value of the property with the given `key` from a record safely and returns an `Option` * of a tuple with the value and the record with the removed property. * If the key is not present, returns `Option.none()`. * - * @example + * **Example** (Popping a value and removing its key) + * * ```ts * import { Record } from "effect" * @@ -742,16 +832,17 @@ export const remove: { * Record.pop(input, "c") // Option.none() * ``` * - * @category utils + * @category mutations * @since 2.0.0 */ export const pop: { /** - * Retrieves the value of the property with the given `key` from a record and returns an `Option` + * Retrieves the value of the property with the given `key` from a record safely and returns an `Option` * of a tuple with the value and the record with the removed property. * If the key is not present, returns `Option.none()`. * - * @example + * **Example** (Popping a value and removing its key) + * * ```ts * import { Record } from "effect" * @@ -761,16 +852,17 @@ export const pop: { * Record.pop(input, "c") // Option.none() * ``` * - * @category utils + * @category mutations * @since 2.0.0 */ (key: X): (self: ReadonlyRecord) => Option.Option<[A, Record, A>]> /** - * Retrieves the value of the property with the given `key` from a record and returns an `Option` + * Retrieves the value of the property with the given `key` from a record safely and returns an `Option` * of a tuple with the value and the record with the removed property. * If the key is not present, returns `Option.none()`. * - * @example + * **Example** (Popping a value and removing its key) + * * ```ts * import { Record } from "effect" * @@ -780,7 +872,7 @@ export const pop: { * Record.pop(input, "c") // Option.none() * ``` * - * @category utils + * @category mutations * @since 2.0.0 */ (self: ReadonlyRecord, key: X): Option.Option<[A, Record, A>]> @@ -793,7 +885,8 @@ export const pop: { /** * Maps a record into another record by applying a transformation function to each of its values. * - * @example + * **Example** (Mapping record values) + * * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -814,7 +907,8 @@ export const map: { /** * Maps a record into another record by applying a transformation function to each of its values. * - * @example + * **Example** (Mapping record values) + * * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -835,7 +929,8 @@ export const map: { /** * Maps a record into another record by applying a transformation function to each of its values. * - * @example + * **Example** (Mapping record values) + * * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -867,7 +962,8 @@ export const map: { /** * Maps the keys of a `ReadonlyRecord` while preserving the corresponding values. * - * @example + * **Example** (Mapping record keys) + * * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -885,7 +981,8 @@ export const mapKeys: { /** * Maps the keys of a `ReadonlyRecord` while preserving the corresponding values. * - * @example + * **Example** (Mapping record keys) + * * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -903,7 +1000,8 @@ export const mapKeys: { /** * Maps the keys of a `ReadonlyRecord` while preserving the corresponding values. * - * @example + * **Example** (Mapping record keys) + * * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -936,7 +1034,8 @@ export const mapKeys: { /** * Maps entries of a `ReadonlyRecord` using the provided function, allowing modification of both keys and corresponding values. * - * @example + * **Example** (Mapping record entries) + * * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -954,7 +1053,8 @@ export const mapEntries: { /** * Maps entries of a `ReadonlyRecord` using the provided function, allowing modification of both keys and corresponding values. * - * @example + * **Example** (Mapping record entries) + * * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -972,7 +1072,8 @@ export const mapEntries: { /** * Maps entries of a `ReadonlyRecord` using the provided function, allowing modification of both keys and corresponding values. * - * @example + * **Example** (Mapping record entries) + * * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -1006,7 +1107,8 @@ export const mapEntries: { * Transforms a record by applying the function `f` to each key and value in the original record. * If the function succeeds, the key-value pair is included in the output record. * - * @example + * **Example** (Filtering and mapping with Result) + * * ```ts * import { Record, Result } from "effect" * import * as assert from "node:assert" @@ -1024,7 +1126,8 @@ export const filterMap: { * Transforms a record by applying the function `f` to each key and value in the original record. * If the function succeeds, the key-value pair is included in the output record. * - * @example + * **Example** (Filtering and mapping with Result) + * * ```ts * import { Record, Result } from "effect" * import * as assert from "node:assert" @@ -1042,7 +1145,8 @@ export const filterMap: { * Transforms a record by applying the function `f` to each key and value in the original record. * If the function succeeds, the key-value pair is included in the output record. * - * @example + * **Example** (Filtering and mapping with Result) + * * ```ts * import { Record, Result } from "effect" * import * as assert from "node:assert" @@ -1076,7 +1180,8 @@ export const filterMap: { /** * Selects properties from a record whose values match the given predicate. * - * @example + * **Example** (Filtering record values) + * * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -1092,7 +1197,8 @@ export const filter: { /** * Selects properties from a record whose values match the given predicate. * - * @example + * **Example** (Filtering record values) + * * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -1108,7 +1214,8 @@ export const filter: { /** * Selects properties from a record whose values match the given predicate. * - * @example + * **Example** (Filtering record values) + * * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -1124,7 +1231,8 @@ export const filter: { /** * Selects properties from a record whose values match the given predicate. * - * @example + * **Example** (Filtering record values) + * * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -1140,7 +1248,8 @@ export const filter: { /** * Selects properties from a record whose values match the given predicate. * - * @example + * **Example** (Filtering record values) + * * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -1170,9 +1279,11 @@ export const filter: { ) /** - * Given a record with `Option` values, returns a new record containing only the `Some` values, preserving the original keys. + * Returns a new record containing only the `Some` values from a record of + * `Option` values, preserving the original keys. + * + * **Example** (Extracting Some values) * - * @example * ```ts * import { Option, Record } from "effect" * import * as assert from "node:assert" @@ -1202,9 +1313,11 @@ export const getSomes: ( } /** - * Given a record with `Result` values, returns a new record containing only the `Err` values, preserving the original keys. + * Returns a new record containing only the `Err` values from a record of + * `Result` values, preserving the original keys. + * + * **Example** (Extracting Result failures) * - * @example * ```ts * import { Record, Result } from "effect" * import * as assert from "node:assert" @@ -1220,7 +1333,7 @@ export const getSomes: ( * ``` * * @category filtering - * @since 2.0.0 + * @since 4.0.0 */ export const getFailures = ( self: ReadonlyRecord> @@ -1237,9 +1350,11 @@ export const getFailures = ( } /** - * Given a record with `Result` values, returns a new record containing only the `Ok` values, preserving the original keys. + * Returns a new record containing only the `Ok` values from a record of + * `Result` values, preserving the original keys. + * + * **Example** (Extracting Result successes) * - * @example * ```ts * import { Record, Result } from "effect" * import * as assert from "node:assert" @@ -1255,7 +1370,7 @@ export const getFailures = ( * ``` * * @category filtering - * @since 2.0.0 + * @since 4.0.0 */ export const getSuccesses = ( self: ReadonlyRecord> @@ -1272,9 +1387,16 @@ export const getSuccesses = ( } /** - * Partitions the elements of a record into two groups: those that match a filter, and those that don't. + * Applies a function to each record entry and partitions the returned `Result` + * values into two records. + * + * **Details** + * + * Failure values are collected in the left record, and success values are + * collected in the right record, preserving the original keys. + * + * **Example** (Partitioning with Result) * - * @example * ```ts * import { Record, Result } from "effect" * import * as assert from "node:assert" @@ -1289,9 +1411,16 @@ export const getSuccesses = ( */ export const partition: { /** - * Partitions the elements of a record into two groups: those that match a filter, and those that don't. + * Applies a function to each record entry and partitions the returned `Result` + * values into two records. + * + * **Details** + * + * Failure values are collected in the left record, and success values are + * collected in the right record, preserving the original keys. + * + * **Example** (Partitioning with Result) * - * @example * ```ts * import { Record, Result } from "effect" * import * as assert from "node:assert" @@ -1308,9 +1437,16 @@ export const partition: { self: ReadonlyRecord ) => [left: Record, B>, right: Record, C>] /** - * Partitions the elements of a record into two groups: those that match a filter, and those that don't. + * Applies a function to each record entry and partitions the returned `Result` + * values into two records. + * + * **Details** + * + * Failure values are collected in the left record, and success values are + * collected in the right record, preserving the original keys. + * + * **Example** (Partitioning with Result) * - * @example * ```ts * import { Record, Result } from "effect" * import * as assert from "node:assert" @@ -1348,7 +1484,8 @@ export const partition: { * Partitions a record of `Result` values into two separate records, * one with the `Err` values and one with the `Ok` values. * - * @example + * **Example** (Separating Result values) + * * ```ts * import { Record, Result } from "effect" * import * as assert from "node:assert" @@ -1367,9 +1504,10 @@ export const separate: ( ) => [Record, A>, Record, B>] = partition(identity) /** - * Retrieve the keys of a given record as an array. + * Retrieves the keys of a given record as an array. + * + * **Example** (Getting record keys) * - * @example * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -1384,9 +1522,10 @@ export const keys = (self: ReadonlyRecord): Object.keys(self) as Array /** - * Retrieve the values of a given record as an array. + * Retrieves the values of a given record as an array. + * + * **Example** (Getting record values) * - * @example * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -1400,9 +1539,10 @@ export const keys = (self: ReadonlyRecord): export const values = (self: ReadonlyRecord): Array => collect(self, (_, a) => a) /** - * Add a new key-value pair or update an existing key's value in a record. + * Adds a new key-value pair or update an existing key's value in a record. + * + * **Example** (Setting a record value) * - * @example * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -1411,14 +1551,15 @@ export const values = (self: ReadonlyRecord): Array(key: K1, value: B): (self: ReadonlyRecord) => Record /** - * Add a new key-value pair or update an existing key's value in a record. + * Adds a new key-value pair or update an existing key's value in a record. + * + * **Example** (Setting a record value) * - * @example * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -1443,7 +1585,7 @@ export const set: { * assert.deepStrictEqual(Record.set("c", 5)({ a: 1, b: 2 }), { a: 1, b: 2, c: 5 }) * ``` * - * @category utils + * @category mutations * @since 2.0.0 */ (self: ReadonlyRecord, key: K1, value: B): Record @@ -1459,24 +1601,33 @@ export const set: { ) /** - * Check if all the keys and values in one record are also found in another record. + * Checks whether all the keys and values in one record are also found in another record. * Uses the provided equivalence function to compare values. * - * @example - * ```ts - * import { Equal, Record } from "effect" - * import * as assert from "node:assert" + * **Example** (Checking subrecords with a custom equivalence) * - * const isSubrecord = Record.isSubrecordBy(Equal.asEquivalence()) + * ```ts + * import { Equivalence, Record } from "effect" * - * assert.deepStrictEqual( - * Record.isSubrecord({ a: 1 } as Record, { a: 1, b: 2 }), - * true - * ) - * assert.deepStrictEqual( - * Record.isSubrecord({ a: 1, b: 2 }, { a: 1 } as Record), - * false + * const isSubrecord = Record.isSubrecordBy( + * Equivalence.make((self, that) => self.toLowerCase() === that.toLowerCase()) * ) + * + * const required: Record.ReadonlyRecord = { role: "Admin" } + * const available: Record.ReadonlyRecord = { + * role: "admin", + * status: "active" + * } + * + * console.log( + * isSubrecord(required, available) + * ) // true + * console.log( + * isSubrecord({ role: "Admin", status: "inactive" }, available) + * ) // false + * console.log( + * isSubrecord(required, { role: "editor", status: "active" }) + * ) // false * ``` * * @category predicates @@ -1496,10 +1647,15 @@ export const isSubrecordBy = (equivalence: Equivalence): { }) /** - * Check if one record is a subrecord of another, meaning it contains all the keys and values found in the second record. - * This comparison uses default equality checks (`Equal.equivalence()`). + * Checks whether the first record is a subrecord of the second record. + * + * **Details** + * + * Returns `true` when every key and value in `self` is also present in `that`. + * Values are compared with Effect equality via `Equal.asEquivalence()`. + * + * **Example** (Checking subrecords) * - * @example * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -1519,10 +1675,15 @@ export const isSubrecordBy = (equivalence: Equivalence): { */ export const isSubrecord: { /** - * Check if one record is a subrecord of another, meaning it contains all the keys and values found in the second record. - * This comparison uses default equality checks (`Equal.equivalence()`). + * Checks whether the first record is a subrecord of the second record. + * + * **Details** + * + * Returns `true` when every key and value in `self` is also present in `that`. + * Values are compared with Effect equality via `Equal.asEquivalence()`. + * + * **Example** (Checking subrecords) * - * @example * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -1542,10 +1703,15 @@ export const isSubrecord: { */ (that: ReadonlyRecord): (self: ReadonlyRecord) => boolean /** - * Check if one record is a subrecord of another, meaning it contains all the keys and values found in the second record. - * This comparison uses default equality checks (`Equal.equivalence()`). + * Checks whether the first record is a subrecord of the second record. + * + * **Details** + * + * Returns `true` when every key and value in `self` is also present in `that`. + * Values are compared with Effect equality via `Equal.asEquivalence()`. + * + * **Example** (Checking subrecords) * - * @example * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -1567,9 +1733,10 @@ export const isSubrecord: { } = isSubrecordBy(Equal.asEquivalence()) /** - * Reduce a record to a single value by combining its entries with a specified function. + * Reduces a record to a single value by combining its entries with a specified function. + * + * **Example** (Reducing record values) * - * @example * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -1585,9 +1752,10 @@ export const isSubrecord: { */ export const reduce: { /** - * Reduce a record to a single value by combining its entries with a specified function. + * Reduces a record to a single value by combining its entries with a specified function. + * + * **Example** (Reducing record values) * - * @example * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -1603,9 +1771,10 @@ export const reduce: { */ (zero: Z, f: (accumulator: Z, value: V, key: K) => Z): (self: ReadonlyRecord) => Z /** - * Reduce a record to a single value by combining its entries with a specified function. + * Reduces a record to a single value by combining its entries with a specified function. + * + * **Example** (Reducing record values) * - * @example * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -1640,9 +1809,10 @@ export const reduce: { ) /** - * Check if all entries in a record meet a specific condition. + * Checks whether all entries in a record meet a specific condition. + * + * **Example** (Checking every record value) * - * @example * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -1656,9 +1826,10 @@ export const reduce: { */ export const every: { /** - * Check if all entries in a record meet a specific condition. + * Checks whether all entries in a record meet a specific condition. + * + * **Example** (Checking every record value) * - * @example * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -1672,9 +1843,10 @@ export const every: { */ (refinement: (value: A, key: K) => value is B): (self: ReadonlyRecord) => self is ReadonlyRecord /** - * Check if all entries in a record meet a specific condition. + * Checks whether all entries in a record meet a specific condition. + * + * **Example** (Checking every record value) * - * @example * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -1688,9 +1860,10 @@ export const every: { */ (predicate: (value: A, key: K) => boolean): (self: ReadonlyRecord) => boolean /** - * Check if all entries in a record meet a specific condition. + * Checks whether all entries in a record meet a specific condition. + * + * **Example** (Checking every record value) * - * @example * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -1704,9 +1877,10 @@ export const every: { */ (self: ReadonlyRecord, refinement: (value: A, key: K) => value is B): self is ReadonlyRecord /** - * Check if all entries in a record meet a specific condition. + * Checks whether all entries in a record meet a specific condition. + * + * **Example** (Checking every record value) * - * @example * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -1735,9 +1909,10 @@ export const every: { ) /** - * Check if any entry in a record meets a specific condition. + * Checks whether any entry in a record meets a specific condition. + * + * **Example** (Checking for any matching value) * - * @example * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -1751,9 +1926,10 @@ export const every: { */ export const some: { /** - * Check if any entry in a record meets a specific condition. + * Checks whether any entry in a record meets a specific condition. + * + * **Example** (Checking for any matching value) * - * @example * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -1767,9 +1943,10 @@ export const some: { */ (predicate: (value: A, key: K) => boolean): (self: ReadonlyRecord) => boolean /** - * Check if any entry in a record meets a specific condition. + * Checks whether any entry in a record meets a specific condition. + * + * **Example** (Checking for any matching value) * - * @example * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -1795,10 +1972,11 @@ export const some: { ) /** - * Merge two records, preserving entries that exist in either of the records. + * Merges two records, preserving entries that exist in either of the records. * For keys that exist in both records, the provided combine function is used to merge the values. * - * @example + * **Example** (Merging records with union) + * * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -1814,10 +1992,11 @@ export const some: { */ export const union: { /** - * Merge two records, preserving entries that exist in either of the records. + * Merges two records, preserving entries that exist in either of the records. * For keys that exist in both records, the provided combine function is used to merge the values. * - * @example + * **Example** (Merging records with union) + * * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -1833,10 +2012,11 @@ export const union: { */ (that: ReadonlyRecord, combine: (selfValue: A, thatValue: B) => C): (self: ReadonlyRecord) => Record /** - * Merge two records, preserving entries that exist in either of the records. + * Merges two records, preserving entries that exist in either of the records. * For keys that exist in both records, the provided combine function is used to merge the values. * - * @example + * **Example** (Merging records with union) + * * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -1886,10 +2066,11 @@ export const union: { ) /** - * Merge two records, retaining only the entries that exist in both records. + * Merges two records, retaining only the entries that exist in both records. * For intersecting keys, the provided combine function is used to merge the values. * - * @example + * **Example** (Merging intersecting keys) + * * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -1905,10 +2086,11 @@ export const union: { */ export const intersection: { /** - * Merge two records, retaining only the entries that exist in both records. + * Merges two records, retaining only the entries that exist in both records. * For intersecting keys, the provided combine function is used to merge the values. * - * @example + * **Example** (Merging intersecting keys) + * * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -1924,10 +2106,11 @@ export const intersection: { */ (that: ReadonlyRecord, combine: (selfValue: A, thatValue: B) => C): (self: ReadonlyRecord) => Record, C> /** - * Merge two records, retaining only the entries that exist in both records. + * Merges two records, retaining only the entries that exist in both records. * For intersecting keys, the provided combine function is used to merge the values. * - * @example + * **Example** (Merging intersecting keys) + * * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -1967,10 +2150,11 @@ export const intersection: { ) /** - * Merge two records, preserving only the entries that are unique to each record. + * Merges two records, preserving only the entries that are unique to each record. * Keys that exist in both records are excluded from the result. * - * @example + * **Example** (Keeping keys unique to each record) + * * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -1986,10 +2170,11 @@ export const intersection: { */ export const difference: { /** - * Merge two records, preserving only the entries that are unique to each record. + * Merges two records, preserving only the entries that are unique to each record. * Keys that exist in both records are excluded from the result. * - * @example + * **Example** (Keeping keys unique to each record) + * * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -2005,10 +2190,11 @@ export const difference: { */ (that: ReadonlyRecord): (self: ReadonlyRecord) => Record /** - * Merge two records, preserving only the entries that are unique to each record. + * Merges two records, preserving only the entries that are unique to each record. * Keys that exist in both records are excluded from the result. * - * @example + * **Example** (Keeping keys unique to each record) + * * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -2051,7 +2237,8 @@ export const difference: { * Create an `Equivalence` for records using the provided `Equivalence` for values. * Two records are considered equivalent if they have the same keys and their corresponding values are equivalent. * - * @example + * **Example** (Comparing records with a value equivalence) + * * ```ts * import { Equal, Record } from "effect" * import * as assert from "node:assert" @@ -2063,7 +2250,7 @@ export const difference: { * ``` * * @category instances - * @since 2.0.0 + * @since 4.0.0 */ export const makeEquivalence = ( equivalence: Equivalence @@ -2075,7 +2262,8 @@ export const makeEquivalence = ( /** * Create a non-empty record from a single element. * - * @example + * **Example** (Creating a singleton record) + * * ```ts * import { Record } from "effect" * import * as assert from "node:assert" @@ -2091,10 +2279,25 @@ export const singleton = (key: K, value: A): Recor } as any) /** - * A `Reducer` for combining `Record`s using union. + * Creates a `Reducer` for combining `Record`s using union, with values for keys that exist in both records combined + * using the provided `Combiner`. * - * Values for keys that exist in both records are combined using the provided `Combiner`. + * **When to use** * + * Use to build a reusable reducer for accumulating many records into one + * union-shaped record, preserving keys from every input and combining + * overlapping values with the supplied combiner. + * + * **Details** + * + * The returned reducer uses `Record.union` for combine and an empty record as + * `initialValue`, so the default `combineAll` folds from `{}` and accumulates + * keys from each input record. + * + * @see {@link union} for one-off record merging with the same union semantics + * @see {@link makeReducerIntersection} for a reducer that keeps only keys present on both sides + * + * @category combining * @since 4.0.0 */ export function makeReducerUnion(combiner: Combiner.Combiner): Reducer.Reducer> { @@ -2105,10 +2308,24 @@ export function makeReducerUnion(combiner: Combiner.Combine } /** - * A `Reducer` for combining `Record`s using intersection. + * Creates a `Reducer` whose `combine` operation intersects two records and + * combines values for keys present in both records. * - * Values are combined using the provided `Combiner`. + * **When to use** * + * Use to build a `Reducer` that combines records by retaining only keys shared + * by both inputs and combining matching values with a `Combiner`. + * + * **Gotchas** + * + * The reducer's `initialValue` is an empty record. Because intersection with + * an empty record is empty, the default `combineAll` folds from `{}` and + * therefore produces `{}` for ordinary non-empty inputs. + * + * @see {@link makeReducerUnion} for a reducer that preserves keys from either input record + * @see {@link intersection} for applying the shared-key merge to one pair of records + * + * @category combining * @since 4.0.0 */ export function makeReducerIntersection( @@ -2124,7 +2341,8 @@ export function makeReducerIntersection( * Returns the first entry that satisfies the specified * predicate, or `None` if no such entry exists. * - * @example + * **Example** (Finding the first matching entry) + * * ```ts * import { Record } from "effect" * @@ -2144,7 +2362,8 @@ export const findFirst: { * Returns the first entry that satisfies the specified * predicate, or `None` if no such entry exists. * - * @example + * **Example** (Finding the first matching entry) + * * ```ts * import { Record } from "effect" * @@ -2164,7 +2383,8 @@ export const findFirst: { * Returns the first entry that satisfies the specified * predicate, or `None` if no such entry exists. * - * @example + * **Example** (Finding the first matching entry) + * * ```ts * import { Record } from "effect" * @@ -2184,7 +2404,8 @@ export const findFirst: { * Returns the first entry that satisfies the specified * predicate, or `None` if no such entry exists. * - * @example + * **Example** (Finding the first matching entry) + * * ```ts * import { Record } from "effect" * @@ -2207,7 +2428,8 @@ export const findFirst: { * Returns the first entry that satisfies the specified * predicate, or `None` if no such entry exists. * - * @example + * **Example** (Finding the first matching entry) + * * ```ts * import { Record } from "effect" * diff --git a/.opencode/node_modules/effect/src/Redactable.ts b/.opencode/node_modules/effect/src/Redactable.ts index 5a929d35e2fbcd89027721bafac5e877f45f149b..23aeb260542877a07012d92909af5dfe8d5c4568 100644 --- a/.opencode/node_modules/effect/src/Redactable.ts +++ b/.opencode/node_modules/effect/src/Redactable.ts @@ -6,64 +6,6 @@ * Typical use cases include masking secrets, tokens, or personal data in logs, traces, * and serialized output. * - * ## Mental model - * - * - **Redactable** - an object that implements `[symbolRedactable]`, a method - * that receives the current `Context` and returns a replacement value. - * - **symbolRedactable** - the well-known `Symbol` key that marks an object as - * redactable. - * - **redact** - the primary entry point: pass any value and get back either its - * redacted form (if it is `Redactable`) or the original value unchanged. - * - **getRedacted** - lower-level helper that calls `[symbolRedactable]` directly - * on a value already known to be `Redactable`. - * - The `Context` passed to `[symbolRedactable]` comes from the current fiber. - * If no fiber is active, an empty `Context` is used. - * - * ## Common tasks - * - * - **Make a value redactable**: implement the {@link Redactable} interface by - * adding a `[symbolRedactable]` method. - * - **Redact an unknown value**: call {@link redact} - it returns the original - * value when it is not redactable. - * - **Check if a value is redactable**: use {@link isRedactable}. - * - **Get the redacted form of a known `Redactable`**: use {@link getRedacted}. - * - * ## Gotchas - * - * - `[symbolRedactable]` receives the fiber's `Context` as its argument. - * - Outside of an Effect runtime (no current fiber), `getRedacted` still works - * but passes an empty `Context`, so service lookups will not find anything. - * - `redact` is not recursive: if a redactable object contains nested - * redactable values, only the outermost redaction is applied. - * - * ## Quickstart - * - * **Example** (Masking an API key) - * - * ```ts - * import { Context, Redactable } from "effect" - * - * class ApiKey { - * constructor(readonly raw: string) {} - * - * [Redactable.symbolRedactable](_ctx: Context.Context) { - * return this.raw.slice(0, 4) + "..." - * } - * } - * - * const key = new ApiKey("sk-1234567890abcdef") - * - * console.log(Redactable.isRedactable(key)) // true - * console.log(Redactable.redact(key)) // "sk-1..." - * console.log(Redactable.redact("plain")) // "plain" - * ``` - * - * ## See also - * - * - {@link Redactable} - the interface to implement - * - {@link symbolRedactable} - the symbol key - * - {@link redact} - the main redaction entry point - * * @since 4.0.0 */ import type * as Context from "./Context.ts" @@ -71,15 +13,19 @@ import { pipeArguments } from "./Pipeable.ts" import { hasProperty } from "./Predicate.ts" /** - * Symbol used to identify objects that implement the {@link Redactable} + * Defines the symbol used to identify objects that implement the {@link Redactable} * protocol. * - * Add a method under this key to make an object redactable. The method - * receives the current `Context` and must return the replacement value. + * **When to use** + * + * Use as the property key when implementing the `Redactable` protocol. * - * - Use this symbol as the property key when implementing {@link Redactable}. - * - Registered globally via `Symbol.for("~effect/Redactable")`, - * so it is identical across multiple copies of the library at runtime. + * **Details** + * + * Add a method under this key to make an object redactable. The method receives + * the current `Context` and must return the replacement value. The symbol is + * registered globally via `Symbol.for("~effect/Redactable")`, so it is + * identical across multiple copies of the library at runtime. * * **Example** (Masking an API key) * @@ -95,22 +41,25 @@ import { hasProperty } from "./Predicate.ts" * } * ``` * - * See also: - * - {@link Redactable} - the interface this symbol belongs to - * - {@link isRedactable} - check whether a value has this symbol - * - * @since 4.0.0 - * @category symbol + * @see {@link Redactable} for the interface this symbol belongs to + * @see {@link isRedactable} to check whether a value has this symbol + * @category symbols + * @since 3.10.0 */ export const symbolRedactable: unique symbol = Symbol.for("~effect/Redactable") /** * Interface for objects that provide context-aware redacted representations. * - * - Implement this interface on any class or object that holds sensitive data - * and should present a sanitized form when inspected or logged. - * - The `[symbolRedactable]` method receives the current fiber's `Context`. - * - If no fiber is active, an empty `Context` is provided. + * **When to use** + * + * Use to define classes or objects that hold sensitive data and should present + * a sanitized form when inspected or logged. + * + * **Details** + * + * The `[symbolRedactable]` method receives the current fiber's `Context`. If no + * fiber is active, an empty `Context` is provided. * * **Example** (Masking an API key) * @@ -126,13 +75,11 @@ export const symbolRedactable: unique symbol = Symbol.for("~effect/Redactable") * } * ``` * - * See also: - * - {@link symbolRedactable} - the symbol key to implement - * - {@link redact} - apply redaction to any value - * - {@link isRedactable} - type guard for this interface - * - * @since 4.0.0 - * @category Model + * @see {@link symbolRedactable} for the symbol key to implement + * @see {@link redact} to apply redaction to any value + * @see {@link isRedactable} for the type guard for this interface + * @category models + * @since 3.10.0 */ export interface Redactable { readonly [symbolRedactable]: (context: Context.Context) => unknown @@ -142,32 +89,40 @@ export interface Redactable { * Type guard that checks whether a value implements the {@link Redactable} * interface. * - * See also: - * - {@link Redactable} - the interface being checked - * - {@link redact} - applies redaction if the value is redactable + * **When to use** * - * @since 4.0.0 + * Use to narrow an unknown value before calling redaction-specific helpers. + * + * @see {@link Redactable} for the interface being checked + * @see {@link redact} to apply redaction if the value is redactable * @category guards + * @since 3.10.0 */ export const isRedactable = (u: unknown): u is Redactable => hasProperty(u, symbolRedactable) /** - * Redacts a value if it implements {@link Redactable}, otherwise returns it + * Returns a redacted value if it implements {@link Redactable}, otherwise returns it * unchanged. * - * - Use this as the general-purpose entry point for redaction: it is safe to - * call on any value. - * - Internally calls {@link isRedactable} and, if `true`, delegates to - * {@link getRedacted}. - * - Not recursive: nested redactable values inside the returned object are not - * automatically redacted. - * - Pure with respect to its argument (does not mutate the input). + * **When to use** * - * See also: - * - {@link isRedactable} - check before redacting - * - {@link getRedacted} - lower-level variant for known redactables + * Use as the general-purpose entry point for redaction when the input may + * or may not implement the redaction protocol. * - * @since 4.0.0 + * **Details** + * + * This function calls {@link isRedactable} and, when it returns `true`, + * delegates to {@link getRedacted}. + * + * **Gotchas** + * + * Redaction is not recursive. Nested redactable values inside the returned + * object are not automatically redacted. + * + * @see {@link isRedactable} to check before redacting + * @see {@link getRedacted} for the lower-level variant for known redactables + * @category destructors + * @since 3.10.0 */ export function redact(u: unknown): unknown { if (isRedactable(u)) return getRedacted(u) @@ -175,20 +130,26 @@ export function redact(u: unknown): unknown { } /** - * Calls `[symbolRedactable]` on a value that is already known to be - * {@link Redactable} and returns the result. + * Returns the result of calling `[symbolRedactable]` on a value that is + * already known to be {@link Redactable}. + * + * **When to use** + * + * Use when you need to read the redacted representation from a value already + * verified as `Redactable`. + * + * **Details** + * + * This function reads the current fiber's `Context` from the global fiber + * reference and passes it to the redaction method. * - * - Use this when you have already verified the value is `Redactable` (e.g., - * via {@link isRedactable}) and want to avoid a second check. - * - Reads the current fiber's `Context` from the global fiber reference. If - * no fiber is active, an empty `Context` is passed to the redaction - * method. - * - Does not mutate the input. + * **Gotchas** * - * See also: - * - {@link redact} - higher-level variant that handles non-redactable values - * - {@link isRedactable} - type guard to verify before calling this + * If no fiber is active, an empty `Context` is passed to the redaction method. * + * @see {@link redact} for the higher-level variant that handles non-redactable values + * @see {@link isRedactable} for the type guard to verify before calling this + * @category destructors * @since 4.0.0 */ export function getRedacted(redactable: Redactable): unknown { diff --git a/.opencode/node_modules/effect/src/Redacted.ts b/.opencode/node_modules/effect/src/Redacted.ts index 8fbbd2a173a4a39617858003f30d4f2e5d043488..afb1eb698828fd6cedd954cad19eb6d7305eb7dc 100644 --- a/.opencode/node_modules/effect/src/Redacted.ts +++ b/.opencode/node_modules/effect/src/Redacted.ts @@ -1,8 +1,12 @@ /** - * The Redacted module provides functionality for handling sensitive information - * securely within your application. By using the `Redacted` data type, you can - * ensure that sensitive values are not accidentally exposed in logs or error - * messages. + * Wraps sensitive values so normal output does not reveal them. + * + * A `Redacted` shows a redacted placeholder in string, JSON, and inspection + * output, while still storing the original value for trusted code that needs to + * recover it. This helps reduce accidental leaks in logs and diagnostics. This + * module includes constructors, runtime checks, value recovery, wiping of stored + * values, and comparison helpers that avoid exposing the wrapped value at the + * call site. * * @since 3.3.0 */ @@ -18,7 +22,23 @@ import type { Covariant } from "./Types.ts" const TypeId = "~effect/data/Redacted" /** - * @example + * A wrapper for sensitive values whose string, JSON, and inspection output is + * redacted. + * + * **When to use** + * + * Use to carry sensitive values while reducing accidental exposure in string, + * JSON, and inspection output. + * + * **Gotchas** + * + * The underlying value is still stored in memory and can be recovered with + * `Redacted.value` until the wrapper is wiped or becomes unreachable. Use + * `Redacted` to reduce accidental disclosure in logs and diagnostics, not as a + * cryptographic protection mechanism. + * + * **Example** (Creating redacted values) + * * ```ts * import { Redacted } from "effect" * @@ -29,15 +49,22 @@ const TypeId = "~effect/data/Redacted" * // TypeScript will infer the types as Redacted * ``` * - * @since 3.3.0 * @category models + * @since 3.3.0 */ export interface Redacted extends Redacted.Variance, Equal.Equal, Pipeable { readonly label: string | undefined } /** - * @example + * Namespace containing type-level members associated with `Redacted` values. + * + * **When to use** + * + * Use to access type-level helpers associated with `Redacted`. + * + * **Example** (Using namespace utilities) + * * ```ts * import { Redacted } from "effect" * @@ -49,23 +76,23 @@ export interface Redacted extends Redacted.Variance, Equal.Eq * ``` * * @since 3.3.0 - * @category namespace */ export declare namespace Redacted { /** - * @example - * ```ts - * import { Redacted } from "effect" + * Type-level variance marker for `Redacted`. * - * // Variance interface ensures type safety for covariant type parameter - * const stringSecret = Redacted.make("secret") - * const numberSecret = Redacted.make(42) + * **When to use** * - * // TypeScript will infer the types with proper variance - * ``` + * Use when defining internals that need to preserve the covariant value type + * carried by `Redacted`. + * + * **Details** + * + * This interface records the covariant value type carried by a `Redacted` + * value and is not normally referenced directly by users. * - * @since 3.3.0 * @category models + * @since 3.3.0 */ export interface Variance { readonly [TypeId]: { @@ -74,23 +101,47 @@ export declare namespace Redacted { } /** - * @example + * Extracts the underlying value type from a `Redacted` type. + * + * **When to use** + * + * Use to infer the sensitive value type from an existing `Redacted` type. + * + * **Example** (Extracting the redacted value type) + * * ```ts * import { Redacted } from "effect" * - * // Extract the value type from a Redacted instance - * const secret = Redacted.make("my-secret") - * const extractedValue: string = Redacted.value(secret) + * type ApiKey = Redacted.Redacted<{ readonly token: string }> + * type ApiKeyValue = Redacted.Redacted.Value + * + * const rotate = (value: ApiKeyValue): ApiKeyValue => ({ + * token: `${value.token}:rotated` + * }) + * + * console.log(rotate({ token: "secret" })) // { token: "secret:rotated" } * ``` * + * @category utility types * @since 3.3.0 - * @category type-level */ export type Value> = [T] extends [Redacted] ? _A : never } /** - * @example + * Returns `true` if a value is a `Redacted` wrapper. + * + * **When to use** + * + * Use to validate unknown input and narrow it to `Redacted`. + * + * **Details** + * + * When this function returns `true`, TypeScript narrows the value to + * `Redacted`. + * + * **Example** (Checking for redacted values) + * * ```ts * import { Redacted } from "effect" * @@ -101,24 +152,35 @@ export declare namespace Redacted { * console.log(Redacted.isRedacted(plainString)) // false * ``` * - * @since 3.3.0 * @category refinements + * @since 3.3.0 */ export const isRedacted = (u: unknown): u is Redacted => hasProperty(u, TypeId) /** - * This function creates a `Redacted` instance from a given value `A`, - * securely hiding its content. + * Creates a `Redacted` wrapper for a sensitive value. + * + * **When to use** + * + * Use to wrap a sensitive value so normal string, JSON, and inspection output + * is redacted. + * + * **Details** + * + * The wrapper redacts string, JSON, and inspection output to reduce accidental + * disclosure. The original value remains retrievable with `Redacted.value` + * until the wrapper is wiped or becomes unreachable. + * + * **Example** (Creating a redacted value) * - * @example * ```ts * import { Redacted } from "effect" * * const API_KEY = Redacted.make("1234567890") * ``` * - * @since 3.3.0 * @category constructors + * @since 3.3.0 */ export const make = (value: T, options?: { readonly label?: string | undefined @@ -161,7 +223,12 @@ const Proto = { * Retrieves the original value from a `Redacted` instance. Use this function * with caution, as it exposes the sensitive data. * - * @example + * **When to use** + * + * Use when you need the underlying sensitive value at a trusted boundary. + * + * **Example** (Retrieving a redacted value) + * * ```ts * import { Redacted } from "effect" * import * as assert from "node:assert" @@ -171,17 +238,28 @@ const Proto = { * assert.equal(Redacted.value(API_KEY), "1234567890") * ``` * - * @since 3.3.0 * @category getters + * @since 3.3.0 */ export const value: (self: Redacted) => T = redacted.value /** - * Erases the underlying value of a `Redacted` instance, rendering it unusable. - * This function is intended to ensure that sensitive data does not remain in - * memory longer than necessary. + * Deletes the stored value for a `Redacted` wrapper, making future + * `Redacted.value` calls on that wrapper fail. + * + * **When to use** + * + * Use when a `Redacted` wrapper should no longer be able to reveal its stored + * value. + * + * **Gotchas** + * + * This unsafe operation does not zero memory and does not affect other + * references to the original value. It only removes the value from the + * internal redacted registry. + * + * **Example** (Wiping a redacted value) * - * @example * ```ts * import { Redacted } from "effect" * import * as assert from "node:assert" @@ -198,8 +276,8 @@ export const value: (self: Redacted) => T = redacted.value * ) * ``` * - * @since 3.3.0 * @category unsafe + * @since 4.0.0 */ export const wipeUnsafe = (self: Redacted): boolean => redacted.redactedRegistry.delete(self) @@ -208,7 +286,13 @@ export const wipeUnsafe = (self: Redacted): boolean => redacted.redactedRe * equivalence relation for the underlying values `A`. This function is useful * for comparing `Redacted` instances without exposing their contents. * - * @example + * **When to use** + * + * Use when you need to compare wrapped secrets through an approved equality + * rule without exposing the underlying values at each comparison site. + * + * **Example** (Comparing redacted values) + * * ```ts * import { Equivalence, Redacted } from "effect" * import * as assert from "node:assert" @@ -223,8 +307,8 @@ export const wipeUnsafe = (self: Redacted): boolean => redacted.redactedRe * assert.equal(equivalence(API_KEY1, API_KEY3), true) * ``` * - * @category equivalence - * @since 3.3.0 + * @category instances + * @since 4.0.0 */ export const makeEquivalence = (isEquivalent: Equivalence.Equivalence): Equivalence.Equivalence> => Equivalence.make((x, y) => isEquivalent(value(x), value(y))) diff --git a/.opencode/node_modules/effect/src/Reducer.ts b/.opencode/node_modules/effect/src/Reducer.ts index a53c0a2dd54f6bd7a8a8964430fd89399fd01f14..be546bc5043b40a2e87420231a4bd748af459456 100644 --- a/.opencode/node_modules/effect/src/Reducer.ts +++ b/.opencode/node_modules/effect/src/Reducer.ts @@ -1,68 +1,9 @@ /** - * A module for reducing collections of values into a single result. - * - * A `Reducer` extends {@link Combiner.Combiner} by adding an - * `initialValue` (identity element) and a `combineAll` method that folds an - * entire collection. Think `Array.prototype.reduce`, but packaged as a - * reusable, composable value. - * - * ## Mental model - * - * - **Reducer** – a {@link Combiner.Combiner} plus an `initialValue` and a - * `combineAll` method. - * - **initialValue** – the neutral/identity element. Combining any value with - * `initialValue` should return the original value unchanged (e.g. `0` for - * addition, `""` for string concatenation). - * - **combineAll** – folds an `Iterable` starting from `initialValue`. - * When omitted from {@link make}, a default left-to-right fold is used. - * - **Purity** – all reducers produced by this module are pure; they never - * mutate their arguments. - * - **Composability** – reducers can be lifted into `Option`, `Struct`, - * `Tuple`, `Record`, and other container types via helpers in those modules. - * - **Subtype of Combiner** – every `Reducer` is also a valid - * `Combiner`, so you can pass a `Reducer` anywhere a `Combiner` is - * expected. - * - * ## Common tasks - * - * - Create a reducer from a combine function and initial value → {@link make} - * - Swap argument order → {@link flip} - * - Combine two values without an initial value → use {@link Combiner.Combiner} - * instead - * - * ## Gotchas - * - * - `combineAll` on an empty iterable returns `initialValue`, not an error. - * - The default `combineAll` folds left-to-right. If your `combine` is not - * associative, order matters. Pass a custom `combineAll` to {@link make} if - * you need different traversal or short-circuiting. - * - A `Reducer` is also a valid `Combiner` — but a `Combiner` is *not* a - * `Reducer` (it lacks `initialValue`). - * - * ## Quickstart - * - * **Example** (summing a list of numbers) - * - * ```ts - * import { Reducer } from "effect" - * - * const Sum = Reducer.make((a, b) => a + b, 0) - * - * console.log(Sum.combine(3, 4)) - * // Output: 7 - * - * console.log(Sum.combineAll([1, 2, 3, 4])) - * // Output: 10 - * - * console.log(Sum.combineAll([])) - * // Output: 0 - * ``` - * - * ## See also - * - * - {@link make} – the primary constructor - * - {@link Reducer} – the core interface - * - {@link Combiner.Combiner} – the parent interface (no `initialValue`) + * Reusable strategies for reducing many values into one value. A `Reducer` + * extends `Combiner.Combiner` with an `initialValue` for empty collections and + * a `combineAll` method for folding an entire iterable. This module provides a + * constructor for reducers and a helper for reversing the order in which values + * are combined. * * @since 4.0.0 */ @@ -73,23 +14,28 @@ import type * as Combiner from "./Combiner.ts" * Represents a strategy for reducing a collection of values of type `A` into * a single result. * - * Extends {@link Combiner.Combiner} with: - * - `initialValue` – the identity/neutral element for `combine`. - * - `combineAll` – folds an entire `Iterable` from `initialValue`. + * **When to use** * - * When to use: - * - You need to fold/reduce a collection into a single value. + * Use when you need to fold/reduce a collection into a single value. * - You want a reusable reducing strategy that can be passed to library * functions like `Struct.makeReducer`, `Option.makeReducer`, or * `Record.makeReducerUnion`. * - You need both the combining logic *and* a known starting value. * + * **Details** + * + * Extends {@link Combiner.Combiner} with: + * + * - `initialValue` – the identity/neutral element for `combine`. + * - `combineAll` – folds an entire `Iterable` from `initialValue`. + * * Many modules ship pre-built reducers: + * * - `Number.ReducerSum`, `Number.ReducerMultiply` * - `String.ReducerConcat` * - `Boolean.ReducerAnd`, `Boolean.ReducerOr` * - * **Example** (string concatenation reducer) + * **Example** (String concatenation reducer) * * ```ts * import { Reducer } from "effect" @@ -103,32 +49,45 @@ import type * as Combiner from "./Combiner.ts" * @see {@link make} – create a `Reducer` from a function and initial value * @see {@link Combiner.Combiner} – parent interface without `initialValue` * - * @category model + * @category models * @since 4.0.0 */ export interface Reducer extends Combiner.Combiner { - /** Neutral starting value (combining with this changes nothing). */ + /** + * Neutral starting value (combining with this changes nothing). + * + * **When to use** + * + * Use to seed a reduction and represent the result of reducing an empty collection. + */ readonly initialValue: A - /** Combines all values in the collection, starting from `initialValue`. */ + /** + * Combines all values in the collection, starting from `initialValue`. + * + * **When to use** + * + * Use to reduce an iterable with this reducer's initial value and combining operation. + */ readonly combineAll: (collection: Iterable) => A } /** * Creates a `Reducer` from a `combine` function and an `initialValue`. * - * When to use: - * - You have a custom reducing operation not covered by a pre-built reducer. + * **When to use** + * + * Use when you have a custom reducing operation not covered by a pre-built reducer. * - You want to provide an optimized `combineAll` (e.g. short-circuiting on * a known absorbing element like `0` for multiplication). * - * Behavior: + * **Details** + * * - If `combineAll` is omitted, a default left-to-right fold starting from * `initialValue` is used. * - If `combineAll` is provided, it completely replaces the default fold. - * - Pure – the returned reducer does not mutate its arguments. * - * **Example** (multiplication with short-circuit) + * **Example** (Multiplication with short-circuit) * * ```ts * import { Reducer } from "effect" @@ -156,6 +115,7 @@ export interface Reducer extends Combiner.Combiner { * @see {@link Reducer} – the interface this creates * @see {@link flip} – reverse the argument order * + * @category constructors * @since 4.0.0 */ export function make( @@ -180,20 +140,20 @@ export function make( /** * Reverses the argument order of a reducer's `combine` method. * - * When to use: - * - You need the "right" value to act as the accumulator side. - * - You want to reverse the natural direction of a non-commutative reducer - * (e.g. string concatenation becomes prepend). + * **When to use** + * + * Use when you want the right-hand value to act as the accumulator, or need to + * reverse a non-commutative reducer such as string concatenation. + * + * **Details** * - * Behavior: * - Returns a new `Reducer` where `combine(self, that)` calls the original * reducer as `combine(that, self)`. * - The `initialValue` is preserved from the original reducer. * - The `combineAll` is re-derived from the flipped `combine` (using the * default left-to-right fold), not carried over from the original. - * - Does not mutate the input reducer. * - * **Example** (reversing string concatenation) + * **Example** (Reversing string concatenation) * * ```ts * import { Reducer, String } from "effect" @@ -210,6 +170,7 @@ export function make( * @see {@link make} * @see {@link Combiner.flip} – the same operation on a plain `Combiner` * + * @category combinators * @since 4.0.0 */ export function flip(reducer: Reducer): Reducer { diff --git a/.opencode/node_modules/effect/src/Ref.ts b/.opencode/node_modules/effect/src/Ref.ts index df0dc71bbdc582f9b6899e7af3fb78202ed810a5..b6619b9dd6e1601b67cdb1d9cd24a9fdea5be3e7 100644 --- a/.opencode/node_modules/effect/src/Ref.ts +++ b/.opencode/node_modules/effect/src/Ref.ts @@ -1,30 +1,12 @@ /** - * This module provides utilities for working with mutable references in a functional context. + * Stores fiber-safe mutable state inside Effect programs. * - * A Ref is a mutable reference that can be read, written, and atomically modified. Unlike plain - * mutable variables, Refs are thread-safe and work seamlessly with Effect's concurrency model. - * They provide atomic operations for safe state management in concurrent programs. - * - * @example - * ```ts - * import { Effect, Ref } from "effect" - * - * const program = Effect.gen(function*() { - * // Create a ref with initial value - * const counter = yield* Ref.make(0) - * - * // Atomic operations - * yield* Ref.update(counter, (n) => n + 1) - * yield* Ref.update(counter, (n) => n * 2) - * - * const value = yield* Ref.get(counter) - * console.log(value) // 2 - * - * // Atomic modify with return value - * const previous = yield* Ref.getAndSet(counter, 100) - * console.log(previous) // 2 - * }) - * ``` + * A `Ref` holds one value and exposes reads, writes, and atomic + * transformations as effects, so state changes compose with Effect's + * concurrency model. This module includes constructors, safe and unsafe reads, + * set and get-and-set helpers, update and modify helpers, and conditional + * update variants that leave the value unchanged when an `Option.none` result + * is returned. * * @since 2.0.0 */ @@ -41,11 +23,18 @@ const TypeId = "~effect/Ref" /** * A mutable reference that provides atomic read, write, and update operations. * - * Ref is a thread-safe mutable reference type that allows for atomic operations - * on shared state. It supports both simple read/write operations and complex - * atomic transformations. + * **When to use** + * + * Use to keep shared mutable state that is read and updated inside Effect + * programs. + * + * **Details** + * + * A `Ref` is a thread-safe mutable reference type for shared state. It supports + * simple read and write operations as well as atomic transformations. + * + * **Example** (Reading and updating a ref) * - * @example * ```ts * import { Effect, Ref } from "effect" * @@ -66,8 +55,12 @@ const TypeId = "~effect/Ref" * }) * ``` * - * @since 2.0.0 + * @see {@link make} for creating a `Ref` + * @see {@link get} for reading the current value + * @see {@link set} for replacing the current value + * * @category models + * @since 2.0.0 */ export interface Ref extends Ref.Variance, Pipeable { readonly ref: MutableRef.MutableRef @@ -76,14 +69,22 @@ export interface Ref extends Ref.Variance, Pipeable { /** * The Ref namespace containing type definitions and utilities. * + * **When to use** + * + * Use when referring to type members nested under the `Ref` namespace. + * * @since 2.0.0 - * @category models */ export declare namespace Ref { /** * Variance interface for Ref types, defining the type parameter constraints. * - * @example + * **When to use** + * + * Use when working with the type-level variance marker carried by `Ref`. + * + * **Example** (Using invariant refs) + * * ```ts * import { Effect, Ref } from "effect" * @@ -98,8 +99,8 @@ export declare namespace Ref { * }) * ``` * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface Variance { readonly [TypeId]: { @@ -124,10 +125,17 @@ const RefProto = { /** * Creates a new Ref with the specified initial value (unsafe version). * - * This function creates a Ref synchronously without wrapping in Effect. - * Use this only when you're sure about the safety of immediate creation. + * **When to use** + * + * Use when you need immediate synchronous construction and can guarantee + * that creating the `Ref` outside of `Effect` is safe. + * + * **Gotchas** + * + * Prefer `Ref.make` for Effect-wrapped creation in Effect programs. + * + * **Example** (Creating a ref unsafely) * - * @example * ```ts * import { Ref } from "effect" * @@ -142,8 +150,8 @@ const RefProto = { * // Prefer Ref.make for Effect-wrapped creation * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const makeUnsafe = (value: A): Ref => { const self = Object.create(RefProto) @@ -154,10 +162,12 @@ export const makeUnsafe = (value: A): Ref => { /** * Creates a new Ref with the specified initial value. * - * @param value - The initial value for the Ref - * @returns An Effect that creates a new Ref + * **When to use** + * + * Use to create a `Ref` for shared mutable state inside an Effect program. + * + * **Example** (Creating a ref) * - * @example * ```ts * import { Effect, Ref } from "effect" * @@ -168,15 +178,22 @@ export const makeUnsafe = (value: A): Ref => { * }) * ``` * - * @since 2.0.0 + * @see {@link makeUnsafe} for synchronous construction outside Effect code + * * @category constructors + * @since 2.0.0 */ export const make = (value: A): Effect.Effect> => Effect.sync(() => makeUnsafe(value)) /** * Gets the current value of the Ref. * - * @example + * **When to use** + * + * Use to read the current `Ref` value without changing it. + * + * **Example** (Getting the current value) + * * ```ts * import { Effect, Ref } from "effect" * @@ -187,15 +204,22 @@ export const make = (value: A): Effect.Effect> => Effect.sync(() => ma * }) * ``` * - * @since 2.0.0 + * @see {@link set} for replacing the current value + * * @category getters + * @since 2.0.0 */ export const get = (self: Ref) => Effect.sync(() => self.ref.current) /** * Sets the value of the Ref to the specified value. * - * @example + * **When to use** + * + * Use to replace the current `Ref` value with a known value. + * + * **Example** (Setting a value) + * * ```ts * import { Effect, Ref } from "effect" * @@ -215,14 +239,22 @@ export const get = (self: Ref) => Effect.sync(() => self.ref.current) * }) * ``` * - * @since 2.0.0 + * @see {@link getAndSet} for setting while returning the previous value + * @see {@link setAndGet} for setting while returning the new value + * * @category setters + * @since 2.0.0 */ export const set = dual< /** * Sets the value of the Ref to the specified value. * - * @example + * **When to use** + * + * Use to replace the current `Ref` value with a known value. + * + * **Example** (Setting a value) + * * ```ts * import { Effect, Ref } from "effect" * @@ -242,14 +274,22 @@ export const set = dual< * }) * ``` * - * @since 2.0.0 + * @see {@link getAndSet} for setting while returning the previous value + * @see {@link setAndGet} for setting while returning the new value + * * @category setters + * @since 2.0.0 */ (value: A) => (self: Ref) => Effect.Effect, /** * Sets the value of the Ref to the specified value. * - * @example + * **When to use** + * + * Use to replace the current `Ref` value with a known value. + * + * **Example** (Setting a value) + * * ```ts * import { Effect, Ref } from "effect" * @@ -269,18 +309,24 @@ export const set = dual< * }) * ``` * - * @since 2.0.0 + * @see {@link getAndSet} for setting while returning the previous value + * @see {@link setAndGet} for setting while returning the new value + * * @category setters + * @since 2.0.0 */ (self: Ref, value: A) => Effect.Effect >(2, (self: Ref, value: A) => Effect.sync(() => MutableRef.set(self.ref, value))) /** - * Atomically gets the current value of the Ref and sets it to the specified value. + * Gets the current value of the Ref, sets it to the specified value, and returns the previous value atomically. + * + * **When to use** * - * Returns the value that was in the Ref before the update. + * Use to replace a plain `Ref` value while returning the previous value. + * + * **Example** (Replacing a value atomically) * - * @example * ```ts * import { Effect, Ref } from "effect" * @@ -296,16 +342,22 @@ export const set = dual< * }) * ``` * + * @see {@link set} for setting without returning the previous value + * @see {@link getAndUpdate} for deriving the new value from the previous value + * + * @category mutations * @since 2.0.0 - * @category utils */ export const getAndSet = dual< /** - * Atomically gets the current value of the Ref and sets it to the specified value. + * Gets the current value of the Ref, sets it to the specified value, and returns the previous value atomically. + * + * **When to use** + * + * Use to replace a plain `Ref` value while returning the previous value. * - * Returns the value that was in the Ref before the update. + * **Example** (Replacing a value atomically) * - * @example * ```ts * import { Effect, Ref } from "effect" * @@ -321,16 +373,22 @@ export const getAndSet = dual< * }) * ``` * + * @see {@link set} for setting without returning the previous value + * @see {@link getAndUpdate} for deriving the new value from the previous value + * + * @category mutations * @since 2.0.0 - * @category utils */ (value: A) => (self: Ref) => Effect.Effect, /** - * Atomically gets the current value of the Ref and sets it to the specified value. + * Gets the current value of the Ref, sets it to the specified value, and returns the previous value atomically. + * + * **When to use** * - * Returns the value that was in the Ref before the update. + * Use to replace a plain `Ref` value while returning the previous value. + * + * **Example** (Replacing a value atomically) * - * @example * ```ts * import { Effect, Ref } from "effect" * @@ -346,8 +404,11 @@ export const getAndSet = dual< * }) * ``` * + * @see {@link set} for setting without returning the previous value + * @see {@link getAndUpdate} for deriving the new value from the previous value + * + * @category mutations * @since 2.0.0 - * @category utils */ (self: Ref, value: A) => Effect.Effect >(2, (self: Ref, value: A) => @@ -358,11 +419,14 @@ export const getAndSet = dual< })) /** - * Atomically gets the current value of the Ref and updates it with the given function. + * Gets the current value of the Ref, updates it with the given function, and returns the previous value atomically. * - * Returns the value that was in the Ref before the update. + * **When to use** + * + * Use to derive a new `Ref` value while returning the previous value. + * + * **Example** (Updating and returning the previous value) * - * @example * ```ts * import { Effect, Ref } from "effect" * @@ -378,16 +442,22 @@ export const getAndSet = dual< * }) * ``` * + * @see {@link update} for updating without returning the previous value + * @see {@link updateAndGet} for returning the new value instead + * + * @category mutations * @since 2.0.0 - * @category utils */ export const getAndUpdate = dual< /** - * Atomically gets the current value of the Ref and updates it with the given function. + * Gets the current value of the Ref, updates it with the given function, and returns the previous value atomically. + * + * **When to use** * - * Returns the value that was in the Ref before the update. + * Use to derive a new `Ref` value while returning the previous value. + * + * **Example** (Updating and returning the previous value) * - * @example * ```ts * import { Effect, Ref } from "effect" * @@ -403,16 +473,22 @@ export const getAndUpdate = dual< * }) * ``` * + * @see {@link update} for updating without returning the previous value + * @see {@link updateAndGet} for returning the new value instead + * + * @category mutations * @since 2.0.0 - * @category utils */ (f: (a: A) => A) => (self: Ref) => Effect.Effect, /** - * Atomically gets the current value of the Ref and updates it with the given function. + * Gets the current value of the Ref, updates it with the given function, and returns the previous value atomically. + * + * **When to use** + * + * Use to derive a new `Ref` value while returning the previous value. * - * Returns the value that was in the Ref before the update. + * **Example** (Updating and returning the previous value) * - * @example * ```ts * import { Effect, Ref } from "effect" * @@ -428,8 +504,11 @@ export const getAndUpdate = dual< * }) * ``` * + * @see {@link update} for updating without returning the previous value + * @see {@link updateAndGet} for returning the new value instead + * + * @category mutations * @since 2.0.0 - * @category utils */ (self: Ref, f: (a: A) => A) => Effect.Effect >(2, (self: Ref, f: (a: A) => A) => @@ -440,16 +519,22 @@ export const getAndUpdate = dual< })) /** - * Atomically gets the current value of the Ref and updates it with the given partial function. + * Gets the current value of the Ref and updates it atomically with the given partial function. + * + * **When to use** + * + * Use to return the previous `Ref` value while applying a conditional update. + * + * **Details** * - * If the partial function returns `Option.some`, the Ref is updated with the new value. - * If it returns `Option.none`, the Ref is left unchanged. - * Always returns the value that was in the Ref before the attempted update. + * If the partial function returns `Option.some`, the Ref is updated with the + * new value. If it returns `Option.none`, the Ref is left unchanged. The effect + * always returns the value that was in the Ref before the attempted update. + * + * **Example** (Conditionally updating and returning the previous value) * - * @example * ```ts - * import { Effect, Ref } from "effect" - * import * as Option from "effect/Option" + * import { Effect, Option, Ref } from "effect" * * const program = Effect.gen(function*() { * const counter = yield* Ref.make(5) @@ -476,21 +561,30 @@ export const getAndUpdate = dual< * }) * ``` * + * @see {@link getAndUpdate} for always applying an update + * @see {@link updateSome} for conditional updates without returning the previous value + * + * @category mutations * @since 2.0.0 - * @category utils */ export const getAndUpdateSome = dual< /** - * Atomically gets the current value of the Ref and updates it with the given partial function. + * Gets the current value of the Ref and updates it atomically with the given partial function. + * + * **When to use** + * + * Use to return the previous `Ref` value while applying a conditional update. + * + * **Details** + * + * If the partial function returns `Option.some`, the Ref is updated with the + * new value. If it returns `Option.none`, the Ref is left unchanged. The effect + * always returns the value that was in the Ref before the attempted update. * - * If the partial function returns `Option.some`, the Ref is updated with the new value. - * If it returns `Option.none`, the Ref is left unchanged. - * Always returns the value that was in the Ref before the attempted update. + * **Example** (Conditionally updating and returning the previous value) * - * @example * ```ts - * import { Effect, Ref } from "effect" - * import * as Option from "effect/Option" + * import { Effect, Option, Ref } from "effect" * * const program = Effect.gen(function*() { * const counter = yield* Ref.make(5) @@ -517,21 +611,30 @@ export const getAndUpdateSome = dual< * }) * ``` * + * @see {@link getAndUpdate} for always applying an update + * @see {@link updateSome} for conditional updates without returning the previous value + * + * @category mutations * @since 2.0.0 - * @category utils */ (pf: (a: A) => Option.Option) => (self: Ref) => Effect.Effect, /** - * Atomically gets the current value of the Ref and updates it with the given partial function. + * Gets the current value of the Ref and updates it atomically with the given partial function. + * + * **When to use** + * + * Use to return the previous `Ref` value while applying a conditional update. * - * If the partial function returns `Option.some`, the Ref is updated with the new value. - * If it returns `Option.none`, the Ref is left unchanged. - * Always returns the value that was in the Ref before the attempted update. + * **Details** + * + * If the partial function returns `Option.some`, the Ref is updated with the + * new value. If it returns `Option.none`, the Ref is left unchanged. The effect + * always returns the value that was in the Ref before the attempted update. + * + * **Example** (Conditionally updating and returning the previous value) * - * @example * ```ts - * import { Effect, Ref } from "effect" - * import * as Option from "effect/Option" + * import { Effect, Option, Ref } from "effect" * * const program = Effect.gen(function*() { * const counter = yield* Ref.make(5) @@ -558,8 +661,11 @@ export const getAndUpdateSome = dual< * }) * ``` * + * @see {@link getAndUpdate} for always applying an update + * @see {@link updateSome} for conditional updates without returning the previous value + * + * @category mutations * @since 2.0.0 - * @category utils */ (self: Ref, pf: (a: A) => Option.Option) => Effect.Effect >(2, (self: Ref, pf: (a: A) => Option.Option) => @@ -573,11 +679,15 @@ export const getAndUpdateSome = dual< })) /** - * Atomically sets the value of the Ref to the specified value and returns the new value. + * Sets the value of the Ref atomically to the specified value and returns the new value. * - * This is useful when you want to set a value and immediately get it back in one atomic operation. + * **When to use** + * + * Use when you want to set a `Ref` value and immediately get it back in one + * atomic operation. + * + * **Example** (Setting and returning the new value) * - * @example * ```ts * import { Effect, Ref } from "effect" * @@ -602,16 +712,20 @@ export const getAndUpdateSome = dual< * }) * ``` * + * @category mutations * @since 2.0.0 - * @category utils */ export const setAndGet = dual< /** - * Atomically sets the value of the Ref to the specified value and returns the new value. + * Sets the value of the Ref atomically to the specified value and returns the new value. + * + * **When to use** + * + * Use when you want to set a `Ref` value and immediately get it back in one + * atomic operation. * - * This is useful when you want to set a value and immediately get it back in one atomic operation. + * **Example** (Setting and returning the new value) * - * @example * ```ts * import { Effect, Ref } from "effect" * @@ -636,16 +750,20 @@ export const setAndGet = dual< * }) * ``` * + * @category mutations * @since 2.0.0 - * @category utils */ (value: A) => (self: Ref) => Effect.Effect, /** - * Atomically sets the value of the Ref to the specified value and returns the new value. + * Sets the value of the Ref atomically to the specified value and returns the new value. * - * This is useful when you want to set a value and immediately get it back in one atomic operation. + * **When to use** + * + * Use when you want to set a `Ref` value and immediately get it back in one + * atomic operation. + * + * **Example** (Setting and returning the new value) * - * @example * ```ts * import { Effect, Ref } from "effect" * @@ -670,19 +788,28 @@ export const setAndGet = dual< * }) * ``` * + * @category mutations * @since 2.0.0 - * @category utils */ (self: Ref, value: A) => Effect.Effect >(2, (self: Ref, value: A) => Effect.sync(() => self.ref.current = value)) /** - * Atomically modifies the value of the Ref using the given function. + * Modifies the value of the Ref atomically using the given function. + * + * **When to use** * - * The function receives the current value and returns a tuple of [result, newValue]. - * The Ref is updated with the newValue and the result is returned. + * Use to compute both a separate return value and the next stored `Ref` value + * in one atomic update. + * + * **Details** + * + * The function receives the current value and returns a tuple of + * `[result, newValue]`. The Ref is updated with `newValue`, and `result` is + * returned by the effect. + * + * **Example** (Modifying a value atomically) * - * @example * ```ts * import { Effect, Ref } from "effect" * @@ -714,17 +841,29 @@ export const setAndGet = dual< * }) * ``` * - * @since 2.0.0 + * @see {@link updateAndGet} for returning the new stored value + * @see {@link modifySome} for optionally updating while returning a separate result + * * @category setters + * @since 2.0.0 */ export const modify = dual< /** - * Atomically modifies the value of the Ref using the given function. + * Modifies the value of the Ref atomically using the given function. + * + * **When to use** + * + * Use to compute both a separate return value and the next stored `Ref` value + * in one atomic update. * - * The function receives the current value and returns a tuple of [result, newValue]. - * The Ref is updated with the newValue and the result is returned. + * **Details** + * + * The function receives the current value and returns a tuple of + * `[result, newValue]`. The Ref is updated with `newValue`, and `result` is + * returned by the effect. + * + * **Example** (Modifying a value atomically) * - * @example * ```ts * import { Effect, Ref } from "effect" * @@ -756,17 +895,29 @@ export const modify = dual< * }) * ``` * - * @since 2.0.0 + * @see {@link updateAndGet} for returning the new stored value + * @see {@link modifySome} for optionally updating while returning a separate result + * * @category setters + * @since 2.0.0 */ (f: (a: A) => readonly [B, A]) => (self: Ref) => Effect.Effect, /** - * Atomically modifies the value of the Ref using the given function. + * Modifies the value of the Ref atomically using the given function. + * + * **When to use** + * + * Use to compute both a separate return value and the next stored `Ref` value + * in one atomic update. * - * The function receives the current value and returns a tuple of [result, newValue]. - * The Ref is updated with the newValue and the result is returned. + * **Details** + * + * The function receives the current value and returns a tuple of + * `[result, newValue]`. The Ref is updated with `newValue`, and `result` is + * returned by the effect. + * + * **Example** (Modifying a value atomically) * - * @example * ```ts * import { Effect, Ref } from "effect" * @@ -798,8 +949,11 @@ export const modify = dual< * }) * ``` * - * @since 2.0.0 + * @see {@link updateAndGet} for returning the new stored value + * @see {@link modifySome} for optionally updating while returning a separate result + * * @category setters + * @since 2.0.0 */ (self: Ref, f: (a: A) => readonly [B, A]) => Effect.Effect >(2, (self, f) => @@ -810,16 +964,23 @@ export const modify = dual< })) /** - * Atomically modifies the value of the Ref using the given partial function. + * Computes a result atomically and optionally updates the value of the `Ref`. + * + * **When to use** + * + * Use to compute a return value while optionally updating a plain `Ref`. + * + * **Details** * - * The function receives the current value and returns an Option of [result, newValue]. - * If the function returns `Option.some([result, newValue])`, the Ref is updated with newValue and result is returned. - * If it returns `Option.none()`, the Ref is left unchanged and the fallback value is returned. + * The callback receives the current value and returns `[result, nextValue]`, + * where `nextValue` is an `Option`. If `nextValue` is `Option.some(value)`, + * the `Ref` is updated to `value`; if it is `Option.none()`, the `Ref` is left + * unchanged. The returned effect always succeeds with `result`. + * + * **Example** (Conditionally modifying a value) * - * @example * ```ts - * import { Effect, Ref } from "effect" - * import * as Option from "effect/Option" + * import { Effect, Option, Ref } from "effect" * * const program = Effect.gen(function*() { * const counter = yield* Ref.make(5) @@ -854,21 +1015,31 @@ export const modify = dual< * }) * ``` * - * @since 2.0.0 + * @see {@link modify} for always storing a new value + * @see {@link updateSome} for optional updates without a separate return value + * * @category setters + * @since 2.0.0 */ export const modifySome: { /** - * Atomically modifies the value of the Ref using the given partial function. + * Computes a result atomically and optionally updates the value of the `Ref`. + * + * **When to use** + * + * Use to compute a return value while optionally updating a plain `Ref`. + * + * **Details** * - * The function receives the current value and returns an Option of [result, newValue]. - * If the function returns `Option.some([result, newValue])`, the Ref is updated with newValue and result is returned. - * If it returns `Option.none()`, the Ref is left unchanged and the fallback value is returned. + * The callback receives the current value and returns `[result, nextValue]`, + * where `nextValue` is an `Option`. If `nextValue` is `Option.some(value)`, + * the `Ref` is updated to `value`; if it is `Option.none()`, the `Ref` is left + * unchanged. The returned effect always succeeds with `result`. + * + * **Example** (Conditionally modifying a value) * - * @example * ```ts - * import { Effect, Ref } from "effect" - * import * as Option from "effect/Option" + * import { Effect, Option, Ref } from "effect" * * const program = Effect.gen(function*() { * const counter = yield* Ref.make(5) @@ -903,21 +1074,31 @@ export const modifySome: { * }) * ``` * - * @since 2.0.0 + * @see {@link modify} for always storing a new value + * @see {@link updateSome} for optional updates without a separate return value + * * @category setters + * @since 2.0.0 */ (pf: (a: A) => readonly [B, Option.Option]): (self: Ref) => Effect.Effect /** - * Atomically modifies the value of the Ref using the given partial function. + * Computes a result atomically and optionally updates the value of the `Ref`. + * + * **When to use** + * + * Use to compute a return value while optionally updating a plain `Ref`. + * + * **Details** * - * The function receives the current value and returns an Option of [result, newValue]. - * If the function returns `Option.some([result, newValue])`, the Ref is updated with newValue and result is returned. - * If it returns `Option.none()`, the Ref is left unchanged and the fallback value is returned. + * The callback receives the current value and returns `[result, nextValue]`, + * where `nextValue` is an `Option`. If `nextValue` is `Option.some(value)`, + * the `Ref` is updated to `value`; if it is `Option.none()`, the `Ref` is left + * unchanged. The returned effect always succeeds with `result`. + * + * **Example** (Conditionally modifying a value) * - * @example * ```ts - * import { Effect, Ref } from "effect" - * import * as Option from "effect/Option" + * import { Effect, Option, Ref } from "effect" * * const program = Effect.gen(function*() { * const counter = yield* Ref.make(5) @@ -952,22 +1133,32 @@ export const modifySome: { * }) * ``` * - * @since 2.0.0 + * @see {@link modify} for always storing a new value + * @see {@link updateSome} for optional updates without a separate return value + * * @category setters + * @since 2.0.0 */ (self: Ref, pf: (a: A) => readonly [B, Option.Option]): Effect.Effect } = dual< /** - * Atomically modifies the value of the Ref using the given partial function. + * Computes a result atomically and optionally updates the value of the `Ref`. + * + * **When to use** + * + * Use to compute a return value while optionally updating a plain `Ref`. * - * The function receives the current value and returns an Option of [result, newValue]. - * If the function returns `Option.some([result, newValue])`, the Ref is updated with newValue and result is returned. - * If it returns `Option.none()`, the Ref is left unchanged and the fallback value is returned. + * **Details** + * + * The callback receives the current value and returns `[result, nextValue]`, + * where `nextValue` is an `Option`. If `nextValue` is `Option.some(value)`, + * the `Ref` is updated to `value`; if it is `Option.none()`, the `Ref` is left + * unchanged. The returned effect always succeeds with `result`. + * + * **Example** (Conditionally modifying a value) * - * @example * ```ts - * import { Effect, Ref } from "effect" - * import * as Option from "effect/Option" + * import { Effect, Option, Ref } from "effect" * * const program = Effect.gen(function*() { * const counter = yield* Ref.make(5) @@ -1002,21 +1193,31 @@ export const modifySome: { * }) * ``` * - * @since 2.0.0 + * @see {@link modify} for always storing a new value + * @see {@link updateSome} for optional updates without a separate return value + * * @category setters + * @since 2.0.0 */ (pf: (a: A) => readonly [B, Option.Option]) => (self: Ref) => Effect.Effect, /** - * Atomically modifies the value of the Ref using the given partial function. + * Computes a result atomically and optionally updates the value of the `Ref`. + * + * **When to use** + * + * Use to compute a return value while optionally updating a plain `Ref`. * - * The function receives the current value and returns an Option of [result, newValue]. - * If the function returns `Option.some([result, newValue])`, the Ref is updated with newValue and result is returned. - * If it returns `Option.none()`, the Ref is left unchanged and the fallback value is returned. + * **Details** + * + * The callback receives the current value and returns `[result, nextValue]`, + * where `nextValue` is an `Option`. If `nextValue` is `Option.some(value)`, + * the `Ref` is updated to `value`; if it is `Option.none()`, the `Ref` is left + * unchanged. The returned effect always succeeds with `result`. + * + * **Example** (Conditionally modifying a value) * - * @example * ```ts - * import { Effect, Ref } from "effect" - * import * as Option from "effect/Option" + * import { Effect, Option, Ref } from "effect" * * const program = Effect.gen(function*() { * const counter = yield* Ref.make(5) @@ -1051,8 +1252,11 @@ export const modifySome: { * }) * ``` * - * @since 2.0.0 + * @see {@link modify} for always storing a new value + * @see {@link updateSome} for optional updates without a separate return value + * * @category setters + * @since 2.0.0 */ (self: Ref, pf: (a: A) => readonly [B, Option.Option]) => Effect.Effect >(2, (self, pf) => @@ -1062,9 +1266,14 @@ export const modifySome: { })) /** - * Atomically updates the value of the Ref using the given function. + * Updates the value of the Ref atomically using the given function. + * + * **When to use** + * + * Use to apply a `Ref` state transition without returning a value. + * + * **Example** (Updating a value) * - * @example * ```ts * import { Effect, Ref } from "effect" * @@ -1087,14 +1296,22 @@ export const modifySome: { * }) * ``` * - * @since 2.0.0 + * @see {@link updateAndGet} for returning the new value + * @see {@link getAndUpdate} for returning the previous value + * * @category setters + * @since 2.0.0 */ export const update = dual< /** - * Atomically updates the value of the Ref using the given function. + * Updates the value of the Ref atomically using the given function. + * + * **When to use** + * + * Use to apply a `Ref` state transition without returning a value. + * + * **Example** (Updating a value) * - * @example * ```ts * import { Effect, Ref } from "effect" * @@ -1117,14 +1334,22 @@ export const update = dual< * }) * ``` * - * @since 2.0.0 + * @see {@link updateAndGet} for returning the new value + * @see {@link getAndUpdate} for returning the previous value + * * @category setters + * @since 2.0.0 */ (f: (a: A) => A) => (self: Ref) => Effect.Effect, /** - * Atomically updates the value of the Ref using the given function. + * Updates the value of the Ref atomically using the given function. + * + * **When to use** + * + * Use to apply a `Ref` state transition without returning a value. + * + * **Example** (Updating a value) * - * @example * ```ts * import { Effect, Ref } from "effect" * @@ -1147,8 +1372,11 @@ export const update = dual< * }) * ``` * - * @since 2.0.0 + * @see {@link updateAndGet} for returning the new value + * @see {@link getAndUpdate} for returning the previous value + * * @category setters + * @since 2.0.0 */ (self: Ref, f: (a: A) => A) => Effect.Effect >(2, (self: Ref, f: (a: A) => A) => @@ -1157,9 +1385,14 @@ export const update = dual< })) /** - * Atomically updates the value of the Ref using the given function and returns the new value. + * Updates the value of the Ref atomically using the given function and returns the new value. + * + * **When to use** + * + * Use to apply a `Ref` state transition and return the new stored value. + * + * **Example** (Updating and returning the new value) * - * @example * ```ts * import { Effect, Ref } from "effect" * @@ -1176,14 +1409,22 @@ export const update = dual< * }) * ``` * + * @see {@link update} for updating without returning the new value + * @see {@link getAndUpdate} for returning the previous value instead + * + * @category mutations * @since 2.0.0 - * @category utils */ export const updateAndGet = dual< /** - * Atomically updates the value of the Ref using the given function and returns the new value. + * Updates the value of the Ref atomically using the given function and returns the new value. + * + * **When to use** + * + * Use to apply a `Ref` state transition and return the new stored value. + * + * **Example** (Updating and returning the new value) * - * @example * ```ts * import { Effect, Ref } from "effect" * @@ -1200,14 +1441,22 @@ export const updateAndGet = dual< * }) * ``` * + * @see {@link update} for updating without returning the new value + * @see {@link getAndUpdate} for returning the previous value instead + * + * @category mutations * @since 2.0.0 - * @category utils */ (f: (a: A) => A) => (self: Ref) => Effect.Effect, /** - * Atomically updates the value of the Ref using the given function and returns the new value. + * Updates the value of the Ref atomically using the given function and returns the new value. + * + * **When to use** + * + * Use to apply a `Ref` state transition and return the new stored value. + * + * **Example** (Updating and returning the new value) * - * @example * ```ts * import { Effect, Ref } from "effect" * @@ -1224,22 +1473,31 @@ export const updateAndGet = dual< * }) * ``` * + * @see {@link update} for updating without returning the new value + * @see {@link getAndUpdate} for returning the previous value instead + * + * @category mutations * @since 2.0.0 - * @category utils */ (self: Ref, f: (a: A) => A) => Effect.Effect >(2, (self: Ref, f: (a: A) => A) => Effect.sync(() => self.ref.current = f(self.ref.current))) /** - * Atomically updates the value of the Ref using the given partial function. + * Updates the value of the Ref atomically using the given partial function. + * + * **When to use** + * + * Use to apply a conditional `Ref` update without returning a value. + * + * **Details** * - * If the partial function returns `Option.some`, the Ref is updated with the new value. - * If it returns `Option.none`, the Ref is left unchanged. + * If the partial function returns `Option.some`, the Ref is updated with the + * new value. If it returns `Option.none`, the Ref is left unchanged. + * + * **Example** (Conditionally updating a value) * - * @example * ```ts - * import { Effect, Ref } from "effect" - * import * as Option from "effect/Option" + * import { Effect, Option, Ref } from "effect" * * const program = Effect.gen(function*() { * const counter = yield* Ref.make(5) @@ -1265,20 +1523,29 @@ export const updateAndGet = dual< * }) * ``` * - * @since 2.0.0 + * @see {@link update} for always applying an update + * @see {@link updateSomeAndGet} for returning the resulting current value + * * @category setters + * @since 2.0.0 */ export const updateSome = dual< /** - * Atomically updates the value of the Ref using the given partial function. + * Updates the value of the Ref atomically using the given partial function. + * + * **When to use** + * + * Use to apply a conditional `Ref` update without returning a value. + * + * **Details** * - * If the partial function returns `Option.some`, the Ref is updated with the new value. - * If it returns `Option.none`, the Ref is left unchanged. + * If the partial function returns `Option.some`, the Ref is updated with the + * new value. If it returns `Option.none`, the Ref is left unchanged. + * + * **Example** (Conditionally updating a value) * - * @example * ```ts - * import { Effect, Ref } from "effect" - * import * as Option from "effect/Option" + * import { Effect, Option, Ref } from "effect" * * const program = Effect.gen(function*() { * const counter = yield* Ref.make(5) @@ -1304,20 +1571,29 @@ export const updateSome = dual< * }) * ``` * - * @since 2.0.0 + * @see {@link update} for always applying an update + * @see {@link updateSomeAndGet} for returning the resulting current value + * * @category setters + * @since 2.0.0 */ (f: (a: A) => Option.Option) => (self: Ref) => Effect.Effect, /** - * Atomically updates the value of the Ref using the given partial function. + * Updates the value of the Ref atomically using the given partial function. + * + * **When to use** + * + * Use to apply a conditional `Ref` update without returning a value. * - * If the partial function returns `Option.some`, the Ref is updated with the new value. - * If it returns `Option.none`, the Ref is left unchanged. + * **Details** + * + * If the partial function returns `Option.some`, the Ref is updated with the + * new value. If it returns `Option.none`, the Ref is left unchanged. + * + * **Example** (Conditionally updating a value) * - * @example * ```ts - * import { Effect, Ref } from "effect" - * import * as Option from "effect/Option" + * import { Effect, Option, Ref } from "effect" * * const program = Effect.gen(function*() { * const counter = yield* Ref.make(5) @@ -1343,8 +1619,11 @@ export const updateSome = dual< * }) * ``` * - * @since 2.0.0 + * @see {@link update} for always applying an update + * @see {@link updateSomeAndGet} for returning the resulting current value + * * @category setters + * @since 2.0.0 */ (self: Ref, f: (a: A) => Option.Option) => Effect.Effect >(2, (self: Ref, f: (a: A) => Option.Option) => @@ -1356,16 +1635,23 @@ export const updateSome = dual< })) /** - * Atomically updates the value of the Ref using the given partial function and returns the current value. + * Updates the value of the Ref atomically using the given partial function and returns the current value. + * + * **When to use** + * + * Use to apply a conditional `Ref` update and return the resulting current + * value. * - * If the partial function returns `Option.some`, the Ref is updated with the new value. - * If it returns `Option.none`, the Ref is left unchanged. - * Returns the current value of the Ref after the potential update. + * **Details** + * + * If the partial function returns `Option.some`, the Ref is updated with the + * new value. If it returns `Option.none`, the Ref is left unchanged. The effect + * returns the current value of the Ref after the potential update. + * + * **Example** (Conditionally updating and returning the current value) * - * @example * ```ts - * import { Effect, Ref } from "effect" - * import * as Option from "effect/Option" + * import { Effect, Option, Ref } from "effect" * * const program = Effect.gen(function*() { * const counter = yield* Ref.make(10) @@ -1386,21 +1672,31 @@ export const updateSome = dual< * }) * ``` * + * @see {@link updateSome} for conditional updates without returning a value + * @see {@link updateAndGet} for always updating and returning the new value + * + * @category mutations * @since 2.0.0 - * @category utils */ export const updateSomeAndGet = dual< /** - * Atomically updates the value of the Ref using the given partial function and returns the current value. + * Updates the value of the Ref atomically using the given partial function and returns the current value. + * + * **When to use** + * + * Use to apply a conditional `Ref` update and return the resulting current + * value. + * + * **Details** * - * If the partial function returns `Option.some`, the Ref is updated with the new value. - * If it returns `Option.none`, the Ref is left unchanged. - * Returns the current value of the Ref after the potential update. + * If the partial function returns `Option.some`, the Ref is updated with the + * new value. If it returns `Option.none`, the Ref is left unchanged. The effect + * returns the current value of the Ref after the potential update. + * + * **Example** (Conditionally updating and returning the current value) * - * @example * ```ts - * import { Effect, Ref } from "effect" - * import * as Option from "effect/Option" + * import { Effect, Option, Ref } from "effect" * * const program = Effect.gen(function*() { * const counter = yield* Ref.make(10) @@ -1421,21 +1717,31 @@ export const updateSomeAndGet = dual< * }) * ``` * + * @see {@link updateSome} for conditional updates without returning a value + * @see {@link updateAndGet} for always updating and returning the new value + * + * @category mutations * @since 2.0.0 - * @category utils */ (pf: (a: A) => Option.Option) => (self: Ref) => Effect.Effect, /** - * Atomically updates the value of the Ref using the given partial function and returns the current value. + * Updates the value of the Ref atomically using the given partial function and returns the current value. + * + * **When to use** * - * If the partial function returns `Option.some`, the Ref is updated with the new value. - * If it returns `Option.none`, the Ref is left unchanged. - * Returns the current value of the Ref after the potential update. + * Use to apply a conditional `Ref` update and return the resulting current + * value. + * + * **Details** + * + * If the partial function returns `Option.some`, the Ref is updated with the + * new value. If it returns `Option.none`, the Ref is left unchanged. The effect + * returns the current value of the Ref after the potential update. + * + * **Example** (Conditionally updating and returning the current value) * - * @example * ```ts - * import { Effect, Ref } from "effect" - * import * as Option from "effect/Option" + * import { Effect, Option, Ref } from "effect" * * const program = Effect.gen(function*() { * const counter = yield* Ref.make(10) @@ -1456,8 +1762,11 @@ export const updateSomeAndGet = dual< * }) * ``` * + * @see {@link updateSome} for conditional updates without returning a value + * @see {@link updateAndGet} for always updating and returning the new value + * + * @category mutations * @since 2.0.0 - * @category utils */ (self: Ref, pf: (a: A) => Option.Option) => Effect.Effect >(2, (self: Ref, pf: (a: A) => Option.Option) => @@ -1472,10 +1781,17 @@ export const updateSomeAndGet = dual< /** * Gets the current value of the Ref synchronously (unsafe version). * - * This function reads the current value without wrapping in Effect. - * Use this only when you're sure about the safety of immediate access. + * **When to use** + * + * Use when you need immediate synchronous access and can guarantee that + * reading the `Ref` outside of `Effect` is safe. + * + * **Gotchas** + * + * Prefer `Ref.get` for Effect-wrapped access in Effect programs. + * + * **Example** (Reading a ref unsafely) * - * @example * ```ts * import { Ref } from "effect" * @@ -1490,7 +1806,7 @@ export const updateSomeAndGet = dual< * // Prefer Ref.get for Effect-wrapped access * ``` * - * @since 2.0.0 * @category getters + * @since 4.0.0 */ export const getUnsafe = (self: Ref): A => self.ref.current diff --git a/.opencode/node_modules/effect/src/References.ts b/.opencode/node_modules/effect/src/References.ts index 65dbd986a48a100719d505b977c7e46e34b973a7..bc7926e3e5a09639076b94ad34e651f9b51b6015 100644 --- a/.opencode/node_modules/effect/src/References.ts +++ b/.opencode/node_modules/effect/src/References.ts @@ -1,12 +1,13 @@ /** - * This module provides a collection of reference implementations for commonly used - * Effect runtime configuration values. These references allow you to access and - * modify runtime behavior such as concurrency limits, scheduling policies, - * tracing configuration, and logging settings. + * The `References` module exposes the built-in `Context.Reference` keys that + * the Effect runtime consults for execution settings and diagnostic metadata. + * These references cover concurrency, scheduling, logging, tracing, and + * low-level diagnostic state. * - * References are special service instances that can be dynamically updated - * during runtime, making them ideal for configuration that may need to change - * based on application state or external conditions. + * A `Context.Reference` is a service key with a default value. Reading one + * of these references returns the value from the current fiber context, and + * providing a new value changes behavior for the provided effect and the fibers + * it starts. * * @since 4.0.0 */ @@ -21,42 +22,119 @@ import { CurrentTraceLevel, DisablePropagation, MinimumTraceLevel, type SpanLink export { /** - * @since 4.0.0 + * Context reference for the current trace level used for dynamic trace filtering. + * + * **When to use** + * + * Use to set the default trace level for spans created in a scope when span + * options do not provide `level`. + * + * @see {@link MinimumTraceLevel} for configuring the threshold that decides whether spans at a given level are sampled or exported + * * @category references + * @since 4.0.0 */ CurrentTraceLevel, /** - * @since 4.0.0 + * Context reference for disabling trace propagation in the current context. + * + * **When to use** + * + * Use to mark tracing work as non-propagating while still allowing local span + * tracking. + * + * **Details** + * + * Annotated spans become non-propagating no-op spans, and parent selection + * skips spans marked with disabled propagation. + * + * @see {@link TracerEnabled} for disabling span registration instead of only propagation + * * @category references + * @since 4.0.0 */ DisablePropagation, /** - * @since 4.0.0 + * Context reference for the maximum operation budget before a fiber yields to the scheduler. + * + * **When to use** + * + * Use to configure the runtime reference for the fiber operation budget that + * triggers a scheduler yield. + * + * **Details** + * + * The default value is `2048` operations. + * + * @see {@link PreventSchedulerYield} for bypassing scheduler yield checks instead of changing the operation budget + * * @category references + * @since 4.0.0 */ MaxOpsBeforeYield, /** - * @since 4.0.0 + * Context reference for the minimum trace level threshold for span sampling. + * + * **When to use** + * + * Use to set the trace-level threshold that decides whether newly created + * spans are sampled and exported. + * + * @see {@link CurrentTraceLevel} for setting the level assigned to spans before this threshold is applied + * * @category references + * @since 4.0.0 */ MinimumTraceLevel, /** - * @since 4.0.0 + * Context reference for whether the runtime bypasses scheduler yield checks. + * + * **When to use** + * + * Use to bypass automatic scheduler yield checks in a controlled runtime scope + * where throughput is preferred over scheduler fairness. + * + * **Details** + * + * When set to `true`, the fiber run loop skips `Scheduler.shouldYield`. The + * default value is `false`. + * + * **Gotchas** + * + * Disabling automatic yield checks can let long-running fibers monopolize the + * JavaScript thread. + * + * @see {@link MaxOpsBeforeYield} for tuning the operation budget while keeping scheduler yield checks enabled + * * @category references + * @since 4.0.0 */ PreventSchedulerYield, /** - * @since 4.0.0 + * Context reference for the active tracer service used to create spans. + * + * **When to use** + * + * Use to access or override the active tracer service through the references + * module when working directly with Effect runtime references. + * * @category references + * @since 4.0.0 */ Tracer } /** - * Reference for controlling the current concurrency limit. Can be set to "unbounded" + * Context reference for controlling the current concurrency limit. Can be set to "unbounded" * for unlimited concurrency or a specific number to limit concurrent operations. * - * @example + * **When to use** + * + * Use to configure the default concurrency limit for operations that read + * concurrency from the current context. + * + * **Example** (Setting current concurrency) + * * ```ts * import { Effect, References } from "effect" * @@ -93,10 +171,16 @@ export { export const CurrentConcurrency: Context.Reference = references.CurrentConcurrency /** - * Reference for managing log annotations that are automatically added to all log entries. + * Context reference for managing log annotations that are automatically added to all log entries. * These annotations provide contextual metadata that appears in every log message. * - * @example + * **When to use** + * + * Use to attach shared contextual metadata to every log entry emitted in the + * current context. + * + * **Example** (Managing log annotations) + * * ```ts * import { Console, Effect, References } from "effect" * @@ -143,16 +227,27 @@ export const CurrentConcurrency: Context.Reference = refer * }) * ``` * - * @since 4.0.0 * @category references + * @since 4.0.0 */ export const CurrentLogAnnotations: Context.Reference> = references.CurrentLogAnnotations /** - * Reference for controlling the current log level for dynamic filtering. + * Context reference for the current log severity used by `Effect.log` when no explicit + * level is provided. + * + * **When to use** + * + * Use to set the default severity for `Effect.log` entries that do not provide + * an explicit level. + * + * **Details** + * + * Use `MinimumLogLevel` to control which log entries are filtered out. + * + * **Example** (Changing the current log level) * - * @example * ```ts * import { Console, Effect, References } from "effect" * @@ -192,10 +287,16 @@ export const CurrentLogAnnotations: Context.Reference = references.CurrentLogLevel /** - * Reference for managing log spans that track the duration and hierarchy of operations. + * Context reference for managing log spans that track the duration and hierarchy of operations. * Each span represents a labeled time period for performance analysis and debugging. * - * @example + * **When to use** + * + * Use to carry the active log span stack that should be included with log + * entries in the current context. + * + * **Example** (Tracking log spans) + * * ```ts * import { Console, Effect, References } from "effect" * @@ -205,7 +306,7 @@ export const CurrentLogLevel: Context.Reference = references.CurrentLo * console.log(current.length) // 0 * * // Add a log span manually - * const startTime = Date.now() + * const databaseConnectionStartedAt = 0 * yield* Effect.provideService( * Effect.gen(function*() { * // Simulate some work @@ -216,10 +317,11 @@ export const CurrentLogLevel: Context.Reference = references.CurrentLo * console.log("Active spans:", spans.map(([label]) => label)) // ["database-connection"] * }), * References.CurrentLogSpans, - * [["database-connection", startTime]] + * [["database-connection", databaseConnectionStartedAt]] * ) * * // Add another span + * const dataProcessingStartedAt = 100 * yield* Effect.provideService( * Effect.gen(function*() { * const spans = yield* References.CurrentLogSpans @@ -229,8 +331,8 @@ export const CurrentLogLevel: Context.Reference = references.CurrentLo * }), * References.CurrentLogSpans, * [ - * ["database-connection", startTime], - * ["data-processing", Date.now()] + * ["database-connection", databaseConnectionStartedAt], + * ["data-processing", dataProcessingStartedAt] * ] * ) * @@ -246,23 +348,44 @@ export const CurrentLogLevel: Context.Reference = references.CurrentLo * }) * ``` * - * @since 4.0.0 * @category references + * @since 4.0.0 */ export const CurrentLogSpans: Context.Reference> = references.CurrentLogSpans /** - * @since 4.0.0 + * Context reference for the current captured stack-frame chain for the running + * fiber. + * + * **When to use** + * + * Use when writing low-level tracing or diagnostic integrations that need direct + * access to the stack-frame chain carried by the current fiber. + * + * **Details** + * + * Effect and Layer tracing use this reference to attach stack-frame information + * to failures and interruption causes. It is normally managed by tracing APIs + * rather than provided directly by application code. + * + * @see {@link StackFrame} for the frame node stored in this reference + * * @category references + * @since 4.0.0 */ export const CurrentStackFrame: Context.Reference = references.CurrentStackFrame /** - * Reference for setting the minimum log level threshold. Log entries below this + * Context reference for setting the minimum log level threshold. Log entries below this * level will be filtered out completely. * - * @example + * **When to use** + * + * Use to filter out log entries below a severity threshold. + * + * **Example** (Setting the minimum log level) + * * ```ts * import { Console, Effect, References } from "effect" * @@ -310,10 +433,15 @@ export const CurrentStackFrame: Context.Reference = refe export const MinimumLogLevel: Context.Reference = references.MinimumLogLevel /** - * Reference for controlling whether tracing is enabled globally. When set to false, + * Context reference for controlling whether tracing is enabled globally. When set to false, * spans will not be registered with the tracer and tracing overhead is minimized. * - * @example + * **When to use** + * + * Use to disable or re-enable span registration in the current context. + * + * **Example** (Toggling tracing) + * * ```ts * import { Effect, References } from "effect" * @@ -350,16 +478,21 @@ export const MinimumLogLevel: Context.Reference = references.MinimumLo * }) * ``` * - * @since 4.0.0 * @category references + * @since 4.0.0 */ export const TracerEnabled: Context.Reference = references.TracerEnabled /** - * Reference for managing span annotations that are automatically added to all new spans. + * Context reference for managing span annotations that are automatically added to all new spans. * These annotations provide context and metadata that applies across multiple spans. * - * @example + * **When to use** + * + * Use to attach shared metadata to every span created in the current context. + * + * **Example** (Managing span annotations) + * * ```ts * import { Effect, References } from "effect" * @@ -402,17 +535,22 @@ export const TracerEnabled: Context.Reference = references.TracerEnable * }) * ``` * - * @since 4.0.0 * @category references + * @since 4.0.0 */ export const TracerSpanAnnotations: Context.Reference> = references.TracerSpanAnnotations /** - * Reference for managing span links that are automatically added to all new spans. + * Context reference for managing span links that are automatically added to all new spans. * Span links connect related spans that are not in a parent-child relationship. * - * @example + * **When to use** + * + * Use to attach shared links to every span created in the current context. + * + * **Example** (Managing span links) + * * ```ts * import { Effect, References, Tracer } from "effect" * @@ -465,17 +603,22 @@ export const TracerSpanAnnotations: Context.Reference> = references.TracerSpanLinks /** - * Reference for controlling whether trace timing is enabled globally. When set + * Context reference for controlling whether trace timing is enabled globally. When set * to false, spans will not contain timing information (trace time will always * be set to zero). * - * @example + * **When to use** + * + * Use to disable or re-enable timing capture for spans in the current context. + * + * **Example** (Toggling trace timing) + * * ```ts * import { Effect, References } from "effect" * @@ -508,14 +651,31 @@ export const TracerSpanLinks: Context.Reference> = refer * }) * ``` * - * @since 4.0.0 * @category references + * @since 4.0.0 */ export const TracerTimingEnabled: Context.Reference = references.TracerTimingEnabled /** - * The log level for unhandled errors. This reference allows you to set the log - * level for unhandled errors that occur during Effect execution. + * Context reference for the log severity used when a pool finalizer reports an + * unhandled error. + * + * **When to use** + * + * Use to choose whether and at which severity pool finalizer failures are + * reported. + * + * **Details** + * + * The default level is `"Error"`. + * + * **Gotchas** + * + * Providing `undefined` suppresses this report; it does not fall back to + * `CurrentLogLevel`. + * + * @see {@link CurrentLogLevel} for the default severity used by ordinary `Effect.log` calls + * @see {@link MinimumLogLevel} for filtering emitted log entries by threshold * * @category references * @since 4.0.0 @@ -523,8 +683,22 @@ export const TracerTimingEnabled: Context.Reference = references.Tracer export const UnhandledLogLevel: Context.Reference = references.UnhandledLogLevel /** - * @since 4.0.0 + * A captured stack-frame node used to describe the traced execution path. + * + * **When to use** + * + * Use when reading or supplying the stack-frame chain that Effect tracing uses + * to attach diagnostic call-site information to failures and interruptions. + * + * **Details** + * + * Each frame has a span or operation `name`, a lazy `stack` supplier, and an + * optional `parent` frame that links it to the previous captured frame. + * + * @see {@link CurrentStackFrame} for the fiber reference carrying the active stack-frame chain + * * @category references + * @since 4.0.0 */ export interface StackFrame { readonly name: string @@ -533,23 +707,55 @@ export interface StackFrame { } /** - * @since 4.0.0 + * Context reference for the set of loggers currently used by Effect logging + * operations. + * + * **When to use** + * + * Use to inspect or provide the complete set of loggers used by Effect logging + * in the current context. + * + * **Details** + * + * The default set contains the built-in default logger and tracer logger. + * Providing this reference changes which `Logger` instances receive log entries + * in the current context. + * * @category references + * @since 4.0.0 */ export const CurrentLoggers: Context.Reference>> = internalEffect.CurrentLoggers /** - * @since 4.0.0 + * Context reference for controlling whether built-in console loggers write to stderr. + * + * **When to use** + * + * Use to configure the runtime reference that controls whether built-in console + * loggers write to stderr. + * + * **Details** + * + * The default value is `false`. When set to `true`, the built-in default logger + * and TTY pretty console logger call `console.error` instead of `console.log`. + * * @category references + * @since 4.0.0 */ export const LogToStderr: Context.Reference = internalEffect.LogToStderr export { /** - * Reference for the current scheduler implementation used by the Effect runtime. + * Context reference for the current scheduler implementation used by the Effect runtime. * Controls how Effects are scheduled and executed. * - * @example + * **When to use** + * + * Use to provide the scheduler implementation that fibers use in the current + * context. + * + * **Example** (Providing a custom scheduler) + * * ```ts * import { Effect, References, Scheduler } from "effect" * diff --git a/.opencode/node_modules/effect/src/RegExp.ts b/.opencode/node_modules/effect/src/RegExp.ts index 017ef4e03654d79016f061a314b1090e47d4b66b..0123914f8ae89465721603af11c62c335ae5ad21 100644 --- a/.opencode/node_modules/effect/src/RegExp.ts +++ b/.opencode/node_modules/effect/src/RegExp.ts @@ -1,14 +1,27 @@ /** - * This module provides utility functions for working with RegExp in TypeScript. + * Tools for working with JavaScript regular expressions from the Effect module + * namespace. The module exposes the native `RegExp` constructor, a guard for + * narrowing unknown values, and escaping for literal text that will be embedded + * in a pattern. + * + * Reach for `RegExp` when you need to build a regular expression from user or + * data-driven text, check whether an unknown value is already a `RegExp`, or + * access the native constructor without leaving the Effect namespace. * * @since 2.0.0 */ import * as predicate from "./Predicate.ts" /** - * @since 4.0.0 - * @category constructors - * @example + * Exposes the JavaScript regular expression constructor from `globalThis`. + * + * **When to use** + * + * Use to construct JavaScript regular expressions through the Effect module + * namespace. + * + * **Example** (Creating a regular expression) + * * ```ts * import { RegExp } from "effect" * @@ -19,13 +32,21 @@ import * as predicate from "./Predicate.ts" * console.log(pattern.test("Hello World")) // true * console.log(pattern.test("goodbye")) // false * ``` + * + * @category constructors + * @since 4.0.0 */ export const RegExp = globalThis.RegExp /** - * Tests if a value is a `RegExp`. + * Checks whether a value is a `RegExp`. + * + * **When to use** + * + * Use to validate unknown input before treating it as a regular expression. + * + * **Example** (Checking for regular expressions) * - * @example * ```ts * import { RegExp } from "effect" * import * as assert from "node:assert" @@ -42,7 +63,12 @@ export const isRegExp: (input: unknown) => input is RegExp = predicate.isRegExp /** * Escapes special characters in a regular expression pattern. * - * @example + * **When to use** + * + * Use to turn literal text into a safe regular expression pattern fragment. + * + * **Example** (Escaping a pattern string) + * * ```ts * import { RegExp } from "effect" * import * as assert from "node:assert" @@ -50,7 +76,7 @@ export const isRegExp: (input: unknown) => input is RegExp = predicate.isRegExp * assert.deepStrictEqual(RegExp.escape("a*b"), "a\\*b") * ``` * - * @category utilities + * @category RegExp * @since 2.0.0 */ export const escape = (string: string): string => string.replace(/[/\\^$*+?.()|[\]{}]/g, "\\$&") diff --git a/.opencode/node_modules/effect/src/Request.ts b/.opencode/node_modules/effect/src/Request.ts index b621e66a93f61b4a72569180119d00dc3c612b24..f022b5cefbd5e2e656cfa534b170ca0a8bde1505 100644 --- a/.opencode/node_modules/effect/src/Request.ts +++ b/.opencode/node_modules/effect/src/Request.ts @@ -1,15 +1,11 @@ /** - * The `Request` module provides a way to model requests to external data sources - * in a functional and composable manner. Requests represent descriptions of - * operations that can be batched, cached, and executed efficiently. + * Typed request values for data loading with `Effect.request`. * - * A `Request` represents a request that: - * - Yields a value of type `A` on success - * - Can fail with an error of type `E` - * - Requires services of type `R` - * - * Requests are primarily used with RequestResolver to implement efficient - * data fetching patterns, including automatic batching and caching. + * A request describes one logical piece of work without performing it. It + * records the success type, typed error, service requirements, and fields a + * resolver needs to complete the request. Requests are paired with + * `RequestResolver`, which performs backend-specific loading and completes each + * pending request entry with a success, failure, cause, exit, or effect. * * @since 2.0.0 */ @@ -30,7 +26,8 @@ const TypeId = "~effect/Request" * A `Request` is a request from a data source for a value of type `A` * that may fail with an `E` and have requirements of type `R`. * - * @example + * **Example** (Defining typed requests) + * * ```ts * import type { Request } from "effect" * @@ -46,20 +43,41 @@ const TypeId = "~effect/Request" * } * ``` * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface Request extends Variance {} /** - * @since 2.0.0 + * Alias for any `Request`, regardless of its success, error, or service + * requirements. + * + * **When to use** + * + * Use as a generic constraint for APIs that accept any request while preserving + * each concrete request's success, error, and service types. + * + * @see {@link Request} for the request interface + * @see {@link Success} for extracting a request's success type + * @see {@link Error} for extracting a request's error type + * @see {@link Services} for extracting a request's service requirements + * @see {@link Result} for the exit type produced by completing a request + * * @category models + * @since 4.0.0 */ export type Any = Request /** - * @since 2.0.0 + * Variance marker carried by every `Request`. + * + * **Details** + * + * This marker preserves the success, error, and service requirement types for + * Effect's type-level machinery. Users normally get it by extending `Request`. + * * @category models + * @since 2.0.0 */ export interface Variance { readonly [TypeId]: { @@ -70,7 +88,16 @@ export interface Variance { } /** - * @example + * The constructor type returned by `Request.of` and `Request.tagged`. + * + * **Details** + * + * The constructor accepts the request's data fields, excluding request variance + * fields and any fields already supplied by the constructor such as `_tag`, and + * returns a value of the request type. + * + * **Example** (Using generated request constructors) + * * ```ts * import { Request } from "effect" * @@ -84,8 +111,8 @@ export interface Variance { * const userRequest = GetUser({ id: 123 }) * ``` * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface Constructor, T extends keyof R = never> { (args: Types.VoidIfEmpty)>>>): R @@ -94,7 +121,8 @@ export interface Constructor, T extends keyof R /** * A utility type to extract the error type from a `Request`. * - * @example + * **Example** (Extracting a request error type) + * * ```ts * import type { Request } from "effect" * @@ -106,15 +134,16 @@ export interface Constructor, T extends keyof R * type UserError = Request.Error // Error * ``` * + * @category utility types * @since 2.0.0 - * @category type-level */ export type Error> = [T] extends [Request] ? _E : never /** * A utility type to extract the value type from a `Request`. * - * @example + * **Example** (Extracting a request success type) + * * ```ts * import type { Request } from "effect" * @@ -127,8 +156,8 @@ export type Error> = [T] extends [Request // string * ``` * + * @category utility types * @since 2.0.0 - * @category type-level */ export type Success> = [T] extends [Request] ? _A : never @@ -136,8 +165,8 @@ export type Success> = [T] extends [Request> = [T] extends [Request] ? _R : never @@ -145,7 +174,8 @@ export type Services> = [T] extends [Request> = [T] extends [Request // Exit.Exit * ``` * + * @category utility types * @since 2.0.0 - * @category type-level */ export type Result> = T extends Request ? Exit.Exit : never @@ -174,6 +204,16 @@ const requestVariance = Equal.byReferenceUnsafe({ }) /** + * Prototype used by Effect's request constructors. + * + * **Details** + * + * This low-level value provides the structural request marker for values + * created by `Request.of`, `Request.tagged`, `Request.Class`, and + * `Request.TaggedClass`. Most users should use those constructors instead of + * interacting with the prototype directly. + * + * @category prototypes * @since 4.0.0 */ export const RequestPrototype: Request = { @@ -182,9 +222,10 @@ export const RequestPrototype: Request = { } /** - * Tests if a value is a `Request`. + * Checks whether a value is a `Request`. + * + * **Example** (Checking request values) * - * @example * ```ts * import { Request } from "effect" * @@ -212,7 +253,8 @@ export const isRequest = (u: unknown): u is Request = /** * Creates a constructor function for a specific Request type. * - * @example + * **Example** (Creating untagged request constructors) + * * ```ts * import { Request } from "effect" * @@ -244,7 +286,8 @@ export const of = >(): Constructor => (args) * Creates a constructor function for a tagged Request type. The tag is automatically * added to the request, making it useful for discriminated unions. * - * @example + * **Example** (Creating tagged request constructors) + * * ```ts * import { Request } from "effect" * @@ -292,7 +335,15 @@ export const tagged = & { _tag: string }>( } /** - * @example + * Defines request types with TypeScript classes. + * + * **Details** + * + * Subclasses pass their data fields to `super`, and instances are marked as + * `Request` values while retaining the provided readonly fields. + * + * **Example** (Defining request classes) + * * ```ts * import { Request } from "effect" * @@ -306,8 +357,8 @@ export const tagged = & { _tag: string }>( * console.log(getUserRequest.id) // 123 * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const Class: new, Success, Error = never, Context = never>( args: Types.Equals>, {}> extends true ? void @@ -323,7 +374,15 @@ export const Class: new, Success, Error = never, C })() /** - * @example + * Creates a class constructor for requests with a fixed `_tag` field. + * + * **Details** + * + * Use this when defining class-based request types that should participate in + * tagged unions or tag-based request resolvers. + * + * **Example** (Defining tagged request classes) + * * ```ts * import { Request } from "effect" * @@ -336,8 +395,8 @@ export const Class: new, Success, Error = never, C * console.log(request.id) // 123 * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const TaggedClass = ( tag: Tag @@ -351,24 +410,51 @@ export const TaggedClass = ( } /** - * Completes a request entry with the provided result. This is typically used - * within RequestResolver implementations to fulfill pending requests. + * Completes a request entry with the provided result. + * + * **When to use** + * + * Use when you need to finish a `Request.Entry` with a prebuilt final `Exit` + * result. + * + * @see {@link completeEffect} for completing an entry from an effect that may succeed or fail + * @see {@link succeed} for completing an entry with a successful value + * @see {@link fail} for completing an entry with a typed failure + * @see {@link failCause} for completing an entry with a failure `Cause` * * @category completion * @since 2.0.0 */ export const complete: { /** - * Completes a request entry with the provided result. This is typically used - * within RequestResolver implementations to fulfill pending requests. + * Completes a request entry with the provided result. + * + * **When to use** + * + * Use when you need to finish a `Request.Entry` with a prebuilt final `Exit` + * result. + * + * @see {@link completeEffect} for completing an entry from an effect that may succeed or fail + * @see {@link succeed} for completing an entry with a successful value + * @see {@link fail} for completing an entry with a typed failure + * @see {@link failCause} for completing an entry with a failure `Cause` * * @category completion * @since 2.0.0 */ (result: Result): (self: Entry) => Effect.Effect /** - * Completes a request entry with the provided result. This is typically used - * within RequestResolver implementations to fulfill pending requests. + * Completes a request entry with the provided result. + * + * **When to use** + * + * Use when you need to finish a `Request.Entry` with a prebuilt final `Exit` + * result. + * + * @see {@link completeEffect} for completing an entry from an effect that may succeed or fail + * @see {@link succeed} for completing an entry with a successful value + * @see {@link fail} for completing an entry with a typed failure + * @see {@link failCause} for completing an entry with a failure `Cause` * * @category completion * @since 2.0.0 @@ -381,18 +467,81 @@ export const complete: { ) /** - * @since 2.0.0 + * Completes a request entry with the result of an effect. + * + * **When to use** + * + * Use to finish a `Request.Entry` by running an effect whose success or typed + * failure should become the request result. + * + * **Details** + * + * If the effect succeeds, the entry is completed successfully with its value. + * If the effect fails, the entry is completed with that failure. + * + * **Gotchas** + * + * The returned effect itself does not fail with the request error. + * + * @see {@link complete} for completing an entry with a prebuilt `Exit` + * @see {@link succeed} for completing an entry with a successful value + * @see {@link fail} for completing an entry with a typed failure + * @see {@link failCause} for completing an entry with a failure `Cause` + * * @category completion + * @since 2.0.0 */ export const completeEffect: { /** - * @since 2.0.0 + * Completes a request entry with the result of an effect. + * + * **When to use** + * + * Use to finish a `Request.Entry` by running an effect whose success or typed + * failure should become the request result. + * + * **Details** + * + * If the effect succeeds, the entry is completed successfully with its value. + * If the effect fails, the entry is completed with that failure. + * + * **Gotchas** + * + * The returned effect itself does not fail with the request error. + * + * @see {@link complete} for completing an entry with a prebuilt `Exit` + * @see {@link succeed} for completing an entry with a successful value + * @see {@link fail} for completing an entry with a typed failure + * @see {@link failCause} for completing an entry with a failure `Cause` + * * @category completion + * @since 2.0.0 */ (effect: Effect.Effect, Error, R>): (self: Entry) => Effect.Effect /** - * @since 2.0.0 + * Completes a request entry with the result of an effect. + * + * **When to use** + * + * Use to finish a `Request.Entry` by running an effect whose success or typed + * failure should become the request result. + * + * **Details** + * + * If the effect succeeds, the entry is completed successfully with its value. + * If the effect fails, the entry is completed with that failure. + * + * **Gotchas** + * + * The returned effect itself does not fail with the request error. + * + * @see {@link complete} for completing an entry with a prebuilt `Exit` + * @see {@link succeed} for completing an entry with a successful value + * @see {@link fail} for completing an entry with a typed failure + * @see {@link failCause} for completing an entry with a failure `Cause` + * * @category completion + * @since 2.0.0 */ (self: Entry, effect: Effect.Effect, Error, R>): Effect.Effect } = dual( @@ -405,18 +554,54 @@ export const completeEffect: { ) /** - * @since 2.0.0 + * Completes a request entry with a typed failure. + * + * **When to use** + * + * Use to report a request-specific typed error while implementing a + * `RequestResolver`. + * + * @see {@link failCause} for completing an entry with a full `Cause` + * @see {@link complete} for completing an entry with an existing `Exit` + * @see {@link completeEffect} for completing an entry from an effect result + * @see {@link succeed} for completing an entry successfully + * * @category completion + * @since 2.0.0 */ export const fail: { /** - * @since 2.0.0 + * Completes a request entry with a typed failure. + * + * **When to use** + * + * Use to report a request-specific typed error while implementing a + * `RequestResolver`. + * + * @see {@link failCause} for completing an entry with a full `Cause` + * @see {@link complete} for completing an entry with an existing `Exit` + * @see {@link completeEffect} for completing an entry from an effect result + * @see {@link succeed} for completing an entry successfully + * * @category completion + * @since 2.0.0 */ (error: Error): (self: Entry) => Effect.Effect /** - * @since 2.0.0 + * Completes a request entry with a typed failure. + * + * **When to use** + * + * Use to report a request-specific typed error while implementing a + * `RequestResolver`. + * + * @see {@link failCause} for completing an entry with a full `Cause` + * @see {@link complete} for completing an entry with an existing `Exit` + * @see {@link completeEffect} for completing an entry from an effect result + * @see {@link succeed} for completing an entry successfully + * * @category completion + * @since 2.0.0 */ (self: Entry, error: Error): Effect.Effect } = dual( @@ -425,18 +610,54 @@ export const fail: { ) /** - * @since 2.0.0 + * Completes a request entry with a failure `Cause`. + * + * **When to use** + * + * Use when you need a `RequestResolver` to complete an entry with structured + * cause information rather than only the request's typed error value. + * + * @see {@link fail} for completing an entry with a typed error value + * @see {@link complete} for completing an entry with an existing `Exit` + * @see {@link completeEffect} for completing an entry from an effect result + * @see {@link succeed} for completing an entry successfully + * * @category completion + * @since 2.0.0 */ export const failCause: { /** - * @since 2.0.0 + * Completes a request entry with a failure `Cause`. + * + * **When to use** + * + * Use when you need a `RequestResolver` to complete an entry with structured + * cause information rather than only the request's typed error value. + * + * @see {@link fail} for completing an entry with a typed error value + * @see {@link complete} for completing an entry with an existing `Exit` + * @see {@link completeEffect} for completing an entry from an effect result + * @see {@link succeed} for completing an entry successfully + * * @category completion + * @since 2.0.0 */ (cause: Cause.Cause>): (self: Entry) => Effect.Effect /** - * @since 2.0.0 + * Completes a request entry with a failure `Cause`. + * + * **When to use** + * + * Use when you need a `RequestResolver` to complete an entry with structured + * cause information rather than only the request's typed error value. + * + * @see {@link fail} for completing an entry with a typed error value + * @see {@link complete} for completing an entry with an existing `Exit` + * @see {@link completeEffect} for completing an entry from an effect result + * @see {@link succeed} for completing an entry successfully + * * @category completion + * @since 2.0.0 */ (self: Entry, cause: Cause.Cause>): Effect.Effect } = dual( @@ -446,18 +667,54 @@ export const failCause: { ) /** - * @since 2.0.0 + * Completes a request entry successfully with the supplied value. + * + * **When to use** + * + * Use when you need to finish a `Request.Entry` with a successful request + * value. + * + * @see {@link complete} for completing an entry with a prebuilt `Exit` + * @see {@link completeEffect} for completing an entry from an effect result + * @see {@link fail} for completing an entry with a typed failure + * @see {@link failCause} for completing an entry with a failure `Cause` + * * @category completion + * @since 2.0.0 */ export const succeed: { /** - * @since 2.0.0 + * Completes a request entry successfully with the supplied value. + * + * **When to use** + * + * Use when you need to finish a `Request.Entry` with a successful request + * value. + * + * @see {@link complete} for completing an entry with a prebuilt `Exit` + * @see {@link completeEffect} for completing an entry from an effect result + * @see {@link fail} for completing an entry with a typed failure + * @see {@link failCause} for completing an entry with a failure `Cause` + * * @category completion + * @since 2.0.0 */ (value: Success): (self: Entry) => Effect.Effect /** - * @since 2.0.0 + * Completes a request entry successfully with the supplied value. + * + * **When to use** + * + * Use when you need to finish a `Request.Entry` with a successful request + * value. + * + * @see {@link complete} for completing an entry with a prebuilt `Exit` + * @see {@link completeEffect} for completing an entry from an effect result + * @see {@link fail} for completing an entry with a typed failure + * @see {@link failCause} for completing an entry with a failure `Cause` + * * @category completion + * @since 2.0.0 */ (self: Entry, value: Success): Effect.Effect } = dual( @@ -467,8 +724,16 @@ export const succeed: { ) /** - * @since 2.0.0 + * A pending request handed to a `RequestResolver`. + * + * **Details** + * + * An entry contains the original request, the fiber context needed to run it, + * an `uninterruptible` flag used by batching and caching internals, and the + * `completeUnsafe` callback used by resolvers to supply the final `Exit`. + * * @category entry + * @since 2.0.0 */ export interface Entry { readonly request: R @@ -485,8 +750,16 @@ export interface Entry { } /** - * @since 2.0.0 + * Creates a `Request.Entry` from its component fields. + * + * **Details** + * + * This is a low-level helper for request runtime and resolver infrastructure; + * most application code receives entries from a `RequestResolver` instead of + * constructing them directly. + * * @category entry + * @since 2.0.0 */ export const makeEntry = (options: { readonly request: R diff --git a/.opencode/node_modules/effect/src/RequestResolver.ts b/.opencode/node_modules/effect/src/RequestResolver.ts index 6568ae333ee0f6b159260837051f988f88fa2456..7c9e47fa1c7cc6389ff211664845d1073aad9e03 100644 --- a/.opencode/node_modules/effect/src/RequestResolver.ts +++ b/.opencode/node_modules/effect/src/RequestResolver.ts @@ -1,4 +1,12 @@ /** + * Resolves data requests made with `Effect.request`. + * + * A `Request` describes what a fiber needs, while a `RequestResolver` describes + * how to collect request entries, group them into batches, run backend work, + * and complete each waiting entry. This module includes constructors for common + * resolver shapes and tools for controlling batching, grouping, delays, + * tracing, caching, racing, hooks around resolver execution, and persistence. + * * @since 2.0.0 */ import type { NonEmptyArray } from "./Array.ts" @@ -27,29 +35,26 @@ import * as Persistence from "./unstable/persistence/Persistence.ts" const TypeId = "~effect/RequestResolver" /** - * The `RequestResolver` interface requires an environment `R` and handles - * the execution of requests of type `A`. - * - * Implementations must provide a `runAll` method, which processes a collection - * of requests and produces an effect that fulfills these requests. Requests are - * organized into a `Array>`, where the outer `Array` groups requests - * into batches that are executed sequentially, and each inner `Array` contains - * requests that can be executed in parallel. This structure allows - * implementations to analyze all incoming requests collectively and optimize - * query execution accordingly. - * - * Implementations are typically specialized for a subtype of `Request`. - * However, they are not strictly limited to these subtypes as long as they can - * map any given request type to `Request`. Implementations should inspect - * the collection of requests to identify the needed information and execute the - * corresponding queries. It is imperative that implementations resolve all the - * requests they receive. Failing to do so will lead to a `QueryFailure` error - * during query execution. - * - * @example + * A resolver that executes and completes batched `Request` entries. + * + * **Details** + * + * A resolver controls how requests are grouped, delayed, optionally + * pre-checked, and finally run. Its `runAll` method receives a non-empty batch + * of `Request.Entry` values for a single batch key and must complete every + * received entry, usually by calling `completeUnsafe` or one of the `Request` + * completion helpers. + * + * **Gotchas** + * + * If a resolver finishes without completing an entry, the waiting request fails + * because the resolver did not supply a result. + * + * **Example** (Defining a request resolver) + * * ```ts - * import type { Request } from "effect" * import { Effect, Exit, RequestResolver } from "effect" + * import type { Request } from "effect" * * interface GetUserRequest extends Request.Request { * readonly _tag: "GetUserRequest" @@ -66,8 +71,8 @@ const TypeId = "~effect/RequestResolver" * ) * ``` * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface RequestResolver extends RequestResolver.Variance, Pipeable { readonly delay: Effect.Effect @@ -97,13 +102,21 @@ export interface RequestResolver extends RequestResolv } /** + * Namespace containing type-level helpers associated with `RequestResolver`. + * * @since 2.0.0 - * @category models */ export declare namespace RequestResolver { /** - * @since 2.0.0 + * Variance marker carried by every `RequestResolver`. + * + * **Details** + * + * This marker preserves the request type accepted by the resolver for + * Effect's type-level machinery. Users normally do not implement it directly. + * * @category models + * @since 2.0.0 */ export interface Variance { readonly [TypeId]: { @@ -125,17 +138,45 @@ const RequestResolverProto = { /** * Returns `true` if the specified value is a `RequestResolver`, `false` otherwise. * - * @since 2.0.0 + * **When to use** + * + * Use to narrow unknown values before passing them to APIs that require a + * `RequestResolver`. + * + * @see {@link RequestResolver} for the type narrowed by this guard + * * @category guards + * @since 2.0.0 */ export const isRequestResolver = (u: unknown): u is RequestResolver => hasProperty(u, TypeId) /** - * Low-level constructor for creating a request resolver with fine-grained + * Creates a request resolver with fine-grained * control over its behavior. * - * @since 4.0.0 + * **When to use** + * + * Use when you need to supply the resolver batching primitives directly, + * including the batch key, optional pre-check, delay effect, collection cutoff, + * and batch runner. + * + * **Details** + * + * `batchKey` groups request entries, `delay` schedules batch execution, + * `collectWhile` can end collection early, and `runAll` receives a non-empty + * batch for one key. + * + * **Gotchas** + * + * Accepted entries must be completed. If `runAll` succeeds with incomplete + * entries, waiting requests fail. If `preCheck` returns `false`, the entry is + * not batched, so it must be completed or linked to another completion path. + * + * @see {@link make} for constructing a resolver from a batch runner + * @see {@link makeGrouped} for constructing a resolver that groups requests by key + * * @category constructors + * @since 4.0.0 */ export const makeWith = (options: { readonly batchKey: (request: Request.Entry) => unknown @@ -159,7 +200,8 @@ const defaultKey = (_request: unknown): unknown => defaultKeyObject /** * Constructs a request resolver with the specified method to run requests. * - * @example + * **Example** (Creating a request resolver) + * * ```ts * import { Effect, Exit, Request, RequestResolver } from "effect" * @@ -184,8 +226,8 @@ const defaultKey = (_request: unknown): unknown => defaultKeyObject * const getUserEffect = Effect.request(GetUserRequest({ id: 123 }), UserResolver) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const make = ( runAll: (entries: NonEmptyArray>, key: unknown) => Effect.Effect> @@ -200,9 +242,12 @@ export const make = ( /** * Constructs a request resolver with the requests grouped by a calculated key. * + * **Details** + * * The key can use the Equal trait to determine if two keys are equal. * - * @example + * **Example** (Grouping requests by key) + * * ```ts * import { Effect, Exit, Request, RequestResolver } from "effect" * @@ -228,8 +273,8 @@ export const make = ( * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const makeGrouped = (options: { readonly key: (entry: Request.Entry) => K @@ -258,7 +303,8 @@ const hashGroupKey = (get: (entry: Request.Entry) => K) => { /** * Constructs a request resolver from a pure function. * - * @example + * **Example** (Creating a resolver from a pure function) + * * ```ts * import { Effect, Request, RequestResolver } from "effect" * @@ -281,8 +327,8 @@ const hashGroupKey = (get: (entry: Request.Entry) => K) => { * // Will resolve to 25 * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const fromFunction = ( f: (entry: Request.Entry) => Request.Success @@ -302,7 +348,8 @@ export const fromFunction = ( * and returns a list of results of the same size. Each item in the result * list must correspond to the item at the same index in the request list. * - * @example + * **Example** (Batching pure request handling) + * * ```ts * import { Effect, Request, RequestResolver } from "effect" * @@ -324,8 +371,8 @@ export const fromFunction = ( * const batchedEffect = Effect.all(effects) // [2, 4, 6] * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const fromFunctionBatched = ( f: (entries: NonEmptyArray>) => Iterable> @@ -344,7 +391,8 @@ export const fromFunctionBatched = ( /** * Constructs a request resolver from an effectual function. * - * @example + * **Example** (Creating a resolver from an effectful function) + * * ```ts * import { Effect, Request, RequestResolver } from "effect" * @@ -374,8 +422,8 @@ export const fromFunctionBatched = ( * ) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const fromEffect = ( f: (entry: Request.Entry) => Effect.Effect, Request.Error> @@ -406,10 +454,11 @@ export const fromEffect = ( * in the result list must correspond to the item at the same index in the * request list. * - * @example + * **Example** (Handling tagged request batches) + * * ```ts - * import type { Request } from "effect" * import { Effect, RequestResolver } from "effect" + * import type { Request } from "effect" * * interface GetUser extends Request.Request { * readonly _tag: "GetUser" @@ -432,8 +481,8 @@ export const fromEffect = ( * }) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const fromEffectTagged = () => < @@ -483,7 +532,8 @@ export const fromEffectTagged = ): (self: RequestResolver) => RequestResolver /** * Sets the batch delay effect for this request resolver. * - * @example + * **Example** (Setting an effectful batch delay) + * * ```ts * import { Effect, Exit, Request, RequestResolver } from "effect" * @@ -578,8 +630,8 @@ export const setDelayEffect: { * ) * ``` * - * @since 4.0.0 * @category delay + * @since 4.0.0 */ (self: RequestResolver, delay: Effect.Effect): RequestResolver } = dual( @@ -594,7 +646,8 @@ export const setDelayEffect: { /** * Sets the batch delay window for this request resolver to the specified duration. * - * @example + * **Example** (Setting a batch delay) + * * ```ts * import { Effect, Exit, Request, RequestResolver } from "effect" * @@ -618,14 +671,15 @@ export const setDelayEffect: { * const delayedResolver2 = RequestResolver.setDelay(resolver, 100) * ``` * - * @since 4.0.0 * @category delay + * @since 4.0.0 */ export const setDelay: { /** * Sets the batch delay window for this request resolver to the specified duration. * - * @example + * **Example** (Setting a batch delay) + * * ```ts * import { Effect, Exit, Request, RequestResolver } from "effect" * @@ -649,14 +703,15 @@ export const setDelay: { * const delayedResolver2 = RequestResolver.setDelay(resolver, 100) * ``` * - * @since 4.0.0 * @category delay + * @since 4.0.0 */ (duration: Duration.Input): (self: RequestResolver) => RequestResolver /** * Sets the batch delay window for this request resolver to the specified duration. * - * @example + * **Example** (Setting a batch delay) + * * ```ts * import { Effect, Exit, Request, RequestResolver } from "effect" * @@ -680,8 +735,8 @@ export const setDelay: { * const delayedResolver2 = RequestResolver.setDelay(resolver, 100) * ``` * - * @since 4.0.0 * @category delay + * @since 4.0.0 */ (self: RequestResolver, duration: Duration.Input): RequestResolver } = dual( @@ -694,10 +749,10 @@ export const setDelay: { ) /** - * A request resolver aspect that executes requests between two effects, `before` - * and `after`, where the result of `before` can be used by `after`. + * Wraps request resolver execution between `before` and `after` effects. + * + * **Example** (Running effects around request resolution) * - * @example * ```ts * import { Effect, Exit, Request, RequestResolver } from "effect" * @@ -720,25 +775,26 @@ export const setDelay: { * (entries) => * Effect.gen(function*() { * yield* Effect.log(`Starting batch of ${entries.length} requests`) - * return Date.now() + * return entries.length * }), - * (entries, startTime) => + * (entries, initialSize) => * Effect.gen(function*() { - * const duration = Date.now() - startTime - * yield* Effect.log(`Batch completed in ${duration}ms`) + * yield* Effect.log( + * `Batch completed with ${entries.length} requests (started with ${initialSize})` + * ) * }) * ) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const around: { /** - * A request resolver aspect that executes requests between two effects, `before` - * and `after`, where the result of `before` can be used by `after`. + * Wraps request resolver execution between `before` and `after` effects. + * + * **Example** (Running effects around request resolution) * - * @example * ```ts * import { Effect, Exit, Request, RequestResolver } from "effect" * @@ -761,28 +817,29 @@ export const around: { * (entries) => * Effect.gen(function*() { * yield* Effect.log(`Starting batch of ${entries.length} requests`) - * return Date.now() + * return entries.length * }), - * (entries, startTime) => + * (entries, initialSize) => * Effect.gen(function*() { - * const duration = Date.now() - startTime - * yield* Effect.log(`Batch completed in ${duration}ms`) + * yield* Effect.log( + * `Batch completed with ${entries.length} requests (started with ${initialSize})` + * ) * }) * ) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ ( before: (entries: NonEmptyArray>>) => Effect.Effect>, after: (entries: NonEmptyArray>>, a: A2) => Effect.Effect> ): (self: RequestResolver) => RequestResolver /** - * A request resolver aspect that executes requests between two effects, `before` - * and `after`, where the result of `before` can be used by `after`. + * Wraps request resolver execution between `before` and `after` effects. + * + * **Example** (Running effects around request resolution) * - * @example * ```ts * import { Effect, Exit, Request, RequestResolver } from "effect" * @@ -805,18 +862,19 @@ export const around: { * (entries) => * Effect.gen(function*() { * yield* Effect.log(`Starting batch of ${entries.length} requests`) - * return Date.now() + * return entries.length * }), - * (entries, startTime) => + * (entries, initialSize) => * Effect.gen(function*() { - * const duration = Date.now() - startTime - * yield* Effect.log(`Batch completed in ${duration}ms`) + * yield* Effect.log( + * `Batch completed with ${entries.length} requests (started with ${initialSize})` + * ) * }) * ) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ ( self: RequestResolver, @@ -839,17 +897,37 @@ export const around: { })) /** - * A request resolver that never executes requests. + * Creates a request resolver that never executes requests. + * + * **When to use** + * + * Use as a resolver value for request types that are statically impossible and + * should never be issued. + * + * **Gotchas** + * + * If this resolver is used for an actual request, the request waits forever + * unless the fiber is interrupted. + * + * @see {@link make} for constructing a resolver that executes batches and completes request entries * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const never: RequestResolver = make(() => Effect.never) /** - * Returns a request resolver that executes at most `n` requests in parallel. + * Returns a request resolver that collects at most `n` requests into each + * batch. + * + * **Details** + * + * When more than `n` requests are waiting for the same resolver and batch key, + * the current batch is run and additional requests are collected into later + * batches. + * + * **Example** (Limiting parallel request batches) * - * @example * ```ts * import { Effect, Exit, Request, RequestResolver } from "effect" * @@ -878,14 +956,22 @@ export const never: RequestResolver = make(() => Effect.never) * ) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const batchN: { /** - * Returns a request resolver that executes at most `n` requests in parallel. + * Returns a request resolver that collects at most `n` requests into each + * batch. + * + * **Details** + * + * When more than `n` requests are waiting for the same resolver and batch key, + * the current batch is run and additional requests are collected into later + * batches. + * + * **Example** (Limiting parallel request batches) * - * @example * ```ts * import { Effect, Exit, Request, RequestResolver } from "effect" * @@ -914,14 +1000,22 @@ export const batchN: { * ) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (n: number): (self: RequestResolver) => RequestResolver /** - * Returns a request resolver that executes at most `n` requests in parallel. + * Returns a request resolver that collects at most `n` requests into each + * batch. + * + * **Details** + * + * When more than `n` requests are waiting for the same resolver and batch key, + * the current batch is run and additional requests are collected into later + * batches. + * + * **Example** (Limiting parallel request batches) * - * @example * ```ts * import { Effect, Exit, Request, RequestResolver } from "effect" * @@ -950,8 +1044,8 @@ export const batchN: { * ) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (self: RequestResolver, n: number): RequestResolver } = dual(2, (self: RequestResolver, n: number): RequestResolver => @@ -961,10 +1055,11 @@ export const batchN: { })) /** - * Transform a request resolver by grouping requests using the specified key + * Transforms a request resolver by grouping requests using the specified key * function. * - * @example + * **Example** (Grouping resolver requests) + * * ```ts * import { Effect, Exit, Request, RequestResolver } from "effect" * @@ -1007,15 +1102,16 @@ export const batchN: { * ] * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const grouped: { /** - * Transform a request resolver by grouping requests using the specified key + * Transforms a request resolver by grouping requests using the specified key * function. * - * @example + * **Example** (Grouping resolver requests) + * * ```ts * import { Effect, Exit, Request, RequestResolver } from "effect" * @@ -1058,15 +1154,16 @@ export const grouped: { * ] * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (f: (entry: Request.Entry) => K): (self: RequestResolver) => RequestResolver /** - * Transform a request resolver by grouping requests using the specified key + * Transforms a request resolver by grouping requests using the specified key * function. * - * @example + * **Example** (Grouping resolver requests) + * * ```ts * import { Effect, Exit, Request, RequestResolver } from "effect" * @@ -1109,8 +1206,8 @@ export const grouped: { * ] * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: RequestResolver, f: (entry: Request.Entry) => K): RequestResolver } = dual( @@ -1123,13 +1220,16 @@ export const grouped: { ) /** - * Returns a new request resolver that executes requests by sending them to this - * request resolver and that request resolver, returning the results from the first data - * source to complete and safely interrupting the loser. + * Returns a request resolver that sends each batch to both resolvers and + * completes with the first resolver to finish. + * + * **Details** * - * The batch delay is determined by the first request resolver. + * The losing resolver run is interrupted after the winning resolver completes + * the batch. + * + * **Example** (Racing request resolvers) * - * @example * ```ts * import { Effect, Exit, Request, RequestResolver } from "effect" * @@ -1163,18 +1263,21 @@ export const grouped: { * const racingResolver = RequestResolver.race(fastResolver, slowResolver) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const race: { /** - * Returns a new request resolver that executes requests by sending them to this - * request resolver and that request resolver, returning the results from the first data - * source to complete and safely interrupting the loser. + * Returns a request resolver that sends each batch to both resolvers and + * completes with the first resolver to finish. + * + * **Details** + * + * The losing resolver run is interrupted after the winning resolver completes + * the batch. * - * The batch delay is determined by the first request resolver. + * **Example** (Racing request resolvers) * - * @example * ```ts * import { Effect, Exit, Request, RequestResolver } from "effect" * @@ -1208,18 +1311,21 @@ export const race: { * const racingResolver = RequestResolver.race(fastResolver, slowResolver) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (that: RequestResolver): (self: RequestResolver) => RequestResolver /** - * Returns a new request resolver that executes requests by sending them to this - * request resolver and that request resolver, returning the results from the first data - * source to complete and safely interrupting the loser. + * Returns a request resolver that sends each batch to both resolvers and + * completes with the first resolver to finish. + * + * **Details** + * + * The losing resolver run is interrupted after the winning resolver completes + * the batch. * - * The batch delay is determined by the first request resolver. + * **Example** (Racing request resolvers) * - * @example * ```ts * import { Effect, Exit, Request, RequestResolver } from "effect" * @@ -1253,8 +1359,8 @@ export const race: { * const racingResolver = RequestResolver.race(fastResolver, slowResolver) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (self: RequestResolver, that: RequestResolver): RequestResolver } = dual(2, ( @@ -1266,10 +1372,11 @@ export const race: { )) /** - * Add a tracing span to the request resolver, which will also add any span + * Adds a tracing span to the request resolver, which will also add any span * links from the request's. * - * @example + * **Example** (Adding a tracing span) + * * ```ts * import { Effect, Exit, Request, RequestResolver } from "effect" * @@ -1303,15 +1410,16 @@ export const race: { * const effect = Effect.request(GetDataRequest({ id: 123 }), tracedResolver) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const withSpan: { /** - * Add a tracing span to the request resolver, which will also add any span + * Adds a tracing span to the request resolver, which will also add any span * links from the request's. * - * @example + * **Example** (Adding a tracing span) + * * ```ts * import { Effect, Exit, Request, RequestResolver } from "effect" * @@ -1345,18 +1453,19 @@ export const withSpan: { * const effect = Effect.request(GetDataRequest({ id: 123 }), tracedResolver) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ ( name: string, options?: Tracer.SpanOptions | ((entries: NonEmptyArray>) => Tracer.SpanOptions) | undefined ): (self: RequestResolver) => RequestResolver /** - * Add a tracing span to the request resolver, which will also add any span + * Adds a tracing span to the request resolver, which will also add any span * links from the request's. * - * @example + * **Example** (Adding a tracing span) + * * ```ts * import { Effect, Exit, Request, RequestResolver } from "effect" * @@ -1390,8 +1499,8 @@ export const withSpan: { * const effect = Effect.request(GetDataRequest({ id: 123 }), tracedResolver) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ ( self: RequestResolver, @@ -1431,16 +1540,56 @@ export const withSpan: { * Wraps a request resolver in a cache, allowing it to cache results up to a * specified capacity and optional time-to-live. * + * **When to use** + * + * Use to turn a request resolver into a first-class `Cache` when callers need + * cache lookup, refresh, invalidation, or inspection around request results. + * + * **Details** + * + * The request value is the cache key. Cache misses run the resolver via + * `Effect.request`, `timeToLive` receives the request `Exit` and the request, + * and `requireServicesAt` controls whether services are required at lookup time + * or construction time. + * + * **Gotchas** + * + * Cache hits depend on the request value's equality semantics. + * + * @see {@link withCache} for keeping caching behind a resolver used with `Effect.request` + * @see {@link persisted} for storing persistable request results outside process memory + * @see {@link Cache.Cache} for operations available on the returned cache + * + * @category caching * @since 4.0.0 - * @category Caching */ export const asCache: { /** * Wraps a request resolver in a cache, allowing it to cache results up to a * specified capacity and optional time-to-live. * + * **When to use** + * + * Use to turn a request resolver into a first-class `Cache` when callers need + * cache lookup, refresh, invalidation, or inspection around request results. + * + * **Details** + * + * The request value is the cache key. Cache misses run the resolver via + * `Effect.request`, `timeToLive` receives the request `Exit` and the request, + * and `requireServicesAt` controls whether services are required at lookup time + * or construction time. + * + * **Gotchas** + * + * Cache hits depend on the request value's equality semantics. + * + * @see {@link withCache} for keeping caching behind a resolver used with `Effect.request` + * @see {@link persisted} for storing persistable request results outside process memory + * @see {@link Cache.Cache} for operations available on the returned cache + * + * @category caching * @since 4.0.0 - * @category Caching */ < A extends Request.Any, @@ -1465,8 +1614,28 @@ export const asCache: { * Wraps a request resolver in a cache, allowing it to cache results up to a * specified capacity and optional time-to-live. * + * **When to use** + * + * Use to turn a request resolver into a first-class `Cache` when callers need + * cache lookup, refresh, invalidation, or inspection around request results. + * + * **Details** + * + * The request value is the cache key. Cache misses run the resolver via + * `Effect.request`, `timeToLive` receives the request `Exit` and the request, + * and `requireServicesAt` controls whether services are required at lookup time + * or construction time. + * + * **Gotchas** + * + * Cache hits depend on the request value's equality semantics. + * + * @see {@link withCache} for keeping caching behind a resolver used with `Effect.request` + * @see {@link persisted} for storing persistable request results outside process memory + * @see {@link Cache.Cache} for operations available on the returned cache + * + * @category caching * @since 4.0.0 - * @category Caching */ < A extends Request.Any, @@ -1512,19 +1681,57 @@ export const asCache: { }) as any) /** - * Adds caching capabilities to a request resolver, allowing it to cache - * results up to a specified capacity. + * Adds a bounded in-memory cache to a request resolver. + * + * **When to use** + * + * Use to reuse completed results for repeated equal request values while still + * passing a `RequestResolver` to `Effect.request`. + * + * **Details** + * + * Running the returned effect creates the cache and returns a wrapped resolver. + * The cache stores completed success or failure results by request equality up + * to `capacity`. The `strategy` option controls eviction order and defaults to + * `"lru"`; `"fifo"` keeps insertion order. + * + * **Gotchas** + * + * Entries do not expire by time, and completed failures are cached the same as + * successes. Request equality controls cache hits. * + * @see {@link asCache} for exposing the resolver as a `Cache` with time-to-live and service lookup controls + * @see {@link persisted} for backing persistable requests with the configured persistence store + * + * @category caching * @since 4.0.0 - * @category Caching */ export const withCache: { /** - * Adds caching capabilities to a request resolver, allowing it to cache - * results up to a specified capacity. + * Adds a bounded in-memory cache to a request resolver. + * + * **When to use** + * + * Use to reuse completed results for repeated equal request values while still + * passing a `RequestResolver` to `Effect.request`. + * + * **Details** + * + * Running the returned effect creates the cache and returns a wrapped resolver. + * The cache stores completed success or failure results by request equality up + * to `capacity`. The `strategy` option controls eviction order and defaults to + * `"lru"`; `"fifo"` keeps insertion order. + * + * **Gotchas** * + * Entries do not expire by time, and completed failures are cached the same as + * successes. Request equality controls cache hits. + * + * @see {@link asCache} for exposing the resolver as a `Cache` with time-to-live and service lookup controls + * @see {@link persisted} for backing persistable requests with the configured persistence store + * + * @category caching * @since 4.0.0 - * @category Caching */ ( options: { @@ -1533,11 +1740,30 @@ export const withCache: { } ): (self: RequestResolver) => Effect.Effect> /** - * Adds caching capabilities to a request resolver, allowing it to cache - * results up to a specified capacity. + * Adds a bounded in-memory cache to a request resolver. + * + * **When to use** + * + * Use to reuse completed results for repeated equal request values while still + * passing a `RequestResolver` to `Effect.request`. + * + * **Details** + * + * Running the returned effect creates the cache and returns a wrapped resolver. + * The cache stores completed success or failure results by request equality up + * to `capacity`. The `strategy` option controls eviction order and defaults to + * `"lru"`; `"fifo"` keeps insertion order. + * + * **Gotchas** * + * Entries do not expire by time, and completed failures are cached the same as + * successes. Request equality controls cache hits. + * + * @see {@link asCache} for exposing the resolver as a `Cache` with time-to-live and service lookup controls + * @see {@link persisted} for backing persistable requests with the configured persistence store + * + * @category caching * @since 4.0.0 - * @category Caching */ ( self: RequestResolver, @@ -1553,18 +1779,56 @@ export const withCache: { Effect.sync(() => { const strategy = options.strategy ?? "lru" const cache = MutableHashMap.empty; @@ -1617,13 +1881,51 @@ export const withCache: { })) /** - * @since 4.0.0 + * Wraps a request resolver with persistent storage for persistable requests. + * + * **When to use** + * + * Use to keep a `RequestResolver` interface while reusing completed + * `Persistable` request results through a `Persistence` store. + * + * **Details** + * + * Cached results are loaded from the configured persistence store before + * running the underlying resolver. Missing entries are resolved normally and + * written back to the store. Entries marked stale by `staleWhileRevalidate` + * receive the stored result and are also resolved again so the refreshed result + * can be written back to the store. Creating the persisted resolver requires + * `Persistence.Persistence` and `Scope`. + * + * @see {@link withCache} for in-memory resolver caching that does not require persistable request values or a persistence store + * @see {@link asCache} for exposing resolver results through a `Cache` instead of returning another resolver + * * @category Persistence + * @since 4.0.0 */ export const persisted: { /** - * @since 4.0.0 + * Wraps a request resolver with persistent storage for persistable requests. + * + * **When to use** + * + * Use to keep a `RequestResolver` interface while reusing completed + * `Persistable` request results through a `Persistence` store. + * + * **Details** + * + * Cached results are loaded from the configured persistence store before + * running the underlying resolver. Missing entries are resolved normally and + * written back to the store. Entries marked stale by `staleWhileRevalidate` + * receive the stored result and are also resolved again so the refreshed result + * can be written back to the store. Creating the persisted resolver requires + * `Persistence.Persistence` and `Scope`. + * + * @see {@link withCache} for in-memory resolver caching that does not require persistable request values or a persistence store + * @see {@link asCache} for exposing resolver results through a `Cache` instead of returning another resolver + * * @category Persistence + * @since 4.0.0 */ & Persistable.Any>( options: { @@ -1637,8 +1939,27 @@ export const persisted: { Persistence.Persistence | Scope > /** - * @since 4.0.0 + * Wraps a request resolver with persistent storage for persistable requests. + * + * **When to use** + * + * Use to keep a `RequestResolver` interface while reusing completed + * `Persistable` request results through a `Persistence` store. + * + * **Details** + * + * Cached results are loaded from the configured persistence store before + * running the underlying resolver. Missing entries are resolved normally and + * written back to the store. Entries marked stale by `staleWhileRevalidate` + * receive the stored result and are also resolved again so the refreshed result + * can be written back to the store. Creating the persisted resolver requires + * `Persistence.Persistence` and `Scope`. + * + * @see {@link withCache} for in-memory resolver caching that does not require persistable request values or a persistence store + * @see {@link asCache} for exposing resolver results through a `Cache` instead of returning another resolver + * * @category Persistence + * @since 4.0.0 */ < A extends Request.Request & Persistable.Any @@ -1668,8 +1989,27 @@ export const persisted: { ) { const store = yield* (yield* Persistence.Persistence).make(options as any) return makeWith({ ...self, diff --git a/.opencode/node_modules/effect/src/Resource.ts b/.opencode/node_modules/effect/src/Resource.ts index 0043a56de503aede731dc41d880fffe503015af4..7e6d5383e8944c9899bf4cf55b9e74756a7ef992 100644 --- a/.opencode/node_modules/effect/src/Resource.ts +++ b/.opencode/node_modules/effect/src/Resource.ts @@ -1,4 +1,11 @@ /** + * Stores refreshable scoped values. + * + * A `Resource` keeps the latest successful or failed acquisition result. + * It can be read repeatedly, refreshed manually, or refreshed automatically on a + * schedule. Resource acquisition runs in a scope, so replacements and final + * cleanup release the resources owned by previous values. + * * @since 2.0.0 */ import * as Context from "./Context.ts" @@ -18,8 +25,18 @@ const TypeId = "~effect/Resource" as const * A `Resource` is a value loaded into memory that can be refreshed manually or * automatically according to a schedule. * - * @since 2.0.0 + * **When to use** + * + * Use to model a scoped value whose latest acquisition result is kept available + * for repeated reads and can be refreshed manually or on a schedule. + * + * @see {@link manual} for creating a resource refreshed by the caller + * @see {@link auto} for creating a resource refreshed according to a schedule + * @see {@link get} for reading the currently stored acquisition result + * @see {@link refresh} for forcing a new acquisition + * * @category models + * @since 2.0.0 */ export interface Resource extends Pipeable { readonly [TypeId]: typeof TypeId @@ -28,8 +45,19 @@ export interface Resource extends Pipeable { } /** - * @since 2.0.0 + * Returns `true` if the specified value is a `Resource`. + * + * **When to use** + * + * Use to validate unknown values at runtime boundaries before treating them as + * `Resource` values. + * + * **Details** + * + * This predicate narrows the input to `Resource`. + * * @category guards + * @since 4.0.0 */ export const isResource: (u: unknown) => u is Resource = ( u: unknown @@ -58,8 +86,15 @@ const makeUnsafe = ( /** * Creates a `Resource` that must be refreshed manually. * - * @since 2.0.0 + * **When to use** + * + * Use when you need manual control over resource refresh timing rather than an + * automatic schedule. + * + * @see {@link auto} for schedule-driven automatic refreshes + * @see {@link refresh} to manually trigger a resource refresh * @category constructors + * @since 2.0.0 */ export const manual = ( acquire: Effect.Effect @@ -79,8 +114,16 @@ export const manual = ( * Creates a `Resource` that refreshes automatically according to the supplied * schedule. * - * @since 2.0.0 + * **When to use** + * + * Use when a resource should refresh in the background according to a schedule + * for the lifetime of its scope. + * + * @see {@link manual} for caller-controlled refresh timing + * @see {@link refresh} to trigger a refresh explicitly + * * @category constructors + * @since 2.0.0 */ export const auto = ( acquire: Effect.Effect, @@ -94,17 +137,48 @@ export const auto = ( /** * Retrieves the current value stored in this resource. * - * @since 2.0.0 + * **When to use** + * + * Use to read the value currently cached by a `Resource`. + * + * **Gotchas** + * + * If the resource currently stores a failed acquisition result, the returned + * effect fails with the stored error. + * + * @see {@link refresh} to re-run acquisition and update the stored value before a later read + * * @category getters + * @since 2.0.0 */ export const get = (self: Resource): Effect.Effect => Effect.flatMap(ScopedRef.get(self.scopedRef), identity) /** - * Refreshes this resource. + * Re-runs this resource's acquisition effect and updates the current value. + * + * **When to use** + * + * Use to force an existing `Resource` to reacquire its value at a + * caller-controlled point. + * + * **Details** + * + * When acquisition succeeds, refreshing replaces the value stored in the + * resource's scoped reference and releases resources associated with the + * previous value. + * + * **Gotchas** + * + * If acquisition fails, the returned effect fails and the previously stored + * result is left as what `get` reads. + * + * @see {@link get} for reading the current stored value + * @see {@link manual} for resources refreshed only by caller action + * @see {@link auto} for schedule-driven automatic refreshes * + * @category resource management * @since 2.0.0 - * @category utils */ export const refresh = (self: Resource): Effect.Effect => ScopedRef.set(self.scopedRef, Effect.map(self.acquire, Exit.succeed)) diff --git a/.opencode/node_modules/effect/src/Result.ts b/.opencode/node_modules/effect/src/Result.ts index 93faa4d874cd05393f440c70700cc9c888b4bc6d..dd5d8ae11d31ee7c1296944acce7d91de0edfd04 100644 --- a/.opencode/node_modules/effect/src/Result.ts +++ b/.opencode/node_modules/effect/src/Result.ts @@ -1,74 +1,15 @@ /** - * A synchronous, pure type for representing computations that can succeed - * (`Success`) or fail (`Failure`). Unlike `Effect`, `Result` is - * evaluated eagerly and carries no side effects. - * - * **Mental model** - * - * - `Result` is a discriminated union: `Success | Failure` - * - `Success` wraps a value of type `A`, accessed via `.success` - * - `Failure` wraps an error of type `E`, accessed via `.failure` - * - `Result` is a monad: chain operations with {@link flatMap}, compose pipelines with `pipe` - * - All operations are pure and return new `Result` values; the input is never mutated - * - `Result` is yieldable in `Effect.gen`, producing the inner value or short-circuiting on failure - * - * **Common tasks** - * - * - Create from a value: {@link succeed}, {@link fail} - * - Create from nullable: {@link fromNullishOr} - * - Create from Option: {@link fromOption} - * - Create from throwing code: {@link try_ try} - * - Create from predicate: {@link liftPredicate} - * - Transform: {@link map}, {@link mapError}, {@link mapBoth} - * - Unwrap: {@link getOrElse}, {@link getOrNull}, {@link getOrUndefined}, {@link getOrThrow} - * - Pattern match: {@link match} - * - Sequence: {@link flatMap}, {@link andThen}, {@link all} - * - Recover: {@link orElse} - * - Filter: {@link filterOrFail} - * - Convert to Option: {@link getSuccess}, {@link getFailure} - * - Generator syntax: {@link gen} - * - Do notation: {@link Do}, {@link bind}, {@link let_ let} - * - Check variant: {@link isResult}, {@link isSuccess}, {@link isFailure} - * - * **Gotchas** - * - * - `E` defaults to `never`, so `Result` means a result that cannot fail - * - {@link andThen} accepts a `Result`, a function returning a `Result`, a plain value, or a function returning a plain value; {@link flatMap} only accepts a function returning a `Result` - * - {@link all} short-circuits on the first `Failure` and returns it; later elements are not inspected - * - {@link getOrThrow} throws the raw failure value `E`; use {@link getOrThrowWith} for custom error objects - * - {@link tap} runs a side-effect but does not change the result; its return value is ignored - * - * **Quickstart** - * - * **Example** (Parsing and validating with Result) + * Models a value that has already succeeded or failed. * - * ```ts - * import { Result } from "effect" - * - * const parse = (input: string): Result.Result => - * isNaN(Number(input)) - * ? Result.fail("not a number") - * : Result.succeed(Number(input)) - * - * const ensurePositive = (n: number): Result.Result => - * n > 0 ? Result.succeed(n) : Result.fail("not positive") - * - * const result = Result.flatMap(parse("42"), ensurePositive) - * - * console.log(Result.getOrElse(result, (err) => `Error: ${err}`)) - * // Output: 42 - * ``` - * - * **See also** - * - * - {@link succeed} / {@link fail} to create values - * - {@link match} to fold both branches - * - {@link gen} for generator-based composition + * A `Result` is `Success` when a value is available and + * `Failure` when an error is available. It is plain data, so inspecting + * or transforming it does not run side effects. This module includes helpers + * for creating, checking, mapping, combining, and extracting results, plus + * conversions to and from `Option` and nullable values. * * @since 4.0.0 */ -import type { Yieldable } from "./Effect.ts" import * as Equivalence from "./Equivalence.ts" import type { LazyArg } from "./Function.ts" import { constNull, constUndefined, dual, identity } from "./Function.ts" @@ -90,18 +31,19 @@ const TypeId = "~effect/data/Result" /** * A value that is either `Success` or `Failure`. * + * **When to use** + * + * Use when both success and failure should remain available as data and + * `Option` would lose failure information. + * + * **Details** + * * - Use {@link succeed} / {@link fail} to construct * - Use {@link match} to fold both branches * - Use {@link isSuccess} / {@link isFailure} to narrow the type * * `E` defaults to `never`, so `Result` means a result that cannot fail. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: - * - * - `Either` - * * **Example** (Creating and matching a Result) * * ```ts @@ -122,7 +64,7 @@ const TypeId = "~effect/data/Result" * @see {@link match} to fold both branches * @see {@link isSuccess} / {@link isFailure} for type guards * - * @category Models + * @category models * @since 4.0.0 */ export type Result = Success | Failure @@ -130,6 +72,8 @@ export type Result = Success | Failure /** * The failure variant of {@link Result}. Wraps an error of type `E`. * + * **Details** + * * - Access the error via the `.failure` property * - Use {@link isFailure} to narrow a `Result` to `Failure` * - Create with {@link fail} @@ -151,10 +95,10 @@ export type Result = Success | Failure * @see {@link isFailure} to narrow the type * @see {@link Success} for the other variant * - * @category Models + * @category models * @since 4.0.0 */ -export interface Failure extends Pipeable, Inspectable, Yieldable, A, E> { +export interface Failure extends Pipeable, Inspectable { readonly _tag: "Failure" readonly _op: "Failure" readonly failure: E @@ -162,14 +106,37 @@ export interface Failure extends Pipeable, Inspectable, Yieldable< readonly _A: Covariant readonly _E: Covariant } + [Symbol.iterator](): ResultIterator> [Unify.typeSymbol]?: unknown [Unify.unifySymbol]?: ResultUnify [Unify.ignoreSymbol]?: ResultUnifyIgnore } +/** + * Iterator protocol used to yield a `Result` inside {@link gen}, returning the + * success value type back to the generator. + * + * **When to use** + * + * Use when defining or typing `[Symbol.iterator]()` for `Result` values so + * `yield*` can pass the success value type back into `Result.gen`. + * + * @see {@link gen} for writing generator-based `Result` code that consumes this iterator protocol + * + * @category generators + * @since 4.0.0 + */ +export interface ResultIterator> { + next( + ...args: ReadonlyArray + ): IteratorResult> +} + /** * The success variant of {@link Result}. Wraps a value of type `A`. * + * **Details** + * * - Access the value via the `.success` property * - Use {@link isSuccess} to narrow a `Result` to `Success` * - Create with {@link succeed} @@ -191,10 +158,10 @@ export interface Failure extends Pipeable, Inspectable, Yieldable< * @see {@link isSuccess} to narrow the type * @see {@link Failure} for the other variant * - * @category Models + * @category models * @since 4.0.0 */ -export interface Success extends Pipeable, Inspectable, Yieldable, A, E> { +export interface Success extends Pipeable, Inspectable { readonly _tag: "Success" readonly _op: "Success" readonly success: A @@ -202,6 +169,7 @@ export interface Success extends Pipeable, Inspectable, Yieldable< readonly _A: Covariant readonly _E: Covariant } + [Symbol.iterator](): ResultIterator> [Unify.typeSymbol]?: unknown [Unify.unifySymbol]?: ResultUnify [Unify.ignoreSymbol]?: ResultUnifyIgnore @@ -210,10 +178,12 @@ export interface Success extends Pipeable, Inspectable, Yieldable< /** * Type-level utility for unifying `Result` types in generic contexts. * + * **Details** + * * This is an internal interface used by the Effect type system. You typically * do not need to reference it directly. * - * @category Models + * @category models * @since 4.0.0 */ export interface ResultUnify { @@ -223,10 +193,12 @@ export interface ResultUnify { /** * Marker interface for ignoring unification in `Result` types. * + * **Details** + * * This is an internal interface used by the Effect type system. You typically * do not need to reference it directly. * - * @category Models + * @category models * @since 4.0.0 */ export interface ResultUnifyIgnore {} @@ -234,11 +206,13 @@ export interface ResultUnifyIgnore {} /** * Higher-kinded type representation for `Result`. * + * **Details** + * * Used internally to integrate `Result` with generic type-class utilities * (e.g., `map`, `flatMap` abstractions). You typically do not need to * reference this directly. * - * @category Type Lambdas + * @category type lambdas * @since 4.0.0 */ export interface ResultTypeLambda extends TypeLambda { @@ -263,22 +237,21 @@ export interface ResultTypeLambda extends TypeLambda { * type E = Result.Result.Failure * ``` * - * @category Type Level * @since 4.0.0 */ export declare namespace Result { /** * Extracts the failure type `E` from `Result`. * - * @since 4.0.0 * @category Type Level + * @since 4.0.0 */ export type Failure> = [T] extends [Result] ? _E : never /** * Extracts the success type `A` from `Result`. * - * @since 4.0.0 * @category Type Level + * @since 4.0.0 */ export type Success> = [T] extends [Result] ? _A : never } @@ -286,15 +259,10 @@ export declare namespace Result { /** * Creates a `Result` holding a `Success` value. * + * **Details** + * * - Use when you have a value and want to lift it into the `Result` type * - The error type `E` defaults to `never` - * - Does not mutate input; allocates a new `Success` wrapper - * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: - * - * - `Either.right` * * **Example** (Wrapping a value) * @@ -308,9 +276,9 @@ export declare namespace Result { * ``` * * @see {@link fail} to create a Failure - * @see {@link void} for a pre-built `Success` + * @see {@link void_ void} for a pre-built `Success` * - * @category Constructors + * @category constructors * @since 4.0.0 */ export const succeed: (right: A) => Result = result.succeed @@ -318,15 +286,13 @@ export const succeed: (right: A) => Result = result.succeed /** * Creates a `Result` holding a `Failure` value. * - * - Use when you want to represent a failed computation - * - The success type `A` defaults to `never` - * - Does not mutate input; allocates a new `Failure` wrapper + * **When to use** * - * **Previously Known As** + * Use to represent a failed `Result` with a typed failure value. * - * This API replaces the following from Effect 3.x: + * **Details** * - * - `Either.left` + * - The success type `A` defaults to `never` * * **Example** (Creating a failure) * @@ -342,7 +308,7 @@ export const succeed: (right: A) => Result = result.succeed * @see {@link succeed} to create a Success * @see {@link mapError} to transform the error * - * @category Constructors + * @category constructors * @since 4.0.0 */ export const fail: (left: E) => Result = result.fail @@ -350,10 +316,17 @@ export const fail: (left: E) => Result = result.fail const void_: Result = succeed(void 0) export { /** - * A pre-built `Result` holding `undefined` as its success value. + * Provides a pre-built successful `Result` that carries `undefined`. + * + * **When to use** + * + * Use when you need a successful `Result` value that signals completion + * without carrying meaningful data. * - * - Use when you need a `Result` that represents "completed with no meaningful value" - * - Equivalent to `Result.succeed(undefined)` but avoids an extra allocation + * **Details** + * + * This is equivalent to `Result.succeed(undefined)`, but reuses a shared + * `Success` wrapper instead of allocating one each time. * * **Example** (Using void result) * @@ -366,23 +339,42 @@ export { * // Output: true * ``` * - * @see {@link succeed} + * @see {@link succeed} to create a Success with a specific value * - * @category Constructors - * @since 4.0.0 + * @category constructors + * @since 3.13.0 */ void_ as void } /** - * A pre-built `Result` holding `undefined` as its failure value. + * Provides a pre-built failed `Result` whose failure value is `undefined`. * - * - Use when you need a `Result` that represents "failed with no meaningful value" - * - Equivalent to `Result.fail(undefined)` but avoids an extra allocation + * **When to use** * - * @see {@link fail} + * Use when you need a failed `Result` value that acts only as a control signal + * without failure data. * - * @category Constructors + * **Details** + * + * This is equivalent to `Result.fail(undefined)` with type + * `Result`, but reuses a shared `Failure` wrapper instead of + * allocating one each time. + * + * **Example** (Using a failure without a payload) + * + * ```ts + * import { Result } from "effect" + * + * const result = Result.failVoid + * + * console.log(Result.isFailure(result)) + * // Output: true + * ``` + * + * @see {@link fail} to create a Failure with a specific value + * + * @category constructors * @since 4.0.0 */ export const failVoid: Result = fail(void 0) @@ -390,6 +382,13 @@ export const failVoid: Result = fail(void 0) /** * Converts a possibly `null` or `undefined` value into a `Result`. * + * **When to use** + * + * Use when you need `null` or `undefined` input to become a `Failure` while + * present values remain available as `Success`. + * + * **Details** + * * - Non-nullish values become `Success>` * - `null` or `undefined` becomes `Failure` using the provided function * - Supports both data-first and data-last (piped) usage @@ -410,13 +409,20 @@ export const failVoid: Result = fail(void 0) * @see {@link fromOption} to convert from an Option * @see {@link succeed} / {@link fail} for direct construction * - * @category Constructors + * @category constructors * @since 4.0.0 */ export const fromNullishOr: { /** * Converts a possibly `null` or `undefined` value into a `Result`. * + * **When to use** + * + * Use when you need `null` or `undefined` input to become a `Failure` while + * present values remain available as `Success`. + * + * **Details** + * * - Non-nullish values become `Success>` * - `null` or `undefined` becomes `Failure` using the provided function * - Supports both data-first and data-last (piped) usage @@ -437,13 +443,20 @@ export const fromNullishOr: { * @see {@link fromOption} to convert from an Option * @see {@link succeed} / {@link fail} for direct construction * - * @category Constructors + * @category constructors * @since 4.0.0 */ (onNullish: (a: A) => E): (self: A) => Result, E> /** * Converts a possibly `null` or `undefined` value into a `Result`. * + * **When to use** + * + * Use when you need `null` or `undefined` input to become a `Failure` while + * present values remain available as `Success`. + * + * **Details** + * * - Non-nullish values become `Success>` * - `null` or `undefined` becomes `Failure` using the provided function * - Supports both data-first and data-last (piped) usage @@ -464,7 +477,7 @@ export const fromNullishOr: { * @see {@link fromOption} to convert from an Option * @see {@link succeed} / {@link fail} for direct construction * - * @category Constructors + * @category constructors * @since 4.0.0 */ (self: A, onNullish: (a: A) => E): Result, E> @@ -477,6 +490,13 @@ export const fromNullishOr: { /** * Converts an `Option` into a `Result`. * + * **When to use** + * + * Use when an existing `Option` should become a `Result`, preserving `Some` as + * success and turning `None` into a caller-provided failure. + * + * **Details** + * * - `Some` becomes `Success` * - `None` becomes `Failure` using the provided function * - Supports both data-first and data-last (piped) usage @@ -495,16 +515,24 @@ export const fromNullishOr: { * // Output: { _tag: "Failure", failure: "missing", ... } * ``` * - * @see {@link getSuccess} / {@link getFailure} to convert back to Option - * @see {@link fromNullishOr} to convert from nullable values + * @see {@link getSuccess} to extract the success value as an Option + * @see {@link getFailure} to extract the failure value as an Option + * @see {@link fromNullishOr} to build a Result from nullable values * - * @category Constructors - * @since 4.0.0 + * @category constructors + * @since 2.0.0 */ export const fromOption: { /** * Converts an `Option` into a `Result`. * + * **When to use** + * + * Use when an existing `Option` should become a `Result`, preserving `Some` as + * success and turning `None` into a caller-provided failure. + * + * **Details** + * * - `Some` becomes `Success` * - `None` becomes `Failure` using the provided function * - Supports both data-first and data-last (piped) usage @@ -523,16 +551,24 @@ export const fromOption: { * // Output: { _tag: "Failure", failure: "missing", ... } * ``` * - * @see {@link getSuccess} / {@link getFailure} to convert back to Option - * @see {@link fromNullishOr} to convert from nullable values + * @see {@link getSuccess} to extract the success value as an Option + * @see {@link getFailure} to extract the failure value as an Option + * @see {@link fromNullishOr} to build a Result from nullable values * - * @category Constructors - * @since 4.0.0 + * @category constructors + * @since 2.0.0 */ (onNone: () => E): (self: Option) => Result /** * Converts an `Option` into a `Result`. * + * **When to use** + * + * Use when an existing `Option` should become a `Result`, preserving `Some` as + * success and turning `None` into a caller-provided failure. + * + * **Details** + * * - `Some` becomes `Success` * - `None` becomes `Failure` using the provided function * - Supports both data-first and data-last (piped) usage @@ -551,11 +587,12 @@ export const fromOption: { * // Output: { _tag: "Failure", failure: "missing", ... } * ``` * - * @see {@link getSuccess} / {@link getFailure} to convert back to Option - * @see {@link fromNullishOr} to convert from nullable values + * @see {@link getSuccess} to extract the success value as an Option + * @see {@link getFailure} to extract the failure value as an Option + * @see {@link fromNullishOr} to build a Result from nullable values * - * @category Constructors - * @since 4.0.0 + * @category constructors + * @since 2.0.0 */ (self: Option, onNone: () => E): Result } = result.fromOption @@ -591,7 +628,9 @@ const try_: { export { /** - * Wraps a synchronous computation that may throw into a `Result`. + * Wraps a synchronous computation that may throw into a `Result` safely. + * + * **Details** * * - If the function returns normally, the result is `Success` * - If the function throws, the exception is caught and becomes `Failure` @@ -618,16 +657,21 @@ export { * @see {@link succeed} / {@link fail} for direct construction * @see {@link fromNullishOr} for nullable values * - * @category Constructors - * @since 4.0.0 + * @category constructors + * @since 2.0.0 */ try_ as try } /** - * Tests whether a value is a `Result` (either `Success` or `Failure`). + * Checks whether a value is a `Result` (either `Success` or `Failure`). + * + * **When to use** + * + * Use to validate unknown input before operating on it as a `Result`. + * + * **Details** * - * - Use to validate unknown input before operating on it as a `Result` * - Returns `true` for both `Success` and `Failure` variants * - Acts as a TypeScript type guard, narrowing to `Result` * @@ -645,7 +689,7 @@ export { * * @see {@link isSuccess} / {@link isFailure} to narrow to a specific variant * - * @category Type Guards + * @category guards * @since 4.0.0 */ export const isResult: (input: unknown) => input is Result = result.isResult @@ -653,6 +697,12 @@ export const isResult: (input: unknown) => input is Result = r /** * Checks whether a `Result` is a `Failure`. * + * **When to use** + * + * Use to narrow a known `Result` to the `Failure` variant. + * + * **Details** + * * - Acts as a TypeScript type guard, narrowing to `Failure` * - After narrowing, you can access `.failure` to read the error value * @@ -672,7 +722,7 @@ export const isResult: (input: unknown) => input is Result = r * @see {@link isSuccess} for the opposite check * @see {@link isResult} to check if a value is any Result * - * @category Type Guards + * @category guards * @since 4.0.0 */ export const isFailure: (self: Result) => self is Failure = result.isFailure @@ -680,6 +730,12 @@ export const isFailure: (self: Result) => self is Failure = re /** * Checks whether a `Result` is a `Success`. * + * **When to use** + * + * Use to narrow a known `Result` to the `Success` variant. + * + * **Details** + * * - Acts as a TypeScript type guard, narrowing to `Success` * - After narrowing, you can access `.success` to read the value * @@ -699,7 +755,7 @@ export const isFailure: (self: Result) => self is Failure = re * @see {@link isFailure} for the opposite check * @see {@link isResult} to check if a value is any Result * - * @category Type Guards + * @category guards * @since 4.0.0 */ export const isSuccess: (self: Result) => self is Success = result.isSuccess @@ -707,9 +763,15 @@ export const isSuccess: (self: Result) => self is Success = re /** * Extracts the success value as an `Option`, discarding the failure. * + * **When to use** + * + * Use when you need to extract the success value from a `Result` as an + * `Option` and discard failure information. + * + * **Details** + * * - `Success` becomes `Some` * - `Failure` becomes `None` - * - Use when you only care about the success case and want to discard error info * * **Example** (Extracting the success as an Option) * @@ -726,7 +788,7 @@ export const isSuccess: (self: Result) => self is Success = re * @see {@link getFailure} to extract the error instead * @see {@link fromOption} for the reverse conversion * - * @category Getters + * @category getters * @since 4.0.0 */ export const getSuccess: (self: Result) => Option = result.getSuccess @@ -734,9 +796,15 @@ export const getSuccess: (self: Result) => Option = result.getSuc /** * Extracts the failure value as an `Option`, discarding the success. * + * **When to use** + * + * Use when you need to extract the failure value from a `Result` as an + * `Option` and discard successful values. + * + * **Details** + * * - `Failure` becomes `Some` * - `Success` becomes `None` - * - Use when you only care about the error case * * **Example** (Extracting the failure as an Option) * @@ -753,7 +821,7 @@ export const getSuccess: (self: Result) => Option = result.getSuc * @see {@link getSuccess} to extract the success instead * @see {@link fromOption} for the reverse conversion * - * @category Getters + * @category getters * @since 4.0.0 */ export const getFailure: (self: Result) => Option = result.getFailure @@ -761,6 +829,8 @@ export const getFailure: (self: Result) => Option = result.getFai /** * Creates an `Equivalence` for comparing two `Result` values. * + * **Details** + * * - Two `Success` values are equal when the `success` equivalence says so * - Two `Failure` values are equal when the `failure` equivalence says so * - A `Success` and a `Failure` are never equal @@ -782,7 +852,7 @@ export const getFailure: (self: Result) => Option = result.getFai * // Output: false * ``` * - * @category Equivalence + * @category instances * @since 4.0.0 */ export const makeEquivalence = ( @@ -798,10 +868,15 @@ export const makeEquivalence = ( /** * Transforms both the success and failure channels of a `Result`. * + * **When to use** + * + * Use to transform both success and failure values without changing whether the + * result succeeds or fails. + * + * **Details** + * * - Applies `onSuccess` if the result is a `Success` * - Applies `onFailure` if the result is a `Failure` - * - Returns a new `Result`; does not mutate the input - * - Use when you need to transform both channels in a single operation * * **Example** (Mapping both channels) * @@ -823,17 +898,22 @@ export const makeEquivalence = ( * @see {@link mapError} to transform only the error value * @see {@link match} to fold into a single value * - * @category Mapping - * @since 4.0.0 + * @category mapping + * @since 2.0.0 */ export const mapBoth: { /** * Transforms both the success and failure channels of a `Result`. * + * **When to use** + * + * Use to transform both success and failure values without changing whether the + * result succeeds or fails. + * + * **Details** + * * - Applies `onSuccess` if the result is a `Success` * - Applies `onFailure` if the result is a `Failure` - * - Returns a new `Result`; does not mutate the input - * - Use when you need to transform both channels in a single operation * * **Example** (Mapping both channels) * @@ -855,8 +935,8 @@ export const mapBoth: { * @see {@link mapError} to transform only the error value * @see {@link match} to fold into a single value * - * @category Mapping - * @since 4.0.0 + * @category mapping + * @since 2.0.0 */ ( options: { @@ -867,10 +947,15 @@ export const mapBoth: { /** * Transforms both the success and failure channels of a `Result`. * + * **When to use** + * + * Use to transform both success and failure values without changing whether the + * result succeeds or fails. + * + * **Details** + * * - Applies `onSuccess` if the result is a `Success` * - Applies `onFailure` if the result is a `Failure` - * - Returns a new `Result`; does not mutate the input - * - Use when you need to transform both channels in a single operation * * **Example** (Mapping both channels) * @@ -892,8 +977,8 @@ export const mapBoth: { * @see {@link mapError} to transform only the error value * @see {@link match} to fold into a single value * - * @category Mapping - * @since 4.0.0 + * @category mapping + * @since 2.0.0 */ ( self: Result, @@ -913,9 +998,14 @@ export const mapBoth: { /** * Transforms the failure channel of a `Result`, leaving the success channel unchanged. * + * **When to use** + * + * Use to transform only the failure channel while preserving success values. + * + * **Details** + * * - If the result is a `Failure`, applies `f` to the error and returns a new `Failure` * - If the result is a `Success`, returns it as-is - * - Does not mutate the input * * **Example** (Adding context to an error) * @@ -933,16 +1023,21 @@ export const mapBoth: { * @see {@link map} to transform only the success value * @see {@link mapBoth} to transform both channels * - * @category Mapping + * @category mapping * @since 4.0.0 */ export const mapError: { /** * Transforms the failure channel of a `Result`, leaving the success channel unchanged. * + * **When to use** + * + * Use to transform only the failure channel while preserving success values. + * + * **Details** + * * - If the result is a `Failure`, applies `f` to the error and returns a new `Failure` * - If the result is a `Success`, returns it as-is - * - Does not mutate the input * * **Example** (Adding context to an error) * @@ -960,16 +1055,21 @@ export const mapError: { * @see {@link map} to transform only the success value * @see {@link mapBoth} to transform both channels * - * @category Mapping + * @category mapping * @since 4.0.0 */ (f: (err: E) => E2): (self: Result) => Result /** * Transforms the failure channel of a `Result`, leaving the success channel unchanged. * + * **When to use** + * + * Use to transform only the failure channel while preserving success values. + * + * **Details** + * * - If the result is a `Failure`, applies `f` to the error and returns a new `Failure` * - If the result is a `Success`, returns it as-is - * - Does not mutate the input * * **Example** (Adding context to an error) * @@ -987,7 +1087,7 @@ export const mapError: { * @see {@link map} to transform only the success value * @see {@link mapBoth} to transform both channels * - * @category Mapping + * @category mapping * @since 4.0.0 */ (self: Result, f: (err: E) => E2): Result @@ -1000,9 +1100,15 @@ export const mapError: { /** * Transforms the success channel of a `Result`, leaving the failure channel unchanged. * + * **When to use** + * + * Use to apply a transformation to the success value of a `Result` while + * preserving any existing failure. + * + * **Details** + * * - If the result is a `Success`, applies `f` to the value and returns a new `Success` * - If the result is a `Failure`, returns it as-is - * - Does not mutate the input * - Use {@link flatMap} if `f` returns a `Result` (to avoid nested Results) * * **Example** (Doubling the success value) @@ -1022,16 +1128,22 @@ export const mapError: { * @see {@link mapBoth} to transform both channels * @see {@link flatMap} when `f` returns a `Result` * - * @category Mapping - * @since 4.0.0 + * @category mapping + * @since 2.0.0 */ export const map: { /** * Transforms the success channel of a `Result`, leaving the failure channel unchanged. * + * **When to use** + * + * Use to apply a transformation to the success value of a `Result` while + * preserving any existing failure. + * + * **Details** + * * - If the result is a `Success`, applies `f` to the value and returns a new `Success` * - If the result is a `Failure`, returns it as-is - * - Does not mutate the input * - Use {@link flatMap} if `f` returns a `Result` (to avoid nested Results) * * **Example** (Doubling the success value) @@ -1051,16 +1163,22 @@ export const map: { * @see {@link mapBoth} to transform both channels * @see {@link flatMap} when `f` returns a `Result` * - * @category Mapping - * @since 4.0.0 + * @category mapping + * @since 2.0.0 */ (f: (ok: A) => A2): (self: Result) => Result /** * Transforms the success channel of a `Result`, leaving the failure channel unchanged. * + * **When to use** + * + * Use to apply a transformation to the success value of a `Result` while + * preserving any existing failure. + * + * **Details** + * * - If the result is a `Success`, applies `f` to the value and returns a new `Success` * - If the result is a `Failure`, returns it as-is - * - Does not mutate the input * - Use {@link flatMap} if `f` returns a `Result` (to avoid nested Results) * * **Example** (Doubling the success value) @@ -1080,8 +1198,8 @@ export const map: { * @see {@link mapBoth} to transform both channels * @see {@link flatMap} when `f` returns a `Result` * - * @category Mapping - * @since 4.0.0 + * @category mapping + * @since 2.0.0 */ (self: Result, f: (ok: A) => A2): Result } = dual( @@ -1093,10 +1211,16 @@ export const map: { /** * Folds a `Result` into a single value by applying one of two functions. * + * **When to use** + * + * Use when a `Result`'s success and failure branches should be collapsed into + * one plain output type. + * + * **Details** + * * - Applies `onSuccess` if the result is a `Success` * - Applies `onFailure` if the result is a `Failure` * - Both branches must return the same type (or a common supertype) - * - Use when you need to "exit" the `Result` type and produce a plain value * * **Example** (Folding to a string) * @@ -1118,17 +1242,23 @@ export const map: { * @see {@link merge} to extract `A | E` without mapping * @see {@link getOrElse} to unwrap only the success with a fallback * - * @category Pattern Matching - * @since 4.0.0 + * @category pattern matching + * @since 2.0.0 */ export const match: { /** * Folds a `Result` into a single value by applying one of two functions. * + * **When to use** + * + * Use when a `Result`'s success and failure branches should be collapsed into + * one plain output type. + * + * **Details** + * * - Applies `onSuccess` if the result is a `Success` * - Applies `onFailure` if the result is a `Failure` * - Both branches must return the same type (or a common supertype) - * - Use when you need to "exit" the `Result` type and produce a plain value * * **Example** (Folding to a string) * @@ -1150,8 +1280,8 @@ export const match: { * @see {@link merge} to extract `A | E` without mapping * @see {@link getOrElse} to unwrap only the success with a fallback * - * @category Pattern Matching - * @since 4.0.0 + * @category pattern matching + * @since 2.0.0 */ ( options: { @@ -1162,10 +1292,16 @@ export const match: { /** * Folds a `Result` into a single value by applying one of two functions. * + * **When to use** + * + * Use when a `Result`'s success and failure branches should be collapsed into + * one plain output type. + * + * **Details** + * * - Applies `onSuccess` if the result is a `Success` * - Applies `onFailure` if the result is a `Failure` * - Both branches must return the same type (or a common supertype) - * - Use when you need to "exit" the `Result` type and produce a plain value * * **Example** (Folding to a string) * @@ -1187,8 +1323,8 @@ export const match: { * @see {@link merge} to extract `A | E` without mapping * @see {@link getOrElse} to unwrap only the success with a fallback * - * @category Pattern Matching - * @since 4.0.0 + * @category pattern matching + * @since 2.0.0 */ ( self: Result, @@ -1208,6 +1344,13 @@ export const match: { /** * Lifts a value into a `Result` based on a predicate or refinement. * + * **When to use** + * + * Use to construct a `Result` from a raw value guarded by a predicate or + * refinement. + * + * **Details** + * * - If the predicate returns `true`, the value becomes `Success` * - If the predicate returns `false`, `orFailWith` produces the error for `Failure` * - Also accepts a `Refinement` to narrow the success type @@ -1232,13 +1375,20 @@ export const match: { * @see {@link filterOrFail} to validate a value that is already in a `Result` * @see {@link fromNullishOr} for nullable-based construction * - * @category Constructors - * @since 4.0.0 + * @category constructors + * @since 3.4.0 */ export const liftPredicate: { /** * Lifts a value into a `Result` based on a predicate or refinement. * + * **When to use** + * + * Use to construct a `Result` from a raw value guarded by a predicate or + * refinement. + * + * **Details** + * * - If the predicate returns `true`, the value becomes `Success` * - If the predicate returns `false`, `orFailWith` produces the error for `Failure` * - Also accepts a `Refinement` to narrow the success type @@ -1263,13 +1413,20 @@ export const liftPredicate: { * @see {@link filterOrFail} to validate a value that is already in a `Result` * @see {@link fromNullishOr} for nullable-based construction * - * @category Constructors - * @since 4.0.0 + * @category constructors + * @since 3.4.0 */ (refinement: Refinement, orFailWith: (a: A) => E): (a: A) => Result /** * Lifts a value into a `Result` based on a predicate or refinement. * + * **When to use** + * + * Use to construct a `Result` from a raw value guarded by a predicate or + * refinement. + * + * **Details** + * * - If the predicate returns `true`, the value becomes `Success` * - If the predicate returns `false`, `orFailWith` produces the error for `Failure` * - Also accepts a `Refinement` to narrow the success type @@ -1294,13 +1451,20 @@ export const liftPredicate: { * @see {@link filterOrFail} to validate a value that is already in a `Result` * @see {@link fromNullishOr} for nullable-based construction * - * @category Constructors - * @since 4.0.0 + * @category constructors + * @since 3.4.0 */ (predicate: Predicate, orFailWith: (a: A) => E): (a: B) => Result /** * Lifts a value into a `Result` based on a predicate or refinement. * + * **When to use** + * + * Use to construct a `Result` from a raw value guarded by a predicate or + * refinement. + * + * **Details** + * * - If the predicate returns `true`, the value becomes `Success` * - If the predicate returns `false`, `orFailWith` produces the error for `Failure` * - Also accepts a `Refinement` to narrow the success type @@ -1325,13 +1489,20 @@ export const liftPredicate: { * @see {@link filterOrFail} to validate a value that is already in a `Result` * @see {@link fromNullishOr} for nullable-based construction * - * @category Constructors - * @since 4.0.0 + * @category constructors + * @since 3.4.0 */ (self: A, refinement: Refinement, orFailWith: (a: A) => E): Result /** * Lifts a value into a `Result` based on a predicate or refinement. * + * **When to use** + * + * Use to construct a `Result` from a raw value guarded by a predicate or + * refinement. + * + * **Details** + * * - If the predicate returns `true`, the value becomes `Success` * - If the predicate returns `false`, `orFailWith` produces the error for `Failure` * - Also accepts a `Refinement` to narrow the success type @@ -1356,8 +1527,8 @@ export const liftPredicate: { * @see {@link filterOrFail} to validate a value that is already in a `Result` * @see {@link fromNullishOr} for nullable-based construction * - * @category Constructors - * @since 4.0.0 + * @category constructors + * @since 3.4.0 */ (self: B, predicate: Predicate, orFailWith: (a: A) => E): Result } = dual( @@ -1370,6 +1541,13 @@ export const liftPredicate: { * Validates the success value of a `Result` using a predicate, failing with a * custom error if the predicate returns `false`. * + * **When to use** + * + * Use to validate an already-successful `Result` value with a predicate or + * refinement. + * + * **Details** + * * - If the result is already a `Failure`, it is returned as-is * - If the predicate passes, the `Success` is returned unchanged * - If the predicate fails, `orFailWith` produces the error for a new `Failure` @@ -1395,14 +1573,21 @@ export const liftPredicate: { * @see {@link liftPredicate} to create a `Result` from a raw value with a predicate * @see {@link flatMap} for general conditional chaining * + * @category filtering * @since 4.0.0 - * @category Filtering */ export const filterOrFail: { /** * Validates the success value of a `Result` using a predicate, failing with a * custom error if the predicate returns `false`. * + * **When to use** + * + * Use to validate an already-successful `Result` value with a predicate or + * refinement. + * + * **Details** + * * - If the result is already a `Failure`, it is returned as-is * - If the predicate passes, the `Success` is returned unchanged * - If the predicate fails, `orFailWith` produces the error for a new `Failure` @@ -1428,8 +1613,8 @@ export const filterOrFail: { * @see {@link liftPredicate} to create a `Result` from a raw value with a predicate * @see {@link flatMap} for general conditional chaining * + * @category filtering * @since 4.0.0 - * @category Filtering */ ( refinement: Refinement, B>, @@ -1439,6 +1624,13 @@ export const filterOrFail: { * Validates the success value of a `Result` using a predicate, failing with a * custom error if the predicate returns `false`. * + * **When to use** + * + * Use to validate an already-successful `Result` value with a predicate or + * refinement. + * + * **Details** + * * - If the result is already a `Failure`, it is returned as-is * - If the predicate passes, the `Success` is returned unchanged * - If the predicate fails, `orFailWith` produces the error for a new `Failure` @@ -1464,14 +1656,21 @@ export const filterOrFail: { * @see {@link liftPredicate} to create a `Result` from a raw value with a predicate * @see {@link flatMap} for general conditional chaining * + * @category filtering * @since 4.0.0 - * @category Filtering */ (predicate: Predicate>, orFailWith: (value: NoInfer) => E2): (self: Result) => Result /** * Validates the success value of a `Result` using a predicate, failing with a * custom error if the predicate returns `false`. * + * **When to use** + * + * Use to validate an already-successful `Result` value with a predicate or + * refinement. + * + * **Details** + * * - If the result is already a `Failure`, it is returned as-is * - If the predicate passes, the `Success` is returned unchanged * - If the predicate fails, `orFailWith` produces the error for a new `Failure` @@ -1497,8 +1696,8 @@ export const filterOrFail: { * @see {@link liftPredicate} to create a `Result` from a raw value with a predicate * @see {@link flatMap} for general conditional chaining * + * @category filtering * @since 4.0.0 - * @category Filtering */ ( self: Result, @@ -1509,6 +1708,13 @@ export const filterOrFail: { * Validates the success value of a `Result` using a predicate, failing with a * custom error if the predicate returns `false`. * + * **When to use** + * + * Use to validate an already-successful `Result` value with a predicate or + * refinement. + * + * **Details** + * * - If the result is already a `Failure`, it is returned as-is * - If the predicate passes, the `Success` is returned unchanged * - If the predicate fails, `orFailWith` produces the error for a new `Failure` @@ -1534,8 +1740,8 @@ export const filterOrFail: { * @see {@link liftPredicate} to create a `Result` from a raw value with a predicate * @see {@link flatMap} for general conditional chaining * + * @category filtering * @since 4.0.0 - * @category Filtering */ (self: Result, predicate: Predicate, orFailWith: (value: A) => E2): Result } = dual(3, ( @@ -1548,6 +1754,8 @@ export const filterOrFail: { * Unwraps a `Result` into `A | E` by returning the inner value regardless * of whether it is a success or failure. * + * **Details** + * * - `Success` returns `A` * - `Failure` returns `E` * - Useful when both channels share a compatible type @@ -1567,14 +1775,21 @@ export const filterOrFail: { * @see {@link match} to map each branch to a common type * @see {@link getOrElse} to provide a fallback for failures * - * @category Getters - * @since 4.0.0 + * @category getters + * @since 2.0.0 */ export const merge: (self: Result) => E | A = match({ onFailure: identity, onSuccess: identity }) /** * Extracts the success value, or computes a fallback from the error. * + * **When to use** + * + * Use when you need the success value from a `Result`, with a fallback computed + * from the failure value. + * + * **Details** + * * - `Success` returns the inner value * - `Failure` applies `onFailure` to the error and returns the result * - The return type is `A | A2` (union of both branches) @@ -1594,14 +1809,22 @@ export const merge: (self: Result) => E | A = match({ onFailure: ide * @see {@link getOrNull} / {@link getOrUndefined} for simpler fallbacks * @see {@link getOrThrow} to throw on failure * @see {@link match} to map both branches + * @see {@link orElse} to recover with another Result instead of unwrapping * - * @category Getters - * @since 4.0.0 + * @category getters + * @since 2.0.0 */ export const getOrElse: { /** * Extracts the success value, or computes a fallback from the error. * + * **When to use** + * + * Use when you need the success value from a `Result`, with a fallback computed + * from the failure value. + * + * **Details** + * * - `Success` returns the inner value * - `Failure` applies `onFailure` to the error and returns the result * - The return type is `A | A2` (union of both branches) @@ -1621,14 +1844,22 @@ export const getOrElse: { * @see {@link getOrNull} / {@link getOrUndefined} for simpler fallbacks * @see {@link getOrThrow} to throw on failure * @see {@link match} to map both branches + * @see {@link orElse} to recover with another Result instead of unwrapping * - * @category Getters - * @since 4.0.0 + * @category getters + * @since 2.0.0 */ (onFailure: (err: E) => A2): (self: Result) => A2 | A /** * Extracts the success value, or computes a fallback from the error. * + * **When to use** + * + * Use when you need the success value from a `Result`, with a fallback computed + * from the failure value. + * + * **Details** + * * - `Success` returns the inner value * - `Failure` applies `onFailure` to the error and returns the result * - The return type is `A | A2` (union of both branches) @@ -1648,9 +1879,10 @@ export const getOrElse: { * @see {@link getOrNull} / {@link getOrUndefined} for simpler fallbacks * @see {@link getOrThrow} to throw on failure * @see {@link match} to map both branches + * @see {@link orElse} to recover with another Result instead of unwrapping * - * @category Getters - * @since 4.0.0 + * @category getters + * @since 2.0.0 */ (self: Result, onFailure: (err: E) => A2): A | A2 } = dual( @@ -1662,9 +1894,15 @@ export const getOrElse: { /** * Extracts the success value, or returns `null` on failure. * + * **When to use** + * + * Use when you need to pass failed `Result` values to APIs that represent + * absence as `null`. + * + * **Details** + * * - `Success` returns `A` * - `Failure` returns `null` - * - Convenient for interop with APIs that use `null` to represent absence * * **Example** (Unwrapping to nullable) * @@ -1681,17 +1919,23 @@ export const getOrElse: { * @see {@link getOrUndefined} to return `undefined` instead * @see {@link getOrElse} for a custom fallback * - * @category Getters - * @since 4.0.0 + * @category getters + * @since 2.0.0 */ export const getOrNull: (self: Result) => A | null = getOrElse(constNull) /** * Extracts the success value, or returns `undefined` on failure. * + * **When to use** + * + * Use when you need to pass failed `Result` values to APIs that represent + * absence as `undefined`. + * + * **Details** + * * - `Success` returns `A` * - `Failure` returns `undefined` - * - Convenient for interop with APIs that use `undefined` to represent absence * * **Example** (Unwrapping to optional) * @@ -1708,18 +1952,23 @@ export const getOrNull: (self: Result) => A | null = getOrElse(const * @see {@link getOrNull} to return `null` instead * @see {@link getOrElse} for a custom fallback * - * @category Getters - * @since 4.0.0 + * @category getters + * @since 2.0.0 */ export const getOrUndefined: (self: Result) => A | undefined = getOrElse(constUndefined) /** * Extracts the success value or throws a custom error derived from the failure. * + * **When to use** + * + * Use when converting a `Result` into a thrown exception with a custom error + * message or error type. + * + * **Details** + * * - `Success` returns `A` * - `Failure` throws the value returned by `onFailure(e)` - * - Use when you want to convert a `Result` into a thrown exception with a - * custom error message or error type * * **Example** (Throwing a custom error) * @@ -1741,17 +1990,22 @@ export const getOrUndefined: (self: Result) => A | undefined = getOr * @see {@link getOrThrow} to throw the raw failure value * @see {@link getOrElse} for a non-throwing alternative * - * @category Getters - * @since 4.0.0 + * @category getters + * @since 2.0.0 */ export const getOrThrowWith: { /** * Extracts the success value or throws a custom error derived from the failure. * + * **When to use** + * + * Use when converting a `Result` into a thrown exception with a custom error + * message or error type. + * + * **Details** + * * - `Success` returns `A` * - `Failure` throws the value returned by `onFailure(e)` - * - Use when you want to convert a `Result` into a thrown exception with a - * custom error message or error type * * **Example** (Throwing a custom error) * @@ -1773,17 +2027,22 @@ export const getOrThrowWith: { * @see {@link getOrThrow} to throw the raw failure value * @see {@link getOrElse} for a non-throwing alternative * - * @category Getters - * @since 4.0.0 + * @category getters + * @since 2.0.0 */ (onFailure: (err: E) => unknown): (self: Result) => A /** * Extracts the success value or throws a custom error derived from the failure. * + * **When to use** + * + * Use when converting a `Result` into a thrown exception with a custom error + * message or error type. + * + * **Details** + * * - `Success` returns `A` * - `Failure` throws the value returned by `onFailure(e)` - * - Use when you want to convert a `Result` into a thrown exception with a - * custom error message or error type * * **Example** (Throwing a custom error) * @@ -1805,8 +2064,8 @@ export const getOrThrowWith: { * @see {@link getOrThrow} to throw the raw failure value * @see {@link getOrElse} for a non-throwing alternative * - * @category Getters - * @since 4.0.0 + * @category getters + * @since 2.0.0 */ (self: Result, onFailure: (err: E) => unknown): A } = dual(2, (self: Result, onFailure: (err: E) => unknown): A => { @@ -1819,6 +2078,12 @@ export const getOrThrowWith: { /** * Extracts the success value or throws the raw failure value `E`. * + * **When to use** + * + * Use when unchecked boundaries should turn failures into thrown exceptions. + * + * **Details** + * * - `Success` returns `A` * - `Failure` throws `E` directly * - Use {@link getOrThrowWith} for a custom error object @@ -1838,8 +2103,8 @@ export const getOrThrowWith: { * @see {@link getOrThrowWith} for custom error mapping * @see {@link getOrElse} for a non-throwing alternative * - * @category Getters - * @since 4.0.0 + * @category getters + * @since 2.0.0 */ export const getOrThrow: (self: Result) => A = getOrThrowWith(identity) @@ -1847,9 +2112,15 @@ export const getOrThrow: (self: Result) => A = getOrThrowWith(identi * Returns the original `Result` if it is a `Success`, otherwise applies * `that` to the error and returns the resulting `Result`. * + * **When to use** + * + * Use when a failure should recover into another `Result` while keeping + * successes unchanged. + * + * **Details** + * * - `Success` is returned unchanged * - `Failure` calls `that(e)` to produce a new `Result` - * - Use to provide a recovery path or fallback computation on failure * * **Example** (Recovering from a failure) * @@ -1867,17 +2138,23 @@ export const getOrThrow: (self: Result) => A = getOrThrowWith(identi * @see {@link getOrElse} to unwrap with a fallback value (not a Result) * @see {@link mapError} to transform the error without recovering * - * @category Error Handling - * @since 4.0.0 + * @category error handling + * @since 2.0.0 */ export const orElse: { /** * Returns the original `Result` if it is a `Success`, otherwise applies * `that` to the error and returns the resulting `Result`. * + * **When to use** + * + * Use when a failure should recover into another `Result` while keeping + * successes unchanged. + * + * **Details** + * * - `Success` is returned unchanged * - `Failure` calls `that(e)` to produce a new `Result` - * - Use to provide a recovery path or fallback computation on failure * * **Example** (Recovering from a failure) * @@ -1895,17 +2172,23 @@ export const orElse: { * @see {@link getOrElse} to unwrap with a fallback value (not a Result) * @see {@link mapError} to transform the error without recovering * - * @category Error Handling - * @since 4.0.0 + * @category error handling + * @since 2.0.0 */ (that: (err: E) => Result): (self: Result) => Result /** * Returns the original `Result` if it is a `Success`, otherwise applies * `that` to the error and returns the resulting `Result`. * + * **When to use** + * + * Use when a failure should recover into another `Result` while keeping + * successes unchanged. + * + * **Details** + * * - `Success` is returned unchanged * - `Failure` calls `that(e)` to produce a new `Result` - * - Use to provide a recovery path or fallback computation on failure * * **Example** (Recovering from a failure) * @@ -1923,8 +2206,8 @@ export const orElse: { * @see {@link getOrElse} to unwrap with a fallback value (not a Result) * @see {@link mapError} to transform the error without recovering * - * @category Error Handling - * @since 4.0.0 + * @category error handling + * @since 2.0.0 */ (self: Result, that: (err: E) => Result): Result } = dual( @@ -1936,6 +2219,13 @@ export const orElse: { /** * Chains a function that returns a `Result` onto a successful value. * + * **When to use** + * + * Use to sequence `Result`-returning computations that should short-circuit on + * failure. + * + * **Details** + * * - If `self` is a `Success`, applies `f` to the value and returns the resulting `Result` * - If `self` is a `Failure`, short-circuits and returns it unchanged * - The error types are merged into a union (`E | E2`) @@ -1959,13 +2249,20 @@ export const orElse: { * @see {@link andThen} for a more flexible variant that also accepts plain values * @see {@link map} when `f` does not return a `Result` * - * @category Sequencing - * @since 4.0.0 + * @category sequencing + * @since 2.0.0 */ export const flatMap: { /** * Chains a function that returns a `Result` onto a successful value. * + * **When to use** + * + * Use to sequence `Result`-returning computations that should short-circuit on + * failure. + * + * **Details** + * * - If `self` is a `Success`, applies `f` to the value and returns the resulting `Result` * - If `self` is a `Failure`, short-circuits and returns it unchanged * - The error types are merged into a union (`E | E2`) @@ -1989,13 +2286,20 @@ export const flatMap: { * @see {@link andThen} for a more flexible variant that also accepts plain values * @see {@link map} when `f` does not return a `Result` * - * @category Sequencing - * @since 4.0.0 + * @category sequencing + * @since 2.0.0 */ (f: (a: A) => Result): (self: Result) => Result /** * Chains a function that returns a `Result` onto a successful value. * + * **When to use** + * + * Use to sequence `Result`-returning computations that should short-circuit on + * failure. + * + * **Details** + * * - If `self` is a `Success`, applies `f` to the value and returns the resulting `Result` * - If `self` is a `Failure`, short-circuits and returns it unchanged * - The error types are merged into a union (`E | E2`) @@ -2019,8 +2323,8 @@ export const flatMap: { * @see {@link andThen} for a more flexible variant that also accepts plain values * @see {@link map} when `f` does not return a `Result` * - * @category Sequencing - * @since 4.0.0 + * @category sequencing + * @since 2.0.0 */ (self: Result, f: (a: A) => Result): Result } = dual( @@ -2030,7 +2334,14 @@ export const flatMap: { ) /** - * A flexible variant of {@link flatMap} that accepts multiple input shapes. + * Provides a flexible variant of {@link flatMap} that accepts multiple input shapes. + * + * **When to use** + * + * Use to sequence a next step that may be a `Result`, a function, or a plain + * value. + * + * **Details** * * The second argument can be: * - A function `(a: A) => Result` (same as `flatMap`) @@ -2066,12 +2377,19 @@ export const flatMap: { * @see {@link flatMap} for the stricter variant (function returning Result only) * @see {@link map} when you always return a plain value * - * @category Sequencing - * @since 4.0.0 + * @category sequencing + * @since 2.0.0 */ export const andThen: { /** - * A flexible variant of {@link flatMap} that accepts multiple input shapes. + * Provides a flexible variant of {@link flatMap} that accepts multiple input shapes. + * + * **When to use** + * + * Use to sequence a next step that may be a `Result`, a function, or a plain + * value. + * + * **Details** * * The second argument can be: * - A function `(a: A) => Result` (same as `flatMap`) @@ -2107,12 +2425,19 @@ export const andThen: { * @see {@link flatMap} for the stricter variant (function returning Result only) * @see {@link map} when you always return a plain value * - * @category Sequencing - * @since 4.0.0 + * @category sequencing + * @since 2.0.0 */ (f: (a: A) => Result): (self: Result) => Result /** - * A flexible variant of {@link flatMap} that accepts multiple input shapes. + * Provides a flexible variant of {@link flatMap} that accepts multiple input shapes. + * + * **When to use** + * + * Use to sequence a next step that may be a `Result`, a function, or a plain + * value. + * + * **Details** * * The second argument can be: * - A function `(a: A) => Result` (same as `flatMap`) @@ -2148,12 +2473,19 @@ export const andThen: { * @see {@link flatMap} for the stricter variant (function returning Result only) * @see {@link map} when you always return a plain value * - * @category Sequencing - * @since 4.0.0 + * @category sequencing + * @since 2.0.0 */ (f: Result): (self: Result) => Result /** - * A flexible variant of {@link flatMap} that accepts multiple input shapes. + * Provides a flexible variant of {@link flatMap} that accepts multiple input shapes. + * + * **When to use** + * + * Use to sequence a next step that may be a `Result`, a function, or a plain + * value. + * + * **Details** * * The second argument can be: * - A function `(a: A) => Result` (same as `flatMap`) @@ -2189,12 +2521,19 @@ export const andThen: { * @see {@link flatMap} for the stricter variant (function returning Result only) * @see {@link map} when you always return a plain value * - * @category Sequencing - * @since 4.0.0 + * @category sequencing + * @since 2.0.0 */ (f: (a: A) => A2): (self: Result) => Result /** - * A flexible variant of {@link flatMap} that accepts multiple input shapes. + * Provides a flexible variant of {@link flatMap} that accepts multiple input shapes. + * + * **When to use** + * + * Use to sequence a next step that may be a `Result`, a function, or a plain + * value. + * + * **Details** * * The second argument can be: * - A function `(a: A) => Result` (same as `flatMap`) @@ -2230,12 +2569,19 @@ export const andThen: { * @see {@link flatMap} for the stricter variant (function returning Result only) * @see {@link map} when you always return a plain value * - * @category Sequencing - * @since 4.0.0 + * @category sequencing + * @since 2.0.0 */ (right: NotFunction): (self: Result) => Result /** - * A flexible variant of {@link flatMap} that accepts multiple input shapes. + * Provides a flexible variant of {@link flatMap} that accepts multiple input shapes. + * + * **When to use** + * + * Use to sequence a next step that may be a `Result`, a function, or a plain + * value. + * + * **Details** * * The second argument can be: * - A function `(a: A) => Result` (same as `flatMap`) @@ -2271,12 +2617,19 @@ export const andThen: { * @see {@link flatMap} for the stricter variant (function returning Result only) * @see {@link map} when you always return a plain value * - * @category Sequencing - * @since 4.0.0 + * @category sequencing + * @since 2.0.0 */ (self: Result, f: (a: A) => Result): Result /** - * A flexible variant of {@link flatMap} that accepts multiple input shapes. + * Provides a flexible variant of {@link flatMap} that accepts multiple input shapes. + * + * **When to use** + * + * Use to sequence a next step that may be a `Result`, a function, or a plain + * value. + * + * **Details** * * The second argument can be: * - A function `(a: A) => Result` (same as `flatMap`) @@ -2312,12 +2665,19 @@ export const andThen: { * @see {@link flatMap} for the stricter variant (function returning Result only) * @see {@link map} when you always return a plain value * - * @category Sequencing - * @since 4.0.0 + * @category sequencing + * @since 2.0.0 */ (self: Result, f: Result): Result /** - * A flexible variant of {@link flatMap} that accepts multiple input shapes. + * Provides a flexible variant of {@link flatMap} that accepts multiple input shapes. + * + * **When to use** + * + * Use to sequence a next step that may be a `Result`, a function, or a plain + * value. + * + * **Details** * * The second argument can be: * - A function `(a: A) => Result` (same as `flatMap`) @@ -2353,12 +2713,19 @@ export const andThen: { * @see {@link flatMap} for the stricter variant (function returning Result only) * @see {@link map} when you always return a plain value * - * @category Sequencing - * @since 4.0.0 + * @category sequencing + * @since 2.0.0 */ (self: Result, f: (a: A) => A2): Result /** - * A flexible variant of {@link flatMap} that accepts multiple input shapes. + * Provides a flexible variant of {@link flatMap} that accepts multiple input shapes. + * + * **When to use** + * + * Use to sequence a next step that may be a `Result`, a function, or a plain + * value. + * + * **Details** * * The second argument can be: * - A function `(a: A) => Result` (same as `flatMap`) @@ -2394,8 +2761,8 @@ export const andThen: { * @see {@link flatMap} for the stricter variant (function returning Result only) * @see {@link map} when you always return a plain value * - * @category Sequencing - * @since 4.0.0 + * @category sequencing + * @since 2.0.0 */ (self: Result, f: NotFunction): Result } = dual( @@ -2413,6 +2780,13 @@ export const andThen: { /** * Collects a structure of `Result`s into a single `Result` of collected values. * + * **When to use** + * + * Use to collect independent `Result` values into one `Result` while preserving + * the original structure. + * + * **Details** + * * Accepts: * - A tuple/array: returns `Result` with a tuple/array of success values * - A struct (record): returns `Result` with a struct of success values @@ -2439,8 +2813,8 @@ export const andThen: { * @see {@link flatMap} for chaining two Results sequentially * @see {@link gen} for generator-based composition of multiple Results * - * @category Sequencing - * @since 4.0.0 + * @category sequencing + * @since 2.0.0 */ // @ts-expect-error export const all: > | Record>>( @@ -2481,6 +2855,13 @@ export const all: > | Record` becomes `Failure` (i.e., `Result`) * - `Failure` becomes `Success` (i.e., `Result`) * - Useful when you want to apply success-oriented operations (like `map`) @@ -2500,14 +2881,21 @@ export const all: > | Record(self: Result): Result => isFailure(self) ? succeed(self.failure) : fail(self.success) /** - * Generator-based syntax for composing `Result` values sequentially. + * Provides generator-based syntax for composing `Result` values sequentially. + * + * **When to use** + * + * Use when you need generator syntax to compose sequential `Result` + * computations instead of nested `flatMap` calls. + * + * **Details** * * - Use `yield*` to unwrap a `Result` inside the generator; if any yielded * `Result` is a `Failure`, the generator short-circuits and returns that failure @@ -2532,8 +2920,8 @@ export const flip = (self: Result): Result => * @see {@link flatMap} for point-free sequential composition * @see {@link all} to collect multiple independent Results * - * @category Generators - * @since 4.0.0 + * @category generators + * @since 2.0.0 */ export const gen: Gen.Gen = (...args) => { const f = args.length === 1 ? args[0] : args[1].bind(args[0]) @@ -2554,7 +2942,15 @@ export const gen: Gen.Gen = (...args) => { // ------------------------------------------------------------------------------------- /** - * Starting point for the "do notation" simulation with `Result`. + * Provides the starting point for the "do notation" simulation with `Result`. + * + * **When to use** + * + * Use to start a `Result` do-notation pipeline from an empty successful record + * before adding named fields from `Result`-producing computations and pure + * computed values. + * + * **Details** * * Creates a `Result<{}>` (success with an empty object). Use with * {@link bind} to add `Result`-producing fields and {@link let_ let} @@ -2578,9 +2974,10 @@ export const gen: Gen.Gen = (...args) => { * @see {@link bind} to add Result-producing fields * @see {@link let_ let} to add pure computed fields * @see {@link gen} for an alternative generator-based syntax + * @see {@link bindTo} for starting a do-notation chain from an existing Result * - * @category Do Notation - * @since 4.0.0 + * @category do notation + * @since 2.0.0 */ export const Do: Result<{}> = succeed({}) @@ -2588,6 +2985,14 @@ export const Do: Result<{}> = succeed({}) * Adds a named field to the do-notation accumulator by running a `Result`-producing * function that receives the current accumulated object. * + * **When to use** + * + * Use when you need to add a `Result`-producing step to a `Result` + * do-notation pipeline and store its successful value under a named field in + * the accumulated object. + * + * **Details** + * * - Short-circuits on the first `Failure` * - The field name must not collide with existing keys * - Use {@link let_ let} for pure (non-Result) computed fields @@ -2610,14 +3015,22 @@ export const Do: Result<{}> = succeed({}) * @see {@link let_ let} for pure computed fields * @see {@link bindTo} to wrap an initial Result into a named field * - * @category Do Notation - * @since 4.0.0 + * @category do notation + * @since 2.0.0 */ export const bind: { /** * Adds a named field to the do-notation accumulator by running a `Result`-producing * function that receives the current accumulated object. * + * **When to use** + * + * Use when you need to add a `Result`-producing step to a `Result` + * do-notation pipeline and store its successful value under a named field in + * the accumulated object. + * + * **Details** + * * - Short-circuits on the first `Failure` * - The field name must not collide with existing keys * - Use {@link let_ let} for pure (non-Result) computed fields @@ -2640,14 +3053,22 @@ export const bind: { * @see {@link let_ let} for pure computed fields * @see {@link bindTo} to wrap an initial Result into a named field * - * @category Do Notation - * @since 4.0.0 + * @category do notation + * @since 2.0.0 */ (name: Exclude, f: (a: NoInfer) => Result): (self: Result) => Result<{ [K in N | keyof A]: K extends keyof A ? A[K] : B }, L1 | L2> /** * Adds a named field to the do-notation accumulator by running a `Result`-producing * function that receives the current accumulated object. * + * **When to use** + * + * Use when you need to add a `Result`-producing step to a `Result` + * do-notation pipeline and store its successful value under a named field in + * the accumulated object. + * + * **Details** + * * - Short-circuits on the first `Failure` * - The field name must not collide with existing keys * - Use {@link let_ let} for pure (non-Result) computed fields @@ -2670,8 +3091,8 @@ export const bind: { * @see {@link let_ let} for pure computed fields * @see {@link bindTo} to wrap an initial Result into a named field * - * @category Do Notation - * @since 4.0.0 + * @category do notation + * @since 2.0.0 */ ( self: Result, @@ -2682,8 +3103,17 @@ export const bind: { /** * Wraps the success value of a `Result` into a named field, producing a - * `Result>`. This is typically used to start a do-notation - * chain from an existing `Result`. + * `Result>`. + * + * **When to use** + * + * Use to name the success value of an existing `Result` before continuing a + * do-notation pipeline. + * + * **Details** + * + * This is typically used to start a do-notation chain from an existing + * `Result`. * * **Example** (Wrapping a value into a named field) * @@ -2701,14 +3131,23 @@ export const bind: { * @see {@link Do} to start from an empty object * @see {@link bind} to add more fields * - * @category Do Notation - * @since 4.0.0 + * @category do notation + * @since 2.0.0 */ export const bindTo: { /** * Wraps the success value of a `Result` into a named field, producing a - * `Result>`. This is typically used to start a do-notation - * chain from an existing `Result`. + * `Result>`. + * + * **When to use** + * + * Use to name the success value of an existing `Result` before continuing a + * do-notation pipeline. + * + * **Details** + * + * This is typically used to start a do-notation chain from an existing + * `Result`. * * **Example** (Wrapping a value into a named field) * @@ -2726,14 +3165,23 @@ export const bindTo: { * @see {@link Do} to start from an empty object * @see {@link bind} to add more fields * - * @category Do Notation - * @since 4.0.0 + * @category do notation + * @since 2.0.0 */ (name: N): (self: Result) => Result, L> /** * Wraps the success value of a `Result` into a named field, producing a - * `Result>`. This is typically used to start a do-notation - * chain from an existing `Result`. + * `Result>`. + * + * **When to use** + * + * Use to name the success value of an existing `Result` before continuing a + * do-notation pipeline. + * + * **Details** + * + * This is typically used to start a do-notation chain from an existing + * `Result`. * * **Example** (Wrapping a value into a named field) * @@ -2751,8 +3199,8 @@ export const bindTo: { * @see {@link Do} to start from an empty object * @see {@link bind} to add more fields * - * @category Do Notation - * @since 4.0.0 + * @category do notation + * @since 2.0.0 */ (self: Result, name: N): Result, L> } = doNotation.bindTo(map) @@ -2774,6 +3222,13 @@ export { * Adds a named field to the do-notation accumulator by computing a pure * (non-Result) value from the current accumulated object. * + * **When to use** + * + * Use when you need to add a derived field that cannot fail inside a + * do-notation pipeline. + * + * **Details** + * * - Use {@link bind} when the computation returns a `Result` * - The field name must not collide with existing keys * @@ -2795,8 +3250,8 @@ export { * @see {@link Do} to start the do-notation chain * @see {@link bind} for Result-producing fields * - * @category Do Notation - * @since 4.0.0 + * @category do notation + * @since 2.0.0 */ let_ as let } @@ -2804,6 +3259,13 @@ export { /** * Transforms `Option>` into `Result, E>`. * + * **When to use** + * + * Use when optional absence should be treated as a successful `None`, while an + * inner `Result` failure should still fail the whole result. + * + * **Details** + * * - `None` becomes `Success(None)` * - `Some(Success(a))` becomes `Success(Some(a))` * - `Some(Failure(e))` becomes `Failure(e)` @@ -2824,8 +3286,8 @@ export { * * @see {@link transposeMapOption} to map and transpose in one step * - * @since 3.14.0 * @category Transposing + * @since 3.14.0 */ export const transposeOption = ( self: Option> @@ -2837,6 +3299,13 @@ export const transposeOption = ( * Maps an `Option` value with a `Result`-producing function, then transposes * the structure from `Option>` to `Result, E>`. * + * **When to use** + * + * Use when an optional value should be validated only when present, preserving + * absence as a successful `None`. + * + * **Details** + * * - `None` becomes `Success(None)` (the function is never called) * - `Some(a)` where `f(a)` is `Success(b)` becomes `Success(Some(b))` * - `Some(a)` where `f(a)` is `Failure(e)` becomes `Failure(e)` @@ -2860,14 +3329,21 @@ export const transposeOption = ( * * @see {@link transposeOption} when the Option already contains a Result * - * @since 3.15.0 * @category Transposing + * @since 3.15.0 */ export const transposeMapOption = dual< /** * Maps an `Option` value with a `Result`-producing function, then transposes * the structure from `Option>` to `Result, E>`. * + * **When to use** + * + * Use when an optional value should be validated only when present, preserving + * absence as a successful `None`. + * + * **Details** + * * - `None` becomes `Success(None)` (the function is never called) * - `Some(a)` where `f(a)` is `Success(b)` becomes `Success(Some(b))` * - `Some(a)` where `f(a)` is `Failure(e)` becomes `Failure(e)` @@ -2891,14 +3367,21 @@ export const transposeMapOption = dual< * * @see {@link transposeOption} when the Option already contains a Result * - * @since 3.15.0 * @category Transposing + * @since 3.15.0 */ (f: (self: A) => Result) => (self: Option) => Result, E>, /** * Maps an `Option` value with a `Result`-producing function, then transposes * the structure from `Option>` to `Result, E>`. * + * **When to use** + * + * Use when an optional value should be validated only when present, preserving + * absence as a successful `None`. + * + * **Details** + * * - `None` becomes `Success(None)` (the function is never called) * - `Some(a)` where `f(a)` is `Success(b)` becomes `Success(Some(b))` * - `Some(a)` where `f(a)` is `Failure(e)` becomes `Failure(e)` @@ -2922,17 +3405,24 @@ export const transposeMapOption = dual< * * @see {@link transposeOption} when the Option already contains a Result * - * @since 3.15.0 * @category Transposing + * @since 3.15.0 */ (self: Option, f: (self: A) => Result) => Result, E> >(2, (self, f) => option_.isNone(self) ? succeedNone : map(f(self.value), option_.some)) /** - * A pre-built `Result>` that succeeds with `None`. + * Provides a pre-built `Result>` that succeeds with `None`. * - * - Equivalent to `Result.succeed(Option.none())` but avoids an extra allocation - * - Useful with {@link transposeOption} patterns + * **When to use** + * + * Use when an optional success should be absent, such as the `None` branch of + * `transposeOption` or `transposeMapOption`. + * + * **Details** + * + * This is equivalent to `Result.succeed(Option.none())`, but reuses a shared + * `Success` wrapper instead of allocating one each time. * * **Example** (Using succeedNone) * @@ -2944,8 +3434,10 @@ export const transposeMapOption = dual< * ``` * * @see {@link succeedSome} for the `Some` counterpart + * @see {@link transposeOption} to transpose an Option that already contains a Result + * @see {@link transposeMapOption} to map and transpose an Option in one step * - * @category Constructors + * @category constructors * @since 4.0.0 */ export const succeedNone = succeed(option_.none) @@ -2953,6 +3445,8 @@ export const succeedNone = succeed(option_.none) /** * Creates a `Result>` that succeeds with `Some(a)`. * + * **Details** + * * - Equivalent to `Result.succeed(Option.some(a))` * - Useful with {@link transposeOption} patterns * @@ -2968,7 +3462,7 @@ export const succeedNone = succeed(option_.none) * * @see {@link succeedNone} for the `None` counterpart * - * @category Constructors + * @category constructors * @since 4.0.0 */ export const succeedSome = (a: A): Result, E> => succeed(option_.some(a)) @@ -2976,6 +3470,8 @@ export const succeedSome = (a: A): Result, E> => succeed /** * Runs a side-effect on the success value without altering the `Result`. * + * **Details** + * * - If the result is a `Success`, calls `f` with the value (return value is ignored) * - If the result is a `Failure`, `f` is not called * - Returns the original `Result` unchanged (same reference) @@ -2998,13 +3494,15 @@ export const succeedSome = (a: A): Result, E> => succeed * * @see {@link map} to transform the success value * - * @category Mapping + * @category mapping * @since 4.0.0 */ export const tap: { /** * Runs a side-effect on the success value without altering the `Result`. * + * **Details** + * * - If the result is a `Success`, calls `f` with the value (return value is ignored) * - If the result is a `Failure`, `f` is not called * - Returns the original `Result` unchanged (same reference) @@ -3027,13 +3525,15 @@ export const tap: { * * @see {@link map} to transform the success value * - * @category Mapping + * @category mapping * @since 4.0.0 */ (f: (a: A) => void): (self: Result) => Result /** * Runs a side-effect on the success value without altering the `Result`. * + * **Details** + * * - If the result is a `Success`, calls `f` with the value (return value is ignored) * - If the result is a `Failure`, `f` is not called * - Returns the original `Result` unchanged (same reference) @@ -3056,7 +3556,7 @@ export const tap: { * * @see {@link map} to transform the success value * - * @category Mapping + * @category mapping * @since 4.0.0 */ (self: Result, f: (a: A) => void): Result diff --git a/.opencode/node_modules/effect/src/Runtime.ts b/.opencode/node_modules/effect/src/Runtime.ts index b686815308810e633856cdd974b3956fa79cb0bd..5dff83402c83d5ae5ad893fa46fe133c42ce7eea 100644 --- a/.opencode/node_modules/effect/src/Runtime.ts +++ b/.opencode/node_modules/effect/src/Runtime.ts @@ -1,28 +1,11 @@ /** - * This module provides utilities for running Effect programs and managing their execution lifecycle. - * - * The Runtime module contains functions for creating main program runners that handle process - * teardown, error reporting, and exit code management. These utilities are particularly useful - * for creating CLI applications and server processes that need to manage their lifecycle properly. - * - * @example - * ```ts - * import { Effect, Fiber, Runtime } from "effect" - * - * // Create a main runner for Node.js - * const runMain = Runtime.makeRunMain((options) => { - * process.on("SIGINT", () => Effect.runFork(Fiber.interrupt(options.fiber))) - * process.on("SIGTERM", () => Effect.runFork(Fiber.interrupt(options.fiber))) - * - * options.fiber.addObserver((exit) => { - * options.teardown(exit, (code) => process.exit(code)) - * }) - * }) - * - * // Use the runner - * const program = Effect.log("Hello, World!") - * runMain(program) - * ``` + * Helpers for turning an `Effect` program into a host application's main entry + * point. This module is the low-level layer used by platform adapters to run a + * main effect, observe its fiber, report unhandled failures, and translate the + * resulting `Exit` into an application or process exit code. It provides + * `makeRunMain`, the default teardown behavior, and error markers for custom + * exit codes and already-reported failures. Application code usually calls the + * platform-provided runner instead of using this module directly. * * @since 4.0.0 */ @@ -35,13 +18,19 @@ import type * as Fiber from "./Fiber.ts" /** * Represents a teardown function that handles program completion and determines the exit code. * - * The teardown function is called when an Effect program completes (either successfully or with failure) - * and is responsible for determining the appropriate exit code and performing any cleanup operations. + * **When to use** + * + * Use when integrating {@link makeRunMain} with a host platform that needs to + * translate an Effect `Exit` into a process, worker, or application exit code. + * + * **Details** * - * @param exit - The result of the Effect program execution - * @param onExit - Callback to execute with the determined exit code + * A teardown function is called when an Effect program completes, either + * successfully or with a failure. It determines the appropriate exit code and + * can perform cleanup before invoking the supplied `onExit` callback. + * + * **Example** (Customizing teardown behavior) * - * @example * ```ts * import { Effect, Exit, Runtime } from "effect" * @@ -69,7 +58,7 @@ import type * as Fiber from "./Fiber.ts" * runMain(program, { teardown: customTeardown }) * ``` * - * @category Model + * @category models * @since 4.0.0 */ export interface Teardown { @@ -77,40 +66,52 @@ export interface Teardown { } /** - * The default teardown function that determines exit codes based on Effect completion. + * The default teardown function that determines exit codes from an Effect exit. * - * This teardown function follows standard Unix conventions: - * - Returns exit code 0 for successful completion - * - Returns exit code 1 for failures (except interruption-only failures) - * - Returns exit code 0 for interruption-only failures + * **When to use** * - * @example - * ```ts - * import { Effect, Exit, Runtime } from "effect" + * Use as the standard teardown for main programs with conventional process + * exit codes and support for {@link errorExitCode}. + * + * **Details** * - * // The default teardown behavior - * const program1 = Effect.succeed(42) - * const program2 = Effect.fail("error") - * const program3 = Effect.interrupt + * This teardown follows these exit-code rules: + * + * - `0` for successful completion. + * - `130` for interruption-only failures. + * - The squashed error's {@link errorExitCode} value for other failures when + * present. + * - `1` for other failures. + * + * **Gotchas** + * + * The `130` code is used only when the Cause contains interruptions and no + * other failure reasons. Mixed causes use the squashed error path instead. + * + * **Example** (Using default teardown) + * + * ```ts + * import { Exit, Runtime } from "effect" * - * // Using defaultTeardown directly * const logExitCode = (exit: Exit.Exit) => { * Runtime.defaultTeardown(exit, (code) => { * console.log(`Exit code: ${code}`) * }) * } * - * // Success case - exit code 0 * logExitCode(Exit.succeed(42)) + * // Output: Exit code: 0 * - * // Failure case - exit code 1 * logExitCode(Exit.fail("error")) + * // Output: Exit code: 1 * - * // Interruption case - exit code 0 * logExitCode(Exit.interrupt(123)) + * // Output: Exit code: 130 * ``` * - * @category Teardown + * @see {@link errorExitCode} for customizing failure exit codes + * + * @category running * @since 4.0.0 */ export const defaultTeardown: Teardown = ( @@ -125,13 +126,32 @@ export const defaultTeardown: Teardown = ( /** * Creates a platform-specific main program runner that handles Effect execution lifecycle. * - * This function creates a runner that can execute Effect programs as main entry points, - * handling process signals, fiber management, and teardown operations. The provided - * function receives a fiber and teardown callback to implement platform-specific behavior. + * **When to use** + * + * Use when building a runtime adapter for a host platform. + * + * **Details** * - * @param f - Function that sets up platform-specific behavior for the running Effect + * The runner executes Effect programs as main entry points. The provided + * function receives a forked fiber and a teardown callback so it can install + * platform-specific signal handling, fiber observers, and final exit behavior. + * + * Most applications should use a platform-provided runner, such as + * `NodeRuntime.runMain`, rather than constructing one directly. + * + * `disableErrorReporting` disables the automatic log emitted for unreported + * non-interruption failures. It does not change exit-code calculation or the + * custom teardown callback. + * + * **Gotchas** + * + * The setup function is responsible for observing the fiber and eventually + * invoking teardown. `makeRunMain` also tries to keep the host process alive + * with a long interval while the main fiber is running; if the host blocks + * timers, the runner still starts but cannot use that keep-alive fallback. + * + * **Example** (Creating platform runners) * - * @example * ```ts * import { Effect, Fiber, Runtime } from "effect" * @@ -175,7 +195,7 @@ export const defaultTeardown: Teardown = ( * }) * ``` * - * @category Run main + * @category running * @since 4.0.0 */ export const makeRunMain = ( @@ -231,7 +251,14 @@ declare global { } /** - * @category Exit code management + * Type-level key for the `Runtime.errorExitCode` marker. + * + * **When to use** + * + * Use to type properties keyed by `Runtime.errorExitCode` on custom error + * values. + * + * @category symbols * @since 4.0.0 */ export type errorExitCode = "~effect/Runtime/errorExitCode" @@ -240,6 +267,24 @@ export type errorExitCode = "~effect/Runtime/errorExitCode" * Allows associating an exit code with an error for determining the process * exit code on failure. * + * **When to use** + * + * Use when error classes should map failures to a specific process exit code + * when handled by {@link defaultTeardown}. + * + * **Details** + * + * Attach this marker as a readonly property on an error object. When the main + * program fails, {@link defaultTeardown} squashes the Cause and reads the marker + * from the resulting error value. + * + * **Gotchas** + * + * The marker is read from the squashed failure value. If a Cause contains + * multiple failures, the selected squashed error determines the exit code. + * + * **Example** (Setting a process exit code) + * * ```ts * import { Data, Effect, Runtime } from "effect" * import { NodeRuntime } from "@effect/platform-node" @@ -252,13 +297,37 @@ export type errorExitCode = "~effect/Runtime/errorExitCode" * NodeRuntime.runMain(Effect.fail(new MyError())) * ``` * - * @category Exit code management + * @see {@link errorReported} for controlling automatic error logging + * @see {@link defaultTeardown} for the default failure exit-code rules that read this marker + * @see {@link getErrorExitCode} for reading the marker from unknown error values + * + * @category symbols * @since 4.0.0 */ export const errorExitCode: errorExitCode = "~effect/Runtime/errorExitCode" /** - * @category Exit code management + * Reads the runtime exit-code marker from an unknown error value. + * + * **When to use** + * + * Use to read a custom failure exit code from an unknown error value, falling + * back to the default failure code. + * + * **Details** + * + * Returns the numeric `[Runtime.errorExitCode]` property when it is present on + * an object. Otherwise returns `1`, the default failure exit code used by + * `defaultTeardown`. + * + * **Gotchas** + * + * Non-object values, missing markers, and non-number marker values all return + * `1`. + * + * @see {@link errorExitCode} for the marker read by this function + * + * @category accessors * @since 4.0.0 */ export const getErrorExitCode = (u: unknown): number => { @@ -272,20 +341,48 @@ export const getErrorExitCode = (u: unknown): number => { } /** - * @category Error reporting management + * Type-level key for the `Runtime.errorReported` marker. + * + * **When to use** + * + * Use to type properties keyed by `Runtime.errorReported` on custom error + * values. + * + * @category symbols * @since 4.0.0 */ export type errorReported = "~effect/Runtime/errorReported" /** - * Allows an error to opt-out of error reporting. + * Defines the runtime marker that controls default `runMain` error logging for an error. + * + * **When to use** + * + * Use when you need error classes reported by application code to avoid being + * logged again by the default main runner. + * + * **Details** + * + * Set `[Runtime.errorReported]` to `false` on an error object to suppress the + * runtime log because the error has already been reported. Omitted or + * non-boolean values are treated as `true`, so failures are logged by default. + * + * **Gotchas** + * + * This marker controls only automatic error logging. It does not change the + * failure Cause or the process exit code. + * `makeRunMain` reads the marker from `Cause.squash(cause)`, so for causes + * with multiple failures, the squashed error determines whether default logging + * is suppressed. + * + * **Example** (Suppressing error reporting) * * ```ts * import { Data, Effect, Runtime } from "effect" * import { NodeRuntime } from "@effect/platform-node" * * class MyError extends Data.TaggedError("MyError") { - * readonly [Runtime.errorReported] = true + * readonly [Runtime.errorReported] = false * } * * // If the program fails with MyError, the process will exit with code 1 but @@ -293,13 +390,35 @@ export type errorReported = "~effect/Runtime/errorReported" * NodeRuntime.runMain(Effect.fail(new MyError())) * ``` * - * @category Error reporting management + * @see {@link errorExitCode} for controlling failure exit codes + * @see {@link getErrorReported} for reading the marker from unknown error values + * + * @category symbols * @since 4.0.0 */ export const errorReported: errorReported = "~effect/Runtime/errorReported" /** - * @category Error reporting management + * Reads the runtime error-reporting marker from an unknown error value. + * + * **When to use** + * + * Use to read whether an unknown error value should be treated as already + * reported by the default main runner. + * + * **Details** + * + * Returns a boolean `[Runtime.errorReported]` property when it is present on an + * object. Otherwise returns `true`, so failures are logged by default. + * + * **Gotchas** + * + * Non-object values, missing markers, and non-boolean marker values all return + * `true`. + * + * @see {@link errorReported} for the marker read by this function + * + * @category accessors * @since 4.0.0 */ export const getErrorReported = (u: unknown): boolean => { diff --git a/.opencode/node_modules/effect/src/Schedule.ts b/.opencode/node_modules/effect/src/Schedule.ts index 83de1290fba7f8f1b9ccee69b0edce2b50f9114d..626b153a9456e2c32728aef3f24b73aae841c0bf 100644 --- a/.opencode/node_modules/effect/src/Schedule.ts +++ b/.opencode/node_modules/effect/src/Schedule.ts @@ -1,31 +1,10 @@ /** - * This module provides utilities for creating and composing schedules for retrying operations, - * repeating effects, and implementing various timing strategies. + * Describes policies for retrying, repeating, and pacing Effect programs. * - * A Schedule is a function that takes an input and returns a decision whether to continue or halt, - * along with a delay duration. Schedules can be combined, transformed, and used to implement - * sophisticated retry and repetition logic. - * - * @example - * ```ts - * import { Effect, Schedule } from "effect" - * - * // Retry with exponential backoff - * const retryPolicy = Schedule.exponential("100 millis", 2.0) - * .pipe(Schedule.both(Schedule.recurs(3))) - * - * const program = Effect.gen(function*() { - * // This will retry up to 3 times with exponential backoff - * const result = yield* Effect.retry( - * Effect.fail("Network error"), - * retryPolicy - * ) - * }) - * - * // Repeat on a fixed schedule - * const heartbeat = Effect.log("heartbeat") - * .pipe(Effect.repeat(Schedule.spaced("30 seconds"))) - * ``` + * A `Schedule` is stepped with an input value. Each + * step either stops or produces an output together with the delay before the + * next step. Schedules are used by retry, repeat, stream, and channel APIs to + * decide when work should continue, how long to wait, and when to stop. * * @since 2.0.0 */ @@ -53,9 +32,14 @@ const randomNext: Effect = random.Random.useSync((random) => random.next /** * A Schedule defines a strategy for repeating or retrying effects based on some policy. * - * @example + * **Example** (Defining retry and repeat schedules) + * * ```ts - * import { Console, Effect, Schedule } from "effect" + * import { Console, Data, Effect, Schedule } from "effect" + * + * class NetworkError extends Data.TaggedError("NetworkError")<{ + * readonly attempt: number + * }> {} * * // Basic retry schedule - retry up to 3 times with exponential backoff * const retrySchedule = Schedule.exponential("100 millis").pipe( @@ -66,25 +50,29 @@ const randomNext: Effect = random.Random.useSync((random) => random.next * const repeatSchedule: Schedule.Schedule = Schedule * .spaced("30 seconds") * - * // Advanced schedule with custom logic - * const smartRetry = Schedule.exponential("1 second") - * * const program = Effect.gen(function*() { - * // Using retry schedule + * let attempts = 0 + * * const result1 = yield* Effect.retry( - * Effect.suspend(() => Math.random() > 0.5 ? Effect.fail("temporary error") : Effect.succeed("Success")), + * Effect.gen(function*() { + * attempts++ + * if (attempts < 3) { + * return yield* Effect.fail(new NetworkError({ attempt: attempts })) + * } + * return "Success" + * }), * retrySchedule * ) + * console.log(result1) // "Success" * - * // Using repeat schedule * yield* Console.log("heartbeat").pipe( * Effect.repeat(repeatSchedule.pipe(Schedule.take(5))) * ) * }) * ``` * + * @category models * @since 2.0.0 - * @category Models */ export interface Schedule extends Schedule.Variance, Pipeable @@ -93,7 +81,8 @@ export interface Schedule { readonly input: Input @@ -127,18 +116,19 @@ export interface InputMetadata { /** * Extended metadata that includes both input metadata and the output value from the schedule. * - * @example + * **Example** (Logging schedule output metadata) + * * ```ts * import { Console, Duration, Effect, Schedule } from "effect" * - * // Custom schedule that logs metadata including output + * // Custom schedule that logs metadata and output for each recurrence * const loggingSchedule = Schedule.unfold(0, (n) => Effect.succeed(n + 1)).pipe( * Schedule.addDelay(() => Effect.succeed(Duration.millis(100))), - * Schedule.tapOutput((output) => { - * return Console.log( - * `Output: ${output}` - * ) - * }) + * Schedule.collectWhile((metadata) => + * Console.log( + * `Output: ${metadata.output}, attempt: ${metadata.attempt}, elapsed: ${metadata.elapsed}ms` + * ).pipe(Effect.as(metadata.attempt <= 3)) + * ) * ) * * const program = Effect.gen(function*() { @@ -149,13 +139,13 @@ export interface InputMetadata { * }) * * // Output logs will show: - * // "Output: 0, Attempt: 1, Elapsed: 0ms, Since previous: 0ms" - * // "Output: 1, Attempt: 2, Elapsed: 100ms, Since previous: 100ms" - * // "Output: 2, Attempt: 3, Elapsed: 200ms, Since previous: 100ms" + * // Output: 0, attempt: 1, elapsed: 0ms + * // Output: 1, attempt: 2, elapsed: 100ms + * // Output: 2, attempt: 3, elapsed: 200ms * ``` * + * @category metadata * @since 4.0.0 - * @category Metadata */ export interface Metadata extends InputMetadata { readonly output: Output @@ -163,8 +153,17 @@ export interface Metadata extends InputMetada } /** + * Context reference containing metadata for the currently running schedule step. + * + * **Details** + * + * Repeat, retry, stream, and channel scheduling operations provide this service + * to effects run between schedule steps. The default value contains undefined + * input and output values, zero duration, and zeroed timing fields before any + * schedule step has produced metadata. + * + * @category metadata * @since 4.0.0 - * @category Metadata */ export const CurrentMetadata = Context.Reference("effect/Schedule/CurrentMetadata", { defaultValue: constant({ @@ -182,7 +181,8 @@ export const CurrentMetadata = Context.Reference("effect/Schedule/Curr /** * The Schedule namespace contains types and utilities for working with schedules. * - * @example + * **Example** (Creating custom schedules with the namespace) + * * ```ts * import { Duration, Effect, Schedule } from "effect" * @@ -210,13 +210,13 @@ export const CurrentMetadata = Context.Reference("effect/Schedule/Curr * ``` * * @since 2.0.0 - * @category models */ export declare namespace Schedule { /** * Variance interface that defines the type parameter relationships for Schedule. * - * @example + * **Example** (Understanding schedule variance) + * * ```ts * import { Effect, Schedule } from "effect" * @@ -240,44 +240,24 @@ export declare namespace Schedule { * const serviceSchedule = Schedule.spaced("5 seconds") * ``` * + * @category models * @since 2.0.0 - * @category Models */ export interface Variance { readonly [TypeId]: VarianceStruct } /** - * Internal structure that holds the variance annotations for Schedule type parameters. - * - * @example - * ```ts - * import { Effect, Schedule } from "effect" - * - * // The variance struct defines how Schedule's type parameters behave - * // This internal interface is used for type variance annotations + * Type-level marker used by `Schedule.Variance` to record the variance of + * `Schedule` type parameters. * - * // Example showing variance relationships: - * interface Animal { - * name: string - * } - * interface Dog extends Animal { - * breed: string - * } - * - * // Output is covariant - more specific types can be substituted - * const stringSchedule = Schedule.spaced("1 second").pipe( - * Schedule.map(() => Effect.succeed("output")) - * ) - * - * // Input is contravariant - more general types can be accepted - * const numberSchedule = Schedule.exponential("100 millis") + * **Details** * - * // This enables proper type relationships where schedules can be composed safely - * ``` + * This interface exists for TypeScript inference and assignability. Users + * normally do not construct or inspect it directly. * - * @since 2.0.0 - * @category Models + * @category models + * @since 4.0.0 */ export interface VarianceStruct { readonly _Out: Covariant @@ -301,7 +281,8 @@ const ScheduleProto = { /** * Type guard that checks if a value is a Schedule. * - * @example + * **Example** (Checking for schedules) + * * ```ts * import { Schedule } from "effect" * @@ -314,34 +295,33 @@ const ScheduleProto = { * console.log(Schedule.isSchedule(undefined)) // false * ``` * - * @since 2.0.0 * @category guards + * @since 2.0.0 */ export const isSchedule = (u: unknown): u is Schedule => hasProperty(u, TypeId) /** * Creates a Schedule from a step function that returns a Pull. * - * @example - * ```ts - * import { Schedule } from "effect" + * **Example** (Creating a custom schedule from a step function) * - * // fromStep is an advanced function for creating custom schedules - * // It requires a step function that returns a Pull value + * ```ts + * import { Cause, Duration, Effect, Schedule } from "effect" * - * // Most users should use simpler schedule constructors like: - * const simpleSchedule = Schedule.exponential("100 millis") - * const spacedSchedule = Schedule.spaced("1 second") - * const recurringSchedule = Schedule.recurs(5) + * const schedule = Schedule.fromStep(Effect.sync(() => { + * let count = 0 * - * // These can be combined and transformed as needed - * const complexSchedule = simpleSchedule.pipe( - * Schedule.both(Schedule.recurs(3)) - * ) + * return (_now: number, _input: string) => { + * if (count >= 3) { + * return Cause.done(count) + * } + * return Effect.succeed([count++, Duration.millis(100)] as [number, Duration.Duration]) + * } + * })) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fromStep = ( step: Effect< @@ -371,26 +351,25 @@ const metadataFn = () => { /** * Creates a Schedule from a step function that receives metadata about the schedule's execution. * - * @example - * ```ts - * import { Effect, Schedule } from "effect" + * **Example** (Creating a metadata-aware schedule) * - * // fromStepWithMetadata is an advanced function for creating schedules - * // that need access to execution metadata like timing and recurrence count + * ```ts + * import { Cause, Duration, Effect, Schedule } from "effect" * - * // Most users should use simpler metadata-aware functions like: - * const metadataSchedule = Schedule.spaced("1 second").pipe( - * Schedule.collectWhile((metadata) => Effect.succeed(metadata.attempt <= 5)) - * ) + * const firstThreeInputs = Schedule.fromStepWithMetadata(Effect.succeed((metadata: Schedule.InputMetadata) => { + * if (metadata.attempt > 3) { + * return Cause.done("finished") + * } * - * // Or use existing schedules with metadata transformations: - * const conditionalSchedule = Schedule.exponential("100 millis").pipe( - * Schedule.tapOutput((output) => Effect.log(`Output: ${output}`)) - * ) + * return Effect.succeed([ + * `attempt ${metadata.attempt}: ${metadata.input}`, + * Duration.millis(250) + * ] as [string, Duration.Duration]) + * })) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fromStepWithMetadata = ( step: Effect< @@ -407,7 +386,8 @@ export const fromStepWithMetadata = ( /** * Extracts the step function from a Schedule. * - * @example + * **Example** (Extracting a schedule step function) + * * ```ts * import { Effect, Schedule } from "effect" * @@ -417,16 +397,17 @@ export const fromStepWithMetadata = ( * const program = Effect.gen(function*() { * const stepFn = yield* Schedule.toStep(schedule) * - * // Use the step function directly for custom logic - * const now = Date.now() + * // Use the step function directly for custom logic. The timestamp is + * // supplied by the caller, so tests can pass a deterministic value. + * const now = 0 * const result = yield* stepFn(now, "input") * * console.log(`Step result: ${result}`) * }) * ``` * - * @since 4.0.0 * @category destructors + * @since 4.0.0 */ export const toStep = ( schedule: Schedule @@ -441,11 +422,25 @@ export const toStep = ( ) /** - * Extracts a step function from a Schedule that provides metadata about each - * execution. It will also handle sleeping for the computed delay. + * Extracts a step function from a `Schedule` that sleeps for each computed + * delay and returns metadata for the completed step. + * + * **When to use** + * + * Use to drive a schedule manually while preserving the computed output, + * delay, input, attempt, and elapsed timing metadata for each step. + * + * **Details** + * + * The returned step reads the current time from `Clock` when invoked, calls the + * schedule step with that timestamp and input, sleeps for the returned + * duration, and then yields `Metadata`. + * + * @see {@link toStep} for manually supplying the timestamp and handling the returned delay yourself + * @see {@link toStepWithSleep} for the same automatic sleeping behavior when only the schedule output is needed * - * @since 4.0.0 * @category destructors + * @since 4.0.0 */ export const toStepWithMetadata = ( schedule: Schedule @@ -479,7 +474,8 @@ export const toStepWithMetadata = ( /** * Extracts a step function from a Schedule that automatically handles sleep delays. * - * @example + * **Example** (Extracting a sleeping step function) + * * ```ts * import { Effect, Schedule } from "effect" * @@ -502,8 +498,8 @@ export const toStepWithMetadata = ( * }) * ``` * - * @since 4.0.0 * @category destructors + * @since 4.0.0 */ export const toStepWithSleep = ( schedule: Schedule @@ -519,31 +515,28 @@ export const toStepWithSleep = ( /** * Returns a new `Schedule` that adds the delay computed by the specified - * effectful function to the the next recurrence of the schedule. + * effectful function to the next recurrence of the schedule. + * + * **Example** (Adding extra delay to a schedule) * - * @example * ```ts * import { Console, Data, Duration, Effect, Schedule } from "effect" * * class RetryAttemptError extends Data.TaggedError("RetryAttemptError")<{ readonly message: string }> {} * - * // Add random jitter to schedule delays - * const jitteredSchedule = Schedule.addDelay( + * // Add a deterministic extra delay based on the schedule output + * const delayedSchedule = Schedule.addDelay( * Schedule.exponential("100 millis").pipe(Schedule.take(5)), * (output) => - * // Add random jitter between 0-50ms - * Effect.succeed(Duration.millis(Math.random() * 50)) + * Effect.succeed(Duration.millis(Duration.toMillis(output) * 0.25)) * ) * - * const jitterProgram = Effect.gen(function*() { + * const repeatProgram = Effect.gen(function*() { * yield* Effect.repeat( - * Effect.gen(function*() { - * yield* Console.log(`Task executed at ${new Date().toISOString()}`) - * return "jittered task" - * }), - * jitteredSchedule.pipe( + * Effect.succeed("delayed task"), + * delayedSchedule.pipe( * Schedule.tapOutput((delay) => - * Console.log(`Base delay with jitter applied`) + * Console.log(`Base delay: ${delay}`) * ) * ) * ) @@ -571,12 +564,15 @@ export const toStepWithSleep = ( * ) * }) * - * // Add effectful delay computation + * // Add effectful delay computation from deterministic service data + * const loadByExecution = [1, 3, 2, 4] as const + * * const dynamicSchedule = Schedule.addDelay( * Schedule.spaced("1 second").pipe(Schedule.take(4)), - * (executionNumber) => - * // Simulate checking system load and return additional delay - * Effect.succeed(Duration.millis(Math.random() > 0.7 ? 2000 : 500)) + * (executionNumber) => { + * const load = loadByExecution[executionNumber] ?? 1 + * return Effect.succeed(Duration.millis(load * 100)) + * } * ) * * const dynamicProgram = Effect.gen(function*() { @@ -589,25 +585,6 @@ export const toStepWithSleep = ( * ) * }) * - * // Add delay based on previous execution results (30% extra) - * const resultBasedSchedule = Schedule.addDelay( - * Schedule.fibonacci("200 millis").pipe(Schedule.take(5)), - * (fibonacciDelay) => - * Effect.succeed(Duration.millis(Duration.toMillis(fibonacciDelay) * 0.3)) - * ) - * - * const resultProgram = Effect.gen(function*() { - * yield* Effect.repeat( - * Effect.gen(function*() { - * yield* Console.log("Result-based delay task") - * return Math.random() - * }), - * resultBasedSchedule.pipe( - * Schedule.tapOutput((delay) => Console.log(`Fibonacci delay: ${delay}`)) - * ) - * ) - * }) - * * // Combine with retry for progressive backoff * const progressiveRetrySchedule = Schedule.addDelay( * Schedule.exponential("50 millis").pipe(Schedule.take(4)), @@ -632,37 +609,34 @@ export const toStepWithSleep = ( * }) * ``` * + * @category delays & timeouts * @since 2.0.0 - * @category utils */ export const addDelay: { /** * Returns a new `Schedule` that adds the delay computed by the specified - * effectful function to the the next recurrence of the schedule. + * effectful function to the next recurrence of the schedule. + * + * **Example** (Adding extra delay to a schedule) * - * @example * ```ts * import { Console, Data, Duration, Effect, Schedule } from "effect" * * class RetryAttemptError extends Data.TaggedError("RetryAttemptError")<{ readonly message: string }> {} * - * // Add random jitter to schedule delays - * const jitteredSchedule = Schedule.addDelay( + * // Add a deterministic extra delay based on the schedule output + * const delayedSchedule = Schedule.addDelay( * Schedule.exponential("100 millis").pipe(Schedule.take(5)), * (output) => - * // Add random jitter between 0-50ms - * Effect.succeed(Duration.millis(Math.random() * 50)) + * Effect.succeed(Duration.millis(Duration.toMillis(output) * 0.25)) * ) * - * const jitterProgram = Effect.gen(function*() { + * const repeatProgram = Effect.gen(function*() { * yield* Effect.repeat( - * Effect.gen(function*() { - * yield* Console.log(`Task executed at ${new Date().toISOString()}`) - * return "jittered task" - * }), - * jitteredSchedule.pipe( + * Effect.succeed("delayed task"), + * delayedSchedule.pipe( * Schedule.tapOutput((delay) => - * Console.log(`Base delay with jitter applied`) + * Console.log(`Base delay: ${delay}`) * ) * ) * ) @@ -690,12 +664,15 @@ export const addDelay: { * ) * }) * - * // Add effectful delay computation + * // Add effectful delay computation from deterministic service data + * const loadByExecution = [1, 3, 2, 4] as const + * * const dynamicSchedule = Schedule.addDelay( * Schedule.spaced("1 second").pipe(Schedule.take(4)), - * (executionNumber) => - * // Simulate checking system load and return additional delay - * Effect.succeed(Duration.millis(Math.random() > 0.7 ? 2000 : 500)) + * (executionNumber) => { + * const load = loadByExecution[executionNumber] ?? 1 + * return Effect.succeed(Duration.millis(load * 100)) + * } * ) * * const dynamicProgram = Effect.gen(function*() { @@ -708,25 +685,6 @@ export const addDelay: { * ) * }) * - * // Add delay based on previous execution results (30% extra) - * const resultBasedSchedule = Schedule.addDelay( - * Schedule.fibonacci("200 millis").pipe(Schedule.take(5)), - * (fibonacciDelay) => - * Effect.succeed(Duration.millis(Duration.toMillis(fibonacciDelay) * 0.3)) - * ) - * - * const resultProgram = Effect.gen(function*() { - * yield* Effect.repeat( - * Effect.gen(function*() { - * yield* Console.log("Result-based delay task") - * return Math.random() - * }), - * resultBasedSchedule.pipe( - * Schedule.tapOutput((delay) => Console.log(`Fibonacci delay: ${delay}`)) - * ) - * ) - * }) - * * // Combine with retry for progressive backoff * const progressiveRetrySchedule = Schedule.addDelay( * Schedule.exponential("50 millis").pipe(Schedule.take(4)), @@ -751,39 +709,36 @@ export const addDelay: { * }) * ``` * + * @category delays & timeouts * @since 2.0.0 - * @category utils */ (f: (output: Output) => Effect): ( self: Schedule ) => Schedule /** * Returns a new `Schedule` that adds the delay computed by the specified - * effectful function to the the next recurrence of the schedule. + * effectful function to the next recurrence of the schedule. + * + * **Example** (Adding extra delay to a schedule) * - * @example * ```ts * import { Console, Data, Duration, Effect, Schedule } from "effect" * * class RetryAttemptError extends Data.TaggedError("RetryAttemptError")<{ readonly message: string }> {} * - * // Add random jitter to schedule delays - * const jitteredSchedule = Schedule.addDelay( + * // Add a deterministic extra delay based on the schedule output + * const delayedSchedule = Schedule.addDelay( * Schedule.exponential("100 millis").pipe(Schedule.take(5)), * (output) => - * // Add random jitter between 0-50ms - * Effect.succeed(Duration.millis(Math.random() * 50)) + * Effect.succeed(Duration.millis(Duration.toMillis(output) * 0.25)) * ) * - * const jitterProgram = Effect.gen(function*() { + * const repeatProgram = Effect.gen(function*() { * yield* Effect.repeat( - * Effect.gen(function*() { - * yield* Console.log(`Task executed at ${new Date().toISOString()}`) - * return "jittered task" - * }), - * jitteredSchedule.pipe( + * Effect.succeed("delayed task"), + * delayedSchedule.pipe( * Schedule.tapOutput((delay) => - * Console.log(`Base delay with jitter applied`) + * Console.log(`Base delay: ${delay}`) * ) * ) * ) @@ -811,12 +766,15 @@ export const addDelay: { * ) * }) * - * // Add effectful delay computation + * // Add effectful delay computation from deterministic service data + * const loadByExecution = [1, 3, 2, 4] as const + * * const dynamicSchedule = Schedule.addDelay( * Schedule.spaced("1 second").pipe(Schedule.take(4)), - * (executionNumber) => - * // Simulate checking system load and return additional delay - * Effect.succeed(Duration.millis(Math.random() > 0.7 ? 2000 : 500)) + * (executionNumber) => { + * const load = loadByExecution[executionNumber] ?? 1 + * return Effect.succeed(Duration.millis(load * 100)) + * } * ) * * const dynamicProgram = Effect.gen(function*() { @@ -829,25 +787,6 @@ export const addDelay: { * ) * }) * - * // Add delay based on previous execution results (30% extra) - * const resultBasedSchedule = Schedule.addDelay( - * Schedule.fibonacci("200 millis").pipe(Schedule.take(5)), - * (fibonacciDelay) => - * Effect.succeed(Duration.millis(Duration.toMillis(fibonacciDelay) * 0.3)) - * ) - * - * const resultProgram = Effect.gen(function*() { - * yield* Effect.repeat( - * Effect.gen(function*() { - * yield* Console.log("Result-based delay task") - * return Math.random() - * }), - * resultBasedSchedule.pipe( - * Schedule.tapOutput((delay) => Console.log(`Fibonacci delay: ${delay}`)) - * ) - * ) - * }) - * * // Combine with retry for progressive backoff * const progressiveRetrySchedule = Schedule.addDelay( * Schedule.exponential("50 millis").pipe(Schedule.take(4)), @@ -872,8 +811,8 @@ export const addDelay: { * }) * ``` * + * @category delays & timeouts * @since 2.0.0 - * @category utils */ ( self: Schedule, @@ -890,11 +829,11 @@ export const addDelay: { )) /** - * Returns a new `Schedule` that will first execute the left (i.e. `self`) - * schedule to completion. Once the left schedule is complete, the right (i.e. - * `other`) schedule will be executed to completion. + * Returns a schedule that runs `self` to completion, then runs `other`, and + * merges their outputs. + * + * **Example** (Sequencing quick and slow retries) * - * @example * ```ts * import { Console, Data, Effect, Schedule } from "effect" * @@ -926,16 +865,16 @@ export const addDelay: { * }) * ``` * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ export const andThen: { /** - * Returns a new `Schedule` that will first execute the left (i.e. `self`) - * schedule to completion. Once the left schedule is complete, the right (i.e. - * `other`) schedule will be executed to completion. + * Returns a schedule that runs `self` to completion, then runs `other`, and + * merges their outputs. + * + * **Example** (Sequencing quick and slow retries) * - * @example * ```ts * import { Console, Data, Effect, Schedule } from "effect" * @@ -967,18 +906,18 @@ export const andThen: { * }) * ``` * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ (other: Schedule): ( self: Schedule ) => Schedule /** - * Returns a new `Schedule` that will first execute the left (i.e. `self`) - * schedule to completion. Once the left schedule is complete, the right (i.e. - * `other`) schedule will be executed to completion. + * Returns a schedule that runs `self` to completion, then runs `other`, and + * merges their outputs. + * + * **Example** (Sequencing quick and slow retries) * - * @example * ```ts * import { Console, Data, Effect, Schedule } from "effect" * @@ -1010,8 +949,8 @@ export const andThen: { * }) * ``` * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ ( self: Schedule, @@ -1024,15 +963,17 @@ export const andThen: { map(andThenResult(self, other), (result) => effect.succeed(Result.merge(result)))) /** - * Returns a new `Schedule` that will first execute the left (i.e. `self`) - * schedule to completion. Once the left schedule is complete, the right (i.e. - * `other`) schedule will be executed to completion. + * Returns a schedule that runs `self` to completion, then runs `other`, and + * preserves which schedule produced each output. + * + * **Details** * - * The output of the resulting schedule is a `Result` where outputs of the - * left schedule are emitted as `Result.Err` and outputs of the right - * schedule are emitted as `Result.Ok`. + * The resulting schedule emits a `Result` to indicate which phase produced + * each output: outputs from `self` are emitted as `Failure`, and outputs from + * `other` are emitted as `Success`. + * + * **Example** (Tracking sequential schedule phases) * - * @example * ```ts * import { Console, Effect, Result, Schedule } from "effect" * @@ -1060,20 +1001,22 @@ export const andThen: { * }) * ``` * - * @since 2.0.0 * @category sequencing + * @since 4.0.0 */ export const andThenResult: { /** - * Returns a new `Schedule` that will first execute the left (i.e. `self`) - * schedule to completion. Once the left schedule is complete, the right (i.e. - * `other`) schedule will be executed to completion. + * Returns a schedule that runs `self` to completion, then runs `other`, and + * preserves which schedule produced each output. + * + * **Details** * - * The output of the resulting schedule is a `Result` where outputs of the - * left schedule are emitted as `Result.Err` and outputs of the right - * schedule are emitted as `Result.Ok`. + * The resulting schedule emits a `Result` to indicate which phase produced + * each output: outputs from `self` are emitted as `Failure`, and outputs from + * `other` are emitted as `Success`. + * + * **Example** (Tracking sequential schedule phases) * - * @example * ```ts * import { Console, Effect, Result, Schedule } from "effect" * @@ -1101,22 +1044,24 @@ export const andThenResult: { * }) * ``` * - * @since 2.0.0 * @category sequencing + * @since 4.0.0 */ (other: Schedule): ( self: Schedule ) => Schedule, Input & Input2, Error | Error2, Env | Env2> /** - * Returns a new `Schedule` that will first execute the left (i.e. `self`) - * schedule to completion. Once the left schedule is complete, the right (i.e. - * `other`) schedule will be executed to completion. + * Returns a schedule that runs `self` to completion, then runs `other`, and + * preserves which schedule produced each output. * - * The output of the resulting schedule is a `Result` where outputs of the - * left schedule are emitted as `Result.Err` and outputs of the right - * schedule are emitted as `Result.Ok`. + * **Details** + * + * The resulting schedule emits a `Result` to indicate which phase produced + * each output: outputs from `self` are emitted as `Failure`, and outputs from + * `other` are emitted as `Success`. + * + * **Example** (Tracking sequential schedule phases) * - * @example * ```ts * import { Console, Effect, Result, Schedule } from "effect" * @@ -1144,8 +1089,8 @@ export const andThenResult: { * }) * ``` * - * @since 2.0.0 * @category sequencing + * @since 4.0.0 */ ( self: Schedule, @@ -1179,15 +1124,17 @@ export const andThenResult: { if (currentStep) return currentStep(now, input) return toStep< /** - * Returns a new `Schedule` that will first execute the left (i.e. `self`) - * schedule to completion. Once the left schedule is complete, the right (i.e. - * `other`) schedule will be executed to completion. + * Returns a schedule that runs `self` to completion, then runs `other`, and + * preserves which schedule produced each output. * - * The output of the resulting schedule is a `Result` where outputs of the - * left schedule are emitted as `Result.Err` and outputs of the right - * schedule are emitted as `Result.Ok`. + * **Details** + * + * The resulting schedule emits a `Result` to indicate which phase produced + * each output: outputs from `self` are emitted as `Failure`, and outputs from + * `other` are emitted as `Success`. + * + * **Example** (Tracking sequential schedule phases) * - * @example * ```ts * import { Console, Effect, Result, Schedule } from "effect" * @@ -1215,20 +1162,22 @@ export const andThenResult: { * }) * ``` * - * @since 2.0.0 * @category sequencing + * @since 4.0.0 */ Result.Result, /** - * Returns a new `Schedule` that will first execute the left (i.e. `self`) - * schedule to completion. Once the left schedule is complete, the right (i.e. - * `other`) schedule will be executed to completion. + * Returns a schedule that runs `self` to completion, then runs `other`, and + * preserves which schedule produced each output. + * + * **Details** * - * The output of the resulting schedule is a `Result` where outputs of the - * left schedule are emitted as `Result.Err` and outputs of the right - * schedule are emitted as `Result.Ok`. + * The resulting schedule emits a `Result` to indicate which phase produced + * each output: outputs from `self` are emitted as `Failure`, and outputs from + * `other` are emitted as `Success`. + * + * **Example** (Tracking sequential schedule phases) * - * @example * ```ts * import { Console, Effect, Result, Schedule } from "effect" * @@ -1256,20 +1205,22 @@ export const andThenResult: { * }) * ``` * - * @since 2.0.0 * @category sequencing + * @since 4.0.0 */ Input & Input2, /** - * Returns a new `Schedule` that will first execute the left (i.e. `self`) - * schedule to completion. Once the left schedule is complete, the right (i.e. - * `other`) schedule will be executed to completion. + * Returns a schedule that runs `self` to completion, then runs `other`, and + * preserves which schedule produced each output. + * + * **Details** + * + * The resulting schedule emits a `Result` to indicate which phase produced + * each output: outputs from `self` are emitted as `Failure`, and outputs from + * `other` are emitted as `Success`. * - * The output of the resulting schedule is a `Result` where outputs of the - * left schedule are emitted as `Result.Err` and outputs of the right - * schedule are emitted as `Result.Ok`. + * **Example** (Tracking sequential schedule phases) * - * @example * ```ts * import { Console, Effect, Result, Schedule } from "effect" * @@ -1297,20 +1248,22 @@ export const andThenResult: { * }) * ``` * - * @since 2.0.0 * @category sequencing + * @since 4.0.0 */ Error | Error2, /** - * Returns a new `Schedule` that will first execute the left (i.e. `self`) - * schedule to completion. Once the left schedule is complete, the right (i.e. - * `other`) schedule will be executed to completion. + * Returns a schedule that runs `self` to completion, then runs `other`, and + * preserves which schedule produced each output. * - * The output of the resulting schedule is a `Result` where outputs of the - * left schedule are emitted as `Result.Err` and outputs of the right - * schedule are emitted as `Result.Ok`. + * **Details** + * + * The resulting schedule emits a `Result` to indicate which phase produced + * each output: outputs from `self` are emitted as `Failure`, and outputs from + * `other` are emitted as `Success`. + * + * **Example** (Tracking sequential schedule phases) * - * @example * ```ts * import { Console, Effect, Result, Schedule } from "effect" * @@ -1338,8 +1291,8 @@ export const andThenResult: { * }) * ``` * - * @since 2.0.0 * @category sequencing + * @since 4.0.0 */ Env | Env2 >(currentSide === 0 ? left : right).pipe( @@ -1365,7 +1318,12 @@ export const andThenResult: { * to recur, using the maximum of the two durations between recurrences and * outputting a tuple of the outputs of both schedules. * - * @example + * **When to use** + * + * Use when the combined schedule should continue only while both schedules still recur. + * + * **Example** (Combining time and attempt limits) + * * ```ts * import { Console, Data, Effect, Schedule } from "effect" * @@ -1382,7 +1340,7 @@ export const andThenResult: { * const program = Effect.gen(function*() { * const results = yield* Effect.repeat( * Effect.gen(function*() { - * yield* Console.log(`Task executed at ${new Date().toISOString()}`) + * yield* Console.log("Task executed") * return "task completed" * }), * bothSchedule.pipe( @@ -1426,8 +1384,10 @@ export const andThenResult: { * // Compare with either which provides union semantics (OR logic) * ``` * + * @see {@link either} for continuing while either schedule still recurs + * + * @category combining * @since 2.0.0 - * @category utilities */ export const both: { /** @@ -1435,7 +1395,12 @@ export const both: { * to recur, using the maximum of the two durations between recurrences and * outputting a tuple of the outputs of both schedules. * - * @example + * **When to use** + * + * Use when the combined schedule should continue only while both schedules still recur. + * + * **Example** (Combining time and attempt limits) + * * ```ts * import { Console, Data, Effect, Schedule } from "effect" * @@ -1452,7 +1417,7 @@ export const both: { * const program = Effect.gen(function*() { * const results = yield* Effect.repeat( * Effect.gen(function*() { - * yield* Console.log(`Task executed at ${new Date().toISOString()}`) + * yield* Console.log("Task executed") * return "task completed" * }), * bothSchedule.pipe( @@ -1496,8 +1461,10 @@ export const both: { * // Compare with either which provides union semantics (OR logic) * ``` * + * @see {@link either} for continuing while either schedule still recurs + * + * @category combining * @since 2.0.0 - * @category utilities */ (other: Schedule): ( self: Schedule @@ -1507,7 +1474,12 @@ export const both: { * to recur, using the maximum of the two durations between recurrences and * outputting a tuple of the outputs of both schedules. * - * @example + * **When to use** + * + * Use when the combined schedule should continue only while both schedules still recur. + * + * **Example** (Combining time and attempt limits) + * * ```ts * import { Console, Data, Effect, Schedule } from "effect" * @@ -1524,7 +1496,7 @@ export const both: { * const program = Effect.gen(function*() { * const results = yield* Effect.repeat( * Effect.gen(function*() { - * yield* Console.log(`Task executed at ${new Date().toISOString()}`) + * yield* Console.log("Task executed") * return "task completed" * }), * bothSchedule.pipe( @@ -1568,8 +1540,10 @@ export const both: { * // Compare with either which provides union semantics (OR logic) * ``` * + * @see {@link either} for continuing while either schedule still recurs + * + * @category combining * @since 2.0.0 - * @category utilities */ ( self: Schedule, @@ -1586,7 +1560,13 @@ export const both: { * to recur, using the maximum of the two durations between recurrences and * outputting the result of the left schedule (i.e. `self`). * - * @example + * **When to use** + * + * Use when two schedules must both allow recurrence and only the left schedule's + * output is needed. + * + * **Example** (Combining schedules and keeping the left output) + * * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -1609,8 +1589,8 @@ export const both: { * }) * ``` * + * @category combining * @since 2.0.0 - * @category utilities */ export const bothLeft: { /** @@ -1618,7 +1598,13 @@ export const bothLeft: { * to recur, using the maximum of the two durations between recurrences and * outputting the result of the left schedule (i.e. `self`). * - * @example + * **When to use** + * + * Use when two schedules must both allow recurrence and only the left schedule's + * output is needed. + * + * **Example** (Combining schedules and keeping the left output) + * * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -1641,8 +1627,8 @@ export const bothLeft: { * }) * ``` * + * @category combining * @since 2.0.0 - * @category utilities */ (other: Schedule): ( self: Schedule @@ -1652,7 +1638,13 @@ export const bothLeft: { * to recur, using the maximum of the two durations between recurrences and * outputting the result of the left schedule (i.e. `self`). * - * @example + * **When to use** + * + * Use when two schedules must both allow recurrence and only the left schedule's + * output is needed. + * + * **Example** (Combining schedules and keeping the left output) + * * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -1675,8 +1667,8 @@ export const bothLeft: { * }) * ``` * + * @category combining * @since 2.0.0 - * @category utilities */ ( self: Schedule, @@ -1692,7 +1684,13 @@ export const bothLeft: { * to recur, using the maximum of the two durations between recurrences and * outputting the result of the right schedule (i.e. `other`). * - * @example + * **When to use** + * + * Use when two schedules must both allow recurrence and only the right + * schedule's output is needed. + * + * **Example** (Combining schedules and keeping the right output) + * * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -1717,8 +1715,8 @@ export const bothLeft: { * }) * ``` * + * @category combining * @since 2.0.0 - * @category utilities */ export const bothRight: { /** @@ -1726,7 +1724,13 @@ export const bothRight: { * to recur, using the maximum of the two durations between recurrences and * outputting the result of the right schedule (i.e. `other`). * - * @example + * **When to use** + * + * Use when two schedules must both allow recurrence and only the right + * schedule's output is needed. + * + * **Example** (Combining schedules and keeping the right output) + * * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -1751,8 +1755,8 @@ export const bothRight: { * }) * ``` * + * @category combining * @since 2.0.0 - * @category utilities */ (other: Schedule): ( self: Schedule @@ -1762,7 +1766,13 @@ export const bothRight: { * to recur, using the maximum of the two durations between recurrences and * outputting the result of the right schedule (i.e. `other`). * - * @example + * **When to use** + * + * Use when two schedules must both allow recurrence and only the right + * schedule's output is needed. + * + * **Example** (Combining schedules and keeping the right output) + * * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -1787,8 +1797,8 @@ export const bothRight: { * }) * ``` * + * @category combining * @since 2.0.0 - * @category utilities */ ( self: Schedule, @@ -1805,7 +1815,13 @@ export const bothRight: { * outputting the result of the combination of both schedule outputs using the * specified `combine` function. * - * @example + * **When to use** + * + * Use when two schedules must both allow recurrence and their outputs should be + * combined into a custom value. + * + * **Example** (Combining schedule outputs) + * * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -1834,8 +1850,8 @@ export const bothRight: { * }) * ``` * + * @category combining * @since 2.0.0 - * @category utilities */ export const bothWith: { /** @@ -1844,7 +1860,13 @@ export const bothWith: { * outputting the result of the combination of both schedule outputs using the * specified `combine` function. * - * @example + * **When to use** + * + * Use when two schedules must both allow recurrence and their outputs should be + * combined into a custom value. + * + * **Example** (Combining schedule outputs) + * * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -1873,8 +1895,8 @@ export const bothWith: { * }) * ``` * + * @category combining * @since 2.0.0 - * @category utilities */ ( other: Schedule, @@ -1888,7 +1910,13 @@ export const bothWith: { * outputting the result of the combination of both schedule outputs using the * specified `combine` function. * - * @example + * **When to use** + * + * Use when two schedules must both allow recurrence and their outputs should be + * combined into a custom value. + * + * **Example** (Combining schedule outputs) + * * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -1917,8 +1945,8 @@ export const bothWith: { * }) * ``` * + * @category combining * @since 2.0.0 - * @category utilities */ ( self: Schedule, @@ -1954,10 +1982,16 @@ export const bothWith: { ))) /** - * Returns a new `Schedule` that always recurs, collecting all inputs of the - * schedule into an array. + * Returns a new `Schedule` that follows `self` and outputs the inputs seen so + * far as an array. + * + * **Details** + * + * This does not make the schedule run forever. The collected schedule stops + * when `self` stops and fails when `self` fails. + * + * **Example** (Collecting schedule inputs) * - * @example * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -1979,18 +2013,24 @@ export const bothWith: { * }) * ``` * - * @since 2.0.0 - * @category utilities + * @category collecting + * @since 4.0.0 */ export const collectInputs = ( self: Schedule ): Schedule, Input, Error, Env> => collectWhile(passthrough(self), () => effect.succeed(true)) /** - * Returns a new `Schedule` that always recurs, collecting all outputs of the - * schedule into an array. + * Returns a new `Schedule` that follows `self` and outputs the schedule outputs + * seen so far as an array. + * + * **Details** + * + * This does not make the schedule run forever. The collected schedule stops + * when `self` stops and fails when `self` fails. + * + * **Example** (Collecting schedule outputs) * - * @example * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -2010,8 +2050,8 @@ export const collectInputs = ( * }) * ``` * - * @since 2.0.0 - * @category utilities + * @category collecting + * @since 4.0.0 */ export const collectOutputs = ( self: Schedule @@ -2021,31 +2061,11 @@ export const collectOutputs = ( * Returns a new `Schedule` that recurs as long as the specified `predicate` * returns `true`, collecting all outputs of the schedule into an array. * - * @example + * **Example** (Collecting outputs while a condition holds) + * * ```ts * import { Console, Effect, Schedule } from "effect" * - * // Collect outputs while under time limit - * const collectForTime = Schedule.collectWhile( - * Schedule.spaced("500 millis"), - * (metadata) => Effect.succeed(metadata.elapsed < 3000) // Stop after 3 seconds - * ) - * - * const timeBasedProgram = Effect.gen(function*() { - * const results = yield* Effect.repeat( - * Effect.gen(function*() { - * const value = Math.floor(Math.random() * 100) - * yield* Console.log(`Generated value: ${value}`) - * return value - * }), - * collectForTime - * ) - * - * yield* Console.log( - * `Collected ${results.length} values: [${results.join(", ")}]` - * ) - * }) - * * // Collect outputs while condition is met * const collectWhileSmall = Schedule.collectWhile( * Schedule.exponential("100 millis"), @@ -2056,16 +2076,16 @@ export const collectOutputs = ( * const conditionalProgram = Effect.gen(function*() { * let attempt = 0 * - * const delays = yield* Effect.repeat( + * const attempts = yield* Effect.repeat( * Effect.gen(function*() { * attempt++ * yield* Console.log(`Retry attempt ${attempt}`) - * return `${Date.now()}` + * return `attempt-${attempt}` * }), * collectWhileSmall * ) * - * yield* Console.log(`Collected attempts: [${delays.join(", ")}]`) + * yield* Console.log(`Collected attempts: [${attempts.join(", ")}]`) * }) * * // Collect with effectful predicate @@ -2082,19 +2102,17 @@ export const collectOutputs = ( * ) * * const effectfulProgram = Effect.gen(function*() { - * const timestamps = yield* Effect.repeat( - * Effect.gen(function*() { - * const now = new Date().toISOString() - * yield* Console.log(`Task at ${now}`) - * return now - * }), + * const results = yield* Effect.repeat( + * Effect.succeed("checked"), * collectWithCheck * ) * - * yield* Console.log(`Final collection: ${timestamps.length} items`) + * yield* Console.log(`Final collection: ${results.length} items`) * }) * * // Collect samples with condition + * const samples = [12, 18, 24, 30, 36] + * * const collectSamples = Schedule.collectWhile( * Schedule.spaced("200 millis"), * (metadata) => @@ -2102,55 +2120,36 @@ export const collectOutputs = ( * ) * * const samplingProgram = Effect.gen(function*() { - * const samples = yield* Effect.repeat( + * let index = 0 + * const collected = yield* Effect.repeat( * Effect.gen(function*() { - * const sample = Math.random() * 100 - * yield* Console.log(`Sample: ${sample.toFixed(1)}`) + * const sample = samples[index++] + * yield* Console.log(`Sample: ${sample}`) * return sample * }), * collectSamples * ) * - * const average = samples.reduce((sum, s) => sum + s, 0) / samples.length + * const average = collected.reduce((sum, s) => sum + s, 0) / collected.length * yield* Console.log( - * `Collected ${samples.length} samples, average: ${average.toFixed(1)}` + * `Collected ${collected.length} samples, average: ${average.toFixed(1)}` * ) * }) * ``` * + * @category collecting * @since 2.0.0 - * @category utilities */ export const collectWhile: { /** * Returns a new `Schedule` that recurs as long as the specified `predicate` * returns `true`, collecting all outputs of the schedule into an array. * - * @example + * **Example** (Collecting outputs while a condition holds) + * * ```ts * import { Console, Effect, Schedule } from "effect" * - * // Collect outputs while under time limit - * const collectForTime = Schedule.collectWhile( - * Schedule.spaced("500 millis"), - * (metadata) => Effect.succeed(metadata.elapsed < 3000) // Stop after 3 seconds - * ) - * - * const timeBasedProgram = Effect.gen(function*() { - * const results = yield* Effect.repeat( - * Effect.gen(function*() { - * const value = Math.floor(Math.random() * 100) - * yield* Console.log(`Generated value: ${value}`) - * return value - * }), - * collectForTime - * ) - * - * yield* Console.log( - * `Collected ${results.length} values: [${results.join(", ")}]` - * ) - * }) - * * // Collect outputs while condition is met * const collectWhileSmall = Schedule.collectWhile( * Schedule.exponential("100 millis"), @@ -2161,16 +2160,16 @@ export const collectWhile: { * const conditionalProgram = Effect.gen(function*() { * let attempt = 0 * - * const delays = yield* Effect.repeat( + * const attempts = yield* Effect.repeat( * Effect.gen(function*() { * attempt++ * yield* Console.log(`Retry attempt ${attempt}`) - * return `${Date.now()}` + * return `attempt-${attempt}` * }), * collectWhileSmall * ) * - * yield* Console.log(`Collected attempts: [${delays.join(", ")}]`) + * yield* Console.log(`Collected attempts: [${attempts.join(", ")}]`) * }) * * // Collect with effectful predicate @@ -2187,19 +2186,17 @@ export const collectWhile: { * ) * * const effectfulProgram = Effect.gen(function*() { - * const timestamps = yield* Effect.repeat( - * Effect.gen(function*() { - * const now = new Date().toISOString() - * yield* Console.log(`Task at ${now}`) - * return now - * }), + * const results = yield* Effect.repeat( + * Effect.succeed("checked"), * collectWithCheck * ) * - * yield* Console.log(`Final collection: ${timestamps.length} items`) + * yield* Console.log(`Final collection: ${results.length} items`) * }) * * // Collect samples with condition + * const samples = [12, 18, 24, 30, 36] + * * const collectSamples = Schedule.collectWhile( * Schedule.spaced("200 millis"), * (metadata) => @@ -2207,24 +2204,25 @@ export const collectWhile: { * ) * * const samplingProgram = Effect.gen(function*() { - * const samples = yield* Effect.repeat( + * let index = 0 + * const collected = yield* Effect.repeat( * Effect.gen(function*() { - * const sample = Math.random() * 100 - * yield* Console.log(`Sample: ${sample.toFixed(1)}`) + * const sample = samples[index++] + * yield* Console.log(`Sample: ${sample}`) * return sample * }), * collectSamples * ) * - * const average = samples.reduce((sum, s) => sum + s, 0) / samples.length + * const average = collected.reduce((sum, s) => sum + s, 0) / collected.length * yield* Console.log( - * `Collected ${samples.length} samples, average: ${average.toFixed(1)}` + * `Collected ${collected.length} samples, average: ${average.toFixed(1)}` * ) * }) * ``` * + * @category collecting * @since 2.0.0 - * @category utilities */ ( predicate: ( @@ -2237,31 +2235,11 @@ export const collectWhile: { * Returns a new `Schedule` that recurs as long as the specified `predicate` * returns `true`, collecting all outputs of the schedule into an array. * - * @example + * **Example** (Collecting outputs while a condition holds) + * * ```ts * import { Console, Effect, Schedule } from "effect" * - * // Collect outputs while under time limit - * const collectForTime = Schedule.collectWhile( - * Schedule.spaced("500 millis"), - * (metadata) => Effect.succeed(metadata.elapsed < 3000) // Stop after 3 seconds - * ) - * - * const timeBasedProgram = Effect.gen(function*() { - * const results = yield* Effect.repeat( - * Effect.gen(function*() { - * const value = Math.floor(Math.random() * 100) - * yield* Console.log(`Generated value: ${value}`) - * return value - * }), - * collectForTime - * ) - * - * yield* Console.log( - * `Collected ${results.length} values: [${results.join(", ")}]` - * ) - * }) - * * // Collect outputs while condition is met * const collectWhileSmall = Schedule.collectWhile( * Schedule.exponential("100 millis"), @@ -2272,16 +2250,16 @@ export const collectWhile: { * const conditionalProgram = Effect.gen(function*() { * let attempt = 0 * - * const delays = yield* Effect.repeat( + * const attempts = yield* Effect.repeat( * Effect.gen(function*() { * attempt++ * yield* Console.log(`Retry attempt ${attempt}`) - * return `${Date.now()}` + * return `attempt-${attempt}` * }), * collectWhileSmall * ) * - * yield* Console.log(`Collected attempts: [${delays.join(", ")}]`) + * yield* Console.log(`Collected attempts: [${attempts.join(", ")}]`) * }) * * // Collect with effectful predicate @@ -2298,19 +2276,17 @@ export const collectWhile: { * ) * * const effectfulProgram = Effect.gen(function*() { - * const timestamps = yield* Effect.repeat( - * Effect.gen(function*() { - * const now = new Date().toISOString() - * yield* Console.log(`Task at ${now}`) - * return now - * }), + * const results = yield* Effect.repeat( + * Effect.succeed("checked"), * collectWithCheck * ) * - * yield* Console.log(`Final collection: ${timestamps.length} items`) + * yield* Console.log(`Final collection: ${results.length} items`) * }) * * // Collect samples with condition + * const samples = [12, 18, 24, 30, 36] + * * const collectSamples = Schedule.collectWhile( * Schedule.spaced("200 millis"), * (metadata) => @@ -2318,24 +2294,25 @@ export const collectWhile: { * ) * * const samplingProgram = Effect.gen(function*() { - * const samples = yield* Effect.repeat( + * let index = 0 + * const collected = yield* Effect.repeat( * Effect.gen(function*() { - * const sample = Math.random() * 100 - * yield* Console.log(`Sample: ${sample.toFixed(1)}`) + * const sample = samples[index++] + * yield* Console.log(`Sample: ${sample}`) * return sample * }), * collectSamples * ) * - * const average = samples.reduce((sum, s) => sum + s, 0) / samples.length + * const average = collected.reduce((sum, s) => sum + s, 0) / collected.length * yield* Console.log( - * `Collected ${samples.length} samples, average: ${average.toFixed(1)}` + * `Collected ${collected.length} samples, average: ${average.toFixed(1)}` * ) * }) * ``` * + * @category collecting * @since 2.0.0 - * @category utilities */ ( self: Schedule, @@ -2358,7 +2335,8 @@ export const collectWhile: { * Returns a new `Schedule` that recurs on the specified `Cron` schedule and * outputs the duration between recurrences. * - * @example + * **Example** (Scheduling work with cron expressions) + * * ```ts * import { Console, Data, Effect, Schedule } from "effect" * @@ -2370,7 +2348,7 @@ export const collectWhile: { * const minutelyProgram = Effect.gen(function*() { * yield* Effect.repeat( * Effect.gen(function*() { - * yield* Console.log(`Minutely task at ${new Date().toISOString()}`) + * yield* Console.log("Running minutely task") * return "minute" * }), * everyMinute.pipe( @@ -2408,8 +2386,8 @@ export const collectWhile: { * Effect.gen(function*() { * yield* Console.log("Generating weekly report...") * const report = { - * week: Math.floor(Date.now() / (7 * 24 * 60 * 60 * 1000)), - * timestamp: new Date().toISOString() + * week: 42, + * status: "ready" as const * } * yield* Console.log(`Report generated: ${JSON.stringify(report)}`) * return report @@ -2422,10 +2400,13 @@ export const collectWhile: { * const businessHoursCheck = Schedule.cron("0,15,30,45 9-17 * * 1-5") * * const businessProgram = Effect.gen(function*() { + * const statuses = ["healthy", "healthy", "degraded", "healthy"] as const + * let index = 0 + * * yield* Effect.repeat( * Effect.gen(function*() { * yield* Console.log("Business hours health check...") - * const status = Math.random() > 0.1 ? "healthy" : "degraded" + * const status = statuses[index++] * yield* Console.log(`System status: ${status}`) * return status * }), @@ -2442,9 +2423,9 @@ export const collectWhile: { * yield* Effect.repeat( * Effect.gen(function*() { * yield* Console.log("Processing monthly invoices...") - * const invoiceCount = Math.floor(Math.random() * 100) + 50 + * const invoiceCount = 72 * yield* Console.log(`Processed ${invoiceCount} invoices`) - * return { count: invoiceCount, date: new Date().toISOString() } + * return { count: invoiceCount, batch: "2024-01-a" } * }), * monthlyInvoice.pipe(Schedule.take(1)) * ) @@ -2458,11 +2439,13 @@ export const collectWhile: { * ) * * const robustProgram = Effect.gen(function*() { + * let attempt = 0 + * * yield* Effect.repeat( * Effect.gen(function*() { + * attempt++ * yield* Console.log("Complex scheduled task...") - * // Simulate occasional failures - * if (Math.random() < 0.3) { + * if (attempt === 1) { * return yield* Effect.fail(new ScheduledTaskError({ message: "Scheduled task failed" })) * } * return "success" @@ -2476,15 +2459,16 @@ export const collectWhile: { * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 2.0.0 */ export const cron: { /** * Returns a new `Schedule` that recurs on the specified `Cron` schedule and * outputs the duration between recurrences. * - * @example + * **Example** (Scheduling work with cron expressions) + * * ```ts * import { Console, Data, Effect, Schedule } from "effect" * @@ -2496,7 +2480,7 @@ export const cron: { * const minutelyProgram = Effect.gen(function*() { * yield* Effect.repeat( * Effect.gen(function*() { - * yield* Console.log(`Minutely task at ${new Date().toISOString()}`) + * yield* Console.log("Running minutely task") * return "minute" * }), * everyMinute.pipe( @@ -2534,8 +2518,8 @@ export const cron: { * Effect.gen(function*() { * yield* Console.log("Generating weekly report...") * const report = { - * week: Math.floor(Date.now() / (7 * 24 * 60 * 60 * 1000)), - * timestamp: new Date().toISOString() + * week: 42, + * status: "ready" as const * } * yield* Console.log(`Report generated: ${JSON.stringify(report)}`) * return report @@ -2548,10 +2532,13 @@ export const cron: { * const businessHoursCheck = Schedule.cron("0,15,30,45 9-17 * * 1-5") * * const businessProgram = Effect.gen(function*() { + * const statuses = ["healthy", "healthy", "degraded", "healthy"] as const + * let index = 0 + * * yield* Effect.repeat( * Effect.gen(function*() { * yield* Console.log("Business hours health check...") - * const status = Math.random() > 0.1 ? "healthy" : "degraded" + * const status = statuses[index++] * yield* Console.log(`System status: ${status}`) * return status * }), @@ -2568,9 +2555,9 @@ export const cron: { * yield* Effect.repeat( * Effect.gen(function*() { * yield* Console.log("Processing monthly invoices...") - * const invoiceCount = Math.floor(Math.random() * 100) + 50 + * const invoiceCount = 72 * yield* Console.log(`Processed ${invoiceCount} invoices`) - * return { count: invoiceCount, date: new Date().toISOString() } + * return { count: invoiceCount, batch: "2024-01-a" } * }), * monthlyInvoice.pipe(Schedule.take(1)) * ) @@ -2584,11 +2571,13 @@ export const cron: { * ) * * const robustProgram = Effect.gen(function*() { + * let attempt = 0 + * * yield* Effect.repeat( * Effect.gen(function*() { + * attempt++ * yield* Console.log("Complex scheduled task...") - * // Simulate occasional failures - * if (Math.random() < 0.3) { + * if (attempt === 1) { * return yield* Effect.fail(new ScheduledTaskError({ message: "Scheduled task failed" })) * } * return "success" @@ -2602,15 +2591,16 @@ export const cron: { * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 2.0.0 */ (expression: Cron.Cron): Schedule /** * Returns a new `Schedule` that recurs on the specified `Cron` schedule and * outputs the duration between recurrences. * - * @example + * **Example** (Scheduling work with cron expressions) + * * ```ts * import { Console, Data, Effect, Schedule } from "effect" * @@ -2622,7 +2612,7 @@ export const cron: { * const minutelyProgram = Effect.gen(function*() { * yield* Effect.repeat( * Effect.gen(function*() { - * yield* Console.log(`Minutely task at ${new Date().toISOString()}`) + * yield* Console.log("Running minutely task") * return "minute" * }), * everyMinute.pipe( @@ -2660,8 +2650,8 @@ export const cron: { * Effect.gen(function*() { * yield* Console.log("Generating weekly report...") * const report = { - * week: Math.floor(Date.now() / (7 * 24 * 60 * 60 * 1000)), - * timestamp: new Date().toISOString() + * week: 42, + * status: "ready" as const * } * yield* Console.log(`Report generated: ${JSON.stringify(report)}`) * return report @@ -2674,10 +2664,13 @@ export const cron: { * const businessHoursCheck = Schedule.cron("0,15,30,45 9-17 * * 1-5") * * const businessProgram = Effect.gen(function*() { + * const statuses = ["healthy", "healthy", "degraded", "healthy"] as const + * let index = 0 + * * yield* Effect.repeat( * Effect.gen(function*() { * yield* Console.log("Business hours health check...") - * const status = Math.random() > 0.1 ? "healthy" : "degraded" + * const status = statuses[index++] * yield* Console.log(`System status: ${status}`) * return status * }), @@ -2694,9 +2687,9 @@ export const cron: { * yield* Effect.repeat( * Effect.gen(function*() { * yield* Console.log("Processing monthly invoices...") - * const invoiceCount = Math.floor(Math.random() * 100) + 50 + * const invoiceCount = 72 * yield* Console.log(`Processed ${invoiceCount} invoices`) - * return { count: invoiceCount, date: new Date().toISOString() } + * return { count: invoiceCount, batch: "2024-01-a" } * }), * monthlyInvoice.pipe(Schedule.take(1)) * ) @@ -2710,11 +2703,13 @@ export const cron: { * ) * * const robustProgram = Effect.gen(function*() { + * let attempt = 0 + * * yield* Effect.repeat( * Effect.gen(function*() { + * attempt++ * yield* Console.log("Complex scheduled task...") - * // Simulate occasional failures - * if (Math.random() < 0.3) { + * if (attempt === 1) { * return yield* Effect.fail(new ScheduledTaskError({ message: "Scheduled task failed" })) * } * return "success" @@ -2728,13 +2723,13 @@ export const cron: { * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 2.0.0 */ (expression: string, tz?: string | DateTime.TimeZone): Schedule } = (expression: string | Cron.Cron, tz?: string | DateTime.TimeZone) => { const parsed = Cron.isCron(expression) ? Result.succeed(expression) : Cron.parse(expression, tz) - return fromStep(effect.map(parsed.asEffect(), (cron) => (now, _) => + return fromStep(effect.map(effect.fromResult(parsed), (cron) => (now, _) => effect.sync(() => { const next = Cron.next(cron, now).getTime() const duration = Duration.millis(next - now) @@ -2743,9 +2738,10 @@ export const cron: { } /** - * Returns a new schedule that outputs the delay between each occurence. + * Returns a new schedule that outputs the delay between each occurrence. + * + * **Example** (Extracting schedule delays) * - * @example * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -2768,7 +2764,7 @@ export const cron: { * ) * }) * - * // Monitor delays from a fibonacci schedule + * // Monitor delays from a Fibonacci schedule * const fibonacciDelays = Schedule.delays( * Schedule.fibonacci("200 millis").pipe(Schedule.take(8)) * ) @@ -2805,7 +2801,7 @@ export const cron: { * yield* Effect.repeat( * Effect.gen(function*() { * yield* Console.log("Adaptive task execution") - * return Date.now() + * return "completed" * }), * adaptiveDelays.pipe( * Schedule.tapOutput((delay) => Console.log(`Adaptive delay: ${delay}`)) @@ -2822,8 +2818,8 @@ export const cron: { * ) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const delays = (self: Schedule): Schedule => fromStep( @@ -2840,11 +2836,30 @@ export const delays = (self: Schedule): Schedule => { const duration = Duration.fromInputUnsafe(durationInput) @@ -2859,7 +2874,12 @@ export const duration = (durationInput: Duration.Input): Schedule => while_( @@ -2953,7 +2972,12 @@ export const during = (duration: Duration.Input): Schedule => * to recur, using the minimum of the two durations between recurrences and * outputting a tuple of the outputs of both schedules. * - * @example + * **When to use** + * + * Use when the combined schedule should continue while at least one schedule still recurs. + * + * **Example** (Combining schedules with either semantics) + * * ```ts * import { Console, Data, Effect, Schedule } from "effect" * @@ -2970,7 +2994,7 @@ export const during = (duration: Duration.Input): Schedule => * const program = Effect.gen(function*() { * const results = yield* Effect.repeat( * Effect.gen(function*() { - * yield* Console.log(`Task executed at ${new Date().toISOString()}`) + * yield* Console.log("Task executed") * return "task completed" * }), * eitherSchedule.pipe( @@ -3013,11 +3037,13 @@ export const during = (duration: Duration.Input): Schedule => * }) * * // Either provides union semantics (OR logic) - * // Compare with intersect which provides intersection semantics (AND logic) + * // Compare with both, which provides intersection semantics (AND logic) * ``` * + * @see {@link both} for continuing only while both schedules still recur + * + * @category combining * @since 2.0.0 - * @category utilities */ export const either: { /** @@ -3025,7 +3051,12 @@ export const either: { * to recur, using the minimum of the two durations between recurrences and * outputting a tuple of the outputs of both schedules. * - * @example + * **When to use** + * + * Use when the combined schedule should continue while at least one schedule still recurs. + * + * **Example** (Combining schedules with either semantics) + * * ```ts * import { Console, Data, Effect, Schedule } from "effect" * @@ -3042,7 +3073,7 @@ export const either: { * const program = Effect.gen(function*() { * const results = yield* Effect.repeat( * Effect.gen(function*() { - * yield* Console.log(`Task executed at ${new Date().toISOString()}`) + * yield* Console.log("Task executed") * return "task completed" * }), * eitherSchedule.pipe( @@ -3085,11 +3116,13 @@ export const either: { * }) * * // Either provides union semantics (OR logic) - * // Compare with intersect which provides intersection semantics (AND logic) + * // Compare with both, which provides intersection semantics (AND logic) * ``` * + * @see {@link both} for continuing only while both schedules still recur + * + * @category combining * @since 2.0.0 - * @category utilities */ (other: Schedule): ( self: Schedule @@ -3099,7 +3132,12 @@ export const either: { * to recur, using the minimum of the two durations between recurrences and * outputting a tuple of the outputs of both schedules. * - * @example + * **When to use** + * + * Use when the combined schedule should continue while at least one schedule still recurs. + * + * **Example** (Combining schedules with either semantics) + * * ```ts * import { Console, Data, Effect, Schedule } from "effect" * @@ -3116,7 +3154,7 @@ export const either: { * const program = Effect.gen(function*() { * const results = yield* Effect.repeat( * Effect.gen(function*() { - * yield* Console.log(`Task executed at ${new Date().toISOString()}`) + * yield* Console.log("Task executed") * return "task completed" * }), * eitherSchedule.pipe( @@ -3159,11 +3197,13 @@ export const either: { * }) * * // Either provides union semantics (OR logic) - * // Compare with intersect which provides intersection semantics (AND logic) + * // Compare with both, which provides intersection semantics (AND logic) * ``` * + * @see {@link both} for continuing only while both schedules still recur + * + * @category combining * @since 2.0.0 - * @category utilities */ ( self: Schedule, @@ -3180,7 +3220,13 @@ export const either: { * to recur, using the minimum of the two durations between recurrences and * outputting the result of the left schedule (i.e. `self`). * - * @example + * **When to use** + * + * Use when either schedule may keep recurrence going and only the left + * schedule's output is needed. + * + * **Example** (Combining either schedules and keeping the left output) + * * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -3206,8 +3252,8 @@ export const either: { * }) * ``` * - * @since 2.0.0 - * @category utilities + * @category combining + * @since 4.0.0 */ export const eitherLeft: { /** @@ -3215,7 +3261,13 @@ export const eitherLeft: { * to recur, using the minimum of the two durations between recurrences and * outputting the result of the left schedule (i.e. `self`). * - * @example + * **When to use** + * + * Use when either schedule may keep recurrence going and only the left + * schedule's output is needed. + * + * **Example** (Combining either schedules and keeping the left output) + * * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -3241,8 +3293,8 @@ export const eitherLeft: { * }) * ``` * - * @since 2.0.0 - * @category utilities + * @category combining + * @since 4.0.0 */ (other: Schedule): ( self: Schedule @@ -3252,7 +3304,13 @@ export const eitherLeft: { * to recur, using the minimum of the two durations between recurrences and * outputting the result of the left schedule (i.e. `self`). * - * @example + * **When to use** + * + * Use when either schedule may keep recurrence going and only the left + * schedule's output is needed. + * + * **Example** (Combining either schedules and keeping the left output) + * * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -3278,8 +3336,8 @@ export const eitherLeft: { * }) * ``` * - * @since 2.0.0 - * @category utilities + * @category combining + * @since 4.0.0 */ ( self: Schedule, @@ -3295,7 +3353,13 @@ export const eitherLeft: { * to recur, using the minimum of the two durations between recurrences and * outputting the result of the right schedule (i.e. `other`). * - * @example + * **When to use** + * + * Use when either schedule may keep recurrence going and only the right + * schedule's output is needed. + * + * **Example** (Combining either schedules and keeping the right output) + * * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -3321,8 +3385,8 @@ export const eitherLeft: { * }) * ``` * - * @since 2.0.0 - * @category utilities + * @category combining + * @since 4.0.0 */ export const eitherRight: { /** @@ -3330,7 +3394,13 @@ export const eitherRight: { * to recur, using the minimum of the two durations between recurrences and * outputting the result of the right schedule (i.e. `other`). * - * @example + * **When to use** + * + * Use when either schedule may keep recurrence going and only the right + * schedule's output is needed. + * + * **Example** (Combining either schedules and keeping the right output) + * * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -3356,8 +3426,8 @@ export const eitherRight: { * }) * ``` * - * @since 2.0.0 - * @category utilities + * @category combining + * @since 4.0.0 */ (other: Schedule): ( self: Schedule @@ -3367,7 +3437,13 @@ export const eitherRight: { * to recur, using the minimum of the two durations between recurrences and * outputting the result of the right schedule (i.e. `other`). * - * @example + * **When to use** + * + * Use when either schedule may keep recurrence going and only the right + * schedule's output is needed. + * + * **Example** (Combining either schedules and keeping the right output) + * * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -3393,8 +3469,8 @@ export const eitherRight: { * }) * ``` * - * @since 2.0.0 - * @category utilities + * @category combining + * @since 4.0.0 */ ( self: Schedule, @@ -3411,7 +3487,13 @@ export const eitherRight: { * outputting the result of the combination of both schedule outputs using the * specified `combine` function. * - * @example + * **When to use** + * + * Use when either schedule may keep recurrence going and their outputs should be + * combined into a custom value. + * + * **Example** (Combining either schedule outputs) + * * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -3441,8 +3523,8 @@ export const eitherRight: { * }) * ``` * + * @category combining * @since 2.0.0 - * @category utilities */ export const eitherWith: { /** @@ -3451,7 +3533,13 @@ export const eitherWith: { * outputting the result of the combination of both schedule outputs using the * specified `combine` function. * - * @example + * **When to use** + * + * Use when either schedule may keep recurrence going and their outputs should be + * combined into a custom value. + * + * **Example** (Combining either schedule outputs) + * * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -3481,8 +3569,8 @@ export const eitherWith: { * }) * ``` * + * @category combining * @since 2.0.0 - * @category utilities */ ( other: Schedule, @@ -3496,7 +3584,13 @@ export const eitherWith: { * outputting the result of the combination of both schedule outputs using the * specified `combine` function. * - * @example + * **When to use** + * + * Use when either schedule may keep recurrence going and their outputs should be + * combined into a custom value. + * + * **Example** (Combining either schedule outputs) + * * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -3526,8 +3620,8 @@ export const eitherWith: { * }) * ``` * + * @category combining * @since 2.0.0 - * @category utilities */ ( self: Schedule, @@ -3558,7 +3652,13 @@ export const eitherWith: { * outputting the result of the combination of both schedule outputs using the * specified `combine` function. * - * @example + * **When to use** + * + * Use when either schedule may keep recurrence going and their outputs should be + * combined into a custom value. + * + * **Example** (Combining either schedule outputs) + * * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -3588,8 +3688,8 @@ export const eitherWith: { * }) * ``` * + * @category combining * @since 2.0.0 - * @category utilities */ [Output3, Duration.Duration]>([ combine(leftResult[0], rightDone as Output2), @@ -3612,14 +3712,16 @@ export const eitherWith: { ))) /** - * A schedule that always recurs and returns the total elapsed duration since the first recurrence. + * Schedule that always recurs and returns the total elapsed duration since the + * first recurrence. + * + * **Details** * * This schedule never stops and outputs the cumulative time that has passed since the schedule * started executing. Useful for tracking execution time or implementing time-based logic. * - * @returns A schedule that outputs the elapsed duration and never stops + * **Example** (Measuring elapsed schedule time) * - * @example * ```ts * import { Console, Duration, Effect, Schedule } from "effect" * @@ -3637,19 +3739,20 @@ export const eitherWith: { * }) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const elapsed: Schedule = fromStepWithMetadata( effect.succeed((meta) => effect.succeed([Duration.millis(meta.elapsed), Duration.zero] as const)) ) /** - * A schedule that always recurs, but will wait a certain amount between + * Schedule that always recurs, but will wait a certain amount between * repetitions, given by `base * factor.pow(n)`, where `n` is the number of * repetitions so far. Returns the current duration between recurrences. * - * @example + * **Example** (Retrying with exponential backoff) + * * ```ts * import { Console, Data, Effect, Schedule } from "effect" * @@ -3689,8 +3792,8 @@ export const elapsed: Schedule = fromStepWithMetadata( * // Will retry with delays: 50ms, 100ms, 200ms before success * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const exponential = ( base: Duration.Input, @@ -3704,21 +3807,22 @@ export const exponential = ( } /** - * A schedule that always recurs, increasing delays by summing the preceding - * two delays (similar to the fibonacci sequence). Returns the current + * Schedule that always recurs, increasing delays by summing the preceding + * two delays (similar to the Fibonacci sequence). Returns the current * duration between recurrences. * - * @example + * **Example** (Retrying with Fibonacci backoff) + * * ```ts * import { Console, Data, Effect, Schedule } from "effect" * * class RetryAttemptError extends Data.TaggedError("RetryAttemptError")<{ readonly message: string }> {} * - * // Basic fibonacci schedule starting with 100ms + * // Basic Fibonacci schedule starting with 100ms * const fibSchedule = Schedule.fibonacci("100 millis") * // Delays: 100ms, 100ms, 200ms, 300ms, 500ms, 800ms, 1300ms, ... * - * // Retry with fibonacci backoff for gradual increase + * // Retry with Fibonacci backoff for gradual increase * const retryWithFib = Effect.gen(function*() { * let attempt = 0 * @@ -3742,9 +3846,9 @@ export const exponential = ( * yield* Console.log(`Final result: ${result}`) * }) * - * // Heartbeat with fibonacci intervals (starts fast, gets slower) + * // Heartbeat with Fibonacci intervals (starts fast, gets slower) * const adaptiveHeartbeat = Effect.gen(function*() { - * yield* Console.log(`Heartbeat at ${new Date().toISOString()}`) + * yield* Console.log("Heartbeat") * return "pulse" * }).pipe( * Effect.repeat( @@ -3766,8 +3870,8 @@ export const exponential = ( * }) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const fibonacci = (one: Duration.Input): Schedule => { const oneMillis = Duration.toMillis(Duration.fromInputUnsafe(one)) @@ -3788,24 +3892,31 @@ export const fibonacci = (one: Duration.Input): Schedule => { * Returns a `Schedule` that recurs on the specified fixed `interval` and * outputs the number of repetitions of the schedule so far. * - * If the action run between updates takes longer than the interval, then the - * action will be run immediately, but re-runs will not "pile up". + * **When to use** * - * ``` + * Use when recurrences should stay aligned to a regular cadence. + * + * **Gotchas** + * + * If the action run between recurrences takes longer than the interval, the + * next recurrence happens immediately, but missed intervals are not replayed. + * + * ```text * |-----interval-----|-----interval-----|-----interval-----| * |---------action--------||action|-----|action|-----------| * ``` * - * @example + * **Example** (Repeating on fixed intervals) + * * ```ts * import { Console, Effect, Schedule } from "effect" * - * // Fixed interval schedule - runs exactly every 1 second + * // Fixed interval schedule - recurs on a one-second cadence * const everySecond = Schedule.fixed("1 second") * * // Health check that runs at fixed intervals * const healthCheck = Effect.gen(function*() { - * yield* Console.log(`Health check at ${new Date().toISOString()}`) + * yield* Console.log("Health check") * yield* Effect.sleep("200 millis") // simulate health check work * return "healthy" * }).pipe( @@ -3843,8 +3954,10 @@ export const fibonacci = (one: Duration.Input): Schedule => { * }) * ``` * - * @since 2.0.0 + * @see {@link spaced} for delaying after each action completes + * * @category constructors + * @since 2.0.0 */ export const fixed = (interval: Duration.Input): Schedule => { const window = Duration.toMillis(Duration.fromInputUnsafe(interval)) @@ -3874,7 +3987,8 @@ export const fixed = (interval: Duration.Input): Schedule => { * Returns a new `Schedule` that maps the output of this schedule using the * specified function. * - * @example + * **Example** (Mapping schedule outputs) + * * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -3892,7 +4006,6 @@ export const fixed = (interval: Duration.Input): Schedule => { * const structuredSchedule = Schedule.spaced("1 second").pipe( * Schedule.map((recurrence) => Effect.succeed({ * iteration: recurrence + 1, - * timestamp: new Date().toISOString(), * phase: recurrence < 5 ? "warmup" as const : "steady" as const * })) * ) @@ -3904,7 +4017,7 @@ export const fixed = (interval: Duration.Input): Schedule => { * Schedule.take(8), * Schedule.tapOutput((info) => * Console.log( - * `${info.phase} phase - iteration ${info.iteration} at ${info.timestamp}` + * `${info.phase} phase - iteration ${info.iteration}` * ) * ) * ) @@ -3929,15 +4042,16 @@ export const fixed = (interval: Duration.Input): Schedule => { * ) * ``` * - * @since 2.0.0 * @category mapping + * @since 2.0.0 */ export const map: { /** * Returns a new `Schedule` that maps the output of this schedule using the * specified function. * - * @example + * **Example** (Mapping schedule outputs) + * * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -3955,7 +4069,6 @@ export const map: { * const structuredSchedule = Schedule.spaced("1 second").pipe( * Schedule.map((recurrence) => Effect.succeed({ * iteration: recurrence + 1, - * timestamp: new Date().toISOString(), * phase: recurrence < 5 ? "warmup" as const : "steady" as const * })) * ) @@ -3967,7 +4080,7 @@ export const map: { * Schedule.take(8), * Schedule.tapOutput((info) => * Console.log( - * `${info.phase} phase - iteration ${info.iteration} at ${info.timestamp}` + * `${info.phase} phase - iteration ${info.iteration}` * ) * ) * ) @@ -3992,8 +4105,8 @@ export const map: { * ) * ``` * - * @since 2.0.0 * @category mapping + * @since 2.0.0 */ (f: (output: Output) => Output2 | Effect): ( self: Schedule @@ -4002,7 +4115,8 @@ export const map: { * Returns a new `Schedule` that maps the output of this schedule using the * specified function. * - * @example + * **Example** (Mapping schedule outputs) + * * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -4020,7 +4134,6 @@ export const map: { * const structuredSchedule = Schedule.spaced("1 second").pipe( * Schedule.map((recurrence) => Effect.succeed({ * iteration: recurrence + 1, - * timestamp: new Date().toISOString(), * phase: recurrence < 5 ? "warmup" as const : "steady" as const * })) * ) @@ -4032,7 +4145,7 @@ export const map: { * Schedule.take(8), * Schedule.tapOutput((info) => * Console.log( - * `${info.phase} phase - iteration ${info.iteration} at ${info.timestamp}` + * `${info.phase} phase - iteration ${info.iteration}` * ) * ) * ) @@ -4057,8 +4170,8 @@ export const map: { * ) * ``` * - * @since 2.0.0 * @category mapping + * @since 2.0.0 */ ( self: Schedule, @@ -4086,9 +4199,10 @@ export const map: { /** * Returns a new `Schedule` that modifies the delay of the next recurrence - * of the schedule using the specified effectual function. + * of the schedule using the specified effectful function. + * + * **Example** (Modifying delays from schedule output) * - * @example * ```ts * import { Console, Duration, Effect, Schedule } from "effect" * @@ -4113,15 +4227,16 @@ export const map: { * }) * ``` * + * @category delays & timeouts * @since 2.0.0 - * @category utilities */ export const modifyDelay: { /** * Returns a new `Schedule` that modifies the delay of the next recurrence - * of the schedule using the specified effectual function. + * of the schedule using the specified effectful function. + * + * **Example** (Modifying delays from schedule output) * - * @example * ```ts * import { Console, Duration, Effect, Schedule } from "effect" * @@ -4146,8 +4261,8 @@ export const modifyDelay: { * }) * ``` * + * @category delays & timeouts * @since 2.0.0 - * @category utilities */ ( f: ( @@ -4159,9 +4274,10 @@ export const modifyDelay: { ) => Schedule /** * Returns a new `Schedule` that modifies the delay of the next recurrence - * of the schedule using the specified effectual function. + * of the schedule using the specified effectful function. + * + * **Example** (Modifying delays from schedule output) * - * @example * ```ts * import { Console, Duration, Effect, Schedule } from "effect" * @@ -4186,8 +4302,8 @@ export const modifyDelay: { * }) * ``` * + * @category delays & timeouts * @since 2.0.0 - * @category utilities */ ( self: Schedule, @@ -4212,10 +4328,19 @@ export const modifyDelay: { /** * Returns a new `Schedule` that randomly adjusts each recurrence delay. * - * Delays are jittered between `80%` and `120%` of the original delay. + * **When to use** + * + * Use to add random variation to an existing schedule's recurrence delays while + * preserving its output and completion behavior. + * + * **Details** + * + * Each recurrence delay is scaled by a random factor between `0.8` and `1.2`. + * + * @see {@link modifyDelay} for replacing recurrence delays with a custom effectful transformation * + * @category delays & timeouts * @since 2.0.0 - * @category utilities */ export const jittered = ( self: Schedule @@ -4229,7 +4354,8 @@ export const jittered = ( /** * Returns a new `Schedule` that outputs the inputs of the specified schedule. * - * @example + * **Example** (Passing inputs through as outputs) + * * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -4251,8 +4377,8 @@ export const jittered = ( * }) * ``` * + * @category mapping * @since 2.0.0 - * @category utilities */ export const passthrough = ( self: Schedule @@ -4268,7 +4394,18 @@ export const passthrough = ( * Returns a `Schedule` which can only be stepped the specified number of * `times` before it terminates. * - * @example + * **When to use** + * + * Use when you need a counter schedule with no additional delay. + * + * **Gotchas** + * + * `recurs(n)` counts schedule recurrences, not the first evaluation of the + * effect being repeated or retried. For retrying, this means one initial + * attempt plus at most `n` retries. + * + * **Example** (Limiting recurrences) + * * ```ts * import { Console, Data, Effect, Schedule } from "effect" * @@ -4300,13 +4437,13 @@ export const passthrough = ( * * // Combining recurs with other schedules for sophisticated retry logic * const complexRetry = Schedule.exponential("100 millis").pipe( - * Schedule.both(Schedule.recurs(3)) // At most 3 attempts + * Schedule.both(Schedule.recurs(3)) // At most 3 retries * ) * - * // Repeat an effect exactly 10 times - * const exactlyTenTimes = Effect.gen(function*() { + * // Allow ten recurrences after the initial run + * const tenRecurrences = Effect.gen(function*() { * yield* Console.log("Executing task...") - * return Math.random() + * return "completed" * }).pipe( * Effect.repeat(Schedule.recurs(10)) * ) @@ -4317,6 +4454,8 @@ export const passthrough = ( * ) * ``` * + * @see {@link take} for limiting an existing schedule + * * @category constructors * @since 2.0.0 */ @@ -4328,7 +4467,8 @@ export const recurs = (times: number): Schedule => * using the specified effectful `combine` function and starting from the * specified `initial` state. * - * @example + * **Example** (Reducing schedule outputs) + * * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -4353,24 +4493,24 @@ export const recurs = (times: number): Schedule => * yield* Console.log(`Final sum: ${finalSum}`) * }) * - * // Build a history of execution times + * // Build a history of execution counts * const historySchedule = Schedule.reduce( * Schedule.spaced("1 second").pipe(Schedule.take(4)), * () => [] as Array, // Initial empty array - * (history, executionNumber) => Effect.succeed([...history, Date.now()]) + * (history, executionNumber) => Effect.succeed([...history, executionNumber]) * ) * * const historyProgram = Effect.gen(function*() { * const timeline = yield* Effect.repeat( * Effect.gen(function*() { - * yield* Console.log("Recording timestamp...") + * yield* Console.log("Recording execution...") * return "recorded" * }), * historySchedule * ) * * yield* Console.log( - * `Execution timeline: ${timeline.length} timestamps recorded` + * `Execution timeline: ${timeline.join(", ")}` * ) * }) * @@ -4431,8 +4571,8 @@ export const recurs = (times: number): Schedule => * }) * ``` * + * @category folding * @since 2.0.0 - * @category utilities */ export const reduce: { /** @@ -4440,7 +4580,8 @@ export const reduce: { * using the specified effectful `combine` function and starting from the * specified `initial` state. * - * @example + * **Example** (Reducing schedule outputs) + * * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -4465,24 +4606,24 @@ export const reduce: { * yield* Console.log(`Final sum: ${finalSum}`) * }) * - * // Build a history of execution times + * // Build a history of execution counts * const historySchedule = Schedule.reduce( * Schedule.spaced("1 second").pipe(Schedule.take(4)), * () => [] as Array, // Initial empty array - * (history, executionNumber) => Effect.succeed([...history, Date.now()]) + * (history, executionNumber) => Effect.succeed([...history, executionNumber]) * ) * * const historyProgram = Effect.gen(function*() { * const timeline = yield* Effect.repeat( * Effect.gen(function*() { - * yield* Console.log("Recording timestamp...") + * yield* Console.log("Recording execution...") * return "recorded" * }), * historySchedule * ) * * yield* Console.log( - * `Execution timeline: ${timeline.length} timestamps recorded` + * `Execution timeline: ${timeline.join(", ")}` * ) * }) * @@ -4543,8 +4684,8 @@ export const reduce: { * }) * ``` * + * @category folding * @since 2.0.0 - * @category utilities */ ( initial: LazyArg, @@ -4557,7 +4698,8 @@ export const reduce: { * using the specified effectful `combine` function and starting from the * specified `initial` state. * - * @example + * **Example** (Reducing schedule outputs) + * * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -4582,24 +4724,24 @@ export const reduce: { * yield* Console.log(`Final sum: ${finalSum}`) * }) * - * // Build a history of execution times + * // Build a history of execution counts * const historySchedule = Schedule.reduce( * Schedule.spaced("1 second").pipe(Schedule.take(4)), * () => [] as Array, // Initial empty array - * (history, executionNumber) => Effect.succeed([...history, Date.now()]) + * (history, executionNumber) => Effect.succeed([...history, executionNumber]) * ) * * const historyProgram = Effect.gen(function*() { * const timeline = yield* Effect.repeat( * Effect.gen(function*() { - * yield* Console.log("Recording timestamp...") + * yield* Console.log("Recording execution...") * return "recorded" * }), * historySchedule * ) * * yield* Console.log( - * `Execution timeline: ${timeline.length} timestamps recorded` + * `Execution timeline: ${timeline.join(", ")}` * ) * }) * @@ -4660,8 +4802,8 @@ export const reduce: { * }) * ``` * + * @category folding * @since 2.0.0 - * @category utilities */ ( self: Schedule, @@ -4700,7 +4842,12 @@ export const reduce: { * Returns a schedule that recurs continuously, each repetition spaced the * specified duration from the last run. * - * @example + * **When to use** + * + * Use when each delay should start after the previous action completes. + * + * **Example** (Repeating with fixed spacing) + * * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -4709,7 +4856,7 @@ export const reduce: { * * // Heartbeat that runs indefinitely with fixed spacing * const heartbeat = Effect.gen(function*() { - * yield* Console.log(`Heartbeat at ${new Date().toISOString()}`) + * yield* Console.log("Heartbeat") * }).pipe( * Effect.repeat(everyTwoSeconds) * ) @@ -4742,20 +4889,143 @@ export const reduce: { * }) * ``` * - * @since 2.0.0 + * @see {@link fixed} for recurrence aligned to a regular cadence + * * @category constructors + * @since 2.0.0 */ export const spaced = (duration: Duration.Input): Schedule => { const decoded = Duration.fromInputUnsafe(duration) return fromStepWithMetadata(effect.succeed((meta) => effect.succeed([meta.attempt - 1, decoded]))) } +/** + * Returns a new `Schedule` that allows execution of an effectful function for + * every decision of the schedule, but does not alter the inputs and outputs of + * the schedule. + * + * **Details** + * + * The callback receives the full schedule metadata, including the input, output, + * computed delay duration, current attempt, and elapsed timing information. + * + * **Example** (Tapping schedule metadata) + * + * ```ts + * import { Console, Effect, Schedule } from "effect" + * + * const monitoredSchedule = Schedule.exponential("100 millis").pipe( + * Schedule.take(5), + * Schedule.tap((metadata) => + * Console.log( + * `Attempt ${metadata.attempt} produced ${metadata.output} ` + + * `after ${metadata.elapsed}ms; next delay is ${metadata.duration}` + * ) + * ) + * ) + * + * const program = Effect.retry( + * Effect.fail("transient error"), + * monitoredSchedule + * ) + * ``` + * + * @category sequencing + * @since 4.0.0 + */ +export const tap: { + /** + * Returns a new `Schedule` that allows execution of an effectful function for + * every decision of the schedule, but does not alter the inputs and outputs of + * the schedule. + * + * **Details** + * + * The callback receives the full schedule metadata, including the input, output, + * computed delay duration, current attempt, and elapsed timing information. + * + * **Example** (Tapping schedule metadata) + * + * ```ts + * import { Console, Effect, Schedule } from "effect" + * + * const monitoredSchedule = Schedule.exponential("100 millis").pipe( + * Schedule.take(5), + * Schedule.tap((metadata) => + * Console.log( + * `Attempt ${metadata.attempt} produced ${metadata.output} ` + + * `after ${metadata.elapsed}ms; next delay is ${metadata.duration}` + * ) + * ) + * ) + * + * const program = Effect.retry( + * Effect.fail("transient error"), + * monitoredSchedule + * ) + * ``` + * + * @category sequencing + * @since 4.0.0 + */ + (f: (metadata: Metadata) => Effect): ( + self: Schedule + ) => Schedule + /** + * Returns a new `Schedule` that allows execution of an effectful function for + * every decision of the schedule, but does not alter the inputs and outputs of + * the schedule. + * + * **Details** + * + * The callback receives the full schedule metadata, including the input, output, + * computed delay duration, current attempt, and elapsed timing information. + * + * **Example** (Tapping schedule metadata) + * + * ```ts + * import { Console, Effect, Schedule } from "effect" + * + * const monitoredSchedule = Schedule.exponential("100 millis").pipe( + * Schedule.take(5), + * Schedule.tap((metadata) => + * Console.log( + * `Attempt ${metadata.attempt} produced ${metadata.output} ` + + * `after ${metadata.elapsed}ms; next delay is ${metadata.duration}` + * ) + * ) + * ) + * + * const program = Effect.retry( + * Effect.fail("transient error"), + * monitoredSchedule + * ) + * ``` + * + * @category sequencing + * @since 4.0.0 + */ + ( + self: Schedule, + f: (metadata: Metadata) => Effect + ): Schedule +} = dual(2, ( + self: Schedule, + f: (metadata: Metadata) => Effect +): Schedule => + fromStep(effect.map(toStep(self), (step) => { + const meta = metadataFn() + return (now, input) => + effect.tap(step(now, input), ([output, duration]) => f({ ...meta(now, input), output, duration })) + }))) + /** * Returns a new `Schedule` that allows execution of an effectful function for * every input to the schedule, but does not alter the inputs and outputs of * the schedule. * - * @example + * **Example** (Tapping retry inputs) + * * ```ts * import { Console, Data, Effect, Schedule } from "effect" * @@ -4791,7 +5061,6 @@ export const spaced = (duration: Duration.Input): Schedule => { * Schedule.take(5), * Schedule.tapInput((input: unknown) => * Effect.gen(function*() { - * yield* Console.log(`Processing input at ${new Date().toISOString()}`) * yield* Console.log(`Input type: ${typeof input}`) * // In real applications, might send metrics to monitoring system * }) @@ -4813,10 +5082,13 @@ export const spaced = (duration: Duration.Input): Schedule => { * ) * * const validationProgram = Effect.gen(function*() { + * let count = 0 + * * yield* Effect.repeat( * Effect.gen(function*() { + * count++ * yield* Console.log("Task with validation") - * return { data: Math.random(), timestamp: Date.now() } + * return { data: `sample-${count}` } * }), * validatingSchedule * ) @@ -4828,10 +5100,10 @@ export const spaced = (duration: Duration.Input): Schedule => { * Schedule.tapInput((error: RetryError) => * Effect.gen(function*() { * if (String(error).includes("critical")) { - * yield* Console.log(`🚨 CRITICAL ERROR: ${String(error)}`) + * yield* Console.log(`Critical error: ${String(error)}`) * // In real applications, might trigger alerts or notifications * } else { - * yield* Console.log(`ℹ️ Regular error: ${String(error)}`) + * yield* Console.log(`Regular error: ${String(error)}`) * } * }) * ) @@ -4865,14 +5137,14 @@ export const spaced = (duration: Duration.Input): Schedule => { * ), * Schedule.tapInput((error: RetryError) => * String(error).length > 20 - * ? Console.log("📝 Long error message detected") + * ? Console.log("Long error message detected") * : Effect.void * ) * ) * ``` * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ export const tapInput: { /** @@ -4880,7 +5152,8 @@ export const tapInput: { * every input to the schedule, but does not alter the inputs and outputs of * the schedule. * - * @example + * **Example** (Tapping retry inputs) + * * ```ts * import { Console, Data, Effect, Schedule } from "effect" * @@ -4916,7 +5189,6 @@ export const tapInput: { * Schedule.take(5), * Schedule.tapInput((input: unknown) => * Effect.gen(function*() { - * yield* Console.log(`Processing input at ${new Date().toISOString()}`) * yield* Console.log(`Input type: ${typeof input}`) * // In real applications, might send metrics to monitoring system * }) @@ -4938,10 +5210,13 @@ export const tapInput: { * ) * * const validationProgram = Effect.gen(function*() { + * let count = 0 + * * yield* Effect.repeat( * Effect.gen(function*() { + * count++ * yield* Console.log("Task with validation") - * return { data: Math.random(), timestamp: Date.now() } + * return { data: `sample-${count}` } * }), * validatingSchedule * ) @@ -4953,10 +5228,10 @@ export const tapInput: { * Schedule.tapInput((error: RetryError) => * Effect.gen(function*() { * if (String(error).includes("critical")) { - * yield* Console.log(`🚨 CRITICAL ERROR: ${String(error)}`) + * yield* Console.log(`Critical error: ${String(error)}`) * // In real applications, might trigger alerts or notifications * } else { - * yield* Console.log(`ℹ️ Regular error: ${String(error)}`) + * yield* Console.log(`Regular error: ${String(error)}`) * } * }) * ) @@ -4990,14 +5265,14 @@ export const tapInput: { * ), * Schedule.tapInput((error: RetryError) => * String(error).length > 20 - * ? Console.log("📝 Long error message detected") + * ? Console.log("Long error message detected") * : Effect.void * ) * ) * ``` * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ (f: (input: Input) => Effect): ( self: Schedule @@ -5007,7 +5282,8 @@ export const tapInput: { * every input to the schedule, but does not alter the inputs and outputs of * the schedule. * - * @example + * **Example** (Tapping retry inputs) + * * ```ts * import { Console, Data, Effect, Schedule } from "effect" * @@ -5043,7 +5319,6 @@ export const tapInput: { * Schedule.take(5), * Schedule.tapInput((input: unknown) => * Effect.gen(function*() { - * yield* Console.log(`Processing input at ${new Date().toISOString()}`) * yield* Console.log(`Input type: ${typeof input}`) * // In real applications, might send metrics to monitoring system * }) @@ -5065,10 +5340,13 @@ export const tapInput: { * ) * * const validationProgram = Effect.gen(function*() { + * let count = 0 + * * yield* Effect.repeat( * Effect.gen(function*() { + * count++ * yield* Console.log("Task with validation") - * return { data: Math.random(), timestamp: Date.now() } + * return { data: `sample-${count}` } * }), * validatingSchedule * ) @@ -5080,10 +5358,10 @@ export const tapInput: { * Schedule.tapInput((error: RetryError) => * Effect.gen(function*() { * if (String(error).includes("critical")) { - * yield* Console.log(`🚨 CRITICAL ERROR: ${String(error)}`) + * yield* Console.log(`Critical error: ${String(error)}`) * // In real applications, might trigger alerts or notifications * } else { - * yield* Console.log(`ℹ️ Regular error: ${String(error)}`) + * yield* Console.log(`Regular error: ${String(error)}`) * } * }) * ) @@ -5117,14 +5395,14 @@ export const tapInput: { * ), * Schedule.tapInput((error: RetryError) => * String(error).length > 20 - * ? Console.log("📝 Long error message detected") + * ? Console.log("Long error message detected") * : Effect.void * ) * ) * ``` * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ ( self: Schedule, @@ -5144,7 +5422,8 @@ export const tapInput: { * every output of the schedule, but does not alter the inputs and outputs of * the schedule. * - * @example + * **Example** (Tapping schedule outputs) + * * ```ts * import { Console, Data, Effect, Schedule } from "effect" * @@ -5192,7 +5471,7 @@ export const tapInput: { * Effect.gen(function*() { * const delayMs = delay.toString() * if (delayMs.includes("1000")) { // Alert on delays >= 1 second - * yield* Console.log(`🚨 High delay detected: ${delay}`) + * yield* Console.log(`High delay detected: ${delay}`) * } * }) * ) @@ -5202,8 +5481,7 @@ export const tapInput: { * yield* Effect.repeat( * Effect.gen(function*() { * yield* Console.log("Performing health check...") - * // Simulate health check - * return Math.random() > 0.7 ? "healthy" : "degraded" + * return "healthy" * }), * alertingSchedule * ) @@ -5215,14 +5493,14 @@ export const tapInput: { * Schedule.tapOutput((count) => Console.log(`Execution ${count + 1}`)), * Schedule.tapOutput((count) => * count % 3 === 0 - * ? Console.log("🎯 Checkpoint reached!") + * ? Console.log("Checkpoint reached") * : Effect.void * ) * ) * ``` * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ export const tapOutput: { /** @@ -5230,7 +5508,8 @@ export const tapOutput: { * every output of the schedule, but does not alter the inputs and outputs of * the schedule. * - * @example + * **Example** (Tapping schedule outputs) + * * ```ts * import { Console, Data, Effect, Schedule } from "effect" * @@ -5278,7 +5557,7 @@ export const tapOutput: { * Effect.gen(function*() { * const delayMs = delay.toString() * if (delayMs.includes("1000")) { // Alert on delays >= 1 second - * yield* Console.log(`🚨 High delay detected: ${delay}`) + * yield* Console.log(`High delay detected: ${delay}`) * } * }) * ) @@ -5288,8 +5567,7 @@ export const tapOutput: { * yield* Effect.repeat( * Effect.gen(function*() { * yield* Console.log("Performing health check...") - * // Simulate health check - * return Math.random() > 0.7 ? "healthy" : "degraded" + * return "healthy" * }), * alertingSchedule * ) @@ -5301,14 +5579,14 @@ export const tapOutput: { * Schedule.tapOutput((count) => Console.log(`Execution ${count + 1}`)), * Schedule.tapOutput((count) => * count % 3 === 0 - * ? Console.log("🎯 Checkpoint reached!") + * ? Console.log("Checkpoint reached") * : Effect.void * ) * ) * ``` * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ (f: (output: Output) => Effect): ( self: Schedule @@ -5318,7 +5596,8 @@ export const tapOutput: { * every output of the schedule, but does not alter the inputs and outputs of * the schedule. * - * @example + * **Example** (Tapping schedule outputs) + * * ```ts * import { Console, Data, Effect, Schedule } from "effect" * @@ -5366,7 +5645,7 @@ export const tapOutput: { * Effect.gen(function*() { * const delayMs = delay.toString() * if (delayMs.includes("1000")) { // Alert on delays >= 1 second - * yield* Console.log(`🚨 High delay detected: ${delay}`) + * yield* Console.log(`High delay detected: ${delay}`) * } * }) * ) @@ -5376,8 +5655,7 @@ export const tapOutput: { * yield* Effect.repeat( * Effect.gen(function*() { * yield* Console.log("Performing health check...") - * // Simulate health check - * return Math.random() > 0.7 ? "healthy" : "degraded" + * return "healthy" * }), * alertingSchedule * ) @@ -5389,14 +5667,14 @@ export const tapOutput: { * Schedule.tapOutput((count) => Console.log(`Execution ${count + 1}`)), * Schedule.tapOutput((count) => * count % 3 === 0 - * ? Console.log("🎯 Checkpoint reached!") + * ? Console.log("Checkpoint reached") * : Effect.void * ) * ) * ``` * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ ( self: Schedule, @@ -5416,21 +5694,32 @@ export const tapOutput: { * from the schedule. Once the specified number of outputs is reached, the * schedule will stop. * - * @example + * **When to use** + * + * Use to limit an existing schedule while preserving its output and delay behavior. + * + * **Gotchas** + * + * `take(n)` limits schedule outputs. When used with repeat or retry, the + * effect is evaluated once before the schedule is stepped, so the total number + * of evaluations can be one greater than the number of outputs taken. + * + * **Example** (Taking a limited number of recurrences) + * * ```ts * import { Console, Data, Effect, Schedule } from "effect" * * class RetryAttemptError extends Data.TaggedError("RetryAttemptError")<{ readonly message: string }> {} * - * // Limit an infinite schedule to run only 5 times + * // Limit an infinite schedule to five recurrences * const limitedHeartbeat = Schedule.spaced("1 second").pipe( - * Schedule.take(5) // Will stop after 5 executions + * Schedule.take(5) // Will stop after 5 schedule outputs * ) * * const heartbeatProgram = Effect.gen(function*() { * yield* Effect.repeat( * Effect.gen(function*() { - * yield* Console.log(`Heartbeat at ${new Date().toISOString()}`) + * yield* Console.log("Heartbeat") * return "pulse" * }), * limitedHeartbeat @@ -5470,15 +5759,15 @@ export const tapOutput: { * * // Combine take with other schedule operations * const samplingSchedule = Schedule.fixed("500 millis").pipe( - * Schedule.take(10), // Sample exactly 10 times + * Schedule.take(10), // Take at most 10 schedule outputs * Schedule.map((count) => Effect.succeed(`Sample #${count + 1}`)) * ) * * const samplingProgram = Effect.gen(function*() { * yield* Effect.repeat( * Effect.gen(function*() { - * const value = Math.random() - * yield* Console.log(`Sampled value: ${value.toFixed(3)}`) + * const value = "sample" + * yield* Console.log(`Sampled value: ${value}`) * return value * }), * samplingSchedule.pipe( @@ -5488,8 +5777,10 @@ export const tapOutput: { * }) * ``` * - * @since 2.0.0 - * @category utilities + * @see {@link recurs} for creating a count-limited schedule + * + * @category taking + * @since 4.0.0 */ export const take: { /** @@ -5497,21 +5788,32 @@ export const take: { * from the schedule. Once the specified number of outputs is reached, the * schedule will stop. * - * @example + * **When to use** + * + * Use to limit an existing schedule while preserving its output and delay behavior. + * + * **Gotchas** + * + * `take(n)` limits schedule outputs. When used with repeat or retry, the + * effect is evaluated once before the schedule is stepped, so the total number + * of evaluations can be one greater than the number of outputs taken. + * + * **Example** (Taking a limited number of recurrences) + * * ```ts * import { Console, Data, Effect, Schedule } from "effect" * * class RetryAttemptError extends Data.TaggedError("RetryAttemptError")<{ readonly message: string }> {} * - * // Limit an infinite schedule to run only 5 times + * // Limit an infinite schedule to five recurrences * const limitedHeartbeat = Schedule.spaced("1 second").pipe( - * Schedule.take(5) // Will stop after 5 executions + * Schedule.take(5) // Will stop after 5 schedule outputs * ) * * const heartbeatProgram = Effect.gen(function*() { * yield* Effect.repeat( * Effect.gen(function*() { - * yield* Console.log(`Heartbeat at ${new Date().toISOString()}`) + * yield* Console.log("Heartbeat") * return "pulse" * }), * limitedHeartbeat @@ -5551,15 +5853,15 @@ export const take: { * * // Combine take with other schedule operations * const samplingSchedule = Schedule.fixed("500 millis").pipe( - * Schedule.take(10), // Sample exactly 10 times + * Schedule.take(10), // Take at most 10 schedule outputs * Schedule.map((count) => Effect.succeed(`Sample #${count + 1}`)) * ) * * const samplingProgram = Effect.gen(function*() { * yield* Effect.repeat( * Effect.gen(function*() { - * const value = Math.random() - * yield* Console.log(`Sampled value: ${value.toFixed(3)}`) + * const value = "sample" + * yield* Console.log(`Sampled value: ${value}`) * return value * }), * samplingSchedule.pipe( @@ -5569,8 +5871,10 @@ export const take: { * }) * ``` * - * @since 2.0.0 - * @category utilities + * @see {@link recurs} for creating a count-limited schedule + * + * @category taking + * @since 4.0.0 */ (n: number): ( self: Schedule @@ -5580,21 +5884,32 @@ export const take: { * from the schedule. Once the specified number of outputs is reached, the * schedule will stop. * - * @example + * **When to use** + * + * Use to limit an existing schedule while preserving its output and delay behavior. + * + * **Gotchas** + * + * `take(n)` limits schedule outputs. When used with repeat or retry, the + * effect is evaluated once before the schedule is stepped, so the total number + * of evaluations can be one greater than the number of outputs taken. + * + * **Example** (Taking a limited number of recurrences) + * * ```ts * import { Console, Data, Effect, Schedule } from "effect" * * class RetryAttemptError extends Data.TaggedError("RetryAttemptError")<{ readonly message: string }> {} * - * // Limit an infinite schedule to run only 5 times + * // Limit an infinite schedule to five recurrences * const limitedHeartbeat = Schedule.spaced("1 second").pipe( - * Schedule.take(5) // Will stop after 5 executions + * Schedule.take(5) // Will stop after 5 schedule outputs * ) * * const heartbeatProgram = Effect.gen(function*() { * yield* Effect.repeat( * Effect.gen(function*() { - * yield* Console.log(`Heartbeat at ${new Date().toISOString()}`) + * yield* Console.log("Heartbeat") * return "pulse" * }), * limitedHeartbeat @@ -5634,15 +5949,15 @@ export const take: { * * // Combine take with other schedule operations * const samplingSchedule = Schedule.fixed("500 millis").pipe( - * Schedule.take(10), // Sample exactly 10 times + * Schedule.take(10), // Take at most 10 schedule outputs * Schedule.map((count) => Effect.succeed(`Sample #${count + 1}`)) * ) * * const samplingProgram = Effect.gen(function*() { * yield* Effect.repeat( * Effect.gen(function*() { - * const value = Math.random() - * yield* Console.log(`Sampled value: ${value.toFixed(3)}`) + * const value = "sample" + * yield* Console.log(`Sampled value: ${value}`) * return value * }), * samplingSchedule.pipe( @@ -5652,8 +5967,10 @@ export const take: { * }) * ``` * - * @since 2.0.0 - * @category utilities + * @see {@link recurs} for creating a count-limited schedule + * + * @category taking + * @since 4.0.0 */ (self: Schedule, n: number): Schedule } = dual(2, ( @@ -5665,7 +5982,8 @@ export const take: { * Creates a schedule that unfolds a state by repeatedly applying a function, * outputting the current state and computing the next state. * - * @example + * **Example** (Unfolding schedule state) + * * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -5713,15 +6031,14 @@ export const take: { * }) * ) * - * // Random jitter schedule - * const jitteredSchedule = Schedule.unfold( - * 1000, - * (baseDelay) => + * // Deterministic delay adjustment schedule + * const adjustedDelaySchedule = Schedule.unfold( + * { delay: 1000, adjustment: 100 }, + * ({ delay, adjustment }) => * Effect.gen(function*() { - * const jitter = Math.random() * 200 - 100 // ±100ms jitter - * const nextDelay = Math.max(100, baseDelay + jitter) - * yield* Console.log(`Jittered delay: ${nextDelay.toFixed(0)}ms`) - * return nextDelay + * const nextDelay = Math.max(100, delay + adjustment) + * yield* Console.log(`Adjusted delay: ${nextDelay}ms`) + * return { delay: nextDelay, adjustment: adjustment * -1 } * }) * ) * @@ -5754,8 +6071,8 @@ export const take: { * }) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const unfold = ( initial: State, @@ -5808,32 +6125,45 @@ const while_: { export { /** - * Returns a new schedule that passes each input and output of the specified - * schedule to the provided `predicate`. + * Returns a new schedule that continues while the predicate returns `true`. * - * If the `predicate` returns `true`, the schedule will continue, otherwise - * the schedule will stop. + * **When to use** * - * @since 2.0.0 - * @category utilities + * Use to stop an existing schedule based on its full metadata, such as the + * current input, output, attempt, delay, or elapsed time. + * + * **Details** + * + * The predicate receives `Metadata`, may return `boolean` or an + * `Effect`, preserves the output and delay when it returns + * `true`, and stops the schedule when it returns `false`. + * + * @see {@link collectWhile} for collecting outputs while using the same predicate + * @see {@link take} for stopping after a fixed number of schedule outputs + * + * @category filtering + * @since 4.0.0 */ while_ as while } /** - * A schedule that divides the timeline to `interval`-long windows, and sleeps + * Schedule that divides the timeline to `interval`-long windows, and sleeps * until the nearest window boundary every time it recurs. * + * **Details** + * * For example, `Schedule.windowed("10 seconds")` would produce a schedule as * follows: * - * ``` + * ```text * 10s 10s 10s 10s * |----------|----------|----------|----------| * |action------|sleep---|act|-sleep|action----| * ``` * - * @example + * **Example** (Repeating on aligned windows) + * * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -5843,8 +6173,7 @@ export { * const program = Effect.gen(function*() { * yield* Effect.repeat( * Effect.gen(function*() { - * const now = new Date().toISOString() - * yield* Console.log(`Window task executed at: ${now}`) + * yield* Console.log("Window task executed") * return "window-task" * }), * windowSchedule.pipe(Schedule.take(4)) @@ -5852,8 +6181,8 @@ export { * }) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const windowed = (interval: Duration.Input): Schedule => { const window = Duration.toMillis(Duration.fromInputUnsafe(interval)) @@ -5868,10 +6197,13 @@ export const windowed = (interval: Duration.Input): Schedule => { /** * Returns a new `Schedule` that will recur forever. * + * **Details** + * * The output of the schedule is the current count of its repetitions thus far * (i.e. `0, 1, 2, ...`). * - * @example + * **Example** (Repeating forever) + * * ```ts * import { Console, Effect, Schedule } from "effect" * @@ -5889,8 +6221,8 @@ export const windowed = (interval: Duration.Input): Schedule => { * }) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const forever: Schedule = spaced(Duration.zero) @@ -5904,42 +6236,53 @@ export { /** * Creates a schedule that always recurs, passing inputs directly as outputs. * + * **When to use** + * + * Use when you need an infinite schedule that preserves input values as + * outputs. + * * **Details** * * This schedule runs indefinitely, returning each input value as its output * without modification. It effectively acts as a pass-through that simply * echoes its input values at each step. * + * @see {@link forever} for an infinite schedule that returns incrementing step counts + * @category constructors * @since 2.0.0 - * @category Constructors */ identity_ as identity } /** - * Ensures that the provided schedule respects a specified input type. + * Ensures that a schedule's input type extends a given type `T`. + * + * **When to use** + * + * Use when you need a generic helper to prove that an existing schedule can + * consume a required input type without changing runtime behavior. + * + * **Example** (Constraining schedule input types) * - * @example * ```ts * import { Schedule } from "effect" * - * // Ensure schedule accepts string inputs - * const stringSchedule = Schedule.exponential("100 millis").pipe( - * Schedule.satisfiesInputType() - * ) + * declare const StringInputSchedule: Schedule.Schedule + * declare const NumberInputSchedule: Schedule.Schedule * - * // Ensure schedule accepts number inputs - * const numberSchedule = Schedule.spaced("1 second").pipe( - * Schedule.satisfiesInputType() - * ) + * const satisfiesStringInput = Schedule.satisfiesInputType() * - * // Type-level constraint - this would be a compile error: - * // Schedule.recurs(3).pipe(Schedule.satisfiesInputType()) - * // where CustomType doesn't match the schedule's input type + * // This works because the schedule input type is string. + * const validSchedule = satisfiesStringInput(StringInputSchedule) + * + * // This would cause a TypeScript compilation error: + * // const invalidSchedule = satisfiesStringInput(NumberInputSchedule) * ``` * - * @since 2.0.0 - * @category ensuring types + * @see {@link setInputType} for adapting an input-agnostic schedule + * + * @category utility types + * @since 4.0.0 */ export const satisfiesInputType = () => ( @@ -5947,34 +6290,62 @@ export const satisfiesInputType = () => ): Schedule => self /** - * Sets the input type of the provided schedule to a specified type, without - * altering the schedule's behavior. + * Sets the input type of the provided schedule without altering its behavior. * - * @since 2.0.0 - * @category ensuring types + * **When to use** + * + * Use to adapt a schedule that does not depend on its input values. + * + * **Details** + * + * This helper is checked at compile time and does not change the schedule's + * runtime behavior. + * + * **Example** (Setting a schedule input type) + * + * ```ts + * import { Schedule } from "effect" + * + * const schedule = Schedule.recurs(3).pipe( + * Schedule.setInputType() + * ) + * ``` + * + * @see {@link satisfiesInputType} for checking an existing input type + * + * @category utility types + * @since 4.0.0 */ export const setInputType = () => (self: Schedule): Schedule => self /** - * Ensures that the provided schedule respects a specified output type. + * Ensures that a schedule's output type extends a given type `T`. + * + * **Details** + * + * This helper is checked at compile time and does not change the schedule's + * runtime behavior. + * + * **Example** (Constraining schedule output types) * - * @example * ```ts - * import { Effect, Schedule } from "effect" + * import { Schedule } from "effect" * - * // satisfiesOutputType is a type-level function for compile-time constraints - * // It ensures that a schedule's output type matches the specified type + * declare const StringOutputSchedule: Schedule.Schedule + * declare const NumberOutputSchedule: Schedule.Schedule * - * // Example with string output - * const stringSchedule = Schedule.exponential("100 millis").pipe( - * Schedule.map(() => Effect.succeed("hello")), - * Schedule.satisfiesOutputType() - * ) + * const satisfiesStringOutput = Schedule.satisfiesOutputType() + * + * // This works because the schedule output type is string. + * const validSchedule = satisfiesStringOutput(StringOutputSchedule) + * + * // This would cause a TypeScript compilation error: + * // const invalidSchedule = satisfiesStringOutput(NumberOutputSchedule) * ``` * - * @since 2.0.0 - * @category ensuring types + * @category utility types + * @since 4.0.0 */ export const satisfiesOutputType = () => ( @@ -5982,9 +6353,15 @@ export const satisfiesOutputType = () => ): Schedule => self /** - * Ensures that the provided schedule respects a specified error type. + * Ensures that a schedule's error type extends a given type `T`. + * + * **Details** + * + * This helper is checked at compile time and does not change the schedule's + * runtime behavior. + * + * **Example** (Constraining schedule error types) * - * @example * ```ts * import { Data, Schedule } from "effect" * @@ -5993,19 +6370,20 @@ export const satisfiesOutputType = () => * message: string * }> {} * - * // Ensure schedule handles CustomError types - * const errorSchedule = Schedule.exponential("100 millis").pipe( - * Schedule.satisfiesErrorType() - * ) + * declare const CustomErrorSchedule: Schedule.Schedule + * declare const StringErrorSchedule: Schedule.Schedule * - * // Ensure schedule handles never errors (no errors) - * const safeSchedule = Schedule.spaced("1 second").pipe( - * Schedule.satisfiesErrorType() - * ) + * const satisfiesCustomError = Schedule.satisfiesErrorType() + * + * // This works because the schedule error type is CustomError. + * const validSchedule = satisfiesCustomError(CustomErrorSchedule) + * + * // This would cause a TypeScript compilation error: + * // const invalidSchedule = satisfiesCustomError(StringErrorSchedule) * ``` * - * @since 2.0.0 - * @category ensuring types + * @category utility types + * @since 4.0.0 */ export const satisfiesErrorType = () => ( @@ -6013,34 +6391,36 @@ export const satisfiesErrorType = () => ): Schedule => self /** - * Ensures that the provided schedule respects a specified context type. + * Ensures that a schedule's context type extends a given type `T`. + * + * **Details** + * + * This helper is checked at compile time and does not change the schedule's + * runtime behavior. + * + * **Example** (Constraining schedule service types) * - * @example * ```ts * import { Schedule } from "effect" * - * // Define service interfaces (type-level only) * interface Logger { * readonly log: (message: string) => void * } * - * interface Database { - * readonly query: (sql: string) => Promise - * } + * declare const LoggerSchedule: Schedule.Schedule + * declare const NumberSchedule: Schedule.Schedule * - * // Ensure schedule requires Logger service - * const loggerSchedule = Schedule.spaced("1 second").pipe( - * Schedule.satisfiesServicesType() - * ) + * const satisfiesLogger = Schedule.satisfiesServicesType() * - * // Ensure schedule requires both Logger and Database services - * const multiServiceSchedule = Schedule.exponential("100 millis").pipe( - * Schedule.satisfiesServicesType() - * ) + * // This works because the schedule context type is Logger. + * const validSchedule = satisfiesLogger(LoggerSchedule) + * + * // This would cause a TypeScript compilation error: + * // const invalidSchedule = satisfiesLogger(NumberSchedule) * ``` * - * @since 2.0.0 - * @category ensuring types + * @category utility types + * @since 4.0.0 */ export const satisfiesServicesType = () => ( diff --git a/.opencode/node_modules/effect/src/Scheduler.ts b/.opencode/node_modules/effect/src/Scheduler.ts index 1bff65d0ad1c0ca078df75544f6326ea2e308392..4e076de558b774af42f24a598d3082078c529bca 100644 --- a/.opencode/node_modules/effect/src/Scheduler.ts +++ b/.opencode/node_modules/effect/src/Scheduler.ts @@ -1,21 +1,33 @@ /** + * Controls how runnable Effect fiber tasks are dispatched. + * + * A scheduler decides how tasks are queued, when queued tasks run, and when a + * fiber should pause so other work can continue. This module includes the + * scheduler service reference, the default `MixedScheduler`, dispatcher types + * for queued tasks, and references for tuning or disabling automatic scheduler + * yields. + * * @since 2.0.0 */ import * as Context from "./Context.ts" import type * as Fiber from "./Fiber.ts" /** - * A scheduler manages the execution of Effects by controlling when and how tasks - * are scheduled and executed. It determines the execution mode (synchronous or - * asynchronous) and handles task prioritization and yielding behavior. + * A scheduler manages the execution of Effect fibers by controlling when queued + * tasks run. * - * The scheduler is responsible for: - * - Scheduling tasks with different priorities - * - Determining when fibers should yield control - * - Managing the execution flow of Effects + * **When to use** + * + * Use to define or provide custom runtime scheduling behavior for Effect fibers. + * + * **Details** + * + * A scheduler determines the execution mode, schedules tasks with different + * priorities, and decides when fibers should yield control after consuming + * their operation budget. * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface Scheduler { readonly executionMode: "sync" | "async" @@ -24,8 +36,23 @@ export interface Scheduler { } /** - * @since 4.0.0 + * A dispatcher created by a `Scheduler` for enqueuing tasks and forcing queued + * tasks to run. + * + * **When to use** + * + * Use when implementing or testing scheduler-created dispatchers that enqueue + * prioritized runtime tasks and flush queued work deterministically. + * + * **Details** + * + * `scheduleTask` queues a task with a priority. `flush` drains pending work + * synchronously, which is useful when callers need deterministic completion of + * already scheduled tasks. Lower priority numbers run first, and equal + * priorities run in FIFO order. + * * @category models + * @since 4.0.0 */ export interface SchedulerDispatcher { scheduleTask(task: () => void, priority: number): void @@ -33,8 +60,20 @@ export interface SchedulerDispatcher { } /** - * @since 4.0.0 + * Context reference for the scheduler used by the Effect runtime. + * + * **When to use** + * + * Use when you need to replace scheduling behavior globally in tests or runtime + * setup, such as forcing deterministic task dispatch. + * + * **Details** + * + * The default value creates a `MixedScheduler`. Provide this service to + * customize execution mode, task dispatching, or yield behavior. + * * @category references + * @since 2.0.0 */ export const Scheduler: Context.Reference = Context.Reference("effect/Scheduler", { defaultValue: () => new MixedScheduler() @@ -81,18 +120,23 @@ class PriorityBuckets { } /** - * A scheduler implementation that provides efficient task scheduling - * with support for both synchronous and asynchronous execution modes. + * Provides a scheduler implementation that batches queued tasks and dispatches them by + * priority. * - * Features: - * - Batches tasks for efficient execution - * - Supports priority-based task scheduling - * - Configurable execution mode (sync/async) - * - Automatic yielding based on operation count - * - Optimized for high-throughput scenarios + * **When to use** + * + * Use when you need the default runtime scheduler directly, including a + * scheduler that batches queued work by priority and preserves FIFO order within + * each priority. + * + * **Details** + * + * `MixedScheduler` supports synchronous and asynchronous execution modes, uses + * operation counts to decide when fibers should yield, and is the default + * scheduler implementation. * - * @since 2.0.0 * @category schedulers + * @since 2.0.0 */ export class MixedScheduler implements Scheduler { readonly executionMode: "sync" | "async" @@ -107,6 +151,13 @@ export class MixedScheduler implements Scheduler { } /** + * Returns whether the fiber has reached its operation budget and should yield. + * + * **When to use** + * + * Use to decide whether a fiber should yield after consuming its current + * operation budget. + * * @since 2.0.0 */ shouldYield(fiber: Fiber.Fiber) { @@ -114,7 +165,14 @@ export class MixedScheduler implements Scheduler { } /** - * @since 2.0.0 + * Creates a dispatcher that schedules work through this scheduler. + * + * **When to use** + * + * Use when you need a standalone dispatcher from a scheduler instance, for + * example in tests that enqueue tasks and then flush them deterministically. + * + * @since 4.0.0 */ makeDispatcher() { return new MixedSchedulerDispatcher(this.setImmediate) @@ -178,27 +236,49 @@ class MixedSchedulerDispatcher implements SchedulerDispatcher { } /** - * A service reference that controls the maximum number of operations a fiber - * can perform before yielding control back to the scheduler. This helps - * prevent long-running fibers from monopolizing the execution thread. + * Context reference that controls the maximum number of operations a fiber + * can perform before yielding control back to the scheduler. * - * The default value is 2048 operations, which provides a good balance between - * performance and fairness in concurrent execution. + * **When to use** + * + * Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler + * operation budget that triggers a yield. + * + * **Details** + * + * The default value is `2048` operations, which balances performance and + * fairness by helping prevent long-running fibers from monopolizing the + * execution thread. + * + * @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget * - * @since 4.0.0 * @category references + * @since 4.0.0 */ export const MaxOpsBeforeYield = Context.Reference("effect/Scheduler/MaxOpsBeforeYield", { defaultValue: () => 2048 }) /** - * A service reference that controls whether the runtime should bypass scheduler + * Context reference that controls whether the runtime should bypass scheduler * yield checks. When set to `true`, the fiber run loop won't call * `Scheduler.shouldYield`. * - * @since 4.0.0 + * **When to use** + * + * Use to bypass scheduler yield checks for controlled runtime workloads where + * cooperative yielding should be disabled. + * + * **Gotchas** + * + * Setting this reference to `true` can let long-running fibers monopolize the + * JavaScript thread. + * + * @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks + * @see {@link Scheduler} for providing custom scheduler yield behavior + * * @category references + * @since 4.0.0 */ export const PreventSchedulerYield = Context.Reference("effect/Scheduler/PreventSchedulerYield", { defaultValue: () => false diff --git a/.opencode/node_modules/effect/src/Schema.ts b/.opencode/node_modules/effect/src/Schema.ts index 2732d677500d186c1016ef7db8c210707435a2cf..6cc9726ae81d87ebdbf83f5095b07738f6b6185a 100644 --- a/.opencode/node_modules/effect/src/Schema.ts +++ b/.opencode/node_modules/effect/src/Schema.ts @@ -1,85 +1,13 @@ /** - * Define data shapes, validate unknown input, and transform values between formats. - * - * ## Mental model - * - * - **Schema** — a description of a data shape. Every schema carries a decoded - * *Type* (the value you work with) and an *Encoded* representation (the - * serialized form, e.g. JSON). - * - **Decoding** — turning unknown external data (API responses, form - * submissions, config files) into typed, validated values. - * - **Encoding** — turning typed values back into a serializable format. - * - **Codec** — a schema that tracks both Type and Encoded, so it can decode - * *and* encode. Most concrete schemas are Codecs. - * - **Check / Filter** — a constraint attached to a schema (e.g. `isMinLength`, - * `isGreaterThan`). Attach them with `.check(...)`. - * - **Transformation** — a pair of functions (decode + encode) that convert - * values between two schemas. Created with {@link decodeTo} / {@link encodeTo}. - * - **Annotation** — metadata attached to a schema (title, description, custom - * keys). Attach with `.annotate(...)`. - * - * ## Common tasks - * - * - Define a struct: {@link Struct} - * - Define a union: {@link Union}, {@link TaggedUnion}, {@link Literals} - * - Define an array: {@link ArraySchema}, {@link NonEmptyArray} - * - Define a record: {@link Record} - * - Define a tuple: {@link Tuple}, {@link TupleWithRest} - * - Validate unknown data synchronously: {@link decodeUnknownSync} - * - Validate unknown data (Effect): {@link decodeUnknownEffect} - * - Encode a value: {@link encodeUnknownSync}, {@link encodeUnknownEffect} - * - Type guard: {@link is} - * - Assertion: {@link asserts} - * - Add constraints: `.check(...)` with filters like {@link isMinLength}, - * {@link isGreaterThan}, {@link isPattern}, {@link isUUID} - * - Transform between schemas: {@link decodeTo}, {@link encodeTo} - * - Add a default for missing keys: {@link withDecodingDefault}, {@link withDecodingDefaultKey} - * - Create branded types: {@link brand} - * - Define classes with validation: {@link Class}, {@link TaggedClass} - * - Define error classes: {@link ErrorClass}, {@link TaggedErrorClass} - * - Generate JSON Schema: {@link toJsonSchemaDocument} - * - Generate test data: {@link toArbitrary} - * - Derive equivalence: {@link toEquivalence} - * - * ## Gotchas - * - * - `Schema.optional` creates `T | undefined` (key can be missing *or* - * `undefined`). Use `Schema.optionalKey` for exact optional properties. - * - `decodeTo` is curried: use `from.pipe(Schema.decodeTo(to, ...))`. - * - `decodeUnknownSync` throws on failure. Use `decodeUnknownExit` or - * `decodeUnknownOption` for non-throwing alternatives. - * - Filters do not change the TypeScript type. Use {@link refine} or - * {@link brand} to narrow the type. - * - Recursive schemas require {@link suspend} to avoid infinite loops. - * - * ## Quickstart - * - * **Example** (Validate a user object) + * Describes data shapes and how unknown input becomes trusted values. * - * ```ts - * import { Schema } from "effect" - * - * const User = Schema.Struct({ - * name: Schema.String.check(Schema.isMinLength(1)), - * age: Schema.Number.check(Schema.isGreaterThanOrEqualTo(0)), - * email: Schema.optionalKey(Schema.String) - * }) - * - * // Decode unknown input — throws on failure - * const user = Schema.decodeUnknownSync(User)({ - * name: "Alice", - * age: 30 - * }) - * - * console.log(user) - * // { name: "Alice", age: 30 } - * ``` - * - * @see {@link Schema} — type-level view tracking only the decoded Type - * @see {@link Codec} — type-level view tracking both Type and Encoded - * @see {@link Struct} — define object shapes - * @see {@link decodeUnknownSync} — synchronous validation - * @see {@link decodeTo} — schema transformations + * A schema can validate input, decode it into an application type, and encode + * that value back to another representation. This module contains the main + * schema, codec, decoder, and encoder APIs, together with schemas for common + * JavaScript values and Effect data types. It also supports refinements, + * transformations, defaults, classes, JSON Schema generation, test data + * generation, formatting, equivalence, optics, and differs derived from schema + * definitions. * * @since 4.0.0 */ @@ -125,12 +53,12 @@ import * as Record_ from "./Record.ts" import * as Redacted_ from "./Redacted.ts" import * as Result_ from "./Result.ts" import * as Scheduler from "./Scheduler.ts" -import * as AST from "./SchemaAST.ts" -import * as Getter from "./SchemaGetter.ts" -import * as Issue from "./SchemaIssue.ts" -import * as Parser from "./SchemaParser.ts" +import * as SchemaAST from "./SchemaAST.ts" +import * as SchemaGetter from "./SchemaGetter.ts" +import * as SchemaIssue from "./SchemaIssue.ts" +import * as SchemaParser from "./SchemaParser.ts" import type * as SchemaRepresentation from "./SchemaRepresentation.ts" -import * as Transformation from "./SchemaTransformation.ts" +import * as SchemaTransformation from "./SchemaTransformation.ts" import type { Assign, Lambda, Mutable, Simplify } from "./Struct.ts" import * as Struct_ from "./Struct.ts" import * as FastCheck from "./testing/FastCheck.ts" @@ -145,6 +73,7 @@ const TypeId = InternalSchema.TypeId * @see {@link optionalKey} — mark a struct field as optional * @see {@link optional} — mark a struct field as optional with `| undefined` * + * @category models * @since 4.0.0 */ export type Optionality = "required" | "optional" @@ -154,6 +83,7 @@ export type Optionality = "required" | "optional" * * @see {@link mutableKey} — mark a struct field as mutable * + * @category models * @since 4.0.0 */ export type Mutability = "readonly" | "mutable" @@ -164,6 +94,7 @@ export type Mutability = "readonly" | "mutable" * @see {@link withConstructorDefault} — add a default to a schema field * @see {@link tag} — creates a literal field with a constructor default * + * @category models * @since 4.0.0 */ export type ConstructorDefault = "no-default" | "with-default" @@ -171,20 +102,22 @@ export type ConstructorDefault = "no-default" | "with-default" /** * Options for `makeEffect`, `make`, and Class constructors. * - * When to use: - * - Pass `disableChecks: true` to skip validation when you trust the data. + * **When to use** + * + * Use when passing `disableChecks: true` to skip validation when you trust the data. * - Pass `parseOptions` to control error reporting behavior. * * @see {@link Bottom.makeEffect} * @see {@link Bottom.make} * - * @since 4.0.0 + * @category options + * @since 3.13.4 */ export interface MakeOptions { /** * The parse options to use for the schema. */ - readonly parseOptions?: AST.ParseOptions | undefined + readonly parseOptions?: SchemaAST.ParseOptions | undefined /** * Whether to disable validation for the schema. */ @@ -196,8 +129,9 @@ export interface MakeOptions { * parameters controlling type inference, mutability, optionality, services, * and transformation behavior. * - * When to use: - * - You are writing advanced generic schema utilities or performing schema + * **When to use** + * + * Use when you are writing advanced generic schema utilities or performing schema * introspection. * - In user code, prefer {@link Schema}, {@link Codec}, {@link Decoder}, or * {@link Encoder} instead. @@ -206,6 +140,7 @@ export interface MakeOptions { * @see {@link Schema} — tracks only the decoded Type * @see {@link Codec} — tracks Type + Encoded * + * @category models * @since 4.0.0 */ export interface Bottom< @@ -213,7 +148,7 @@ export interface Bottom< out E, out RD, out RE, - out Ast extends AST.AST, + out Ast extends SchemaAST.AST, out Rebuild extends Top, out TypeMakeIn = T, out Iso = T, @@ -248,22 +183,67 @@ export interface Bottom< annotate(annotations: Annotations.Bottom): this["Rebuild"] annotateKey(annotations: Annotations.Key): this["Rebuild"] - check(...checks: readonly [AST.Check, ...Array>]): this["Rebuild"] + check(...checks: readonly [SchemaAST.Check, ...Array>]): this["Rebuild"] rebuild(ast: this["ast"]): this["Rebuild"] /** - * @throws {Error} The issue is contained in the error cause. + * Constructs a value from the make input representation synchronously. + * + * **When to use** + * + * Use when constructor input is trusted or when validation failure + * should abort with a thrown `Error`. + * + * **Details** + * + * Applies constructor defaults and type-side validation according to + * `MakeOptions`. + * + * **Gotchas** + * + * Throws an `Error` with the schema issue in its `cause` when validation + * fails. + * + * @see {@link Bottom.makeOption} — construct synchronously and discard validation details + * @see {@link Bottom.makeEffect} — construct through `Effect` when validation failure should stay in the error channel */ make(input: this["~type.make.in"], options?: MakeOptions): this["Type"] + /** + * Constructs a value from the make input representation, returning `Option.none` + * when validation fails. + * + * **When to use** + * + * Use when you only need to know whether construction succeeds + * and do not need validation details. + * + * **Details** + * + * Applies constructor defaults and type-side validation according to + * `MakeOptions`. + * + * @see {@link Bottom.make} — construct synchronously when validation failure should throw + * @see {@link Bottom.makeEffect} — construct through `Effect` when validation details should stay in the error channel + */ makeOption(input: this["~type.make.in"], options?: MakeOptions): Option_.Option + /** + * Constructs a value from the make input representation, returning validation + * failures in the `Effect` error channel. + * + * **When to use** + * + * Use when constructor input may fail validation and you want to + * compose that failure with other `Effect` operations instead of throwing. + * + * @see {@link Bottom.make} — construct synchronously when validation failure should throw + * @see {@link Bottom.makeOption} — construct synchronously and discard validation details + */ makeEffect(input: this["~type.make.in"], options?: MakeOptions): Effect.Effect } /** - * The schema type returned by {@link declareConstructor}, tracking the decoded - * type `T`, the encoded type `E`, and the list of type-parameter schemas - * `TypeParameters`. + * Type-level representation returned by {@link declareConstructor}. * - * @category Constructors + * @category constructors * @since 4.0.0 */ export interface declareConstructor, Iso = T> extends @@ -272,7 +252,7 @@ export interface declareConstructor, T, Iso, @@ -285,6 +265,13 @@ export interface declareConstructor`, `Option`, etc.) by accepting a list of type-parameter schemas * and a decoder factory. * + * **When to use** + * + * Use when you are defining a schema for a generic container whose validation + * depends on one or more type-parameter schemas. + * + * **Details** + * * The outer call `declareConstructor()` fixes the decoded type `T`, * the encoded type `E`, and the optional iso type. The inner call receives: * - `typeParameters` — the concrete schemas for each type variable @@ -297,10 +284,7 @@ export interface declareConstructor` type) * * ```ts - * import { Effect, Schema } from "effect" - * import * as SchemaParser from "effect/SchemaParser" - * import * as Issue from "effect/SchemaIssue" - * import * as Option from "effect/Option" + * import { Effect, Option, Schema, SchemaIssue as Issue, SchemaParser } from "effect" * * interface Box { * readonly value: A @@ -315,7 +299,7 @@ export interface declareConstructor * (u, ast, options) => { * if (!isBox(u)) { - * return Effect.fail(new Issue.InvalidType(ast, Option.some(u))) + * return Effect.fail(new SchemaIssue.InvalidType(ast, Option.some(u))) * } * return Effect.map( * SchemaParser.decodeUnknownEffect(itemCodec)(u.value, options), @@ -327,7 +311,7 @@ export interface declareConstructor() { @@ -337,12 +321,16 @@ export function declareConstructor() { typeParameters: { readonly [K in keyof TypeParameters]: Codec } - ) => (u: unknown, self: AST.Declaration, options: AST.ParseOptions) => Effect.Effect, + ) => ( + u: unknown, + self: SchemaAST.Declaration, + options: SchemaAST.ParseOptions + ) => Effect.Effect, annotations?: Annotations.Declaration ): declareConstructor => { return make( - new AST.Declaration( - typeParameters.map(AST.getAST), + new SchemaAST.Declaration( + typeParameters.map(SchemaAST.getAST), (typeParameters) => run(typeParameters.map((ast) => make(ast)) as any), annotations ) @@ -351,11 +339,10 @@ export function declareConstructor() { } /** - * The schema type returned by {@link declare}, representing a non-parametric - * opaque type `T` with no type parameters. + * Type-level representation returned by {@link declare}. * - * @category Constructors - * @since 4.0.0 + * @category constructors + * @since 3.13.3 */ export interface declare extends declareConstructor { readonly "Rebuild": declare @@ -366,8 +353,10 @@ export interface declare extends declareConstructor` or `Array`, use {@link declareConstructor} instead. + * **When to use** + * + * Use when you are defining a schema for an opaque type with no type parameters + * and validation can be expressed as a type guard. * * **Example** (Schema for a custom `UserId` branded type) * @@ -387,8 +376,8 @@ export interface declare extends declareConstructor( is: (u: unknown) => u is T, @@ -399,15 +388,17 @@ export function declare( () => (input, ast) => is(input) ? Effect.succeed(input) : - Effect.fail(new Issue.InvalidType(ast, Option_.some(input))), + Effect.fail(new SchemaIssue.InvalidType(ast, Option_.some(input))), annotations ) } /** - * Widens a schema's type to the fully-parameterized {@link Bottom} interface, + * Returns a schema widened to the fully-parameterized {@link Bottom} interface, * making all 14 type parameters visible to TypeScript. * + * **Details** + * * Normally, concrete schema interfaces (e.g. `Schema`) hide most type * parameters. `revealBottom` is useful when writing generic utilities that need * to inspect or propagate the complete set of type parameters. @@ -428,6 +419,7 @@ export function declare( * type E = typeof bottom["Encoded"] // string * ``` * + * @category utility types * @since 4.0.0 */ export function revealBottom( @@ -456,6 +448,8 @@ export function revealBottom( * Adds metadata annotations to a schema without changing its runtime behavior. * This is the pipeable (curried) counterpart of the `.annotate` method. * + * **Details** + * * Annotations provide extra context used by documentation generators, JSON * Schema converters, error formatters, and other tooling. Common keys include * `title`, `description`, `examples`, `message`, and `identifier`. @@ -475,7 +469,7 @@ export function revealBottom( * * @see {@link annotateEncoded} to annotate the encoded side instead. * - * @category Annotations + * @category annotations * @since 4.0.0 */ export function annotate(annotations: Annotations.Bottom) { @@ -487,6 +481,8 @@ export function annotate(annotations: Annotations.Bottom(annotations: Annotations.Bottom(annotations: Annotations.Bottom) { @@ -518,6 +514,8 @@ export function annotateEncoded(annotations: Annotations.Bottom(annotations: Annotations.Bottom(annotations: Annotations.Key) { return (self: S): S["Rebuild"] => { - return self.rebuild(AST.annotateKey(self.ast, annotations)) + return self.rebuild(SchemaAST.annotateKey(self.ast, annotations)) } } /** * The existential "any schema" type — all type parameters are erased to `unknown`. * + * **Details** + * * Use `Top` as a constraint when writing generic utilities that must accept *any* * schema regardless of its `Type`, `Encoded`, or service requirements. It is the * widest possible schema type and therefore gives you the least static information. @@ -561,6 +561,7 @@ export function annotateKey(annotations: Annotations.Key` — for decode-only APIs * - {@link Encoder}`` — for encode-only APIs * + * @category models * @since 4.0.0 */ export interface Top extends @@ -569,7 +570,7 @@ export interface Top extends unknown, unknown, unknown, - AST.AST, + SchemaAST.AST, Top, unknown, unknown, @@ -586,7 +587,7 @@ export interface Top extends /** * Namespace of type-level helpers for {@link Schema}. * - * @since 4.0.0 + * @since 3.10.0 */ export declare namespace Schema { /** @@ -602,7 +603,8 @@ export declare namespace Schema { * // { readonly name: string; readonly age: number } * ``` * - * @since 4.0.0 + * @category utility types + * @since 3.10.0 */ export type Type = S extends Top ? S["Type"] : never } @@ -610,6 +612,8 @@ export declare namespace Schema { /** * A typed view of a schema that tracks only the decoded (output) type `T`. * + * **Details** + * * Use `Schema` as a constraint when you want to accept "any schema that * decodes to `T`" and do not need to know or constrain the encoded * representation, required services, or any other type parameters. @@ -632,7 +636,8 @@ export declare namespace Schema { * @see {@link Codec} — also tracks Encoded, DecodingServices, EncodingServices * @see {@link Schema.Type} — extract the decoded type at the type level * - * @since 4.0.0 + * @category models + * @since 3.10.0 */ export interface Schema extends Top { readonly "Type": T @@ -658,7 +663,8 @@ export declare namespace Codec { * // string * ``` * - * @since 4.0.0 + * @category utility types + * @since 3.10.0 */ export type Encoded = S extends Top ? S["Encoded"] : never /** @@ -674,6 +680,7 @@ export declare namespace Codec { * // never * ``` * + * @category utility types * @since 4.0.0 */ export type DecodingServices = S extends Top ? S["DecodingServices"] : never @@ -690,24 +697,17 @@ export declare namespace Codec { * // never * ``` * + * @category utility types * @since 4.0.0 */ export type EncodingServices = S extends Top ? S["EncodingServices"] : never - /** - * Converts a schema type into an assertion function signature. The resulting - * function narrows its argument to `I & S["Type"]`. Only schemas with - * `DecodingServices: never` (i.e. no required services) can be used here. - * - * Produced by {@link asserts}. - * - * @since 4.0.0 - */ - export type ToAsserts = (input: I) => asserts input is I & S["Type"] } /** * A schema that additionally supports optic (lens/prism) operations. * + * **Details** + * * `Optic` extends {@link Schema}`` with an `Iso` type that * describes the isomorphic counterpart used by the optic layer. Crucially, * decoding and encoding require *no* Effect services (`DecodingServices` and @@ -718,6 +718,7 @@ export declare namespace Codec { * `Optic` automatically. You normally interact with this interface through * {@link Optic_} utilities rather than constructing it directly. * + * @category models * @since 4.0.0 */ export interface Optic extends Schema { @@ -731,6 +732,8 @@ export interface Optic extends Schema { * A schema that tracks the decoded type `T`, the encoded type `E`, and the * Effect services required during decoding (`RD`) and encoding (`RE`). * + * **Details** + * * Use `Codec` when you need to preserve full type information * about a schema — both what it decodes to and what it serializes from/to. * Most concrete schemas produced by this module implement `Codec`. @@ -755,6 +758,7 @@ export interface Optic extends Schema { * @see {@link Codec.EncodingServices} — extract required encoding services * @see {@link revealCodec} — helper to make TypeScript infer the full Codec type * + * @category models * @since 4.0.0 */ export interface Codec extends Schema { @@ -767,6 +771,8 @@ export interface Codec extends /** * A {@link Codec} view for APIs that only *decode* (parse/validate) values. * + * **Details** + * * Use `Decoder` to accept "any schema that can decode to `T`" without * constraining or depending on the encoded representation (`Encoded` is * `unknown`) or encoding services. @@ -782,6 +788,7 @@ export interface Codec extends * validate(Schema.NumberFromString) // ok * ``` * + * @category models * @since 4.0.0 */ export interface Decoder extends Codec { @@ -791,6 +798,8 @@ export interface Decoder extends Codec` to accept "any schema that can encode to `E`" without * constraining or depending on the decoded `Type` (`Type` is `unknown`) or * decoding services. @@ -806,6 +815,7 @@ export interface Decoder extends Codec extends Codec { @@ -813,8 +823,10 @@ export interface Encoder extends Codec` or `Top`, the * encoded type and service requirements are erased. Passing the value through @@ -832,6 +844,7 @@ export interface Encoder extends Codec(codec: Codec) { @@ -843,7 +856,9 @@ export { * Error thrown (or returned as the error channel value) when schema decoding * or encoding fails. * - * The `issue` field contains a structured {@link Issue.Issue} tree describing + * **Details** + * + * The `issue` field contains a structured {@link SchemaIssue.Issue} tree describing * every validation failure, including the path to the problematic value, * expected types, and actual values received. `message` renders the issue tree * as a human-readable string. @@ -865,6 +880,7 @@ export { * } * ``` * + * @category errors * @since 4.0.0 */ SchemaError @@ -887,6 +903,7 @@ export { * } * ``` * + * @category guards * @since 4.0.0 */ export function isSchemaError(u: unknown): u is SchemaError { @@ -903,6 +920,8 @@ function makeStandardResult(exit: Exit_.Exit>): St * Returns a "Standard Schema" object conforming to the [Standard Schema * v1](https://standardschema.dev/) specification. * + * **Details** + * * This function creates a schema whose `validate` method attempts to decode and * validate the provided input synchronously. If the underlying `Schema` * includes any asynchronous components (e.g., asynchronous message resolutions @@ -963,17 +982,17 @@ function makeStandardResult(exit: Exit_.Exit>): St export function toStandardSchemaV1>( self: S, options?: { - readonly leafHook?: Issue.LeafHook | undefined - readonly checkHook?: Issue.CheckHook | undefined - readonly parseOptions?: AST.ParseOptions | undefined + readonly leafHook?: SchemaIssue.LeafHook | undefined + readonly checkHook?: SchemaIssue.CheckHook | undefined + readonly parseOptions?: SchemaAST.ParseOptions | undefined } ): StandardSchemaV1 & S { - const decodeUnknownEffect = Parser.decodeUnknownEffect(self) as ( + const decodeUnknownEffect = SchemaParser.decodeUnknownEffect(self) as ( input: unknown, - options?: AST.ParseOptions - ) => Effect.Effect - const parseOptions: AST.ParseOptions = { errors: "all", ...options?.parseOptions } - const formatter = Issue.makeFormatterStandardSchemaV1(options) + options?: SchemaAST.ParseOptions + ) => Effect.Effect + const parseOptions: SchemaAST.ParseOptions = { errors: "all", ...options?.parseOptions } + const formatter = SchemaIssue.makeFormatterStandardSchemaV1(options) const validate: StandardSchemaV1["~standard"]["validate"] = (value: unknown) => { const scheduler = new Scheduler.MixedScheduler() const fiber = Effect.runFork( @@ -1030,13 +1049,14 @@ function toBaseStandardJSONSchemaV1(self: Top, target: StandardJSONSchemaV1.Targ } /** - * Experimental support for converting a schema to a Standard JSON Schema V1. + * Converts a schema to an experimental Standard JSON Schema V1 representation. + * + * **Details** * * https://github.com/standard-schema/standard-schema/pull/134 * * @category Standard Schema * @since 4.0.0 - * @experimental */ export function toStandardJSONSchemaV1(self: S): StandardJSONSchemaV1 & S { const jsonSchema: StandardJSONSchemaV1.Props["jsonSchema"] = { @@ -1067,6 +1087,8 @@ export function toStandardJSONSchemaV1(self: S): StandardJSONSche * Creates a type guard function that checks if a value conforms to a given * schema. * + * **Details** + * * This function returns a predicate that performs a type-safe check, narrowing * the type of the input value if the check passes. It's particularly useful for * runtime type validation and TypeScript type narrowing. @@ -1089,61 +1111,77 @@ export function toStandardJSONSchemaV1(self: S): StandardJSONSche * } * ``` * - * @category Asserting - * @since 4.0.0 + * @category guards + * @since 3.10.0 */ -export const is = Parser.is +export const is = SchemaParser.is /** * Creates an assertion function that throws an error if the input doesn't match * the schema. * - * This function is useful for runtime type checking with TypeScript's `asserts` - * type guard. It narrows the type of the input if the assertion succeeds, or - * throws an error if it fails. + * **When to use** + * + * Use to validate unknown input at runtime while narrowing the value with a + * TypeScript assertion signature. + * + * **Details** + * + * The input is narrowed if the assertion succeeds. If validation fails, the + * assertion throws. * * **Example** (Basic Usage) * * ```ts * import { Schema } from "effect" * - * const assertString: (u: unknown) => asserts u is string = Schema.asserts( - * Schema.String - * ) + * const input: unknown = "hello" * - * // This will pass silently (no return value) - * try { - * assertString("hello") - * console.log("String assertion passed") - * } catch (error) { - * console.log("String assertion failed") - * } + * // This will pass silently (no return value) and narrow input to string + * Schema.asserts(Schema.String, input) + * console.log(input.toUpperCase()) * * // This will throw an error * try { - * assertString(123) + * const invalid: unknown = 123 + * Schema.asserts(Schema.String, invalid) * } catch (error) { * console.log("Non-string assertion failed as expected") * } * ``` * - * @category Asserting + * @category guards * @since 4.0.0 */ -export const asserts = Parser.asserts +export const asserts: (schema: S, input: I) => asserts input is I & S["Type"] = SchemaParser.asserts /** * Decodes an `unknown` input against a schema, returning an `Effect` that - * succeeds with the decoded value or fails with a {@link SchemaError}. Use this - * when the input type is not statically known. Prefer {@link decodeEffect} when - * the input is already typed as the schema's `Encoded` type. + * succeeds with the decoded value or fails with a {@link SchemaError}. + * + * **When to use** + * + * Use when you need to decode unknown input in an `Effect` whose failure + * channel is `SchemaError`. * - * @category Decoding + * **Details** + * + * Prefer {@link decodeEffect} when the input is already typed as the schema's + * `Encoded` type. + * Options may be provided either when creating the decoder or when applying it; + * application options override creation options. + * + * @see {@link SchemaParser.decodeUnknownEffect} for the adapter that fails with `SchemaIssue.Issue` directly + * + * @category decoding * @since 4.0.0 */ -export function decodeUnknownEffect(schema: S) { - const parser = Parser.decodeUnknownEffect(schema) - return (input: unknown, options?: AST.ParseOptions): Effect.Effect => { +export function decodeUnknownEffect(schema: S, options?: SchemaAST.ParseOptions) { + const parser = SchemaParser.decodeUnknownEffect(schema, options) + return ( + input: unknown, + options?: SchemaAST.ParseOptions + ): Effect.Effect => { return Effect.mapErrorEager(parser(input, options), (issue) => new SchemaError(issue)) } } @@ -1151,30 +1189,58 @@ export function decodeUnknownEffect(schema: S) { /** * Decodes a typed input (the schema's `Encoded` type) against a schema, * returning an `Effect` that succeeds with the decoded value or fails with a - * {@link SchemaError}. Use this when the input is already typed; for `unknown` - * input use {@link decodeUnknownEffect}. + * {@link SchemaError}. + * + * **When to use** * - * @category Decoding + * Use when you need to decode input already typed as the schema's `Encoded` + * type in an `Effect` whose failure channel is `SchemaError`. + * + * **Details** + * + * For `unknown` input use {@link decodeUnknownEffect}. + * Options may be provided either when creating the decoder or when applying it; + * application options override creation options. + * + * @see {@link SchemaParser.decodeEffect} for the adapter that fails with `SchemaIssue.Issue` directly + * + * @category decoding * @since 4.0.0 */ export const decodeEffect: ( - schema: S -) => (input: S["Encoded"], options?: AST.ParseOptions) => Effect.Effect = - decodeUnknownEffect + schema: S, + options?: SchemaAST.ParseOptions +) => ( + input: S["Encoded"], + options?: SchemaAST.ParseOptions +) => Effect.Effect = decodeUnknownEffect /** * Decodes an `unknown` input against a schema synchronously, returning an * `Exit` that is either a `Success` with the decoded value or a `Failure` with - * a {@link SchemaError}. Only usable with schemas that have no - * `DecodingServices` requirement. Prefer {@link decodeExit} when the input is - * already typed as the schema's `Encoded` type. + * a {@link SchemaError}. + * + * **When to use** + * + * Use when you need to decode unknown input into an `Exit` whose failure + * contains `SchemaError`. + * + * **Details** + * + * Only usable with schemas that have no `DecodingServices` requirement. Prefer + * {@link decodeExit} when the input is already typed as the schema's `Encoded` + * type. + * Options may be provided either when creating the decoder or when applying it; + * application options override creation options. + * + * @see {@link SchemaParser.decodeUnknownExit} for the adapter whose failure contains `SchemaIssue.Issue` directly * - * @category Decoding + * @category decoding * @since 4.0.0 */ -export function decodeUnknownExit>(schema: S) { - const parser = Parser.decodeUnknownExit(schema) - return (input: unknown, options?: AST.ParseOptions): Exit_.Exit => { +export function decodeUnknownExit>(schema: S, options?: SchemaAST.ParseOptions) { + const parser = SchemaParser.decodeUnknownExit(schema, options) + return (input: unknown, options?: SchemaAST.ParseOptions): Exit_.Exit => { return Exit_.mapError(parser(input, options), (issue) => new SchemaError(issue)) } } @@ -1182,79 +1248,205 @@ export function decodeUnknownExit>(schema: S) { /** * Decodes a typed input (the schema's `Encoded` type) against a schema * synchronously, returning an `Exit` that is either a `Success` with the - * decoded value or a `Failure` with a {@link SchemaError}. Only usable with - * schemas that have no `DecodingServices` requirement. For `unknown` input use - * {@link decodeUnknownExit}. + * decoded value or a `Failure` with a {@link SchemaError}. * - * @category Decoding + * **When to use** + * + * Use when you need to decode already typed `Encoded` input into an `Exit` + * whose failure contains `SchemaError`. + * + * **Details** + * + * Only usable with schemas that have no `DecodingServices` requirement. For + * `unknown` input use {@link decodeUnknownExit}. + * Options may be provided either when creating the decoder or when applying it; + * application options override creation options. + * + * @see {@link SchemaParser.decodeExit} for the adapter whose failure contains `SchemaIssue.Issue` directly + * + * @category decoding * @since 4.0.0 */ export const decodeExit: >( - schema: S -) => (input: S["Encoded"], options?: AST.ParseOptions) => Exit_.Exit = decodeUnknownExit + schema: S, + options?: SchemaAST.ParseOptions +) => (input: S["Encoded"], options?: SchemaAST.ParseOptions) => Exit_.Exit = decodeUnknownExit /** * Decodes an `unknown` input against a schema, returning an `Option` that is - * `Some` with the decoded value on success or `None` on failure. Prefer this - * over {@link decodeUnknownExit} or {@link decodeUnknownEffect} when you only - * need to know whether decoding succeeded and don't need error details. For - * typed input use {@link decodeOption}. + * `Some` with the decoded value on success or `None` on failure. * - * @category Decoding - * @since 4.0.0 + * **When to use** + * + * Use when you do not know the input type statically and only need to know + * whether decoding succeeded. + * + * **Details** + * + * Prefer this over {@link decodeUnknownExit} or {@link decodeUnknownEffect} + * when you don't need error details. For input already typed as the schema's + * `Encoded` type use {@link decodeOption}. + * Options may be provided either when creating the decoder or when applying it; + * application options override creation options. + * + * @category decoding + * @since 3.10.0 */ -export const decodeUnknownOption = Parser.decodeUnknownOption +export const decodeUnknownOption: >( + schema: S, + options?: SchemaAST.ParseOptions +) => (input: unknown, options?: SchemaAST.ParseOptions) => Option_.Option = SchemaParser.decodeUnknownOption /** * Decodes a typed input (the schema's `Encoded` type) against a schema, * returning an `Option` that is `Some` with the decoded value on success or - * `None` on failure. For `unknown` input use {@link decodeUnknownOption}. + * `None` on failure. * - * @category Decoding - * @since 4.0.0 + * **When to use** + * + * Use when you already have input typed as the schema's `Encoded` type and + * only need to know whether decoding succeeded. + * + * **Details** + * + * For `unknown` input use {@link decodeUnknownOption}. + * Options may be provided either when creating the decoder or when applying it; + * application options override creation options. + * + * @category decoding + * @since 3.10.0 */ -export const decodeOption = Parser.decodeOption +export const decodeOption: >( + schema: S, + options?: SchemaAST.ParseOptions +) => (input: S["Encoded"], options?: SchemaAST.ParseOptions) => Option_.Option = decodeUnknownOption /** - * Decodes an `unknown` input against a schema, returning a `Promise` that - * resolves with the decoded value or rejects with a {@link SchemaError}. Useful - * for integrating with Promise-based APIs. For typed input use - * {@link decodePromise}. + * Decodes an `unknown` input against a schema, returning a `Result` that + * succeeds with the decoded value or fails with a {@link SchemaError}. + * + * **When to use** + * + * Use when you do not know the input type statically and want decoding to + * return a `Result` with `SchemaError` failure data. * - * @category Decoding + * **Details** + * + * For input already typed as the schema's `Encoded` type use + * {@link decodeResult}. + * Options may be provided either when creating the decoder or when applying it; + * application options override creation options. + * + * @see {@link SchemaParser.decodeUnknownResult} for the adapter that fails with `SchemaIssue.Issue` directly + * + * @category decoding * @since 4.0.0 */ -export const decodeUnknownResult = Parser.decodeUnknownResult +export function decodeUnknownResult>(schema: S, options?: SchemaAST.ParseOptions) { + const parser = SchemaParser.decodeUnknownResult(schema, options) + return (input: unknown, options?: SchemaAST.ParseOptions): Result_.Result => { + return Result_.mapError(parser(input, options), (issue) => new SchemaError(issue)) + } +} /** - * @category Decoding + * Decodes a typed input (the schema's `Encoded` type) against a schema, + * returning a `Result` that succeeds with the decoded value or fails with a + * {@link SchemaError}. + * + * **When to use** + * + * Use when you already have input typed as the schema's `Encoded` type and + * want decoding to return a `Result` with `SchemaError` failure data. + * + * **Details** + * + * For `unknown` input use {@link decodeUnknownResult}. + * Options may be provided either when creating the decoder or when applying it; + * application options override creation options. + * + * @see {@link SchemaParser.decodeResult} for the adapter that fails with `SchemaIssue.Issue` directly + * + * @category decoding * @since 4.0.0 */ -export const decodeResult = Parser.decodeResult +export const decodeResult: >( + schema: S, + options?: SchemaAST.ParseOptions +) => (input: S["Encoded"], options?: SchemaAST.ParseOptions) => Result_.Result = + decodeUnknownResult /** - * @category Decoding - * @since 4.0.0 + * Decodes an `unknown` input against a schema, returning a `Promise` that + * resolves with the decoded value or rejects with a {@link SchemaError}. + * + * **When to use** + * + * Use when you need decoding of unknown input to return a JavaScript `Promise` + * that rejects with `SchemaError`. + * + * **Details** + * + * For input already typed as the schema's `Encoded` type use + * {@link decodePromise}. + * Options may be provided either when creating the decoder or when applying it; + * application options override creation options. + * + * @see {@link SchemaParser.decodeUnknownPromise} for the adapter that rejects with `SchemaIssue.Issue` directly + * + * @category decoding + * @since 3.10.0 */ -export const decodeUnknownPromise = Parser.decodeUnknownPromise +export function decodeUnknownPromise>(schema: S, options?: SchemaAST.ParseOptions) { + const parser = decodeUnknownEffect(schema, options) + return (input: unknown, options?: SchemaAST.ParseOptions): Promise => { + return Effect.runPromise(parser(input, options)) + } +} /** * Decodes a typed input (the schema's `Encoded` type) against a schema, * returning a `Promise` that resolves with the decoded value or rejects with a - * {@link SchemaError}. For `unknown` input use {@link decodeUnknownPromise}. + * {@link SchemaError}. * - * @category Decoding - * @since 4.0.0 + * **When to use** + * + * Use when you already have input typed as the schema's `Encoded` type and + * need decoding to return a JavaScript `Promise` that rejects with + * `SchemaError`. + * + * **Details** + * + * For `unknown` input use `decodeUnknownPromise`. + * Options may be provided either when creating the decoder or when applying it; + * application options override creation options. + * + * @see {@link SchemaParser.decodePromise} for the adapter that rejects with `SchemaIssue.Issue` directly + * + * @category decoding + * @since 3.10.0 */ -export const decodePromise = Parser.decodePromise +export const decodePromise: >( + schema: S, + options?: SchemaAST.ParseOptions +) => (input: S["Encoded"], options?: SchemaAST.ParseOptions) => Promise = decodeUnknownPromise /** - * Decodes an `unknown` input against a schema synchronously, throwing a - * {@link SchemaError} on failure. Use this when you want to validate data at a - * boundary and treat a schema mismatch as an unrecoverable error. For - * non-throwing alternatives see {@link decodeUnknownOption}, - * {@link decodeUnknownExit}, or {@link decodeUnknownEffect}. For typed input - * use {@link decodeSync}. + * Decodes an `unknown` input against a schema synchronously, returning the + * decoded value or throwing a {@link SchemaError}. + * + * **When to use** + * + * Use when you need to validate unknown data at a synchronous boundary and want + * schema mismatches to throw `SchemaError`. + * + * **Details** + * + * For input already typed as the schema's `Encoded` type use `decodeSync`. + * Only service-free schemas can be decoded synchronously. For non-throwing + * alternatives see `decodeUnknownOption`, `decodeUnknownExit`, or + * `decodeUnknownEffect`. Options may be provided either when creating the + * decoder or when applying it; application options override creation options. * * **Example** (Decoding with a transformation schema) * @@ -1273,26 +1465,59 @@ export const decodePromise = Parser.decodePromise * // └─ Expected a numeric string, actual "not a number" * ``` * - * @category Decoding + * @see {@link SchemaParser.decodeUnknownSync} for the adapter that throws an `Error` whose cause is `SchemaIssue.Issue` + * + * @category decoding * @since 4.0.0 */ -export const decodeUnknownSync = Parser.decodeUnknownSync +export function decodeUnknownSync>(schema: S, options?: SchemaAST.ParseOptions) { + const parser = decodeUnknownEffect(schema, options) + return (input: unknown, options?: SchemaAST.ParseOptions): S["Type"] => { + return Effect.runSync(parser(input, options) as Effect.Effect) + } +} /** * Decodes a typed input (the schema's `Encoded` type) against a schema - * synchronously, throwing a {@link SchemaError} on failure. For `unknown` input - * use {@link decodeUnknownSync}. + * synchronously, returning the decoded value or throwing a {@link SchemaError}. + * + * **When to use** + * + * Use when you already have input typed as the schema's `Encoded` type and + * want schema mismatches to throw `SchemaError` synchronously. + * + * **Details** * - * @category Decoding + * For `unknown` input use `decodeUnknownSync`. + * Only service-free schemas can be decoded synchronously. Options may be + * provided either when creating the decoder or when applying it; application + * options override creation options. + * + * @see {@link SchemaParser.decodeSync} for the adapter that throws an `Error` whose cause is `SchemaIssue.Issue` + * + * @category decoding * @since 4.0.0 */ -export const decodeSync = Parser.decodeSync +export const decodeSync: >( + schema: S, + options?: SchemaAST.ParseOptions +) => (input: S["Encoded"], options?: SchemaAST.ParseOptions) => S["Type"] = decodeUnknownSync /** * Encodes an `unknown` input against a schema, returning an `Effect` that - * succeeds with the encoded value or fails with a {@link SchemaError}. Use this - * when the input type is not statically known. Prefer {@link encodeEffect} when - * the input is already typed as the schema's `Type`. + * succeeds with the encoded value or fails with a {@link SchemaError}. + * + * **When to use** + * + * Use when you need to encode unknown input in an `Effect` whose failure + * channel is `SchemaError`. + * + * **Details** + * + * Prefer {@link encodeEffect} when the value is already typed as the schema's + * `Type`. + * Options may be provided either when creating the encoder or when applying it; + * application options override creation options. * * **Example** (Encoding a value to a string) * @@ -1305,14 +1530,16 @@ export const decodeSync = Parser.decodeSync * // Output: "42" * ``` * - * @category Encoding + * @see {@link SchemaParser.encodeUnknownEffect} for the adapter that fails with `SchemaIssue.Issue` directly + * + * @category encoding * @since 4.0.0 */ -export function encodeUnknownEffect(schema: S) { - const parser = Parser.encodeUnknownEffect(schema) +export function encodeUnknownEffect(schema: S, options?: SchemaAST.ParseOptions) { + const parser = SchemaParser.encodeUnknownEffect(schema, options) return ( input: unknown, - options?: AST.ParseOptions + options?: SchemaAST.ParseOptions ): Effect.Effect => { return Effect.mapErrorEager(parser(input, options), (issue) => new SchemaError(issue)) } @@ -1321,30 +1548,57 @@ export function encodeUnknownEffect(schema: S) { /** * Encodes a typed input (the schema's `Type`) against a schema, returning an * `Effect` that succeeds with the encoded value or fails with a - * {@link SchemaError}. Use this when the input is already typed; for `unknown` - * input use {@link encodeUnknownEffect}. + * {@link SchemaError}. + * + * **When to use** + * + * Use when you need to encode input already typed as the schema's `Type` in + * an `Effect` whose failure channel is `SchemaError`. + * + * **Details** * - * @category Encoding + * For `unknown` input use {@link encodeUnknownEffect}. + * Options may be provided either when creating the encoder or when applying it; + * application options override creation options. + * + * @see {@link SchemaParser.encodeEffect} for the adapter that fails with `SchemaIssue.Issue` directly + * + * @category encoding * @since 4.0.0 */ export const encodeEffect: ( - schema: S -) => (input: S["Type"], options?: AST.ParseOptions) => Effect.Effect = - encodeUnknownEffect + schema: S, + options?: SchemaAST.ParseOptions +) => ( + input: S["Type"], + options?: SchemaAST.ParseOptions +) => Effect.Effect = encodeUnknownEffect /** * Encodes an `unknown` input against a schema synchronously, returning an * `Exit` that is either a `Success` with the encoded value or a `Failure` with - * a {@link SchemaError}. Only usable with schemas that have no - * `EncodingServices` requirement. Prefer {@link encodeExit} when the input is - * already typed as the schema's `Type`. + * a {@link SchemaError}. + * + * **When to use** * - * @category Encoding + * Use when you need to encode unknown input into an `Exit` whose failure + * contains `SchemaError`. + * + * **Details** + * + * Only usable with schemas that have no `EncodingServices` requirement. Prefer + * {@link encodeExit} when the value is already typed as the schema's `Type`. + * Options may be provided either when creating the encoder or when applying it; + * application options override creation options. + * + * @see {@link SchemaParser.encodeUnknownExit} for the adapter whose failure contains `SchemaIssue.Issue` directly + * + * @category encoding * @since 4.0.0 */ -export function encodeUnknownExit>(schema: S) { - const parser = Parser.encodeUnknownExit(schema) - return (input: unknown, options?: AST.ParseOptions): Exit_.Exit => { +export function encodeUnknownExit>(schema: S, options?: SchemaAST.ParseOptions) { + const parser = SchemaParser.encodeUnknownExit(schema, options) + return (input: unknown, options?: SchemaAST.ParseOptions): Exit_.Exit => { return Exit_.mapError(parser(input, options), (issue) => new SchemaError(issue)) } } @@ -1352,98 +1606,246 @@ export function encodeUnknownExit>(schema: S) { /** * Encodes a typed input (the schema's `Type`) against a schema synchronously, * returning an `Exit` that is either a `Success` with the encoded value or a - * `Failure` with a {@link SchemaError}. Only usable with schemas that have no - * `EncodingServices` requirement. For `unknown` input use - * {@link encodeUnknownExit}. + * `Failure` with a {@link SchemaError}. + * + * **When to use** + * + * Use when you need to encode already typed schema values into an `Exit` whose + * failure contains `SchemaError`. * - * @category Encoding + * **Details** + * + * Only usable with schemas that have no `EncodingServices` requirement. For + * `unknown` input use {@link encodeUnknownExit}. + * Options may be provided either when creating the encoder or when applying it; + * application options override creation options. + * + * @see {@link SchemaParser.encodeExit} for the adapter whose failure contains `SchemaIssue.Issue` directly + * + * @category encoding * @since 4.0.0 */ export const encodeExit: >( - schema: S -) => (input: S["Type"], options?: AST.ParseOptions) => Exit_.Exit = encodeUnknownExit + schema: S, + options?: SchemaAST.ParseOptions +) => (input: S["Type"], options?: SchemaAST.ParseOptions) => Exit_.Exit = encodeUnknownExit /** * Encodes an `unknown` input against a schema, returning an `Option` that is - * `Some` with the encoded value on success or `None` on failure. Prefer this - * over {@link encodeUnknownExit} or {@link encodeUnknownEffect} when you only - * need to know whether encoding succeeded and don't need error details. For - * typed input use {@link encodeOption}. + * `Some` with the encoded value on success or `None` on failure. * - * @category Encoding - * @since 4.0.0 + * **When to use** + * + * Use when you do not know the input type statically and only need to know + * whether encoding succeeded. + * + * **Details** + * + * Prefer this over {@link encodeUnknownExit} or {@link encodeUnknownEffect} + * when you don't need error details. For values already typed as the schema's + * `Type` use {@link encodeOption}. + * Options may be provided either when creating the encoder or when applying it; + * application options override creation options. + * + * @category encoding + * @since 3.10.0 */ -export const encodeUnknownOption = Parser.encodeUnknownOption +export const encodeUnknownOption: >( + schema: S, + options?: SchemaAST.ParseOptions +) => (input: unknown, options?: SchemaAST.ParseOptions) => Option_.Option = + SchemaParser.encodeUnknownOption /** * Encodes a typed input (the schema's `Type`) against a schema, returning an * `Option` that is `Some` with the encoded value on success or `None` on - * failure. For `unknown` input use {@link encodeUnknownOption}. + * failure. * - * @category Encoding - * @since 4.0.0 + * **When to use** + * + * Use when you already have a value typed as the schema's `Type` and only need + * to know whether encoding succeeded. + * + * **Details** + * + * For `unknown` input use {@link encodeUnknownOption}. + * Options may be provided either when creating the encoder or when applying it; + * application options override creation options. + * + * @category encoding + * @since 3.10.0 */ -export const encodeOption = Parser.encodeOption +export const encodeOption: >( + schema: S, + options?: SchemaAST.ParseOptions +) => (input: S["Type"], options?: SchemaAST.ParseOptions) => Option_.Option = encodeUnknownOption /** - * Encodes an `unknown` input against a schema, returning a `Promise` that - * resolves with the encoded value or rejects with a {@link SchemaError}. Useful - * for integrating with Promise-based APIs. For typed input use - * {@link encodePromise}. + * Encodes an `unknown` input against a schema, returning a `Result` that + * succeeds with the encoded value or fails with a {@link SchemaError}. + * + * **When to use** + * + * Use when you do not know the input type statically and want encoding to + * return a `Result` with `SchemaError` failure data. + * + * **Details** + * + * For values already typed as the schema's `Type` use {@link encodeResult}. + * Options may be provided either when creating the encoder or when applying it; + * application options override creation options. + * + * @see {@link SchemaParser.encodeUnknownResult} for the adapter that fails with `SchemaIssue.Issue` directly * - * @category Encoding + * @category encoding * @since 4.0.0 */ -export const encodeUnknownResult = Parser.encodeUnknownResult +export function encodeUnknownResult>(schema: S, options?: SchemaAST.ParseOptions) { + const parser = SchemaParser.encodeUnknownResult(schema, options) + return (input: unknown, options?: SchemaAST.ParseOptions): Result_.Result => { + return Result_.mapError(parser(input, options), (issue) => new SchemaError(issue)) + } +} /** - * @category Encoding + * Encodes a typed input (the schema's `Type`) against a schema, returning a + * `Result` that succeeds with the encoded value or fails with a + * {@link SchemaError}. + * + * **When to use** + * + * Use when you already have a value typed as the schema's `Type` and want + * encoding to return a `Result` with `SchemaError` failure data. + * + * **Details** + * + * For `unknown` input use {@link encodeUnknownResult}. + * Options may be provided either when creating the encoder or when applying it; + * application options override creation options. + * + * @see {@link SchemaParser.encodeResult} for the adapter that fails with `SchemaIssue.Issue` directly + * + * @category encoding * @since 4.0.0 */ -export const encodeResult = Parser.encodeResult +export const encodeResult: >( + schema: S, + options?: SchemaAST.ParseOptions +) => (input: S["Type"], options?: SchemaAST.ParseOptions) => Result_.Result = + encodeUnknownResult /** - * @category Encoding - * @since 4.0.0 + * Encodes an `unknown` input against a schema, returning a `Promise` that + * resolves with the encoded value or rejects with a {@link SchemaError}. + * + * **When to use** + * + * Use when you need encoding of unknown input to return a JavaScript `Promise` + * that rejects with `SchemaError`. + * + * **Details** + * + * For values already typed as the schema's `Type` use {@link encodePromise}. + * Options may be provided either when creating the encoder or when applying it; + * application options override creation options. + * + * @see {@link SchemaParser.encodeUnknownPromise} for the adapter that rejects with `SchemaIssue.Issue` directly + * + * @category encoding + * @since 3.10.0 */ -export const encodeUnknownPromise = Parser.encodeUnknownPromise +export function encodeUnknownPromise>(schema: S, options?: SchemaAST.ParseOptions) { + const parser = encodeUnknownEffect(schema, options) + return (input: unknown, options?: SchemaAST.ParseOptions): Promise => { + return Effect.runPromise(parser(input, options)) + } +} /** * Encodes a typed input (the schema's `Type`) against a schema, returning a * `Promise` that resolves with the encoded value or rejects with a - * {@link SchemaError}. For `unknown` input use {@link encodeUnknownPromise}. + * {@link SchemaError}. * - * @category Encoding - * @since 4.0.0 + * **When to use** + * + * Use when you already have a value typed as the schema's `Type` and need + * encoding to return a JavaScript `Promise` that rejects with `SchemaError`. + * + * **Details** + * + * For `unknown` input use {@link encodeUnknownPromise}. + * Options may be provided either when creating the encoder or when applying it; + * application options override creation options. + * + * @see {@link SchemaParser.encodePromise} for the adapter that rejects with `SchemaIssue.Issue` directly + * + * @category encoding + * @since 3.10.0 */ -export const encodePromise = Parser.encodePromise +export const encodePromise: >( + schema: S, + options?: SchemaAST.ParseOptions +) => (input: S["Type"], options?: SchemaAST.ParseOptions) => Promise = encodeUnknownPromise /** * Encodes an `unknown` input against a schema synchronously, throwing a - * {@link SchemaError} on failure. Use this when you want to serialize data at a - * boundary and treat a schema mismatch as an unrecoverable error. For - * non-throwing alternatives see {@link encodeUnknownOption}, - * {@link encodeUnknownExit}, or {@link encodeUnknownEffect}. For typed input - * use {@link encodeSync}. + * {@link SchemaError} on failure. + * + * **When to use** * - * @category Encoding + * Use when you need to serialize unknown data at a synchronous boundary and + * want schema mismatches to throw `SchemaError`. + * + * **Details** + * + * For non-throwing alternatives see {@link encodeUnknownOption}, + * {@link encodeUnknownExit}, or {@link encodeUnknownEffect}. For values + * already typed as the schema's `Type` use {@link encodeSync}. + * Options may be provided either when creating the encoder or when applying it; + * application options override creation options. + * + * @see {@link SchemaParser.encodeUnknownSync} for the adapter that throws an `Error` whose cause is `SchemaIssue.Issue` + * + * @category encoding * @since 4.0.0 */ -export const encodeUnknownSync = Parser.encodeUnknownSync +export function encodeUnknownSync>(schema: S, options?: SchemaAST.ParseOptions) { + const parser = encodeUnknownEffect(schema, options) + return (input: unknown, options?: SchemaAST.ParseOptions): S["Encoded"] => { + return Effect.runSync(parser(input, options) as Effect.Effect) + } +} /** * Encodes a typed input (the schema's `Type`) against a schema synchronously, - * throwing a {@link SchemaError} on failure. For `unknown` input use - * {@link encodeUnknownSync}. + * throwing a {@link SchemaError} on failure. * - * @category Encoding + * **When to use** + * + * Use when you already have a value typed as the schema's `Type` and want + * schema mismatches to throw `SchemaError` synchronously. + * + * **Details** + * + * For `unknown` input use {@link encodeUnknownSync}. + * Options may be provided either when creating the encoder or when applying it; + * application options override creation options. + * + * @see {@link SchemaParser.encodeSync} for the adapter that throws an `Error` whose cause is `SchemaIssue.Issue` + * + * @category encoding * @since 4.0.0 */ -export const encodeSync = Parser.encodeSync +export const encodeSync: >( + schema: S, + options?: SchemaAST.ParseOptions +) => (input: S["Type"], options?: SchemaAST.ParseOptions) => S["Encoded"] = encodeUnknownSync /** * Creates a schema from an AST (Abstract Syntax Tree) node. * + * **Details** + * * This is the fundamental constructor for all schemas in the Effect Schema * library. It takes an AST node and wraps it in a fully-typed schema that * preserves all type information and provides the complete schema API. @@ -1453,8 +1855,8 @@ export const encodeSync = Parser.encodeSync * the bridge between the untyped AST representation and the strongly-typed * schema. * - * @category Constructors - * @since 4.0.0 + * @category constructors + * @since 3.10.0 */ export const make: (ast: S["ast"], options?: object) => S = InternalSchema.make @@ -1476,6 +1878,7 @@ export const make: (ast: S["ast"], options?: object) => S = Inter * // "a" * ``` * + * @category constructors * @since 4.0.0 */ export function asClass(schema: S): S & { new(_: never): {} } { @@ -1485,20 +1888,19 @@ export function asClass(schema: S): S & { new(_: never): {} } { } /** - * Tests if a value is a `Schema`. + * Checks whether a value is a `Schema`. * - * @category Guards - * @since 4.0.0 + * @category guards + * @since 3.10.0 */ export function isSchema(u: unknown): u is Top { return Predicate.hasProperty(u, TypeId) && u[TypeId] === TypeId } /** - * Companion type for an exact optional struct key. The key may be absent, but - * when present must match the wrapped schema (no implicit `undefined`). - * Produced by {@link optionalKey}. + * Type-level representation returned by {@link optionalKey}. * + * @category models * @since 4.0.0 */ export interface optionalKey extends @@ -1547,9 +1949,12 @@ interface optionalKeyLambda extends Lambda { * type Person = typeof schema["Type"] * ``` * + * @category combinators * @since 4.0.0 */ -export const optionalKey = Struct_.lambda((schema) => make(AST.optionalKey(schema.ast), { schema })) +export const optionalKey = Struct_.lambda((schema) => + make(SchemaAST.optionalKey(schema.ast), { schema }) +) interface requiredKeyLambda extends Lambda { (self: optionalKey): S @@ -1558,18 +1963,23 @@ interface requiredKeyLambda extends Lambda { } /** - * Reverses {@link optionalKey}, returning the inner required schema. Only - * applicable to schemas already wrapped with `optionalKey`. + * Reverses `optionalKey` and returns the inner required schema. + * + * **When to use** + * + * Use to remove optional-key wrapping from a schema field that was previously + * wrapped with {@link optionalKey}. * + * @category combinators * @since 4.0.0 */ export const requiredKey = Struct_.lambda((self) => self.schema) /** - * Companion type for an optional struct key that also accepts `undefined`. - * Equivalent to `optionalKey>`. Produced by {@link optional}. + * Type-level representation returned by {@link optional}. * - * @since 4.0.0 + * @category models + * @since 3.10.0 */ export interface optional extends optionalKey> { readonly "Rebuild": optional @@ -1584,7 +1994,10 @@ interface optionalLambda extends Lambda { * Marks a struct field as optional, allowing the key to be absent or * `undefined`. * - * explicitly set to `undefined`. Equivalent to `optionalKey(UndefinedOr(S))`. + * **Details** + * + * The resulting property may be absent or explicitly set to `undefined`. + * Equivalent to `optionalKey(UndefinedOr(S))`. * * Use {@link optionalKey} instead if you want exact optional semantics (absent * only, not `undefined`). @@ -1603,7 +2016,8 @@ interface optionalLambda extends Lambda { * type Person = typeof schema.Type * ``` * - * @since 4.0.0 + * @category combinators + * @since 3.10.0 */ export const optional = Struct_.lambda((self) => optionalKey(UndefinedOr(self))) @@ -1614,17 +2028,26 @@ interface requiredLambda extends Lambda { } /** - * Reverses {@link optional}, returning the inner schema (unwrapping `UndefinedOr`). - * Only applicable to schemas already wrapped with `optional`. + * Reverses `optional` and returns the inner schema. * - * @since 4.0.0 + * **When to use** + * + * Use to remove optional wrapping from a schema field that was previously + * wrapped with {@link optional}. + * + * **Details** + * + * This also unwraps the `UndefinedOr` member added by `optional`. + * + * @category combinators + * @since 3.10.0 */ export const required = Struct_.lambda((self) => self.schema.members[0]) /** - * Companion type for a mutable struct key. The key's property is writable. - * Produced by {@link mutableKey}. + * Type-level representation returned by {@link mutableKey}. * + * @category models * @since 4.0.0 */ export interface mutableKey extends @@ -1658,9 +2081,12 @@ interface mutableKeyLambda extends Lambda { * Makes a struct field mutable (removes the `readonly` modifier on the property). * Use {@link readonlyKey} to reverse. * + * @category combinators * @since 4.0.0 */ -export const mutableKey = Struct_.lambda((schema) => make(AST.mutableKey(schema.ast), { schema })) +export const mutableKey = Struct_.lambda((schema) => + make(SchemaAST.mutableKey(schema.ast), { schema }) +) interface readonlyKeyLambda extends Lambda { (self: mutableKey): S @@ -1669,17 +2095,22 @@ interface readonlyKeyLambda extends Lambda { } /** - * Reverses {@link mutableKey}, returning the inner schema as readonly again. - * Only applicable to schemas already wrapped with `mutableKey`. + * Reverses `mutableKey` and returns the inner readonly schema. + * + * **When to use** + * + * Use to remove mutable-key wrapping from a schema field that was previously + * wrapped with {@link mutableKey}. * + * @category combinators * @since 4.0.0 */ export const readonlyKey = Struct_.lambda((self) => self.schema) /** - * Schema type that collapses a transformation schema to its decoded `Type` on - * both sides (Type = Encoded = S["Type"]). Produced by {@link toType}. + * Type-level representation returned by {@link toType}. * + * @category transforming * @since 4.0.0 */ export interface toType extends @@ -1711,14 +2142,15 @@ interface toTypeLambda extends Lambda { * Extracts the type-side schema: sets `Encoded` to equal the decoded `Type`, * discarding the encoding transformation path. * + * @category transforming * @since 4.0.0 */ -export const toType = Struct_.lambda((schema) => make(AST.toType(schema.ast), { schema })) +export const toType = Struct_.lambda((schema) => make(SchemaAST.toType(schema.ast), { schema })) /** - * Schema type that collapses a transformation schema to its `Encoded` side on - * both sides (Type = Encoded = S["Encoded"]). Produced by {@link toEncoded}. + * Type-level representation returned by {@link toEncoded}. * + * @category transforming * @since 4.0.0 */ export interface toEncoded extends @@ -1727,7 +2159,7 @@ export interface toEncoded extends S["Encoded"], never, never, - AST.AST, + SchemaAST.AST, toEncoded, S["Encoded"], S["Encoded"], @@ -1750,16 +2182,17 @@ interface toEncodedLambda extends Lambda { * Extracts the encoded-side schema: sets `Type` to equal the `Encoded`, * discarding the decoding transformation path. * + * @category transforming * @since 4.0.0 */ -export const toEncoded = Struct_.lambda((schema) => make(AST.toEncoded(schema.ast), { schema })) +export const toEncoded = Struct_.lambda((schema) => make(SchemaAST.toEncoded(schema.ast), { schema })) const FlipTypeId = "~effect/Schema/flip" /** - * Schema type representing a flipped schema where `Type` and `Encoded` are - * swapped. Produced by {@link flip}. + * Type-level representation returned by {@link flip}. * + * @category transforming * @since 4.0.0 */ export interface flip extends @@ -1768,7 +2201,7 @@ export interface flip extends S["Type"], S["EncodingServices"], S["DecodingServices"], - AST.AST, + SchemaAST.AST, flip, S["Encoded"], S["Encoded"], @@ -1790,8 +2223,15 @@ function isFlip$(schema: Top): schema is flip { } /** - * Swaps the `Type` and `Encoded` of a schema, inverting the transformation - * direction. Calling `flip` twice returns the original schema. + * Swaps the decoded and encoded sides of a schema. + * + * **When to use** + * + * Use to invert a schema transformation direction. + * + * **Details** + * + * Calling `flip` twice returns the original schema. * * **Example** (Flip a number-from-string schema) * @@ -1803,31 +2243,35 @@ function isFlip$(schema: Top): schema is flip { * // flipped: decodes number → string * ``` * + * @category transforming * @since 4.0.0 */ export function flip(schema: S): S extends flip ? F["Rebuild"] : flip export function flip(schema: S): flip { if (isFlip$(schema)) { - return schema.schema.rebuild(AST.flip(schema.ast)) + return schema.schema.rebuild(SchemaAST.flip(schema.ast)) } - return make(AST.flip(schema.ast), { [FlipTypeId]: FlipTypeId, schema }) + return make(SchemaAST.flip(schema.ast), { [FlipTypeId]: FlipTypeId, schema }) } /** - * Represents a schema for a single literal value. + * Type-level representation returned by {@link Literal}. * - * @see {@link Literal} for the constructor function. - * @since 4.0.0 + * @category models + * @since 3.10.0 */ -export interface Literal extends Bottom> { +export interface Literal + extends Bottom> +{ readonly literal: L - transform(to: L2): decodeTo, Literal> + transform(to: L2): decodeTo, Literal> } /** * Creates a schema for a single literal value (string, number, bigint, boolean, or null). * * **Example** (String literal) + * * ```ts * import { Schema } from "effect" * @@ -1838,15 +2282,16 @@ export interface Literal extends Bottom(literal: L): Literal { - const out = make>(new AST.Literal(literal), { +export function Literal(literal: L): Literal { + const out = make>(new SchemaAST.Literal(literal), { literal, - transform(to: L2): decodeTo, Literal> { + transform(to: L2): decodeTo, Literal> { return out.pipe(decodeTo(Literal(to), { - decode: Getter.transform(() => to), - encode: Getter.transform(() => literal) + decode: SchemaGetter.transform(() => to), + encode: SchemaGetter.transform(() => literal) })) } }) @@ -1856,10 +2301,18 @@ export function Literal(literal: L): Literal { /** * Namespace for {@link TemplateLiteral} helper types. * - * @since 4.0.0 + * @since 3.10.0 */ export declare namespace TemplateLiteral { /** + * Constraint for schema parts that can appear inside a `TemplateLiteral`. + * + * **Details** + * + * The schema's encoded value must be a `string`, `number`, or `bigint` so it can + * be converted into a template literal string segment. + * + * @category utility types * @since 4.0.0 */ export interface SchemaPart extends Top { @@ -1867,16 +2320,26 @@ export declare namespace TemplateLiteral { } /** + * Literal value that can be used directly as a part of a `TemplateLiteral`. + * + * @category utility types * @since 4.0.0 */ export type LiteralPart = string | number | bigint /** + * A single part of a `TemplateLiteral`, either an interpolated schema part or a + * literal `string`, `number`, or `bigint`. + * + * @category utility types * @since 4.0.0 */ export type Part = SchemaPart | LiteralPart /** + * Ordered list of parts used to construct a `TemplateLiteral` schema. + * + * @category utility types * @since 4.0.0 */ export type Parts = ReadonlyArray @@ -1889,18 +2352,21 @@ export declare namespace TemplateLiteral { : never /** - * @since 4.0.0 + * Computes the encoded string literal type produced by concatenating the encoded + * forms of all template literal parts. + * + * @category utility types + * @since 3.10.0 */ export type Encoded = Parts extends readonly [...infer Init, infer Last] ? AppendType, Last> : `` } /** - * Represents a schema that validates strings matching a template literal pattern. - * The encoded type is a string formed by concatenating the parts. + * Type-level representation returned by {@link TemplateLiteral}. * - * @see {@link TemplateLiteral} for the constructor function. - * @since 4.0.0 + * @category models + * @since 3.10.0 */ export interface TemplateLiteral extends Bottom< @@ -1908,7 +2374,7 @@ export interface TemplateLiteral extends TemplateLiteral.Encoded, never, never, - AST.TemplateLiteral, + SchemaAST.TemplateLiteral, TemplateLiteral > { @@ -1916,14 +2382,20 @@ export interface TemplateLiteral extends } function templateLiteralFromParts(parts: Parts) { - return new AST.TemplateLiteral(parts.map((part) => isSchema(part) ? part.ast : new AST.Literal(part))) + return new SchemaAST.TemplateLiteral(parts.map((part) => isSchema(part) ? part.ast : new SchemaAST.Literal(part))) } /** * Creates a schema that validates strings matching a template literal pattern. Each part can be * a literal string/number/bigint or a schema whose encoded type is a string, number, or bigint. * + * **When to use** + * + * Use when the decoded value should remain the matched string and you do not + * need the individual template parts parsed into a tuple. + * * **Example** (URL path pattern) + * * ```ts * import { Schema } from "effect" * @@ -1932,7 +2404,8 @@ function templateLiteralFromParts(parts: Pa * ``` * * @see {@link TemplateLiteralParser} for a schema that also parses matched parts into a tuple. - * @since 4.0.0 + * @category constructors + * @since 3.10.0 */ export function TemplateLiteral(parts: Parts): TemplateLiteral { return make(templateLiteralFromParts(parts), { parts }) @@ -1941,11 +2414,19 @@ export function TemplateLiteral(parts /** * Namespace for {@link TemplateLiteralParser} helper types. * - * @since 4.0.0 + * @since 3.10.0 */ export declare namespace TemplateLiteralParser { /** - * @since 4.0.0 + * Computes the decoded tuple type produced by `TemplateLiteralParser`. + * + * **Details** + * + * Literal parts contribute their literal value to the tuple. Schema parts + * contribute their decoded `Type`. + * + * @category utility types + * @since 3.10.0 */ export type Type = Parts extends readonly [infer Head, ...infer Tail] ? readonly [ Head extends TemplateLiteral.LiteralPart ? Head : @@ -1957,11 +2438,10 @@ export declare namespace TemplateLiteralParser { } /** - * Represents a schema that validates strings matching a template literal pattern and decodes - * them into a tuple of typed values, one per schema part. + * Type-level representation returned by {@link TemplateLiteralParser}. * - * @see {@link TemplateLiteralParser} for the constructor function. - * @since 4.0.0 + * @category models + * @since 3.10.0 */ export interface TemplateLiteralParser extends Bottom< @@ -1969,7 +2449,7 @@ export interface TemplateLiteralParser exte TemplateLiteral.Encoded, never, never, - AST.Arrays, + SchemaAST.Arrays, TemplateLiteralParser > { @@ -1977,10 +2457,20 @@ export interface TemplateLiteralParser exte } /** - * Like {@link TemplateLiteral} but decodes the matched string into a readonly tuple of typed values, - * one element per schema part. + * Schema for parsing template literal matches into typed tuple parts. + * + * **When to use** + * + * Use to validate a template literal string and decode the matched parts into + * typed values. + * + * **Details** + * + * Unlike {@link TemplateLiteral}, this schema decodes the matched string into a + * readonly tuple with one element per schema part. * * **Example** (Parse path parameters) + * * ```ts * import { Schema } from "effect" * @@ -1989,7 +2479,8 @@ export interface TemplateLiteralParser exte * ``` * * @see {@link TemplateLiteral} for a validation-only version that keeps the string encoded. - * @since 4.0.0 + * @category constructors + * @since 3.10.0 */ export function TemplateLiteralParser( parts: Parts @@ -1998,14 +2489,13 @@ export function TemplateLiteralParser } /** - * Represents a schema derived from a TypeScript `const enum` or a plain enum object, - * accepting any of its values. + * Type-level representation returned by {@link Enum}. * - * @see {@link Enum} for the constructor function. + * @category models * @since 4.0.0 */ export interface Enum - extends Bottom> + extends Bottom> { readonly enums: A } @@ -2014,6 +2504,7 @@ export interface Enum * Creates a schema from a TypeScript enum object. Validates that the input is one of the enum's values. * * **Example** (Direction enum) + * * ```ts * import { Schema } from "effect" * @@ -2026,11 +2517,12 @@ export interface Enum * // accepts "Up" or "Down" * ``` * + * @category constructors * @since 4.0.0 */ export function Enum(enums: A): Enum { return make( - new AST.Enum( + new SchemaAST.Enum( Object.keys(enums).filter( (key) => typeof enums[enums[key]] !== "number" ).map((key) => [key, enums[key]]) @@ -2040,212 +2532,244 @@ export function Enum(enums: A): Enum } /** - * Schema for the `never` type. Always fails validation. + * Type-level representation of {@link Never}. * - * @see {@link Never} for the schema value. - * @since 4.0.0 + * @category models + * @since 3.10.0 */ -export interface Never extends Bottom {} +export interface Never extends Bottom {} /** * Schema for the `never` type. Always fails validation — no value satisfies it. * - * @since 4.0.0 + * @category schemas + * @since 3.10.0 */ -export const Never: Never = make(AST.never) +export const Never: Never = make(SchemaAST.never) /** - * Schema for the `any` type. Accepts any value without validation. + * Type-level representation of {@link Any}. * - * @see {@link Any} for the schema value. - * @since 4.0.0 + * @category models + * @since 3.10.0 */ -export interface Any extends Bottom {} +export interface Any extends Bottom {} /** * Schema for the `any` type. Accepts any value without validation. * * @see {@link Unknown} for a safer alternative that uses `unknown`. - * @since 4.0.0 + * @category schemas + * @since 3.10.0 */ -export const Any: Any = make(AST.any) +export const Any: Any = make(SchemaAST.any) /** - * Schema for the `unknown` type. Accepts any value without validation. + * Type-level representation of {@link Unknown}. * - * @see {@link Unknown} for the schema value. - * @since 4.0.0 + * @category models + * @since 3.10.0 */ -export interface Unknown extends Bottom {} +export interface Unknown extends Bottom {} /** * Schema for the `unknown` type. Accepts any value without validation. * + * **When to use** + * + * Use as a top schema when you need to accept any input while preserving + * TypeScript's `unknown` safety at use sites. + * * @see {@link Any} for the `any` variant. - * @since 4.0.0 + * @category schemas + * @since 3.10.0 */ -export const Unknown: Unknown = make(AST.unknown) +export const Unknown: Unknown = make(SchemaAST.unknown) /** - * Schema for the `null` literal. Validates that the input is strictly `null`. + * Type-level representation of {@link Null}. * - * @see {@link Null} for the schema value. - * @since 4.0.0 + * @category models + * @since 3.10.0 */ -export interface Null extends Bottom {} +export interface Null extends Bottom {} /** * Schema for the `null` literal. Validates that the input is strictly `null`. * * @see {@link NullOr} for a union with another schema. - * @since 4.0.0 + * @category schemas + * @since 3.10.0 */ -export const Null: Null = make(AST.null) +export const Null: Null = make(SchemaAST.null) /** - * Schema for the `undefined` literal. Validates that the input is strictly `undefined`. + * Type-level representation of {@link Undefined}. * - * @see {@link Undefined} for the schema value. - * @since 4.0.0 + * @category models + * @since 3.10.0 */ -export interface Undefined extends Bottom {} +export interface Undefined extends Bottom {} /** * Schema for the `undefined` literal. Validates that the input is strictly `undefined`. * * @see {@link UndefinedOr} for a union with another schema. - * @since 4.0.0 + * @category schemas + * @since 3.10.0 */ -export const Undefined: Undefined = make(AST.undefined) +export const Undefined: Undefined = make(SchemaAST.undefined) /** - * Schema for `string` values. + * Type-level representation of {@link String}. * - * @see {@link String} for the schema value. + * @category models * @since 4.0.0 */ -export interface String extends Bottom {} +export interface String extends Bottom {} /** * Schema for `string` values. Validates that the input is `typeof` `"string"`. * + * @category schemas * @since 4.0.0 */ -export const String: String = make(AST.string) +export const String: String = make(SchemaAST.string) /** - * Schema for `number` values, including `NaN`, `Infinity`, and `-Infinity`. + * Type-level representation of {@link Number}. * - * @see {@link Number} for the schema value. + * @category models * @since 4.0.0 */ -export interface Number extends Bottom {} +export interface Number extends Bottom {} /** * Schema for `number` values, including `NaN`, `Infinity`, and `-Infinity`. * - * **Default Json Serializer** + * **Details** + * + * Default JSON serializer: * * - Finite numbers are serialized as numbers. * - Non-finite values are serialized as strings (`"NaN"`, `"Infinity"`, `"-Infinity"`). * * @see {@link Finite} for a schema that excludes non-finite values. + * @category schemas * @since 4.0.0 */ -export const Number: Number = make(AST.number) +export const Number: Number = make(SchemaAST.number) /** - * Schema for `boolean` values. + * Type-level representation of {@link Boolean}. * - * @see {@link Boolean} for the schema value. + * @category models * @since 4.0.0 */ -export interface Boolean extends Bottom {} +export interface Boolean extends Bottom {} /** * Schema for `boolean` values. Validates that the input is `typeof` `"boolean"`. * - * @category Boolean + * **When to use** + * + * Use to validate values that are already JavaScript booleans. + * + * @see {@link BooleanFromBit} for a schema that decodes bit literals `0` or `1` into a boolean + * + * @category boolean * @since 4.0.0 */ -export const Boolean: Boolean = make(AST.boolean) +export const Boolean: Boolean = make(SchemaAST.boolean) /** - * Schema for `symbol` values. + * Type-level representation of {@link Symbol}. * - * @see {@link Symbol} for the schema value. + * @category models * @since 4.0.0 */ -export interface Symbol extends Bottom {} +export interface Symbol extends Bottom {} /** * Schema for `symbol` values. Validates that the input is `typeof` `"symbol"`. * * @see {@link UniqueSymbol} for a schema that matches a specific symbol. + * @category schemas * @since 4.0.0 */ -export const Symbol: Symbol = make(AST.symbol) +export const Symbol: Symbol = make(SchemaAST.symbol) /** - * Schema for `bigint` values. + * Type-level representation of {@link BigInt}. * - * @see {@link BigInt} for the schema value. + * @category models * @since 4.0.0 */ -export interface BigInt extends Bottom {} +export interface BigInt extends Bottom {} /** * Schema for `bigint` values. Validates that the input is `typeof` `"bigint"`. * + * **When to use** + * + * Use when the input is already a bigint and the schema should validate and + * preserve bigint values without parsing from another representation. + * + * @see {@link BigIntFromString} for parsing string input into a bigint + * + * @category schemas * @since 4.0.0 */ -export const BigInt: BigInt = make(AST.bigInt) +export const BigInt: BigInt = make(SchemaAST.bigInt) /** - * Schema for the `void` type. + * Type-level representation of {@link Void}. * - * @see {@link Void} for the schema value. - * @since 4.0.0 + * @category models + * @since 3.10.0 */ -export interface Void extends Bottom {} +export interface Void extends Bottom {} /** * Schema for the `void` type. Accepts `undefined` as the encoded value. * - * @since 4.0.0 + * @category schemas + * @since 3.10.0 */ -export const Void: Void = make(AST.void) +export const Void: Void = make(SchemaAST.void) /** - * Schema for the `object` type keyword. + * Type-level representation of {@link ObjectKeyword}. * - * @see {@link ObjectKeyword} for the schema value. + * @category models * @since 4.0.0 */ -export interface ObjectKeyword extends Bottom {} +export interface ObjectKeyword extends Bottom {} /** * Schema for the `object` type. Validates that the input is a non-null object or function * (i.e. `typeof value === "object" && value !== null || typeof value === "function"`). * + * @category schemas * @since 4.0.0 */ -export const ObjectKeyword: ObjectKeyword = make(AST.objectKeyword) +export const ObjectKeyword: ObjectKeyword = make(SchemaAST.objectKeyword) /** - * Represents a schema for a specific unique symbol. + * Type-level representation returned by {@link UniqueSymbol}. * - * @see {@link UniqueSymbol} for the constructor function. + * @category models * @since 4.0.0 */ export interface UniqueSymbol - extends Bottom> + extends Bottom> {} /** * Creates a schema for a specific symbol. Only that exact symbol satisfies the schema. * * **Example** (Specific symbol) + * * ```ts * import { Schema } from "effect" * @@ -2254,15 +2778,18 @@ export interface UniqueSymbol * ``` * * @see {@link Symbol} for a schema that accepts any symbol. + * @category constructors * @since 4.0.0 */ export function UniqueSymbol(symbol: sym): UniqueSymbol { - return make(new AST.UniqueSymbol(symbol)) + return make(new SchemaAST.UniqueSymbol(symbol)) } /** * Namespace for struct field type utilities. * + * **Details** + * * These types compute the decoded `Type`, encoded `Encoded`, and constructor * input `MakeIn` of a {@link Struct} from its field map, handling optional, * mutable, and other field modifiers automatically. @@ -2273,13 +2800,14 @@ export function UniqueSymbol(symbol: sym): UniqueSymbo * - `Struct.MakeIn` — constructor input (optional/defaulted fields may be omitted) * - `Struct.DecodingServices` / `Struct.EncodingServices` — required services * - * @since 4.0.0 + * @since 3.10.0 */ export declare namespace Struct { /** * Constraint for a struct field map: an object whose values are schemas. * - * @since 4.0.0 + * @category utility types + * @since 3.10.0 */ export type Fields = { readonly [x: PropertyKey]: Top } @@ -2298,13 +2826,21 @@ export declare namespace Struct { O extends keyof F = TypeOptionalKeys, M extends keyof F = TypeMutableKeys > = - & { readonly [K in Exclude]: F[K]["Type"] } - & { readonly [K in Exclude]?: F[K]["Type"] } - & { [K in Exclude]: F[K]["Type"] } - & { [K in M & O]?: F[K]["Type"] } + & { readonly [K in keyof F as K extends M | O ? never : K]: F[K]["Type"] } + & { readonly [K in keyof F as K extends O ? K extends M ? never : K : never]?: F[K]["Type"] } + & { -readonly [K in keyof F as K extends M ? K extends O ? never : K : never]: F[K]["Type"] } + & { -readonly [K in keyof F as K extends M & O ? K : never]?: F[K]["Type"] } /** - * @since 4.0.0 + * Computes the decoded object type for a struct field map. + * + * **Details** + * + * Field schemas contribute their decoded `Type`. `optionalKey` and `optional` + * produce optional properties, while `mutableKey` produces writable properties. + * + * @category utility types + * @since 3.10.0 */ export type Type = Simplify> @@ -2313,12 +2849,21 @@ export declare namespace Struct { O extends keyof F = TypeOptionalKeys, M extends keyof F = TypeMutableKeys > = - & { readonly [K in Exclude]: F[K]["Iso"] } - & { readonly [K in Exclude]?: F[K]["Iso"] } - & { [K in Exclude]: F[K]["Iso"] } - & { [K in M & O]?: F[K]["Iso"] } + & { readonly [K in keyof F as K extends M | O ? never : K]: F[K]["Iso"] } + & { readonly [K in keyof F as K extends O ? K extends M ? never : K : never]?: F[K]["Iso"] } + & { -readonly [K in keyof F as K extends M ? K extends O ? never : K : never]: F[K]["Iso"] } + & { -readonly [K in keyof F as K extends M & O ? K : never]?: F[K]["Iso"] } /** + * Computes the iso object type for a struct field map from each field schema's + * `Iso` type. + * + * **Details** + * + * The resulting property optionality and mutability follow the same field + * modifiers used by `Struct.Type`. + * + * @category utility types * @since 4.0.0 */ export type Iso = Simplify> @@ -2338,22 +2883,39 @@ export declare namespace Struct { O extends keyof F = EncodedOptionalKeys, M extends keyof F = EncodedMutableKeys > = - & { readonly [K in Exclude]: F[K]["Encoded"] } - & { readonly [K in Exclude]?: F[K]["Encoded"] } - & { [K in Exclude]: F[K]["Encoded"] } - & { [K in M & O]?: F[K]["Encoded"] } + & { readonly [K in keyof F as K extends M | O ? never : K]: F[K]["Encoded"] } + & { readonly [K in keyof F as K extends O ? K extends M ? never : K : never]?: F[K]["Encoded"] } + & { -readonly [K in keyof F as K extends M ? K extends O ? never : K : never]: F[K]["Encoded"] } + & { -readonly [K in keyof F as K extends M & O ? K : never]?: F[K]["Encoded"] } /** - * @since 4.0.0 + * Computes the encoded object type for a struct field map. + * + * **Details** + * + * Field schemas contribute their `Encoded` type. Encoded-side optionality and + * mutability modifiers determine whether properties are optional or writable in + * the encoded shape. + * + * @category utility types + * @since 3.10.0 */ export type Encoded = Simplify> /** + * Union of all decoding service requirements needed by the schemas in a struct + * field map. + * + * @category utility types * @since 4.0.0 */ export type DecodingServices = { readonly [K in keyof F]: F[K]["DecodingServices"] }[keyof F] /** + * Union of all encoding service requirements needed by the schemas in a struct + * field map. + * + * @category utility types * @since 4.0.0 */ export type EncodingServices = { readonly [K in keyof F]: F[K]["EncodingServices"] }[keyof F] @@ -2371,13 +2933,24 @@ export declare namespace Struct { & { readonly [K in keyof F as K extends O ? K : never]?: F[K]["~type.make"] } /** + * Computes the input object type accepted when constructing a struct value. + * + * **Details** + * + * Required fields use each field schema's `~type.make` input. Fields marked + * optional or with a constructor default may be omitted. + * + * @category utility types * @since 4.0.0 */ export type MakeIn = Simplify> } /** - * @since 4.0.0 + * Type-level representation returned by {@link Struct}. + * + * @category models + * @since 3.10.0 */ export interface Struct extends Bottom< @@ -2385,7 +2958,7 @@ export interface Struct extends Struct.Encoded, Struct.DecodingServices, Struct.EncodingServices, - AST.Objects, + SchemaAST.Objects, Struct, Struct.MakeIn, Struct.Iso @@ -2416,7 +2989,9 @@ export interface Struct extends /** * Returns a new struct with the fields modified by the provided function. * - * **Options** + * **Details** + * + * Options: * * - `unsafePreserveChecks` - if `true`, keep any `.check(...)` constraints * that were attached to the original union. Defaults to `false`. @@ -2435,7 +3010,7 @@ export interface Struct extends ): Struct>> } -function makeStruct(ast: AST.Objects, fields: Fields): Struct { +function makeStruct(ast: SchemaAST.Objects, fields: Fields): Struct { return make(ast, { fields, mapFields( @@ -2446,7 +3021,7 @@ function makeStruct(ast: AST.Objects, fields } | undefined ): Struct { const fields = f(this.fields) - return makeStruct(AST.struct(fields, options?.unsafePreserveChecks ? this.ast.checks : undefined), fields) + return makeStruct(SchemaAST.struct(fields, options?.unsafePreserveChecks ? this.ast.checks : undefined), fields) } }) } @@ -2454,6 +3029,8 @@ function makeStruct(ast: AST.Objects, fields /** * Defines a struct schema from a map of field schemas. * + * **Details** + * * Each field value is a schema. Use {@link optionalKey} or {@link optional} to * mark fields as optional, and {@link mutableKey} to mark them as mutable. * @@ -2479,11 +3056,11 @@ function makeStruct(ast: AST.Objects, fields * // { name: 'Alice', age: 30 } * ``` * - * @category Constructors - * @since 4.0.0 + * @category constructors + * @since 3.10.0 */ export function Struct(fields: Fields): Struct { - return makeStruct(AST.struct(fields, undefined), fields) + return makeStruct(SchemaAST.struct(fields, undefined), fields) } interface fieldsAssign extends Lambda { @@ -2496,8 +3073,16 @@ interface fieldsAssign extends Lambda { } /** - * A shortcut for `MyStruct.mapFields(Struct.assign(fields))`. This is useful - * when you want to add new fields to an existing struct or a union of structs. + * Adds fields to a struct schema through a struct-mapping lambda. + * + * **When to use** + * + * Use to add the same fields to an existing struct or every struct member of a + * union. + * + * **Details** + * + * This is a shortcut for `MyStruct.mapFields(Struct.assign(fields))`. * * **Example** (Adding fields to a union of structs) * @@ -2511,6 +3096,7 @@ interface fieldsAssign extends Lambda { * ]).mapMembers(Tuple.map(Schema.fieldsAssign({ c: Schema.Number }))) * ``` * + * @category combinators * @since 4.0.0 */ export function fieldsAssign(fields: NewFields) { @@ -2518,9 +3104,9 @@ export function fieldsAssign(fields: NewF } /** - * Schema type for a struct with renamed encoded keys. Produced by - * {@link encodeKeys}. + * Type-level representation returned by {@link encodeKeys}. * + * @category transforming * @since 4.0.0 */ export interface encodeKeys< @@ -2539,12 +3125,19 @@ export interface encodeKeys< > {} +const canonicalPropertyKey = (key: PropertyKey): string | symbol => + typeof key === "symbol" ? key : globalThis.String(key) + /** * Renames struct keys in the encoded form without changing the decoded type. * + * **Details** + * * Takes a partial mapping `{ decodedKey: encodedKey }` and produces a * transformation schema that decodes from the renamed keys and encodes back to * the renamed keys. Keys not present in the mapping are left unchanged. + * If two existing fields would produce the same encoded key, construction + * fails. * * **Example** (Rename `name` to `full_name` in the encoded form) * @@ -2560,7 +3153,7 @@ export interface encodeKeys< * // { name: 'Alice', age: 30 } * ``` * - * @category Struct transformations + * @category transforming * @since 4.0.0 */ export function encodeKeys< @@ -2569,21 +3162,29 @@ export function encodeKeys< >(mapping: M) { return function(self: S): encodeKeys { const fields: any = {} + const appliedMapping: any = {} const reverseMapping: any = {} - for (const k in self.fields) { + const seenEncodedKeys = new Set() + for (const k of Reflect.ownKeys(self.fields)) { const encoded = toEncoded(self.fields[k]) - if (Object.hasOwn(mapping, k)) { - fields[mapping[k]!] = encoded - reverseMapping[mapping[k]!] = k - } else { - fields[k] = encoded + const hasMapping = Object.hasOwn(mapping, k) + const encodedKey = hasMapping ? (mapping as any)[k] as PropertyKey : k + const canonical = canonicalPropertyKey(encodedKey) + if (seenEncodedKeys.has(canonical)) { + throw new globalThis.Error(`Duplicate encoded keys: ${formatPropertyKey(encodedKey)}`) + } + seenEncodedKeys.add(canonical) + fields[encodedKey] = encoded + if (hasMapping) { + appliedMapping[k] = encodedKey + reverseMapping[encodedKey] = k } } return Struct(fields).pipe(decodeTo( self, - Transformation.transform({ + SchemaTransformation.transform({ decode: Struct_.renameKeys(reverseMapping), - encode: Struct_.renameKeys(mapping) + encode: Struct_.renameKeys(appliedMapping) }) )) as any } @@ -2592,6 +3193,8 @@ export function encodeKeys< /** * Adds derived fields to a struct schema during decoding. * + * **Details** + * * Each new field is derived from the decoded struct value via a function that * returns `Option`. On encoding the derived fields are stripped. This allows * computed or enriched fields to live in the decoded type without appearing in @@ -2615,8 +3218,8 @@ export function encodeKeys< * // Alice Smith * ``` * + * @category transforming * @since 4.0.0 - * @experimental */ export function extendTo, const Fields extends Struct.Fields>( /** The new fields to add */ @@ -2631,7 +3234,7 @@ export function extendTo, const Fields extends S const to = Struct({ ...f, ...fields }) return self.pipe(decodeTo( to, - Transformation.transform({ + SchemaTransformation.transform({ decode: (input) => { const out: any = { ...input } for (const k in fields) { @@ -2658,14 +3261,24 @@ export function extendTo, const Fields extends S /** * Namespace for `Record` type utilities. * + * **Details** + * * - `Record.Key` — constraint for the key schema (must encode to `PropertyKey`) * - `Record.Type` — decoded type of the record * - `Record.Encoded` — encoded type of the record * - * @since 4.0.0 + * @since 3.10.0 */ export declare namespace Record { /** + * Constraint for schemas that can be used as record keys. + * + * **Details** + * + * The key schema must decode and encode property keys (`string`, `number`, or + * `symbol`) so it can describe object property names. + * + * @category utility types * @since 4.0.0 */ export interface Key extends Codec { @@ -2674,7 +3287,17 @@ export declare namespace Record { } /** - * @since 4.0.0 + * Computes the decoded object type for a record schema from its key and value + * schemas. + * + * **Details** + * + * The key schema supplies the property keys and the value schema supplies each + * property's decoded `Type`. Optional and mutable value schemas affect the + * resulting property optionality and writability. + * + * @category utility types + * @since 3.10.0 */ export type Type = Value extends { readonly "~type.optionality": "optional" } ? @@ -2684,6 +3307,10 @@ export declare namespace Record { : { readonly [P in Key["Type"]]: Value["Type"] } /** + * Computes the iso object type for a record schema from the key schema's `Iso` + * keys and the value schema's `Iso` values. + * + * @category utility types * @since 4.0.0 */ export type Iso = Value extends @@ -2694,7 +3321,16 @@ export declare namespace Record { : { readonly [P in Key["Iso"]]: Value["Iso"] } /** - * @since 4.0.0 + * Computes the encoded object type for a record schema from the key and value + * schemas' encoded types. + * + * **Details** + * + * Encoded-side optionality and mutability on the value schema determine whether + * the encoded record properties are optional or writable. + * + * @category utility types + * @since 3.10.0 */ export type Encoded = Value extends { readonly "~encoded.optionality": "optional" } ? @@ -2704,6 +3340,10 @@ export declare namespace Record { : { readonly [P in Key["Encoded"]]: Value["Encoded"] } /** + * Union of the decoding service requirements of a record's key schema and value + * schema. + * + * @category utility types * @since 4.0.0 */ export type DecodingServices = @@ -2711,6 +3351,10 @@ export declare namespace Record { | Value["DecodingServices"] /** + * Union of the encoding service requirements of a record's key schema and value + * schema. + * + * @category utility types * @since 4.0.0 */ export type EncodingServices = @@ -2718,6 +3362,15 @@ export declare namespace Record { | Value["EncodingServices"] /** + * Computes the input object type accepted when constructing a record value. + * + * **Details** + * + * Keys use the key schema's `~type.make` type and values use the value schema's + * `~type.make` type. Value optionality and mutability determine whether + * properties are optional or writable. + * + * @category utility types * @since 4.0.0 */ export type MakeIn = Value extends @@ -2729,9 +3382,9 @@ export declare namespace Record { } /** - * Companion type for a key-value record (map) with a typed key and value schema. - * Produced by {@link Record}. + * Type-level representation returned by {@link Record}. * + * @category models * @since 4.0.0 */ export interface $Record extends @@ -2740,7 +3393,7 @@ export interface $Record extends Record.Encoded, Record.DecodingServices, Record.EncodingServices, - AST.Objects, + SchemaAST.Objects, $Record, Simplify>, Record.Iso @@ -2768,8 +3421,8 @@ export interface $Record extends * // { a: 1, b: 2 } * ``` * - * @category Constructors - * @since 4.0.0 + * @category constructors + * @since 3.10.0 */ export function Record( key: Key, @@ -2782,14 +3435,16 @@ export function Record( } ): $Record { const keyValueCombiner = options?.keyValueCombiner?.decode || options?.keyValueCombiner?.encode - ? new AST.KeyValueCombiner(options.keyValueCombiner.decode, options.keyValueCombiner.encode) + ? new SchemaAST.KeyValueCombiner(options.keyValueCombiner.decode, options.keyValueCombiner.encode) : undefined - return make(AST.record(key.ast, value.ast, keyValueCombiner), { key, value }) + return make(SchemaAST.record(key.ast, value.ast, keyValueCombiner), { key, value }) } /** * Namespace for `StructWithRest` type utilities. * + * **Details** + * * - `StructWithRest.Type` — decoded type (struct type intersected with record types) * - `StructWithRest.Encoded` — encoded type * @@ -2797,12 +3452,20 @@ export function Record( */ export declare namespace StructWithRest { /** + * Constraint for object-like schemas that can be used as the fixed portion of a + * `StructWithRest` schema. + * + * @category utility types * @since 4.0.0 */ - export type Objects = Top & { readonly ast: AST.Objects } + export type Objects = Top & { readonly ast: SchemaAST.Objects } /** - * @since 4.0.0 + * Readonly list of record schemas that provide the additional index signatures + * for a `StructWithRest` schema. + * + * @category utility types + * @since 3.10.0 */ export type Records = ReadonlyArray<$Record> @@ -2810,53 +3473,122 @@ export declare namespace StructWithRest { Head & MergeTuple : {} + type Intersect< + S extends Objects, + Records extends StructWithRest.Records, + Side extends "Type" | "Iso" | "Encoded" | "~type.make" + > = + & S[Side] + & MergeTuple<{ readonly [K in keyof Records]: Records[K][Side] }> + /** - * @since 4.0.0 + * Computes the decoded type for `StructWithRest` by intersecting the base object + * schema's decoded `Type` with the decoded types of all rest record schemas. + * + * @category utility types + * @since 3.10.0 */ - export type Type = - & S["Type"] - & MergeTuple<{ readonly [K in keyof Records]: Records[K]["Type"] }> + export type Type = Intersect /** + * Computes the iso type for `StructWithRest` by intersecting the base object + * schema's `Iso` type with the `Iso` types of all rest record schemas. + * + * @category utility types * @since 4.0.0 */ - export type Iso = - & S["Iso"] - & MergeTuple<{ readonly [K in keyof Records]: Records[K]["Iso"] }> + export type Iso = Intersect + + /** + * Computes the encoded type for `StructWithRest` by intersecting the base object + * schema's encoded type with the encoded types of all rest record schemas. + * + * @category utility types + * @since 3.10.0 + */ + export type Encoded = Intersect /** + * Computes the input type accepted when constructing a `StructWithRest` value by + * intersecting the base object's make input with the make inputs of all rest + * record schemas. + * + * @category utility types * @since 4.0.0 */ - export type Encoded = - & S["Encoded"] - & MergeTuple<{ readonly [K in keyof Records]: Records[K]["Encoded"] }> + export type MakeIn = Intersect + + type Services< + S extends Objects, + Records extends StructWithRest.Records, + Side extends "DecodingServices" | "EncodingServices" + > = + | S[Side] + | { [K in keyof Records]: Records[K][Side] }[number] /** + * Union of the decoding service requirements of the base object schema and all + * rest record schemas. + * + * @category utility types * @since 4.0.0 */ - export type DecodingServices = - | S["DecodingServices"] - | { [K in keyof Records]: Records[K]["DecodingServices"] }[number] + export type DecodingServices = Services< + S, + Records, + "DecodingServices" + > /** + * Union of the encoding service requirements of the base object schema and all + * rest record schemas. + * + * @category utility types * @since 4.0.0 */ - export type EncodingServices = - | S["EncodingServices"] - | { [K in keyof Records]: Records[K]["EncodingServices"] }[number] + export type EncodingServices = Services< + S, + Records, + "EncodingServices" + > + + type IncompatibleKeys> = { + [K in OK]: Required>[K] extends B[K] ? never : K + }[OK] + + type IncompatibleSideKeys< + S extends Objects, + Records extends StructWithRest.Records, + Side extends "Type" | "Encoded" | "Iso" | "~type.make" + > = { + [I in keyof Records]: Records[I][Side] extends object ? IncompatibleKeys : never + }[number] /** + * Validates that the records are compatible with the struct. + * + * @category utility types * @since 4.0.0 */ - export type MakeIn = - & S["~type.make"] - & MergeTuple<{ readonly [K in keyof Records]: Records[K]["~type.make"] }> + export type ValidateRecords = [ + | IncompatibleSideKeys + | IncompatibleSideKeys + | IncompatibleSideKeys + | IncompatibleSideKeys + ] extends [never] ? unknown + : { + "incompatible index signatures": + | IncompatibleSideKeys + | IncompatibleSideKeys + | IncompatibleSideKeys + | IncompatibleSideKeys + } } /** - * Companion type for a struct combined with one or more record schemas. Produced - * by {@link StructWithRest}. + * Type-level representation returned by {@link StructWithRest}. * + * @category models * @since 4.0.0 */ export interface StructWithRest< @@ -2868,7 +3600,7 @@ export interface StructWithRest< Simplify>, StructWithRest.DecodingServices, StructWithRest.EncodingServices, - AST.Objects, + SchemaAST.Objects, StructWithRest, Simplify>, Simplify> @@ -2889,14 +3621,14 @@ export interface StructWithRest< * * const schema = Schema.StructWithRest( * Schema.Struct({ id: Schema.Number }), - * [Schema.Record(Schema.String, Schema.String)] + * [Schema.Record(Schema.String, Schema.Number)] * ) * - * // { readonly id: number } & { readonly [x: string]: string } + * // { readonly id: number, readonly [x: string]: number } * type T = typeof schema.Type * ``` * - * @category Constructors + * @category constructors * @since 4.0.0 */ export function StructWithRest< @@ -2904,24 +3636,30 @@ export function StructWithRest< const Records extends StructWithRest.Records >( schema: S, - records: Records + records: Records & StructWithRest.ValidateRecords ): StructWithRest { - return make(AST.structWithRest(schema.ast, records.map(AST.getAST)), { schema, records }) + return make(SchemaAST.structWithRest(schema.ast, records.map(SchemaAST.getAST)), { schema, records }) } /** * Namespace for `Tuple` type utilities. * + * **Details** + * * - `Tuple.Elements` — constraint for the element schema array * - `Tuple.Type` — decoded tuple type * - `Tuple.Encoded` — encoded tuple type * - `Tuple.MakeIn` — constructor input tuple * - * @since 4.0.0 + * @since 3.10.0 */ export declare namespace Tuple { /** - * @since 4.0.0 + * Constraint for the readonly array of element schemas used to define a + * fixed-length `Tuple` schema. + * + * @category utility types + * @since 3.10.0 */ export type Elements = ReadonlyArray @@ -2936,7 +3674,15 @@ export declare namespace Tuple { : Out /** - * @since 4.0.0 + * Computes the decoded tuple type for a tuple element schema array. + * + * **Details** + * + * Each element contributes its decoded `Type`; optional element schemas produce + * optional tuple positions. + * + * @category utility types + * @since 3.10.0 */ export type Type = Type_ @@ -2951,6 +3697,10 @@ export declare namespace Tuple { : Out /** + * Computes the iso tuple type for a tuple element schema array from each + * element schema's `Iso` type. + * + * @category utility types * @since 4.0.0 */ export type Iso = Iso_ @@ -2966,16 +3716,32 @@ export declare namespace Tuple { : Out /** - * @since 4.0.0 + * Computes the encoded tuple type for a tuple element schema array. + * + * **Details** + * + * Each element contributes its `Encoded` type; encoded-side optional element + * schemas produce optional tuple positions. + * + * @category utility types + * @since 3.10.0 */ export type Encoded = Encoded_ /** + * Union of all decoding service requirements needed by the tuple element + * schemas. + * + * @category utility types * @since 4.0.0 */ export type DecodingServices = E[number]["DecodingServices"] /** + * Union of all encoding service requirements needed by the tuple element + * schemas. + * + * @category utility types * @since 4.0.0 */ export type EncodingServices = E[number]["EncodingServices"] @@ -2993,15 +3759,24 @@ export declare namespace Tuple { Out /** + * Computes the input tuple type accepted when constructing a tuple value. + * + * **Details** + * + * Each element uses its `~type.make` input type. Optional elements and elements + * with constructor defaults produce optional tuple positions. + * + * @category utility types * @since 4.0.0 */ export type MakeIn = MakeIn_ } /** - * Companion type for a fixed-length tuple. Produced by {@link Tuple}. + * Type-level representation returned by {@link Tuple}. * - * @since 4.0.0 + * @category models + * @since 3.10.0 */ export interface Tuple extends Bottom< @@ -3009,7 +3784,7 @@ export interface Tuple extends Tuple.Encoded, Tuple.DecodingServices, Tuple.EncodingServices, - AST.Arrays, + SchemaAST.Arrays, Tuple, Tuple.MakeIn, Tuple.Iso @@ -3019,7 +3794,9 @@ export interface Tuple extends /** * Returns a new tuple with the elements modified by the provided function. * - * **Options** + * **Details** + * + * Options: * * - `unsafePreserveChecks` - if `true`, keep any `.check(...)` constraints * that were attached to the original union. Defaults to `false`. @@ -3038,7 +3815,7 @@ export interface Tuple extends ): Tuple>> } -function makeTuple(ast: AST.Arrays, elements: Elements): Tuple { +function makeTuple(ast: SchemaAST.Arrays, elements: Elements): Tuple { return make(ast, { elements, mapElements( @@ -3049,7 +3826,7 @@ function makeTuple(ast: AST.Arrays, elements: E } | undefined ): Tuple>> { const elements = f(this.elements) - return makeTuple(AST.tuple(elements, options?.unsafePreserveChecks ? this.ast.checks : undefined), elements) + return makeTuple(SchemaAST.tuple(elements, options?.unsafePreserveChecks ? this.ast.checks : undefined), elements) } }) } @@ -3069,16 +3846,18 @@ function makeTuple(ast: AST.Arrays, elements: E * // [ 'hello', 42 ] * ``` * - * @category Constructors - * @since 4.0.0 + * @category constructors + * @since 3.10.0 */ export function Tuple>(elements: Elements): Tuple { - return makeTuple(AST.tuple(elements), elements) + return makeTuple(SchemaAST.tuple(elements), elements) } /** * Namespace for `TupleWithRest` type utilities. * + * **Details** + * * - `TupleWithRest.TupleType` — constraint for the leading tuple schema * - `TupleWithRest.Rest` — the rest element schema(s) * - `TupleWithRest.Type` — decoded type (fixed elements + rest) @@ -3088,23 +3867,44 @@ export function Tuple>(elements: Eleme */ export declare namespace TupleWithRest { /** - * @since 4.0.0 + * Constraint for tuple-like schemas that can be used as the fixed leading + * portion of a `TupleWithRest` schema. + * + * @category utility types + * @since 3.10.0 */ export type TupleType = Top & { readonly Type: ReadonlyArray readonly Encoded: ReadonlyArray - readonly ast: AST.Arrays + readonly ast: SchemaAST.Arrays readonly "~type.make": ReadonlyArray readonly "Iso": ReadonlyArray } /** - * @since 4.0.0 + * Non-empty list of schemas used for the rest portion of a `TupleWithRest`. + * + * **Details** + * + * The first schema describes the repeated rest element. Additional schemas, when + * present, describe trailing tuple elements after the repeated rest segment. + * + * @category utility types + * @since 3.10.0 */ export type Rest = readonly [Top, ...Array] /** - * @since 4.0.0 + * Computes the decoded tuple type for a `TupleWithRest`. + * + * **Details** + * + * The output starts with the fixed tuple elements, continues with zero or more + * values decoded by the first rest schema, and includes any trailing rest schemas + * as fixed tuple positions. + * + * @category utility types + * @since 3.10.0 */ export type Type, Rest extends TupleWithRest.Rest> = Rest extends readonly [infer Head extends Top, ...infer Tail extends ReadonlyArray] ? Readonly<[ @@ -3115,6 +3915,15 @@ export declare namespace TupleWithRest { T /** + * Computes the iso tuple type for a `TupleWithRest`. + * + * **Details** + * + * The output starts with the fixed tuple's `Iso` elements, continues with zero + * or more values using the first rest schema's `Iso`, and includes any trailing + * rest schemas as fixed tuple positions. + * + * @category utility types * @since 4.0.0 */ export type Iso, Rest extends TupleWithRest.Rest> = Rest extends @@ -3126,7 +3935,16 @@ export declare namespace TupleWithRest { T /** - * @since 4.0.0 + * Computes the encoded tuple type for `TupleWithRest`. + * + * **Details** + * + * The leading tuple's encoded elements are kept first. The encoded type of the + * first rest schema may repeat zero or more times, and the encoded types of any + * additional rest schemas become required trailing tuple elements. + * + * @category utility types + * @since 3.10.0 */ export type Encoded, Rest extends TupleWithRest.Rest> = Rest extends readonly [infer Head extends Top, ...infer Tail extends ReadonlyArray] ? readonly [ @@ -3137,6 +3955,15 @@ export declare namespace TupleWithRest { E /** + * Computes the constructor input tuple type for `TupleWithRest`. + * + * **Details** + * + * The leading tuple's make input elements are kept first. The make input type of + * the first rest schema may repeat zero or more times, and the make input types + * of any additional rest schemas become required trailing tuple elements. + * + * @category utility types * @since 4.0.0 */ export type MakeIn, Rest extends TupleWithRest.Rest> = Rest extends @@ -3149,9 +3976,9 @@ export declare namespace TupleWithRest { } /** - * Companion type for a tuple with additional rest elements. Produced by - * {@link TupleWithRest}. + * Type-level representation returned by {@link TupleWithRest}. * + * @category models * @since 4.0.0 */ export interface TupleWithRest< @@ -3163,7 +3990,7 @@ export interface TupleWithRest< TupleWithRest.Encoded, S["DecodingServices"] | Rest[number]["DecodingServices"], S["EncodingServices"] | Rest[number]["EncodingServices"], - AST.Arrays, + SchemaAST.Arrays, TupleWithRest, TupleWithRest.MakeIn, TupleWithRest.Iso @@ -3174,9 +4001,15 @@ export interface TupleWithRest< } /** - * Extends a fixed-length tuple schema with rest elements, creating a variadic - * tuple that starts with the fixed elements and ends with zero or more rest - * elements. + * Extends a fixed-length tuple schema with a variadic rest segment. + * + * **Details** + * + * The resulting tuple starts with the fixed elements from `schema`. The first + * schema in `rest` is the repeatable element schema, and any additional schemas + * in `rest` are required trailing tuple elements after the variadic segment. For + * example, `[Schema.Boolean, Schema.String]` represents zero or more booleans + * followed by a final string. * * **Example** (Tuple with rest) * @@ -3194,19 +4027,20 @@ export interface TupleWithRest< * // [ 'hello', 1, true, false ] * ``` * - * @category Constructors + * @category constructors * @since 4.0.0 */ export function TupleWithRest, const Rest extends TupleWithRest.Rest>( schema: S, rest: Rest ): TupleWithRest { - return make(AST.tupleWithRest(schema.ast, rest.map(AST.getAST)), { schema, rest }) + return make(SchemaAST.tupleWithRest(schema.ast, rest.map(SchemaAST.getAST)), { schema, rest }) } /** - * Companion type for a `ReadonlyArray`. Produced by {@link ArraySchema}. + * Type-level representation returned by {@link Array}. * + * @category models * @since 4.0.0 */ export interface $Array extends @@ -3215,13 +4049,13 @@ export interface $Array extends ReadonlyArray, S["DecodingServices"], S["EncodingServices"], - AST.Arrays, + SchemaAST.Arrays, $Array, ReadonlyArray, ReadonlyArray > { - readonly schema: S + readonly value: S } interface ArrayLambda extends Lambda { @@ -3230,10 +4064,12 @@ interface ArrayLambda extends Lambda { } /** - * @category Constructors + * @category constructors * @since 4.0.0 */ -const ArraySchema = Struct_.lambda((schema) => make(new AST.Arrays(false, [], [schema.ast]), { schema })) +const ArraySchema = Struct_.lambda((schema) => + make(new SchemaAST.Arrays(false, [], [schema.ast]), { value: schema }) +) export { /** @@ -3251,16 +4087,17 @@ export { * // [ 'a', 'b', 'c' ] * ``` * - * @category Constructors + * @category constructors * @since 4.0.0 */ ArraySchema as Array } /** - * Companion type for a non-empty `ReadonlyArray`. Produced by {@link NonEmptyArray}. + * Type-level representation returned by {@link NonEmptyArray}. * - * @since 4.0.0 + * @category models + * @since 3.10.0 */ export interface NonEmptyArray extends Bottom< @@ -3268,13 +4105,13 @@ export interface NonEmptyArray extends readonly [S["Encoded"], ...Array], S["DecodingServices"], S["EncodingServices"], - AST.Arrays, + SchemaAST.Arrays, NonEmptyArray, readonly [S["~type.make"], ...Array], readonly [S["Iso"], ...Array] > { - readonly schema: S + readonly value: S } interface NonEmptyArrayLambda extends Lambda { @@ -3297,39 +4134,53 @@ interface NonEmptyArrayLambda extends Lambda { * Schema.decodeUnknownSync(schema)([]) // throws * ``` * - * @category Constructors - * @since 4.0.0 + * @category constructors + * @since 3.10.0 */ export const NonEmptyArray = Struct_.lambda((schema) => - make(new AST.Arrays(false, [schema.ast], [schema.ast]), { schema }) + make(new SchemaAST.Arrays(false, [schema.ast], [schema.ast]), { value: schema }) ) /** - * @category Arrays - * @since 4.0.0 + * Type-level representation returned by {@link ArrayEnsure}. + * + * @category constructors + * @since 3.10.0 */ export interface ArrayEnsure extends decodeTo<$Array>, Union]>> { readonly "Rebuild": ArrayEnsure } /** - * Decodes a single value or an array of values into an array. + * Creates a schema that accepts either a value decoded by `schema` or an array + * decoded by `Schema.Array(schema)`, then returns an array. * - * Decoding: - * - a single value is decoded as a one-element array - * - an array is decoded as-is + * **When to use** * - * Encoding: - * - a one-element array is encoded as a single value - * - arrays with more than one element are encoded as arrays + * Use to accept input that may be provided either as one item or as an array, + * while normalizing decoded values to a readonly array. * - * @category Arrays - * @since 4.0.0 + * **Details** + * + * During encoding, one-element arrays are encoded as the single element. Empty + * arrays and arrays with two or more elements are encoded as arrays. + * + * **Gotchas** + * + * The single-value branch is tried before the array branch. If `schema` itself + * accepts arrays, an array input can be treated as one value and wrapped in a + * one-element array. + * + * @see {@link Array} for accepting only array input + * @see {@link NonEmptyArray} for requiring at least one decoded element + * + * @category constructors + * @since 3.10.0 */ export function ArrayEnsure(schema: S): ArrayEnsure { return Union([schema, ArraySchema(schema)]).pipe(decodeTo( ArraySchema(toType(schema)), - Transformation.transform({ + SchemaTransformation.transform({ decode: Arr.ensure, encode: (array) => array.length === 1 ? array[0] : array }) @@ -3337,8 +4188,9 @@ export function ArrayEnsure(schema: S): ArrayEnsure { } /** - * Companion type for an array with unique elements. Produced by {@link UniqueArray}. + * Type-level representation returned by {@link UniqueArray}. * + * @category models * @since 4.0.0 */ export interface UniqueArray extends $Array { @@ -3348,10 +4200,12 @@ export interface UniqueArray extends $Array { /** * Returns a new array schema that ensures all elements are unique. * + * **Details** + * * The equivalence used to determine uniqueness is the one provided by * `Schema.toEquivalence(item)`. * - * @category Constructors + * @category constructors * @since 4.0.0 */ export function UniqueArray(item: S): UniqueArray { @@ -3359,12 +4213,12 @@ export function UniqueArray(item: S): UniqueArray { } /** - * Schema type that makes array or tuple elements mutable (removes `readonly`). - * Produced by {@link mutable}. + * Type-level representation returned by {@link mutable}. * - * @since 4.0.0 + * @category transforming + * @since 3.10.0 */ -export interface mutable extends +export interface mutable extends Bottom< Mutable, Mutable, @@ -3388,8 +4242,9 @@ export interface mutable extends } interface mutableLambda extends Lambda { - (self: S): mutable - readonly "~lambda.out": this["~lambda.in"] extends Top & { readonly "ast": AST.Arrays } ? mutable + (self: S): mutable + readonly "~lambda.out": this["~lambda.in"] extends Top & { readonly "ast": SchemaAST.Arrays } ? + mutable : "Error: schema not eligible for mutable" } @@ -3407,16 +4262,18 @@ interface mutableLambda extends Lambda { * type T = typeof schema.Type * ``` * - * @since 4.0.0 + * @category transforming + * @since 3.10.0 */ export const mutable = Struct_.lambda((schema) => { - return make(new AST.Arrays(true, schema.ast.elements, schema.ast.rest), { schema }) + return make(new SchemaAST.Arrays(true, schema.ast.elements, schema.ast.rest), { schema }) }) /** - * Companion type for a union of multiple schemas. Produced by {@link Union}. + * Type-level representation returned by {@link Union}. * - * @since 4.0.0 + * @category models + * @since 3.10.0 */ export interface Union> extends Bottom< @@ -3424,7 +4281,7 @@ export interface Union> extends { [K in keyof Members]: Members[K]["Encoded"] }[number], { [K in keyof Members]: Members[K]["DecodingServices"] }[number], { [K in keyof Members]: Members[K]["EncodingServices"] }[number], - AST.Union<{ [K in keyof Members]: Members[K]["ast"] }[number]>, + SchemaAST.Union<{ [K in keyof Members]: Members[K]["ast"] }[number]>, Union, { [K in keyof Members]: Members[K]["~type.make"] }[number], { [K in keyof Members]: Members[K]["Iso"] }[number] @@ -3434,7 +4291,9 @@ export interface Union> extends /** * Returns a new union with the members modified by the provided function. * - * **Options** + * **Details** + * + * Options: * * - `unsafePreserveChecks` - if `true`, keep any `.check(...)` constraints * that were attached to the original union. Defaults to `false`. @@ -3454,7 +4313,7 @@ export interface Union> extends } function makeUnion>( - ast: AST.Union, + ast: SchemaAST.Union, members: Members ): Union { return make(ast, { @@ -3468,7 +4327,7 @@ function makeUnion>( ): Union>> { const members = f(this.members) return makeUnion( - AST.union(members, this.ast.mode, options?.unsafePreserveChecks ? this.ast.checks : undefined), + SchemaAST.union(members, this.ast.mode, options?.unsafePreserveChecks ? this.ast.checks : undefined), members ) } @@ -3479,6 +4338,8 @@ function makeUnion>( * Creates a union schema from an array of member schemas. Members are tested in * order; the first match is returned. * + * **Details** + * * Optionally, specify `mode`: * - `"anyOf"` (default) — matches if any member matches. * - `"oneOf"` — matches if exactly one member matches. @@ -3494,24 +4355,24 @@ function makeUnion>( * Schema.decodeUnknownSync(schema)(42) // 42 * ``` * - * @category Constructors - * @since 4.0.0 + * @category constructors + * @since 3.10.0 */ export function Union>( members: Members, options?: { mode?: "anyOf" | "oneOf" } ): Union { - return makeUnion(AST.union(members, options?.mode ?? "anyOf", undefined), members) + return makeUnion(SchemaAST.union(members, options?.mode ?? "anyOf", undefined), members) } /** - * Represents a union schema of multiple literal values. + * Type-level representation returned by {@link Literals}. * - * @see {@link Literals} for the constructor function. + * @category models * @since 4.0.0 */ -export interface Literals> - extends Bottom, Literals> +export interface Literals> + extends Bottom, Literals> { readonly literals: L readonly members: { readonly [K in keyof L]: Literal } @@ -3522,7 +4383,7 @@ export interface Literals> pick>(literals: L2): Literals - transform( + transform( to: L2 ): Union<{ [I in keyof L]: decodeTo, Literal> }> } @@ -3531,6 +4392,7 @@ export interface Literals> * Creates a union schema from an array of literal values. * * **Example** (Status codes) + * * ```ts * import { Schema } from "effect" * @@ -3539,12 +4401,12 @@ export interface Literals> * ``` * * @see {@link Literal} for a schema that represents a single literal. - * @category Constructors + * @category constructors * @since 4.0.0 */ -export function Literals>(literals: L): Literals { +export function Literals>(literals: L): Literals { const members = literals.map(Literal) as { readonly [K in keyof L]: Literal } - return make(AST.union(members, "anyOf", undefined), { + return make(SchemaAST.union(members, "anyOf", undefined), { literals, members, mapMembers>( @@ -3556,7 +4418,7 @@ export function Literals>(litera pick>(literals: L2): Literals { return Literals(literals) }, - transform( + transform( to: L2 ): Union<{ [I in keyof L]: decodeTo, Literal> }> { return Union(members.map((member, index) => member.transform(to[index]))) as any @@ -3565,9 +4427,10 @@ export function Literals>(litera } /** - * Companion type for `S | null`. Produced by {@link NullOr}. + * Type-level representation returned by {@link NullOr}. * - * @since 4.0.0 + * @category models + * @since 3.10.0 */ export interface NullOr extends Union { readonly "Rebuild": NullOr @@ -3581,15 +4444,16 @@ interface NullOrLambda extends Lambda { /** * Creates a union schema of `S | null`. * - * @category Constructors - * @since 4.0.0 + * @category constructors + * @since 3.10.0 */ export const NullOr = Struct_.lambda((self) => Union([self, Null])) /** - * Companion type for `S | undefined`. Produced by {@link UndefinedOr}. + * Type-level representation returned by {@link UndefinedOr}. * - * @since 4.0.0 + * @category models + * @since 3.10.0 */ export interface UndefinedOr extends Union { readonly "Rebuild": UndefinedOr @@ -3603,14 +4467,16 @@ interface UndefinedOrLambda extends Lambda { /** * Creates a union schema of `S | undefined`. * - * @category Constructors - * @since 4.0.0 + * @category constructors + * @since 3.10.0 */ export const UndefinedOr = Struct_.lambda((self) => Union([self, Undefined])) /** - * Companion type for `S | null | undefined`. Produced by {@link NullishOr}. - * @since 4.0.0 + * Type-level representation returned by {@link NullishOr}. + * + * @category models + * @since 3.10.0 */ export interface NullishOr extends Union { readonly "Rebuild": NullishOr @@ -3623,14 +4489,17 @@ interface NullishOrLambda extends Lambda { /** * Creates a union schema of `S | null | undefined`. - * @category Constructors - * @since 4.0.0 + * + * @category constructors + * @since 3.10.0 */ export const NullishOr = Struct_.lambda((self) => Union([self, Null, Undefined])) /** - * Schema type wrapping a lazily-evaluated schema. Produced by {@link suspend}. - * @since 4.0.0 + * Type-level representation returned by {@link suspend}. + * + * @category models + * @since 3.10.0 */ export interface suspend extends Bottom< @@ -3638,7 +4507,7 @@ export interface suspend extends S["Encoded"], S["DecodingServices"], S["EncodingServices"], - AST.Suspend, + SchemaAST.Suspend, suspend, S["~type.make.in"], S["Iso"], @@ -3658,6 +4527,7 @@ export interface suspend extends * preventing infinite recursion during schema definition. * * **Example** (Recursive tree schema) + * * ```ts * import { Schema } from "effect" * @@ -3672,18 +4542,19 @@ export interface suspend extends * }) * ``` * - * @category Constructors - * @since 4.0.0 + * @category constructors + * @since 3.10.0 */ export function suspend(f: () => S): suspend { - return make(new AST.Suspend(() => f().ast)) + return make(new SchemaAST.Suspend(() => f().ast)) } /** - * Pipeable function that attaches one or more filter checks to a schema without - * changing the TypeScript type. + * Attaches one or more filter checks to a schema without changing the + * TypeScript type. * * **Example** (Adding checks to a schema) + * * ```ts * import { Schema } from "effect" * @@ -3692,18 +4563,20 @@ export function suspend(f: () => S): suspend { * ) * ``` * - * @category Filtering + * @category filtering * @since 4.0.0 */ -export function check(...checks: readonly [AST.Check, ...Array>]) { +export function check( + ...checks: readonly [SchemaAST.Check, ...Array>] +) { return (self: S): S["Rebuild"] => self.check(...checks) } /** - * The output type of {@link refine}, narrowing the schema's `Type` to `T` via a - * type guard. + * Type-level representation returned by {@link refine}. * - * @since 4.0.0 + * @category filtering + * @since 3.10.0 */ export interface refine extends Bottom< @@ -3731,24 +4604,32 @@ export interface refine extends * Narrows the TypeScript type of a schema's output via a type guard predicate, * attaching the guard as a runtime filter check. * - * @category Filtering - * @since 4.0.0 + * **Details** + * + * The `annotations` parameter annotates the filter created by the refinement. + * With the default formatter, failed refinements use `message` first, + * `expected` second, and `` when neither is provided. `identifier` + * names type-level failures before the refinement runs; it does not name the + * failed refinement itself. + * + * @category filtering + * @since 3.10.0 */ export function refine( refinement: (value: S["Type"]) => value is T, annotations?: Annotations.Filter ) { return (schema: S): refine => - make(AST.appendChecks(schema.ast, [AST.makeFilterByGuard(refinement, annotations)]), { schema }) + make(SchemaAST.appendChecks(schema.ast, [SchemaAST.makeFilterByGuard(refinement, annotations)]), { schema }) } type DistributeBrands = UnionToIntersection : never> /** - * The output type of {@link brand}, intersecting the schema's `Type` with one or - * more {@link Brand.Brand} tags. + * Type-level representation returned by {@link brand}. * - * @since 4.0.0 + * @category branding + * @since 3.10.0 */ export interface brand extends Bottom< @@ -3777,20 +4658,32 @@ export interface brand extends * Adds a nominal brand to a schema, intersecting the output type with * `Brand.Brand` to prevent accidental mixing of structurally identical types. * - * @category Branding - * @since 4.0.0 + * **When to use** + * + * Use to make values decoded by an existing schema nominally distinct when the + * schema already carries the runtime validation you need. + * + * **Gotchas** + * + * `brand` adds brand metadata and narrows the TypeScript output type, but it + * does not add runtime checks. + * + * @see {@link fromBrand} for applying a Brand constructor's checks along with the brand tag + * + * @category branding + * @since 3.10.0 */ export function brand(identifier: B) { return (schema: S): brand => - make(AST.brand(schema.ast, identifier), { schema, identifier }) + make(SchemaAST.brand(schema.ast, identifier), { schema, identifier }) } /** * Creates a branded schema from a {@link Brand.Constructor}, applying the * constructor's checks and brand tag to the underlying schema. * - * @category Branding - * @since 4.0.0 + * @category branding + * @since 3.10.0 */ export function fromBrand>(identifier: string, ctor: Brand.Constructor) { return }>( @@ -3801,12 +4694,9 @@ export function fromBrand>(identifier: string, ctor: } /** - * A schema that wraps another schema and intercepts its decoding pipeline. - * - * The interceptor receives the full decoding `Effect` and may replace, modify, - * or augment it — including adding service requirements via `RD`. + * Type-level representation returned by {@link middlewareDecoding}. * - * @see {@link middlewareDecoding} for the constructor + * @category decoding * @since 4.0.0 */ export interface middlewareDecoding extends @@ -3834,6 +4724,8 @@ export interface middlewareDecoding extends /** * Intercepts the decoding pipeline of a schema. * + * **Details** + * * The provided function receives the current decoding `Effect` and `ParseOptions`, * and returns a new `Effect` — potentially adding service requirements (`RD`), * recovering from errors, or augmenting the result. @@ -3851,28 +4743,26 @@ export interface middlewareDecoding extends * ``` * * @see {@link catchDecoding} for a simpler error-recovery variant + * @category decoding * @since 4.0.0 */ export function middlewareDecoding( decode: ( - effect: Effect.Effect, Issue.Issue, S["DecodingServices"]>, - options: AST.ParseOptions - ) => Effect.Effect, Issue.Issue, RD> + effect: Effect.Effect, SchemaIssue.Issue, S["DecodingServices"]>, + options: SchemaAST.ParseOptions + ) => Effect.Effect, SchemaIssue.Issue, RD> ) { return (schema: S): middlewareDecoding => make( - AST.middlewareDecoding(schema.ast, new Transformation.Middleware(decode, identity)), + SchemaAST.middlewareDecoding(schema.ast, new SchemaTransformation.Middleware(decode, identity)), { schema } ) } /** - * A schema that wraps another schema and intercepts its encoding pipeline. - * - * The interceptor receives the full encoding `Effect` and may replace, modify, - * or augment it — including adding service requirements via `RE`. + * Type-level representation returned by {@link middlewareEncoding}. * - * @see {@link middlewareEncoding} for the constructor + * @category encoding * @since 4.0.0 */ export interface middlewareEncoding extends @@ -3900,6 +4790,8 @@ export interface middlewareEncoding extends /** * Intercepts the encoding pipeline of a schema. * + * **Details** + * * The provided function receives the current encoding `Effect` and `ParseOptions`, * and returns a new `Effect` — potentially adding service requirements (`RE`), * recovering from errors, or augmenting the result. @@ -3917,17 +4809,18 @@ export interface middlewareEncoding extends * ``` * * @see {@link catchEncoding} for a simpler error-recovery variant + * @category encoding * @since 4.0.0 */ export function middlewareEncoding( encode: ( - effect: Effect.Effect, Issue.Issue, S["EncodingServices"]>, - options: AST.ParseOptions - ) => Effect.Effect, Issue.Issue, RE> + effect: Effect.Effect, SchemaIssue.Issue, S["EncodingServices"]>, + options: SchemaAST.ParseOptions + ) => Effect.Effect, SchemaIssue.Issue, RE> ) { return (schema: S): middlewareEncoding => make( - AST.middlewareEncoding(schema.ast, new Transformation.Middleware(identity, encode)), + SchemaAST.middlewareEncoding(schema.ast, new SchemaTransformation.Middleware(identity, encode)), { schema } ) } @@ -3935,6 +4828,8 @@ export function middlewareEncoding( /** * Recovers from a decoding error by providing a fallback value. * + * **Details** + * * The handler receives the `Issue` and returns an `Effect` that either * succeeds with a fallback value or re-fails with a (possibly different) issue. * @@ -3949,21 +4844,37 @@ export function middlewareEncoding( * ``` * * @see {@link catchDecodingWithContext} to add service requirements to the handler + * @category error handling * @since 4.0.0 */ export function catchDecoding( - f: (issue: Issue.Issue) => Effect.Effect, Issue.Issue> + f: (issue: SchemaIssue.Issue) => Effect.Effect, SchemaIssue.Issue> ): (self: S) => S["Rebuild"] { return catchDecodingWithContext(f) } /** - * Like {@link catchDecoding}, but the handler may require Effect services (`R`). + * Recovers from a decoding error with a handler that may require Effect services. + * + * **When to use** + * + * Use when you need decoding fallback logic to require services from the Effect + * context. * + * **Details** + * + * The handler receives the `Issue` and returns an `Effect` that either succeeds + * with a fallback value or re-fails with a (possibly different) issue. The + * handler's services are added to the schema's decoding services. + * + * @see {@link catchDecoding} for recovery handlers that do not require services + * @see {@link middlewareDecoding} for intercepting or replacing the full decoding pipeline + * + * @category error handling * @since 4.0.0 */ export function catchDecodingWithContext( - f: (issue: Issue.Issue) => Effect.Effect, Issue.Issue, R> + f: (issue: SchemaIssue.Issue) => Effect.Effect, SchemaIssue.Issue, R> ) { return (self: S): middlewareDecoding => self.pipe(middlewareDecoding(Effect.catchEager(f))) @@ -3972,37 +4883,52 @@ export function catchDecodingWithContext( /** * Recovers from an encoding error by providing a fallback value. * + * **Details** + * * The handler receives the `Issue` and returns an `Effect` that either * succeeds with a fallback value or re-fails with a (possibly different) issue. * * @see {@link catchEncodingWithContext} to add service requirements to the handler + * @category error handling * @since 4.0.0 */ export function catchEncoding( - f: (issue: Issue.Issue) => Effect.Effect, Issue.Issue> + f: (issue: SchemaIssue.Issue) => Effect.Effect, SchemaIssue.Issue> ): (self: S) => S["Rebuild"] { return catchEncodingWithContext(f) } /** - * Like {@link catchEncoding}, but the handler may require Effect services (`R`). + * Recovers from an encoding error with a handler that may require Effect services. + * + * **When to use** + * + * Use when you need encoding fallback logic to require services from the Effect + * context. + * + * **Details** + * + * The handler receives the `Issue` and returns an `Effect` that either succeeds + * with a fallback encoded value or re-fails with a (possibly different) issue. + * The handler's services are added to the schema's encoding services. * + * @see {@link catchEncoding} for recovery handlers that do not require services + * @see {@link middlewareEncoding} for intercepting or replacing the full encoding pipeline + * + * @category error handling * @since 4.0.0 */ export function catchEncodingWithContext( - f: (issue: Issue.Issue) => Effect.Effect, Issue.Issue, R> + f: (issue: SchemaIssue.Issue) => Effect.Effect, SchemaIssue.Issue, R> ) { return (self: S): middlewareEncoding => self.pipe(middlewareEncoding(Effect.catchEager(f))) } /** - * The type produced by {@link decodeTo} when a custom transformation is provided. - * - * - `Type` is `To["Type"]`, `Encoded` is `From["Encoded"]` - * - Decoding services from both `from` and `to` are combined + * Type-level representation returned by {@link decodeTo}. * - * @see {@link compose} for the passthrough (no transformation) variant + * @category transforming * @since 4.0.0 */ export interface decodeTo extends @@ -4029,36 +4955,38 @@ export interface decodeTo extends decodeTo {} /** * Creates a schema that transforms from a source schema to a target schema. * - * This is a curried function: call it with the target schema `to` (and optionally a transformation), - * then call the returned function with the source schema `from`. The resulting schema decodes from - * `From["Encoded"]` to `To["Type"]` and encodes from `To["Type"]` back to `From["Encoded"]`. + * **When to use** + * + * Use when decoding should change the schema's decoded type or encoded shape, + * with an optional custom bidirectional transformation. + * + * **Details** + * + * Call it with the target schema `to` and then pipe the source schema `from` + * into the returned function. The resulting schema decodes from + * `From["Encoded"]` to `To["Type"]` and encodes from `To["Type"]` back to + * `From["Encoded"]`. + * + * When no transformation is provided, `SchemaTransformation.passthrough()` is + * used, so `From["Type"]` must already be compatible with `To["Encoded"]`. + * The resulting schema combines decoding and encoding services from both + * schemas and any custom transformation. * - * **Key guarantees:** - * - Resulting schema has `Type = To["Type"]` and `Encoded = From["Encoded"]` - * - When `transformation` is omitted, uses `Transformation.passthrough()` (schema composition) - * - Combines decoding/encoding services from both `from` and `to` schemas - * - Transformation `decode` maps `From["Type"]` → `To["Encoded"]` (used during encoding) - * - Transformation `encode` maps `To["Encoded"]` → `From["Type"]` (used during decoding) + * **Gotchas** * - * **AI note - Common mistakes:** - * - **Direction confusion**: Remember `to` is the target (what you decode TO), `from` is the source (what you decode FROM) - * - **Currying**: This is curried - must use pipe: `from.pipe(Schema.decodeTo(to))` - * - **Transformation direction**: `decode` goes `From["Type"]` → `To["Encoded"]`, `encode` goes `To["Encoded"]` → `From["Type"]` - * - **Passthrough assumption**: Without transformation, schemas must satisfy `To["Encoded"] === From["Type"]` or use passthrough helpers - * - **Service dependencies**: Resulting schema requires services from both schemas; use `Schema.provideService` if needed + * In a custom transformation, `decode` maps `From["Type"]` to `To["Encoded"]` + * and is used on the encoding path, while `encode` maps `To["Encoded"]` to + * `From["Type"]` and is used on the decoding path. * * **Example** (String to Number with transformation) * @@ -4079,29 +5007,30 @@ export interface compose extends decodeTo(to: To): (from: From) => compose export function decodeTo( to: To, transformation: { - readonly decode: Getter.Getter, NoInfer, RD> - readonly encode: Getter.Getter, NoInfer, RE> + readonly decode: SchemaGetter.Getter, NoInfer, RD> + readonly encode: SchemaGetter.Getter, NoInfer, RE> } ): (from: From) => decodeTo export function decodeTo( to: To, transformation?: { - readonly decode: Getter.Getter - readonly encode: Getter.Getter + readonly decode: SchemaGetter.Getter + readonly encode: SchemaGetter.Getter } | undefined ) { return (from: From) => { return make( - AST.decodeTo( + SchemaAST.decodeTo( from.ast, to.ast, - transformation ? Transformation.make(transformation) : Transformation.passthrough() + transformation ? SchemaTransformation.make(transformation) : SchemaTransformation.passthrough() ), { from, @@ -4114,21 +5043,26 @@ export function decodeTo(transformation: { - readonly decode: Getter.Getter - readonly encode: Getter.Getter + readonly decode: SchemaGetter.Getter + readonly encode: SchemaGetter.Getter }) { return (self: S): decodeTo, S, RD, RE> => { return self.pipe(decodeTo(toType(self), transformation)) @@ -4158,11 +5093,17 @@ export function decode(transformation: { } /** - * Like {@link decodeTo} but reverses the direction: the `from` schema acts as the target (decoded type) - * and `to` acts as the encoded source. + * Reverses a schema transformation so the encoded schema is supplied first. + * + * **When to use** + * + * Use to define a transformation by naming the encoded schema before the + * decoded schema. * - * `encodeTo(to)(from)` is equivalent to `to.pipe(decodeTo(from))` — useful when it reads more - * naturally to specify the encoded schema first. + * **Details** + * + * `encodeTo(to)(from)` is equivalent to `to.pipe(decodeTo(from))`. The `from` + * schema acts as the target decoded schema and `to` acts as the encoded source. * * **Example** (Encode a number back to string) * @@ -4177,6 +5118,7 @@ export function decode(transformation: { * ) * ``` * + * @category transforming * @since 4.0.0 */ export function encodeTo( @@ -4185,15 +5127,15 @@ export function encodeTo( export function encodeTo( to: To, transformation: { - readonly decode: Getter.Getter, NoInfer, RD> - readonly encode: Getter.Getter, NoInfer, RE> + readonly decode: SchemaGetter.Getter, NoInfer, RD> + readonly encode: SchemaGetter.Getter, NoInfer, RE> } ): (from: From) => decodeTo export function encodeTo( to: To, transformation?: { - readonly decode: Getter.Getter - readonly encode: Getter.Getter + readonly decode: SchemaGetter.Getter + readonly encode: SchemaGetter.Getter } ) { return (from: From): decodeTo => { @@ -4207,6 +5149,8 @@ export function encodeTo(transformation: { - readonly decode: Getter.Getter - readonly encode: Getter.Getter + readonly decode: SchemaGetter.Getter + readonly encode: SchemaGetter.Getter }) { return (self: S): decodeTo, RD, RE> => { return toEncoded(self).pipe(decodeTo(self, transformation)) @@ -4237,8 +5182,11 @@ export function encode(transformation: { /** * Constraint used to ensure a schema field does not already have a constructor default. * + * **Details** + * * Only schemas that satisfy this constraint can be passed to {@link withConstructorDefault}. * + * @category models * @since 4.0.0 */ export interface WithoutConstructorDefault { @@ -4246,10 +5194,10 @@ export interface WithoutConstructorDefault { } /** - * The type produced by {@link withConstructorDefault} — a schema with `"~type.constructor.default": "with-default"`. + * Type-level representation returned by {@link withConstructorDefault}. * - * @see {@link withConstructorDefault} for the constructor - * @since 4.0.0 + * @category constructors + * @since 3.10.0 */ export interface withConstructorDefault extends Bottom< @@ -4276,6 +5224,8 @@ export interface withConstructorDefault( // `S["~type.make.in"]` instead of `S["Type"]` is intentional here because // it makes easier to define the default value if there are nested defaults - defaultValue: Effect.Effect + defaultValue: Effect.Effect ) { return (schema: S): withConstructorDefault => - make(AST.withConstructorDefault(schema.ast, defaultValue), { schema }) + make(SchemaAST.withConstructorDefault(schema.ast, Effect.mapErrorEager(defaultValue, (e) => e.issue)), { schema }) } /** - * The type produced by {@link withDecodingDefaultKey}: a schema whose `Encoded` - * side is `optionalKey` and that fills in a default `Encoded` value during decoding. + * Type-level representation returned by {@link withDecodingDefaultKey}. * - * @see {@link withDecodingDefaultKey} for the constructor + * @category decoding * @since 4.0.0 */ -export interface withDecodingDefaultKey extends decodeTo>> { - readonly "Rebuild": withDecodingDefaultKey +export interface withDecodingDefaultKey extends decodeTo>, R> { + readonly "Rebuild": withDecodingDefaultKey } /** * Options for {@link withDecodingDefaultKey} and {@link withDecodingDefault}. * + * **Details** + * * - `encodingStrategy`: * - `"passthrough"` (default): pass the value through during encoding * - `"omit"`: omit the key from the encoded output * + * @category options * @since 4.0.0 */ export type DecodingDefaultOptions = { @@ -4334,11 +5287,13 @@ export type DecodingDefaultOptions = { * Makes a struct key optional on the `Encoded` side and provides a default * `Encoded` value when the key is missing during decoding. * + * **Details** + * * The key uses `optionalKey` on the encoded side, so it may be absent from the * input object but **not** `undefined`. The default value is specified in terms * of the `Encoded` type (before any decoding transformations). * - * **Options** + * Options: * * - `encodingStrategy`: * - `"passthrough"` (default): include the value in the encoded output. @@ -4359,33 +5314,32 @@ export type DecodingDefaultOptions = { * * @see {@link withDecodingDefault} for the value-level variant (key absent **or** `undefined`) * @see {@link withDecodingDefaultTypeKey} for the variant where the default is a `Type` value + * @category decoding * @since 4.0.0 */ -export function withDecodingDefaultKey( - defaultValue: Effect.Effect, +export function withDecodingDefaultKey( + defaultValue: Effect.Effect, options?: DecodingDefaultOptions ) { - const encode = options?.encodingStrategy === "omit" ? Getter.omit() : Getter.passthrough() - return (self: S): withDecodingDefaultKey => { + const encode = options?.encodingStrategy === "omit" ? SchemaGetter.omit() : SchemaGetter.passthrough() + return (self: S): withDecodingDefaultKey => { return optionalKey(toEncoded(self)).pipe(decodeTo(self, { - decode: Getter.withDefault(defaultValue), + decode: SchemaGetter.withDefault(Effect.mapErrorEager(defaultValue, (e) => e.issue)), encode })) } } /** - * The type produced by {@link withDecodingDefaultTypeKey}: a schema whose - * `Encoded` side is `optionalKey` and that fills in a default `Type` value - * during decoding. + * Type-level representation returned by {@link withDecodingDefaultTypeKey}. * - * @see {@link withDecodingDefaultTypeKey} for the constructor + * @category decoding * @since 4.0.0 */ -export interface withDecodingDefaultTypeKey - extends decodeTo>, optionalKey> +export interface withDecodingDefaultTypeKey + extends decodeTo, R>, optionalKey> { - readonly "Rebuild": withDecodingDefaultTypeKey + readonly "Rebuild": withDecodingDefaultTypeKey } /** @@ -4393,11 +5347,13 @@ export interface withDecodingDefaultTypeKey * key may be absent but **not** `undefined`) and provides a default `Type` * value when the key is missing during decoding. * + * **Details** + * * Unlike {@link withDecodingDefaultKey}, the default value is specified in * terms of the `Type` (decoded) representation, so it does not need to go * through the decoding transformation. * - * **Options** + * Options: * * - `encodingStrategy`: * - `"passthrough"` (default): include the value in the encoded output. @@ -4405,29 +5361,29 @@ export interface withDecodingDefaultTypeKey * * @see {@link withDecodingDefaultKey} for the variant where the default is an `Encoded` value * @see {@link withDecodingDefaultType} for the value-level variant + * @category decoding * @since 4.0.0 */ -export function withDecodingDefaultTypeKey( - defaultValue: Effect.Effect, +export function withDecodingDefaultTypeKey( + defaultValue: Effect.Effect, options?: DecodingDefaultOptions ) { - return (self: S): withDecodingDefaultTypeKey => { + return (self: S): withDecodingDefaultTypeKey => { return toType(self).pipe( - withDecodingDefaultKey>(defaultValue, options), + withDecodingDefaultKey, R>(defaultValue, options), encodeTo(optionalKey(self)) ) } } /** - * The type produced by {@link withDecodingDefault}: a schema whose `Encoded` - * side is `optional` and that fills in a default `Encoded` value during decoding. + * Type-level representation returned by {@link withDecodingDefault}. * - * @see {@link withDecodingDefault} for the constructor - * @since 4.0.0 + * @category decoding + * @since 3.10.0 */ -export interface withDecodingDefault extends decodeTo>> { - readonly "Rebuild": withDecodingDefault +export interface withDecodingDefault extends decodeTo>, R> { + readonly "Rebuild": withDecodingDefault } /** @@ -4435,10 +5391,17 @@ export interface withDecodingDefault extends decodeTo extends decodeTo( - defaultValue: Effect.Effect, +export function withDecodingDefault( + defaultValue: Effect.Effect, options?: DecodingDefaultOptions ) { - const encode = options?.encodingStrategy === "omit" ? Getter.omit() : Getter.passthrough() - return (self: S): withDecodingDefault => { + const encode = options?.encodingStrategy === "omit" ? SchemaGetter.omit() : SchemaGetter.passthrough() + return (self: S): withDecodingDefault => { return optional(toEncoded(self)).pipe(decodeTo(self, { - decode: Getter.withDefault(defaultValue), + decode: SchemaGetter.withDefault(Effect.mapErrorEager(defaultValue, (e) => e.issue)), encode })) } } /** - * The type produced by {@link withDecodingDefaultType}: a schema whose - * `Encoded` side is `optional` and that fills in a default `Type` value during - * decoding. + * Type-level representation returned by {@link withDecodingDefaultType}. * - * @see {@link withDecodingDefaultType} for the constructor + * @category decoding * @since 4.0.0 */ -export interface withDecodingDefaultType extends decodeTo>, optional> { - readonly "Rebuild": withDecodingDefaultType +export interface withDecodingDefaultType + extends decodeTo, R>, optional> +{ + readonly "Rebuild": withDecodingDefaultType } /** @@ -4491,11 +5455,18 @@ export interface withDecodingDefaultType extends decodeTo extends decodeTo( - defaultValue: Effect.Effect, +export function withDecodingDefaultType( + defaultValue: Effect.Effect, options?: DecodingDefaultOptions ) { - return (self: S): withDecodingDefaultType => { + return (self: S): withDecodingDefaultType => { return toType(self).pipe( - withDecodingDefault>(defaultValue, options), + withDecodingDefault, R>(defaultValue, options), encodeTo(optional(self)) ) } } /** - * The type produced by {@link tag} — a literal schema with a constructor default. - * - * Used as the type of the `_tag` field in {@link TaggedStruct} and related helpers. + * Type-level representation returned by {@link tag}. * - * @see {@link tag} for the constructor - * @since 4.0.0 + * @category constructors + * @since 3.10.0 */ -export interface tag extends withConstructorDefault> {} +export interface tag extends withConstructorDefault> {} /** * Combines a {@link Literal} schema with {@link withConstructorDefault}, making it ideal @@ -4546,16 +5516,25 @@ export interface tag extends withConstructorDefaul * * @see {@link tagDefaultOmit} to also omit the tag during encoding * @see {@link TaggedStruct} for a shorthand that adds `_tag` automatically - * @since 4.0.0 + * @category constructors + * @since 3.10.0 */ -export function tag(literal: Tag): tag { +export function tag(literal: Tag): tag { return Literal(literal).pipe(withConstructorDefault(Effect.succeed(literal))) } /** - * Like {@link tag}, but additionally omits the tag field from the encoded output. - * Useful when the encoded form (e.g. JSON) does not include the discriminator key, - * but the decoded type and constructor still need it. + * Creates a literal `_tag` schema that is omitted from encoded output. + * + * **When to use** + * + * Use to decode data that omits the discriminator field while still constructing + * values with a `_tag` for tagged union matching. + * + * **Details** + * + * The tag is filled during decoding and construction, like {@link tag}, but is + * omitted when encoding. * * **Example** (Tag omitted during encoding) * @@ -4573,26 +5552,31 @@ export function tag(literal: Tag): tag { * ``` * * @see {@link tag} for the variant that keeps the tag during encoding + * @category constructors * @since 4.0.0 */ -export function tagDefaultOmit(literal: Tag) { +export function tagDefaultOmit(literal: Tag) { return tag(literal).pipe(withDecodingDefaultKey(Effect.succeed(literal), { encodingStrategy: "omit" })) } /** - * The type produced by {@link TaggedStruct} — a {@link Struct} with an extra `_tag` field of type {@link tag}. + * Type-level representation returned by {@link TaggedStruct}. * - * @see {@link TaggedStruct} for the constructor - * @since 4.0.0 + * @category models + * @since 3.10.0 */ -export type TaggedStruct = Struct< +export type TaggedStruct = Struct< Simplify<{ readonly _tag: tag } & Fields> > /** - * A tagged struct is a struct that includes a `_tag` field. This field is used - * to identify the specific variant of the object, which is especially useful - * when working with union types. + * Creates a struct schema with an automatically populated `_tag` field. + * + * **When to use** + * + * Use to define a tagged union case from a literal tag and a set of fields. + * + * **Details** * * When using the `make` method, the `_tag` field is optional and will be * added automatically. However, when decoding or encoding, the `_tag` field @@ -4628,10 +5612,10 @@ export type TaggedStruct( +export function TaggedStruct( value: Tag, fields: Fields ): TaggedStruct { @@ -4656,7 +5640,7 @@ type TaggedUnionUtils< readonly cases: Simplify<{ [M in Flattened[number] as M["Type"][Tag]]: M }> readonly isAnyOf: ( keys: ReadonlyArray - ) => (value: Members[number]["Type"]) => value is Extract + ) => (value: Members[number]["Type"]) => value is Extract readonly guards: { [M in Flattened[number] as M["Type"][Tag]]: (u: unknown) => u is M["Type"] } readonly match: { < @@ -4676,11 +5660,10 @@ type TaggedUnionUtils< } /** - * The type produced by {@link toTaggedUnion} — a {@link Union} augmented with `cases`, `guards`, `isAnyOf`, and `match` utilities. + * Type-level representation returned by {@link toTaggedUnion}. * - * @see {@link toTaggedUnion} for the constructor + * @category combinators * @since 4.0.0 - * @experimental */ export type toTaggedUnion< Tag extends PropertyKey, @@ -4708,8 +5691,8 @@ export type toTaggedUnion< * ``` * * @see {@link TaggedUnion} for a shorthand that builds the union from scratch + * @category combinators * @since 4.0.0 - * @experimental */ export function toTaggedUnion(tag: Tag) { return >( @@ -4727,13 +5710,13 @@ export function toTaggedUnion(tag: Tag) { const ast = schema.ast if ( - AST.isUnion(ast) && "members" in schema && globalThis.Array.isArray(schema.members) && + SchemaAST.isUnion(ast) && "members" in schema && globalThis.Array.isArray(schema.members) && schema.members.every(isSchema) ) { return schema.members.forEach(walk) } - const sentinels = AST.collectSentinels(ast) + const sentinels = SchemaAST.collectSentinels(ast) if (sentinels.length > 0) { const literal = sentinels.find((s) => s.key === tag)?.literal if (Predicate.isPropertyKey(literal)) { @@ -4761,12 +5744,10 @@ export function toTaggedUnion(tag: Tag) { } /** - * A union schema that exposes `cases`, `guards`, `isAnyOf`, and `match` utilities keyed by the `_tag` discriminant. - * Produced by {@link TaggedUnion}. + * Type-level representation returned by {@link TaggedUnion}. * - * @see {@link TaggedUnion} for the constructor + * @category models * @since 4.0.0 - * @experimental */ export interface TaggedUnion> extends Bottom< @@ -4774,7 +5755,7 @@ export interface TaggedUnion> extends { [K in keyof Cases]: Cases[K]["Encoded"] }[keyof Cases], { [K in keyof Cases]: Cases[K]["DecodingServices"] }[keyof Cases], { [K in keyof Cases]: Cases[K]["EncodingServices"] }[keyof Cases], - AST.Union, + SchemaAST.Union, TaggedUnion, { [K in keyof Cases]: Cases[K]["~type.make"] }[keyof Cases] > @@ -4818,7 +5799,7 @@ export interface TaggedUnion> extends * ``` * * @see {@link toTaggedUnion} to augment an existing union instead - * @category Constructors + * @category constructors * @since 4.0.0 */ export function TaggedUnion>( @@ -4835,11 +5816,9 @@ export function TaggedUnion extends @@ -4885,6 +5864,7 @@ export interface Opaque extends * // person: Person * ``` * + * @category constructors * @since 4.0.0 */ export function Opaque() { @@ -4896,10 +5876,10 @@ export function Opaque() { } /** - * The type produced by {@link instanceOf} — a declaration schema that validates class instances. + * Type-level representation returned by {@link instanceOf}. * - * @see {@link instanceOf} for the constructor - * @since 4.0.0 + * @category models + * @since 3.10.0 */ export interface instanceOf extends declare { readonly "Rebuild": instanceOf @@ -4920,8 +5900,8 @@ export interface instanceOf extends declare { * // decoded: Date * ``` * - * @category Constructors - * @since 4.0.0 + * @category constructors + * @since 3.10.0 */ export function instanceOf any, Iso = InstanceType>( constructor: C, @@ -4931,20 +5911,21 @@ export function instanceOf any, Iso = In } /** - * Constructs an `AST.Link` that describes how a value of type `T` encodes to and decodes from a `To` schema. + * Constructs an `SchemaAST.Link` that describes how a value of type `T` encodes to and decodes from a `To` schema. * Used when building low-level AST transformations that bridge two schema types. * + * @category transforming * @since 4.0.0 */ export function link() { return ( encodeTo: To, transformation: { - readonly decode: Getter.Getter> - readonly encode: Getter.Getter, T> + readonly decode: SchemaGetter.Getter> + readonly encode: SchemaGetter.Getter, T> } - ): AST.Link => { - return new AST.Link(encodeTo.ast, Transformation.make(transformation)) + ): SchemaAST.Link => { + return new SchemaAST.Link(encodeTo.ast, SchemaTransformation.make(transformation)) } } @@ -4953,9 +5934,18 @@ export function link() { // ----------------------------------------------------------------------------- /** - * Creates a custom filter check from a predicate function. The predicate - * receives the input value, the schema's AST, and parse options, and returns - * a value of type {@link FilterOutput}. + * Creates a custom validation filter from a predicate function. + * + * **Details** + * + * The predicate receives the decoded input value, the schema AST, and parse + * options, and returns a `FilterOutput`. Non-success outputs are normalized into + * schema issues. The `annotations` parameter annotates the filter itself; with + * the default formatter, failures use `message` first, `expected` second, and + * `` when neither is provided. + * + * When `abort` is `true`, parsing stops after this filter fails instead of + * collecting later check failures. * * **Example** (Failure at a nested path) * @@ -4998,56 +5988,60 @@ export function link() { * // at ["c"])])) * ``` * - * @category Checks Constructors + * @category constructors * @since 4.0.0 */ export const makeFilter: ( - filter: (input: T, ast: AST.AST, options: AST.ParseOptions) => FilterOutput, + filter: (input: T, ast: SchemaAST.AST, options: SchemaAST.ParseOptions) => FilterOutput, annotations?: Annotations.Filter | undefined, abort?: boolean -) => AST.Filter = AST.makeFilter +) => SchemaAST.Filter = SchemaAST.makeFilter /** * A single failure reported by a filter predicate. Used as the element type * of the array arm of {@link FilterOutput}, and also accepted on its own. * + * **Details** + * * - `string`: failure with that string as the message. Produces an - * {@link Issue.InvalidValue} wrapping the input, with the string used as + * {@link SchemaIssue.InvalidValue} wrapping the input, with the string used as * the issue's `message` annotation. - * - {@link Issue.Issue}: a fully-formed issue, returned as-is. + * - {@link SchemaIssue.Issue}: a fully-formed issue, returned as-is. * - `{ path, issue }`: failure attached to a nested path. `issue` is either - * a `string` (wrapped in an {@link Issue.InvalidValue}) or a full - * {@link Issue.Issue}; the result is wrapped in an {@link Issue.Pointer} + * a `string` (wrapped in an {@link SchemaIssue.InvalidValue}) or a full + * {@link SchemaIssue.Issue}; the result is wrapped in an {@link SchemaIssue.Pointer} * at the given `path`. * - * @category model - * @since 4.0.0 + * @category models + * @since 3.10.0 */ -export type FilterIssue = string | Issue.Issue | { +export type FilterIssue = string | SchemaIssue.Issue | { readonly path: ReadonlyArray - readonly issue: string | Issue.Issue + readonly issue: string | SchemaIssue.Issue } /** * The value a filter predicate (see {@link makeFilter}) may return. * - * Each shape is normalized into an {@link Issue.Issue} (or `undefined` for + * **Details** + * + * Each shape is normalized into an {@link SchemaIssue.Issue} (or `undefined` for * success) before being attached to the parse result: * * - `undefined`: success. The input satisfies the filter. * - `true`: success. Equivalent to `undefined`, useful when the predicate is * a plain boolean expression. - * - `false`: generic failure. Produces an {@link Issue.InvalidValue} wrapping + * - `false`: generic failure. Produces an {@link SchemaIssue.InvalidValue} wrapping * the input, with no custom message. * - {@link FilterIssue}: a single failure. See {@link FilterIssue} for the - * shapes (`string`, {@link Issue.Issue}, or `{ path, issue }`). + * shapes (`string`, {@link SchemaIssue.Issue}, or `{ path, issue }`). * - `ReadonlyArray`: several failures reported together. An * empty array is treated as success; a single-element array is equivalent * to returning that element directly; otherwise the entries are grouped - * into an {@link Issue.Composite}. + * into an {@link SchemaIssue.Composite}. * - * @category model - * @since 4.0.0 + * @category models + * @since 3.10.0 */ export type FilterOutput = | undefined @@ -5056,17 +6050,17 @@ export type FilterOutput = | ReadonlyArray /** - * Groups multiple checks into a single {@link AST.FilterGroup}, applying + * Groups multiple checks into a single {@link SchemaAST.FilterGroup}, applying * optional shared annotations to the group as a whole. * - * @category Checks Constructors + * @category constructors * @since 4.0.0 */ export function makeFilterGroup( - checks: readonly [AST.Check, ...Array>], + checks: readonly [SchemaAST.Check, ...Array>], annotations: Annotations.Filter | undefined = undefined -): AST.FilterGroup { - return new AST.FilterGroup(checks, annotations) +): SchemaAST.FilterGroup { + return new SchemaAST.FilterGroup(checks, annotations) } const TRIMMED_PATTERN = "^\\S[\\s\\S]*\\S$|^\\S$|^$" @@ -5074,12 +6068,14 @@ const TRIMMED_PATTERN = "^\\S[\\s\\S]*\\S$|^\\S$|^$" /** * Validates that a string has no leading or trailing whitespace. * - * **JSON Schema** + * **Details** + * + * JSON Schema: * * This check corresponds to a `pattern` constraint in JSON Schema that * matches strings without leading or trailing whitespace. * - * **Arbitrary** + * Arbitrary: * * When generating test data with fast-check, this applies a `patterns` * constraint to ensure generated strings match the trimmed pattern. @@ -5096,8 +6092,8 @@ export function isTrimmed(annotations?: Annotations.Filter) { _tag: "isTrimmed", regExp: new globalThis.RegExp(TRIMMED_PATTERN) }, - toArbitraryConstraint: { - string: { + arbitrary: { + constraint: { patterns: [TRIMMED_PATTERN] } }, @@ -5109,11 +6105,13 @@ export function isTrimmed(annotations?: Annotations.Filter) { /** * Validates that a string matches the specified regular expression pattern. * - * **JSON Schema** + * **Details** + * + * JSON Schema: * * This check corresponds to the `pattern` constraint in JSON Schema. * - * **Arbitrary** + * Arbitrary: * * When generating test data with fast-check, this applies a `patterns` * constraint to ensure generated strings match the specified RegExp pattern. @@ -5121,18 +6119,20 @@ export function isTrimmed(annotations?: Annotations.Filter) { * @category String checks * @since 4.0.0 */ -export const isPattern: (regExp: globalThis.RegExp, annotations?: Annotations.Filter) => AST.Filter = - AST.isPattern +export const isPattern: (regExp: globalThis.RegExp, annotations?: Annotations.Filter) => SchemaAST.Filter = + SchemaAST.isPattern /** * Validates that a string represents a finite number. * - * **JSON Schema** + * **Details** + * + * JSON Schema: * * This check corresponds to a `pattern` constraint in JSON Schema that matches * strings representing finite numbers. * - * **Arbitrary** + * Arbitrary: * * When generating test data with fast-check, this applies a `patterns` * constraint to ensure generated strings match the number string pattern. @@ -5140,46 +6140,43 @@ export const isPattern: (regExp: globalThis.RegExp, annotations?: Annotations.Fi * @category String checks * @since 4.0.0 */ -export const isStringFinite: (annotations?: Annotations.Filter) => AST.Filter = AST.isStringFinite +export const isStringFinite: (annotations?: Annotations.Filter) => SchemaAST.Filter = SchemaAST.isStringFinite /** - * Validates that a string represents a valid BigInt (can be parsed as a BigInt). - * - * **JSON Schema** + * Validates that a string is a signed base-10 integer literal for Effect's + * BigInt string encoding. * - * This check corresponds to a `pattern` constraint in JSON Schema that matches - * strings representing BigInt values. + * **Details** * - * **Arbitrary** + * The check uses the pattern `^-?\d+$`. It does not accept leading `+`, decimal + * points, exponent notation, separators, or non-decimal inputs such as + * hexadecimal strings. * - * When generating test data with fast-check, this applies a `patterns` - * constraint to ensure generated strings match the BigInt string pattern. + * JSON Schema: + * This check corresponds to a `pattern` constraint with the same signed + * base-10 integer pattern. * * @category String checks * @since 4.0.0 */ -export const isStringBigInt: (annotations?: Annotations.Filter) => AST.Filter = AST.isStringBigInt +export const isStringBigInt: (annotations?: Annotations.Filter) => SchemaAST.Filter = SchemaAST.isStringBigInt /** - * Validates that a string represents a valid Symbol (can be parsed as a Symbol). - * - * **JSON Schema** - * - * This check corresponds to a `pattern` constraint in JSON Schema that matches - * strings representing Symbol values. + * Validates that a string has the `Symbol(description)` format used by Effect's + * symbol string encoding. * - * **Arbitrary** + * **Details** * - * When generating test data with fast-check, this applies a `patterns` - * constraint to ensure generated strings match the Symbol string pattern. + * The check uses the pattern `^Symbol\((.*)\)$`. It is not a general test for + * whether a string can be passed to JavaScript's `Symbol()` function. * * @category String checks * @since 4.0.0 */ -export const isStringSymbol: (annotations?: Annotations.Filter) => AST.Filter = AST.isStringSymbol +export const isStringSymbol: (annotations?: Annotations.Filter) => SchemaAST.Filter = SchemaAST.isStringSymbol /** - * Returns a RegExp for validating an RFC 4122 UUID. + * Returns a RegExp for validating an RFC 9562 / RFC 4122 UUID. * * Optionally specify a version 1-8. If no version is specified (`undefined`), all versions are supported. */ @@ -5189,24 +6186,36 @@ const getUUIDRegExp = (version?: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8): globalThis.RegE `^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${version}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$` ) } - return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000)$/; + return /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|[fF]{8}-[fF]{4}-[fF]{4}-[fF]{4}-[fF]{12})$/; } /** - * Validates that a string is a valid Universally Unique Identifier (UUID). - * Optionally specify a version (1-8) to validate against a specific UUID version. - * If no version is specified (`undefined`), all versions are supported. + * Validates that a string is a strict Universally Unique Identifier (UUID). + * + * **When to use** + * + * Use when you need UUID semantics, including version and RFC variant bits, + * rather than only the dashed hexadecimal shape. * - * **JSON Schema** + * **Details** + * + * Without a version argument, this accepts UUID versions 1 through 8, the nil + * UUID (`00000000-0000-0000-0000-000000000000`), and the max UUID + * (`ffffffff-ffff-ffff-ffff-ffffffffffff`). With a version argument, this + * accepts only UUIDs with that version and RFC variant bits; nil and max UUIDs + * are not versioned UUIDs and do not match version-specific checks. + * + * JSON Schema: * * This check corresponds to a `pattern` constraint in JSON Schema that matches * UUID format, and includes a `format: "uuid"` annotation. * - * **Arbitrary** + * Arbitrary: * * When generating test data with fast-check, this applies a `patterns` * constraint to ensure generated strings match the UUID pattern. * + * @see {@link isGUID} for shape-only GUID validation. * @category String checks * @since 4.0.0 */ @@ -5226,16 +6235,58 @@ export function isUUID(version?: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8, annotations?: An ) } +const GUID_REGEXP = /^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/ + +/** + * Validates that a string has the GUID / UUID textual shape. + * + * **When to use** + * + * Use when you need to accept dashed hexadecimal identifiers without enforcing + * UUID version or variant bits. + * + * **Details** + * + * This check accepts strings in the `8-4-4-4-12` hexadecimal form. JSON Schema + * output includes the corresponding `pattern` constraint and intentionally does + * not include `format: "uuid"` because GUID validation is looser than UUID + * validation. + * + * Arbitrary: + * + * When generating test data with fast-check, this applies a `patterns` + * constraint to ensure generated strings match the GUID pattern. + * + * @see {@link isUUID} for strict UUID validation. + * @category String checks + * @since 4.0.0 + */ +export function isGUID(annotations?: Annotations.Filter) { + return isPattern( + GUID_REGEXP, + { + expected: "a GUID", + meta: { + _tag: "isGUID", + regExp: GUID_REGEXP + }, + ...annotations + } + ) +} + /** * Validates that a string is a valid ULID (Universally Unique Lexicographically * Sortable Identifier). * - * **JSON Schema** + * **Details** + * + * JSON Schema: * * This check corresponds to a `pattern` constraint in JSON Schema that matches * the ULID format. * - * **Arbitrary** + * Arbitrary: * * When generating test data with fast-check, this applies a `patterns` * constraint to ensure generated strings match the ULID pattern. @@ -5260,12 +6311,14 @@ export function isULID(annotations?: Annotations.Filter) { /** * Validates that a string is valid Base64 encoded data. * - * **JSON Schema** + * **Details** + * + * JSON Schema: * * This check corresponds to a `pattern` constraint in JSON Schema that matches * Base64 format. * - * **Arbitrary** + * Arbitrary: * * When generating test data with fast-check, this applies a `patterns` * constraint to ensure generated strings match the Base64 pattern. @@ -5292,12 +6345,14 @@ export function isBase64(annotations?: Annotations.Filter) { * Validates that a string is valid Base64URL encoded data (Base64 with URL-safe * characters). * - * **JSON Schema** + * **Details** + * + * JSON Schema: * * This check corresponds to a `pattern` constraint in JSON Schema that matches * Base64URL format. * - * **Arbitrary** + * Arbitrary: * * When generating test data with fast-check, this applies a `patterns` * constraint to ensure generated strings match the Base64URL pattern. @@ -5321,17 +6376,14 @@ export function isBase64Url(annotations?: Annotations.Filter) { } /** - * Validates that a string starts with the specified prefix. - * - * **JSON Schema** + * Validates at runtime that a string starts with the specified literal prefix. * - * This check corresponds to a `pattern` constraint in JSON Schema that matches - * strings starting with the specified prefix. - * - * **Arbitrary** + * **Details** * - * When generating test data with fast-check, this applies a `patterns` - * constraint to ensure generated strings start with the required prefix. + * Notes: + * The JSON Schema and arbitrary metadata are built from `^${startsWith}` without + * escaping regexp metacharacters. If the prefix contains regexp syntax, generated + * patterns may not be equivalent to the runtime `startsWith` check. * * @category String checks * @since 4.0.0 @@ -5347,8 +6399,8 @@ export function isStartsWith(startsWith: string, annotations?: Annotations.Filte startsWith, regExp: new globalThis.RegExp(`^${startsWith}`) }, - toArbitraryConstraint: { - string: { + arbitrary: { + constraint: { patterns: [`^${startsWith}`] } }, @@ -5358,17 +6410,14 @@ export function isStartsWith(startsWith: string, annotations?: Annotations.Filte } /** - * Validates that a string ends with the specified suffix. - * - * **JSON Schema** + * Validates at runtime that a string ends with the specified literal suffix. * - * This check corresponds to a `pattern` constraint in JSON Schema that matches - * strings ending with the specified suffix. - * - * **Arbitrary** + * **Details** * - * When generating test data with fast-check, this applies a `patterns` - * constraint to ensure generated strings end with the required suffix. + * Notes: + * The JSON Schema and arbitrary metadata are built from `${endsWith}$` without + * escaping regexp metacharacters. If the suffix contains regexp syntax, generated + * patterns may not be equivalent to the runtime `endsWith` check. * * @category String checks * @since 4.0.0 @@ -5384,8 +6433,8 @@ export function isEndsWith(endsWith: string, annotations?: Annotations.Filter) { endsWith, regExp: new globalThis.RegExp(`${endsWith}$`) }, - toArbitraryConstraint: { - string: { + arbitrary: { + constraint: { patterns: [`${endsWith}$`] } }, @@ -5395,17 +6444,14 @@ export function isEndsWith(endsWith: string, annotations?: Annotations.Filter) { } /** - * Validates that a string contains the specified substring. - * - * **JSON Schema** + * Validates at runtime that a string contains the specified literal substring. * - * This check corresponds to a `pattern` constraint in JSON Schema that matches - * strings containing the specified substring. - * - * **Arbitrary** + * **Details** * - * When generating test data with fast-check, this applies a `patterns` - * constraint to ensure generated strings contain the required substring. + * Notes: + * The JSON Schema and arbitrary metadata use the substring as a raw regexp + * pattern. If the substring contains regexp syntax, generated patterns may not be + * equivalent to the runtime `includes` check. * * @category String checks * @since 4.0.0 @@ -5421,8 +6467,8 @@ export function isIncludes(includes: string, annotations?: Annotations.Filter) { includes, regExp: new globalThis.RegExp(includes) }, - toArbitraryConstraint: { - string: { + arbitrary: { + constraint: { patterns: [includes] } }, @@ -5432,19 +6478,15 @@ export function isIncludes(includes: string, annotations?: Annotations.Filter) { } const UPPERCASED_PATTERN = "^[^a-z]*$" - -/** - * Validates that a string contains only uppercase characters. - * - * **JSON Schema** - * - * This check corresponds to a `pattern` constraint in JSON Schema that matches - * strings with only uppercase characters. + +/** + * Validates that a string is unchanged by JavaScript's `toUpperCase()`. * - * **Arbitrary** + * **Details** * - * When generating test data with fast-check, this applies a `patterns` - * constraint to ensure generated strings contain only uppercase characters. + * This accepts empty strings and characters that do not have lowercase forms, + * such as digits, punctuation, and whitespace. It rejects strings that would + * change when uppercased. * * @category String checks * @since 4.0.0 @@ -5458,8 +6500,8 @@ export function isUppercased(annotations?: Annotations.Filter) { _tag: "isUppercased", regExp: new globalThis.RegExp(UPPERCASED_PATTERN) }, - toArbitraryConstraint: { - string: { + arbitrary: { + constraint: { patterns: [UPPERCASED_PATTERN] } }, @@ -5471,17 +6513,13 @@ export function isUppercased(annotations?: Annotations.Filter) { const LOWERCASED_PATTERN = "^[^A-Z]*$" /** - * Validates that a string contains only lowercase characters. - * - * **JSON Schema** + * Validates that a string is unchanged by JavaScript's `toLowerCase()`. * - * This check corresponds to a `pattern` constraint in JSON Schema that matches - * strings with only lowercase characters. - * - * **Arbitrary** + * **Details** * - * When generating test data with fast-check, this applies a `patterns` - * constraint to ensure generated strings contain only lowercase characters. + * This accepts empty strings and characters that do not have uppercase forms, + * such as digits, punctuation, and whitespace. It rejects strings that would + * change when lowercased. * * @category String checks * @since 4.0.0 @@ -5495,8 +6533,8 @@ export function isLowercased(annotations?: Annotations.Filter) { _tag: "isLowercased", regExp: new globalThis.RegExp(LOWERCASED_PATTERN) }, - toArbitraryConstraint: { - string: { + arbitrary: { + constraint: { patterns: [LOWERCASED_PATTERN] } }, @@ -5508,17 +6546,13 @@ export function isLowercased(annotations?: Annotations.Filter) { const CAPITALIZED_PATTERN = "^[^a-z]?.*$" /** - * Validates that a string has its first character in uppercase. - * - * **JSON Schema** + * Validates that the first character of a string is unchanged by + * `toUpperCase()`. * - * This check corresponds to a `pattern` constraint in JSON Schema that matches - * strings with the first character in uppercase. - * - * **Arbitrary** + * **Details** * - * When generating test data with fast-check, this applies a `patterns` - * constraint to ensure generated strings have the first character in uppercase. + * Empty strings pass. Strings whose first character has no lowercase form, such + * as a digit, punctuation mark, or whitespace, also pass. * * @category String checks * @since 4.0.0 @@ -5532,8 +6566,8 @@ export function isCapitalized(annotations?: Annotations.Filter) { _tag: "isCapitalized", regExp: new globalThis.RegExp(CAPITALIZED_PATTERN) }, - toArbitraryConstraint: { - string: { + arbitrary: { + constraint: { patterns: [CAPITALIZED_PATTERN] } }, @@ -5545,17 +6579,13 @@ export function isCapitalized(annotations?: Annotations.Filter) { const UNCAPITALIZED_PATTERN = "^[^A-Z]?.*$" /** - * Validates that a string has its first character in lowercase. - * - * **JSON Schema** + * Validates that the first character of a string is unchanged by + * `toLowerCase()`. * - * This check corresponds to a `pattern` constraint in JSON Schema that matches - * strings with the first character in lowercase. - * - * **Arbitrary** + * **Details** * - * When generating test data with fast-check, this applies a `patterns` - * constraint to ensure generated strings have the first character in lowercase. + * Empty strings pass. Strings whose first character has no uppercase form, such + * as a digit, punctuation mark, or whitespace, also pass. * * @category String checks * @since 4.0.0 @@ -5569,8 +6599,8 @@ export function isUncapitalized(annotations?: Annotations.Filter) { _tag: "isUncapitalized", regExp: new globalThis.RegExp(UNCAPITALIZED_PATTERN) }, - toArbitraryConstraint: { - string: { + arbitrary: { + constraint: { patterns: [UNCAPITALIZED_PATTERN] } }, @@ -5582,15 +6612,17 @@ export function isUncapitalized(annotations?: Annotations.Filter) { /** * Validates that a number is finite (not `Infinity`, `-Infinity`, or `NaN`). * - * **JSON Schema** + * **Details** + * + * JSON Schema: * * This check does not have a direct JSON Schema equivalent, but ensures the * number is valid and finite. * - * **Arbitrary** + * Arbitrary: * - * When generating test data with fast-check, this applies `noDefaultInfinity` - * and `noNaN` constraints to ensure generated numbers are finite. + * When generating test data with fast-check, this applies `noNaN: true` and + * `noInfinity: true` constraints to ensure generated numbers are finite. * * @category Number checks * @since 4.0.0 @@ -5603,9 +6635,9 @@ export function isFinite(annotations?: Annotations.Filter) { meta: { _tag: "isFinite" }, - toArbitraryConstraint: { - number: { - noDefaultInfinity: true, + arbitrary: { + constraint: { + noInfinity: true, noNaN: true } }, @@ -5615,8 +6647,8 @@ export function isFinite(annotations?: Annotations.Filter) { } /** - * Generic factory for creating a "greater than" (`>`) check for any ordered - * type by supplying an {@link Order.Order} instance. + * Creates a greater-than (`>`) check for any ordered type from an + * `Order.Order` instance. * * @category Order checks * @since 4.0.0 @@ -5633,6 +6665,15 @@ export function makeIsGreaterThan(options: { (input) => gt(input, exclusiveMinimum), { expected: `a value greater than ${formatter(exclusiveMinimum)}`, + arbitrary: { + constraint: { + ordered: { + order: options.order, + minimum: exclusiveMinimum, + exclusiveMinimum: true + } + } + }, ...options.annotate?.(exclusiveMinimum), ...annotations } @@ -5641,8 +6682,8 @@ export function makeIsGreaterThan(options: { } /** - * Generic factory for creating a ">=" check for any ordered type by supplying - * an {@link Order.Order} instance. + * Creates a greater-than-or-equal-to (`>=`) check for any ordered type from an + * `Order.Order` instance. * * @category Order checks * @since 4.0.0 @@ -5659,6 +6700,14 @@ export function makeIsGreaterThanOrEqualTo(options: { (input) => gte(input, minimum), { expected: `a value greater than or equal to ${formatter(minimum)}`, + arbitrary: { + constraint: { + ordered: { + order: options.order, + minimum + } + } + }, ...options.annotate?.(minimum), ...annotations } @@ -5667,8 +6716,8 @@ export function makeIsGreaterThanOrEqualTo(options: { } /** - * Generic factory for creating a "<" check for any ordered type by supplying - * an {@link Order.Order} instance. + * Creates a less-than (`<`) check for any ordered type from an `Order.Order` + * instance. * * @category Order checks * @since 4.0.0 @@ -5685,6 +6734,15 @@ export function makeIsLessThan(options: { (input) => lt(input, exclusiveMaximum), { expected: `a value less than ${formatter(exclusiveMaximum)}`, + arbitrary: { + constraint: { + ordered: { + order: options.order, + maximum: exclusiveMaximum, + exclusiveMaximum: true + } + } + }, ...options.annotate?.(exclusiveMaximum), ...annotations } @@ -5693,8 +6751,8 @@ export function makeIsLessThan(options: { } /** - * Generic factory for creating a "<=" check for any ordered type by supplying - * an {@link Order.Order} instance. + * Creates a less-than-or-equal-to (`<=`) check for any ordered type from an + * `Order.Order` instance. * * @category Order checks * @since 4.0.0 @@ -5711,6 +6769,14 @@ export function makeIsLessThanOrEqualTo(options: { (input) => lte(input, maximum), { expected: `a value less than or equal to ${formatter(maximum)}`, + arbitrary: { + constraint: { + ordered: { + order: options.order, + maximum + } + } + }, ...options.annotate?.(maximum), ...annotations } @@ -5719,8 +6785,8 @@ export function makeIsLessThanOrEqualTo(options: { } /** - * Generic factory for creating an inclusive/exclusive range check for any - * ordered type by supplying an {@link Order.Order} instance. + * Creates an inclusive or exclusive range check for any ordered type from an + * `Order.Order` instance. * * @category Order checks * @since 4.0.0 @@ -5756,6 +6822,17 @@ export function makeIsBetween(deriveOptions: { expected: `a value between ${formatter(options.minimum)}${options.exclusiveMinimum ? " (excluded)" : ""} and ${ formatter(options.maximum) }${options.exclusiveMaximum ? " (excluded)" : ""}`, + arbitrary: { + constraint: { + ordered: { + order: deriveOptions.order, + minimum: options.minimum, + maximum: options.maximum, + ...(options.exclusiveMinimum && { exclusiveMinimum: true }), + ...(options.exclusiveMaximum && { exclusiveMaximum: true }) + } + } + }, ...deriveOptions.annotate?.(options), ...annotations } @@ -5764,8 +6841,8 @@ export function makeIsBetween(deriveOptions: { } /** - * Generic factory for creating a divisibility check for any numeric type by - * supplying a remainder function and a zero value. + * Creates a divisibility check for any numeric type from a remainder function + * and a zero value. * * @category Numeric checks * @since 4.0.0 @@ -5792,15 +6869,17 @@ export function makeIsMultipleOf(options: { /** * Validates that a number is greater than the specified value (exclusive). * - * **JSON Schema** + * **Details** + * + * JSON Schema: * * This check corresponds to the `exclusiveMinimum` constraint in JSON Schema. * - * **Arbitrary** + * Arbitrary: * - * When generating test data with fast-check, this applies a `min` constraint - * with `minExcluded: true` to ensure generated numbers are greater than the - * specified value. + * When generating test data with fast-check, this applies an + * `exclusiveMinimum` constraint to ensure generated numbers are greater than + * the specified value. * * @category Number checks * @since 4.0.0 @@ -5811,12 +6890,6 @@ export const isGreaterThan = makeIsGreaterThan({ meta: { _tag: "isGreaterThan", exclusiveMinimum - }, - toArbitraryConstraint: { - number: { - min: exclusiveMinimum, - minExcluded: true - } } }) }) @@ -5825,13 +6898,15 @@ export const isGreaterThan = makeIsGreaterThan({ * Validates that a number is greater than or equal to the specified value * (inclusive). * - * **JSON Schema** + * **Details** + * + * JSON Schema: * * This check corresponds to the `minimum` constraint in JSON Schema. * - * **Arbitrary** + * Arbitrary: * - * When generating test data with fast-check, this applies a `min` constraint + * When generating test data with fast-check, this applies a `minimum` constraint * to ensure generated numbers are greater than or equal to the specified value. * * @category Number checks @@ -5843,11 +6918,6 @@ export const isGreaterThanOrEqualTo = makeIsGreaterThanOrEqualTo({ meta: { _tag: "isGreaterThanOrEqualTo", minimum - }, - toArbitraryConstraint: { - number: { - min: minimum - } } }) }) @@ -5855,14 +6925,16 @@ export const isGreaterThanOrEqualTo = makeIsGreaterThanOrEqualTo({ /** * Validates that a number is less than the specified value (exclusive). * - * **JSON Schema** + * **Details** + * + * JSON Schema: * * This check corresponds to the `exclusiveMaximum` constraint in JSON Schema. * - * **Arbitrary** + * Arbitrary: * - * When generating test data with fast-check, this applies a `max` constraint - * with `maxExcluded: true` to ensure generated numbers are less than the + * When generating test data with fast-check, this applies an + * `exclusiveMaximum` constraint to ensure generated numbers are less than the * specified value. * * @category Number checks @@ -5874,12 +6946,6 @@ export const isLessThan = makeIsLessThan({ meta: { _tag: "isLessThan", exclusiveMaximum - }, - toArbitraryConstraint: { - number: { - max: exclusiveMaximum, - maxExcluded: true - } } }) }) @@ -5888,13 +6954,15 @@ export const isLessThan = makeIsLessThan({ * Validates that a number is less than or equal to the specified value * (inclusive). * - * **JSON Schema** + * **Details** + * + * JSON Schema: * * This check corresponds to the `maximum` constraint in JSON Schema. * - * **Arbitrary** + * Arbitrary: * - * When generating test data with fast-check, this applies a `max` constraint + * When generating test data with fast-check, this applies a `maximum` constraint * to ensure generated numbers are less than or equal to the specified value. * * @category Number checks @@ -5906,11 +6974,6 @@ export const isLessThanOrEqualTo = makeIsLessThanOrEqualTo({ meta: { _tag: "isLessThanOrEqualTo", maximum - }, - toArbitraryConstraint: { - number: { - max: maximum - } } }) }) @@ -5919,16 +6982,19 @@ export const isLessThanOrEqualTo = makeIsLessThanOrEqualTo({ * Validates that a number is within a specified range. The range boundaries can * be inclusive or exclusive based on the provided options. * - * **JSON Schema** + * **Details** + * + * JSON Schema: * * This check corresponds to `minimum`/`maximum` or `exclusiveMinimum`/`exclusiveMaximum` * constraints in JSON Schema, depending on the options provided. * - * **Arbitrary** + * Arbitrary: * - * When generating test data with fast-check, this applies `min` and `max` - * constraints with optional `minExcluded` and `maxExcluded` flags to ensure - * generated numbers fall within the specified range. + * When generating test data with fast-check, this applies `minimum` and + * `maximum` constraints with optional `exclusiveMinimum` and + * `exclusiveMaximum` flags to ensure generated numbers fall within the + * specified range. * * @category Number checks * @since 4.0.0 @@ -5940,14 +7006,6 @@ export const isBetween = makeIsBetween({ meta: { _tag: "isBetween", ...options - }, - toArbitraryConstraint: { - number: { - min: options.minimum, - max: options.maximum, - ...(options.exclusiveMinimum && { minExcluded: true }), - ...(options.exclusiveMaximum && { maxExcluded: true }) - } } } } @@ -5956,11 +7014,13 @@ export const isBetween = makeIsBetween({ /** * Validates that a number is a multiple of the specified divisor. * - * **JSON Schema** + * **Details** + * + * JSON Schema: * * This check corresponds to the `multipleOf` constraint in JSON Schema. * - * **Arbitrary** + * Arbitrary: * * When generating test data with fast-check, this applies constraints to ensure * generated numbers are multiples of the specified divisor. @@ -5984,13 +7044,15 @@ export const isMultipleOf = makeIsMultipleOf({ * Validates that a number is a safe integer (within the safe integer range * that can be exactly represented in JavaScript). * - * **JSON Schema** + * **Details** + * + * JSON Schema: * * This check corresponds to the `type: "integer"` constraint in JSON Schema. * - * **Arbitrary** + * Arbitrary: * - * When generating test data with fast-check, this applies an `isInteger: true` + * When generating test data with fast-check, this applies an `integer: true` * constraint to ensure generated numbers are integers. * * @category Integer checks @@ -6004,9 +7066,9 @@ export function isInt(annotations?: Annotations.Filter) { meta: { _tag: "isInt" }, - toArbitraryConstraint: { - number: { - isInteger: true + arbitrary: { + constraint: { + integer: true } }, ...annotations @@ -6018,12 +7080,14 @@ export function isInt(annotations?: Annotations.Filter) { * Validates that a number is a 32-bit signed integer (range: -2,147,483,648 to * 2,147,483,647). * - * **JSON Schema** + * **Details** + * + * JSON Schema: * * This check corresponds to the `format: "int32"` constraint in OpenAPI 3.1, * or `minimum`/`maximum` constraints in other JSON Schema targets. * - * **Arbitrary** + * Arbitrary: * * When generating test data with fast-check, this applies integer and range * constraints to ensure generated numbers are 32-bit signed integers. @@ -6032,7 +7096,7 @@ export function isInt(annotations?: Annotations.Filter) { * @since 4.0.0 */ export function isInt32(annotations?: Annotations.Filter) { - return new AST.FilterGroup( + return new SchemaAST.FilterGroup( [ isInt(annotations), isBetween({ minimum: -2147483648, maximum: 2147483647 }) @@ -6048,12 +7112,14 @@ export function isInt32(annotations?: Annotations.Filter) { * Validates that a number is a 32-bit unsigned integer (range: 0 to * 4,294,967,295). * - * **JSON Schema** + * **Details** + * + * JSON Schema: * * This check corresponds to the `format: "uint32"` constraint in OpenAPI 3.1, * or `minimum`/`maximum` constraints in other JSON Schema targets. * - * **Arbitrary** + * Arbitrary: * * When generating test data with fast-check, this applies integer and range * constraints to ensure generated numbers are 32-bit unsigned integers. @@ -6062,7 +7128,7 @@ export function isInt32(annotations?: Annotations.Filter) { * @since 4.0.0 */ export function isUint32(annotations?: Annotations.Filter) { - return new AST.FilterGroup( + return new SchemaAST.FilterGroup( [ isInt(), isBetween({ minimum: 0, maximum: 4294967295 }) @@ -6078,14 +7144,16 @@ export function isUint32(annotations?: Annotations.Filter) { * Validates that a Date object represents a valid date (not an invalid date * like `new Date("invalid")`). * - * **JSON Schema** + * **Details** + * + * JSON Schema: * * This check does not have a direct JSON Schema equivalent, as JSON Schema * validates date strings, not Date objects. * - * **Arbitrary** + * Arbitrary: * - * When generating test data with fast-check, this applies a `noInvalidDate` + * When generating test data with fast-check, this applies a `valid: true` * constraint to ensure generated Date objects are valid. * * @category Date checks @@ -6099,9 +7167,9 @@ export function isDateValid(annotations?: Annotations.Filter) { meta: { _tag: "isDateValid" }, - toArbitraryConstraint: { - date: { - noInvalidDate: true + arbitrary: { + constraint: { + valid: true } }, ...annotations @@ -6112,11 +7180,13 @@ export function isDateValid(annotations?: Annotations.Filter) { /** * Validates that a Date is greater than the specified value (exclusive). * - * **Arbitrary** + * **Details** * - * When generating test data with fast-check, this applies a `min` constraint - * with `minExcluded: true` to ensure generated Date objects are greater than the - * specified value. + * Arbitrary: + * + * When generating test data with fast-check, this applies a `min` constraint of + * one millisecond after the specified value to ensure generated Date objects are + * greater than it. * * @category Date checks * @since 4.0.0 @@ -6127,12 +7197,6 @@ export const isGreaterThanDate = makeIsGreaterThan({ meta: { _tag: "isGreaterThanDate", exclusiveMinimum - }, - toArbitraryConstraint: { - date: { - min: exclusiveMinimum, - minExcluded: true - } } }) }) @@ -6141,12 +7205,14 @@ export const isGreaterThanDate = makeIsGreaterThan({ * Validates that a Date is greater than or equal to the specified date * (inclusive). * - * **JSON Schema** + * **Details** + * + * JSON Schema: * * This check does not have a direct JSON Schema equivalent, as JSON Schema * validates date strings, not Date objects. * - * **Arbitrary** + * Arbitrary: * * When generating test data with fast-check, this applies a `min` constraint * to ensure generated Date objects are greater than or equal to the specified @@ -6161,11 +7227,6 @@ export const isGreaterThanOrEqualToDate = makeIsGreaterThanOrEqualTo({ meta: { _tag: "isGreaterThanOrEqualToDate", minimum - }, - toArbitraryConstraint: { - date: { - min: minimum - } } }) }) @@ -6173,11 +7234,13 @@ export const isGreaterThanOrEqualToDate = makeIsGreaterThanOrEqualTo({ /** * Validates that a Date is less than the specified value (exclusive). * - * **Arbitrary** + * **Details** * - * When generating test data with fast-check, this applies a `max` constraint - * with `maxExcluded: true` to ensure generated Date objects are less than the - * specified value. + * Arbitrary: + * + * When generating test data with fast-check, this applies a `max` constraint of + * one millisecond before the specified value to ensure generated Date objects + * are less than it. * * @category Date checks * @since 4.0.0 @@ -6188,12 +7251,6 @@ export const isLessThanDate = makeIsLessThan({ meta: { _tag: "isLessThanDate", exclusiveMaximum - }, - toArbitraryConstraint: { - date: { - max: exclusiveMaximum, - maxExcluded: true - } } }) }) @@ -6202,12 +7259,14 @@ export const isLessThanDate = makeIsLessThan({ * Validates that a Date is less than or equal to the specified date * (inclusive). * - * **JSON Schema** + * **Details** + * + * JSON Schema: * * This check does not have a direct JSON Schema equivalent, as JSON Schema * validates date strings, not Date objects. * - * **Arbitrary** + * Arbitrary: * * When generating test data with fast-check, this applies a `max` constraint * to ensure generated Date objects are less than or equal to the specified @@ -6222,11 +7281,6 @@ export const isLessThanOrEqualToDate = makeIsLessThanOrEqualTo({ meta: { _tag: "isLessThanOrEqualToDate", maximum - }, - toArbitraryConstraint: { - date: { - max: maximum - } } }) }) @@ -6235,15 +7289,18 @@ export const isLessThanOrEqualToDate = makeIsLessThanOrEqualTo({ * Validates that a Date is within a specified range. The range boundaries can * be inclusive or exclusive based on the provided options. * - * **JSON Schema** + * **Details** + * + * JSON Schema: * * This check does not have a direct JSON Schema equivalent, as JSON Schema * validates date strings, not Date objects. * - * **Arbitrary** + * Arbitrary: * * When generating test data with fast-check, this applies `min` and `max` - * constraints to ensure generated Date objects fall within the specified range. + * constraints to ensure generated Date objects fall within the specified range, + * shifting exclusive bounds by one millisecond. * * @category Date checks * @since 4.0.0 @@ -6254,12 +7311,6 @@ export const isBetweenDate = makeIsBetween({ meta: { _tag: "isBetweenDate", ...options - }, - toArbitraryConstraint: { - date: { - min: options.minimum, - max: options.maximum - } } }) }) @@ -6267,10 +7318,12 @@ export const isBetweenDate = makeIsBetween({ /** * Validates that a BigInt is greater than the specified value (exclusive). * - * **Arbitrary** + * **Details** * - * When generating test data with fast-check, this applies a `min` constraint - * with `minExcluded: true` to ensure generated BigInts are greater than the + * Arbitrary: + * + * When generating test data with fast-check, this applies a `min` constraint of + * `exclusiveMinimum + 1n` to ensure generated BigInts are greater than the * specified value. * * @category BigInt checks @@ -6282,12 +7335,6 @@ export const isGreaterThanBigInt = makeIsGreaterThan({ meta: { _tag: "isGreaterThanBigInt", exclusiveMinimum - }, - toArbitraryConstraint: { - bigint: { - min: exclusiveMinimum, - minExcluded: true - } } }) }) @@ -6296,7 +7343,9 @@ export const isGreaterThanBigInt = makeIsGreaterThan({ * Validates that a BigInt is greater than or equal to the specified value * (inclusive). * - * **Arbitrary** + * **Details** + * + * Arbitrary: * * When generating test data with fast-check, this applies a `min` constraint * to ensure generated BigInt values are greater than or equal to the specified @@ -6311,11 +7360,6 @@ export const isGreaterThanOrEqualToBigInt = makeIsGreaterThanOrEqualTo({ meta: { _tag: "isGreaterThanOrEqualToBigInt", minimum - }, - toArbitraryConstraint: { - bigint: { - min: minimum - } } }) }) @@ -6323,10 +7367,12 @@ export const isGreaterThanOrEqualToBigInt = makeIsGreaterThanOrEqualTo({ /** * Validates that a BigInt is less than the specified value (exclusive). * - * **Arbitrary** + * **Details** * - * When generating test data with fast-check, this applies a `max` constraint - * with `maxExcluded: true` to ensure generated BigInts are less than the + * Arbitrary: + * + * When generating test data with fast-check, this applies a `max` constraint of + * `exclusiveMaximum - 1n` to ensure generated BigInts are less than the * specified value. * * @category BigInt checks @@ -6338,12 +7384,6 @@ export const isLessThanBigInt = makeIsLessThan({ meta: { _tag: "isLessThanBigInt", exclusiveMaximum - }, - toArbitraryConstraint: { - bigint: { - max: exclusiveMaximum, - maxExcluded: true - } } }) }) @@ -6352,7 +7392,9 @@ export const isLessThanBigInt = makeIsLessThan({ * Validates that a BigInt is less than or equal to the specified value * (inclusive). * - * **Arbitrary** + * **Details** + * + * Arbitrary: * * When generating test data with fast-check, this applies a `max` constraint * to ensure generated BigInt values are less than or equal to the specified @@ -6367,11 +7409,6 @@ export const isLessThanOrEqualToBigInt = makeIsLessThanOrEqualTo({ meta: { _tag: "isLessThanOrEqualToBigInt", maximum - }, - toArbitraryConstraint: { - bigint: { - max: maximum - } } }) }) @@ -6380,7 +7417,9 @@ export const isLessThanOrEqualToBigInt = makeIsLessThanOrEqualTo({ * Validates that a BigInt is within a specified range. The range boundaries can * be inclusive or exclusive based on the provided options. * - * **Arbitrary** + * **Details** + * + * Arbitrary: * * When generating test data with fast-check, this applies `min` and `max` * constraints to ensure generated BigInt values fall within the specified @@ -6395,12 +7434,6 @@ export const isBetweenBigInt = makeIsBetween({ meta: { _tag: "isBetweenBigInt", ...options - }, - toArbitraryConstraint: { - bigint: { - min: options.minimum, - max: options.maximum - } } }) }) @@ -6452,7 +7485,12 @@ export const isLessThanOrEqualToBigDecimal = makeIsLessThanOrEqualTo({ }) /** - * Validates that a BigDecimal is within a specified range. + * Validates that a `BigDecimal` is within a specified range. + * + * **Details** + * + * The minimum and maximum boundaries are inclusive by default. Pass + * `exclusiveMinimum` or `exclusiveMaximum` to exclude either boundary. * * @category BigDecimal checks * @since 4.0.0 @@ -6466,18 +7504,21 @@ export const isBetweenBigDecimal = makeIsBetween({ * Validates that a value has at least the specified length. Works with strings * and arrays. * - * **JSON Schema** + * **Details** + * + * JSON Schema: * * This check corresponds to the `minLength` constraint for strings or the * `minItems` constraint for arrays in JSON Schema. * - * **Arbitrary** + * Arbitrary: * * When generating test data with fast-check, this applies a `minLength` * constraint to ensure generated strings or arrays have at least the required * length. * * **Example** (Minimum length check) + * * ```ts * import { Schema } from "effect" * @@ -6498,12 +7539,9 @@ export function isMinLength(minLength: number, annotations?: Annotations.Filter) _tag: "isMinLength", minLength }, - [AST.STRUCTURAL_ANNOTATION_KEY]: true, - toArbitraryConstraint: { - string: { - minLength - }, - array: { + [SchemaAST.STRUCTURAL_ANNOTATION_KEY]: true, + arbitrary: { + constraint: { minLength } }, @@ -6516,12 +7554,14 @@ export function isMinLength(minLength: number, annotations?: Annotations.Filter) * Validates that a value has at least one element. Works with strings and arrays. * This is equivalent to `isMinLength(1)`. * - * **JSON Schema** + * **Details** + * + * JSON Schema: * * This check corresponds to the `minLength: 1` constraint for strings or the * `minItems: 1` constraint for arrays in JSON Schema. * - * **Arbitrary** + * Arbitrary: * * When generating test data with fast-check, this applies a `minLength: 1` * constraint to ensure generated strings or arrays are non-empty. @@ -6537,12 +7577,14 @@ export function isNonEmpty(annotations?: Annotations.Filter) { * Validates that a value has at most the specified length. Works with strings * and arrays. * - * **JSON Schema** + * **Details** + * + * JSON Schema: * * This check corresponds to the `maxLength` constraint for strings or the * `maxItems` constraint for arrays in JSON Schema. * - * **Arbitrary** + * Arbitrary: * * When generating test data with fast-check, this applies a `maxLength` * constraint to ensure generated strings or arrays have at most the required @@ -6561,12 +7603,9 @@ export function isMaxLength(maxLength: number, annotations?: Annotations.Filter) _tag: "isMaxLength", maxLength }, - [AST.STRUCTURAL_ANNOTATION_KEY]: true, - toArbitraryConstraint: { - string: { - maxLength - }, - array: { + [SchemaAST.STRUCTURAL_ANNOTATION_KEY]: true, + arbitrary: { + constraint: { maxLength } }, @@ -6579,12 +7618,14 @@ export function isMaxLength(maxLength: number, annotations?: Annotations.Filter) * Validates that a value's length is within the specified range. Works with * strings and arrays. * - * **JSON Schema** + * **Details** + * + * JSON Schema: * * This check corresponds to `minLength`/`maxLength` constraints for strings * or `minItems`/`maxItems` constraints for arrays in JSON Schema. * - * **Arbitrary** + * Arbitrary: * * When generating test data with fast-check, this applies `minLength` and * `maxLength` constraints to ensure generated strings or arrays have a length @@ -6607,13 +7648,9 @@ export function isLengthBetween(minimum: number, maximum: number, annotations?: minimum, maximum }, - [AST.STRUCTURAL_ANNOTATION_KEY]: true, - toArbitraryConstraint: { - string: { - minLength: minimum, - maxLength: maximum - }, - array: { + [SchemaAST.STRUCTURAL_ANNOTATION_KEY]: true, + arbitrary: { + constraint: { minLength: minimum, maxLength: maximum } @@ -6627,16 +7664,18 @@ export function isLengthBetween(minimum: number, maximum: number, annotations?: * Validates that a value has at least the specified size. Works with values * that have a `size` property, such as `Set` or `Map`. * - * **JSON Schema** + * **Details** + * + * JSON Schema: * * This check does not have a direct JSON Schema equivalent, as it applies to * values with a `size` property rather than standard JSON Schema types. * - * **Arbitrary** + * Arbitrary: * - * When generating test data with fast-check, this applies a `minLength` - * constraint to the array representation to ensure generated values have at - * least the required size. + * When generating test data with fast-check, this applies a node-local + * `minLength` constraint. Generators for values with a final `.size`, such as + * sets and maps, interpret it as final cardinality. * * @category Size checks * @since 4.0.0 @@ -6651,9 +7690,9 @@ export function isMinSize(minSize: number, annotations?: Annotations.Filter) { _tag: "isMinSize", minSize }, - [AST.STRUCTURAL_ANNOTATION_KEY]: true, - toArbitraryConstraint: { - array: { + [SchemaAST.STRUCTURAL_ANNOTATION_KEY]: true, + arbitrary: { + constraint: { minLength: minSize } }, @@ -6666,16 +7705,18 @@ export function isMinSize(minSize: number, annotations?: Annotations.Filter) { * Validates that a value has at most the specified size. Works with values * that have a `size` property, such as `Set` or `Map`. * - * **JSON Schema** + * **Details** + * + * JSON Schema: * * This check does not have a direct JSON Schema equivalent, as it applies to * values with a `size` property rather than standard JSON Schema types. * - * **Arbitrary** + * Arbitrary: * - * When generating test data with fast-check, this applies a `maxLength` - * constraint to the array representation to ensure generated values have at - * most the required size. + * When generating test data with fast-check, this applies a node-local + * `maxLength` constraint. Generators for values with a final `.size`, such as + * sets and maps, interpret it as final cardinality. * * @category Size checks * @since 4.0.0 @@ -6690,9 +7731,9 @@ export function isMaxSize(maxSize: number, annotations?: Annotations.Filter) { _tag: "isMaxSize", maxSize }, - [AST.STRUCTURAL_ANNOTATION_KEY]: true, - toArbitraryConstraint: { - array: { + [SchemaAST.STRUCTURAL_ANNOTATION_KEY]: true, + arbitrary: { + constraint: { maxLength: maxSize } }, @@ -6705,16 +7746,18 @@ export function isMaxSize(maxSize: number, annotations?: Annotations.Filter) { * Validates that a value's size is within the specified range. Works with * values that have a `size` property, such as `Set` or `Map`. * - * **JSON Schema** + * **Details** + * + * JSON Schema: * * This check does not have a direct JSON Schema equivalent, as it applies to * values with a `size` property rather than standard JSON Schema types. * - * **Arbitrary** + * Arbitrary: * - * When generating test data with fast-check, this applies `minLength` and - * `maxLength` constraints to ensure generated values have a size within the - * specified range. + * When generating test data with fast-check, this applies node-local + * `minLength` and `maxLength` constraints. Generators for values with a final + * `.size`, such as sets and maps, interpret them as final cardinality. * * @category Size checks * @since 4.0.0 @@ -6733,9 +7776,9 @@ export function isSizeBetween(minimum: number, maximum: number, annotations?: An minimum, maximum }, - [AST.STRUCTURAL_ANNOTATION_KEY]: true, - toArbitraryConstraint: { - array: { + [SchemaAST.STRUCTURAL_ANNOTATION_KEY]: true, + arbitrary: { + constraint: { minLength: minimum, maxLength: maximum } @@ -6750,16 +7793,17 @@ export function isSizeBetween(minimum: number, maximum: number, annotations?: An * properties. This includes both string and symbol keys when counting * properties. * - * **JSON Schema** + * **Details** + * + * JSON Schema: * * This check corresponds to the `minProperties` constraint in JSON Schema. * - * **Arbitrary** + * Arbitrary: * - * When generating test data with fast-check, this applies a `minLength` - * constraint to the array of entries that is generated before being converted - * to an object, ensuring the resulting object has at least the required number - * of properties. + * When generating test data with fast-check, this applies a node-local + * `minLength` constraint. Object generators interpret it as the final number + * of own properties. * * @category Object checks * @since 4.0.0 @@ -6774,9 +7818,9 @@ export function isMinProperties(minProperties: number, annotations?: Annotations _tag: "isMinProperties", minProperties }, - [AST.STRUCTURAL_ANNOTATION_KEY]: true, - toArbitraryConstraint: { - array: { + [SchemaAST.STRUCTURAL_ANNOTATION_KEY]: true, + arbitrary: { + constraint: { minLength: minProperties } }, @@ -6789,16 +7833,17 @@ export function isMinProperties(minProperties: number, annotations?: Annotations * Validates that an object contains at most the specified number of properties. * This includes both string and symbol keys when counting properties. * - * **JSON Schema** + * **Details** + * + * JSON Schema: * * This check corresponds to the `maxProperties` constraint in JSON Schema. * - * **Arbitrary** + * Arbitrary: * - * When generating test data with fast-check, this applies a `maxLength` - * constraint to the array of entries that is generated before being converted - * to an object, ensuring the resulting object has at most the required number - * of properties. + * When generating test data with fast-check, this applies a node-local + * `maxLength` constraint. Object generators interpret it as the final number + * of own properties. * * @category Object checks * @since 4.0.0 @@ -6813,9 +7858,9 @@ export function isMaxProperties(maxProperties: number, annotations?: Annotations _tag: "isMaxProperties", maxProperties }, - [AST.STRUCTURAL_ANNOTATION_KEY]: true, - toArbitraryConstraint: { - array: { + [SchemaAST.STRUCTURAL_ANNOTATION_KEY]: true, + arbitrary: { + constraint: { maxLength: maxProperties } }, @@ -6828,16 +7873,18 @@ export function isMaxProperties(maxProperties: number, annotations?: Annotations * Validates that an object contains between `minimum` and `maximum` properties (inclusive). * This includes both string and symbol keys when counting properties. * - * **JSON Schema** + * **Details** + * + * JSON Schema: * * This check corresponds to `minProperties` and `maxProperties` * constraints in JSON Schema. * - * **Arbitrary** + * Arbitrary: * - * When generating test data with fast-check, this applies `minLength` and - * `maxLength` constraints to the array of entries that is generated before - * being converted to an object. + * When generating test data with fast-check, this applies node-local + * `minLength` and `maxLength` constraints. Object generators interpret them as + * the final number of own properties. * * @category Object checks * @since 4.0.0 @@ -6856,9 +7903,9 @@ export function isPropertiesLengthBetween(minimum: number, maximum: number, anno minimum, maximum }, - [AST.STRUCTURAL_ANNOTATION_KEY]: true, - toArbitraryConstraint: { - array: { + [SchemaAST.STRUCTURAL_ANNOTATION_KEY]: true, + arbitrary: { + constraint: { minLength: minimum, maxLength: maximum } @@ -6869,32 +7916,37 @@ export function isPropertiesLengthBetween(minimum: number, maximum: number, anno } /** - * Validates that all property names in an object satisfy the provided key - * schema (encoded side of the schema). + * Validates that every own property key of an object satisfies the encoded side + * of the provided key schema. + * + * **Details** * - * **JSON Schema** + * This check uses `Reflect.ownKeys`, so symbol keys are validated in addition to + * string property names. * - * This check corresponds to the `propertyNames` constraint in JSON Schema. + * JSON Schema: + * For string property names, this corresponds to the `propertyNames` constraint + * in JSON Schema. * * @category Object checks * @since 4.0.0 */ export function isPropertyNames(keySchema: Top, annotations?: Annotations.Filter) { const propertyNames = toEncoded(keySchema) - const parser = Parser._issue(propertyNames.ast) + const parser = SchemaParser._issue(propertyNames.ast) return makeFilter( (input, ast, options) => { const keys = Reflect.ownKeys(input) - const issues: Array = [] + const issues: Array = [] for (const key of keys) { const issue = parser(key, options) if (issue !== undefined) { - issues.push(new Issue.Pointer([key], issue)) + issues.push(new SchemaIssue.Pointer([key], issue)) if (options.errors === "first") break } } if (Arr.isArrayNonEmpty(issues)) { - return new Issue.Composite(ast, Option_.some(input), issues) + return new SchemaIssue.Composite(ast, Option_.some(input), issues) } return true }, @@ -6904,25 +7956,24 @@ export function isPropertyNames(keySchema: Top, annotations?: Annotations.Filter _tag: "isPropertyNames", propertyNames: propertyNames.ast }, - [AST.STRUCTURAL_ANNOTATION_KEY]: true, + [SchemaAST.STRUCTURAL_ANNOTATION_KEY]: true, ...annotations } ) } /** - * Validates that all items in an array are unique according to the provided - * equivalence function. + * Validates that all items in an array are unique according to Effect equality. * - * **JSON Schema** + * **Details** * + * JSON Schema: * This check corresponds to the `uniqueItems: true` constraint in JSON Schema. * - * **Arbitrary** - * - * When generating test data with fast-check, this applies a `comparator` - * constraint using the provided equivalence function to ensure generated arrays - * contain only unique items. + * Arbitrary: + * When generating test data with fast-check, this applies a node-local + * `unique: true` constraint. Array generators translate it to `fast-check` + * `uniqueArray` using Effect equality. * * @category Array checks * @since 4.0.0 @@ -6936,9 +7987,9 @@ export function isUnique(annotations?: Annotations.Filter) { meta: { _tag: "isUnique" }, - toArbitraryConstraint: { - array: { - comparator: equivalence + arbitrary: { + constraint: { + unique: true } }, ...annotations @@ -6951,62 +8002,60 @@ export function isUnique(annotations?: Annotations.Filter) { // ----------------------------------------------------------------------------- /** - * Companion type for {@link NonEmptyString}. + * Type-level representation of {@link NonEmptyString}. * - * @category String - * @since 4.0.0 + * @category string + * @since 3.10.0 */ export interface NonEmptyString extends String { readonly "Rebuild": NonEmptyString } /** - * A schema for non-empty strings. Validates that a string has at least one + * Schema for non-empty strings. Validates that a string has at least one * character. * - * @category String - * @since 4.0.0 + * @category string + * @since 3.10.0 */ export const NonEmptyString: NonEmptyString = String.check(isNonEmpty()) /** - * Companion type for {@link Char}. + * Type-level representation of {@link Char}. * - * @category String - * @since 4.0.0 + * @category string + * @since 3.10.0 */ export interface Char extends String { readonly "Rebuild": Char } /** - * A schema representing a single character. + * Schema for strings whose JavaScript `length` is exactly `1`. * - * @category String - * @since 4.0.0 - */ -export const Char: Char = String.check(isLengthBetween(1, 1)) - -/** - * Schema for the `Option` type, representing an optional value that is - * either `None` or `Some`. + * **When to use** * - * **Example** (Option schema) + * Use to validate string values that must have `length === 1`. * - * ```ts - * import { Schema } from "effect" - * import { Option } from "effect" + * **Gotchas** * - * const schema = Schema.Option(Schema.Number) + * This schema uses JavaScript `String.length`, so visible characters made from + * multiple UTF-16 code units do not satisfy `length === 1`. * - * Schema.decodeUnknownSync(schema)(Option.some(1)) - * // => Some(1) - * Schema.decodeUnknownSync(schema)(Option.none()) - * // => None - * ``` + * @see {@link String} for unconstrained string values + * @see {@link NonEmptyString} for strings with length greater than zero + * @see {@link isLengthBetween} for the underlying length check + * + * @category string + * @since 3.10.0 + */ +export const Char: Char = String.check(isLengthBetween(1, 1)) + +/** + * Type-level representation returned by {@link Option}. * * @category Option - * @since 4.0.0 + * @since 3.10.0 */ export interface Option extends declareConstructor< @@ -7021,6 +8070,13 @@ export interface Option extends } /** + * Iso representation used for `Option` schemas. + * + * **Details** + * + * `None` is represented as `{ _tag: "None" }`, while `Some` is represented as + * `{ _tag: "Some", value }` using the wrapped schema's `Iso` type. + * * @category Option * @since 4.0.0 */ @@ -7029,10 +8085,10 @@ export type OptionIso = | { readonly _tag: "Some"; readonly value: A["Iso"] } /** - * Creates a schema for `Option`. See {@link Option} for details. + * Schema for `Option` values. * * @category Option - * @since 4.0.0 + * @since 3.10.0 */ export function Option(value: A): Option { const schema = declareConstructor< @@ -7047,14 +8103,15 @@ export function Option(value: A): Option { return Effect.succeedNone } return Effect.mapBothEager( - Parser.decodeUnknownEffect(value)(input.value, options), + SchemaParser.decodeUnknownEffect(value)(input.value, options), { onSuccess: Option_.some, - onFailure: (issue) => new Issue.Composite(ast, Option_.some(input), [new Issue.Pointer(["value"], issue)]) + onFailure: (issue) => + new SchemaIssue.Composite(ast, Option_.some(input), [new SchemaIssue.Pointer(["value"], issue)]) } ) } - return Effect.fail(new Issue.InvalidType(ast, Option_.some(input))) + return Effect.fail(new SchemaIssue.InvalidType(ast, Option_.some(input))) }, { typeConstructor: { @@ -7072,17 +8129,18 @@ export function Option(value: A): Option { Struct({ _tag: Literal("Some"), value }), Struct({ _tag: Literal("None") }) ]), - Transformation.transform({ + SchemaTransformation.transform({ decode: (e) => e._tag === "None" ? Option_.none() : Option_.some(e.value), encode: (o) => (Option_.isSome(o) ? { _tag: "Some", value: o.value } as const : { _tag: "None" } as const) }) ), toArbitrary: ([value]) => (fc, ctx) => { - return fc.oneof( - ctx?.isSuspend ? { maxDepth: 2, depthIdentifier: "Option" } : {}, - fc.constant(Option_.none()), - value.map(Option_.some) + const terminal = fc.constant(Option_.none()) + const arbitrary = fc.oneof( + terminal, + value.arbitrary.map(Option_.some) ) + return withRecursion(fc, ctx, terminal, arbitrary) }, toEquivalence: ([value]) => Option_.makeEquivalence(value), toFormatter: ([value]) => @@ -7096,10 +8154,10 @@ export function Option(value: A): Option { } /** - * Companion type for {@link OptionFromNullOr}. + * Type-level representation returned by {@link OptionFromNullOr}. * * @category Option - * @since 4.0.0 + * @since 3.10.0 */ export interface OptionFromNullOr extends decodeTo>, NullOr> { readonly "Rebuild": OptionFromNullOr @@ -7108,60 +8166,55 @@ export interface OptionFromNullOr extends decodeTo` value. * - * Decoding: - * - `null` is decoded as `None` - * - other values are decoded as `Some` + * **Details** * - * Encoding: - * - `None` is encoded as `null` - * - `Some` is encoded as the value + * Decoding maps `null` to `None` and all other values to `Some`. Encoding maps + * `None` to `null` and maps `Some` to its value. * * @category Option - * @since 4.0.0 + * @since 3.10.0 */ export function OptionFromNullOr(schema: S): OptionFromNullOr { return NullOr(schema).pipe(decodeTo( Option(toType(schema)), - Transformation.optionFromNullOr() + SchemaTransformation.optionFromNullOr() )) } /** - * Companion type for {@link OptionFromUndefinedOr}. + * Type-level representation returned by {@link OptionFromUndefinedOr}. * * @category Option - * @since 4.0.0 + * @since 3.10.0 */ export interface OptionFromUndefinedOr extends decodeTo>, UndefinedOr> { readonly "Rebuild": OptionFromUndefinedOr } /** - * Decodes an undefined-or value `T` to a required `Option` value. + * Decodes a required value that may be `undefined` to a required `Option` + * value. * - * Decoding: - * - `undefined` is decoded as `None` - * - other values are decoded as `Some` + * **Details** * - * Encoding: - * - `None` is encoded as `undefined` - * - `Some` is encoded as the value + * Decoding maps `undefined` to `None` and all other values to `Some`. Encoding + * maps `None` to `undefined` and maps `Some` to its value. * * @category Option - * @since 4.0.0 + * @since 3.10.0 */ export function OptionFromUndefinedOr(schema: S): OptionFromUndefinedOr { return UndefinedOr(schema).pipe(decodeTo( Option(toType(schema)), - Transformation.optionFromUndefinedOr() + SchemaTransformation.optionFromUndefinedOr() )) } /** - * Companion type for {@link OptionFromNullishOr}. + * Type-level representation returned by {@link OptionFromNullishOr}. * * @category Option - * @since 4.0.0 + * @since 3.10.0 */ export interface OptionFromNullishOr extends decodeTo>, NullishOr> { readonly "Rebuild": OptionFromNullishOr @@ -7170,16 +8223,15 @@ export interface OptionFromNullishOr extends decodeTo` value. * - * Decoding: - * - `null` and `undefined` are decoded as `None` - * - other values are decoded as `Some` + * **Details** * - * Encoding: - * - `None` is encoded as `null` or `undefined` depending on the provided `options.onNoneEncoding` (defaults to `undefined`) - * - `Some` is encoded as the value + * Decoding maps `null` and `undefined` to `None` and all other values to + * `Some`. Encoding maps `None` to `null` or `undefined` depending on + * `options.onNoneEncoding`, which defaults to `undefined`, and maps `Some` to + * its value. * * @category Option - * @since 4.0.0 + * @since 3.10.0 */ export function OptionFromNullishOr( schema: S, @@ -7189,12 +8241,12 @@ export function OptionFromNullishOr( ): OptionFromNullishOr { return NullishOr(schema).pipe(decodeTo( Option(toType(schema)), - Transformation.optionFromNullishOr(options) + SchemaTransformation.optionFromNullishOr(options) )) } /** - * Companion type for {@link OptionFromOptionalKey}. + * Type-level representation returned by {@link OptionFromOptionalKey}. * * @category Option * @since 4.0.0 @@ -7206,13 +8258,10 @@ export interface OptionFromOptionalKey extends decodeTo` value. * - * Decoding: - * - a missing key is decoded as `None` - * - a present value is decoded as `Some` + * **Details** * - * Encoding: - * - `None` is encoded as missing key - * - `Some` is encoded as the value + * Decoding maps a missing key to `None` and a present value to `Some`. + * Encoding maps `None` to a missing key and maps `Some` to its value. * * @category Option * @since 4.0.0 @@ -7220,12 +8269,12 @@ export interface OptionFromOptionalKey extends decodeTo(schema: S): OptionFromOptionalKey { return optionalKey(schema).pipe(decodeTo( Option(toType(schema)), - Transformation.optionFromOptionalKey() + SchemaTransformation.optionFromOptionalKey() )) } /** - * Companion type for {@link OptionFromOptional}. + * Type-level representation returned by {@link OptionFromOptional}. * * @category Option * @since 4.0.0 @@ -7235,17 +8284,14 @@ export interface OptionFromOptional extends decodeTo` + * Decodes an optional or `undefined` value `A` to a required `Option` * value. * - * Decoding: - * - a missing key is decoded as `None` - * - a present key with an `undefined` value is decoded as `None` - * - all other values are decoded as `Some` + * **Details** * - * Encoding: - * - `None` is encoded as missing key - * - `Some` is encoded as the value + * Decoding maps a missing key or a present `undefined` value to `None`, and + * maps all other values to `Some`. Encoding maps `None` to a missing key and + * maps `Some` to its value. * * @category Option * @since 4.0.0 @@ -7253,12 +8299,12 @@ export interface OptionFromOptional extends decodeTo(schema: S): OptionFromOptional { return optional(schema).pipe(decodeTo( Option(toType(schema)), - Transformation.optionFromOptional() + SchemaTransformation.optionFromOptional() )) } /** - * Companion type for {@link OptionFromOptionalNullOr}. + * Type-level representation returned by {@link OptionFromOptionalNullOr}. * * @category Option * @since 4.0.0 @@ -7271,17 +8317,12 @@ export interface OptionFromOptionalNullOr extends decodeTo extends @@ -7328,7 +8368,14 @@ export interface Result extends } /** - * @category Result + * Iso representation used for `Result` schemas. + * + * **Details** + * + * Successful results are represented as `{ _tag: "Success", success }`, while + * failed results are represented as `{ _tag: "Failure", failure }`. + * + * @category schemas * @since 4.0.0 */ export type ResultIso = @@ -7336,9 +8383,9 @@ export type ResultIso = | { readonly _tag: "Failure"; readonly failure: E["Iso"] } /** - * Creates a schema for `Result`. See {@link Result} for details. + * Schema for `Result` values. * - * @category Result + * @category schemas * @since 4.0.0 */ export function Result( @@ -7353,18 +8400,20 @@ export function Result( [success, failure], ([success, failure]) => (input, ast, options) => { if (!Result_.isResult(input)) { - return Effect.fail(new Issue.InvalidType(ast, Option_.some(input))) + return Effect.fail(new SchemaIssue.InvalidType(ast, Option_.some(input))) } switch (input._tag) { case "Success": - return Effect.mapBothEager(Parser.decodeEffect(success)(input.success, options), { + return Effect.mapBothEager(SchemaParser.decodeEffect(success)(input.success, options), { onSuccess: Result_.succeed, - onFailure: (issue) => new Issue.Composite(ast, Option_.some(input), [new Issue.Pointer(["success"], issue)]) + onFailure: (issue) => + new SchemaIssue.Composite(ast, Option_.some(input), [new SchemaIssue.Pointer(["success"], issue)]) }) case "Failure": - return Effect.mapBothEager(Parser.decodeEffect(failure)(input.failure, options), { + return Effect.mapBothEager(SchemaParser.decodeEffect(failure)(input.failure, options), { onSuccess: Result_.fail, - onFailure: (issue) => new Issue.Composite(ast, Option_.some(input), [new Issue.Pointer(["failure"], issue)]) + onFailure: (issue) => + new SchemaIssue.Composite(ast, Option_.some(input), [new SchemaIssue.Pointer(["failure"], issue)]) }) } }, @@ -7384,7 +8433,7 @@ export function Result( Struct({ _tag: Literal("Success"), success }), Struct({ _tag: Literal("Failure"), failure }) ]), - Transformation.transform({ + SchemaTransformation.transform({ decode: (e): Result_.Result => e._tag === "Success" ? Result_.succeed(e.success) : Result_.fail(e.failure), encode: (r) => @@ -7394,11 +8443,16 @@ export function Result( }) ), toArbitrary: ([success, failure]) => (fc, ctx) => { - return fc.oneof( - ctx?.isSuspend ? { maxDepth: 2, depthIdentifier: "Result" } : {}, - success.map(Result_.succeed), - failure.map(Result_.fail) + const terminal = oneOfArbitraries( + fc, + success.terminal?.map((a): Result_.Result => Result_.succeed(a)), + failure.terminal?.map((e): Result_.Result => Result_.fail(e)) + ) + const arbitrary = fc.oneof( + success.arbitrary.map((a): Result_.Result => Result_.succeed(a)), + failure.arbitrary.map((e): Result_.Result => Result_.fail(e)) ) + return withRecursion(fc, ctx, terminal, arbitrary) }, toEquivalence: ([success, failure]) => Result_.makeEquivalence(success, failure), toFormatter: ([success, failure]) => @@ -7412,11 +8466,10 @@ export function Result( } /** - * Schema for the `Redacted` type, providing secure handling of sensitive - * values. The inner value is hidden from error messages. + * Type-level representation returned by {@link Redacted}. * * @category Redacted - * @since 4.0.0 + * @since 3.10.0 */ export interface Redacted extends declareConstructor< @@ -7430,69 +8483,71 @@ export interface Redacted extends } /** - * Creates a schema for the `Redacted` type, providing secure handling of - * sensitive information. + * Schema for values that hide sensitive information from error output and + * inspection. + * + * **Details** * * If the wrapped schema fails, the issue will be redacted to prevent both * the actual value and the schema details from being exposed. * - * **Options** + * Options: * * - `label`: When provided, the schema will behave as follows: * - Values will be validated against the label in addition to the wrapped schema * - The default JSON serializer will deserialize into a `Redacted` instance with the label * - The arbitrary generator will produce a `Redacted` instance with the label * - The formatter will return the label - * - * **Default JSON serializer** - * - * The default JSON serializer will fail when attempting to serialize a `Redacted` value, - * but it will deserialize a value into a `Redacted` instance. + * - `disallowJsonEncode`: When set to `true`, when attempting to encode a `Redacted` instance + * into JSON, it will fail with an error. This is useful when the wrapped schema is + * sensitive and should not be exposed in JSON. * * @category Redacted - * @since 4.0.0 + * @since 3.10.0 */ export function Redacted(value: S, options?: { readonly label?: string | undefined + readonly disallowJsonEncode?: boolean | undefined }): Redacted { const decodeLabel = typeof options?.label === "string" - ? Parser.decodeUnknownEffect(Literal(options.label)) + ? SchemaParser.decodeUnknownEffect(Literal(options.label)) : undefined const schema = declareConstructor, Redacted_.Redacted>()( [value], ([value]) => (input, ast, poptions) => { if (Redacted_.isRedacted(input)) { - const label: Effect.Effect = decodeLabel !== undefined + const label: Effect.Effect = decodeLabel !== undefined ? Effect.mapErrorEager( decodeLabel(input.label, poptions), - (issue) => new Issue.Pointer(["label"], issue) + (issue) => new SchemaIssue.Pointer(["label"], issue) ) : Effect.void return Effect.flatMapEager( label, () => Effect.mapBothEager( - Parser.decodeUnknownEffect(value)(Redacted_.value(input), poptions), + SchemaParser.decodeUnknownEffect(value)(Redacted_.value(input), poptions), { onSuccess: () => input, onFailure: (/** ignore the actual issue because of security reasons */) => { const oinput = Option_.some(input) - return new Issue.Composite(ast, oinput, [ - new Issue.Pointer(["value"], new Issue.InvalidValue(oinput)) + return new SchemaIssue.Composite(ast, oinput, [ + new SchemaIssue.Pointer(["value"], new SchemaIssue.InvalidValue(oinput)) ]) } } ) ) } - return Effect.fail(new Issue.InvalidType(ast, Option_.some(input))) + return Effect.fail(new SchemaIssue.InvalidType(ast, Option_.some(input))) }, { typeConstructor: { - _tag: "effect/Redacted" + _tag: "effect/Redacted", + options }, generation: { - runtime: `Schema.Redacted(?)`, + runtime: options !== undefined ? `Schema.Redacted(?, ${format(options)})` : `Schema.Redacted(?)`, Type: `Redacted.Redacted`, importDeclaration: `import * as Redacted from "effect/Redacted"` }, @@ -7501,14 +8556,19 @@ export function Redacted(value: S, options?: { link>()( redact(value), { - decode: Getter.transform((e) => Redacted_.make(e, { label: options?.label })), - encode: Getter.forbidden((oe) => - "Cannot serialize Redacted" + - (Option_.isSome(oe) && typeof oe.value.label === "string" ? ` with label: "${oe.value.label}"` : "") - ) + decode: SchemaGetter.transform((e) => Redacted_.make(e, { label: options?.label })), + encode: options?.disallowJsonEncode ? + SchemaGetter.forbidden((oe) => + "Cannot serialize Redacted" + + (Option_.isSome(oe) && typeof oe.value.label === "string" ? ` with label: "${oe.value.label}"` : "") + ) : + SchemaGetter.transform(Redacted_.value) } ), - toArbitrary: ([value]) => () => value.map((a) => Redacted_.make(a, { label: options?.label })), + toArbitrary: ([value]) => () => ({ + arbitrary: value.arbitrary.map((a) => Redacted_.make(a, { label: options?.label })), + terminal: value.terminal?.map((a) => Redacted_.make(a, { label: options?.label })) + }), toFormatter: () => globalThis.String, toEquivalence: ([value]) => Redacted_.makeEquivalence(value) } @@ -7517,7 +8577,7 @@ export function Redacted(value: S, options?: { } /** - * Companion type for {@link RedactedFromValue}. + * Type-level representation returned by {@link RedactedFromValue}. * * @category Redacted * @since 4.0.0 @@ -7536,7 +8596,7 @@ export interface RedactedFromValue * @since 4.0.0 */ export function redact(schema: S): middlewareDecoding { - return schema.pipe(middlewareDecoding(Effect.mapErrorEager(Issue.redact))) + return schema.pipe(middlewareDecoding(Effect.mapErrorEager(SchemaIssue.redact))) } /** @@ -7549,22 +8609,29 @@ export function redact(schema: S): middlewareDecoding(value: S, options?: { readonly label?: string | undefined + readonly disallowEncode?: boolean | undefined }): RedactedFromValue { return redact(value).pipe( - decodeTo(Redacted(toType(value), options), { - decode: Getter.transform((t) => Redacted_.make(t, { label: options?.label })), - encode: Getter.forbidden((oe) => - "Cannot encode Redacted" + - (Option_.isSome(oe) && typeof oe.value.label === "string" ? ` with label: "${oe.value.label}"` : "") - ) - }) + decodeTo( + Redacted(toType(value), { + label: options?.label, + disallowJsonEncode: options?.disallowEncode + }), + { + decode: SchemaGetter.transform((t) => Redacted_.make(t, { label: options?.label })), + encode: options?.disallowEncode ? + SchemaGetter.forbidden((oe) => + "Cannot encode Redacted" + + (Option_.isSome(oe) && typeof oe.value.label === "string" ? ` with label: "${oe.value.label}"` : "") + ) : + SchemaGetter.transform(Redacted_.value) + } + ) ) } /** - * Schema for a single `Cause.Reason`, representing one reason a fiber may - * fail: a typed error (`Fail`), an unexpected defect (`Die`), or an interrupt - * (`Interrupt`). + * Type-level representation returned by {@link CauseReason}. * * @category CauseReason * @since 4.0.0 @@ -7583,6 +8650,13 @@ export interface CauseReason extends } /** + * Iso representation used for `CauseReason` schemas. + * + * **Details** + * + * Failures are represented with a `Fail` tag and encoded error, defects with a + * `Die` tag and encoded defect, and interrupts with an optional `fiberId`. + * * @category CauseReason * @since 4.0.0 */ @@ -7598,7 +8672,21 @@ export type CauseReasonIso = { } /** - * Creates a schema for `Cause.Reason`. See {@link CauseReason} for details. + * Creates a schema for `Cause.Reason` values using separate schemas for typed + * failures and unexpected defects. + * + * **When to use** + * + * Use when serializing or decoding individual cause reasons separately from a + * full failure cause, with distinct schemas for typed errors and defects. + * + * **Details** + * + * `Fail` reasons use the `error` schema, `Die` reasons use the `defect` schema, + * and `Interrupt` reasons carry only an optional fiber id. + * + * @see {@link Cause} for constructing schemas for full Cause values + * @see {@link CauseReasonIso} for the ISO shape of each cause reason * * @category CauseReason * @since 4.0.0 @@ -7608,24 +8696,25 @@ export function CauseReason(error: E, defect: D): [error, defect], ([error, defect]) => (input, ast, options) => { if (!Cause_.isReason(input)) { - return Effect.fail(new Issue.InvalidType(ast, Option_.some(input))) + return Effect.fail(new SchemaIssue.InvalidType(ast, Option_.some(input))) } switch (input._tag) { case "Fail": return Effect.mapBothEager( - Parser.decodeUnknownEffect(error)(input.error, options), + SchemaParser.decodeUnknownEffect(error)(input.error, options), { onSuccess: Cause_.makeFailReason, - onFailure: (issue) => new Issue.Composite(ast, Option_.some(input), [new Issue.Pointer(["error"], issue)]) + onFailure: (issue) => + new SchemaIssue.Composite(ast, Option_.some(input), [new SchemaIssue.Pointer(["error"], issue)]) } ) case "Die": return Effect.mapBothEager( - Parser.decodeUnknownEffect(defect)(input.defect, options), + SchemaParser.decodeUnknownEffect(defect)(input.defect, options), { onSuccess: Cause_.makeDieReason, onFailure: (issue) => - new Issue.Composite(ast, Option_.some(input), [new Issue.Pointer(["defect"], issue)]) + new SchemaIssue.Composite(ast, Option_.some(input), [new SchemaIssue.Pointer(["defect"], issue)]) } ) case "Interrupt": @@ -7649,7 +8738,7 @@ export function CauseReason(error: E, defect: D): Struct({ _tag: Literal("Die"), defect }), Struct({ _tag: Literal("Interrupt"), fiberId: UndefinedOr(Finite) }) ]), - Transformation.transform({ + SchemaTransformation.transform({ decode: (e) => { switch (e._tag) { case "Fail": @@ -7671,15 +8760,19 @@ export function CauseReason(error: E, defect: D): return make(schema.ast, { error, defect }) } -function causeReasonToArbitrary(error: FastCheck.Arbitrary, defect: FastCheck.Arbitrary) { - return (fc: typeof FastCheck, ctx: Annotations.ToArbitrary.Context | undefined) => { - return fc.oneof( - ctx?.isSuspend ? { maxDepth: 2, depthIdentifier: "Cause.Failure" } : {}, - fc.constant(Cause_.makeInterruptReason()), +function causeReasonToArbitrary( + error: Annotations.ToArbitrary.TypeParameter, + defect: Annotations.ToArbitrary.TypeParameter +) { + return (fc: typeof FastCheck, ctx: Annotations.ToArbitrary.Context) => { + const terminal = fc.constant(Cause_.makeInterruptReason()) + const arbitrary = fc.oneof( + terminal, fc.integer({ min: 1 }).map(Cause_.makeInterruptReason), - error.map((e) => Cause_.makeFailReason(e)), - defect.map((d) => Cause_.makeDieReason(d)) + error.arbitrary.map((e) => Cause_.makeFailReason(e)), + defect.arbitrary.map((d) => Cause_.makeDieReason(d)) ) + return withRecursion(fc, ctx, terminal, arbitrary) } } @@ -7711,11 +8804,10 @@ function causeReasonToFormatter(error: Formatter, defect: Formatter`, an ordered collection of reasons a fiber failed, - * combining typed errors, defects, and interrupts. + * Type-level representation returned by {@link Cause}. * * @category Cause - * @since 4.0.0 + * @since 3.10.0 */ export interface Cause extends declareConstructor< @@ -7731,16 +8823,42 @@ export interface Cause extends } /** + * Iso representation used for `Cause` schemas: an ordered array of + * `CauseReasonIso` values. + * + * **When to use** + * + * Use when working with the ISO shape of a `Cause` schema, such as `toIso` + * optics or codecs that expose a cause as its ordered array of encoded reasons. + * + * @see {@link Cause} for constructing schemas for full Cause values + * @see {@link CauseReasonIso} for the ISO shape of each array element + * * @category Cause * @since 4.0.0 */ export type CauseIso = ReadonlyArray> /** - * Creates a schema for `Cause`. See {@link Cause} for details. + * Creates a schema for `Cause` values using separate schemas for typed failures + * and unexpected defects. + * + * **When to use** + * + * Use to validate, transform, or serialize Effect failure causes when typed + * failures and unexpected defects need separate schemas. + * + * **Details** + * + * The `error` schema is applied to `Fail` reasons and the `defect` schema is + * applied to `Die` reasons. Interrupt reasons do not use either schema and + * carry only an optional fiber id. + * + * @see {@link CauseReason} for the schema used by each individual cause reason + * @see {@link CauseIso} for the ordered array representation used by the schema ISO * * @category Cause - * @since 4.0.0 + * @since 3.10.0 */ export function Cause(error: E, defect: D): Cause { const schema = declareConstructor, Cause_.Cause, CauseIso>()( @@ -7749,11 +8867,12 @@ export function Cause(error: E, defect: D): Cause< const failures = ArraySchema(CauseReason(error, defect)) return (input, ast, options) => { if (!Cause_.isCause(input)) { - return Effect.fail(new Issue.InvalidType(ast, Option_.some(input))) + return Effect.fail(new SchemaIssue.InvalidType(ast, Option_.some(input))) } - return Effect.mapBothEager(Parser.decodeUnknownEffect(failures)(input.reasons, options), { + return Effect.mapBothEager(SchemaParser.decodeUnknownEffect(failures)(input.reasons, options), { onSuccess: Cause_.fromReasons, - onFailure: (issue) => new Issue.Composite(ast, Option_.some(input), [new Issue.Pointer(["failures"], issue)]) + onFailure: (issue) => + new SchemaIssue.Composite(ast, Option_.some(input), [new SchemaIssue.Pointer(["failures"], issue)]) }) } }, @@ -7770,7 +8889,7 @@ export function Cause(error: E, defect: D): Cause< toCodec: ([error, defect]) => link>()( ArraySchema(CauseReason(error, defect)), - Transformation.transform({ + SchemaTransformation.transform({ decode: Cause_.fromReasons, encode: ({ reasons: failures }) => failures }) @@ -7783,9 +8902,15 @@ export function Cause(error: E, defect: D): Cause< return make(schema.ast, { error, defect }) } -function causeToArbitrary(error: FastCheck.Arbitrary, defect: FastCheck.Arbitrary) { - return (fc: typeof FastCheck, ctx: Annotations.ToArbitrary.Context | undefined) => { - return fc.array(causeReasonToArbitrary(error, defect)(fc, ctx)).map(Cause_.fromReasons) +function causeToArbitrary( + error: Annotations.ToArbitrary.TypeParameter, + defect: Annotations.ToArbitrary.TypeParameter +) { + return (fc: typeof FastCheck, ctx: Annotations.ToArbitrary.Context) => { + const reason = causeReasonToArbitrary(error, defect)(fc, ctx) + const terminal = fc.constant(Cause_.empty) + const arbitrary = fc.array(reason.arbitrary).map(Cause_.fromReasons) + return withRecursion(fc, ctx, terminal, arbitrary) } } @@ -7800,7 +8925,7 @@ function causeToFormatter(error: Formatter, defect: Formatter) { } /** - * Companion type for {@link Error}. + * Type-level representation of {@link Error}. * * @category Error * @since 4.0.0 @@ -7809,143 +8934,157 @@ export interface Error extends instanceOf { readonly "Rebuild": Error } -const ErrorJsonEncoded = Struct({ - message: String, - name: optionalKey(String), - stack: optionalKey(String) -}) - /** - * A schema that represents `Error` objects. - * - * The default json serializer decodes to a struct with `name` and `message` - * properties (stack is omitted for security). + * Options for {@link Error} and {@link Defect}. * - * @category Schemas + * @category options * @since 4.0.0 */ -export const Error: Error = instanceOf(globalThis.Error, { - typeConstructor: { - _tag: "Error" - }, - generation: { - runtime: `Schema.Error`, - Type: `globalThis.Error` - }, - expected: "Error", - toCodecJson: () => link()(ErrorJsonEncoded, Transformation.errorFromErrorJsonEncoded()), - toArbitrary: () => (fc) => fc.string().map((message) => new globalThis.Error(message)) -}) +export interface ErrorOptions { + /** + * Includes string stack traces in encoded `Error` values when set to `true`. + * + * @default false + */ + readonly includeStack?: boolean | undefined + /** + * Excludes `Error.cause` values from encoded `Error` values when set to + * `true`. + * + * @default false + */ + readonly excludeCause?: boolean | undefined +} + +type ErrorOptionsKey = 0 | 1 | 2 | 3 + +const getErrorOptionsKey = (options?: ErrorOptions): ErrorOptionsKey => + ((options?.includeStack === true ? 1 : 0) | + (options?.excludeCause === true ? 2 : 0)) as ErrorOptionsKey + +const getErrorOptions = (key: ErrorOptionsKey): ErrorOptions | undefined => { + switch (key) { + case 0: + return undefined + case 1: + return { includeStack: true } + case 2: + return { excludeCause: true } + case 3: + return { includeStack: true, excludeCause: true } + } +} + +const errorSchemaCache: Array = [] /** - * A schema that represents `Error` objects. + * Schema for JavaScript `Error` objects. * - * The default json serializer decodes to a struct with `name`, `message` and - * `stack` properties. + * **Details** * - * @category Schemas + * Default JSON serializer: + * + * Encodes an `Error` as an object with `message`, optional `name`, and optional + * `cause` properties, and decodes that object back into an `Error`. Stack + * traces are omitted by default for security. Pass `{ includeStack: true }` to + * include stack traces, or `{ excludeCause: true }` to omit causes. + * + * @category constructors * @since 4.0.0 */ -export const ErrorWithStack: Error = instanceOf(globalThis.Error, { - typeConstructor: { - _tag: "ErrorWithStack" - }, - generation: { - runtime: `Schema.ErrorWithStack`, - Type: `globalThis.Error` - }, - expected: "Error", - toCodecJson: () => - link()( - ErrorJsonEncoded, - Transformation.errorFromErrorJsonEncoded({ - includeStack: true - }) - ), - toArbitrary: () => (fc) => fc.string().map((message) => new globalThis.Error(message)) -}) +export function Error(options?: ErrorOptions): Error { + const key = getErrorOptionsKey(options) + const cached = errorSchemaCache[key] + if (cached !== undefined) { + return cached + } + const normalizedOptions = getErrorOptions(key) + const schema = instanceOf(globalThis.Error, { + typeConstructor: { + _tag: "Error", + ...(normalizedOptions === undefined ? {} : { options: normalizedOptions }) + }, + generation: { + runtime: normalizedOptions !== undefined ? `Schema.Error(${format(normalizedOptions)})` : `Schema.Error()`, + Type: `globalThis.Error` + }, + expected: "Error", + toCodecJson: () => link()(JsonError, SchemaTransformation.errorFromJsonError(normalizedOptions)), + toArbitrary: () => (fc) => fc.string().map((message) => new globalThis.Error(message)) + }) + errorSchemaCache[key] = schema + return schema +} /** - * Companion type for {@link Defect}. + * Type-level representation of {@link Defect}. * * @category Defect - * @since 4.0.0 + * @since 3.10.0 */ -export interface Defect extends - Union< - readonly [ - decodeTo< - Error, - Struct<{ - readonly message: String - readonly name: optionalKey - readonly stack: optionalKey - }> - >, - decodeTo - ] - > -{ +export interface Defect extends decodeTo { readonly "Rebuild": Defect } -const defectTransformation = new Transformation.Transformation( - Getter.passthrough(), - Getter.transform((u) => { - try { - return JSON.parse(JSON.stringify(u)) - } catch { - return format(u) - } - }) -) +const defectSchemaCache: Array = [] /** - * A schema that represents defects. + * Schema for unexpected defect values represented as `unknown` with a JSON + * encoded form. + * + * **When to use** + * + * Use when you need a schema for `Cause` defects or other unexpected failures + * whose runtime value may be any value. + * + * **Details** + * + * The encoded side is {@link Json}. During decoding, JSON objects with a string + * `message` property are decoded into JavaScript `Error` values, preserving a + * non-default `name` and any string `stack`. Other JSON values decode + * unchanged. + * + * During encoding, JavaScript `Error` values encode to JSON objects with + * `name`, `message`, and optional `cause` properties. Pass + * `{ includeStack: true }` to include string stack traces in encoded `Error` + * defects, or `{ excludeCause: true }` to omit causes. Other values are + * serialized through Effect's JSON formatter and then parsed back into JSON + * when possible. + * + * **Gotchas** + * + * This schema is for carrying defects across JSON boundaries, not for + * preserving every JavaScript value exactly. Some values cannot round-trip + * unchanged: * - * @category Constructors - * @since 4.0.0 - */ -export const Defect: Defect = Union([ - ErrorJsonEncoded.pipe(decodeTo(Error, Transformation.errorFromErrorJsonEncoded())), - Any.pipe(decodeTo( - Unknown.annotate({ - toCodecJson: () => link()(Any, defectTransformation), - toArbitrary: () => (fc) => fc.json() - }), - defectTransformation - )) -]) - -/** - * A schema that represents defects, that also includes stack traces in the - * encoded form. + * - A non-`Error` object such as `{ message: "boom" }` encodes as an + * error-shaped JSON object and decodes back as an `Error`. + * - JSON serialization normalizes unsupported values. For example, + * `undefined` array elements encode as `null`, unsupported object properties + * are omitted, and circular references are dropped. + * - Values that cannot be represented as JSON fall back to Effect's formatted + * string representation. * - * @category Defect + * @see {@link Error} for a schema that only accepts JavaScript `Error` values. + * @category constructors * @since 4.0.0 */ -export const DefectWithStack: Defect = Union([ - ErrorJsonEncoded.pipe(decodeTo( - ErrorWithStack, - Transformation.errorFromErrorJsonEncoded({ - includeStack: true - }) - )), - Any.pipe(decodeTo( - Unknown.annotate({ - toCodecJson: () => link()(Any, defectTransformation), - toArbitrary: () => (fc) => fc.json() - }), - defectTransformation - )) -]) +export function Defect(options?: ErrorOptions): Defect { + const key = getErrorOptionsKey(options) + const cached = defectSchemaCache[key] + if (cached !== undefined) { + return cached + } + const schema = Json.pipe(decodeTo(Unknown, SchemaTransformation.defectFromJson(getErrorOptions(key)))) + defectSchemaCache[key] = schema + return schema +} /** - * Schema for `Exit`, representing the result of a fiber execution — - * either a success with value `A` or a failure with `Cause`. + * Type-level representation returned by {@link Exit}. * * @category Exit - * @since 4.0.0 + * @since 3.10.0 */ export interface Exit extends declareConstructor< @@ -7962,6 +9101,13 @@ export interface Exit extends } /** + * Iso representation used for `Exit` schemas. + * + * **Details** + * + * Successful exits are represented as `{ _tag: "Success", value }`, while failed + * exits are represented as `{ _tag: "Failure", cause }`. + * * @category Exit * @since 4.0.0 */ @@ -7974,10 +9120,16 @@ export type ExitIso = { } /** - * Creates a schema for `Exit`. See {@link Exit} for details. + * Creates a schema for `Exit` values using schemas for the success value, typed + * failure, and unexpected defect channels. + * + * **When to use** + * + * Use when serializing or validating an effect outcome where success, typed + * failure, and defects each need their own schema. * * @category Exit - * @since 4.0.0 + * @since 3.10.0 */ export function Exit(value: A, error: E, defect: D): Exit { const schema = declareConstructor< @@ -7990,25 +9142,25 @@ export function Exit(value: A, erro const cause = Cause(error, defect) return (input, ast, options) => { if (!Exit_.isExit(input)) { - return Effect.fail(new Issue.InvalidType(ast, Option_.some(input))) + return Effect.fail(new SchemaIssue.InvalidType(ast, Option_.some(input))) } switch (input._tag) { case "Success": return Effect.mapBothEager( - Parser.decodeUnknownEffect(value)(input.value, options), + SchemaParser.decodeUnknownEffect(value)(input.value, options), { onSuccess: Exit_.succeed, onFailure: (issue) => - new Issue.Composite(ast, Option_.some(input), [new Issue.Pointer(["value"], issue)]) + new SchemaIssue.Composite(ast, Option_.some(input), [new SchemaIssue.Pointer(["value"], issue)]) } ) case "Failure": return Effect.mapBothEager( - Parser.decodeUnknownEffect(cause)(input.cause, options), + SchemaParser.decodeUnknownEffect(cause)(input.cause, options), { onSuccess: Exit_.failCause, onFailure: (issue) => - new Issue.Composite(ast, Option_.some(input), [new Issue.Pointer(["cause"], issue)]) + new SchemaIssue.Composite(ast, Option_.some(input), [new SchemaIssue.Pointer(["cause"], issue)]) } ) } @@ -8030,7 +9182,7 @@ export function Exit(value: A, erro Struct({ _tag: Literal("Success"), value }), Struct({ _tag: Literal("Failure"), cause: Cause(error, defect) }) ]), - Transformation.transform({ + SchemaTransformation.transform({ decode: (e): Exit_.Exit => e._tag === "Success" ? Exit_.succeed(e.value) : Exit_.failCause(e.cause), encode: (exit) => @@ -8039,12 +9191,19 @@ export function Exit(value: A, erro : { _tag: "Failure", cause: exit.cause } as const }) ), - toArbitrary: ([value, error, defect]) => (fc, ctx) => - fc.oneof( - ctx?.isSuspend ? { maxDepth: 2, depthIdentifier: "Exit" } : {}, - value.map((v) => Exit_.succeed(v)), - causeToArbitrary(error, defect)(fc, ctx).map((cause) => Exit_.failCause(cause)) - ), + toArbitrary: ([value, error, defect]) => (fc, ctx) => { + const cause = causeToArbitrary(error, defect)(fc, ctx) + const terminal = oneOfArbitraries( + fc, + value.terminal?.map((v): Exit_.Exit => Exit_.succeed(v)), + cause.terminal?.map((cause): Exit_.Exit => Exit_.failCause(cause)) + ) + const arbitrary = fc.oneof( + value.arbitrary.map((v): Exit_.Exit => Exit_.succeed(v)), + cause.arbitrary.map((cause): Exit_.Exit => Exit_.failCause(cause)) + ) + return withRecursion(fc, ctx, terminal, arbitrary) + }, toEquivalence: ([value, error, defect]) => { const cause = causeToEquivalence(error, defect) return (a, b) => { @@ -8074,7 +9233,7 @@ export function Exit(value: A, erro } /** - * Companion type for {@link ReadonlyMap}. + * Type-level representation returned by {@link ReadonlyMap}. * * @category ReadonlyMap * @since 4.0.0 @@ -8093,17 +9252,110 @@ export interface $ReadonlyMap extends } /** + * Iso representation used for `ReadonlyMap` schemas: an array of readonly + * `[key, value]` tuples using each entry schema's `Iso` type. + * * @category ReadonlyMap * @since 4.0.0 */ export type ReadonlyMapIso = ReadonlyArray +function oneOfArbitraries( + fc: typeof FastCheck, + a: FastCheck.Arbitrary | undefined, + b: FastCheck.Arbitrary | undefined +) { + return a === undefined ? b : b === undefined ? a : fc.oneof(a, b) +} + +function withRecursion( + fc: typeof FastCheck, + ctx: Annotations.ToArbitrary.Context, + terminal: FastCheck.Arbitrary | undefined, + arbitrary: FastCheck.Arbitrary +) { + return { + arbitrary: terminal === undefined || ctx.recursion === undefined + ? arbitrary + : fc.oneof(ctx.recursion, terminal, arbitrary), + terminal + } +} + +function arrayFromItems( + fc: typeof FastCheck, + item: FastCheck.Arbitrary, + constraints: FastCheck.ArrayConstraints | undefined, + comparator?: ((a: T, b: T) => boolean) | undefined +) { + return comparator === undefined + ? fc.array(item, constraints) + : fc.uniqueArray(item, { ...constraints, comparator }) +} + +function collectionArbitrary( + fc: typeof FastCheck, + ctx: Annotations.ToArbitrary.Context, + item: FastCheck.Arbitrary, + terminalItem: FastCheck.Arbitrary | undefined, + fromIterable: (items: Array) => Out, + comparator?: ((a: T, b: T) => boolean) | undefined +) { + const constraint = ctx.constraint + const constraints = constraint === undefined || + (constraint.minLength === undefined && constraint.maxLength === undefined) + ? undefined + : { + ...(constraint.minLength !== undefined ? { minLength: constraint.minLength } : {}), + ...(constraint.maxLength !== undefined ? { maxLength: constraint.maxLength } : {}) + } + if ( + constraints?.minLength !== undefined && constraints.maxLength !== undefined && + constraints.minLength > constraints.maxLength + ) { + throw new globalThis.Error("Unable to derive an arbitrary for size constraints") + } + const minLength = constraints?.minLength ?? 0 + const terminal = minLength === 0 + ? fc.constant>([]) + : terminalItem === undefined + ? undefined + : arrayFromItems(fc, terminalItem, { ...constraints, maxLength: minLength }, comparator) + const arrays = withRecursion( + fc, + ctx, + terminal, + arrayFromItems(fc, item, constraints, comparator) + ) + return { + arbitrary: arrays.arbitrary.map(fromIterable), + terminal: arrays.terminal?.map(fromIterable) + } +} + +function entriesArbitrary( + fc: typeof FastCheck, + ctx: Annotations.ToArbitrary.Context, + key: Annotations.ToArbitrary.TypeParameter, + value: Annotations.ToArbitrary.TypeParameter, + fromIterable: (items: Array<[K, V]>) => Out +) { + return collectionArbitrary( + fc, + ctx, + fc.tuple(key.arbitrary, value.arbitrary), + key.terminal === undefined || value.terminal === undefined ? undefined : fc.tuple(key.terminal, value.terminal), + fromIterable, + ([a], [b]) => Equal.equals(a, b) + ) +} + /** - * Creates a schema that validates a `ReadonlyMap` where keys and values must - * conform to the provided schemas. + * Schema for readonly maps whose keys and values conform to the provided + * schemas. * * @category ReadonlyMap - * @since 4.0.0 + * @since 3.10.0 */ export function ReadonlyMap(key: Key, value: Value): $ReadonlyMap { const schema = declareConstructor< @@ -8117,15 +9369,15 @@ export function ReadonlyMap(key: Key, value: return (input, ast, options) => { if (input instanceof globalThis.Map) { return Effect.mapBothEager( - Parser.decodeUnknownEffect(array)([...input], options), + SchemaParser.decodeUnknownEffect(array)([...input], options), { onSuccess: (array: ReadonlyArray) => new globalThis.Map(array), onFailure: (issue) => - new Issue.Composite(ast, Option_.some(input), [new Issue.Pointer(["entries"], issue)]) + new SchemaIssue.Composite(ast, Option_.some(input), [new SchemaIssue.Pointer(["entries"], issue)]) } ) } - return Effect.fail(new Issue.InvalidType(ast, Option_.some(input))) + return Effect.fail(new SchemaIssue.InvalidType(ast, Option_.some(input))) } }, { @@ -8140,18 +9392,12 @@ export function ReadonlyMap(key: Key, value: toCodec: ([key, value]) => link>()( ArraySchema(Tuple([key, value])), - Transformation.transform({ + SchemaTransformation.transform({ decode: (e) => new globalThis.Map(e), encode: (map) => [...map.entries()] }) ), - toArbitrary: ([key, value]) => (fc, ctx) => { - return fc.oneof( - ctx?.isSuspend ? { maxDepth: 2, depthIdentifier: "ReadonlyMap" } : {}, - fc.constant([]), - fc.array(fc.tuple(key, value), ctx?.constraints?.array) - ).map((as) => new globalThis.Map(as)) - }, + toArbitrary: ([key, value]) => (fc, ctx) => entriesArbitrary(fc, ctx, key, value, (as) => new globalThis.Map(as)), toEquivalence: ([key, value]) => Equal.makeCompareMap(key, value), toFormatter: ([key, value]) => (t) => { const size = t.size @@ -8167,11 +9413,10 @@ export function ReadonlyMap(key: Key, value: } /** - * Schema for an Effect `HashMap` where keys and values must conform to the - * provided schemas. + * Type-level representation returned by {@link HashMap}. * * @category HashMap - * @since 4.0.0 + * @since 3.10.0 */ export interface HashMap extends declareConstructor< @@ -8187,17 +9432,19 @@ export interface HashMap extends } /** + * Iso representation used for `HashMap` schemas: an array of readonly + * `[key, value]` tuples using each entry schema's `Iso` type. + * * @category HashMap * @since 4.0.0 */ export type HashMapIso = ReadonlyArray /** - * Creates a schema that validates a `HashMap` where keys and values must - * conform to the provided schemas. + * Schema for hash maps whose keys and values conform to the provided schemas. * * @category HashMap - * @since 4.0.0 + * @since 3.10.0 */ export function HashMap(key: Key, value: Value): HashMap { const schema = declareConstructor< @@ -8211,15 +9458,15 @@ export function HashMap(key: Key, value: Val return (input, ast, options) => { if (HashMap_.isHashMap(input)) { return Effect.mapBothEager( - Parser.decodeUnknownEffect(entries)(HashMap_.toEntries(input), options), + SchemaParser.decodeUnknownEffect(entries)(HashMap_.toEntries(input), options), { onSuccess: HashMap_.fromIterable, onFailure: (issue) => - new Issue.Composite(ast, Option_.some(input), [new Issue.Pointer(["entries"], issue)]) + new SchemaIssue.Composite(ast, Option_.some(input), [new SchemaIssue.Pointer(["entries"], issue)]) } ) } - return Effect.fail(new Issue.InvalidType(ast, Option_.some(input))) + return Effect.fail(new SchemaIssue.InvalidType(ast, Option_.some(input))) } }, { @@ -8235,18 +9482,12 @@ export function HashMap(key: Key, value: Val toCodec: ([key, value]) => link>()( ArraySchema(Tuple([key, value])), - Transformation.transform({ + SchemaTransformation.transform({ decode: HashMap_.fromIterable, encode: HashMap_.toEntries }) ), - toArbitrary: ([key, value]) => (fc, ctx) => { - return fc.oneof( - ctx?.isSuspend ? { maxDepth: 2, depthIdentifier: "HashMap" } : {}, - fc.constant([]), - fc.array(fc.tuple(key, value), ctx?.constraints?.array) - ).map(HashMap_.fromIterable) - }, + toArbitrary: ([key, value]) => (fc, ctx) => entriesArbitrary(fc, ctx, key, value, HashMap_.fromIterable), toEquivalence: ([key, value]) => Equal.makeCompareMap(key, value), toFormatter: ([key, value]) => (t) => { const size = HashMap_.size(t) @@ -8262,7 +9503,7 @@ export function HashMap(key: Key, value: Val } /** - * Companion type for {@link ReadonlySet}. + * Type-level representation returned by {@link ReadonlySet}. * * @category ReadonlySet * @since 4.0.0 @@ -8280,14 +9521,19 @@ export interface $ReadonlySet extends } /** + * Iso representation used for `ReadonlySet` schemas: an array of element values + * using the element schema's `Iso` type. + * * @category ReadonlySet * @since 4.0.0 */ export type ReadonlySetIso = ReadonlyArray /** + * Schema for readonly sets whose values conform to the provided element schema. + * * @category ReadonlySet - * @since 4.0.0 + * @since 3.10.0 */ export function ReadonlySet(value: Value): $ReadonlySet { const schema = declareConstructor< @@ -8301,15 +9547,15 @@ export function ReadonlySet(value: Value): $ReadonlySet { if (input instanceof globalThis.Set) { return Effect.mapBothEager( - Parser.decodeUnknownEffect(array)([...input], options), + SchemaParser.decodeUnknownEffect(array)([...input], options), { onSuccess: (array: ReadonlyArray) => new globalThis.Set(array), onFailure: (issue) => - new Issue.Composite(ast, Option_.some(input), [new Issue.Pointer(["values"], issue)]) + new SchemaIssue.Composite(ast, Option_.some(input), [new SchemaIssue.Pointer(["values"], issue)]) } ) } - return Effect.fail(new Issue.InvalidType(ast, Option_.some(input))) + return Effect.fail(new SchemaIssue.InvalidType(ast, Option_.some(input))) } }, { @@ -8324,18 +9570,13 @@ export function ReadonlySet(value: Value): $ReadonlySet link>()( ArraySchema(value), - Transformation.transform({ + SchemaTransformation.transform({ decode: (e) => new globalThis.Set(e), encode: (set) => [...set.values()] }) ), - toArbitrary: ([value]) => (fc, ctx) => { - return fc.oneof( - ctx?.isSuspend ? { maxDepth: 2, depthIdentifier: "ReadonlySet" } : {}, - fc.constant([]), - fc.array(value, ctx?.constraints?.array) - ).map((as) => new globalThis.Set(as)) - }, + toArbitrary: ([value]) => (fc, ctx) => + collectionArbitrary(fc, ctx, value.arbitrary, value.terminal, (as) => new globalThis.Set(as), Equal.equals), toEquivalence: ([value]) => Equal.makeCompareSet(value), toFormatter: ([value]) => (t) => { const size = t.size @@ -8351,11 +9592,10 @@ export function ReadonlySet(value: Value): $ReadonlySet extends declareConstructor< @@ -8370,17 +9610,19 @@ export interface HashSet extends } /** + * Iso representation used for `HashSet` schemas: an array of element values + * using the element schema's `Iso` type. + * * @category HashSet * @since 4.0.0 */ export type HashSetIso = ReadonlyArray /** - * Creates a schema that validates a `HashSet` where values must conform to the - * provided schema. + * Schema for hash sets whose values conform to the provided element schema. * * @category HashSet - * @since 4.0.0 + * @since 3.10.0 */ export function HashSet(value: Value): HashSet { const schema = declareConstructor< @@ -8394,15 +9636,15 @@ export function HashSet(value: Value): HashSet { return (input, ast, options) => { if (HashSet_.isHashSet(input)) { return Effect.mapBothEager( - Parser.decodeUnknownEffect(values)(Arr.fromIterable(input), options), + SchemaParser.decodeUnknownEffect(values)(Arr.fromIterable(input), options), { onSuccess: HashSet_.fromIterable, onFailure: (issue) => - new Issue.Composite(ast, Option_.some(input), [new Issue.Pointer(["values"], issue)]) + new SchemaIssue.Composite(ast, Option_.some(input), [new SchemaIssue.Pointer(["values"], issue)]) } ) } - return Effect.fail(new Issue.InvalidType(ast, Option_.some(input))) + return Effect.fail(new SchemaIssue.InvalidType(ast, Option_.some(input))) } }, { @@ -8417,18 +9659,13 @@ export function HashSet(value: Value): HashSet { toCodec: ([value]) => link>()( ArraySchema(value), - Transformation.transform({ + SchemaTransformation.transform({ decode: HashSet_.fromIterable, encode: Arr.fromIterable }) ), - toArbitrary: ([value]) => (fc, ctx) => { - return fc.oneof( - ctx?.isSuspend ? { maxDepth: 2, depthIdentifier: "HashSet" } : {}, - fc.constant([]), - fc.array(value, ctx?.constraints?.array) - ).map(HashSet_.fromIterable) - }, + toArbitrary: ([value]) => (fc, ctx) => + collectionArbitrary(fc, ctx, value.arbitrary, value.terminal, HashSet_.fromIterable, Equal.equals), toEquivalence: ([value]) => Equal.makeCompareSet(value), toFormatter: ([value]) => (t) => { const size = HashSet_.size(t) @@ -8444,11 +9681,10 @@ export function HashSet(value: Value): HashSet { } /** - * Schema for an Effect `Chunk` (immutable array-like collection) where values - * must conform to the provided schema. + * Type-level representation returned by {@link Chunk}. * * @category Chunk - * @since 4.0.0 + * @since 3.10.0 */ export interface Chunk extends declareConstructor< @@ -8463,17 +9699,26 @@ export interface Chunk extends } /** + * Iso representation used for `Chunk` schemas: an array of element values using + * the element schema's `Iso` type. + * + * **When to use** + * + * Use when annotating type-level helpers that work with the readonly-array ISO + * shape of a `Chunk` schema. + * + * @see {@link Chunk} for the schema interface and constructor that use this ISO representation + * * @category Chunk * @since 4.0.0 */ export type ChunkIso = ReadonlyArray /** - * Creates a schema that validates a `Chunk` where values must conform to the - * provided schema. + * Schema for chunks whose values conform to the provided element schema. * * @category Chunk - * @since 4.0.0 + * @since 3.10.0 */ export function Chunk(value: Value): Chunk { const schema = declareConstructor< @@ -8487,15 +9732,15 @@ export function Chunk(value: Value): Chunk { return (input, ast, options) => { if (Chunk_.isChunk(input)) { return Effect.mapBothEager( - Parser.decodeUnknownEffect(values)(Arr.fromIterable(input), options), + SchemaParser.decodeUnknownEffect(values)(Arr.fromIterable(input), options), { onSuccess: Chunk_.fromIterable, onFailure: (issue) => - new Issue.Composite(ast, Option_.some(input), [new Issue.Pointer(["values"], issue)]) + new SchemaIssue.Composite(ast, Option_.some(input), [new SchemaIssue.Pointer(["values"], issue)]) } ) } - return Effect.fail(new Issue.InvalidType(ast, Option_.some(input))) + return Effect.fail(new SchemaIssue.InvalidType(ast, Option_.some(input))) } }, { @@ -8510,18 +9755,13 @@ export function Chunk(value: Value): Chunk { toCodec: ([value]) => link>()( ArraySchema(value), - Transformation.transform({ + SchemaTransformation.transform({ decode: Chunk_.fromIterable, encode: Arr.fromIterable }) ), - toArbitrary: ([value]) => (fc, ctx) => { - return fc.oneof( - ctx?.isSuspend ? { maxDepth: 2, depthIdentifier: "Chunk" } : {}, - fc.constant([]), - fc.array(value, ctx?.constraints?.array) - ).map(Chunk_.fromIterable) - }, + toArbitrary: ([value]) => (fc, ctx) => + collectionArbitrary(fc, ctx, value.arbitrary, value.terminal, Chunk_.fromIterable), toEquivalence: ([value]) => Chunk_.makeEquivalence(value), toFormatter: ([value]) => (t) => { const size = Chunk_.size(t) @@ -8537,7 +9777,7 @@ export function Chunk(value: Value): Chunk { } /** - * Companion type for {@link RegExp}. + * Type-level representation of {@link RegExp}. * * @category RegExp * @since 4.0.0 @@ -8549,6 +9789,8 @@ export interface RegExp extends instanceOf { /** * Schema for JavaScript `RegExp` objects. * + * **Details** + * * The default JSON serializer encodes a `RegExp` as `{ source, flags }`. * * @category RegExp @@ -8571,11 +9813,11 @@ export const RegExp: RegExp = instanceOf( source: String, flags: String }), - Transformation.transformOrFail({ + SchemaTransformation.transformOrFail({ decode: (e) => Effect.try({ try: () => new globalThis.RegExp(e.source, e.flags), - catch: (e) => new Issue.InvalidValue(Option_.some(e), { message: globalThis.String(e) }) + catch: (e) => new SchemaIssue.InvalidValue(Option_.some(e), { message: globalThis.String(e) }) }), encode: (regExp) => Effect.succeed({ @@ -8611,7 +9853,7 @@ export const RegExp: RegExp = instanceOf( ) /** - * Companion type for {@link URL}. + * Type-level representation of {@link URL}. * * @category URL * @since 4.0.0 @@ -8623,14 +9865,16 @@ export interface URL extends instanceOf { const URLString = String.annotate({ expected: "a string that will be decoded as a URL" }) /** - * A schema for JavaScript `URL` objects. + * Schema for JavaScript `URL` objects. + * + * **Details** * - * **Default JSON serializer** + * Default JSON serializer: * * - encodes `URL` as a `string` * - * @since 4.0.0 * @category URL + * @since 4.0.0 */ export const URL: URL = instanceOf( globalThis.URL, @@ -8646,7 +9890,7 @@ export const URL: URL = instanceOf( toCodecJson: () => link()( URLString, - Transformation.urlFromString + SchemaTransformation.urlFromString ), toArbitrary: () => (fc) => fc.webUrl().map((s) => new globalThis.URL(s)), toEquivalence: () => (a, b) => a.toString() === b.toString() @@ -8654,7 +9898,7 @@ export const URL: URL = instanceOf( ) /** - * Companion type for {@link URLFromString}. + * Type-level representation of {@link URLFromString}. * * @category URL * @since 4.0.0 @@ -8664,7 +9908,9 @@ export interface URLFromString extends decodeTo { } /** - * A transformation schema that decodes a `string` into a `URL`. + * Schema that decodes a `string` into a `URL`. + * + * **Details** * * Decoding: * - A **valid** URL `string` is decoded as a `URL` @@ -8675,10 +9921,10 @@ export interface URLFromString extends decodeTo { * @category URL * @since 4.0.0 */ -export const URLFromString: URLFromString = URLString.pipe(decodeTo(URL, Transformation.urlFromString)) +export const URLFromString: URLFromString = URLString.pipe(decodeTo(URL, SchemaTransformation.urlFromString)) /** - * Companion type for {@link Date}. + * Type-level representation of {@link Date}. * * @category Date * @since 4.0.0 @@ -8687,14 +9933,53 @@ export interface Date extends instanceOf { readonly "Rebuild": Date } +type DateArbitraryConstraints = FastCheck.DateConstraints & { + readonly valid?: boolean | undefined +} + +function dateArbitraryConstraints( + constraint: Annotations.ToArbitrary.Constraint | undefined, + ordered: Annotations.ToArbitrary.OrderedConstraint | undefined, + base?: DateArbitraryConstraints | undefined, + toDate?: (value: T) => globalThis.Date +): FastCheck.DateConstraints { + const out: FastCheck.DateConstraints = { ...base } + delete (out as any).valid + if (base?.valid || constraint?.valid) { + out.noInvalidDate = true + } + if (ordered?.minimum !== undefined) { + const minimum = toDate === undefined ? ordered.minimum as globalThis.Date : toDate(ordered.minimum) + const nextMin = ordered.exclusiveMinimum ? new globalThis.Date(minimum.getTime() + 1) : minimum + if (out.min === undefined || nextMin.getTime() > out.min.getTime()) { + out.min = nextMin + } + } + if (ordered?.maximum !== undefined) { + const maximum = toDate === undefined ? ordered.maximum as globalThis.Date : toDate(ordered.maximum) + const nextMax = ordered.exclusiveMaximum ? new globalThis.Date(maximum.getTime() - 1) : maximum + if (out.max === undefined || nextMax.getTime() < out.max.getTime()) { + out.max = nextMax + } + } + return out +} + const DateString = String.annotate({ expected: "a string in ISO 8601 format that will be decoded as a Date" }) /** - * A schema for JavaScript `Date` objects. + * Schema for JavaScript `Date` objects. + * + * **When to use** * - * This schema accepts any `Date` instance, including invalid dates (e.g., `new - * Date("invalid")`). For validating only valid dates, use {@link DateValid} - * instead. The default JSON serializer encodes `Date` as an ISO 8601 string. + * Use to validate in-memory values that must already be JavaScript date + * objects. + * + * **Details** + * + * This schema accepts any `Date` instance, including invalid dates. The default + * JSON serializer encodes valid dates as ISO 8601 strings; invalid dates encode + * as `"Invalid Date"`. * * **Example** (Date schema) * @@ -8705,6 +9990,8 @@ const DateString = String.annotate({ expected: "a string in ISO 8601 format that * // => Date { 2024-01-01T00:00:00.000Z } * ``` * + * @see {@link DateValid} for accepting only valid Date instances + * * @category Date * @since 4.0.0 */ @@ -8722,38 +10009,57 @@ export const Date: Date = instanceOf( toCodecJson: () => link()( DateString, - Transformation.dateFromString + SchemaTransformation.dateFromString ), - toArbitrary: () => (fc, ctx) => fc.date(ctx?.constraints?.date) + toArbitrary: () => (fc, ctx) => + fc.date(dateArbitraryConstraints( + ctx?.constraint, + ctx?.constraint?.ordered?.order === Order.Date ? ctx.constraint.ordered : undefined + )) } ) /** - * Companion type for {@link DateFromString}. + * Type-level representation of {@link DateFromString}. * * @category Date - * @since 4.0.0 + * @since 3.10.0 */ export interface DateFromString extends decodeTo { readonly "Rebuild": DateFromString } /** - * A transformation schema that parses an ISO 8601 string into a `Date`. + * Schema that decodes a string into a JavaScript `Date`. + * + * **When to use** + * + * Use to model string-encoded dates that decode to JavaScript `Date` objects + * and encode back to strings. + * + * **Details** * * Decoding: - * - A `string` is decoded as a `Date`. + * The string is passed to JavaScript `Date` construction. * * Encoding: - * - A `Date` is encoded as a `string`. + * A valid `Date` is encoded as an ISO string; an invalid `Date` is encoded as + * `"Invalid Date"`. + * + * **Gotchas** + * + * Invalid date strings can decode to invalid `Date` instances. + * + * @see {@link Date} for accepting Date instances directly + * @see {@link DateValid} for rejecting invalid Date instances * * @category Date - * @since 4.0.0 + * @since 3.10.0 */ -export const DateFromString: DateFromString = DateString.pipe(decodeTo(Date, Transformation.dateFromString)) +export const DateFromString: DateFromString = DateString.pipe(decodeTo(Date, SchemaTransformation.dateFromString)) /** - * Companion type for {@link DateValid}. + * Type-level representation of {@link DateValid}. * * @category Date * @since 4.0.0 @@ -8763,7 +10069,9 @@ export interface DateValid extends Date { } /** - * A schema for **valid** JavaScript `Date` objects. + * Schema for **valid** JavaScript `Date` objects. + * + * **Details** * * This schema accepts `Date` instances but rejects invalid dates (such as `new * Date("invalid")`). @@ -8774,17 +10082,19 @@ export interface DateValid extends Date { export const DateValid: DateValid = Date.check(isDateValid()) /** - * Companion type for {@link Duration}. + * Type-level representation of {@link Duration}. * * @category Duration - * @since 4.0.0 + * @since 3.10.0 */ export interface Duration extends declare { readonly "Rebuild": Duration } /** - * A schema for `Duration` values. + * Schema for `Duration` values. + * + * **Details** * * The default JSON serializer encodes `Duration` as a tagged object with the * duration type and value. @@ -8792,8 +10102,7 @@ export interface Duration extends declare { * **Example** (Duration schema) * * ```ts - * import { Schema } from "effect" - * import { Duration } from "effect" + * import { Duration, Schema } from "effect" * * Schema.decodeUnknownSync(Schema.Duration)(Duration.seconds(5)) * // => Duration(5s) @@ -8801,7 +10110,7 @@ export interface Duration extends declare { * * @category Duration * - * @since 4.0.0 + * @since 3.10.0 */ export const Duration: Duration = declare( Duration_.isDuration, @@ -8823,7 +10132,7 @@ export const Duration: Duration = declare( Struct({ _tag: Literal("Nanos"), value: BigInt }), Struct({ _tag: Literal("Millis"), value: Int }) ]), - Transformation.transform({ + SchemaTransformation.transform({ decode: (e) => { switch (e._tag) { case "Infinity": @@ -8865,7 +10174,7 @@ export const Duration: Duration = declare( const DurationString = String.annotate({ expected: "a string that will be decoded as a Duration" }) /** - * Companion type for {@link DurationFromString}. + * Type-level representation of {@link DurationFromString}. * * @category Duration * @since 4.0.0 @@ -8875,7 +10184,9 @@ export interface DurationFromString extends decodeTo { } /** - * A transformation schema that parses a string into a `Duration`. + * Schema that parses a string into a `Duration`. + * + * **Details** * * Decoding: * - A `string` is decoded as a `Duration`, accepting any format that @@ -8888,14 +10199,14 @@ export interface DurationFromString extends decodeTo { * @since 4.0.0 */ export const DurationFromString: DurationFromString = DurationString.pipe( - decodeTo(Duration, Transformation.durationFromString) + decodeTo(Duration, SchemaTransformation.durationFromString) ) /** - * Companion type for {@link DurationFromNanos}. + * Type-level representation of {@link DurationFromNanos}. * * @category Duration - * @since 4.0.0 + * @since 3.10.0 */ export interface DurationFromNanos extends decodeTo { readonly "Rebuild": DurationFromNanos @@ -8904,37 +10215,43 @@ export interface DurationFromNanos extends decodeTo { const bigint0 = globalThis.BigInt(0) /** - * A transformation schema that decodes a non-negative `bigint` into a - * `Duration`, treating the `bigint` value as the duration in nanoseconds. + * Schema that decodes a non-negative `bigint` into a + * `Duration`, treating the bigint as nanoseconds. + * + * **Details** * * Decoding: - * - A non-negative `bigint` representing nanoseconds is decoded as a `Duration` + * A non-negative `bigint` representing nanoseconds is decoded as a `Duration`. * * Encoding: - * - A `Duration` is encoded to a non-negative `bigint` representing nanoseconds + * Finite durations are encoded as a non-negative `bigint` number of nanoseconds. + * Encoding fails when the duration cannot be represented as nanoseconds, such as + * `Duration.infinity`. * * @category Duration - * @since 4.0.0 + * @since 3.10.0 */ export const DurationFromNanos: DurationFromNanos = BigInt.check(isGreaterThanOrEqualToBigInt(bigint0)).pipe( - decodeTo(Duration, Transformation.durationFromNanos) + decodeTo(Duration, SchemaTransformation.durationFromNanos) ) /** - * Companion type for {@link DurationFromMillis}. + * Type-level representation of {@link DurationFromMillis}. * * @category Duration - * @since 4.0.0 + * @since 3.10.0 */ export interface DurationFromMillis extends decodeTo { readonly "Rebuild": DurationFromMillis } /** - * A transformation schema that decodes a non-negative (possibly infinite) + * Schema that decodes a non-negative (possibly infinite) * integer into a `Duration`, treating the integer value as the duration in * milliseconds. * + * **Details** + * * Decoding: * - A non-negative (possibly infinite) integer representing milliseconds is * decoded as a `Duration` @@ -8944,17 +10261,17 @@ export interface DurationFromMillis extends decodeTo { * representing milliseconds * * @category Duration - * @since 4.0.0 + * @since 3.10.0 */ export const DurationFromMillis: DurationFromMillis = Number.check(isGreaterThanOrEqualTo(0)).pipe( - decodeTo(Duration, Transformation.durationFromMillis) + decodeTo(Duration, SchemaTransformation.durationFromMillis) ) /** - * Companion type for {@link BigDecimal}. + * Type-level representation of {@link BigDecimal}. * * @category BigDecimal - * @since 4.0.0 + * @since 3.10.0 */ export interface BigDecimal extends declare { readonly "Rebuild": BigDecimal @@ -8962,15 +10279,99 @@ export interface BigDecimal extends declare { const BigDecimalString = String.annotate({ expected: "a string that will be decoded as a BigDecimal" }) +const bigDecimalDefaultMaxScale = 20 +const bigDecimalInvalidOrderedConstraintsError = "Unable to derive an arbitrary for the ordered BigDecimal constraints" + +function bigDecimalScaleValueAtScale(bd: BigDecimal_.BigDecimal, scale: number): bigint { + return BigDecimal_.scale(bd, scale).value +} + +function bigDecimalMinValueAtScale( + minimum: BigDecimal_.BigDecimal, + scale: number, + excluded: boolean +): bigint { + return excluded + ? bigDecimalScaleValueAtScale(BigDecimal_.floor(minimum, scale), scale) + globalThis.BigInt(1) + : bigDecimalScaleValueAtScale(BigDecimal_.ceil(minimum, scale), scale) +} + +function bigDecimalMaxValueAtScale( + maximum: BigDecimal_.BigDecimal, + scale: number, + excluded: boolean +): bigint { + return excluded + ? bigDecimalScaleValueAtScale(BigDecimal_.ceil(maximum, scale), scale) - globalThis.BigInt(1) + : bigDecimalScaleValueAtScale(BigDecimal_.floor(maximum, scale), scale) +} + +function bigDecimalMaxScale(ordered: Annotations.ToArbitrary.OrderedConstraint): number { + return Math.max( + bigDecimalDefaultMaxScale, + ordered.minimum?.scale ?? 0, + ordered.maximum?.scale ?? 0, + ordered.exclusiveMinimum && ordered.minimum !== undefined ? ordered.minimum.scale + 1 : 0, + ordered.exclusiveMaximum && ordered.maximum !== undefined ? ordered.maximum.scale + 1 : 0 + ) +} + +function bigDecimalValueConstraintsAtScale( + ordered: Annotations.ToArbitrary.OrderedConstraint, + scale: number +): FastCheck.BigIntConstraints | undefined { + const constraints: FastCheck.BigIntConstraints = {} + if (ordered.minimum !== undefined) { + constraints.min = bigDecimalMinValueAtScale(ordered.minimum, scale, ordered.exclusiveMinimum === true) + } + if (ordered.maximum !== undefined) { + constraints.max = bigDecimalMaxValueAtScale(ordered.maximum, scale, ordered.exclusiveMaximum === true) + } + if (constraints.min !== undefined && constraints.max !== undefined && constraints.min > constraints.max) { + return undefined + } + return constraints +} + +function bigDecimalScaleConstraints( + ordered: Annotations.ToArbitrary.OrderedConstraint +): FastCheck.IntegerConstraints { + const max = bigDecimalMaxScale(ordered) + if (bigDecimalValueConstraintsAtScale(ordered, max) === undefined) { + throw new globalThis.Error(bigDecimalInvalidOrderedConstraintsError) + } + + let min = 0 + let high = max + while (min < high) { + const scale = min + Math.floor((high - min) / 2) + if (bigDecimalValueConstraintsAtScale(ordered, scale) === undefined) { + min = scale + 1 + } else { + high = scale + } + } + return { min, max } +} + /** - * A schema for `BigDecimal` values. + * Schema for `BigDecimal` values. + * + * **When to use** * - * **Default JSON serializer** + * Use when you already have Effect decimal instances and need schema + * validation, formatting, equivalence, and JSON string serialization. + * + * **Details** + * + * Default JSON serializer: * * - encodes `BigDecimal` as a `string` * + * @see {@link BigDecimalFromString} for parsing string input into a BigDecimal + * * @category BigDecimal - * @since 4.0.0 + * @since 3.10.0 */ export const BigDecimal: BigDecimal = declare( BigDecimal_.isBigDecimal, @@ -8987,18 +10388,32 @@ export const BigDecimal: BigDecimal = declare( toCodecJson: () => link()( BigDecimalString, - Transformation.bigDecimalFromString + SchemaTransformation.bigDecimalFromString ), - toArbitrary: () => (fc) => - fc.tuple(fc.bigInt(), fc.integer({ min: 0, max: 20 })) - .map(([value, scale]) => BigDecimal_.make(value, scale)), + toArbitrary: () => (fc, ctx) => { + const ordered = ctx.constraint?.ordered?.order === BigDecimal_.Order + ? ctx.constraint.ordered as Annotations.ToArbitrary.OrderedConstraint + : undefined + if (ordered === undefined) { + return fc.tuple(fc.bigInt(), fc.integer({ min: 0, max: bigDecimalDefaultMaxScale })) + .map(([value, scale]) => BigDecimal_.make(value, scale)) + } + + return fc.integer(bigDecimalScaleConstraints(ordered)).chain((scale) => { + const constraints = bigDecimalValueConstraintsAtScale(ordered, scale) + if (constraints === undefined) { + throw new globalThis.Error(bigDecimalInvalidOrderedConstraintsError) + } + return fc.bigInt(constraints).map((value) => BigDecimal_.make(value, scale)) + }) + }, toFormatter: () => (bd) => BigDecimal_.format(bd), toEquivalence: () => BigDecimal_.Equivalence } ) /** - * Companion type for {@link BigDecimalFromString}. + * Type-level representation of {@link BigDecimalFromString}. * * @category BigDecimal * @since 4.0.0 @@ -9008,25 +10423,40 @@ export interface BigDecimalFromString extends decodeTo { } /** - * A transformation schema that parses a string into a `BigDecimal`. + * Schema that parses a string into a `BigDecimal`. + * + * **When to use** + * + * Use to parse decimal or exponent-notation strings into arbitrary-precision + * BigDecimal values while encoding them back to strings. + * + * **Details** * * Decoding: - * - A `string` is decoded as a `BigDecimal`. + * - A `string` is decoded with `BigDecimal.fromString`. * * Encoding: - * - A `BigDecimal` is encoded as a `string`. + * - A `BigDecimal` is encoded with `BigDecimal.format`. + * + * **Gotchas** + * + * An empty string decodes as zero. + * + * @see {@link BigDecimal} for validating values that are already BigDecimal values + * @see {@link BigIntFromString} for parsing base-10 integer strings into bigint values + * @see {@link NumberFromString} for parsing JavaScript number strings * * @category BigDecimal * @since 4.0.0 */ export const BigDecimalFromString: BigDecimalFromString = BigDecimalString.pipe( - decodeTo(BigDecimal, Transformation.bigDecimalFromString) + decodeTo(BigDecimal, SchemaTransformation.bigDecimalFromString) ) /** - * Companion type for {@link UnknownFromJsonString}. + * Type-level representation of {@link UnknownFromJsonString}. * - * @category JSON + * @category models * @since 4.0.0 */ export interface UnknownFromJsonString extends fromJsonString { @@ -9034,7 +10464,9 @@ export interface UnknownFromJsonString extends fromJsonString { } /** - * A transformation schema that decodes a JSON-encoded string into an `unknown` value. + * Schema that decodes a JSON-encoded string into an `unknown` value. + * + * **Details** * * Decoding: * - A `string` is decoded as an `unknown` value. @@ -9044,7 +10476,7 @@ export interface UnknownFromJsonString extends fromJsonString { * - Any value is encoded as a JSON string using `JSON.stringify`. * - If the value is not a valid JSON value, encoding fails. * - * **Example** + * **Example** (Decoding unknown JSON strings) * * ```ts * import { Schema } from "effect" @@ -9053,15 +10485,15 @@ export interface UnknownFromJsonString extends fromJsonString { * // => { a: 1, b: 2 } * ``` * - * @category JSON + * @category schemas * @since 4.0.0 */ export const UnknownFromJsonString: UnknownFromJsonString = fromJsonString(Unknown) /** - * Companion type for {@link fromJsonString}. + * Type-level representation returned by {@link fromJsonString}. * - * @category JSON + * @category models * @since 4.0.0 */ export interface fromJsonString extends decodeTo { @@ -9072,13 +10504,21 @@ export interface fromJsonString extends decodeTo { * Returns a schema that decodes a JSON string and then decodes the parsed value * using the given schema. * + * **Details** + * * This is useful when working with JSON-encoded strings where the actual * structure of the value is known and described by an existing schema. * * The resulting schema first parses the input string as JSON, and then runs the * provided schema on the parsed result. * - * **Example** + * JSON Schema generation: + * + * When using `fromJsonString` with `draft-2020-12` or `openApi3.1`, the + * resulting schema will be a JSON Schema with a `contentSchema` property that + * contains the JSON Schema for the given schema. + * + * **Example** (Decoding JSON strings with a schema) * * ```ts * import { Schema } from "effect" @@ -9090,13 +10530,7 @@ export interface fromJsonString extends decodeTo { * // => { a: 1 } * ``` * - * **Json Schema Generation** - * - * When using `fromJsonString` with `draft-2020-12` or `openApi3.1`, the - * resulting schema will be a JSON Schema with a `contentSchema` property that - * contains the JSON Schema for the given schema. - * - * **Example** + * **Example** (Emitting JSON Schema for a JSON string decoder) * * ```ts * import { Schema } from "effect" @@ -9129,21 +10563,21 @@ export interface fromJsonString extends decodeTo { * // } * ``` * - * @category JSON + * @category constructors * @since 4.0.0 */ export function fromJsonString(schema: S): fromJsonString { return String.annotate({ expected: "a string that will be decoded as JSON", contentMediaType: "application/json", - contentSchema: AST.toEncoded(schema.ast) - }).pipe(decodeTo(schema, Transformation.fromJsonString)) + contentSchema: SchemaAST.toEncoded(schema.ast) + }).pipe(decodeTo(schema, SchemaTransformation.fromJsonString)) } /** - * Companion type for {@link File}. + * Type-level representation of {@link File}. * - * @category File + * @category file * @since 4.0.0 */ export interface File extends instanceOf { @@ -9153,10 +10587,12 @@ export interface File extends instanceOf { /** * Schema for JavaScript `File` objects. * + * **Details** + * * The default JSON serializer encodes a `File` as `{ data, type, name, lastModified }` * where `data` is base64-encoded. * - * @category File + * @category file * @since 4.0.0 */ export const File: File = instanceOf(globalThis.File, { @@ -9176,12 +10612,12 @@ export const File: File = instanceOf(globalThis.File, { name: String, lastModified: Number }), - Transformation.transformOrFail({ + SchemaTransformation.transformOrFail({ decode: (e) => Result_.match(Encoding.decodeBase64(e.data), { onFailure: (error) => Effect.fail( - new Issue.InvalidValue(Option_.some(e.data), { + new SchemaIssue.InvalidValue(Option_.some(e.data), { message: error.message }) ), @@ -9204,7 +10640,7 @@ export const File: File = instanceOf(globalThis.File, { } }, catch: (e) => - new Issue.InvalidValue(Option_.some(file), { + new SchemaIssue.InvalidValue(Option_.some(file), { message: globalThis.String(e) }) }) @@ -9213,7 +10649,7 @@ export const File: File = instanceOf(globalThis.File, { }) /** - * Companion type for {@link FormData}. + * Type-level representation of {@link FormData}. * * @category FormData * @since 4.0.0 @@ -9225,6 +10661,8 @@ export interface FormData extends instanceOf { /** * Schema for JavaScript `FormData` objects. * + * **Details** + * * The default JSON serializer encodes a `FormData` as an array of `[key, entry]` * pairs where each entry is tagged as `"String"` or `"File"`. * @@ -9251,7 +10689,7 @@ export const FormData: FormData = instanceOf(globalThis.FormData, { ]) ]) ), - Transformation.transformOrFail({ + SchemaTransformation.transformOrFail({ decode: (e) => { const out = new globalThis.FormData() for (const [key, entry] of e) { @@ -9275,7 +10713,7 @@ export const FormData: FormData = instanceOf(globalThis.FormData, { }) /** - * Companion type for {@link fromFormData}. + * Type-level representation returned by {@link fromFormData}. * * @category FormData * @since 4.0.0 @@ -9285,15 +10723,26 @@ export interface fromFormData extends decodeTo { } /** - * `Schema.fromFormData` returns a schema that reads a `FormData` instance, - * converts it into a tree record using bracket notation, and then decodes the - * resulting structure using the provided schema. + * Schema for decoding `FormData` through a bracket-notation tree. + * + * **When to use** + * + * Use to decode browser or multipart form data into a structured schema value. + * + * **Details** * * The decoding process has two steps: * * 1. Parse `FormData` into a nested tree record. * 2. Decode the parsed value with the given schema. * + * You can express nested values using bracket notation. + * + * If you want to decode values that are not strings, use + * `Schema.toCodecStringTree` with the `keepDeclarations: true` option. + * This serializer preserves values such as numbers and `Blob` objects when + * compatible with the schema. + * * **Example** (Decoding a flat structure) * * ```ts @@ -9313,8 +10762,6 @@ export interface fromFormData extends decodeTo { * // Success({"a":"1"}) * ``` * - * You can express nested values using bracket notation. - * * **Example** (Nested fields) * * ```ts @@ -9339,11 +10786,6 @@ export interface fromFormData extends decodeTo { * // Success({"a":"1","b":{"c":"2","d":"3"}}) * ``` * - * If you want to decode values that are not strings, use - * `Schema.toCodecStringTree` with the `keepDeclarations: true` option. - * This serializer preserves values such as numbers and `Blob` objects when - * compatible with the schema. - * * **Example** (Parsing non-string values) * * ```ts @@ -9365,16 +10807,17 @@ export interface fromFormData extends decodeTo { * // Success({"a":1}) // Note: the value is a number * ``` * + * @category decoding * @since 4.0.0 */ export function fromFormData(schema: S): fromFormData { - return FormData.pipe(decodeTo(schema, Transformation.fromFormData)) + return FormData.pipe(decodeTo(schema, SchemaTransformation.fromFormData)) } /** - * Companion type for {@link URLSearchParams}. + * Type-level representation of {@link URLSearchParams}. * - * @category URLSearchParams + * @category search params * @since 4.0.0 */ export interface URLSearchParams extends instanceOf { @@ -9384,9 +10827,11 @@ export interface URLSearchParams extends instanceOf /** * Schema for JavaScript `URLSearchParams` objects. * + * **Details** + * * The default JSON serializer encodes a `URLSearchParams` as a query string. * - * @category URLSearchParams + * @category search params * @since 4.0.0 */ export const URLSearchParams: URLSearchParams = instanceOf(globalThis.URLSearchParams, { @@ -9401,7 +10846,7 @@ export const URLSearchParams: URLSearchParams = instanceOf(globalThis.URLSearchP toCodecJson: () => link()( String.annotate({ expected: "a query string that will be decoded as URLSearchParams" }), - Transformation.transform({ + SchemaTransformation.transform({ decode: (e) => new globalThis.URLSearchParams(e), encode: (params) => params.toString() }) @@ -9409,9 +10854,9 @@ export const URLSearchParams: URLSearchParams = instanceOf(globalThis.URLSearchP }) /** - * Companion type for {@link fromURLSearchParams}. + * Type-level representation returned by {@link fromURLSearchParams}. * - * @category URLSearchParams + * @category search params * @since 4.0.0 */ export interface fromURLSearchParams extends decodeTo { @@ -9419,15 +10864,25 @@ export interface fromURLSearchParams extends decodeTo extends decodeTo extends decodeTo extends decodeTo(schema: S): fromURLSearchParams { - return URLSearchParams.pipe(decodeTo(schema, Transformation.fromURLSearchParams)) + return URLSearchParams.pipe(decodeTo(schema, SchemaTransformation.fromURLSearchParams)) } /** - * Companion type for {@link Finite}. + * Type-level representation of {@link Finite}. * * @category Number - * @since 4.0.0 + * @since 3.10.0 */ export interface Finite extends Number { readonly "Rebuild": Finite } /** - * A schema for finite numbers, rejecting `NaN`, `Infinity`, and `-Infinity`. + * Schema for finite numbers, rejecting `NaN`, `Infinity`, and `-Infinity`. * * @category Number - * @since 4.0.0 + * @since 3.10.0 */ export const Finite: Finite = Number.check(isFinite()) /** - * Companion type for {@link Int}. + * Type-level representation of {@link Int}. * * @category Number - * @since 4.0.0 + * @since 3.10.0 */ export interface Int extends Number { readonly "Rebuild": Int } /** - * A schema for integers, rejecting `NaN`, `Infinity`, and `-Infinity`. + * Schema for integers, rejecting `NaN`, `Infinity`, and `-Infinity`. * * @category Number - * @since 4.0.0 + * @since 3.10.0 */ export const Int: Int = Number.check(isInt()) /** - * Companion type for {@link NumberFromString}. + * Type-level representation of {@link NumberFromString}. * * @category Number - * @since 4.0.0 + * @since 3.10.0 */ export interface NumberFromString extends decodeTo { readonly "Rebuild": NumberFromString } /** - * A transformation schema that parses a string into a number. + * Schema that parses a string into a `number` using JavaScript + * number coercion. + * + * **Details** * * Decoding: - * - A `string` is decoded as a finite number. + * A `string` is decoded as a number, including possible non-finite values such as + * `NaN`, `Infinity`, and `-Infinity`. Use `FiniteFromString` to reject non-finite + * numbers. * * Encoding: - * - A number is encoded as a `string`. + * A number is encoded as a `string`. * * @category Number - * @since 4.0.0 + * @since 3.10.0 */ export const NumberFromString: NumberFromString = String.annotate({ expected: "a string that will be decoded as a number" -}).pipe(decodeTo(Number, Transformation.numberFromString)) +}).pipe(decodeTo(Number, SchemaTransformation.numberFromString)) /** - * Companion type for {@link FiniteFromString}. + * Type-level representation of {@link FiniteFromString}. * * @category Number * @since 4.0.0 @@ -9569,7 +11025,9 @@ export interface FiniteFromString extends decodeTo { } /** - * A transformation schema that parses a string into a finite number. + * Schema that parses a string into a finite number. + * + * **Details** * * Decoding: * - A `string` is decoded as a finite number, rejecting `NaN`, `Infinity`, and @@ -9583,10 +11041,10 @@ export interface FiniteFromString extends decodeTo { */ export const FiniteFromString: FiniteFromString = String.annotate({ expected: "a string that will be decoded as a finite number" -}).pipe(decodeTo(Finite, Transformation.numberFromString)) +}).pipe(decodeTo(Finite, SchemaTransformation.numberFromString)) /** - * Companion type for {@link BigIntFromString}. + * Type-level representation of {@link BigIntFromString}. * * @category BigInt * @since 4.0.0 @@ -9596,7 +11054,14 @@ export interface BigIntFromString extends decodeTo { } /** - * A transformation schema that parses a string into a `bigint`. + * Schema that parses a string into a `bigint`. + * + * **When to use** + * + * Use to parse signed base-10 integer strings into bigint values while encoding + * bigint values back to decimal strings. + * + * **Details** * * Decoding: * - A `string` is decoded as a `bigint`. @@ -9604,43 +11069,54 @@ export interface BigIntFromString extends decodeTo { * Encoding: * - A `bigint` is encoded as a `string`. * + * **Gotchas** + * + * Decoding accepts only strings matching `^-?\d+$`. + * + * @see {@link isStringBigInt} for the string predicate used by this schema + * @see {@link BigInt} for validating values that are already bigint values + * @see {@link NumberFromString} for parsing JavaScript number strings, including non-finite values + * @see {@link BigDecimalFromString} for parsing decimal number strings + * * @category BigInt * @since 4.0.0 */ -export const BigIntFromString: BigIntFromString = make(AST.bigIntString).pipe( - decodeTo(BigInt, Transformation.bigintFromString) +export const BigIntFromString: BigIntFromString = make(SchemaAST.bigIntString).pipe( + decodeTo(BigInt, SchemaTransformation.bigintFromString) ) /** - * Companion type for {@link Trimmed}. + * Type-level representation of {@link Trimmed}. * - * @category String - * @since 4.0.0 + * @category string + * @since 3.10.0 */ export interface Trimmed extends String { readonly "Rebuild": Trimmed } /** - * A schema for strings that contains no leading or trailing whitespaces. + * Schema for strings that contains no leading or trailing whitespaces. * - * @category String - * @since 4.0.0 + * @category string + * @since 3.10.0 */ export const Trimmed: Trimmed = String.check(isTrimmed()) /** - * Companion type for {@link Trim}. + * Type-level representation of {@link Trim}. * - * @category String - * @since 4.0.0 + * @category string + * @since 3.10.0 */ export interface Trim extends decodeTo { readonly "Rebuild": Trim } /** - * A transformation schema that trims whitespace from a string. + * Schema that trims whitespace from a string. + * + * **Details** * * Decoding: * - A `string` is decoded as a string with no leading or trailing whitespaces. @@ -9648,18 +11124,18 @@ export interface Trim extends decodeTo { * Encoding: * - The trimmed string is encoded as is. * - * @category String - * @since 4.0.0 + * @category string + * @since 3.10.0 */ export const Trim: Trim = String.annotate({ expected: "a string that will be decoded as a trimmed string" -}).pipe(decodeTo(Trimmed, Transformation.trim())) +}).pipe(decodeTo(Trimmed, SchemaTransformation.trim())) /** - * Companion type for {@link StringFromBase64}. + * Type-level representation of {@link StringFromBase64}. * - * @category String - * @since 4.0.0 + * @category string + * @since 3.10.0 */ export interface StringFromBase64 extends decodeTo { readonly "Rebuild": StringFromBase64 @@ -9668,26 +11144,28 @@ export interface StringFromBase64 extends decodeTo { /** * Decodes a base64 (RFC4648) encoded string into a UTF-8 string. * + * **Details** + * * Decoding: * - A **valid** base64 encoded string is decoded as a UTF-8 `string`. * * Encoding: * - A `string` is encoded as a base64-encoded string. * - * @category String - * @since 4.0.0 + * @category string + * @since 3.10.0 */ export const StringFromBase64: StringFromBase64 = String.annotate({ expected: "a base64 encoded string that will be decoded as a UTF-8 string" }).pipe( - decodeTo(String, Transformation.stringFromBase64String) + decodeTo(String, SchemaTransformation.stringFromBase64String) ) /** - * Companion type for {@link StringFromBase64Url}. + * Type-level representation of {@link StringFromBase64Url}. * - * @category String - * @since 4.0.0 + * @category string + * @since 3.10.0 */ export interface StringFromBase64Url extends decodeTo { readonly "Rebuild": StringFromBase64Url @@ -9696,26 +11174,28 @@ export interface StringFromBase64Url extends decodeTo { /** * Decodes a base64 (URL) encoded string into a UTF-8 string. * + * **Details** + * * Decoding: * - A **valid** base64 (URL) encoded string is decoded as a UTF-8 `string`. * * Encoding: * - A `string` is encoded as a base64 (URL) encoded string. * - * @category String - * @since 4.0.0 + * @category string + * @since 3.10.0 */ export const StringFromBase64Url: StringFromBase64Url = String.annotate({ expected: "a base64 (URL) encoded string that will be decoded as a UTF-8 string" }).pipe( - decodeTo(String, Transformation.stringFromBase64UrlString) + decodeTo(String, SchemaTransformation.stringFromBase64UrlString) ) /** - * Companion type for {@link StringFromHex}. + * Type-level representation of {@link StringFromHex}. * - * @category String - * @since 4.0.0 + * @category string + * @since 3.10.0 */ export interface StringFromHex extends decodeTo { readonly "Rebuild": StringFromHex @@ -9724,26 +11204,28 @@ export interface StringFromHex extends decodeTo { /** * Decodes a hex encoded string into a UTF-8 string. * + * **Details** + * * Decoding: * - A **valid** hex encoded string is decoded as a UTF-8 `string`. * * Encoding: * - A `string` is encoded as a hex string. * - * @category String - * @since 4.0.0 + * @category string + * @since 3.10.0 */ export const StringFromHex: StringFromHex = String.annotate({ expected: "a hex encoded string that will be decoded as a UTF-8 string" }).pipe( - decodeTo(String, Transformation.stringFromHexString) + decodeTo(String, SchemaTransformation.stringFromHexString) ) /** - * Companion type for {@link StringFromUriComponent}. + * Type-level representation of {@link StringFromUriComponent}. * - * @category String - * @since 4.0.0 + * @category string + * @since 3.12.0 */ export interface StringFromUriComponent extends decodeTo { readonly "Rebuild": StringFromUriComponent @@ -9753,13 +11235,15 @@ export interface StringFromUriComponent extends decodeTo { * Decodes a URI component encoded string into a UTF-8 string. * Can be used to store data in a URL. * + * **Details** + * * Decoding: * - A **valid** URI component encoded string is decoded as a UTF-8 `string`. * * Encoding: * - A `string` is encoded as a URI component encoded string. * - * **Example** + * **Example** (Decoding URI component strings) * * ```ts * import { Schema } from "effect" @@ -9777,17 +11261,18 @@ export interface StringFromUriComponent extends decodeTo { * // %7B%22maxItemPerPage%22%3A10%2C%22page%22%3A1%7D * ``` * - * @category String - * @since 4.0.0 + * @category string + * @since 3.12.0 */ export const StringFromUriComponent: StringFromUriComponent = String.annotate({ expected: "a URI component encoded string that will be decoded as a UTF-8 string" }).pipe( - decodeTo(String, Transformation.stringFromUriComponent) + decodeTo(String, SchemaTransformation.stringFromUriComponent) ) /** - * A union schema for JavaScript property keys: `number | symbol | string`. + * Schema for property keys accepted by Effect schemas: finite `number`, + * `symbol`, or `string`. * * @category PropertyKey * @since 4.0.0 @@ -9795,7 +11280,14 @@ export const StringFromUriComponent: StringFromUriComponent = String.annotate({ export const PropertyKey = Union([Finite, Symbol, String]) /** - * @category StandardSchema + * Schema for a Standard Schema v1 failure result. + * + * **Details** + * + * The result contains an `issues` array where each issue has a message and an + * optional path made of property keys or keyed path segments. + * + * @category Standard Schema * @since 4.0.0 */ export const StandardSchemaV1FailureResult = Struct({ @@ -9806,9 +11298,9 @@ export const StandardSchemaV1FailureResult = Struct({ }) /** - * Companion type for {@link BooleanFromBit}. + * Type-level representation of {@link BooleanFromBit}. * - * @category Boolean + * @category boolean * @since 4.0.0 */ export interface BooleanFromBit extends decodeTo> { @@ -9816,15 +11308,28 @@ export interface BooleanFromBit extends decodeTo bit === 1, encode: (bool) => bool ? 1 : 0 }) @@ -9832,7 +11337,7 @@ export const BooleanFromBit: BooleanFromBit = Literals([0, 1]).pipe( ) /** - * Companion type for {@link Uint8Array}. + * Type-level representation of {@link Uint8Array}. * * @category Uint8Array * @since 4.0.0 @@ -9848,9 +11353,11 @@ const Base64String = String.annotate({ }) /** - * A schema for JavaScript `Uint8Array` objects. + * Schema for JavaScript `Uint8Array` objects. * - * **Default JSON serializer** + * **Details** + * + * Default JSON serializer: * * The default JSON serializer encodes Uint8Array as a Base64 encoded string. * @@ -9869,25 +11376,27 @@ export const Uint8Array: Uint8Array = instanceOf(globalThis.Uint8Array link>()( Base64String, - Transformation.uint8ArrayFromBase64String + SchemaTransformation.uint8ArrayFromBase64String ), toArbitrary: () => (fc) => fc.uint8Array() }) /** - * Companion type for {@link Uint8ArrayFromBase64}. + * Type-level representation of {@link Uint8ArrayFromBase64}. * * @category Uint8Array - * @since 4.0.0 + * @since 3.10.0 */ export interface Uint8ArrayFromBase64 extends decodeTo { readonly "Rebuild": Uint8ArrayFromBase64 } /** - * A transformation schema that decodes a base64 encoded string into a + * Schema that decodes a base64 encoded string into a * `Uint8Array`. * + * **Details** + * * Decoding: * - A **valid** base64 encoded string is decoded as a `Uint8Array`. * @@ -9895,26 +11404,28 @@ export interface Uint8ArrayFromBase64 extends decodeTo { * - A `Uint8Array` is encoded as a base64-encoded string. * * @category Uint8Array - * @since 4.0.0 + * @since 3.10.0 */ export const Uint8ArrayFromBase64: Uint8ArrayFromBase64 = Base64String.pipe( - decodeTo(Uint8Array, Transformation.uint8ArrayFromBase64String) + decodeTo(Uint8Array, SchemaTransformation.uint8ArrayFromBase64String) ) /** - * Companion type for {@link Uint8ArrayFromBase64Url}. + * Type-level representation of {@link Uint8ArrayFromBase64Url}. * * @category Uint8Array - * @since 4.0.0 + * @since 3.10.0 */ export interface Uint8ArrayFromBase64Url extends decodeTo { readonly "Rebuild": Uint8ArrayFromBase64Url } /** - * A transformation schema that decodes a base64 (URL) encoded string into a + * Schema that decodes a base64 (URL) encoded string into a * `Uint8Array`. * + * **Details** + * * Decoding: * - A **valid** base64 (URL) encoded string is decoded as a `Uint8Array`. * @@ -9922,31 +11433,33 @@ export interface Uint8ArrayFromBase64Url extends decodeTo { * - A `Uint8Array` is encoded as a base64 (URL) encoded string. * * @category Uint8Array - * @since 4.0.0 + * @since 3.10.0 */ export const Uint8ArrayFromBase64Url: Uint8ArrayFromBase64Url = String.annotate({ expected: "a base64 (URL) encoded string that will be decoded as a Uint8Array" }).pipe( decodeTo(Uint8Array, { - decode: Getter.decodeBase64Url(), - encode: Getter.encodeBase64Url() + decode: SchemaGetter.decodeBase64Url(), + encode: SchemaGetter.encodeBase64Url() }) ) /** - * Companion type for {@link Uint8ArrayFromHex}. + * Type-level representation of {@link Uint8ArrayFromHex}. * * @category Uint8Array - * @since 4.0.0 + * @since 3.10.0 */ export interface Uint8ArrayFromHex extends decodeTo { readonly "Rebuild": Uint8ArrayFromHex } /** - * A transformation schema that decodes a hex encoded string into a + * Schema that decodes a hex encoded string into a * `Uint8Array`. * + * **Details** + * * Decoding: * - A **valid** hex encoded string is decoded as a `Uint8Array`. * @@ -9954,36 +11467,47 @@ export interface Uint8ArrayFromHex extends decodeTo { * - A `Uint8Array` is encoded as a hex encoded string. * * @category Uint8Array - * @since 4.0.0 + * @since 3.10.0 */ export const Uint8ArrayFromHex: Uint8ArrayFromHex = String.annotate({ expected: "a hex encoded string that will be decoded as a Uint8Array" }).pipe( decodeTo(Uint8Array, { - decode: Getter.decodeHex(), - encode: Getter.encodeHex() + decode: SchemaGetter.decodeHex(), + encode: SchemaGetter.encodeHex() }) ) /** - * Companion type for {@link DateTimeUtc}. + * Type-level representation of {@link DateTimeUtc}. * * @category DateTime - * @since 4.0.0 + * @since 3.10.0 */ export interface DateTimeUtc extends declare { readonly "Rebuild": DateTimeUtc } /** - * A schema for `DateTime.Utc` values. + * Schema for `DateTime.Utc` values. + * + * **When to use** + * + * Use to validate existing `DateTime.Utc` schema values and use the default JSON + * codec that represents them as UTC ISO strings. + * + * **Details** * - * **Default JSON serializer** + * The default JSON codec decodes UTC ISO strings into `DateTime.Utc` values and + * encodes `DateTime.Utc` values as UTC ISO strings. * - * - encodes `DateTime.Utc` as a UTC ISO string + * @see {@link DateTimeUtcFromString} for decoding date-time strings into UTC values + * @see {@link DateTimeUtcFromDate} for decoding JavaScript Date values into UTC values + * @see {@link DateTimeUtcFromMillis} for decoding epoch milliseconds into UTC values + * @see {@link DateTimeZoned} for preserving zoned DateTime values * * @category DateTime - * @since 4.0.0 + * @since 3.10.0 */ export const DateTimeUtc: DateTimeUtc = declare( (u) => DateTime.isDateTime(u) && DateTime.isUtc(u), @@ -10000,27 +11524,40 @@ export const DateTimeUtc: DateTimeUtc = declare( toCodecJson: () => link()( String, - Transformation.dateTimeUtcFromString + SchemaTransformation.dateTimeUtcFromString ), toArbitrary: () => (fc, ctx) => - fc.date({ noInvalidDate: true, ...ctx?.constraints?.date }).map((date) => DateTime.fromDateUnsafe(date)), + fc.date(dateArbitraryConstraints( + ctx?.constraint, + ctx?.constraint?.ordered?.order === DateTime.Order ? ctx.constraint.ordered : undefined, + { valid: true }, + DateTime.toDateUtc + )) + .map((date) => DateTime.fromDateUnsafe(date)), toFormatter: () => (utc) => utc.toString(), toEquivalence: () => DateTime.Equivalence } ) /** - * Companion type for {@link DateTimeUtcFromDate}. + * Type-level representation of {@link DateTimeUtcFromDate}. * * @category DateTime - * @since 4.0.0 + * @since 3.12.0 */ export interface DateTimeUtcFromDate extends decodeTo { readonly "Rebuild": DateTimeUtcFromDate } /** - * A transformation schema that decodes a `Date` into a `DateTime.Utc`. + * Schema that decodes a `Date` into a `DateTime.Utc`. + * + * **When to use** + * + * Use when you need to decode valid JavaScript `Date` objects into + * `DateTime.Utc` values. + * + * **Details** * * Decoding: * - A **valid** `Date` is decoded as a `DateTime.Utc` @@ -10028,18 +11565,23 @@ export interface DateTimeUtcFromDate extends decodeTo { * Encoding: * - A `DateTime.Utc` is encoded as a `Date` * + * @see {@link DateTimeUtc} for validating values that are already `DateTime.Utc` + * @see {@link DateTimeUtcFromString} for decoding date-time strings into UTC values + * @see {@link DateTimeUtcFromMillis} for decoding epoch milliseconds into UTC values + * @see {@link DateValid} for validating Date instances without converting them + * * @category DateTime - * @since 4.0.0 + * @since 3.12.0 */ export const DateTimeUtcFromDate: DateTimeUtcFromDate = DateValid.pipe( decodeTo(DateTimeUtc, { - decode: Getter.dateTimeUtcFromInput(), - encode: Getter.transform(DateTime.toDateUtc) + decode: SchemaGetter.dateTimeUtcFromInput(), + encode: SchemaGetter.transform(DateTime.toDateUtc) }) ) /** - * Companion type for {@link DateTimeUtcFromString}. + * Type-level representation of {@link DateTimeUtcFromString}. * * @category DateTime * @since 4.0.0 @@ -10049,15 +11591,18 @@ export interface DateTimeUtcFromString extends decodeTo { } /** - * A transformation schema that decodes a string into a `DateTime.Utc`. + * Schema that decodes a date-time string into a `DateTime.Utc`. + * + * **Details** * * Decoding: - * - A `string` that can be parsed by `Date.parse` is decoded as a - * `DateTime.Utc` + * + * - A string accepted by `DateTime.make` is parsed and normalized to UTC. Strings + * without an explicit zone are interpreted as UTC. * * Encoding: - * - A `DateTime.Utc` is encoded as a `string` in ISO 8601 format, ignoring any - * time zone. + * + * - A `DateTime.Utc` is encoded as a UTC ISO 8601 string. * * @category DateTime * @since 4.0.0 @@ -10067,12 +11612,12 @@ export const DateTimeUtcFromString: DateTimeUtcFromString = String.annotate({ }).pipe( decodeTo( DateTimeUtc, - Transformation.dateTimeUtcFromString + SchemaTransformation.dateTimeUtcFromString ) ) /** - * Companion type for {@link DateTimeUtcFromMillis}. + * Type-level representation of {@link DateTimeUtcFromMillis}. * * @category DateTime * @since 4.0.0 @@ -10082,7 +11627,9 @@ export interface DateTimeUtcFromMillis extends decodeTo } /** - * A transformation schema that decodes a number into a `DateTime.Utc`. + * Schema that decodes a number into a `DateTime.Utc`. + * + * **Details** * * Decoding: * - A number of milliseconds since the Unix epoch is decoded as a `DateTime.Utc` @@ -10095,30 +11642,32 @@ export interface DateTimeUtcFromMillis extends decodeTo */ export const DateTimeUtcFromMillis: DateTimeUtcFromMillis = Number.pipe( decodeTo(DateTimeUtc, { - decode: Getter.dateTimeUtcFromInput(), - encode: Getter.transform(DateTime.toEpochMillis) + decode: SchemaGetter.dateTimeUtcFromInput(), + encode: SchemaGetter.transform(DateTime.toEpochMillis) }) ) /** - * Companion type for {@link TimeZoneOffset}. + * Type-level representation of {@link TimeZoneOffset}. * * @category DateTime - * @since 4.0.0 + * @since 3.10.0 */ export interface TimeZoneOffset extends declare { readonly "Rebuild": TimeZoneOffset } /** - * A schema for `DateTime.TimeZone.Offset` values. + * Schema for `DateTime.TimeZone.Offset` values. * - * **Default JSON serializer** + * **Details** + * + * Default JSON serializer: * * - encodes `DateTime.TimeZone.Offset` as a number (offset in milliseconds) * * @category DateTime - * @since 4.0.0 + * @since 3.10.0 */ export const TimeZoneOffset: TimeZoneOffset = declare( DateTime.isTimeZoneOffset, @@ -10135,7 +11684,7 @@ export const TimeZoneOffset: TimeZoneOffset = declare( toCodecJson: () => link()( Number, - Transformation.timeZoneOffsetFromNumber + SchemaTransformation.timeZoneOffsetFromNumber ), toArbitrary: () => (fc) => fc.integer({ min: -12 * 60 * 60 * 1000, max: 14 * 60 * 60 * 1000 }).map((n) => DateTime.zoneMakeOffset(n)), @@ -10145,10 +11694,10 @@ export const TimeZoneOffset: TimeZoneOffset = declare( ) /** - * Companion type for {@link TimeZoneNamed}. + * Type-level representation of {@link TimeZoneNamed}. * * @category DateTime - * @since 4.0.0 + * @since 3.10.0 */ export interface TimeZoneNamed extends declare { readonly "Rebuild": TimeZoneNamed @@ -10157,14 +11706,16 @@ export interface TimeZoneNamed extends declare { const TimeZoneNamedString = String.annotate({ expected: "an IANA time zone identifier" }) /** - * A schema for `DateTime.TimeZone.Named` values. + * Schema for `DateTime.TimeZone.Named` values. + * + * **Details** * - * **Default JSON serializer** + * Default JSON serializer: * * - encodes `DateTime.TimeZone.Named` as a string (IANA time zone identifier) * * @category DateTime - * @since 4.0.0 + * @since 3.10.0 */ export const TimeZoneNamed: TimeZoneNamed = declare( DateTime.isTimeZoneNamed, @@ -10181,7 +11732,7 @@ export const TimeZoneNamed: TimeZoneNamed = declare( toCodecJson: () => link()( TimeZoneNamedString, - Transformation.timeZoneNamedFromString + SchemaTransformation.timeZoneNamedFromString ), toArbitrary: () => (fc) => fc.constantFrom( @@ -10195,7 +11746,7 @@ export const TimeZoneNamed: TimeZoneNamed = declare( ) /** - * Companion type for {@link TimeZoneNamedFromString}. + * Type-level representation of {@link TimeZoneNamedFromString}. * * @category DateTime * @since 4.0.0 @@ -10205,7 +11756,9 @@ export interface TimeZoneNamedFromString extends decodeTo } /** - * A transformation schema that parses an IANA time zone identifier string into a `DateTime.TimeZone.Named`. + * Schema that parses an IANA time zone identifier string into a `DateTime.TimeZone.Named`. + * + * **Details** * * Decoding: * - A `string` is decoded as a `DateTime.TimeZone.Named`. @@ -10217,14 +11770,14 @@ export interface TimeZoneNamedFromString extends decodeTo * @since 4.0.0 */ export const TimeZoneNamedFromString: TimeZoneNamedFromString = TimeZoneNamedString.pipe( - decodeTo(TimeZoneNamed, Transformation.timeZoneNamedFromString) + decodeTo(TimeZoneNamed, SchemaTransformation.timeZoneNamedFromString) ) /** - * Companion type for {@link TimeZone}. + * Type-level representation of {@link TimeZone}. * * @category DateTime - * @since 4.0.0 + * @since 3.10.0 */ export interface TimeZone extends declare { readonly "Rebuild": TimeZone @@ -10235,15 +11788,17 @@ const TimeZoneString = String.annotate({ }) /** - * A schema for `DateTime.TimeZone` values. + * Schema for `DateTime.TimeZone` values. + * + * **Details** * - * **Default JSON serializer** + * Default JSON serializer: * * - encodes `DateTime.TimeZone` as a string (IANA identifier or offset like * `+03:00`) * * @category DateTime - * @since 4.0.0 + * @since 3.10.0 */ export const TimeZone: TimeZone = declare( DateTime.isTimeZone, @@ -10260,7 +11815,7 @@ export const TimeZone: TimeZone = declare( toCodecJson: () => link()( TimeZoneString, - Transformation.timeZoneFromString + SchemaTransformation.timeZoneFromString ), toArbitrary: () => (fc) => fc.oneof( @@ -10277,7 +11832,7 @@ export const TimeZone: TimeZone = declare( ) /** - * Companion type for {@link TimeZoneFromString}. + * Type-level representation of {@link TimeZoneFromString}. * * @category DateTime * @since 4.0.0 @@ -10287,7 +11842,9 @@ export interface TimeZoneFromString extends decodeTo { } /** - * A transformation schema that parses a time zone string into a `DateTime.TimeZone`. + * Schema that parses a time zone string into a `DateTime.TimeZone`. + * + * **Details** * * Decoding: * - A `string` (IANA identifier or offset like `+03:00`) is decoded as a `DateTime.TimeZone`. @@ -10299,14 +11856,14 @@ export interface TimeZoneFromString extends decodeTo { * @since 4.0.0 */ export const TimeZoneFromString: TimeZoneFromString = TimeZoneString.pipe( - decodeTo(TimeZone, Transformation.timeZoneFromString) + decodeTo(TimeZone, SchemaTransformation.timeZoneFromString) ) /** - * Companion type for {@link DateTimeZoned}. + * Type-level representation of {@link DateTimeZoned}. * * @category DateTime - * @since 4.0.0 + * @since 3.10.0 */ export interface DateTimeZoned extends declare { readonly "Rebuild": DateTimeZoned @@ -10317,15 +11874,19 @@ const DateTimeZonedString = String.annotate({ }) /** - * A schema for `DateTime.Zoned` values. + * Schema for `DateTime.Zoned` values. + * + * **Details** * - * **Default JSON serializer** + * Default JSON serializer: * - * - encodes `DateTime.Zoned` as a string in the format + * - encodes offset zones as an ISO date-time with a numeric offset, such as + * `YYYY-MM-DDTHH:mm:ss.sss+HH:MM` + * - encodes named zones by appending the IANA identifier in brackets, such as * `YYYY-MM-DDTHH:mm:ss.sss+HH:MM[Time/Zone]` * * @category DateTime - * @since 4.0.0 + * @since 3.10.0 */ export const DateTimeZoned: DateTimeZoned = declare( (u) => DateTime.isDateTime(u) && DateTime.isZoned(u), @@ -10342,16 +11903,20 @@ export const DateTimeZoned: DateTimeZoned = declare( toCodecJson: () => link()( DateTimeZonedString, - Transformation.dateTimeZonedFromString + SchemaTransformation.dateTimeZonedFromString ), toArbitrary: () => (fc, ctx) => fc.tuple( - fc.date({ - noInvalidDate: true, - min: new globalThis.Date(-8640000000000000 + 14 * 60 * 60 * 1000), - max: new globalThis.Date(8640000000000000 - 14 * 60 * 60 * 1000), - ...ctx?.constraints?.date - }), + fc.date(dateArbitraryConstraints( + ctx?.constraint, + ctx?.constraint?.ordered?.order === DateTime.Order ? ctx.constraint.ordered : undefined, + { + max: new globalThis.Date(8640000000000000 - 14 * 60 * 60 * 1000), + min: new globalThis.Date(-8640000000000000 + 14 * 60 * 60 * 1000), + valid: true + }, + DateTime.toDateUtc + )), fc.constantFrom("UTC", "Europe/London", "America/New_York", "Asia/Tokyo", "Australia/Sydney") ).map(([date, zone]) => DateTime.makeZonedUnsafe(date, { timeZone: zone })), toFormatter: () => (zoned) => DateTime.formatIsoZoned(zoned), @@ -10360,7 +11925,7 @@ export const DateTimeZoned: DateTimeZoned = declare( ) /** - * Companion type for {@link DateTimeZonedFromString}. + * Type-level representation of {@link DateTimeZonedFromString}. * * @category DateTime * @since 4.0.0 @@ -10370,7 +11935,9 @@ export interface DateTimeZonedFromString extends decodeTo } /** - * A transformation schema that parses a zoned DateTime string into a `DateTime.Zoned`. + * Schema that parses a zoned DateTime string into a `DateTime.Zoned`. + * + * **Details** * * Decoding: * - A `string` (e.g. `2024-01-01T00:00:00.000+00:00[Europe/London]`) is decoded as a `DateTime.Zoned`. @@ -10382,7 +11949,7 @@ export interface DateTimeZonedFromString extends decodeTo * @since 4.0.0 */ export const DateTimeZonedFromString: DateTimeZonedFromString = DateTimeZonedString.pipe( - decodeTo(DateTimeZoned, Transformation.dateTimeZonedFromString) + decodeTo(DateTimeZoned, SchemaTransformation.dateTimeZonedFromString) ) // ----------------------------------------------------------------------------- @@ -10390,15 +11957,10 @@ export const DateTimeZonedFromString: DateTimeZonedFromString = DateTimeZonedStr // ----------------------------------------------------------------------------- /** - * Interface for schema-backed classes created with {@link Class}. - * - * A `Class` is a TypeScript class whose constructor validates its input - * against a {@link Struct} schema. Instances are always structurally valid. + * Type-level representation returned by {@link Class}. * - * The interface exposes the schema's `fields`, an `identifier` string, and - * helpers such as `mapFields`, `annotate`, `check`, and `extend`. - * - * @since 4.0.0 + * @category models + * @since 3.10.0 */ export interface Class extends Bottom< @@ -10406,7 +11968,7 @@ export interface Class, S>, RequiredKeys extends never ? void | S["~type.make.in"] : S["~type.make.in"], S["Iso"], @@ -10429,7 +11991,9 @@ export interface Class { - return Parser.makeOption(getClassSchema(this) as any)(input ?? {}, options) as any + return SchemaParser.makeOption(getClassSchema(this) as any)(input ?? {}, options) as any } static makeEffect(input: S["~type.make.in"], options?: MakeOptions): Effect.Effect { - return Effect.mapErrorEager( - Parser.makeEffect(getClassSchema(this) as any)(input ?? {}, options), - (issue) => new SchemaError(issue) - ) as any + return (getClassSchema(this) as any).makeEffect(input ?? {}, options) } static annotate(annotations: Annotations.Declaration) { - return this.rebuild(AST.annotate(this.ast, annotations)) + return this.rebuild(SchemaAST.annotate(this.ast, annotations)) } static annotateKey(annotations: Annotations.Key) { - return this.rebuild(AST.annotateKey(this.ast, annotations)) + return this.rebuild(SchemaAST.annotateKey(this.ast, annotations)) } - static check(...checks: readonly [AST.Check, ...Array>]) { - return this.rebuild(AST.appendChecks(this.ast, checks)) + static check(...checks: readonly [SchemaAST.Check, ...Array>]) { + return this.rebuild(SchemaAST.appendChecks(this.ast, checks)) } static extend( identifier: string @@ -10537,7 +12098,7 @@ function makeClass< return makeClass( this, identifier, - makeStruct(AST.struct(fields, struct.ast.checks, { identifier }), fields), + makeStruct(SchemaAST.struct(fields, struct.ast.checks, { identifier }), fields), annotations, proto ) @@ -10561,9 +12122,9 @@ function makeClass< } function getClassTransformation(self: new(...args: ReadonlyArray) => any) { - return new Transformation.Transformation( - Getter.transform((input) => new self(input)), - Getter.passthrough() + return new SchemaTransformation.Transformation( + SchemaGetter.transform((input) => new self(input)), + SchemaGetter.passthrough() ) } @@ -10583,22 +12144,24 @@ function getClassSchemaFactory( if (memo === undefined) { const transformation = getClassTransformation(self) const to = make>( - new AST.Declaration( + new SchemaAST.Declaration( [from.ast], () => (input, ast) => { return input instanceof self || Predicate.hasProperty(input, getClassTypeId(identifier)) ? Effect.succeed(input) : - Effect.fail(new Issue.InvalidType(ast, Option_.some(input))) + Effect.fail(new SchemaIssue.InvalidType(ast, Option_.some(input))) }, { identifier, - [AST.ClassTypeId]: ([from]: readonly [AST.AST]) => new AST.Link(from, transformation), - toCodec: ([from]: readonly [Codec]) => new AST.Link(from.ast, transformation), - toArbitrary: ([from]: readonly [FastCheck.Arbitrary]) => () => - from.map((args) => new self(args)), + [SchemaAST.ClassTypeId]: ([from]: readonly [SchemaAST.AST]) => new SchemaAST.Link(from, transformation), + toCodec: ([from]: readonly [Codec]) => new SchemaAST.Link(from.ast, transformation), + toArbitrary: ([from]: readonly [Annotations.ToArbitrary.TypeParameter]) => () => ({ + arbitrary: from.arbitrary.map((args: S["Type"]) => new self(args)), + terminal: from.terminal?.map((args: S["Type"]) => new self(args)) + }), toFormatter: ([from]: readonly [Formatter]) => (t: Self) => `${self.identifier}(${from(t)})`, - "~sentinels": AST.collectSentinels(from.ast), + "~sentinels": SchemaAST.collectSentinels(from.ast), ...annotations } ) @@ -10619,11 +12182,22 @@ type MissingSelfGeneric = /** * Creates a schema-backed class whose constructor validates input against a * {@link Struct} schema. Construction throws a {@link SchemaError} on invalid - * input (unless `disableChecks` is set in the options). + * input. + * + * **When to use** + * + * Use when you need a schema-backed data class with validated construction, + * schema-derived decoding/encoding, and class-style methods or inheritance. + * + * **Details** * * Pass the desired class type as the first type parameter. The second optional * type parameter can be used to add nominal brands. * + * **Gotchas** + * + * Passing `disableChecks` in the options skips constructor validation. + * * **Example** (Basic class) * * ```ts @@ -10657,18 +12231,33 @@ type MissingSelfGeneric = * console.log(dog.breed) // "Labrador" * ``` * - * @category Constructors - * @since 4.0.0 + * @see {@link TaggedClass} for adding a `_tag` literal field to the class schema + * @see {@link ErrorClass} for defining schema-backed error classes + * @see {@link TaggedErrorClass} for defining tagged schema-backed error classes + * + * @category constructors + * @since 3.10.0 */ export const Class: { /** * Creates a schema-backed class whose constructor validates input against a * {@link Struct} schema. Construction throws a {@link SchemaError} on invalid - * input (unless `disableChecks` is set in the options). + * input. + * + * **When to use** + * + * Use when you need a schema-backed data class with validated construction, + * schema-derived decoding/encoding, and class-style methods or inheritance. + * + * **Details** * * Pass the desired class type as the first type parameter. The second optional * type parameter can be used to add nominal brands. * + * **Gotchas** + * + * Passing `disableChecks` in the options skips constructor validation. + * * **Example** (Basic class) * * ```ts @@ -10702,18 +12291,33 @@ export const Class: { * console.log(dog.breed) // "Labrador" * ``` * - * @category Constructors - * @since 4.0.0 + * @see {@link TaggedClass} for adding a `_tag` literal field to the class schema + * @see {@link ErrorClass} for defining schema-backed error classes + * @see {@link TaggedErrorClass} for defining tagged schema-backed error classes + * + * @category constructors + * @since 3.10.0 */ (identifier: string): { /** * Creates a schema-backed class whose constructor validates input against a * {@link Struct} schema. Construction throws a {@link SchemaError} on invalid - * input (unless `disableChecks` is set in the options). + * input. + * + * **When to use** + * + * Use when you need a schema-backed data class with validated construction, + * schema-derived decoding/encoding, and class-style methods or inheritance. + * + * **Details** * * Pass the desired class type as the first type parameter. The second optional * type parameter can be used to add nominal brands. * + * **Gotchas** + * + * Passing `disableChecks` in the options skips constructor validation. + * * **Example** (Basic class) * * ```ts @@ -10747,8 +12351,12 @@ export const Class: { * console.log(dog.breed) // "Labrador" * ``` * - * @category Constructors - * @since 4.0.0 + * @see {@link TaggedClass} for adding a `_tag` literal field to the class schema + * @see {@link ErrorClass} for defining schema-backed error classes + * @see {@link TaggedErrorClass} for defining tagged schema-backed error classes + * + * @category constructors + * @since 3.10.0 */ ( fields: Fields, @@ -10757,11 +12365,22 @@ export const Class: { /** * Creates a schema-backed class whose constructor validates input against a * {@link Struct} schema. Construction throws a {@link SchemaError} on invalid - * input (unless `disableChecks` is set in the options). + * input. + * + * **When to use** + * + * Use when you need a schema-backed data class with validated construction, + * schema-derived decoding/encoding, and class-style methods or inheritance. + * + * **Details** * * Pass the desired class type as the first type parameter. The second optional * type parameter can be used to add nominal brands. * + * **Gotchas** + * + * Passing `disableChecks` in the options skips constructor validation. + * * **Example** (Basic class) * * ```ts @@ -10795,8 +12414,12 @@ export const Class: { * console.log(dog.breed) // "Labrador" * ``` * - * @category Constructors - * @since 4.0.0 + * @see {@link TaggedClass} for adding a `_tag` literal field to the class schema + * @see {@link ErrorClass} for defining schema-backed error classes + * @see {@link TaggedErrorClass} for defining tagged schema-backed error classes + * + * @category constructors + * @since 3.10.0 */ >(schema: S, annotations?: Annotations.Declaration): [Self] extends [never] ? MissingSelfGeneric<"Schema.Class"> : Class } @@ -10820,9 +12443,14 @@ export const Class: { } /** - * Like {@link Class} but automatically adds a `_tag` literal field set to the - * given `tag` value. This makes instances compatible with tagged union - * discrimination patterns. + * Defines a schema-backed class with an automatically populated `_tag` field. + * + * **When to use** + * + * Use to define class instances that are validated by a schema and participate + * in tagged union matching. + * + * **Details** * * The optional `identifier` parameter overrides the schema identifier; * it defaults to the `tag` value. @@ -10841,14 +12469,19 @@ export const Class: { * console.log(c.radius) // 5 * ``` * - * @category Constructors - * @since 4.0.0 + * @category constructors + * @since 3.10.0 */ export const TaggedClass: { /** - * Like {@link Class} but automatically adds a `_tag` literal field set to the - * given `tag` value. This makes instances compatible with tagged union - * discrimination patterns. + * Defines a schema-backed class with an automatically populated `_tag` field. + * + * **When to use** + * + * Use to define class instances that are validated by a schema and participate + * in tagged union matching. + * + * **Details** * * The optional `identifier` parameter overrides the schema identifier; * it defaults to the `tag` value. @@ -10867,14 +12500,19 @@ export const TaggedClass: { * console.log(c.radius) // 5 * ``` * - * @category Constructors - * @since 4.0.0 + * @category constructors + * @since 3.10.0 */ (identifier?: string): { /** - * Like {@link Class} but automatically adds a `_tag` literal field set to the - * given `tag` value. This makes instances compatible with tagged union - * discrimination patterns. + * Defines a schema-backed class with an automatically populated `_tag` field. + * + * **When to use** + * + * Use to define class instances that are validated by a schema and participate + * in tagged union matching. + * + * **Details** * * The optional `identifier` parameter overrides the schema identifier; * it defaults to the `tag` value. @@ -10893,8 +12531,8 @@ export const TaggedClass: { * console.log(c.radius) // 5 * ``` * - * @category Constructors - * @since 4.0.0 + * @category constructors + * @since 3.10.0 */ ( tag: Tag, @@ -10902,9 +12540,14 @@ export const TaggedClass: { annotations?: Annotations.Declaration]> ): [Self] extends [never] ? MissingSelfGeneric<"Schema.TaggedClass"> : Class, Brand> /** - * Like {@link Class} but automatically adds a `_tag` literal field set to the - * given `tag` value. This makes instances compatible with tagged union - * discrimination patterns. + * Defines a schema-backed class with an automatically populated `_tag` field. + * + * **When to use** + * + * Use to define class instances that are validated by a schema and participate + * in tagged union matching. + * + * **Details** * * The optional `identifier` parameter overrides the schema identifier; * it defaults to the `tag` value. @@ -10923,8 +12566,8 @@ export const TaggedClass: { * console.log(c.radius) // 5 * ``` * - * @category Constructors - * @since 4.0.0 + * @category constructors + * @since 3.10.0 */ >( tag: Tag, @@ -10942,13 +12585,14 @@ export const TaggedClass: { schema: Struct.Fields | Struct, annotations?: Annotations.Declaration]> ): any => { + const struct = isStruct(schema) ? + schema.mapFields((fields) => ({ _tag: tag(tagValue), ...fields }), { + unsafePreserveChecks: true + }) : + TaggedStruct(tagValue, schema) return Class(identifier ?? tagValue)( - isStruct(schema) ? - schema.mapFields((fields) => ({ _tag: tag(tagValue), ...fields }), { - unsafePreserveChecks: true - }) : - TaggedStruct(tagValue, schema), - annotations + struct, + annotations as Annotations.Declaration ) } } @@ -10973,7 +12617,7 @@ export const TaggedClass: { * }) * ``` * - * @category Constructors + * @category constructors * @since 4.0.0 */ export const ErrorClass: { @@ -10997,7 +12641,7 @@ export const ErrorClass: { * }) * ``` * - * @category Constructors + * @category constructors * @since 4.0.0 */ (identifier: string): { @@ -11021,7 +12665,7 @@ export const ErrorClass: { * }) * ``` * - * @category Constructors + * @category constructors * @since 4.0.0 */ ( @@ -11049,7 +12693,7 @@ export const ErrorClass: { * }) * ``` * - * @category Constructors + * @category constructors * @since 4.0.0 */ >(schema: S, annotations?: Annotations.Declaration): [Self] extends [never] ? MissingSelfGeneric<"Schema.ErrorClass"> : Class @@ -11075,9 +12719,13 @@ export const ErrorClass: { } /** - * Like {@link ErrorClass} but automatically adds a `_tag` literal field. The - * resulting class is both a schema-validated, yieldable error and a tagged - * union member. + * Defines a schema-backed yieldable error class with an automatically populated + * `_tag` field. + * + * **When to use** + * + * Use to define typed errors that are schema validated, yielded in `Effect.gen`, + * and matched as tagged union members. * * **Example** (Tagged error class) * @@ -11093,14 +12741,18 @@ export const ErrorClass: { * }) * ``` * - * @category Constructors - * @since 4.0.0 + * @category constructors + * @since 3.10.0 */ export const TaggedErrorClass: { /** - * Like {@link ErrorClass} but automatically adds a `_tag` literal field. The - * resulting class is both a schema-validated, yieldable error and a tagged - * union member. + * Defines a schema-backed yieldable error class with an automatically populated + * `_tag` field. + * + * **When to use** + * + * Use to define typed errors that are schema validated, yielded in `Effect.gen`, + * and matched as tagged union members. * * **Example** (Tagged error class) * @@ -11116,14 +12768,18 @@ export const TaggedErrorClass: { * }) * ``` * - * @category Constructors - * @since 4.0.0 + * @category constructors + * @since 3.10.0 */ (identifier?: string): { /** - * Like {@link ErrorClass} but automatically adds a `_tag` literal field. The - * resulting class is both a schema-validated, yieldable error and a tagged - * union member. + * Defines a schema-backed yieldable error class with an automatically populated + * `_tag` field. + * + * **When to use** + * + * Use to define typed errors that are schema validated, yielded in `Effect.gen`, + * and matched as tagged union members. * * **Example** (Tagged error class) * @@ -11139,8 +12795,8 @@ export const TaggedErrorClass: { * }) * ``` * - * @category Constructors - * @since 4.0.0 + * @category constructors + * @since 3.10.0 */ ( tag: Tag, @@ -11149,9 +12805,13 @@ export const TaggedErrorClass: { ): [Self] extends [never] ? MissingSelfGeneric<"Schema.TaggedErrorClass"> : Class, Cause_.YieldableError & Brand> /** - * Like {@link ErrorClass} but automatically adds a `_tag` literal field. The - * resulting class is both a schema-validated, yieldable error and a tagged - * union member. + * Defines a schema-backed yieldable error class with an automatically populated + * `_tag` field. + * + * **When to use** + * + * Use to define typed errors that are schema validated, yielded in `Effect.gen`, + * and matched as tagged union members. * * **Example** (Tagged error class) * @@ -11167,8 +12827,8 @@ export const TaggedErrorClass: { * }) * ``` * - * @category Constructors - * @since 4.0.0 + * @category constructors + * @since 3.10.0 */ >( tag: Tag, @@ -11186,13 +12846,14 @@ export const TaggedErrorClass: { schema: Struct.Fields | Struct, annotations?: Annotations.Declaration]> ): any => { + const struct = isStruct(schema) ? + schema.mapFields((fields) => ({ _tag: tag(tagValue), ...fields }), { + unsafePreserveChecks: true + }) : + TaggedStruct(tagValue, schema) return ErrorClass(identifier ?? tagValue)( - isStruct(schema) ? - schema.mapFields((fields) => ({ _tag: tag(tagValue), ...fields }), { - unsafePreserveChecks: true - }) : - TaggedStruct(tagValue, schema), - annotations + struct, + annotations as Annotations.Declaration ) } } @@ -11215,7 +12876,12 @@ export type LazyArbitrary = (fc: typeof FastCheck) => FastCheck.Arbitrary * Derives a {@link LazyArbitrary} from a schema. The result is memoized so * repeated calls with the same schema are cheap. * - * Prefer {@link toArbitrary} when you just need the arbitrary directly. + * **Details** + * + * Prefer {@link toArbitrary} when you need the arbitrary directly, or when you + * want derivation diagnostics via `{ report: true }`. Unsupported schema + * nodes, impossible constraints, invalid candidates, and recursive schemas + * without a finite terminal path fail immediately. * * @category Arbitrary * @since 4.0.0 @@ -11229,6 +12895,13 @@ export function toArbitraryLazy(schema: S): LazyArbitrary(schema: S): LazyArbitrary(schema: S): FastCheck.Arbitrary { +export function toArbitrary(schema: S): FastCheck.Arbitrary +export function toArbitrary( + schema: S, + options: { readonly report: true } +): Annotations.ToArbitrary.WithReport> +export function toArbitrary( + schema: S, + options?: { readonly report?: boolean } +): FastCheck.Arbitrary | Annotations.ToArbitrary.WithReport> { + if (options?.report === true) { + const lawc = InternalArbitrary.memoized(schema.ast) + const report = InternalArbitrary.makeReport() + InternalArbitrary.collectReport(schema.ast, report) + return { + value: lawc(FastCheck, {}), + report: InternalArbitrary.toReport(report) + } + } return toArbitraryLazy(schema)(FastCheck) } @@ -11256,10 +12946,13 @@ export function toArbitrary(schema: S): FastCheck.Arbitrary(toFormatter: () => Formatter< * a value to its human-readable string representation, recursing into structs, * arrays, and unions. * + * **Details** + * * The optional `onBefore` hook lets you intercept specific AST nodes before * the default formatting logic runs. * @@ -11283,18 +12978,18 @@ export function overrideToFormatter(toFormatter: () => Formatter< */ export function toFormatter(schema: Schema, options?: { readonly onBefore?: - | ((ast: AST.AST, recur: (ast: AST.AST) => Formatter) => Formatter | undefined) + | ((ast: SchemaAST.AST, recur: (ast: SchemaAST.AST) => Formatter) => Formatter | undefined) | undefined }): Formatter { return recur(schema.ast) - function recur(ast: AST.AST): Formatter { + function recur(ast: SchemaAST.AST): Formatter { // --------------------------------------------- // handle annotation // --------------------------------------------- const annotation = InternalAnnotations.resolve(ast)?.["toFormatter"] if (typeof annotation === "function") { - return annotation(AST.isDeclaration(ast) ? ast.typeParameters.map(recur) : []) + return annotation(SchemaAST.isDeclaration(ast) ? ast.typeParameters.map(recur) : []) } // --------------------------------------------- // handle onBefore @@ -11311,7 +13006,7 @@ export function toFormatter(schema: Schema, options?: { return on(ast) } - function on(ast: AST.AST): Formatter { + function on(ast: SchemaAST.AST): Formatter { switch (ast._tag) { default: return format @@ -11330,7 +13025,7 @@ export function toFormatter(schema: Schema, options?: { // --------------------------------------------- for (; i < elements.length; i++) { if (t.length < i + 1) { - if (AST.isOptional(ast.elements[i])) { + if (SchemaAST.isOptional(ast.elements[i])) { continue } } else { @@ -11373,7 +13068,7 @@ export function toFormatter(schema: Schema, options?: { const ps = ast.propertySignatures[i] const name = ps.name visited.add(name) - if (AST.isOptional(ps.type) && !Object.hasOwn(t, name)) { + if (SchemaAST.isOptional(ps.type) && !Object.hasOwn(t, name)) { continue } out.push(`${formatPropertyKey(name)}: ${propertySignatures[i](t[name])}`) @@ -11382,7 +13077,7 @@ export function toFormatter(schema: Schema, options?: { // handle index signatures // --------------------------------------------- for (let i = 0; i < indexSignatures.length; i++) { - const keys = AST.getIndexSignatureKeys(t, ast.indexSignatures[i].parameter) + const keys = SchemaAST.getIndexSignatureKeys(t, ast.indexSignatures[i].parameter) for (const key of keys) { if (visited.has(key)) { continue @@ -11396,10 +13091,10 @@ export function toFormatter(schema: Schema, options?: { } } case "Union": { - const getCandidates = (t: any) => AST.getCandidates(t, ast.types) + const getCandidates = (t: any) => SchemaAST.getCandidates(t, ast.types) return (t) => { const candidates = getCandidates(t) - const refinements = candidates.map(Parser._is) + const refinements = candidates.map(SchemaParser._is) for (let i = 0; i < candidates.length; i++) { const is = refinements[i] if (is(t)) { @@ -11410,7 +13105,7 @@ export function toFormatter(schema: Schema, options?: { } } case "Suspend": { - const get = AST.memoizeThunk(() => recur(ast.thunk())) + const get = SchemaAST.memoizeThunk(() => recur(ast.thunk())) return (t) => get()(t) } } @@ -11423,10 +13118,14 @@ export function toFormatter(schema: Schema, options?: { /** * Overrides the equivalence derivation for a schema by supplying a custom - * `Equivalence`. Use this when the default structural equivalence derived by - * {@link toEquivalence} is not appropriate for a type. + * `Equivalence`. * - * @category Equivalence + * **When to use** + * + * Use when you need a custom equivalence instead of the default structural + * equivalence derived by {@link toEquivalence}. + * + * @category instances * @since 4.0.0 */ export function overrideToEquivalence(toEquivalence: () => Equivalence.Equivalence) { @@ -11449,7 +13148,7 @@ export function overrideToEquivalence(toEquivalence: () => Equiva * console.log(eq({ id: 1, name: "Alice" }, { id: 2, name: "Alice" })) // false * ``` * - * @category Equivalence + * @category instances * @since 4.0.0 */ export function toEquivalence(schema: Schema): Equivalence.Equivalence { @@ -11479,6 +13178,7 @@ export function toRepresentation(schema: Top): SchemaRepresentation.Document { /** * Options for {@link toJsonSchemaDocument}. * + * @category options * @since 4.0.0 */ export interface ToJsonSchemaOptions { @@ -11486,6 +13186,8 @@ export interface ToJsonSchemaOptions { * Controls how additional properties are handled while resolving the JSON * schema. * + * **Details** + * * Possible values include: * - `false`: Disallow additional properties (default) * - `true`: Allow additional properties @@ -11497,14 +13199,73 @@ export interface ToJsonSchemaOptions { * provided them) based on the `expected` annotation of the check. */ readonly generateDescriptions?: boolean | undefined + /** + * A predicate that controls which additional annotation keys (beyond the + * standard JSON Schema keys) are included in the generated output. + * + * **When to use** + * + * Use when you need to include non-standard annotation keys in the generated + * JSON Schema, such as Monaco Editor properties (`markdownDescription`, + * `defaultSnippets`) or vendor extensions (`x-*`). + * + * **Details** + * + * Standard JSON Schema keys (`title`, `description`, `default`, `examples`, + * `readOnly`, `writeOnly`, `format`, `contentEncoding`, `contentMediaType`, + * `contentSchema`) are always included. This predicate is checked for any + * *other* annotation key. + * + * **Gotchas** + * + * Prefer whitelisting the custom annotation keys you want to emit instead of + * using a broad predicate such as `() => true`, because broad predicates can + * include Effect-specific annotations that are preserved for internal schema + * generation. + * + * **Example** (Including custom annotations) + * + * ```ts + * import { Schema } from "effect" + * + * const schema = Schema.String.annotate({ + * description: "A name", + * markdownDescription: "The **name** field" + * }) + * + * const doc = Schema.toJsonSchemaDocument(schema, { + * includeAnnotationKey: (key) => + * key === "markdownDescription" || key.startsWith("x-") + * }) + * + * console.log(doc.schema) + * // { + * // type: "string", + * // description: "A name", + * // markdownDescription: "The **name** field" + * // } + * ``` + */ + readonly includeAnnotationKey?: ((key: string) => boolean) | undefined } /** - * Returns a JSON Schema Document (draft-2020-12). + * Returns a JSON Schema document using draft 2020-12. + * + * **Details** + * + * The `options` parameter controls generation details such as additional + * properties and synthesized check descriptions; it does not change the draft + * target. + * + * **Gotchas** * - * You can use the `options` parameter to return a different target JSON Schema. + * JSON Schema generation is best-effort. Some Effect schema semantics cannot + * be represented exactly in JSON Schema, and importing an emitted JSON Schema + * may produce an equivalent approximation rather than the original schema + * shape. * - * @category JsonSchema + * @category converting * @since 4.0.0 */ export function toJsonSchemaDocument(schema: Top, options?: ToJsonSchemaOptions): JsonSchema.Document<"draft-2020-12"> { @@ -11522,8 +13283,8 @@ export function toJsonSchemaDocument(schema: Top, options?: ToJsonSchemaOptions) // ----------------------------------------------------------------------------- /** - * Derives a canonical JSON codec from a schema. The encoded form is `unknown` - * (any JSON-compatible value), decoded to the schema's `Type`. + * Derives a canonical JSON codec from a schema. The encoded form is `Json`, and + * decoding produces the schema's `Type`. * * @category Canonical Codecs * @since 4.0.0 @@ -11532,28 +13293,28 @@ export function toCodecJson(schema: Codec): Codec { +const toCodecJsonTop = SchemaAST.toCodec((ast) => { const out = toCodecJsonBase(ast, toCodecJsonTop) - return out !== ast && AST.isOptional(ast) ? AST.optionalKeyLastLink(out) : out + return out !== ast && SchemaAST.isOptional(ast) ? SchemaAST.optionalKeyLastLink(out) : out }) -function toCodecJsonBase(ast: AST.AST, recur: (ast: AST.AST) => AST.AST): AST.AST { +function toCodecJsonBase(ast: SchemaAST.AST, recur: (ast: SchemaAST.AST) => SchemaAST.AST): SchemaAST.AST { switch (ast._tag) { case "Declaration": { const getLink = ast.annotations?.toCodecJson ?? ast.annotations?.toCodec if (Predicate.isFunction(getLink)) { - const tps = AST.isDeclaration(ast) - ? ast.typeParameters.map((tp) => InternalSchema.make(AST.toEncoded(tp))) + const tps = SchemaAST.isDeclaration(ast) + ? ast.typeParameters.map((tp) => InternalSchema.make(SchemaAST.toEncoded(tp))) : [] const link = getLink(tps) const to = recur(link.to) - return AST.replaceEncoding(ast, to === link.to ? [link] : [new AST.Link(to, link.transformation)]) + return SchemaAST.replaceEncoding(ast, to === link.to ? [link] : [new SchemaAST.Link(to, link.transformation)]) } - return AST.replaceEncoding(ast, [AST.unknownToNull]) + return SchemaAST.replaceEncoding(ast, [SchemaAST.unknownToNull]) } case "Unknown": case "ObjectKeyword": - return AST.replaceEncoding(ast, [AST.unknownToJson]) + return SchemaAST.replaceEncoding(ast, [SchemaAST.unknownToJson]) case "Undefined": case "Void": case "Literal": @@ -11572,13 +13333,14 @@ function toCodecJsonBase(ast: AST.AST, recur: (ast: AST.AST) => AST.AST): AST.AS case "Union": { const sortedTypes = InternalSchema.jsonReorder(ast.types) if (sortedTypes !== ast.types) { - return new AST.Union( + return new SchemaAST.Union( sortedTypes, ast.mode, ast.annotations, ast.checks, ast.encoding, - ast.context + ast.context, + ast.encodingChecks ).recur(recur) } return ast.recur(recur) @@ -11599,22 +13361,22 @@ function toCodecJsonBase(ast: AST.AST, recur: (ast: AST.AST) => AST.AST): AST.AS * @since 4.0.0 */ export function toCodecIso(schema: S): Codec { - return make(toCodecIsoTop(AST.toType(schema.ast))) + return make(toCodecIsoTop(SchemaAST.toType(schema.ast))) } -const toCodecIsoTop = memoize((ast: AST.AST): AST.AST => { +const toCodecIsoTop = memoize((ast: SchemaAST.AST): SchemaAST.AST => { const out = toCodecIsoBase(ast, toCodecIsoTop) - return out !== ast && AST.isOptional(ast) ? AST.optionalKeyLastLink(out) : out + return out !== ast && SchemaAST.isOptional(ast) ? SchemaAST.optionalKeyLastLink(out) : out }) -function toCodecIsoBase(ast: AST.AST, recur: (ast: AST.AST) => AST.AST): AST.AST { +function toCodecIsoBase(ast: SchemaAST.AST, recur: (ast: SchemaAST.AST) => SchemaAST.AST): SchemaAST.AST { switch (ast._tag) { case "Declaration": { const getLink = ast.annotations?.toCodecIso ?? ast.annotations?.toCodec if (Predicate.isFunction(getLink)) { const link = getLink(ast.typeParameters.map((tp) => InternalSchema.make(tp))) const to = recur(link.to) - return AST.replaceEncoding(ast, to === link.to ? [link] : [new AST.Link(to, link.transformation)]) + return SchemaAST.replaceEncoding(ast, to === link.to ? [link] : [new SchemaAST.Link(to, link.transformation)]) } return ast } @@ -11637,13 +13399,15 @@ function toCodecIsoBase(ast: AST.AST, recur: (ast: AST.AST) => AST.AST): AST.AST export type StringTree = Tree /** - * The StringTree canonical codec converts **every leaf value to a string**, while - * preserving the original structure. + * Converts a schema to the StringTree canonical codec, where every leaf value + * becomes a string while preserving the original structure. + * + * **Details** * * Declarations are converted to `undefined` (unless they have a * `toCodecJson` or `toCodec` annotation). * - * **Options** + * Options: * * - `keepDeclarations`: if `true`, it **does not** convert declarations to * `undefined` but instead keeps them as they are (unless they have a @@ -11686,9 +13450,13 @@ type XmlEncoderOptions = { } /** - * Derives an XML encoder from a codec. Encodes a value to an XML string by - * first converting it through {@link toCodecStringTree}, then serializing the - * resulting tree to XML. + * Derives an XML encoder from a codec. + * + * **Details** + * + * The returned function encodes a value through `toCodecStringTree` and returns + * an `Effect` that succeeds with the XML string or fails with `SchemaError` if + * codec encoding fails. * * @category Canonical Codecs * @since 4.0.0 @@ -11788,7 +13556,7 @@ const xml = { } } -function getStringTreePriority(ast: AST.AST): number { +function getStringTreePriority(ast: SchemaAST.AST): number { switch (ast._tag) { case "Null": case "Boolean": @@ -11805,30 +13573,30 @@ function getStringTreePriority(ast: AST.AST): number { const treeReorder = InternalSchema.makeReorder(getStringTreePriority) function serializerTree( - ast: AST.AST, - recur: (ast: AST.AST) => AST.AST, - onMissingAnnotation: (ast: AST.AST) => AST.AST -): AST.AST { + ast: SchemaAST.AST, + recur: (ast: SchemaAST.AST) => SchemaAST.AST, + onMissingAnnotation: (ast: SchemaAST.AST) => SchemaAST.AST +): SchemaAST.AST { switch (ast._tag) { case "Declaration": { const getLink = ast.annotations?.toCodecJson ?? ast.annotations?.toCodec if (Predicate.isFunction(getLink)) { - const tps = AST.isDeclaration(ast) - ? ast.typeParameters.map((tp) => make(recur(AST.toEncoded(tp)))) + const tps = SchemaAST.isDeclaration(ast) + ? ast.typeParameters.map((tp) => make(recur(SchemaAST.toEncoded(tp)))) : [] const link = getLink(tps) const to = recur(link.to) - return AST.replaceEncoding(ast, to === link.to ? [link] : [new AST.Link(to, link.transformation)]) + return SchemaAST.replaceEncoding(ast, to === link.to ? [link] : [new SchemaAST.Link(to, link.transformation)]) } return onMissingAnnotation(ast) } case "Null": - return AST.replaceEncoding(ast, [nullToString]) + return SchemaAST.replaceEncoding(ast, [nullToString]) case "Boolean": - return AST.replaceEncoding(ast, [booleanToString]) + return SchemaAST.replaceEncoding(ast, [booleanToString]) case "Unknown": case "ObjectKeyword": - return AST.replaceEncoding(ast, [AST.unknownToStringTree]) + return SchemaAST.replaceEncoding(ast, [SchemaAST.unknownToStringTree]) case "Enum": case "Number": case "Literal": @@ -11845,13 +13613,14 @@ function serializerTree( case "Union": { const sortedTypes = treeReorder(ast.types) if (sortedTypes !== ast.types) { - return new AST.Union( + return new SchemaAST.Union( sortedTypes, ast.mode, ast.annotations, ast.checks, ast.encoding, - ast.context + ast.context, + ast.encodingChecks ).recur(recur) } return ast.recur(recur) @@ -11864,75 +13633,75 @@ function serializerTree( return ast } -const nullToString = new AST.Link( - new AST.Literal("null"), - new Transformation.Transformation( - Getter.transform(() => null), - Getter.transform(() => "null") +const nullToString = new SchemaAST.Link( + new SchemaAST.Literal("null"), + new SchemaTransformation.Transformation( + SchemaGetter.transform(() => null), + SchemaGetter.transform(() => "null") ) ) -const booleanToString = new AST.Link( - new AST.Union([new AST.Literal("true"), new AST.Literal("false")], "anyOf"), - new Transformation.Transformation( - Getter.transform((s) => s === "true"), - Getter.String() +const booleanToString = new SchemaAST.Link( + new SchemaAST.Union([new SchemaAST.Literal("true"), new SchemaAST.Literal("false")], "anyOf"), + new SchemaTransformation.Transformation( + SchemaGetter.transform((s) => s === "true"), + SchemaGetter.String() ) ) -const serializerStringTree = AST.toCodec((ast) => { - const out = serializerTree(ast, serializerStringTree, (ast) => AST.replaceEncoding(ast, [unknownToUndefined])) - if (out !== ast && AST.isOptional(ast)) { - return AST.optionalKeyLastLink(out) +const serializerStringTree = SchemaAST.toCodec((ast) => { + const out = serializerTree(ast, serializerStringTree, (ast) => SchemaAST.replaceEncoding(ast, [unknownToUndefined])) + if (out !== ast && SchemaAST.isOptional(ast)) { + return SchemaAST.optionalKeyLastLink(out) } return out }) -const unknownToUndefined = new AST.Link( - AST.undefined, - new Transformation.Transformation( - Getter.passthrough(), - Getter.transform(() => undefined) +const unknownToUndefined = new SchemaAST.Link( + SchemaAST.undefined, + new SchemaTransformation.Transformation( + SchemaGetter.passthrough(), + SchemaGetter.transform(() => undefined) ) ) -const serializerStringTreeKeepDeclarations = AST.toCodec((ast) => { +const serializerStringTreeKeepDeclarations = SchemaAST.toCodec((ast) => { const out = serializerTree(ast, serializerStringTreeKeepDeclarations, identity) - if (out !== ast && AST.isOptional(ast)) { - return AST.optionalKeyLastLink(out) + if (out !== ast && SchemaAST.isOptional(ast)) { + return SchemaAST.optionalKeyLastLink(out) } return out }) const SERIALIZER_ENSURE_ARRAY = "~effect/Schema/SERIALIZER_ENSURE_ARRAY" -const toCodecEnsureArray = AST.toCodec((ast) => { - if (AST.isUnion(ast) && ast.annotations?.[SERIALIZER_ENSURE_ARRAY]) { +const toCodecEnsureArray = SchemaAST.toCodec((ast) => { + if (SchemaAST.isUnion(ast) && ast.annotations?.[SERIALIZER_ENSURE_ARRAY]) { return ast } const out = onSerializerEnsureArray(ast) - if (AST.isArrays(out)) { - const ensure = new AST.Union( + if (SchemaAST.isArrays(out)) { + const ensure = new SchemaAST.Union( [ out, - AST.decodeTo( - AST.string, + SchemaAST.decodeTo( + SchemaAST.string, out, - new Transformation.Transformation( - Getter.split(), - Getter.passthrough() + new SchemaTransformation.Transformation( + SchemaGetter.split(), + SchemaGetter.passthrough() ) ) ], "anyOf", { [SERIALIZER_ENSURE_ARRAY]: true } ) - return AST.isOptional(ast) ? AST.optionalKey(ensure) : ensure + return SchemaAST.isOptional(ast) ? SchemaAST.optionalKey(ensure) : ensure } return out }) -function onSerializerEnsureArray(ast: AST.AST): AST.AST { +function onSerializerEnsureArray(ast: SchemaAST.AST): SchemaAST.AST { switch (ast._tag) { default: return ast @@ -11958,7 +13727,7 @@ function onSerializerEnsureArray(ast: AST.AST): AST.AST { */ export function toIso(schema: S): Optic_.Iso { const serializer = toCodecIso(schema) - return Optic_.makeIso(Parser.encodeSync(serializer), Parser.decodeSync(serializer)) + return Optic_.makeIso(SchemaParser.encodeSync(serializer), SchemaParser.decodeSync(serializer)) } /** @@ -11982,8 +13751,7 @@ export function toIsoFocus(_: S): Optic_.Iso } /** - * The schema type returned by {@link overrideToCodecIso}. Carries a custom - * `Iso` type parameter and exposes the original `schema`. + * Type-level representation returned by {@link overrideToCodecIso}. * * @category Optic * @since 4.0.0 @@ -12011,26 +13779,33 @@ export interface overrideToCodecIso extends } /** - * Overrides the ISO codec derivation for a schema by providing a target codec - * and explicit `decode`/`encode` getters. The resulting schema carries a - * custom `Iso` type, which changes the schema's type parameter — use - * {@link overrideToCodecIso} when the default ISO transformation is not + * Overrides a schema's derived ISO codec with an explicit target codec. + * + * **When to use** + * + * Use to provide a custom ISO transformation when the default derivation is not * appropriate. * + * **Details** + * + * The resulting schema carries a custom `Iso` type parameter and uses the + * provided `decode` and `encode` getters to transform between the schema type + * and the target codec. + * * @category Optic * @since 4.0.0 */ export function overrideToCodecIso( to: Codec, transformation: { - readonly decode: Getter.Getter - readonly encode: Getter.Getter + readonly decode: SchemaGetter.Getter + readonly encode: SchemaGetter.Getter } ) { return (schema: S): overrideToCodecIso => { return make( - AST.annotate(schema.ast, { - toCodecIso: () => new AST.Link(to.ast, Transformation.make(transformation)) + SchemaAST.annotate(schema.ast, { + toCodecIso: () => new SchemaAST.Link(to.ast, SchemaTransformation.make(transformation)) }), { schema } ) @@ -12046,13 +13821,13 @@ export function overrideToCodecIso( * {@link toCodecJson}), computes RFC 6902 JSON Patch operations between old * and new values, and can apply patches back to the typed value. * - * @category JsonPatch + * @category converting * @since 4.0.0 */ export function toDifferJsonPatch(schema: Codec): Differ { const serializer = toCodecJson(schema) - const get = Parser.encodeSync(serializer) - const set = Parser.decodeSync(serializer) + const get = SchemaParser.encodeSync(serializer) + const set = SchemaParser.decodeSync(serializer) return { empty: [], diff: (oldValue, newValue) => JsonPatch.get(get(oldValue), get(newValue)), @@ -12066,6 +13841,9 @@ export function toDifferJsonPatch(schema: Codec): Differ(node: S) { * readonly record of `string → Json`. For the corresponding schema, see the * {@link Json} const. * - * @category JSON + * @category models * @since 4.0.0 */ export type Json = null | number | boolean | string | JsonArray | JsonObject @@ -12119,7 +13897,7 @@ export type Json = null | number | boolean | string | JsonArray | JsonObject /** * A readonly array of {@link Json} values. * - * @category JSON + * @category models * @since 4.0.0 */ export interface JsonArray extends ReadonlyArray {} @@ -12127,7 +13905,7 @@ export interface JsonArray extends ReadonlyArray {} /** * A readonly record whose values are {@link Json} values. * - * @category JSON + * @category models * @since 4.0.0 */ export interface JsonObject { @@ -12146,13 +13924,23 @@ export interface JsonObject { * console.log(result._tag) // "Some" * ``` * - * @category JSON + * @category schemas * @since 4.0.0 */ -export const Json: Codec = make(AST.Json) +export const Json: Codec = make(SchemaAST.Json) + +const JsonError = Struct({ + message: String, + name: optionalKey(String), + stack: optionalKey(String), + cause: optionalKey(Json) +}) /** - * @category JSON + * Recursive TypeScript type for mutable JSON values: `null`, `number`, + * `boolean`, `string`, mutable arrays, or mutable string-keyed records. + * + * @category models * @since 4.0.0 */ export type MutableJson = null | number | boolean | string | MutableJsonArray | MutableJsonObject @@ -12160,7 +13948,7 @@ export type MutableJson = null | number | boolean | string | MutableJsonArray | /** * A mutable array of {@link MutableJson} values. * - * @category JSON + * @category models * @since 4.0.0 */ export interface MutableJsonArray extends Array {} @@ -12168,7 +13956,7 @@ export interface MutableJsonArray extends Array {} /** * A mutable record whose values are {@link MutableJson} values. * - * @category JSON + * @category models * @since 4.0.0 */ export interface MutableJsonObject { @@ -12179,10 +13967,10 @@ export interface MutableJsonObject { * Schema that accepts any mutable JSON-compatible value. See {@link Json} for * the immutable variant. * - * @category JSON + * @category schemas * @since 4.0.0 */ -export const MutableJson: Codec = make(AST.MutableJson) +export const MutableJson: Codec = make(SchemaAST.MutableJson) // ----------------------------------------------------------------------------- // Annotations @@ -12220,6 +14008,8 @@ export function resolveAnnotationsKey(schema: S): Annotations.Key * metadata to schemas. Annotations control documentation, validation messages, * JSON Schema generation, equivalence, arbitrary generation, and more. * + * **Details** + * * Use {@link resolveAnnotations} to read the annotations attached to a schema at * runtime. * @@ -12230,6 +14020,8 @@ export declare namespace Annotations { * This interface is used to define the annotations that can be attached to a * schema. You can extend this interface to define your own annotations. * + * **Details** + * * Note that both a missing key or `undefined` is used to indicate that the * annotation is not present. * @@ -12264,7 +14056,7 @@ export declare namespace Annotations { * } * ``` * - * @category Model + * @category models * @since 4.0.0 */ export interface Annotations { @@ -12275,9 +14067,21 @@ export declare namespace Annotations { * Annotations shared by all schema nodes. These map to common JSON Schema / * OpenAPI fields: `title`, `description`, `format`, etc. * + * @category models * @since 4.0.0 */ export interface Augment extends Annotations { + /** + * Human-readable description of what a value is expected to satisfy. + * + * **Details** + * + * For filter and refinement failures, the default formatter uses + * `message` first, then `expected`, and finally falls back to ``. + * + * Use this to name a failed filter in the default message: + * `Expected , got `. + */ readonly expected?: string | undefined readonly title?: string | undefined readonly description?: string | undefined @@ -12292,6 +14096,7 @@ export declare namespace Annotations { /** * Extends {@link Augment} with type-parametric `default` and `examples` fields. * + * @category models * @since 4.0.0 */ export interface Documentation extends Augment { @@ -12304,7 +14109,7 @@ export declare namespace Annotations { * with an optional `messageMissingKey` to override the error message when * the property key is absent during decoding. * - * @category Model + * @category models * @since 4.0.0 */ export interface Key extends Documentation { @@ -12320,20 +14125,42 @@ export declare namespace Annotations { * arbitrary generation hooks. {@link Declaration} and other annotation * interfaces build on top of this. * - * @category Model + * @category models * @since 4.0.0 */ export interface Bottom> extends Documentation { /** - * The message to use when the value is invalid. + * Complete message to use when this schema node reports an issue. + * + * **Details** + * + * This replaces the default message for matching issue types instead of + * only changing the expected label. For a filter or refinement failure, + * annotate the filter with `message` to replace the whole filter failure + * message, or `expected` to keep the default + * `Expected , got ` shape. */ readonly message?: string | undefined /** * The message to use when a key is unexpected. */ readonly messageUnexpectedKey?: string | undefined + /** + * Stable identifier for this schema node. + * + * **Details** + * + * Identifiers are used by schema tooling, including JSON Schema + * generation, to name references. The default formatter also uses + * `identifier` as the expected label for type-level failures, such as + * `Expected UserId, got null`. + * + * `identifier` does not name a failed filter or refinement. If the base + * type matches and a filter fails, put `expected` or `message` on the + * filter/refinement instead. + */ readonly identifier?: string | undefined - readonly parseOptions?: AST.ParseOptions | undefined + readonly parseOptions?: SchemaAST.ParseOptions | undefined /** * Optional metadata used to identify or extend the filter with custom data. */ @@ -12348,16 +14175,26 @@ export declare namespace Annotations { } /** + * Helpers for projecting declaration type-parameter schemas into decoded or + * encoded codec arrays used by annotation hooks. + * * @since 4.0.0 */ export namespace TypeParameters { /** + * Maps declaration type-parameter schemas to codecs for their decoded `Type` + * values. + * + * @category utility types * @since 4.0.0 */ export type Type> = { readonly [K in keyof TypeParameters]: Codec } /** + * Maps declaration type-parameter schemas to codecs for their `Encoded` values. + * + * @category utility types * @since 4.0.0 */ export type Encoded> = { @@ -12372,26 +14209,27 @@ export declare namespace Annotations { * derived capabilities (JSON encoding, property testing, etc.) can be * provided for the custom type. * - * @category Model + * @category models * @since 4.0.0 */ export interface Declaration = readonly []> extends Bottom { readonly toCodec?: - | ((typeParameters: TypeParameters.Encoded) => AST.Link) + | ((typeParameters: TypeParameters.Encoded) => SchemaAST.Link) | undefined readonly toCodecJson?: - | ((typeParameters: TypeParameters.Encoded) => AST.Link) + | ((typeParameters: TypeParameters.Encoded) => SchemaAST.Link) | undefined readonly toCodecIso?: - | ((typeParameters: TypeParameters.Type) => AST.Link) + | ((typeParameters: TypeParameters.Type) => SchemaAST.Link) | undefined readonly toArbitrary?: ToArbitrary.Declaration | undefined readonly toEquivalence?: ToEquivalence.Declaration | undefined readonly toFormatter?: ToFormatter.Declaration | undefined readonly typeConstructor?: { readonly _tag: string + readonly [key: string]: unknown } | undefined readonly generation?: { readonly runtime: string @@ -12400,11 +14238,11 @@ export declare namespace Annotations { readonly importDeclaration?: string | undefined } | undefined /** - * Used to collect sentinels from a Declaration AST. + * Used to collect sentinels from a Declaration SchemaAST. * * @internal */ - readonly "~sentinels"?: ReadonlyArray | undefined + readonly "~sentinels"?: ReadonlyArray | undefined } /** @@ -12412,104 +14250,333 @@ export declare namespace Annotations { * {@link Augment} with an optional error message, identifier, and metadata. * Filters are intentionally non-parametric to keep them covariant. * - * @category Model + * @category models * @since 4.0.0 */ export interface Filter extends Augment { + /** + * Complete message to use when this filter or refinement fails. + * + * **Details** + * + * The default formatter checks filter annotations in this order: + * `message`, then `expected`, then ``. + */ readonly message?: string | undefined + /** + * Stable identifier for the schema after this filter is attached. + * + * **Details** + * + * This can affect schema tooling such as JSON Schema generation and + * type-level failures before the filter runs, but it does not name the + * failed filter itself. For filter failure messages, use `expected` or + * `message`. + */ readonly identifier?: string | undefined /** * Optional metadata used to identify or extend the filter with custom data. */ readonly meta?: Meta | undefined - readonly toArbitraryConstraint?: - | ToArbitrary.Constraint + /** + * Optional hints used by arbitrary derivation for this filter. + * + * **Details** + * + * The same annotation can be attached to a single filter or a + * `FilterGroup`. Group hints apply to the same schema node while child + * filters are still collected and checked normally. + */ + readonly arbitrary?: + | ToArbitrary.Filter | undefined /** * Marks the filter as *structural*, meaning it applies to the shape or * structure of the container (e.g., array length, object keys) rather than * the contents. * + * **Details** + * * Example: `minLength` on an array is a structural filter. */ readonly "~structural"?: boolean | undefined } /** + * Types used by arbitrary-derivation annotations to configure `toArbitrary` + * hooks, filter hints, candidate sources, diagnostics, and merged generation + * constraints. + * * @since 4.0.0 */ export namespace ToArbitrary { /** + * Arbitrary-generation hints attached to a filter or filter group. + * + * **Details** + * + * `constraint` refines the schema node's base generator. `candidate` adds a + * weighted source before all filters run. If neither hint is provided, the + * filter does not guide generation; generated values are still checked by + * the filter predicate. With `{ report: true }`, this is reported as + * `OpaqueFilter`. + * + * @category models * @since 4.0.0 */ - export interface StringConstraints extends FastCheck.StringSharedConstraints { - readonly patterns?: readonly [string, ...Array] + export interface Filter { + readonly constraint?: Constraint | undefined + readonly candidate?: Candidate | undefined } /** + * Additional arbitrary source used before final filter checks run. + * + * **Details** + * + * The base generator keeps weight `1`; candidates default to weight `1` + * and must use a positive integer weight. `make` receives the merged + * constraint for the current node and may return `undefined` to opt out, + * including for recursive terminal branches. Candidate values are still + * checked by every schema filter, so invalid candidates affect efficiency but + * not validity. + * + * @category models * @since 4.0.0 */ - export interface NumberConstraints extends FastCheck.FloatConstraints { - readonly isInteger?: boolean + export interface Candidate { + readonly weight?: number | undefined + readonly make: ( + fc: typeof FastCheck, + context: Context + ) => FastCheck.Arbitrary | undefined } /** + * Ordered constraint accumulated from range checks. + * + * **Details** + * + * Generators consume these constraints only when they recognize `order`, + * such as `Order.Number`, `Order.BigInt`, DateTime, or BigDecimal. Merging + * constraints with different `Order` instances fails fast. + * + * @category models * @since 4.0.0 */ - export interface BigIntConstraints extends FastCheck.BigIntConstraints {} + export interface OrderedConstraint { + readonly order: Order.Order + readonly minimum?: T | undefined + readonly exclusiveMinimum?: boolean | undefined + readonly maximum?: T | undefined + readonly exclusiveMaximum?: boolean | undefined + } /** + * Node-local arbitrary-generation constraint accumulated from schema checks. + * + * **Details** + * + * `Constraint` is a generation hint for the current schema AST node, not a + * self-describing validation contract. Each generator consumes the fields it + * understands for the current node and ignores the rest; final schema + * filters still validate every generated value. + * + * `minLength` and `maxLength` represent node-local cardinality: string + * length for strings, array length for arrays, final own-property count for + * objects, and final size/cardinality for sets, maps, hash collections, and + * chunks. `patterns` are concatenated and used by string generators. + * `integer`, `noNaN`, `noInfinity`, `valid`, and `unique` are true when any + * contributing filter sets them. Range bounds live in `ordered` so ordered + * values can share the same representation. + * + * @category models * @since 4.0.0 */ - export interface ArrayConstraints extends FastCheck.ArrayConstraints { - readonly comparator?: (a: any, b: any) => boolean + export interface Constraint { + readonly minLength?: number | undefined + readonly maxLength?: number | undefined + readonly patterns?: readonly [string, ...Array] + readonly integer?: boolean | undefined + readonly noInfinity?: boolean | undefined + readonly noNaN?: boolean | undefined + readonly valid?: boolean | undefined + readonly unique?: boolean | undefined + readonly ordered?: OrderedConstraint | undefined } /** + * Recursion budget passed to arbitrary-derivation hooks. + * + * **Details** + * + * Pass this object to `fc.oneof` when combining terminal and recursive + * branches. Put the terminal branch first because fast-check uses only the + * first branch once `maxDepth` is reached for `depthIdentifier`. + * + * @category models * @since 4.0.0 */ - export interface DateConstraints extends FastCheck.DateConstraints {} + export interface Recursion { + readonly maxDepth: number + readonly depthIdentifier: FastCheck.DepthIdentifier | string + } /** + * Context passed to arbitrary-derivation hooks and candidate factories. + * + * **Details** + * + * `constraint` contains the merged constraint for the current schema + * node. `recursion` is present while deriving through a suspended schema; + * hooks that build recursive alternatives should pass it to `fc.oneof` with + * the finite branch first. + * + * @category models * @since 4.0.0 */ - export interface Constraint { - readonly string?: StringConstraints | undefined - readonly number?: NumberConstraints | undefined - readonly bigint?: BigIntConstraints | undefined - readonly array?: ArrayConstraints | undefined - readonly date?: DateConstraints | undefined + export interface Context { + readonly constraint?: ToArbitrary.Constraint | undefined + readonly recursion?: ToArbitrary.Recursion | undefined } /** + * Arbitrary generators derived for a declaration type parameter. + * + * **Details** + * + * `arbitrary` is the normal generator. `terminal` is the finite generator + * used while building recursive terminal branches and is `undefined` when + * no finite path is known. Optional containers can ignore it; non-empty + * containers need it for their terminal branch. + * + * @category models * @since 4.0.0 */ - export interface Context { - /** - * This flag is set to `true` when the current schema is a suspend. The goal - * is to avoid infinite recursion when generating arbitrary values for - * suspends, so implementations should try to avoid excessive recursion. - */ - readonly isSuspend?: boolean | undefined - readonly constraints?: ToArbitrary.Constraint | undefined + export interface TypeParameter { + readonly arbitrary: FastCheck.Arbitrary + readonly terminal: FastCheck.Arbitrary | undefined } /** + * Arbitrary derivation returned by declaration hooks. + * + * **Details** + * + * `arbitrary` is the normal generator. `terminal` is an optional finite + * branch for recursive schemas. If omitted, it defaults to `arbitrary` only + * for declarations without type parameters. + * + * @category models + * @since 4.0.0 + */ + export interface Derivation { + readonly arbitrary: FastCheck.Arbitrary + readonly terminal?: FastCheck.Arbitrary | undefined + } + + /** + * Output accepted from declaration arbitrary hooks. + * + * **Details** + * + * A bare fast-check arbitrary is shorthand for `{ arbitrary }`, useful for + * atomic declarations such as URLs. Generic declarations that need precise + * recursive behavior should return a {@link Derivation} with `terminal`. + * + * @category models + * @since 4.0.0 + */ + export type Output = FastCheck.Arbitrary | Derivation + + /** + * Hook signature for declaration schema arbitrary annotations. + * + * **Details** + * + * Type parameters expose normal and terminal generators. A declaration with + * no type parameters can return a bare arbitrary; a generic declaration + * must return `terminal` explicitly when it has a finite branch depending on + * parameters. + * + * @category models * @since 4.0.0 */ export interface Declaration> { ( - /* Arbitraries for any type parameters of the schema (if present) */ - typeParameters: { readonly [K in keyof TypeParameters]: FastCheck.Arbitrary } - ): (fc: typeof FastCheck, context: Context) => FastCheck.Arbitrary + /* Arbitrary derivations for any type parameters of the schema (if present) */ + typeParameters: { readonly [K in keyof TypeParameters]: TypeParameter } + ): (fc: typeof FastCheck, context: Context) => Output + } + + /** + * Wraps a derived value together with arbitrary-derivation diagnostics. + * + * @category models + * @since 4.0.0 + */ + export interface WithReport { + readonly value: A + readonly report: Report + } + + /** + * Diagnostics collected while deriving an arbitrary. + * + * **Details** + * + * Reports contain warnings only. Unsupported schema nodes, impossible + * constraints, invalid candidate weights, and throwing candidate factories + * fail immediately. + * + * @category models + * @since 4.0.0 + */ + export interface Report { + readonly warnings: ReadonlyArray + } + + /** + * Non-fatal arbitrary-derivation warning. + * + * @category models + * @since 4.0.0 + */ + export type Warning = OpaqueFilterWarning + + /** + * Warning emitted when a filter is handled only by the final `.filter`. + * + * **Details** + * + * The filter is still enforced. The warning means it did not contribute + * a constraint or candidate, so generation may rely on fast-check discards. + * + * @category models + * @since 4.0.0 + */ + export interface OpaqueFilterWarning { + readonly _tag: "OpaqueFilter" + readonly path: ReadonlyArray + readonly description?: string | undefined } } /** + * Types used by formatter annotations to customize formatter derivation for + * declaration schemas. + * * @since 4.0.0 */ export namespace ToFormatter { /** + * Hook signature for declaration schema formatter annotations. + * + * **Details** + * + * Given formatters for any type parameters, returns a formatter for `T`. + * + * @category models * @since 4.0.0 */ export interface Declaration> { @@ -12521,10 +14588,20 @@ export declare namespace Annotations { } /** + * Types used by equivalence annotations to customize equivalence derivation for + * declaration schemas. + * * @since 4.0.0 */ export namespace ToEquivalence { /** + * Hook signature for declaration schema equivalence annotations. + * + * **Details** + * + * Given equivalences for any type parameters, returns an `Equivalence` for `T`. + * + * @category models * @since 4.0.0 */ export interface Declaration> { @@ -12536,7 +14613,13 @@ export declare namespace Annotations { } /** - * @category Model + * Annotations that can be attached to schema issues. + * + * **Details** + * + * The optional `message` field overrides the default issue message. + * + * @category models * @since 4.0.0 */ export interface Issue extends Annotations { @@ -12544,8 +14627,14 @@ export declare namespace Annotations { } /** - * This MUST NOT be extended with custom meta. + * Registry of metadata payloads emitted by built-in schema filters and checks. * + * **Details** + * + * Do not augment this interface with custom metadata; extend `MetaDefinitions` + * instead. + * + * @category models * @since 4.0.0 */ export interface BuiltInMetaDefinitions { @@ -12588,6 +14677,10 @@ export declare namespace Annotations { readonly regExp: globalThis.RegExp readonly version: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | undefined } + readonly isGUID: { + readonly _tag: "isGUID" + readonly regExp: globalThis.RegExp + } readonly isULID: { readonly _tag: "isULID" readonly regExp: globalThis.RegExp @@ -12732,7 +14825,7 @@ export declare namespace Annotations { } readonly isPropertyNames: { readonly _tag: "isPropertyNames" - readonly propertyNames: AST.AST + readonly propertyNames: SchemaAST.AST } // Arrays Meta readonly isUnique: { @@ -12755,18 +14848,30 @@ export declare namespace Annotations { } /** + * Union of all metadata payloads defined by `BuiltInMetaDefinitions`. + * + * @category utility types * @since 4.0.0 */ export type BuiltInMeta = BuiltInMetaDefinitions[keyof BuiltInMetaDefinitions] /** - * This MAY be extended with custom meta. + * Augmentable registry of schema filter metadata payloads. + * + * **Details** * + * Extend this interface to add custom values accepted by annotation `meta` + * fields. + * + * @category models * @since 4.0.0 */ export interface MetaDefinitions extends BuiltInMetaDefinitions {} /** + * Union of built-in and user-augmented schema filter metadata payloads. + * + * @category utility types * @since 4.0.0 */ export type Meta = MetaDefinitions[keyof MetaDefinitions] diff --git a/.opencode/node_modules/effect/src/SchemaAST.ts b/.opencode/node_modules/effect/src/SchemaAST.ts index 65fc69b2ff912e422f60564e42697d2d358ff765..a551ffedc8fd06caa02aba49c978fb1f44a2f5f9 100644 --- a/.opencode/node_modules/effect/src/SchemaAST.ts +++ b/.opencode/node_modules/effect/src/SchemaAST.ts @@ -1,74 +1,12 @@ /** - * Abstract Syntax Tree (AST) representation for Effect schemas. - * - * This module defines the runtime data structures that represent schemas. - * Most users work with the `Schema` module directly; use `SchemaAST` when you - * need to inspect, traverse, or programmatically transform schema definitions. - * - * ## Mental model - * - * - **{@link AST}** — discriminated union (`_tag`) of all schema node types - * (e.g. `String`, `Objects`, `Union`, `Suspend`) - * - **{@link Base}** — abstract base class shared by every node; carries - * annotations, checks, encoding chain, and context - * - **{@link Encoding}** — a non-empty chain of {@link Link} values describing - * how to transform between the decoded (type) and encoded (wire) form - * - **{@link Check}** — a validation filter ({@link Filter} or - * {@link FilterGroup}) attached to an AST node - * - **{@link Context}** — per-property metadata: optionality, mutability, - * default values, key annotations - * - **Guards** — type-narrowing predicates for each AST variant (e.g. - * {@link isString}, {@link isObjects}) - * - * ## Common tasks - * - * - Inspect what kind of schema you have → guard functions ({@link isString}, - * {@link isObjects}, {@link isUnion}, etc.) - * - Get the decoded (type-level) AST → {@link toType} - * - Get the encoded (wire-format) AST → {@link toEncoded} - * - Swap decode/encode directions → {@link flip} - * - Read annotations → {@link resolve}, {@link resolveAt}, - * {@link resolveIdentifier} - * - Build a transformation between schemas → {@link decodeTo} - * - Add regex validation → {@link isPattern} - * - * ## Gotchas - * - * - AST nodes are structurally immutable; modification helpers return new - * objects via `Object.create`. - * - {@link Arrays} represents both tuples and arrays; {@link Objects} - * represents both structs and records. - * - {@link toType} and {@link toEncoded} are memoized — same input yields - * same output reference. - * - {@link Suspend} lazily resolves its inner AST via a thunk; the thunk is - * memoized on first call. - * - * ## Quickstart - * - * **Example** (Inspecting a schema's AST) + * Represents Effect schemas as runtime trees. * - * ```ts - * import { Schema, SchemaAST } from "effect" - * - * const schema = Schema.Struct({ name: Schema.String, age: Schema.Number }) - * const ast = schema.ast - * - * if (SchemaAST.isObjects(ast)) { - * console.log(ast.propertySignatures.map(ps => ps.name)) - * // ["name", "age"] - * } - * - * const encoded = SchemaAST.toEncoded(ast) - * console.log(SchemaAST.isObjects(encoded)) // true - * ``` - * - * ## See also - * - * - {@link AST} - * - {@link toType} - * - {@link toEncoded} - * - {@link flip} - * - {@link resolve} + * Every `Schema` has an AST made from nodes for declarations, primitives, + * literals, arrays, objects, unions, suspended schemas, checks, annotations, + * encoding links, and parsing context. Most users work with the higher-level + * `Schema` module. Use `SchemaAST` when you need to inspect schema nodes, build + * ASTs programmatically, change encoded or decoded views, collect issues, or + * run low-level schema checks. * * @since 4.0.0 */ @@ -89,14 +27,17 @@ import * as Predicate from "./Predicate.ts" import * as RegEx from "./RegExp.ts" import * as Result from "./Result.ts" import type * as Schema from "./Schema.ts" -import * as Getter from "./SchemaGetter.ts" -import * as Issue from "./SchemaIssue.ts" -import type * as Parser from "./SchemaParser.ts" -import * as Transformation from "./SchemaTransformation.ts" +import * as SchemaGetter from "./SchemaGetter.ts" +import * as SchemaIssue from "./SchemaIssue.ts" +import type * as SchemaParser from "./SchemaParser.ts" +import * as SchemaTransformation from "./SchemaTransformation.ts" +import type * as FastCheck from "./testing/FastCheck.ts" /** * Discriminated union of all AST node types. * + * **Details** + * * Every `Schema` has an `.ast` property of this type. Use the guard functions * ({@link isString}, {@link isObjects}, etc.) to narrow to a specific variant, * then access variant-specific fields. @@ -107,9 +48,8 @@ import * as Transformation from "./SchemaTransformation.ts" * * @see {@link Base} * @see {@link isAST} - * - * @category model - * @since 4.0.0 + * @category models + * @since 3.10.0 */ export type AST = | Declaration @@ -141,12 +81,13 @@ function makeGuard(tag: T) { /** * Returns `true` if the value is an {@link AST} node (any variant). * + * **Details** + * * Uses the internal `TypeId` brand to distinguish AST nodes from arbitrary * objects. * * @see {@link AST} - * - * @category Guard + * @category guards * @since 4.0.0 */ export function isAST(u: unknown): u is AST { @@ -156,15 +97,31 @@ export function isAST(u: unknown): u is AST { /** * Narrows an {@link AST} to {@link Declaration}. * - * @category Guard - * @since 4.0.0 + * **When to use** + * + * Use to recognize declaration AST nodes before running declaration-specific + * handling. + * + * @see {@link Declaration} for the AST node type narrowed by this guard + * + * @category guards + * @since 3.10.0 */ export const isDeclaration = makeGuard("Declaration") /** * Narrows an {@link AST} to {@link Null}. * - * @category Guard + * **When to use** + * + * Use to recognize an AST node that represents exactly the `null` literal when + * inspecting, traversing, or transforming schema ASTs. + * + * @see {@link Null} for the AST node type narrowed by this guard + * @see {@link null_ null} for the singleton `Null` AST instance + * @see {@link isLiteral} for exact primitive literal AST nodes + * + * @category guards * @since 4.0.0 */ export const isNull = makeGuard("Null") @@ -172,7 +129,14 @@ export const isNull = makeGuard("Null") /** * Narrows an {@link AST} to {@link Undefined}. * - * @category Guard + * **When to use** + * + * Use to identify AST nodes that represent exactly the JavaScript `undefined` + * value. + * + * @see {@link isVoid} for narrowing AST nodes that represent TypeScript `void` instead of exact `undefined` + * + * @category guards * @since 4.0.0 */ export const isUndefined = makeGuard("Undefined") @@ -180,7 +144,14 @@ export const isUndefined = makeGuard("Undefined") /** * Narrows an {@link AST} to {@link Void}. * - * @category Guard + * **When to use** + * + * Use to identify AST nodes that represent the TypeScript `void` type before + * handling `Void`-specific schema behavior. + * + * @see {@link isUndefined} for narrowing AST nodes that represent the literal `undefined` value instead of TypeScript `void` + * + * @category guards * @since 4.0.0 */ export const isVoid = makeGuard("Void") @@ -188,7 +159,15 @@ export const isVoid = makeGuard("Void") /** * Narrows an {@link AST} to {@link Never}. * - * @category Guard + * **When to use** + * + * Use to detect the AST node for a schema that can never match before handling + * other schema variants. + * + * @see {@link Never} for the AST node type narrowed by this guard + * @see {@link never} for the singleton `Never` AST instance + * + * @category guards * @since 4.0.0 */ export const isNever = makeGuard("Never") @@ -196,7 +175,14 @@ export const isNever = makeGuard("Never") /** * Narrows an {@link AST} to {@link Unknown}. * - * @category Guard + * **When to use** + * + * Use when you need to inspect a schema AST and handle the `Unknown` node + * variant specifically. + * + * @see {@link isAny} for the guard for the `Any` node, whose parsed result is typed as `any` rather than `unknown` + * + * @category guards * @since 4.0.0 */ export const isUnknown = makeGuard("Unknown") @@ -204,7 +190,14 @@ export const isUnknown = makeGuard("Unknown") /** * Narrows an {@link AST} to {@link Any}. * - * @category Guard + * **When to use** + * + * Use when you need to inspect a schema AST and handle the `Any` node + * variant specifically. + * + * @see {@link isUnknown} for the guard for the `Unknown` node, whose parsed result is typed as `unknown` rather than `any` + * + * @category guards * @since 4.0.0 */ export const isAny = makeGuard("Any") @@ -212,7 +205,16 @@ export const isAny = makeGuard("Any") /** * Narrows an {@link AST} to {@link String}. * - * @category Guard + * **When to use** + * + * Use to detect schema AST nodes that match any string value while inspecting + * or transforming a Schema AST. + * + * @see {@link String} for the AST node class narrowed by this guard + * @see {@link string} for the singleton `String` AST instance + * @see {@link isLiteral} for exact primitive literal AST nodes, including exact string literals + * + * @category guards * @since 4.0.0 */ export const isString = makeGuard("String") @@ -220,7 +222,12 @@ export const isString = makeGuard("String") /** * Narrows an {@link AST} to {@link Number}. * - * @category Guard + * **When to use** + * + * Use to detect `Number` AST nodes while inspecting, traversing, or transforming + * schema ASTs. + * + * @category guards * @since 4.0.0 */ export const isNumber = makeGuard("Number") @@ -228,7 +235,15 @@ export const isNumber = makeGuard("Number") /** * Narrows an {@link AST} to {@link Boolean}. * - * @category Guard + * **When to use** + * + * Use to identify the `Boolean` AST variant while inspecting, traversing, or + * transforming schema definitions. + * + * @see {@link Boolean} for the AST node type matched by this guard + * @see {@link boolean} for the singleton instance to use when constructing a boolean AST directly + * + * @category guards * @since 4.0.0 */ export const isBoolean = makeGuard("Boolean") @@ -236,7 +251,14 @@ export const isBoolean = makeGuard("Boolean") /** * Narrows an {@link AST} to {@link BigInt}. * - * @category Guard + * **When to use** + * + * Use to identify bigint AST nodes while inspecting or transforming schema ASTs. + * + * @see {@link BigInt} for the AST node matched by this guard + * @see {@link bigInt} for the singleton instance; use `isBigInt` when narrowing an existing `AST` value + * + * @category guards * @since 4.0.0 */ export const isBigInt = makeGuard("BigInt") @@ -244,7 +266,14 @@ export const isBigInt = makeGuard("BigInt") /** * Narrows an {@link AST} to {@link Symbol}. * - * @category Guard + * **When to use** + * + * Use to narrow an `AST` node before handling the `Symbol` variant for schemas + * that accept any JavaScript symbol value. + * + * @see {@link isUniqueSymbol} for the sibling guard that narrows the `UniqueSymbol` variant for one exact symbol value + * + * @category guards * @since 4.0.0 */ export const isSymbol = makeGuard("Symbol") @@ -252,31 +281,54 @@ export const isSymbol = makeGuard("Symbol") /** * Narrows an {@link AST} to {@link Literal}. * - * @category Guard - * @since 4.0.0 + * **When to use** + * + * Use to recognize exact string, number, boolean, or bigint literal AST nodes. + * + * @see {@link Literal} for the AST node type narrowed by this guard + * @see {@link LiteralValue} for the values stored by literal nodes + * + * @category guards + * @since 3.10.0 */ export const isLiteral = makeGuard("Literal") /** * Narrows an {@link AST} to {@link UniqueSymbol}. * - * @category Guard - * @since 4.0.0 + * @category guards + * @since 3.10.0 */ export const isUniqueSymbol = makeGuard("UniqueSymbol") /** * Narrows an {@link AST} to {@link ObjectKeyword}. * - * @category Guard - * @since 4.0.0 + * **When to use** + * + * Use to identify the AST node for the TypeScript `object` keyword when + * inspecting or transforming a Schema AST. + * + * @see {@link ObjectKeyword} for the AST node matched by this guard + * @see {@link objectKeyword} for the singleton `ObjectKeyword` AST instance + * @see {@link isObjects} for struct and record AST nodes + * + * @category guards + * @since 3.10.0 */ export const isObjectKeyword = makeGuard("ObjectKeyword") /** * Narrows an {@link AST} to {@link Enum}. * - * @category Guard + * **When to use** + * + * Use to recognize enum AST nodes before reading enum cases or running + * enum-specific handling. + * + * @see {@link Enum} for the AST node type narrowed by this guard + * + * @category guards * @since 4.0.0 */ export const isEnum = makeGuard("Enum") @@ -284,15 +336,22 @@ export const isEnum = makeGuard("Enum") /** * Narrows an {@link AST} to {@link TemplateLiteral}. * - * @category Guard - * @since 4.0.0 + * @category guards + * @since 3.10.0 */ export const isTemplateLiteral = makeGuard("TemplateLiteral") /** * Narrows an {@link AST} to {@link Arrays}. * - * @category Guard + * **When to use** + * + * Use to recognize array-like AST nodes before reading their element, rest, or + * mutability metadata. + * + * @see {@link Arrays} for the AST node type narrowed by this guard + * + * @category guards * @since 4.0.0 */ export const isArrays = makeGuard("Arrays") @@ -300,7 +359,7 @@ export const isArrays = makeGuard("Arrays") /** * Narrows an {@link AST} to {@link Objects}. * - * @category Guard + * @category guards * @since 4.0.0 */ export const isObjects = makeGuard("Objects") @@ -308,23 +367,26 @@ export const isObjects = makeGuard("Objects") /** * Narrows an {@link AST} to {@link Union}. * - * @category Guard - * @since 4.0.0 + * @category guards + * @since 3.10.0 */ export const isUnion = makeGuard("Union") /** * Narrows an {@link AST} to {@link Suspend}. * - * @category Guard - * @since 4.0.0 + * @category guards + * @since 3.10.0 */ export const isSuspend = makeGuard("Suspend") /** - * A single step in an {@link Encoding} chain, pairing a target {@link AST} - * with a `Transformation` or `Middleware` that converts values between the - * current node and the target. + * Represents a single step in an {@link Encoding} chain. + * + * **Details** + * + * A link pairs a target {@link AST} with a `Transformation` or `Middleware` + * that converts values between the current node and the target. * * - `to` — the AST node on the other side of this transformation step. * - `transformation` — the bidirectional conversion logic (decode/encode). @@ -334,21 +396,20 @@ export const isSuspend = makeGuard("Suspend") * * @see {@link Encoding} * @see {@link decodeTo} - * - * @category model + * @category models * @since 4.0.0 */ export class Link { readonly to: AST readonly transformation: - | Transformation.Transformation - | Transformation.Middleware + | SchemaTransformation.Transformation + | SchemaTransformation.Middleware constructor( to: AST, transformation: - | Transformation.Transformation - | Transformation.Middleware + | SchemaTransformation.Transformation + | SchemaTransformation.Middleware ) { this.to = to this.transformation = transformation @@ -359,60 +420,65 @@ export class Link { * A non-empty chain of {@link Link} values representing the transformation * steps between a schema's decoded (type) form and its encoded (wire) form. * + * **Details** + * * Stored on {@link Base.encoding}. When `undefined`, the node has no * encoding transformation (type and encoded forms are identical). * * @see {@link Link} * @see {@link toEncoded} - * - * @category model + * @category models * @since 4.0.0 */ export type Encoding = readonly [Link, ...Array] /** - * Options that control parsing/validation behavior. + * Options that control schema parsing, validation, transformation, and output behavior. * - * Pass to `Schema.decodeUnknown`, `Schema.encode`, etc. to customize error - * reporting, excess property handling, and output key ordering. + * **Details** * - * - `errors` — `"first"` (default) stops at the first error; `"all"` - * collects every error. - * - `onExcessProperty` — `"ignore"` (default) strips unknown keys; + * Pass to `Schema.decodeUnknown`, `Schema.encode`, and related APIs to customize + * error reporting, excess property handling, output key ordering, check + * execution, and asynchronous parser concurrency. + * + * - `errors` — `"first"` (default) stops at the first error; `"all"` collects + * every error. + * - `onExcessProperty` — `"ignore"` (default) strips unknown object keys; * `"error"` fails; `"preserve"` keeps them. * - `propertyOrder` — `"none"` (default) lets the system choose key order; * `"original"` preserves input key order. + * - `disableChecks` — skips validation checks while still applying defaults and + * transformations. + * - `concurrency` — maximum number of async parse effects to run concurrently; + * defaults to `1`, or use `"unbounded"`. * - * @category model - * @since 4.0.0 + * @category options + * @since 3.10.0 */ export interface ParseOptions { /** - * The `errors` option allows you to receive all parsing errors when - * attempting to parse a value using a schema. By default only the first error - * is returned, but by setting the `errors` option to `"all"`, you can receive - * all errors that occurred during the parsing process. This can be useful for - * debugging or for providing more comprehensive error messages to the user. + * Controls how many parsing errors are reported. + * + * **Details** * - * default: "first" + * The default, `"first"`, stops at the first error. Set the option to `"all"` + * to collect every parsing error, which can help with debugging or with + * presenting more complete error messages to a user. + * + * @default "first" */ readonly errors?: "first" | "all" | undefined /** - * When using a `Objects` to parse a value, by default any properties that - * are not specified in the schema will be stripped out from the output. This - * is because the `Objects` is expecting a specific shape for the parsed - * value, and any excess properties do not conform to that shape. + * Controls how object parsing handles keys that are not declared by the schema. * - * However, you can use the `onExcessProperty` option (default value: - * `"ignore"`) to trigger a parsing error. This can be particularly useful in - * cases where you need to detect and handle potential errors or unexpected - * values. + * **Details** * - * If you want to allow excess properties to remain, you can use - * `onExcessProperty` set to `"preserve"`. + * The default, `"ignore"`, strips unspecified properties from the output. Use + * `"error"` to fail when an excess property is present, or `"preserve"` to + * keep excess properties in the output. * - * default: "ignore" + * @default "ignore" */ readonly onExcessProperty?: "ignore" | "error" | "preserve" | undefined @@ -422,16 +488,20 @@ export interface ParseOptions { * important for the consuming processes or when maintaining the input order * enhances readability and usability. * + * **Details** + * * By default, the `propertyOrder` option is set to `"none"`. This means that * the internal system decides the order of keys to optimize parsing speed. - * The order of keys in this mode should not be considered stable, and it's - * recommended not to rely on key ordering as it may change in future updates - * without notice. * * Setting `propertyOrder` to `"original"` ensures that the keys are ordered * as they appear in the input during the decoding/encoding process. * - * default: "none" + * **Gotchas** + * + * The key order for `"none"` should not be considered stable and may change + * in future updates without notice. + * + * @default "none" */ readonly propertyOrder?: "none" | "original" | undefined @@ -444,7 +514,7 @@ export interface ParseOptions { /** * The maximum number of async effects to run concurrently. * - * Defaults to 1. + * @default 1 */ readonly concurrency?: number | "unbounded" | undefined } @@ -453,7 +523,9 @@ export interface ParseOptions { export const defaultParseOptions: ParseOptions = {} /** - * Per-property metadata attached to AST nodes via {@link Base.context}. + * Represents per-property metadata attached to AST nodes via {@link Base.context}. + * + * **Details** * * Tracks whether a property key is optional, mutable, has a constructor * default, or carries key-level annotations. Typically set by helpers like @@ -468,8 +540,7 @@ export const defaultParseOptions: ParseOptions = {} * * @see {@link optionalKey} * @see {@link isOptional} - * - * @category model + * @category models * @since 4.0.0 */ export class Context { @@ -497,14 +568,15 @@ export class Context { * Non-empty array of validation {@link Check} values attached to an AST node * via {@link Base.checks}. * + * **Details** + * * Checks are run after basic type matching succeeds. They represent * refinements like `minLength`, `pattern`, `int`, etc. * * @see {@link Check} * @see {@link Filter} * @see {@link FilterGroup} - * - * @category model + * @category models * @since 4.0.0 */ export type Checks = readonly [Check, ...Array>] @@ -512,7 +584,9 @@ export type Checks = readonly [Check, ...Array>] const TypeId = "~effect/Schema" /** - * Abstract base class for all {@link AST} node variants. + * Represents the abstract base class for all {@link AST} node variants. + * + * **Details** * * Every AST node extends `Base` and inherits these fields: * @@ -526,8 +600,7 @@ const TypeId = "~effect/Schema" * Subclasses add a `_tag` discriminant and variant-specific data. * * @see {@link AST} - * - * @category model + * @category models * @since 4.0.0 */ export abstract class Base { @@ -557,53 +630,67 @@ export abstract class Base { /** * AST node for user-defined opaque types with custom parsing logic. * - * Use when none of the built-in AST nodes fit. The `run` function receives - * `typeParameters` and returns a parser that validates/transforms raw input. + * **When to use** + * + * Use when you need a custom schema AST node because none of the built-in + * nodes fit. + * + * **Details** * * - `typeParameters` — inner schemas this declaration is parameterized over * (e.g. the element type for a custom collection). - * - `run` — factory producing the actual parse function. + * - `run` — factory that receives `typeParameters` and returns a parser that + * validates or transforms raw input. * * @see {@link isDeclaration} - * - * @category model - * @since 4.0.0 + * @category models + * @since 3.10.0 */ export class Declaration extends Base { readonly _tag = "Declaration" readonly typeParameters: ReadonlyArray readonly run: ( typeParameters: ReadonlyArray - ) => (input: unknown, self: Declaration, options: ParseOptions) => Effect.Effect + ) => (input: unknown, self: Declaration, options: ParseOptions) => Effect.Effect + readonly encodingChecks: Checks | undefined constructor( typeParameters: ReadonlyArray, run: ( typeParameters: ReadonlyArray - ) => (input: unknown, self: Declaration, options: ParseOptions) => Effect.Effect, + ) => (input: unknown, self: Declaration, options: ParseOptions) => Effect.Effect, annotations?: Schema.Annotations.Annotations, checks?: Checks, encoding?: Encoding, - context?: Context + context?: Context, + encodingChecks?: Checks ) { super(annotations, checks, encoding, context) this.typeParameters = typeParameters this.run = run + this.encodingChecks = encodingChecks } /** @internal */ - getParser(): Parser.Parser { + getParser(): SchemaParser.Parser { const run = this.run(this.typeParameters) return (oinput, options) => { if (Option.isNone(oinput)) return Effect.succeedNone return Effect.mapEager(run(oinput.value, this, options), Option.some) } } - /** @internal */ - recur(recur: (ast: AST) => AST) { + private rebuild(recur: (ast: AST) => AST, checks: Checks | undefined, encodingChecks: Checks | undefined) { const tps = mapOrSame(this.typeParameters, recur) return tps === this.typeParameters ? this : - new Declaration(tps, this.run, this.annotations, this.checks, undefined, this.context) + new Declaration(tps, this.run, this.annotations, checks, undefined, this.context, encodingChecks) + } + /** @internal */ + recur(recur: (ast: AST) => AST) { + return this.rebuild(recur, this.checks, this.encodingChecks) + } + /** @internal */ + flip(recur: (ast: AST) => AST) { + return this.rebuild(recur, this.encodingChecks, this.checks) } /** @internal */ getExpected(): string { @@ -616,12 +703,13 @@ export class Declaration extends Base { /** * AST node matching the `null` literal value. * + * **Details** + * * Parsing succeeds only when the input is exactly `null`. * - * @see {@link null} + * @see {@link null_ null} * @see {@link isNull} - * - * @category model + * @category models * @since 4.0.0 */ export class Null extends Base { @@ -639,8 +727,14 @@ export class Null extends Base { const null_ = new Null() export { /** - * Singleton {@link Null} AST instance. + * Provides the singleton {@link Null} AST instance. * + * **When to use** + * + * Use when you need the shared AST node for exact null values while inspecting + * or constructing schema ASTs. + * + * @category constants * @since 4.0.0 */ null_ as null @@ -649,12 +743,13 @@ export { /** * AST node matching the `undefined` value. * + * **Details** + * * Parsing succeeds only when the input is exactly `undefined`. * * @see {@link undefined} * @see {@link isUndefined} - * - * @category model + * @category models * @since 4.0.0 */ export class Undefined extends Base { @@ -675,17 +770,23 @@ export class Undefined extends Base { const undefinedToNull = new Link( null_, - new Transformation.Transformation( - Getter.transform(() => undefined), - Getter.transform(() => null) + new SchemaTransformation.Transformation( + SchemaGetter.transform(() => undefined), + SchemaGetter.transform(() => null) ) ) const undefined_ = new Undefined() export { /** - * Singleton {@link Undefined} AST instance. + * Provides the singleton {@link Undefined} AST instance. * + * **When to use** + * + * Use when you need the shared AST node for exact undefined values while + * inspecting or constructing schema ASTs. + * + * @category constants * @since 4.0.0 */ undefined_ as undefined @@ -694,13 +795,14 @@ export { /** * AST node matching the `void` type (accepts `undefined` at runtime). * + * **Details** + * * Behaves like {@link Undefined} for parsing but represents the TypeScript * `void` type semantically. * - * @see {@link void} + * @see {@link void_ void} * @see {@link isVoid} - * - * @category model + * @category models * @since 4.0.0 */ export class Void extends Base { @@ -722,8 +824,18 @@ export class Void extends Base { const void_ = new Void() export { /** - * Singleton {@link Void} AST instance. + * Provides the singleton {@link Void} AST instance. * + * **When to use** + * + * Use when constructing or comparing AST nodes that represent the TypeScript + * `void` type and accept `undefined` at runtime. + * + * @see {@link Void} for the AST node class + * @see {@link undefined} for the sibling AST singleton that matches exactly `undefined` + * @see {@link isVoid} for narrowing an AST to a `Void` node + * + * @category constructors * @since 4.0.0 */ void_ as void @@ -732,13 +844,14 @@ export { /** * AST node representing the `never` type — no value matches. * + * **Details** + * * Parsing always fails. Useful as a placeholder in unions or as the result * of narrowing that eliminates all options. * * @see {@link never} * @see {@link isNever} - * - * @category model + * @category models * @since 4.0.0 */ export class Never extends Base { @@ -754,8 +867,17 @@ export class Never extends Base { } /** - * Singleton {@link Never} AST instance. + * Provides the singleton {@link Never} AST instance. + * + * **When to use** + * + * Use to reuse the canonical bottom-type AST node when constructing, + * comparing, or returning ASTs. + * + * @see {@link Never} for the AST node class + * @see {@link isNever} for narrowing an AST to a `Never` node * + * @category constructors * @since 4.0.0 */ export const never = new Never() @@ -766,7 +888,7 @@ export const never = new Never() * @see {@link any} * @see {@link isAny} * - * @category model + * @category models * @since 4.0.0 */ export class Any extends Base { @@ -782,8 +904,16 @@ export class Any extends Base { } /** - * Singleton {@link Any} AST instance. + * Provides the singleton {@link Any} AST instance. * + * **When to use** + * + * Use when you need the singleton AST node for the TypeScript `any` type and + * intentionally want parsing to accept every input value. + * + * @see {@link unknown} for the sibling AST singleton that also accepts every value while preserving the safer `unknown` type + * + * @category constructors * @since 4.0.0 */ export const any = new Any() @@ -791,13 +921,14 @@ export const any = new Any() /** * AST node representing the `unknown` type — every value matches. * + * **Details** + * * Unlike {@link Any}, this is type-safe: the parsed result is typed as * `unknown` rather than `any`. * * @see {@link unknown} * @see {@link isUnknown} - * - * @category model + * @category models * @since 4.0.0 */ export class Unknown extends Base { @@ -813,8 +944,16 @@ export class Unknown extends Base { } /** - * Singleton {@link Unknown} AST instance. + * Provides the singleton {@link Unknown} AST instance. + * + * **When to use** + * + * Use when you need the reusable AST singleton for a schema node that accepts + * every value while keeping parsed values opaque. + * + * @see {@link any} for the singleton that accepts every value as `any` * + * @category constructors * @since 4.0.0 */ export const unknown = new Unknown() @@ -826,8 +965,8 @@ export const unknown = new Unknown() * @see {@link objectKeyword} * @see {@link isObjectKeyword} * - * @category model - * @since 4.0.0 + * @category models + * @since 3.10.0 */ export class ObjectKeyword extends Base { readonly _tag = "ObjectKeyword" @@ -842,21 +981,31 @@ export class ObjectKeyword extends Base { } /** - * Singleton {@link ObjectKeyword} AST instance. + * Provides the singleton {@link ObjectKeyword} AST instance. * - * @since 4.0.0 + * **When to use** + * + * Use to reuse the canonical AST node for the TypeScript `object` keyword when + * building or comparing `SchemaAST` values directly. + * + * @see {@link ObjectKeyword} for the AST node class + * @see {@link isObjectKeyword} for narrowing an AST to an `ObjectKeyword` node + * + * @category constructors + * @since 3.10.0 */ export const objectKeyword = new ObjectKeyword() /** * AST node representing a TypeScript `enum`. * + * **Details** + * * Holds `enums` as an array of `[name, value]` pairs where values are * `string | number`. Parsing succeeds when the input matches any enum value. * * @see {@link isEnum} - * - * @category model + * @category models * @since 4.0.0 */ export class Enum extends Base { @@ -888,9 +1037,9 @@ export class Enum extends Base { return replaceEncoding(this, [ new Link( new Union(Object.keys(coercions).map((k) => new Literal(k)), "anyOf"), - new Transformation.Transformation( - Getter.transform((s) => coercions[s]), - Getter.String() + new SchemaTransformation.Transformation( + SchemaGetter.transform((s) => coercions[s]), + SchemaGetter.String() ) ) ]) @@ -930,14 +1079,15 @@ function isTemplateLiteralPart(ast: AST): ast is TemplateLiteralPart { * AST node representing a TypeScript template literal type * (e.g. `` `user_${string}` ``). * + * **Details** + * * `parts` is an array of AST nodes; each part contributes to the * template literal pattern. A regex is derived from the parts to validate * strings at runtime. * * @see {@link isTemplateLiteral} - * - * @category model - * @since 4.0.0 + * @category models + * @since 3.10.0 */ export class TemplateLiteral extends Base { readonly _tag = "TemplateLiteral" @@ -966,12 +1116,12 @@ export class TemplateLiteral extends Base { this.encodedParts = encodedParts } /** @internal */ - getParser(recur: (ast: AST) => Parser.Parser): Parser.Parser { + getParser(recur: (ast: AST) => SchemaParser.Parser): SchemaParser.Parser { const parser = recur(this.asTemplateLiteralParser()) return (oinput: Option.Option, options: ParseOptions) => Effect.mapBothEager(parser(oinput, options), { onSuccess: () => oinput, - onFailure: (issue) => new Issue.Composite(this, oinput, [issue]) + onFailure: (issue) => new SchemaIssue.Composite(this, oinput, [issue]) }) } /** @internal */ @@ -985,17 +1135,17 @@ export class TemplateLiteral extends Base { return decodeTo( string, tuple, - new Transformation.Transformation( - Getter.transformOrFail((s: string) => { + new SchemaTransformation.Transformation( + SchemaGetter.transformOrFail((s: string) => { const match = regExp.exec(s) if (match) return Effect.succeed(match.slice(1, this.parts.length + 1)) return Effect.fail( - new Issue.InvalidValue(Option.some(s), { + new SchemaIssue.InvalidValue(Option.some(s), { message: `Expected a value matching ${regExp.source}, got ${format(s)}` }) ) }), - Getter.transform((parts) => parts.join("")) + SchemaGetter.transform((parts) => parts.join("")) ) ) } @@ -1004,13 +1154,14 @@ export class TemplateLiteral extends Base { /** * AST node matching a specific `unique symbol` value. * + * **Details** + * * Parsing succeeds only when the input is reference-equal to the stored * `symbol`. * * @see {@link isUniqueSymbol} - * - * @category model - * @since 4.0.0 + * @category models + * @since 3.10.0 */ export class UniqueSymbol extends Base { readonly _tag = "UniqueSymbol" @@ -1045,8 +1196,8 @@ export class UniqueSymbol extends Base { * * @see {@link Literal} * - * @category model - * @since 4.0.0 + * @category models + * @since 3.10.0 */ export type LiteralValue = string | number | boolean | bigint @@ -1054,6 +1205,8 @@ export type LiteralValue = string | number | boolean | bigint * AST node matching an exact primitive value (string, number, boolean, or * bigint). * + * **Details** + * * Parsing succeeds only when the input is strictly equal (`===`) to the * stored `literal`. Numeric literals must be finite — `Infinity`, `-Infinity`, * and `NaN` are rejected at construction time. @@ -1069,9 +1222,8 @@ export type LiteralValue = string | number | boolean | bigint * * @see {@link LiteralValue} * @see {@link isLiteral} - * - * @category model - * @since 4.0.0 + * @category models + * @since 3.10.0 */ export class Literal extends Base { readonly _tag = "Literal" @@ -1113,9 +1265,9 @@ function literalToString(ast: Literal): Literal { return replaceEncoding(ast, [ new Link( new Literal(literalAsString), - new Transformation.Transformation( - Getter.transform(() => ast.literal), - Getter.transform(() => literalAsString) + new SchemaTransformation.Transformation( + SchemaGetter.transform(() => ast.literal), + SchemaGetter.transform(() => literalAsString) ) ) ]) @@ -1127,7 +1279,7 @@ function literalToString(ast: Literal): Literal { * @see {@link string} * @see {@link isString} * - * @category model + * @category models * @since 4.0.0 */ export class String extends Base { @@ -1143,8 +1295,16 @@ export class String extends Base { } /** - * Singleton {@link String} AST instance. + * Provides the singleton {@link String} AST instance. * + * **When to use** + * + * Use as the shared `SchemaAST` node for unconstrained JavaScript strings. + * + * @see {@link String} for the AST node class + * @see {@link isString} for narrowing an AST to a string node + * + * @category constructors * @since 4.0.0 */ export const string = new String() @@ -1153,7 +1313,10 @@ export const string = new String() * AST node matching any `number` value (including `NaN`, `Infinity`, * `-Infinity`). * + * **Details** + * * Default JSON serialization: + * * - Finite numbers are serialized as JSON numbers. * - `Infinity`, `-Infinity`, and `NaN` are serialized as JSON strings. * @@ -1162,8 +1325,7 @@ export const string = new String() * * @see {@link number} * @see {@link isNumber} - * - * @category model + * @category models * @since 4.0.0 */ export class Number extends Base { @@ -1205,8 +1367,17 @@ function hasCheck(checks: ReadonlyArray>, tag: string): boolean { } /** - * Singleton {@link Number} AST instance. + * Provides the singleton {@link Number} AST instance. + * + * **When to use** + * + * Use when you need the canonical `SchemaAST` node for schemas that accept any + * JavaScript number value. * + * @see {@link Number} for the AST node class and serialization behavior + * @see {@link Literal} for exact finite numeric literal AST nodes + * + * @category constructors * @since 4.0.0 */ export const number = new Number() @@ -1217,7 +1388,7 @@ export const number = new Number() * @see {@link boolean} * @see {@link isBoolean} * - * @category model + * @category models * @since 4.0.0 */ export class Boolean extends Base { @@ -1233,8 +1404,17 @@ export class Boolean extends Base { } /** - * Singleton {@link Boolean} AST instance. + * Provides the singleton {@link Boolean} AST instance. + * + * **When to use** + * + * Use to reuse the standard AST node that accepts either `true` or `false` when + * constructing schema ASTs directly. + * + * @see {@link Boolean} for the AST node class + * @see {@link Literal} for exact boolean literal AST nodes * + * @category constructors * @since 4.0.0 */ export const boolean = new Boolean() @@ -1242,13 +1422,19 @@ export const boolean = new Boolean() /** * AST node matching any `symbol` value. * + * **When to use** + * + * Use when you need the AST node class for schemas that match any JavaScript + * symbol value. + * + * **Details** + * * When serialized to a string-based codec, symbols are converted via * `Symbol.keyFor` and must be registered with `Symbol.for`. * * @see {@link symbol} * @see {@link isSymbol} - * - * @category model + * @category models * @since 4.0.0 */ export class Symbol extends Base { @@ -1268,8 +1454,21 @@ export class Symbol extends Base { } /** - * Singleton {@link Symbol} AST instance. + * Provides the singleton {@link Symbol} AST instance. + * + * **When to use** + * + * Use to reuse the singleton AST node for schemas that match any JavaScript + * symbol value. + * + * **Gotchas** + * + * String-based codecs can encode only symbols registered with `Symbol.for`, + * because the implementation uses `Symbol.keyFor`. * + * @see {@link UniqueSymbol} for an AST node that matches one specific symbol + * + * @category constructors * @since 4.0.0 */ export const symbol = new Symbol() @@ -1277,13 +1476,14 @@ export const symbol = new Symbol() /** * AST node matching any `bigint` value. * + * **Details** + * * When serialized to a string-based codec, bigints are converted to/from * their decimal string representation. * * @see {@link bigInt} * @see {@link isBigInt} - * - * @category model + * @category models * @since 4.0.0 */ export class BigInt extends Base { @@ -1303,8 +1503,17 @@ export class BigInt extends Base { } /** - * Singleton {@link BigInt} AST instance. + * Provides the singleton {@link BigInt} AST instance. + * + * **When to use** + * + * Use to reuse the canonical `BigInt` AST node when constructing, inspecting, + * or transforming schemas at the AST level. * + * @see {@link BigInt} for the AST node class and string-codec behavior + * @see {@link isBigInt} for narrowing an AST to a `BigInt` node + * + * @category constructors * @since 4.0.0 */ export const bigInt = new BigInt() @@ -1312,6 +1521,13 @@ export const bigInt = new BigInt() /** * AST node for array-like types — both tuples and arrays. * + * **When to use** + * + * Use when constructing or inspecting AST nodes for tuple or array-like schemas, + * including rest elements. + * + * **Details** + * * - `elements` — positional element types (tuple elements). An element is * optional if its {@link Context.isOptional} is `true`. * - `rest` — the rest/variadic element types. When non-empty, the first @@ -1320,6 +1536,8 @@ export const bigInt = new BigInt() * - `isMutable` — whether the resulting array is `readonly` (`false`) or * mutable (`true`). * + * **Gotchas** + * * Construction enforces TypeScript ordering rules: a required element * cannot follow an optional one, and an optional element cannot follow a * rest element. @@ -1340,8 +1558,7 @@ export const bigInt = new BigInt() * * @see {@link isArrays} * @see {@link Objects} - * - * @category model + * @category models * @since 4.0.0 */ export class Arrays extends Base { @@ -1349,6 +1566,7 @@ export class Arrays extends Base { readonly isMutable: boolean readonly elements: ReadonlyArray readonly rest: ReadonlyArray + readonly encodingChecks: Checks | undefined constructor( isMutable: boolean, @@ -1357,12 +1575,14 @@ export class Arrays extends Base { annotations?: Schema.Annotations.Annotations, checks?: Checks, encoding?: Encoding, - context?: Context + context?: Context, + encodingChecks?: Checks ) { super(annotations, checks, encoding, context) this.isMutable = isMutable this.elements = elements this.rest = rest + this.encodingChecks = encodingChecks // A required element cannot follow an optional element. ts(1257) const i = elements.findIndex(isOptional) @@ -1376,7 +1596,7 @@ export class Arrays extends Base { } } /** @internal */ - getParser(recur: (ast: AST) => Parser.Parser): Parser.Parser { + getParser(recur: (ast: AST) => SchemaParser.Parser): SchemaParser.Parser { // oxlint-disable-next-line @typescript-eslint/no-this-alias const ast = this const elements = ast.elements.map((ast) => ({ ast, parser: recur(ast) })) @@ -1386,7 +1606,10 @@ export class Arrays extends Base { const [head, ...tail] = rest const tailLen = tail.length - function getParser(tailThreshold: number, index: number): { readonly ast: AST; readonly parser: Parser.Parser } { + function getParser( + tailThreshold: number, + index: number + ): { readonly ast: AST; readonly parser: SchemaParser.Parser } { if (index < elementLen) { return elements[index] } else if (index >= tailThreshold) { @@ -1403,7 +1626,7 @@ export class Arrays extends Base { // If the input is not an array, return early with an error if (!Array.isArray(input)) { - return yield* Effect.fail(new Issue.InvalidType(ast, oinput)) + return yield* Effect.fail(new SchemaIssue.InvalidType(ast, oinput)) } const len = input.length @@ -1414,7 +1637,7 @@ export class Arrays extends Base { len, tailThreshold: resolveTailThreshold(len, elementLen, tailLen), output: new globalThis.Array(len), - issues: undefined as Arr.NonEmptyArray | undefined, + issues: undefined as Arr.NonEmptyArray | undefined, options } const concurrency = resolveConcurrency(options?.concurrency) @@ -1429,28 +1652,44 @@ export class Arrays extends Base { // --------------------------------------------- if (ast.rest.length === 0 && len > elementLen) { for (let i = elementLen; i <= len - 1; i++) { - const issue = new Issue.Pointer([i], new Issue.UnexpectedKey(ast, input[i])) + const issue = new SchemaIssue.Pointer([i], new SchemaIssue.UnexpectedKey(ast, input[i])) if (options.errors === "all") { if (state.issues) state.issues.push(issue) else state.issues = [issue] } else { - return yield* Effect.fail(new Issue.Composite(ast, oinput, [issue])) + return yield* Effect.fail(new SchemaIssue.Composite(ast, oinput, [issue])) } } } if (state.issues) { - return yield* Effect.fail(new Issue.Composite(ast, oinput, state.issues)) + return yield* Effect.fail(new SchemaIssue.Composite(ast, oinput, state.issues)) } return Option.some(state.output) }) } - /** @internal */ - recur(recur: (ast: AST) => AST) { + private rebuild(recur: (ast: AST) => AST, checks: Checks | undefined, encodingChecks: Checks | undefined) { const elements = mapOrSame(this.elements, recur) const rest = mapOrSame(this.rest, recur) return elements === this.elements && rest === this.rest ? this : - new Arrays(this.isMutable, elements, rest, this.annotations, this.checks, undefined, this.context) + new Arrays( + this.isMutable, + elements, + rest, + this.annotations, + checks, + undefined, + this.context, + encodingChecks + ) + } + /** @internal */ + recur(recur: (ast: AST) => AST) { + return this.rebuild(recur, this.checks, this.encodingChecks) + } + /** @internal */ + flip(recur: (ast: AST) => AST) { + return this.rebuild(recur, this.encodingChecks, this.checks) } /** @internal */ getExpected(): string { @@ -1461,11 +1700,14 @@ const parseArray = iterateEager<{ readonly ast: AST readonly oinput: Option.Option readonly len: number - readonly getParser: (tailThreshold: number, index: number) => { readonly ast: AST; readonly parser: Parser.Parser } + readonly getParser: ( + tailThreshold: number, + index: number + ) => { readonly ast: AST; readonly parser: SchemaParser.Parser } readonly tailThreshold: number readonly options: ParseOptions readonly output: Array - issues: Array | undefined + issues: Array | undefined }, unknown>()({ onItem(s, item, i) { const value = i < s.len ? Option.some(item) : Option.none() @@ -1479,12 +1721,12 @@ const parseArray = iterateEager<{ } else { const p = s.getParser(s.tailThreshold, i) if (isOptional(p.ast)) return - const issue = new Issue.Pointer([i], new Issue.MissingKey(p.ast.context?.annotations)) + const issue = new SchemaIssue.Pointer([i], new SchemaIssue.MissingKey(p.ast.context?.annotations)) if (s.options.errors === "all") { if (s.issues) s.issues.push(issue) else s.issues = [issue] } else { - return Exit.fail(new Issue.Composite(s.ast, s.oinput, [issue])) + return Exit.fail(new SchemaIssue.Composite(s.ast, s.oinput, [issue])) } } } @@ -1507,22 +1749,22 @@ const wrapPropertyKeyIssue = ( s: { readonly oinput: Option.Option readonly options: ParseOptions - issues: Array | undefined + issues: Array | undefined }, ast: AST, key: PropertyKey, - exit: Exit.Failure + exit: Exit.Failure ) => { const issueResult = Cause.findError(exit.cause) if (Result.isFailure(issueResult)) { return exit } - const issue = new Issue.Pointer([key], issueResult.success) + const issue = new SchemaIssue.Pointer([key], issueResult.success) if (s.options.errors === "all") { if (s.issues) s.issues.push(issue) else s.issues = [issue] } else { - return Exit.fail(new Issue.Composite(ast, s.oinput, [issue])) + return Exit.fail(new SchemaIssue.Composite(ast, s.oinput, [issue])) } } @@ -1562,16 +1804,17 @@ export function getIndexSignatureKeys( } /** - * A named property within an {@link Objects} node. + * Represents a named property within an {@link Objects} node. + * + * **Details** * * Pairs a `name` (any `PropertyKey`) with a `type` ({@link AST}). The * property's optionality and mutability are determined by the `type`'s * {@link Context}. * * @see {@link Objects} - * - * @category model - * @since 4.0.0 + * @category models + * @since 3.10.0 */ export class PropertySignature { readonly name: PropertyKey @@ -1587,7 +1830,9 @@ export class PropertySignature { } /** - * Bidirectional merge strategy for index signature key-value pairs. + * Represents a bidirectional merge strategy for index signature key-value pairs. + * + * **Details** * * Used by {@link IndexSignature} when the same key appears multiple times * (e.g. from `Schema.extend` or overlapping records). Provides separate @@ -1595,8 +1840,7 @@ export class PropertySignature { * merged. * * @see {@link IndexSignature} - * - * @category model + * @category models * @since 4.0.0 */ export class KeyValueCombiner { @@ -1617,21 +1861,29 @@ export class KeyValueCombiner { } /** - * An index signature entry within an {@link Objects} node. + * Represents an index signature entry within an {@link Objects} node. + * + * **When to use** + * + * Use when constructing or inspecting object AST entries for record-like keys + * and values. + * + * **Details** * * - `parameter` — the key type AST (e.g. {@link String} for `string` keys, * {@link TemplateLiteral} for patterned keys). - * - `type` — the value type AST. + * - `type` — the value type SchemaAST. * - `merge` — optional {@link KeyValueCombiner} for handling duplicate keys. * + * **Gotchas** + * * Using `Schema.optionalKey` on the value type is not allowed for index * signatures (throws at construction); use `Schema.optional` instead. * * @see {@link Objects} * @see {@link PropertySignature} - * - * @category model - * @since 4.0.0 + * @category models + * @since 3.10.0 */ export class IndexSignature { readonly parameter: AST @@ -1653,14 +1905,24 @@ export class IndexSignature { } /** - * AST node for object-like types — both structs and records. + * AST node for object-like schemas, including structs and records. + * + * **When to use** + * + * Use when constructing or inspecting AST nodes for structs or records rather + * than array-like schemas. + * + * **Details** * * - `propertySignatures` — named properties with their types (struct fields). * - `indexSignatures` — index signature entries (record patterns), each with - * a `parameter` AST (the key type) and a `type` AST (the value type). + * a `parameter` AST for matching keys and a `type` AST for values. + * + * An `Objects` node with no properties and no index signatures performs only a + * non-nullish check: it accepts any value except `null` and `undefined`, + * including primitive values. * - * An `Objects` with no properties and no index signatures acts as a bare - * `object | array` type check (accepts any non-nullish value). + * **Gotchas** * * Duplicate property names throw at construction time. * @@ -1684,14 +1946,14 @@ export class IndexSignature { * @see {@link PropertySignature} * @see {@link IndexSignature} * @see {@link Arrays} - * - * @category model + * @category models * @since 4.0.0 */ export class Objects extends Base { readonly _tag = "Objects" readonly propertySignatures: ReadonlyArray readonly indexSignatures: ReadonlyArray + readonly encodingChecks: Checks | undefined constructor( propertySignatures: ReadonlyArray, @@ -1699,11 +1961,13 @@ export class Objects extends Base { annotations?: Schema.Annotations.Annotations, checks?: Checks, encoding?: Encoding, - context?: Context + context?: Context, + encodingChecks?: Checks ) { super(annotations, checks, encoding, context) this.propertySignatures = propertySignatures this.indexSignatures = indexSignatures + this.encodingChecks = encodingChecks // Duplicate property signatures const duplicates = propertySignatures.map((ps) => ps.name).filter((name, i, arr) => arr.indexOf(name) !== i) @@ -1712,14 +1976,14 @@ export class Objects extends Base { } } /** @internal */ - getParser(recur: (ast: AST) => Parser.Parser): Parser.Parser { + getParser(recur: (ast: AST) => SchemaParser.Parser): SchemaParser.Parser { // oxlint-disable-next-line @typescript-eslint/no-this-alias const ast = this const expectedKeys: Array = [] const expectedKeysSet = new Set() const properties: Array<{ readonly ps: PropertySignature | IndexSignature - readonly parser: Parser.Parser + readonly parser: SchemaParser.Parser readonly name: PropertyKey readonly type: AST }> = [] @@ -1747,7 +2011,7 @@ export class Objects extends Base { readonly input: Record readonly options: ParseOptions readonly out: Record - issues: Array | undefined + issues: Array | undefined }, [key: PropertyKey, is: IndexSignature]>()({ onItem: Effect.fnUntracedEager(function*( s, @@ -1757,7 +2021,7 @@ export class Objects extends Base { const effKey = parserKey(Option.some(key), s.options) const exitKey = (effectIsExit(effKey) ? effKey : yield* Effect.exit(effKey)) as Exit.Exit< Option.Option, - Issue.Issue + SchemaIssue.Issue > if (exitKey._tag === "Failure") { const eff = wrapPropertyKeyIssue(s, ast, key, exitKey) @@ -1775,6 +2039,9 @@ export class Objects extends Base { return } else if (exitKey.value._tag === "Some" && exitValue.value._tag === "Some") { const k2 = exitKey.value.value + if (expectedKeysSet.has(key) || expectedKeysSet.has(k2)) { + return + } const v2 = exitValue.value.value if (is.merge && is.merge.decode && Object.hasOwn(s.out, k2)) { const [k, v] = is.merge.decode.combine([k2, s.out[k2]], [k2, v2]) @@ -1784,7 +2051,7 @@ export class Objects extends Base { } } }), - step: (_s, _, exit: Exit.Exit) => exit._tag === "Failure" ? exit : undefined + step: (_s, _, exit: Exit.Exit) => exit._tag === "Failure" ? exit : undefined }) : undefined @@ -1796,7 +2063,7 @@ export class Objects extends Base { // If the input is not a record, return early with an error if (!(typeof input === "object" && input !== null && !Array.isArray(input))) { - return yield* Effect.fail(new Issue.InvalidType(ast, oinput)) + return yield* Effect.fail(new SchemaIssue.InvalidType(ast, oinput)) } const out: Record = {} @@ -1805,7 +2072,7 @@ export class Objects extends Base { oinput, input, out, - issues: undefined as Arr.NonEmptyArray | undefined, + issues: undefined as Arr.NonEmptyArray | undefined, options } const errorsAllOption = options.errors === "all" @@ -1823,7 +2090,7 @@ export class Objects extends Base { if (!expectedKeysSet.has(key)) { // key is unexpected if (onExcessPropertyError) { - const issue = new Issue.Pointer([key], new Issue.UnexpectedKey(ast, input[key])) + const issue = new SchemaIssue.Pointer([key], new SchemaIssue.UnexpectedKey(ast, input[key])) if (errorsAllOption) { if (state.issues) { state.issues.push(issue) @@ -1832,7 +2099,7 @@ export class Objects extends Base { } continue } else { - return yield* Effect.fail(new Issue.Composite(ast, oinput, [issue])) + return yield* Effect.fail(new SchemaIssue.Composite(ast, oinput, [issue])) } } else { // preserve key @@ -1868,7 +2135,7 @@ export class Objects extends Base { } if (state.issues) { - return yield* Effect.fail(new Issue.Composite(ast, oinput, state.issues)) + return yield* Effect.fail(new SchemaIssue.Composite(ast, oinput, state.issues)) } if (options.propertyOrder === "original") { // preserve input keys order @@ -1886,7 +2153,9 @@ export class Objects extends Base { } private rebuild( recur: (ast: AST) => AST, - flipMerge: boolean + flipMerge: boolean, + checks: Checks | undefined, + encodingChecks: Checks | undefined ): Objects { const props = mapOrSame(this.propertySignatures, (ps) => { const t = recur(ps.type) @@ -1904,15 +2173,23 @@ export class Objects extends Base { return props === this.propertySignatures && indexes === this.indexSignatures ? this - : new Objects(props, indexes, this.annotations, this.checks, undefined, this.context) + : new Objects( + props, + indexes, + this.annotations, + checks, + undefined, + this.context, + encodingChecks + ) } /** @internal */ flip(recur: (ast: AST) => AST): AST { - return this.rebuild(recur, true) + return this.rebuild(recur, true, this.encodingChecks, this.checks) } /** @internal */ recur(recur: (ast: AST) => AST): AST { - return this.rebuild(recur, false) + return this.rebuild(recur, false, this.checks, this.encodingChecks) } /** @internal */ getExpected(): string { @@ -1923,7 +2200,7 @@ export class Objects extends Base { type ParsedProperty = { readonly ps: PropertySignature | IndexSignature - readonly parser: Parser.Parser + readonly parser: SchemaParser.Parser readonly name: PropertyKey readonly type: AST } @@ -1934,7 +2211,7 @@ const parseProperties = iterateEager<{ readonly input: Record readonly options: ParseOptions readonly out: Record - issues: Array | undefined + issues: Array | undefined }, ParsedProperty>()({ onItem( s: { @@ -1942,7 +2219,7 @@ const parseProperties = iterateEager<{ readonly input: Record readonly options: ParseOptions readonly out: Record - issues: Array | undefined + issues: Array | undefined }, p ) { @@ -1957,14 +2234,14 @@ const parseProperties = iterateEager<{ } else if (exit.value._tag === "Some") { internalRecord.set(s.out, p.name, exit.value.value) } else if (!isOptional(p.type)) { - const issue = new Issue.Pointer([p.name], new Issue.MissingKey(p.type.context?.annotations)) + const issue = new SchemaIssue.Pointer([p.name], new SchemaIssue.MissingKey(p.type.context?.annotations)) if (s.options.errors === "all") { if (s.issues) s.issues.push(issue) else s.issues = [issue] return } else { return Exit.fail( - new Issue.Composite(s.ast, s.oinput, [issue]) + new SchemaIssue.Composite(s.ast, s.oinput, [issue]) ) } } @@ -2228,6 +2505,8 @@ export function getCandidates(input: any, types: ReadonlyArray): ReadonlyAr /** * AST node representing a union of schemas. * + * **Details** + * * - `types` — the member AST nodes. * - `mode` — `"anyOf"` succeeds on the first match (like TypeScript unions); * `"oneOf"` requires exactly one member to match (fails if multiple do). @@ -2251,14 +2530,14 @@ export function getCandidates(input: any, types: ReadonlyArray): ReadonlyAr * ``` * * @see {@link isUnion} - * - * @category model - * @since 4.0.0 + * @category models + * @since 3.10.0 */ export class Union extends Base { readonly _tag = "Union" readonly types: ReadonlyArray readonly mode: "anyOf" | "oneOf" + readonly encodingChecks: Checks | undefined constructor( types: ReadonlyArray, @@ -2266,14 +2545,16 @@ export class Union extends Base { annotations?: Schema.Annotations.Annotations, checks?: Checks, encoding?: Encoding, - context?: Context + context?: Context, + encodingChecks?: Checks ) { super(annotations, checks, encoding, context) this.types = types this.mode = mode + this.encodingChecks = encodingChecks } /** @internal */ - getParser(recur: (ast: AST) => Parser.Parser): Parser.Parser { + getParser(recur: (ast: AST) => SchemaParser.Parser): SchemaParser.Parser { // oxlint-disable-next-line @typescript-eslint/no-this-alias const ast = this @@ -2291,25 +2572,36 @@ export class Union extends Base { input, out: undefined, successes: [], - issues: undefined as Arr.NonEmptyArray | undefined, + issues: undefined as Arr.NonEmptyArray | undefined, options } const concurrency = resolveConcurrency(options?.concurrency) const eff = parseUnion(state, candidates, concurrency) if (!eff) { - return state.out ? Effect.succeed(state.out) : Effect.fail(new Issue.AnyOf(ast, input, state.issues ?? [])) + return state.out + ? Effect.succeed(state.out) + : Effect.fail(new SchemaIssue.AnyOf(ast, input, state.issues ?? [])) } return Effect.flatMap(eff, (_) => { - return state.out ? Effect.succeed(state.out) : Effect.fail(new Issue.AnyOf(ast, input, state.issues ?? [])) + return state.out + ? Effect.succeed(state.out) + : Effect.fail(new SchemaIssue.AnyOf(ast, input, state.issues ?? [])) }) } } - /** @internal */ - recur(recur: (ast: AST) => AST) { + private rebuild(recur: (ast: AST) => AST, checks: Checks | undefined, encodingChecks: Checks | undefined) { const types = mapOrSame(this.types, recur) return types === this.types ? this : - new Union(types, this.mode, this.annotations, this.checks, undefined, this.context) + new Union(types, this.mode, this.annotations, checks, undefined, this.context, encodingChecks) + } + /** @internal */ + recur(recur: (ast: AST) => AST) { + return this.rebuild(recur, this.checks, this.encodingChecks) + } + /** @internal */ + flip(recur: (ast: AST) => AST) { + return this.rebuild(recur, this.encodingChecks, this.checks) } /** @internal */ getExpected(getExpected: (ast: AST) => string): string { @@ -2351,14 +2643,14 @@ export class Union extends Base { } const parseUnion = iterateEager<{ - readonly recur: (ast: AST) => Parser.Parser + readonly recur: (ast: AST) => SchemaParser.Parser readonly ast: Union readonly oinput: Option.Option readonly input: unknown readonly options: ParseOptions out: Option.Option | undefined successes: Array - issues: Array | undefined + issues: Array | undefined }, AST>()({ onItem(s, ast) { const parser = s.recur(ast) @@ -2375,7 +2667,7 @@ const parseUnion = iterateEager<{ } else { if (s.out && s.ast.mode === "oneOf") { s.successes.push(candidate) - return Exit.fail(new Issue.OneOf(s.ast, s.input, s.successes)) + return Exit.fail(new SchemaIssue.OneOf(s.ast, s.input, s.successes)) } s.out = exit.value s.successes.push(candidate) @@ -2394,9 +2686,9 @@ const nonFiniteLiterals = new Union([ const numberToJson = new Link( new Union([number, nonFiniteLiterals], "anyOf"), - new Transformation.Transformation( - Getter.Number(), - Getter.transform((n) => globalThis.Number.isFinite(n) ? n : globalThis.String(n)) + new SchemaTransformation.Transformation( + SchemaGetter.Number(), + SchemaGetter.transform((n) => globalThis.Number.isFinite(n) ? n : globalThis.String(n)) ) ) @@ -2425,6 +2717,8 @@ export function memoizeThunk(f: () => A): () => A { /** * AST node for lazy/recursive schemas. * + * **Details** + * * Wraps a thunk (`() => AST`) that is memoized on first call. Use this to * define recursive or mutually recursive schemas without infinite loops at * construction time. @@ -2448,9 +2742,8 @@ export function memoizeThunk(f: () => A): () => A { * ``` * * @see {@link isSuspend} - * - * @category model - * @since 4.0.0 + * @category models + * @since 3.10.0 */ export class Suspend extends Base { readonly _tag = "Suspend" @@ -2463,16 +2756,25 @@ export class Suspend extends Base { encoding?: Encoding, context?: Context ) { - super(annotations, checks, encoding, context) + if (checks !== undefined) { + throw new Error("Cannot add checks to Suspend") + } + super(annotations, undefined, encoding, context) this.thunk = memoizeThunk(thunk) } /** @internal */ - getParser(recur: (ast: AST) => Parser.Parser): Parser.Parser { + getParser(recur: (ast: AST) => SchemaParser.Parser): SchemaParser.Parser { return recur(this.thunk()) } /** @internal */ recur(recur: (ast: AST) => AST) { - return new Suspend(() => recur(this.thunk()), this.annotations, this.checks, undefined, this.context) + return new Suspend( + () => recur(this.thunk()), + this.annotations, + undefined, + undefined, + this.context + ) } /** @internal */ getExpected(getExpected: (ast: AST) => string): string { @@ -2480,12 +2782,27 @@ export class Suspend extends Base { } } +/** @internal */ +export function getEncodingChecks(ast: AST): Checks | undefined { + switch (ast._tag) { + case "Declaration": + case "Arrays": + case "Objects": + case "Union": + return ast.encodingChecks + default: + return undefined + } +} + // ----------------------------------------------------------------------------- // Checks // ----------------------------------------------------------------------------- /** - * A single validation check attached to an AST node. + * Represents a single validation check attached to an AST node. + * + * **Details** * * - `run` — the validation function. Returns `undefined` on success, or an * `Issue` on failure. @@ -2500,13 +2817,12 @@ export class Suspend extends Base { * @see {@link FilterGroup} * @see {@link Check} * @see {@link isPattern} - * - * @category model + * @category models * @since 4.0.0 */ export class Filter extends Pipeable.Class { readonly _tag = "Filter" - readonly run: (input: E, self: AST, options: ParseOptions) => Issue.Issue | undefined + readonly run: (input: E, self: AST, options: ParseOptions) => SchemaIssue.Issue | undefined readonly annotations: Schema.Annotations.Filter | undefined /** * Whether the parsing process should be aborted after this check has failed. @@ -2514,7 +2830,7 @@ export class Filter extends Pipeable.Class { readonly aborted: boolean constructor( - run: (input: E, self: AST, options: ParseOptions) => Issue.Issue | undefined, + run: (input: E, self: AST, options: ParseOptions) => SchemaIssue.Issue | undefined, annotations: Schema.Annotations.Filter | undefined = undefined, /** * Whether the parsing process should be aborted after this check has failed. @@ -2539,7 +2855,9 @@ export class Filter extends Pipeable.Class { } /** - * A composite validation check grouping multiple {@link Check} values. + * Represents a composite validation check grouping multiple {@link Check} values. + * + * **Details** * * Created by calling `.and()` on a {@link Filter} or another `FilterGroup`. * All inner checks are run; failures from aborted filters still stop @@ -2547,8 +2865,7 @@ export class Filter extends Pipeable.Class { * * @see {@link Filter} * @see {@link Check} - * - * @category model + * @category models * @since 4.0.0 */ export class FilterGroup extends Pipeable.Class { @@ -2577,12 +2894,13 @@ export class FilterGroup extends Pipeable.Class { * A validation check — either a single {@link Filter} or a composite * {@link FilterGroup}. * + * **Details** + * * Stored in the {@link Checks} array on {@link Base.checks}. * * @see {@link Filter} * @see {@link FilterGroup} - * - * @category model + * @category models * @since 4.0.0 */ export type Check = Filter | FilterGroup @@ -2594,7 +2912,7 @@ export function makeFilter( aborted: boolean = false ): Filter { return new Filter( - (input, ast, options) => Issue.make(input, ast, filter(input, ast, options)), + (input, ast, options) => SchemaIssue.make(input, ast, filter(input, ast, options)), annotations, aborted ) @@ -2606,19 +2924,31 @@ export function makeFilterByGuard( annotations?: Schema.Annotations.Filter ): Filter { return new Filter( - (input: E) => is(input) ? undefined : new Issue.InvalidValue(Option.some(input)), + (input: E) => is(input) ? undefined : new SchemaIssue.InvalidValue(Option.some(input)), annotations, true // after a guard, we always want to abort ) } /** - * Creates a {@link Filter} that validates strings against a regular expression. + * Creates a {@link Filter} that validates strings by running `RegExp.test`. + * + * **When to use** + * + * Use when string validation should be represented as a schema `Filter` backed + * by a regular expression. + * + * **Details** * - * - Returns a `Filter` suitable for use with `Schema.filter` or - * attached directly to a `String` AST node via checks. - * - The regex `source` is stored in annotations for serialization and - * arbitrary generation. + * The filter can be used with `Schema.filter` or attached directly to a + * `String` AST node through checks. The regular expression source is stored in + * annotations for serialization and arbitrary generation. + * + * **Gotchas** + * + * Use a non-global, non-sticky regular expression, or reset `lastIndex` + * yourself, because `RegExp.test` is stateful for expressions with the `g` or + * `y` flag. * * **Example** (Validating an email pattern) * @@ -2629,7 +2959,7 @@ export function makeFilterByGuard( * ``` * * @see {@link Filter} - * + * @category constructors * @since 4.0.0 */ export function isPattern(regExp: globalThis.RegExp, annotations?: Schema.Annotations.Filter) { @@ -2642,8 +2972,8 @@ export function isPattern(regExp: globalThis.RegExp, annotations?: Schema.Annota _tag: "isPattern", regExp }, - toArbitraryConstraint: { - string: { + arbitrary: { + constraint: { patterns: [regExp.source] } }, @@ -2701,6 +3031,9 @@ export function annotate(ast: A, annotations: Schema.Annotations. /** @internal */ export function replaceChecks(ast: A, checks: Checks | undefined): A { + if (ast._tag === "Suspend" && checks !== undefined) { + throw new Error("Cannot add checks to Suspend") + } if (ast.checks === checks) { return ast } @@ -2732,7 +3065,7 @@ export function applyToLastLink(f: (ast: AST) => AST) { /** @internal */ export function middlewareDecoding( ast: AST, - middleware: Transformation.Middleware + middleware: SchemaTransformation.Middleware ): AST { return appendTransformation(ast, middleware, toType(ast)) } @@ -2740,7 +3073,7 @@ export function middlewareDecoding( /** @internal */ export function middlewareEncoding( ast: AST, - middleware: Transformation.Middleware + middleware: SchemaTransformation.Middleware ): AST { return appendTransformation(toEncoded(ast), middleware, ast) } @@ -2748,8 +3081,8 @@ export function middlewareEncoding( function appendTransformation( from: AST, transformation: - | Transformation.Transformation - | Transformation.Middleware, + | SchemaTransformation.Transformation + | SchemaTransformation.Middleware, to: A ): A { const link = new Link(from, transformation) @@ -2803,12 +3136,14 @@ export const optionalKeyLastLink = applyToLastLink(optionalKey) * Marks an AST node's property key as optional by setting * {@link Context.isOptional} to `true`. * + * **Details** + * * Also propagates the optional flag through the last link of the encoding * chain if present. * * @see {@link isOptional} * @see {@link Context} - * + * @category transforming * @since 4.0.0 */ export function optionalKey(ast: A): A { @@ -2835,11 +3170,11 @@ export function mutableKey(ast: A): A { /** @internal */ export function withConstructorDefault( ast: A, - defaultValue: Effect.Effect + defaultValue: Effect.Effect ): A { - const transformation = new Transformation.Transformation( - Getter.withDefault(defaultValue), - Getter.passthrough() + const transformation = new SchemaTransformation.Transformation( + SchemaGetter.withDefault(defaultValue), + SchemaGetter.passthrough() ) const encoding: Encoding = [new Link(unknown, transformation)] const context = ast.context ? @@ -2852,23 +3187,24 @@ export function withConstructorDefault( * Attaches a `Transformation` to the `to` AST, making it decode from the * `from` AST and encode back to it. * + * **Details** + * * This is the low-level primitive behind `Schema.transform` and * `Schema.transformOrFail`. It appends a {@link Link} to the `to` node's * encoding chain. * - * - Does not mutate either input. * - Returns a new AST with the same type as `to`. * * @see {@link Link} * @see {@link Encoding} * @see {@link flip} - * + * @category transforming * @since 4.0.0 */ export function decodeTo( from: AST, to: A, - transformation: Transformation.Transformation + transformation: SchemaTransformation.Transformation ): A { return appendTransformation(from, transformation, to) } @@ -2928,12 +3264,14 @@ export function record(key: AST, value: AST, keyValueCombiner: KeyValueCombiner /** * Returns `true` if the AST node represents an optional property. * + * **Details** + * * Checks `ast.context?.isOptional`. Defaults to `false` when no * {@link Context} is set. * * @see {@link optionalKey} * @see {@link Context} - * + * @category predicates * @since 4.0.0 */ export function isOptional(ast: AST): boolean { @@ -2949,10 +3287,11 @@ export function isMutable(ast: AST): boolean { * Strips all encoding transformations from an AST, returning the decoded * (type-level) representation. * + * **Details** + * * - Memoized: same input reference → same output reference. * - Recursively walks into composite nodes ({@link Arrays}, {@link Objects}, * {@link Union}, {@link Suspend}). - * - Does not mutate the input. * * **Example** (Getting the type AST) * @@ -2966,7 +3305,7 @@ export function isMutable(ast: AST): boolean { * * @see {@link toEncoded} * @see {@link flip} - * + * @category transforming * @since 4.0.0 */ export const toType = memoize((ast: A): A => { @@ -2974,18 +3313,25 @@ export const toType = memoize((ast: A): A => { return toType(replaceEncoding(ast, undefined)) } const out: any = ast - return out.recur?.(toType) ?? out + const type = out.recur?.(toType) ?? out + if (getEncodingChecks(type)) { + return modifyOwnPropertyDescriptors(type, (d) => { + d.encodingChecks.value = undefined + }) + } + return type }) /** * Returns the encoded (wire-format) AST by flipping and then stripping * encodings. * + * **Details** + * * Equivalent to `toType(flip(ast))`. This gives you the AST that describes * the shape of the serialized/encoded data. * * - Memoized: same input reference → same output reference. - * - Does not mutate the input. * * **Example** (Getting the encoded AST) * @@ -2999,7 +3345,7 @@ export const toType = memoize((ast: A): A => { * * @see {@link toType} * @see {@link flip} - * + * @category transforming * @since 4.0.0 */ export const toEncoded = memoize((ast: AST): AST => { @@ -3027,17 +3373,18 @@ function flipEncoding(ast: AST, encoding: Encoding): AST { /** * Swaps the decode and encode directions of an AST's {@link Encoding} chain. * + * **Details** + * * After flipping, what was decoding becomes encoding and vice versa. This is * the core operation behind `Schema.encode` — encoding a value is decoding - * with a flipped AST. + * with a flipped SchemaAST. * * - Memoized: same input reference → same output reference. * - Recursively walks composite nodes. - * - Does not mutate the input. * * @see {@link toType} * @see {@link toEncoded} - * + * @category transforming * @since 4.0.0 */ export const flip = memoize((ast: AST): AST => { @@ -3102,7 +3449,7 @@ function handleTemplateLiteralASTPartParens(part: TemplateLiteralPart, s: string function fromConst( ast: AST, value: T -): Parser.Parser { +): SchemaParser.Parser { const succeed = Effect.succeedSome(value) return (oinput) => { if (oinput._tag === "None") { @@ -3110,21 +3457,21 @@ function fromConst( } return oinput.value === value ? succeed - : Effect.fail(new Issue.InvalidType(ast, oinput)) + : Effect.fail(new SchemaIssue.InvalidType(ast, oinput)) } } function fromRefinement( ast: AST, refinement: (input: unknown) => input is T -): Parser.Parser { +): SchemaParser.Parser { return (oinput) => { if (oinput._tag === "None") { return Effect.succeedNone } return refinement(oinput.value) ? Effect.succeed(oinput) - : Effect.fail(new Issue.InvalidType(ast, oinput)) + : Effect.fail(new SchemaIssue.InvalidType(ast, oinput)) } } @@ -3198,12 +3545,12 @@ const finiteString = appendChecks(string, [isStringFinite()]) const finiteToString = new Link( finiteString, - Transformation.numberFromString + SchemaTransformation.numberFromString ) const numberToString = new Link( new Union([finiteString, nonFiniteLiterals], "anyOf"), - Transformation.numberFromString + SchemaTransformation.numberFromString ) /** @@ -3235,7 +3582,7 @@ export const bigIntString = appendChecks(string, [isStringBigInt({ const bigIntToString = new Link( bigIntString, - Transformation.bigintFromString + SchemaTransformation.bigintFromString ) const REGEXP_PATTERN = "Symbol\\((.*)\\)" @@ -3250,15 +3597,15 @@ export const symbolString = appendChecks(string, [isStringSymbol()]) */ const symbolToString = new Link( symbolString, - new Transformation.Transformation( - Getter.transform((description) => globalThis.Symbol.for(isStringSymbolRegExp.exec(description)![1])), - Getter.transformOrFail((sym: symbol) => { + new SchemaTransformation.Transformation( + SchemaGetter.transform((description) => globalThis.Symbol.for(isStringSymbolRegExp.exec(description)![1])), + SchemaGetter.transformOrFail((sym: symbol) => { const key = globalThis.Symbol.keyFor(sym) if (key !== undefined) { return Effect.succeed(globalThis.String(sym)) } return Effect.fail( - new Issue.Forbidden(Option.some(sym), { message: "cannot serialize to string, Symbol is not registered" }) + new SchemaIssue.Forbidden(Option.some(sym), { message: "cannot serialize to string, Symbol is not registered" }) ) }) ) @@ -3283,7 +3630,7 @@ export function isStringSymbol(annotations?: Schema.Annotations.Filter) { export function collectIssues( checks: ReadonlyArray>, value: T, - issues: Array, + issues: Array, ast: AST, options: ParseOptions ) { @@ -3294,7 +3641,7 @@ export function collectIssues( } else { const issue = check.run(value, ast, options) if (issue) { - issues.push(new Issue.Filter(value, check, issue)) + issues.push(new SchemaIssue.Filter(value, check, issue)) if (check.aborted || options?.errors !== "all") { return } @@ -3307,11 +3654,11 @@ export function collectIssues( export function runChecks( checks: readonly [Check, ...Array>], s: T -): Result.Result { - const issues: Array = [] +): Result.Result { + const issues: Array = [] collectIssues(checks, s, issues, unknown, { errors: "all" }) if (Arr.isArrayNonEmpty(issues)) { - const issue = new Issue.Composite(unknown, Option.some(s), issues) + const issue = new SchemaIssue.Composite(unknown, Option.some(s), issues) return Result.fail(issue) } return Result.succeed(s) @@ -3326,6 +3673,8 @@ export const STRUCTURAL_ANNOTATION_KEY = "~structural" /** * Returns all annotations from the AST node. * + * **Details** + * * If the node has {@link Checks}, returns annotations from the last check * (which is where user-supplied annotations end up after `.pipe(Schema.annotations(...))`). * Otherwise returns `Base.annotations` directly. @@ -3344,7 +3693,7 @@ export const STRUCTURAL_ANNOTATION_KEY = "~structural" * @see {@link resolveIdentifier} * @see {@link resolveTitle} * @see {@link resolveDescription} - * + * @category annotations * @since 4.0.0 */ export const resolve: (ast: AST) => Schema.Annotations.Annotations | undefined = InternalAnnotations.resolve @@ -3352,11 +3701,13 @@ export const resolve: (ast: AST) => Schema.Annotations.Annotations | undefined = /** * Returns a single annotation value by key from the AST node. * + * **Details** + * * Like {@link resolve}, reads from the last check's annotations when checks * are present. Returns `undefined` if the key is not found. * * @see {@link resolve} - * + * @category annotations * @since 4.0.0 */ export const resolveAt: (key: string) => (ast: AST) => A | undefined = InternalAnnotations.resolveAt @@ -3364,12 +3715,14 @@ export const resolveAt: (key: string) => (ast: AST) => A | undefined = Intern /** * Returns the `identifier` annotation from the AST node, if set. * + * **Details** + * * The identifier is typically set by `Schema.annotations({ identifier: "..." })` * and is used for error messages and schema identification. * * @see {@link resolve} * @see {@link resolveTitle} - * + * @category annotations * @since 4.0.0 */ export const resolveIdentifier: (ast: AST) => string | undefined = InternalAnnotations.resolveIdentifier @@ -3381,6 +3734,7 @@ export const resolveIdentifier: (ast: AST) => string | undefined = InternalAnnot * @see {@link resolveIdentifier} * @see {@link resolveDescription} * + * @category annotations * @since 4.0.0 */ export const resolveTitle: (ast: AST) => string | undefined = InternalAnnotations.resolveTitle @@ -3392,6 +3746,7 @@ export const resolveTitle: (ast: AST) => string | undefined = InternalAnnotation * @see {@link resolveTitle} * @see {@link resolveIdentifier} * + * @category annotations * @since 4.0.0 */ export const resolveDescription: (ast: AST) => string | undefined = InternalAnnotations.resolveDescription @@ -3450,7 +3805,7 @@ export const Json = new Declaration( () => (input, ast) => isJson(input) ? Effect.succeed(input) : - Effect.fail(new Issue.InvalidType(ast, Option.some(input))), + Effect.fail(new SchemaIssue.InvalidType(ast, Option.some(input))), { typeConstructor: { _tag: "effect/Json" @@ -3460,7 +3815,8 @@ export const Json = new Declaration( Type: `Schema.Json` }, expected: "JSON value", - toCodecJson: () => new Link(unknown, Transformation.passthrough()) + toCodecJson: () => new Link(unknown, SchemaTransformation.passthrough()), + toArbitrary: () => (fc: typeof FastCheck) => fc.jsonValue() } ) @@ -3478,16 +3834,16 @@ export const MutableJson = annotate(Json, { /** @internal */ export const unknownToNull = new Link( null_, - new Transformation.Transformation( - Getter.passthrough(), - Getter.transform(() => null) + new SchemaTransformation.Transformation( + SchemaGetter.passthrough(), + SchemaGetter.transform(() => null) ) ) /** @internal */ export const unknownToJson = new Link( Json, - Transformation.passthrough() + SchemaTransformation.passthrough() ) /** @@ -3524,15 +3880,15 @@ const StringTree = new Declaration( () => (input, ast) => isStringTree(input) ? Effect.succeed(input) : - Effect.fail(new Issue.InvalidType(ast, Option.some(input))), + Effect.fail(new SchemaIssue.InvalidType(ast, Option.some(input))), { expected: "StringTree", - toCodecStringTree: () => new Link(unknown, Transformation.passthrough()) + toCodecStringTree: () => new Link(unknown, SchemaTransformation.passthrough()) } ) /** @internal */ export const unknownToStringTree = new Link( StringTree, - Transformation.passthrough() + SchemaTransformation.passthrough() ) diff --git a/.opencode/node_modules/effect/src/SchemaGetter.ts b/.opencode/node_modules/effect/src/SchemaGetter.ts index 255089a10d759f12d3cf93688a8fce49e1aa30b4..6dcbaa5131ca7dcd01e5e11328c2e3fef7ca7144 100644 --- a/.opencode/node_modules/effect/src/SchemaGetter.ts +++ b/.opencode/node_modules/effect/src/SchemaGetter.ts @@ -1,87 +1,13 @@ /** - * Composable transformation primitives for the Effect Schema system. - * - * A `Getter` represents a single-direction transformation from an - * encoded type `E` to a decoded type `T`. Getters are the building blocks - * that `Schema.decodeTo` and `Schema.decode` use to define how values are - * transformed during encoding and decoding. They handle optionality - * (`Option` in, `Option` out), can fail with `Issue`, and can require - * Effect services via `R`. - * - * ## Mental model - * - * - **Getter**: A function `Option -> Effect, Issue, R>`. It - * transforms an optional encoded value into an optional decoded value, - * possibly failing or requiring services. - * - **Passthrough**: The identity getter — returns the input unchanged. Used - * when no transformation is needed. Optimized away during composition. - * - **Option-awareness**: Getters receive and return `Option` to handle - * missing keys in structs. `Option.None` means the key is absent. - * - **Composition**: Getters compose left-to-right via `.compose()`. A - * passthrough on either side is a no-op (identity optimization). - * - **Issue**: The error type for all getter failures (see `SchemaIssue`). - * - * ## Common tasks - * - * - Pass a value through unchanged → {@link passthrough} - * - Transform a value purely → {@link transform} - * - Transform a value with possible failure → {@link transformOrFail} - * - Transform with full Option control → {@link transformOptional} - * - Handle missing keys → {@link onNone}, {@link required}, {@link withDefault} - * - Handle present values → {@link onSome} - * - Validate a value with an effectful check → {@link checkEffect} - * - Produce a constant value → {@link succeed} - * - Always fail → {@link fail}, {@link forbidden} - * - Omit a value from output → {@link omit} - * - Coerce to a primitive type → {@link String}, {@link Number}, {@link Boolean}, {@link BigInt}, {@link Date} - * - Transform strings → {@link trim}, {@link capitalize}, {@link toLowerCase}, {@link toUpperCase}, {@link split}, {@link splitKeyValue}, {@link joinKeyValue} - * - Parse/stringify JSON → {@link parseJson}, {@link stringifyJson} - * - Encode/decode Base64 → {@link encodeBase64}, {@link decodeBase64}, {@link decodeBase64String} - * - Encode/decode Hex → {@link encodeHex}, {@link decodeHex}, {@link decodeHexString} - * - Encode/decode URI components → {@link encodeUriComponent}, {@link decodeUriComponent} - * - Parse DateTime → {@link dateTimeUtcFromInput} - * - Decode/encode FormData → {@link decodeFormData}, {@link encodeFormData} - * - Decode/encode URLSearchParams → {@link decodeURLSearchParams}, {@link encodeURLSearchParams} - * - Build nested tree from bracket paths → {@link makeTreeRecord} - * - Flatten nested tree to bracket paths → {@link collectBracketPathEntries} - * - * ## Gotchas - * - * - Getters are not bidirectional. To define a full encode/decode pair, supply - * both a `decode` and an `encode` getter to `Schema.decodeTo`. - * - `passthrough` requires `T === E` by default. Use `{ strict: false }` to - * bypass the type constraint, or use {@link passthroughSupertype} / {@link passthroughSubtype}. - * - `transform` skips `None` inputs (missing keys) — the function is only - * called when a value is present. Use `transformOptional` if you need to - * handle missing values. - * - `parseJson` without a `reviver` returns `Schema.MutableJson`. With a - * reviver, the return type widens to `unknown`. - * - `split` treats an empty string as an empty array, not `[""]`. - * - * ## Quickstart - * - * **Example** (Using SchemaGetter with Schema.decodeTo) + * Builds one-way conversions used by schemas. * - * ```ts - * import { Schema, SchemaGetter } from "effect" - * - * const NumberFromString = Schema.String.pipe( - * Schema.decodeTo(Schema.Number, { - * decode: SchemaGetter.transform((s) => Number(s)), - * encode: SchemaGetter.transform((n) => String(n)) - * }) - * ) - * - * const result = Schema.decodeUnknownSync(NumberFromString)("42") - * // result: 42 - * ``` - * - * ## See also - * - * - {@link Getter} — the core class - * - {@link transform} — most common constructor - * - {@link passthrough} — identity getter - * - {@link transformOrFail} — fallible transformation + * A `Getter` receives an optional encoded value and returns an + * optional decoded value. It can also report a schema issue or require Effect + * services. Schema transformations use getters to describe one direction of a + * conversion, for example decoding a field from input data. This module + * includes basic getters, validation helpers, pure and effectful conversions, + * and ready-made conversions for common string, number, binary, date, form, and + * URL-related values. * * @since 4.0.0 */ @@ -93,28 +19,28 @@ import * as Pipeable from "./Pipeable.ts" import * as Predicate from "./Predicate.ts" import * as Result from "./Result.ts" import type * as Schema from "./Schema.ts" -import type * as AST from "./SchemaAST.ts" -import * as Issue from "./SchemaIssue.ts" +import type * as SchemaAST from "./SchemaAST.ts" +import * as SchemaIssue from "./SchemaIssue.ts" import * as Str from "./String.ts" /** - * A composable transformation from an encoded type `E` to a decoded type `T`. + * Represents a composable transformation from an encoded type `E` to a decoded type `T`. + * + * **When to use** * - * A Getter wraps a function `Option -> Effect, Issue, R>`: - * - Receives `Option.None` when the encoded key is absent (e.g. missing struct field). - * - Returns `Option.None` to omit the value from the decoded output. - * - Fails with `Issue` on invalid input. - * - May require Effect services via `R`. + * Use when you need a schema getter to build and compose custom transformations + * for `Schema.decodeTo` or `Schema.decode`. * - * Use this when: - * - Building custom schema transformations with `Schema.decodeTo` or `Schema.decode`. - * - Composing multiple transformation steps into a single getter. + * **Details** * - * Behavior: - * - Immutable — constructing or composing getters does not mutate existing instances. - * - `.map(f)` applies `f` to the decoded value (inside the `Some`), leaving `None` unchanged. - * - `.compose(other)` chains two getters: the output of `this` feeds into `other`. - * Passthrough getters on either side are optimized away. + * A getter wraps a function `Option -> Effect, Issue, R>`. It + * receives `Option.None` when the encoded key is absent, such as a missing + * struct field, and returns `Option.None` to omit the value from the decoded + * output. It fails with `Issue` on invalid input and may require Effect + * services via `R`. `.map(f)` applies `f` to the decoded value inside `Some` + * while leaving `None` unchanged. `.compose(other)` chains two getters by + * feeding the output of `this` into `other`; passthrough getters on either side + * are optimized away. * * **Example** (Creating and composing getters) * @@ -127,25 +53,24 @@ import * as Str from "./String.ts" * // composed: Getter — parses then doubles * ``` * - * See also: - * - {@link transform} — create a getter from a pure function - * - {@link passthrough} — identity getter - * - {@link transformOrFail} — fallible transformation + * @see {@link transform} to create a getter from a pure function + * @see {@link passthrough} for the identity getter + * @see {@link transformOrFail} for fallible transformation * - * @category model + * @category models * @since 4.0.0 */ export class Getter extends Pipeable.Class { readonly run: ( input: Option.Option, - options: AST.ParseOptions - ) => Effect.Effect, Issue.Issue, R> + options: SchemaAST.ParseOptions + ) => Effect.Effect, SchemaIssue.Issue, R> constructor( run: ( input: Option.Option, - options: AST.ParseOptions - ) => Effect.Effect, Issue.Issue, R> + options: SchemaAST.ParseOptions + ) => Effect.Effect, SchemaIssue.Issue, R> ) { super() this.run = run @@ -167,13 +92,15 @@ export class Getter extends Pipeable.Class { /** * Creates a getter that always produces the given constant value, ignoring the input. * - * Use this when: - * - A schema field should always decode to a fixed value. - * - You need a placeholder getter that produces a known default. + * **When to use** + * + * Use when you need a schema getter that always decodes a field to a fixed + * value. * - * Behavior: - * - Pure, no side effects. - * - Always returns `Option.some(t)` regardless of whether input is `Some` or `None`. + * **Details** + * + * The getter is pure and always returns `Option.some(t)` regardless of whether + * the input is `Some` or `None`. * * **Example** (Constant getter) * @@ -184,11 +111,10 @@ export class Getter extends Pipeable.Class { * // alwaysZero: Getter<0, unknown> — always produces 0 * ``` * - * See also: - * - {@link transform} — when you need to use the input value - * - {@link passthrough} — when you want to keep the input as-is + * @see {@link transform} when you need to use the input value + * @see {@link passthrough} when you want to keep the input as-is * - * @category Constructors + * @category constructors * @since 4.0.0 */ export function succeed(t: T): Getter { @@ -198,44 +124,48 @@ export function succeed(t: T): Getter { /** * Creates a getter that always fails with the given issue. * - * Use this when: - * - A transformation should unconditionally reject input. + * **When to use** + * + * Use when you need a schema getter that unconditionally rejects input. * - Building custom validation getters that produce specific error types. * - * Behavior: + * **Details** + * * - Always fails with the `Issue` returned by `f`. * - The failure function receives the original `Option` input for error context. * * **Example** (Always-failing getter) * * ```ts - * import { SchemaGetter, SchemaIssue, Option } from "effect" + * import { Option, SchemaGetter, SchemaIssue } from "effect" * * const rejectAll = SchemaGetter.fail( * (oe) => new SchemaIssue.InvalidValue(oe, { message: "not allowed" }) * ) * ``` * - * See also: - * - {@link forbidden} — convenience for `Forbidden` issues - * - {@link checkEffect} — fail conditionally based on input value + * @see {@link forbidden} for a convenience helper for `Forbidden` issues + * @see {@link checkEffect} to fail conditionally based on input value * - * @category Constructors + * @category constructors * @since 4.0.0 */ -export function fail(f: (oe: Option.Option) => Issue.Issue): Getter { +export function fail(f: (oe: Option.Option) => SchemaIssue.Issue): Getter { return new Getter((oe) => Effect.fail(f(oe))) } /** * Creates a getter that always fails with a `Forbidden` issue. * - * Use this when: - * - A field or direction (encode/decode) should be disallowed entirely. + * **When to use** + * + * Use when you need a schema getter to disallow a field or direction + * (encode/decode) entirely. * - You want a clear "forbidden" error message in schema validation output. * - * Behavior: - * - Always fails with `Issue.Forbidden`. + * **Details** + * + * - Always fails with `SchemaIssue.Forbidden`. * - The message function receives the `Option` input for context. * * **Example** (Forbidding a decode direction) @@ -248,14 +178,13 @@ export function fail(f: (oe: Option.Option) => Issue.Issue): Getter(message: (oe: Option.Option) => string): Getter { - return fail((oe) => new Issue.Forbidden(oe, { message: message(oe) })) + return fail((oe) => new SchemaIssue.Forbidden(oe, { message: message(oe) })) } const passthrough_ = new Getter(Effect.succeed) @@ -267,11 +196,13 @@ function isPassthrough(getter: Getter): getter is typeof passt /** * Returns the identity getter — passes the value through unchanged. * - * Use this when: - * - No transformation is needed between encoded and decoded types. - * - One side of a `decodeTo` pair (encode or decode) should be a no-op. + * **When to use** + * + * Use when you need a schema getter for one side of a `decodeTo` pair, either + * encode or decode, to pass values through unchanged. + * + * **Details** * - * Behavior: * - Pure, no allocation (singleton instance). * - Optimized away during `.compose()` — composing with a passthrough is free. * - The default overload requires `T === E`. Pass `{ strict: false }` to opt @@ -291,12 +222,11 @@ function isPassthrough(getter: Getter): getter is typeof passt * ) * ``` * - * See also: - * - {@link passthroughSupertype} — when `T extends E` - * - {@link passthroughSubtype} — when `E extends T` - * - {@link transform} — when you need to change the value + * @see {@link passthroughSupertype} when `T extends E` + * @see {@link passthroughSubtype} when `E extends T` + * @see {@link transform} when you need to change the value * - * @category Constructors + * @category constructors * @since 4.0.0 */ export function passthrough(options: { readonly strict: false }): Getter @@ -306,13 +236,15 @@ export function passthrough(): Getter { } /** - * Returns the identity getter, typed for when the decoded type `T` is a supertype of `E`. + * Returns the identity getter typed for the relationship `T extends E`. + * + * **When to use** + * + * Use when you need a schema getter that passes values through when the + * decoded/output type is narrower than the encoded/input type. * - * Use this when: - * - The decoded type is wider than the encoded type (e.g. `string` from a string literal). - * - You need type-safe passthrough without `{ strict: false }`. + * **Details** * - * Behavior: * - Same singleton as {@link passthrough} — no allocation, optimized in composition. * * **Example** (Supertype passthrough) @@ -324,11 +256,10 @@ export function passthrough(): Getter { * const g = SchemaGetter.passthroughSupertype() * ``` * - * See also: - * - {@link passthrough} — when types are identical - * - {@link passthroughSubtype} — when `E extends T` + * @see {@link passthrough} when types are identical + * @see {@link passthroughSubtype} when `E extends T` * - * @category Constructors + * @category constructors * @since 4.0.0 */ export function passthroughSupertype(): Getter @@ -339,11 +270,13 @@ export function passthroughSupertype(): Getter { /** * Returns the identity getter, typed for when the encoded type `E` is a subtype of `T`. * - * Use this when: - * - The encoded type is narrower than the decoded type. - * - You need type-safe passthrough without `{ strict: false }`. + * **When to use** + * + * Use when you need a schema getter that passes values through without + * `{ strict: false }` for an encoded type that narrows the decoded type. + * + * **Details** * - * Behavior: * - Same singleton as {@link passthrough} — no allocation, optimized in composition. * * **Example** (Subtype passthrough) @@ -355,11 +288,10 @@ export function passthroughSupertype(): Getter { * const g = SchemaGetter.passthroughSubtype() * ``` * - * See also: - * - {@link passthrough} — when types are identical - * - {@link passthroughSupertype} — when `T extends E` + * @see {@link passthrough} when types are identical + * @see {@link passthroughSupertype} when `T extends E` * - * @category Constructors + * @category constructors * @since 4.0.0 */ export function passthroughSubtype(): Getter @@ -370,11 +302,14 @@ export function passthroughSubtype(): Getter { /** * Creates a getter that handles the case when the input is absent (`Option.None`). * - * Use this when: - * - You need to provide a fallback or computed value for missing struct keys. + * **When to use** + * + * Use when you need a schema getter to provide a fallback or computed value for + * missing struct keys. * - Building custom "default value" logic more complex than {@link withDefault}. * - * Behavior: + * **Details** + * * - When input is `None`, calls `f` to produce the result. * - When input is `Some`, passes it through unchanged. * - `f` receives the parse options and may return `None` to keep the value absent. @@ -382,23 +317,22 @@ export function passthroughSubtype(): Getter { * **Example** (Default timestamp for missing field) * * ```ts - * import { SchemaGetter, Effect, Option } from "effect" + * import { Effect, Option, SchemaGetter } from "effect" * * const withTimestamp = SchemaGetter.onNone(() => * Effect.succeed(Option.some(Date.now())) * ) * ``` * - * See also: - * - {@link required} — fails if input is absent - * - {@link withDefault} — simpler default value for undefined inputs - * - {@link onSome} — handle only present values + * @see {@link required} when absent input should fail + * @see {@link withDefault} for a simpler default value for undefined inputs + * @see {@link onSome} to handle only present values * - * @category Constructors + * @category constructors * @since 4.0.0 */ export function onNone( - f: (options: AST.ParseOptions) => Effect.Effect, Issue.Issue, R> + f: (options: SchemaAST.ParseOptions) => Effect.Effect, SchemaIssue.Issue, R> ): Getter { return new Getter((ot, options) => Option.isNone(ot) ? f(options) : Effect.succeed(ot)) } @@ -406,12 +340,14 @@ export function onNone( /** * Creates a getter that fails with `MissingKey` if the input is absent (`Option.None`). * - * Use this when: - * - A struct field must be present in the encoded input. - * - You want schema validation to report a missing key error. + * **When to use** + * + * Use when you need a schema getter to require a struct field in the encoded + * input and report a missing key error when it is absent. + * + * **Details** * - * Behavior: - * - When input is `None`, fails with `Issue.MissingKey`. + * - When input is `None`, fails with `SchemaIssue.MissingKey`. * - When input is `Some`, passes it through unchanged. * - Optional `annotations` customize the error message for the missing key. * @@ -423,25 +359,27 @@ export function onNone( * const mustExist = SchemaGetter.required() * ``` * - * See also: - * - {@link onNone} — provide a fallback instead of failing - * - {@link withDefault} — substitute a default for undefined values + * @see {@link onNone} to provide a fallback instead of failing + * @see {@link withDefault} to substitute a default for undefined values * - * @category Constructors + * @category constructors * @since 4.0.0 */ export function required(annotations?: Schema.Annotations.Key): Getter { - return onNone(() => Effect.fail(new Issue.MissingKey(annotations))) + return onNone(() => Effect.fail(new SchemaIssue.MissingKey(annotations))) } /** * Creates a getter that handles present values (`Option.Some`), passing `None` through. * - * Use this when: - * - You need to transform or validate only when a value is present. + * **When to use** + * + * Use when you need a schema getter to transform or validate only when a field + * value is present. * - Missing keys should remain absent in the output. * - * Behavior: + * **Details** + * * - When input is `None`, returns `None` (no-op). * - When input is `Some(e)`, calls `f(e, options)` to produce the result. * - `f` may return `None` to omit the value, or fail with an `Issue`. @@ -449,23 +387,22 @@ export function required(annotations?: Schema.Annotations.Ke * **Example** (Transform only present values) * * ```ts - * import { SchemaGetter, Effect, Option } from "effect" + * import { Effect, Option, SchemaGetter } from "effect" * * const parseIfPresent = SchemaGetter.onSome( * (s) => Effect.succeed(Option.some(Number(s))) * ) * ``` * - * See also: - * - {@link onNone} — handle only absent values - * - {@link transform} — simpler pure transformation of present values - * - {@link transformOrFail} — fallible transformation of present values + * @see {@link onNone} to handle only absent values + * @see {@link transform} for a simpler pure transformation of present values + * @see {@link transformOrFail} for fallible transformation of present values * - * @category Constructors + * @category constructors * @since 4.0.0 */ export function onSome( - f: (e: E, options: AST.ParseOptions) => Effect.Effect, Issue.Issue, R> + f: (e: E, options: SchemaAST.ParseOptions) => Effect.Effect, SchemaIssue.Issue, R> ): Getter { return new Getter((oe, options) => Option.isNone(oe) ? Effect.succeedNone : f(oe.value, options)) } @@ -473,39 +410,41 @@ export function onSome( /** * Creates a getter that validates a value using an effectful check function. * - * Use this when: - * - You need to validate a decoded value (e.g. check a constraint or call an external service). + * **When to use** + * + * Use when you need a schema getter to validate a decoded value (e.g. check a + * constraint or call an external service). * - The validation may be asynchronous or require Effect services. * - * Behavior: + * **Details** + * * - Only runs when input is `Some` — `None` passes through. * - The check function returns a validation result: * - `undefined` or `true` — value is valid, passes through. * - `false` or a `string` — value is invalid, fails with an `Issue`. * - An `Issue` object — fails with that issue directly. * - `{ path, issue }` — fails with a nested path issue (`issue` may be a - * message string or a full {@link Issue.Issue}). + * message string or a full {@link SchemaIssue.Issue}). * - Does not transform the value — input and output types are the same. * * **Example** (Effectful validation) * * ```ts - * import { SchemaGetter, Effect } from "effect" + * import { Effect, SchemaGetter } from "effect" * * const nonNegative = SchemaGetter.checkEffect((n) => * Effect.succeed(n >= 0 ? undefined : "must be non-negative") * ) * ``` * - * See also: - * - {@link transform} — when you need to change the value, not just validate - * - {@link fail} — unconditional failure + * @see {@link transform} when you need to change the value, not just validate + * @see {@link fail} for unconditional failure * - * @category Constructors + * @category constructors * @since 4.0.0 */ export function checkEffect( - f: (input: T, options: AST.ParseOptions) => Effect.Effect< + f: (input: T, options: SchemaAST.ParseOptions) => Effect.Effect< undefined | boolean | Schema.FilterIssue, never, R @@ -513,7 +452,7 @@ export function checkEffect( ): Getter { return onSome((t, options) => { return f(t, options).pipe(Effect.flatMapEager((out) => { - const issue = Issue.makeSingle(t, out) + const issue = SchemaIssue.makeSingle(t, out) return issue ? Effect.fail(issue) : Effect.succeed(Option.some(t)) @@ -524,15 +463,16 @@ export function checkEffect( /** * Creates a getter that applies a pure function to present values. * - * This is the most commonly used constructor. It transforms `Some(e)` to - * `Some(f(e))` and leaves `None` unchanged. + * **When to use** * - * Use this when: - * - You have a pure, infallible transformation between types. + * Use when you need a schema getter for a pure, infallible transformation + * between types. * - Building encode/decode pairs for `Schema.decodeTo`. * - * Behavior: - * - Pure, does not mutate input. + * **Details** + * + * - This is the most commonly used constructor. + * - Transforms `Some(e)` to `Some(f(e))` and leaves `None` unchanged. * - Skips `None` inputs — only called when a value is present. * - Never fails. * @@ -549,12 +489,11 @@ export function checkEffect( * ) * ``` * - * See also: - * - {@link transformOrFail} — when the transformation can fail - * - {@link transformOptional} — when you need to handle `None` inputs - * - {@link passthrough} — when no transformation is needed + * @see {@link transformOrFail} when the transformation can fail + * @see {@link transformOptional} when you need to handle `None` inputs + * @see {@link passthrough} when no transformation is needed * - * @category Constructors + * @category constructors * @since 4.0.0 */ export function transform(f: (e: E) => T): Getter { @@ -564,11 +503,13 @@ export function transform(f: (e: E) => T): Getter { /** * Creates a getter that applies a fallible, effectful transformation to present values. * - * Use this when: - * - The transformation may fail (e.g. parsing, validation). - * - The transformation needs Effect services or is async. + * **When to use** + * + * Use when you need a schema getter for a transformation that may fail, require + * Effect services, or run asynchronously. + * + * **Details** * - * Behavior: * - Skips `None` inputs — only called when a value is present. * - On success, wraps the result in `Some`. * - On failure, propagates the `Issue`. @@ -576,7 +517,7 @@ export function transform(f: (e: E) => T): Getter { * **Example** (Parsing with failure) * * ```ts - * import { SchemaGetter, SchemaIssue, Effect, Option } from "effect" + * import { Effect, Option, SchemaGetter, SchemaIssue } from "effect" * * const safeParseInt = SchemaGetter.transformOrFail( * (s) => { @@ -588,15 +529,14 @@ export function transform(f: (e: E) => T): Getter { * ) * ``` * - * See also: - * - {@link transform} — when transformation cannot fail - * - {@link onSome} — when you need full `Option` control over the output + * @see {@link transform} when transformation cannot fail + * @see {@link onSome} when you need full `Option` control over the output * - * @category Constructors + * @category constructors * @since 4.0.0 */ export function transformOrFail( - f: (e: E, options: AST.ParseOptions) => Effect.Effect + f: (e: E, options: SchemaAST.ParseOptions) => Effect.Effect ): Getter { return onSome((e, options) => f(e, options).pipe(Effect.mapEager(Option.some))) } @@ -604,29 +544,30 @@ export function transformOrFail( /** * Creates a getter that transforms the full `Option` — both present and absent values. * - * Use this when: - * - You need to handle both `Some` and `None` cases. - * - You want to turn a present value into absent, or vice versa. + * **When to use** + * + * Use when you need a schema getter to handle both `Some` and `None` cases. * - * Behavior: - * - Pure, never fails. - * - Receives the full `Option` and must return `Option`. + * **Details** + * + * The getter is pure and never fails. It receives the full `Option` and + * must return `Option`, so it can turn a present value into absent or an + * absent value into present. * * **Example** (Filter out empty strings) * * ```ts - * import { SchemaGetter, Option } from "effect" + * import { Option, SchemaGetter } from "effect" * * const skipEmpty = SchemaGetter.transformOptional((o) => * Option.filter(o, (s) => s.length > 0) * ) * ``` * - * See also: - * - {@link transform} — simpler, only handles present values - * - {@link omit} — always returns `None` + * @see {@link transform} when you only need to transform present values + * @see {@link omit} when you always want `None` * - * @category Constructors + * @category constructors * @since 4.0.0 */ export function transformOptional(f: (oe: Option.Option) => Option.Option): Getter { @@ -636,10 +577,13 @@ export function transformOptional(f: (oe: Option.Option) => Option.Opti /** * Creates a getter that always returns `None`, effectively omitting the value from output. * - * Use this when: - * - A field should be excluded during decoding or encoding. + * **When to use** + * + * Use when you need a schema getter to exclude a field during decoding or + * encoding. + * + * **Details** * - * Behavior: * - Always returns `Option.None` regardless of input. * - Never fails. * @@ -651,11 +595,10 @@ export function transformOptional(f: (oe: Option.Option) => Option.Opti * const omitField = SchemaGetter.omit() * ``` * - * See also: - * - {@link transformOptional} — when you want conditional omission - * - {@link forbidden} — when you want to fail instead of silently omit + * @see {@link transformOptional} when you want conditional omission + * @see {@link forbidden} when you want to fail instead of silently omit * - * @category Constructors + * @category constructors * @since 4.0.0 */ export function omit(): Getter { @@ -665,10 +608,13 @@ export function omit(): Getter { /** * Creates a getter that replaces `undefined` values with a default. * - * Use this when: - * - A field may be `undefined` in the encoded input and should have a fallback. + * **When to use** + * + * Use when you need a schema getter to provide a fallback for a field that may + * be `undefined` in the encoded input. + * + * **Details** * - * Behavior: * - If the input is `Some(undefined)` or `None`, produces `Some(T)`. * - If the input is `Some(value)` where value is not `undefined`, passes it through. * - `defaultValue` is an `Effect` that will be executed each time a default is needed. @@ -682,29 +628,32 @@ export function omit(): Getter { * // Getter * ``` * - * See also: - * - {@link onNone} — handle only absent keys (not `undefined` values) - * - {@link required} — fail instead of providing a default + * @see {@link onNone} to handle only absent keys (not `undefined` values) + * @see {@link required} when absent input should fail instead of using a default * - * @category Constructors + * @category constructors * @since 4.0.0 */ -export function withDefault(defaultValue: Effect.Effect): Getter { +export function withDefault( + defaultValue: Effect.Effect +): Getter { return new Getter((o) => { const filtered = Option.filter(o, Predicate.isNotUndefined) - return Option.isSome(filtered) ? Effect.succeed(filtered) : Effect.map(defaultValue, Option.some) + return Option.isSome(filtered) ? Effect.succeed(filtered) : Effect.mapEager(defaultValue, Option.some) }) } /** * Coerces any value to a `string` using the global `String()` constructor. * - * Use this when: - * - You need a string representation of an arbitrary encoded value. + * **When to use** + * + * Use when you need a schema getter to coerce a present encoded value to a + * string with `String()`. * - * Behavior: - * - Pure, never fails. - * - Delegates to `globalThis.String`. + * **Details** + * + * The getter is pure, never fails, and delegates to `globalThis.String`. * * **Example** (Coerce to string) * @@ -715,8 +664,7 @@ export function withDefault(defaultValue: Effect.Effect): Getter * ``` * - * See also: - * - {@link transform} — for custom string conversions + * @see {@link transform} for custom string conversions * * @category Coercions * @since 4.0.0 @@ -728,12 +676,15 @@ export function String(): Getter { /** * Coerces any value to a `number` using the global `Number()` constructor. * - * Use this when: - * - You need numeric coercion of an encoded value. + * **When to use** + * + * Use when you need a schema getter to coerce a present encoded value to a + * number with `Number()`. + * + * **Details** * - * Behavior: - * - Pure, never fails (may produce `NaN` for non-numeric inputs). - * - Delegates to `globalThis.Number`. + * The getter is pure, never fails, and delegates to `globalThis.Number`. It may + * produce `NaN` for non-numeric inputs. * * **Example** (Coerce to number) * @@ -744,8 +695,7 @@ export function String(): Getter { * // Getter * ``` * - * See also: - * - {@link transformOrFail} — for validated number parsing + * @see {@link transformOrFail} for validated number parsing * * @category Coercions * @since 4.0.0 @@ -757,12 +707,14 @@ export function Number(): Getter { /** * Coerces any value to a `boolean` using the global `Boolean()` constructor. * - * Use this when: - * - You need boolean coercion (truthiness check) of an encoded value. + * **When to use** * - * Behavior: - * - Pure, never fails. - * - Delegates to `globalThis.Boolean`. + * Use when you need a schema getter to coerce a present encoded value to a + * boolean with `Boolean()`. + * + * **Details** + * + * The getter is pure, never fails, and delegates to `globalThis.Boolean`. * * **Example** (Coerce to boolean) * @@ -783,10 +735,13 @@ export function Boolean(): Getter { /** * Coerces a value to `bigint` using the global `BigInt()` constructor. * - * Use this when: - * - You need to convert strings, numbers, or booleans to `bigint`. + * **When to use** + * + * Use when you need a schema getter to convert a present string, number, or + * boolean value to `bigint`. + * + * **Details** * - * Behavior: * - Delegates to `globalThis.BigInt`. * - Throws at runtime if the input cannot be converted (e.g. non-numeric string). * @@ -809,10 +764,13 @@ export function BigInt(): Getter(): Getter * ``` * - * See also: - * - {@link dateTimeUtcFromInput} — validated DateTime parsing + * @see {@link dateTimeUtcFromInput} for validated DateTime parsing * * @category Coercions * @since 4.0.0 @@ -836,9 +793,10 @@ export function Date(): Getter { } /** - * Trims whitespace from both ends of a string. + * Strips whitespace from both ends of a string. + * + * **Details** * - * Behavior: * - Pure, delegates to `String.trim`. * * **Example** (Trim whitespace) @@ -859,7 +817,8 @@ export function trim(): Getter { /** * Capitalizes the first character of a string. * - * Behavior: + * **Details** + * * - Pure, delegates to `String.capitalize`. * * **Example** (Capitalize string) @@ -878,9 +837,10 @@ export function capitalize(): Getter { } /** - * Lowercases the first character of a string. + * Uncapitalizes the first character of a string. + * + * **Details** * - * Behavior: * - Pure, delegates to `String.uncapitalize`. * * **Example** (Uncapitalize string) @@ -901,7 +861,8 @@ export function uncapitalize(): Getter { /** * Converts a `snake_case` string to `camelCase`. * - * Behavior: + * **Details** + * * - Pure, delegates to `String.snakeToCamel`. * * **Example** (Snake to camel) @@ -912,8 +873,7 @@ export function uncapitalize(): Getter { * const toCamel = SchemaGetter.snakeToCamel() * ``` * - * See also: - * - {@link camelToSnake} — inverse operation + * @see {@link camelToSnake} for the inverse operation * * @category string * @since 4.0.0 @@ -925,7 +885,8 @@ export function snakeToCamel(): Getter { /** * Converts a `camelCase` string to `snake_case`. * - * Behavior: + * **Details** + * * - Pure, delegates to `String.camelToSnake`. * * **Example** (Camel to snake) @@ -936,8 +897,7 @@ export function snakeToCamel(): Getter { * const toSnake = SchemaGetter.camelToSnake() * ``` * - * See also: - * - {@link snakeToCamel} — inverse operation + * @see {@link snakeToCamel} for the inverse operation * * @category string * @since 4.0.0 @@ -949,7 +909,8 @@ export function camelToSnake(): Getter { /** * Converts a string to lowercase. * - * Behavior: + * **Details** + * * - Pure, delegates to `String.toLowerCase`. * * **Example** (To lowercase) @@ -960,8 +921,7 @@ export function camelToSnake(): Getter { * const lower = SchemaGetter.toLowerCase() * ``` * - * See also: - * - {@link toUpperCase} — inverse operation + * @see {@link toUpperCase} for the inverse operation * * @category string * @since 4.0.0 @@ -973,7 +933,8 @@ export function toLowerCase(): Getter { /** * Converts a string to uppercase. * - * Behavior: + * **Details** + * * - Pure, delegates to `String.toUpperCase`. * * **Example** (To uppercase) @@ -984,8 +945,7 @@ export function toLowerCase(): Getter { * const upper = SchemaGetter.toUpperCase() * ``` * - * See also: - * - {@link toLowerCase} — inverse operation + * @see {@link toLowerCase} for the inverse operation * * @category string * @since 4.0.0 @@ -1001,14 +961,17 @@ type ParseJsonOptions = { /** * Parses a JSON string into a value. * - * Use this when: - * - An encoded value is a JSON string that needs to be parsed during decoding. + * **When to use** + * + * Use when you need a schema getter to parse a present encoded JSON string + * during decoding. + * + * **Details** * - * Behavior: * - Skips `None` inputs. * - Without `reviver`: returns `Schema.MutableJson` (typed JSON). * - With `reviver`: returns `unknown` (reviver may produce arbitrary values). - * - On parse failure, fails with `Issue.InvalidValue` containing the error message. + * - On parse failure, fails with `SchemaIssue.InvalidValue` containing the error message. * * **Example** (Parse JSON) * @@ -1019,10 +982,9 @@ type ParseJsonOptions = { * // Getter * ``` * - * See also: - * - {@link stringifyJson} — inverse operation + * @see {@link stringifyJson} for the inverse operation * - * @category Json + * @category JSON getters * @since 4.0.0 */ export function parseJson(): Getter @@ -1031,7 +993,7 @@ export function parseJson(options?: ParseJsonOptions | undefin return onSome((input) => Effect.try({ try: () => Option.some(JSON.parse(input, options?.reviver)), - catch: (e) => new Issue.InvalidValue(Option.some(input), { message: globalThis.String(e) }) + catch: (e) => new SchemaIssue.InvalidValue(Option.some(input), { message: globalThis.String(e) }) }) ) } @@ -1042,15 +1004,23 @@ type StringifyJsonOptions = { } /** - * Stringifies a value to JSON. + * Stringifies a present value using `JSON.stringify`. * - * Use this when: - * - A decoded value needs to be serialized to a JSON string during encoding. + * **When to use** + * + * Use when you need a schema getter to serialize a present decoded value to + * JSON text during encoding. + * + * **Details** * - * Behavior: * - Skips `None` inputs. - * - On stringify failure (e.g. circular references), fails with `Issue.InvalidValue`. - * - Supports optional `replacer` and `space` options (same as `JSON.stringify`). + * - On thrown stringify failures, such as circular references, fails with + * `SchemaIssue.InvalidValue`. + * - Supports optional `replacer` and `space` options, matching + * `JSON.stringify`. + * - If `JSON.stringify` returns `undefined`, such as for `undefined`, + * functions, symbols, or a replacer that removes the root value, that + * `undefined` result is returned rather than converted into an `Issue`. * * **Example** (Stringify JSON) * @@ -1061,17 +1031,16 @@ type StringifyJsonOptions = { * // Getter * ``` * - * See also: - * - {@link parseJson} — inverse operation + * @see {@link parseJson} for the inverse operation * - * @category Json + * @category JSON getters * @since 4.0.0 */ export function stringifyJson(options?: StringifyJsonOptions): Getter { return onSome((input) => Effect.try({ try: () => Option.some(JSON.stringify(input, options?.replacer, options?.space)), - catch: (e) => new Issue.InvalidValue(Option.some(input), { message: globalThis.String(e) }) + catch: (e) => new SchemaIssue.InvalidValue(Option.some(input), { message: globalThis.String(e) }) }) ) } @@ -1079,13 +1048,16 @@ export function stringifyJson(options?: StringifyJsonOptions): Getter { a: "1", b: "2" } * ``` * - * See also: - * - {@link joinKeyValue} — inverse operation - * - {@link split} — split into an array of strings + * @see {@link joinKeyValue} for the inverse operation + * @see {@link split} to split into an array of strings * * @category string * @since 4.0.0 @@ -1123,12 +1094,16 @@ export function splitKeyValue(options?: { /** * Joins a record of key-value pairs into a delimited string. * - * Use this when: - * - A decoded record needs to be serialized as a delimited key-value string. + * **When to use** + * + * Use when you need a schema getter to serialize a present decoded record as a + * delimited key-value string. + * + * **Details** * - * Behavior: - * - Joins entries with `separator` (default `,`) and key/value with `keyValueSeparator` (default `=`). - * - Pure, never fails. + * The getter is pure and never fails. It joins entries with `separator` + * (default `,`) and joins each key and value with `keyValueSeparator` (default + * `=`). * * **Example** (Join key-value record) * @@ -1139,8 +1114,7 @@ export function splitKeyValue(options?: { * // { a: "1", b: "2" } -> "a=1,b=2" * ``` * - * See also: - * - {@link splitKeyValue} — inverse operation + * @see {@link splitKeyValue} for the inverse operation * * @category string * @since 4.0.0 @@ -1159,13 +1133,15 @@ export function joinKeyValue>(options?: { /** * Splits a string into an array of strings by a separator. * - * Use this when: - * - An encoded string is a delimited list (e.g. CSV values). + * **When to use** * - * Behavior: - * - Splits by `separator` (default `,`). - * - An empty string produces an empty array (not `[""]`). - * - Pure, never fails. + * Use when you need a schema getter to split a present encoded string + * containing a delimited list, such as CSV values. + * + * **Details** + * + * The getter is pure and never fails. It splits by `separator` (default `,`). + * An empty string produces an empty array, not `[""]`. * * **Example** (Split comma-separated string) * @@ -1177,8 +1153,7 @@ export function joinKeyValue>(options?: { * // "" -> [] * ``` * - * See also: - * - {@link splitKeyValue} — when values are key-value pairs + * @see {@link splitKeyValue} when values are key-value pairs * * @category string * @since 4.0.0 @@ -1193,8 +1168,9 @@ export function split(options?: { /** * Encodes a `Uint8Array` or string to a Base64 string. * - * Behavior: - * - Pure, never fails. + * **Details** + * + * The getter is pure and never fails. * * **Example** (Encode to Base64) * @@ -1204,12 +1180,11 @@ export function split(options?: { * const encode = SchemaGetter.encodeBase64() * ``` * - * See also: - * - {@link decodeBase64} — inverse (to `Uint8Array`) - * - {@link decodeBase64String} — inverse (to `string`) - * - {@link encodeBase64Url} — URL-safe variant + * @see {@link decodeBase64} for the inverse operation to `Uint8Array` + * @see {@link decodeBase64String} for the inverse operation to `string` + * @see {@link encodeBase64Url} for the URL-safe variant * - * @category Base64 + * @category Base64 getters * @since 4.0.0 */ export function encodeBase64(): Getter { @@ -1219,8 +1194,9 @@ export function encodeBase64(): Getter /** * Encodes a `Uint8Array` or string to a URL-safe Base64 string. * - * Behavior: - * - Pure, never fails. + * **Details** + * + * The getter is pure and never fails. * * **Example** (Encode to Base64Url) * @@ -1230,12 +1206,11 @@ export function encodeBase64(): Getter * const encode = SchemaGetter.encodeBase64Url() * ``` * - * See also: - * - {@link decodeBase64Url} — inverse (to `Uint8Array`) - * - {@link decodeBase64UrlString} — inverse (to `string`) - * - {@link encodeBase64} — standard Base64 variant + * @see {@link decodeBase64Url} for the inverse operation to `Uint8Array` + * @see {@link decodeBase64UrlString} for the inverse operation to `string` + * @see {@link encodeBase64} for the standard Base64 variant * - * @category Base64 + * @category Base64 getters * @since 4.0.0 */ export function encodeBase64Url(): Getter { @@ -1245,8 +1220,9 @@ export function encodeBase64Url(): Getter(): Getter() * ``` * - * See also: - * - {@link decodeHex} — inverse (to `Uint8Array`) - * - {@link decodeHexString} — inverse (to `string`) + * @see {@link decodeHex} for the inverse operation to `Uint8Array` + * @see {@link decodeHexString} for the inverse operation to `string` * - * @category Hex + * @category Hex getters * @since 4.0.0 */ export function encodeHex(): Getter { @@ -1270,8 +1245,9 @@ export function encodeHex(): Getter { /** * Decodes a Base64 string to a `Uint8Array`. * - * Behavior: - * - Fails with `Issue.InvalidValue` if the input is not valid Base64. + * **Details** + * + * - Fails with `SchemaIssue.InvalidValue` if the input is not valid Base64. * * **Example** (Decode Base64 to bytes) * @@ -1282,27 +1258,27 @@ export function encodeHex(): Getter { * // Getter * ``` * - * See also: - * - {@link decodeBase64String} — decode to `string` instead - * - {@link encodeBase64} — inverse operation + * @see {@link decodeBase64String} to decode to `string` instead + * @see {@link encodeBase64} for the inverse operation * - * @category Base64 + * @category Base64 getters * @since 4.0.0 */ export function decodeBase64(): Getter { return transformOrFail((input) => - Result.mapError( - Encoding.decodeBase64(input), - (e) => new Issue.InvalidValue(Option.some(input), { message: e.message }) - ).asEffect() + Effect.mapErrorEager( + Effect.fromResult(Encoding.decodeBase64(input)), + (e) => new SchemaIssue.InvalidValue(Option.some(input), { message: e.message }) + ) ) } /** * Decodes a Base64 string to a UTF-8 `string`. * - * Behavior: - * - Fails with `Issue.InvalidValue` if the input is not valid Base64. + * **Details** + * + * - Fails with `SchemaIssue.InvalidValue` if the input is not valid Base64. * * **Example** (Decode Base64 to string) * @@ -1313,17 +1289,16 @@ export function decodeBase64(): Getter { * // Getter * ``` * - * See also: - * - {@link decodeBase64} — decode to `Uint8Array` instead - * - {@link encodeBase64} — inverse operation + * @see {@link decodeBase64} to decode to `Uint8Array` instead + * @see {@link encodeBase64} for the inverse operation * - * @category Base64 + * @category Base64 getters * @since 4.0.0 */ export function decodeBase64String(): Getter { return transformOrFail((input) => Result.match(Encoding.decodeBase64String(input), { - onFailure: (e) => Effect.fail(new Issue.InvalidValue(Option.some(input), { message: e.message })), + onFailure: (e) => Effect.fail(new SchemaIssue.InvalidValue(Option.some(input), { message: e.message })), onSuccess: Effect.succeed }) ) @@ -1332,8 +1307,9 @@ export function decodeBase64String(): Getter { /** * Decodes a URL-safe Base64 string to a `Uint8Array`. * - * Behavior: - * - Fails with `Issue.InvalidValue` if the input is not valid Base64Url. + * **Details** + * + * - Fails with `SchemaIssue.InvalidValue` if the input is not valid Base64Url. * * **Example** (Decode Base64Url to bytes) * @@ -1344,17 +1320,16 @@ export function decodeBase64String(): Getter { * // Getter * ``` * - * See also: - * - {@link decodeBase64UrlString} — decode to `string` instead - * - {@link encodeBase64Url} — inverse operation + * @see {@link decodeBase64UrlString} to decode to `string` instead + * @see {@link encodeBase64Url} for the inverse operation * - * @category Base64 + * @category Base64 getters * @since 4.0.0 */ export function decodeBase64Url(): Getter { return transformOrFail((input) => Result.match(Encoding.decodeBase64Url(input), { - onFailure: (e) => Effect.fail(new Issue.InvalidValue(Option.some(input), { message: e.message })), + onFailure: (e) => Effect.fail(new SchemaIssue.InvalidValue(Option.some(input), { message: e.message })), onSuccess: Effect.succeed }) ) @@ -1363,8 +1338,9 @@ export function decodeBase64Url(): Getter { /** * Decodes a URL-safe Base64 string to a UTF-8 `string`. * - * Behavior: - * - Fails with `Issue.InvalidValue` if the input is not valid Base64Url. + * **Details** + * + * - Fails with `SchemaIssue.InvalidValue` if the input is not valid Base64Url. * * **Example** (Decode Base64Url to string) * @@ -1375,17 +1351,16 @@ export function decodeBase64Url(): Getter { * // Getter * ``` * - * See also: - * - {@link decodeBase64Url} — decode to `Uint8Array` instead - * - {@link encodeBase64Url} — inverse operation + * @see {@link decodeBase64Url} to decode to `Uint8Array` instead + * @see {@link encodeBase64Url} for the inverse operation * - * @category Base64 + * @category Base64 getters * @since 4.0.0 */ export function decodeBase64UrlString(): Getter { return transformOrFail((input) => Result.match(Encoding.decodeBase64UrlString(input), { - onFailure: (e) => Effect.fail(new Issue.InvalidValue(Option.some(input), { message: e.message })), + onFailure: (e) => Effect.fail(new SchemaIssue.InvalidValue(Option.some(input), { message: e.message })), onSuccess: Effect.succeed }) ) @@ -1394,8 +1369,9 @@ export function decodeBase64UrlString(): Getter { /** * Decodes a hexadecimal string to a `Uint8Array`. * - * Behavior: - * - Fails with `Issue.InvalidValue` if the input is not valid hex. + * **Details** + * + * - Fails with `SchemaIssue.InvalidValue` if the input is not valid hex. * * **Example** (Decode hex to bytes) * @@ -1406,17 +1382,16 @@ export function decodeBase64UrlString(): Getter { * // Getter * ``` * - * See also: - * - {@link decodeHexString} — decode to `string` instead - * - {@link encodeHex} — inverse operation + * @see {@link decodeHexString} to decode to `string` instead + * @see {@link encodeHex} for the inverse operation * - * @category Hex + * @category Hex getters * @since 4.0.0 */ export function decodeHex(): Getter { return transformOrFail((input) => Result.match(Encoding.decodeHex(input), { - onFailure: (e) => Effect.fail(new Issue.InvalidValue(Option.some(input), { message: e.message })), + onFailure: (e) => Effect.fail(new SchemaIssue.InvalidValue(Option.some(input), { message: e.message })), onSuccess: Effect.succeed }) ) @@ -1425,8 +1400,9 @@ export function decodeHex(): Getter { /** * Decodes a hexadecimal string to a UTF-8 `string`. * - * Behavior: - * - Fails with `Issue.InvalidValue` if the input is not valid hex. + * **Details** + * + * - Fails with `SchemaIssue.InvalidValue` if the input is not valid hex. * * **Example** (Decode hex to string) * @@ -1437,27 +1413,29 @@ export function decodeHex(): Getter { * // Getter * ``` * - * See also: - * - {@link decodeHex} — decode to `Uint8Array` instead - * - {@link encodeHex} — inverse operation + * @see {@link decodeHex} to decode to `Uint8Array` instead + * @see {@link encodeHex} for the inverse operation * - * @category Hex + * @category Hex getters * @since 4.0.0 */ export function decodeHexString(): Getter { return transformOrFail((input) => Result.match(Encoding.decodeHexString(input), { - onFailure: (e) => Effect.fail(new Issue.InvalidValue(Option.some(input), { message: e.message })), + onFailure: (e) => Effect.fail(new SchemaIssue.InvalidValue(Option.some(input), { message: e.message })), onSuccess: Effect.succeed }) ) } /** - * Encodes a string using `encodeURIComponent`. + * Encodes a present string using `encodeURIComponent`. + * + * **Details** * - * Behavior: - * - Pure, never fails. + * - Skips `None` inputs. + * - May throw a `URIError` for malformed surrogate pairs; this exception is not + * converted into an `Issue`. * * **Example** (Encode a URI component) * @@ -1467,8 +1445,7 @@ export function decodeHexString(): Getter { * const encode = SchemaGetter.encodeUriComponent() * ``` * - * See also: - * - {@link decodeUriComponent} - inverse operation + * @see {@link decodeUriComponent} for the inverse operation * * @category URI * @since 4.0.0 @@ -1480,8 +1457,9 @@ export function encodeUriComponent(): Getter { /** * Decodes a URI component encoded string using `decodeURIComponent`. * - * Behavior: - * - Fails with `Issue.InvalidValue` if the input contains malformed percent-encoding sequences. + * **Details** + * + * - Fails with `SchemaIssue.InvalidValue` if the input contains malformed percent-encoding sequences. * * **Example** (Decode a URI component) * @@ -1492,8 +1470,7 @@ export function encodeUriComponent(): Getter { * // Getter * ``` * - * See also: - * - {@link encodeUriComponent} - inverse operation + * @see {@link encodeUriComponent} for the inverse operation * * @category URI * @since 4.0.0 @@ -1504,7 +1481,7 @@ export function decodeUriComponent(): Getter { return Effect.succeed(globalThis.decodeURIComponent(input)) } catch (e) { return Effect.fail( - new Issue.InvalidValue(Option.some(input), { + new SchemaIssue.InvalidValue(Option.some(input), { message: e instanceof URIError ? e.message : "Invalid URI component" }) ) @@ -1513,13 +1490,21 @@ export function decodeUriComponent(): Getter { } /** - * Parses a `DateTime.Input` value (string, number, or Date) into a `DateTime.Utc`. + * Parses a `DateTime.Input` value into a `DateTime.Utc`. + * + * **When to use** * - * Use this when: - * - An encoded value represents a date/time and should be decoded to a `DateTime.Utc`. + * Use when you need a schema getter to decode a present encoded date/time value + * to a `DateTime.Utc`. * - * Behavior: - * - Fails with `Issue.InvalidValue` if the input cannot be parsed as a valid DateTime. + * **Details** + * + * - Accepted input includes existing `DateTime` values, partial date/time parts, + * instant objects, zoned instant objects, JavaScript `Date` instances, epoch + * milliseconds, and date strings. + * - Converts successfully parsed values to UTC. + * - Fails with `SchemaIssue.InvalidValue` if the input cannot be parsed as a valid + * `DateTime`. * * **Example** (Parse DateTime) * @@ -1530,8 +1515,7 @@ export function decodeUriComponent(): Getter { * // Getter * ``` * - * See also: - * - {@link Date} — simpler coercion to `Date` (no validation) + * @see {@link Date} for a simpler coercion to `Date` (no validation) * * @category DateTime * @since 4.0.0 @@ -1539,7 +1523,8 @@ export function decodeUriComponent(): Getter { export function dateTimeUtcFromInput(): Getter { return transformOrFail((input) => { return Option.match(DateTime.make(input), { - onNone: () => Effect.fail(new Issue.InvalidValue(Option.some(input), { message: "Invalid DateTime input" })), + onNone: () => + Effect.fail(new SchemaIssue.InvalidValue(Option.some(input), { message: "Invalid DateTime input" })), onSome: (dt) => Effect.succeed(DateTime.toUtc(dt)) }) }) @@ -1548,13 +1533,16 @@ export function dateTimeUtcFromInput(): Gette /** * Decodes a `FormData` object into a nested tree structure using bracket-path notation. * - * Use this when: - * - Parsing `FormData` from HTTP requests into structured objects. + * **When to use** + * + * Use when you need a schema getter to parse `FormData` from HTTP requests into + * structured objects. + * + * **Details** * - * Behavior: - * - Pure, never fails. - * - Interprets bracket-path keys (e.g. `user[name]`, `items[0]`) to build nested objects/arrays. - * - Leaf values are `string` or `Blob`. + * The getter is pure and never fails. It interprets bracket-path keys such as + * `user[name]` and `items[0]` to build nested objects or arrays, and each leaf + * value is a `string` or `Blob`. * * **Example** (Decode FormData) * @@ -1565,10 +1553,9 @@ export function dateTimeUtcFromInput(): Gette * // Getter, FormData> * ``` * - * See also: - * - {@link encodeFormData} — inverse operation - * - {@link makeTreeRecord} — the underlying bracket-path parser - * - {@link decodeURLSearchParams} — similar for URLSearchParams + * @see {@link encodeFormData} for the inverse operation + * @see {@link makeTreeRecord} for the underlying bracket-path parser + * @see {@link decodeURLSearchParams} for the URLSearchParams variant * * @category FormData * @since 4.0.0 @@ -1584,13 +1571,16 @@ const collectFormDataEntries = collectBracketPathEntries((value): value is strin /** * Encodes a nested object into a `FormData` instance using bracket-path notation. * - * Use this when: - * - Serializing structured data to `FormData` for HTTP requests. + * **When to use** * - * Behavior: - * - Pure, never fails. - * - Flattens nested objects/arrays into bracket-path keys (e.g. `user[name]`, `items[0]`). - * - Non-object inputs produce an empty `FormData`. + * Use when you need a schema getter to serialize structured data to `FormData` + * for HTTP requests. + * + * **Details** + * + * The getter is pure and never fails. It flattens nested objects or arrays into + * bracket-path keys such as `user[name]` and `items[0]`. Non-object inputs + * produce an empty `FormData`. * * **Example** (Encode to FormData) * @@ -1601,10 +1591,9 @@ const collectFormDataEntries = collectBracketPathEntries((value): value is strin * // Getter * ``` * - * See also: - * - {@link decodeFormData} — inverse operation - * - {@link collectBracketPathEntries} — the underlying flattener - * - {@link encodeURLSearchParams} — similar for URLSearchParams + * @see {@link decodeFormData} for the inverse operation + * @see {@link collectBracketPathEntries} for the underlying flattener + * @see {@link encodeURLSearchParams} for the URLSearchParams variant * * @category FormData * @since 4.0.0 @@ -1625,13 +1614,16 @@ export function encodeFormData(): Getter { /** * Decodes a `URLSearchParams` object into a nested tree structure using bracket-path notation. * - * Use this when: - * - Parsing query parameters from URLs into structured objects. + * **When to use** + * + * Use when you need a schema getter to parse query parameters from URLs into + * structured objects. * - * Behavior: - * - Pure, never fails. - * - Interprets bracket-path keys (e.g. `user[name]`, `items[0]`) to build nested objects/arrays. - * - Leaf values are `string`. + * **Details** + * + * The getter is pure and never fails. It interprets bracket-path keys such as + * `user[name]` and `items[0]` to build nested objects or arrays, and each leaf + * value is a `string`. * * **Example** (Decode URLSearchParams) * @@ -1642,12 +1634,11 @@ export function encodeFormData(): Getter { * // Getter, URLSearchParams> * ``` * - * See also: - * - {@link encodeURLSearchParams} — inverse operation - * - {@link makeTreeRecord} — the underlying bracket-path parser - * - {@link decodeFormData} — similar for FormData + * @see {@link encodeURLSearchParams} for the inverse operation + * @see {@link makeTreeRecord} for the underlying bracket-path parser + * @see {@link decodeFormData} for the FormData variant * - * @category URLSearchParams + * @category search params * @since 4.0.0 */ export function decodeURLSearchParams(): Getter, URLSearchParams> { @@ -1659,13 +1650,15 @@ const collectURLSearchParamsEntries = collectBracketPathEntries(Predicate.isStri /** * Encodes a nested object into a `URLSearchParams` instance using bracket-path notation. * - * Use this when: - * - Serializing structured data to query parameters for URLs. + * **When to use** + * + * Use when you need a schema getter to serialize structured data to query + * parameters for URLs. + * + * **Details** * - * Behavior: - * - Pure, never fails. - * - Flattens nested objects/arrays into bracket-path keys. - * - Non-object inputs produce an empty `URLSearchParams`. + * The getter is pure and never fails. It flattens nested objects or arrays into + * bracket-path keys. Non-object inputs produce an empty `URLSearchParams`. * * **Example** (Encode to URLSearchParams) * @@ -1676,12 +1669,11 @@ const collectURLSearchParamsEntries = collectBracketPathEntries(Predicate.isStri * // Getter * ``` * - * See also: - * - {@link decodeURLSearchParams} — inverse operation - * - {@link collectBracketPathEntries} — the underlying flattener - * - {@link encodeFormData} — similar for FormData + * @see {@link decodeURLSearchParams} for the inverse operation + * @see {@link collectBracketPathEntries} for the underlying flattener + * @see {@link encodeFormData} for the FormData variant * - * @category URLSearchParams + * @category search params * @since 4.0.0 */ export function encodeURLSearchParams(): Getter { @@ -1714,16 +1706,18 @@ function bracketPathToTokens(bracketPath: string): Array { /** * Builds a nested tree object from a list of bracket-path entries. * - * A bracket path is a string like `"user[address][city]"` that describes nested - * object/array structure. This function interprets those paths and constructs the - * corresponding nested object. + * **When to use** * - * Use this when: - * - Parsing FormData or URLSearchParams entries into structured objects. + * Use when you need a schema getter to parse FormData or URLSearchParams + * entries into structured objects. * - You have flat key-value pairs with bracket-path keys that need nesting. * - * Behavior: - * - Mutates and returns a new object (does not mutate the input array). + * **Details** + * + * - A bracket path is a string like `"user[address][city]"` that describes nested + * object/array structure. + * - Interprets bracket paths and constructs the corresponding nested object. + * - Builds and returns a nested object from the input entries. * - Supported syntax: * - `"foo"` → object key `"foo"` * - `"foo[bar]"` → nested `{ foo: { bar: ... } }` @@ -1745,10 +1739,9 @@ function bracketPathToTokens(bracketPath: string): Array { * // { user: { name: "Alice", tags: ["admin", "editor"] } } * ``` * - * See also: - * - {@link collectBracketPathEntries} — inverse operation (tree to flat entries) - * - {@link decodeFormData} — uses this internally - * - {@link decodeURLSearchParams} — uses this internally + * @see {@link collectBracketPathEntries} for the inverse operation (tree to flat entries) + * @see {@link decodeFormData} for a higher-level FormData decoder + * @see {@link decodeURLSearchParams} for a higher-level URLSearchParams decoder * * @category Tree * @since 4.0.0 @@ -1808,14 +1801,17 @@ export function makeTreeRecord( /** * Flattens a nested object into bracket-path entries, filtering leaf values by a type guard. * - * This is the inverse of {@link makeTreeRecord}. It takes a nested object and produces - * flat `[bracketPath, value]` pairs suitable for `FormData` or `URLSearchParams`. + * **When to use** * - * Use this when: - * - Serializing structured objects to flat key-value entries. + * Use when you need a schema getter to serialize structured objects to flat + * key-value entries. * - Building custom `FormData` or `URLSearchParams` encoders. * - * Behavior: + * **Details** + * + * - This is the inverse of {@link makeTreeRecord}. + * - Takes a nested object and produces flat `[bracketPath, value]` pairs suitable for + * `FormData` or `URLSearchParams`. * - Returns a curried function: first call provides the leaf type guard, second call provides the object. * - Recursively traverses objects and arrays. * - If all elements of an array are leaves, encodes them as multiple entries with the same key @@ -1825,17 +1821,16 @@ export function makeTreeRecord( * **Example** (Flatten object to bracket paths) * * ```ts - * import { SchemaGetter, Predicate } from "effect" + * import { Predicate, SchemaGetter } from "effect" * * const collectStrings = SchemaGetter.collectBracketPathEntries(Predicate.isString) * const entries = collectStrings({ user: { name: "Alice", tags: ["admin", "editor"] } }) * // [["user[name]", "Alice"], ["user[tags]", "admin"], ["user[tags]", "editor"]] * ``` * - * See also: - * - {@link makeTreeRecord} — inverse operation (flat entries to tree) - * - {@link encodeFormData} — uses this internally - * - {@link encodeURLSearchParams} — uses this internally + * @see {@link makeTreeRecord} for the inverse operation (flat entries to tree) + * @see {@link encodeFormData} for a higher-level FormData encoder + * @see {@link encodeURLSearchParams} for a higher-level URLSearchParams encoder * * @category Tree * @since 4.0.0 diff --git a/.opencode/node_modules/effect/src/SchemaIssue.ts b/.opencode/node_modules/effect/src/SchemaIssue.ts index 33d0e5696cd576c1cd459f17e2df2b17594b53c9..eb52939d351721b3b49ce9d203e9ba6838175672 100644 --- a/.opencode/node_modules/effect/src/SchemaIssue.ts +++ b/.opencode/node_modules/effect/src/SchemaIssue.ts @@ -1,80 +1,12 @@ /** - * Structured validation errors produced by the Effect Schema system. - * - * When `Schema.decode`, `Schema.encode`, or a filter rejects a value, the - * result is an {@link Issue} — a recursive tree that describes *what* went - * wrong and *where*. This module defines every node type in that tree and - * provides formatters that turn an `Issue` into a human-readable string or a - * Standard Schema V1 failure result. - * - * ## Mental model - * - * - **Issue**: A discriminated union (`_tag`) of all possible validation error - * nodes. It is recursive — composite nodes wrap inner `Issue` children. - * - **Leaf**: A terminal issue with no inner children ({@link InvalidType}, - * {@link InvalidValue}, {@link MissingKey}, {@link UnexpectedKey}, - * {@link Forbidden}, {@link OneOf}). - * - **Composite nodes**: Wrap one or more inner issues to add context — - * {@link Filter}, {@link Encoding}, {@link Pointer}, {@link Composite}, - * {@link AnyOf}. - * - **Pointer**: Adds a property-key path to an inner issue, indicating - * *where* in the input the error occurred. - * - **Formatter**: A function `Issue → Format` that serialises the error tree. - * Two built-in factories are provided: {@link makeFormatterDefault} (plain - * string) and {@link makeFormatterStandardSchemaV1} (Standard Schema V1). - * - * ## Common tasks - * - * - Check if a value is an Issue → {@link isIssue} - * - Extract the actual input from any issue → {@link getActual} - * - Format an issue as a string → {@link makeFormatterDefault} - * - Format an issue for Standard Schema V1 → {@link makeFormatterStandardSchemaV1} - * - Customise leaf formatting → {@link defaultLeafHook} - * - Customise filter formatting → {@link defaultCheckHook} - * - * ## Gotchas - * - * - `Pointer` and `MissingKey` carry no actual value — {@link getActual} - * returns `Option.none()` for them. - * - `AnyOf`, `UnexpectedKey`, `OneOf`, and `Filter` store `actual` as a plain - * `unknown` (not `Option`), so {@link getActual} wraps them with - * `Option.some`. - * - Calling `toString()` on any `Issue` uses the default formatter. To - * customise output, create your own formatter with - * {@link makeFormatterDefault} or {@link makeFormatterStandardSchemaV1}. - * - The `Issue` tree can be deeply nested for complex schemas. Formatters - * flatten composite nodes for display. - * - * ## Quickstart - * - * **Example** (Inspecting a validation error) + * Describes problems found while decoding, encoding, or checking data with + * schemas. * - * ```ts - * import { Schema, SchemaIssue } from "effect" - * - * const Person = Schema.Struct({ - * name: Schema.String, - * age: Schema.Number - * }) - * - * try { - * Schema.decodeUnknownSync(Person)({ name: 42 }) - * } catch (e) { - * if (Schema.isSchemaError(e)) { - * console.log(SchemaIssue.isIssue(e.issue)) - * // true - * console.log(String(e.issue)) - * // formatted error message - * } - * } - * ``` - * - * ## See also - * - * - {@link Issue} — the root union type - * - {@link Leaf} — terminal issue types - * - {@link Formatter} — the formatter interface - * - {@link makeFormatterDefault} — default string formatter + * An `Issue` records what failed and, for nested data, where the failure + * happened. The Schema system uses these values for missing keys, unexpected + * keys, invalid types, invalid values, failed filters, failed transformations, + * and alternatives that did not match. This module also formats issues and + * supports redaction for sensitive values. * * @since 4.0.0 */ @@ -86,21 +18,21 @@ import * as Option from "./Option.ts" import { hasProperty } from "./Predicate.ts" import * as Redacted from "./Redacted.ts" import type * as Schema from "./Schema.ts" -import type * as AST from "./SchemaAST.ts" +import type * as SchemaAST from "./SchemaAST.ts" const TypeId = "~effect/SchemaIssue/Issue" /** * Returns `true` if the given value is an {@link Issue}. * - * When to use: + * **When to use** * - * - Narrowing an `unknown` value to `Issue` in error-handling code. - * - Distinguishing an `Issue` from other error types in a catch-all handler. + * Use when you need to narrow an `unknown` value to `Issue` in error-handling + * code, such as distinguishing an `Issue` from other error types in a catch-all + * handler. * - * Behaviour: + * **Details** * - * - Pure; does not mutate input. * - Checks for the internal `TypeId` brand on the value. * * **Example** (Type-guarding an unknown error) @@ -117,6 +49,7 @@ const TypeId = "~effect/SchemaIssue/Issue" * * @see {@link Issue} * + * @category guards * @since 4.0.0 */ export function isIssue(u: unknown): u is Issue { @@ -126,10 +59,12 @@ export function isIssue(u: unknown): u is Issue { /** * Union of all terminal (leaf) issue types that have no inner `Issue` children. * - * When to use: + * **When to use** * - * - Constraining formatter hooks to only handle terminal nodes. - * - Pattern-matching on the `_tag` of an issue when you only care about leaves. + * Use when constraining formatter hooks to only handle terminal nodes or when + * pattern matching on the `_tag` of an issue and only leaf nodes matter. + * + * **Details** * * Members: {@link InvalidType}, {@link InvalidValue}, {@link MissingKey}, * {@link UnexpectedKey}, {@link Forbidden}, {@link OneOf}. @@ -137,7 +72,7 @@ export function isIssue(u: unknown): u is Issue { * @see {@link Issue} — the full union including composite nodes * @see {@link LeafHook} — formatter hook that operates on `Leaf` values * - * @category model + * @category models * @since 4.0.0 */ export type Leaf = @@ -151,25 +86,24 @@ export type Leaf = /** * The root discriminated union of all validation error nodes. * - * Every node has a `_tag` field for pattern-matching. The union includes both - * terminal {@link Leaf} types and composite types that wrap inner issues: - * {@link Filter}, {@link Encoding}, {@link Pointer}, {@link Composite}, - * {@link AnyOf}. + * **When to use** * - * When to use: + * Use when typing the error channel in `Effect` results from + * schema parsing, or when writing custom formatters or issue-tree walkers. * - * - Typing the error channel in `Effect` results from schema - * parsing. - * - Writing custom formatters or issue-tree walkers. + * **Details** * - * All `Issue` instances have a `toString()` that delegates to the default - * formatter, so `String(issue)` produces a human-readable message. + * Every node has a `_tag` field for pattern-matching. The union includes both + * terminal {@link Leaf} types and composite types that wrap inner issues: + * {@link Filter}, {@link Encoding}, {@link Pointer}, {@link Composite}, + * {@link AnyOf}. All `Issue` instances have a `toString()` that delegates to + * the default formatter, so `String(issue)` produces a human-readable message. * * @see {@link Leaf} — the terminal subset * @see {@link isIssue} — type guard * @see {@link getActual} — extract the actual value from any issue * - * @category model + * @category models * @since 4.0.0 */ export type Issue = @@ -189,14 +123,14 @@ class Base { } /** - * Issue produced when a schema filter (refinement check) fails. + * Represents a schema issue produced when a schema filter (refinement check) fails. * - * When to use: + * **When to use** * - * - Inspect which filter rejected the value. - * - Walk the inner `issue` for the specific validation failure. + * Use when you need to inspect a schema issue that records which refinement + * check rejected the value. * - * Behaviour: + * **Details** * * - `actual` is the raw input value that was tested (plain `unknown`, not * wrapped in `Option`). @@ -219,7 +153,7 @@ class Base { * @see {@link Leaf} — terminal issue types that commonly appear as the inner `issue` * @see {@link CheckHook} — formatter hook for `Filter` issues * - * @category model + * @category models * @since 4.0.0 */ export class Filter extends Base { @@ -231,7 +165,7 @@ export class Filter extends Base { /** * The filter that failed. */ - readonly filter: AST.Filter + readonly filter: SchemaAST.Filter /** * The issue that occurred. */ @@ -245,7 +179,7 @@ export class Filter extends Base { /** * The filter that failed. */ - filter: AST.Filter, + filter: SchemaAST.Filter, /** * The issue that occurred. */ @@ -259,15 +193,14 @@ export class Filter extends Base { } /** - * Issue produced when a schema transformation (encode/decode step) fails. + * Represents a schema issue produced when a schema transformation (encode/decode step) fails. * - * When to use: + * **When to use** * - * - Inspect failures from `Schema.decodeTo` / `Schema.encodeTo` + * Use when you need to inspect failures from `Schema.decodeTo` / `Schema.encodeTo` * transformations. - * - Walk the inner `issue` for the root cause of the transformation failure. * - * Behaviour: + * **Details** * * - `ast` is the AST node for the transformation that failed. * - `actual` is `Option.some(value)` when the input was present, or @@ -277,7 +210,7 @@ export class Filter extends Base { * @see {@link Filter} — failure from a refinement check (not a transformation) * @see {@link Composite} — multiple issues from a single schema node * - * @category model + * @category models * @since 4.0.0 */ export class Encoding extends Base { @@ -285,7 +218,7 @@ export class Encoding extends Base { /** * The schema that caused the issue. */ - readonly ast: AST.AST + readonly ast: SchemaAST.AST /** * The input value that caused the issue. */ @@ -299,7 +232,7 @@ export class Encoding extends Base { /** * The schema that caused the issue. */ - ast: AST.AST, + ast: SchemaAST.AST, /** * The input value that caused the issue. */ @@ -320,12 +253,12 @@ export class Encoding extends Base { * Wraps an inner {@link Issue} with a property-key path, indicating *where* in * a nested structure the error occurred. * - * When to use: + * **When to use** * - * - Walk the issue tree to accumulate path segments for error reporting. - * - Match on `_tag === "Pointer"` when flattening nested issues. + * Use when you need to walk the issue tree to accumulate path segments for error + * reporting. * - * Behaviour: + * **Details** * * - `path` is an array of property keys (strings, numbers, or symbols). * - Has no `actual` value — {@link getActual} returns `Option.none()`. @@ -335,8 +268,8 @@ export class Encoding extends Base { * @see {@link getActual} — returns `Option.none()` for `Pointer` * @see {@link Composite} — groups multiple issues under one schema node * - * @category model - * @since 4.0.0 + * @category models + * @since 3.10.0 */ export class Pointer extends Base { readonly _tag = "Pointer" @@ -366,15 +299,13 @@ export class Pointer extends Base { } /** - * Issue produced when a required key or tuple index is missing from the input. + * Represents a schema issue produced when a required key or tuple index is missing from the input. * - * When to use: + * **When to use** * - * - Detect absent fields in struct/tuple validation. - * - Typically found inside a {@link Pointer} that indicates which key is - * missing. + * Use when you need to detect absent fields in struct/tuple validation. * - * Behaviour: + * **Details** * * - Has no `actual` value — {@link getActual} returns `Option.none()`. * - `annotations` may contain a custom `messageMissingKey` for formatting. @@ -382,7 +313,7 @@ export class Pointer extends Base { * @see {@link Pointer} — wraps this issue with the missing key's path * @see {@link UnexpectedKey} — the opposite case (extra key present) * - * @category model + * @category models * @since 4.0.0 */ export class MissingKey extends Base { @@ -404,16 +335,15 @@ export class MissingKey extends Base { } /** - * Issue produced when an input object or tuple contains a key/index not + * Represents a schema issue produced when an input object or tuple contains a key/index not * declared by the schema. * - * When to use: + * **When to use** * - * - Detect excess properties during strict struct/tuple validation. - * - Typically found inside a {@link Pointer} that indicates which key was - * unexpected. + * Use when you need to detect excess properties during strict struct/tuple + * validation. * - * Behaviour: + * **Details** * * - `actual` is the raw value at the unexpected key (plain `unknown`). * - `ast` is the schema that was being validated against. @@ -422,7 +352,7 @@ export class MissingKey extends Base { * @see {@link MissingKey} — the opposite case (required key absent) * @see {@link Pointer} — wraps this issue with the unexpected key's path * - * @category model + * @category models * @since 4.0.0 */ export class UnexpectedKey extends Base { @@ -430,7 +360,7 @@ export class UnexpectedKey extends Base { /** * The schema that caused the issue. */ - readonly ast: AST.AST + readonly ast: SchemaAST.AST /** * The input value that caused the issue. */ @@ -440,7 +370,7 @@ export class UnexpectedKey extends Base { /** * The schema that caused the issue. */ - ast: AST.AST, + ast: SchemaAST.AST, /** * The input value that caused the issue. */ @@ -453,15 +383,14 @@ export class UnexpectedKey extends Base { } /** - * Issue that groups multiple child issues under a single schema node. + * Represents a schema issue that groups multiple child issues under a single schema node. * - * When to use: + * **When to use** * - * - Walk the issue tree for struct/tuple schemas that collect all field errors - * rather than failing on the first. - * - Match on `_tag === "Composite"` to iterate over `issues`. + * Use when you need to walk the issue tree for struct/tuple schemas that collect + * all field errors rather than failing on the first. * - * Behaviour: + * **Details** * * - `issues` is a non-empty readonly array (at least one child). * - `actual` is `Option.some(value)` when the input was present, or @@ -471,15 +400,15 @@ export class UnexpectedKey extends Base { * @see {@link AnyOf} — used for union no-match errors (similar but different semantics) * @see {@link Pointer} — adds path context to individual issues * - * @category model - * @since 4.0.0 + * @category models + * @since 3.10.0 */ export class Composite extends Base { readonly _tag = "Composite" /** * The schema that caused the issue. */ - readonly ast: AST.AST + readonly ast: SchemaAST.AST /** * The input value that caused the issue. */ @@ -493,7 +422,7 @@ export class Composite extends Base { /** * The schema that caused the issue. */ - ast: AST.AST, + ast: SchemaAST.AST, /** * The input value that caused the issue. */ @@ -511,16 +440,15 @@ export class Composite extends Base { } /** - * Issue produced when the runtime type of the input does not match the type + * Represents a schema issue produced when the runtime type of the input does not match the type * expected by the schema (e.g. got `null` when `string` was expected). * - * When to use: + * **When to use** * - * - Detect basic type mismatches (wrong primitive, null where object expected, - * etc.). - * - The most common leaf issue in typical validation failures. + * Use when you need to detect basic type mismatches, such as a wrong primitive + * or `null` where an object was expected. * - * Behaviour: + * **Details** * * - `ast` is the schema node that expected a different type. * - `actual` is `Option.some(value)` when the input was present, or @@ -544,7 +472,7 @@ export class Composite extends Base { * * @see {@link InvalidValue} — the input has the right type but fails a value constraint * - * @category model + * @category models * @since 4.0.0 */ export class InvalidType extends Base { @@ -552,7 +480,7 @@ export class InvalidType extends Base { /** * The schema that caused the issue. */ - readonly ast: AST.AST + readonly ast: SchemaAST.AST /** * The input value that caused the issue. */ @@ -562,7 +490,7 @@ export class InvalidType extends Base { /** * The schema that caused the issue. */ - ast: AST.AST, + ast: SchemaAST.AST, /** * The input value that caused the issue. */ @@ -575,16 +503,15 @@ export class InvalidType extends Base { } /** - * Issue produced when the input has the correct type but its value violates a + * Represents a schema issue produced when the input has the correct type but its value violates a * constraint (e.g. a string that is too short, a number out of range). * - * When to use: + * **When to use** * - * - Detect constraint violations from `Schema.filter`, `Schema.minLength`, - * `Schema.greaterThan`, etc. - * - Create custom validation errors in `Schema.makeFilter` callbacks. + * Use when you need to detect constraint violations from `Schema.filter`, + * `Schema.minLength`, `Schema.greaterThan`, or similar checks. * - * Behaviour: + * **Details** * * - `actual` is `Option.some(value)` when the failing value is known, or * `Option.none()` when absent. @@ -608,7 +535,7 @@ export class InvalidType extends Base { * @see {@link InvalidType} — the input has the wrong type entirely * @see {@link Filter} — composite wrapper when a schema filter produces this issue * - * @category model + * @category models * @since 4.0.0 */ export class InvalidValue extends Base { @@ -639,15 +566,15 @@ export class InvalidValue extends Base { } /** - * Issue produced when a forbidden operation is encountered during parsing, + * Represents a schema issue produced when a forbidden operation is encountered during parsing, * such as an asynchronous Effect running inside `Schema.decodeUnknownSync`. * - * When to use: + * **When to use** * - * - Detect that a schema requires async execution but was run synchronously. - * - Provide custom error messages via the `annotations.message` field. + * Use when you need to detect that a schema requires async execution but was run + * synchronously. * - * Behaviour: + * **Details** * * - `actual` is `Option.some(value)` when the input is known, or * `Option.none()` when absent. @@ -669,8 +596,8 @@ export class InvalidValue extends Base { * * @see {@link InvalidValue} — for value-constraint failures (not operation failures) * - * @category model - * @since 4.0.0 + * @category models + * @since 3.10.0 */ export class Forbidden extends Base { readonly _tag = "Forbidden" @@ -700,15 +627,14 @@ export class Forbidden extends Base { } /** - * Issue produced when a value does not match *any* member of a union schema. + * Represents a schema issue produced when a value does not match *any* member of a union schema. * - * When to use: + * **When to use** * - * - Inspect which union members were attempted and why each failed. - * - `issues` may be empty when the union has no members or when the input does - * not pass the initial type guard. + * Use when you need to inspect which union members were attempted and why each + * failed. * - * Behaviour: + * **Details** * * - `ast` is the `Union` AST node. * - `actual` is the raw input value (plain `unknown`). @@ -718,7 +644,7 @@ export class Forbidden extends Base { * @see {@link OneOf} — the opposite: *too many* members matched * @see {@link Composite} — groups multiple issues under a non-union schema * - * @category model + * @category models * @since 4.0.0 */ export class AnyOf extends Base { @@ -726,7 +652,7 @@ export class AnyOf extends Base { /** * The schema that caused the issue. */ - readonly ast: AST.Union + readonly ast: SchemaAST.Union /** * The input value that caused the issue. */ @@ -740,7 +666,7 @@ export class AnyOf extends Base { /** * The schema that caused the issue. */ - ast: AST.Union, + ast: SchemaAST.Union, /** * The input value that caused the issue. */ @@ -758,15 +684,15 @@ export class AnyOf extends Base { } /** - * Issue produced when a value matches *multiple* members of a union that is + * Represents a schema issue produced when a value matches *multiple* members of a union that is * configured to allow exactly one match (oneOf mode). * - * When to use: + * **When to use** * - * - Detect ambiguous union matches when `oneOf` validation is enabled. - * - Inspect `successes` to see which members matched. + * Use when you need to detect ambiguous union matches when `oneOf` validation is + * enabled. * - * Behaviour: + * **Details** * * - `ast` is the `Union` AST node. * - `actual` is the raw input value (plain `unknown`). @@ -776,7 +702,7 @@ export class AnyOf extends Base { * * @see {@link AnyOf} — the opposite: *no* members matched * - * @category model + * @category models * @since 4.0.0 */ export class OneOf extends Base { @@ -784,7 +710,7 @@ export class OneOf extends Base { /** * The schema that caused the issue. */ - readonly ast: AST.Union + readonly ast: SchemaAST.Union /** * The input value that caused the issue. */ @@ -792,13 +718,13 @@ export class OneOf extends Base { /** * The schemas that were successful. */ - readonly successes: ReadonlyArray + readonly successes: ReadonlyArray constructor( /** * The schema that caused the issue. */ - ast: AST.Union, + ast: SchemaAST.Union, /** * The input value that caused the issue. */ @@ -806,7 +732,7 @@ export class OneOf extends Base { /** * The schemas that were successful. */ - successes: ReadonlyArray + successes: ReadonlyArray ) { super() this.ast = ast @@ -818,14 +744,13 @@ export class OneOf extends Base { /** * Extracts the actual input value from any {@link Issue} variant. * - * When to use: + * **When to use** * - * - Retrieve the offending value for logging or custom error rendering. - * - Uniformly access `actual` regardless of which issue variant you have. + * Use when you need to retrieve an `Issue`'s offending input value for logging + * or custom error rendering. * - * Behaviour: + * **Details** * - * - Pure; does not mutate the issue. * - Returns `Option.none()` for `Pointer` and `MissingKey` (they carry no * value). * - Returns the existing `Option` for variants that already store `actual` as @@ -847,6 +772,7 @@ export class OneOf extends Base { * @see {@link Issue} * @see {@link isIssue} * + * @category getters * @since 4.0.0 */ export function getActual(issue: Issue): Option.Option { @@ -893,7 +819,7 @@ export function makeSingle(input: unknown, out: undefined | boolean | Schema.Fil } /** @internal */ -export function make(input: unknown, ast: AST.AST, out: Schema.FilterOutput): Issue | undefined { +export function make(input: unknown, ast: SchemaAST.AST, out: Schema.FilterOutput): Issue | undefined { if (Array.isArray(out)) { if (Arr.isReadonlyArrayNonEmpty(out)) { if (out.length === 1) { @@ -911,15 +837,8 @@ export function make(input: unknown, ast: AST.AST, out: Schema.FilterOutput): Is * representation. Specialisation of the generic `Formatter` from * `Formatter.ts` with `Value` fixed to `Issue`. * - * When to use: - * - * - Type custom formatters that accept an `Issue` and return any output format. - * - Use with {@link makeFormatterDefault} or - * {@link makeFormatterStandardSchemaV1} to obtain built-in implementations. - * * @see {@link makeFormatterDefault} — creates a `Formatter` - * @see {@link makeFormatterStandardSchemaV1} — creates a - * `Formatter` + * @see {@link makeFormatterStandardSchemaV1} — creates a `Formatter` * * @category Formatter * @since 4.0.0 @@ -929,10 +848,10 @@ export interface Formatter extends FormatterI {} /** * Callback type used to format {@link Leaf} issues into strings. * - * When to use: + * **When to use** * - * - Pass a custom `LeafHook` to {@link makeFormatterStandardSchemaV1} to - * override how terminal issues are rendered. + * Use when customizing how {@link makeFormatterStandardSchemaV1} renders + * terminal issues. * * @see {@link defaultLeafHook} — the built-in implementation * @see {@link Leaf} — the union of terminal issue types @@ -943,15 +862,13 @@ export interface Formatter extends FormatterI {} export type LeafHook = (issue: Leaf) => string /** - * The built-in {@link LeafHook} used by default formatters. + * Returns the built-in {@link LeafHook} used by default formatters. * - * When to use: + * **When to use** * - * - Use as-is when you only need to customise the {@link CheckHook} but want - * the default leaf rendering. - * - Reference as a starting point for custom `LeafHook` implementations. + * Use as the default leaf renderer when customizing only the {@link CheckHook}. * - * Behaviour: + * **Details** * * - Checks for a `message` annotation first; returns it if present. * - Otherwise generates a default message per `_tag`: @@ -1000,12 +917,12 @@ export const defaultLeafHook: LeafHook = (issue): string => { /** * Callback type used to format {@link Filter} issues into strings. * - * When to use: + * **When to use** * - * - Pass a custom `CheckHook` to {@link makeFormatterStandardSchemaV1} to - * override how filter failures are rendered. + * Use when customizing how {@link makeFormatterStandardSchemaV1} renders + * filter failures. * - * Behaviour: + * **Details** * * - Returns `string` to override the message, or `undefined` to fall back to * the default formatting. @@ -1019,14 +936,13 @@ export const defaultLeafHook: LeafHook = (issue): string => { export type CheckHook = (issue: Filter) => string | undefined /** - * The built-in {@link CheckHook} used by default formatters. + * Returns the built-in {@link CheckHook} used by default formatters. * - * When to use: + * **When to use** * - * - Use as-is when you only need to customise the {@link LeafHook} but want - * the default filter rendering. + * Use as the default filter renderer when customizing only the {@link LeafHook}. * - * Behaviour: + * **Details** * * - Looks for a `message` annotation on the inner issue first, then on the * filter itself. @@ -1046,14 +962,13 @@ export const defaultCheckHook: CheckHook = (issue): string | undefined => { /** * Creates a {@link Formatter} that produces a `StandardSchemaV1.FailureResult`. * - * When to use: + * **When to use** * - * - Integrate with libraries that consume the - * [Standard Schema V1](https://github.com/standard-schema/standard-schema) - * error format. - * - Customise error rendering by providing `leafHook` and/or `checkHook`. + * Use when you need schema parse errors in + * [Standard Schema V1](https://github.com/standard-schema/standard-schema) + * format, optionally customizing leaf or check issue rendering. * - * Behaviour: + * **Details** * * - Returns a `Formatter`. * - Each leaf issue is flattened into `{ message, path }` entries. @@ -1138,7 +1053,7 @@ function toDefaultIssues( } } -function formatCheck(check: AST.Check): string { +function formatCheck(check: SchemaAST.Check): string { const expected = check.annotations?.expected if (typeof expected === "string") return expected @@ -1154,13 +1069,14 @@ function formatCheck(check: AST.Check): string { * Creates a {@link Formatter} that converts an {@link Issue} into a * human-readable multi-line string. * - * When to use: + * **When to use** + * + * Use when you need to format a `SchemaIssue.Issue` as error messages for + * logging, CLI output, or developer-facing diagnostics. * - * - Produce error messages for logging, CLI output, or developer-facing - * diagnostics. - * - This is the default formatter used by `Issue.toString()`. + * **Details** * - * Behaviour: + * This is the default formatter used by `SchemaIssue.toString()`. * * - Flattens the issue tree into `{ message, path }` entries using * {@link defaultLeafHook} and {@link defaultCheckHook}. diff --git a/.opencode/node_modules/effect/src/SchemaParser.ts b/.opencode/node_modules/effect/src/SchemaParser.ts index cc67402a51596278980f3e213265434215453dac..ac029e68d28640a346ba392b5c2b85f56ece17ce 100644 --- a/.opencode/node_modules/effect/src/SchemaParser.ts +++ b/.opencode/node_modules/effect/src/SchemaParser.ts @@ -1,4 +1,13 @@ /** + * Runs schemas against real values. + * + * Schema parsers construct values from schema input, check whether a value + * matches a schema, decode encoded input, and encode decoded values back to + * their external form. This module exposes those operations through several + * result styles, including `Effect`, `Promise`, `Exit`, `Option`, `Result`, and + * synchronous functions that throw. It also contains the lower-level runner that + * walks a schema AST and reports schema failures as `SchemaIssue.Issue` values. + * * @since 4.0.0 */ import * as Arr from "./Array.ts" @@ -6,22 +15,21 @@ import * as Cause from "./Cause.ts" import * as Effect from "./Effect.ts" import * as Exit from "./Exit.ts" import { identity, memoize } from "./Function.ts" -import * as InternalAnnotations from "./internal/schema/annotations.ts" import * as Option from "./Option.ts" import * as Predicate from "./Predicate.ts" import * as Result from "./Result.ts" import type * as Schema from "./Schema.ts" -import * as AST from "./SchemaAST.ts" -import * as Issue from "./SchemaIssue.ts" +import * as SchemaAST from "./SchemaAST.ts" +import * as SchemaIssue from "./SchemaIssue.ts" -const recurDefaults = memoize((ast: AST.AST): AST.AST => { +const recurDefaults = memoize((ast: SchemaAST.AST): SchemaAST.AST => { switch (ast._tag) { case "Declaration": { - const getLink = ast.annotations?.[AST.ClassTypeId] + const getLink = ast.annotations?.[SchemaAST.ClassTypeId] if (Predicate.isFunction(getLink)) { const link = getLink(ast.typeParameters) const to = recurDefaults(link.to) - return AST.replaceEncoding(ast, to === link.to ? [link] : [new AST.Link(to, link.transformation)]) + return SchemaAST.replaceEncoding(ast, to === link.to ? [link] : [new SchemaAST.Link(to, link.transformation)]) } return ast } @@ -30,7 +38,7 @@ const recurDefaults = memoize((ast: AST.AST): AST.AST => { return ast.recur((ast) => { const defaultValue = ast.context?.defaultValue if (defaultValue) { - return AST.replaceEncoding(recurDefaults(ast), defaultValue) + return SchemaAST.replaceEncoding(recurDefaults(ast), defaultValue) } return recurDefaults(ast) }) @@ -42,13 +50,26 @@ const recurDefaults = memoize((ast: AST.AST): AST.AST => { }) /** - * @category Constructing + * Creates an effectful maker for the schema's decoded type side. + * + * **When to use** + * + * Use to construct decoded schema values in `Effect` while preserving + * construction failures as `SchemaIssue.Issue` values in the error channel. + * + * **Details** + * + * The returned function accepts constructor input, applies constructor defaults, + * runs type-side validation unless checks are disabled, and fails with a + * `SchemaIssue.Issue` when construction fails. + * + * @category constructors * @since 4.0.0 */ export function makeEffect(schema: S) { - const ast = recurDefaults(AST.toType(schema.ast)) + const ast = recurDefaults(SchemaAST.toType(schema.ast)) const parser = run(ast) - return (input: S["~type.make.in"], options?: Schema.MakeOptions): Effect.Effect => { + return (input: S["~type.make.in"], options?: Schema.MakeOptions): Effect.Effect => { return parser( input, options?.disableChecks @@ -59,7 +80,15 @@ export function makeEffect(schema: S) { } /** - * @category Constructing + * Creates a synchronous maker that returns `Option.some` with the constructed + * value on success, or `Option.none` when construction fails. + * + * **When to use** + * + * Use when you need to validate schema constructor input and only care whether + * construction succeeds, without exposing `SchemaIssue.Issue` details. + * + * @category constructors * @since 4.0.0 */ export function makeOption(schema: S) { @@ -70,10 +99,22 @@ export function makeOption(schema: S) { } /** - * @category Constructing + * Creates a synchronous maker for the schema's decoded type side. + * + * **When to use** + * + * Use to construct decoded schema values synchronously when invalid input + * should throw an `Error` whose cause is `SchemaIssue.Issue`. + * + * **Details** + * + * The returned function constructs a value from constructor input and throws an + * `Error` with the `SchemaIssue.Issue` in its `cause` when construction fails. + * + * @category constructors * @since 4.0.0 */ -export function makeUnsafe(schema: S) { +export function make(schema: S) { const parser = makeEffect(schema) return (input: S["~type.make.in"], options?: Schema.MakeOptions): S["Type"] => { return Effect.runSync( @@ -86,25 +127,38 @@ export function makeUnsafe(schema: S) { } /** + * Creates a type guard that checks whether an input satisfies the schema's decoded + * type side. + * + * **When to use** + * + * Use to build a type guard for checking the decoded side of a schema without + * exposing issue details. + * + * **Details** + * + * The guard returns `true` on successful validation and `false` on failure, without + * exposing issue details. + * * @category Asserting - * @since 4.0.0 + * @since 3.10.0 */ export function is(schema: Schema.Schema): (input: I) => input is I & T { return _is(schema.ast) } /** @internal */ -export function _is(ast: AST.AST) { - const parser = asExit(run(AST.toType(ast))) +export function _is(ast: SchemaAST.AST) { + const parser = asExit(run(SchemaAST.toType(ast))) return (input: I): input is I & T => { - return Exit.isSuccess(parser(input, AST.defaultParseOptions)) + return Exit.isSuccess(parser(input, SchemaAST.defaultParseOptions)) } } /** @internal */ -export function _issue(ast: AST.AST) { +export function _issue(ast: SchemaAST.AST) { const parser = run(ast) - return (input: unknown, options: AST.ParseOptions): Issue.Issue | undefined => { + return (input: unknown, options: SchemaAST.ParseOptions): SchemaIssue.Issue | undefined => { return Effect.runSync(Effect.matchEager(parser(input, options), { onSuccess: () => undefined, onFailure: identity @@ -113,278 +167,672 @@ export function _issue(ast: AST.AST) { } /** + * Asserts that an input satisfies the schema's decoded type side. + * + * **When to use** + * + * Use to assert that an input satisfies the decoded side of a schema, throwing + * an `Error` whose cause is `SchemaIssue.Issue` when validation fails. + * + * **Details** + * + * The assertion returns normally when validation succeeds and throws when the + * input does not satisfy the schema. + * * @category Asserting * @since 4.0.0 */ -export function asserts(schema: Schema.Schema) { - const parser = asExit(run(AST.toType(schema.ast))) - return (input: I): asserts input is I & T => { - const exit = parser(input, AST.defaultParseOptions) - if (Exit.isFailure(exit)) { - const issue = Cause.findError(exit.cause) - if (Result.isFailure(issue)) { - throw Cause.squash(issue.failure) - } - throw new Error(issue.success.toString(), { cause: issue.success }) +export function asserts(schema: S, input: I): asserts input is I & S["Type"] { + const parser = asExit(run(SchemaAST.toType(schema.ast))) + const exit = parser(input, SchemaAST.defaultParseOptions) + if (Exit.isFailure(exit)) { + const issue = Cause.findError(exit.cause) + if (Result.isFailure(issue)) { + throw Cause.squash(issue.failure) } + throw new Error(issue.success.toString(), { cause: issue.success }) } } /** - * @category Decoding + * Creates an effectful decoder for `unknown` input. + * + * **When to use** + * + * Use when you need to decode untyped boundary input in an `Effect` whose + * failure channel is `SchemaIssue.Issue`, while preserving transformations + * and service requirements. + * + * **Details** + * + * The returned function succeeds with the schema's decoded `Type` or fails with a + * `SchemaIssue.Issue`. Decoding service requirements are preserved in the returned + * `Effect`. Parse options may be provided when creating the decoder and overridden + * when applying it. + * + * @see {@link decodeEffect} for input already typed as the schema's `Encoded` type + * + * @category decoding * @since 4.0.0 */ export function decodeUnknownEffect( - schema: S -): (input: unknown, options?: AST.ParseOptions) => Effect.Effect { - return run(schema.ast) + schema: S, + options?: SchemaAST.ParseOptions +): ( + input: unknown, + options?: SchemaAST.ParseOptions +) => Effect.Effect { + const parser = run(schema.ast) + return options === undefined + ? parser + : (input, overrideOptions) => parser(input, mergeParseOptions(options, overrideOptions)) } /** - * @category Decoding + * Creates an effectful decoder for input already typed as the schema's `Encoded` + * type. + * + * **When to use** + * + * Use when you already have input typed as the schema's `Encoded` type and + * need an `Effect` whose failure channel is `SchemaIssue.Issue`, while + * preserving decoding service requirements. + * + * **Details** + * + * The returned function succeeds with the decoded `Type` or fails with a + * `SchemaIssue.Issue`, preserving any decoding service requirements in the + * returned `Effect`. + * + * @see {@link decodeUnknownEffect} for untyped boundary input + * @see {@link encodeEffect} for the opposite direction + * + * @category decoding * @since 4.0.0 */ export const decodeEffect: ( - schema: S -) => (input: S["Encoded"], options?: AST.ParseOptions) => Effect.Effect = - decodeUnknownEffect + schema: S, + options?: SchemaAST.ParseOptions +) => ( + input: S["Encoded"], + options?: SchemaAST.ParseOptions +) => Effect.Effect = decodeUnknownEffect /** - * @category Decoding - * @since 4.0.0 + * Creates a Promise-based decoder for `unknown` input. + * + * **When to use** + * + * Use when you need to decode untyped input with a service-free schema and + * return a JavaScript `Promise` that rejects with `SchemaIssue.Issue`. + * + * **Details** + * + * The returned function resolves with the decoded `Type` on success and rejects + * with a `SchemaIssue.Issue` on decoding failure. + * + * @see {@link decodePromise} for input already typed as the schema's `Encoded` type + * @see {@link decodeUnknownEffect} for schemas that require decoding services or when failures should remain in `Effect` + * + * @category decoding + * @since 3.10.0 */ export function decodeUnknownPromise>( - schema: S -): (input: unknown, options?: AST.ParseOptions) => Promise { - return asPromise(decodeUnknownEffect(schema)) + schema: S, + options?: SchemaAST.ParseOptions +): (input: unknown, options?: SchemaAST.ParseOptions) => Promise { + return asPromise(decodeUnknownEffect(schema, options)) } /** - * @category Decoding - * @since 4.0.0 + * Creates a Promise-based decoder for input already typed as the schema's + * `Encoded` type. + * + * **When to use** + * + * Use when you already have input typed as the schema's `Encoded` type and need + * decoding to return a JavaScript `Promise` that rejects with `SchemaIssue.Issue`. + * + * **Details** + * + * The returned function resolves with the decoded `Type` on success and rejects + * with a `SchemaIssue.Issue` on decoding failure. + * + * @see {@link decodeUnknownPromise} for untyped input returning a JavaScript `Promise` + * @see {@link decodeEffect} for preserving decoding services and failures in `Effect` + * + * @category decoding + * @since 3.10.0 */ export function decodePromise>( - schema: S -): (input: S["Encoded"], options?: AST.ParseOptions) => Promise { - return asPromise(decodeEffect(schema)) + schema: S, + options?: SchemaAST.ParseOptions +): (input: S["Encoded"], options?: SchemaAST.ParseOptions) => Promise { + return asPromise(decodeEffect(schema, options)) } /** - * @category Decoding + * Creates a synchronous decoder for `unknown` input that reports failure safely + * as an `Exit`. + * + * **When to use** + * + * Use when you need to decode unknown input synchronously into an `Exit` whose + * failure contains `SchemaIssue.Issue`. + * + * **Details** + * + * The returned function produces `Exit.Success` with the decoded `Type`. + * Schema issues are represented by an `Exit.Failure` cause containing a + * `SchemaIssue.Issue`. + * + * **Gotchas** + * + * Because this adapter runs synchronously, async decoding work can produce an + * `Exit.Failure` with a defect cause. + * + * @see {@link decodeExit} for input already typed as the schema's `Encoded` type + * @see {@link decodeUnknownEffect} for preserving decoding services and failures in `Effect` + * @see {@link decodeUnknownResult} for returning schema issues as data + * @see {@link decodeUnknownSync} for throwing on decoding failure + * + * @category decoding * @since 4.0.0 */ export function decodeUnknownExit>( - schema: S -): (input: unknown, options?: AST.ParseOptions) => Exit.Exit { - return asExit(decodeUnknownEffect(schema)) + schema: S, + options?: SchemaAST.ParseOptions +): (input: unknown, options?: SchemaAST.ParseOptions) => Exit.Exit { + return asExit(decodeUnknownEffect(schema, options)) } /** - * @category Decoding + * Creates a synchronous decoder for input already typed as the schema's `Encoded` + * type, reporting failure safely as an `Exit`. + * + * **When to use** + * + * Use when you need synchronous decoding of already typed `Encoded` input into + * an `Exit` whose failure contains `SchemaIssue.Issue`. + * + * **Details** + * + * The returned function produces `Exit.Success` with the decoded `Type` or + * `Exit.Failure` with a `SchemaIssue.Issue`. + * + * @see {@link decodeUnknownExit} for untyped input with the same `Exit` result shape + * @see {@link decodeEffect} for preserving decoding services and failures in `Effect` + * + * @category decoding * @since 4.0.0 */ export const decodeExit: >( - schema: S -) => (input: S["Encoded"], options?: AST.ParseOptions) => Exit.Exit = decodeUnknownExit + schema: S, + options?: SchemaAST.ParseOptions +) => (input: S["Encoded"], options?: SchemaAST.ParseOptions) => Exit.Exit = + decodeUnknownExit -/** - * @category Decoding - * @since 4.0.0 - */ +/** @internal */ export function decodeUnknownOption>( - schema: S -): (input: unknown, options?: AST.ParseOptions) => Option.Option { - return asOption(decodeUnknownEffect(schema)) + schema: S, + options?: SchemaAST.ParseOptions +): (input: unknown, options?: SchemaAST.ParseOptions) => Option.Option { + return asOption(decodeUnknownEffect(schema, options)) } -/** - * @category Decoding - * @since 4.0.0 - */ +/** @internal */ export const decodeOption: >( - schema: S -) => (input: S["Encoded"], options?: AST.ParseOptions) => Option.Option = decodeUnknownOption + schema: S, + options?: SchemaAST.ParseOptions +) => (input: S["Encoded"], options?: SchemaAST.ParseOptions) => Option.Option = decodeUnknownOption /** - * @category Decoding + * Creates a decoder for `unknown` input that reports failure safely as a + * `Result`. + * + * **When to use** + * + * Use when decoding untyped boundary input and you want `SchemaIssue.Issue` + * failures returned as data in a `Result`. + * + * **Details** + * + * The returned function produces `Result.succeed` with the decoded `Type` on + * success or `Result.fail` with a `SchemaIssue.Issue` on decoding failure. + * + * **Gotchas** + * + * This adapter runs synchronously. Schema issues become `Result.fail`, but async + * decoding or defects can still throw. + * + * @see {@link decodeResult} for input already typed as the schema's `Encoded` type + * @see {@link decodeUnknownEffect} for effectful or service-requiring decoding + * + * @category decoding * @since 4.0.0 */ export function decodeUnknownResult>( - schema: S -): (input: unknown, options?: AST.ParseOptions) => Result.Result { - return asResult(decodeUnknownEffect(schema)) + schema: S, + options?: SchemaAST.ParseOptions +): (input: unknown, options?: SchemaAST.ParseOptions) => Result.Result { + return asResult(decodeUnknownEffect(schema, options)) } /** - * @category Decoding + * Creates a decoder for input already typed as the schema's `Encoded` type, + * reporting failure safely as a `Result`. + * + * **When to use** + * + * Use when you already have input typed as the schema's `Encoded` type and want + * schema decoding failures represented as `Result.fail` with `SchemaIssue.Issue`. + * + * **Details** + * + * The returned function produces `Result.succeed` with the decoded `Type` on + * success or `Result.fail` with a `SchemaIssue.Issue` on decoding failure. + * + * **Gotchas** + * + * This synchronous adapter returns `Result.fail` for schema issues, but async + * decoding or other non-schema failures can still throw. + * + * @see {@link decodeUnknownResult} for untyped input with the same `Result` shape + * @see {@link decodeEffect} for effectful or service-requiring decoding + * + * @category decoding * @since 4.0.0 */ export const decodeResult: >( - schema: S -) => (input: S["Encoded"], options?: AST.ParseOptions) => Result.Result = decodeUnknownResult + schema: S, + options?: SchemaAST.ParseOptions +) => (input: S["Encoded"], options?: SchemaAST.ParseOptions) => Result.Result = + decodeUnknownResult /** - * @category Decoding - * @since 4.0.0 + * Creates a synchronous decoder for `unknown` input. + * + * **When to use** + * + * Use to decode untrusted or dynamically typed input at a synchronous boundary + * where invalid data should throw an `Error` whose cause is `SchemaIssue.Issue`. + * + * **Details** + * + * The returned function returns the decoded `Type` on success and throws an + * `Error` with the `SchemaIssue.Issue` in its `cause` on decoding failure. + * + * @see {@link decodeSync} for input already typed as the schema's `Encoded` type + * @see {@link decodeUnknownEffect} for preserving decoding failures in `Effect` + * @see {@link decodeUnknownResult} for returning schema issues as data + * + * @category decoding + * @since 3.10.0 */ export function decodeUnknownSync>( - schema: S -): (input: unknown, options?: AST.ParseOptions) => S["Type"] { - return asSync(decodeUnknownEffect(schema)) + schema: S, + options?: SchemaAST.ParseOptions +): (input: unknown, options?: SchemaAST.ParseOptions) => S["Type"] { + return asSync(decodeUnknownEffect(schema, options)) } /** - * @category Decoding - * @since 4.0.0 + * Creates a synchronous decoder for input already typed as the schema's `Encoded` + * type. + * + * **When to use** + * + * Use to decode values already typed as the schema's `Encoded` input when + * decoding failure should throw an `Error` whose cause is `SchemaIssue.Issue`. + * + * **Details** + * + * The returned function returns the decoded `Type` on success and throws an + * `Error` with the `SchemaIssue.Issue` in its `cause` on decoding failure. + * + * @see {@link decodeUnknownSync} for untrusted or dynamically typed input + * @see {@link decodeResult} for returning schema issues as data + * @see {@link decodeEffect} for preserving decoding failures in `Effect` + * + * @category decoding + * @since 3.10.0 */ export const decodeSync: >( - schema: S -) => (input: S["Encoded"], options?: AST.ParseOptions) => S["Type"] = decodeUnknownSync + schema: S, + options?: SchemaAST.ParseOptions +) => (input: S["Encoded"], options?: SchemaAST.ParseOptions) => S["Type"] = decodeUnknownSync /** - * @category Encoding + * Creates an effectful encoder for `unknown` input. + * + * **When to use** + * + * Use when you need to encode untyped boundary input in an `Effect` whose + * failure channel is `SchemaIssue.Issue`, while preserving service + * requirements. + * + * **Details** + * + * The returned function succeeds with the schema's `Encoded` value or fails with a + * `SchemaIssue.Issue`. Encoding service requirements are preserved in the returned + * `Effect`. Parse options may be provided when creating the encoder and overridden + * when applying it. + * + * @see {@link encodeEffect} for the typed-input variant when the value is already typed as the schema's decoded `Type` + * + * @category encoding * @since 4.0.0 */ export function encodeUnknownEffect( - schema: S -): (input: unknown, options?: AST.ParseOptions) => Effect.Effect { - return run(AST.flip(schema.ast)) + schema: S, + options?: SchemaAST.ParseOptions +): ( + input: unknown, + options?: SchemaAST.ParseOptions +) => Effect.Effect { + const parser = run(SchemaAST.flip(schema.ast)) + return options === undefined + ? parser + : (input, overrideOptions) => parser(input, mergeParseOptions(options, overrideOptions)) } /** - * @category Encoding + * Creates an effectful encoder for input already typed as the schema's decoded + * `Type`. + * + * **When to use** + * + * Use when you need to encode values already typed as the schema's decoded + * `Type` in an `Effect` whose failure channel is `SchemaIssue.Issue`, while + * preserving service requirements. + * + * **Details** + * + * The returned function succeeds with the schema's `Encoded` value or fails with a + * `SchemaIssue.Issue`, preserving any encoding service requirements in the + * returned `Effect`. + * + * @see {@link encodeUnknownEffect} for encoding unknown input before the value is statically typed as the schema's `Type` + * + * @category encoding * @since 4.0.0 */ export const encodeEffect: ( - schema: S -) => (input: S["Type"], options?: AST.ParseOptions) => Effect.Effect = - encodeUnknownEffect + schema: S, + options?: SchemaAST.ParseOptions +) => ( + input: S["Type"], + options?: SchemaAST.ParseOptions +) => Effect.Effect = encodeUnknownEffect /** - * @category Encoding - * @since 4.0.0 + * Creates a Promise-based encoder for `unknown` input. + * + * **When to use** + * + * Use when you need to encode untrusted or dynamically typed values with a + * service-free schema and return a JavaScript `Promise` that rejects with + * `SchemaIssue.Issue`. + * + * **Details** + * + * The returned function resolves with the schema's `Encoded` value on success and + * rejects with a `SchemaIssue.Issue` on encoding failure. + * + * @see {@link encodePromise} for input already typed as the schema's decoded `Type` + * @see {@link encodeUnknownEffect} for schemas that require encoding services or when failures should remain in `Effect` + * + * @category encoding + * @since 3.10.0 */ export const encodeUnknownPromise = >( - schema: S -): (input: unknown, options?: AST.ParseOptions) => Promise => asPromise(encodeUnknownEffect(schema)) + schema: S, + options?: SchemaAST.ParseOptions +): (input: unknown, options?: SchemaAST.ParseOptions) => Promise => + asPromise(encodeUnknownEffect(schema, options)) /** - * @category Encoding - * @since 4.0.0 + * Creates a Promise-based encoder for input already typed as the schema's decoded + * `Type`. + * + * **When to use** + * + * Use when you already have values typed as the schema's decoded `Type` and + * need encoding to return a JavaScript `Promise` that rejects with + * `SchemaIssue.Issue`. + * + * **Details** + * + * The returned function resolves with the schema's `Encoded` value on success and + * rejects with a `SchemaIssue.Issue` on encoding failure. + * + * @see {@link encodeUnknownPromise} for encoding untyped input + * @see {@link encodeEffect} for effectful encoding or schemas with encoding service requirements + * + * @category encoding + * @since 3.10.0 */ export const encodePromise: >( - schema: S -) => (input: S["Type"], options?: AST.ParseOptions) => Promise = encodeUnknownPromise + schema: S, + options?: SchemaAST.ParseOptions +) => (input: S["Type"], options?: SchemaAST.ParseOptions) => Promise = encodeUnknownPromise /** - * @category Encoding + * Creates a synchronous encoder for `unknown` input that reports failure safely + * as an `Exit`. + * + * **When to use** + * + * Use when you need synchronous encoding of unknown input into an `Exit` whose + * failure contains `SchemaIssue.Issue`. + * + * **Details** + * + * The returned function produces `Exit.Success` with the schema's `Encoded` value + * or `Exit.Failure` with a `SchemaIssue.Issue`. + * + * @see {@link encodeExit} for input already typed as the schema's decoded `Type` + * @see {@link encodeUnknownEffect} for effectful encoding that preserves service requirements + * + * @category encoding * @since 4.0.0 */ export function encodeUnknownExit>( - schema: S -): (input: unknown, options?: AST.ParseOptions) => Exit.Exit { - return asExit(encodeUnknownEffect(schema)) + schema: S, + options?: SchemaAST.ParseOptions +): (input: unknown, options?: SchemaAST.ParseOptions) => Exit.Exit { + return asExit(encodeUnknownEffect(schema, options)) } /** - * @category Encoding + * Creates a synchronous encoder for input already typed as the schema's decoded + * `Type`, reporting failure safely as an `Exit`. + * + * **When to use** + * + * Use when you need synchronous encoding of already typed schema values into + * an `Exit` whose failure contains `SchemaIssue.Issue`. + * + * **Details** + * + * The returned function produces `Exit.Success` with the schema's `Encoded` value + * or `Exit.Failure` with a `SchemaIssue.Issue`. + * + * @see {@link encodeUnknownExit} for unknown input with the same `Exit` result shape + * @see {@link encodeEffect} for effectful encoding that preserves service requirements + * + * @category encoding * @since 4.0.0 */ export const encodeExit: >( - schema: S -) => (input: S["Type"], options?: AST.ParseOptions) => Exit.Exit = encodeUnknownExit + schema: S, + options?: SchemaAST.ParseOptions +) => (input: S["Type"], options?: SchemaAST.ParseOptions) => Exit.Exit = + encodeUnknownExit -/** - * @category Encoding - * @since 4.0.0 - */ +/** @internal */ export function encodeUnknownOption>( - schema: S -): (input: unknown, options?: AST.ParseOptions) => Option.Option { - return asOption(encodeUnknownEffect(schema)) + schema: S, + options?: SchemaAST.ParseOptions +): (input: unknown, options?: SchemaAST.ParseOptions) => Option.Option { + return asOption(encodeUnknownEffect(schema, options)) } -/** - * @category Encoding - * @since 4.0.0 - */ +/** @internal */ export const encodeOption: >( - schema: S -) => (input: S["Type"], options?: AST.ParseOptions) => Option.Option = encodeUnknownOption + schema: S, + options?: SchemaAST.ParseOptions +) => (input: S["Type"], options?: SchemaAST.ParseOptions) => Option.Option = encodeUnknownOption /** - * @category Encoding + * Creates an encoder for `unknown` input that reports failure safely as a + * `Result`. + * + * **When to use** + * + * Use when encoding values from an unknown or dynamically typed boundary + * synchronously, and you want `SchemaIssue.Issue` failures returned as `Result` + * data. + * + * **Details** + * + * The returned function produces `Result.succeed` with the schema's `Encoded` + * value on success or `Result.fail` with a `SchemaIssue.Issue` on encoding + * failure. + * + * @see {@link encodeResult} for input already typed as the schema's decoded `Type` + * @see {@link encodeUnknownEffect} for effectful encoding, including schemas with encoding service requirements + * + * @category encoding * @since 4.0.0 */ export function encodeUnknownResult>( - schema: S -): (input: unknown, options?: AST.ParseOptions) => Result.Result { - return asResult(encodeUnknownEffect(schema)) + schema: S, + options?: SchemaAST.ParseOptions +): (input: unknown, options?: SchemaAST.ParseOptions) => Result.Result { + return asResult(encodeUnknownEffect(schema, options)) } /** - * @category Encoding + * Creates an encoder for input already typed as the schema's decoded `Type`, + * reporting failure safely as a `Result`. + * + * **When to use** + * + * Use when you already have input typed as the schema's decoded `Type` and want + * encoding failures returned as `Result.fail` with `SchemaIssue.Issue`. + * + * **Details** + * + * The returned function produces `Result.succeed` with the schema's `Encoded` + * value on success or `Result.fail` with a `SchemaIssue.Issue` on encoding + * failure. + * + * @see {@link encodeUnknownResult} for the same `Result` shape when the input is not already typed + * + * @category encoding * @since 4.0.0 */ export const encodeResult: >( - schema: S -) => (input: S["Type"], options?: AST.ParseOptions) => Result.Result = encodeUnknownResult + schema: S, + options?: SchemaAST.ParseOptions +) => (input: S["Type"], options?: SchemaAST.ParseOptions) => Result.Result = + encodeUnknownResult /** - * @category Encoding - * @since 4.0.0 + * Creates a synchronous encoder for `unknown` input. + * + * **When to use** + * + * Use when you need to encode values from untyped input in synchronous code and + * want encoding failures to throw an `Error` whose cause is `SchemaIssue.Issue`. + * + * **Details** + * + * The returned function returns the schema's `Encoded` value on success and throws + * an `Error` with the `SchemaIssue.Issue` in its `cause` on encoding failure. + * + * @see {@link encodeSync} for input already typed as the schema's decoded `Type` + * @see {@link encodeUnknownEffect} for effectful encoding that preserves service requirements + * + * @category encoding + * @since 3.10.0 */ export function encodeUnknownSync>( - schema: S -): (input: unknown, options?: AST.ParseOptions) => S["Encoded"] { - return asSync(encodeUnknownEffect(schema)) + schema: S, + options?: SchemaAST.ParseOptions +): (input: unknown, options?: SchemaAST.ParseOptions) => S["Encoded"] { + return asSync(encodeUnknownEffect(schema, options)) } /** - * @category Encoding - * @since 4.0.0 + * Creates a synchronous encoder for input already typed as the schema's decoded + * `Type`. + * + * **When to use** + * + * Use to encode already typed schema values synchronously when encoding failure + * should throw an `Error` whose cause is `SchemaIssue.Issue`. + * + * **Details** + * + * The returned function returns the schema's `Encoded` value on success and throws + * an `Error` with the `SchemaIssue.Issue` in its `cause` on encoding failure. + * + * @see {@link encodeUnknownSync} for unknown input with the same throwing boundary + * @see {@link encodeResult} for returning schema issues as data + * @see {@link encodeEffect} for effectful encoding that preserves service requirements + * + * @category encoding + * @since 3.10.0 */ export const encodeSync: >( - schema: S -) => (input: S["Type"], options?: AST.ParseOptions) => S["Encoded"] = encodeUnknownSync + schema: S, + options?: SchemaAST.ParseOptions +) => (input: S["Type"], options?: SchemaAST.ParseOptions) => S["Encoded"] = encodeUnknownSync + +const mergeParseOptions = ( + options: SchemaAST.ParseOptions, + overrideOptions: SchemaAST.ParseOptions | undefined +): SchemaAST.ParseOptions => overrideOptions === undefined ? options : { ...options, ...overrideOptions } /** @internal */ -export function run(ast: AST.AST) { +export function run(ast: SchemaAST.AST) { const parser = recur(ast) - return (input: unknown, options?: AST.ParseOptions): Effect.Effect => - Effect.flatMapEager(parser(Option.some(input), options ?? AST.defaultParseOptions), (oa) => { + return (input: unknown, options?: SchemaAST.ParseOptions): Effect.Effect => + Effect.flatMapEager(parser(Option.some(input), options ?? SchemaAST.defaultParseOptions), (oa) => { if (oa._tag === "None") { - return Effect.fail(new Issue.InvalidValue(oa)) + return Effect.fail(new SchemaIssue.InvalidValue(oa)) } return Effect.succeed(oa.value as T) }) } function asPromise( - parser: (input: E, options?: AST.ParseOptions) => Effect.Effect -): (input: E, options?: AST.ParseOptions) => Promise { - return (input: E, options?: AST.ParseOptions) => Effect.runPromise(parser(input, options)) + parser: (input: E, options?: SchemaAST.ParseOptions) => Effect.Effect +): (input: E, options?: SchemaAST.ParseOptions) => Promise { + return (input: E, options?: SchemaAST.ParseOptions) => Effect.runPromise(parser(input, options)) } function asExit( - parser: (input: E, options?: AST.ParseOptions) => Effect.Effect -): (input: E, options?: AST.ParseOptions) => Exit.Exit { - return (input: E, options?: AST.ParseOptions) => Effect.runSyncExit(parser(input, options) as any) + parser: (input: E, options?: SchemaAST.ParseOptions) => Effect.Effect +): (input: E, options?: SchemaAST.ParseOptions) => Exit.Exit { + return (input: E, options?: SchemaAST.ParseOptions) => Effect.runSyncExit(parser(input, options) as any) } /** @internal */ export function asOption( - parser: (input: E, options?: AST.ParseOptions) => Effect.Effect -): (input: E, options?: AST.ParseOptions) => Option.Option { + parser: (input: E, options?: SchemaAST.ParseOptions) => Effect.Effect +): (input: E, options?: SchemaAST.ParseOptions) => Option.Option { const parserExit = asExit(parser) - return (input: E, options?: AST.ParseOptions) => Exit.getSuccess(parserExit(input, options)) + return (input: E, options?: SchemaAST.ParseOptions) => Exit.getSuccess(parserExit(input, options)) } function asResult( - parser: (input: E, options?: AST.ParseOptions) => Effect.Effect -): (input: E, options?: AST.ParseOptions) => Result.Result { + parser: (input: E, options?: SchemaAST.ParseOptions) => Effect.Effect +): (input: E, options?: SchemaAST.ParseOptions) => Result.Result { const parserExit = asExit(parser) - return (input: E, options?: AST.ParseOptions) => { + return (input: E, options?: SchemaAST.ParseOptions) => { const exit = parserExit(input, options) if (Exit.isSuccess(exit)) { return Result.succeed(exit.value) @@ -398,9 +846,9 @@ function asResult( } function asSync( - parser: (input: E, options?: AST.ParseOptions) => Effect.Effect -): (input: E, options?: AST.ParseOptions) => T { - return (input: E, options?: AST.ParseOptions) => + parser: (input: E, options?: SchemaAST.ParseOptions) => Effect.Effect +): (input: E, options?: SchemaAST.ParseOptions) => T { + return (input: E, options?: SchemaAST.ParseOptions) => Effect.runSync( Effect.mapErrorEager( parser(input, options), @@ -411,14 +859,20 @@ function asSync( /** @internal */ export interface Parser { - (input: Option.Option, options: AST.ParseOptions): Effect.Effect, Issue.Issue, any> + ( + input: Option.Option, + options: SchemaAST.ParseOptions + ): Effect.Effect, SchemaIssue.Issue, any> } const recur = memoize( - (ast: AST.AST): Parser => { + (ast: SchemaAST.AST): Parser => { let parser: Parser - const astOptions = InternalAnnotations.resolve(ast)?.["parseOptions"] - if (!ast.context && !ast.encoding && !ast.checks) { + const encodingChecks = SchemaAST.getEncodingChecks(ast) + const resolvedChecks = ast.checks ?? encodingChecks + const astOptions = (resolvedChecks ? resolvedChecks[resolvedChecks.length - 1].annotations : ast.annotations) + ?.["parseOptions"] + if (!ast.context && !ast.encoding && !ast.checks && !encodingChecks) { return (ou, options) => { parser ??= ast.getParser(recur) if (astOptions) { @@ -427,14 +881,14 @@ const recur = memoize( return parser(ou, options) } } - const isStructural = AST.isArrays(ast) || AST.isObjects(ast) || - (AST.isDeclaration(ast) && ast.typeParameters.length > 0) + const isStructural = SchemaAST.isArrays(ast) || SchemaAST.isObjects(ast) || + (SchemaAST.isDeclaration(ast) && ast.typeParameters.length > 0) return (ou, options) => { if (astOptions) { options = { ...options, ...astOptions } } const encoding = ast.encoding - let srou: Effect.Effect, Issue.Issue, unknown> | undefined + let srou: Effect.Effect, SchemaIssue.Issue, unknown> | undefined if (encoding) { const links = encoding const len = links.length @@ -450,28 +904,43 @@ const recur = memoize( srou = link.transformation.decode(srou, options) } } - srou = Effect.mapErrorEager(srou!, (issue) => new Issue.Encoding(ast, ou, issue)) + srou = Effect.mapErrorEager(srou!, (issue) => new SchemaIssue.Encoding(ast, ou, issue)) } parser ??= ast.getParser(recur) let sroa = srou ? Effect.flatMapEager(srou, (ou) => parser(ou, options)) : parser(ou, options) + if (encodingChecks && !options?.disableChecks) { + sroa = Effect.flatMapEager(sroa, (oa) => { + if (Option.isSome(ou) && Option.isSome(oa)) { + const issues: Array = [] + + SchemaAST.collectIssues(encodingChecks, ou.value, issues, ast, options) + + if (Arr.isArrayNonEmpty(issues)) { + return Effect.fail(new SchemaIssue.Composite(ast, ou, issues)) + } + } + return Effect.succeed(oa) + }) + } + if (ast.checks && !options?.disableChecks) { const checks = ast.checks if (options?.errors === "all" && isStructural && Option.isSome(ou)) { sroa = Effect.catchEager(sroa, (issue) => { - const issues: Array = [] - AST.collectIssues( - checks.filter((check) => check.annotations?.[AST.STRUCTURAL_ANNOTATION_KEY]), + const issues: Array = [] + SchemaAST.collectIssues( + checks.filter((check) => check.annotations?.[SchemaAST.STRUCTURAL_ANNOTATION_KEY]), ou.value, issues, ast, options ) - const out: Issue.Issue = Arr.isArrayNonEmpty(issues) + const out: SchemaIssue.Issue = Arr.isArrayNonEmpty(issues) ? issue._tag === "Composite" && issue.ast === ast - ? new Issue.Composite(ast, issue.actual, [...issue.issues, ...issues]) - : new Issue.Composite(ast, ou, [issue, ...issues]) + ? new SchemaIssue.Composite(ast, issue.actual, [...issue.issues, ...issues]) + : new SchemaIssue.Composite(ast, ou, [issue, ...issues]) : issue return Effect.fail(out) }) @@ -479,12 +948,12 @@ const recur = memoize( sroa = Effect.flatMapEager(sroa, (oa) => { if (Option.isSome(oa)) { const value = oa.value - const issues: Array = [] + const issues: Array = [] - AST.collectIssues(checks, value, issues, ast, options) + SchemaAST.collectIssues(checks, value, issues, ast, options) if (Arr.isArrayNonEmpty(issues)) { - return Effect.fail(new Issue.Composite(ast, oa, issues)) + return Effect.fail(new SchemaIssue.Composite(ast, oa, issues)) } } return Effect.succeed(oa) diff --git a/.opencode/node_modules/effect/src/SchemaRepresentation.ts b/.opencode/node_modules/effect/src/SchemaRepresentation.ts index 0267e77c95084be02e130bdbc0f6879efcc87011..b0f90fc574fce006355ec4c2e92172c8146dfa6f 100644 --- a/.opencode/node_modules/effect/src/SchemaRepresentation.ts +++ b/.opencode/node_modules/effect/src/SchemaRepresentation.ts @@ -1,88 +1,14 @@ /** - * Serializable intermediate representation (IR) of Effect Schema types. - * - * `SchemaRepresentation` sits between the internal `SchemaAST` and external - * formats (JSON Schema, generated TypeScript code, serialized JSON). A - * {@link Representation} is a discriminated union describing the *shape* of a - * schema — its types, checks, annotations, and references — in a form that - * can be round-tripped through JSON and used for code generation. - * - * ## Mental model - * - * - **Representation**: A tagged union (`_tag`) of all supported schema shapes: - * primitives, literals, objects, arrays, unions, declarations, references, - * and suspensions. - * - **Document**: A single {@link Representation} paired with a map of named - * {@link References} (analogous to JSON Schema `$defs`). - * - **MultiDocument**: Like `Document` but holds one or more representations - * sharing the same references. - * - **Check / Filter / FilterGroup**: Validation constraints (min length, - * pattern, integer, etc.) attached to types that support them. - * - **Meta types**: Typed metadata for checks on each category — e.g. - * {@link StringMeta}, {@link NumberMeta}, {@link ArraysMeta}. - * - **Reviver**: A callback used by {@link toSchema} and {@link toCodeDocument} - * to handle `Declaration` nodes (custom types like `Option`, `Date`, etc.). - * - **Code / CodeDocument**: Output of {@link toCodeDocument} — TypeScript - * source strings for runtime schemas and their type-level counterparts. - * - * ## Common tasks - * - * - Convert a Schema AST to a Document → {@link fromAST} - * - Convert multiple ASTs to a MultiDocument → {@link fromASTs} - * - Reconstruct a runtime Schema from a Document → {@link toSchema} - * - Convert a Document to JSON Schema → {@link toJsonSchemaDocument} - * - Convert a MultiDocument to JSON Schema → {@link toJsonSchemaMultiDocument} - * - Parse a JSON Schema document into a Document → {@link fromJsonSchemaDocument} - * - Parse a JSON Schema multi-document → {@link fromJsonSchemaMultiDocument} - * - Generate TypeScript code from a MultiDocument → {@link toCodeDocument} - * - Serialize/deserialize a Document as JSON → {@link DocumentFromJson} - * - Serialize/deserialize a MultiDocument as JSON → {@link MultiDocumentFromJson} - * - Wrap a Document as a MultiDocument → {@link toMultiDocument} - * - * ## Gotchas - * - * - `Declaration` nodes require a {@link Reviver} to reconstruct complex types - * (e.g. `Option`, `Date`). Without one, `toSchema` falls back to the - * declaration's `encodedSchema`. Use {@link toSchemaDefaultReviver} for - * built-in Effect types. - * - `Reference` nodes are resolved against the `references` map in the - * `Document`. An unresolvable `$ref` throws at runtime. - * - `Suspend` wraps a single `thunk` representation; it is used for recursive - * schemas. Circular references are handled by lazy resolution in - * {@link toSchema}. - * - The `$`-prefixed exports (e.g. {@link $Representation}, {@link $Document}) - * are Schema codecs for the representation types themselves — use them to - * validate or encode/decode representation data, not application data. - * - * ## Quickstart - * - * **Example** (Round-trip through JSON) + * Plain data structures for describing schemas in a serializable form. A + * `Representation` is not the original `Schema` object; it is a JSON-friendly + * description of the schema's types, fields, unions, checks, annotations, and + * references. * - * ```ts - * import { Schema, SchemaRepresentation } from "effect" - * - * const Person = Schema.Struct({ - * name: Schema.String, - * age: Schema.Int - * }) - * - * // Schema AST → Document - * const doc = SchemaRepresentation.fromAST(Person.ast) - * - * // Document → JSON Schema - * const jsonSchema = SchemaRepresentation.toJsonSchemaDocument(doc) - * - * // Document → runtime Schema - * const reconstructed = SchemaRepresentation.toSchema(doc) - * ``` - * - * ## See also - * - * - {@link Representation} — the core tagged union - * - {@link Document} — single-schema container - * - {@link fromAST} — entry point from Schema AST - * - {@link toSchema} — reconstruct a runtime Schema - * - {@link toCodeDocument} — generate TypeScript code + * This module defines the representation node types, document types, and + * codecs used to validate those documents. It can build representation + * documents from schema ASTs, turn representation documents back into schemas, + * convert them to and from JSON Schema documents, and generate TypeScript code + * artifacts for schema definitions. * * @since 4.0.0 */ @@ -96,27 +22,31 @@ import * as Option from "./Option.ts" import * as Predicate from "./Predicate.ts" import * as Rec from "./Record.ts" import * as Schema from "./Schema.ts" -import type * as AST from "./SchemaAST.ts" -import * as Getter from "./SchemaGetter.ts" +import type * as SchemaAST from "./SchemaAST.ts" +import * as SchemaGetter from "./SchemaGetter.ts" // ----------------------------------------------------------------------------- // specification // ----------------------------------------------------------------------------- /** - * A custom type declaration (e.g. `Date`, `Option`, `ReadonlySet`). + * A custom type declaration, such as `Date`, `Option`, or `ReadonlySet`. + * + * **When to use** + * + * Use when inspecting or transforming non-primitive schema types. + * + * **Details** * - * - Use when inspecting or transforming non-primitive schema types. - * - `typeParameters` holds the inner type arguments (e.g. the `A` in `Option`). - * - `encodedSchema` is the fallback representation when no {@link Reviver} - * recognizes this declaration. - * - `annotations.typeConstructor` identifies the declaration kind (e.g. - * `{ _tag: "effect/Option" }`). + * `typeParameters` holds the inner type arguments, such as the `A` in + * `Option`. `encodedSchema` is the fallback representation when no + * {@link Reviver} recognizes this declaration. `annotations.typeConstructor` + * identifies the declaration kind, such as `{ _tag: "effect/Option" }`. * * @see {@link Reviver} * @see {@link toSchemaDefaultReviver} * - * @category Model + * @category models * @since 4.0.0 */ export interface Declaration { @@ -128,14 +58,16 @@ export interface Declaration { } /** - * A lazily-resolved representation, used for recursive schemas. + * A lazily resolved representation used for recursive schemas. * - * - `thunk` points to the actual representation (possibly via a {@link Reference}). - * - `checks` is always empty on `Suspend` nodes. + * **Details** + * + * `thunk` points to the actual representation, possibly via a + * {@link Reference}. `checks` is always empty on `Suspend` nodes. * * @see {@link Reference} * - * @category Model + * @category models * @since 4.0.0 */ export interface Suspend { @@ -148,14 +80,25 @@ export interface Suspend { /** * A named reference to a definition in the {@link References} map. * - * - `$ref` is the key into `Document.references` or `MultiDocument.references`. - * - Resolved lazily by {@link toSchema} and {@link toCodeDocument}. - * - Throws at runtime if the key is not found in the references map. + * **When to use** + * + * Use when a representation should point to a named definition instead of + * embedding the definition inline. + * + * **Details** + * + * `$ref` is the key into `Document.references` or `MultiDocument.references`. + * References are resolved lazily by {@link toSchema} and + * {@link toCodeDocument}. + * + * **Gotchas** + * + * Resolution throws at runtime if the key is not found in the references map. * * @see {@link References} * @see {@link Document} * - * @category Model + * @category models * @since 4.0.0 */ export interface Reference { @@ -166,7 +109,7 @@ export interface Reference { /** * The `null` type. * - * @category Model + * @category models * @since 4.0.0 */ export interface Null { @@ -177,7 +120,7 @@ export interface Null { /** * The `undefined` type. * - * @category Model + * @category models * @since 4.0.0 */ export interface Undefined { @@ -188,7 +131,7 @@ export interface Undefined { /** * The `void` type. * - * @category Model + * @category models * @since 4.0.0 */ export interface Void { @@ -199,7 +142,7 @@ export interface Void { /** * The `never` type (no valid values). * - * @category Model + * @category models * @since 4.0.0 */ export interface Never { @@ -210,7 +153,7 @@ export interface Never { /** * The `unknown` type (any value accepted). * - * @category Model + * @category models * @since 4.0.0 */ export interface Unknown { @@ -221,7 +164,7 @@ export interface Unknown { /** * The `any` type. * - * @category Model + * @category models * @since 4.0.0 */ export interface Any { @@ -232,14 +175,17 @@ export interface Any { /** * The `string` type with optional validation checks. * - * - `checks` holds string-specific constraints (min/max length, pattern, UUID, etc.). - * - `contentMediaType` + `contentSchema` indicate the string contains - * encoded data (e.g. `"application/json"` with a nested schema). + * **Details** + * + * `checks` holds string-specific constraints, such as min/max length, pattern, + * and UUID checks. `contentMediaType` and `contentSchema` indicate that the + * string contains encoded data, such as `"application/json"` with a nested + * schema. * * @see {@link StringMeta} * @see {@link Check} * - * @category Model + * @category models * @since 4.0.0 */ export interface String { @@ -253,11 +199,14 @@ export interface String { /** * The `number` type with optional validation checks. * - * - `checks` holds number-specific constraints (int, finite, min, max, multipleOf, etc.). + * **Details** + * + * `checks` holds number-specific constraints, such as int, finite, min, max, + * multipleOf, and between checks. * * @see {@link NumberMeta} * - * @category Model + * @category models * @since 4.0.0 */ export interface Number { @@ -269,7 +218,7 @@ export interface Number { /** * The `boolean` type. * - * @category Model + * @category models * @since 4.0.0 */ export interface Boolean { @@ -282,7 +231,7 @@ export interface Boolean { * * @see {@link BigIntMeta} * - * @category Model + * @category models * @since 4.0.0 */ export interface BigInt { @@ -294,7 +243,7 @@ export interface BigInt { /** * The `symbol` type. * - * @category Model + * @category models * @since 4.0.0 */ export interface Symbol { @@ -305,7 +254,7 @@ export interface Symbol { /** * A specific literal value (`string`, `number`, `boolean`, or `bigint`). * - * @category Model + * @category models * @since 4.0.0 */ export interface Literal { @@ -317,7 +266,7 @@ export interface Literal { /** * A specific unique `symbol` value. * - * @category Model + * @category models * @since 4.0.0 */ export interface UniqueSymbol { @@ -329,7 +278,7 @@ export interface UniqueSymbol { /** * The `object` keyword type (matches any non-primitive). * - * @category Model + * @category models * @since 4.0.0 */ export interface ObjectKeyword { @@ -340,7 +289,7 @@ export interface ObjectKeyword { /** * A TypeScript-style enum. Each entry is a `[name, value]` pair. * - * @category Model + * @category models * @since 4.0.0 */ export interface Enum { @@ -353,7 +302,7 @@ export interface Enum { * A template literal type composed of a sequence of parts (literals, strings, * numbers, etc.). * - * @category Model + * @category models * @since 4.0.0 */ export interface TemplateLiteral { @@ -365,16 +314,17 @@ export interface TemplateLiteral { /** * An array or tuple type. * - * - `elements` are the fixed positional elements (tuple prefix). Each may be - * optional. - * - `rest` are the variadic tail types. A single-element `rest` with no - * `elements` produces a plain `Array`. - * - `checks` holds array-specific constraints (minLength, maxLength, unique, etc.). + * **Details** + * + * `elements` are the fixed positional elements, or tuple prefix, and each may + * be optional. `rest` contains the variadic tail types; a single-element + * `rest` with no `elements` produces a plain `Array`. `checks` holds + * array-specific constraints, such as minLength, maxLength, and unique checks. * * @see {@link Element} * @see {@link ArraysMeta} * - * @category Model + * @category models * @since 4.0.0 */ export interface Arrays { @@ -388,12 +338,14 @@ export interface Arrays { /** * A positional element within an {@link Arrays} tuple. * - * - `isOptional` indicates whether this element can be absent. - * - `type` is the schema representation for this element's value. + * **Details** + * + * `isOptional` indicates whether this element can be absent. `type` is the + * schema representation for this element's value. * * @see {@link Arrays} * - * @category Model + * @category models * @since 4.0.0 */ export interface Element { @@ -405,15 +357,17 @@ export interface Element { /** * An object/struct type with named properties and optional index signatures. * - * - `propertySignatures` are the explicitly named fields. - * - `indexSignatures` define catch-all key/value types (like `Record`). - * - `checks` holds object-specific constraints (minProperties, maxProperties, etc.). + * **Details** + * + * `propertySignatures` are the explicitly named fields. `indexSignatures` + * define catch-all key/value types, such as `Record`. `checks` + * holds object-specific constraints, such as minProperties and maxProperties. * * @see {@link PropertySignature} * @see {@link IndexSignature} * @see {@link ObjectsMeta} * - * @category Model + * @category models * @since 4.0.0 */ export interface Objects { @@ -427,13 +381,15 @@ export interface Objects { /** * A named property within an {@link Objects} representation. * - * - `name` is the property key (string, number, or symbol). - * - `isOptional` indicates whether the key can be absent. - * - `isMutable` indicates whether the property is mutable (vs. readonly). + * **Details** + * + * `name` is the property key, which can be a string, number, or symbol. + * `isOptional` indicates whether the key can be absent. `isMutable` indicates + * whether the property is mutable rather than readonly. * * @see {@link Objects} * - * @category Model + * @category models * @since 4.0.0 */ export interface PropertySignature { @@ -445,14 +401,17 @@ export interface PropertySignature { } /** - * An index signature (e.g. `[key: string]: number`) within an {@link Objects}. + * An index signature, such as `[key: string]: number`, within an + * {@link Objects}. * - * - `parameter` is the key type representation. - * - `type` is the value type representation. + * **Details** + * + * `parameter` is the key type representation. `type` is the value type + * representation. * * @see {@link Objects} * - * @category Model + * @category models * @since 4.0.0 */ export interface IndexSignature { @@ -463,11 +422,12 @@ export interface IndexSignature { /** * A union of multiple representations. * - * - `types` are the union members. - * - `mode` controls JSON Schema output: `"anyOf"` (default) or `"oneOf"` - * (mutually exclusive). + * **Details** + * + * `types` are the union members. `mode` controls JSON Schema output as either + * `"anyOf"` (the default) or mutually exclusive `"oneOf"`. * - * @category Model + * @category models * @since 4.0.0 */ export interface Union { @@ -480,6 +440,8 @@ export interface Union { /** * The core tagged union of all supported schema shapes. * + * **Details** + * * Each variant has a `_tag` discriminator. Switch on `_tag` to handle each * shape. Most variants carry optional `annotations` and some carry `checks` * for validation constraints. @@ -487,7 +449,7 @@ export interface Union { * @see {@link Document} * @see {@link fromAST} * - * @category Model + * @category models * @since 4.0.0 */ export type Representation = @@ -521,7 +483,7 @@ export type Representation = * @see {@link Filter} * @see {@link FilterGroup} * - * @category Model + * @category models * @since 4.0.0 */ export type Check = Filter | FilterGroup @@ -532,7 +494,7 @@ export type Check = Filter | FilterGroup * * @see {@link Check} * - * @category Model + * @category models * @since 4.0.0 */ export interface Filter { @@ -547,7 +509,7 @@ export interface Filter { * * @see {@link Check} * - * @category Model + * @category models * @since 4.0.0 */ export interface FilterGroup { @@ -563,7 +525,7 @@ export interface FilterGroup { * @see {@link String} * @see {@link Check} * - * @category Model + * @category models * @since 4.0.0 */ export type StringMeta = Schema.Annotations.BuiltInMetaDefinitions[ @@ -576,6 +538,7 @@ export type StringMeta = Schema.Annotations.BuiltInMetaDefinitions[ | "isLengthBetween" | "isTrimmed" | "isUUID" + | "isGUID" | "isULID" | "isBase64" | "isBase64Url" @@ -595,7 +558,7 @@ export type StringMeta = Schema.Annotations.BuiltInMetaDefinitions[ * @see {@link Number} * @see {@link Check} * - * @category Model + * @category models * @since 4.0.0 */ export type NumberMeta = Schema.Annotations.BuiltInMetaDefinitions[ @@ -615,7 +578,7 @@ export type NumberMeta = Schema.Annotations.BuiltInMetaDefinitions[ * @see {@link BigInt} * @see {@link Check} * - * @category Model + * @category models * @since 4.0.0 */ export type BigIntMeta = Schema.Annotations.BuiltInMetaDefinitions[ @@ -633,7 +596,7 @@ export type BigIntMeta = Schema.Annotations.BuiltInMetaDefinitions[ * @see {@link Arrays} * @see {@link Check} * - * @category Model + * @category models * @since 4.0.0 */ export type ArraysMeta = Schema.Annotations.BuiltInMetaDefinitions[ @@ -650,7 +613,7 @@ export type ArraysMeta = Schema.Annotations.BuiltInMetaDefinitions[ * @see {@link Objects} * @see {@link Check} * - * @category Model + * @category models * @since 4.0.0 */ export type ObjectsMeta = @@ -667,7 +630,7 @@ export type ObjectsMeta = * @see {@link Declaration} * @see {@link DeclarationMeta} * - * @category Model + * @category models * @since 4.0.0 */ export type DateMeta = Schema.Annotations.BuiltInMetaDefinitions[ @@ -686,7 +649,7 @@ export type DateMeta = Schema.Annotations.BuiltInMetaDefinitions[ * @see {@link Declaration} * @see {@link DeclarationMeta} * - * @category Model + * @category models * @since 4.0.0 */ export type SizeMeta = Schema.Annotations.BuiltInMetaDefinitions[ @@ -699,7 +662,7 @@ export type SizeMeta = Schema.Annotations.BuiltInMetaDefinitions[ * Metadata union for {@link Declaration} checks — either {@link DateMeta} * or {@link SizeMeta}. * - * @category Model + * @category models * @since 4.0.0 */ export type DeclarationMeta = DateMeta | SizeMeta @@ -715,7 +678,7 @@ export type Meta = StringMeta | NumberMeta | BigIntMeta | ArraysMeta | ObjectsMe * @see {@link Reference} * @see {@link Document} * - * @category Model + * @category models * @since 4.0.0 */ export interface References { @@ -725,15 +688,16 @@ export interface References { /** * A single {@link Representation} together with its named {@link References}. * - * - Use {@link fromAST} to create a `Document` from a Schema AST. - * - Use {@link toSchema} to reconstruct a runtime Schema. - * - Use {@link toJsonSchemaDocument} to convert to JSON Schema. - * - Use {@link toMultiDocument} to wrap as a {@link MultiDocument}. + * **When to use** + * + * Use when representing a single Schema AST together with its named references + * before reconstructing a runtime Schema, converting to JSON Schema, or + * wrapping it as a {@link MultiDocument}. * * @see {@link MultiDocument} * @see {@link fromAST} * - * @category Model + * @category models * @since 4.0.0 */ export type Document = { @@ -744,14 +708,16 @@ export type Document = { /** * One or more {@link Representation}s sharing a common {@link References} map. * - * - Use {@link fromASTs} to create from multiple Schema ASTs. - * - Use {@link toCodeDocument} to generate TypeScript code. - * - Use {@link toJsonSchemaMultiDocument} to convert to JSON Schema. + * **When to use** + * + * Use when you use {@link fromASTs} to create this from multiple Schema ASTs, + * {@link toCodeDocument} to generate TypeScript code, and + * {@link toJsonSchemaMultiDocument} to convert to JSON Schema. * * @see {@link Document} * @see {@link fromASTs} * - * @category Model + * @category models * @since 4.0.0 */ export type MultiDocument = { @@ -781,9 +747,17 @@ const toJsonAnnotationsBlacklist: Set = new Set([ export type PrimitiveTree = Schema.Tree /** - * Schema codec for {@link PrimitiveTree}. + * Schema for {@link PrimitiveTree}. * - * @category Schema + * **When to use** + * + * Use to validate recursive annotation metadata trees whose leaves are `null`, + * `number`, `boolean`, `bigint`, `symbol`, or `string`. + * + * @see {@link PrimitiveTree} for the recursive tree type accepted by this codec + * @see {@link $Annotations} for the annotation codec that filters values through this codec + * + * @category schemas * @since 4.0.0 */ export const $PrimitiveTree: Schema.Codec = Schema.Tree( @@ -800,16 +774,29 @@ export const $PrimitiveTree: Schema.Codec = Schema.Tree( const isPrimitiveTree = Schema.is($PrimitiveTree) /** - * Schema codec for `Schema.Annotations.Annotations`. Filters out internal - * annotation keys and non-primitive values during encoding. + * Schema for serializing public `Schema.Annotations.Annotations` values. It + * filters out internal annotation keys and non-primitive values during + * encoding. + * + * **When to use** + * + * Use to serialize schema annotations in representation schemas while retaining + * only primitive-tree metadata. + * + * **Details** * - * @category Schema + * Decoding is passthrough. Encoding removes internal annotation keys and values + * that are not accepted by `$PrimitiveTree`. + * + * @see {@link $PrimitiveTree} for the codec used to filter annotation values + * + * @category schemas * @since 4.0.0 */ export const $Annotations = Schema.Record(Schema.String, Schema.Unknown).pipe( Schema.encodeTo(Schema.Record(Schema.String, $PrimitiveTree), { - decode: Getter.passthrough(), - encode: Getter.transformOptional(Option.flatMap((r) => { + decode: SchemaGetter.passthrough(), + encode: SchemaGetter.transformOptional(Option.flatMap((r) => { const out: Record = {} for (const [k, v] of Object.entries(r)) { if (!toJsonAnnotationsBlacklist.has(k) && isPrimitiveTree(v)) { @@ -822,9 +809,9 @@ export const $Annotations = Schema.Record(Schema.String, Schema.Unknown).pipe( ).annotate({ identifier: "Annotations" }) /** - * Schema codec for the {@link Null} representation node. + * Schema for the {@link Null} representation node. * - * @category Schema + * @category schemas * @since 4.0.0 */ export const $Null = Schema.Struct({ @@ -833,9 +820,9 @@ export const $Null = Schema.Struct({ }).annotate({ identifier: "Null" }) /** - * Schema codec for the {@link Undefined} representation node. + * Schema for the {@link Undefined} representation node. * - * @category Schema + * @category schemas * @since 4.0.0 */ export const $Undefined = Schema.Struct({ @@ -844,9 +831,9 @@ export const $Undefined = Schema.Struct({ }).annotate({ identifier: "Undefined" }) /** - * Schema codec for the {@link Void} representation node. + * Schema for the {@link Void} representation node. * - * @category Schema + * @category schemas * @since 4.0.0 */ export const $Void = Schema.Struct({ @@ -855,9 +842,9 @@ export const $Void = Schema.Struct({ }).annotate({ identifier: "Void" }) /** - * Schema codec for the {@link Never} representation node. + * Schema for the {@link Never} representation node. * - * @category Schema + * @category schemas * @since 4.0.0 */ export const $Never = Schema.Struct({ @@ -866,9 +853,9 @@ export const $Never = Schema.Struct({ }).annotate({ identifier: "Never" }) /** - * Schema codec for the {@link Unknown} representation node. + * Schema for the {@link Unknown} representation node. * - * @category Schema + * @category schemas * @since 4.0.0 */ export const $Unknown = Schema.Struct({ @@ -877,9 +864,9 @@ export const $Unknown = Schema.Struct({ }).annotate({ identifier: "Unknown" }) /** - * Schema codec for the {@link Any} representation node. + * Schema for the {@link Any} representation node. * - * @category Schema + * @category schemas * @since 4.0.0 */ export const $Any = Schema.Struct({ @@ -913,6 +900,11 @@ const $IsUUID = Schema.Struct({ version: Schema.UndefinedOr(Schema.Literals([1, 2, 3, 4, 5, 6, 7, 8])) }).annotate({ identifier: "IsUUID" }) +const $IsGUID = Schema.Struct({ + _tag: Schema.tag("isGUID"), + regExp: Schema.RegExp +}).annotate({ identifier: "IsGUID" }) + const $IsULID = Schema.Struct({ _tag: Schema.tag("isULID"), regExp: Schema.RegExp @@ -990,9 +982,9 @@ const $IsPattern = Schema.Struct({ }).annotate({ identifier: "IsPattern" }) /** - * Schema codec for {@link StringMeta}. + * Schema for {@link StringMeta}. * - * @category Schema + * @category schemas * @since 4.0.0 */ export const $StringMeta = Schema.Union([ @@ -1001,6 +993,7 @@ export const $StringMeta = Schema.Union([ $IsStringSymbol, $IsTrimmed, $IsUUID, + $IsGUID, $IsULID, $IsBase64, $IsBase64Url, @@ -1035,9 +1028,9 @@ function makeCheck(meta: Schema.Codec, identifier: string) { } /** - * Schema codec for the {@link String} representation node. + * Schema for the {@link String} representation node. * - * @category Schema + * @category schemas * @since 4.0.0 */ export const $String = Schema.Struct({ @@ -1090,9 +1083,9 @@ const $IsBetween = Schema.Struct({ }).annotate({ identifier: "IsBetween" }) /** - * Schema codec for {@link NumberMeta}. + * Schema for {@link NumberMeta}. * - * @category Schema + * @category schemas * @since 4.0.0 */ export const $NumberMeta = Schema.Union([ @@ -1107,9 +1100,9 @@ export const $NumberMeta = Schema.Union([ ]).annotate({ identifier: "NumberMeta" }) /** - * Schema codec for the {@link Number} representation node. + * Schema for the {@link Number} representation node. * - * @category Schema + * @category schemas * @since 4.0.0 */ export const $Number = Schema.Struct({ @@ -1119,9 +1112,9 @@ export const $Number = Schema.Struct({ }).annotate({ identifier: "Number" }) /** - * Schema codec for the {@link Boolean} representation node. + * Schema for the {@link Boolean} representation node. * - * @category Schema + * @category schemas * @since 4.0.0 */ export const $Boolean = Schema.Struct({ @@ -1166,9 +1159,21 @@ const $BigIntMeta = Schema.Union([ ]).annotate({ identifier: "BigIntMeta" }) /** - * Schema codec for the {@link BigInt} representation node. + * Schema for the {@link BigInt} representation node. + * + * **When to use** + * + * Use to encode, decode, or validate serialized `BigInt` representation nodes, + * not application `bigint` values. * - * @category Schema + * **Details** + * + * Accepts representation nodes with `_tag: "BigInt"`, optional annotations, + * and bigint-specific validation metadata in `checks`. + * + * @see {@link BigIntMeta} for the metadata accepted by the `checks` array + * + * @category schemas * @since 4.0.0 */ export const $BigInt = Schema.Struct({ @@ -1178,9 +1183,9 @@ export const $BigInt = Schema.Struct({ }).annotate({ identifier: "BigInt" }) /** - * Schema codec for the {@link Symbol} representation node. + * Schema for the {@link Symbol} representation node. * - * @category Schema + * @category schemas * @since 4.0.0 */ export const $Symbol = Schema.Struct({ @@ -1189,10 +1194,10 @@ export const $Symbol = Schema.Struct({ }).annotate({ identifier: "Symbol" }) /** - * Schema codec for the literal value types allowed in a {@link Literal} node + * Schema for the literal value types allowed in a {@link Literal} node * (string, finite number, boolean, or bigint). * - * @category Schema + * @category schemas * @since 4.0.0 */ export const $LiteralValue = Schema.Union([ @@ -1203,9 +1208,9 @@ export const $LiteralValue = Schema.Union([ ]).annotate({ identifier: "LiteralValue" }) /** - * Schema codec for the {@link Literal} representation node. + * Schema for the {@link Literal} representation node. * - * @category Schema + * @category schemas * @since 4.0.0 */ export const $Literal = Schema.Struct({ @@ -1215,9 +1220,9 @@ export const $Literal = Schema.Struct({ }).annotate({ identifier: "Literal" }) /** - * Schema codec for the {@link UniqueSymbol} representation node. + * Schema for the {@link UniqueSymbol} representation node. * - * @category Schema + * @category schemas * @since 4.0.0 */ export const $UniqueSymbol = Schema.Struct({ @@ -1227,9 +1232,9 @@ export const $UniqueSymbol = Schema.Struct({ }).annotate({ identifier: "UniqueSymbol" }) /** - * Schema codec for the {@link ObjectKeyword} representation node. + * Schema for the {@link ObjectKeyword} representation node. * - * @category Schema + * @category schemas * @since 4.0.0 */ export const $ObjectKeyword = Schema.Struct({ @@ -1238,9 +1243,9 @@ export const $ObjectKeyword = Schema.Struct({ }).annotate({ identifier: "ObjectKeyword" }) /** - * Schema codec for the {@link Enum} representation node. + * Schema for the {@link Enum} representation node. * - * @category Schema + * @category schemas * @since 4.0.0 */ export const $Enum = Schema.Struct({ @@ -1258,9 +1263,9 @@ export const $Enum = Schema.Struct({ }).annotate({ identifier: "Enum" }) /** - * Schema codec for the {@link TemplateLiteral} representation node. + * Schema for the {@link TemplateLiteral} representation node. * - * @category Schema + * @category schemas * @since 4.0.0 */ export const $TemplateLiteral = Schema.Struct({ @@ -1270,9 +1275,9 @@ export const $TemplateLiteral = Schema.Struct({ }).annotate({ identifier: "TemplateLiteral" }) /** - * Schema codec for the {@link Element} type (positional tuple element). + * Schema for the {@link Element} type (positional tuple element). * - * @category Schema + * @category schemas * @since 4.0.0 */ export const $Element = Schema.Struct({ @@ -1293,9 +1298,9 @@ const $ArraysMeta = Schema.Union([ ]).annotate({ identifier: "ArraysMeta" }) /** - * Schema codec for the {@link Arrays} representation node. + * Schema for the {@link Arrays} representation node. * - * @category Schema + * @category schemas * @since 4.0.0 */ export const $Arrays = Schema.Struct({ @@ -1307,9 +1312,9 @@ export const $Arrays = Schema.Struct({ }).annotate({ identifier: "Arrays" }) /** - * Schema codec for the {@link PropertySignature} type. + * Schema for the {@link PropertySignature} type. * - * @category Schema + * @category schemas * @since 4.0.0 */ export const $PropertySignature = Schema.Struct({ @@ -1321,9 +1326,9 @@ export const $PropertySignature = Schema.Struct({ }).annotate({ identifier: "PropertySignature" }) /** - * Schema codec for the {@link IndexSignature} type. + * Schema for the {@link IndexSignature} type. * - * @category Schema + * @category schemas * @since 4.0.0 */ export const $IndexSignature = Schema.Struct({ @@ -1353,9 +1358,9 @@ const $IsPropertyNames = Schema.Struct({ }).annotate({ identifier: "IsPropertyNames" }) /** - * Schema codec for {@link ObjectsMeta}. + * Schema for {@link ObjectsMeta}. * - * @category Schema + * @category schemas * @since 4.0.0 */ export const $ObjectsMeta = Schema.Union([ @@ -1366,9 +1371,9 @@ export const $ObjectsMeta = Schema.Union([ ]).annotate({ identifier: "ObjectsMeta" }) /** - * Schema codec for the {@link Objects} representation node. + * Schema for the {@link Objects} representation node. * - * @category Schema + * @category schemas * @since 4.0.0 */ export const $Objects = Schema.Struct({ @@ -1380,9 +1385,9 @@ export const $Objects = Schema.Struct({ }).annotate({ identifier: "Objects" }) /** - * Schema codec for the {@link Union} representation node. + * Schema for the {@link Union} representation node. * - * @category Schema + * @category schemas * @since 4.0.0 */ export const $Union = Schema.Struct({ @@ -1393,9 +1398,9 @@ export const $Union = Schema.Struct({ }).annotate({ identifier: "Union" }) /** - * Schema codec for the {@link Reference} representation node. + * Schema for the {@link Reference} representation node. * - * @category Schema + * @category schemas * @since 4.0.0 */ export const $Reference = Schema.Struct({ @@ -1436,9 +1441,9 @@ const $IsBetweenDate = Schema.Struct({ }).annotate({ identifier: "IsBetweenDate" }) /** - * Schema codec for {@link DateMeta}. + * Schema for {@link DateMeta}. * - * @category Schema + * @category schemas * @since 4.0.0 */ export const $DateMeta = Schema.Union([ @@ -1467,9 +1472,9 @@ const $IsSizeBetween = Schema.Struct({ }).annotate({ identifier: "IsSizeBetween" }) /** - * Schema codec for {@link SizeMeta}. + * Schema for {@link SizeMeta}. * - * @category Schema + * @category schemas * @since 4.0.0 */ export const $SizeMeta = Schema.Union([ @@ -1479,9 +1484,9 @@ export const $SizeMeta = Schema.Union([ ]).annotate({ identifier: "SizeMeta" }) /** - * Schema codec for {@link DeclarationMeta}. + * Schema for {@link DeclarationMeta}. * - * @category Schema + * @category schemas * @since 4.0.0 */ export const $DeclarationMeta = Schema.Union([ @@ -1490,9 +1495,9 @@ export const $DeclarationMeta = Schema.Union([ ]).annotate({ identifier: "DeclarationMeta" }) /** - * Schema codec for the {@link Declaration} representation node. + * Schema for the {@link Declaration} representation node. * - * @category Schema + * @category schemas * @since 4.0.0 */ export const $Declaration = Schema.Struct({ @@ -1504,9 +1509,9 @@ export const $Declaration = Schema.Struct({ }).annotate({ identifier: "Declaration" }) /** - * Schema codec for the {@link Suspend} representation node. + * Schema for the {@link Suspend} representation node. * - * @category Schema + * @category schemas * @since 4.0.0 */ export const $Suspend = Schema.Struct({ @@ -1519,15 +1524,16 @@ export const $Suspend = Schema.Struct({ /** * Type-level helper for the recursive {@link $Representation} codec. * + * @category schemas * @since 4.0.0 */ export interface $Representation extends Schema.Codec {} /** - * Schema codec for the full {@link Representation} union. This is the - * recursive codec that can validate/encode any representation node. + * Schema for the full {@link Representation} union. It recursively validates + * and encodes any representation node. * - * @category Schema + * @category schemas * @since 4.0.0 */ export const $Representation: $Representation = Schema.Union([ @@ -1556,10 +1562,22 @@ export const $Representation: $Representation = Schema.Union([ ]).annotate({ identifier: "Schema" }) /** - * Schema codec for {@link Document}. Use with `Schema.decodeUnknownSync` or - * `Schema.encodeSync` to validate or serialize document data. + * Schema for {@link Document}. + * + * **When to use** + * + * Use to validate or serialize a single schema representation document with + * `Schema.decodeUnknownSync` or `Schema.encodeSync`. + * + * **Gotchas** * - * @category Schema + * This codec validates document structure but does not resolve `$ref` keys + * against `references`. + * + * @see {@link DocumentFromJson} for the JSON-string codec wrapper + * @see {@link $MultiDocument} for validating documents with multiple root representations + * + * @category schemas * @since 4.0.0 */ export const $Document = Schema.Struct({ @@ -1568,9 +1586,9 @@ export const $Document = Schema.Struct({ }).annotate({ identifier: "Document" }) /** - * Schema codec for {@link MultiDocument}. + * Schema for {@link MultiDocument}. * - * @category Schema + * @category schemas * @since 4.0.0 */ export const $MultiDocument = Schema.Struct({ @@ -1585,9 +1603,14 @@ export const $MultiDocument = Schema.Struct({ /** * Converts a Schema AST into a {@link Document}. * - * - Use when you have a single schema and need its representation. - * - Pure function; does not mutate the input AST. - * - Shared/recursive sub-schemas are extracted into the `references` map. + * **When to use** + * + * Use when you have a single Schema AST and need a schema representation + * document. + * + * **Details** + * + * Shared/recursive sub-schemas are extracted into the `references` map. * * **Example** (Converting a Schema to a Document) * @@ -1607,29 +1630,39 @@ export const $MultiDocument = Schema.Struct({ * @see {@link Document} * @see {@link fromASTs} * + * @category constructors * @since 4.0.0 */ -export const fromAST: (ast: AST.AST) => Document = InternalRepresentation.fromAST +export const fromAST: (ast: SchemaAST.AST) => Document = InternalRepresentation.fromAST /** * Converts one or more Schema ASTs into a {@link MultiDocument}. * - * - Use when you have multiple schemas that may share references. - * - Pure function; does not mutate the input ASTs. - * - All schemas share a single `references` map. + * **When to use** + * + * Use when you have multiple Schema ASTs and need one schema representation + * `MultiDocument` with shared references. + * + * **Details** + * + * All schemas share a single `references` map. * * @see {@link MultiDocument} * @see {@link fromAST} * + * @category constructors * @since 4.0.0 */ -export const fromASTs: (asts: readonly [AST.AST, ...Array]) => MultiDocument = InternalRepresentation.fromASTs +export const fromASTs: (asts: readonly [SchemaAST.AST, ...Array]) => MultiDocument = + InternalRepresentation.fromASTs /** - * Schema codec that decodes a {@link Document} from JSON and encodes it back. + * Schema that decodes a {@link Document} from JSON and encodes it back. + * + * **When to use** * - * - Use with `Schema.decodeUnknownSync` / `Schema.encodeSync` to - * serialize/deserialize documents. + * Use when you need a JSON codec for schema representation documents with + * `Schema.decodeUnknownSync` or `Schema.encodeSync`. * * **Example** (Round-tripping a Document through JSON) * @@ -1644,17 +1677,18 @@ export const fromASTs: (asts: readonly [AST.AST, ...Array]) => MultiDoc * @see {@link $Document} * @see {@link MultiDocumentFromJson} * + * @category schemas * @since 4.0.0 */ export const DocumentFromJson: Schema.Codec = Schema.toCodecJson($Document) /** - * Schema codec that decodes a {@link MultiDocument} from JSON and encodes it - * back. + * Schema for `MultiDocument` values encoded as JSON. * * @see {@link $MultiDocument} * @see {@link DocumentFromJson} * + * @category schemas * @since 4.0.0 */ export const MultiDocumentFromJson: Schema.Codec = Schema.toCodecJson($MultiDocument) @@ -1663,13 +1697,15 @@ export const MultiDocumentFromJson: Schema.Codec = S * Wraps a single {@link Document} as a {@link MultiDocument} with one * representation. * - * - Use when an API expects a `MultiDocument` but you only have a single - * `Document`. - * - Pure function; does not mutate the input. + * **When to use** + * + * Use when you need to pass a single schema representation `Document` where an + * API expects a `MultiDocument`. * * @see {@link Document} * @see {@link MultiDocument} * + * @category transforming * @since 4.0.0 */ export function toMultiDocument(document: Document): MultiDocument { @@ -1683,33 +1719,41 @@ export function toMultiDocument(document: Document): MultiDocument { * A callback that handles {@link Declaration} nodes during reconstruction * ({@link toSchema}) or code generation ({@link toCodeDocument}). * - * - Return a value to handle the declaration. - * - Return `undefined` to fall back to default behavior (use `encodedSchema` - * for `toSchema`, or `generation` annotation for `toCodeDocument`). - * - `recur` processes child representations recursively. + * **Details** + * + * Return a value to handle the declaration. Return `undefined` to fall back to + * default behavior, which uses `encodedSchema` for `toSchema` or the + * `generation` annotation for `toCodeDocument`. `recur` processes child + * representations recursively. * * @see {@link toSchema} * @see {@link toSchemaDefaultReviver} * @see {@link toCodeDocument} * + * @category models * @since 4.0.0 */ export type Reviver = (declaration: Declaration, recur: (representation: Representation) => T) => T | undefined /** * Default {@link Reviver} for {@link toSchema} that handles built-in Effect - * types (Option, Result, Redacted, Cause, Exit, ReadonlyMap, HashMap, - * ReadonlySet, - * Date, Duration, URL, RegExp, etc.). + * types, including Option, Result, Redacted, Cause, Exit, ReadonlyMap, HashMap, + * ReadonlySet, Date, Duration, URL, and RegExp. + * + * **When to use** * - * - Pass as `options.reviver` to {@link toSchema} to reconstruct schemas that - * use these types. - * - Returns `undefined` for unrecognized declarations, causing fallback to - * `encodedSchema`. + * Use when you need the default `options.reviver` for {@link toSchema} to + * reconstruct runtime schemas for built-in Effect declarations. + * + * **Details** + * + * The reviver returns `undefined` for unrecognized declarations, causing + * fallback to `encodedSchema`. * * @see {@link toSchema} * @see {@link Reviver} * + * @category transforming * @since 4.0.0 */ export const toSchemaDefaultReviver: Reviver = (s, recur) => { @@ -1721,9 +1765,7 @@ export const toSchemaDefaultReviver: Reviver = (s, recur) => { case "Date": return Schema.Date case "Error": - return Schema.Error - case "ErrorWithStack": - return Schema.ErrorWithStack + return Schema.Error(typeConstructor.options as Schema.ErrorOptions | undefined) case "File": return Schema.File case "FormData": @@ -1746,7 +1788,7 @@ export const toSchemaDefaultReviver: Reviver = (s, recur) => { case "effect/Result": return Schema.Result(typeParameters[0], typeParameters[1]) case "effect/Redacted": - return Schema.Redacted(typeParameters[0]) + return Schema.Redacted(typeParameters[0], typeConstructor.options as any) case "effect/DateTime.TimeZone": return Schema.TimeZone case "effect/DateTime.TimeZone.Named": @@ -1782,15 +1824,23 @@ export const toSchemaDefaultReviver: Reviver = (s, recur) => { } /** - * Reconstructs a runtime Schema from a {@link Document}. + * Creates a runtime Schema from a {@link Document}. + * + * **When to use** + * + * Use when you have a serialized or computed schema representation document and + * need a runtime Schema for decoding/encoding. + * + * **Details** + * + * Pass `options.reviver`, such as {@link toSchemaDefaultReviver}, to handle + * {@link Declaration} nodes for types like `Date` and `Option`. Without a + * reviver, declarations fall back to their `encodedSchema`. Circular references + * are handled via lazy `Schema.suspend`. * - * - Use when you have a serialized or computed representation and need a - * working Schema for decoding/encoding. - * - Pass `options.reviver` (e.g. {@link toSchemaDefaultReviver}) to handle - * {@link Declaration} nodes for types like `Date`, `Option`, etc. - * - Without a reviver, declarations fall back to their `encodedSchema`. - * - Handles circular references via lazy `Schema.suspend`. - * - Throws if a `$ref` is not found in `document.references`. + * **Gotchas** + * + * This throws if a `$ref` is not found in `document.references`. * * **Example** (Reconstructing a Schema) * @@ -1997,7 +2047,7 @@ export function toSchema(document: Document, } } - function toSchemaCheck(check: Check): AST.Check { + function toSchemaCheck(check: Check): SchemaAST.Check { switch (check._tag) { case "Filter": return toSchemaFilter(check) @@ -2007,7 +2057,7 @@ export function toSchema(document: Document, } } - function toSchemaFilter(filter: Filter): AST.Check { + function toSchemaFilter(filter: Filter): SchemaAST.Check { const a = filter.annotations switch (filter.meta._tag) { // String Meta @@ -2029,6 +2079,8 @@ export function toSchema(document: Document, return Schema.isTrimmed(a) case "isUUID": return Schema.isUUID(filter.meta.version, a) + case "isGUID": + return Schema.isGUID(a) case "isULID": return Schema.isULID(a) case "isBase64": @@ -2122,8 +2174,17 @@ export function toSchema(document: Document, /** * Converts a {@link Document} to a Draft 2020-12 JSON Schema document. * - * - Use to produce a standard JSON Schema from an Effect Schema representation. - * - Pure function; does not mutate the input. + * **When to use** + * + * Use when you need to produce a standard JSON Schema document from a schema + * representation `Document`. + * + * **Gotchas** + * + * JSON Schema generation is best-effort. Some Effect schema representation + * semantics cannot be represented exactly in JSON Schema, and importing an + * emitted JSON Schema may produce an equivalent approximation rather than the + * original representation shape. * * **Example** (Generating JSON Schema) * @@ -2140,6 +2201,7 @@ export function toSchema(document: Document, * @see {@link toJsonSchemaMultiDocument} * @see {@link fromJsonSchemaDocument} * + * @category transforming * @since 4.0.0 */ export const toJsonSchemaDocument: ( @@ -2151,13 +2213,23 @@ export const toJsonSchemaDocument: ( * Converts a {@link MultiDocument} to a Draft 2020-12 JSON Schema * multi-document. * - * - Use when you have multiple schemas sharing references. - * - Pure function; does not mutate the input. + * **When to use** + * + * Use when you need to export related schema representation documents together + * so shared definitions stay in multi-document JSON Schema form. + * + * **Gotchas** + * + * JSON Schema generation is best-effort. Some Effect schema representation + * semantics cannot be represented exactly in JSON Schema, and importing an + * emitted JSON Schema may produce equivalent approximations rather than the + * original representation shapes. * * @see {@link MultiDocument} * @see {@link toJsonSchemaDocument} * @see {@link fromJsonSchemaMultiDocument} * + * @category transforming * @since 4.0.0 */ export const toJsonSchemaMultiDocument: ( @@ -2223,10 +2295,13 @@ export type Artifact = * The output of {@link toCodeDocument}: generated TypeScript code for one or * more schemas plus their shared references and auxiliary artifacts. * - * - `codes` — one {@link Code} per input representation. - * - `references.nonRecursives` — topologically sorted non-recursive definitions. - * - `references.recursives` — definitions involved in cycles. - * - `artifacts` — symbols, enums, and import statements needed by the code. + * **Details** + * + * `codes` contains one {@link Code} per input representation. + * `references.nonRecursives` contains topologically sorted non-recursive + * definitions. `references.recursives` contains definitions involved in cycles. + * `artifacts` contains symbols, enums, and import statements needed by the + * code. * * @see {@link toCodeDocument} * @see {@link Code} @@ -2252,13 +2327,18 @@ export type CodeDocument = { /** * Generates TypeScript code strings from a {@link MultiDocument}. * - * - Use to produce source code for Schema definitions (e.g. for codegen tools). - * - `options.reviver` can customize code generation for {@link Declaration} - * nodes. Return `undefined` to fall back to the default logic (which uses - * `generation` annotations or the encoded schema). - * - Performs topological sorting of references to emit non-recursive - * definitions before their dependents. - * - Produces sanitized JavaScript identifiers for `$ref` keys. + * **When to use** + * + * Use when you need to produce source code for Effect Schema definitions from a + * schema representation `MultiDocument`. + * + * **Details** + * + * `options.reviver` can customize code generation for {@link Declaration} + * nodes. Return `undefined` to fall back to the default logic, which uses + * `generation` annotations or the encoded schema. References are + * topologically sorted so non-recursive definitions are emitted before their + * dependents. `$ref` keys are converted to sanitized JavaScript identifiers. * * **Example** (Generating TypeScript code) * @@ -2646,6 +2726,7 @@ export function toCodeDocument(multiDocument: MultiDocument, options?: { const ca = a === "" ? "" : `, ${a}` switch (filter.meta._tag) { case "isTrimmed": + case "isGUID": case "isULID": case "isBase64": case "isBase64Url": @@ -2657,7 +2738,7 @@ export function toCodeDocument(multiDocument: MultiDocument, options?: { case "isInt": case "isUnique": case "isDateValid": - return `Schema.${filter.meta._tag}(${ca})` + return `Schema.${filter.meta._tag}(${a})` case "isStringFinite": case "isStringBigInt": @@ -2883,16 +2964,31 @@ function toRuntimeRegExp(regExp: RegExp): string { /** * Parses a Draft 2020-12 JSON Schema document into a {@link Document}. * - * - Use to import external JSON Schemas into the Effect representation system. - * - `options.onEnter` is an optional hook called on each JSON Schema node - * before processing, allowing pre-transformation. - * - Throws if a `$ref` cannot be resolved within the document's definitions. - * - Circular `$ref`s are detected and cause an error. + * **When to use** + * + * Use when you need to import a Draft 2020-12 JSON Schema document into the + * Effect schema representation system. + * + * **Details** + * + * `options.onEnter` is an optional hook called on each JSON Schema node before + * processing, allowing pre-transformation. + * + * **Gotchas** + * + * JSON Schema import is best-effort. Some JSON Schema constructs do not map + * exactly to Effect schema representations, and importing a schema previously + * emitted by `toJsonSchemaDocument` may produce an equivalent approximation + * rather than the original representation shape. + * + * This throws if a `$ref` cannot be resolved within the document's definitions. + * Circular `$ref`s are detected and cause an error. * * @see {@link Document} * @see {@link toJsonSchemaDocument} * @see {@link fromJsonSchemaMultiDocument} * + * @category constructors * @since 4.0.0 */ export function fromJsonSchemaDocument(document: JsonSchema.Document<"draft-2020-12">, options?: { @@ -2913,15 +3009,30 @@ export function fromJsonSchemaDocument(document: JsonSchema.Document<"draft-2020 * Parses a Draft 2020-12 JSON Schema multi-document into a * {@link MultiDocument}. * - * - Use to import multiple JSON Schemas sharing definitions. - * - `options.onEnter` is an optional hook called on each JSON Schema node - * before processing. - * - Throws if a `$ref` cannot be resolved. + * **When to use** + * + * Use when you need to import a Draft 2020-12 JSON Schema multi-document whose + * schemas share definitions. + * + * **Details** + * + * `options.onEnter` is an optional hook called on each JSON Schema node before + * processing. + * + * **Gotchas** + * + * JSON Schema import is best-effort. Some JSON Schema constructs do not map + * exactly to Effect schema representations, and importing schemas previously + * emitted by `toJsonSchemaMultiDocument` may produce equivalent approximations + * rather than the original representation shapes. + * + * This throws if a `$ref` cannot be resolved. * * @see {@link MultiDocument} * @see {@link toJsonSchemaMultiDocument} * @see {@link fromJsonSchemaDocument} * + * @category constructors * @since 4.0.0 */ export function fromJsonSchemaMultiDocument(document: JsonSchema.MultiDocument<"draft-2020-12">, options?: { @@ -3566,7 +3677,7 @@ function collectAnnotations( return Rec.isEmptyRecord(as) ? undefined : as } -function isLiteralValue(value: unknown): value is AST.LiteralValue { +function isLiteralValue(value: unknown): value is SchemaAST.LiteralValue { return typeof value === "string" || typeof value === "number" || typeof value === "boolean" } diff --git a/.opencode/node_modules/effect/src/SchemaTransformation.ts b/.opencode/node_modules/effect/src/SchemaTransformation.ts index 348afd2be1ee3270e7916c8c47621abf37e17cab..4d2fb16f3926d94d3aca9dcf641dc187c89fd33e 100644 --- a/.opencode/node_modules/effect/src/SchemaTransformation.ts +++ b/.opencode/node_modules/effect/src/SchemaTransformation.ts @@ -1,86 +1,13 @@ /** - * Bidirectional transformations for the Effect Schema system. - * - * A `Transformation` pairs a decode `Getter` and an encode `Getter` into a - * single bidirectional value, used by `Schema.decodeTo`, `Schema.encodeTo`, - * `Schema.decode`, `Schema.encode`, and `Schema.link` to define how values - * are converted between encoded and decoded representations. A `Middleware` - * is the effect-level equivalent — it wraps the entire parsing `Effect` - * pipeline rather than individual values. - * - * ## Mental model - * - * - **Transformation**: A pair of `Getter`s (decode + encode) that convert - * individual values bidirectionally. `T` is the decoded (Type) side, `E` is - * the encoded side. `RD`/`RE` are required Effect services. - * - **Middleware**: Like `Transformation`, but each direction receives the full - * parsing `Effect` and can intercept, retry, or modify the pipeline. - * - **Getter**: A single-direction transform `Option → Effect, Issue, R>` - * (see `SchemaGetter`). - * - **flip()**: Swaps decode and encode, turning a `Transformation` into - * `Transformation`. - * - **compose()**: Chains two transformations left-to-right on the decode side - * and right-to-left on the encode side. - * - **passthrough**: The identity transformation — no conversion in either - * direction. - * - * ## Common tasks - * - * - Convert values purely (sync, infallible) → {@link transform} - * - Convert values with possible failure → {@link transformOrFail} - * - Handle optional/missing keys → {@link transformOptional} - * - Build from existing Getters → {@link make} - * - No-op identity transformation → {@link passthrough} - * - Subtype/supertype coercion → {@link passthroughSupertype}, {@link passthroughSubtype} - * - Trim/case strings → {@link trim}, {@link toLowerCase}, {@link toUpperCase}, {@link capitalize}, {@link uncapitalize}, {@link snakeToCamel} - * - Parse key-value strings → {@link splitKeyValue} - * - Coerce string ↔ number/bigint → {@link numberFromString}, {@link bigintFromString} - * - Coerce string ↔ Date/Duration → {@link dateFromString}, {@link durationFromString} - * - Decode durations → {@link durationFromNanos}, {@link durationFromMillis} - * - Wrap nullable/optional as Option → {@link optionFromNullOr}, {@link optionFromOptionalKey}, {@link optionFromOptional} - * - Parse URLs → {@link urlFromString} - * - Base64 ↔ Uint8Array → {@link uint8ArrayFromBase64String} - * - Base64 ↔ string → {@link stringFromBase64String} - * - URI component ↔ string → {@link stringFromUriComponent} - * - JSON string ↔ unknown → {@link fromJsonString} - * - FormData/URLSearchParams ↔ unknown → {@link fromFormData}, {@link fromURLSearchParams} - * - Check if a value is a Transformation → {@link isTransformation} - * - * ## Gotchas - * - * - `Transformation` operates on individual values; `Middleware` wraps the - * entire parsing Effect. Choose accordingly. - * - `passthrough` requires `T === E` by default. Use `{ strict: false }` to - * bypass, or use {@link passthroughSupertype} / {@link passthroughSubtype}. - * - String transformations like `trim`, `toLowerCase`, and `toUpperCase` use - * `passthrough` on the encode side — they are lossy and do not round-trip. - * - `durationFromNanos` encode can fail if the Duration cannot be represented - * as a `bigint`. - * - * ## Quickstart - * - * **Example** (Defining a custom transformation with Schema.decodeTo) + * Builds two-way conversions used by schemas. * - * ```ts - * import { Schema, SchemaTransformation } from "effect" - * - * const CentsFromDollars = Schema.Number.pipe( - * Schema.decodeTo( - * Schema.Number, - * SchemaTransformation.transform({ - * decode: (dollars) => dollars * 100, - * encode: (cents) => cents / 100 - * }) - * ) - * ) - * ``` - * - * ## See also - * - * - {@link Transformation} — the core bidirectional transformation class - * - {@link Middleware} — effect-pipeline-level transformation - * - {@link transform} — most common constructor - * - {@link passthrough} — identity transformation + * A `Transformation` describes how to decode an encoded value into a + * decoded value and how to encode it back again. Schema APIs use + * transformations to connect two representations, such as a string and a + * number, a JSON value and a richer TypeScript value, or a form field and an + * application value. This module includes transformation and middleware types, + * constructors for pure or effectful conversions, and common conversions used + * by the Schema module. * * @since 4.0.0 */ @@ -89,28 +16,30 @@ import * as BigDecimal from "./BigDecimal.ts" import * as DateTime from "./DateTime.ts" import * as Duration from "./Duration.ts" import * as Effect from "./Effect.ts" -import { formatDate } from "./Formatter.ts" +import { format, formatDate, formatJson } from "./Formatter.ts" import * as Option from "./Option.ts" import * as Predicate from "./Predicate.ts" -import type * as AST from "./SchemaAST.ts" -import * as Getter from "./SchemaGetter.ts" -import * as Issue from "./SchemaIssue.ts" +import type { ErrorOptions, Json } from "./Schema.ts" +import type * as SchemaAST from "./SchemaAST.ts" +import * as SchemaGetter from "./SchemaGetter.ts" +import * as SchemaIssue from "./SchemaIssue.ts" /** - * A middleware that wraps the entire parsing `Effect` pipeline for both + * Middleware that wraps the entire parsing `Effect` pipeline for both * decode and encode directions. * + * **When to use** + * + * Use when you need a schema middleware to catch or recover from parsing + * errors (e.g. `Schema.catchDecoding`), run side effects around the parsing + * pipeline, or access the full `Effect` rather than a single decoded value. + * + * **Details** + * * Unlike `Transformation`, which operates on individual values via `Getter`, * `Middleware` receives the full `Effect` produced by the inner schema and can * intercept, modify, retry, or replace it. * - * When to use this: - * - You need to catch or recover from parsing errors (e.g. `Schema.catchDecoding`). - * - You need to run side effects around the parsing pipeline. - * - You need access to the full `Effect` rather than a single decoded value. - * - * Behavior: - * - Immutable — constructing a Middleware does not mutate existing instances. * - `decode` receives an `Effect, Issue, RDE>` and returns * `Effect, Issue, RDT>`. * - `encode` receives an `Effect, Issue, RET>` and returns @@ -132,32 +61,31 @@ import * as Issue from "./SchemaIssue.ts" * ) * ``` * - * See also: - * - {@link Transformation} — value-level bidirectional transformation + * @see {@link Transformation} — value-level bidirectional transformation * - * @category model + * @category models * @since 4.0.0 */ export class Middleware { readonly _tag = "Middleware" readonly decode: ( - effect: Effect.Effect, Issue.Issue, RDE>, - options: AST.ParseOptions - ) => Effect.Effect, Issue.Issue, RDT> + effect: Effect.Effect, SchemaIssue.Issue, RDE>, + options: SchemaAST.ParseOptions + ) => Effect.Effect, SchemaIssue.Issue, RDT> readonly encode: ( - effect: Effect.Effect, Issue.Issue, RET>, - options: AST.ParseOptions - ) => Effect.Effect, Issue.Issue, REE> + effect: Effect.Effect, SchemaIssue.Issue, RET>, + options: SchemaAST.ParseOptions + ) => Effect.Effect, SchemaIssue.Issue, REE> constructor( decode: ( - effect: Effect.Effect, Issue.Issue, RDE>, - options: AST.ParseOptions - ) => Effect.Effect, Issue.Issue, RDT>, + effect: Effect.Effect, SchemaIssue.Issue, RDE>, + options: SchemaAST.ParseOptions + ) => Effect.Effect, SchemaIssue.Issue, RDT>, encode: ( - effect: Effect.Effect, Issue.Issue, RET>, - options: AST.ParseOptions - ) => Effect.Effect, Issue.Issue, REE> + effect: Effect.Effect, SchemaIssue.Issue, RET>, + options: SchemaAST.ParseOptions + ) => Effect.Effect, SchemaIssue.Issue, REE> ) { this.decode = decode this.encode = encode @@ -170,19 +98,22 @@ export class Middleware { const TypeId = "~effect/SchemaTransformation/Transformation" /** - * A bidirectional transformation between a decoded type `T` and an encoded + * Represents a bidirectional transformation between a decoded type `T` and an encoded * type `E`, built from a pair of `Getter`s. * - * This is the primary building block for `Schema.decodeTo`, `Schema.encodeTo`, - * `Schema.decode`, `Schema.encode`, and `Schema.link`. Each direction is a - * `SchemaGetter.Getter` that handles optionality, failure, and Effect services. + * **When to use** * - * When to use this: - * - You need to define how a schema converts between two representations. + * Use when you need a schema transformation that defines how a schema converts + * between two representations. * - You want to compose multiple transformations into a pipeline. * - You want to flip a transformation to swap decode/encode. * - * Behavior: + * **Details** + * + * This is the primary building block for `Schema.decodeTo`, `Schema.encodeTo`, + * `Schema.decode`, `Schema.encode`, and `Schema.link`. Each direction is a + * `SchemaGetter.Getter` that handles optionality, failure, and Effect services. + * * - Immutable — `flip()` and `compose()` return new instances. * - `flip()` swaps the decode and encode getters. * - `compose(other)` chains: `this.decode` then `other.decode` for decoding, @@ -200,24 +131,23 @@ const TypeId = "~effect/SchemaTransformation/Transformation" * // encode: passthrough (both directions) * ``` * - * See also: - * - {@link make} — construct from `{ decode, encode }` getters - * - {@link transform} — construct from pure functions - * - {@link transformOrFail} — construct from effectful functions - * - {@link Middleware} — effect-pipeline-level alternative + * @see {@link make} — construct from `{ decode, encode }` getters + * @see {@link transform} — construct from pure functions + * @see {@link transformOrFail} — construct from effectful functions + * @see {@link Middleware} — effect-pipeline-level alternative * - * @category model + * @category models * @since 4.0.0 */ export class Transformation { readonly [TypeId] = TypeId readonly _tag = "Transformation" - readonly decode: Getter.Getter - readonly encode: Getter.Getter + readonly decode: SchemaGetter.Getter + readonly encode: SchemaGetter.Getter constructor( - decode: Getter.Getter, - encode: Getter.Getter + decode: SchemaGetter.Getter, + encode: SchemaGetter.Getter ) { this.decode = decode this.encode = encode @@ -236,10 +166,13 @@ export class Transformation { /** * Returns `true` if `u` is a `Transformation` instance. * - * When to use this: - * - Checking whether a value is already a Transformation before wrapping it. + * **When to use** + * + * Use to check whether a value is already a schema transformation before + * wrapping it. + * + * **Details** * - * Behavior: * - Pure predicate, no side effects. * - Acts as a TypeScript type guard. * @@ -255,10 +188,10 @@ export class Transformation { * // false * ``` * - * See also: - * - {@link Transformation} - * - {@link make} + * @see {@link Transformation} + * @see {@link make} * + * @category guards * @since 4.0.0 */ export function isTransformation(u: unknown): u is Transformation { @@ -269,12 +202,14 @@ export function isTransformation(u: unknown): u is Transformation(options: { - readonly decode: Getter.Getter - readonly encode: Getter.Getter + readonly decode: SchemaGetter.Getter + readonly encode: SchemaGetter.Getter }): Transformation => { if (isTransformation(options)) { return options as any @@ -309,11 +244,13 @@ export const make = (options: { * Creates a `Transformation` from effectful decode and encode functions that * can fail with `Issue`. * - * When to use this: - * - The transformation can fail (e.g. parsing, validation). - * - The transformation requires Effect services. + * **When to use** + * + * Use when you need a schema transformation that may fail or require Effect + * services. + * + * **Details** * - * Behavior: * - Each function receives the input value and `ParseOptions`. * - Must return an `Effect` that succeeds with the output or fails with `Issue`. * - Skips `None` inputs (missing keys) — functions are only called on present values. @@ -339,20 +276,20 @@ export const make = (options: { * ) * ``` * - * See also: - * - {@link transform} — for infallible, pure transformations - * - {@link transformOptional} — for transformations that handle missing keys - * - {@link make} — for transformations from existing Getters + * @see {@link transform} — for infallible, pure transformations + * @see {@link transformOptional} — for transformations that handle missing keys + * @see {@link make} — for transformations from existing Getters * - * @since 4.0.0 + * @category constructors + * @since 3.10.0 */ export function transformOrFail(options: { - readonly decode: (e: E, options: AST.ParseOptions) => Effect.Effect - readonly encode: (t: T, options: AST.ParseOptions) => Effect.Effect + readonly decode: (e: E, options: SchemaAST.ParseOptions) => Effect.Effect + readonly encode: (t: T, options: SchemaAST.ParseOptions) => Effect.Effect }): Transformation { return new Transformation( - Getter.transformOrFail(options.decode), - Getter.transformOrFail(options.encode) + SchemaGetter.transformOrFail(options.decode), + SchemaGetter.transformOrFail(options.encode) ) } @@ -360,11 +297,13 @@ export function transformOrFail(options: { * Creates a `Transformation` from pure (sync, infallible) decode and encode * functions. * - * When to use this: - * - The conversion cannot fail. - * - No Effect services are needed. + * **When to use** + * + * Use when you need an infallible schema transformation that does not require + * Effect services. + * + * **Details** * - * Behavior: * - Each function receives the input and returns the output directly. * - Skips `None` inputs (missing keys) — functions are only called on present values. * - Does not allocate Effects internally; uses optimized sync path. @@ -385,20 +324,20 @@ export function transformOrFail(options: { * ) * ``` * - * See also: - * - {@link transformOrFail} — for fallible or effectful transformations - * - {@link transformOptional} — for transformations that handle missing keys - * - {@link passthrough} — when no conversion is needed + * @see {@link transformOrFail} — for fallible or effectful transformations + * @see {@link transformOptional} — for transformations that handle missing keys + * @see {@link passthrough} — when no conversion is needed * - * @since 4.0.0 + * @category constructors + * @since 3.10.0 */ export function transform(options: { readonly decode: (input: E) => T readonly encode: (input: T) => E }): Transformation { return new Transformation( - Getter.transform(options.decode), - Getter.transform(options.encode) + SchemaGetter.transform(options.decode), + SchemaGetter.transform(options.encode) ) } @@ -406,11 +345,14 @@ export function transform(options: { * Creates a `Transformation` where decode and encode operate on `Option` * values, giving full control over missing-key handling. * - * When to use this: - * - You need to produce or consume `Option.None` to represent absent keys. + * **When to use** + * + * Use when you need a schema transformation to produce or consume `Option.None` + * for absent keys. * - You are working with optional struct fields. * - * Behavior: + * **Details** + * * - Each function receives `Option` and returns `Option`. * - `Option.None` input means the key is absent; returning `Option.None` * omits the key from the output. @@ -434,11 +376,11 @@ export function transform(options: { * }) * ``` * - * See also: - * - {@link transform} — when you don't need Option-level control - * - {@link optionFromOptionalKey} — built-in for the common optional-key-to-Option pattern - * - {@link optionFromOptional} — built-in for optional (undefined) to Option + * @see {@link transform} — when you don't need Option-level control + * @see {@link optionFromOptionalKey} — built-in for the common optional-key-to-Option pattern + * @see {@link optionFromOptional} — built-in for optional (undefined) to Option * + * @category constructors * @since 4.0.0 */ export function transformOptional(options: { @@ -446,22 +388,25 @@ export function transformOptional(options: { readonly encode: (input: Option.Option) => Option.Option }): Transformation { return new Transformation( - Getter.transformOptional(options.decode), - Getter.transformOptional(options.encode) + SchemaGetter.transformOptional(options.decode), + SchemaGetter.transformOptional(options.encode) ) } /** - * A string-to-string transformation that trims whitespace on decode. + * Transforms strings by trimming whitespace on decode. * Encode is passthrough (no change). * - * When to use this: - * - Normalizing user input by stripping leading/trailing whitespace. + * **When to use** + * + * Use when you need a schema transformation to normalize user input by + * stripping leading/trailing whitespace. + * + * **Details** * - * Behavior: - * - Decode: applies `String.prototype.trim()`. - * - Encode: passthrough (returns the string unchanged). - * - Not round-trippable if the original had whitespace. + * Decoding applies `String.prototype.trim()`. Encoding is passthrough and + * returns the string unchanged. This is not round-trippable if the original had + * whitespace. * * **Example** (Trimming on decode) * @@ -473,32 +418,34 @@ export function transformOptional(options: { * ) * ``` * - * See also: - * - {@link toLowerCase} - * - {@link toUpperCase} - * - {@link snakeToCamel} + * @see {@link toLowerCase} + * @see {@link toUpperCase} + * @see {@link snakeToCamel} * * @category String transformations * @since 4.0.0 */ export function trim(): Transformation { return new Transformation( - Getter.trim(), - Getter.passthrough() + SchemaGetter.trim(), + SchemaGetter.passthrough() ) } /** - * A string-to-string transformation that converts snake_case to camelCase + * Transforms strings by converting snake_case to camelCase * on decode and camelCase to snake_case on encode. * - * When to use this: - * - Converting API field names between snake_case and camelCase conventions. + * **When to use** * - * Behavior: - * - Decode: `"my_field_name"` → `"myFieldName"`. - * - Encode: `"myFieldName"` → `"my_field_name"`. - * - Round-trippable for standard snake_case/camelCase. + * Use when you need a schema transformation to convert API field names between + * snake_case and camelCase conventions. + * + * **Details** + * + * Decoding converts values such as `"my_field_name"` to `"myFieldName"`. + * Encoding converts values such as `"myFieldName"` back to `"my_field_name"`. + * The transformation is round-trippable for standard snake_case and camelCase. * * **Example** (Snake to camel conversion) * @@ -510,31 +457,32 @@ export function trim(): Transformation { * ) * ``` * - * See also: - * - {@link trim} - * - {@link toLowerCase} + * @see {@link trim} + * @see {@link toLowerCase} * * @category String transformations * @since 4.0.0 */ export function snakeToCamel(): Transformation { return new Transformation( - Getter.snakeToCamel(), - Getter.camelToSnake() + SchemaGetter.snakeToCamel(), + SchemaGetter.camelToSnake() ) } /** - * A string-to-string transformation that lowercases on decode. + * Transforms strings by lowercasing on decode. * Encode is passthrough. * - * When to use this: - * - Normalizing strings to lowercase (e.g. email addresses). + * **When to use** + * + * Use when you need a schema transformation to normalize strings to lowercase + * (e.g. email addresses). * - * Behavior: - * - Decode: applies `String.prototype.toLowerCase()`. - * - Encode: passthrough. - * - Not round-trippable if the original had uppercase characters. + * **Details** + * + * Decoding applies `String.prototype.toLowerCase()`. Encoding is passthrough. + * This is not round-trippable if the original had uppercase characters. * * **Example** (Lowercasing on decode) * @@ -546,31 +494,32 @@ export function snakeToCamel(): Transformation { * ) * ``` * - * See also: - * - {@link toUpperCase} - * - {@link trim} + * @see {@link toUpperCase} + * @see {@link trim} * * @category String transformations * @since 4.0.0 */ export function toLowerCase(): Transformation { return new Transformation( - Getter.toLowerCase(), - Getter.passthrough() + SchemaGetter.toLowerCase(), + SchemaGetter.passthrough() ) } /** - * A string-to-string transformation that uppercases on decode. + * Transforms strings by uppercasing on decode. * Encode is passthrough. * - * When to use this: - * - Normalizing strings to uppercase (e.g. country codes). + * **When to use** + * + * Use when you need a schema transformation to normalize strings to uppercase + * (e.g. country codes). + * + * **Details** * - * Behavior: - * - Decode: applies `String.prototype.toUpperCase()`. - * - Encode: passthrough. - * - Not round-trippable if the original had lowercase characters. + * Decoding applies `String.prototype.toUpperCase()`. Encoding is passthrough. + * This is not round-trippable if the original had lowercase characters. * * **Example** (Uppercasing on decode) * @@ -582,30 +531,32 @@ export function toLowerCase(): Transformation { * ) * ``` * - * See also: - * - {@link toLowerCase} - * - {@link trim} + * @see {@link toLowerCase} + * @see {@link trim} * * @category String transformations * @since 4.0.0 */ export function toUpperCase(): Transformation { return new Transformation( - Getter.toUpperCase(), - Getter.passthrough() + SchemaGetter.toUpperCase(), + SchemaGetter.passthrough() ) } /** - * A string-to-string transformation that capitalizes the first character on + * Transforms strings by capitalizing the first character on * decode. Encode is passthrough. * - * When to use this: - * - Normalizing display names or titles. + * **When to use** * - * Behavior: - * - Decode: uppercases the first character, leaves the rest unchanged. - * - Encode: passthrough. + * Use when you need a schema transformation to normalize display names or + * titles. + * + * **Details** + * + * Decoding uppercases the first character and leaves the rest unchanged. + * Encoding is passthrough. * * **Example** (Capitalizing on decode) * @@ -617,30 +568,32 @@ export function toUpperCase(): Transformation { * ) * ``` * - * See also: - * - {@link uncapitalize} - * - {@link toUpperCase} + * @see {@link uncapitalize} + * @see {@link toUpperCase} * * @category String transformations * @since 4.0.0 */ export function capitalize(): Transformation { return new Transformation( - Getter.capitalize(), - Getter.passthrough() + SchemaGetter.capitalize(), + SchemaGetter.passthrough() ) } /** - * A string-to-string transformation that lowercases the first character on + * Transforms strings by lowercasing the first character on * decode. Encode is passthrough. * - * When to use this: - * - Normalizing identifiers or field names. + * **When to use** + * + * Use when you need a schema transformation to normalize identifiers or field + * names. * - * Behavior: - * - Decode: lowercases the first character, leaves the rest unchanged. - * - Encode: passthrough. + * **Details** + * + * Decoding lowercases the first character and leaves the rest unchanged. + * Encoding is passthrough. * * **Example** (Uncapitalizing on decode) * @@ -652,32 +605,34 @@ export function capitalize(): Transformation { * ) * ``` * - * See also: - * - {@link capitalize} - * - {@link toLowerCase} + * @see {@link capitalize} + * @see {@link toLowerCase} * * @category String transformations * @since 4.0.0 */ export function uncapitalize(): Transformation { return new Transformation( - Getter.uncapitalize(), - Getter.passthrough() + SchemaGetter.uncapitalize(), + SchemaGetter.passthrough() ) } /** - * A transformation that decodes a string into a record of key-value pairs and + * Transforms a string into a record of key-value pairs and * encodes a record of key-value pairs into a string. * - * When to use this: - * - Parsing query-string-like or config-file-like strings into records. + * **When to use** + * + * Use when you need a schema transformation to parse query-string-like or + * config-file-like strings into records. * - * Behavior: - * - Decode: splits the string by `separator` (default `","`) into pairs, - * then splits each pair by `keyValueSeparator` (default `"="`). - * - Encode: joins the record back into a string using the same separators. - * - Round-trippable when keys and values don't contain the separators. + * **Details** + * + * Decoding splits the string by `separator` (default `","`) into pairs, then + * splits each pair by `keyValueSeparator` (default `"="`). Encoding joins the + * record back into a string using the same separators. The transformation is + * round-trippable when keys and values do not contain the separators. * * **Example** (Parsing key-value pairs) * @@ -693,9 +648,8 @@ export function uncapitalize(): Transformation { * // "host:localhost;port:3000" → { host: "localhost", port: "3000" } * ``` * - * See also: - * - {@link trim} - * - {@link snakeToCamel} + * @see {@link trim} + * @see {@link snakeToCamel} * * @category String transformations * @since 4.0.0 @@ -705,26 +659,27 @@ export function splitKeyValue(options?: { readonly keyValueSeparator?: string | undefined }): Transformation, string> { return new Transformation( - Getter.splitKeyValue(options), - Getter.joinKeyValue(options) + SchemaGetter.splitKeyValue(options), + SchemaGetter.joinKeyValue(options) ) } const passthrough_ = new Transformation( - Getter.passthrough(), - Getter.passthrough() + SchemaGetter.passthrough(), + SchemaGetter.passthrough() ) /** - * The identity transformation — returns the input unchanged in both + * Transforms values by returning the input unchanged in both * directions. * - * When to use this: - * - Connecting two schemas that share the same type with no conversion. - * - As a placeholder when `Schema.decodeTo` requires a transformation but - * no actual conversion is needed. + * **When to use** + * + * Use when you need a schema transformation to connect two schemas that share + * the same type with no actual conversion. + * + * **Details** * - * Behavior: * - Both decode and encode are no-ops. * - Returns a shared singleton instance (no allocation per call). * - By default, `T` and `E` must be the same type. Pass `{ strict: false }` @@ -740,11 +695,11 @@ const passthrough_ = new Transformation( * ) * ``` * - * See also: - * - {@link passthroughSupertype} - * - {@link passthroughSubtype} - * - {@link transform} + * @see {@link passthroughSupertype} + * @see {@link passthroughSubtype} + * @see {@link transform} * + * @category constructors * @since 4.0.0 */ export function passthrough(options: { readonly strict: false }): Transformation @@ -754,15 +709,18 @@ export function passthrough(): Transformation { } /** - * A passthrough transformation typed so that `T extends E` — the decoded - * type is a supertype of the encoded type. + * Transforms values without changing them, typed so that `T extends E`, where the decoded + * type `T` is a subtype of the encoded type `E`. * - * When to use this: - * - Widening: the decoded side accepts a broader type than the encoded side. + * **When to use** * - * Behavior: - * - Both decode and encode are no-ops (same as {@link passthrough}). - * - Returns a shared singleton instance. + * Use when you need a no-op schema transformation whose decoded side is + * narrower than the encoded side. + * + * **Details** + * + * Both decode and encode are no-ops and return a shared singleton + * transformation. * * **Example** (Supertype passthrough) * @@ -772,10 +730,10 @@ export function passthrough(): Transformation { * const t = SchemaTransformation.passthroughSupertype<"a" | "b", string>() * ``` * - * See also: - * - {@link passthrough} - * - {@link passthroughSubtype} + * @see {@link passthrough} + * @see {@link passthroughSubtype} * + * @category constructors * @since 4.0.0 */ export function passthroughSupertype(): Transformation @@ -784,13 +742,16 @@ export function passthroughSupertype(): Transformation { } /** - * A passthrough transformation typed so that `E extends T` — the encoded + * Transforms values without changing them, typed so that `E extends T` — the encoded * type is a subtype of the decoded type. * - * When to use this: - * - Narrowing: the encoded side is more specific than the decoded side. + * **When to use** + * + * Use when you need a no-op schema transformation whose encoded side is more + * specific than its decoded side. + * + * **Details** * - * Behavior: * - Both decode and encode are no-ops (same as {@link passthrough}). * - Returns a shared singleton instance. * @@ -802,10 +763,10 @@ export function passthroughSupertype(): Transformation { * const t = SchemaTransformation.passthroughSubtype() * ``` * - * See also: - * - {@link passthrough} - * - {@link passthroughSupertype} + * @see {@link passthrough} + * @see {@link passthroughSupertype} * + * @category constructors * @since 4.0.0 */ export function passthroughSubtype(): Transformation @@ -817,14 +778,17 @@ export function passthroughSubtype(): Transformation { * Decodes a `string` into a `number` and encodes a `number` back to a * `string`. * - * When to use this: - * - Parsing numeric strings from APIs, form data, or URL parameters. + * **When to use** + * + * Use when you need a schema transformation to parse numeric strings from APIs, + * form data, or URL parameters. * - * Behavior: - * - Decode: coerces the string to a number (like `Number(s)`). - * - Encode: coerces the number to a string (like `String(n)`). - * - Does not validate that the result is finite — combine with - * `Schema.Finite` or `Schema.Int` for stricter checks. + * **Details** + * + * Decoding coerces the string to a number like `Number(s)`. Encoding coerces + * the number to a string like `String(n)`. This does not validate that the + * result is finite; combine with `Schema.Finite` or `Schema.Int` for stricter + * checks. * * **Example** (Number from string) * @@ -836,29 +800,31 @@ export function passthroughSubtype(): Transformation { * ) * ``` * - * See also: - * - {@link bigintFromString} - * - {@link transform} + * @see {@link bigintFromString} + * @see {@link transform} * * @category Coercions * @since 4.0.0 */ export const numberFromString = new Transformation( - Getter.Number(), - Getter.String() + SchemaGetter.Number(), + SchemaGetter.String() ) /** * Decodes a `string` into a `bigint` and encodes a `bigint` back to a * `string`. * - * When to use this: - * - Parsing large integer strings (e.g. database IDs, blockchain values). + * **When to use** + * + * Use when you need a schema transformation to parse large integer strings + * (e.g. database IDs, blockchain values). + * + * **Details** * - * Behavior: - * - Decode: coerces the string to a bigint (like `BigInt(s)`). - * - Encode: coerces the bigint to a string (like `String(n)`). - * - Fails on decode if the string is not a valid bigint representation. + * Decoding coerces the string to a bigint like `BigInt(s)`. Encoding coerces + * the bigint to a string like `String(n)`. Decoding fails if the string is not + * a valid bigint representation. * * **Example** (BigInt from string) * @@ -870,28 +836,30 @@ export const numberFromString = new Transformation( * ) * ``` * - * See also: - * - {@link numberFromString} - * - {@link transform} + * @see {@link numberFromString} + * @see {@link transform} * * @category Coercions * @since 4.0.0 */ export const bigintFromString = new Transformation( - Getter.BigInt(), - Getter.String() + SchemaGetter.BigInt(), + SchemaGetter.String() ) /** * Decodes a `string` into a `Date` and encodes a `Date` back to a `string`. * - * When to use this: - * - Parsing ISO 8601 date strings from APIs or user input. + * **When to use** * - * Behavior: - * - Decode: creates a `Date` from the string (like `new Date(s)`). - * - Encode: converts the `Date` to an ISO string (like `date.toISOString()`), - * returning `"Invalid Date"` for invalid dates. + * Use when you need a schema transformation to parse ISO 8601 date strings from + * APIs or user input. + * + * **Details** + * + * Decoding creates a `Date` from the string like `new Date(s)`. Encoding + * converts the `Date` to an ISO string like `date.toISOString()`, returning + * `"Invalid Date"` for invalid dates. * * **Example** (Date from string) * @@ -903,30 +871,32 @@ export const bigintFromString = new Transformation( * ) * ``` * - * See also: - * - {@link numberFromString} - * - {@link dateTimeUtcFromString} + * @see {@link numberFromString} + * @see {@link dateTimeUtcFromString} * * @category Coercions * @since 4.0.0 */ export const dateFromString: Transformation = new Transformation( - Getter.Date(), - Getter.transform(formatDate) + SchemaGetter.Date(), + SchemaGetter.transform(formatDate) ) /** * Decodes a `string` into a `Duration` and encodes a `Duration` back to a * parseable `string`. * - * When to use this: - * - Parsing human-readable duration strings from APIs, config, or user input. + * **When to use** + * + * Use when you need a schema transformation to parse human-readable duration + * strings from APIs, config, or user input. * - * Behavior: - * - Decode: accepts any string that `Duration.fromInput` can parse, including - * `"Infinity"` and `"-Infinity"`. - * - Encode: returns `String(duration)`, producing strings like `"2000 millis"` - * or `"10 nanos"` that round-trip through the parser. + * **Details** + * + * Decoding accepts any string that `Duration.fromInput` can parse, including + * `"Infinity"` and `"-Infinity"`. Encoding returns `String(duration)`, + * producing strings such as `"2000 millis"` or `"10 nanos"` that round-trip + * through the parser. * * **Example** (Duration from string) * @@ -938,10 +908,10 @@ export const dateFromString: Transformation = new Trans * ) * ``` * - * See also: - * - {@link durationFromNanos} - * - {@link durationFromMillis} + * @see {@link durationFromNanos} + * @see {@link durationFromMillis} * + * @category transforming * @since 4.0.0 */ export const durationFromString: Transformation = transformOrFail< @@ -950,7 +920,8 @@ export const durationFromString: Transformation = tra >({ decode: (s) => Option.match(Duration.fromInput(s as Duration.Input), { - onNone: () => Effect.fail(new Issue.InvalidValue(Option.some(s), { message: `Invalid Duration string: ${s}` })), + onNone: () => + Effect.fail(new SchemaIssue.InvalidValue(Option.some(s), { message: `Invalid Duration string: ${s}` })), onSome: Effect.succeed }), encode: (duration) => Effect.succeed(globalThis.String(duration)) @@ -960,13 +931,16 @@ export const durationFromString: Transformation = tra * Decodes a `bigint` (nanoseconds) into a `Duration` and encodes a * `Duration` back to `bigint` nanoseconds. * - * When to use this: - * - Working with nanosecond-precision timestamps or intervals. + * **When to use** + * + * Use when you need a schema transformation for nanosecond-precision timestamps + * or intervals. * - * Behavior: - * - Decode: always succeeds, creating a Duration from nanoseconds. - * - Encode: fails with `InvalidValue` if the Duration cannot be represented - * as a `bigint` (e.g. `Duration.infinity`). + * **Details** + * + * Decoding always succeeds and creates a `Duration` from nanoseconds. Encoding + * fails with `InvalidValue` if the `Duration` cannot be represented as a + * `bigint`, such as `Duration.infinity`. * * **Example** (Duration from nanoseconds) * @@ -978,9 +952,9 @@ export const durationFromString: Transformation = tra * ) * ``` * - * See also: - * - {@link durationFromMillis} + * @see {@link durationFromMillis} * + * @category transforming * @since 4.0.0 */ export const durationFromNanos: Transformation = transformOrFail({ @@ -989,22 +963,25 @@ export const durationFromNanos: Transformation = tran Option.match(Duration.toNanos(a), { onNone: () => Effect.fail( - new Issue.InvalidValue(Option.some(a), { message: `Unable to encode ${a} into a bigint` }) + new SchemaIssue.InvalidValue(Option.some(a), { message: `Unable to encode ${a} into a bigint` }) ), onSome: (nanos) => Effect.succeed(nanos) }) }) /** - * Decodes a `number` (milliseconds) into a `Duration` and encodes a - * `Duration` back to `number` milliseconds. + * Decodes a `number` of milliseconds into a `Duration` and encodes a `Duration` + * back to milliseconds. + * + * **When to use** * - * When to use this: - * - Working with millisecond-precision timestamps (e.g. `Date.now()`). + * Use when you need a schema transformation to decode timeouts, delays, elapsed + * intervals, or other duration values stored as millisecond counts. * - * Behavior: - * - Decode: creates a Duration from milliseconds. Always succeeds. - * - Encode: converts a Duration to milliseconds. Always succeeds. + * **Details** + * + * Decode creates a duration from the number, and encode returns the duration + * length in milliseconds. * * **Example** (Duration from milliseconds) * @@ -1016,9 +993,9 @@ export const durationFromNanos: Transformation = tran * ) * ``` * - * See also: - * - {@link durationFromNanos} + * @see {@link durationFromNanos} * + * @category transforming * @since 4.0.0 */ export const durationFromMillis: Transformation = transform({ @@ -1026,48 +1003,100 @@ export const durationFromMillis: Transformation = tra encode: (a) => Duration.toMillis(a) }) -/** @internal */ -export const errorFromErrorJsonEncoded = (options?: { - readonly includeStack?: boolean | undefined -}): Transformation => - transform({ - decode: (i) => { - const err = new Error(i.message) - if (typeof i.name === "string" && i.name !== "Error") err.name = i.name - if (typeof i.stack === "string") err.stack = i.stack - return err - }, - encode: (a) => { - const e: { - message: string - name?: string - stack?: string - } = { - name: a.name, - message: a.message - } - if (options?.includeStack && typeof a.stack === "string") { - e.stack = a.stack + cause?: Json +} + +const isJsonError = (input: unknown): input is JsonError => + Predicate.isObject(input) && typeof input["message"] === "string" + +const decodeJsonError = (input: JsonError): Error => { + const hasCause = Object.hasOwn(input, "cause") + const err = hasCause + ? new Error(input.message, { cause: decodeDefect(input.cause as Json) }) + : new Error(input.message) + if (typeof input.name === "string" && input.name !== "Error") err.name = input.name + if (typeof input.stack === "string") err.stack = input.stack + return err +} + +const encodeUnknownAsJson = (input: unknown): Json => { + try { + const json = formatJson(input) + return json === undefined ? format(input) : JSON.parse(json) + } catch { + return format(input) + } +} + +const encodeJsonError = ( + input: Error, + options: ErrorOptions | undefined, + encodeDefect: (input: unknown) => Json +): JsonError => { + const encoded: JsonError = { + name: input.name, + message: typeof input.message === "string" ? input.message : "" + } + if (options?.includeStack && typeof input.stack === "string") { + encoded.stack = input.stack + } + if (!options?.excludeCause && input.cause !== undefined) { + encoded.cause = encodeDefect(input.cause) + } + return encoded +} + +const makeEncodeDefect = (options?: ErrorOptions): (input: unknown) => Json => { + const seen = new WeakSet() + const encode = (input: unknown): Json => { + if (Predicate.isError(input)) { + if (seen.has(input)) { + return "[Circular]" } - return e + seen.add(input) + const encoded = encodeJsonError(input, options, encode) + seen.delete(input) + return encoded } + return encodeUnknownAsJson(input) + } + return encode +} + +const decodeDefect = (input: Json): unknown => isJsonError(input) ? decodeJsonError(input) : input + +/** @internal */ +export const errorFromJsonError = (options?: ErrorOptions): Transformation => + transform({ + decode: decodeJsonError, + encode: (input) => makeEncodeDefect(options)(input) as JsonError + }) + +/** @internal */ +export const defectFromJson = (options?: ErrorOptions) => + transform({ + decode: decodeDefect, + encode: makeEncodeDefect(options) }) /** * Decodes `T | null` into `Option` and encodes `Option` back to * `T | null`. * - * When to use this: - * - Converting nullable API fields to `Option`. + * **When to use** * - * Behavior: - * - Decode: `null` → `Option.none()`, non-null → `Option.some(value)`. - * - Encode: `Option.none()` → `null`, `Option.some(value)` → `value`. - * - Pure and synchronous. + * Use when you need a schema transformation to convert nullable API fields to + * `Option`. + * + * **Details** + * + * Decoding maps `null` to `Option.none()` and non-null values to + * `Option.some(value)`. Encoding maps `Option.none()` to `null` and + * `Option.some(value)` to `value`. The transformation is pure and synchronous. * * **Example** (Option from nullable) * @@ -1082,9 +1111,9 @@ export const errorFromErrorJsonEncoded = (options?: { * ) * ``` * - * See also: - * - {@link optionFromNullishOr} + * @see {@link optionFromNullishOr} * + * @category transforming * @since 4.0.0 */ export function optionFromNullOr(): Transformation, T | null> { @@ -1095,16 +1124,19 @@ export function optionFromNullOr(): Transformation, T | null } /** - * Decodes `T | undefined` into `Option` and encodes `Option` back - * to `T | undefined`. + * Decodes `T | undefined` into `Option` and encodes `Option.none()` back to + * `undefined`. * - * When to use this: - * - Converting undefined-or API fields to `Option`. + * **When to use** * - * Behavior: - * - Decode: `undefined` → `Option.none()`, non-undefined → `Option.some(value)`. - * - Encode: `Option.none()` → `undefined`, `Option.some(value)` → `value`. - * - Pure and synchronous. + * Use when you need a schema transformation to convert API fields that use + * `undefined` for absence to `Option`. + * + * **Details** + * + * Decoding maps `undefined` to `Option.none()` and non-undefined values to + * `Option.some(value)`. Encoding maps `Option.none()` to `undefined` and + * `Option.some(value)` to `value`. The transformation is pure and synchronous. * * **Example** (Option from undefined-or) * @@ -1119,10 +1151,10 @@ export function optionFromNullOr(): Transformation, T | null * ) * ``` * - * See also: - * - {@link optionFromOptionalKey} - * - {@link optionFromOptional} + * @see {@link optionFromOptionalKey} + * @see {@link optionFromOptional} * + * @category transforming * @since 4.0.0 */ export function optionFromUndefinedOr(): Transformation, T | undefined> { @@ -1134,17 +1166,20 @@ export function optionFromUndefinedOr(): Transformation, T | /** * Decodes `T | null | undefined` into `Option` and encodes `Option` - * back to `T | null` or `T | undefined` depending on the provided `options.onNoneEncoding` (defaults to `undefined`). + * back to `T | null` or `T | undefined` depending on the provided + * `options.onNoneEncoding` (defaults to `undefined`). * - * When to use this: - * - Converting nullish API fields to `Option` when both `null` and - * `undefined` represent absence. + * **When to use** * - * Behavior: - * - Decode: `null` or `undefined` → `Option.none()`, otherwise → `Option.some(value)`. - * - Encode: `Option.none()` → `null` or `undefined` (per `options.onNoneEncoding`), - * `Option.some(value)` → `value`. - * - Pure and synchronous. + * Use when you need a schema transformation to convert nullish API fields to + * `Option` when both `null` and `undefined` represent absence. + * + * **Details** + * + * Decoding maps `null` and `undefined` to `Option.none()` and all other values + * to `Option.some(value)`. Encoding maps `Option.none()` to `null` or + * `undefined` according to `options.onNoneEncoding`, and maps + * `Option.some(value)` to `value`. The transformation is pure and synchronous. * * **Example** (Option from nullish, encoding None as null) * @@ -1159,10 +1194,10 @@ export function optionFromUndefinedOr(): Transformation, T | * ) * ``` * - * See also: - * - {@link optionFromNullOr} - * - {@link optionFromUndefinedOr} + * @see {@link optionFromNullOr} + * @see {@link optionFromUndefinedOr} * + * @category transforming * @since 4.0.0 */ export function optionFromNullishOr( @@ -1180,14 +1215,17 @@ export function optionFromNullishOr( * Decodes an optional struct key into `Option` and encodes `Option` * back to an optional key. * - * When to use this: - * - Converting optional struct keys (declared with `Schema.optionalKey`) to - * `Option` values. + * **When to use** + * + * Use when you need a schema transformation to convert optional struct keys + * (declared with `Schema.optionalKey`) to `Option` values. * - * Behavior: - * - Decode: absent key (`None`) → `Some(None)`, present key (`Some(v)`) → `Some(Some(v))`. - * - Encode: `Some(None)` → `None` (omit key), `Some(Some(v))` → `Some(v)`. - * - Uses `transformOptional` under the hood. + * **Details** + * + * Decoding maps an absent key (`None`) to `Some(None)` and a present key + * (`Some(v)`) to `Some(Some(v))`. Encoding maps `Some(None)` to `None` to omit + * the key, and maps `Some(Some(v))` to `Some(v)`. This uses + * `transformOptional` under the hood. * * **Example** (Optional key to Option) * @@ -1204,11 +1242,11 @@ export function optionFromNullishOr( * }) * ``` * - * See also: - * - {@link optionFromOptional} - * - {@link optionFromUndefinedOr} - * - {@link transformOptional} + * @see {@link optionFromOptional} + * @see {@link optionFromUndefinedOr} + * @see {@link transformOptional} * + * @category transforming * @since 4.0.0 */ export function optionFromOptionalKey(): Transformation, T> { @@ -1219,16 +1257,20 @@ export function optionFromOptionalKey(): Transformation, T> } /** - * Decodes `T | undefined` into `Option` and encodes `Option` back - * to `T | undefined`. + * Decodes optional values into `Option` and encodes `Option.none()` back to + * an omitted optional value. + * + * **When to use** + * + * Use when you need a schema transformation to convert optional (possibly + * `undefined`) values to `Option`. * - * When to use this: - * - Converting optional (possibly `undefined`) values to `Option`. + * **Details** * - * Behavior: - * - Decode: absent or `undefined` → `Some(None)`, present → `Some(Some(v))`. - * - Encode: `Some(None)` → `None` (omit), `Some(Some(v))` → `Some(v)`. - * - Uses `transformOptional` under the hood; filters out `undefined` on decode. + * Decoding maps an absent or `undefined` value to `Some(None)` and a present + * value to `Some(Some(v))`. Encoding maps `Some(None)` to `None` to omit the + * value, and maps `Some(Some(v))` to `Some(v)`. This uses + * `transformOptional` under the hood and filters out `undefined` on decode. * * **Example** (Optional value to Option) * @@ -1245,11 +1287,11 @@ export function optionFromOptionalKey(): Transformation, T> * }) * ``` * - * See also: - * - {@link optionFromOptionalKey} - * - {@link optionFromUndefinedOr} - * - {@link transformOptional} + * @see {@link optionFromOptionalKey} + * @see {@link optionFromUndefinedOr} + * @see {@link transformOptional} * + * @category transforming * @since 4.0.0 */ export function optionFromOptional(): Transformation, T | undefined> { @@ -1263,13 +1305,15 @@ export function optionFromOptional(): Transformation, T | un * Decodes a `string` into a `URL` and encodes a `URL` back to its `href` * string. * - * When to use this: - * - Parsing URL strings from user input or API responses. + * **When to use** + * + * Use when you need a schema transformation to parse URL strings from user + * input or API responses. + * + * **Details** * - * Behavior: - * - Decode: calls `new URL(s)`. Fails with `InvalidValue` if the string - * is not a valid URL. - * - Encode: returns `url.href`. + * Decoding calls `new URL(s)` and fails with `InvalidValue` if the string is + * not a valid URL. Encoding returns `url.href`. * * **Example** (URL from string) * @@ -1281,17 +1325,17 @@ export function optionFromOptional(): Transformation, T | un * ) * ``` * - * See also: - * - {@link numberFromString} - * - {@link transformOrFail} + * @see {@link numberFromString} + * @see {@link transformOrFail} * + * @category transforming * @since 4.0.0 */ export const urlFromString: Transformation = transformOrFail({ decode: (s) => Effect.try({ try: () => new URL(s), - catch: () => new Issue.InvalidValue(Option.some(s), { message: `Invalid URL string: ${s}` }) + catch: () => new SchemaIssue.InvalidValue(Option.some(s), { message: `Invalid URL string: ${s}` }) }), encode: (url) => Effect.succeed(url.href) }) @@ -1300,14 +1344,18 @@ export const urlFromString: Transformation = transformOrFail = transformOrFail< @@ -1317,7 +1365,7 @@ export const bigDecimalFromString: Transformation decode: (s) => { const result = BigDecimal.fromString(s) return Option.isNone(result) - ? Effect.fail(new Issue.InvalidValue(Option.some(s), { message: `Invalid BigDecimal string: ${s}` })) + ? Effect.fail(new SchemaIssue.InvalidValue(Option.some(s), { message: `Invalid BigDecimal string: ${s}` })) : Effect.succeed(result.value) }, encode: (bd) => Effect.succeed(BigDecimal.format(bd)) @@ -1327,13 +1375,15 @@ export const bigDecimalFromString: Transformation * Decodes a Base64-encoded `string` into a `Uint8Array` and encodes a * `Uint8Array` back to a Base64 string. * - * When to use this: - * - Handling binary data transmitted as Base64 strings (e.g. file uploads, - * API payloads). + * **When to use** + * + * Use when you need a schema transformation for binary data transmitted as + * Base64 strings (e.g. file uploads, API payloads). * - * Behavior: - * - Decode: parses the Base64 string into bytes. - * - Encode: encodes the byte array as a Base64 string. + * **Details** + * + * Decoding parses the Base64 string into bytes. Encoding writes the byte array + * as a Base64 string. * * **Example** (Uint8Array from Base64) * @@ -1345,27 +1395,30 @@ export const bigDecimalFromString: Transformation * ) * ``` * - * See also: - * - {@link fromJsonString} - * - `Schema.Uint8ArrayFromBase64` - a ready-made schema wrapping this transformation. + * @see {@link fromJsonString} + * @see `Schema.Uint8ArrayFromBase64` - a ready-made schema wrapping this transformation. * + * @category encoding * @since 4.0.0 */ export const uint8ArrayFromBase64String: Transformation, string> = new Transformation( - Getter.decodeBase64(), - Getter.encodeBase64() + SchemaGetter.decodeBase64(), + SchemaGetter.encodeBase64() ) /** * Decodes a Base64-encoded `string` into a UTF-8 `string` and encodes a * UTF-8 `string` back to a Base64 string. * - * When to use this: - * - Handling text data transmitted as Base64 strings. + * **When to use** + * + * Use when you need a schema transformation for text data transmitted as Base64 + * strings. * - * Behavior: - * - Decode: parses the Base64 string into a UTF-8 string. - * - Encode: encodes the string as a Base64 string. + * **Details** + * + * Decoding parses the Base64 string into a UTF-8 string. Encoding writes the + * string as a Base64 string. * * **Example** (String from Base64) * @@ -1377,26 +1430,29 @@ export const uint8ArrayFromBase64String: Transformation = new Transformation( - Getter.decodeBase64String(), - Getter.encodeBase64() + SchemaGetter.decodeBase64String(), + SchemaGetter.encodeBase64() ) /** * Decodes a base64 (URL) encoded `string` into a UTF-8 `string` and encodes it back. * - * When to use this: - * - Handling text data transmitted as Base64 URL-safe strings. + * **When to use** + * + * Use when you need a schema transformation for text data transmitted as Base64 + * URL-safe strings. + * + * **Details** * - * Behavior: - * - Decode: parses the Base64 URL string into a UTF-8 string. - * - Encode: encodes the string as a Base64 URL string. + * Decoding parses the Base64 URL string into a UTF-8 string. Encoding writes + * the string as a Base64 URL string. * * **Example** (String from Base64Url) * @@ -1408,26 +1464,29 @@ export const stringFromBase64String: Transformation = new Transf * ) * ``` * - * See also: - * - {@link stringFromBase64String} - * - `Schema.StringFromBase64Url` - a ready-made schema wrapping this transformation. + * @see {@link stringFromBase64String} + * @see `Schema.StringFromBase64Url` - a ready-made schema wrapping this transformation. * + * @category encoding * @since 4.0.0 */ export const stringFromBase64UrlString: Transformation = new Transformation( - Getter.decodeBase64UrlString(), - Getter.encodeBase64Url() + SchemaGetter.decodeBase64UrlString(), + SchemaGetter.encodeBase64Url() ) /** * Decodes a hex encoded `string` into a UTF-8 `string` and encodes it back. * - * When to use this: - * - Handling text data transmitted as hexadecimal strings. + * **When to use** + * + * Use when you need a schema transformation for text data transmitted as + * hexadecimal strings. + * + * **Details** * - * Behavior: - * - Decode: parses the hex string into a UTF-8 string. - * - Encode: encodes the string as a hex string. + * Decoding parses the hex string into a UTF-8 string. Encoding writes the + * string as a hex string. * * **Example** (String from Hex) * @@ -1439,29 +1498,31 @@ export const stringFromBase64UrlString: Transformation = new Tra * ) * ``` * - * See also: - * - {@link stringFromBase64String} - * - `Schema.StringFromHex` - a ready-made schema wrapping this transformation. + * @see {@link stringFromBase64String} + * @see `Schema.StringFromHex` - a ready-made schema wrapping this transformation. * + * @category encoding * @since 4.0.0 */ export const stringFromHexString: Transformation = new Transformation( - Getter.decodeHexString(), - Getter.encodeHex() + SchemaGetter.decodeHexString(), + SchemaGetter.encodeHex() ) /** * Decodes a URI component encoded string into a UTF-8 string and encodes a * UTF-8 string into a URI component encoded string. * - * When to use this: - * - Storing structured data in URL query parameters or fragments. - * - Composing with `Schema.parseJson` to round-trip JSON through a URL. + * **When to use** * - * Behavior: - * - Decode: calls `decodeURIComponent`. Fails if the input contains malformed - * percent-encoding sequences. - * - Encode: calls `encodeURIComponent`. + * Use when you need a schema transformation to store structured data in URL + * query parameters or fragments, such as composing with `Schema.parseJson` to + * round-trip JSON through a URL. + * + * **Details** + * + * Decoding calls `decodeURIComponent` and fails if the input contains malformed + * percent-encoding sequences. Encoding calls `encodeURIComponent`. * * **Example** (URI component schema) * @@ -1473,28 +1534,31 @@ export const stringFromHexString: Transformation = new Transform * ) * ``` * - * See also: - * - {@link stringFromBase64String} - * - `Schema.StringFromUriComponent` - a ready-made schema wrapping this transformation. + * @see {@link stringFromBase64String} + * @see `Schema.StringFromUriComponent` - a ready-made schema wrapping this transformation. * + * @category encoding * @since 4.0.0 */ export const stringFromUriComponent: Transformation = new Transformation( - Getter.decodeUriComponent(), - Getter.encodeUriComponent() + SchemaGetter.decodeUriComponent(), + SchemaGetter.encodeUriComponent() ) /** - * Decodes a JSON `string` into an `unknown` value and encodes an `unknown` - * value back to a JSON string. + * Decodes a JSON string with `JSON.parse` and encodes a value with + * `JSON.stringify`. + * + * **When to use** * - * When to use this: - * - Parsing JSON strings from HTTP bodies, message queues, or storage. - * - Typically composed with a further schema to validate the parsed structure. + * Use when you need a schema transformation to decode JSON stored or + * transmitted as a string, usually before composing with another schema that + * validates the parsed structure. * - * Behavior: - * - Decode: calls `JSON.parse`. Fails if the string is not valid JSON. - * - Encode: calls `JSON.stringify`. + * **Details** + * + * Decode fails with `InvalidValue` for invalid JSON, and encode can fail with + * `InvalidValue` when `JSON.stringify` cannot serialize the value. * * **Example** (Parsing JSON) * @@ -1506,27 +1570,31 @@ export const stringFromUriComponent: Transformation = new Transf * ) * ``` * - * See also: - * - {@link uint8ArrayFromBase64String} - * - {@link fromFormData} + * @see {@link uint8ArrayFromBase64String} + * @see {@link fromFormData} * + * @category decoding * @since 4.0.0 */ export const fromJsonString = new Transformation( - Getter.parseJson(), - Getter.stringifyJson() + SchemaGetter.parseJson(), + SchemaGetter.stringifyJson() ) /** - * Decodes a `FormData` instance into an `unknown` record and encodes an - * `unknown` record back to `FormData`. + * Decodes a `FormData` instance into a nested record using bracket-path keys and + * encodes object-like values back into `FormData`. + * + * **When to use** + * + * Use when you need a schema transformation for form or multipart payloads + * whose keys, such as `user[name]` or `items[0]`, should become nested data. * - * When to use this: - * - Handling HTML form submissions or multipart API requests. + * **Details** * - * Behavior: - * - Decode: extracts entries from the FormData into a plain object. - * - Encode: constructs a FormData from the record's entries. + * Decode preserves string and `Blob` leaves. Encode flattens nested objects and + * arrays into bracket-path entries and returns an empty `FormData` for + * non-object inputs. * * **Example** (Decoding FormData) * @@ -1538,27 +1606,31 @@ export const fromJsonString = new Transformation( * ) * ``` * - * See also: - * - {@link fromURLSearchParams} - * - {@link fromJsonString} + * @see {@link fromURLSearchParams} + * @see {@link fromJsonString} * + * @category decoding * @since 4.0.0 */ export const fromFormData = new Transformation( - Getter.decodeFormData(), - Getter.encodeFormData() + SchemaGetter.decodeFormData(), + SchemaGetter.encodeFormData() ) /** - * Decodes a `URLSearchParams` instance into an `unknown` record and encodes - * an `unknown` record back to `URLSearchParams`. + * Decodes `URLSearchParams` into a nested record using bracket-path keys and + * encodes object-like values back into `URLSearchParams`. * - * When to use this: - * - Parsing URL query parameters. + * **When to use** * - * Behavior: - * - Decode: extracts entries from URLSearchParams into a plain object. - * - Encode: constructs URLSearchParams from the record's entries. + * Use when you need a schema transformation for query strings whose keys, such + * as `filter[name]` or `items[0]`, should become nested data. + * + * **Details** + * + * Decode produces string leaves. Encode flattens nested objects and arrays into + * bracket-path entries and returns empty `URLSearchParams` for non-object + * inputs. * * **Example** (Decoding URLSearchParams) * @@ -1570,18 +1642,35 @@ export const fromFormData = new Transformation( * ) * ``` * - * See also: - * - {@link fromFormData} - * - {@link fromJsonString} + * @see {@link fromFormData} + * @see {@link fromJsonString} * + * @category decoding * @since 4.0.0 */ export const fromURLSearchParams = new Transformation( - Getter.decodeURLSearchParams(), - Getter.encodeURLSearchParams() + SchemaGetter.decodeURLSearchParams(), + SchemaGetter.encodeURLSearchParams() ) /** + * Decodes a numeric time-zone offset in milliseconds into a + * `DateTime.TimeZone.Offset` and encodes it back to the offset number. + * + * **When to use** + * + * Use when you need a schema transformation to represent fixed-offset time + * zones with numeric millisecond offsets. + * + * **Details** + * + * Decode uses `DateTime.zoneMakeOffset`; encode returns the offset's `offset` + * field. + * + * @see {@link timeZoneFromString} for IANA or offset string encodings + * @see {@link timeZoneNamedFromString} for IANA named-zone strings + * + * @category transforming * @since 4.0.0 */ export const timeZoneOffsetFromNumber: Transformation = transform< @@ -1593,6 +1682,22 @@ export const timeZoneOffsetFromNumber: Transformation = transformOrFail< @@ -1601,7 +1706,8 @@ export const timeZoneNamedFromString: Transformation({ decode: (s) => { return Option.match(DateTime.zoneMakeNamed(s), { - onNone: () => Effect.fail(new Issue.InvalidValue(Option.some(s), { message: `Invalid IANA time zone: ${s}` })), + onNone: () => + Effect.fail(new SchemaIssue.InvalidValue(Option.some(s), { message: `Invalid IANA time zone: ${s}` })), onSome: Effect.succeed }) }, @@ -1609,6 +1715,24 @@ export const timeZoneNamedFromString: Transformation = transformOrFail< @@ -1617,7 +1741,7 @@ export const timeZoneFromString: Transformation = tra >({ decode: (s) => { return Option.match(DateTime.zoneFromString(s), { - onNone: () => Effect.fail(new Issue.InvalidValue(Option.some(s), { message: `Invalid time zone: ${s}` })), + onNone: () => Effect.fail(new SchemaIssue.InvalidValue(Option.some(s), { message: `Invalid time zone: ${s}` })), onSome: Effect.succeed }) }, @@ -1625,6 +1749,24 @@ export const timeZoneFromString: Transformation = tra }) /** + * Decodes a date-time string into a `DateTime.Utc` and encodes it back to an ISO + * string. + * + * **When to use** + * + * Use when you need a schema transformation to decode date-time strings to a + * normalized `DateTime.Utc` and encode back as a UTC ISO string. + * + * **Details** + * + * Decode accepts strings supported by `DateTime.make`, converts the result to + * UTC, and fails with `InvalidValue` when parsing fails. Encode uses + * `DateTime.formatIso`. + * + * @see {@link dateTimeZonedFromString} for ISO strings that should preserve zoned date-time information + * @see {@link dateFromString} for decoding into JavaScript `Date` + * + * @category transforming * @since 4.0.0 */ export const dateTimeUtcFromString: Transformation = transformOrFail< @@ -1634,7 +1776,7 @@ export const dateTimeUtcFromString: Transformation = trans decode: (s) => { return Option.match(DateTime.make(s), { onNone: () => - Effect.fail(new Issue.InvalidValue(Option.some(s), { message: `Invalid UTC DateTime string: ${s}` })), + Effect.fail(new SchemaIssue.InvalidValue(Option.some(s), { message: `Invalid UTC DateTime string: ${s}` })), onSome: (result) => Effect.succeed(DateTime.toUtc(result)) }) }, @@ -1642,6 +1784,23 @@ export const dateTimeUtcFromString: Transformation = trans }) /** + * Decodes a zoned date-time string into a `DateTime.Zoned` and encodes it back + * to an ISO zoned string. + * + * **When to use** + * + * Use when you need a schema transformation for ISO zoned date-time strings + * that decode to `DateTime.Zoned` and encode with `DateTime.formatIsoZoned`. + * + * **Details** + * + * Decode uses `DateTime.makeZonedFromString` and fails with `InvalidValue` when + * the input is not a valid zoned date-time. Encode uses + * `DateTime.formatIsoZoned`. + * + * @see {@link dateTimeUtcFromString} for date-time strings that should decode to `DateTime.Utc` and encode as UTC ISO strings + * + * @category transforming * @since 4.0.0 */ export const dateTimeZonedFromString: Transformation = transformOrFail< @@ -1651,7 +1810,7 @@ export const dateTimeZonedFromString: Transformation = t decode: (s) => { return Option.match(DateTime.makeZonedFromString(s), { onNone: () => - Effect.fail(new Issue.InvalidValue(Option.some(s), { message: `Invalid Zoned DateTime string: ${s}` })), + Effect.fail(new SchemaIssue.InvalidValue(Option.some(s), { message: `Invalid Zoned DateTime string: ${s}` })), onSome: Effect.succeed }) }, diff --git a/.opencode/node_modules/effect/src/SchemaUtils.ts b/.opencode/node_modules/effect/src/SchemaUtils.ts index ab8800a07e24debb777cec88ae830a29ac7d6ac8..1746d087aa473cab0819dfb5cb228f8e0450c46e 100644 --- a/.opencode/node_modules/effect/src/SchemaUtils.ts +++ b/.opencode/node_modules/effect/src/SchemaUtils.ts @@ -1,13 +1,37 @@ /** + * Small helpers for schema patterns that are too specialized for the main + * `Schema` module. The current helper builds a schema for an existing class: + * the encoded input is checked with a struct schema, decoding calls the class + * constructor with the decoded properties, and the final value remains an + * instance of that class. + * * @since 4.0.0 */ import { identity } from "./Function.ts" import * as Schema from "./Schema.ts" -import * as Transformation from "./SchemaTransformation.ts" +import * as SchemaTransformation from "./SchemaTransformation.ts" /** + * Builds an experimental schema for instances of a native class using a struct + * schema as the encoded representation. + * + * **When to use** + * + * Use when you need a schema for an existing native class while keeping a + * `Struct` schema as its encoded representation. + * + * **Details** + * + * Decoding constructs `new constructor(props)` from the encoded fields. + * Encoding uses the instance as the encoded shape, so the class should expose + * properties compatible with the provided encoding schema. + * + * @see {@link Schema.instanceOf} for validating existing class instances without a struct encoding + * @see {@link Schema.Class} for defining schema-backed classes directly + * @see {@link Schema.ErrorClass} for defining schema-backed error classes + * + * @category schemas * @since 4.0.0 - * @experimental */ export function getNativeClassSchema any, S extends Schema.Struct>( constructor: C, @@ -16,7 +40,7 @@ export function getNativeClassSchema any, S exten readonly annotations?: Schema.Annotations.Declaration> } ): Schema.decodeTo, S["Iso"]>, S> { - const transformation = Transformation.transform, S["Type"]>({ + const transformation = SchemaTransformation.transform, S["Type"]>({ decode: (props) => new constructor(props), encode: identity }) diff --git a/.opencode/node_modules/effect/src/Scope.ts b/.opencode/node_modules/effect/src/Scope.ts index 69c7003bd26979d8bd3c4b91c7419d6f135e34b1..01dad901161503e798dcb3435caef987429b5e88 100644 --- a/.opencode/node_modules/effect/src/Scope.ts +++ b/.opencode/node_modules/effect/src/Scope.ts @@ -1,15 +1,11 @@ /** - * The `Scope` module provides functionality for managing resource lifecycles - * and cleanup operations in a functional and composable manner. + * Controls how long resources stay open. * - * A `Scope` represents a context where resources can be acquired and automatically - * cleaned up when the scope is closed. This is essential for managing resources - * like file handles, database connections, or any other resources that need - * proper cleanup. - * - * Scopes support both sequential and parallel finalization strategies: - * - Sequential: Finalizers run one after another in reverse order of registration - * - Parallel: Finalizers run concurrently for better performance + * A scope is a lifetime boundary. Code can register cleanup effects on it, and + * closing the scope runs those cleanups with the `Exit` value that ended the + * work. Most application code uses higher-level APIs such as `Effect.scoped` + * and `Layer`, while this module is useful when code needs to create, provide, + * fork, close, or inspect scopes directly. * * @since 2.0.0 */ @@ -27,7 +23,8 @@ const CloseableTypeId = effect.ScopeCloseableTypeId * automatically cleaned up when the scope is closed. Scopes can use * either sequential or parallel finalization strategies. * - * @example + * **Example** (Managing scoped resources) + * * ```ts * import { Effect, Exit, Scope } from "effect" * @@ -44,8 +41,8 @@ const CloseableTypeId = effect.ScopeCloseableTypeId * }) * ``` * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface Scope { readonly [TypeId]: typeof TypeId @@ -56,7 +53,8 @@ export interface Scope { * A `Closeable` scope extends the base `Scope` interface with the ability * to be closed, executing all registered finalizers. * - * @example + * **Example** (Closing a scope) + * * ```ts * import { Console, Effect, Exit, Scope } from "effect" * @@ -71,18 +69,20 @@ export interface Scope { * }) * ``` * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface Closeable extends Scope { readonly [CloseableTypeId]: typeof CloseableTypeId } /** - * The `State` namespace contains types representing the different states - * a scope can be in: Open (accepting new finalizers) or Closed (no longer accepting finalizers). + * The `State` namespace contains the concrete states of a scope: `Empty` + * before any finalizers are registered, `Open` with registered finalizers, and + * `Closed` with the exit value used to close the scope. + * + * **Example** (Checking scope states) * - * @example * ```ts * import { Effect, Exit, Scope } from "effect" * @@ -104,15 +104,20 @@ export interface Closeable extends Scope { * }) * ``` * - * @since 2.0.0 - * @category models + * @since 4.0.0 */ -export namespace State { +export declare namespace State { /** - * Represents an open scope state where finalizers can be added and - * the scope is still accepting new resources. + * Represents an open scope with no registered finalizers yet. + * + * **Details** + * + * Adding the first finalizer transitions the scope to `Open`; closing an + * empty scope transitions directly to `Closed` without producing a finalizer + * effect. + * + * **Example** (Inspecting an empty scope state) * - * @example * ```ts * import { Scope } from "effect" * @@ -125,8 +130,8 @@ export namespace State { * } * ``` * - * @since 2.0.0 * @category models + * @since 4.0.0 */ export type Empty = { readonly _tag: "Empty" @@ -135,7 +140,8 @@ export namespace State { * Represents an open scope state where finalizers can be added and * the scope is still accepting new resources. * - * @example + * **Example** (Inspecting an open scope state) + * * ```ts * import { Scope } from "effect" * @@ -148,8 +154,8 @@ export namespace State { * } * ``` * - * @since 2.0.0 * @category models + * @since 4.0.0 */ export type Open = { readonly _tag: "Open" @@ -159,7 +165,8 @@ export namespace State { * Represents a closed scope state where finalizers have been executed * and the scope is no longer accepting new resources. * - * @example + * **Example** (Inspecting a closed scope state) + * * ```ts * import { Effect, Exit, Scope } from "effect" * @@ -177,8 +184,8 @@ export namespace State { * }) * ``` * - * @since 2.0.0 * @category models + * @since 4.0.0 */ export type Closed = { readonly _tag: "Closed" @@ -187,9 +194,15 @@ export namespace State { } /** - * The service tag for `Scope`, used for dependency injection in the Effect system. + * Service tag for the active resource lifetime. + * + * **When to use** + * + * Use to access the active lifetime when registering finalizers or sharing + * resources with the surrounding scope. + * + * **Example** (Accessing the scope service) * - * @example * ```ts * import { Effect, Scope } from "effect" * @@ -205,15 +218,16 @@ export namespace State { * const scoped = Effect.scoped(program) * ``` * + * @category services * @since 2.0.0 - * @category tags */ export const Scope: Context.Service = effect.scopeTag /** * Creates a new `Scope` with the specified finalizer strategy. * - * @example + * **Example** (Creating a scope) + * * ```ts * import { Console, Effect, Exit, Scope } from "effect" * @@ -241,7 +255,13 @@ export const make: (finalizerStrategy?: "sequential" | "parallel") => Effect Effect Closeable = effect.scopeMakeUnsafe /** - * Provides a `Scope` to an `Effect`, removing the `Scope` requirement from its context. - * This allows you to run effects that require a scope by explicitly providing one. + * Provides a concrete `Scope` to an effect. + * + * **When to use** * - * **Previously Known As** + * Use to run an effect that requires `Scope` with a scope managed by the + * caller. * - * This API replaces the following from Effect 3.x: + * **Details** * - * - `Scope.extend` + * Providing the scope removes the `Scope` requirement from the effect context. + * + * **Example** (Providing a scope) * - * @example * ```ts * import { Console, Effect, Scope } from "effect" * @@ -288,21 +311,24 @@ export const makeUnsafe: (finalizerStrategy?: "sequential" | "parallel") => Clos * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const provide: { /** - * Provides a `Scope` to an `Effect`, removing the `Scope` requirement from its context. - * This allows you to run effects that require a scope by explicitly providing one. + * Provides a concrete `Scope` to an effect. + * + * **When to use** * - * **Previously Known As** + * Use to run an effect that requires `Scope` with a scope managed by the + * caller. * - * This API replaces the following from Effect 3.x: + * **Details** * - * - `Scope.extend` + * Providing the scope removes the `Scope` requirement from the effect context. + * + * **Example** (Providing a scope) * - * @example * ```ts * import { Console, Effect, Scope } from "effect" * @@ -320,21 +346,24 @@ export const provide: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (value: Scope): (self: Effect) => Effect> /** - * Provides a `Scope` to an `Effect`, removing the `Scope` requirement from its context. - * This allows you to run effects that require a scope by explicitly providing one. + * Provides a concrete `Scope` to an effect. * - * **Previously Known As** + * **When to use** * - * This API replaces the following from Effect 3.x: + * Use to run an effect that requires `Scope` with a scope managed by the + * caller. * - * - `Scope.extend` + * **Details** + * + * Providing the scope removes the `Scope` requirement from the effect context. + * + * **Example** (Providing a scope) * - * @example * ```ts * import { Console, Effect, Scope } from "effect" * @@ -352,17 +381,28 @@ export const provide: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Effect, value: Scope): Effect> } = effect.provideScope /** - * Adds a finalizer to a scope that will be executed when the scope is closed. - * Finalizers are cleanup functions that receive the exit value of the scope. + * Registers an exit-aware finalizer on a scope. + * + * **When to use** + * + * Use when cleanup needs to know whether the scope closed with success, + * failure, or interruption. + * + * **Details** + * + * If the scope is open, the finalizer runs when the scope closes and receives + * the scope's exit value. If the scope is already closed, the finalizer runs + * immediately with the stored exit value. + * + * **Example** (Adding an exit-aware finalizer) * - * @example * ```ts * import { Console, Effect, Exit, Scope } from "effect" * @@ -389,17 +429,22 @@ export const provide: { * ``` * * @category combinators - * @since 4.0.0 + * @since 2.0.0 */ export const addFinalizerExit: (scope: Scope, finalizer: (exit: Exit) => Effect) => Effect = effect.scopeAddFinalizerExit /** - * Adds a finalizer to a scope. The finalizer is a simple `Effect` that will be - * executed when the scope is closed, regardless of whether the scope closes - * successfully or with an error. + * Registers a finalizer effect on a scope. + * + * **Details** + * + * If the scope is open, the finalizer runs when the scope closes, regardless of + * whether the scope closes successfully or with an error. If the scope is + * already closed, the finalizer runs immediately. + * + * **Example** (Adding finalizers) * - * @example * ```ts * import { Console, Effect, Exit, Scope } from "effect" * @@ -419,16 +464,22 @@ export const addFinalizerExit: (scope: Scope, finalizer: (exit: Exit) * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 2.0.0 */ export const addFinalizer: (scope: Scope, finalizer: Effect) => Effect = effect.scopeAddFinalizer /** - * Creates a child scope from a parent scope. The child scope inherits the - * parent's finalization strategy unless overridden. + * Creates a closeable child scope registered with a parent scope. + * + * **Details** + * + * Closing the parent closes the child with the same exit value, and closing the + * child detaches it from the parent. The optional finalizer strategy configures + * the child scope and defaults to `"sequential"` when omitted. + * + * **Example** (Creating a child scope) * - * @example * ```ts * import { Console, Effect, Exit, Scope } from "effect" * @@ -451,7 +502,7 @@ export const addFinalizer: (scope: Scope, finalizer: Effect) => Effect< * ``` * * @category combinators - * @since 4.0.0 + * @since 2.0.0 */ export const fork: ( scope: Scope, @@ -459,10 +510,21 @@ export const fork: ( ) => Effect = effect.scopeFork /** - * Creates a child scope from a parent scope synchronously without wrapping it in an `Effect`. - * The child scope inherits the parent's finalization strategy unless overridden. + * Creates a closeable child scope synchronously and registers it with a parent scope. + * + * **When to use** + * + * Use when a child scope must be created synchronously and the caller controls + * both parent and child scope lifetimes. + * + * **Details** + * + * Closing the parent closes the child with the same exit value, and closing the + * child detaches it from the parent. The optional finalizer strategy configures + * the child scope and defaults to `"sequential"` when omitted. + * + * **Example** (Creating a child scope synchronously) * - * @example * ```ts * import { Console, Effect, Exit, Scope } from "effect" * @@ -480,17 +542,26 @@ export const fork: ( * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const forkUnsafe: (scope: Scope, finalizerStrategy?: "sequential" | "parallel") => Closeable = effect.scopeForkUnsafe /** - * Closes a scope, running all registered finalizers in the appropriate order. - * The exit value is passed to each finalizer. + * Closes a scope and runs its registered finalizers. + * + * **When to use** + * + * Use to close a scope manually with a specific exit value. + * + * **Details** + * + * Finalizers run in the scope's configured order and receive the supplied + * `Exit`. + * + * **Example** (Running scope finalizers) * - * @example * ```ts * import { Console, Effect, Exit, Scope } from "effect" * @@ -512,29 +583,100 @@ export const forkUnsafe: (scope: Scope, finalizerStrategy?: "sequential" | "para * ``` * * @category combinators - * @since 4.0.0 + * @since 2.0.0 */ export const close: (self: Scope, exit: Exit) => Effect = effect.scopeClose /** + * Closes a scope unsafely with the provided exit value. + * + * **When to use** + * + * Use when implementing lower-level scope machinery that must transition a + * scope to `Closed` immediately and can run the returned finalizer effect when + * one is produced. + * + * **Details** + * + * Returns an effect that runs registered finalizers, or `undefined` when the + * scope was already closed or no finalizers need to run. + * + * **Gotchas** + * + * Ignoring the returned effect skips registered finalizers. + * + * @see {@link close} for the usual effectful close operation that always returns an `Effect` + * + * @category unsafe * @since 4.0.0 */ export const closeUnsafe: (self: Scope, exit_: Exit) => Effect | undefined = effect.scopeCloseUnsafe /** + * Runs an effect with the provided closeable scope in its context and closes + * that scope when the effect exits. + * + * **When to use** + * + * Use when you already have a `Closeable` scope and want to run an effect that + * requires `Scope` while automatically closing that scope when the effect exits. + * + * **Details** + * + * The scope is closed with the same exit value as the effect, so registered + * finalizers can observe whether the effect succeeded, failed, or was + * interrupted. + * + * @see `provide` for providing a scope without closing it automatically + * @see `Effect.scoped` for creating and closing a fresh scope around a workflow + * * @category combinators - * @since 4.0.0 + * @since 2.0.0 */ export const use: { /** + * Runs an effect with the provided closeable scope in its context and closes + * that scope when the effect exits. + * + * **When to use** + * + * Use when you already have a `Closeable` scope and want to run an effect that + * requires `Scope` while automatically closing that scope when the effect exits. + * + * **Details** + * + * The scope is closed with the same exit value as the effect, so registered + * finalizers can observe whether the effect succeeded, failed, or was + * interrupted. + * + * @see `provide` for providing a scope without closing it automatically + * @see `Effect.scoped` for creating and closing a fresh scope around a workflow + * * @category combinators - * @since 4.0.0 + * @since 2.0.0 */ (scope: Closeable): (self: Effect) => Effect> /** + * Runs an effect with the provided closeable scope in its context and closes + * that scope when the effect exits. + * + * **When to use** + * + * Use when you already have a `Closeable` scope and want to run an effect that + * requires `Scope` while automatically closing that scope when the effect exits. + * + * **Details** + * + * The scope is closed with the same exit value as the effect, so registered + * finalizers can observe whether the effect succeeded, failed, or was + * interrupted. + * + * @see `provide` for providing a scope without closing it automatically + * @see `Effect.scoped` for creating and closing a fresh scope around a workflow + * * @category combinators - * @since 4.0.0 + * @since 2.0.0 */ (self: Effect, scope: Closeable): Effect> } = effect.scopeUse diff --git a/.opencode/node_modules/effect/src/ScopedCache.ts b/.opencode/node_modules/effect/src/ScopedCache.ts index 0dda4dcbc4679e77b2464f54ac53d82d0a1c4437..68a39596089bb83b49b5d3992594f7a6325ecbca 100644 --- a/.opencode/node_modules/effect/src/ScopedCache.ts +++ b/.opencode/node_modules/effect/src/ScopedCache.ts @@ -1,4 +1,13 @@ /** + * Caches values that need scoped resource management. + * + * Each cached entry owns its own `Scope`, so resources opened while creating a + * value stay alive while that entry is cached and are released when the entry is + * removed. A `ScopedCache` also belongs to an outer scope, which closes all + * remaining entries when the cache is closed. Lookups for the same missing key + * share one in-progress effect, and entries can expire, be refreshed, be + * invalidated, or be evicted by capacity limits. + * * @since 4.0.0 */ import * as Arr from "./Array.ts" @@ -21,8 +30,26 @@ import * as Scope from "./Scope.ts" const TypeId = "~effect/ScopedCache" /** - * @since 4.0.0 - * @category Models + * A scoped cache whose values are acquired by a lookup effect and stored in + * per-entry scopes. + * + * **When to use** + * + * Use to cache values that acquire scoped resources and must release those + * resources when entries expire, are evicted, or are invalidated. + * + * **Details** + * + * Concurrent requests for the same key share the same in-flight lookup. + * Entries can expire based on the lookup exit, are evicted when capacity is + * exceeded, and release their entry scopes when invalidated, evicted, expired, + * or when the cache's owning scope closes. + * + * @see {@link make} for creating a scoped cache with a fixed time-to-live + * @see {@link makeWith} for creating a scoped cache with dynamic time-to-live + * + * @category models + * @since 2.0.0 */ export interface ScopedCache extends Pipeable { readonly [TypeId]: typeof TypeId @@ -33,8 +60,20 @@ export interface ScopedCache = { readonly _tag: "Open" @@ -44,11 +83,23 @@ export type State = { } /** - * Represents a cache entry containing a deferred value and optional expiration time. - * This is used internally by the cache implementation to track cached values and their lifetimes. + * A single scoped cache entry. * + * **When to use** + * + * Use when inspecting the open state of a `ScopedCache` and you need the stored + * deferred result, entry scope, or expiration timestamp for a key. + * + * **Details** + * + * The entry contains the deferred lookup result shared by readers, the scope + * that owns resources acquired while computing the value, and an optional + * expiration time in milliseconds. Removing the entry closes its scope. + * + * @see {@link State} for the open/closed cache state that stores entries by key + * + * @category models * @since 4.0.0 - * @category Models */ export interface Entry { expiresAt: number | undefined @@ -57,8 +108,26 @@ export interface Entry { } /** - * @since 4.0.0 - * @category Constructors + * Creates a `ScopedCache` from a lookup function, maximum capacity, and a + * time-to-live function computed from each lookup exit and key. + * + * **When to use** + * + * Use when you need a scoped cache whose entry lifetime depends on each lookup + * result or key. + * + * **Details** + * + * The cache must be constructed in a `Scope`. Each lookup runs in its own entry + * scope, and that scope is closed when the entry expires, is invalidated, is + * evicted by capacity, or when the cache's owning scope closes. + * `requireServicesAt` controls whether lookup services are captured at + * construction time or required when lookup operations run. + * + * @see {@link make} for creating a scoped cache with one fixed time-to-live + * + * @category constructors + * @since 2.0.0 */ export const makeWith = < Key, @@ -103,8 +172,24 @@ export const makeWith = < }) /** - * @since 4.0.0 - * @category Constructors + * Creates a `ScopedCache` with a fixed time-to-live for every lookup result. + * + * **When to use** + * + * Use to create a scoped cache when every cached lookup result should share the + * same lifetime. + * + * **Details** + * + * This is the constant-TTL variant of `makeWith`: values are acquired by the + * lookup effect in per-entry scopes, capacity can evict older entries, and + * entry scopes are closed when entries expire, are invalidated, are evicted, or + * when the cache's owning scope closes. + * + * @see {@link makeWith} for computing time-to-live from each lookup result and key + * + * @category constructors + * @since 2.0.0 */ export const make = < Key, @@ -144,18 +229,75 @@ const Proto = { const defaultTimeToLive = (_: Exit.Exit, _key: unknown): Duration.Duration => Duration.infinity /** + * Gets the value for a key, running the cache lookup when no unexpired entry is + * present. + * + * **When to use** + * + * Use to retrieve a scoped cached value by key when a missing or expired entry + * should run the cache lookup and share the in-flight lookup with concurrent + * callers. + * + * **Details** + * + * Concurrent `get` calls for the same key share the same in-flight lookup. + * Successful and failed lookup exits are cached according to the configured + * TTL. If the cache is closed, the effect is interrupted. + * + * @see {@link getOption} for reading only when an unexpired entry is already cached + * @see {@link getSuccess} for inspecting an already-completed successful entry + * @see {@link refresh} for forcing a new lookup + * + * @category combinators * @since 4.0.0 - * @category Combinators */ export const get: { /** + * Gets the value for a key, running the cache lookup when no unexpired entry is + * present. + * + * **When to use** + * + * Use to retrieve a scoped cached value by key when a missing or expired entry + * should run the cache lookup and share the in-flight lookup with concurrent + * callers. + * + * **Details** + * + * Concurrent `get` calls for the same key share the same in-flight lookup. + * Successful and failed lookup exits are cached according to the configured + * TTL. If the cache is closed, the effect is interrupted. + * + * @see {@link getOption} for reading only when an unexpired entry is already cached + * @see {@link getSuccess} for inspecting an already-completed successful entry + * @see {@link refresh} for forcing a new lookup + * + * @category combinators * @since 4.0.0 - * @category Combinators */ (key: Key): (self: ScopedCache) => Effect.Effect /** + * Gets the value for a key, running the cache lookup when no unexpired entry is + * present. + * + * **When to use** + * + * Use to retrieve a scoped cached value by key when a missing or expired entry + * should run the cache lookup and share the in-flight lookup with concurrent + * callers. + * + * **Details** + * + * Concurrent `get` calls for the same key share the same in-flight lookup. + * Successful and failed lookup exits are cached according to the configured + * TTL. If the cache is closed, the effect is interrupted. + * + * @see {@link getOption} for reading only when an unexpired entry is already cached + * @see {@link getSuccess} for inspecting an already-completed successful entry + * @see {@link refresh} for forcing a new lookup + * + * @category combinators * @since 4.0.0 - * @category Combinators */ (self: ScopedCache, key: Key): Effect.Effect } = dual( @@ -176,12 +318,50 @@ export const get: { } const scope = Scope.makeUnsafe() const deferred = Deferred.makeUnsafe() const entry: Entry = { @@ -233,18 +413,66 @@ const checkCapacity = ( } /** + * Reads an existing unexpired cache entry without running the lookup function. + * + * **When to use** + * + * Use to read a scoped value only when it is already cached, without starting + * the lookup for missing or expired keys. + * + * **Details** + * + * Returns `Option.none` when the key is absent or expired. If an entry exists, + * the effect waits for its cached result and returns `Option.some(value)` on + * success, or fails with the cached lookup error. + * + * @see {@link get} for running the lookup on missing or expired keys + * @see {@link getSuccess} for inspecting only already-completed successful entries + * + * @category combinators * @since 4.0.0 - * @category Combinators */ export const getOption: { /** + * Reads an existing unexpired cache entry without running the lookup function. + * + * **When to use** + * + * Use to read a scoped value only when it is already cached, without starting + * the lookup for missing or expired keys. + * + * **Details** + * + * Returns `Option.none` when the key is absent or expired. If an entry exists, + * the effect waits for its cached result and returns `Option.some(value)` on + * success, or fails with the cached lookup error. + * + * @see {@link get} for running the lookup on missing or expired keys + * @see {@link getSuccess} for inspecting only already-completed successful entries + * + * @category combinators * @since 4.0.0 - * @category Combinators */ (key: Key): (self: ScopedCache) => Effect.Effect, E> /** + * Reads an existing unexpired cache entry without running the lookup function. + * + * **When to use** + * + * Use to read a scoped value only when it is already cached, without starting + * the lookup for missing or expired keys. + * + * **Details** + * + * Returns `Option.none` when the key is absent or expired. If an entry exists, + * the effect waits for its cached result and returns `Option.some(value)` on + * success, or fails with the cached lookup error. + * + * @see {@link get} for running the lookup on missing or expired keys + * @see {@link getSuccess} for inspecting only already-completed successful entries + * + * @category combinators * @since 4.0.0 - * @category Combinators */ (self: ScopedCache, key: Key): Effect.Effect, E> } = dual( @@ -290,24 +518,63 @@ const getImpl = ( * Retrieves the value associated with the specified key from the cache, only if * it contains a resolved successful value. * + * **When to use** + * + * Use to inspect an already-completed successful scoped cache entry without + * running or awaiting the lookup effect. + * + * **Details** + * + * Returns `Option.some` for a resolved successful entry. Returns `Option.none` + * for missing, expired, failed, or still-pending entries. + * + * @see {@link get} for awaiting or starting the lookup effect + * @see {@link getOption} for awaiting an already-cached entry without starting a lookup + * + * @category combinators * @since 4.0.0 - * @category Combinators */ export const getSuccess: { /** * Retrieves the value associated with the specified key from the cache, only if * it contains a resolved successful value. * + * **When to use** + * + * Use to inspect an already-completed successful scoped cache entry without + * running or awaiting the lookup effect. + * + * **Details** + * + * Returns `Option.some` for a resolved successful entry. Returns `Option.none` + * for missing, expired, failed, or still-pending entries. + * + * @see {@link get} for awaiting or starting the lookup effect + * @see {@link getOption} for awaiting an already-cached entry without starting a lookup + * + * @category combinators * @since 4.0.0 - * @category Combinators */ (key: Key): (self: ScopedCache) => Effect.Effect> /** * Retrieves the value associated with the specified key from the cache, only if * it contains a resolved successful value. * + * **When to use** + * + * Use to inspect an already-completed successful scoped cache entry without + * running or awaiting the lookup effect. + * + * **Details** + * + * Returns `Option.some` for a resolved successful entry. Returns `Option.none` + * for missing, expired, failed, or still-pending entries. + * + * @see {@link get} for awaiting or starting the lookup effect + * @see {@link getOption} for awaiting an already-cached entry without starting a lookup + * + * @category combinators * @since 4.0.0 - * @category Combinators */ (self: ScopedCache, key: Key): Effect.Effect> } = dual( @@ -330,27 +597,66 @@ export const getSuccess: { ) /** - * Sets the value associated with the specified key in the cache. This will - * overwrite any existing value for that key, skipping the lookup function. + * Sets a successful value for a key without running the lookup function. + * + * **When to use** + * + * Use to seed or overwrite a scoped cache entry with an already available + * successful value. * + * **Details** + * + * This replaces and closes any existing entry scope for the key, applies the + * cache's TTL using a successful exit for the value, and may evict older + * entries if the cache capacity is exceeded. + * + * @see {@link get} for reading or computing a cached value + * @see {@link refresh} for replacing an entry by running the lookup function + * + * @category combinators * @since 4.0.0 - * @category Combinators */ export const set: { /** - * Sets the value associated with the specified key in the cache. This will - * overwrite any existing value for that key, skipping the lookup function. + * Sets a successful value for a key without running the lookup function. + * + * **When to use** + * + * Use to seed or overwrite a scoped cache entry with an already available + * successful value. + * + * **Details** + * + * This replaces and closes any existing entry scope for the key, applies the + * cache's TTL using a successful exit for the value, and may evict older + * entries if the cache capacity is exceeded. * + * @see {@link get} for reading or computing a cached value + * @see {@link refresh} for replacing an entry by running the lookup function + * + * @category combinators * @since 4.0.0 - * @category Combinators */ (key: Key, value: A): (self: ScopedCache) => Effect.Effect /** - * Sets the value associated with the specified key in the cache. This will - * overwrite any existing value for that key, skipping the lookup function. + * Sets a successful value for a key without running the lookup function. + * + * **When to use** + * + * Use to seed or overwrite a scoped cache entry with an already available + * successful value. + * + * **Details** + * + * This replaces and closes any existing entry scope for the key, applies the + * cache's TTL using a successful exit for the value, and may evict older + * entries if the cache capacity is exceeded. + * + * @see {@link get} for reading or computing a cached value + * @see {@link refresh} for replacing an entry by running the lookup function * + * @category combinators * @since 4.0.0 - * @category Combinators */ (self: ScopedCache, key: Key, value: A): Effect.Effect } = dual( @@ -365,18 +671,44 @@ export const set: { const state = self.state const exit = core.exitSucceed(value) const deferred = Deferred.makeUnsafe() Deferred.doneUnsafe(deferred, exit) @@ -397,24 +729,66 @@ export const set: { ) /** - * Checks if the cache contains an entry for the specified key. + * Checks whether the cache contains an entry for the specified key. + * + * **When to use** + * + * Use to test whether an unexpired entry exists for a key without running the + * cache lookup. + * + * **Details** + * + * This does not start lookups and does not refresh access order. Expired + * entries are treated as absent and their scopes are closed while checking. If + * the cache is closed, the effect is interrupted. * + * @see {@link getOption} for reading an existing cached entry + * @see {@link get} for running the lookup on missing or expired keys + * + * @category combinators * @since 4.0.0 - * @category Combinators */ export const has: { /** - * Checks if the cache contains an entry for the specified key. + * Checks whether the cache contains an entry for the specified key. + * + * **When to use** + * + * Use to test whether an unexpired entry exists for a key without running the + * cache lookup. + * + * **Details** * + * This does not start lookups and does not refresh access order. Expired + * entries are treated as absent and their scopes are closed while checking. If + * the cache is closed, the effect is interrupted. + * + * @see {@link getOption} for reading an existing cached entry + * @see {@link get} for running the lookup on missing or expired keys + * + * @category combinators * @since 4.0.0 - * @category Combinators */ (key: Key): (self: ScopedCache) => Effect.Effect /** - * Checks if the cache contains an entry for the specified key. + * Checks whether the cache contains an entry for the specified key. + * + * **When to use** * + * Use to test whether an unexpired entry exists for a key without running the + * cache lookup. + * + * **Details** + * + * This does not start lookups and does not refresh access order. Expired + * entries are treated as absent and their scopes are closed while checking. If + * the cache is closed, the effect is interrupted. + * + * @see {@link getOption} for reading an existing cached entry + * @see {@link get} for running the lookup on missing or expired keys + * + * @category combinators * @since 4.0.0 - * @category Combinators */ (self: ScopedCache, key: Key): Effect.Effect } = dual( @@ -426,24 +800,75 @@ export const has: { ) /** - * Invalidates the entry associated with the specified key in the cache. + * Removes the entry associated with a key and closes its entry scope. + * + * **When to use** + * + * Use to remove a single key from a scoped cache and release any resources owned + * by that entry before a later lookup computes it again. + * + * **Details** * + * If the key is absent, this is a no-op. + * + * **Gotchas** + * + * If the cache is closed, the effect is interrupted. + * + * @see {@link refresh} for replacing a key by running a new lookup immediately + * @see {@link invalidateWhen} for invalidating only when a cached value matches a predicate + * @see {@link invalidateAll} for removing every cached entry + * + * @category combinators * @since 4.0.0 - * @category Combinators */ export const invalidate: { /** - * Invalidates the entry associated with the specified key in the cache. + * Removes the entry associated with a key and closes its entry scope. + * + * **When to use** + * + * Use to remove a single key from a scoped cache and release any resources owned + * by that entry before a later lookup computes it again. + * + * **Details** * + * If the key is absent, this is a no-op. + * + * **Gotchas** + * + * If the cache is closed, the effect is interrupted. + * + * @see {@link refresh} for replacing a key by running a new lookup immediately + * @see {@link invalidateWhen} for invalidating only when a cached value matches a predicate + * @see {@link invalidateAll} for removing every cached entry + * + * @category combinators * @since 4.0.0 - * @category Combinators */ (key: Key): (self: ScopedCache) => Effect.Effect /** - * Invalidates the entry associated with the specified key in the cache. + * Removes the entry associated with a key and closes its entry scope. + * + * **When to use** + * + * Use to remove a single key from a scoped cache and release any resources owned + * by that entry before a later lookup computes it again. + * + * **Details** * + * If the key is absent, this is a no-op. + * + * **Gotchas** + * + * If the cache is closed, the effect is interrupted. + * + * @see {@link refresh} for replacing a key by running a new lookup immediately + * @see {@link invalidateWhen} for invalidating only when a cached value matches a predicate + * @see {@link invalidateAll} for removing every cached entry + * + * @category combinators * @since 4.0.0 - * @category Combinators */ (self: ScopedCache, key: Key): Effect.Effect } = dual(2, (self: ScopedCache, key: Key): Effect.Effect => @@ -462,27 +887,75 @@ export const invalidate: { )) /** - * Conditionally invalidates the entry associated with the specified key in the cache - * if the predicate returns true for the cached value. + * Invalidates the entry associated with the specified key in the cache when the + * predicate returns true for the cached value. + * + * **When to use** + * + * Use to remove an already-cached scoped value only when the successful cached + * value satisfies a predicate. + * + * **Details** * + * Returns `true` only when a successful cached value matches and is removed. It + * returns `false` for absent, expired, failed, or non-matching entries. + * + * **Gotchas** + * + * A matching invalidation closes the entry scope and releases its resources. + * + * @see {@link invalidate} for unconditional removal by key + * + * @category combinators * @since 4.0.0 - * @category Combinators */ export const invalidateWhen: { /** - * Conditionally invalidates the entry associated with the specified key in the cache - * if the predicate returns true for the cached value. + * Invalidates the entry associated with the specified key in the cache when the + * predicate returns true for the cached value. + * + * **When to use** + * + * Use to remove an already-cached scoped value only when the successful cached + * value satisfies a predicate. * + * **Details** + * + * Returns `true` only when a successful cached value matches and is removed. It + * returns `false` for absent, expired, failed, or non-matching entries. + * + * **Gotchas** + * + * A matching invalidation closes the entry scope and releases its resources. + * + * @see {@link invalidate} for unconditional removal by key + * + * @category combinators * @since 4.0.0 - * @category Combinators */ (key: Key, f: Predicate.Predicate): (self: ScopedCache) => Effect.Effect /** - * Conditionally invalidates the entry associated with the specified key in the cache - * if the predicate returns true for the cached value. + * Invalidates the entry associated with the specified key in the cache when the + * predicate returns true for the cached value. + * + * **When to use** + * + * Use to remove an already-cached scoped value only when the successful cached + * value satisfies a predicate. * + * **Details** + * + * Returns `true` only when a successful cached value matches and is removed. It + * returns `false` for absent, expired, failed, or non-matching entries. + * + * **Gotchas** + * + * A matching invalidation closes the entry scope and releases its resources. + * + * @see {@link invalidate} for unconditional removal by key + * + * @category combinators * @since 4.0.0 - * @category Combinators */ (self: ScopedCache, key: Key, f: Predicate.Predicate): Effect.Effect } = dual( @@ -514,31 +987,61 @@ export const invalidateWhen: { /** * Forces a refresh of the value associated with the specified key in the cache. * + * **When to use** + * + * Use to recompute a scoped cache entry immediately, even when an unexpired + * value is already cached. + * + * **Details** + * * It will always invoke the lookup function to construct a new value, * overwriting any existing value for that key. * + * @see {@link get} for reusing an unexpired entry before running the lookup + * @see {@link invalidate} for removing an entry without recomputing it + * + * @category combinators * @since 4.0.0 - * @category Combinators */ export const refresh: { /** * Forces a refresh of the value associated with the specified key in the cache. * + * **When to use** + * + * Use to recompute a scoped cache entry immediately, even when an unexpired + * value is already cached. + * + * **Details** + * * It will always invoke the lookup function to construct a new value, * overwriting any existing value for that key. * + * @see {@link get} for reusing an unexpired entry before running the lookup + * @see {@link invalidate} for removing an entry without recomputing it + * + * @category combinators * @since 4.0.0 - * @category Combinators */ (key: Key): (self: ScopedCache) => Effect.Effect /** * Forces a refresh of the value associated with the specified key in the cache. * + * **When to use** + * + * Use to recompute a scoped cache entry immediately, even when an unexpired + * value is already cached. + * + * **Details** + * * It will always invoke the lookup function to construct a new value, * overwriting any existing value for that key. * + * @see {@link get} for reusing an unexpired entry before running the lookup + * @see {@link invalidate} for removing an entry without recomputing it + * + * @category combinators * @since 4.0.0 - * @category Combinators */ (self: ScopedCache, key: Key): Effect.Effect } = dual( @@ -551,20 +1054,40 @@ export const refresh: { const deferred = Deferred.makeUnsafe() const entry: Entry = { @@ -602,10 +1125,20 @@ export const refresh: { ) /** - * Invalidates all entries in the cache. + * Removes every entry from the cache and closes each entry scope. + * + * **When to use** + * + * Use to clear a scoped cache and release resources owned by all cached entries. + * + * **Details** * + * If the cache is closed, the effect is interrupted. + * + * @see {@link invalidate} for removing one cached entry + * + * @category combinators * @since 4.0.0 - * @category Combinators */ export const invalidateAll = (self: ScopedCache): Effect.Effect => core.withFiber((parent) => { @@ -630,12 +1163,18 @@ const invalidateAllImpl = ( /** * Retrieves the approximate number of entries in the cache. * + * **When to use** + * + * Use to inspect how many entries are currently stored in the scoped cache. + * + * **Gotchas** + * * Note that expired entries are counted until they are accessed and removed. * The size reflects the current number of entries stored, not the number * of valid entries. * + * @category combinators * @since 4.0.0 - * @category Combinators */ export const size = (self: ScopedCache): Effect.Effect => effect.sync(() => self.state._tag === "Closed" ? 0 : MutableHashMap.size(self.state.map)) @@ -643,8 +1182,19 @@ export const size = (self: ScopedCache): Effect.Effe /** * Retrieves all active keys from the cache, automatically filtering out expired entries. * + * **When to use** + * + * Use to inspect currently cached unexpired keys without running cache lookups. + * + * **Gotchas** + * + * Expired entries are removed and their scopes are closed while filtering. + * + * @see {@link entries} for retrieving successful cached key-value pairs + * @see {@link values} for retrieving only successfully cached values + * + * @category combinators * @since 4.0.0 - * @category Combinators */ export const keys = (self: ScopedCache): Effect.Effect> => core.withFiber((fiber) => { @@ -668,19 +1218,43 @@ export const keys = (self: ScopedCache): Effect.Effe * Retrieves all successfully cached values from the cache, excluding failed * lookups and expired entries. * + * **When to use** + * + * Use to inspect currently successful cached values without running cache + * lookups. + * + * **Gotchas** + * + * Expired entries are removed and their scopes are closed while filtering. + * + * @see {@link entries} for retrieving successful cached key-value pairs + * @see {@link keys} for retrieving only cached keys + * + * @category combinators * @since 4.0.0 - * @category Combinators */ export const values = (self: ScopedCache): Effect.Effect> => effect.map(entries(self), Arr.map(([, value]) => value)) /** - * Retrieves all key-value pairs from the cache as an iterable. This function + * Retrieves all key-value pairs from the cache as an array. This function * only returns entries with successfully resolved values, filtering out any * failed lookups or expired entries. * + * **When to use** + * + * Use to inspect the currently successful cached key-value pairs without + * running cache lookups. + * + * **Gotchas** + * + * Expired entries are removed and their scopes are closed while filtering. + * + * @see {@link keys} for retrieving only cached keys + * @see {@link values} for retrieving only cached values + * + * @category combinators * @since 4.0.0 - * @category Combinators */ export const entries = (self: ScopedCache): Effect.Effect> => core.withFiber((fiber) => { diff --git a/.opencode/node_modules/effect/src/ScopedRef.ts b/.opencode/node_modules/effect/src/ScopedRef.ts index 45fddf4d070796b7c1bd2e8b5d642862469e6c39..78a6ed5b4b9b25fff2312ea033f5831f933ff9a3 100644 --- a/.opencode/node_modules/effect/src/ScopedRef.ts +++ b/.opencode/node_modules/effect/src/ScopedRef.ts @@ -1,4 +1,12 @@ /** + * Stores a current value together with the scope that owns it. + * + * A `ScopedRef` is useful for resource-backed values such as clients, + * connections, subscriptions, or handles. Replacing the value acquires the + * replacement in a new scope and releases the resources owned by the previous + * value. Reads can be effectful or synchronous, and updates are synchronized so + * only one replacement happens at a time. + * * @since 2.0.0 */ import * as Effect from "./Effect.ts" @@ -18,8 +26,14 @@ const TypeId = "~effect/ScopedRef" * resources). The reference itself takes care of properly releasing resources * for the old value whenever a new value is obtained. * - * @since 2.0.0 + * **When to use** + * + * Use when an application needs to keep a current resource-backed value and + * later replace it with another acquired value while ensuring the previous + * value is released. + * * @category models + * @since 2.0.0 */ export interface ScopedRef extends Pipeable { readonly [TypeId]: typeof TypeId @@ -47,11 +61,16 @@ const makeUnsafe = ( } /** - * Creates a new `ScopedRef` from an effect that resourcefully produces a - * value. + * Creates a new `ScopedRef` from an effect that acquires the initial value. * - * @since 2.0.0 + * **When to use** + * + * Use when creating a `ScopedRef` whose initial value requires acquiring + * resources that must be released. + * + * @see {@link make} for creating a `ScopedRef` from a value that does not require resource acquisition * @category constructors + * @since 2.0.0 */ export const fromAcquire: ( acquire: Effect.Effect @@ -69,27 +88,59 @@ export const fromAcquire: ( }, Effect.uninterruptible) /** - * Retrieves the current value of the scoped reference. + * Retrieves the current value of the scoped reference synchronously. + * + * **When to use** + * + * Use when you need immediate synchronous access to the current `ScopedRef` + * value and can guarantee that reading outside the `Effect` API is safe. + * + * @see {@link get} for Effect-wrapped access in Effect programs * - * @since 4.0.0 * @category getters + * @since 4.0.0 */ export const getUnsafe = (self: ScopedRef): A => self.backing.backing.ref.current[1] /** - * Retrieves the current value of the scoped reference. + * Retrieves the current value of the scoped reference effectfully. + * + * **When to use** + * + * Use to read the value currently stored in a `ScopedRef` inside an `Effect` + * workflow. + * + * @see {@link getUnsafe} for reading the current value synchronously when an unsafe read is acceptable * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export const get = (self: ScopedRef): Effect.Effect => Effect.sync(() => getUnsafe(self)) /** - * Creates a new `ScopedRef` from the specified value. This method should - * not be used for values whose creation require the acquisition of resources. + * Creates a new `ScopedRef` from the specified value. + * + * **When to use** + * + * Use to create a `ScopedRef` when the initial value is already available or + * can be produced without acquiring resources. + * + * **Details** + * + * The `evaluate` function runs when the returned effect runs. The returned + * effect requires a `Scope`, and the reference closes the currently stored + * value's scope when that outer scope closes. + * + * **Gotchas** + * + * Do not use `make` for an initial value whose creation acquires resources; use + * `fromAcquire` so acquisition and finalization are tracked. + * + * @see {@link fromAcquire} for creating a `ScopedRef` from an effect that acquires the initial value + * @see {@link set} for replacing the current value with a newly acquired value * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const make = (evaluate: LazyArg): Effect.Effect, never, Scope.Scope> => Effect.suspend(() => { @@ -100,39 +151,60 @@ export const make = (evaluate: LazyArg): Effect.Effect, never }) /** - * Sets the value of this reference to the specified resourcefully-created - * value. Any resources associated with the old value will be released. + * Sets the value of this reference to a newly acquired scoped value, releasing + * any resources associated with the old value. + * + * **When to use** + * + * Use to replace the current value of an existing `ScopedRef` with a newly + * acquired scoped value while releasing resources for the previous value. + * + * **Details** * * This method will not return until either the reference is successfully * changed to the new value, with old resources released, or until the attempt * to acquire a new value fails. * + * @category setters * @since 2.0.0 - * @category getters */ export const set: { /** - * Sets the value of this reference to the specified resourcefully-created - * value. Any resources associated with the old value will be released. + * Sets the value of this reference to a newly acquired scoped value, releasing + * any resources associated with the old value. + * + * **When to use** + * + * Use to replace the current value of an existing `ScopedRef` with a newly + * acquired scoped value while releasing resources for the previous value. + * + * **Details** * * This method will not return until either the reference is successfully * changed to the new value, with old resources released, or until the attempt * to acquire a new value fails. * + * @category setters * @since 2.0.0 - * @category getters */ (acquire: Effect.Effect): (self: ScopedRef) => Effect.Effect> /** - * Sets the value of this reference to the specified resourcefully-created - * value. Any resources associated with the old value will be released. + * Sets the value of this reference to a newly acquired scoped value, releasing + * any resources associated with the old value. + * + * **When to use** + * + * Use to replace the current value of an existing `ScopedRef` with a newly + * acquired scoped value while releasing resources for the previous value. + * + * **Details** * * This method will not return until either the reference is successfully * changed to the new value, with old resources released, or until the attempt * to acquire a new value fails. * + * @category setters * @since 2.0.0 - * @category getters */ (self: ScopedRef, acquire: Effect.Effect): Effect.Effect> } = dual( diff --git a/.opencode/node_modules/effect/src/Semaphore.ts b/.opencode/node_modules/effect/src/Semaphore.ts index 45e413cf285039830a4bd13d8868f0331baa5c5b..af9c0c47cd6b2f846c5ea813f3db46c6da90d58b 100644 --- a/.opencode/node_modules/effect/src/Semaphore.ts +++ b/.opencode/node_modules/effect/src/Semaphore.ts @@ -1,5 +1,14 @@ /** - * @since 2.0.0 + * Limits how many effects can use a shared resource at the same time. + * + * A `Semaphore` owns a number of permits. Work can run only after acquiring the + * permits it needs, and those permits are returned when the work finishes. This + * module includes constructors, automatic wrappers that acquire and release + * permits around an effect, manual permit operations, a non-waiting variant for + * work that should only run immediately, and resizing support for an existing + * semaphore. + * + * @since 4.0.0 */ import type * as Effect from "./Effect.ts" import type { Fiber } from "./Fiber.ts" @@ -9,9 +18,21 @@ import * as internal from "./internal/effect.ts" import type * as Option from "./Option.ts" /** - * @category models - * @since 2.0.0 - * @example + * A counting semaphore that coordinates concurrent access with permits. + * + * **When to use** + * + * Use to coordinate concurrent effects that need bounded access to a shared + * resource. + * + * **Details** + * + * Effects can acquire permits, wait until enough permits are available, + * release permits, or run with permits that are automatically released when + * the effect exits. + * + * **Example** (Controlling concurrent access) + * * ```ts * import { Effect, Semaphore } from "effect" * @@ -24,10 +45,20 @@ import type * as Option from "./Option.ts" * ) * }) * ``` + * + * @see {@link make} for creating a semaphore inside Effect code + * @see {@link makeUnsafe} for creating a semaphore synchronously + * + * @category models + * @since 4.0.0 */ export interface Semaphore { /** * Adjusts the number of permits available in the semaphore. + * + * **When to use** + * + * Use to change the total permit count of an existing semaphore. */ resize(this: Semaphore, permits: number): Effect.Effect @@ -35,6 +66,10 @@ export interface Semaphore { * Runs an effect with the given number of permits and releases the permits * when the effect completes. * + * **When to use** + * + * Use to run an effect while holding a specified number of semaphore permits. + * * **Details** * * This function acquires the specified number of permits before executing @@ -48,6 +83,10 @@ export interface Semaphore { * Runs an effect with the given number of permits and releases the permits * when the effect completes. * + * **When to use** + * + * Use to run an effect while holding exactly one semaphore permit. + * * **Details** * * This function acquires the specified number of permits before executing @@ -61,6 +100,11 @@ export interface Semaphore { * Runs an effect only if the specified number of permits are immediately * available. * + * **When to use** + * + * Use when guarded work should run only if the requested permits are + * immediately available. + * * **Details** * * This function attempts to acquire the specified number of permits. If they @@ -77,31 +121,45 @@ export interface Semaphore { * Acquires the specified number of permits and returns the resulting * available permits, suspending the task if they are not yet available. * Concurrent pending `take` calls are processed in a first-in, first-out manner. + * + * **When to use** + * + * Use to manually acquire permits for lower-level coordination protocols. */ take(this: Semaphore, permits: number): Effect.Effect /** * Releases the specified number of permits and returns the resulting * available permits. + * + * **When to use** + * + * Use to manually return permits acquired by a lower-level coordination + * protocol. */ release(this: Semaphore, permits: number): Effect.Effect /** * Releases all permits held by this semaphore and returns the resulting available permits. + * + * **When to use** + * + * Use to return every currently taken permit to the semaphore at once. */ readonly releaseAll: Effect.Effect } /** - * Unsafely creates a new Semaphore. + * Creates a `Semaphore` synchronously with the specified total + * number of permits. * - * **Previously Known As** + * **When to use** * - * This API replaces the following from Effect 3.x: + * Use to construct a semaphore synchronously when an immediate value is + * required outside an Effect workflow. * - * - `Effect.makeSemaphoreUnsafe` + * **Example** (Creating an unsafe semaphore) * - * @example * ```ts * import { Effect, Semaphore } from "effect" * @@ -126,8 +184,8 @@ export interface Semaphore { * ], { concurrency: "unbounded" }) * ``` * - * @since 2.0.0 * @category constructors + * @since 4.0.0 */ export const makeUnsafe = (permits: number): Semaphore => new SemaphoreImpl(permits) @@ -236,15 +294,15 @@ class SemaphoreImpl implements Semaphore { } /** - * Creates a new Semaphore. + * Creates a `Semaphore` initialized with the specified total number of permits. * - * **Previously Known As** + * **When to use** * - * This API replaces the following from Effect 3.x: + * Use to create a semaphore inside Effect code for bounding concurrency with + * automatic or manual permit management. * - * - `Effect.makeSemaphore` + * **Example** (Creating a semaphore) * - * @example * ```ts * import { Effect, Semaphore } from "effect" * @@ -265,30 +323,72 @@ class SemaphoreImpl implements Semaphore { * }) * ``` * - * @since 2.0.0 * @category constructors + * @since 4.0.0 */ export const make = (permits: number): Effect.Effect => internal.sync(() => new SemaphoreImpl(permits)) /** - * Adjusts the number of permits available in the semaphore. + * Sets the total number of permits managed by the semaphore. + * + * **When to use** + * + * Use to change the concurrency limit of an existing semaphore while keeping + * current acquisitions in place. + * + * **Details** + * + * Existing acquisitions remain taken after resizing. If the new total is less + * than the currently taken permit count, new acquisitions wait until enough + * permits are released. + * + * @see {@link make} for creating a semaphore with an initial permit count + * @see {@link release} for returning permits without changing semaphore capacity * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const resize: { /** - * Adjusts the number of permits available in the semaphore. + * Sets the total number of permits managed by the semaphore. + * + * **When to use** + * + * Use to change the concurrency limit of an existing semaphore while keeping + * current acquisitions in place. + * + * **Details** + * + * Existing acquisitions remain taken after resizing. If the new total is less + * than the currently taken permit count, new acquisitions wait until enough + * permits are released. + * + * @see {@link make} for creating a semaphore with an initial permit count + * @see {@link release} for returning permits without changing semaphore capacity * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (permits: number): (self: Semaphore) => Effect.Effect /** - * Adjusts the number of permits available in the semaphore. + * Sets the total number of permits managed by the semaphore. + * + * **When to use** + * + * Use to change the concurrency limit of an existing semaphore while keeping + * current acquisitions in place. + * + * **Details** + * + * Existing acquisitions remain taken after resizing. If the new total is less + * than the currently taken permit count, new acquisitions wait until enough + * permits are released. + * + * @see {@link make} for creating a semaphore with an initial permit count + * @see {@link release} for returning permits without changing semaphore capacity * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Semaphore, permits: number): Effect.Effect } = dual(2, (self: Semaphore, permits: number) => self.resize(permits)) @@ -297,24 +397,69 @@ export const resize: { * Runs an effect with the given number of permits and releases the permits when * the effect completes. * - * @since 4.0.0 + * **When to use** + * + * Use to run an effect while holding a specified number of semaphore permits + * for the duration of that effect. + * + * **Details** + * + * The effect waits until enough permits are available. Acquired permits are + * released when the wrapped effect exits. + * + * @see {@link withPermit} for acquiring exactly one permit + * @see {@link withPermitsIfAvailable} for running only when permits are immediately available + * @see {@link take} for manually acquiring permits + * @see {@link release} for manually returning permits + * * @category combinators + * @since 4.0.0 */ export const withPermits: { /** * Runs an effect with the given number of permits and releases the permits when * the effect completes. * - * @since 4.0.0 + * **When to use** + * + * Use to run an effect while holding a specified number of semaphore permits + * for the duration of that effect. + * + * **Details** + * + * The effect waits until enough permits are available. Acquired permits are + * released when the wrapped effect exits. + * + * @see {@link withPermit} for acquiring exactly one permit + * @see {@link withPermitsIfAvailable} for running only when permits are immediately available + * @see {@link take} for manually acquiring permits + * @see {@link release} for manually returning permits + * * @category combinators + * @since 4.0.0 */ (self: Semaphore, permits: number): (effect: Effect.Effect) => Effect.Effect /** * Runs an effect with the given number of permits and releases the permits when * the effect completes. * - * @since 4.0.0 + * **When to use** + * + * Use to run an effect while holding a specified number of semaphore permits + * for the duration of that effect. + * + * **Details** + * + * The effect waits until enough permits are available. Acquired permits are + * released when the wrapped effect exits. + * + * @see {@link withPermit} for acquiring exactly one permit + * @see {@link withPermitsIfAvailable} for running only when permits are immediately available + * @see {@link take} for manually acquiring permits + * @see {@link release} for manually returning permits + * * @category combinators + * @since 4.0.0 */ (self: Semaphore, permits: number, effect: Effect.Effect): Effect.Effect } = ((self: Semaphore, permits: number, effect?: Effect.Effect) => { @@ -326,24 +471,54 @@ export const withPermits: { * Runs an effect with a single permit and releases the permit when the effect * completes. * - * @since 4.0.0 + * **When to use** + * + * Use to guard an effect with exactly one semaphore permit while automatically + * releasing that permit when the effect exits. + * + * @see {@link withPermits} for acquiring more than one permit + * @see {@link withPermitsIfAvailable} for running only when permits are immediately available + * @see {@link take} for manually acquiring permits + * @see {@link release} for manually returning permits + * * @category combinators + * @since 4.0.0 */ export const withPermit: { /** * Runs an effect with a single permit and releases the permit when the effect * completes. * - * @since 4.0.0 + * **When to use** + * + * Use to guard an effect with exactly one semaphore permit while automatically + * releasing that permit when the effect exits. + * + * @see {@link withPermits} for acquiring more than one permit + * @see {@link withPermitsIfAvailable} for running only when permits are immediately available + * @see {@link take} for manually acquiring permits + * @see {@link release} for manually returning permits + * * @category combinators + * @since 4.0.0 */ (self: Semaphore): (effect: Effect.Effect) => Effect.Effect /** * Runs an effect with a single permit and releases the permit when the effect * completes. * - * @since 4.0.0 + * **When to use** + * + * Use to guard an effect with exactly one semaphore permit while automatically + * releasing that permit when the effect exits. + * + * @see {@link withPermits} for acquiring more than one permit + * @see {@link withPermitsIfAvailable} for running only when permits are immediately available + * @see {@link take} for manually acquiring permits + * @see {@link release} for manually returning permits + * * @category combinators + * @since 4.0.0 */ (self: Semaphore, effect: Effect.Effect): Effect.Effect } = ((self: Semaphore, effect?: Effect.Effect) => { @@ -355,24 +530,66 @@ export const withPermit: { * Runs an effect only if the specified number of permits are immediately * available. * - * @since 4.0.0 + * **When to use** + * + * Use when guarded work should run only if the requested permits are + * immediately available. + * + * **Details** + * + * When the permits are unavailable, the effect is not run and the result is + * `Option.none`. When permits are available, the effect is run, its result is + * wrapped in `Option.some`, and the acquired permits are released when the + * effect exits. + * + * @see {@link withPermits} for the variant that waits until permits are available + * * @category combinators + * @since 4.0.0 */ export const withPermitsIfAvailable: { /** * Runs an effect only if the specified number of permits are immediately * available. * - * @since 4.0.0 + * **When to use** + * + * Use when guarded work should run only if the requested permits are + * immediately available. + * + * **Details** + * + * When the permits are unavailable, the effect is not run and the result is + * `Option.none`. When permits are available, the effect is run, its result is + * wrapped in `Option.some`, and the acquired permits are released when the + * effect exits. + * + * @see {@link withPermits} for the variant that waits until permits are available + * * @category combinators + * @since 4.0.0 */ (self: Semaphore, permits: number): (effect: Effect.Effect) => Effect.Effect, E, R> /** * Runs an effect only if the specified number of permits are immediately * available. * - * @since 4.0.0 + * **When to use** + * + * Use when guarded work should run only if the requested permits are + * immediately available. + * + * **Details** + * + * When the permits are unavailable, the effect is not run and the result is + * `Option.none`. When permits are available, the effect is run, its result is + * wrapped in `Option.some`, and the acquired permits are released when the + * effect exits. + * + * @see {@link withPermits} for the variant that waits until permits are available + * * @category combinators + * @since 4.0.0 */ (self: Semaphore, permits: number, effect: Effect.Effect): Effect.Effect, E, R> } = ((self: Semaphore, permits: number, effect?: Effect.Effect) => { @@ -381,27 +598,66 @@ export const withPermitsIfAvailable: { }) as any /** - * Acquires the specified number of permits and returns the resulting available - * permits, suspending the task if they are not yet available. + * Acquires the specified number of permits and returns the acquired permit + * count. + * + * **When to use** + * + * Use when you need manual permit acquisition for a lower-level protocol with + * explicit acquisition and release control. + * + * **Details** + * + * The effect waits until enough permits are available. + * + * @see {@link withPermit} for automatically acquiring and releasing one permit around an effect + * @see {@link withPermits} for automatically acquiring and releasing multiple permits around an effect + * @see {@link release} for returning manually acquired permits * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const take: { /** - * Acquires the specified number of permits and returns the resulting available - * permits, suspending the task if they are not yet available. + * Acquires the specified number of permits and returns the acquired permit + * count. + * + * **When to use** + * + * Use when you need manual permit acquisition for a lower-level protocol with + * explicit acquisition and release control. + * + * **Details** + * + * The effect waits until enough permits are available. + * + * @see {@link withPermit} for automatically acquiring and releasing one permit around an effect + * @see {@link withPermits} for automatically acquiring and releasing multiple permits around an effect + * @see {@link release} for returning manually acquired permits * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (permits: number): (self: Semaphore) => Effect.Effect /** - * Acquires the specified number of permits and returns the resulting available - * permits, suspending the task if they are not yet available. + * Acquires the specified number of permits and returns the acquired permit + * count. + * + * **When to use** + * + * Use when you need manual permit acquisition for a lower-level protocol with + * explicit acquisition and release control. + * + * **Details** + * + * The effect waits until enough permits are available. + * + * @see {@link withPermit} for automatically acquiring and releasing one permit around an effect + * @see {@link withPermits} for automatically acquiring and releasing multiple permits around an effect + * @see {@link release} for returning manually acquired permits * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Semaphore, permits: number): Effect.Effect } = dual(2, (self: Semaphore, permits: number) => self.take(permits)) @@ -410,24 +666,87 @@ export const take: { * Releases the specified number of permits and returns the resulting available * permits. * - * @since 4.0.0 + * **When to use** + * + * Use when you need to return permits acquired with `take` in a lower-level + * permit protocol with explicit release control. + * + * **Details** + * + * Running the effect releases the requested permits, wakes waiting acquirers + * when permits become available, and returns the current available permit + * count. + * + * **Gotchas** + * + * Manual `take` / `release` usage must keep permit counts balanced. Prefer + * `withPermit` or `withPermits` when the acquisition can be scoped to one + * effect. + * + * @see {@link take} for manually acquiring permits + * @see {@link releaseAll} for returning every currently taken permit + * @see {@link withPermits} for automatic acquire and release around an effect + * * @category combinators + * @since 4.0.0 */ export const release: { /** * Releases the specified number of permits and returns the resulting available * permits. * - * @since 4.0.0 + * **When to use** + * + * Use when you need to return permits acquired with `take` in a lower-level + * permit protocol with explicit release control. + * + * **Details** + * + * Running the effect releases the requested permits, wakes waiting acquirers + * when permits become available, and returns the current available permit + * count. + * + * **Gotchas** + * + * Manual `take` / `release` usage must keep permit counts balanced. Prefer + * `withPermit` or `withPermits` when the acquisition can be scoped to one + * effect. + * + * @see {@link take} for manually acquiring permits + * @see {@link releaseAll} for returning every currently taken permit + * @see {@link withPermits} for automatic acquire and release around an effect + * * @category combinators + * @since 4.0.0 */ (permits: number): (self: Semaphore) => Effect.Effect /** * Releases the specified number of permits and returns the resulting available * permits. * - * @since 4.0.0 + * **When to use** + * + * Use when you need to return permits acquired with `take` in a lower-level + * permit protocol with explicit release control. + * + * **Details** + * + * Running the effect releases the requested permits, wakes waiting acquirers + * when permits become available, and returns the current available permit + * count. + * + * **Gotchas** + * + * Manual `take` / `release` usage must keep permit counts balanced. Prefer + * `withPermit` or `withPermits` when the acquisition can be scoped to one + * effect. + * + * @see {@link take} for manually acquiring permits + * @see {@link releaseAll} for returning every currently taken permit + * @see {@link withPermits} for automatic acquire and release around an effect + * * @category combinators + * @since 4.0.0 */ (self: Semaphore, permits: number): Effect.Effect } = dual(2, (self: Semaphore, permits: number) => self.release(permits)) @@ -436,7 +755,15 @@ export const release: { * Releases all permits held by this semaphore and returns the resulting * available permits. * - * @since 4.0.0 + * **When to use** + * + * Use to return every currently taken permit to a semaphore at once, typically + * during cleanup of manual `take` / `release` protocols. + * + * @see {@link release} for releasing a known permit count + * @see {@link withPermits} for automatic acquire and release around an effect + * * @category combinators + * @since 4.0.0 */ export const releaseAll = (self: Semaphore): Effect.Effect => self.releaseAll diff --git a/.opencode/node_modules/effect/src/Sink.ts b/.opencode/node_modules/effect/src/Sink.ts index 4b63ac88d83d2ff30d6976627305aacf2eddd29f..4fb4aa5a3180a0576d20cc1ece1f911499a11c7b 100644 --- a/.opencode/node_modules/effect/src/Sink.ts +++ b/.opencode/node_modules/effect/src/Sink.ts @@ -1,4 +1,12 @@ /** + * Consumes values from a `Stream` and produces one final result. + * + * A `Sink` may read no input, a fixed amount of input, or keep reading until a + * condition is met. If it reads more than it needs, it can return leftovers so + * the stream can continue from those values. Sinks are used to collect, fold, + * search, count, or otherwise reduce streamed input, and they can be composed + * when a stream needs more than one consuming step. + * * @since 2.0.0 */ import type { NonEmptyReadonlyArray } from "./Array.ts" @@ -36,11 +44,10 @@ const TypeId = "~effect/Sink" * and will eventually yield a value of type `A` together with a remainder of * type `L` (i.e. any leftovers). * - * @example + * **Example** (Running a sink with a stream) + * * ```ts - * import { Effect } from "effect" - * import * as Sink from "effect/Sink" - * import * as Stream from "effect/Stream" + * import { Effect, Sink, Stream } from "effect" * * // Create a simple sink that always succeeds with a value * const sink: Sink.Sink = Sink.succeed(42) @@ -53,8 +60,8 @@ const TypeId = "~effect/Sink" * // Output: 42 * ``` * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface Sink extends Sink.Variance, Pipeable @@ -69,33 +76,32 @@ export interface Sink = readonly [value: A, leftover?: NonEmptyReadonlyArray | undefined] const endVoid = Effect.succeed([void 0] as End) /** - * Interface for Sink unification, used internally by the Effect type system - * to provide proper type inference when using Sink with other Effect types. - * - * @example - * ```ts - * import type { Effect } from "effect" - * import type * as Sink from "effect/Sink" - * import type * as Unify from "effect/Unify" + * Type-level unification support for `Sink` values. * - * // SinkUnify helps unify Sink and Effect types - * declare const sink: Sink.Sink - * declare const effect: Effect.Effect + * **Details** * - * // The unification system handles mixed operations - * type Combined = Sink.SinkUnify<{ [Unify.typeSymbol]?: any }> - * ``` + * This preserves the result, input, leftover, error, and service type + * parameters when Effect's `Unify` machinery normalizes generic values that + * include sinks. Users normally do not need to reference this interface + * directly. * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface SinkUnify extends Effect.EffectUnify { Sink?: () => A[Unify.typeSymbol] extends @@ -111,16 +117,13 @@ export interface SinkUnify extends Effec } /** - * Interface used to ignore certain types during Sink unification. - * Part of the internal type system machinery. + * Marker used by Effect's `Unify` machinery for `Sink` values. * - * @example - * ```ts - * import type * as Sink from "effect/Sink" + * **Details** * - * // Used internally by the type system - * type IgnoreConfig = Sink.SinkUnifyIgnore - * ``` + * It prevents the inherited `Effect` unifier from being selected when + * sink-specific unification should preserve the `Sink` type parameters. Users + * normally do not need to reference this interface directly. * * @category models * @since 2.0.0 @@ -132,53 +135,35 @@ export interface SinkUnifyIgnore { /** * Namespace containing types and interfaces for Sink variance and type relationships. * - * @example - * ```ts - * import type * as Sink from "effect/Sink" - * - * // The Sink namespace contains internal type definitions - * // These are used internally for type safety and variance - * type SinkType = Sink.Sink - * ``` - * * @since 2.0.0 - * @category models */ export declare namespace Sink { /** - * Represents the variance annotations for a Sink type. - * Used internally to track how type parameters flow through the Sink. + * Type-level variance marker for `Sink`. * - * @example - * ```ts - * import type * as Sink from "effect/Sink" + * **Details** * - * // The variance interface is used internally - * // It defines how type parameters behave in Sink - * type SinkWithVariance = Sink.Sink & { variance: "internal" } - * ``` + * The result `A`, leftovers `L`, errors `E`, and services `R` are + * covariant. The input type `In` is contravariant because values flow into + * the sink. * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface Variance { readonly [TypeId]: VarianceStruct } /** - * The internal structure representing Sink variance annotations. - * Contains the actual variance markers for each type parameter. + * Structural encoding used by `Sink.Variance` to record each `Sink` type + * parameter's variance. * - * @example - * ```ts - * import type * as Sink from "effect/Sink" + * **Details** * - * // The variance structure is used internally by the type system - * // It ensures proper type safety for Sink operations - * type SinkInstance = Sink.Sink - * ``` + * `_A`, `_L`, `_E`, and `_R` are covariant markers. `_In` is a + * contravariant marker. * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface VarianceStruct { _A: Types.Covariant @@ -205,9 +190,10 @@ const SinkProto = { } /** - * Checks if a value is a Sink. + * Checks whether a value is a Sink. + * + * **Example** (Checking for a sink) * - * @example * ```ts * import { Sink } from "effect" * @@ -218,16 +204,22 @@ const SinkProto = { * console.log(Sink.isSink(notStream)) // false * ``` * - * @since 2.0.0 * @category guards + * @since 4.0.0 */ export const isSink = (u: unknown): u is Sink => hasProperty(u, TypeId) /** * Creates a sink from a `Channel`. * - * @since 2.0.0 + * **When to use** + * + * Use to create a `Sink` from a `Channel` that processes non-empty arrays of + * input values. + * + * @see {@link toChannel} for converting a `Sink` back to a `Channel` * @category constructors + * @since 2.0.0 */ export const fromChannel = ( channel: Channel.Channel< @@ -248,8 +240,16 @@ export const fromChannel = ( ) /** - * @since 4.0.0 + * Creates a `Sink` from a low-level transform function. + * + * **Details** + * + * The transform receives the upstream pull of non-empty input arrays and the + * active scope, and returns an effect that completes with the sink's `End` + * value. + * * @category constructors + * @since 4.0.0 */ export const fromTransform = ( transform: ( @@ -265,7 +265,8 @@ export const fromTransform = ( /** * Creates a `Channel` from a Sink. * - * @example + * **Example** (Converting a sink to a channel) + * * ```ts * import { Sink } from "effect" * @@ -274,8 +275,8 @@ export const fromTransform = ( * const channel = Sink.toChannel(sink) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const toChannel = ( self: Sink @@ -288,8 +289,16 @@ export const toChannel = ( ) /** - * @since 4.0.0 + * Creates a pipe-style constructor for sinks over input type `In`. + * + * **Details** + * + * The returned function exposes the sink input as a `Stream`, applies the + * provided pipeline, and uses the final effect's success value as the sink + * result. + * * @category constructors + * @since 4.0.0 */ export const make = (): make.Constructor => (...fns: []) => fromTransform((upstream, scope) => @@ -302,10 +311,22 @@ export const make = (): make.Constructor => (...fns: []) => ) /** + * Companion namespace containing overload types for the pipe-style sink + * constructor returned by `Sink.make`. + * * @since 4.0.0 */ export declare namespace make { /** + * Overloaded function type returned by `Sink.make`. + * + * **Details** + * + * The first pipeline function receives the sink input as a `Stream`. The + * final pipeline step must return an `Effect`, whose success value becomes + * the sink result. + * + * @category models * @since 4.0.0 */ export interface Constructor { @@ -399,24 +420,46 @@ export declare namespace make { } /** - * @since 4.0.0 + * Creates a sink that ignores upstream input and completes from an effect that + * already returns an `End`. + * + * **When to use** + * + * Use when you need to create a sink from an effect that returns both the sink + * result value and optional leftovers. + * * @category constructors + * @since 4.0.0 */ export const fromEffectEnd = ( effect: Effect.Effect, E, R> ): Sink => fromTransform(() => effect) /** - * @since 4.0.0 + * Creates a sink that ignores upstream input and completes with the success + * value of the provided effect. + * + * **Details** + * + * If the effect fails, the sink fails with the same error. + * * @category constructors + * @since 2.0.0 */ export const fromEffect = ( effect: Effect.Effect ): Sink => fromEffectEnd(Effect.map(effect, (a) => [a])) /** - * @since 2.0.0 + * Creates a sink that offers every consumed input element to a queue. + * + * **Details** + * + * When the upstream stream ends, the sink ends the queue and completes with + * `void`. + * * @category constructors + * @since 2.0.0 */ export const fromQueue = ( queue: Queue.Queue @@ -433,8 +476,14 @@ export const fromQueue = ( ) /** - * @since 2.0.0 + * Creates a sink that publishes every consumed input element to a `PubSub`. + * + * **Details** + * + * The sink completes with `void` when the upstream stream ends. + * * @category constructors + * @since 2.0.0 */ export const fromPubSub = ( pubsub: PubSub.PubSub @@ -443,7 +492,8 @@ export const fromPubSub = ( /** * A sink that immediately ends with the specified value. * - * @example + * **Example** (Succeeding with a value) + * * ```ts * import { Effect, Sink, Stream } from "effect" * @@ -458,8 +508,8 @@ export const fromPubSub = ( * // Output: 42 * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const succeed = (a: A, leftovers?: NonEmptyReadonlyArray | undefined): Sink => fromEffectEnd(Effect.succeed([a, leftovers])) @@ -467,16 +517,16 @@ export const succeed = (a: A, leftovers?: NonEmptyReadonlyArray /** * A sink that immediately ends with the specified lazily evaluated value. * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const sync = (a: LazyArg): Sink => fromEffect(Effect.sync(a)) /** * A sink that is created from a lazily evaluated sink. * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const suspend = (evaluate: LazyArg>): Sink => fromTransform((upstream, scope) => evaluate().transform(upstream, scope)) @@ -484,7 +534,8 @@ export const suspend = (evaluate: LazyArg>) /** * A sink that always fails with the specified error. * - * @example + * **Example** (Failing with an error) + * * ```ts * import { Effect, Sink, Stream } from "effect" * @@ -499,15 +550,16 @@ export const suspend = (evaluate: LazyArg>) * // Output: Error: Sink failed * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const fail = (e: E): Sink => fromEffectEnd(Effect.fail(e)) /** * A sink that always fails with the specified lazily evaluated error. * - * @example + * **Example** (Failing with a lazy error) + * * ```ts * import { Effect, Sink, Stream } from "effect" * @@ -522,8 +574,8 @@ export const fail = (e: E): Sink => fromEffectEnd(E * // Output: Error: Lazy error * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const failSync = (evaluate: LazyArg): Sink => fromEffectEnd(Effect.failSync(evaluate)) @@ -531,7 +583,8 @@ export const failSync = (evaluate: LazyArg): Sink(evaluate: LazyArg): Sink(cause: Cause.Cause): Sink => fromEffectEnd(Effect.failCause(cause)) @@ -555,7 +608,8 @@ export const failCause = (cause: Cause.Cause): Sink(cause: Cause.Cause): Sink(evaluate: LazyArg>): Sink => fromEffectEnd(Effect.failCauseSync(evaluate)) @@ -579,7 +633,8 @@ export const failCauseSync = (evaluate: LazyArg>): Sink(evaluate: LazyArg>): Sink => fromEffectEnd(Effect.die(defect)) /** * A sink that never completes. * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const never: Sink = fromEffectEnd(Effect.never) /** - * Drains the remaining elements from the stream after the sink finishes + * Drops leftovers produced by a sink. + * + * **Details** * + * The sink result is preserved, but any leftover elements are discarded + * instead of being returned to downstream sink composition. This does not + * continue pulling additional elements from the upstream stream. + * + * @category filtering * @since 2.0.0 - * @category utils */ export const ignoreLeftover = (self: Sink): Sink => mapEnd(self, ([a]) => [a]) /** - * Drains elements from the stream by ignoring all inputs. + * Consumes and ignores all stream inputs. + * + * **When to use** + * + * Use to consume all upstream input and complete with void when the input + * values and any aggregate result are not needed. + * + * @see {@link count} for consuming all input while returning the number of elements + * @see {@link forEach} for consuming all input while running an effect for each element * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const drain: Sink = fromTransform((upstream) => Pull.catchDone( @@ -633,8 +702,23 @@ export const drain: Sink = fromTransform((upstream) => * A sink that folds its inputs with the provided function, termination * predicate and initial state. * - * @since 2.0.0 + * **When to use** + * + * Use to accumulate stream input element by element with an effectful step and + * stop based on the accumulated state. + * + * **Details** + * + * The initial state is evaluated lazily. Each input element is folded with the + * effectful function, and the sink continues while `contFn` returns `true`. If + * the sink stops in the middle of a pulled array, the remaining elements from + * that array are returned as leftovers. + * + * @see {@link foldArray} for folding each pulled non-empty input array at once + * @see {@link foldUntil} for folding until a fixed maximum number of elements is consumed + * * @category folding + * @since 2.0.0 */ export const fold = ( s: LazyArg, @@ -661,8 +745,24 @@ export const fold = ( }) /** - * @since 2.0.0 + * Folds non-empty input arrays into state with an effectful function. + * + * **When to use** + * + * Use to update state with an effectful function once per pulled non-empty + * input array when batch-level processing is the natural unit. + * + * **Details** + * + * The initial state is evaluated lazily. After each pulled array is folded, + * the sink continues while `contFn` returns `true`; otherwise it completes + * with the current state. + * + * @see {@link fold} for folding element by element and returning leftovers when stopping mid-array + * @see {@link reduceWhileArrayEffect} for array-level effectful reducing that checks the predicate before consuming input + * * @category folding + * @since 4.0.0 */ export const foldArray = ( s: LazyArg, @@ -684,8 +784,16 @@ export const foldArray = ( }) /** - * @since 2.0.0 + * Folds input elements into state until the specified maximum number of + * elements has been consumed or the upstream stream ends. + * + * **Details** + * + * If the sink stops in the middle of a pulled array, the remaining elements + * from that array are returned as leftovers. + * * @category folding + * @since 2.0.0 */ export const foldUntil = ( s: LazyArg, @@ -703,8 +811,15 @@ export const foldUntil = ( /** * A sink that returns whether all elements satisfy the specified predicate. * - * @since 2.0.0 + * **When to use** + * + * Use to reduce a stream to a boolean that is true only when every input + * satisfies a pure predicate. + * + * @see {@link some} for the dual any-match check + * * @category constructors + * @since 2.0.0 */ export const every = (predicate: Predicate): Sink => fold( @@ -716,8 +831,15 @@ export const every = (predicate: Predicate): Sink => /** * A sink that returns whether an element satisfies the specified predicate. * - * @since 2.0.0 + * **When to use** + * + * Use to reduce a stream to a boolean that is true when any input satisfies a + * pure predicate. + * + * @see {@link every} for the all-match check + * * @category constructors + * @since 2.0.0 */ export const some = (predicate: Predicate): Sink => fold( @@ -729,22 +851,64 @@ export const some = (predicate: Predicate): Sink => /** * Transforms this sink's result. * - * @since 2.0.0 + * **When to use** + * + * Use to compute a new result from the original sink result while preserving + * the sink's input consumption behavior. + * + * **Details** + * + * The transformed sink preserves the original sink's input type, leftovers, + * errors, and requirements. + * + * @see {@link mapEffect} for effectful result transformations + * @see {@link as} for replacing the result with a constant value + * @see {@link mapEnd} for transforming both the result and leftovers + * * @category mapping + * @since 2.0.0 */ export const map: { /** * Transforms this sink's result. * - * @since 2.0.0 + * **When to use** + * + * Use to compute a new result from the original sink result while preserving + * the sink's input consumption behavior. + * + * **Details** + * + * The transformed sink preserves the original sink's input type, leftovers, + * errors, and requirements. + * + * @see {@link mapEffect} for effectful result transformations + * @see {@link as} for replacing the result with a constant value + * @see {@link mapEnd} for transforming both the result and leftovers + * * @category mapping + * @since 2.0.0 */ (f: (a: A) => A2): (self: Sink) => Sink /** * Transforms this sink's result. * - * @since 2.0.0 + * **When to use** + * + * Use to compute a new result from the original sink result while preserving + * the sink's input consumption behavior. + * + * **Details** + * + * The transformed sink preserves the original sink's input type, leftovers, + * errors, and requirements. + * + * @see {@link mapEffect} for effectful result transformations + * @see {@link as} for replacing the result with a constant value + * @see {@link mapEnd} for transforming both the result and leftovers + * * @category mapping + * @since 2.0.0 */ (self: Sink, f: (a: A) => A2): Sink } = dual( @@ -754,24 +918,45 @@ export const map: { ) /** - * Set the sink's result to a constant value. + * Sets the sink's result to a constant value. + * + * **When to use** + * + * Use to keep a sink's input consumption, errors, requirements, and leftovers + * while replacing only its result with a known value. + * + * @see {@link map} for computing the replacement from the original result * - * @since 2.0.0 * @category mapping + * @since 2.0.0 */ export const as: { /** - * Set the sink's result to a constant value. + * Sets the sink's result to a constant value. + * + * **When to use** + * + * Use to keep a sink's input consumption, errors, requirements, and leftovers + * while replacing only its result with a known value. + * + * @see {@link map} for computing the replacement from the original result * - * @since 2.0.0 * @category mapping + * @since 2.0.0 */ (a2: A2): (self: Sink) => Sink /** - * Set the sink's result to a constant value. + * Sets the sink's result to a constant value. + * + * **When to use** + * + * Use to keep a sink's input consumption, errors, requirements, and leftovers + * while replacing only its result with a known value. + * + * @see {@link map} for computing the replacement from the original result * - * @since 2.0.0 * @category mapping + * @since 2.0.0 */ (self: Sink, a2: A2): Sink } = dual( @@ -782,22 +967,22 @@ export const as: { /** * Transforms this sink's input elements. * - * @since 2.0.0 * @category mapping + * @since 2.0.0 */ export const mapInput: { /** * Transforms this sink's input elements. * - * @since 2.0.0 * @category mapping + * @since 2.0.0 */ (f: (input: In0) => In): (self: Sink) => Sink /** * Transforms this sink's input elements. * - * @since 2.0.0 * @category mapping + * @since 2.0.0 */ (self: Sink, f: (input: In0) => In): Sink } = dual( @@ -807,24 +992,24 @@ export const mapInput: { ) /** - * Effectfully transforms this sink's input elements. + * Transforms this sink's input elements effectfully. * - * @since 2.0.0 * @category mapping + * @since 2.0.0 */ export const mapInputEffect: { /** - * Effectfully transforms this sink's input elements. + * Transforms this sink's input elements effectfully. * - * @since 2.0.0 * @category mapping + * @since 2.0.0 */ (f: (input: In0) => Effect.Effect): (self: Sink) => Sink /** - * Effectfully transforms this sink's input elements. + * Transforms this sink's input elements effectfully. * - * @since 2.0.0 * @category mapping + * @since 2.0.0 */ (self: Sink, f: (input: In0) => Effect.Effect): Sink } = dual( @@ -836,26 +1021,29 @@ export const mapInputEffect: { ) /** - * Transforms this sink's input elements. + * Transforms each non-empty array of upstream input before it is fed to this + * sink. * - * @since 4.0.0 * @category mapping + * @since 4.0.0 */ export const mapInputArray: { /** - * Transforms this sink's input elements. + * Transforms each non-empty array of upstream input before it is fed to this + * sink. * - * @since 4.0.0 * @category mapping + * @since 4.0.0 */ ( f: (input: Arr.NonEmptyReadonlyArray) => Arr.NonEmptyReadonlyArray ): (self: Sink) => Sink /** - * Transforms this sink's input elements. + * Transforms each non-empty array of upstream input before it is fed to this + * sink. * - * @since 4.0.0 * @category mapping + * @since 4.0.0 */ ( self: Sink, @@ -870,26 +1058,29 @@ export const mapInputArray: { ) /** - * Effectfully transforms this sink's input elements. + * Transforms each non-empty array of upstream input effectfully before it is + * fed to this sink. * - * @since 4.0.0 * @category mapping + * @since 4.0.0 */ export const mapInputArrayEffect: { /** - * Effectfully transforms this sink's input elements. + * Transforms each non-empty array of upstream input effectfully before it is + * fed to this sink. * - * @since 4.0.0 * @category mapping + * @since 4.0.0 */ ( f: (input: Arr.NonEmptyReadonlyArray) => Effect.Effect, E2, R2> ): (self: Sink) => Sink /** - * Effectfully transforms this sink's input elements. + * Transforms each non-empty array of upstream input effectfully before it is + * fed to this sink. * - * @since 4.0.0 * @category mapping + * @since 4.0.0 */ ( self: Sink, @@ -910,24 +1101,36 @@ export const mapInputArrayEffect: { ) /** - * Transforms this sink's result. + * Transforms the full `End` produced by this sink. + * + * **Details** + * + * This can change both the result value and the optional leftovers. * - * @since 4.0.0 * @category mapping + * @since 4.0.0 */ export const mapEnd: { /** - * Transforms this sink's result. + * Transforms the full `End` produced by this sink. + * + * **Details** + * + * This can change both the result value and the optional leftovers. * - * @since 4.0.0 * @category mapping + * @since 4.0.0 */ (f: (a: End) => End): (self: Sink) => Sink /** - * Transforms this sink's result. + * Transforms the full `End` produced by this sink. + * + * **Details** + * + * This can change both the result value and the optional leftovers. * - * @since 4.0.0 * @category mapping + * @since 4.0.0 */ (self: Sink, f: (a: End) => End): Sink } = dual( @@ -950,24 +1153,39 @@ const transformEffect = ( ): Sink => fromTransform((upstream, scope) => f(self.transform(upstream, scope))) /** - * Effectfully transforms this sink's result. + * Transforms the full `End` produced by this sink effectfully. + * + * **Details** + * + * This can change both the result value and the optional leftovers, and the + * transformation can fail or require services. * - * @since 4.0.0 * @category mapping + * @since 4.0.0 */ export const mapEffectEnd: { /** - * Effectfully transforms this sink's result. + * Transforms the full `End` produced by this sink effectfully. + * + * **Details** + * + * This can change both the result value and the optional leftovers, and the + * transformation can fail or require services. * - * @since 4.0.0 * @category mapping + * @since 4.0.0 */ (f: (end: End) => Effect.Effect, E2, R2>): (self: Sink) => Sink /** - * Effectfully transforms this sink's result. + * Transforms the full `End` produced by this sink effectfully. + * + * **Details** + * + * This can change both the result value and the optional leftovers, and the + * transformation can fail or require services. * - * @since 4.0.0 * @category mapping + * @since 4.0.0 */ ( self: Sink, @@ -979,24 +1197,66 @@ export const mapEffectEnd: { ): Sink => transformEffect(self, Effect.flatMap(f))) /** - * Effectfully transforms this sink's result. + * Transforms this sink's result effectfully. + * + * **When to use** + * + * Use when you need a sink result transformation that is effectful, can fail, + * or requires services. + * + * **Details** + * + * The transformed sink preserves the original sink's input consumption and + * leftovers while adding the errors and requirements of the transformation. + * + * @see {@link map} for pure result transformations + * @see {@link mapEffectEnd} for effectfully transforming both the result and leftovers + * @see {@link flatMap} for continuing with another sink based on the result * - * @since 2.0.0 * @category mapping + * @since 2.0.0 */ export const mapEffect: { /** - * Effectfully transforms this sink's result. + * Transforms this sink's result effectfully. + * + * **When to use** + * + * Use when you need a sink result transformation that is effectful, can fail, + * or requires services. + * + * **Details** + * + * The transformed sink preserves the original sink's input consumption and + * leftovers while adding the errors and requirements of the transformation. + * + * @see {@link map} for pure result transformations + * @see {@link mapEffectEnd} for effectfully transforming both the result and leftovers + * @see {@link flatMap} for continuing with another sink based on the result * - * @since 2.0.0 * @category mapping + * @since 2.0.0 */ (f: (a: A) => Effect.Effect): (self: Sink) => Sink /** - * Effectfully transforms this sink's result. + * Transforms this sink's result effectfully. + * + * **When to use** + * + * Use when you need a sink result transformation that is effectful, can fail, + * or requires services. + * + * **Details** + * + * The transformed sink preserves the original sink's input consumption and + * leftovers while adding the errors and requirements of the transformation. + * + * @see {@link map} for pure result transformations + * @see {@link mapEffectEnd} for effectfully transforming both the result and leftovers + * @see {@link flatMap} for continuing with another sink based on the result * - * @since 2.0.0 * @category mapping + * @since 2.0.0 */ (self: Sink, f: (a: A) => Effect.Effect): Sink } = dual(2, ( @@ -1007,22 +1267,22 @@ export const mapEffect: { /** * Transforms the errors emitted by this sink using `f`. * - * @since 2.0.0 * @category mapping + * @since 2.0.0 */ export const mapError: { /** * Transforms the errors emitted by this sink using `f`. * - * @since 2.0.0 * @category mapping + * @since 2.0.0 */ (f: (error: E) => E2): (self: Sink) => Sink /** * Transforms the errors emitted by this sink using `f`. * - * @since 2.0.0 * @category mapping + * @since 2.0.0 */ (self: Sink, f: (error: E) => E2): Sink } = dual(2, ( @@ -1033,22 +1293,22 @@ export const mapError: { /** * Transforms the leftovers emitted by this sink using `f`. * - * @since 2.0.0 * @category mapping + * @since 2.0.0 */ export const mapLeftover: { /** * Transforms the leftovers emitted by this sink using `f`. * - * @since 2.0.0 * @category mapping + * @since 2.0.0 */ (f: (leftover: L) => L2): (self: Sink) => Sink /** * Transforms the leftovers emitted by this sink using `f`. * - * @since 2.0.0 * @category mapping + * @since 2.0.0 */ (self: Sink, f: (leftover: L) => L2): Sink } = dual(2, ( @@ -1057,8 +1317,16 @@ export const mapLeftover: { ): Sink => mapEnd(self, ([a, l]) => [a, l && Arr.map(l, f)])) /** - * @since 2.0.0 + * Collects up to `n` input elements into an array. + * + * **Details** + * + * If `n` is less than or equal to zero, the sink completes with an empty array. + * If more elements are pulled than needed, the remaining elements from the same + * array are returned as leftovers. + * * @category collecting + * @since 2.0.0 */ export const take = (n: number): Sink, In, In> => fromTransform((upstream) => { @@ -1097,10 +1365,21 @@ export const take = (n: number): Sink, In, In> => * another sink from the provided function which will continue to run until it * yields a result. * - * This function essentially runs sinks in sequence. + * **When to use** + * + * Use to compose sinks when the next sink depends on the result produced by the + * previous sink. + * + * **Details** + * + * Leftovers from the first sink are fed to the sink returned by `f` before more + * upstream input is pulled. + * + * @see {@link map} for transforming the result without switching sinks + * @see {@link mapEffect} for effectfully transforming the result without switching sinks * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ export const flatMap: { /** @@ -1108,10 +1387,21 @@ export const flatMap: { * another sink from the provided function which will continue to run until it * yields a result. * - * This function essentially runs sinks in sequence. + * **When to use** + * + * Use to compose sinks when the next sink depends on the result produced by the + * previous sink. + * + * **Details** + * + * Leftovers from the first sink are fed to the sink returned by `f` before more + * upstream input is pulled. + * + * @see {@link map} for transforming the result without switching sinks + * @see {@link mapEffect} for effectfully transforming the result without switching sinks * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ (f: (a: A) => Sink): (self: Sink) => Sink /** @@ -1119,10 +1409,21 @@ export const flatMap: { * another sink from the provided function which will continue to run until it * yields a result. * - * This function essentially runs sinks in sequence. + * **When to use** + * + * Use to compose sinks when the next sink depends on the result produced by the + * previous sink. + * + * **Details** + * + * Leftovers from the first sink are fed to the sink returned by `f` before more + * upstream input is pulled. + * + * @see {@link map} for transforming the result without switching sinks + * @see {@link mapEffect} for effectfully transforming the result without switching sinks * - * @since 2.0.0 * @category sequencing + * @since 2.0.0 */ (self: Sink, f: (a: A) => Sink): Sink } = dual(2, ( @@ -1155,11 +1456,11 @@ export const flatMap: { })) /** - * A sink that reduces its inputs using the provided function `f` starting from - * the provided `initial` state while the specified `predicate` returns `true`. + * A sink that reduces input elements from the provided `initial` state with + * `f` while the specified `predicate` returns `true`. * - * @since 2.0.0 * @category reducing + * @since 4.0.0 */ export const reduceWhile = ( initial: LazyArg, @@ -1191,12 +1492,11 @@ export const reduceWhile = ( }) /** - * A sink that reduces its inputs using the provided effectful function `f` - * starting from the provided `initial` state while the specified `predicate` - * returns `true`. + * A sink that effectfully reduces input elements from the provided `initial` + * state with `f` while the specified `predicate` returns `true`. * - * @since 2.0.0 * @category reducing + * @since 4.0.0 */ export const reduceWhileEffect = ( initial: LazyArg, @@ -1233,11 +1533,11 @@ export const reduceWhileEffect = ( }) /** - * A sink that reduces its inputs using the provided function `f` starting from - * the provided `initial` state while the specified `predicate` returns `true`. + * A sink that reduces non-empty input arrays from the provided `initial` state + * with `f` while the specified `predicate` returns `true`. * - * @since 4.0.0 * @category reducing + * @since 4.0.0 */ export const reduceWhileArray = ( initial: LazyArg, @@ -1265,12 +1565,11 @@ export const reduceWhileArray = ( }) /** - * A sink that reduces its inputs using the provided effectful function `f` - * starting from the provided `initial` state while the specified `predicate` - * returns `true`. + * A sink that effectfully reduces non-empty input arrays from the provided + * `initial` state with `f` while the specified `predicate` returns `true`. * - * @since 4.0.0 * @category reducing + * @since 4.0.0 */ export const reduceWhileArrayEffect = ( initial: LazyArg, @@ -1300,8 +1599,8 @@ export const reduceWhileArrayEffect = ( * A sink that reduces its inputs using the provided function `f` starting from * the provided `initial` state. * - * @since 2.0.0 * @category reducing + * @since 4.0.0 */ export const reduce = (initial: LazyArg, f: (s: S, input: In) => S): Sink => reduceArray(initial, (s, arr) => { @@ -1315,8 +1614,8 @@ export const reduce = (initial: LazyArg, f: (s: S, input: In) => S): S * A sink that reduces its inputs using the provided function `f` starting from * the specified `initial` state. * - * @since 2.0.0 * @category reducing + * @since 4.0.0 */ export const reduceArray = ( initial: LazyArg, @@ -1338,8 +1637,8 @@ export const reduceArray = ( * A sink that reduces its inputs using the provided effectful function `f` * starting from the specified `initial` state. * - * @since 2.0.0 * @category reducing + * @since 4.0.0 */ export const reduceEffect = ( initial: LazyArg, @@ -1351,8 +1650,14 @@ const head_ = reduceWhile(Option.none, Option.isNone, (_, in_) => Optio /** * Creates a sink containing the first value. * - * @since 2.0.0 + * **Details** + * + * Returns `Option.some(first)` for non-empty input, or `Option.none` when the + * upstream ends without input. The first element is consumed; later elements + * from the same pulled array are emitted as leftovers. + * * @category constructors + * @since 2.0.0 */ export const head = (): Sink, In, In> => head_ as any @@ -1361,30 +1666,89 @@ const last_ = reduceArray(Option.none, (_, arr) => Arr.last(arr)) /** * Creates a sink containing the last value. * - * @since 2.0.0 + * **When to use** + * + * Use when you need to consume all upstream input and keep only the final + * element. + * + * **Details** + * + * Returns `Option.some(last)` with the final input value, or `Option.none` when + * the upstream ends without input. + * + * **Gotchas** + * + * This sink produces a result only when the upstream ends, so it does not + * complete for a stream that does not end. + * + * @see {@link head} for taking the first input value instead + * * @category constructors + * @since 2.0.0 */ export const last = (): Sink, In> => last_ as any /** - * Creates a sink containing the first matching value. + * Creates a sink containing the first value matched by a synchronous predicate. + * + * **When to use** + * + * Use to scan stream input until the first matching element is found and return + * that element as an `Option`. + * + * **Details** + * + * Returns `Option.none` if the upstream stream ends before a match is found. + * Refinement predicates narrow the returned value type. The matching input is + * consumed; any later elements from the same pulled array are returned as + * leftovers. + * + * @see {@link findEffect} for an effectful predicate that can fail or require services * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const find: { /** - * Creates a sink containing the first matching value. + * Creates a sink containing the first value matched by a synchronous predicate. + * + * **When to use** + * + * Use to scan stream input until the first matching element is found and return + * that element as an `Option`. + * + * **Details** + * + * Returns `Option.none` if the upstream stream ends before a match is found. + * Refinement predicates narrow the returned value type. The matching input is + * consumed; any later elements from the same pulled array are returned as + * leftovers. + * + * @see {@link findEffect} for an effectful predicate that can fail or require services * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ (refinement: Refinement): Sink, In, In> /** - * Creates a sink containing the first matching value. + * Creates a sink containing the first value matched by a synchronous predicate. + * + * **When to use** + * + * Use to scan stream input until the first matching element is found and return + * that element as an `Option`. + * + * **Details** + * + * Returns `Option.none` if the upstream stream ends before a match is found. + * Refinement predicates narrow the returned value type. The matching input is + * consumed; any later elements from the same pulled array are returned as + * leftovers. + * + * @see {@link findEffect} for an effectful predicate that can fail or require services * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ (predicate: Predicate): Sink, In, In> } = (predicate: Predicate): Sink, In, In> => @@ -1395,10 +1759,23 @@ export const find: { ) /** - * Creates a sink containing the first matching value. + * Creates a sink containing the first value matched by an effectful predicate. + * + * **When to use** + * + * Use when you need to run effects, fail, or use services while searching for + * the first matching input. + * + * **Details** + * + * Returns `Option.some` with the first input whose predicate result is `true`, + * or `Option.none` if the upstream stream ends first. If the predicate effect + * fails, the sink fails with the same error. + * + * @see {@link find} for the synchronous predicate variant * - * @since 4.0.0 * @category constructors + * @since 2.0.0 */ export const findEffect = ( predicate: (input: In) => Effect.Effect @@ -1412,8 +1789,8 @@ export const findEffect = ( /** * Creates a sink which sums up its inputs. * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const sum: Sink = reduceArray(() => 0, (s, arr) => { for (let i = 0; i < arr.length; i++) { @@ -1425,16 +1802,26 @@ export const sum: Sink = reduceArray(() => 0, (s, arr) => { /** * A sink that counts the number of elements fed to it. * - * @since 2.0.0 + * **When to use** + * + * Use to consume input and return only the number of elements received. + * * @category constructors + * @since 2.0.0 */ export const count: Sink = reduceArray(() => 0, (s, arr) => s + arr.length) /** * Accumulates incoming elements into an array. * - * @since 2.0.0 + * **When to use** + * + * Use when you need a sink result containing all upstream input elements. + * + * @see {@link take} for collecting only a fixed number of input elements + * * @category constructors + * @since 4.0.0 */ export const collect = (): Sink, In> => reduceArray(Arr.empty, (s, arr) => { @@ -1443,18 +1830,42 @@ export const collect = (): Sink, In> => }) /** - * @since 4.0.0 + * Collects the longest input prefix whose elements satisfy the predicate or + * refinement. + * + * **Details** + * + * The first failing input is consumed and excluded from the result. Any later + * elements from the same pulled array are returned as leftovers. + * * @category constructors + * @since 4.0.0 */ export const takeWhile: { /** - * @since 4.0.0 + * Collects the longest input prefix whose elements satisfy the predicate or + * refinement. + * + * **Details** + * + * The first failing input is consumed and excluded from the result. Any later + * elements from the same pulled array are returned as leftovers. + * * @category constructors + * @since 4.0.0 */ (refinement: Refinement): Sink, In, In> /** - * @since 4.0.0 + * Collects the longest input prefix whose elements satisfy the predicate or + * refinement. + * + * **Details** + * + * The first failing input is consumed and excluded from the result. Any later + * elements from the same pulled array are returned as leftovers. + * * @category constructors + * @since 4.0.0 */ (predicate: Predicate): Sink, In, In> } = (predicate: Predicate): Sink, In, In> => @@ -1479,8 +1890,17 @@ export const takeWhile: { }) /** - * @since 4.0.0 + * Applies a `Filter` to input elements while it succeeds, collecting each + * successful output. + * + * **Details** + * + * The first input for which the filter fails is consumed and excluded from the + * result. Any later elements from the same pulled array are returned as + * leftovers. + * * @category constructors + * @since 4.0.0 */ export const takeWhileFilter = ( filter: Filter.Filter @@ -1507,13 +1927,29 @@ export const takeWhileFilter = ( }) /** - * @since 4.0.0 + * Collects input elements effectfully while the predicate succeeds. + * + * **Details** + * + * The first input for which the predicate returns `false` is consumed and + * excluded from the result. Any later elements from the same pulled array are + * returned as leftovers. + * * @category constructors + * @since 4.0.0 */ export const takeWhileEffect: { /** - * @since 4.0.0 + * Collects input elements effectfully while the predicate succeeds. + * + * **Details** + * + * The first input for which the predicate returns `false` is consumed and + * excluded from the result. Any later elements from the same pulled array are + * returned as leftovers. + * * @category constructors + * @since 4.0.0 */ (predicate: (input: In) => Effect.Effect): Sink, In, In, E, R> } = ( @@ -1552,8 +1988,17 @@ export const takeWhileEffect: { }) /** - * @since 4.0.0 + * Applies a `FilterEffect` to input elements effectfully while it succeeds, + * collecting each successful output. + * + * **Details** + * + * The first input for which the filter fails is consumed and excluded from the + * result. Any later elements from the same pulled array are returned as + * leftovers. + * * @category constructors + * @since 4.0.0 */ export const takeWhileFilterEffect = ( filter: Filter.FilterEffect @@ -1585,8 +2030,11 @@ export const takeWhileFilterEffect = ( }) /** - * @since 4.0.0 + * Collects input elements until the predicate returns `true`, including the + * matching element in the result. + * * @category constructors + * @since 4.0.0 */ export const takeUntil = (predicate: Predicate): Sink, In, In> => suspend(() => { @@ -1599,8 +2047,15 @@ export const takeUntil = (predicate: Predicate): Sink, In, In> }) /** - * @since 4.0.0 + * Collects input elements effectfully until the predicate returns `true`, + * including the matching element in the result. + * + * **Details** + * + * If the predicate effect fails, the sink fails with the same error. + * * @category constructors + * @since 4.0.0 */ export const takeUntilEffect = ( predicate: (input: In) => Effect.Effect @@ -1622,7 +2077,8 @@ export const takeUntilEffect = ( * A sink that executes the provided effectful function for every item fed * to it. * - * @example + * **Example** (Running effects for each item) + * * ```ts * import { Console, Effect, Sink, Stream } from "effect" * @@ -1640,8 +2096,8 @@ export const takeUntilEffect = ( * // Processing: 3 * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const forEach = ( f: (input: In) => Effect.Effect @@ -1651,7 +2107,8 @@ export const forEach = ( * A sink that executes the provided effectful function for every Chunk fed * to it. * - * @example + * **Example** (Running effects for each chunk) + * * ```ts * import { Console, Effect, Sink, Stream } from "effect" * @@ -1670,8 +2127,8 @@ export const forEach = ( * // Output: Processing chunk of 5 items: [1, 2, 3, 4, 5] * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const forEachArray = ( f: (input: NonEmptyReadonlyArray) => Effect.Effect @@ -1685,8 +2142,15 @@ export const forEachArray = ( ) /** - * @since 2.0.0 + * Runs an effectful function for each input element while it returns `true`. + * + * **Details** + * + * The sink stops consuming input when the function returns `false` or when the + * upstream stream ends, and completes with `void`. + * * @category constructors + * @since 2.0.0 */ export const forEachWhile = ( f: (input: In) => Effect.Effect @@ -1700,8 +2164,16 @@ export const forEachWhile = ( })) /** - * @since 2.0.0 + * Runs an effectful function for each non-empty input array while it returns + * `true`. + * + * **Details** + * + * The sink stops consuming input when the function returns `false` or when the + * upstream stream ends, and completes with `void`. + * * @category constructors + * @since 4.0.0 */ export const forEachWhileArray = ( f: (input: NonEmptyReadonlyArray) => Effect.Effect @@ -1718,7 +2190,8 @@ export const forEachWhileArray = ( /** * Creates a sink produced from a scoped effect. * - * @example + * **Example** (Unwrapping a sink effect) + * * ```ts * import { Console, Effect, Sink, Stream } from "effect" * @@ -1739,35 +2212,32 @@ export const forEachWhileArray = ( * // Item: 3 * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const unwrap = ( effect: Effect.Effect, E, R> ): Sink | R2> => fromChannel(Channel.unwrap(Effect.map(effect, toChannel))) /** - * Summarize a sink by running an effect when the sink starts and again when - * it completes. + * Runs a summary effect when the sink starts and again when it completes. * + * @category mapping * @since 2.0.0 - * @category utils */ export const summarized: { /** - * Summarize a sink by running an effect when the sink starts and again when - * it completes. + * Runs a summary effect when the sink starts and again when it completes. * + * @category mapping * @since 2.0.0 - * @category utils */ (summary: Effect.Effect, f: (start: A2, end: A2) => A3): (self: Sink) => Sink<[A, A3], In, L, E2 | E, R2 | R> /** - * Summarize a sink by running an effect when the sink starts and again when - * it completes. + * Runs a summary effect when the sink starts and again when it completes. * + * @category mapping * @since 2.0.0 - * @category utils */ ( self: Sink, @@ -1789,8 +2259,8 @@ export const summarized: { /** * Returns the sink that executes this one and times its execution. * + * @category mapping * @since 2.0.0 - * @category utils */ export const withDuration = ( self: Sink @@ -1798,24 +2268,47 @@ export const withDuration = ( summarized(self, Clock.currentTimeNanos, (start, end) => Duration.nanos(end - start)) /** - * @since 2.0.0 + * A sink that drains all input and returns the elapsed duration. + * * @category constructors + * @since 2.0.0 */ export const timed: Sink = map(withDuration(drain), ([, duration]) => duration) /** - * @since 4.0.0 - * @category Services + * Provides a `Context` to this sink. + * + * **Details** + * + * Services contained in the provided context are removed from the sink's + * service requirements. + * + * @category services + * @since 2.0.0 */ export const provideContext: { /** - * @since 4.0.0 - * @category Services + * Provides a `Context` to this sink. + * + * **Details** + * + * Services contained in the provided context are removed from the sink's + * service requirements. + * + * @category services + * @since 2.0.0 */ (context: Context.Context): (self: Sink) => Sink> /** - * @since 4.0.0 - * @category Services + * Provides a `Context` to this sink. + * + * **Details** + * + * Services contained in the provided context are removed from the sink's + * service requirements. + * + * @category services + * @since 2.0.0 */ (self: Sink, context: Context.Context): Sink> } = dual(2, ( @@ -1829,18 +2322,39 @@ export const provideContext: { )) /** + * Provides a single service implementation to this sink. + * + * **Details** + * + * The service identified by `key` is removed from the sink's service + * requirements. + * + * @category services * @since 4.0.0 - * @category Services */ export const provideService: { /** + * Provides a single service implementation to this sink. + * + * **Details** + * + * The service identified by `key` is removed from the sink's service + * requirements. + * + * @category services * @since 4.0.0 - * @category Services */ (key: Context.Key, value: Types.NoInfer): (self: Sink) => Sink> /** + * Provides a single service implementation to this sink. + * + * **Details** + * + * The service identified by `key` is removed from the sink's service + * requirements. + * + * @category services * @since 4.0.0 - * @category Services */ ( self: Sink, @@ -1859,18 +2373,42 @@ export const provideService: { )) /** + * Runs a fallback sink if this sink fails with a typed error. + * + * **Details** + * + * The fallback is built from the error and continues consuming from the same + * upstream stream. If the upstream stream had already ended, the fallback sees + * the upstream end instead. + * + * @category error handling * @since 2.0.0 - * @category Error handling */ export const orElse: { /** + * Runs a fallback sink if this sink fails with a typed error. + * + * **Details** + * + * The fallback is built from the error and continues consuming from the same + * upstream stream. If the upstream stream had already ended, the fallback sees + * the upstream end instead. + * + * @category error handling * @since 2.0.0 - * @category Error handling */ (f: (error: Types.NoInfer) => Sink): (self: Sink) => Sink /** + * Runs a fallback sink if this sink fails with a typed error. + * + * **Details** + * + * The fallback is built from the error and continues consuming from the same + * upstream stream. If the upstream stream had already ended, the fallback sees + * the upstream end instead. + * + * @category error handling * @since 2.0.0 - * @category Error handling */ (self: Sink, f: (error: E) => Sink): Sink } = dual(2, ( @@ -1899,18 +2437,66 @@ export const orElse: { })) /** + * Handles failures from this sink by inspecting the full `Cause`. + * + * **When to use** + * + * Use to recover from a sink failure based on the full `Cause` instead of only + * the typed error value. + * + * **Details** + * + * When this sink fails, the handler effect is run and its success value + * becomes the sink result. If the handler fails, the returned sink fails with + * that error. + * + * @see {@link catch_ catch} for recovering from typed errors only + * @see {@link orElse} for recovering by switching to another sink + * + * @category error handling * @since 4.0.0 - * @category Error handling */ export const catchCause: { /** + * Handles failures from this sink by inspecting the full `Cause`. + * + * **When to use** + * + * Use to recover from a sink failure based on the full `Cause` instead of only + * the typed error value. + * + * **Details** + * + * When this sink fails, the handler effect is run and its success value + * becomes the sink result. If the handler fails, the returned sink fails with + * that error. + * + * @see {@link catch_ catch} for recovering from typed errors only + * @see {@link orElse} for recovering by switching to another sink + * + * @category error handling * @since 4.0.0 - * @category Error handling */ (f: (error: Cause.Cause>) => Effect.Effect): (self: Sink) => Sink /** + * Handles failures from this sink by inspecting the full `Cause`. + * + * **When to use** + * + * Use to recover from a sink failure based on the full `Cause` instead of only + * the typed error value. + * + * **Details** + * + * When this sink fails, the handler effect is run and its success value + * becomes the sink result. If the handler fails, the returned sink fails with + * that error. + * + * @see {@link catch_ catch} for recovering from typed errors only + * @see {@link orElse} for recovering by switching to another sink + * + * @category error handling * @since 4.0.0 - * @category Error handling */ ( self: Sink, @@ -1944,25 +2530,56 @@ const catch_: { export { /** + * Handles typed errors from this sink with an effectful fallback value. + * + * **When to use** + * + * Use to recover from a typed sink failure by producing the replacement + * result with an `Effect`. + * + * @see {@link catchCause} for recovering from the full failure cause + * @see {@link orElse} for recovering by switching to another sink + * + * @category error handling * @since 4.0.0 - * @category Error handling */ catch_ as catch } /** - * @since 4.0.0 + * Runs an effect after this sink completes, fails, or is interrupted. + * + * **Details** + * + * The effect receives the sink's `Exit` for the result value. The original + * sink result and leftovers are preserved unless the finalizer itself fails. + * * @category Finalization + * @since 4.0.0 */ export const onExit: { /** - * @since 4.0.0 + * Runs an effect after this sink completes, fails, or is interrupted. + * + * **Details** + * + * The effect receives the sink's `Exit` for the result value. The original + * sink result and leftovers are preserved unless the finalizer itself fails. + * * @category Finalization + * @since 4.0.0 */ (f: (exit: Exit.Exit) => Effect.Effect): (self: Sink) => Sink /** - * @since 4.0.0 + * Runs an effect after this sink completes, fails, or is interrupted. + * + * **Details** + * + * The effect receives the sink's `Exit` for the result value. The original + * sink result and leftovers are preserved unless the finalizer itself fails. + * * @category Finalization + * @since 4.0.0 */ ( self: Sink, @@ -1978,18 +2595,39 @@ export const onExit: { )) /** - * @since 4.0.0 + * Runs a finalizer effect after this sink completes, fails, or is interrupted. + * + * **Details** + * + * The original sink result and leftovers are preserved unless the finalizer + * itself fails. + * * @category Finalization + * @since 2.0.0 */ export const ensuring: { /** - * @since 4.0.0 + * Runs a finalizer effect after this sink completes, fails, or is interrupted. + * + * **Details** + * + * The original sink result and leftovers are preserved unless the finalizer + * itself fails. + * * @category Finalization + * @since 2.0.0 */ (effect: Effect.Effect): (self: Sink) => Sink /** - * @since 4.0.0 + * Runs a finalizer effect after this sink completes, fails, or is interrupted. + * + * **Details** + * + * The original sink result and leftovers are preserved unless the finalizer + * itself fails. + * * @category Finalization + * @since 2.0.0 */ (self: Sink, effect: Effect.Effect): Sink } = dual(2, ( diff --git a/.opencode/node_modules/effect/src/Stdio.ts b/.opencode/node_modules/effect/src/Stdio.ts index bf53545bc51e0962f1a7557a27147a85bde173d2..899c75e62a2332a250bd76246a0292b57ac3b0bf 100644 --- a/.opencode/node_modules/effect/src/Stdio.ts +++ b/.opencode/node_modules/effect/src/Stdio.ts @@ -1,4 +1,14 @@ /** + * Service contract for command-line arguments and standard input, output, and + * error output. It lets programs depend on standard I/O through the Effect + * environment instead of reading from or writing to global process handles + * directly. + * + * The service exposes arguments as an `Effect`, stdout and stderr as `Sink`s + * that accept strings or bytes, and stdin as a byte `Stream`. This module also + * provides a constructor for service values and a small test layer with + * overridable defaults. + * * @since 4.0.0 */ import * as Context from "./Context.ts" @@ -9,20 +19,46 @@ import * as Sink from "./Sink.ts" import * as Stream from "./Stream.ts" /** + * String literal type used as the unique brand for the `Stdio` service. + * + * **When to use** + * + * Use to type the runtime identifier stored on `Stdio` service implementations. + * + * @category type IDs * @since 4.0.0 - * @category Type IDs */ export type TypeId = "~effect/Stdio" /** + * Runtime identifier stored on `Stdio` service implementations. + * + * **Details** + * + * This marker is part of the runtime representation of `Stdio` service + * implementations. + * + * @category type IDs * @since 4.0.0 - * @category Type IDs */ export const TypeId: TypeId = "~effect/Stdio" /** + * Defines the service interface for process standard I/O. + * + * **When to use** + * + * Use to depend on command-line arguments and standard I/O through the Effect + * environment. + * + * **Details** + * + * The service provides command-line arguments, sinks for standard output and + * standard error, and a stream of standard input bytes. I/O operations can fail + * with `PlatformError`. + * + * @category models * @since 4.0.0 - * @category Models */ export interface Stdio { readonly [TypeId]: TypeId @@ -36,14 +72,39 @@ export interface Stdio { readonly stdin: Stream.Stream } /** + * Service tag for process standard I/O. + * + * **When to use** + * + * Use when you need command-line arguments or standard I/O streams supplied by + * an effect's environment. + * + * @see {@link make} for constructing a `Stdio` service directly + * @see {@link layerTest} for a test layer with defaults and overrides + * + * @category services * @since 4.0.0 - * @category Services */ export const Stdio: Context.Service = Context.Service(TypeId) /** + * Creates a `Stdio` service implementation from the provided fields and + * attaches the `Stdio` type identifier. + * + * **When to use** + * + * Use when you need to assemble a concrete `Stdio` service from command-line + * arguments and standard I/O implementations. + * + * **Details** + * + * The returned service reuses the supplied fields unchanged and only adds the + * `Stdio` type identifier; it does not create a `Layer` or provide defaults. + * + * @see {@link layerTest} for a test layer with default fields that can be overridden + * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const make = (options: Omit): Stdio => ({ [TypeId]: TypeId, @@ -51,8 +112,23 @@ export const make = (options: Omit): Stdio => ({ }) /** + * Creates a test layer for `Stdio`. + * + * **When to use** + * + * Use to provide deterministic standard I/O in tests while overriding only the + * command-line arguments, input stream, or output sinks relevant to the case. + * + * **Details** + * + * Any provided fields override defaults. By default, arguments are empty, + * standard output and error are draining sinks, and standard input is an empty + * stream. + * + * @see {@link make} for constructing a `Stdio` service directly without a `Layer` or defaults + * + * @category layers * @since 4.0.0 - * @category Layers */ export const layerTest = (impl: Partial): Layer.Layer => Layer.succeed( diff --git a/.opencode/node_modules/effect/src/Stream.ts b/.opencode/node_modules/effect/src/Stream.ts index e433c8482e5fd9986ba191f79964799e6aab881e..75c57b3b6709414f75ce42530df8d8af8a556d4d 100644 --- a/.opencode/node_modules/effect/src/Stream.ts +++ b/.opencode/node_modules/effect/src/Stream.ts @@ -1,4 +1,13 @@ /** + * Describes effectful sources that emit values over time. + * + * A `Stream` can emit many `A` values, fail with `E`, and require + * services `R` while it is being consumed. Streams are useful for data that is + * pulled in steps, such as values from collections, queues, pubsubs, schedules, + * callbacks, async iterables, or platform streams. The APIs here cover the full + * stream lifecycle: create a stream, transform or combine it, control buffering + * and timing, handle failures, and finally consume it. + * * @since 2.0.0 */ // @effect-diagnostics returnEffectInGen:off @@ -30,7 +39,7 @@ import * as Option from "./Option.ts" import type { Pipeable } from "./Pipeable.ts" import type { Predicate, Refinement } from "./Predicate.ts" import { hasProperty, isNotUndefined, isTagged } from "./Predicate.ts" -import type * as PubSub from "./PubSub.ts" +import * as PubSub from "./PubSub.ts" import * as Pull from "./Pull.ts" import * as Queue from "./Queue.ts" import * as RcMap from "./RcMap.ts" @@ -53,19 +62,32 @@ import type { OmitReason, ReasonTags, Tags, + TupleOf, unassigned } from "./Types.ts" import type * as Unify from "./Unify.ts" /** + * String literal type used as the unique brand for `Stream` values. + * + * @category type IDs * @since 4.0.0 - * @category Type Identifiers */ export type TypeId = "~effect/Stream" /** + * Runtime identifier stored on `Stream` values and used by `isStream` to + * recognize them. + * + * **Details** + * + * This marker is part of the runtime representation of `Stream` values. Prefer + * `isStream` when narrowing unknown values. + * + * @see {@link isStream} for the public guard that checks this identifier + * + * @category type IDs * @since 4.0.0 - * @category Type Identifiers */ export const TypeId: TypeId = "~effect/Stream" @@ -73,11 +95,14 @@ export const TypeId: TypeId = "~effect/Stream" * A `Stream` describes a program that can emit many `A` values, fail * with `E`, and require `R`. * + * **Details** + * * Streams are pull-based with backpressure and emit chunks to amortize effect * evaluation. They support monadic composition and error handling similar to * `Effect`, adapted for multiple values. * - * @example + * **Example** (Creating and consuming streams) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -95,8 +120,8 @@ export const TypeId: TypeId = "~effect/Stream" * // 6 * ``` * + * @category models * @since 2.0.0 - * @category Models */ export interface Stream extends Variance, Pipeable { readonly channel: Channel.Channel, E, void, unknown, unknown, unknown, R> @@ -108,20 +133,8 @@ export interface Stream extends Variance - * declare const effect: Effect.Effect - * - * // The unification system handles mixed operations - * const combined = Effect.zip(stream.pipe(Stream.runCollect), effect) - * ``` - * + * @category models * @since 2.0.0 - * @category Models */ export interface StreamUnify extends Effect.EffectUnify { Stream?: () => A[Unify.typeSymbol] extends Stream | infer _ ? Stream : never @@ -130,16 +143,7 @@ export interface StreamUnify extends Eff /** * Type-level marker that excludes Stream from unification. * - * @example - * ```ts - * import type * as Stream from "effect/Stream" - * - * // Used internally by the type system - * // Users typically don't interact with this directly - * type StreamIgnore = Stream.StreamUnifyIgnore - * ``` - * - * @category Models + * @category models * @since 2.0.0 */ export interface StreamUnifyIgnore { @@ -149,17 +153,17 @@ export interface StreamUnifyIgnore { /** * Type lambda for Stream used in higher-kinded type operations. * - * @example + * **Example** (Using the stream type lambda) + * * ```ts - * import type { Kind } from "effect/HKT" - * import type { StreamTypeLambda } from "effect/Stream" + * import type { HKT, Stream } from "effect" * * // Create a Stream type using the type lambda - * type NumberStream = Kind + * type NumberStream = HKT.Kind * // Equivalent to: Stream * ``` * - * @category Type Lambdas + * @category type lambdas * @since 2.0.0 */ export interface StreamTypeLambda extends TypeLambda { @@ -167,20 +171,30 @@ export interface StreamTypeLambda extends TypeLambda { } /** - * Variance markers for Stream type parameters. + * Type-level variance marker for `Stream`. * + * **Details** + * + * The emitted value `A`, error `E`, and service requirement `R` type + * parameters are covariant. + * + * @category models * @since 2.0.0 - * @category Models */ export interface Variance { readonly [TypeId]: VarianceStruct } /** - * Structural encoding of Stream type parameter variance. + * Structural encoding used by `Variance` to record each `Stream` type + * parameter's variance. * - * @since 2.0.0 - * @category Models + * **Details** + * + * `_A`, `_E`, and `_R` are covariant markers. + * + * @category models + * @since 3.4.0 */ export interface VarianceStruct { readonly _A: Covariant @@ -191,7 +205,8 @@ export interface VarianceStruct { /** * Extract the success type from a Stream type. * - * @example + * **Example** (Extracting the success type from a Stream type) + * * ```ts * import type { Stream } from "effect" * @@ -200,15 +215,16 @@ export interface VarianceStruct { * // SuccessType is number * ``` * + * @category utility types * @since 3.4.0 - * @category Type-Level */ export type Success> = [T] extends [Stream] ? _A : never /** * Extract the error type from a Stream type. * - * @example + * **Example** (Extracting the error type from a Stream type) + * * ```ts * import type { Stream } from "effect" * @@ -217,19 +233,16 @@ export type Success> = [T] extends [Stream> = [T] extends [Stream] ? _E : never /** * Extract the services type from a Stream type. * - * **Previously Known As:** + * **Example** (Extracting the services type from a Stream type) * - * This type alias was named `Context` in Effect 3.x. - * - * @example * ```ts * import type { Stream } from "effect" * @@ -241,8 +254,8 @@ export type Error> = [T] extends [Stream> = [T] extends [Stream] ? _R : never @@ -250,7 +263,8 @@ export type Services> = [T] extends [Stream> = [T] extends [Stream => hasProperty(u, TypeId) /** * The default chunk size used by Stream constructors and combinators. * - * @example + * **Example** (Reading the default chunk size) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -287,7 +302,7 @@ export const isStream = (u: unknown): u is Stream => * // Output: 4096 * ``` * - * @category Constants + * @category constants * @since 2.0.0 */ export const DefaultChunkSize: number = Channel.DefaultChunkSize @@ -295,21 +310,16 @@ export const DefaultChunkSize: number = Channel.DefaultChunkSize /** * Describes how merged streams decide when to halt. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: - * - * - `StreamHaltStrategy.HaltStrategy` - * - * @category Models - * @since 2.0.0 + * @category models + * @since 4.0.0 */ export type HaltStrategy = Channel.HaltStrategy /** * Creates a stream from a array-emitting `Channel`. * - * @example + * **Example** (Creating a stream from an array-emitting channel) + * * ```ts * import { Channel, Console, Effect, Stream } from "effect" * @@ -323,18 +333,18 @@ export type HaltStrategy = Channel.HaltStrategy * // Output: [ 1, 2, 3 ] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const fromChannel: , E, R>( channel: Channel.Channel ) => Stream ? A : never, E, R> = internal.fromChannel /** - * Either emits the success value of this effect or terminates the stream - * with the failure value of this effect. + * Creates a stream from an effect. + * + * **Example** (Creating a stream from an effect) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -348,8 +358,8 @@ export const fromChannel: , E, R>( * // Output: [ 42 ] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const fromEffect = (effect: Effect.Effect): Stream => fromChannel(Channel.fromEffect(Effect.map(effect, Arr.of))) @@ -357,9 +367,10 @@ export const fromEffect = (effect: Effect.Effect): Stream string @@ -382,8 +393,8 @@ export const fromEffect = (effect: Effect.Effect): Stream(service: Context.Key): Stream => fromEffect(Effect.service(service)) @@ -391,9 +402,15 @@ export const service = (service: Context.Key): Stream = * Optionally accesses a service from the context and emits the result as a * single element. * - * @example + * **When to use** + * + * Use when you need a stream that emits an optional service from the context + * without requiring that service to be present. + * + * **Example** (Accessing an optional service as a stream) + * * ```ts - * import { Effect, Option, Context, Stream } from "effect" + * import { Context, Effect, Option, Stream } from "effect" * * class Greeter extends Context.Service string @@ -421,8 +438,8 @@ export const service = (service: Context.Key): Stream = * // Output: [ "Hello, World!" ] * ``` * + * @category context * @since 4.0.0 - * @category Context */ export const serviceOption = (service: Context.Key): Stream> => fromEffect(Effect.serviceOption(service)) @@ -430,7 +447,8 @@ export const serviceOption = (service: Context.Key): Stream(service: Context.Key): Stream(effect: Effect.Effect): Stream => fromPull(Effect.succeed(Effect.flatMap(effect, () => Cause.done()))) @@ -453,13 +471,8 @@ export const fromEffectDrain = (effect: Effect.Effect): Stream /** * Creates a stream from an effect producing a value of type `A` which repeats forever. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Repeating an effect forever) * - * - `Stream.repeatEffect` - * - * @example * ```ts * import { Console, Effect, Random, Stream } from "effect" * @@ -475,8 +488,8 @@ export const fromEffectDrain = (effect: Effect.Effect): Stream * // Output: [ 3891571149, 4239494205, 2352981603, 2339111046, 1488052210 ] * ``` * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const fromEffectRepeat = (effect: Effect.Effect): Stream, R> => fromPull(Effect.succeed(Effect.map(effect, Arr.of))) @@ -485,13 +498,8 @@ export const fromEffectRepeat = (effect: Effect.Effect): Strea * Creates a stream from an effect producing a value of type `A`, which is * repeated using the specified schedule. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Repeating an effect with a schedule) * - * - `Stream.repeatEffectWithSchedule` - * - * @example * ```ts * import { Console, Effect, Schedule, Stream } from "effect" * @@ -508,8 +516,8 @@ export const fromEffectRepeat = (effect: Effect.Effect): Strea * // Output: [ "ping", "ping", "ping" ] * ``` * - * @since 2.0.0 - * @category Constructors + * @category constructors + * @since 4.0.0 */ export const fromEffectSchedule = ( effect: Effect.Effect, @@ -536,9 +544,11 @@ export const fromEffectSchedule = ( })) /** - * Creates a stream that emits void values spaced by the specified duration. + * Creates a stream that emits `void` immediately once, then emits another + * `void` after each specified interval. + * + * **Example** (Emitting ticks on an interval) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -554,8 +564,8 @@ export const fromEffectSchedule = ( * // Output: [ undefined, undefined, undefined ] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const tick = (interval: Duration.Input): Stream => fromPull(Effect.sync(() => { @@ -574,10 +584,13 @@ export const tick = (interval: Duration.Input): Stream => /** * Creates a stream from a pull effect, such as one produced by `Stream.toPull`. * + * **Details** + * * A pull effect yields chunks on demand and completes when the upstream stream ends. * See `Stream.toPull` for a matching producer. * - * @example + * **Example** (Creating a stream from a pull effect) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -595,17 +608,18 @@ export const tick = (interval: Duration.Input): Stream => * // Output: [1, 2, 3] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const fromPull = ( pull: Effect.Effect, E, void, R>, EX, RX> ): Stream | EX, R | RX> => fromChannel(Channel.fromPull(pull)) /** - * Derive a stream by transforming its pull effect. + * Derives a stream by transforming its pull effect. + * + * **Example** (Transforming a pull effect) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -622,8 +636,8 @@ export const fromPull = ( * // Output: [ 1, 2, 3 ] * ``` * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const transformPull = ( self: Stream, @@ -642,10 +656,13 @@ export const transformPull = ( /** * Transforms a stream by effectfully transforming its pull effect. * + * **Details** + * * A forked scope is also provided to the transformation function, which is * closed once the resulting stream has finished processing. * - * @example + * **Example** (Transforming a stream by effectfully transforming its pull effect) + * * ```ts * import { Console, Effect, Scope, Stream } from "effect" * @@ -670,8 +687,8 @@ export const transformPull = ( * // Releasing scope * ``` * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const transformPullBracket = ( self: Stream, @@ -694,7 +711,8 @@ export const transformPullBracket = ( /** * Creates a channel from a stream. * - * @example + * **Example** (Converting a stream to a channel) + * * ```ts * import { Channel, Console, Effect, Stream } from "effect" * @@ -709,8 +727,8 @@ export const transformPullBracket = ( * // Output: [ 1, 2, 3 ] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const toChannel = ( stream: Stream @@ -719,23 +737,17 @@ export const toChannel = ( /** * Creates a stream from a callback that can emit values into a queue. * - * You can use the `Queue` with the apis from the `Queue` module to emit - * values to the stream or to signal the stream ending. + * **When to use** + * + * Use when you need callback-based code to emit stream values by offering to a + * `Queue`, or signal stream completion through the `Queue` module APIs. * * By default it uses an "unbounded" buffer size. * You can customize the buffer size and strategy by passing an object as the * second argument with the `bufferSize` and `strategy` fields. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Creating a stream from a callback that can emit values into a queue) * - * - `Stream.async` - * - `Stream.asyncEffect` - * - `Stream.asyncPush` - * - `Stream.asyncScoped` - * - * @example * ```ts * import { Console, Effect, Queue, Stream } from "effect" * @@ -759,8 +771,8 @@ export const toChannel = ( * Effect.runPromise(program) * ``` * - * @since 2.0.0 - * @category Constructors + * @category constructors + * @since 4.0.0 */ export const callback = ( f: (queue: Queue.Queue) => Effect.Effect, @@ -773,7 +785,8 @@ export const callback = ( /** * Creates an empty stream. * - * @example + * **Example** (Creating an empty stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -786,15 +799,16 @@ export const callback = ( * // [] * ``` * - * @since 4.0.0 - * @category Constructors + * @category constructors + * @since 2.0.0 */ export const empty: Stream = fromChannel(Channel.empty) /** * Creates a single-valued pure stream. * - * @example + * **Example** (Creating a single-valued pure stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -807,15 +821,16 @@ export const empty: Stream = fromChannel(Channel.empty) * // [ 3 ] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const succeed = (value: A): Stream => fromChannel(Channel.succeed(Arr.of(value))) /** * Creates a stream from a sequence of values. * - * @example + * **Example** (Creating a stream from a sequence of values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -829,17 +844,20 @@ export const succeed = (value: A): Stream => fromChannel(Channel.succeed(A * Effect.runPromise(program) * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const make = >(...values: As): Stream => fromArray(values) /** * Creates a stream that synchronously evaluates a function and emits the result as a single value. * + * **Details** + * * The function is evaluated each time the stream is run. * - * @example + * **Example** (Evaluating a value synchronously) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -852,17 +870,20 @@ export const make = >(...values: As): Stream * // Output: [ 3 ] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const sync = (evaluate: LazyArg): Stream => fromChannel(Channel.sync(() => Arr.of(evaluate()))) /** * Creates a lazily constructed stream. * + * **Details** + * * The stream factory is evaluated each time the stream is run. * - * @example + * **Example** (Creating a lazily constructed stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -875,8 +896,8 @@ export const sync = (evaluate: LazyArg): Stream => fromChannel(Channel. * // Output: [ 1, 2, 3 ] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const suspend = (stream: LazyArg>): Stream => fromChannel(Channel.suspend(() => stream().channel)) @@ -884,7 +905,8 @@ export const suspend = (stream: LazyArg>): Stream(stream: LazyArg>): Stream(error: E): Stream => fromChannel(Channel.fail(error)) /** * Terminates with the specified lazily evaluated error. * - * @example + * **Example** (Failing a stream lazily) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -922,15 +945,16 @@ export const fail = (error: E): Stream => fromChannel(Channel.fail( * // { _id: 'Exit', _tag: 'Failure', cause: { _id: 'Cause', _tag: 'Fail', failure: 'Uh oh!' } } * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const failSync = (evaluate: LazyArg): Stream => fromChannel(Channel.failSync(evaluate)) /** * Creates a stream that fails with the specified `Cause`. * - * @example + * **Example** (Failing with a cause) + * * ```ts * import { Cause, Console, Effect, Stream } from "effect" * @@ -947,15 +971,16 @@ export const failSync = (evaluate: LazyArg): Stream => fromChann * Effect.runPromise(program) * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const failCause = (cause: Cause.Cause): Stream => fromChannel(Channel.failCause(cause)) /** * The stream that dies with the specified defect. * - * @example + * **Example** (Dying with a defect) + * * ```ts * import { Cause, Console, Effect, Exit, Stream } from "effect" * @@ -979,15 +1004,16 @@ export const failCause = (cause: Cause.Cause): Stream => fromCha * // Output: Exit.Failure(Error: Boom) * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const die = (defect: unknown): Stream => fromChannel(Channel.die(defect)) /** * The stream that always fails with the specified lazily evaluated `Cause`. * - * @example + * **Example** (Failing with a lazy cause) + * * ```ts * import { Cause, Console, Effect, Stream } from "effect" * @@ -1005,8 +1031,8 @@ export const die = (defect: unknown): Stream => fromChannel(Channel.die(d * // { _id: 'Exit', _tag: 'Failure', cause: { _id: 'Cause', _tag: 'Fail', failure: 'Connection timeout after retries' } } * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const failCauseSync = (evaluate: LazyArg>): Stream => fromChannel(Channel.failCauseSync(evaluate)) @@ -1014,9 +1040,12 @@ export const failCauseSync = (evaluate: LazyArg>): Stream(evaluate: LazyArg>): Stream(iterator: IterableIterator, maxChunkSize?: number): Stream => fromChannel(Channel.fromIteratorArray(() => iterator, maxChunkSize)) @@ -1046,11 +1075,12 @@ export const fromIteratorSucceed = (iterator: IterableIterator, maxChunkSi /** * Creates a new `Stream` from an iterable collection of values. * - * **Options** + * **Details** * * - `chunkSize`: Maximum number of values emitted per chunk. * - * @example + * **Example** (Creating a stream from an iterable) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -1066,8 +1096,8 @@ export const fromIteratorSucceed = (iterator: IterableIterator, maxChunkSi * // Output: [ 1, 2, 3 ] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const fromIterable = ( iterable: Iterable, @@ -1082,9 +1112,15 @@ export const fromIterable = ( /** * Creates a stream from an effect producing an iterable of values. * - * @example + * **When to use** + * + * Use when the iterable must be acquired from an Effect before the stream emits, + * and acquisition services or failures should be part of the stream. + * + * **Example** (Creating a stream from an iterable effect) + * * ```ts - * import { Console, Effect, Context, Stream } from "effect" + * import { Console, Context, Effect, Stream } from "effect" * * class UserRepo extends Context.Service> @@ -1110,8 +1146,8 @@ export const fromIterable = ( * // Output: [ "user1", "user2" ] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const fromIterableEffect = (iterable: Effect.Effect, E, R>): Stream => unwrap(Effect.map(iterable, fromIterable)) @@ -1119,13 +1155,8 @@ export const fromIterableEffect = (iterable: Effect.Effect, /** * Creates a stream by repeatedly running an effect that yields an iterable of values. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Repeating an iterable effect) * - * - `Stream.repeatEffectChunk` - * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -1141,8 +1172,8 @@ export const fromIterableEffect = (iterable: Effect.Effect, * // Output: [ 1, 2, 1, 2, 1 ] * ``` * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const fromIterableEffectRepeat = ( iterable: Effect.Effect, E, R> @@ -1151,13 +1182,8 @@ export const fromIterableEffectRepeat = ( /** * Creates a stream from an array of values. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Creating a stream from an array of values) * - * - `Stream.fromChunk` - * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -1171,8 +1197,8 @@ export const fromIterableEffectRepeat = ( * // Output: [ 1, 2, 3 ] * ``` * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const fromArray = (array: ReadonlyArray): Stream => Arr.isReadonlyArrayNonEmpty(array) ? fromChannel(Channel.succeed(array)) : empty @@ -1180,7 +1206,13 @@ export const fromArray = (array: ReadonlyArray): Stream => /** * Creates a stream from an effect that produces an array of values. * - * @example + * **When to use** + * + * Use when the array must be acquired from an Effect before the stream emits, + * and acquisition services or failures should be part of the stream. + * + * **Example** (Creating a stream from an effect that produces an array of values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -1194,8 +1226,8 @@ export const fromArray = (array: ReadonlyArray): Stream => * // Output: [ "Ada", "Grace" ] * ``` * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const fromArrayEffect = ( effect: Effect.Effect, E, R> @@ -1204,13 +1236,8 @@ export const fromArrayEffect = ( /** * Creates a stream from an arbitrary number of arrays. * - * **Previously Known As** + * **Example** (Creating a stream from an arbitrary number of arrays) * - * This API replaces the following from Effect 3.x: - * - * - `Stream.fromChunks` - * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -1224,22 +1251,23 @@ export const fromArrayEffect = ( * // Output: [ 1, 2, 3, 4 ] * ``` * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const fromArrays = >>( ...arrays: Arr ): Stream => fromChannel(Channel.fromArray(Arr.filter(arrays, Arr.isReadonlyArrayNonEmpty))) /** - * Creates a stream from a queue of values. + * Creates a stream that pulls values from a `Queue.Dequeue`. * - * **Options** + * **Details** * - * - `maxChunkSize`: The maximum number of queued elements to put in one chunk in the stream - * - `shutdown`: If `true`, the queue will be shutdown after the stream is evaluated (defaults to `false`) + * The stream emits non-empty batches of queued values and ends when the queue + * fails with `Cause.Done`; other queue failures are propagated. + * + * **Example** (Creating a stream from a queue of values) * - * @example * ```ts * import { Console, Effect, Queue, Stream } from "effect" * @@ -1259,8 +1287,8 @@ export const fromArrays = >>( * // Output: [ 1, 2, 3 ] * ``` * - * @since 4.0.0 - * @category Constructors + * @category constructors + * @since 2.0.0 */ export const fromQueue = (queue: Queue.Dequeue): Stream> => fromChannel(Channel.fromQueueArray(queue)) @@ -1268,7 +1296,8 @@ export const fromQueue = (queue: Queue.Dequeue): Stream(queue: Queue.Dequeue): Stream(pubsub: PubSub.PubSub): Stream => fromChannel(Channel.fromPubSubArray(pubsub)) /** * Creates a stream from a PubSub of `Take` values. * + * **Details** + * * `Take` values include end and failure signals. * - * @example + * **Example** (Creating a stream from PubSub takes) + * * ```ts * import { Console, Effect, Exit, PubSub, Stream, Take } from "effect" * @@ -1324,18 +1356,23 @@ export const fromPubSub = (pubsub: PubSub.PubSub): Stream => fromChanne * // Output: [ 1, 2 ] * ``` * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const fromPubSubTake = (pubsub: PubSub.PubSub>): Stream => fromChannel(Channel.fromPubSubTake(pubsub)) /** - * Creates a stream from a `ReadableStream`. + * Creates a stream from a lazily supplied Web `ReadableStream`. * - * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream. + * **Details** + * + * The stream reads from a `ReadableStreamDefaultReader`, maps read failures + * with `onError`, and closes the reader when the stream finalizes. By default + * the reader is canceled; set `releaseLockOnEnd` to release the lock instead. + * + * **Example** (Creating a stream from a ReadableStream) * - * @example * ```ts * import { Console, Data, Effect, Stream } from "effect" * @@ -1363,8 +1400,8 @@ export const fromPubSubTake = (pubsub: PubSub.PubSub>): St * // Output: [ 1, 2, 3 ] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const fromReadableStream = ( options: { @@ -1379,7 +1416,7 @@ export const fromReadableStream = ( scope, options.releaseLockOnEnd ? Effect.sync(() => reader.releaseLock()) - : Effect.promise(() => reader.cancel()) + : Effect.promise(() => reader.cancel().catch(constVoid)) ) return Effect.flatMap( Effect.tryPromise({ @@ -1393,9 +1430,10 @@ export const fromReadableStream = ( /** * Creates a stream from an AsyncIterable. * - * @example + * **Example** (Creating a stream from an AsyncIterable) + * * ```ts - * import { Console, Data, Effect, Stream } from "effect" + * import { Data, Effect, Stream } from "effect" * * class StreamError extends Data.TaggedError("StreamError")<{ readonly cause: unknown }> {} * @@ -1405,18 +1443,17 @@ export const fromReadableStream = ( * yield 3 * })() * - * const program = Effect.gen(function*() { + * Effect.runPromise(Effect.gen(function*() { * const stream = Stream.fromAsyncIterable(iterable, (cause) => new StreamError({ cause })) * const values = yield* Stream.runCollect(stream) - * yield* Console.log(values) - * }) + * yield* Effect.sync(() => console.log(values)) + * })) * - * Effect.runPromise(program) - * // Output: [ 1, 2, 3 ] + * // [ 1, 2, 3 ] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const fromAsyncIterable = ( iterable: AsyncIterable, @@ -1427,7 +1464,8 @@ export const fromAsyncIterable = ( * Creates a stream that emits each output of a schedule that does not require input, * for as long as the schedule continues. * - * @example + * **Example** (Creating a stream from a schedule) + * * ```ts * import { Console, Effect, Schedule, Stream } from "effect" * @@ -1444,8 +1482,8 @@ export const fromAsyncIterable = ( * // Output: [ 0, 1, 2 ] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const fromSchedule = (schedule: Schedule.Schedule): Stream => fromPull( @@ -1458,10 +1496,14 @@ export const fromSchedule = (schedule: Schedule.Schedule(schedule: Schedule.Schedule(pubsub: PubSub.Subscription): Stream => fromChannel(Channel.fromSubscriptionArray(pubsub)) @@ -1490,8 +1532,8 @@ export const fromSubscription = (pubsub: PubSub.Subscription): Stream = /** * Interface representing an event listener target. * + * @category models * @since 3.4.0 - * @category Models */ export interface EventListener { addEventListener( @@ -1516,26 +1558,35 @@ export interface EventListener { /** * Creates a stream from an event listener. * - * @example + * **Example** (Creating a stream from an event listener) + * * ```ts - * import { Console, Effect, Stream } from "effect" + * import { Effect, Stream } from "effect" * - * declare const target: Stream.EventListener + * class NumberTarget implements Stream.EventListener { + * addEventListener(event: string, f: (event: number) => void) { + * if (event === "data") { + * f(1) + * f(2) + * f(3) + * } + * } + * removeEventListener(_event: string, _f: (event: number) => void) {} + * } * - * const program = Effect.gen(function*() { - * const stream = Stream.fromEventListener(target, "data").pipe( + * Effect.runPromise(Effect.gen(function*() { + * const stream = Stream.fromEventListener(new NumberTarget(), "data").pipe( * Stream.take(3) * ) * const values = yield* Stream.runCollect(stream) - * yield* Console.log(values) - * }) + * yield* Effect.sync(() => console.log(values)) + * })) * - * Effect.runPromise(program) - * // Output: [ 1, 2, 3 ] + * // [ 1, 2, 3 ] * ``` * + * @category constructors * @since 3.1.0 - * @category Constructors */ export const fromEventListener = ( target: EventListener, @@ -1558,9 +1609,16 @@ export const fromEventListener = ( }, { bufferSize: typeof options === "object" ? options.bufferSize : undefined }) /** - * Creates a stream by peeling off successive layers of a state value. + * Creates a stream by repeatedly applying an effectful step function to a + * state. + * + * **Details** + * + * Each `readonly [value, nextState]` result emits `value` and continues with + * `nextState`; returning `undefined` ends the stream. + * + * **Example** (Unfolding stream state) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -1574,8 +1632,8 @@ export const fromEventListener = ( * // Output: [ 1, 2, 3, 4, 5 ] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const unfold = ( s: S, @@ -1591,14 +1649,22 @@ export const unfold = ( })) /** - * Like `Stream.unfold`, but allows the emission of values to end one step further - * than the unfolding of the state. This is useful for embedding paginated APIs, - * hence the name. + * Creates a stream by repeatedly evaluating an effectful page function. + * + * **When to use** + * + * Use to consume paginated APIs where each step returns a batch of values + * together with an optional next state. + * + * **Details** + * + * This is similar to {@link unfold}, but each step can emit zero or more values + * and independently decide whether another state should be requested. + * + * **Example** (Paginating stream state) * - * @example * ```ts - * import { Console, Effect, Stream } from "effect" - * import * as Option from "effect/Option" + * import { Console, Effect, Option, Stream } from "effect" * * const stream = Stream.paginate(0, (n: number) => * Effect.succeed( @@ -1612,8 +1678,8 @@ export const unfold = ( * // Output: [ 0, 1, 2, 3 ] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const paginate = ( s: S, @@ -1641,7 +1707,8 @@ export const paginate = ( /** * Creates an infinite stream by repeatedly applying a function to a seed value. * - * @example + * **Example** (Iterating from a seed value) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -1656,8 +1723,8 @@ export const paginate = ( * // Output: [ 1, 2, 3 ] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const iterate = (value: A, next: (value: A) => A): Stream => unfold(value, (a) => Effect.succeed([a, next(a)])) @@ -1665,10 +1732,13 @@ export const iterate = (value: A, next: (value: A) => A): Stream => /** * Constructs a stream from a range of integers, including both endpoints. * + * **Details** + * * If the provided `min` is greater than `max`, the stream will not emit any * values. * - * @example + * **Example** (Creating a numeric range) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -1680,8 +1750,9 @@ export const iterate = (value: A, next: (value: A) => A): Stream => * Effect.runPromise(program) * // Output: [ 1, 2, 3, 4, 5 ] * ``` - * @since 4.0.0 - * @category Constructors + * + * @category constructors + * @since 2.0.0 */ export const range = ( min: number, @@ -1708,7 +1779,8 @@ export const range = ( /** * The stream that never produces any value or fails with any error. * - * @example + * **Example** (Creating a never-ending stream) + * * ```ts * import { Effect, Stream } from "effect" * @@ -1721,15 +1793,16 @@ export const range = ( * // [] * ``` * - * @since 4.0.0 - * @category Constructors + * @category constructors + * @since 2.0.0 */ export const never: Stream = fromChannel(Channel.never) /** * Creates a stream produced from an `Effect`. * - * @example + * **Example** (Unwrapping a stream effect) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -1744,8 +1817,8 @@ export const never: Stream = fromChannel(Channel.never) * // [1, 2, 3] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const unwrap = ( effect: Effect.Effect, E, R> @@ -1755,7 +1828,8 @@ export const unwrap = ( * Runs a stream that requires `Scope` in a managed scope, ensuring its * finalizers are run when the stream completes. * - * @example + * **Example** (Scoping a stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -1774,8 +1848,8 @@ export const unwrap = ( * // [ "resource" ] * ``` * + * @category constructors * @since 2.0.0 - * @category Constructors */ export const scoped = ( self: Stream @@ -1784,7 +1858,8 @@ export const scoped = ( /** * Transforms the elements of this stream using the supplied function. * - * @example + * **Example** (Mapping stream values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -1797,14 +1872,15 @@ export const scoped = ( * // [ 1, 3, 5 ] * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ export const map: { /** * Transforms the elements of this stream using the supplied function. * - * @example + * **Example** (Mapping stream values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -1817,14 +1893,15 @@ export const map: { * // [ 1, 3, 5 ] * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ (f: (a: A, i: number) => B): (self: Stream) => Stream /** * Transforms the elements of this stream using the supplied function. * - * @example + * **Example** (Mapping stream values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -1837,8 +1914,8 @@ export const map: { * // [ 1, 3, 5 ] * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ (self: Stream, f: (a: A, i: number) => B): Stream } = dual(2, (self: Stream, f: (a: A, i: number) => B): Stream => @@ -1853,7 +1930,8 @@ export const map: { /** * Maps both the failure and success channels of a stream. * - * @example + * **Example** (Mapping both the failure and success channels of a stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -1882,14 +1960,15 @@ export const map: { * // Output: [ "error: boom" ] * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ export const mapBoth: { /** * Maps both the failure and success channels of a stream. * - * @example + * **Example** (Mapping both the failure and success channels of a stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -1918,8 +1997,8 @@ export const mapBoth: { * // Output: [ "error: boom" ] * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ ( options: { readonly onFailure: (e: E) => E2; readonly onSuccess: (a: A) => A2 } @@ -1927,7 +2006,8 @@ export const mapBoth: { /** * Maps both the failure and success channels of a stream. * - * @example + * **Example** (Mapping both the failure and success channels of a stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -1956,8 +2036,8 @@ export const mapBoth: { * // Output: [ "error: boom" ] * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ ( self: Stream, @@ -1975,13 +2055,8 @@ export const mapBoth: { /** * Transforms each emitted chunk using the provided function, which receives the chunk and its index. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Mapping stream chunks) * - * - `Stream.mapChunks` - * - * @example * ```ts * import { Array, Console, Effect, Stream } from "effect" * @@ -1998,20 +2073,15 @@ export const mapBoth: { * // Output: [ 1, 2, 4, 5 ] * ``` * - * @since 2.0.0 - * @category Mapping + * @category mapping + * @since 4.0.0 */ export const mapArray: { /** * Transforms each emitted chunk using the provided function, which receives the chunk and its index. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Mapping stream chunks) * - * - `Stream.mapChunks` - * - * @example * ```ts * import { Array, Console, Effect, Stream } from "effect" * @@ -2028,8 +2098,8 @@ export const mapArray: { * // Output: [ 1, 2, 4, 5 ] * ``` * - * @since 2.0.0 - * @category Mapping + * @category mapping + * @since 4.0.0 */ ( f: (a: Arr.NonEmptyReadonlyArray, i: number) => Arr.NonEmptyReadonlyArray @@ -2037,13 +2107,8 @@ export const mapArray: { /** * Transforms each emitted chunk using the provided function, which receives the chunk and its index. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Mapping stream chunks) * - * - `Stream.mapChunks` - * - * @example * ```ts * import { Array, Console, Effect, Stream } from "effect" * @@ -2060,8 +2125,8 @@ export const mapArray: { * // Output: [ 1, 2, 4, 5 ] * ``` * - * @since 2.0.0 - * @category Mapping + * @category mapping + * @since 4.0.0 */ ( self: Stream, @@ -2075,7 +2140,13 @@ export const mapArray: { /** * Maps over elements of the stream with the specified effectful function. * - * @example + * **When to use** + * + * Use when each stream element transformation needs an Effect, service + * dependency, failure channel, or configured concurrency. + * + * **Example** (Effectfully mapping stream values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2103,14 +2174,20 @@ export const mapArray: { * // [2, 4, 6] * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ export const mapEffect: { /** * Maps over elements of the stream with the specified effectful function. * - * @example + * **When to use** + * + * Use when each stream element transformation needs an Effect, service + * dependency, failure channel, or configured concurrency. + * + * **Example** (Effectfully mapping stream values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2138,8 +2215,8 @@ export const mapEffect: { * // [2, 4, 6] * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ ( f: (a: A, i: number) => Effect.Effect, @@ -2151,7 +2228,13 @@ export const mapEffect: { /** * Maps over elements of the stream with the specified effectful function. * - * @example + * **When to use** + * + * Use when each stream element transformation needs an Effect, service + * dependency, failure channel, or configured concurrency. + * + * **Example** (Effectfully mapping stream values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2179,8 +2262,8 @@ export const mapEffect: { * // [2, 4, 6] * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ ( self: Stream, @@ -2208,7 +2291,13 @@ export const mapEffect: { /** * Flattens a stream of `Effect` values into a stream of their results. * - * @example + * **When to use** + * + * Use when stream elements already are effects and their successes should become + * stream elements while their failures enter the stream error channel. + * + * **Example** (Flattening a stream of Effect values into a stream of their results) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2223,8 +2312,8 @@ export const mapEffect: { * // Output: [1, 2, 3] * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ export const flattenEffect: < Arg extends Stream, any, any> | { @@ -2254,15 +2343,15 @@ export const flattenEffect: < ) /** - * Effectfully maps over non-empty array chunks emitted by the stream. + * Maps over non-empty array chunks emitted by the stream effectfully. * - * **Previously Known As** + * **When to use** * - * This API replaces the following from Effect 3.x: + * Use when transformation needs to see and replace each non-empty emitted chunk + * effectfully instead of mapping individual stream elements. * - * - `Stream.mapChunksEffect` + * **Example** (Effectfully mapping stream chunks) * - * @example * ```ts * import { Array, Console, Effect, Stream } from "effect" * @@ -2281,20 +2370,20 @@ export const flattenEffect: < * // Output: [1, 2, 13, 14] * ``` * + * @category mapping * @since 4.0.0 - * @category Mapping */ export const mapArrayEffect: { /** - * Effectfully maps over non-empty array chunks emitted by the stream. + * Maps over non-empty array chunks emitted by the stream effectfully. * - * **Previously Known As** + * **When to use** * - * This API replaces the following from Effect 3.x: + * Use when transformation needs to see and replace each non-empty emitted chunk + * effectfully instead of mapping individual stream elements. * - * - `Stream.mapChunksEffect` + * **Example** (Effectfully mapping stream chunks) * - * @example * ```ts * import { Array, Console, Effect, Stream } from "effect" * @@ -2313,22 +2402,22 @@ export const mapArrayEffect: { * // Output: [1, 2, 13, 14] * ``` * + * @category mapping * @since 4.0.0 - * @category Mapping */ ( f: (a: Arr.NonEmptyReadonlyArray, i: number) => Effect.Effect, E2, R2> ): (self: Stream) => Stream /** - * Effectfully maps over non-empty array chunks emitted by the stream. + * Maps over non-empty array chunks emitted by the stream effectfully. * - * **Previously Known As** + * **When to use** * - * This API replaces the following from Effect 3.x: + * Use when transformation needs to see and replace each non-empty emitted chunk + * effectfully instead of mapping individual stream elements. * - * - `Stream.mapChunksEffect` + * **Example** (Effectfully mapping stream chunks) * - * @example * ```ts * import { Array, Console, Effect, Stream } from "effect" * @@ -2347,8 +2436,8 @@ export const mapArrayEffect: { * // Output: [1, 2, 13, 14] * ``` * + * @category mapping * @since 4.0.0 - * @category Mapping */ ( self: Stream, @@ -2362,15 +2451,12 @@ export const mapArrayEffect: { /** * Lifts failures and successes into a `Result`, yielding a stream that cannot fail. * - * The stream ends after the first failure, emitting a `Result.fail` value. - * - * **Previously Known As:** + * **Details** * - * This API replaces the following from Effect 3.x: + * The stream ends after the first failure, emitting a `Result.fail` value. * - * - `Stream.either` + * **Example** (Converting failures to results) * - * @example * ```ts * import { Console, Effect, Result, Stream } from "effect" * @@ -2391,8 +2477,8 @@ export const mapArrayEffect: { * // Output: [ "success: 1", "success: 2", "failure: boom" ] * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const result = (self: Stream): Stream, never, R> => self.pipe( @@ -2403,7 +2489,8 @@ export const result = (self: Stream): Stream(self: Stream): Stream( f: (a: NoInfer) => Effect.Effect, @@ -2474,7 +2562,8 @@ export const tap: { /** * Runs the provided effect for each element while preserving the elements. * - * @example + * **Example** (Tapping stream values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2500,8 +2589,8 @@ export const tap: { * // [ 2, 4, 6 ] * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ ( self: Stream, @@ -2526,7 +2615,8 @@ export const tap: { /** * Returns a stream that effectfully "peeks" at elements and failures. * - * @example + * **Example** (Tapping values and errors) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2551,14 +2641,15 @@ export const tap: { * // [ 1, 2, 3 ] * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const tapBoth: { /** * Returns a stream that effectfully "peeks" at elements and failures. * - * @example + * **Example** (Tapping values and errors) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2583,8 +2674,8 @@ export const tapBoth: { * // [ 1, 2, 3 ] * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ ( options: { @@ -2596,7 +2687,8 @@ export const tapBoth: { /** * Returns a stream that effectfully "peeks" at elements and failures. * - * @example + * **Example** (Tapping values and errors) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2621,8 +2713,8 @@ export const tapBoth: { * // [ 1, 2, 3 ] * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ ( self: Stream, @@ -2646,10 +2738,10 @@ export const tapBoth: { )) /** - * Sends all elements emitted by this stream to the specified sink in addition - * to emitting them. + * Runs a sink for all stream elements while still emitting them downstream. + * + * **Example** (Tapping values with a sink) * - * @example * ```ts * import { Console, Effect, Ref, Sink, Stream } from "effect" * @@ -2672,15 +2764,15 @@ export const tapBoth: { * // Output: [1, 2, 3] * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const tapSink: { /** - * Sends all elements emitted by this stream to the specified sink in addition - * to emitting them. + * Runs a sink for all stream elements while still emitting them downstream. + * + * **Example** (Tapping values with a sink) * - * @example * ```ts * import { Console, Effect, Ref, Sink, Stream } from "effect" * @@ -2703,15 +2795,15 @@ export const tapSink: { * // Output: [1, 2, 3] * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (sink: Sink.Sink): (self: Stream) => Stream /** - * Sends all elements emitted by this stream to the specified sink in addition - * to emitting them. + * Runs a sink for all stream elements while still emitting them downstream. + * + * **Example** (Tapping values with a sink) * - * @example * ```ts * import { Console, Effect, Ref, Sink, Stream } from "effect" * @@ -2734,8 +2826,8 @@ export const tapSink: { * // Output: [1, 2, 3] * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (self: Stream, sink: Sink.Sink): Stream } = dual( @@ -2804,9 +2896,17 @@ export const tapSink: { ) /** - * Maps each element to a stream and concatenates the results in order. + * Maps each element to a stream and flattens the resulting streams. + * + * **Details** + * + * With the default sequential concurrency, inner streams are concatenated in + * input order. When `concurrency` is greater than `1` or `"unbounded"`, + * multiple inner streams may run at the same time and their outputs are merged + * as they arrive. + * + * **Example** (FlatMapping stream values) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2822,14 +2922,22 @@ export const tapSink: { * // Output: [ 1, 2, 2, 4, 3, 6 ] * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ export const flatMap: { /** - * Maps each element to a stream and concatenates the results in order. + * Maps each element to a stream and flattens the resulting streams. + * + * **Details** + * + * With the default sequential concurrency, inner streams are concatenated in + * input order. When `concurrency` is greater than `1` or `"unbounded"`, + * multiple inner streams may run at the same time and their outputs are merged + * as they arrive. + * + * **Example** (FlatMapping stream values) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2845,8 +2953,8 @@ export const flatMap: { * // Output: [ 1, 2, 2, 4, 3, 6 ] * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ ( f: (a: A) => Stream, @@ -2856,9 +2964,17 @@ export const flatMap: { } | undefined ): (self: Stream) => Stream /** - * Maps each element to a stream and concatenates the results in order. + * Maps each element to a stream and flattens the resulting streams. + * + * **Details** + * + * With the default sequential concurrency, inner streams are concatenated in + * input order. When `concurrency` is greater than `1` or `"unbounded"`, + * multiple inner streams may run at the same time and their outputs are merged + * as they arrive. + * + * **Example** (FlatMapping stream values) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2874,8 +2990,8 @@ export const flatMap: { * // Output: [ 1, 2, 2, 4, 3, 6 ] * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ ( self: Stream, @@ -2903,7 +3019,8 @@ export const flatMap: { * Switches to the latest stream produced by the mapping function, interrupting * the previous stream when a new element arrives. * - * @example + * **Example** (Switching to the latest stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2919,15 +3036,16 @@ export const flatMap: { * }) * ``` * + * @category sequencing * @since 4.0.0 - * @category Sequencing */ export const switchMap: { /** * Switches to the latest stream produced by the mapping function, interrupting * the previous stream when a new element arrives. * - * @example + * **Example** (Switching to the latest stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2943,8 +3061,8 @@ export const switchMap: { * }) * ``` * + * @category sequencing * @since 4.0.0 - * @category Sequencing */ ( f: (a: A) => Stream, @@ -2957,7 +3075,8 @@ export const switchMap: { * Switches to the latest stream produced by the mapping function, interrupting * the previous stream when a new element arrives. * - * @example + * **Example** (Switching to the latest stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -2973,8 +3092,8 @@ export const switchMap: { * }) * ``` * + * @category sequencing * @since 4.0.0 - * @category Sequencing */ ( self: Stream, @@ -2999,10 +3118,17 @@ export const switchMap: { )) /** - * Flattens a stream of streams into a single stream by concatenating the - * inner streams in strict order. + * Flattens a stream of streams into a single stream. + * + * **Details** + * + * With the default sequential concurrency, inner streams are concatenated in + * strict order. When `concurrency` is greater than `1` or `"unbounded"`, + * multiple inner streams may run at the same time and their outputs are merged + * as they arrive. + * + * **Example** (Flattening nested streams) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3021,8 +3147,8 @@ export const switchMap: { * // Output: [ 1, 2, 3, 4, 5, 6 ] * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ export const flatten: < Arg extends Stream, any, any> | { @@ -3053,13 +3179,8 @@ export const flatten: < /** * Flattens a stream of non-empty arrays into a stream of elements. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: - * - * - `Stream.flattenChunks` + * **Example** (Flattening a stream of non-empty arrays into a stream of elements) * - * @example * ```ts * import { Array, Console, Effect, Stream } from "effect" * @@ -3074,8 +3195,8 @@ export const flatten: < * // Output: [ 1, 2, 3 ] * ``` * + * @category sequencing * @since 4.0.0 - * @category Sequencing */ export const flattenArray = (self: Stream, E, R>): Stream => fromChannel(Channel.flattenArray(self.channel)) @@ -3083,7 +3204,8 @@ export const flattenArray = (self: Stream, /** * Converts this stream to one that runs its effects but emits no elements. * - * @example + * **Example** (Draining stream values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3096,8 +3218,8 @@ export const flattenArray = (self: Stream, * // Output: [] * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const drain = (self: Stream): Stream => fromChannel(Channel.drain(self.channel)) @@ -3105,7 +3227,8 @@ export const drain = (self: Stream): Stream => fr * Runs the provided stream in the background while this stream runs, interrupting it * when this stream completes and failing if the background stream fails or defects. * - * @example + * **Example** (Draining a stream in the background) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3125,15 +3248,16 @@ export const drain = (self: Stream): Stream => fr * // Output: [ 1, 2 ] * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const drainFork: { /** * Runs the provided stream in the background while this stream runs, interrupting it * when this stream completes and failing if the background stream fails or defects. * - * @example + * **Example** (Draining a stream in the background) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3153,15 +3277,16 @@ export const drainFork: { * // Output: [ 1, 2 ] * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (that: Stream): (self: Stream) => Stream /** * Runs the provided stream in the background while this stream runs, interrupting it * when this stream completes and failing if the background stream fails or defects. * - * @example + * **Example** (Draining a stream in the background) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3181,8 +3306,8 @@ export const drainFork: { * // Output: [ 1, 2 ] * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (self: Stream, that: Stream): Stream } = dual( @@ -3194,7 +3319,8 @@ export const drainFork: { /** * Repeats the entire stream according to the provided schedule. * - * @example + * **Example** (Repeating a stream on a schedule) + * * ```ts * import { Console, Effect, Schedule, Stream } from "effect" * @@ -3211,14 +3337,15 @@ export const drainFork: { * // Output: [ 1, 1, 1, 1, 1 ] * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const repeat: { /** * Repeats the entire stream according to the provided schedule. * - * @example + * **Example** (Repeating a stream on a schedule) + * * ```ts * import { Console, Effect, Schedule, Stream } from "effect" * @@ -3235,8 +3362,8 @@ export const repeat: { * // Output: [ 1, 1, 1, 1, 1 ] * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ ( schedule: @@ -3248,7 +3375,8 @@ export const repeat: { /** * Repeats the entire stream according to the provided schedule. * - * @example + * **Example** (Repeating a stream on a schedule) + * * ```ts * import { Console, Effect, Schedule, Stream } from "effect" * @@ -3265,8 +3393,8 @@ export const repeat: { * // Output: [ 1, 1, 1, 1, 1 ] * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ ( self: Stream, @@ -3286,9 +3414,10 @@ export const repeat: { ): Stream => fromChannel(Channel.repeat(self.channel, schedule))) /** - * Spaces the stream's elements according to the provided `schedule`. + * Schedules the stream's elements according to the provided schedule. + * + * **Example** (Scheduling stream elements) * - * @example * ```ts * import { Console, Effect, Schedule, Stream } from "effect" * @@ -3305,14 +3434,15 @@ export const repeat: { * // Output: [ 1, 2, 3 ] * ``` * + * @category rate limiting * @since 2.0.0 - * @category Rate Limiting */ export const schedule: { /** - * Spaces the stream's elements according to the provided `schedule`. + * Schedules the stream's elements according to the provided schedule. + * + * **Example** (Scheduling stream elements) * - * @example * ```ts * import { Console, Effect, Schedule, Stream } from "effect" * @@ -3329,14 +3459,15 @@ export const schedule: { * // Output: [ 1, 2, 3 ] * ``` * + * @category rate limiting * @since 2.0.0 - * @category Rate Limiting */ (schedule: Schedule.Schedule, E2, R2>): (self: Stream) => Stream /** - * Spaces the stream's elements according to the provided `schedule`. + * Schedules the stream's elements according to the provided schedule. + * + * **Example** (Scheduling stream elements) * - * @example * ```ts * import { Console, Effect, Schedule, Stream } from "effect" * @@ -3353,8 +3484,8 @@ export const schedule: { * // Output: [ 1, 2, 3 ] * ``` * + * @category rate limiting * @since 2.0.0 - * @category Rate Limiting */ (self: Stream, schedule: Schedule.Schedule, E2, R2>): Stream } = dual(2, ( @@ -3371,7 +3502,8 @@ export const schedule: { /** * Ends the stream if it does not produce a value within the specified duration. * - * @example + * **Example** (Timing out a stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3388,14 +3520,15 @@ export const schedule: { * // Output: [ 1 ] * ``` * + * @category rate limiting * @since 2.0.0 - * @category Rate Limiting */ export const timeout: { /** * Ends the stream if it does not produce a value within the specified duration. * - * @example + * **Example** (Timing out a stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3412,14 +3545,15 @@ export const timeout: { * // Output: [ 1 ] * ``` * + * @category rate limiting * @since 2.0.0 - * @category Rate Limiting */ (duration: Duration.Input): (self: Stream) => Stream /** * Ends the stream if it does not produce a value within the specified duration. * - * @example + * **Example** (Timing out a stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3436,8 +3570,8 @@ export const timeout: { * // Output: [ 1 ] * ``` * + * @category rate limiting * @since 2.0.0 - * @category Rate Limiting */ (self: Stream, duration: Duration.Input): Stream } = dual( @@ -3450,13 +3584,53 @@ export const timeout: { ) /** - * @since 2.0.0 - * @category Rate Limiting + * Switches to a fallback stream if this stream does not emit a value within + * the specified duration. + * + * **When to use** + * + * Use when a stream should continue with another stream if an upstream pull + * waits longer than the allowed duration. + * + * **Details** + * + * The timeout is checked for each pull. A zero duration uses `orElse` + * immediately, while an infinite duration leaves the original stream + * unchanged. + * + * **Gotchas** + * + * The fallback stream is not timed after the switch. + * + * @see {@link timeout} for ending the stream instead of switching to a fallback stream + * + * @category rate limiting + * @since 4.0.0 */ export const timeoutOrElse: { /** - * @since 2.0.0 - * @category Rate Limiting + * Switches to a fallback stream if this stream does not emit a value within + * the specified duration. + * + * **When to use** + * + * Use when a stream should continue with another stream if an upstream pull + * waits longer than the allowed duration. + * + * **Details** + * + * The timeout is checked for each pull. A zero duration uses `orElse` + * immediately, while an infinite duration leaves the original stream + * unchanged. + * + * **Gotchas** + * + * The fallback stream is not timed after the switch. + * + * @see {@link timeout} for ending the stream instead of switching to a fallback stream + * + * @category rate limiting + * @since 4.0.0 */ ( options: { @@ -3465,8 +3639,28 @@ export const timeoutOrElse: { } ): (self: Stream) => Stream /** - * @since 2.0.0 - * @category Rate Limiting + * Switches to a fallback stream if this stream does not emit a value within + * the specified duration. + * + * **When to use** + * + * Use when a stream should continue with another stream if an upstream pull + * waits longer than the allowed duration. + * + * **Details** + * + * The timeout is checked for each pull. A zero duration uses `orElse` + * immediately, while an infinite duration leaves the original stream + * unchanged. + * + * **Gotchas** + * + * The fallback stream is not timed after the switch. + * + * @see {@link timeout} for ending the stream instead of switching to a fallback stream + * + * @category rate limiting + * @since 4.0.0 */ ( self: Stream, @@ -3536,9 +3730,8 @@ export const timeoutOrElse: { * Repeats each element of the stream according to the provided schedule, * including the original emission. * - * @since 2.0.0 - * @category Sequencing - * @example + * **Example** (Repeating stream elements) + * * ```ts * import { Console, Effect, Schedule, Stream } from "effect" * @@ -3553,15 +3746,17 @@ export const timeoutOrElse: { * Effect.runPromise(program) * // Output: [ "A", "A", "B", "B", "C", "C" ] * ``` + * + * @category sequencing + * @since 2.0.0 */ export const repeatElements: { /** * Repeats each element of the stream according to the provided schedule, * including the original emission. * - * @since 2.0.0 - * @category Sequencing - * @example + * **Example** (Repeating stream elements) + * * ```ts * import { Console, Effect, Schedule, Stream } from "effect" * @@ -3576,15 +3771,17 @@ export const repeatElements: { * Effect.runPromise(program) * // Output: [ "A", "A", "B", "B", "C", "C" ] * ``` + * + * @category sequencing + * @since 2.0.0 */ (schedule: Schedule.Schedule): (self: Stream) => Stream /** * Repeats each element of the stream according to the provided schedule, * including the original emission. * - * @since 2.0.0 - * @category Sequencing - * @example + * **Example** (Repeating stream elements) + * * ```ts * import { Console, Effect, Schedule, Stream } from "effect" * @@ -3599,6 +3796,9 @@ export const repeatElements: { * Effect.runPromise(program) * // Output: [ "A", "A", "B", "B", "C", "C" ] * ``` + * + * @category sequencing + * @since 2.0.0 */ (self: Stream, schedule: Schedule.Schedule): Stream } = dual( @@ -3641,7 +3841,8 @@ export const repeatElements: { /** * Repeats this stream forever. * - * @example + * **Example** (Repeating a stream forever) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3659,21 +3860,16 @@ export const repeatElements: { * // Output: [ "A", "B", "A", "B", "A" ] * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const forever = (self: Stream): Stream => fromChannel(Channel.forever(self.channel)) /** - * Submerges the iterables emitted by this stream into the stream's structure. + * Flattens the iterables emitted by this stream into the stream's structure. * - * **Previously Known As** + * **Example** (Flattening iterable values) * - * This API replaces the following from Effect 3.x: - * - * - `Stream.flattenIterables` - * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3687,8 +3883,8 @@ export const forever = (self: Stream): Stream => from * // Output: [ 1, 2, 3, 4 ] * ``` * + * @category mapping * @since 4.0.0 - * @category Mapping */ export const flattenIterable = (self: Stream, E, R>): Stream => flatMap(self, fromIterable) @@ -3697,7 +3893,8 @@ export const flattenIterable = (self: Stream, E, R>): Strea * Unwraps `Take` values, emitting elements from non-empty arrays and ending or * failing when the `Exit` signals completion. * - * @example + * **Example** (Flattening Take values) + * * ```ts * import { Array, Console, Effect, Exit, Stream } from "effect" * @@ -3716,8 +3913,8 @@ export const flattenIterable = (self: Stream, E, R>): Strea * // Output: [ 1, 2, 3 ] * ``` * - * @since 4.0.0 - * @category Sequencing + * @category sequencing + * @since 2.0.0 */ export const flattenTake = (self: Stream, E2, R>): Stream => self.channel.pipe( @@ -3730,7 +3927,8 @@ export const flattenTake = (self: Stream, E2, R>): * Concatenates two streams, emitting all elements from the first stream * followed by all elements from the second stream. * - * @example + * **Example** (Concatenating streams) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3743,15 +3941,16 @@ export const flattenTake = (self: Stream, E2, R>): * // Output: [ 1, 2, 3, 4, 5, 6 ] * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const concat: { /** * Concatenates two streams, emitting all elements from the first stream * followed by all elements from the second stream. * - * @example + * **Example** (Concatenating streams) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3764,15 +3963,16 @@ export const concat: { * // Output: [ 1, 2, 3, 4, 5, 6 ] * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (that: Stream): (self: Stream) => Stream /** * Concatenates two streams, emitting all elements from the first stream * followed by all elements from the second stream. * - * @example + * **Example** (Concatenating streams) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3785,8 +3985,8 @@ export const concat: { * // Output: [ 1, 2, 3, 4, 5, 6 ] * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (self: Stream, that: Stream): Stream } = dual( @@ -3796,7 +3996,8 @@ export const concat: { * Concatenates two streams, emitting all elements from the first stream * followed by all elements from the second stream. * - * @example + * **Example** (Concatenating streams) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3809,8 +4010,8 @@ export const concat: { * // Output: [ 1, 2, 3, 4, 5, 6 ] * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ Stream>([self, that])) ) @@ -3818,7 +4019,8 @@ export const concat: { /** * Prepends the values from the provided iterable before the stream's elements. * - * @example + * **Example** (Prepending values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3835,14 +4037,15 @@ export const concat: { * Effect.runPromise(program) * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const prepend: { /** * Prepends the values from the provided iterable before the stream's elements. * - * @example + * **Example** (Prepending values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3859,14 +4062,15 @@ export const prepend: { * Effect.runPromise(program) * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (values: Iterable): (self: Stream) => Stream /** * Prepends the values from the provided iterable before the stream's elements. * - * @example + * **Example** (Prepending values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3883,8 +4087,8 @@ export const prepend: { * Effect.runPromise(program) * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (self: Stream, values: Iterable): Stream } = dual(2, ( @@ -3895,10 +4099,13 @@ export const prepend: { /** * Merges two streams, emitting elements from both as they arrive. * + * **Details** + * * By default, the merged stream ends when both streams end. Use * `haltStrategy` to change the termination behavior. * - * @example + * **Example** (Merging stream values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3914,17 +4121,20 @@ export const prepend: { * // Output: [ 1, 2, 3, 4 ] * ``` * + * @category merging * @since 2.0.0 - * @category Merging */ export const merge: { /** * Merges two streams, emitting elements from both as they arrive. * + * **Details** + * * By default, the merged stream ends when both streams end. Use * `haltStrategy` to change the termination behavior. * - * @example + * **Example** (Merging stream values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3940,8 +4150,8 @@ export const merge: { * // Output: [ 1, 2, 3, 4 ] * ``` * + * @category merging * @since 2.0.0 - * @category Merging */ ( that: Stream, @@ -3952,10 +4162,13 @@ export const merge: { /** * Merges two streams, emitting elements from both as they arrive. * + * **Details** + * * By default, the merged stream ends when both streams end. Use * `haltStrategy` to change the termination behavior. * - * @example + * **Example** (Merging stream values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -3971,8 +4184,8 @@ export const merge: { * // Output: [ 1, 2, 3, 4 ] * ``` * + * @category merging * @since 2.0.0 - * @category Merging */ ( self: Stream, @@ -3995,12 +4208,18 @@ export const merge: { /** * Merges this stream with a background effect, keeping the stream's elements. * + * **When to use** + * + * Use when an effect should run concurrently for the lifetime of a stream while + * only the stream's elements remain in the output. + * + * **Details** + * * The effect runs concurrently, fails the stream if it fails, and is interrupted * when the stream completes. * - * @since 4.0.0 - * @category Merging - * @example + * **Example** (Merging with a background effect) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4017,17 +4236,26 @@ export const merge: { * // Output: side task * // Output: [ 1, 2, 3 ] * ``` + * + * @category merging + * @since 4.0.0 */ export const mergeEffect: { /** * Merges this stream with a background effect, keeping the stream's elements. * + * **When to use** + * + * Use when an effect should run concurrently for the lifetime of a stream while + * only the stream's elements remain in the output. + * + * **Details** + * * The effect runs concurrently, fails the stream if it fails, and is interrupted * when the stream completes. * - * @since 4.0.0 - * @category Merging - * @example + * **Example** (Merging with a background effect) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4044,17 +4272,26 @@ export const mergeEffect: { * // Output: side task * // Output: [ 1, 2, 3 ] * ``` + * + * @category merging + * @since 4.0.0 */ (effect: Effect.Effect): (self: Stream) => Stream /** * Merges this stream with a background effect, keeping the stream's elements. * + * **When to use** + * + * Use when an effect should run concurrently for the lifetime of a stream while + * only the stream's elements remain in the output. + * + * **Details** + * * The effect runs concurrently, fails the stream if it fails, and is interrupted * when the stream completes. * - * @since 4.0.0 - * @category Merging - * @example + * **Example** (Merging with a background effect) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4071,6 +4308,9 @@ export const mergeEffect: { * // Output: side task * // Output: [ 1, 2, 3 ] * ``` + * + * @category merging + * @since 4.0.0 */ (self: Stream, effect: Effect.Effect): Stream } = dual( @@ -4086,13 +4326,14 @@ export const mergeEffect: { * Merges this stream and the specified stream together, tagging values from the * left stream as `Result.succeed` and values from the right stream as `Result.fail`. * - * **Previously Known As** + * **When to use** * - * This API replaces the following from Effect 3.x: + * Use when values from both streams should be emitted and downstream code needs + * left values wrapped as successful `Result` values and right values wrapped as + * failed `Result` values. * - * - `Stream.mergeEither` + * **Example** (Merging streams into results) * - * @example * ```ts * import { Console, Effect, Result, Stream } from "effect" * @@ -4118,21 +4359,22 @@ export const mergeEffect: { * // Output: [ "left:left", "right:right" ] * ``` * - * @since 2.0.0 - * @category Merging + * @category merging + * @since 4.0.0 */ export const mergeResult: { /** * Merges this stream and the specified stream together, tagging values from the * left stream as `Result.succeed` and values from the right stream as `Result.fail`. * - * **Previously Known As** + * **When to use** * - * This API replaces the following from Effect 3.x: + * Use when values from both streams should be emitted and downstream code needs + * left values wrapped as successful `Result` values and right values wrapped as + * failed `Result` values. * - * - `Stream.mergeEither` + * **Example** (Merging streams into results) * - * @example * ```ts * import { Console, Effect, Result, Stream } from "effect" * @@ -4158,21 +4400,22 @@ export const mergeResult: { * // Output: [ "left:left", "right:right" ] * ``` * - * @since 2.0.0 - * @category Merging + * @category merging + * @since 4.0.0 */ (that: Stream): (self: Stream) => Stream, E2 | E, R2 | R> /** * Merges this stream and the specified stream together, tagging values from the * left stream as `Result.succeed` and values from the right stream as `Result.fail`. * - * **Previously Known As** + * **When to use** * - * This API replaces the following from Effect 3.x: + * Use when values from both streams should be emitted and downstream code needs + * left values wrapped as successful `Result` values and right values wrapped as + * failed `Result` values. * - * - `Stream.mergeEither` + * **Example** (Merging streams into results) * - * @example * ```ts * import { Console, Effect, Result, Stream } from "effect" * @@ -4198,8 +4441,8 @@ export const mergeResult: { * // Output: [ "left:left", "right:right" ] * ``` * - * @since 2.0.0 - * @category Merging + * @category merging + * @since 4.0.0 */ (self: Stream, that: Stream): Stream, E | E2, R | R2> } = dual( @@ -4217,11 +4460,19 @@ export const mergeResult: { /** * Merges two streams while emitting only the values from the left stream. * + * **When to use** + * + * Use when the right stream is needed for its effects or failures, but downstream + * consumers should only receive values from the left stream. + * + * **Details** + * * The right stream still runs for its effects, and any failures from the right * stream are propagated. The merged stream completes when the left stream * completes, interrupting the right stream. * - * @example + * **Example** (Merging streams while keeping left values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4236,18 +4487,26 @@ export const mergeResult: { * // Output: [ 1, 2 ] * ``` * + * @category merging * @since 2.0.0 - * @category Merging */ export const mergeLeft: { /** * Merges two streams while emitting only the values from the left stream. * + * **When to use** + * + * Use when the right stream is needed for its effects or failures, but downstream + * consumers should only receive values from the left stream. + * + * **Details** + * * The right stream still runs for its effects, and any failures from the right * stream are propagated. The merged stream completes when the left stream * completes, interrupting the right stream. * - * @example + * **Example** (Merging streams while keeping left values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4262,18 +4521,26 @@ export const mergeLeft: { * // Output: [ 1, 2 ] * ``` * + * @category merging * @since 2.0.0 - * @category Merging */ (right: Stream): (left: Stream) => Stream /** * Merges two streams while emitting only the values from the left stream. * + * **When to use** + * + * Use when the right stream is needed for its effects or failures, but downstream + * consumers should only receive values from the left stream. + * + * **Details** + * * The right stream still runs for its effects, and any failures from the right * stream are propagated. The merged stream completes when the left stream * completes, interrupting the right stream. * - * @example + * **Example** (Merging streams while keeping left values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4288,8 +4555,8 @@ export const mergeLeft: { * // Output: [ 1, 2 ] * ``` * + * @category merging * @since 2.0.0 - * @category Merging */ (left: Stream, right: Stream): Stream } = dual( @@ -4302,10 +4569,18 @@ export const mergeLeft: { * Merges this stream and the specified stream together, emitting only the * values from the right stream while the left stream runs for its effects. * + * **When to use** + * + * Use when the left stream is needed for its effects or failures, but downstream + * consumers should only receive values from the right stream. + * + * **Details** + * * The merged stream ends when the right stream completes, interrupting the * left stream. Failures from the left stream still fail the merged stream. * - * @example + * **Example** (Merging streams while keeping right values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4325,18 +4600,26 @@ export const mergeLeft: { * // Output: [ 1, 2 ] * ``` * + * @category merging * @since 2.0.0 - * @category Merging */ export const mergeRight: { /** * Merges this stream and the specified stream together, emitting only the * values from the right stream while the left stream runs for its effects. * + * **When to use** + * + * Use when the left stream is needed for its effects or failures, but downstream + * consumers should only receive values from the right stream. + * + * **Details** + * * The merged stream ends when the right stream completes, interrupting the * left stream. Failures from the left stream still fail the merged stream. * - * @example + * **Example** (Merging streams while keeping right values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4356,18 +4639,26 @@ export const mergeRight: { * // Output: [ 1, 2 ] * ``` * + * @category merging * @since 2.0.0 - * @category Merging */ (right: Stream): (left: Stream) => Stream /** * Merges this stream and the specified stream together, emitting only the * values from the right stream while the left stream runs for its effects. * + * **When to use** + * + * Use when the left stream is needed for its effects or failures, but downstream + * consumers should only receive values from the right stream. + * + * **Details** + * * The merged stream ends when the right stream completes, interrupting the * left stream. Failures from the left stream still fail the merged stream. * - * @example + * **Example** (Merging streams while keeping right values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4387,8 +4678,8 @@ export const mergeRight: { * // Output: [ 1, 2 ] * ``` * + * @category merging * @since 2.0.0 - * @category Merging */ (left: Stream, right: Stream): Stream } = dual( @@ -4400,10 +4691,19 @@ export const mergeRight: { /** * Merges a collection of streams, running up to the specified number concurrently. * - * @since 2.0.0 - * @category Merging + * **When to use** + * + * Use to merge an iterable of already-created streams while bounding how many + * inner streams may run at the same time. + * + * **Details** + * + * The `concurrency` option is required and may be a number or `"unbounded"`. + * `bufferSize` controls buffering between inner streams, and outputs are + * emitted as they arrive under concurrent merging. + * + * **Example** (Merging streams with bounded concurrency) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4422,15 +4722,30 @@ export const mergeRight: { * Effect.runPromise(program) * // Output: [ "B", "A" ] * ``` + * + * @see {@link merge} for merging exactly two streams and choosing a halt strategy + * @see {@link flatten} for flattening a stream that already emits streams + * + * @category merging + * @since 2.0.0 */ export const mergeAll: { /** * Merges a collection of streams, running up to the specified number concurrently. * - * @since 2.0.0 - * @category Merging + * **When to use** + * + * Use to merge an iterable of already-created streams while bounding how many + * inner streams may run at the same time. + * + * **Details** + * + * The `concurrency` option is required and may be a number or `"unbounded"`. + * `bufferSize` controls buffering between inner streams, and outputs are + * emitted as they arrive under concurrent merging. + * + * **Example** (Merging streams with bounded concurrency) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4449,6 +4764,12 @@ export const mergeAll: { * Effect.runPromise(program) * // Output: [ "B", "A" ] * ``` + * + * @see {@link merge} for merging exactly two streams and choosing a halt strategy + * @see {@link flatten} for flattening a stream that already emits streams + * + * @category merging + * @since 2.0.0 */ ( options: { @@ -4459,10 +4780,19 @@ export const mergeAll: { /** * Merges a collection of streams, running up to the specified number concurrently. * - * @since 2.0.0 - * @category Merging + * **When to use** + * + * Use to merge an iterable of already-created streams while bounding how many + * inner streams may run at the same time. + * + * **Details** + * + * The `concurrency` option is required and may be a number or `"unbounded"`. + * `bufferSize` controls buffering between inner streams, and outputs are + * emitted as they arrive under concurrent merging. + * + * **Example** (Merging streams with bounded concurrency) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4481,6 +4811,12 @@ export const mergeAll: { * Effect.runPromise(program) * // Output: [ "B", "A" ] * ``` + * + * @see {@link merge} for merging exactly two streams and choosing a halt strategy + * @see {@link flatten} for flattening a stream that already emits streams + * + * @category merging + * @since 2.0.0 */ ( streams: Iterable>, @@ -4501,9 +4837,12 @@ export const mergeAll: { * Creates the cartesian product of two streams, running the `right` stream for * each element in the `left` stream. * + * **Details** + * * See also `Stream.zip` for the more common point-wise variant. * - * @example + * **Example** (Computing cartesian products) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4518,17 +4857,20 @@ export const mergeAll: { * // Output: [ [ 1, "a" ], [ 1, "b" ], [ 2, "a" ], [ 2, "b" ] ] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ export const cross: { /** * Creates the cartesian product of two streams, running the `right` stream for * each element in the `left` stream. * + * **Details** + * * See also `Stream.zip` for the more common point-wise variant. * - * @example + * **Example** (Computing cartesian products) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4543,17 +4885,20 @@ export const cross: { * // Output: [ [ 1, "a" ], [ 1, "b" ], [ 2, "a" ], [ 2, "b" ] ] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ (right: Stream): (left: Stream) => Stream<[AL, AR], EL | ER, RL | RR> /** * Creates the cartesian product of two streams, running the `right` stream for * each element in the `left` stream. * + * **Details** + * * See also `Stream.zip` for the more common point-wise variant. * - * @example + * **Example** (Computing cartesian products) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4568,8 +4913,8 @@ export const cross: { * // Output: [ [ 1, "a" ], [ 1, "b" ], [ 2, "a" ], [ 2, "b" ] ] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ (left: Stream, right: Stream): Stream<[AL, AR], EL | ER, RL | RR> } = dual(2, ( @@ -4580,11 +4925,14 @@ export const cross: { /** * Creates a cartesian product of elements from two streams using a function. * + * **Details** + * * The `right` stream is rerun for every element in the `left` stream. * * See also `Stream.zipWith` for the more common point-wise variant. * - * @example + * **Example** (Combining cartesian products) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4600,18 +4948,21 @@ export const cross: { * // Output: [ "1-a", "1-b", "2-a", "2-b" ] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ export const crossWith: { /** * Creates a cartesian product of elements from two streams using a function. * + * **Details** + * * The `right` stream is rerun for every element in the `left` stream. * * See also `Stream.zipWith` for the more common point-wise variant. * - * @example + * **Example** (Combining cartesian products) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4627,18 +4978,21 @@ export const crossWith: { * // Output: [ "1-a", "1-b", "2-a", "2-b" ] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ (right: Stream, f: (left: AL, right: AR) => A): (left: Stream) => Stream /** * Creates a cartesian product of elements from two streams using a function. * + * **Details** + * * The `right` stream is rerun for every element in the `left` stream. * * See also `Stream.zipWith` for the more common point-wise variant. * - * @example + * **Example** (Combining cartesian products) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4654,8 +5008,8 @@ export const crossWith: { * // Output: [ "1-a", "1-b", "2-a", "2-b" ] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ ( left: Stream, @@ -4671,7 +5025,8 @@ export const crossWith: { /** * Zips two streams point-wise with a combining function, ending when either stream ends. * - * @example + * **Example** (Zipping streams with a function) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4689,14 +5044,15 @@ export const crossWith: { * // Output: [ "1-a", "2-b", "3-c" ] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ export const zipWith: { /** * Zips two streams point-wise with a combining function, ending when either stream ends. * - * @example + * **Example** (Zipping streams with a function) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4714,14 +5070,15 @@ export const zipWith: { * // Output: [ "1-a", "2-b", "3-c" ] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ (right: Stream, f: (left: AL, right: AR) => A): (left: Stream) => Stream /** * Zips two streams point-wise with a combining function, ending when either stream ends. * - * @example + * **Example** (Zipping streams with a function) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4739,8 +5096,8 @@ export const zipWith: { * // Output: [ "1-a", "2-b", "3-c" ] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ ( left: Stream, @@ -4773,15 +5130,12 @@ const zipArrays = ( /** * Zips two streams by applying a function to non-empty arrays of elements. * - * The function returns output plus leftover arrays that carry into the next pull. - * - * **Previously Known As** + * **Details** * - * This API replaces the following from Effect 3.x: + * The function returns output plus leftover arrays that carry into the next pull. * - * - `Stream.zipWithChunks` + * **Example** (Zipping stream chunks) * - * @example * ```ts * import { Array, Console, Effect, Stream } from "effect" * @@ -4804,22 +5158,19 @@ const zipArrays = ( * // Output: [[1, "a"], [2, "b"], [3, "c"], [4, "d"], [5, "e"]] * ``` * - * @since 2.0.0 - * @category Zipping + * @category zipping + * @since 4.0.0 */ export const zipWithArray: { /** * Zips two streams by applying a function to non-empty arrays of elements. * - * The function returns output plus leftover arrays that carry into the next pull. - * - * **Previously Known As** + * **Details** * - * This API replaces the following from Effect 3.x: + * The function returns output plus leftover arrays that carry into the next pull. * - * - `Stream.zipWithChunks` + * **Example** (Zipping stream chunks) * - * @example * ```ts * import { Array, Console, Effect, Stream } from "effect" * @@ -4842,8 +5193,8 @@ export const zipWithArray: { * // Output: [[1, "a"], [2, "b"], [3, "c"], [4, "d"], [5, "e"]] * ``` * - * @since 2.0.0 - * @category Zipping + * @category zipping + * @since 4.0.0 */ ( right: Stream, @@ -4859,15 +5210,12 @@ export const zipWithArray: { /** * Zips two streams by applying a function to non-empty arrays of elements. * - * The function returns output plus leftover arrays that carry into the next pull. - * - * **Previously Known As** + * **Details** * - * This API replaces the following from Effect 3.x: + * The function returns output plus leftover arrays that carry into the next pull. * - * - `Stream.zipWithChunks` + * **Example** (Zipping stream chunks) * - * @example * ```ts * import { Array, Console, Effect, Stream } from "effect" * @@ -4890,8 +5238,8 @@ export const zipWithArray: { * // Output: [[1, "a"], [2, "b"], [3, "c"], [4, "d"], [5, "e"]] * ``` * - * @since 2.0.0 - * @category Zipping + * @category zipping + * @since 4.0.0 */ ( left: Stream, @@ -4963,7 +5311,8 @@ export const zipWithArray: { * Zips this stream with another point-wise and emits tuples of elements from * both streams. The new stream ends when either stream ends. * - * @example + * **Example** (Zipping streams) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -4981,15 +5330,16 @@ export const zipWithArray: { * // Output: [[1, "a"], [2, "b"], [3, "c"]] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ export const zip: { /** * Zips this stream with another point-wise and emits tuples of elements from * both streams. The new stream ends when either stream ends. * - * @example + * **Example** (Zipping streams) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5007,15 +5357,16 @@ export const zip: { * // Output: [[1, "a"], [2, "b"], [3, "c"]] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ (that: Stream): (self: Stream) => Stream<[A, A2], E2 | E, R2 | R> /** * Zips this stream with another point-wise and emits tuples of elements from * both streams. The new stream ends when either stream ends. * - * @example + * **Example** (Zipping streams) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5033,8 +5384,8 @@ export const zip: { * // Output: [[1, "a"], [2, "b"], [3, "c"]] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ (self: Stream, that: Stream): Stream<[A, A2], E | E2, R | R2> } = dual( @@ -5049,9 +5400,12 @@ export const zip: { * Zips this stream with another point-wise and keeps only the values from * the left stream. * + * **Details** + * * The resulting stream ends when either side ends. * - * @example + * **Example** (Zipping streams while keeping left values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5067,17 +5421,20 @@ export const zip: { * // Output: [1, 2] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ export const zipLeft: { /** * Zips this stream with another point-wise and keeps only the values from * the left stream. * + * **Details** + * * The resulting stream ends when either side ends. * - * @example + * **Example** (Zipping streams while keeping left values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5093,17 +5450,20 @@ export const zipLeft: { * // Output: [1, 2] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ (right: Stream): (left: Stream) => Stream /** * Zips this stream with another point-wise and keeps only the values from * the left stream. * + * **Details** + * * The resulting stream ends when either side ends. * - * @example + * **Example** (Zipping streams while keeping left values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5119,8 +5479,8 @@ export const zipLeft: { * // Output: [1, 2] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ (left: Stream, right: Stream): Stream } = dual( @@ -5142,7 +5502,8 @@ export const zipLeft: { /** * Zips this stream with another point-wise, keeping only right values and ending when either stream ends. * - * @example + * **Example** (Zipping streams while keeping right values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5158,14 +5519,15 @@ export const zipLeft: { * // Output: ["a", "b"] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ export const zipRight: { /** * Zips this stream with another point-wise, keeping only right values and ending when either stream ends. * - * @example + * **Example** (Zipping streams while keeping right values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5181,14 +5543,15 @@ export const zipRight: { * // Output: ["a", "b"] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ (right: Stream): (left: Stream) => Stream /** * Zips this stream with another point-wise, keeping only right values and ending when either stream ends. * - * @example + * **Example** (Zipping streams while keeping right values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5204,8 +5567,8 @@ export const zipRight: { * // Output: ["a", "b"] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ (left: Stream, right: Stream): Stream } = dual( @@ -5228,9 +5591,12 @@ export const zipRight: { * Zips this stream with another point-wise and emits tuples of elements from * both streams, flattening the left tuple. * + * **Details** + * * The new stream will end when one of the sides ends. * - * @example + * **Example** (Zipping and flattening tuples) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5250,17 +5616,20 @@ export const zipRight: { * // Output: [[1, "a", "x"], [2, "b", "y"], [3, "c", "z"]] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ export const zipFlatten: { /** * Zips this stream with another point-wise and emits tuples of elements from * both streams, flattening the left tuple. * + * **Details** + * * The new stream will end when one of the sides ends. * - * @example + * **Example** (Zipping and flattening tuples) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5280,17 +5649,20 @@ export const zipFlatten: { * // Output: [[1, "a", "x"], [2, "b", "y"], [3, "c", "z"]] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ (that: Stream): , E, R>(self: Stream) => Stream<[...A, A2], E2 | E, R2 | R> /** * Zips this stream with another point-wise and emits tuples of elements from * both streams, flattening the left tuple. * + * **Details** + * * The new stream will end when one of the sides ends. * - * @example + * **Example** (Zipping and flattening tuples) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5310,8 +5682,8 @@ export const zipFlatten: { * // Output: [[1, "a", "x"], [2, "b", "y"], [3, "c", "z"]] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ , E, R, A2, E2, R2>(self: Stream, that: Stream): Stream<[...A, A2], E | E2, R | R2> } = dual( @@ -5325,7 +5697,8 @@ export const zipFlatten: { /** * Zips this stream together with the index of elements. * - * @example + * **Example** (Zipping elements with indices) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5341,8 +5714,8 @@ export const zipFlatten: { * // Output: [["a", 0], ["b", 1], ["c", 2], ["d", 3]] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ export const zipWithIndex = (self: Stream): Stream<[A, number], E, R> => map(self, (a, i) => [a, i]) @@ -5350,7 +5723,8 @@ export const zipWithIndex = (self: Stream): Stream<[A, number] * Zips each element with the next element, pairing the final element with * `Option.none()`. * - * @example + * **Example** (Zipping elements with next values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5368,8 +5742,8 @@ export const zipWithIndex = (self: Stream): Stream<[A, number] * // ] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ export const zipWithNext = (self: Stream): Stream<[A, Option.Option], E, R> => mapAccumArray(self, Option.none, (acc, arr) => { @@ -5394,7 +5768,8 @@ export const zipWithNext = (self: Stream): Stream<[A, Option.O /** * Zips each element with its previous element, starting with `None`. * - * @example + * **Example** (Zipping elements with previous values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5414,8 +5789,8 @@ export const zipWithNext = (self: Stream): Stream<[A, Option.O * // ] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ export const zipWithPrevious = (self: Stream): Stream<[Option.Option, A], E, R> => mapAccumArray(self, Option.none, (acc, arr) => { @@ -5431,7 +5806,8 @@ export const zipWithPrevious = (self: Stream): Stream<[Option. /** * Zips each element with its previous and next values. * - * @example + * **Example** (Zipping elements with neighbors) + * * ```ts * import { Console, Effect, Option, Stream } from "effect" * @@ -5447,8 +5823,8 @@ export const zipWithPrevious = (self: Stream): Stream<[Option. * // Output: [ [Option.none(), 1, Option.some(2)], [Option.some(1), 2, Option.some(3)], [Option.some(2), 3, Option.none()] ] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ export const zipWithPreviousAndNext = ( self: Stream @@ -5485,11 +5861,19 @@ export const zipWithPreviousAndNext = ( * Zips multiple streams so that when a value is emitted by any stream, it is * combined with the latest values from the other streams to produce a result. * + * **When to use** + * + * Use when each stream should contribute its latest value after all streams have + * emitted at least once. + * + * **Gotchas** + * * Note: tracking the latest value is done on a per-array basis. That means * that emitted elements that are not the last value in arrays will never be * used for zipping. * - * @example + * **Example** (Zipping latest values from many streams) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5508,8 +5892,8 @@ export const zipWithPreviousAndNext = ( * // Output: [ [ 1, "a", true ], [ 2, "a", true ], [ 3, "a", true ], [ 3, "b", true ], [ 3, "c", true ], [ 3, "c", false ], [ 3, "c", true ] ] * ``` * - * @since 2.0.0 - * @category Zipping + * @category zipping + * @since 3.3.0 */ export const zipLatestAll = >>( ...streams: T @@ -5553,11 +5937,19 @@ export const zipLatestAll = >>( /** * Combines two streams by emitting each new element with the latest value from the other stream. * + * **When to use** + * + * Use when two streams should start emitting combined pairs after both have + * produced at least one value. + * + * **Gotchas** + * * Note: tracking the latest value is done on a per-array basis. That means * that emitted elements that are not the last value in arrays will never be * used for zipping. * - * @example + * **Example** (Zipping latest values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5572,18 +5964,26 @@ export const zipLatestAll = >>( * // Output: [ [1, "a"] ] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ export const zipLatest: { /** * Combines two streams by emitting each new element with the latest value from the other stream. * + * **When to use** + * + * Use when two streams should start emitting combined pairs after both have + * produced at least one value. + * + * **Gotchas** + * * Note: tracking the latest value is done on a per-array basis. That means * that emitted elements that are not the last value in arrays will never be * used for zipping. * - * @example + * **Example** (Zipping latest values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5598,18 +5998,26 @@ export const zipLatest: { * // Output: [ [1, "a"] ] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ (right: Stream): (left: Stream) => Stream<[AL, AR], EL | ER, RL | RR> /** * Combines two streams by emitting each new element with the latest value from the other stream. * + * **When to use** + * + * Use when two streams should start emitting combined pairs after both have + * produced at least one value. + * + * **Gotchas** + * * Note: tracking the latest value is done on a per-array basis. That means * that emitted elements that are not the last value in arrays will never be * used for zipping. * - * @example + * **Example** (Zipping latest values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5624,8 +6032,8 @@ export const zipLatest: { * // Output: [ [1, "a"] ] * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ (left: Stream, right: Stream): Stream<[AL, AR], EL | ER, RL | RR> } = dual( @@ -5640,11 +6048,19 @@ export const zipLatest: { * Combines the latest values from both streams whenever either emits, using * the provided function. * + * **When to use** + * + * Use when two streams should start emitting custom combined values after both + * have produced at least one value. + * + * **Gotchas** + * * Note: tracking the latest value is done on a per-array basis. That means * that emitted elements that are not the last value in arrays will never be * used for zipping. * - * @example + * **Example** (Zipping latest values with a function) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5663,19 +6079,27 @@ export const zipLatest: { * }) * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ export const zipLatestWith: { /** * Combines the latest values from both streams whenever either emits, using * the provided function. * + * **When to use** + * + * Use when two streams should start emitting custom combined values after both + * have produced at least one value. + * + * **Gotchas** + * * Note: tracking the latest value is done on a per-array basis. That means * that emitted elements that are not the last value in arrays will never be * used for zipping. * - * @example + * **Example** (Zipping latest values with a function) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5694,19 +6118,27 @@ export const zipLatestWith: { * }) * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ (right: Stream, f: (left: AL, right: AR) => A): (left: Stream) => Stream /** * Combines the latest values from both streams whenever either emits, using * the provided function. * + * **When to use** + * + * Use when two streams should start emitting custom combined values after both + * have produced at least one value. + * + * **Gotchas** + * * Note: tracking the latest value is done on a per-array basis. That means * that emitted elements that are not the last value in arrays will never be * used for zipping. * - * @example + * **Example** (Zipping latest values with a function) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5725,8 +6157,8 @@ export const zipLatestWith: { * }) * ``` * + * @category zipping * @since 2.0.0 - * @category Zipping */ ( left: Stream, @@ -5743,12 +6175,17 @@ export const zipLatestWith: { ) /** - * Races multiple streams and emits values from the first stream to produce a value, interrupting the rest. + * Runs all streams concurrently until one stream emits its first value, then + * mirrors that winning stream and interrupts the rest. * - * @since 3.7.0 - * @category Racing + * **Details** + * + * Failures or completion from losing streams before a winner is chosen are + * ignored unless every stream fails or completes before emitting. After a + * winner is chosen, that stream's later failures are propagated. + * + * **Example** (Racing multiple streams) * - * @example * ```ts * import { Console, Effect, Schedule, Stream } from "effect" * @@ -5763,6 +6200,9 @@ export const zipLatestWith: { * Effect.runPromise(program) * // Output: [ 0, 1, 2 ] * ``` + * + * @category racing + * @since 3.5.0 */ export const raceAll = >>( ...streams: S @@ -5794,10 +6234,17 @@ export const raceAll = >>( )) /** - * Returns a stream that mirrors the first upstream to emit an item. - * As soon as one stream emits, the other is interrupted and failures propagate. + * Runs both streams concurrently until one stream emits its first value, then + * mirrors that winning stream and interrupts the other. + * + * **Details** + * + * A failure or completion from one side before the other side emits does not + * win the race unless both sides fail or complete before emitting. After a + * winner is chosen, that stream's later failures are propagated. + * + * **Example** (Racing two streams) * - * @example * ```ts * import { Console, Effect, Schedule, Stream } from "effect" * @@ -5815,15 +6262,22 @@ export const raceAll = >>( * // Output: [ 0, 1, 2 ] * ``` * + * @category racing * @since 3.7.0 - * @category Racing */ export const race: { /** - * Returns a stream that mirrors the first upstream to emit an item. - * As soon as one stream emits, the other is interrupted and failures propagate. + * Runs both streams concurrently until one stream emits its first value, then + * mirrors that winning stream and interrupts the other. + * + * **Details** + * + * A failure or completion from one side before the other side emits does not + * win the race unless both sides fail or complete before emitting. After a + * winner is chosen, that stream's later failures are propagated. + * + * **Example** (Racing two streams) * - * @example * ```ts * import { Console, Effect, Schedule, Stream } from "effect" * @@ -5841,15 +6295,22 @@ export const race: { * // Output: [ 0, 1, 2 ] * ``` * + * @category racing * @since 3.7.0 - * @category Racing */ (right: Stream): (left: Stream) => Stream /** - * Returns a stream that mirrors the first upstream to emit an item. - * As soon as one stream emits, the other is interrupted and failures propagate. + * Runs both streams concurrently until one stream emits its first value, then + * mirrors that winning stream and interrupts the other. + * + * **Details** + * + * A failure or completion from one side before the other side emits does not + * win the race unless both sides fail or complete before emitting. After a + * winner is chosen, that stream's later failures are propagated. + * + * **Example** (Racing two streams) * - * @example * ```ts * import { Console, Effect, Schedule, Stream } from "effect" * @@ -5867,8 +6328,8 @@ export const race: { * // Output: [ 0, 1, 2 ] * ``` * + * @category racing * @since 3.7.0 - * @category Racing */ (left: Stream, right: Stream): Stream } = dual(2, ( @@ -5879,7 +6340,8 @@ export const race: { /** * Filters a stream to the elements that satisfy a predicate. * - * @example + * **Example** (Filtering stream values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5895,14 +6357,15 @@ export const race: { * // Output: [ 2, 4 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ export const filter: { /** * Filters a stream to the elements that satisfy a predicate. * - * @example + * **Example** (Filtering stream values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5918,14 +6381,15 @@ export const filter: { * // Output: [ 2, 4 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (refinement: Refinement, B>): (self: Stream) => Stream /** * Filters a stream to the elements that satisfy a predicate. * - * @example + * **Example** (Filtering stream values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5941,14 +6405,15 @@ export const filter: { * // Output: [ 2, 4 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (predicate: Predicate>): (self: Stream) => Stream /** * Filters a stream to the elements that satisfy a predicate. * - * @example + * **Example** (Filtering stream values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5964,14 +6429,15 @@ export const filter: { * // Output: [ 2, 4 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (self: Stream, refinement: Refinement): Stream /** * Filters a stream to the elements that satisfy a predicate. * - * @example + * **Example** (Filtering stream values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -5987,8 +6453,8 @@ export const filter: { * // Output: [ 2, 4 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (self: Stream, predicate: Predicate): Stream } = dual( @@ -6002,22 +6468,61 @@ export const filter: { /** * Filters and maps stream elements in one pass using a `Filter`. * - * @since 4.0.0 - * @category Filtering + * **When to use** + * + * Use to keep only stream elements accepted by a `Filter` and emit each filter + * success value. + * + * **Details** + * + * `Result.succeed` values are emitted and `Result.fail` values are skipped. + * + * @see {@link filter} for keeping original elements with a boolean predicate or refinement + * @see {@link filterMapEffect} for an effectful `Filter` + * @see {@link partition} for consuming both filter success and failure values + * + * @category filtering + * @since 2.0.0 */ export const filterMap: { /** * Filters and maps stream elements in one pass using a `Filter`. * - * @since 4.0.0 - * @category Filtering + * **When to use** + * + * Use to keep only stream elements accepted by a `Filter` and emit each filter + * success value. + * + * **Details** + * + * `Result.succeed` values are emitted and `Result.fail` values are skipped. + * + * @see {@link filter} for keeping original elements with a boolean predicate or refinement + * @see {@link filterMapEffect} for an effectful `Filter` + * @see {@link partition} for consuming both filter success and failure values + * + * @category filtering + * @since 2.0.0 */ (filter: Filter.Filter, B, X>): (self: Stream) => Stream /** * Filters and maps stream elements in one pass using a `Filter`. * - * @since 4.0.0 - * @category Filtering + * **When to use** + * + * Use to keep only stream elements accepted by a `Filter` and emit each filter + * success value. + * + * **Details** + * + * `Result.succeed` values are emitted and `Result.fail` values are skipped. + * + * @see {@link filter} for keeping original elements with a boolean predicate or refinement + * @see {@link filterMapEffect} for an effectful `Filter` + * @see {@link partition} for consuming both filter success and failure values + * + * @category filtering + * @since 2.0.0 */ (self: Stream, filter: Filter.Filter): Stream } = dual( @@ -6029,9 +6534,10 @@ export const filterMap: { ) /** - * Effectfully filters elements in a single pass. + * Filters elements in a single pass effectfully. + * + * **Example** (Effectfully filtering stream values) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -6046,14 +6552,15 @@ export const filterMap: { * // Output: [ 3, 4 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ export const filterEffect: { /** - * Effectfully filters elements in a single pass. + * Filters elements in a single pass effectfully. + * + * **Example** (Effectfully filtering stream values) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -6068,14 +6575,15 @@ export const filterEffect: { * // Output: [ 3, 4 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (predicate: (a: NoInfer, i: number) => Effect.Effect): (self: Stream) => Stream /** - * Effectfully filters elements in a single pass. + * Filters elements in a single pass effectfully. + * + * **Example** (Effectfully filtering stream values) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -6090,8 +6598,8 @@ export const filterEffect: { * // Output: [ 3, 4 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ ( self: Stream, @@ -6106,24 +6614,66 @@ export const filterEffect: { ) /** - * Effectfully filters and maps elements in a single pass. + * Filters and maps elements in one pass effectfully using a `FilterEffect`. * - * @since 4.0.0 - * @category Filtering + * **When to use** + * + * Use to apply effectful logic that can reject stream elements or emit + * transformed values before they continue downstream. + * + * **Details** + * + * `Result.succeed` values are emitted, `Result.fail` values are skipped, and + * effect failures fail the stream. + * + * @see {@link filterMap} for the synchronous `Filter` variant + * @see {@link filterEffect} for effectfully keeping original elements + * @see {@link mapEffect} for effectfully transforming every element + * + * @category filtering + * @since 2.0.0 */ export const filterMapEffect: { /** - * Effectfully filters and maps elements in a single pass. + * Filters and maps elements in one pass effectfully using a `FilterEffect`. * - * @since 4.0.0 - * @category Filtering + * **When to use** + * + * Use to apply effectful logic that can reject stream elements or emit + * transformed values before they continue downstream. + * + * **Details** + * + * `Result.succeed` values are emitted, `Result.fail` values are skipped, and + * effect failures fail the stream. + * + * @see {@link filterMap} for the synchronous `Filter` variant + * @see {@link filterEffect} for effectfully keeping original elements + * @see {@link mapEffect} for effectfully transforming every element + * + * @category filtering + * @since 2.0.0 */ (filter: Filter.FilterEffect, B, X, EX, RX>): (self: Stream) => Stream /** - * Effectfully filters and maps elements in a single pass. + * Filters and maps elements in one pass effectfully using a `FilterEffect`. * - * @since 4.0.0 - * @category Filtering + * **When to use** + * + * Use to apply effectful logic that can reject stream elements or emit + * transformed values before they continue downstream. + * + * **Details** + * + * `Result.succeed` values are emitted, `Result.fail` values are skipped, and + * effect failures fail the stream. + * + * @see {@link filterMap} for the synchronous `Filter` variant + * @see {@link filterEffect} for effectfully keeping original elements + * @see {@link mapEffect} for effectfully transforming every element + * + * @category filtering + * @since 2.0.0 */ (self: Stream, filter: Filter.FilterEffect): Stream } = dual( @@ -6135,11 +6685,17 @@ export const filterMapEffect: { ) /** - * Partitions a stream using a `Filter` and exposes passing and failing values as queues. + * Partitions a stream using a `Filter` and exposes passing and failing values + * as scoped queues. + * + * **Details** * - * Each queue fails with the stream error or `Cause.Done` when the source ends. + * The queues are backed by a fiber in the current scope and should be consumed + * while that scope remains open. Each queue fails with the stream error or + * `Cause.Done` when the source ends. + * + * **Example** (Partitioning a stream into queues) * - * @example * ```ts * import { Console, Effect, Result, Stream } from "effect" * @@ -6160,16 +6716,22 @@ export const filterMapEffect: { * Effect.runPromise(Effect.scoped(program)) * ``` * + * @category filtering * @since 4.0.0 - * @category Filtering */ export const partitionQueue: { /** - * Partitions a stream using a `Filter` and exposes passing and failing values as queues. + * Partitions a stream using a `Filter` and exposes passing and failing values + * as scoped queues. + * + * **Details** * - * Each queue fails with the stream error or `Cause.Done` when the source ends. + * The queues are backed by a fiber in the current scope and should be consumed + * while that scope remains open. Each queue fails with the stream error or + * `Cause.Done` when the source ends. + * + * **Example** (Partitioning a stream into queues) * - * @example * ```ts * import { Console, Effect, Result, Stream } from "effect" * @@ -6190,8 +6752,8 @@ export const partitionQueue: { * Effect.runPromise(Effect.scoped(program)) * ``` * + * @category filtering * @since 4.0.0 - * @category Filtering */ ( filter: Filter.Filter, Pass, Fail>, @@ -6207,11 +6769,17 @@ export const partitionQueue: { R | Scope.Scope > /** - * Partitions a stream using a `Filter` and exposes passing and failing values as queues. + * Partitions a stream using a `Filter` and exposes passing and failing values + * as scoped queues. + * + * **Details** * - * Each queue fails with the stream error or `Cause.Done` when the source ends. + * The queues are backed by a fiber in the current scope and should be consumed + * while that scope remains open. Each queue fails with the stream error or + * `Cause.Done` when the source ends. + * + * **Example** (Partitioning a stream into queues) * - * @example * ```ts * import { Console, Effect, Result, Stream } from "effect" * @@ -6232,8 +6800,8 @@ export const partitionQueue: { * Effect.runPromise(Effect.scoped(program)) * ``` * + * @category filtering * @since 4.0.0 - * @category Filtering */ ( self: Stream, @@ -6270,12 +6838,18 @@ export const partitionQueue: { const pull = yield* Channel.toPullScoped(self.channel, scope) const capacity = options?.capacity === "unbounded" ? undefined : options?.capacity ?? DefaultChunkSize const passes = yield* Queue.make({ capacity }) const fails = yield* Queue.make({ capacity }) @@ -6431,17 +7023,49 @@ export const partitionQueue: { ) /** - * Splits a stream using an effectful `Filter`, producing pass and fail streams. + * Splits a stream with an effectful `Filter`, returning scoped streams for + * filter successes and failures. + * + * **When to use** + * + * Use when you need to classify each stream element with an effectful `Filter` + * and consume both passing and failing mapped values as streams. + * + * **Details** * + * The returned streams are backed by queues in the current scope and should be + * consumed while that scope remains open. The first stream emits success values + * from the filter, and the second emits failure values. + * + * @see {@link partition} for the pure `Filter` variant, which returns the failing stream before the passing stream + * @see {@link partitionQueue} for the lower-level queue result + * @see {@link filterMapEffect} for effectful filtering that discards failed filter results + * + * @category filtering * @since 4.0.0 - * @category Filtering */ export const partitionEffect: { /** - * Splits a stream using an effectful `Filter`, producing pass and fail streams. + * Splits a stream with an effectful `Filter`, returning scoped streams for + * filter successes and failures. + * + * **When to use** + * + * Use when you need to classify each stream element with an effectful `Filter` + * and consume both passing and failing mapped values as streams. * + * **Details** + * + * The returned streams are backed by queues in the current scope and should be + * consumed while that scope remains open. The first stream emits success values + * from the filter, and the second emits failure values. + * + * @see {@link partition} for the pure `Filter` variant, which returns the failing stream before the passing stream + * @see {@link partitionQueue} for the lower-level queue result + * @see {@link filterMapEffect} for effectful filtering that discards failed filter results + * + * @category filtering * @since 4.0.0 - * @category Filtering */ ( filter: Filter.FilterEffect, Pass, Fail, EX, RX>, @@ -6458,10 +7082,26 @@ export const partitionEffect: { R | RX | Scope.Scope > /** - * Splits a stream using an effectful `Filter`, producing pass and fail streams. + * Splits a stream with an effectful `Filter`, returning scoped streams for + * filter successes and failures. + * + * **When to use** + * + * Use when you need to classify each stream element with an effectful `Filter` + * and consume both passing and failing mapped values as streams. + * + * **Details** + * + * The returned streams are backed by queues in the current scope and should be + * consumed while that scope remains open. The first stream emits success values + * from the filter, and the second emits failure values. + * + * @see {@link partition} for the pure `Filter` variant, which returns the failing stream before the passing stream + * @see {@link partitionQueue} for the lower-level queue result + * @see {@link filterMapEffect} for effectful filtering that discards failed filter results * + * @category filtering * @since 4.0.0 - * @category Filtering */ ( self: Stream, @@ -6497,34 +7137,114 @@ export const partitionEffect: { > => Effect.map( partitionQueue, /** - * Splits a stream using an effectful `Filter`, producing pass and fail streams. + * Splits a stream with an effectful `Filter`, returning scoped streams for + * filter successes and failures. + * + * **When to use** + * + * Use when you need to classify each stream element with an effectful `Filter` + * and consume both passing and failing mapped values as streams. + * + * **Details** * + * The returned streams are backed by queues in the current scope and should be + * consumed while that scope remains open. The first stream emits success values + * from the filter, and the second emits failure values. + * + * @see {@link partition} for the pure `Filter` variant, which returns the failing stream before the passing stream + * @see {@link partitionQueue} for the lower-level queue result + * @see {@link filterMapEffect} for effectful filtering that discards failed filter results + * + * @category filtering * @since 4.0.0 - * @category Filtering */ E | EX, /** - * Splits a stream using an effectful `Filter`, producing pass and fail streams. + * Splits a stream with an effectful `Filter`, returning scoped streams for + * filter successes and failures. + * + * **When to use** + * + * Use when you need to classify each stream element with an effectful `Filter` + * and consume both passing and failing mapped values as streams. * + * **Details** + * + * The returned streams are backed by queues in the current scope and should be + * consumed while that scope remains open. The first stream emits success values + * from the filter, and the second emits failure values. + * + * @see {@link partition} for the pure `Filter` variant, which returns the failing stream before the passing stream + * @see {@link partitionQueue} for the lower-level queue result + * @see {@link filterMapEffect} for effectful filtering that discards failed filter results + * + * @category filtering * @since 4.0.0 - * @category Filtering */ R | RX, /** - * Splits a stream using an effectful `Filter`, producing pass and fail streams. + * Splits a stream with an effectful `Filter`, returning scoped streams for + * filter successes and failures. + * + * **When to use** * + * Use when you need to classify each stream element with an effectful `Filter` + * and consume both passing and failing mapped values as streams. + * + * **Details** + * + * The returned streams are backed by queues in the current scope and should be + * consumed while that scope remains open. The first stream emits success values + * from the filter, and the second emits failure values. + * + * @see {@link partition} for the pure `Filter` variant, which returns the failing stream before the passing stream + * @see {@link partitionQueue} for the lower-level queue result + * @see {@link filterMapEffect} for effectful filtering that discards failed filter results + * + * @category filtering * @since 4.0.0 - * @category Filtering */ Pass, /** - * Splits a stream using an effectful `Filter`, producing pass and fail streams. + * Splits a stream with an effectful `Filter`, returning scoped streams for + * filter successes and failures. + * + * **When to use** + * + * Use when you need to classify each stream element with an effectful `Filter` + * and consume both passing and failing mapped values as streams. + * + * **Details** + * + * The returned streams are backed by queues in the current scope and should be + * consumed while that scope remains open. The first stream emits success values + * from the filter, and the second emits failure values. * + * @see {@link partition} for the pure `Filter` variant, which returns the failing stream before the passing stream + * @see {@link partitionQueue} for the lower-level queue result + * @see {@link filterMapEffect} for effectful filtering that discards failed filter results + * + * @category filtering * @since 4.0.0 - * @category Filtering */ Fail>( mapEffect(self, (a) => filter(a as NoInfer), options), @@ -6536,15 +7256,17 @@ export const partitionEffect: { ) /** - * Splits a stream into excluded and satisfying substreams using a `Filter`. + * Splits a stream into scoped excluded and satisfying substreams using a + * `Filter`. * - * The faster stream may advance up to `bufferSize` elements ahead of the slower - * one. + * **Details** * - * @since 4.0.0 - * @category Filtering + * The returned streams are backed by queues in the current scope and should be + * consumed while that scope remains open. The faster stream may advance up to + * `bufferSize` elements ahead of the slower one. + * + * **Example** (Partitioning a stream) * - * @example * ```ts * import { Console, Effect, Result, Stream } from "effect" * @@ -6561,18 +7283,23 @@ export const partitionEffect: { * // Output: [ 2, 4 ] * }) * ``` + * + * @category filtering + * @since 2.0.0 */ export const partition: { /** - * Splits a stream into excluded and satisfying substreams using a `Filter`. + * Splits a stream into scoped excluded and satisfying substreams using a + * `Filter`. * - * The faster stream may advance up to `bufferSize` elements ahead of the slower - * one. + * **Details** * - * @since 4.0.0 - * @category Filtering + * The returned streams are backed by queues in the current scope and should be + * consumed while that scope remains open. The faster stream may advance up to + * `bufferSize` elements ahead of the slower one. + * + * **Example** (Partitioning a stream) * - * @example * ```ts * import { Console, Effect, Result, Stream } from "effect" * @@ -6589,6 +7316,9 @@ export const partition: { * // Output: [ 2, 4 ] * }) * ``` + * + * @category filtering + * @since 2.0.0 */ ( filter: Filter.Filter, Pass, Fail>, @@ -6601,15 +7331,17 @@ export const partition: { R | Scope.Scope > /** - * Splits a stream into excluded and satisfying substreams using a `Filter`. + * Splits a stream into scoped excluded and satisfying substreams using a + * `Filter`. * - * The faster stream may advance up to `bufferSize` elements ahead of the slower - * one. + * **Details** * - * @since 4.0.0 - * @category Filtering + * The returned streams are backed by queues in the current scope and should be + * consumed while that scope remains open. The faster stream may advance up to + * `bufferSize` elements ahead of the slower one. + * + * **Example** (Partitioning a stream) * - * @example * ```ts * import { Console, Effect, Result, Stream } from "effect" * @@ -6626,6 +7358,9 @@ export const partition: { * // Output: [ 2, 4 ] * }) * ``` + * + * @category filtering + * @since 2.0.0 */ ( self: Stream, @@ -6657,7 +7392,8 @@ export const partition: { * Returns the specified stream if the given condition is satisfied, otherwise * returns an empty stream. * - * @example + * **Example** (Conditionally keeping a stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -6672,15 +7408,16 @@ export const partition: { * // Output: [] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ export const when: { /** * Returns the specified stream if the given condition is satisfied, otherwise * returns an empty stream. * - * @example + * **Example** (Conditionally keeping a stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -6695,15 +7432,16 @@ export const when: { * // Output: [] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (test: Effect.Effect): (self: Stream) => Stream /** * Returns the specified stream if the given condition is satisfied, otherwise * returns an empty stream. * - * @example + * **Example** (Conditionally keeping a stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -6718,8 +7456,8 @@ export const when: { * // Output: [] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (self: Stream, test: Effect.Effect): Stream } = dual(2, ( @@ -6735,9 +7473,12 @@ export const when: { * Runs a sink to peel off enough elements to produce a value and returns that * value with the remaining stream in a scope. * + * **Details** + * * The returned stream is only valid within the scope. * - * @example + * **Example** (Peeling a stream with a sink) + * * ```ts * import { Console, Effect, Sink, Stream } from "effect" * @@ -6756,17 +7497,20 @@ export const when: { * // Output: [ [1, 2, 3], [4, 5, 6] ] * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const peel: { /** * Runs a sink to peel off enough elements to produce a value and returns that * value with the remaining stream in a scope. * + * **Details** + * * The returned stream is only valid within the scope. * - * @example + * **Example** (Peeling a stream with a sink) + * * ```ts * import { Console, Effect, Sink, Stream } from "effect" * @@ -6785,17 +7529,20 @@ export const peel: { * // Output: [ [1, 2, 3], [4, 5, 6] ] * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ (sink: Sink.Sink): (self: Stream) => Effect.Effect<[A2, Stream], E2 | E, Scope.Scope | R2 | R> /** * Runs a sink to peel off enough elements to produce a value and returns that * value with the remaining stream in a scope. * + * **Details** + * * The returned stream is only valid within the scope. * - * @example + * **Example** (Peeling a stream with a sink) + * * ```ts * import { Console, Effect, Sink, Stream } from "effect" * @@ -6814,8 +7561,8 @@ export const peel: { * // Output: [ [1, 2, 3], [4, 5, 6] ] * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ (self: Stream, sink: Sink.Sink): Effect.Effect<[A2, Stream], E | E2, Scope.Scope | R | R2> } = dual( @@ -6847,10 +7594,15 @@ export const peel: { * Buffers up to `capacity` elements so a faster producer can progress * independently of a slower consumer. * - * Note: This combinator destroys chunking. Use `Stream.rechunk` afterwards if - * you need fixed chunk sizes. + * **Details** + * + * Finite buffers use the configured queue strategy: `"suspend"` applies + * backpressure, while `"dropping"` and `"sliding"` may discard elements when + * the buffer is full. This combinator destroys chunking; use `Stream.rechunk` + * afterward if you need fixed chunk sizes. + * + * **Example** (Buffering stream elements) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -6866,18 +7618,23 @@ export const peel: { * // Output: [ 1, 2, 3 ] * ``` * + * @category rate limiting * @since 2.0.0 - * @category Rate Limiting */ export const buffer: { /** * Buffers up to `capacity` elements so a faster producer can progress * independently of a slower consumer. * - * Note: This combinator destroys chunking. Use `Stream.rechunk` afterwards if - * you need fixed chunk sizes. + * **Details** + * + * Finite buffers use the configured queue strategy: `"suspend"` applies + * backpressure, while `"dropping"` and `"sliding"` may discard elements when + * the buffer is full. This combinator destroys chunking; use `Stream.rechunk` + * afterward if you need fixed chunk sizes. + * + * **Example** (Buffering stream elements) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -6893,8 +7650,8 @@ export const buffer: { * // Output: [ 1, 2, 3 ] * ``` * + * @category rate limiting * @since 2.0.0 - * @category Rate Limiting */ ( options: { readonly capacity: "unbounded" } | { @@ -6906,10 +7663,15 @@ export const buffer: { * Buffers up to `capacity` elements so a faster producer can progress * independently of a slower consumer. * - * Note: This combinator destroys chunking. Use `Stream.rechunk` afterwards if - * you need fixed chunk sizes. + * **Details** + * + * Finite buffers use the configured queue strategy: `"suspend"` applies + * backpressure, while `"dropping"` and `"sliding"` may discard elements when + * the buffer is full. This combinator destroys chunking; use `Stream.rechunk` + * afterward if you need fixed chunk sizes. + * + * **Example** (Buffering stream elements) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -6925,8 +7687,8 @@ export const buffer: { * // Output: [ 1, 2, 3 ] * ``` * + * @category rate limiting * @since 2.0.0 - * @category Rate Limiting */ ( self: Stream, @@ -6947,15 +7709,15 @@ export const buffer: { * Allows a faster producer to progress independently of a slower consumer by * buffering up to `capacity` chunks in a queue. * - * This combinator preserves chunking and is best with power-of-2 capacities. + * **Details** * - * **Previously Known As** + * Finite buffers use the configured queue strategy: `"suspend"` applies + * backpressure, while `"dropping"` and `"sliding"` may discard chunks when the + * buffer is full. This combinator preserves chunking and is best with + * power-of-2 capacities. * - * This API replaces the following from Effect 3.x: + * **Example** (Buffering stream chunks) * - * - `Stream.bufferChunks` - * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -6970,23 +7732,23 @@ export const buffer: { * // Output: [ 1, 2, 3, 4 ] * ``` * - * @since 2.0.0 - * @category Rate Limiting + * @category rate limiting + * @since 4.0.0 */ export const bufferArray: { /** * Allows a faster producer to progress independently of a slower consumer by * buffering up to `capacity` chunks in a queue. * - * This combinator preserves chunking and is best with power-of-2 capacities. - * - * **Previously Known As** + * **Details** * - * This API replaces the following from Effect 3.x: + * Finite buffers use the configured queue strategy: `"suspend"` applies + * backpressure, while `"dropping"` and `"sliding"` may discard chunks when the + * buffer is full. This combinator preserves chunking and is best with + * power-of-2 capacities. * - * - `Stream.bufferChunks` + * **Example** (Buffering stream chunks) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -7001,8 +7763,8 @@ export const bufferArray: { * // Output: [ 1, 2, 3, 4 ] * ``` * - * @since 2.0.0 - * @category Rate Limiting + * @category rate limiting + * @since 4.0.0 */ ( options: { readonly capacity: "unbounded" } | { @@ -7014,15 +7776,15 @@ export const bufferArray: { * Allows a faster producer to progress independently of a slower consumer by * buffering up to `capacity` chunks in a queue. * - * This combinator preserves chunking and is best with power-of-2 capacities. + * **Details** * - * **Previously Known As** + * Finite buffers use the configured queue strategy: `"suspend"` applies + * backpressure, while `"dropping"` and `"sliding"` may discard chunks when the + * buffer is full. This combinator preserves chunking and is best with + * power-of-2 capacities. * - * This API replaces the following from Effect 3.x: + * **Example** (Buffering stream chunks) * - * - `Stream.bufferChunks` - * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -7037,8 +7799,8 @@ export const bufferArray: { * // Output: [ 1, 2, 3, 4 ] * ``` * - * @since 2.0.0 - * @category Rate Limiting + * @category rate limiting + * @since 4.0.0 */ ( self: Stream, @@ -7060,13 +7822,8 @@ export const bufferArray: { * one fails. Allows recovery from all causes of failure, including * interruption if the stream is uninterruptible. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Catching stream causes) * - * - `Stream.catchAllCause` - * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -7088,8 +7845,8 @@ export const bufferArray: { * // Output: [ 1, 2, 999 ] * ``` * - * @since 4.0.0 - * @category Error Handling + * @category error handling + * @since 2.0.0 */ export const catchCause: { /** @@ -7097,13 +7854,8 @@ export const catchCause: { * one fails. Allows recovery from all causes of failure, including * interruption if the stream is uninterruptible. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Catching stream causes) * - * - `Stream.catchAllCause` - * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -7125,8 +7877,8 @@ export const catchCause: { * // Output: [ 1, 2, 999 ] * ``` * - * @since 4.0.0 - * @category Error Handling + * @category error handling + * @since 2.0.0 */ (f: (cause: Cause.Cause) => Stream): (self: Stream) => Stream /** @@ -7134,13 +7886,8 @@ export const catchCause: { * one fails. Allows recovery from all causes of failure, including * interruption if the stream is uninterruptible. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Catching stream causes) * - * - `Stream.catchAllCause` - * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -7162,8 +7909,8 @@ export const catchCause: { * // Output: [ 1, 2, 999 ] * ``` * - * @since 4.0.0 - * @category Error Handling + * @category error handling + * @since 2.0.0 */ (self: Stream, f: (cause: Cause.Cause) => Stream): Stream } = dual(2, ( @@ -7179,13 +7926,8 @@ export const catchCause: { * Runs an effect when the stream fails without changing its values or error, * unless the tap effect itself fails. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Tapping stream causes) * - * - `Stream.tapErrorCause` - * - * @example * ```ts * import { Cause, Console, Effect, Stream } from "effect" * @@ -7205,21 +7947,16 @@ export const catchCause: { * // Output: [ 1, 2, 0 ] * ``` * - * @since 4.0.0 - * @category Error Handling + * @category error handling + * @since 2.0.0 */ export const tapCause: { /** * Runs an effect when the stream fails without changing its values or error, * unless the tap effect itself fails. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Tapping stream causes) * - * - `Stream.tapErrorCause` - * - * @example * ```ts * import { Cause, Console, Effect, Stream } from "effect" * @@ -7239,21 +7976,16 @@ export const tapCause: { * // Output: [ 1, 2, 0 ] * ``` * - * @since 4.0.0 - * @category Error Handling + * @category error handling + * @since 2.0.0 */ (f: (cause: Cause.Cause) => Effect.Effect): (self: Stream) => Stream /** * Runs an effect when the stream fails without changing its values or error, * unless the tap effect itself fails. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Tapping stream causes) * - * - `Stream.tapErrorCause` - * - * @example * ```ts * import { Cause, Console, Effect, Stream } from "effect" * @@ -7273,8 +8005,8 @@ export const tapCause: { * // Output: [ 1, 2, 0 ] * ``` * - * @since 4.0.0 - * @category Error Handling + * @category error handling + * @since 2.0.0 */ ( self: Stream, @@ -7306,13 +8038,8 @@ export { /** * Switches over to the stream produced by the provided function if this one fails. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Catching stream failures) * - * - `Stream.catchAll` - * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -7330,16 +8057,17 @@ export { * // Output: [ 1, 2, 999 ] * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ catch_ as catch } /** - * Effectfully peeks at errors without changing the stream unless the tap fails. + * Peeks at errors effectfully without changing the stream unless the tap fails. + * + * **Example** (Effectfully peeking at errors) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -7360,14 +8088,15 @@ export { * // [ 1, 2, 999 ] * ``` * - * @since 4.0.0 - * @category Error Handling + * @category error handling + * @since 2.0.0 */ export const tapError: { /** - * Effectfully peeks at errors without changing the stream unless the tap fails. + * Peeks at errors effectfully without changing the stream unless the tap fails. + * + * **Example** (Effectfully peeking at errors) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -7388,14 +8117,15 @@ export const tapError: { * // [ 1, 2, 999 ] * ``` * - * @since 4.0.0 - * @category Error Handling + * @category error handling + * @since 2.0.0 */ (f: (error: E) => Effect.Effect): (self: Stream) => Stream /** - * Effectfully peeks at errors without changing the stream unless the tap fails. + * Peeks at errors effectfully without changing the stream unless the tap fails. + * + * **Example** (Effectfully peeking at errors) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -7416,8 +8146,8 @@ export const tapError: { * // [ 1, 2, 999 ] * ``` * - * @since 4.0.0 - * @category Error Handling + * @category error handling + * @since 2.0.0 */ (self: Stream, f: (error: E) => Effect.Effect): Stream } = dual(2, ( @@ -7432,17 +8162,14 @@ export const tapError: { /** * Recovers from errors that match a predicate by switching to a recovery stream. * + * **Details** + * * When a failure matches the filter, the stream switches to the recovery * stream. Non-matching failures propagate downstream, so the error type is * preserved unless the filter narrows it. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Catching matching failures) * - * - `Stream.catchSome` - * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -7463,24 +8190,21 @@ export const tapError: { * Effect.runPromise(program) * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const catchIf: { /** * Recovers from errors that match a predicate by switching to a recovery stream. * + * **Details** + * * When a failure matches the filter, the stream switches to the recovery * stream. Non-matching failures propagate downstream, so the error type is * preserved unless the filter narrows it. * - * **Previously Known As** + * **Example** (Catching matching failures) * - * This API replaces the following from Effect 3.x: - * - * - `Stream.catchSome` - * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -7501,28 +8225,27 @@ export const catchIf: { * Effect.runPromise(program) * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ - , R3 = never>( + ( refinement: Refinement, EB>, f: (e: EB) => Stream, orElse?: ((e: Exclude) => Stream) | undefined - ): (self: Stream) => Stream + ): ( + self: Stream + ) => Stream, E2 | E3 | (A3 extends unassigned ? Exclude : never), R | R2 | R3> /** * Recovers from errors that match a predicate by switching to a recovery stream. * + * **Details** + * * When a failure matches the filter, the stream switches to the recovery * stream. Non-matching failures propagate downstream, so the error type is * preserved unless the filter narrows it. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Catching matching failures) * - * - `Stream.catchSome` - * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -7543,28 +8266,27 @@ export const catchIf: { * Effect.runPromise(program) * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ - ( + ( predicate: Predicate>, f: (e: NoInfer) => Stream, orElse?: ((e: NoInfer) => Stream) | undefined - ): (self: Stream) => Stream + ): ( + self: Stream + ) => Stream, E2 | E3 | (A3 extends unassigned ? E : never), R | R2 | R3> /** * Recovers from errors that match a predicate by switching to a recovery stream. * + * **Details** + * * When a failure matches the filter, the stream switches to the recovery * stream. Non-matching failures propagate downstream, so the error type is * preserved unless the filter narrows it. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: - * - * - `Stream.catchSome` + * **Example** (Catching matching failures) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -7585,29 +8307,26 @@ export const catchIf: { * Effect.runPromise(program) * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ - , R3 = never>( + ( self: Stream, refinement: Refinement, f: (e: EB) => Stream, orElse?: ((e: Exclude) => Stream) | undefined - ): Stream + ): Stream, E2 | E3 | (A3 extends unassigned ? Exclude : never), R | R2 | R3> /** * Recovers from errors that match a predicate by switching to a recovery stream. * + * **Details** + * * When a failure matches the filter, the stream switches to the recovery * stream. Non-matching failures propagate downstream, so the error type is * preserved unless the filter narrows it. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: + * **Example** (Catching matching failures) * - * - `Stream.catchSome` - * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -7628,15 +8347,15 @@ export const catchIf: { * Effect.runPromise(program) * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ - ( + ( self: Stream, predicate: Predicate, f: (e: E) => Stream, orElse?: ((e: E) => Stream) | undefined - ): Stream + ): Stream, E2 | E3 | (A3 extends unassigned ? E : never), R | R2 | R3> } = dual((args) => isStream(args[0]), < A, E, @@ -7666,35 +8385,82 @@ export const catchIf: { * Recovers from errors that match a `Filter` by switching to a recovery * stream. * + * **When to use** + * + * Use to recover from stream errors with a reusable `Filter` when matching can + * also narrow or transform the error before choosing the recovery stream. + * + * **Details** + * + * Successful filter results are passed to `f`. Failed filter results go to + * `orElse` when provided; otherwise the filter failure is re-failed. + * + * @see {@link catchIf} for predicate or refinement based recovery + * @see {@link catchTag} for `_tag` based recovery from one tagged error + * @see {@link catchTags} for `_tag` based recovery from multiple tagged errors + * @see {@link catchCauseFilter} for filtering full causes + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const catchFilter: { /** * Recovers from errors that match a `Filter` by switching to a recovery * stream. * + * **When to use** + * + * Use to recover from stream errors with a reusable `Filter` when matching can + * also narrow or transform the error before choosing the recovery stream. + * + * **Details** + * + * Successful filter results are passed to `f`. Failed filter results go to + * `orElse` when provided; otherwise the filter failure is re-failed. + * + * @see {@link catchIf} for predicate or refinement based recovery + * @see {@link catchTag} for `_tag` based recovery from one tagged error + * @see {@link catchTags} for `_tag` based recovery from multiple tagged errors + * @see {@link catchCauseFilter} for filtering full causes + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ - ( + ( filter: Filter.Filter, EB, X>, f: (failure: EB) => Stream, orElse?: ((failure: X) => Stream) | undefined - ): (self: Stream) => Stream + ): ( + self: Stream + ) => Stream, E2 | E3 | (A3 extends unassigned ? X : never), R | R2 | R3> /** * Recovers from errors that match a `Filter` by switching to a recovery * stream. * + * **When to use** + * + * Use to recover from stream errors with a reusable `Filter` when matching can + * also narrow or transform the error before choosing the recovery stream. + * + * **Details** + * + * Successful filter results are passed to `f`. Failed filter results go to + * `orElse` when provided; otherwise the filter failure is re-failed. + * + * @see {@link catchIf} for predicate or refinement based recovery + * @see {@link catchTag} for `_tag` based recovery from one tagged error + * @see {@link catchTags} for `_tag` based recovery from multiple tagged errors + * @see {@link catchCauseFilter} for filtering full causes + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ - ( + ( self: Stream, filter: Filter.Filter, EB, X>, f: (failure: EB) => Stream, orElse?: ((failure: X) => Stream) | undefined - ): Stream + ): Stream, E2 | E3 | (A3 extends unassigned ? X : never), R | R2 | R3> } = dual((args) => isStream(args[0]), < A, E, @@ -7726,12 +8492,13 @@ export const catchFilter: { * Recovers from failures whose `_tag` matches the provided value by switching to * the stream returned by `f`. * - * **When to Use** + * **When to use** * - * Use `catchTag` when your error type is a tagged union with a readonly `_tag` - * field and you want to handle a specific error case. + * Use when you need to handle a specific error case from a stream whose error + * type is a tagged union with a readonly `_tag` field. + * + * **Example** (Catching tagged failures) * - * @example * ```ts * import { Console, Data, Effect, Stream } from "effect" * @@ -7752,20 +8519,21 @@ export const catchFilter: { * Effect.runPromise(program) * ``` * - * @since 4.0.0 - * @category Error Handling + * @category error handling + * @since 2.0.0 */ export const catchTag: { /** * Recovers from failures whose `_tag` matches the provided value by switching to * the stream returned by `f`. * - * **When to Use** + * **When to use** + * + * Use when you need to handle a specific error case from a stream whose error + * type is a tagged union with a readonly `_tag` field. * - * Use `catchTag` when your error type is a tagged union with a readonly `_tag` - * field and you want to handle a specific error case. + * **Example** (Catching tagged failures) * - * @example * ```ts * import { Console, Data, Effect, Stream } from "effect" * @@ -7786,8 +8554,8 @@ export const catchTag: { * Effect.runPromise(program) * ``` * - * @since 4.0.0 - * @category Error Handling + * @category error handling + * @since 2.0.0 */ < const K extends Tags | Arr.NonEmptyReadonlyArray>, @@ -7795,8 +8563,8 @@ export const catchTag: { A1, E1, R1, - A2 = never, - E2 = ExcludeTag ? K[number] : K>, + A2 = unassigned, + E2 = never, R2 = never >( k: K, @@ -7808,17 +8576,24 @@ export const catchTag: { | undefined ): ( self: Stream - ) => Stream + ) => Stream< + A | A1 | Exclude, + | E1 + | E2 + | (A2 extends unassigned ? ExcludeTag ? K[number] : K> : never), + R | R1 | R2 + > /** * Recovers from failures whose `_tag` matches the provided value by switching to * the stream returned by `f`. * - * **When to Use** + * **When to use** * - * Use `catchTag` when your error type is a tagged union with a readonly `_tag` - * field and you want to handle a specific error case. + * Use when you need to handle a specific error case from a stream whose error + * type is a tagged union with a readonly `_tag` field. + * + * **Example** (Catching tagged failures) * - * @example * ```ts * import { Console, Data, Effect, Stream } from "effect" * @@ -7839,8 +8614,8 @@ export const catchTag: { * Effect.runPromise(program) * ``` * - * @since 4.0.0 - * @category Error Handling + * @category error handling + * @since 2.0.0 */ < A, @@ -7850,8 +8625,8 @@ export const catchTag: { R1, E1, A1, - A2 = never, - E2 = ExcludeTag ? K[number] : K>, + A2 = unassigned, + E2 = never, R2 = never >( self: Stream, @@ -7860,7 +8635,13 @@ export const catchTag: { orElse?: | ((e: ExcludeTag ? K[number] : K>) => Stream) | undefined - ): Stream + ): Stream< + A | A1 | Exclude, + | E1 + | E2 + | (A2 extends unassigned ? ExcludeTag ? K[number] : K> : never), + R | R1 | R2 + > } = dual( (args) => isStream(args[0]), < @@ -7892,7 +8673,8 @@ export const catchTag: { /** * Switches to a recovery stream based on matching `_tag` handlers. * - * @example + * **Example** (Catching tagged failures with handlers) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -7922,14 +8704,15 @@ export const catchTag: { * // Output: [ "fallback" ] * ``` * - * @since 4.0.0 - * @category Error Handling + * @category error handling + * @since 2.0.0 */ export const catchTags: { /** * Switches to a recovery stream based on matching `_tag` handlers. * - * @example + * **Example** (Catching tagged failures with handlers) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -7959,8 +8742,8 @@ export const catchTags: { * // Output: [ "fallback" ] * ``` * - * @since 4.0.0 - * @category Error Handling + * @category error handling + * @since 2.0.0 */ < E, @@ -7968,19 +8751,20 @@ export const catchTags: { [K in E["_tag"]]+?: (error: Extract) => Stream } : {}), - A2 = never, - E2 = Exclude, + A2 = unassigned, + E2 = never, R2 = never >( cases: Cases, orElse?: ((e: Exclude) => Stream) | undefined ): (self: Stream) => Stream< | A - | A2 + | Exclude | { [K in keyof Cases]: Cases[K] extends ((...args: Array) => Stream) ? A : never }[keyof Cases], | E2 + | (A2 extends unassigned ? Exclude : never) | { [K in keyof Cases]: Cases[K] extends ((...args: Array) => Stream) ? E : never }[keyof Cases], @@ -7993,7 +8777,8 @@ export const catchTags: { /** * Switches to a recovery stream based on matching `_tag` handlers. * - * @example + * **Example** (Catching tagged failures with handlers) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -8023,8 +8808,8 @@ export const catchTags: { * // Output: [ "fallback" ] * ``` * - * @since 4.0.0 - * @category Error Handling + * @category error handling + * @since 2.0.0 */ < R, @@ -8034,8 +8819,8 @@ export const catchTags: { [K in E["_tag"]]+?: (error: Extract) => Stream } : {}), - A2 = never, - E2 = Exclude, + A2 = unassigned, + E2 = never, R2 = never >( self: Stream, @@ -8043,11 +8828,12 @@ export const catchTags: { orElse?: ((e: Exclude) => Stream) | undefined ): Stream< | A - | A2 + | Exclude | { [K in keyof Cases]: Cases[K] extends ((...args: Array) => Stream) ? A : never }[keyof Cases], | E2 + | (A2 extends unassigned ? Exclude : never) | { [K in keyof Cases]: Cases[K] extends ((...args: Array) => Stream) ? E : never }[keyof Cases], @@ -8075,10 +8861,17 @@ export const catchTags: { /** * Catches a specific reason within a tagged error. * - * Use this to handle nested error causes without removing the parent error - * from the error channel. The handler receives the unwrapped reason. + * **When to use** + * + * Use to handle nested error causes without removing the parent error + * from the error channel. + * + * **Details** + * + * The handler receives the unwrapped reason. + * + * **Example** (Catching a tagged error reason) * - * @example * ```ts * import { Console, Data, Effect, Stream } from "effect" * @@ -8112,17 +8905,24 @@ export const catchTags: { * // Output: [ "retry: 60" ] * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const catchReason: { /** * Catches a specific reason within a tagged error. * - * Use this to handle nested error causes without removing the parent error - * from the error channel. The handler receives the unwrapped reason. + * **When to use** + * + * Use to handle nested error causes without removing the parent error + * from the error channel. + * + * **Details** + * + * The handler receives the unwrapped reason. + * + * **Example** (Catching a tagged error reason) * - * @example * ```ts * import { Console, Data, Effect, Stream } from "effect" * @@ -8156,8 +8956,8 @@ export const catchReason: { * // Output: [ "retry: 60" ] * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ < K extends Tags, @@ -8184,14 +8984,25 @@ export const catchReason: { | undefined ): ( self: Stream - ) => Stream, (A3 extends unassigned ? E : ExcludeTag) | E2 | E3, R | R2 | R3> + ) => Stream< + A | A2 | Exclude, + ExcludeTag | E2 | E3 | (A3 extends unassigned ? ExtractTag : never), + R | R2 | R3 + > /** * Catches a specific reason within a tagged error. * - * Use this to handle nested error causes without removing the parent error - * from the error channel. The handler receives the unwrapped reason. + * **When to use** + * + * Use to handle nested error causes without removing the parent error + * from the error channel. + * + * **Details** + * + * The handler receives the unwrapped reason. + * + * **Example** (Catching a tagged error reason) * - * @example * ```ts * import { Console, Data, Effect, Stream } from "effect" * @@ -8225,8 +9036,8 @@ export const catchReason: { * // Output: [ "retry: 60" ] * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ < A, @@ -8248,7 +9059,11 @@ export const catchReason: { orElse?: | ((reason: ExcludeReason, RK>, error: OmitReason, RK>) => Stream) | undefined - ): Stream, (A3 extends unassigned ? E : ExcludeTag) | E2 | E3, R | R2 | R3> + ): Stream< + A | A2 | Exclude, + ExcludeTag | E2 | E3 | (A3 extends unassigned ? ExtractTag : never), + R | R2 | R3 + > } = dual( (args) => isStream(args[0]), < @@ -8271,7 +9086,11 @@ export const catchReason: { orElse?: | ((reason: ExcludeReason, RK>, error: OmitReason, RK>) => Stream) | undefined - ): Stream, (A3 extends unassigned ? E : ExcludeTag) | E2 | E3, R | R2 | R3> => + ): Stream< + A | A2 | Exclude, + ExcludeTag | E2 | E3 | (A3 extends unassigned ? ExtractTag : never), + R | R2 | R3 + > => fromChannel( Channel.catchReason( toChannel(self), @@ -8286,7 +9105,8 @@ export const catchReason: { /** * Catches multiple reasons within a tagged error using an object of handlers. * - * @example + * **Example** (Catching tagged error reasons) + * * ```ts * import { Console, Data, Effect, Stream } from "effect" * @@ -8321,14 +9141,15 @@ export const catchReason: { * // Output: [ "retry: 60" ] * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const catchReasons: { /** * Catches multiple reasons within a tagged error using an object of handlers. * - * @example + * **Example** (Catching tagged error reasons) + * * ```ts * import { Console, Data, Effect, Stream } from "effect" * @@ -8363,8 +9184,8 @@ export const catchReasons: { * // Output: [ "retry: 60" ] * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ < K extends Tags, @@ -8393,8 +9214,9 @@ export const catchReasons: { | { [RK in keyof Cases]: Cases[RK] extends (...args: Array) => Stream ? A : never }[keyof Cases], - | (A2 extends unassigned ? E : ExcludeTag) + | ExcludeTag | E2 + | (A2 extends unassigned ? ExtractTag : never) | { [RK in keyof Cases]: Cases[RK] extends (...args: Array) => Stream ? E : never }[keyof Cases], @@ -8407,7 +9229,8 @@ export const catchReasons: { /** * Catches multiple reasons within a tagged error using an object of handlers. * - * @example + * **Example** (Catching tagged error reasons) + * * ```ts * import { Console, Data, Effect, Stream } from "effect" * @@ -8442,8 +9265,8 @@ export const catchReasons: { * // Output: [ "retry: 60" ] * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ < A, @@ -8475,8 +9298,9 @@ export const catchReasons: { | { [RK in keyof Cases]: Cases[RK] extends (...args: Array) => Stream ? A : never }[keyof Cases], - | (A2 extends unassigned ? E : ExcludeTag) + | ExcludeTag | E2 + | (A2 extends unassigned ? ExtractTag : never) | { [RK in keyof Cases]: Cases[RK] extends (...args: Array) => Stream ? E : never }[keyof Cases], @@ -8509,7 +9333,8 @@ export const catchReasons: { /** * Transforms the errors emitted by this stream using `f`. * - * @example + * **Example** (Mapping stream errors) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -8526,14 +9351,15 @@ export const catchReasons: { * // Output: [ "recovered from mapped: bad" ] * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ export const mapError: { /** * Transforms the errors emitted by this stream using `f`. * - * @example + * **Example** (Mapping stream errors) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -8550,14 +9376,15 @@ export const mapError: { * // Output: [ "recovered from mapped: bad" ] * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ (f: (error: E) => E2): (self: Stream) => Stream /** * Transforms the errors emitted by this stream using `f`. * - * @example + * **Example** (Mapping stream errors) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -8574,8 +9401,8 @@ export const mapError: { * // Output: [ "recovered from mapped: bad" ] * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ (self: Stream, f: (error: E) => E2): Stream } = dual(2, ( @@ -8587,13 +9414,8 @@ export const mapError: { * Recovers from stream failures by filtering the `Cause` and switching to a recovery stream. * Non-matching causes are re-emitted as failures. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: - * - * - `Stream.catchSomeCause` + * **Example** (Catching matching causes) * - * @example * ```ts * import { Cause, Console, Effect, Stream } from "effect" * @@ -8613,21 +9435,16 @@ export const mapError: { * // Output: [ "Recovered: NetworkError" ] * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const catchCauseIf: { /** * Recovers from stream failures by filtering the `Cause` and switching to a recovery stream. * Non-matching causes are re-emitted as failures. * - * **Previously Known As** + * **Example** (Catching matching causes) * - * This API replaces the following from Effect 3.x: - * - * - `Stream.catchSomeCause` - * - * @example * ```ts * import { Cause, Console, Effect, Stream } from "effect" * @@ -8647,8 +9464,8 @@ export const catchCauseIf: { * // Output: [ "Recovered: NetworkError" ] * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ ( predicate: Predicate>, @@ -8660,13 +9477,8 @@ export const catchCauseIf: { * Recovers from stream failures by filtering the `Cause` and switching to a recovery stream. * Non-matching causes are re-emitted as failures. * - * **Previously Known As** - * - * This API replaces the following from Effect 3.x: - * - * - `Stream.catchSomeCause` + * **Example** (Catching matching causes) * - * @example * ```ts * import { Cause, Console, Effect, Stream } from "effect" * @@ -8686,8 +9498,8 @@ export const catchCauseIf: { * // Output: [ "Recovered: NetworkError" ] * ``` * + * @category error handling * @since 4.0.0 - * @category Error Handling */ ( self: Stream, @@ -8711,16 +9523,48 @@ export const catchCauseIf: { * Recovers from stream failures by filtering the `Cause` and switching to a * recovery stream. * + * **When to use** + * + * Use when you need to recover a stream only from causes selected by a + * `Filter`, while giving the recovery both the selected value and the original + * `Cause`. + * + * **Details** + * + * The filter is applied to the full `Cause`. A successful filter result is + * passed to `f` together with the original cause; a failed filter result + * re-fails with the residual cause. + * + * @see {@link catchCauseIf} for predicate-based cause selection + * @see {@link catchFilter} for filtering typed error values instead of full causes + * @see {@link catchCause} for recovering from every cause without filtering + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const catchCauseFilter: { /** * Recovers from stream failures by filtering the `Cause` and switching to a * recovery stream. * + * **When to use** + * + * Use when you need to recover a stream only from causes selected by a + * `Filter`, while giving the recovery both the selected value and the original + * `Cause`. + * + * **Details** + * + * The filter is applied to the full `Cause`. A successful filter result is + * passed to `f` together with the original cause; a failed filter result + * re-fails with the residual cause. + * + * @see {@link catchCauseIf} for predicate-based cause selection + * @see {@link catchFilter} for filtering typed error values instead of full causes + * @see {@link catchCause} for recovering from every cause without filtering + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ >( filter: Filter.Filter, EB, X>, @@ -8732,8 +9576,24 @@ export const catchCauseFilter: { * Recovers from stream failures by filtering the `Cause` and switching to a * recovery stream. * + * **When to use** + * + * Use when you need to recover a stream only from causes selected by a + * `Filter`, while giving the recovery both the selected value and the original + * `Cause`. + * + * **Details** + * + * The filter is applied to the full `Cause`. A successful filter result is + * passed to `f` together with the original cause; a failed filter result + * re-fails with the residual cause. + * + * @see {@link catchCauseIf} for predicate-based cause selection + * @see {@link catchFilter} for filtering typed error values instead of full causes + * @see {@link catchCause} for recovering from every cause without filtering + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ >( self: Stream, @@ -8756,7 +9616,8 @@ export const catchCauseFilter: { /** * Switches to a fallback stream if this stream is empty. * - * @example + * **Example** (Switching on empty streams) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -8772,14 +9633,15 @@ export const catchCauseFilter: { * // Output: [ 1, 2 ] * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ export const orElseIfEmpty: { /** * Switches to a fallback stream if this stream is empty. * - * @example + * **Example** (Switching on empty streams) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -8795,14 +9657,15 @@ export const orElseIfEmpty: { * // Output: [ 1, 2 ] * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ (orElse: LazyArg>): (self: Stream) => Stream /** * Switches to a fallback stream if this stream is empty. * - * @example + * **Example** (Switching on empty streams) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -8818,8 +9681,8 @@ export const orElseIfEmpty: { * // Output: [ 1, 2 ] * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ (self: Stream, orElse: LazyArg>): Stream } = dual(2, ( @@ -8834,7 +9697,8 @@ export const orElseIfEmpty: { /** * Returns a stream that emits a fallback value when this stream fails. * - * @example + * **Example** (Recovering with a fallback value) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -8851,14 +9715,15 @@ export const orElseIfEmpty: { * // Output: [ "Recovered: NetworkError" ] * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ export const orElseSucceed: { /** * Returns a stream that emits a fallback value when this stream fails. * - * @example + * **Example** (Recovering with a fallback value) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -8875,14 +9740,15 @@ export const orElseSucceed: { * // Output: [ "Recovered: NetworkError" ] * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ (f: (error: E) => A2): (self: Stream) => Stream /** * Returns a stream that emits a fallback value when this stream fails. * - * @example + * **Example** (Recovering with a fallback value) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -8899,8 +9765,8 @@ export const orElseSucceed: { * // Output: [ "Recovered: NetworkError" ] * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ (self: Stream, f: (error: E) => A2): Stream } = dual(2, ( @@ -8911,7 +9777,8 @@ export const orElseSucceed: { /** * Turns typed failures into defects, making the stream infallible. * - * @example + * **Example** (Turning failures into defects) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -8928,17 +9795,26 @@ export const orElseSucceed: { * // Output: [ 1, 2, 3 ] * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ export const orDie = (self: Stream): Stream => fromChannel(Channel.orDie(self.channel)) /** * Ignores failures and ends the stream on error. * - * Use the `log` option to emit the full {@link Cause} when the stream fails. + * **When to use** + * + * Use when you want a failing stream to end gracefully rather than propagate + * the error. + * + * **Details** + * + * The `log` option controls whether the failure is logged before the stream + * terminates. + * + * **Example** (Ignoring stream failures) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -8955,17 +9831,26 @@ export const orDie = (self: Stream): Stream => fr * // Output: [ 1, 2, 3 ] * ``` * - * @example - * ```ts - * import { Stream } from "effect" - * - * const stream = Stream.fail("boom") + * **Example** (Configuring ignore logging) * - * const program = stream.pipe(Stream.ignore({ log: "Error" })) - * ``` + * ```ts + * import { Effect, Stream } from "effect" * + * Effect.runPromise(Effect.gen(function*() { + * const values = yield* Stream.fail("boom").pipe( + * Stream.ignore({ log: false }), + * Stream.runCollect + * ) + * yield* Effect.sync(() => console.log(values)) + * })) + * + * // [] + * ``` + * + * @see {@link ignoreCause} for a variant that also ignores defects, not just typed failures + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const ignore: < Arg extends Stream | { @@ -8990,22 +9875,32 @@ export const ignore: < /** * Ignores the stream's failure cause, including defects, and ends the stream. * - * Use the `log` option to emit the full {@link Cause} when the stream fails. + * **When to use** + * + * Use when you need to silently suppress a stream's entire failure cause, + * including both typed errors and defects, rather than propagate it downstream. + * + * **Example** (Ignoring stream failure causes) * - * @example * ```ts * import { Effect, Stream } from "effect" * - * const stream = Stream.make(1, 2).pipe( - * Stream.concat(Stream.fail("boom")), - * Stream.ignoreCause({ log: "Error" }) - * ) + * Effect.runPromise(Effect.gen(function*() { + * const values = yield* Stream.make(1, 2).pipe( + * Stream.concat(Stream.die("boom")), + * Stream.ignoreCause({ log: false }), + * Stream.runCollect + * ) + * yield* Effect.sync(() => console.log(values)) + * })) * - * const program = Stream.runCollect(stream) + * // [ 1, 2 ] * ``` * + * @see {@link ignore} to ignore only typed failures without suppressing defects + * + * @category error handling * @since 4.0.0 - * @category Error Handling */ export const ignoreCause: < Arg extends Stream | { @@ -9026,7 +9921,9 @@ export const ignoreCause: < ) /** - * When the stream fails, retry it according to the given schedule. + * Retries the stream according to the given schedule when it fails. + * + * **Details** * * This retries the entire stream, so will re-execute all of the stream's * acquire operations. @@ -9034,7 +9931,8 @@ export const ignoreCause: < * The schedule is reset as soon as the first element passes through the * stream again. * - * @example + * **Example** (Retrying stream failures) + * * ```ts * import { Console, Effect, Schedule, Stream } from "effect" * @@ -9053,12 +9951,14 @@ export const ignoreCause: < * // Output: [ 1, 1 ] * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ export const retry: { /** - * When the stream fails, retry it according to the given schedule. + * Retries the stream according to the given schedule when it fails. + * + * **Details** * * This retries the entire stream, so will re-execute all of the stream's * acquire operations. @@ -9066,7 +9966,8 @@ export const retry: { * The schedule is reset as soon as the first element passes through the * stream again. * - * @example + * **Example** (Retrying stream failures) + * * ```ts * import { Console, Effect, Schedule, Stream } from "effect" * @@ -9085,8 +9986,8 @@ export const retry: { * // Output: [ 1, 1 ] * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ ( policy: @@ -9096,7 +9997,9 @@ export const retry: { ) => Schedule.Schedule, E2, R2>) ): (self: Stream) => Stream /** - * When the stream fails, retry it according to the given schedule. + * Retries the stream according to the given schedule when it fails. + * + * **Details** * * This retries the entire stream, so will re-execute all of the stream's * acquire operations. @@ -9104,7 +10007,8 @@ export const retry: { * The schedule is reset as soon as the first element passes through the * stream again. * - * @example + * **Example** (Retrying stream failures) + * * ```ts * import { Console, Effect, Schedule, Stream } from "effect" * @@ -9123,8 +10027,8 @@ export const retry: { * // Output: [ 1, 1 ] * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ ( self: Stream, @@ -9147,16 +10051,19 @@ export const retry: { ) /** - * Apply an `ExecutionPlan` to a stream, retrying with step-provided resources + * Applies an `ExecutionPlan` to a stream, retrying with step-provided resources * until it succeeds or the plan is exhausted. * + * **Details** + * * By default, a failing step can fallback even after emitting elements; set * `preventFallbackOnPartialStream` to fail instead of mixing partial output with * a later fallback. * - * @example + * **Example** (Applying an execution plan) + * * ```ts - * import { Console, Effect, ExecutionPlan, Layer, Context, Stream } from "effect" + * import { Console, Context, Effect, ExecutionPlan, Layer, Stream } from "effect" * * class Service extends Context.Service()("Service", { * make: Effect.succeed({ @@ -9172,7 +10079,7 @@ export const retry: { * { provide: Service.Good } * ) * - * const stream = Stream.unwrap(Effect.map(Service.asEffect(), (_) => _.stream)) + * const stream = Stream.unwrap(Effect.map(Service, (_) => _.stream)) * * const program = Effect.gen(function*() { * const items = yield* stream.pipe(Stream.withExecutionPlan(plan), Stream.runCollect) @@ -9183,22 +10090,24 @@ export const retry: { * // Output: [ 1, 2, 3 ] * ``` * + * @category error handling * @since 3.16.0 - * @category Error Handling - * @experimental */ export const withExecutionPlan: { /** - * Apply an `ExecutionPlan` to a stream, retrying with step-provided resources + * Applies an `ExecutionPlan` to a stream, retrying with step-provided resources * until it succeeds or the plan is exhausted. * + * **Details** + * * By default, a failing step can fallback even after emitting elements; set * `preventFallbackOnPartialStream` to fail instead of mixing partial output with * a later fallback. * - * @example + * **Example** (Applying an execution plan) + * * ```ts - * import { Console, Effect, ExecutionPlan, Layer, Context, Stream } from "effect" + * import { Console, Context, Effect, ExecutionPlan, Layer, Stream } from "effect" * * class Service extends Context.Service()("Service", { * make: Effect.succeed({ @@ -9214,7 +10123,7 @@ export const withExecutionPlan: { * { provide: Service.Good } * ) * - * const stream = Stream.unwrap(Effect.map(Service.asEffect(), (_) => _.stream)) + * const stream = Stream.unwrap(Effect.map(Service, (_) => _.stream)) * * const program = Effect.gen(function*() { * const items = yield* stream.pipe(Stream.withExecutionPlan(plan), Stream.runCollect) @@ -9225,25 +10134,27 @@ export const withExecutionPlan: { * // Output: [ 1, 2, 3 ] * ``` * + * @category error handling * @since 3.16.0 - * @category Error Handling - * @experimental */ ( policy: ExecutionPlan.ExecutionPlan<{ provides: Provides; input: Input; error: PolicyE; requirements: R2 }>, options?: { readonly preventFallbackOnPartialStream?: boolean | undefined } ): (self: Stream) => Stream> /** - * Apply an `ExecutionPlan` to a stream, retrying with step-provided resources + * Applies an `ExecutionPlan` to a stream, retrying with step-provided resources * until it succeeds or the plan is exhausted. * + * **Details** + * * By default, a failing step can fallback even after emitting elements; set * `preventFallbackOnPartialStream` to fail instead of mixing partial output with * a later fallback. * - * @example + * **Example** (Applying an execution plan) + * * ```ts - * import { Console, Effect, ExecutionPlan, Layer, Context, Stream } from "effect" + * import { Console, Context, Effect, ExecutionPlan, Layer, Stream } from "effect" * * class Service extends Context.Service()("Service", { * make: Effect.succeed({ @@ -9259,7 +10170,7 @@ export const withExecutionPlan: { * { provide: Service.Good } * ) * - * const stream = Stream.unwrap(Effect.map(Service.asEffect(), (_) => _.stream)) + * const stream = Stream.unwrap(Effect.map(Service, (_) => _.stream)) * * const program = Effect.gen(function*() { * const items = yield* stream.pipe(Stream.withExecutionPlan(plan), Stream.runCollect) @@ -9270,9 +10181,8 @@ export const withExecutionPlan: { * // Output: [ 1, 2, 3 ] * ``` * + * @category error handling * @since 3.16.0 - * @category Error Handling - * @experimental */ ( self: Stream, @@ -9309,16 +10219,19 @@ export const withExecutionPlan: { }) ) let lastError = Option.none()("Service", { * make: Effect.succeed({ @@ -9334,7 +10247,7 @@ export const withExecutionPlan: { * { provide: Service.Good } * ) * - * const stream = Stream.unwrap(Effect.map(Service.asEffect(), (_) => _.stream)) + * const stream = Stream.unwrap(Effect.map(Service, (_) => _.stream)) * * const program = Effect.gen(function*() { * const items = yield* stream.pipe(Stream.withExecutionPlan(plan), Stream.runCollect) @@ -9345,9 +10258,8 @@ export const withExecutionPlan: { * // Output: [ 1, 2, 3 ] * ``` * + * @category error handling * @since 3.16.0 - * @category Error Handling - * @experimental */ E | PolicyE>() const loop: Stream< @@ -9402,7 +10314,8 @@ export const withExecutionPlan: { /** * Takes the first `n` elements from this stream, returning `Stream.empty` when `n < 1`. * - * @example + * **Example** (Taking values from the left) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -9418,14 +10331,15 @@ export const withExecutionPlan: { * // Output: [ 1, 2, 3 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ export const take: { /** * Takes the first `n` elements from this stream, returning `Stream.empty` when `n < 1`. * - * @example + * **Example** (Taking values from the left) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -9441,14 +10355,15 @@ export const take: { * // Output: [ 1, 2, 3 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (n: number): (self: Stream) => Stream /** * Takes the first `n` elements from this stream, returning `Stream.empty` when `n < 1`. * - * @example + * **Example** (Taking values from the left) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -9464,8 +10379,8 @@ export const take: { * // Output: [ 1, 2, 3 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (self: Stream, n: number): Stream } = dual( @@ -9477,7 +10392,8 @@ export const take: { /** * Keeps the last `n` elements from this stream. * - * @example + * **Example** (Taking elements from the right) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -9493,14 +10409,15 @@ export const take: { * // Output: [ 4, 5, 6 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ export const takeRight: { /** * Keeps the last `n` elements from this stream. * - * @example + * **Example** (Taking elements from the right) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -9516,14 +10433,15 @@ export const takeRight: { * // Output: [ 4, 5, 6 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (n: number): (self: Stream) => Stream /** * Keeps the last `n` elements from this stream. * - * @example + * **Example** (Taking elements from the right) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -9539,8 +10457,8 @@ export const takeRight: { * // Output: [ 4, 5, 6 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (self: Stream, n: number): Stream } = dual( @@ -9562,9 +10480,12 @@ export const takeRight: { /** * Takes elements until the predicate matches. * + * **Details** + * * When `excludeLast` is `true`, the matching element is dropped. * - * @example + * **Example** (Taking until a predicate matches) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -9587,16 +10508,19 @@ export const takeRight: { * }) * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ export const takeUntil: { /** * Takes elements until the predicate matches. * + * **Details** + * * When `excludeLast` is `true`, the matching element is dropped. * - * @example + * **Example** (Taking until a predicate matches) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -9619,8 +10543,8 @@ export const takeUntil: { * }) * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ ( predicate: (a: NoInfer, n: number) => boolean, @@ -9631,9 +10555,12 @@ export const takeUntil: { /** * Takes elements until the predicate matches. * + * **Details** + * * When `excludeLast` is `true`, the matching element is dropped. * - * @example + * **Example** (Taking until a predicate matches) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -9656,8 +10583,8 @@ export const takeUntil: { * }) * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ ( self: Stream, @@ -9692,9 +10619,15 @@ export const takeUntil: { ) /** - * Effectful predicate version of `takeUntil`. + * Takes stream elements until an effectful predicate returns `true`. + * + * **When to use** + * + * Use when the stopping condition needs an Effect or service and predicate + * failure should fail the stream. + * + * **Example** (Taking until an effectful predicate matches) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -9710,14 +10643,20 @@ export const takeUntil: { * // Output: [ 1, 2, 3 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ export const takeUntilEffect: { /** - * Effectful predicate version of `takeUntil`. + * Takes stream elements until an effectful predicate returns `true`. + * + * **When to use** + * + * Use when the stopping condition needs an Effect or service and predicate + * failure should fail the stream. + * + * **Example** (Taking until an effectful predicate matches) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -9733,8 +10672,8 @@ export const takeUntilEffect: { * // Output: [ 1, 2, 3 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ ( predicate: (a: NoInfer, n: number) => Effect.Effect, @@ -9743,9 +10682,15 @@ export const takeUntilEffect: { } ): (self: Stream) => Stream /** - * Effectful predicate version of `takeUntil`. + * Takes stream elements until an effectful predicate returns `true`. + * + * **When to use** + * + * Use when the stopping condition needs an Effect or service and predicate + * failure should fail the stream. + * + * **Example** (Taking until an effectful predicate matches) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -9761,8 +10706,8 @@ export const takeUntilEffect: { * // Output: [ 1, 2, 3 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ ( self: Stream, @@ -9799,7 +10744,8 @@ export const takeUntilEffect: { /** * Takes the longest initial prefix of elements that satisfy the predicate. * - * @example + * **Example** (Taking while a predicate holds) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -9816,14 +10762,15 @@ export const takeUntilEffect: { * // Output: [ 1, 2 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ export const takeWhile: { /** * Takes the longest initial prefix of elements that satisfy the predicate. * - * @example + * **Example** (Taking while a predicate holds) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -9840,14 +10787,15 @@ export const takeWhile: { * // Output: [ 1, 2 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (refinement: (a: NoInfer, n: number) => a is B): (self: Stream) => Stream /** * Takes the longest initial prefix of elements that satisfy the predicate. * - * @example + * **Example** (Taking while a predicate holds) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -9864,14 +10812,15 @@ export const takeWhile: { * // Output: [ 1, 2 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (predicate: (a: NoInfer, n: number) => boolean): (self: Stream) => Stream /** * Takes the longest initial prefix of elements that satisfy the predicate. * - * @example + * **Example** (Taking while a predicate holds) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -9888,14 +10837,15 @@ export const takeWhile: { * // Output: [ 1, 2 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (self: Stream, refinement: (a: NoInfer, n: number) => a is B): Stream /** * Takes the longest initial prefix of elements that satisfy the predicate. * - * @example + * **Example** (Taking while a predicate holds) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -9912,8 +10862,8 @@ export const takeWhile: { * // Output: [ 1, 2 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (self: Stream, predicate: (a: NoInfer, n: number) => boolean): Stream } = dual( @@ -9945,24 +10895,66 @@ export const takeWhile: { ) /** - * Takes the longest initial prefix of elements that satisfy the filter. + * Takes the longest initial prefix accepted by a `Filter` and emits the + * filter's success values. + * + * **When to use** + * + * Use to keep the leading stream elements that a `Filter` accepts, emit the + * filter's success values, and stop at the first filter failure. + * + * **Details** + * + * The stream stops at the first `Result.fail` returned by the filter. + * + * @see {@link takeWhile} for keeping original elements with a boolean predicate or refinement + * @see {@link filterMap} for filtering across the whole stream instead of only the leading prefix + * @see {@link dropWhileFilter} for dropping the accepted prefix and keeping the remaining original elements * + * @category filtering * @since 4.0.0 - * @category Filtering */ export const takeWhileFilter: { /** - * Takes the longest initial prefix of elements that satisfy the filter. + * Takes the longest initial prefix accepted by a `Filter` and emits the + * filter's success values. * + * **When to use** + * + * Use to keep the leading stream elements that a `Filter` accepts, emit the + * filter's success values, and stop at the first filter failure. + * + * **Details** + * + * The stream stops at the first `Result.fail` returned by the filter. + * + * @see {@link takeWhile} for keeping original elements with a boolean predicate or refinement + * @see {@link filterMap} for filtering across the whole stream instead of only the leading prefix + * @see {@link dropWhileFilter} for dropping the accepted prefix and keeping the remaining original elements + * + * @category filtering * @since 4.0.0 - * @category Filtering */ (f: Filter.Filter, B, X>): (self: Stream) => Stream /** - * Takes the longest initial prefix of elements that satisfy the filter. + * Takes the longest initial prefix accepted by a `Filter` and emits the + * filter's success values. + * + * **When to use** + * + * Use to keep the leading stream elements that a `Filter` accepts, emit the + * filter's success values, and stop at the first filter failure. + * + * **Details** * + * The stream stops at the first `Result.fail` returned by the filter. + * + * @see {@link takeWhile} for keeping original elements with a boolean predicate or refinement + * @see {@link filterMap} for filtering across the whole stream instead of only the leading prefix + * @see {@link dropWhileFilter} for dropping the accepted prefix and keeping the remaining original elements + * + * @category filtering * @since 4.0.0 - * @category Filtering */ (self: Stream, f: Filter.Filter, B, X>): Stream } = dual( @@ -9996,7 +10988,13 @@ export const takeWhileFilter: { /** * Takes elements from the stream while the effectful predicate is `true`. * - * @example + * **When to use** + * + * Use when the leading-prefix predicate needs an Effect or service and the + * stream should stop before the first false result. + * + * **Example** (Effectfully taking while a predicate holds) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -10012,14 +11010,20 @@ export const takeWhileFilter: { * // Output: [ 1, 2 ] * ``` * - * @since 2.0.0 - * @category Filtering + * @category filtering + * @since 4.0.0 */ export const takeWhileEffect: { /** * Takes elements from the stream while the effectful predicate is `true`. * - * @example + * **When to use** + * + * Use when the leading-prefix predicate needs an Effect or service and the + * stream should stop before the first false result. + * + * **Example** (Effectfully taking while a predicate holds) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -10035,14 +11039,20 @@ export const takeWhileEffect: { * // Output: [ 1, 2 ] * ``` * - * @since 2.0.0 - * @category Filtering + * @category filtering + * @since 4.0.0 */ (predicate: (a: NoInfer, n: number) => Effect.Effect): (self: Stream) => Stream /** * Takes elements from the stream while the effectful predicate is `true`. * - * @example + * **When to use** + * + * Use when the leading-prefix predicate needs an Effect or service and the + * stream should stop before the first false result. + * + * **Example** (Effectfully taking while a predicate holds) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -10058,8 +11068,8 @@ export const takeWhileEffect: { * // Output: [ 1, 2 ] * ``` * - * @since 2.0.0 - * @category Filtering + * @category filtering + * @since 4.0.0 */ ( self: Stream, @@ -10078,7 +11088,8 @@ export const takeWhileEffect: { /** * Drops the first `n` elements from this stream. * - * @example + * **Example** (Dropping values from the left) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -10094,14 +11105,15 @@ export const takeWhileEffect: { * // Output: [ 3, 4, 5 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ export const drop: { /** * Drops the first `n` elements from this stream. * - * @example + * **Example** (Dropping values from the left) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -10117,14 +11129,15 @@ export const drop: { * // Output: [ 3, 4, 5 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (n: number): (self: Stream) => Stream /** * Drops the first `n` elements from this stream. * - * @example + * **Example** (Dropping values from the left) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -10140,8 +11153,8 @@ export const drop: { * // Output: [ 3, 4, 5 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (self: Stream, n: number): Stream } = dual( @@ -10166,7 +11179,8 @@ export const drop: { * Drops elements until the specified predicate evaluates to `true`, then drops * that matching element. * - * @example + * **Example** (Dropping until a predicate matches) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -10179,15 +11193,16 @@ export const drop: { * }) * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ export const dropUntil: { /** * Drops elements until the specified predicate evaluates to `true`, then drops * that matching element. * - * @example + * **Example** (Dropping until a predicate matches) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -10200,15 +11215,16 @@ export const dropUntil: { * }) * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (predicate: (a: NoInfer, index: number) => boolean): (self: Stream) => Stream /** * Drops elements until the specified predicate evaluates to `true`, then drops * that matching element. * - * @example + * **Example** (Dropping until a predicate matches) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -10221,8 +11237,8 @@ export const dropUntil: { * }) * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ ( self: Stream, @@ -10237,9 +11253,13 @@ export const dropUntil: { * Drops all elements of the stream until the specified effectful predicate * evaluates to `true`. * - * The first element that satisfies the predicate is also dropped. + * **When to use** + * + * Use when dropping the leading prefix requires an Effect or service and the + * first matching element should also be dropped. + * + * **Example** (Dropping until an effectful predicate matches) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -10255,17 +11275,21 @@ export const dropUntil: { * // Output: [ 4, 5 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ export const dropUntilEffect: { /** * Drops all elements of the stream until the specified effectful predicate * evaluates to `true`. * - * The first element that satisfies the predicate is also dropped. + * **When to use** + * + * Use when dropping the leading prefix requires an Effect or service and the + * first matching element should also be dropped. + * + * **Example** (Dropping until an effectful predicate matches) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -10281,8 +11305,8 @@ export const dropUntilEffect: { * // Output: [ 4, 5 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ ( predicate: (a: NoInfer, index: number) => Effect.Effect @@ -10291,9 +11315,13 @@ export const dropUntilEffect: { * Drops all elements of the stream until the specified effectful predicate * evaluates to `true`. * - * The first element that satisfies the predicate is also dropped. + * **When to use** + * + * Use when dropping the leading prefix requires an Effect or service and the + * first matching element should also be dropped. + * + * **Example** (Dropping until an effectful predicate matches) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -10309,8 +11337,8 @@ export const dropUntilEffect: { * // Output: [ 4, 5 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ ( self: Stream, @@ -10331,7 +11359,8 @@ export const dropUntilEffect: { /** * Drops elements from the stream while the specified predicate evaluates to `true`. * - * @example + * **Example** (Dropping while a predicate holds) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -10347,14 +11376,15 @@ export const dropUntilEffect: { * // Output: [ 3, 4, 5 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ export const dropWhile: { /** * Drops elements from the stream while the specified predicate evaluates to `true`. * - * @example + * **Example** (Dropping while a predicate holds) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -10370,14 +11400,15 @@ export const dropWhile: { * // Output: [ 3, 4, 5 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (predicate: (a: NoInfer, index: number) => boolean): (self: Stream) => Stream /** * Drops elements from the stream while the specified predicate evaluates to `true`. * - * @example + * **Example** (Dropping while a predicate holds) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -10393,8 +11424,8 @@ export const dropWhile: { * // Output: [ 3, 4, 5 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ ( self: Stream, @@ -10420,22 +11451,67 @@ export const dropWhile: { /** * Drops elements while the filter succeeds. * + * **When to use** + * + * Use when you need to remove a leading stream prefix based on a synchronous + * `Filter` result while preserving the remaining original stream elements. + * + * **Details** + * + * `Result.succeed` drops the current element. The first `Result.fail` stops + * dropping, emits that original element, and the rest of the source stream is + * emitted without further filtering. + * + * @see {@link dropWhile} for boolean predicate prefix dropping + * @see {@link takeWhileFilter} for keeping the accepted prefix as filter success values + * @see {@link dropWhileEffect} for effectful predicate prefix dropping + * + * @category filtering * @since 4.0.0 - * @category Filtering */ export const dropWhileFilter: { /** * Drops elements while the filter succeeds. * + * **When to use** + * + * Use when you need to remove a leading stream prefix based on a synchronous + * `Filter` result while preserving the remaining original stream elements. + * + * **Details** + * + * `Result.succeed` drops the current element. The first `Result.fail` stops + * dropping, emits that original element, and the rest of the source stream is + * emitted without further filtering. + * + * @see {@link dropWhile} for boolean predicate prefix dropping + * @see {@link takeWhileFilter} for keeping the accepted prefix as filter success values + * @see {@link dropWhileEffect} for effectful predicate prefix dropping + * + * @category filtering * @since 4.0.0 - * @category Filtering */ (filter: Filter.Filter, B, X>): (self: Stream) => Stream /** * Drops elements while the filter succeeds. * + * **When to use** + * + * Use when you need to remove a leading stream prefix based on a synchronous + * `Filter` result while preserving the remaining original stream elements. + * + * **Details** + * + * `Result.succeed` drops the current element. The first `Result.fail` stops + * dropping, emits that original element, and the rest of the source stream is + * emitted without further filtering. + * + * @see {@link dropWhile} for boolean predicate prefix dropping + * @see {@link takeWhileFilter} for keeping the accepted prefix as filter success values + * @see {@link dropWhileEffect} for effectful predicate prefix dropping + * + * @category filtering * @since 4.0.0 - * @category Filtering */ (self: Stream, filter: Filter.Filter, B, X>): Stream } = dual(2, ( @@ -10457,7 +11533,8 @@ export const dropWhileFilter: { /** * Drops elements while the specified effectful predicate evaluates to `true`. * - * @example + * **Example** (Effectfully dropping while a predicate holds) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -10473,14 +11550,15 @@ export const dropWhileFilter: { * // Output: [ 3, 4, 5 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ export const dropWhileEffect: { /** * Drops elements while the specified effectful predicate evaluates to `true`. * - * @example + * **Example** (Effectfully dropping while a predicate holds) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -10496,8 +11574,8 @@ export const dropWhileEffect: { * // Output: [ 3, 4, 5 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ ( predicate: (a: NoInfer, index: number) => Effect.Effect @@ -10505,7 +11583,8 @@ export const dropWhileEffect: { /** * Drops elements while the specified effectful predicate evaluates to `true`. * - * @example + * **Example** (Effectfully dropping while a predicate holds) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -10521,8 +11600,8 @@ export const dropWhileEffect: { * // Output: [ 3, 4, 5 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ ( self: Stream, @@ -10555,9 +11634,12 @@ export const dropWhileEffect: { /** * Drops the last specified number of elements from this stream. * + * **Details** + * * Keeps the last `n` elements in memory to drop them on completion. * - * @example + * **Example** (Dropping values from the right) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -10573,16 +11655,19 @@ export const dropWhileEffect: { * // Output: [ 1, 2, 3 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ export const dropRight: { /** * Drops the last specified number of elements from this stream. * + * **Details** + * * Keeps the last `n` elements in memory to drop them on completion. * - * @example + * **Example** (Dropping values from the right) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -10598,16 +11683,19 @@ export const dropRight: { * // Output: [ 1, 2, 3 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (n: number): (self: Stream) => Stream /** * Drops the last specified number of elements from this stream. * + * **Details** + * * Keeps the last `n` elements in memory to drop them on completion. * - * @example + * **Example** (Dropping values from the right) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -10623,8 +11711,8 @@ export const dropRight: { * // Output: [ 1, 2, 3 ] * ``` * + * @category filtering * @since 2.0.0 - * @category Filtering */ (self: Stream, n: number): Stream } = dual( @@ -10636,9 +11724,12 @@ export const dropRight: { const list = MutableList.make() const emit: Pull.Pull, E> = Effect.flatMap(pull, (arr) => { @@ -10672,7 +11763,8 @@ export const dropRight: { /** * Exposes the underlying chunks as a stream of non-empty arrays. * - * @example + * **Example** (Exposing stream chunks) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -10689,8 +11781,8 @@ export const dropRight: { * // Output: [ [ 1, 2 ], [ 3, 4 ] ] * ``` * + * @category grouping * @since 2.0.0 - * @category Grouping */ export const chunks = (self: Stream): Stream, E, R> => self.channel.pipe( @@ -10699,11 +11791,14 @@ export const chunks = (self: Stream): Stream(self: Stream): Stream(self: Stream) => Stream /** - * Re-chunks the stream into arrays of the specified size, preserving element order. + * Groups the stream into arrays of the specified size, preserving element order. + * + * **Details** * * The size is clamped to at least 1. * - * @example + * **Example** (Rechunking stream elements) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -10772,8 +11873,8 @@ export const rechunk: { * // Output: [ [ 1, 2 ], [ 3, 4 ], [ 5 ] ] * ``` * + * @category grouping * @since 2.0.0 - * @category Grouping */ (self: Stream, size: number): Stream } = dual(2, (self: Stream, target: number): Stream => { @@ -10781,11 +11882,14 @@ export const rechunk: { return transformPull(self, (pull, _scope) => Effect.sync(() => { let chunk = Arr.empty() as Arr.NonEmptyArray let index = 0 @@ -10850,9 +11954,10 @@ export const rechunk: { /** * Emits a sliding window of `n` elements. * - * @example + * **Example** (Emitting sliding windows) + * * ```ts - * import { Console, Effect, Stream, pipe } from "effect" + * import { Console, Effect, pipe, Stream } from "effect" * * Effect.gen(function*() { * const result = yield* pipe( @@ -10865,16 +11970,17 @@ export const rechunk: { * // Output: [ [1, 2], [2, 3], [3, 4], [4, 5] ] * ``` * + * @category grouping * @since 2.0.0 - * @category Grouping */ export const sliding: { /** * Emits a sliding window of `n` elements. * - * @example + * **Example** (Emitting sliding windows) + * * ```ts - * import { Console, Effect, Stream, pipe } from "effect" + * import { Console, Effect, pipe, Stream } from "effect" * * Effect.gen(function*() { * const result = yield* pipe( @@ -10887,16 +11993,17 @@ export const sliding: { * // Output: [ [1, 2], [2, 3], [3, 4], [4, 5] ] * ``` * + * @category grouping * @since 2.0.0 - * @category Grouping */ (chunkSize: number): (self: Stream) => Stream, E, R> /** * Emits a sliding window of `n` elements. * - * @example + * **Example** (Emitting sliding windows) + * * ```ts - * import { Console, Effect, Stream, pipe } from "effect" + * import { Console, Effect, pipe, Stream } from "effect" * * Effect.gen(function*() { * const result = yield* pipe( @@ -10909,8 +12016,8 @@ export const sliding: { * // Output: [ [1, 2], [2, 3], [3, 4], [4, 5] ] * ``` * + * @category grouping * @since 2.0.0 - * @category Grouping */ (self: Stream, chunkSize: number): Stream, E, R> } = dual( @@ -10922,6 +12029,8 @@ export const sliding: { /** * Emits sliding windows of `chunkSize` elements, advancing by `stepSize`. * + * **Example** (Emitting sliding windows with a step size) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -10937,13 +12046,15 @@ export const sliding: { * // Output: [ [ 1, 2, 3 ], [ 3, 4, 5 ] ] * ``` * + * @category grouping * @since 2.0.0 - * @category Grouping */ export const slidingSize: { /** * Emits sliding windows of `chunkSize` elements, advancing by `stepSize`. * + * **Example** (Emitting sliding windows with a step size) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -10959,13 +12070,15 @@ export const slidingSize: { * // Output: [ [ 1, 2, 3 ], [ 3, 4, 5 ] ] * ``` * + * @category grouping * @since 2.0.0 - * @category Grouping */ (chunkSize: number, stepSize: number): (self: Stream) => Stream, E, R> /** * Emits sliding windows of `chunkSize` elements, advancing by `stepSize`. * + * **Example** (Emitting sliding windows with a step size) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -10981,8 +12094,8 @@ export const slidingSize: { * // Output: [ [ 1, 2, 3 ], [ 3, 4, 5 ] ] * ``` * + * @category grouping * @since 2.0.0 - * @category Grouping */ (self: Stream, chunkSize: number, stepSize: number): Stream, E, R> } = dual( @@ -10994,6 +12107,8 @@ export const slidingSize: { const list = MutableList.make() let emitted = false @@ -11052,9 +12167,12 @@ export const slidingSize: { /** * Splits the stream into non-empty groups whenever the predicate matches. * + * **Details** + * * Matching elements act as delimiters and are not included in the output. * - * @example + * **Example** (Splitting on matching values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -11070,16 +12188,19 @@ export const slidingSize: { * // Output: [ [1, 2, 3], [5, 6, 7], [9] ] * ``` * + * @category grouping * @since 2.0.0 - * @category Grouping */ export const split: { /** * Splits the stream into non-empty groups whenever the predicate matches. * + * **Details** + * * Matching elements act as delimiters and are not included in the output. * - * @example + * **Example** (Splitting on matching values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -11095,16 +12216,19 @@ export const split: { * // Output: [ [1, 2, 3], [5, 6, 7], [9] ] * ``` * + * @category grouping * @since 2.0.0 - * @category Grouping */ (refinement: Refinement, B>): (self: Stream) => Stream>, E, R> /** * Splits the stream into non-empty groups whenever the predicate matches. * + * **Details** + * * Matching elements act as delimiters and are not included in the output. * - * @example + * **Example** (Splitting on matching values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -11120,16 +12244,19 @@ export const split: { * // Output: [ [1, 2, 3], [5, 6, 7], [9] ] * ``` * + * @category grouping * @since 2.0.0 - * @category Grouping */ (predicate: Predicate>): (self: Stream) => Stream, E, R> /** * Splits the stream into non-empty groups whenever the predicate matches. * + * **Details** + * * Matching elements act as delimiters and are not included in the output. * - * @example + * **Example** (Splitting on matching values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -11145,16 +12272,19 @@ export const split: { * // Output: [ [1, 2, 3], [5, 6, 7], [9] ] * ``` * + * @category grouping * @since 2.0.0 - * @category Grouping */ (self: Stream, refinement: Refinement): Stream>, E, R> /** * Splits the stream into non-empty groups whenever the predicate matches. * + * **Details** + * * Matching elements act as delimiters and are not included in the output. * - * @example + * **Example** (Splitting on matching values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -11170,8 +12300,8 @@ export const split: { * // Output: [ [1, 2, 3], [5, 6, 7], [9] ] * ``` * + * @category grouping * @since 2.0.0 - * @category Grouping */ (self: Stream, predicate: Predicate): Stream, E, R> } = dual(2, ( @@ -11182,9 +12312,12 @@ export const split: { const out = Arr.empty>() for (let i = 0; i < arr.length; i++) { @@ -11225,10 +12358,13 @@ export const split: { * Combines elements from this stream and the specified stream by repeatedly * applying a stateful function that can pull from either side. * + * **Details** + * * Where possible, prefer `Stream.combineArray` for a more efficient * implementation. * - * @example + * **Example** (Combining streams with state) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -11251,18 +12387,21 @@ export const split: { * // Output: [ "L:A", "R:1", "L:B", "R:2", "L:C", "R:3" ] * ``` * + * @category merging * @since 2.0.0 - * @category Merging */ export const combine: { /** * Combines elements from this stream and the specified stream by repeatedly * applying a stateful function that can pull from either side. * + * **Details** + * * Where possible, prefer `Stream.combineArray` for a more efficient * implementation. * - * @example + * **Example** (Combining streams with state) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -11285,8 +12424,8 @@ export const combine: { * // Output: [ "L:A", "R:1", "L:B", "R:2", "L:C", "R:3" ] * ``` * + * @category merging * @since 2.0.0 - * @category Merging */ ( that: Stream, @@ -11301,10 +12440,13 @@ export const combine: { * Combines elements from this stream and the specified stream by repeatedly * applying a stateful function that can pull from either side. * + * **Details** + * * Where possible, prefer `Stream.combineArray` for a more efficient * implementation. * - * @example + * **Example** (Combining streams with state) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -11327,8 +12469,8 @@ export const combine: { * // Output: [ "L:A", "R:1", "L:B", "R:2", "L:C", "R:3" ] * ``` * + * @category merging * @since 2.0.0 - * @category Merging */ ( self: Stream, @@ -11361,19 +12503,21 @@ export const combine: { )) /** - * Combines the arrays (chunks) from this stream and the specified stream by - * repeatedly applying the function `f` to extract an array using both sides and - * conceptually "offer" it to the destination stream. `f` can maintain some - * internal state to control the combining process, with the initial state - * being specified by `s`. + * Combines two streams chunk-by-chunk with a stateful pull function. * - * **Previously Known As** + * **When to use** * - * This API replaces the following from Effect 3.x: + * Use to coordinate pulling chunks from two streams when each emitted chunk + * depends on both sides and local state. * - * - `Stream.combineChunks` + * **Details** + * + * The combining function receives the current state and pull functions for the + * left and right streams. It returns the next non-empty chunk together with the + * next state. + * + * **Example** (Combining stream chunks with state) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -11398,24 +12542,26 @@ export const combine: { * // Output: [ 1, 2, 10, 20 ] * ``` * - * @since 2.0.0 - * @category Sequencing + * @category sequencing + * @since 4.0.0 */ export const combineArray: { /** - * Combines the arrays (chunks) from this stream and the specified stream by - * repeatedly applying the function `f` to extract an array using both sides and - * conceptually "offer" it to the destination stream. `f` can maintain some - * internal state to control the combining process, with the initial state - * being specified by `s`. + * Combines two streams chunk-by-chunk with a stateful pull function. * - * **Previously Known As** + * **When to use** * - * This API replaces the following from Effect 3.x: + * Use to coordinate pulling chunks from two streams when each emitted chunk + * depends on both sides and local state. * - * - `Stream.combineChunks` + * **Details** + * + * The combining function receives the current state and pull functions for the + * left and right streams. It returns the next non-empty chunk together with the + * next state. + * + * **Example** (Combining stream chunks with state) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -11440,8 +12586,8 @@ export const combineArray: { * // Output: [ 1, 2, 10, 20 ] * ``` * - * @since 2.0.0 - * @category Sequencing + * @category sequencing + * @since 4.0.0 */ ( that: Stream, @@ -11453,19 +12599,21 @@ export const combineArray: { ) => Effect.Effect, S], E3, R3> ): (self: Stream) => Stream, R2 | R3 | R> /** - * Combines the arrays (chunks) from this stream and the specified stream by - * repeatedly applying the function `f` to extract an array using both sides and - * conceptually "offer" it to the destination stream. `f` can maintain some - * internal state to control the combining process, with the initial state - * being specified by `s`. + * Combines two streams chunk-by-chunk with a stateful pull function. * - * **Previously Known As** + * **When to use** * - * This API replaces the following from Effect 3.x: + * Use to coordinate pulling chunks from two streams when each emitted chunk + * depends on both sides and local state. * - * - `Stream.combineChunks` + * **Details** + * + * The combining function receives the current state and pull functions for the + * left and right streams. It returns the next non-empty chunk together with the + * next state. + * + * **Example** (Combining stream chunks with state) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -11490,8 +12638,8 @@ export const combineArray: { * // Output: [ 1, 2, 10, 20 ] * ``` * - * @since 2.0.0 - * @category Sequencing + * @category sequencing + * @since 4.0.0 */ ( self: Stream, @@ -11521,9 +12669,10 @@ export const combineArray: { ))) /** - * Statefully maps elements, emitting zero or more outputs per input. + * Maps elements statefully, emitting zero or more outputs per input. + * + * **Example** (Statefully mapping stream values) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -11543,14 +12692,15 @@ export const combineArray: { * // Output: [ 0, 1, 3, 6, 10, 15, 21 ] * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ export const mapAccum: { /** - * Statefully maps elements, emitting zero or more outputs per input. + * Maps elements statefully, emitting zero or more outputs per input. + * + * **Example** (Statefully mapping stream values) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -11570,8 +12720,8 @@ export const mapAccum: { * // Output: [ 0, 1, 3, 6, 10, 15, 21 ] * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ ( initial: LazyArg, @@ -11581,9 +12731,10 @@ export const mapAccum: { } ): (self: Stream) => Stream /** - * Statefully maps elements, emitting zero or more outputs per input. + * Maps elements statefully, emitting zero or more outputs per input. + * + * **Example** (Statefully mapping stream values) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -11603,8 +12754,8 @@ export const mapAccum: { * // Output: [ 0, 1, 3, 6, 10, 15, 21 ] * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ ( self: Stream, @@ -11627,9 +12778,10 @@ export const mapAccum: { initial, (state, arr) => { const acc = Arr.empty() for (let index = 0; index < arr.length; index++) { @@ -11671,11 +12823,14 @@ export const mapAccum: { ))) /** - * Statefully maps over non-empty chunk arrays, emitting zero or more values per chunk. + * Maps over non-empty chunk arrays statefully, emitting zero or more values per chunk. + * + * **Details** * * The mapping function runs once per chunk and the state is threaded across chunks. * - * @example + * **Example** (Statefully mapping stream chunks) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -11695,16 +12850,19 @@ export const mapAccum: { * // Output: [ 3, 10, 21 ] * ``` * - * @since 2.0.0 - * @category Mapping + * @category mapping + * @since 4.0.0 */ export const mapAccumArray: { /** - * Statefully maps over non-empty chunk arrays, emitting zero or more values per chunk. + * Maps over non-empty chunk arrays statefully, emitting zero or more values per chunk. + * + * **Details** * * The mapping function runs once per chunk and the state is threaded across chunks. * - * @example + * **Example** (Statefully mapping stream chunks) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -11724,8 +12882,8 @@ export const mapAccumArray: { * // Output: [ 3, 10, 21 ] * ``` * - * @since 2.0.0 - * @category Mapping + * @category mapping + * @since 4.0.0 */ ( initial: LazyArg, @@ -11735,11 +12893,14 @@ export const mapAccumArray: { } ): (self: Stream) => Stream /** - * Statefully maps over non-empty chunk arrays, emitting zero or more values per chunk. + * Maps over non-empty chunk arrays statefully, emitting zero or more values per chunk. + * + * **Details** * * The mapping function runs once per chunk and the state is threaded across chunks. * - * @example + * **Example** (Statefully mapping stream chunks) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -11759,8 +12920,8 @@ export const mapAccumArray: { * // Output: [ 3, 10, 21 ] * ``` * - * @since 2.0.0 - * @category Mapping + * @category mapping + * @since 4.0.0 */ ( self: Stream, @@ -11799,9 +12960,22 @@ export const mapAccumArray: { const emptyArr = Arr.empty() /** - * Statefully and effectfully maps over the elements of this stream to produce new elements. + * Maps each element statefully and effectfully, emitting zero or more output + * values per input. + * + * **When to use** + * + * Use when stateful element mapping needs Effects or can fail while emitting + * zero or more values per input element. + * + * **Details** + * + * The mapping effect receives the current state and element, then returns the + * next state plus the values to emit. The state is threaded through the + * stream. + * + * **Example** (Effectfully mapping stream values with state) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -11820,14 +12994,27 @@ const emptyArr = Arr.empty() * // Output: [ 1, 2, 3 ] * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ export const mapAccumEffect: { /** - * Statefully and effectfully maps over the elements of this stream to produce new elements. + * Maps each element statefully and effectfully, emitting zero or more output + * values per input. + * + * **When to use** + * + * Use when stateful element mapping needs Effects or can fail while emitting + * zero or more values per input element. + * + * **Details** + * + * The mapping effect receives the current state and element, then returns the + * next state plus the values to emit. The state is threaded through the + * stream. + * + * **Example** (Effectfully mapping stream values with state) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -11846,8 +13033,8 @@ export const mapAccumEffect: { * // Output: [ 1, 2, 3 ] * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ ( initial: LazyArg, @@ -11857,9 +13044,22 @@ export const mapAccumEffect: { } ): (self: Stream) => Stream /** - * Statefully and effectfully maps over the elements of this stream to produce new elements. + * Maps each element statefully and effectfully, emitting zero or more output + * values per input. + * + * **When to use** + * + * Use when stateful element mapping needs Effects or can fail while emitting + * zero or more values per input element. + * + * **Details** + * + * The mapping effect receives the current state and element, then returns the + * next state plus the values to emit. The state is threaded through the + * stream. + * + * **Example** (Effectfully mapping stream values with state) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -11878,8 +13078,8 @@ export const mapAccumEffect: { * // Output: [ 1, 2, 3 ] * ``` * + * @category mapping * @since 2.0.0 - * @category Mapping */ ( self: Stream, @@ -11907,9 +13107,22 @@ export const mapAccumEffect: { ([state, values]) => [ state, Arr.isReadonlyArrayNonEmpty(values) ? Arr.of(values) : Arr.empty>() ] @@ -11947,9 +13160,21 @@ export const mapAccumEffect: { )) /** - * Statefully and effectfully maps over chunks of this stream to emit new values. + * Maps each non-empty input chunk statefully and effectfully, emitting zero or + * more output values per chunk. + * + * **When to use** + * + * Use when stateful mapping should process each emitted non-empty chunk with an + * Effect instead of each element separately. + * + * **Details** + * + * The mapping effect receives the current state and chunk, then returns the + * next state plus the values to emit. The state is threaded across chunks. + * + * **Example** (Effectfully mapping stream chunks with state) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -11971,14 +13196,26 @@ export const mapAccumEffect: { * // Output: [ 3, 10 ] * ``` * - * @since 2.0.0 - * @category Mapping + * @category mapping + * @since 4.0.0 */ export const mapAccumArrayEffect: { /** - * Statefully and effectfully maps over chunks of this stream to emit new values. + * Maps each non-empty input chunk statefully and effectfully, emitting zero or + * more output values per chunk. + * + * **When to use** + * + * Use when stateful mapping should process each emitted non-empty chunk with an + * Effect instead of each element separately. + * + * **Details** + * + * The mapping effect receives the current state and chunk, then returns the + * next state plus the values to emit. The state is threaded across chunks. + * + * **Example** (Effectfully mapping stream chunks with state) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -12000,8 +13237,8 @@ export const mapAccumArrayEffect: { * // Output: [ 3, 10 ] * ``` * - * @since 2.0.0 - * @category Mapping + * @category mapping + * @since 4.0.0 */ ( initial: LazyArg, @@ -12011,9 +13248,21 @@ export const mapAccumArrayEffect: { } ): (self: Stream) => Stream /** - * Statefully and effectfully maps over chunks of this stream to emit new values. + * Maps each non-empty input chunk statefully and effectfully, emitting zero or + * more output values per chunk. + * + * **When to use** + * + * Use when stateful mapping should process each emitted non-empty chunk with an + * Effect instead of each element separately. + * + * **Details** + * + * The mapping effect receives the current state and chunk, then returns the + * next state plus the values to emit. The state is threaded across chunks. + * + * **Example** (Effectfully mapping stream chunks with state) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -12035,8 +13284,8 @@ export const mapAccumArrayEffect: { * // Output: [ 3, 10 ] * ``` * - * @since 2.0.0 - * @category Mapping + * @category mapping + * @since 4.0.0 */ ( self: Stream, @@ -12080,7 +13329,8 @@ export const mapAccumArrayEffect: { /** * Accumulates state across the stream, emitting the initial state and each updated state. * - * @example + * **Example** (Scanning stream state) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -12096,14 +13346,15 @@ export const mapAccumArrayEffect: { * // Output: [ 0, 1, 3, 6 ] * ``` * - * @since 2.0.0 * @category Accumulation + * @since 2.0.0 */ export const scan: { /** * Accumulates state across the stream, emitting the initial state and each updated state. * - * @example + * **Example** (Scanning stream state) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -12119,14 +13370,15 @@ export const scan: { * // Output: [ 0, 1, 3, 6 ] * ``` * - * @since 2.0.0 * @category Accumulation + * @since 2.0.0 */ (initial: S, f: (s: S, a: A) => S): (self: Stream) => Stream /** * Accumulates state across the stream, emitting the initial state and each updated state. * - * @example + * **Example** (Scanning stream state) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -12142,8 +13394,8 @@ export const scan: { * // Output: [ 0, 1, 3, 6 ] * ``` * - * @since 2.0.0 * @category Accumulation + * @since 2.0.0 */ (self: Stream, initial: S, f: (s: S, a: A) => S): Stream } = dual(3, ( @@ -12157,7 +13409,8 @@ export const scan: { const states = Arr.empty() as Arr.NonEmptyArray if (isFirst) { @@ -12190,9 +13443,10 @@ export const scan: { })) /** - * Effectfully accumulates state and emits the initial state plus each accumulated state. + * Accumulates state effectfully and emits the initial state plus each accumulated state. + * + * **Example** (Effectfully scanning stream state) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -12206,14 +13460,15 @@ export const scan: { * }) * ``` * - * @since 2.0.0 * @category Accumulation + * @since 2.0.0 */ export const scanEffect: { /** - * Effectfully accumulates state and emits the initial state plus each accumulated state. + * Accumulates state effectfully and emits the initial state plus each accumulated state. + * + * **Example** (Effectfully scanning stream state) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -12227,14 +13482,15 @@ export const scanEffect: { * }) * ``` * - * @since 2.0.0 * @category Accumulation + * @since 2.0.0 */ (initial: S, f: (s: S, a: A) => Effect.Effect): (self: Stream) => Stream /** - * Effectfully accumulates state and emits the initial state plus each accumulated state. + * Accumulates state effectfully and emits the initial state plus each accumulated state. + * + * **Example** (Effectfully scanning stream state) * - * @example * ```ts * import { Console, Effect, Stream } from "effect" * @@ -12248,8 +13504,8 @@ export const scanEffect: { * }) * ``` * - * @since 2.0.0 * @category Accumulation + * @since 2.0.0 */ ( self: Stream, @@ -12271,7 +13527,8 @@ export const scanEffect: { /** * Drops earlier elements within the debounce window and emits only the latest element after the pause. * - * @example + * **Example** (Debouncing stream elements) + * * ```ts * import { Console, Duration, Effect, Stream } from "effect" * @@ -12288,14 +13545,15 @@ export const scanEffect: { * }) * ``` * + * @category rate limiting * @since 2.0.0 - * @category Rate Limiting */ export const debounce: { /** * Drops earlier elements within the debounce window and emits only the latest element after the pause. * - * @example + * **Example** (Debouncing stream elements) + * * ```ts * import { Console, Duration, Effect, Stream } from "effect" * @@ -12312,14 +13570,15 @@ export const debounce: { * }) * ``` * + * @category rate limiting * @since 2.0.0 - * @category Rate Limiting */ (duration: Duration.Input): (self: Stream) => Stream /** * Drops earlier elements within the debounce window and emits only the latest element after the pause. * - * @example + * **Example** (Debouncing stream elements) + * * ```ts * import { Console, Duration, Effect, Stream } from "effect" * @@ -12336,8 +13595,8 @@ export const debounce: { * }) * ``` * + * @category rate limiting * @since 2.0.0 - * @category Rate Limiting */ (self: Stream, duration: Duration.Input): Stream } = dual( @@ -12411,10 +13670,16 @@ export const debounce: { ) /** - * Delays the arrays of this stream according to the given bandwidth - * parameters using the token bucket algorithm. Allows for burst processing by - * allowing the bucket to accumulate tokens up to a `units + burst` threshold. - * The weight of each array is determined by the effectful `cost` function. + * Rate-limits stream chunks with an effectful cost function. + * + * **When to use** + * + * Use to throttle chunks when computing each chunk's cost requires an effect. + * + * **Details** + * + * Uses a token bucket. The bucket can accumulate up to `units + burst` tokens, + * and each chunk consumes the cost returned by the effectful `cost` function. * * If using the "enforce" strategy, arrays that do not meet the bandwidth * constraints are dropped. If using the "shape" strategy, arrays are delayed @@ -12422,7 +13687,8 @@ export const debounce: { * * Defaults to the "shape" strategy. * - * @example + * **Example** (Throttling stream chunks effectfully) + * * ```ts * import { Console, Effect, Schedule, Stream } from "effect" * @@ -12443,15 +13709,21 @@ export const debounce: { * // Output: [0, 1, 2, 3, 4, 5] * ``` * + * @category rate limiting * @since 2.0.0 - * @category Rate Limiting */ export const throttleEffect: { /** - * Delays the arrays of this stream according to the given bandwidth - * parameters using the token bucket algorithm. Allows for burst processing by - * allowing the bucket to accumulate tokens up to a `units + burst` threshold. - * The weight of each array is determined by the effectful `cost` function. + * Rate-limits stream chunks with an effectful cost function. + * + * **When to use** + * + * Use to throttle chunks when computing each chunk's cost requires an effect. + * + * **Details** + * + * Uses a token bucket. The bucket can accumulate up to `units + burst` tokens, + * and each chunk consumes the cost returned by the effectful `cost` function. * * If using the "enforce" strategy, arrays that do not meet the bandwidth * constraints are dropped. If using the "shape" strategy, arrays are delayed @@ -12459,7 +13731,8 @@ export const throttleEffect: { * * Defaults to the "shape" strategy. * - * @example + * **Example** (Throttling stream chunks effectfully) + * * ```ts * import { Console, Effect, Schedule, Stream } from "effect" * @@ -12480,8 +13753,8 @@ export const throttleEffect: { * // Output: [0, 1, 2, 3, 4, 5] * ``` * + * @category rate limiting * @since 2.0.0 - * @category Rate Limiting */ ( options: { @@ -12493,10 +13766,16 @@ export const throttleEffect: { } ): (self: Stream) => Stream /** - * Delays the arrays of this stream according to the given bandwidth - * parameters using the token bucket algorithm. Allows for burst processing by - * allowing the bucket to accumulate tokens up to a `units + burst` threshold. - * The weight of each array is determined by the effectful `cost` function. + * Rate-limits stream chunks with an effectful cost function. + * + * **When to use** + * + * Use to throttle chunks when computing each chunk's cost requires an effect. + * + * **Details** + * + * Uses a token bucket. The bucket can accumulate up to `units + burst` tokens, + * and each chunk consumes the cost returned by the effectful `cost` function. * * If using the "enforce" strategy, arrays that do not meet the bandwidth * constraints are dropped. If using the "shape" strategy, arrays are delayed @@ -12504,7 +13783,8 @@ export const throttleEffect: { * * Defaults to the "shape" strategy. * - * @example + * **Example** (Throttling stream chunks effectfully) + * * ```ts * import { Console, Effect, Schedule, Stream } from "effect" * @@ -12525,8 +13805,8 @@ export const throttleEffect: { * // Output: [0, 1, 2, 3, 4, 5] * ``` * + * @category rate limiting * @since 2.0.0 - * @category Rate Limiting */ ( self: Stream, @@ -12642,9 +13922,16 @@ const throttleShapeEffect = ( })) /** - * Delays the arrays of this stream using a token bucket and a per-array cost. - * Allows bursts by letting the bucket accumulate up to a `units + burst` - * threshold. The weight of each array is determined by the `cost` function. + * Rate-limits stream chunks with a synchronous cost function. + * + * **When to use** + * + * Use to throttle chunks when each chunk's cost can be computed synchronously. + * + * **Details** + * + * Uses a token bucket. The bucket can accumulate up to `units + burst` tokens, + * and each chunk consumes the cost returned by `cost`. * * If using the "enforce" strategy, arrays that do not meet the bandwidth * constraints are dropped. If using the "shape" strategy, arrays are delayed @@ -12652,7 +13939,8 @@ const throttleShapeEffect = ( * * Defaults to the "shape" strategy. * - * @example + * **Example** (Throttling stream chunks) + * * ```ts * import { Console, Effect, Schedule, Stream } from "effect" * @@ -12673,14 +13961,21 @@ const throttleShapeEffect = ( * }) * ``` * + * @category rate limiting * @since 2.0.0 - * @category Rate Limiting */ export const throttle: { /** - * Delays the arrays of this stream using a token bucket and a per-array cost. - * Allows bursts by letting the bucket accumulate up to a `units + burst` - * threshold. The weight of each array is determined by the `cost` function. + * Rate-limits stream chunks with a synchronous cost function. + * + * **When to use** + * + * Use to throttle chunks when each chunk's cost can be computed synchronously. + * + * **Details** + * + * Uses a token bucket. The bucket can accumulate up to `units + burst` tokens, + * and each chunk consumes the cost returned by `cost`. * * If using the "enforce" strategy, arrays that do not meet the bandwidth * constraints are dropped. If using the "shape" strategy, arrays are delayed @@ -12688,7 +13983,8 @@ export const throttle: { * * Defaults to the "shape" strategy. * - * @example + * **Example** (Throttling stream chunks) + * * ```ts * import { Console, Effect, Schedule, Stream } from "effect" * @@ -12709,8 +14005,8 @@ export const throttle: { * }) * ``` * + * @category rate limiting * @since 2.0.0 - * @category Rate Limiting */ ( options: { @@ -12722,9 +14018,16 @@ export const throttle: { } ): (self: Stream) => Stream /** - * Delays the arrays of this stream using a token bucket and a per-array cost. - * Allows bursts by letting the bucket accumulate up to a `units + burst` - * threshold. The weight of each array is determined by the `cost` function. + * Rate-limits stream chunks with a synchronous cost function. + * + * **When to use** + * + * Use to throttle chunks when each chunk's cost can be computed synchronously. + * + * **Details** + * + * Uses a token bucket. The bucket can accumulate up to `units + burst` tokens, + * and each chunk consumes the cost returned by `cost`. * * If using the "enforce" strategy, arrays that do not meet the bandwidth * constraints are dropped. If using the "shape" strategy, arrays are delayed @@ -12732,7 +14035,8 @@ export const throttle: { * * Defaults to the "shape" strategy. * - * @example + * **Example** (Throttling stream chunks) + * * ```ts * import { Console, Effect, Schedule, Stream } from "effect" * @@ -12753,8 +14057,8 @@ export const throttle: { * }) * ``` * + * @category rate limiting * @since 2.0.0 - * @category Rate Limiting */ ( self: Stream, @@ -12787,9 +14091,12 @@ export const throttle: { /** * Partitions the stream into non-empty arrays of the specified size. * + * **Details** + * * The final array may be smaller if there are not enough elements to fill it. * - * @example + * **Example** (Grouping elements by size) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -12805,16 +14112,19 @@ export const throttle: { * // Output: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8 ] ] * ``` * + * @category grouping * @since 2.0.0 - * @category Grouping */ export const grouped: { /** * Partitions the stream into non-empty arrays of the specified size. * + * **Details** + * * The final array may be smaller if there are not enough elements to fill it. * - * @example + * **Example** (Grouping elements by size) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -12830,16 +14140,19 @@ export const grouped: { * // Output: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8 ] ] * ``` * + * @category grouping * @since 2.0.0 - * @category Grouping */ (n: number): (self: Stream) => Stream, E, R> /** * Partitions the stream into non-empty arrays of the specified size. * + * **Details** + * * The final array may be smaller if there are not enough elements to fill it. * - * @example + * **Example** (Grouping elements by size) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -12855,8 +14168,8 @@ export const grouped: { * // Output: [ [ 1, 2, 3 ], [ 4, 5, 6 ], [ 7, 8 ] ] * ``` * + * @category grouping * @since 2.0.0 - * @category Grouping */ (self: Stream, n: number): Stream, E, R> } = dual( @@ -12868,7 +14181,8 @@ export const grouped: { * Partitions the stream into arrays, emitting when the chunk size is reached * or the duration passes. * - * @example + * **Example** (Grouping elements by size or time) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -12884,15 +14198,16 @@ export const grouped: { * // Output: [ [ 1, 2 ], [ 3 ] ] * ``` * + * @category grouping * @since 2.0.0 - * @category Grouping */ export const groupedWithin: { /** * Partitions the stream into arrays, emitting when the chunk size is reached * or the duration passes. * - * @example + * **Example** (Grouping elements by size or time) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -12908,15 +14223,16 @@ export const groupedWithin: { * // Output: [ [ 1, 2 ], [ 3 ] ] * ``` * + * @category grouping * @since 2.0.0 - * @category Grouping */ (chunkSize: number, duration: Duration.Input): (self: Stream) => Stream, E, R> /** * Partitions the stream into arrays, emitting when the chunk size is reached * or the duration passes. * - * @example + * **Example** (Grouping elements by size or time) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -12932,8 +14248,8 @@ export const groupedWithin: { * // Output: [ [ 1, 2 ], [ 3 ] ] * ``` * + * @category grouping * @since 2.0.0 - * @category Grouping */ (self: Stream, chunkSize: number, duration: Duration.Input): Stream, E, R> } = dual(3, ( @@ -12950,7 +14266,8 @@ export const groupedWithin: { /** * Groups elements into keyed substreams using an effectful classifier. * - * @example + * **Example** (Grouping elements into keyed substreams using an effectful classifier) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -12975,14 +14292,15 @@ export const groupedWithin: { * // Output: [ [ "odd", [ 1, 3, 5 ] ], [ "even", [ 2, 4 ] ] ] * ``` * + * @category grouping * @since 2.0.0 - * @category Grouping */ export const groupBy: { /** * Groups elements into keyed substreams using an effectful classifier. * - * @example + * **Example** (Grouping elements into keyed substreams using an effectful classifier) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -13007,8 +14325,8 @@ export const groupBy: { * // Output: [ [ "odd", [ 1, 3, 5 ] ], [ "even", [ 2, 4 ] ] ] * ``` * + * @category grouping * @since 2.0.0 - * @category Grouping */ ( f: (a: NoInfer) => Effect.Effect, @@ -13020,7 +14338,8 @@ export const groupBy: { /** * Groups elements into keyed substreams using an effectful classifier. * - * @example + * **Example** (Grouping elements into keyed substreams using an effectful classifier) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -13045,8 +14364,8 @@ export const groupBy: { * // Output: [ [ "odd", [ 1, 3, 5 ] ], [ "even", [ 2, 4 ] ] ] * ``` * + * @category grouping * @since 2.0.0 - * @category Grouping */ ( self: Stream, @@ -13083,7 +14402,8 @@ export const groupBy: { /** * Groups elements by a key and emits a stream per key. * - * @example + * **Example** (Grouping elements by key) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -13106,14 +14426,15 @@ export const groupBy: { * // Output: [ [ "odd", [ 1, 3, 5 ] ], [ "even", [ 2, 4 ] ] ] * ``` * + * @category grouping * @since 2.0.0 - * @category Grouping */ export const groupByKey: { /** * Groups elements by a key and emits a stream per key. * - * @example + * **Example** (Grouping elements by key) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -13136,8 +14457,8 @@ export const groupByKey: { * // Output: [ [ "odd", [ 1, 3, 5 ] ], [ "even", [ 2, 4 ] ] ] * ``` * + * @category grouping * @since 2.0.0 - * @category Grouping */ ( f: (a: NoInfer) => K, @@ -13149,7 +14470,8 @@ export const groupByKey: { /** * Groups elements by a key and emits a stream per key. * - * @example + * **Example** (Grouping elements by key) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -13172,8 +14494,8 @@ export const groupByKey: { * // Output: [ [ "odd", [ 1, 3, 5 ] ], [ "even", [ 2, 4 ] ] ] * ``` * + * @category grouping * @since 2.0.0 - * @category Grouping */ ( self: Stream, @@ -13195,7 +14517,8 @@ export const groupByKey: { const batch = MutableHashMap.empty>() return groupByImpl( @@ -13327,18 +14651,69 @@ const groupByImpl = ( ) /** + * Groups consecutive elements that have equal keys into non-empty arrays. + * + * **When to use** + * + * Use when you already have a stream ordered by the grouping key and want to + * emit each consecutive run as a non-empty array while keeping later + * non-adjacent runs separate. + * + * **Details** + * + * The key is computed with `f`; adjacent elements whose keys are equal by + * `Equal.equals` are emitted as one `[key, group]`. Later non-adjacent runs + * with the same key are emitted separately. + * + * @see {@link groupByKey} for grouping all elements with the same key across the stream + * @see {@link groupBy} for custom grouped stream construction + * + * @category grouping * @since 2.0.0 - * @category Grouping */ export const groupAdjacentBy: { /** + * Groups consecutive elements that have equal keys into non-empty arrays. + * + * **When to use** + * + * Use when you already have a stream ordered by the grouping key and want to + * emit each consecutive run as a non-empty array while keeping later + * non-adjacent runs separate. + * + * **Details** + * + * The key is computed with `f`; adjacent elements whose keys are equal by + * `Equal.equals` are emitted as one `[key, group]`. Later non-adjacent runs + * with the same key are emitted separately. + * + * @see {@link groupByKey} for grouping all elements with the same key across the stream + * @see {@link groupBy} for custom grouped stream construction + * + * @category grouping * @since 2.0.0 - * @category Grouping */ (f: (a: NoInfer) => K): (self: Stream) => Stream], E, R> /** + * Groups consecutive elements that have equal keys into non-empty arrays. + * + * **When to use** + * + * Use when you already have a stream ordered by the grouping key and want to + * emit each consecutive run as a non-empty array while keeping later + * non-adjacent runs separate. + * + * **Details** + * + * The key is computed with `f`; adjacent elements whose keys are equal by + * `Equal.equals` are emitted as one `[key, group]`. Later non-adjacent runs + * with the same key are emitted separately. + * + * @see {@link groupByKey} for grouping all elements with the same key across the stream + * @see {@link groupBy} for custom grouped stream construction + * + * @category grouping * @since 2.0.0 - * @category Grouping */ (self: Stream, f: (a: NoInfer) => K): Stream], E, R> } = dual(2, ( @@ -13350,8 +14725,25 @@ export const groupAdjacentBy: { let currentKey: K = undefined as any let group: Arr.NonEmptyArray | undefined let toEmit = Arr.empty]>() const loop: Pull.Pull< @@ -13394,7 +14786,8 @@ export const groupAdjacentBy: { /** * Applies a sink transducer to the stream and emits each sink result. * - * @example + * **Example** (Transducing with a sink) + * * ```ts * import { Console, Effect, Sink, Stream } from "effect" * @@ -13409,14 +14802,15 @@ export const groupAdjacentBy: { * }) * ``` * - * @since 2.0.0 * @category Aggregation + * @since 2.0.0 */ export const transduce = dual< /** * Applies a sink transducer to the stream and emits each sink result. * - * @example + * **Example** (Transducing with a sink) + * * ```ts * import { Console, Effect, Sink, Stream } from "effect" * @@ -13431,14 +14825,15 @@ export const transduce = dual< * }) * ``` * - * @since 2.0.0 * @category Aggregation + * @since 2.0.0 */ (sink: Sink.Sink) => (self: Stream) => Stream, /** * Applies a sink transducer to the stream and emits each sink result. * - * @example + * **Example** (Transducing with a sink) + * * ```ts * import { Console, Effect, Sink, Stream } from "effect" * @@ -13453,8 +14848,8 @@ export const transduce = dual< * }) * ``` * - * @since 2.0.0 * @category Aggregation + * @since 2.0.0 */ (self: Stream, sink: Sink.Sink) => Stream >( @@ -13499,10 +14894,13 @@ export const transduce = dual< /** * Aggregates elements using the provided sink and emits each sink result as a stream element. * + * **Details** + * * The stream runs the upstream and downstream in separate fibers, so the sink can keep * consuming input while downstream is busy processing the previous output. * - * @example + * **Example** (Aggregating with a sink) + * * ```ts * import { Console, Effect, Sink, Stream } from "effect" * @@ -13519,17 +14917,20 @@ export const transduce = dual< * // [ 6, 15 ] * ``` * - * @since 2.0.0 * @category Aggregation + * @since 2.0.0 */ export const aggregate: { /** * Aggregates elements using the provided sink and emits each sink result as a stream element. * + * **Details** + * * The stream runs the upstream and downstream in separate fibers, so the sink can keep * consuming input while downstream is busy processing the previous output. * - * @example + * **Example** (Aggregating with a sink) + * * ```ts * import { Console, Effect, Sink, Stream } from "effect" * @@ -13546,17 +14947,20 @@ export const aggregate: { * // [ 6, 15 ] * ``` * - * @since 2.0.0 * @category Aggregation + * @since 2.0.0 */ (sink: Sink.Sink): (self: Stream) => Stream /** * Aggregates elements using the provided sink and emits each sink result as a stream element. * + * **Details** + * * The stream runs the upstream and downstream in separate fibers, so the sink can keep * consuming input while downstream is busy processing the previous output. * - * @example + * **Example** (Aggregating with a sink) + * * ```ts * import { Console, Effect, Sink, Stream } from "effect" * @@ -13573,8 +14977,8 @@ export const aggregate: { * // [ 6, 15 ] * ``` * - * @since 2.0.0 * @category Aggregation + * @since 2.0.0 */ (self: Stream, sink: Sink.Sink): Stream } = dual(2, ( @@ -13585,9 +14989,12 @@ export const aggregate: { /** * Aggregates elements with a sink, emitting each result when the sink completes or the schedule triggers. * + * **Details** + * * The schedule can flush the current aggregation even if the sink has not finished. * - * @example + * **Example** (Aggregating with a sink and schedule) + * * ```ts * import { Console, Effect, Schedule, Sink, Stream } from "effect" * @@ -13605,16 +15012,19 @@ export const aggregate: { * // Output: [ 6, 15 ] * ``` * - * @since 2.0.0 * @category Aggregation + * @since 2.0.0 */ export const aggregateWithin: { /** * Aggregates elements with a sink, emitting each result when the sink completes or the schedule triggers. * + * **Details** + * * The schedule can flush the current aggregation even if the sink has not finished. * - * @example + * **Example** (Aggregating with a sink and schedule) + * * ```ts * import { Console, Effect, Schedule, Sink, Stream } from "effect" * @@ -13632,8 +15042,8 @@ export const aggregateWithin: { * // Output: [ 6, 15 ] * ``` * - * @since 2.0.0 * @category Aggregation + * @since 2.0.0 */ ( sink: Sink.Sink, @@ -13642,9 +15052,12 @@ export const aggregateWithin: { /** * Aggregates elements with a sink, emitting each result when the sink completes or the schedule triggers. * + * **Details** + * * The schedule can flush the current aggregation even if the sink has not finished. * - * @example + * **Example** (Aggregating with a sink and schedule) + * * ```ts * import { Console, Effect, Schedule, Sink, Stream } from "effect" * @@ -13662,8 +15075,8 @@ export const aggregateWithin: { * // Output: [ 6, 15 ] * ``` * - * @since 2.0.0 * @category Aggregation + * @since 2.0.0 */ ( self: Stream, @@ -13683,9 +15096,12 @@ export const aggregateWithin: { const buffer = yield* Queue.make | typeof scheduleStep, /** * Aggregates elements with a sink, emitting each result when the sink completes or the schedule triggers. * + * **Details** + * * The schedule can flush the current aggregation even if the sink has not finished. * - * @example + * **Example** (Aggregating with a sink and schedule) + * * ```ts * import { Console, Effect, Schedule, Sink, Stream } from "effect" * @@ -13729,8 +15148,8 @@ export const aggregateWithin: { * // Output: [ 6, 15 ] * ``` * - * @since 2.0.0 * @category Aggregation + * @since 2.0.0 */ E | Cause.Done>({ capacity: 0 @@ -13752,9 +15171,12 @@ export const aggregateWithin: { let lastOutput = Option.none() let leftover: Arr.NonEmptyReadonlyArray | undefined @@ -13831,12 +15253,254 @@ export const aggregateWithin: { ) })))) +/** + * Creates a fixed-size tuple of streams that each emit + * the same elements as the source stream. + * + * **Details** + * + * The source stream starts after all downstream streams have been subscribed. + * With the default suspend strategy, the source can only advance `capacity` + * chunks ahead of the slowest downstream stream. If a downstream stream is + * interrupted, it unsubscribes from the broadcast so it no longer contributes + * backpressure. + * + * **Example** (Broadcasting to two consumers) + * + * ```ts + * import { Console, Effect, Stream } from "effect" + * + * const program = Effect.scoped( + * Effect.gen(function*() { + * const [left, right] = yield* Stream.make(1, 2, 3).pipe( + * Stream.broadcastN({ n: 2, capacity: 8 }) + * ) + * + * const values = yield* Effect.all([ + * Stream.runCollect(left), + * Stream.runCollect(right) + * ], { concurrency: "unbounded" }) + * + * yield* Console.log(values) + * }) + * ) + * + * Effect.runPromise(program) + * // Output: [[1, 2, 3], [1, 2, 3]] + * ``` + * + * @category Broadcast + * @since 4.0.0 + */ +export const broadcastN: { + /** + * Creates a fixed-size tuple of streams that each emit + * the same elements as the source stream. + * + * **Details** + * + * The source stream starts after all downstream streams have been subscribed. + * With the default suspend strategy, the source can only advance `capacity` + * chunks ahead of the slowest downstream stream. If a downstream stream is + * interrupted, it unsubscribes from the broadcast so it no longer contributes + * backpressure. + * + * **Example** (Broadcasting to two consumers) + * + * ```ts + * import { Console, Effect, Stream } from "effect" + * + * const program = Effect.scoped( + * Effect.gen(function*() { + * const [left, right] = yield* Stream.make(1, 2, 3).pipe( + * Stream.broadcastN({ n: 2, capacity: 8 }) + * ) + * + * const values = yield* Effect.all([ + * Stream.runCollect(left), + * Stream.runCollect(right) + * ], { concurrency: "unbounded" }) + * + * yield* Console.log(values) + * }) + * ) + * + * Effect.runPromise(program) + * // Output: [[1, 2, 3], [1, 2, 3]] + * ``` + * + * @category Broadcast + * @since 4.0.0 + */ + ( + options: { + readonly n: N + readonly capacity: "unbounded" + readonly replay?: number | undefined + } | { + readonly n: N + readonly capacity: number + readonly strategy?: "sliding" | "dropping" | "suspend" | undefined + readonly replay?: number | undefined + } + ): (self: Stream) => Effect.Effect>, never, Scope.Scope | R> + /** + * Creates a fixed-size tuple of streams that each emit + * the same elements as the source stream. + * + * **Details** + * + * The source stream starts after all downstream streams have been subscribed. + * With the default suspend strategy, the source can only advance `capacity` + * chunks ahead of the slowest downstream stream. If a downstream stream is + * interrupted, it unsubscribes from the broadcast so it no longer contributes + * backpressure. + * + * **Example** (Broadcasting to two consumers) + * + * ```ts + * import { Console, Effect, Stream } from "effect" + * + * const program = Effect.scoped( + * Effect.gen(function*() { + * const [left, right] = yield* Stream.make(1, 2, 3).pipe( + * Stream.broadcastN({ n: 2, capacity: 8 }) + * ) + * + * const values = yield* Effect.all([ + * Stream.runCollect(left), + * Stream.runCollect(right) + * ], { concurrency: "unbounded" }) + * + * yield* Console.log(values) + * }) + * ) + * + * Effect.runPromise(program) + * // Output: [[1, 2, 3], [1, 2, 3]] + * ``` + * + * @category Broadcast + * @since 4.0.0 + */ + ( + self: Stream, + options: { + readonly n: N + readonly capacity: "unbounded" + readonly replay?: number | undefined + } | { + readonly capacity: number + readonly n: N + readonly strategy?: "sliding" | "dropping" | "suspend" | undefined + readonly replay?: number | undefined + } + ): Effect.Effect>, never, Scope.Scope | R> +} = dual( + 2, + Effect.fnUntraced(function*( + self: Stream, + options: { + readonly n: N + readonly capacity: "unbounded" + readonly replay?: number | undefined + } | { + readonly n: N + readonly capacity: number + readonly strategy?: "sliding" | "dropping" | "suspend" | undefined + readonly replay?: number | undefined + } + ) { + const pubsub = yield* makePubSub>(options) + const streams = new Array(options.n) + const parentScope = yield* Scope.Scope + for (let i = 0; i < options.n; i++) { + const scope = Scope.forkUnsafe(parentScope) + const subscription = yield* PubSub.subscribe(pubsub).pipe( + Effect.provideService(Scope.Scope, scope) + ) + streams[i] = Channel.fromEffectTake(PubSub.take(subscription)).pipe( + Channel.onExit((exit) => Scope.close(scope, exit)), + fromChannel + ) + } + yield* Channel.runForEach(self.channel, (value) => PubSub.publish(pubsub, value)).pipe( + Effect.onExit((exit) => PubSub.publish(pubsub, exit)), + Effect.forkScoped + ) + return streams as TupleOf> + }) +) + +const makePubSub = ( + options: { + readonly capacity: "unbounded" + readonly replay?: number | undefined + } | { + readonly capacity: number + readonly strategy?: "dropping" | "sliding" | "suspend" | undefined + readonly replay?: number | undefined + } +) => + Effect.acquireRelease( + options.capacity === "unbounded" + ? PubSub.unbounded(options) + : options.strategy === "dropping" + ? PubSub.dropping(options) + : options.strategy === "sliding" + ? PubSub.sliding(options) + : PubSub.bounded(options), + PubSub.shutdown + ) + /** * Creates a PubSub-backed stream that multicasts the source to all subscribers. * + * **Details** + * * The returned stream is scoped and uses the provided PubSub capacity and replay settings. * - * @example + * **Example** (Broadcasting a stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -13860,16 +15524,19 @@ export const aggregateWithin: { * // Output: [[1, 2, 3], [1, 2, 3]] * ``` * - * @since 2.0.0 * @category Broadcast + * @since 2.0.0 */ export const broadcast: { /** * Creates a PubSub-backed stream that multicasts the source to all subscribers. * + * **Details** + * * The returned stream is scoped and uses the provided PubSub capacity and replay settings. * - * @example + * **Example** (Broadcasting a stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -13893,8 +15560,8 @@ export const broadcast: { * // Output: [[1, 2, 3], [1, 2, 3]] * ``` * - * @since 2.0.0 * @category Broadcast + * @since 2.0.0 */ ( options: { @@ -13909,9 +15576,12 @@ export const broadcast: { /** * Creates a PubSub-backed stream that multicasts the source to all subscribers. * + * **Details** + * * The returned stream is scoped and uses the provided PubSub capacity and replay settings. * - * @example + * **Example** (Broadcasting a stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -13935,8 +15605,8 @@ export const broadcast: { * // Output: [[1, 2, 3], [1, 2, 3]] * ``` * - * @since 2.0.0 * @category Broadcast + * @since 2.0.0 */ ( self: Stream, @@ -13964,11 +15634,14 @@ export const broadcast: { /** * Returns a new Stream that multicasts the original stream, subscribing when the first consumer starts. * + * **Details** + * * The upstream continues running while there is at least one consumer and is finalized after the last one exits. * If `idleTimeToLive` is set, the upstream is kept alive for that duration so a later subscriber can continue from * the next element instead of restarting. * - * @example + * **Example** (Sharing a stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -13989,18 +15662,21 @@ export const broadcast: { * // output: [[1], [1]] * ``` * - * @since 2.0.0 * @category Broadcast + * @since 3.8.0 */ export const share: { /** * Returns a new Stream that multicasts the original stream, subscribing when the first consumer starts. * + * **Details** + * * The upstream continues running while there is at least one consumer and is finalized after the last one exits. * If `idleTimeToLive` is set, the upstream is kept alive for that duration so a later subscriber can continue from * the next element instead of restarting. * - * @example + * **Example** (Sharing a stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -14021,8 +15697,8 @@ export const share: { * // output: [[1], [1]] * ``` * - * @since 2.0.0 * @category Broadcast + * @since 3.8.0 */ ( options: { @@ -14039,11 +15715,14 @@ export const share: { /** * Returns a new Stream that multicasts the original stream, subscribing when the first consumer starts. * + * **Details** + * * The upstream continues running while there is at least one consumer and is finalized after the last one exits. * If `idleTimeToLive` is set, the upstream is kept alive for that duration so a later subscriber can continue from * the next element instead of restarting. * - * @example + * **Example** (Sharing a stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -14064,8 +15743,8 @@ export const share: { * // output: [[1], [1]] * ``` * - * @since 2.0.0 * @category Broadcast + * @since 3.8.0 */ ( self: Stream, @@ -14104,10 +15783,13 @@ export const share: { /** * Pipes this stream through a channel that consumes and emits chunked elements. * + * **Details** + * * The channel receives `NonEmptyReadonlyArray` chunks and can transform both the * output elements and error type. * - * @example + * **Example** (Piping through a channel) + * * ```ts * import { Array, Channel, Console, Effect, Stream } from "effect" * @@ -14130,17 +15812,20 @@ export const share: { * // => [2, 4, 6] * ``` * - * @since 2.0.0 * @category Pipe + * @since 2.0.0 */ export const pipeThroughChannel: { /** * Pipes this stream through a channel that consumes and emits chunked elements. * + * **Details** + * * The channel receives `NonEmptyReadonlyArray` chunks and can transform both the * output elements and error type. * - * @example + * **Example** (Piping through a channel) + * * ```ts * import { Array, Channel, Console, Effect, Stream } from "effect" * @@ -14163,8 +15848,8 @@ export const pipeThroughChannel: { * // => [2, 4, 6] * ``` * - * @since 2.0.0 * @category Pipe + * @since 2.0.0 */ ( channel: Channel.Channel, E2, unknown, Arr.NonEmptyReadonlyArray, E, unknown, R2> @@ -14172,10 +15857,13 @@ export const pipeThroughChannel: { /** * Pipes this stream through a channel that consumes and emits chunked elements. * + * **Details** + * * The channel receives `NonEmptyReadonlyArray` chunks and can transform both the * output elements and error type. * - * @example + * **Example** (Piping through a channel) + * * ```ts * import { Array, Channel, Console, Effect, Stream } from "effect" * @@ -14198,8 +15886,8 @@ export const pipeThroughChannel: { * // => [2, 4, 6] * ``` * - * @since 2.0.0 * @category Pipe + * @since 2.0.0 */ ( self: Stream, @@ -14214,76 +15902,72 @@ export const pipeThroughChannel: { * Pipes values through the provided channel while preserving this stream's * failures alongside any channel failures. * + * **Details** + * * Upstream failures are not passed to the channel, so the resulting stream can * fail with either the original stream error or the channel error. * - * @example + * **Example** (Piping through a channel with failures) + * * ```ts - * import type { Channel } from "effect" - * import { Console, Effect, Stream } from "effect" + * import { Array, Channel, Effect, Stream } from "effect" + * + * type NumberChunk = readonly [number, ...Array] * - * declare const transformChannel: Channel.Channel< - * readonly [string, ...Array], - * "ChannelError", - * unknown, - * readonly [number, ...Array], - * "StreamError", - * unknown, - * never - * > + * const stringifyChunks = Channel.identity().pipe( + * Channel.map((chunk) => Array.map(chunk, String)) + * ) * * Effect.runPromise(Effect.gen(function*() { * const result = yield* Stream.make(1, 2, 3).pipe( - * Stream.pipeThroughChannelOrFail(transformChannel), + * Stream.rechunk(2), + * Stream.pipeThroughChannelOrFail(stringifyChunks), * Stream.runCollect * ) * - * yield* Console.log(result) + * yield* Effect.sync(() => console.log(result)) * })) - * // Output: - * // ["1", "2", "3"] + * // [ "1", "2", "3" ] * ``` * - * @since 2.0.0 * @category Pipe + * @since 2.0.0 */ export const pipeThroughChannelOrFail: { /** * Pipes values through the provided channel while preserving this stream's * failures alongside any channel failures. * + * **Details** + * * Upstream failures are not passed to the channel, so the resulting stream can * fail with either the original stream error or the channel error. * - * @example + * **Example** (Piping through a channel with failures) + * * ```ts - * import type { Channel } from "effect" - * import { Console, Effect, Stream } from "effect" + * import { Array, Channel, Effect, Stream } from "effect" * - * declare const transformChannel: Channel.Channel< - * readonly [string, ...Array], - * "ChannelError", - * unknown, - * readonly [number, ...Array], - * "StreamError", - * unknown, - * never - * > + * type NumberChunk = readonly [number, ...Array] + * + * const stringifyChunks = Channel.identity().pipe( + * Channel.map((chunk) => Array.map(chunk, String)) + * ) * * Effect.runPromise(Effect.gen(function*() { * const result = yield* Stream.make(1, 2, 3).pipe( - * Stream.pipeThroughChannelOrFail(transformChannel), + * Stream.rechunk(2), + * Stream.pipeThroughChannelOrFail(stringifyChunks), * Stream.runCollect * ) * - * yield* Console.log(result) + * yield* Effect.sync(() => console.log(result)) * })) - * // Output: - * // ["1", "2", "3"] + * // [ "1", "2", "3" ] * ``` * - * @since 2.0.0 * @category Pipe + * @since 2.0.0 */ ( channel: Channel.Channel, E2, unknown, Arr.NonEmptyReadonlyArray, E, unknown, R2> @@ -14292,38 +15976,36 @@ export const pipeThroughChannelOrFail: { * Pipes values through the provided channel while preserving this stream's * failures alongside any channel failures. * + * **Details** + * * Upstream failures are not passed to the channel, so the resulting stream can * fail with either the original stream error or the channel error. * - * @example + * **Example** (Piping through a channel with failures) + * * ```ts - * import type { Channel } from "effect" - * import { Console, Effect, Stream } from "effect" + * import { Array, Channel, Effect, Stream } from "effect" * - * declare const transformChannel: Channel.Channel< - * readonly [string, ...Array], - * "ChannelError", - * unknown, - * readonly [number, ...Array], - * "StreamError", - * unknown, - * never - * > + * type NumberChunk = readonly [number, ...Array] + * + * const stringifyChunks = Channel.identity().pipe( + * Channel.map((chunk) => Array.map(chunk, String)) + * ) * * Effect.runPromise(Effect.gen(function*() { * const result = yield* Stream.make(1, 2, 3).pipe( - * Stream.pipeThroughChannelOrFail(transformChannel), + * Stream.rechunk(2), + * Stream.pipeThroughChannelOrFail(stringifyChunks), * Stream.runCollect * ) * - * yield* Console.log(result) + * yield* Effect.sync(() => console.log(result)) * })) - * // Output: - * // ["1", "2", "3"] + * // [ "1", "2", "3" ] * ``` * - * @since 2.0.0 * @category Pipe + * @since 2.0.0 */ ( self: Stream, @@ -14337,9 +16019,12 @@ export const pipeThroughChannelOrFail: { /** * Pipes the stream through `Sink.toChannel`, emitting only the sink leftovers. * + * **Details** + * * If the sink completes mid-chunk, the remaining elements become the output stream. * - * @example + * **Example** (Piping through a sink) + * * ```ts * import { Console, Effect, Sink, Stream } from "effect" * @@ -14356,16 +16041,19 @@ export const pipeThroughChannelOrFail: { * //=> [ 3, 4 ] * ``` * - * @since 2.0.0 * @category Pipe + * @since 2.0.0 */ export const pipeThrough: { /** * Pipes the stream through `Sink.toChannel`, emitting only the sink leftovers. * + * **Details** + * * If the sink completes mid-chunk, the remaining elements become the output stream. * - * @example + * **Example** (Piping through a sink) + * * ```ts * import { Console, Effect, Sink, Stream } from "effect" * @@ -14382,16 +16070,19 @@ export const pipeThrough: { * //=> [ 3, 4 ] * ``` * - * @since 2.0.0 * @category Pipe + * @since 2.0.0 */ (sink: Sink.Sink): (self: Stream) => Stream /** * Pipes the stream through `Sink.toChannel`, emitting only the sink leftovers. * + * **Details** + * * If the sink completes mid-chunk, the remaining elements become the output stream. * - * @example + * **Example** (Piping through a sink) + * * ```ts * import { Console, Effect, Sink, Stream } from "effect" * @@ -14408,8 +16099,8 @@ export const pipeThrough: { * //=> [ 3, 4 ] * ``` * - * @since 2.0.0 * @category Pipe + * @since 2.0.0 */ (self: Stream, sink: Sink.Sink): Stream } = dual( @@ -14425,7 +16116,8 @@ export const pipeThrough: { /** * Collects all elements into an array and emits it as a single element. * - * @example + * **Example** (Collecting values into a stream element) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -14440,15 +16132,16 @@ export const pipeThrough: { * // [1, 2, 3] * ``` * - * @since 2.0.0 * @category Accumulation + * @since 4.0.0 */ export const collect = (self: Stream): Stream, E, R> => fromEffect(runCollect(self)) /** * Accumulates elements into a growing array, emitting the cumulative array for each input chunk. * - * @example + * **Example** (Accumulating stream elements) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -14466,8 +16159,8 @@ export const collect = (self: Stream): Stream, E, R> * //=> { _id: 'Chunk', values: [ [ 1 ], [ 1, 2 ], [ 1, 2, 3 ] ] } * ``` * - * @since 2.0.0 * @category Accumulation + * @since 2.0.0 */ export const accumulate = (self: Stream): Stream, E, R> => mapAccumArray(self, Arr.empty, (acc, as) => { @@ -14478,7 +16171,8 @@ export const accumulate = (self: Stream): Stream(self: Stream): Stream(self: Stream): Stream => changesWith(self, Equal.equals) /** * Returns a stream that only emits elements that are not equal to the previously emitted element, as determined by the specified predicate. * - * @example + * **Example** (Emitting values that changed by equivalence) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -14520,14 +16215,15 @@ export const changes = (self: Stream): Stream => chan * // ["A", "B"] * ``` * - * @since 2.0.0 * @category Deduplication + * @since 2.0.0 */ export const changesWith: { /** * Returns a stream that only emits elements that are not equal to the previously emitted element, as determined by the specified predicate. * - * @example + * **Example** (Emitting values that changed by equivalence) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -14544,14 +16240,15 @@ export const changesWith: { * // ["A", "B"] * ``` * - * @since 2.0.0 * @category Deduplication + * @since 2.0.0 */ (f: (x: A, y: A) => boolean): (self: Stream) => Stream /** * Returns a stream that only emits elements that are not equal to the previously emitted element, as determined by the specified predicate. * - * @example + * **Example** (Emitting values that changed by equivalence) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -14568,8 +16265,8 @@ export const changesWith: { * // ["A", "B"] * ``` * - * @since 2.0.0 * @category Deduplication + * @since 2.0.0 */ (self: Stream, f: (x: A, y: A) => boolean): Stream } = dual( @@ -14602,9 +16299,12 @@ export const changesWith: { /** * Emits only elements that differ from the previous element, using an effectful equality check. * + * **Details** + * * The predicate runs for each element after the first; returning `true` treats it as equal and skips it. * - * @example + * **Example** (Effectfully emitting changed values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -14620,16 +16320,19 @@ export const changesWith: { * // { _id: "Chunk", values: [ 1, 2, 3 ] } * ``` * - * @since 2.0.0 * @category Deduplication + * @since 2.0.0 */ export const changesWithEffect: { /** * Emits only elements that differ from the previous element, using an effectful equality check. * + * **Details** + * * The predicate runs for each element after the first; returning `true` treats it as equal and skips it. * - * @example + * **Example** (Effectfully emitting changed values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -14645,16 +16348,19 @@ export const changesWithEffect: { * // { _id: "Chunk", values: [ 1, 2, 3 ] } * ``` * - * @since 2.0.0 * @category Deduplication + * @since 2.0.0 */ (f: (x: A, y: A) => Effect.Effect): (self: Stream) => Stream /** * Emits only elements that differ from the previous element, using an effectful equality check. * + * **Details** + * * The predicate runs for each element after the first; returning `true` treats it as equal and skips it. * - * @example + * **Example** (Effectfully emitting changed values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -14670,8 +16376,8 @@ export const changesWithEffect: { * // { _id: "Chunk", values: [ 1, 2, 3 ] } * ``` * - * @since 2.0.0 * @category Deduplication + * @since 2.0.0 */ (self: Stream, f: (x: A, y: A) => Effect.Effect): Stream } = dual( @@ -14714,7 +16420,8 @@ export const changesWithEffect: { /** * Decodes Uint8Array chunks into strings using TextDecoder with an optional encoding. * - * @example + * **Example** (Decoding Uint8Array chunks into strings using TextDecoder with an optional encoding) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -14736,8 +16443,8 @@ export const changesWithEffect: { * // ["Hello", " World"] * ``` * + * @category encoding * @since 2.0.0 - * @category Encoding */ export const decodeText: < Arg extends Stream | { @@ -14765,7 +16472,8 @@ export const decodeText: < /** * Encodes a stream of strings into UTF-8 `Uint8Array` chunks. * - * @example + * **Example** (Encoding a stream of strings into UTF-8 Uint8Array chunks) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -14781,8 +16489,8 @@ export const decodeText: < * // [[72, 101, 108, 108, 111], [32], [87, 111, 114, 108, 100]] * ``` * + * @category encoding * @since 2.0.0 - * @category Encoding */ export const encodeText = (self: Stream): Stream => suspend(() => { @@ -14793,7 +16501,8 @@ export const encodeText = (self: Stream): Stream(self: Stream): Stream(self: Stream): Stream => self.channel.pipe( @@ -14818,7 +16527,8 @@ export const splitLines = (self: Stream): Stream(self: Stream): Stream(element: A2): (self: Stream) => Stream /** * Inserts the provided element between emitted elements. * - * @example + * **Example** (Interspersing stream elements) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -14874,8 +16586,8 @@ export const intersperse: { * // [1, 0, 2, 0, 3, 0, 4] * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (self: Stream, element: A2): Stream } = dual(2, (self: Stream, element: A2): Stream => @@ -14893,11 +16605,14 @@ export const intersperse: { })) /** - * Intersperse stream elements with a middle value, adding a start and end value. + * Adds a start value, middle value, and end value around stream elements. + * + * **Details** * * The start and end values are always emitted, even when the stream is empty. * - * @example + * **Example** (Interspersing stream affixes) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -14914,16 +16629,19 @@ export const intersperse: { * // [ "[", "a", ",", "b", ",", "c", "]" ] * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ export const intersperseAffixes: { /** - * Intersperse stream elements with a middle value, adding a start and end value. + * Adds a start value, middle value, and end value around stream elements. + * + * **Details** * * The start and end values are always emitted, even when the stream is empty. * - * @example + * **Example** (Interspersing stream affixes) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -14940,16 +16658,19 @@ export const intersperseAffixes: { * // [ "[", "a", ",", "b", ",", "c", "]" ] * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ (options: { readonly start: A2; readonly middle: A3; readonly end: A4 }): (self: Stream) => Stream /** - * Intersperse stream elements with a middle value, adding a start and end value. + * Adds a start value, middle value, and end value around stream elements. + * + * **Details** * * The start and end values are always emitted, even when the stream is empty. * - * @example + * **Example** (Interspersing stream affixes) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -14966,8 +16687,8 @@ export const intersperseAffixes: { * // [ "[", "a", ",", "b", ",", "c", "]" ] * ``` * + * @category sequencing * @since 2.0.0 - * @category Sequencing */ ( self: Stream, @@ -14987,7 +16708,8 @@ export const intersperseAffixes: { * each stream; when one ends, the remaining values from the other stream are * emitted. * - * @example + * **Example** (Interleaving streams) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -15004,8 +16726,9 @@ export const intersperseAffixes: { * Effect.runPromise(program) * // [2, 5, 3, 6, 7] * ``` + * + * @category merging * @since 2.0.0 - * @category Merging */ export const interleave: { /** @@ -15013,7 +16736,8 @@ export const interleave: { * each stream; when one ends, the remaining values from the other stream are * emitted. * - * @example + * **Example** (Interleaving streams) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -15030,8 +16754,9 @@ export const interleave: { * Effect.runPromise(program) * // [2, 5, 3, 6, 7] * ``` + * + * @category merging * @since 2.0.0 - * @category Merging */ (that: Stream): (self: Stream) => Stream /** @@ -15039,7 +16764,8 @@ export const interleave: { * each stream; when one ends, the remaining values from the other stream are * emitted. * - * @example + * **Example** (Interleaving streams) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -15056,8 +16782,9 @@ export const interleave: { * Effect.runPromise(program) * // [2, 5, 3, 6, 7] * ``` + * + * @category merging * @since 2.0.0 - * @category Merging */ (self: Stream, that: Stream): Stream } = dual( @@ -15073,10 +16800,13 @@ export const interleave: { /** * Interleaves two streams deterministically by following a boolean decider stream. * + * **Details** + * * The decider controls how many elements are pulled; if one side ends, pulls for * that side are ignored. * - * @example + * **Example** (Interleaving two streams deterministically by following a boolean decider stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -15096,17 +16826,20 @@ export const interleave: { * // [ 1, 2, 4, 3, 5 ] * ``` * + * @category merging * @since 2.0.0 - * @category Merging */ export const interleaveWith: { /** * Interleaves two streams deterministically by following a boolean decider stream. * + * **Details** + * * The decider controls how many elements are pulled; if one side ends, pulls for * that side are ignored. * - * @example + * **Example** (Interleaving two streams deterministically by following a boolean decider stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -15126,17 +16859,20 @@ export const interleaveWith: { * // [ 1, 2, 4, 3, 5 ] * ``` * + * @category merging * @since 2.0.0 - * @category Merging */ (that: Stream, decider: Stream): (self: Stream) => Stream /** * Interleaves two streams deterministically by following a boolean decider stream. * + * **Details** + * * The decider controls how many elements are pulled; if one side ends, pulls for * that side are ignored. * - * @example + * **Example** (Interleaving two streams deterministically by following a boolean decider stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -15156,8 +16892,8 @@ export const interleaveWith: { * // [ 1, 2, 4, 3, 5 ] * ``` * + * @category merging * @since 2.0.0 - * @category Merging */ ( self: Stream, @@ -15184,10 +16920,13 @@ export const interleaveWith: { return Effect.succeed(retry); }) @@ -15222,10 +16961,13 @@ export const interleaveWith: { return Effect.succeed(retry); }) @@ -15273,10 +17015,13 @@ export const interleaveWith: { * success will be discarded. This combinator will also interrupt any * in-progress element being pulled from upstream. * + * **Details** + * * If the effect completes with a failure before the stream completes, the * returned stream will emit that failure. * - * @example + * **Example** (Interrupting when an effect completes) + * * ```ts * import { Console, Deferred, Effect, Stream } from "effect" * @@ -15299,8 +17044,8 @@ export const interleaveWith: { * // => [1, 2] * ``` * + * @category interruption * @since 2.0.0 - * @category Interruption */ export const interruptWhen: { /** @@ -15309,10 +17054,13 @@ export const interruptWhen: { * success will be discarded. This combinator will also interrupt any * in-progress element being pulled from upstream. * + * **Details** + * * If the effect completes with a failure before the stream completes, the * returned stream will emit that failure. * - * @example + * **Example** (Interrupting when an effect completes) + * * ```ts * import { Console, Deferred, Effect, Stream } from "effect" * @@ -15335,8 +17083,8 @@ export const interruptWhen: { * // => [1, 2] * ``` * + * @category interruption * @since 2.0.0 - * @category Interruption */ (effect: Effect.Effect): (self: Stream) => Stream /** @@ -15345,10 +17093,13 @@ export const interruptWhen: { * success will be discarded. This combinator will also interrupt any * in-progress element being pulled from upstream. * + * **Details** + * * If the effect completes with a failure before the stream completes, the * returned stream will emit that failure. * - * @example + * **Example** (Interrupting when an effect completes) + * * ```ts * import { Console, Deferred, Effect, Stream } from "effect" * @@ -15371,8 +17122,8 @@ export const interruptWhen: { * // => [1, 2] * ``` * + * @category interruption * @since 2.0.0 - * @category Interruption */ (self: Stream, effect: Effect.Effect): Stream } = dual( @@ -15382,9 +17133,24 @@ export const interruptWhen: { ) /** - * Halts evaluation after the current element once the provided effect completes; the effect is forked, its success is discarded, failures fail the stream, and it does not interrupt an in-progress pull (use `interruptWhen` for that). + * Stops a stream after the current element when an effect completes. + * + * **When to use** + * + * Use to stop before the next pull after an external signal completes. + * + * **Details** + * + * The effect is forked, its success value is discarded, and its failure fails + * the stream. + * + * **Gotchas** + * + * This does not interrupt an in-progress pull. Use {@link interruptWhen} when + * the stream should be interrupted immediately. + * + * **Example** (Halting a stream after an effect completes) * - * @example * ```ts * import { Console, Deferred, Effect, Stream } from "effect" * @@ -15403,14 +17169,29 @@ export const interruptWhen: { * // [1, 2] * ``` * + * @category interruption * @since 2.0.0 - * @category Interruption */ export const haltWhen: { /** - * Halts evaluation after the current element once the provided effect completes; the effect is forked, its success is discarded, failures fail the stream, and it does not interrupt an in-progress pull (use `interruptWhen` for that). + * Stops a stream after the current element when an effect completes. + * + * **When to use** + * + * Use to stop before the next pull after an external signal completes. + * + * **Details** + * + * The effect is forked, its success value is discarded, and its failure fails + * the stream. + * + * **Gotchas** + * + * This does not interrupt an in-progress pull. Use {@link interruptWhen} when + * the stream should be interrupted immediately. + * + * **Example** (Halting a stream after an effect completes) * - * @example * ```ts * import { Console, Deferred, Effect, Stream } from "effect" * @@ -15429,14 +17210,29 @@ export const haltWhen: { * // [1, 2] * ``` * + * @category interruption * @since 2.0.0 - * @category Interruption */ (effect: Effect.Effect): (self: Stream) => Stream /** - * Halts evaluation after the current element once the provided effect completes; the effect is forked, its success is discarded, failures fail the stream, and it does not interrupt an in-progress pull (use `interruptWhen` for that). + * Stops a stream after the current element when an effect completes. + * + * **When to use** + * + * Use to stop before the next pull after an external signal completes. + * + * **Details** + * + * The effect is forked, its success value is discarded, and its failure fails + * the stream. + * + * **Gotchas** + * + * This does not interrupt an in-progress pull. Use {@link interruptWhen} when + * the stream should be interrupted immediately. + * + * **Example** (Halting a stream after an effect completes) * - * @example * ```ts * import { Console, Deferred, Effect, Stream } from "effect" * @@ -15455,8 +17251,8 @@ export const haltWhen: { * // [1, 2] * ``` * + * @category interruption * @since 2.0.0 - * @category Interruption */ (self: Stream, effect: Effect.Effect): Stream } = dual( @@ -15468,7 +17264,8 @@ export const haltWhen: { /** * Runs the provided finalizer when the stream exits, passing the exit value. * - * @example + * **Example** (Running a finalizer on exit) + * * ```ts * import { Console, Effect, Exit, Stream } from "effect" * @@ -15487,14 +17284,15 @@ export const haltWhen: { * // Stream completed successfully * ``` * - * @since 4.0.0 * @category Finalization + * @since 4.0.0 */ export const onExit: { /** * Runs the provided finalizer when the stream exits, passing the exit value. * - * @example + * **Example** (Running a finalizer on exit) + * * ```ts * import { Console, Effect, Exit, Stream } from "effect" * @@ -15513,8 +17311,8 @@ export const onExit: { * // Stream completed successfully * ``` * - * @since 4.0.0 * @category Finalization + * @since 4.0.0 */ ( finalizer: (exit: Exit.Exit) => Effect.Effect @@ -15522,7 +17320,8 @@ export const onExit: { /** * Runs the provided finalizer when the stream exits, passing the exit value. * - * @example + * **Example** (Running a finalizer on exit) + * * ```ts * import { Console, Effect, Exit, Stream } from "effect" * @@ -15541,8 +17340,8 @@ export const onExit: { * // Stream completed successfully * ``` * - * @since 4.0.0 * @category Finalization + * @since 4.0.0 */ ( self: Stream, @@ -15556,10 +17355,13 @@ export const onExit: { /** * Runs the provided effect when the stream fails, passing the failure cause. * + * **Gotchas** + * * Note: Unlike `Effect.onError` there is no guarantee that the provided * effect will not be interrupted. * - * @example + * **Example** (Running an effect on errors) + * * ```ts * import { Cause, Console, Effect, Stream } from "effect" * @@ -15577,17 +17379,20 @@ export const onExit: { * // Stream failed: boom * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ export const onError: { /** * Runs the provided effect when the stream fails, passing the failure cause. * + * **Gotchas** + * * Note: Unlike `Effect.onError` there is no guarantee that the provided * effect will not be interrupted. * - * @example + * **Example** (Running an effect on errors) + * * ```ts * import { Cause, Console, Effect, Stream } from "effect" * @@ -15605,17 +17410,20 @@ export const onError: { * // Stream failed: boom * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ (cleanup: (cause: Cause.Cause) => Effect.Effect): (self: Stream) => Stream /** * Runs the provided effect when the stream fails, passing the failure cause. * + * **Gotchas** + * * Note: Unlike `Effect.onError` there is no guarantee that the provided * effect will not be interrupted. * - * @example + * **Example** (Running an effect on errors) + * * ```ts * import { Cause, Console, Effect, Stream } from "effect" * @@ -15633,8 +17441,8 @@ export const onError: { * // Stream failed: boom * ``` * + * @category error handling * @since 2.0.0 - * @category Error Handling */ ( self: Stream, @@ -15648,7 +17456,8 @@ export const onError: { /** * Runs the provided effect before this stream starts. * - * @example + * **Example** (Running an effect on start) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -15667,14 +17476,15 @@ export const onError: { * // [1, 2, 3] * ``` * - * @since 4.0.0 - * @category Sequencing + * @category sequencing + * @since 3.6.0 */ export const onStart: { /** * Runs the provided effect before this stream starts. * - * @example + * **Example** (Running an effect on start) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -15693,14 +17503,15 @@ export const onStart: { * // [1, 2, 3] * ``` * - * @since 4.0.0 - * @category Sequencing + * @category sequencing + * @since 3.6.0 */ (onStart: Effect.Effect): (self: Stream) => Stream /** * Runs the provided effect before this stream starts. * - * @example + * **Example** (Running an effect on start) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -15719,8 +17530,8 @@ export const onStart: { * // [1, 2, 3] * ``` * - * @since 4.0.0 - * @category Sequencing + * @category sequencing + * @since 3.6.0 */ (self: Stream, onStart: Effect.Effect): Stream } = dual(2, ( @@ -15731,7 +17542,8 @@ export const onStart: { /** * Runs the provided effect with the first element emitted by the stream. * - * @example + * **Example** (Running an effect on the first value) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -15744,14 +17556,15 @@ export const onStart: { * // Output: first=1 * ``` * + * @category sequencing * @since 4.0.0 - * @category Sequencing */ export const onFirst: { /** * Runs the provided effect with the first element emitted by the stream. * - * @example + * **Example** (Running an effect on the first value) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -15764,14 +17577,15 @@ export const onFirst: { * // Output: first=1 * ``` * + * @category sequencing * @since 4.0.0 - * @category Sequencing */ (onFirst: (element: NoInfer) => Effect.Effect): (self: Stream) => Stream /** * Runs the provided effect with the first element emitted by the stream. * - * @example + * **Example** (Running an effect on the first value) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -15784,8 +17598,8 @@ export const onFirst: { * // Output: first=1 * ``` * + * @category sequencing * @since 4.0.0 - * @category Sequencing */ ( self: Stream, @@ -15799,7 +17613,8 @@ export const onFirst: { /** * Runs the provided effect when the stream ends successfully. * - * @example + * **Example** (Running an effect on end) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -15816,14 +17631,15 @@ export const onFirst: { * // [1, 2, 3] * ``` * - * @since 4.0.0 - * @category Sequencing + * @category sequencing + * @since 3.6.0 */ export const onEnd: { /** * Runs the provided effect when the stream ends successfully. * - * @example + * **Example** (Running an effect on end) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -15840,14 +17656,15 @@ export const onEnd: { * // [1, 2, 3] * ``` * - * @since 4.0.0 - * @category Sequencing + * @category sequencing + * @since 3.6.0 */ (onEnd: Effect.Effect): (self: Stream) => Stream /** * Runs the provided effect when the stream ends successfully. * - * @example + * **Example** (Running an effect on end) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -15864,8 +17681,8 @@ export const onEnd: { * // [1, 2, 3] * ``` * - * @since 4.0.0 - * @category Sequencing + * @category sequencing + * @since 3.6.0 */ (self: Stream, onEnd: Effect.Effect): Stream } = dual(2, ( @@ -15876,7 +17693,8 @@ export const onEnd: { /** * Executes the provided finalizer after this stream's finalizers run. * - * @example + * **Example** (Ensuring finalization) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -15894,14 +17712,15 @@ export const onEnd: { * //=> [1, 2] * ``` * - * @since 4.0.0 * @category Finalization + * @since 2.0.0 */ export const ensuring: { /** * Executes the provided finalizer after this stream's finalizers run. * - * @example + * **Example** (Ensuring finalization) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -15919,14 +17738,15 @@ export const ensuring: { * //=> [1, 2] * ``` * - * @since 4.0.0 * @category Finalization + * @since 2.0.0 */ (finalizer: Effect.Effect): (self: Stream) => Stream /** * Executes the provided finalizer after this stream's finalizers run. * - * @example + * **Example** (Ensuring finalization) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -15944,8 +17764,8 @@ export const ensuring: { * //=> [1, 2] * ``` * - * @since 4.0.0 * @category Finalization + * @since 2.0.0 */ (self: Stream, finalizer: Effect.Effect): Stream } = dual( @@ -15959,11 +17779,10 @@ export const ensuring: { * service requirements. Use `options.local` to build the layer every time; by * default, layers are shared between provide calls. * - * **Previously Known As:** `provideSomeLayer`, `provideSomeContext`. + * **Example** (Providing stream requirements) * - * @example * ```ts - * import { Console, Effect, Layer, Context, Stream } from "effect" + * import { Console, Context, Effect, Layer, Stream } from "effect" * * class Env extends Context.Service()("Env") {} * @@ -15987,8 +17806,8 @@ export const ensuring: { * // ["Hello, Ada"] * ``` * + * @category services * @since 4.0.0 - * @category Services */ export const provide: { /** @@ -15996,11 +17815,10 @@ export const provide: { * service requirements. Use `options.local` to build the layer every time; by * default, layers are shared between provide calls. * - * **Previously Known As:** `provideSomeLayer`, `provideSomeContext`. + * **Example** (Providing stream requirements) * - * @example * ```ts - * import { Console, Effect, Layer, Context, Stream } from "effect" + * import { Console, Context, Effect, Layer, Stream } from "effect" * * class Env extends Context.Service()("Env") {} * @@ -16024,8 +17842,8 @@ export const provide: { * // ["Hello, Ada"] * ``` * + * @category services * @since 4.0.0 - * @category Services */ ( layer: Layer.Layer | Context.Context, @@ -16040,11 +17858,10 @@ export const provide: { * service requirements. Use `options.local` to build the layer every time; by * default, layers are shared between provide calls. * - * **Previously Known As:** `provideSomeLayer`, `provideSomeContext`. + * **Example** (Providing stream requirements) * - * @example * ```ts - * import { Console, Effect, Layer, Context, Stream } from "effect" + * import { Console, Context, Effect, Layer, Stream } from "effect" * * class Env extends Context.Service()("Env") {} * @@ -16068,8 +17885,8 @@ export const provide: { * // ["Hello, Ada"] * ``` * + * @category services * @since 4.0.0 - * @category Services */ ( self: Stream, @@ -16089,9 +17906,10 @@ export const provide: { /** * Provides multiple services to the stream using a context. * - * @example + * **Example** (Providing multiple services to the stream using a context) + * * ```ts - * import { Console, Effect, Context, Stream } from "effect" + * import { Console, Context, Effect, Stream } from "effect" * * class Config extends Context.Service()("Config") {} * class Greeter extends Context.Service string }>()("Greeter") {} @@ -16117,16 +17935,17 @@ export const provide: { * // ["Hello!"] * ``` * - * @since 4.0.0 - * @category Services + * @category services + * @since 2.0.0 */ export const provideContext: { /** * Provides multiple services to the stream using a context. * - * @example + * **Example** (Providing multiple services to the stream using a context) + * * ```ts - * import { Console, Effect, Context, Stream } from "effect" + * import { Console, Context, Effect, Stream } from "effect" * * class Config extends Context.Service()("Config") {} * class Greeter extends Context.Service string }>()("Greeter") {} @@ -16152,16 +17971,17 @@ export const provideContext: { * // ["Hello!"] * ``` * - * @since 4.0.0 - * @category Services + * @category services + * @since 2.0.0 */ (context: Context.Context): (self: Stream) => Stream> /** * Provides multiple services to the stream using a context. * - * @example + * **Example** (Providing multiple services to the stream using a context) + * * ```ts - * import { Console, Effect, Context, Stream } from "effect" + * import { Console, Context, Effect, Stream } from "effect" * * class Config extends Context.Service()("Config") {} * class Greeter extends Context.Service string }>()("Greeter") {} @@ -16187,8 +18007,8 @@ export const provideContext: { * // ["Hello!"] * ``` * - * @since 4.0.0 - * @category Services + * @category services + * @since 2.0.0 */ (self: Stream, context: Context.Context): Stream> } = dual( @@ -16201,9 +18021,10 @@ export const provideContext: { * Provides the stream with a single required service, eliminating that * requirement from its environment. * - * @example + * **Example** (Providing a stream service) + * * ```ts - * import { Console, Effect, Context, Stream } from "effect" + * import { Console, Context, Effect, Stream } from "effect" * * class Greeter extends Context.Service string @@ -16230,17 +18051,18 @@ export const provideContext: { * //=> ["Hello, Ada"] * ``` * - * @since 4.0.0 - * @category Services + * @category services + * @since 2.0.0 */ export const provideService: { /** * Provides the stream with a single required service, eliminating that * requirement from its environment. * - * @example + * **Example** (Providing a stream service) + * * ```ts - * import { Console, Effect, Context, Stream } from "effect" + * import { Console, Context, Effect, Stream } from "effect" * * class Greeter extends Context.Service string @@ -16267,8 +18089,8 @@ export const provideService: { * //=> ["Hello, Ada"] * ``` * - * @since 4.0.0 - * @category Services + * @category services + * @since 2.0.0 */ (key: Context.Key, service: NoInfer): ( self: Stream @@ -16277,9 +18099,10 @@ export const provideService: { * Provides the stream with a single required service, eliminating that * requirement from its environment. * - * @example + * **Example** (Providing a stream service) + * * ```ts - * import { Console, Effect, Context, Stream } from "effect" + * import { Console, Context, Effect, Stream } from "effect" * * class Greeter extends Context.Service string @@ -16306,8 +18129,8 @@ export const provideService: { * //=> ["Hello, Ada"] * ``` * - * @since 4.0.0 - * @category Services + * @category services + * @since 2.0.0 */ (self: Stream, key: Context.Key, service: NoInfer): Stream> } = dual(3, ( @@ -16319,9 +18142,10 @@ export const provideService: { /** * Provides a service to the stream using an effect, removing the requirement and adding the effect's error and environment. * - * @example + * **Example** (Providing a stream service effectfully) + * * ```ts - * import { Console, Effect, Context, Stream } from "effect" + * import { Console, Context, Effect, Stream } from "effect" * * class ApiConfig extends Context.Service()("ApiConfig") {} * @@ -16351,16 +18175,17 @@ export const provideService: { * // ["https://example.com"] * ``` * - * @since 4.0.0 - * @category Services + * @category services + * @since 2.0.0 */ export const provideServiceEffect: { /** * Provides a service to the stream using an effect, removing the requirement and adding the effect's error and environment. * - * @example + * **Example** (Providing a stream service effectfully) + * * ```ts - * import { Console, Effect, Context, Stream } from "effect" + * import { Console, Context, Effect, Stream } from "effect" * * class ApiConfig extends Context.Service()("ApiConfig") {} * @@ -16390,8 +18215,8 @@ export const provideServiceEffect: { * // ["https://example.com"] * ``` * - * @since 4.0.0 - * @category Services + * @category services + * @since 2.0.0 */ (key: Context.Key, service: Effect.Effect, ES, RS>): ( self: Stream @@ -16399,9 +18224,10 @@ export const provideServiceEffect: { /** * Provides a service to the stream using an effect, removing the requirement and adding the effect's error and environment. * - * @example + * **Example** (Providing a stream service effectfully) + * * ```ts - * import { Console, Effect, Context, Stream } from "effect" + * import { Console, Context, Effect, Stream } from "effect" * * class ApiConfig extends Context.Service()("ApiConfig") {} * @@ -16431,8 +18257,8 @@ export const provideServiceEffect: { * // ["https://example.com"] * ``` * - * @since 4.0.0 - * @category Services + * @category services + * @since 2.0.0 */ ( self: Stream, @@ -16449,9 +18275,10 @@ export const provideServiceEffect: { * Transforms the stream's required services by mapping the current context * to a new one. * - * @example + * **Example** (Updating the stream context) + * * ```ts - * import { Console, Effect, Context, Stream } from "effect" + * import { Console, Context, Effect, Stream } from "effect" * * class Logger extends Context.Service()("Logger") {} * class Config extends Context.Service()("Config") {} @@ -16481,17 +18308,18 @@ export const provideServiceEffect: { * //=> [ "Hello World" ] * ``` * - * @since 2.0.0 - * @category Services + * @category services + * @since 4.0.0 */ export const updateContext: { /** * Transforms the stream's required services by mapping the current context * to a new one. * - * @example + * **Example** (Updating the stream context) + * * ```ts - * import { Console, Effect, Context, Stream } from "effect" + * import { Console, Context, Effect, Stream } from "effect" * * class Logger extends Context.Service()("Logger") {} * class Config extends Context.Service()("Config") {} @@ -16521,8 +18349,8 @@ export const updateContext: { * //=> [ "Hello World" ] * ``` * - * @since 2.0.0 - * @category Services + * @category services + * @since 4.0.0 */ (f: (context: Context.Context) => Context.Context): ( self: Stream @@ -16531,9 +18359,10 @@ export const updateContext: { * Transforms the stream's required services by mapping the current context * to a new one. * - * @example + * **Example** (Updating the stream context) + * * ```ts - * import { Console, Effect, Context, Stream } from "effect" + * import { Console, Context, Effect, Stream } from "effect" * * class Logger extends Context.Service()("Logger") {} * class Config extends Context.Service()("Config") {} @@ -16563,8 +18392,8 @@ export const updateContext: { * //=> [ "Hello World" ] * ``` * - * @since 2.0.0 - * @category Services + * @category services + * @since 4.0.0 */ ( self: Stream, @@ -16578,9 +18407,10 @@ export const updateContext: { /** * Updates a single service in the stream environment by applying a function. * - * @example + * **Example** (Updating a stream service) + * * ```ts - * import { Console, Effect, Context, Stream } from "effect" + * import { Console, Context, Effect, Stream } from "effect" * * class Counter extends Context.Service()("Counter") {} * @@ -16597,16 +18427,17 @@ export const updateContext: { * // Output: Updated count: 1 * ``` * + * @category services * @since 2.0.0 - * @category Services */ export const updateService: { /** * Updates a single service in the stream environment by applying a function. * - * @example + * **Example** (Updating a stream service) + * * ```ts - * import { Console, Effect, Context, Stream } from "effect" + * import { Console, Context, Effect, Stream } from "effect" * * class Counter extends Context.Service()("Counter") {} * @@ -16623,8 +18454,8 @@ export const updateService: { * // Output: Updated count: 1 * ``` * + * @category services * @since 2.0.0 - * @category Services */ (key: Context.Key, f: (service: NoInfer) => S): ( self: Stream @@ -16632,9 +18463,10 @@ export const updateService: { /** * Updates a single service in the stream environment by applying a function. * - * @example + * **Example** (Updating a stream service) + * * ```ts - * import { Console, Effect, Context, Stream } from "effect" + * import { Console, Context, Effect, Stream } from "effect" * * class Counter extends Context.Service()("Counter") {} * @@ -16651,8 +18483,8 @@ export const updateService: { * // Output: Updated count: 1 * ``` * + * @category services * @since 2.0.0 - * @category Services */ ( self: Stream, @@ -16674,7 +18506,8 @@ export const updateService: { /** * Wraps the stream with a new span for tracing. * - * @example + * **Example** (Wrapping a stream in a span) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -16689,14 +18522,15 @@ export const updateService: { * // [1, 2, 3] * ``` * - * @since 4.0.0 - * @category Tracing + * @category tracing + * @since 2.0.0 */ export const withSpan: { /** * Wraps the stream with a new span for tracing. * - * @example + * **Example** (Wrapping a stream in a span) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -16711,14 +18545,15 @@ export const withSpan: { * // [1, 2, 3] * ``` * - * @since 4.0.0 - * @category Tracing + * @category tracing + * @since 2.0.0 */ (name: string, options?: SpanOptions): (self: Stream) => Stream> /** * Wraps the stream with a new span for tracing. * - * @example + * **Example** (Wrapping a stream in a span) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -16733,8 +18568,8 @@ export const withSpan: { * // [1, 2, 3] * ``` * - * @since 4.0.0 - * @category Tracing + * @category tracing + * @since 2.0.0 */ (self: Stream, name: string, options?: SpanOptions): Stream> } = function() { @@ -16751,9 +18586,10 @@ export const withSpan: { /** * Provides the entry point for do-notation style stream composition. * - * @example + * **Example** (Starting stream do notation) + * * ```ts - * import { Console, Effect, Stream, pipe } from "effect" + * import { Console, Effect, pipe, Stream } from "effect" * * const program = pipe( * Stream.Do, @@ -16770,8 +18606,8 @@ export const withSpan: { * //=> [{ value: 1, next: 2 }, { value: 2, next: 3 }] * ``` * - * @since 4.0.0 - * @category Do Notation + * @category do notation + * @since 2.0.0 */ export const Do: Stream<{}> = succeed({}) @@ -16795,7 +18631,8 @@ export { /** * Adds a computed field to the current Do-notation record. * - * @example + * **Example** (Adding a computed field) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -16813,8 +18650,8 @@ export { * // [{ x: 2, y: 6 }] * ``` * - * @since 4.0.0 - * @category Do Notation + * @category do notation + * @since 2.0.0 */ let_ as let } @@ -16822,7 +18659,8 @@ export { /** * Binds the result of a stream to a field in the do-notation record. * - * @example + * **Example** (Binding a stream value) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -16837,14 +18675,15 @@ export { * // [{ a: 1, b: 2 }, { a: 2, b: 3 }] * ``` * - * @since 4.0.0 - * @category Do Notation + * @category do notation + * @since 2.0.0 */ export const bind: { /** * Binds the result of a stream to a field in the do-notation record. * - * @example + * **Example** (Binding a stream value) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -16859,8 +18698,8 @@ export const bind: { * // [{ a: 1, b: 2 }, { a: 2, b: 3 }] * ``` * - * @since 4.0.0 - * @category Do Notation + * @category do notation + * @since 2.0.0 */ ( tag: Exclude, @@ -16873,7 +18712,8 @@ export const bind: { /** * Binds the result of a stream to a field in the do-notation record. * - * @example + * **Example** (Binding a stream value) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -16888,8 +18728,8 @@ export const bind: { * // [{ a: 1, b: 2 }, { a: 2, b: 3 }] * ``` * - * @since 4.0.0 - * @category Do Notation + * @category do notation + * @since 2.0.0 */ ( self: Stream, @@ -16914,7 +18754,8 @@ export const bind: { /** * Binds an Effect-produced value into the do-notation record for each stream element. * - * @example + * **Example** (Binding an effect value) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -16932,14 +18773,15 @@ export const bind: { * // [{ value: 1, double: 2 }, { value: 2, double: 4 }] * ``` * - * @since 4.0.0 - * @category Do Notation + * @category do notation + * @since 2.0.0 */ export const bindEffect: { /** * Binds an Effect-produced value into the do-notation record for each stream element. * - * @example + * **Example** (Binding an effect value) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -16957,8 +18799,8 @@ export const bindEffect: { * // [{ value: 1, double: 2 }, { value: 2, double: 4 }] * ``` * - * @since 4.0.0 - * @category Do Notation + * @category do notation + * @since 2.0.0 */ ( tag: Exclude, @@ -16972,7 +18814,8 @@ export const bindEffect: { /** * Binds an Effect-produced value into the do-notation record for each stream element. * - * @example + * **Example** (Binding an effect value) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -16990,8 +18833,8 @@ export const bindEffect: { * // [{ value: 1, double: 2 }, { value: 2, double: 4 }] * ``` * - * @since 4.0.0 - * @category Do Notation + * @category do notation + * @since 2.0.0 */ ( self: Stream, @@ -17018,7 +18861,8 @@ export const bindEffect: { /** * Maps each element into a record keyed by the provided name. * - * @example + * **Example** (Binding values to a record key) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -17030,14 +18874,15 @@ export const bindEffect: { * // [{ value: 1 }, { value: 2 }, { value: 3 }] * ``` * - * @category Do Notation - * @since 4.0.0 + * @category do notation + * @since 2.0.0 */ export const bindTo: { /** * Maps each element into a record keyed by the provided name. * - * @example + * **Example** (Binding values to a record key) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -17049,14 +18894,15 @@ export const bindTo: { * // [{ value: 1 }, { value: 2 }, { value: 3 }] * ``` * - * @category Do Notation - * @since 4.0.0 + * @category do notation + * @since 2.0.0 */ (name: N): (self: Stream) => Stream<{ [K in N]: A }, E, R> /** * Maps each element into a record keyed by the provided name. * - * @example + * **Example** (Binding values to a record key) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -17068,8 +18914,8 @@ export const bindTo: { * // [{ value: 1 }, { value: 2 }, { value: 3 }] * ``` * - * @category Do Notation - * @since 4.0.0 + * @category do notation + * @since 2.0.0 */ (self: Stream, name: N): Stream<{ [K in N]: A }, E, R> } = dual(2, ( @@ -17080,7 +18926,8 @@ export const bindTo: { /** * Runs a stream with a sink and returns the sink result. * - * @example + * **Example** (Running a stream with a sink) + * * ```ts * import { Console, Effect, Sink, Stream } from "effect" * @@ -17090,14 +18937,15 @@ export const bindTo: { * // 6 * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const run: { /** * Runs a stream with a sink and returns the sink result. * - * @example + * **Example** (Running a stream with a sink) + * * ```ts * import { Console, Effect, Sink, Stream } from "effect" * @@ -17107,14 +18955,15 @@ export const run: { * // 6 * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ (sink: Sink.Sink): (self: Stream) => Effect.Effect /** * Runs a stream with a sink and returns the sink result. * - * @example + * **Example** (Running a stream with a sink) + * * ```ts * import { Console, Effect, Sink, Stream } from "effect" * @@ -17124,8 +18973,8 @@ export const run: { * // 6 * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ (self: Stream, sink: Sink.Sink): Effect.Effect } = dual(2, ( @@ -17142,7 +18991,8 @@ export const run: { /** * Runs the stream and collects all elements into an array. * - * @example + * **Example** (Collecting stream values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -17157,8 +19007,8 @@ export const run: { * // [1, 2, 3, 4, 5] * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const runCollect = (self: Stream): Effect.Effect, E, R> => Channel.runFold( @@ -17175,7 +19025,8 @@ export const runCollect = (self: Stream): Effect.Effect(self: Stream): Effect.Effect(self: Stream): Effect.Effect => Channel.runFold(self.channel, () => 0, (acc, chunk) => acc + chunk.length) @@ -17199,7 +19050,8 @@ export const runCount = (self: Stream): Effect.Effect(self: Stream): Effect.Effect(self: Stream): Effect.Effect => Channel.runFold(self.channel, () => 0, (acc, chunk) => { @@ -17226,7 +19078,8 @@ export const runSum = (self: Stream): Effect.Effect(self: Stream): Effect.Effect(initial: LazyArg, f: (acc: Z, a: A) => Z): ( self: Stream @@ -17276,7 +19130,8 @@ export const runFold: { /** * Runs the stream and folds elements using a pure reducer. * - * @example + * **Example** (Folding stream values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -17293,8 +19148,8 @@ export const runFold: { * // 6 * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ (self: Stream, initial: LazyArg, f: (acc: Z, a: A) => Z): Effect.Effect } = dual(3, ( @@ -17312,7 +19167,13 @@ export const runFold: { /** * Runs the stream and folds elements using an effectful reducer. * - * @example + * **When to use** + * + * Use when reducing stream elements needs Effects, services, or failures in the + * reducer. + * + * **Example** (Effectfully folding stream values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -17329,14 +19190,20 @@ export const runFold: { * // 6 * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const runFoldEffect: { /** * Runs the stream and folds elements using an effectful reducer. * - * @example + * **When to use** + * + * Use when reducing stream elements needs Effects, services, or failures in the + * reducer. + * + * **Example** (Effectfully folding stream values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -17353,8 +19220,8 @@ export const runFoldEffect: { * // 6 * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ (initial: LazyArg, f: (acc: Z, a: A) => Effect.Effect): ( self: Stream @@ -17362,7 +19229,13 @@ export const runFoldEffect: { /** * Runs the stream and folds elements using an effectful reducer. * - * @example + * **When to use** + * + * Use when reducing stream elements needs Effects, services, or failures in the + * reducer. + * + * **Example** (Effectfully folding stream values) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -17379,8 +19252,8 @@ export const runFoldEffect: { * // 6 * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ ( self: Stream, @@ -17411,7 +19284,8 @@ export const runFoldEffect: { /** * Runs the stream and returns the first element as an `Option`. * - * @example + * **Example** (Getting the first stream value) + * * ```ts * import { Console, Effect, Option, Stream } from "effect" * @@ -17424,8 +19298,8 @@ export const runFoldEffect: { * // 1 * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const runHead = (self: Stream): Effect.Effect, E, R> => Effect.map(Channel.runHead(self.channel), Option.map(Arr.getUnsafe(0))) @@ -17433,8 +19307,26 @@ export const runHead = (self: Stream): Effect.Effect(self: Stream): Effect.Effect, E, R> => Effect.map(Channel.runLast(self.channel), Option.map(Arr.lastNonEmpty)) @@ -17442,7 +19334,8 @@ export const runLast = (self: Stream): Effect.Effect(self: Stream): Effect.Effect(f: (a: A) => Effect.Effect): (self: Stream) => Effect.Effect /** * Runs the provided effectful callback for each element of the stream. * - * @example + * **Example** (Running an effect for each value) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -17504,8 +19399,8 @@ export const runForEach: { * // Processing: 3 * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ (self: Stream, f: (a: A) => Effect.Effect): Effect.Effect } = dual(2, ( @@ -17525,7 +19420,8 @@ export const runForEach: { * Runs the stream, applying the effectful predicate to each element and * stopping when it returns `false`. * - * @example + * **Example** (Running effects while a predicate holds) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -17546,15 +19442,16 @@ export const runForEach: { * // Processing: 3 * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const runForEachWhile: { /** * Runs the stream, applying the effectful predicate to each element and * stopping when it returns `false`. * - * @example + * **Example** (Running effects while a predicate holds) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -17575,15 +19472,16 @@ export const runForEachWhile: { * // Processing: 3 * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ (f: (a: A) => Effect.Effect): (self: Stream) => Effect.Effect /** * Runs the stream, applying the effectful predicate to each element and * stopping when it returns `false`. * - * @example + * **Example** (Running effects while a predicate holds) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -17604,8 +19502,8 @@ export const runForEachWhile: { * // Processing: 3 * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ (self: Stream, f: (a: A) => Effect.Effect): Effect.Effect } = dual(2, ( @@ -17631,7 +19529,8 @@ export const runForEachWhile: { /** * Consumes the stream in chunks, passing each non-empty array to the callback. * - * @example + * **Example** (Consuming stream chunks) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -17647,14 +19546,15 @@ export const runForEachWhile: { * // Processing chunk: 1, 2, 3, 4, 5 * ``` * - * @since 2.0.0 - * @category Destructors + * @category destructors + * @since 4.0.0 */ export const runForEachArray: { /** * Consumes the stream in chunks, passing each non-empty array to the callback. * - * @example + * **Example** (Consuming stream chunks) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -17670,14 +19570,15 @@ export const runForEachArray: { * // Processing chunk: 1, 2, 3, 4, 5 * ``` * - * @since 2.0.0 - * @category Destructors + * @category destructors + * @since 4.0.0 */ (f: (a: Arr.NonEmptyReadonlyArray) => Effect.Effect): (self: Stream) => Effect.Effect /** * Consumes the stream in chunks, passing each non-empty array to the callback. * - * @example + * **Example** (Consuming stream chunks) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -17693,8 +19594,8 @@ export const runForEachArray: { * // Processing chunk: 1, 2, 3, 4, 5 * ``` * - * @since 2.0.0 - * @category Destructors + * @category destructors + * @since 4.0.0 */ ( self: Stream, @@ -17708,7 +19609,8 @@ export const runForEachArray: { /** * Runs the stream for its effects, discarding emitted elements. * - * @example + * **Example** (Draining a stream run) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -17726,18 +19628,21 @@ export const runForEachArray: { * // Processing: 3 * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const runDrain = (self: Stream): Effect.Effect => Channel.runDrain(self.channel) /** * Returns a scoped pull for manually consuming the stream's output chunks. * + * **Details** + * * The pull fails with `Cause.Done` when the stream ends and with the stream * error on failure. * - * @example + * **Example** (Creating a scoped pull) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -17755,8 +19660,8 @@ export const runDrain = (self: Stream): Effect.Effect( self: Stream @@ -17765,7 +19670,8 @@ export const toPull = ( /** * Concatenates all emitted strings into a single string. * - * @example + * **Example** (Joining strings from a stream) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -17779,8 +19685,8 @@ export const toPull = ( * // Hello World! * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const mkString = (self: Stream): Effect.Effect => Channel.runFold( @@ -17792,7 +19698,8 @@ export const mkString = (self: Stream): Effect.Effect(self: Stream): Effect.Effect(self: Stream): Effect.Effect => Effect.map( @@ -17843,9 +19750,17 @@ export const mkUint8Array = (self: Stream): Effect.Effec /** * Converts the stream to a `ReadableStream` using the provided services. * + * **When to use** + * + * Use when bridging to Web Streams and you already have the `Context` required + * to run the stream outside an `Effect`. + * + * **Details** + * * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream. * - * @example + * **Example** (Converting to a ReadableStream with services) + * * ```ts * import { Context, Stream } from "effect" * @@ -17853,16 +19768,24 @@ export const mkUint8Array = (self: Stream): Effect.Effec * const readableStream = Stream.toReadableStreamWith(stream, Context.empty()) * ``` * - * @since 2.0.0 - * @category Destructors + * @category destructors + * @since 4.0.0 */ export const toReadableStreamWith = dual< /** * Converts the stream to a `ReadableStream` using the provided services. * + * **When to use** + * + * Use when bridging to Web Streams and you already have the `Context` required + * to run the stream outside an `Effect`. + * + * **Details** + * * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream. * - * @example + * **Example** (Converting to a ReadableStream with services) + * * ```ts * import { Context, Stream } from "effect" * @@ -17870,8 +19793,8 @@ export const toReadableStreamWith = dual< * const readableStream = Stream.toReadableStreamWith(stream, Context.empty()) * ``` * - * @since 2.0.0 - * @category Destructors + * @category destructors + * @since 4.0.0 */ ( context: Context.Context, @@ -17880,9 +19803,17 @@ export const toReadableStreamWith = dual< /** * Converts the stream to a `ReadableStream` using the provided services. * + * **When to use** + * + * Use when bridging to Web Streams and you already have the `Context` required + * to run the stream outside an `Effect`. + * + * **Details** + * * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream. * - * @example + * **Example** (Converting to a ReadableStream with services) + * * ```ts * import { Context, Stream } from "effect" * @@ -17890,8 +19821,8 @@ export const toReadableStreamWith = dual< * const readableStream = Stream.toReadableStreamWith(stream, Context.empty()) * ``` * - * @since 2.0.0 - * @category Destructors + * @category destructors + * @since 4.0.0 */ ( self: Stream, @@ -17948,9 +19879,12 @@ export const toReadableStreamWith = dual< /** * Converts a stream to a `ReadableStream`. * + * **Details** + * * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream. * - * @example + * **Example** (Converting a stream to a ReadableStream) + * * ```ts * import { Stream } from "effect" * @@ -17958,16 +19892,19 @@ export const toReadableStreamWith = dual< * const reader = readableStream.getReader() * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const toReadableStream: { /** * Converts a stream to a `ReadableStream`. * + * **Details** + * * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream. * - * @example + * **Example** (Converting a stream to a ReadableStream) + * * ```ts * import { Stream } from "effect" * @@ -17975,8 +19912,8 @@ export const toReadableStream: { * const reader = readableStream.getReader() * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ (options?: { readonly strategy?: QueuingStrategy | undefined }): ( self: Stream @@ -17984,9 +19921,12 @@ export const toReadableStream: { /** * Converts a stream to a `ReadableStream`. * + * **Details** + * * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream. * - * @example + * **Example** (Converting a stream to a ReadableStream) + * * ```ts * import { Stream } from "effect" * @@ -17994,8 +19934,8 @@ export const toReadableStream: { * const reader = readableStream.getReader() * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ ( self: Stream, @@ -18012,9 +19952,17 @@ export const toReadableStream: { /** * Creates an Effect that builds a ReadableStream from the stream. * + * **When to use** + * + * Use when bridging to Web Streams from inside an `Effect` so the required + * services can be captured from the current context. + * + * **Details** + * * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream. * - * @example + * **Example** (Creating a ReadableStream effect) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -18028,16 +19976,24 @@ export const toReadableStream: { * Effect.runPromise(effect) * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const toReadableStreamEffect: { /** * Creates an Effect that builds a ReadableStream from the stream. * + * **When to use** + * + * Use when bridging to Web Streams from inside an `Effect` so the required + * services can be captured from the current context. + * + * **Details** + * * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream. * - * @example + * **Example** (Creating a ReadableStream effect) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -18051,8 +20007,8 @@ export const toReadableStreamEffect: { * Effect.runPromise(effect) * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ (options?: { readonly strategy?: QueuingStrategy | undefined }): ( self: Stream @@ -18060,9 +20016,17 @@ export const toReadableStreamEffect: { /** * Creates an Effect that builds a ReadableStream from the stream. * + * **When to use** + * + * Use when bridging to Web Streams from inside an `Effect` so the required + * services can be captured from the current context. + * + * **Details** + * * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream. * - * @example + * **Example** (Creating a ReadableStream effect) + * * ```ts * import { Console, Effect, Stream } from "effect" * @@ -18076,8 +20040,8 @@ export const toReadableStreamEffect: { * Effect.runPromise(effect) * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ ( self: Stream, @@ -18093,9 +20057,17 @@ export const toReadableStreamEffect: { Effect.context(), (context) => toReadableStreamWith(self, context, options) @@ -18120,7 +20092,13 @@ export const toReadableStreamEffect: { /** * Converts the stream to an `AsyncIterable` using the provided services. * - * @example + * **When to use** + * + * Use when converting outside an Effect and you already have the `Context` + * needed to run the stream. + * + * **Example** (Converting to an AsyncIterable with services) + * * ```ts * import { Context, Stream } from "effect" * @@ -18132,18 +20110,27 @@ export const toReadableStreamEffect: { * for await (const value of iterable) { * results.push(value) * } - * return results + * console.log(results) * } + * + * collect() + * // [ 1, 2, 3 ] * ``` * - * @since 2.0.0 - * @category Destructors + * @category destructors + * @since 4.0.0 */ export const toAsyncIterableWith: { /** * Converts the stream to an `AsyncIterable` using the provided services. * - * @example + * **When to use** + * + * Use when converting outside an Effect and you already have the `Context` + * needed to run the stream. + * + * **Example** (Converting to an AsyncIterable with services) + * * ```ts * import { Context, Stream } from "effect" * @@ -18155,18 +20142,27 @@ export const toAsyncIterableWith: { * for await (const value of iterable) { * results.push(value) * } - * return results + * console.log(results) * } + * + * collect() + * // [ 1, 2, 3 ] * ``` * - * @since 2.0.0 - * @category Destructors + * @category destructors + * @since 4.0.0 */ (context: Context.Context): (self: Stream) => AsyncIterable /** * Converts the stream to an `AsyncIterable` using the provided services. * - * @example + * **When to use** + * + * Use when converting outside an Effect and you already have the `Context` + * needed to run the stream. + * + * **Example** (Converting to an AsyncIterable with services) + * * ```ts * import { Context, Stream } from "effect" * @@ -18178,12 +20174,15 @@ export const toAsyncIterableWith: { * for await (const value of iterable) { * results.push(value) * } - * return results + * console.log(results) * } + * + * collect() + * // [ 1, 2, 3 ] * ``` * - * @since 2.0.0 - * @category Destructors + * @category destructors + * @since 4.0.0 */ (self: Stream, context: Context.Context): AsyncIterable } = dual( @@ -18229,9 +20228,15 @@ export const toAsyncIterableWith: { /** * Creates an effect that yields an `AsyncIterable` using the current services. * - * @example + * **When to use** + * + * Use when the `AsyncIterable` should be created inside Effect with the current + * context supplying the stream's services. + * + * **Example** (Creating an AsyncIterable effect) + * * ```ts - * import { Console, Effect, Stream } from "effect" + * import { Effect, Stream } from "effect" * * const stream = Stream.make(1, 2, 3) * @@ -18244,15 +20249,15 @@ export const toAsyncIterableWith: { * } * return collected * }) - * yield* Console.log(values) + * yield* Effect.sync(() => console.log(values)) * }) * * Effect.runPromise(program) - * //=> [ 1, 2, 3 ] + * // [ 1, 2, 3 ] * ``` * - * @since 2.0.0 - * @category Destructors + * @category destructors + * @since 3.15.0 */ export const toAsyncIterableEffect = (self: Stream): Effect.Effect, never, R> => Effect.map( @@ -18263,27 +20268,28 @@ export const toAsyncIterableEffect = (self: Stream): Effect.Ef /** * Converts a stream to an `AsyncIterable` for `for await...of` consumption. * - * @example + * **Example** (Converting to an async iterable) + * * ```ts - * import { Effect, Stream } from "effect" + * import { Stream } from "effect" * * const stream = Stream.make(1, 2, 3) * - * const program = Effect.gen(function* () { + * const collect = async () => { * const iterable = Stream.toAsyncIterable(stream) - * const results = yield* Effect.promise(async () => { - * const values: Array = [] - * for await (const value of iterable) { - * values.push(value) - * } - * return values - * }) - * return results - * }) + * const values: Array = [] + * for await (const value of iterable) { + * values.push(value) + * } + * console.log(values) + * } + * + * collect() + * // [ 1, 2, 3 ] * ``` * - * @since 2.0.0 - * @category Destructors + * @category destructors + * @since 3.15.0 */ export const toAsyncIterable = (self: Stream): AsyncIterable => toAsyncIterableWith(self, Context.empty()) @@ -18291,10 +20297,13 @@ export const toAsyncIterable = (self: Stream): AsyncIterable => /** * Runs the stream, publishing elements into the provided PubSub. * + * **Details** + * * `shutdownOnEnd` controls whether the PubSub is shut down when the stream ends. * It only shuts down when set to `true`. * - * @example + * **Example** (Running a stream into a PubSub) + * * ```ts * import { Console, Effect, PubSub, Stream } from "effect" * @@ -18316,17 +20325,20 @@ export const toAsyncIterable = (self: Stream): AsyncIterable => * //=> 2 * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const runIntoPubSub: { /** * Runs the stream, publishing elements into the provided PubSub. * + * **Details** + * * `shutdownOnEnd` controls whether the PubSub is shut down when the stream ends. * It only shuts down when set to `true`. * - * @example + * **Example** (Running a stream into a PubSub) + * * ```ts * import { Console, Effect, PubSub, Stream } from "effect" * @@ -18348,8 +20360,8 @@ export const runIntoPubSub: { * //=> 2 * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ ( pubsub: PubSub.PubSub, @@ -18360,10 +20372,13 @@ export const runIntoPubSub: { /** * Runs the stream, publishing elements into the provided PubSub. * + * **Details** + * * `shutdownOnEnd` controls whether the PubSub is shut down when the stream ends. * It only shuts down when set to `true`. * - * @example + * **Example** (Running a stream into a PubSub) + * * ```ts * import { Console, Effect, PubSub, Stream } from "effect" * @@ -18385,8 +20400,8 @@ export const runIntoPubSub: { * //=> 2 * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ ( self: Stream, @@ -18404,12 +20419,15 @@ export const runIntoPubSub: { ): Effect.Effect => Channel.runIntoPubSubArray(self.channel, pubsub, options)) /** - * Converts a stream to a PubSub for concurrent consumption. + * Converts a stream to a PubSub of emitted values for concurrent consumption. + * + * **Details** * * `shutdownOnEnd` indicates whether the PubSub should be shut down when the * stream ends. By default this is `true`. * - * @example + * **Example** (Converting a stream to a PubSub for concurrent consumption) + * * ```ts * import { Console, Effect, PubSub, Stream } from "effect" * @@ -18424,17 +20442,20 @@ export const runIntoPubSub: { * })) * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const toPubSub: { /** - * Converts a stream to a PubSub for concurrent consumption. + * Converts a stream to a PubSub of emitted values for concurrent consumption. + * + * **Details** * * `shutdownOnEnd` indicates whether the PubSub should be shut down when the * stream ends. By default this is `true`. * - * @example + * **Example** (Converting a stream to a PubSub for concurrent consumption) + * * ```ts * import { Console, Effect, PubSub, Stream } from "effect" * @@ -18449,8 +20470,8 @@ export const toPubSub: { * })) * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ ( options: { @@ -18465,12 +20486,15 @@ export const toPubSub: { } ): (self: Stream) => Effect.Effect, never, R | Scope.Scope> /** - * Converts a stream to a PubSub for concurrent consumption. + * Converts a stream to a PubSub of emitted values for concurrent consumption. + * + * **Details** * * `shutdownOnEnd` indicates whether the PubSub should be shut down when the * stream ends. By default this is `true`. * - * @example + * **Example** (Converting a stream to a PubSub for concurrent consumption) + * * ```ts * import { Console, Effect, PubSub, Stream } from "effect" * @@ -18485,8 +20509,8 @@ export const toPubSub: { * })) * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ ( self: Stream, @@ -18519,11 +20543,14 @@ export const toPubSub: { ) /** - * Converts a stream to a PubSub for concurrent consumption. + * Converts a stream to a PubSub of `Take` values for concurrent consumption. + * + * **Details** * * `Take` values include the stream's end and failure signals. * - * @example + * **Example** (Converting to a PubSub of takes) + * * ```ts * import { Console, Effect, PubSub, Stream } from "effect" * @@ -18540,16 +20567,19 @@ export const toPubSub: { * }) * ``` * + * @category destructors * @since 4.0.0 - * @category Destructors */ export const toPubSubTake: { /** - * Converts a stream to a PubSub for concurrent consumption. + * Converts a stream to a PubSub of `Take` values for concurrent consumption. + * + * **Details** * * `Take` values include the stream's end and failure signals. * - * @example + * **Example** (Converting to a PubSub of takes) + * * ```ts * import { Console, Effect, PubSub, Stream } from "effect" * @@ -18566,8 +20596,8 @@ export const toPubSubTake: { * }) * ``` * + * @category destructors * @since 4.0.0 - * @category Destructors */ ( options: { @@ -18580,11 +20610,14 @@ export const toPubSubTake: { } ): (self: Stream) => Effect.Effect>, never, R | Scope.Scope> /** - * Converts a stream to a PubSub for concurrent consumption. + * Converts a stream to a PubSub of `Take` values for concurrent consumption. + * + * **Details** * * `Take` values include the stream's end and failure signals. * - * @example + * **Example** (Converting to a PubSub of takes) + * * ```ts * import { Console, Effect, PubSub, Stream } from "effect" * @@ -18601,8 +20634,8 @@ export const toPubSubTake: { * }) * ``` * + * @category destructors * @since 4.0.0 - * @category Destructors */ ( self: Stream, @@ -18632,9 +20665,17 @@ export const toPubSubTake: { ) /** - * Converts a stream to a Queue for concurrent consumption. + * Creates a scoped dequeue that is fed by the stream for concurrent + * consumption. + * + * **Details** + * + * Elements are offered to the queue as the stream runs. Stream completion is + * signaled with `Cause.Done`, stream failures fail the queue, and the queue is + * shut down when the surrounding scope closes. + * + * **Example** (Converting a stream to a Queue for concurrent consumption) * - * @example * ```ts * import { Effect, Queue, Stream } from "effect" * @@ -18645,14 +20686,22 @@ export const toPubSubTake: { * }) * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const toQueue: { /** - * Converts a stream to a Queue for concurrent consumption. + * Creates a scoped dequeue that is fed by the stream for concurrent + * consumption. + * + * **Details** + * + * Elements are offered to the queue as the stream runs. Stream completion is + * signaled with `Cause.Done`, stream failures fail the queue, and the queue is + * shut down when the surrounding scope closes. + * + * **Example** (Converting a stream to a Queue for concurrent consumption) * - * @example * ```ts * import { Effect, Queue, Stream } from "effect" * @@ -18663,8 +20712,8 @@ export const toQueue: { * }) * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ ( options: { @@ -18675,9 +20724,17 @@ export const toQueue: { } ): (self: Stream) => Effect.Effect, never, R | Scope.Scope> /** - * Converts a stream to a Queue for concurrent consumption. + * Creates a scoped dequeue that is fed by the stream for concurrent + * consumption. + * + * **Details** + * + * Elements are offered to the queue as the stream runs. Stream completion is + * signaled with `Cause.Done`, stream failures fail the queue, and the queue is + * shut down when the surrounding scope closes. + * + * **Example** (Converting a stream to a Queue for concurrent consumption) * - * @example * ```ts * import { Effect, Queue, Stream } from "effect" * @@ -18688,8 +20745,8 @@ export const toQueue: { * }) * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ ( self: Stream, @@ -18718,7 +20775,8 @@ export const toQueue: { * Runs the stream, offering each element to the provided queue and ending it * with `Cause.Done` when the stream completes. * - * @example + * **Example** (Running a stream into a queue) + * * ```ts * import { Cause, Effect, Queue, Stream } from "effect" * @@ -18740,15 +20798,16 @@ export const toQueue: { * }) * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ export const runIntoQueue: { /** * Runs the stream, offering each element to the provided queue and ending it * with `Cause.Done` when the stream completes. * - * @example + * **Example** (Running a stream into a queue) + * * ```ts * import { Cause, Effect, Queue, Stream } from "effect" * @@ -18770,15 +20829,16 @@ export const runIntoQueue: { * }) * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ (queue: Queue.Queue): (self: Stream) => Effect.Effect /** * Runs the stream, offering each element to the provided queue and ending it * with `Cause.Done` when the stream completes. * - * @example + * **Example** (Running a stream into a queue) + * * ```ts * import { Cause, Effect, Queue, Stream } from "effect" * @@ -18800,8 +20860,8 @@ export const runIntoQueue: { * }) * ``` * + * @category destructors * @since 2.0.0 - * @category Destructors */ (self: Stream, queue: Queue.Queue): Effect.Effect } = dual(2, ( diff --git a/.opencode/node_modules/effect/src/String.ts b/.opencode/node_modules/effect/src/String.ts index a374902bc2e0cd4cc2950c5447b52a10d436b631..c04a8f8f93450eb5a7ad516795be9ee3361f97e1 100644 --- a/.opencode/node_modules/effect/src/String.ts +++ b/.opencode/node_modules/effect/src/String.ts @@ -1,6 +1,10 @@ /** - * This module provides utility functions and type class instances for working with the `string` type in TypeScript. - * It includes functions for basic string manipulation. + * Works with TypeScript `string` values. + * + * This module exposes common string operations in a pipe-friendly style. The + * helpers cover checks, comparison, concatenation, trimming, casing, slicing, + * padding, replacement, normalization, safe character access, search helpers + * that return `Option`, and joining strings through a reducer. * * @since 2.0.0 */ @@ -18,7 +22,19 @@ import * as predicate from "./Predicate.ts" import * as Reducer from "./Reducer.ts" /** - * Reference to the global `String` constructor. + * Exposes the global string constructor. + * + * **When to use** + * + * Use to access native JavaScript string coercion or constructor behavior from + * the Effect module namespace. + * + * **Gotchas** + * + * Calling `String(value)` returns a primitive string. Calling + * `new String(value)` creates a boxed `String` object. + * + * @see {@link isString} for checking whether a value is a primitive string * * @category constructors * @since 4.0.0 @@ -26,9 +42,10 @@ import * as Reducer from "./Reducer.ts" export const String = globalThis.String /** - * Tests if a value is a `string`. + * Checks whether a value is a `string`. + * + * **Example** (Checking for strings) * - * @example * ```ts * import { String } from "effect" * import * as assert from "node:assert" @@ -43,9 +60,11 @@ export const String = globalThis.String export const isString: Refinement = predicate.isString /** - * `Order` instance for comparing strings using lexicographic ordering. + * Provides an `Order` instance for comparing strings using lexicographic + * ordering. + * + * **Example** (Comparing strings lexicographically) * - * @example * ```ts * import { String } from "effect" * @@ -60,9 +79,10 @@ export const isString: Refinement = predicate.isString export const Order: order.Order = order.String /** - * An `Equivalence` instance for strings using strict equality (`===`). + * Provides an `Equivalence` instance for strings using strict equality (`===`). + * + * **Example** (Comparing strings for equality) * - * @example * ```ts * import { String } from "effect" * @@ -71,14 +91,19 @@ export const Order: order.Order = order.String * ``` * * @category instances - * @since 4.0.0 + * @since 2.0.0 */ export const Equivalence: Equ.Equivalence = Equ.String /** - * The empty string `""`. + * Provides the empty string `""`. + * + * **When to use** + * + * Use when you need the canonical empty string value from the `String` module. + * + * **Example** (Using the empty string) * - * @example * ```ts * import { String } from "effect" * @@ -86,7 +111,7 @@ export const Equivalence: Equ.Equivalence = Equ.String * console.log(String.isEmpty(String.empty)) // true * ``` * - * @category constructors + * @category constants * @since 2.0.0 */ export const empty: "" = "" as const @@ -94,7 +119,8 @@ export const empty: "" = "" as const /** * Concatenates two strings at the type level. * - * @example + * **Example** (Concatenating string literal types) + * * ```ts * import type { String } from "effect" * @@ -110,7 +136,8 @@ export type Concat = `${A}${B}` /** * Concatenates two strings at runtime. * - * @example + * **Example** (Concatenating strings) + * * ```ts * import { pipe, String } from "effect" * @@ -121,14 +148,15 @@ export type Concat = `${A}${B}` * console.log(result2) // "helloworld" * ``` * - * @category concatenating + * @category combining * @since 2.0.0 */ export const concat: { /** * Concatenates two strings at runtime. * - * @example + * **Example** (Concatenating strings) + * * ```ts * import { pipe, String } from "effect" * @@ -139,14 +167,15 @@ export const concat: { * console.log(result2) // "helloworld" * ``` * - * @category concatenating + * @category combining * @since 2.0.0 */ (that: B): (self: A) => Concat /** * Concatenates two strings at runtime. * - * @example + * **Example** (Concatenating strings) + * * ```ts * import { pipe, String } from "effect" * @@ -157,7 +186,7 @@ export const concat: { * console.log(result2) // "helloworld" * ``` * - * @category concatenating + * @category combining * @since 2.0.0 */ (self: A, that: B): Concat @@ -166,7 +195,8 @@ export const concat: { /** * Converts a string to uppercase. * - * @example + * **Example** (Converting strings to uppercase) + * * ```ts * import { pipe, String } from "effect" * import * as assert from "node:assert" @@ -183,7 +213,8 @@ export const toUpperCase = (self: S): Uppercase => self.toU /** * Converts a string to lowercase. * - * @example + * **Example** (Converting strings to lowercase) + * * ```ts * import { pipe, String } from "effect" * import * as assert from "node:assert" @@ -200,7 +231,8 @@ export const toLowerCase = (self: T): Lowercase => self.toL /** * Capitalizes the first character of a string. * - * @example + * **Example** (Capitalizing a string) + * * ```ts * import { pipe, String } from "effect" * import * as assert from "node:assert" @@ -221,7 +253,8 @@ export const capitalize = (self: T): Capitalize => { /** * Uncapitalizes the first character of a string. * - * @example + * **Example** (Uncapitalizing a string) + * * ```ts * import { pipe, String } from "effect" * import * as assert from "node:assert" @@ -240,9 +273,15 @@ export const uncapitalize = (self: T): Uncapitalize => { } /** - * Replaces the first occurrence of a substring or pattern in a string. + * Replaces matches in a string using `String.prototype.replace`. + * + * **Details** + * + * String search values and non-global regular expressions replace the first + * match; global regular expressions replace every match. + * + * **Example** (Replacing a substring) * - * @example * ```ts * import { pipe, String } from "effect" * import * as assert from "node:assert" @@ -263,7 +302,8 @@ export const replace = (searchValue: string | RegExp, replaceValue: string) => ( /** * Type-level representation of trimming whitespace from both ends of a string. * - * @example + * **Example** (Trimming whitespace at the type level) + * * ```ts * import type { String } from "effect" * @@ -278,7 +318,8 @@ export type Trim = TrimEnd> /** * Removes whitespace from both ends of a string. * - * @example + * **Example** (Trimming whitespace) + * * ```ts * import { String } from "effect" * import * as assert from "node:assert" @@ -295,7 +336,8 @@ export const trim = (self: A): Trim => self.trim() as Trim< /** * Type-level representation of trimming whitespace from the start of a string. * - * @example + * **Example** (Trimming leading whitespace at the type level) + * * ```ts * import type { String } from "effect" * @@ -310,7 +352,8 @@ export type TrimStart = A extends `${" " | "\n" | "\t" | "\r"} /** * Removes whitespace from the start of a string. * - * @example + * **Example** (Trimming leading whitespace) + * * ```ts * import { String } from "effect" * import * as assert from "node:assert" @@ -327,7 +370,8 @@ export const trimStart = (self: A): TrimStart => self.trimS /** * Type-level representation of trimming whitespace from the end of a string. * - * @example + * **Example** (Trimming trailing whitespace at the type level) + * * ```ts * import type { String } from "effect" * @@ -342,7 +386,8 @@ export type TrimEnd = A extends `${infer B}${" " | "\n" | "\t" /** * Removes whitespace from the end of a string. * - * @example + * **Example** (Trimming trailing whitespace) + * * ```ts * import { String } from "effect" * import * as assert from "node:assert" @@ -359,7 +404,8 @@ export const trimEnd = (self: A): TrimEnd => self.trimEnd() /** * Extracts a section of a string and returns it as a new string. * - * @example + * **Example** (Slicing strings) + * * ```ts * import { pipe, String } from "effect" * import * as assert from "node:assert" @@ -374,9 +420,10 @@ export const trimEnd = (self: A): TrimEnd => self.trimEnd() export const slice = (start?: number, end?: number) => (self: string): string => self.slice(start, end) /** - * Test whether a `string` is empty. + * Checks whether a `string` is empty. + * + * **Example** (Checking for empty strings) * - * @example * ```ts * import { String } from "effect" * import * as assert from "node:assert" @@ -391,9 +438,10 @@ export const slice = (start?: number, end?: number) => (self: string): string => export const isEmpty = (self: string): self is "" => self.length === 0 /** - * Test whether a `string` is non empty. + * Checks whether a `string` is non-empty. + * + * **Example** (Checking for non-empty strings) * - * @example * ```ts * import { String } from "effect" * import * as assert from "node:assert" @@ -408,9 +456,10 @@ export const isEmpty = (self: string): self is "" => self.length === 0 export const isNonEmpty = (self: string): boolean => self.length > 0 /** - * Calculate the number of characters in a `string`. + * Returns the JavaScript string length, measured in UTF-16 code units. + * + * **Example** (Getting string length) * - * @example * ```ts * import { String } from "effect" * import * as assert from "node:assert" @@ -418,7 +467,7 @@ export const isNonEmpty = (self: string): boolean => self.length > 0 * assert.deepStrictEqual(String.length("abc"), 3) * ``` * - * @category utilities + * @category getters * @since 2.0.0 */ export const length = (self: string): number => self.length @@ -426,7 +475,8 @@ export const length = (self: string): number => self.length /** * Splits a string into an array of substrings using a separator. * - * @example + * **Example** (Splitting strings) + * * ```ts * import { pipe, String } from "effect" * import * as assert from "node:assert" @@ -443,7 +493,8 @@ export const split: { /** * Splits a string into an array of substrings using a separator. * - * @example + * **Example** (Splitting strings) + * * ```ts * import { pipe, String } from "effect" * import * as assert from "node:assert" @@ -460,7 +511,8 @@ export const split: { /** * Splits a string into an array of substrings using a separator. * - * @example + * **Example** (Splitting strings) + * * ```ts * import { pipe, String } from "effect" * import * as assert from "node:assert" @@ -483,7 +535,8 @@ export const split: { * Returns `true` if `searchString` appears as a substring of `self`, at one or more positions that are * greater than or equal to `position`; otherwise, returns `false`. * - * @example + * **Example** (Checking for substrings) + * * ```ts * import { pipe, String } from "effect" * import * as assert from "node:assert" @@ -501,7 +554,8 @@ export const includes = (searchString: string, position?: number) => (self: stri /** * Returns `true` if the string starts with the specified search string. * - * @example + * **Example** (Checking string prefixes) + * * ```ts * import { pipe, String } from "effect" * import * as assert from "node:assert" @@ -519,7 +573,8 @@ export const startsWith = (searchString: string, position?: number) => (self: st /** * Returns `true` if the string ends with the specified search string. * - * @example + * **Example** (Checking string suffixes) + * * ```ts * import { pipe, String } from "effect" * import * as assert from "node:assert" @@ -535,9 +590,9 @@ export const endsWith = (searchString: string, position?: number) => (self: stri self.endsWith(searchString, position) /** - * Returns the character code at the specified index, or `None` if the index is out of bounds. + * Returns the character code at the specified index safely, or `None` if the index is out of bounds. * - * **Example** + * **Example** (Reading character codes) * * ```ts * import { String } from "effect" @@ -551,9 +606,9 @@ export const endsWith = (searchString: string, position?: number) => (self: stri */ export const charCodeAt: { /** - * Returns the character code at the specified index, or `None` if the index is out of bounds. + * Returns the character code at the specified index safely, or `None` if the index is out of bounds. * - * **Example** + * **Example** (Reading character codes) * * ```ts * import { String } from "effect" @@ -567,9 +622,9 @@ export const charCodeAt: { */ (index: number): (self: string) => Option.Option /** - * Returns the character code at the specified index, or `None` if the index is out of bounds. + * Returns the character code at the specified index safely, or `None` if the index is out of bounds. * - * **Example** + * **Example** (Reading character codes) * * ```ts * import { String } from "effect" @@ -591,7 +646,7 @@ export const charCodeAt: { /** * Extracts characters from a string between two specified indices. * - * **Example** + * **Example** (Extracting substrings) * * ```ts * import { pipe, String } from "effect" @@ -606,9 +661,9 @@ export const charCodeAt: { export const substring = (start: number, end?: number) => (self: string): string => self.substring(start, end) /** - * Returns the character at the specified index, or `None` if the index is out of bounds. + * Returns the character at the specified relative index safely, or `None` if the index is out of bounds. * - * **Example** + * **Example** (Accessing characters safely) * * ```ts * import { pipe, String } from "effect" @@ -622,9 +677,9 @@ export const substring = (start: number, end?: number) => (self: string): string */ export const at: { /** - * Returns the character at the specified index, or `None` if the index is out of bounds. + * Returns the character at the specified relative index safely, or `None` if the index is out of bounds. * - * **Example** + * **Example** (Accessing characters safely) * * ```ts * import { pipe, String } from "effect" @@ -638,9 +693,9 @@ export const at: { */ (index: number): (self: string) => Option.Option /** - * Returns the character at the specified index, or `None` if the index is out of bounds. + * Returns the character at the specified relative index safely, or `None` if the index is out of bounds. * - * **Example** + * **Example** (Accessing characters safely) * * ```ts * import { pipe, String } from "effect" @@ -656,9 +711,9 @@ export const at: { } = dual(2, (self: string, index: number): Option.Option => Option.fromUndefinedOr(self.at(index))) /** - * Returns the character at the specified index, or `None` if the index is out of bounds. + * Returns the character at the specified non-negative index safely, or `None` if the index is out of bounds. * - * **Example** + * **Example** (Reading characters safely) * * ```ts * import { pipe, String } from "effect" @@ -672,9 +727,9 @@ export const at: { */ export const charAt: { /** - * Returns the character at the specified index, or `None` if the index is out of bounds. + * Returns the character at the specified non-negative index safely, or `None` if the index is out of bounds. * - * **Example** + * **Example** (Reading characters safely) * * ```ts * import { pipe, String } from "effect" @@ -688,9 +743,9 @@ export const charAt: { */ (index: number): (self: string) => Option.Option /** - * Returns the character at the specified index, or `None` if the index is out of bounds. + * Returns the character at the specified non-negative index safely, or `None` if the index is out of bounds. * - * **Example** + * **Example** (Reading characters safely) * * ```ts * import { pipe, String } from "effect" @@ -709,9 +764,9 @@ export const charAt: { ) /** - * Returns the Unicode code point at the specified index, or `None` if the index is out of bounds. + * Returns the Unicode code point at the specified index safely, or `None` if the index is out of bounds. * - * **Example** + * **Example** (Reading code points) * * ```ts * import { pipe, String } from "effect" @@ -725,9 +780,9 @@ export const charAt: { */ export const codePointAt: { /** - * Returns the Unicode code point at the specified index, or `None` if the index is out of bounds. + * Returns the Unicode code point at the specified index safely, or `None` if the index is out of bounds. * - * **Example** + * **Example** (Reading code points) * * ```ts * import { pipe, String } from "effect" @@ -741,9 +796,9 @@ export const codePointAt: { */ (index: number): (self: string) => Option.Option /** - * Returns the Unicode code point at the specified index, or `None` if the index is out of bounds. + * Returns the Unicode code point at the specified index safely, or `None` if the index is out of bounds. * - * **Example** + * **Example** (Reading code points) * * ```ts * import { pipe, String } from "effect" @@ -759,9 +814,9 @@ export const codePointAt: { } = dual(2, (self: string, index: number): Option.Option => Option.fromUndefinedOr(self.codePointAt(index))) /** - * Returns the index of the first occurrence of a substring, or `None` if not found. + * Returns the index of the first occurrence of a substring safely, or `None` if not found. * - * **Example** + * **Example** (Finding the first substring index) * * ```ts * import { pipe, String } from "effect" @@ -777,9 +832,9 @@ export const indexOf = (searchString: string) => (self: string): Option.Option (self: string): Option.Opti Option.filter(Option.some(self.lastIndexOf(searchString)), number.isGreaterThanOrEqualTo(0)) /** - * Compares two strings according to the current locale. + * Computes locale-aware ordering for two strings, with optional locales and + * collator options, and returns the result as an `Ordering` (`-1`, `0`, or + * `1`). + * + * **Example** (Comparing strings by locale) * - * @example * ```ts * import { pipe, String } from "effect" * import * as assert from "node:assert" @@ -815,15 +873,21 @@ export const localeCompare = number.sign(self.localeCompare(that, locales, options)) /** - * A `pipe`-able version of the native `match` method. + * Matches a string against a pattern safely and returns `Option.some` with the match + * array, or `Option.none` when the pattern does not match. * - * **Example** + * **Example** (Matching regular expressions) * * ```ts - * import { pipe, String } from "effect" + * import { Option, pipe, String } from "effect" + * + * const match = pipe("hello", String.match(/l+/)) * - * pipe("hello", String.match(/l+/)) // Option.some(["ll"]) - * pipe("hello", String.match(/x/)) // Option.none() + * if (Option.isSome(match)) { + * console.log(`${match.value[0]}@${match.value.index}`) // "ll@2" + * } + * + * console.log(Option.isNone(pipe("hello", String.match(/x/)))) // true * ``` * * @category searching @@ -833,14 +897,18 @@ export const match = (regExp: RegExp | string) => (self: string): Option.Option< Option.fromNullOr(self.match(regExp)) /** - * It is the `pipe`-able version of the native `matchAll` method. + * Returns an iterator over all regular expression matches in the string using + * native `String.prototype.matchAll` semantics. + * + * **Example** (Iterating regular expression matches) * - * @example * ```ts * import { pipe, String } from "effect" * * const matches = pipe("hello world", String.matchAll(/l/g)) - * console.log(Array.from(matches)) // [["l"], ["l"], ["l"]] + * console.log( + * Array.from(matches, (match) => `${match[0]}@${match.index}`).join(", ") + * ) // "l@2, l@3, l@9" * ``` * * @category searching @@ -851,7 +919,8 @@ export const matchAll = (regExp: RegExp) => (self: string): IterableIterator (self: stri /** * Pads the string from the end with a given fill string to a specified length. * - * @example + * **Example** (Padding strings at the end) + * * ```ts * import { pipe, String } from "effect" * import * as assert from "node:assert" @@ -893,7 +963,8 @@ export const padEnd = (maxLength: number, fillString?: string) => (self: string) /** * Pads the string from the start with a given fill string to a specified length. * - * @example + * **Example** (Padding strings at the start) + * * ```ts * import { pipe, String } from "effect" * import * as assert from "node:assert" @@ -911,7 +982,8 @@ export const padStart = (maxLength: number, fillString?: string) => (self: strin /** * Repeats the string the specified number of times. * - * @example + * **Example** (Repeating strings) + * * ```ts * import { pipe, String } from "effect" * import * as assert from "node:assert" @@ -928,7 +1000,8 @@ export const repeat = (count: number) => (self: string): string => self.repeat(c /** * Replaces all occurrences of a substring or pattern in a string. * - * @example + * **Example** (Replacing all matches) + * * ```ts * import { pipe, String } from "effect" * import * as assert from "node:assert" @@ -944,9 +1017,10 @@ export const replaceAll = (searchValue: string | RegExp, replaceValue: string) = self.replaceAll(searchValue, replaceValue) /** - * Searches for a match between a regular expression and the string. + * Returns the index of the first match for a string or regular expression safely, or + * `Option.none` when no match is found. * - * **Example** + * **Example** (Searching strings) * * ```ts * import { String } from "effect" @@ -961,9 +1035,10 @@ export const replaceAll = (searchValue: string | RegExp, replaceValue: string) = */ export const search: { /** - * Searches for a match between a regular expression and the string. + * Returns the index of the first match for a string or regular expression safely, or + * `Option.none` when no match is found. * - * **Example** + * **Example** (Searching strings) * * ```ts * import { String } from "effect" @@ -978,9 +1053,10 @@ export const search: { */ (regExp: RegExp | string): (self: string) => Option.Option /** - * Searches for a match between a regular expression and the string. + * Returns the index of the first match for a string or regular expression safely, or + * `Option.none` when no match is found. * - * **Example** + * **Example** (Searching strings) * * ```ts * import { String } from "effect" @@ -1003,7 +1079,8 @@ export const search: { /** * Converts the string to lowercase according to the specified locale. * - * @example + * **Example** (Lowercasing strings by locale) + * * ```ts * import { pipe, String } from "effect" * import * as assert from "node:assert" @@ -1021,7 +1098,8 @@ export const toLocaleLowerCase = (locale?: string | Array) => (self: str /** * Converts the string to uppercase according to the specified locale. * - * @example + * **Example** (Uppercasing strings by locale) + * * ```ts * import { pipe, String } from "effect" * import * as assert from "node:assert" @@ -1037,7 +1115,9 @@ export const toLocaleUpperCase = (locale?: string | Array) => (self: str self.toLocaleUpperCase(locale) /** - * Keep the specified number of characters from the start of a string. + * Keeps the specified number of characters from the start of a string. + * + * **Details** * * If `n` is larger than the available number of characters, the string will * be returned whole. @@ -1046,7 +1126,8 @@ export const toLocaleUpperCase = (locale?: string | Array) => (self: str * * If `n` is a float, it will be rounded down to the nearest integer. * - * @example + * **Example** (Taking characters from the start) + * * ```ts * import { String } from "effect" * import * as assert from "node:assert" @@ -1059,7 +1140,9 @@ export const toLocaleUpperCase = (locale?: string | Array) => (self: str */ export const takeLeft: { /** - * Keep the specified number of characters from the start of a string. + * Keeps the specified number of characters from the start of a string. + * + * **Details** * * If `n` is larger than the available number of characters, the string will * be returned whole. @@ -1068,7 +1151,8 @@ export const takeLeft: { * * If `n` is a float, it will be rounded down to the nearest integer. * - * @example + * **Example** (Taking characters from the start) + * * ```ts * import { String } from "effect" * import * as assert from "node:assert" @@ -1081,7 +1165,9 @@ export const takeLeft: { */ (n: number): (self: string) => string /** - * Keep the specified number of characters from the start of a string. + * Keeps the specified number of characters from the start of a string. + * + * **Details** * * If `n` is larger than the available number of characters, the string will * be returned whole. @@ -1090,7 +1176,8 @@ export const takeLeft: { * * If `n` is a float, it will be rounded down to the nearest integer. * - * @example + * **Example** (Taking characters from the start) + * * ```ts * import { String } from "effect" * import * as assert from "node:assert" @@ -1105,7 +1192,9 @@ export const takeLeft: { } = dual(2, (self: string, n: number): string => self.slice(0, Math.max(n, 0))) /** - * Keep the specified number of characters from the end of a string. + * Keeps the specified number of characters from the end of a string. + * + * **Details** * * If `n` is larger than the available number of characters, the string will * be returned whole. @@ -1114,7 +1203,8 @@ export const takeLeft: { * * If `n` is a float, it will be rounded down to the nearest integer. * - * @example + * **Example** (Taking characters from the end) + * * ```ts * import { String } from "effect" * import * as assert from "node:assert" @@ -1127,7 +1217,9 @@ export const takeLeft: { */ export const takeRight: { /** - * Keep the specified number of characters from the end of a string. + * Keeps the specified number of characters from the end of a string. + * + * **Details** * * If `n` is larger than the available number of characters, the string will * be returned whole. @@ -1136,7 +1228,8 @@ export const takeRight: { * * If `n` is a float, it will be rounded down to the nearest integer. * - * @example + * **Example** (Taking characters from the end) + * * ```ts * import { String } from "effect" * import * as assert from "node:assert" @@ -1149,7 +1242,9 @@ export const takeRight: { */ (n: number): (self: string) => string /** - * Keep the specified number of characters from the end of a string. + * Keeps the specified number of characters from the end of a string. + * + * **Details** * * If `n` is larger than the available number of characters, the string will * be returned whole. @@ -1158,7 +1253,8 @@ export const takeRight: { * * If `n` is a float, it will be rounded down to the nearest integer. * - * @example + * **Example** (Taking characters from the end) + * * ```ts * import { String } from "effect" * import * as assert from "node:assert" @@ -1182,7 +1278,8 @@ const LF = 0x0a * Returns an `IterableIterator` which yields each line contained within the * string, trimming off the trailing newline character. * - * @example + * **Example** (Iterating lines without separators) + * * ```ts * import { String } from "effect" * @@ -1199,7 +1296,8 @@ export const linesIterator = (self: string): LinesIterator => linesSeparated(sel * Returns an `IterableIterator` which yields each line contained within the * string as well as the trailing newline character. * - * @example + * **Example** (Iterating lines with separators) + * * ```ts * import { String } from "effect" * @@ -1213,11 +1311,11 @@ export const linesIterator = (self: string): LinesIterator => linesSeparated(sel export const linesWithSeparators = (s: string): LinesIterator => linesSeparated(s, false) /** - * For every line in this string, strip a leading prefix consisting of blanks - * or control characters followed by the character specified by `marginChar` - * from the line. + * Strips a leading margin prefix from every line using the supplied margin + * character. + * + * **Example** (Stripping custom margins) * - * @example * ```ts * import { String } from "effect" * @@ -1231,11 +1329,11 @@ export const linesWithSeparators = (s: string): LinesIterator => linesSeparated( */ export const stripMarginWith: { /** - * For every line in this string, strip a leading prefix consisting of blanks - * or control characters followed by the character specified by `marginChar` - * from the line. + * Strips a leading margin prefix from every line using the supplied margin + * character. + * + * **Example** (Stripping custom margins) * - * @example * ```ts * import { String } from "effect" * @@ -1249,11 +1347,11 @@ export const stripMarginWith: { */ (marginChar: string): (self: string) => string /** - * For every line in this string, strip a leading prefix consisting of blanks - * or control characters followed by the character specified by `marginChar` - * from the line. + * Strips a leading margin prefix from every line using the supplied margin + * character. + * + * **Example** (Stripping custom margins) * - * @example * ```ts * import { String } from "effect" * @@ -1287,10 +1385,10 @@ export const stripMarginWith: { }) /** - * For every line in this string, strip a leading prefix consisting of blanks - * or control characters followed by the `"|"` character from the line. + * Strips a leading `|` margin prefix from every line. + * + * **Example** (Stripping pipe margins) * - * @example * ```ts * import { String } from "effect" * @@ -1307,7 +1405,8 @@ export const stripMargin = (self: string): string => stripMarginWith(self, "|") /** * Converts a snake_case string to camelCase. * - * @example + * **Example** (Converting snake_case to camelCase) + * * ```ts * import { String } from "effect" * @@ -1329,7 +1428,8 @@ export const snakeToCamel = (self: string): string => { /** * Converts a snake_case string to PascalCase. * - * @example + * **Example** (Converting snake_case to PascalCase) + * * ```ts * import { String } from "effect" * @@ -1351,7 +1451,8 @@ export const snakeToPascal = (self: string): string => { /** * Converts a snake_case string to kebab-case. * - * @example + * **Example** (Converting snake_case to kebab-case) + * * ```ts * import { String } from "effect" * @@ -1367,7 +1468,8 @@ export const snakeToKebab = (self: string): string => self.replace(/_/g, "-") /** * Converts a camelCase string to snake_case. * - * @example + * **Example** (Converting camelCase to snake_case) + * * ```ts * import { String } from "effect" * @@ -1383,7 +1485,8 @@ export const camelToSnake = (self: string): string => self.replace(/([A-Z])/g, " /** * Converts a PascalCase string to snake_case. * - * @example + * **Example** (Converting PascalCase to snake_case) + * * ```ts * import { String } from "effect" * @@ -1400,7 +1503,8 @@ export const pascalToSnake = (self: string): string => /** * Converts a kebab-case string to snake_case. * - * @example + * **Example** (Converting kebab-case to snake_case) + * * ```ts * import { String } from "effect" * @@ -1461,7 +1565,7 @@ class LinesIterator implements IterableIterator { } /** - * Test if the provided character is a line break character (i.e. either `"\r"` + * Checks whether the provided character is a line break character (i.e. either `"\r"` * or `"\n"`). */ const isLineBreak = (char: string): boolean => { @@ -1470,7 +1574,7 @@ const isLineBreak = (char: string): boolean => { } /** - * Test if the provided characters combine to form a carriage return/line-feed + * Checks whether the provided characters combine to form a carriage return/line-feed * (i.e. `"\r\n"`). */ const isLineBreak2 = (char0: string, char1: string): boolean => char0.charCodeAt(0) === CR && char1.charCodeAt(0) === LF @@ -1478,14 +1582,38 @@ const isLineBreak2 = (char0: string, char1: string): boolean => char0.charCodeAt const linesSeparated = (self: string, stripped: boolean): LinesIterator => new LinesIterator(self, stripped) /** - * Normalize a string to a specific case format + * Normalizes a string by splitting it into word parts, transforming each part, + * and joining the parts with a configurable delimiter. + * + * **When to use** + * + * Use when you need custom word-case output with a delimiter or part transform + * that the fixed case helpers do not provide. + * + * @see {@link pascalCase} for fixed PascalCase output + * @see {@link camelCase} for fixed lower-initial camelCase output + * @see {@link constantCase} for fixed uppercase underscore-separated output + * @see {@link kebabCase} for fixed lowercase hyphen-separated output + * @see {@link snakeCase} for fixed lowercase underscore-separated output * * @category transforming * @since 4.0.0 */ export const noCase: { /** - * Normalize a string to a specific case format + * Normalizes a string by splitting it into word parts, transforming each part, + * and joining the parts with a configurable delimiter. + * + * **When to use** + * + * Use when you need custom word-case output with a delimiter or part transform + * that the fixed case helpers do not provide. + * + * @see {@link pascalCase} for fixed PascalCase output + * @see {@link camelCase} for fixed lower-initial camelCase output + * @see {@link constantCase} for fixed uppercase underscore-separated output + * @see {@link kebabCase} for fixed lowercase hyphen-separated output + * @see {@link snakeCase} for fixed lowercase underscore-separated output * * @category transforming * @since 4.0.0 @@ -1499,7 +1627,19 @@ export const noCase: { } ): (self: string) => string /** - * Normalize a string to a specific case format + * Normalizes a string by splitting it into word parts, transforming each part, + * and joining the parts with a configurable delimiter. + * + * **When to use** + * + * Use when you need custom word-case output with a delimiter or part transform + * that the fixed case helpers do not provide. + * + * @see {@link pascalCase} for fixed PascalCase output + * @see {@link camelCase} for fixed lower-initial camelCase output + * @see {@link constantCase} for fixed uppercase underscore-separated output + * @see {@link kebabCase} for fixed lowercase hyphen-separated output + * @see {@link snakeCase} for fixed lowercase underscore-separated output * * @category transforming * @since 4.0.0 @@ -1557,8 +1697,17 @@ const pascalCaseTransform = (input: string, index: number): string => { /** * Converts a string to PascalCase. * - * @since 4.0.0 + * **When to use** + * + * Use to normalize strings from spaces, separators, or camel/Pascal word + * boundaries into PascalCase. + * + * @see {@link camelCase} for lower-initial camelCase output + * @see {@link noCase} for configurable delimiters and part transforms + * @see {@link snakeToPascal} for converting known snake_case input only + * * @category transforming + * @since 4.0.0 */ export const pascalCase: (self: string) => string = noCase({ delimiter: "", @@ -1573,8 +1722,19 @@ const camelCaseTransform = (input: string, index: number): string => /** * Converts a string to camelCase. * - * @since 4.0.0 + * **When to use** + * + * Use to normalize mixed word separators or existing PascalCase/camelCase text + * into lower-initial camelCase identifiers. + * + * @see {@link noCase} for configurable delimiters and part transforms + * @see {@link pascalCase} for upper-initial PascalCase output + * @see {@link snakeCase} for lowercase underscore-separated output + * @see {@link kebabCase} for lowercase hyphen-separated output + * @see {@link constantCase} for uppercase underscore-separated output + * * @category transforming + * @since 4.0.0 */ export const camelCase: (self: string) => string = noCase({ delimiter: "", @@ -1584,8 +1744,19 @@ export const camelCase: (self: string) => string = noCase({ /** * Converts a string to CONSTANT_CASE (uppercase with underscores). * - * @since 4.0.0 + * **When to use** + * + * Use to normalize words from mixed input formats into uppercase, + * underscore-separated identifiers. + * + * @see {@link snakeCase} for lowercase underscore-separated output + * @see {@link kebabCase} for lowercase hyphen-separated output + * @see {@link camelCase} for lower-initial camelCase output + * @see {@link pascalCase} for upper-initial PascalCase output + * @see {@link noCase} for configurable delimiters and part transforms + * * @category transforming + * @since 4.0.0 */ export const constantCase: (self: string) => string = noCase({ delimiter: "_", @@ -1595,8 +1766,19 @@ export const constantCase: (self: string) => string = noCase({ /** * Converts a string to kebab-case (lowercase with hyphens). * - * @since 4.0.0 + * **When to use** + * + * Use to normalize free-form labels, identifiers, or keys into lowercase + * hyphen-separated text. + * + * @see {@link noCase} for configurable delimiters and part transforms + * @see {@link snakeCase} for lowercase underscore-separated output + * @see {@link constantCase} for uppercase underscore-separated output + * @see {@link camelCase} for lower-initial camelCase output + * @see {@link pascalCase} for upper-initial PascalCase output + * * @category transforming + * @since 4.0.0 */ export const kebabCase: (self: string) => string = noCase({ delimiter: "-" @@ -1605,16 +1787,36 @@ export const kebabCase: (self: string) => string = noCase({ /** * Converts a string to snake_case (lowercase with underscores). * - * @since 4.0.0 + * **When to use** + * + * Use to normalize mixed-case or separator-delimited text into lowercase words + * joined with underscores. + * + * @see {@link noCase} for configurable lower-level normalization + * @see {@link kebabCase} for lowercase hyphen-separated output + * @see {@link constantCase} for uppercase underscore-separated output + * * @category transforming + * @since 4.0.0 */ export const snakeCase: (self: string) => string = noCase({ delimiter: "_" }) /** - * A `Reducer` for concatenating `string`s. + * Reducer for concatenating `string`s. + * + * **When to use** + * + * Use to concatenate many strings through APIs that consume a `Reducer`. + * + * **Details** + * + * The reducer starts from `""`, so combining an empty collection returns `""`. + * + * @see {@link concat} for concatenating two strings directly * + * @category combining * @since 4.0.0 */ export const ReducerConcat: Reducer.Reducer = Reducer.make((a, b) => a + b, "") diff --git a/.opencode/node_modules/effect/src/Struct.ts b/.opencode/node_modules/effect/src/Struct.ts index 8054931ca37fa30c1071731c5762c51fbb9a0e62..b577ad0aea49465f80a3623db6a4b5a47ff5fd9d 100644 --- a/.opencode/node_modules/effect/src/Struct.ts +++ b/.opencode/node_modules/effect/src/Struct.ts @@ -1,75 +1,12 @@ /** - * Utilities for creating, transforming, and comparing plain TypeScript objects - * (structs). Every function produces a new object — inputs are never mutated. - * - * ## Mental model - * - * - **Struct**: A plain JS object with a fixed set of known keys (e.g., - * `{ name: string; age: number }`). Not a generic key-value record. - * - **Dual API**: Most functions accept arguments in both data-first - * (`Struct.pick(obj, keys)`) and data-last (`pipe(obj, Struct.pick(keys))`) - * style. - * - **Immutability**: All operations return a new object; the original is - * never modified. - * - **Lambda**: A type-level function interface (`~lambda.in` / `~lambda.out`) - * used by {@link map}, {@link mapPick}, and {@link mapOmit} so the compiler - * can track how value types change. - * - **Evolver pattern**: {@link evolve}, {@link evolveKeys}, and - * {@link evolveEntries} let you selectively transform values, keys, or both - * while leaving untouched properties unchanged. - * - * ## Common tasks - * - * - Access a property in a pipeline → {@link get} - * - List string keys with proper types → {@link keys} - * - Subset / remove properties → {@link pick}, {@link omit} - * - Merge two structs (second wins) → {@link assign} - * - Rename keys → {@link renameKeys} - * - Transform selected values → {@link evolve} - * - Transform selected keys → {@link evolveKeys} - * - Transform both keys and values → {@link evolveEntries} - * - Map all values with a typed lambda → {@link map}, {@link mapPick}, - * {@link mapOmit} - * - Compare structs → {@link makeEquivalence}, {@link makeOrder} - * - Combine / reduce structs → {@link makeCombiner}, {@link makeReducer} - * - Flatten intersection types → {@link Simplify} - * - Strip `readonly` modifiers → {@link Mutable} - * - * ## Gotchas - * - * - {@link keys} only returns `string` keys; symbol keys are excluded. - * - {@link pick} and {@link omit} iterate with `for...in`, which includes - * inherited enumerable properties but excludes non-enumerable ones. - * - {@link assign} spreads with `...`; property order follows standard - * JS spread rules. - * - {@link map}, {@link mapPick}, {@link mapOmit} require a {@link Lambda} - * value created with {@link lambda}; a plain function won't type-check. - * - * ## Quickstart - * - * **Example** (Picking, renaming, and evolving struct properties) + * Works with plain TypeScript objects, also called structs. * - * ```ts - * import { pipe, Struct } from "effect" - * - * const user = { firstName: "Alice", lastName: "Smith", age: 30, admin: false } - * - * const result = pipe( - * user, - * Struct.pick(["firstName", "age"]), - * Struct.evolve({ age: (n) => n + 1 }), - * Struct.renameKeys({ firstName: "name" }) - * ) - * - * console.log(result) // { name: "Alice", age: 31 } - * ``` - * - * ## See also - * - * - {@link Equivalence} – building equivalence relations for structs - * - {@link Order} – ordering structs by their fields - * - {@link Combiner} – combining two values of the same type - * - {@link Reducer} – combining with an initial value + * The runtime helpers in this module create new objects instead of mutating + * their inputs. They cover common object workflows such as reading properties, + * listing typed keys, picking or omitting fields, assigning and renaming keys, + * transforming values, deriving comparison helpers, and creating records from a + * list of keys. The module also includes type-level helpers for simplifying and + * merging object shapes. * * @since 2.0.0 */ @@ -83,10 +20,14 @@ import * as Reducer from "./Reducer.ts" /** * Flattens intersection types into a single object type for readability. * - * - Use when hovering over a type shows `A & B & C` instead of the merged - * shape. - * - Purely cosmetic — no runtime effect. - * - Preserves `readonly` modifiers; use {@link Mutable} to strip them. + * **When to use** + * + * Use when hovering over a type shows `A & B & C` instead of the merged shape. + * + * **Details** + * + * This helper is purely cosmetic at the type level and has no runtime effect. + * It preserves `readonly` modifiers; use {@link Mutable} to strip them. * * **Example** (Flattening an intersection) * @@ -102,8 +43,7 @@ import * as Reducer from "./Reducer.ts" * * @see {@link Mutable} – also flattens but removes `readonly` * @see {@link Assign} – merges two types with right-side precedence - * - * @category Type-Level Programming + * @category utility types * @since 4.0.0 */ export type Simplify = { [K in keyof T]: T[K] } & {} @@ -111,9 +51,14 @@ export type Simplify = { [K in keyof T]: T[K] } & {} /** * Removes `readonly` modifiers from all properties of an object type. * - * - Use when you need a mutable version of a readonly interface. - * - Purely cosmetic at the type level — no runtime effect. - * - Also flattens intersections like {@link Simplify}. + * **When to use** + * + * Use when you need a mutable version of a readonly interface. + * + * **Details** + * + * This helper is purely cosmetic at the type level and has no runtime effect. + * It also flattens intersections like {@link Simplify}. * * **Example** (Making a readonly type mutable) * @@ -126,8 +71,7 @@ export type Simplify = { [K in keyof T]: T[K] } & {} * ``` * * @see {@link Simplify} – flattens intersections without removing `readonly` - * - * @category Type-Level Programming + * @category utility types * @since 4.0.0 */ export type Mutable = { -readonly [K in keyof T]: T[K] } & {} @@ -136,9 +80,14 @@ export type Mutable = { -readonly [K in keyof T]: T[K] } & {} * Merges two object types with properties from `U` taking precedence over `T` * on overlapping keys (like `Object.assign` at the type level). * - * - Use when you need the type-level equivalent of `{ ...T, ...U }`. - * - When no keys overlap, returns a simple intersection for efficiency. - * - When keys overlap, the type from `U` wins. + * **When to use** + * + * Use when you need the type-level equivalent of `{ ...T, ...U }`. + * + * **Details** + * + * When no keys overlap, this returns a simple intersection for efficiency. + * When keys overlap, the type from `U` wins. * * **Example** (Merging two types with overlapping keys) * @@ -153,8 +102,7 @@ export type Mutable = { -readonly [K in keyof T]: T[K] } & {} * * @see {@link assign} – the runtime equivalent * @see {@link Simplify} – flatten the resulting intersection - * - * @category Type-Level Programming + * @category utility types * @since 4.0.0 */ export type Assign = Simplify & U> @@ -162,9 +110,13 @@ export type Assign = Simplify = Simplify(key: K): (self: S) => S[K] /** * Retrieves the value at `key` from a struct. * - * - Use in a pipeline when you need to extract a single property. - * - Does not mutate the input. - * - The return type is narrowed to `S[K]`. + * **When to use** + * + * Use to extract a single property from a struct in a pipeline. + * + * **Details** + * + * The return type is narrowed to `S[K]`. * * **Example** (Extracting a property in a pipeline) * @@ -223,8 +181,7 @@ export const get: { * * @see {@link keys} – list all string keys of a struct * @see {@link pick} – extract multiple properties into a new struct - * - * @category Getters + * @category getters * @since 2.0.0 */ (self: S, key: K): S[K] @@ -233,10 +190,14 @@ export const get: { /** * Returns the string keys of a struct as a properly typed `Array`. * - * - Use instead of `Object.keys` when you want the return type narrowed to the - * known keys of the struct. - * - Symbol keys are excluded; only string keys are returned. - * - Does not mutate the input. + * **When to use** + * + * Use when you want a typed replacement for `Object.keys` that narrows the result + * to the known string keys of the struct. + * + * **Gotchas** + * + * Symbol keys are excluded; only string keys are returned. * * **Example** (Typed keys) * @@ -251,7 +212,6 @@ export const get: { * * @see {@link get} – access a single key's value * @see {@link pick} – select a subset of keys into a new struct - * * @category Key utilities * @since 3.6.0 */ @@ -261,9 +221,13 @@ export const keys = (self: S): Array<(keyof S) & string> => /** * Creates a new struct containing only the specified keys. * - * - Use to narrow a struct down to a subset of its properties. - * - Does not mutate the input; returns a fresh object. - * - Keys not present in the struct are silently ignored. + * **When to use** + * + * Use to narrow a struct down to a subset of its properties. + * + * **Gotchas** + * + * Keys not present in the struct are silently ignored. * * **Example** (Selecting specific properties) * @@ -277,7 +241,6 @@ export const keys = (self: S): Array<(keyof S) & string> => * * @see {@link omit} – the inverse (exclude keys instead) * @see {@link get} – extract a single value - * * @category filtering * @since 2.0.0 */ @@ -285,9 +248,13 @@ export const pick: { /** * Creates a new struct containing only the specified keys. * - * - Use to narrow a struct down to a subset of its properties. - * - Does not mutate the input; returns a fresh object. - * - Keys not present in the struct are silently ignored. + * **When to use** + * + * Use to narrow a struct down to a subset of its properties. + * + * **Gotchas** + * + * Keys not present in the struct are silently ignored. * * **Example** (Selecting specific properties) * @@ -301,7 +268,6 @@ export const pick: { * * @see {@link omit} – the inverse (exclude keys instead) * @see {@link get} – extract a single value - * * @category filtering * @since 2.0.0 */ @@ -309,9 +275,13 @@ export const pick: { /** * Creates a new struct containing only the specified keys. * - * - Use to narrow a struct down to a subset of its properties. - * - Does not mutate the input; returns a fresh object. - * - Keys not present in the struct are silently ignored. + * **When to use** + * + * Use to narrow a struct down to a subset of its properties. + * + * **Gotchas** + * + * Keys not present in the struct are silently ignored. * * **Example** (Selecting specific properties) * @@ -325,7 +295,6 @@ export const pick: { * * @see {@link omit} – the inverse (exclude keys instead) * @see {@link get} – extract a single value - * * @category filtering * @since 2.0.0 */ @@ -340,9 +309,13 @@ export const pick: { /** * Creates a new struct with the specified keys removed. * - * - Use to exclude sensitive or irrelevant fields from a struct. - * - Does not mutate the input; returns a fresh object. - * - Keys not present in the struct are silently ignored. + * **When to use** + * + * Use to exclude sensitive or irrelevant fields from a struct. + * + * **Gotchas** + * + * Keys not present in the struct are silently ignored. * * **Example** (Removing a property) * @@ -355,7 +328,6 @@ export const pick: { * ``` * * @see {@link pick} – the inverse (keep only specified keys) - * * @category filtering * @since 2.0.0 */ @@ -363,9 +335,13 @@ export const omit: { /** * Creates a new struct with the specified keys removed. * - * - Use to exclude sensitive or irrelevant fields from a struct. - * - Does not mutate the input; returns a fresh object. - * - Keys not present in the struct are silently ignored. + * **When to use** + * + * Use to exclude sensitive or irrelevant fields from a struct. + * + * **Gotchas** + * + * Keys not present in the struct are silently ignored. * * **Example** (Removing a property) * @@ -378,7 +354,6 @@ export const omit: { * ``` * * @see {@link pick} – the inverse (keep only specified keys) - * * @category filtering * @since 2.0.0 */ @@ -386,9 +361,13 @@ export const omit: { /** * Creates a new struct with the specified keys removed. * - * - Use to exclude sensitive or irrelevant fields from a struct. - * - Does not mutate the input; returns a fresh object. - * - Keys not present in the struct are silently ignored. + * **When to use** + * + * Use to exclude sensitive or irrelevant fields from a struct. + * + * **Gotchas** + * + * Keys not present in the struct are silently ignored. * * **Example** (Removing a property) * @@ -401,7 +380,6 @@ export const omit: { * ``` * * @see {@link pick} – the inverse (keep only specified keys) - * * @category filtering * @since 2.0.0 */ @@ -417,9 +395,13 @@ export const omit: { * Merges two structs into a new struct. When both structs share a key, the * value from `that` (the second struct) wins. * - * - Use when you want `{ ...self, ...that }` with proper types. - * - Does not mutate either input; returns a fresh object. - * - The result type is `Simplify>`. + * **When to use** + * + * Use when you want `{ ...self, ...that }` with proper types. + * + * **Details** + * + * The result type is `Simplify>`. * * **Example** (Merging structs with overlapping keys) * @@ -434,7 +416,6 @@ export const omit: { * * @see {@link Assign} – the type-level equivalent * @see {@link evolve} – transform individual values instead of replacing them - * * @category combining * @since 4.0.0 */ @@ -443,9 +424,13 @@ export const assign: { * Merges two structs into a new struct. When both structs share a key, the * value from `that` (the second struct) wins. * - * - Use when you want `{ ...self, ...that }` with proper types. - * - Does not mutate either input; returns a fresh object. - * - The result type is `Simplify>`. + * **When to use** + * + * Use when you want `{ ...self, ...that }` with proper types. + * + * **Details** + * + * The result type is `Simplify>`. * * **Example** (Merging structs with overlapping keys) * @@ -460,7 +445,6 @@ export const assign: { * * @see {@link Assign} – the type-level equivalent * @see {@link evolve} – transform individual values instead of replacing them - * * @category combining * @since 4.0.0 */ @@ -469,9 +453,13 @@ export const assign: { * Merges two structs into a new struct. When both structs share a key, the * value from `that` (the second struct) wins. * - * - Use when you want `{ ...self, ...that }` with proper types. - * - Does not mutate either input; returns a fresh object. - * - The result type is `Simplify>`. + * **When to use** + * + * Use when you want `{ ...self, ...that }` with proper types. + * + * **Details** + * + * The result type is `Simplify>`. * * **Example** (Merging structs with overlapping keys) * @@ -486,7 +474,6 @@ export const assign: { * * @see {@link Assign} – the type-level equivalent * @see {@link evolve} – transform individual values instead of replacing them - * * @category combining * @since 4.0.0 */ @@ -505,13 +492,17 @@ type Evolved = Simplify< > /** - * Selectively transforms values of a struct using per-key functions. Keys + * Transforms values of a struct selectively using per-key functions. Keys * without a corresponding function are copied unchanged. * - * - Use when you want to update specific fields while keeping the rest intact. - * - Does not mutate the input; returns a fresh object. - * - Each transform function receives the current value and returns the new - * value; the return type can differ from the input type. + * **When to use** + * + * Use when you want to update specific fields while keeping the rest intact. + * + * **Details** + * + * Each transform function receives the current value and returns the new value; + * the return type can differ from the input type. * * **Example** (Transforming selected values) * @@ -531,19 +522,22 @@ type Evolved = Simplify< * @see {@link evolveKeys} – transform keys instead of values * @see {@link evolveEntries} – transform both keys and values * @see {@link map} – apply the same transformation to all values - * * @category transforming * @since 2.0.0 */ export const evolve: { /** - * Selectively transforms values of a struct using per-key functions. Keys + * Transforms values of a struct selectively using per-key functions. Keys * without a corresponding function are copied unchanged. * - * - Use when you want to update specific fields while keeping the rest intact. - * - Does not mutate the input; returns a fresh object. - * - Each transform function receives the current value and returns the new - * value; the return type can differ from the input type. + * **When to use** + * + * Use when you want to update specific fields while keeping the rest intact. + * + * **Details** + * + * Each transform function receives the current value and returns the new value; + * the return type can differ from the input type. * * **Example** (Transforming selected values) * @@ -563,19 +557,22 @@ export const evolve: { * @see {@link evolveKeys} – transform keys instead of values * @see {@link evolveEntries} – transform both keys and values * @see {@link map} – apply the same transformation to all values - * * @category transforming * @since 2.0.0 */ >(e: E): (self: S) => Evolved /** - * Selectively transforms values of a struct using per-key functions. Keys + * Transforms values of a struct selectively using per-key functions. Keys * without a corresponding function are copied unchanged. * - * - Use when you want to update specific fields while keeping the rest intact. - * - Does not mutate the input; returns a fresh object. - * - Each transform function receives the current value and returns the new - * value; the return type can differ from the input type. + * **When to use** + * + * Use when you want to update specific fields while keeping the rest intact. + * + * **Details** + * + * Each transform function receives the current value and returns the new value; + * the return type can differ from the input type. * * **Example** (Transforming selected values) * @@ -595,7 +592,6 @@ export const evolve: { * @see {@link evolveKeys} – transform keys instead of values * @see {@link evolveEntries} – transform both keys and values * @see {@link map} – apply the same transformation to all values - * * @category transforming * @since 2.0.0 */ @@ -614,13 +610,17 @@ type KeyEvolved = Simplify< > /** - * Selectively transforms keys of a struct using per-key functions. Keys without + * Transforms keys of a struct selectively using per-key functions. Keys without * a corresponding function are copied unchanged. * - * - Use when you need computed key names (e.g., uppercasing, prefixing). - * - Each transform function receives the key name and must return a new - * `PropertyKey`. - * - Does not mutate the input; returns a fresh object. + * **When to use** + * + * Use when you need computed key names, such as uppercasing or prefixing. + * + * **Details** + * + * Each transform function receives the key name and must return a new + * `PropertyKey`. * * **Example** (Renaming keys with functions) * @@ -639,19 +639,22 @@ type KeyEvolved = Simplify< * @see {@link renameKeys} – rename keys with a static mapping * @see {@link evolve} – transform values instead of keys * @see {@link evolveEntries} – transform both keys and values - * * @category Key utilities * @since 4.0.0 */ export const evolveKeys: { /** - * Selectively transforms keys of a struct using per-key functions. Keys without + * Transforms keys of a struct selectively using per-key functions. Keys without * a corresponding function are copied unchanged. * - * - Use when you need computed key names (e.g., uppercasing, prefixing). - * - Each transform function receives the key name and must return a new - * `PropertyKey`. - * - Does not mutate the input; returns a fresh object. + * **When to use** + * + * Use when you need computed key names, such as uppercasing or prefixing. + * + * **Details** + * + * Each transform function receives the key name and must return a new + * `PropertyKey`. * * **Example** (Renaming keys with functions) * @@ -670,19 +673,22 @@ export const evolveKeys: { * @see {@link renameKeys} – rename keys with a static mapping * @see {@link evolve} – transform values instead of keys * @see {@link evolveEntries} – transform both keys and values - * * @category Key utilities * @since 4.0.0 */ >(e: E): (self: S) => KeyEvolved /** - * Selectively transforms keys of a struct using per-key functions. Keys without + * Transforms keys of a struct selectively using per-key functions. Keys without * a corresponding function are copied unchanged. * - * - Use when you need computed key names (e.g., uppercasing, prefixing). - * - Each transform function receives the key name and must return a new - * `PropertyKey`. - * - Does not mutate the input; returns a fresh object. + * **When to use** + * + * Use when you need computed key names, such as uppercasing or prefixing. + * + * **Details** + * + * Each transform function receives the key name and must return a new + * `PropertyKey`. * * **Example** (Renaming keys with functions) * @@ -701,7 +707,6 @@ export const evolveKeys: { * @see {@link renameKeys} – rename keys with a static mapping * @see {@link evolve} – transform values instead of keys * @see {@link evolveEntries} – transform both keys and values - * * @category Key utilities * @since 4.0.0 */ @@ -726,13 +731,17 @@ type EntryEvolved = { } /** - * Selectively transforms both keys and values of a struct. Each per-key + * Transforms both keys and values of a struct selectively. Each per-key * function receives `(key, value)` and must return a `[newKey, newValue]` * tuple. Keys without a corresponding function are copied unchanged. * - * - Use when you need to rename a key and change its value in one step. - * - Does not mutate the input; returns a fresh object. - * - The return type is fully tracked at the type level. + * **When to use** + * + * Use when you need to rename a key and change its value in one step. + * + * **Details** + * + * The return type is fully tracked at the type level. * * **Example** (Transforming keys and values together) * @@ -751,19 +760,22 @@ type EntryEvolved = { * * @see {@link evolve} – transform values only * @see {@link evolveKeys} – transform keys only - * - * @category Utilities + * @category transforming * @since 4.0.0 */ export const evolveEntries: { /** - * Selectively transforms both keys and values of a struct. Each per-key + * Transforms both keys and values of a struct selectively. Each per-key * function receives `(key, value)` and must return a `[newKey, newValue]` * tuple. Keys without a corresponding function are copied unchanged. * - * - Use when you need to rename a key and change its value in one step. - * - Does not mutate the input; returns a fresh object. - * - The return type is fully tracked at the type level. + * **When to use** + * + * Use when you need to rename a key and change its value in one step. + * + * **Details** + * + * The return type is fully tracked at the type level. * * **Example** (Transforming keys and values together) * @@ -782,19 +794,22 @@ export const evolveEntries: { * * @see {@link evolve} – transform values only * @see {@link evolveKeys} – transform keys only - * - * @category Utilities + * @category transforming * @since 4.0.0 */ >(e: E): (self: S) => EntryEvolved /** - * Selectively transforms both keys and values of a struct. Each per-key + * Transforms both keys and values of a struct selectively. Each per-key * function receives `(key, value)` and must return a `[newKey, newValue]` * tuple. Keys without a corresponding function are copied unchanged. * - * - Use when you need to rename a key and change its value in one step. - * - Does not mutate the input; returns a fresh object. - * - The return type is fully tracked at the type level. + * **When to use** + * + * Use when you need to rename a key and change its value in one step. + * + * **Details** + * + * The return type is fully tracked at the type level. * * **Example** (Transforming keys and values together) * @@ -813,8 +828,7 @@ export const evolveEntries: { * * @see {@link evolve} – transform values only * @see {@link evolveKeys} – transform keys only - * - * @category Utilities + * @category transforming * @since 4.0.0 */ >(self: S, e: E): EntryEvolved @@ -829,9 +843,13 @@ export const evolveEntries: { * Renames keys in a struct using a static `{ oldKey: newKey }` mapping. Keys * not mentioned in the mapping are copied unchanged. * - * - Use for simple, declarative key renaming without custom logic. - * - Does not mutate the input; returns a fresh object. - * - For computed key names, use {@link evolveKeys} instead. + * **When to use** + * + * Use when you need simple, declarative key renaming without custom logic. + * + * **Details** + * + * For computed key names, use {@link evolveKeys} instead. * * **Example** (Renaming keys) * @@ -847,7 +865,6 @@ export const evolveEntries: { * * @see {@link evolveKeys} – rename keys using functions * @see {@link evolveEntries} – rename keys and transform values - * * @category Key utilities * @since 4.0.0 */ @@ -856,9 +873,13 @@ export const renameKeys: { * Renames keys in a struct using a static `{ oldKey: newKey }` mapping. Keys * not mentioned in the mapping are copied unchanged. * - * - Use for simple, declarative key renaming without custom logic. - * - Does not mutate the input; returns a fresh object. - * - For computed key names, use {@link evolveKeys} instead. + * **When to use** + * + * Use when you need simple, declarative key renaming without custom logic. + * + * **Details** + * + * For computed key names, use {@link evolveKeys} instead. * * **Example** (Renaming keys) * @@ -874,7 +895,6 @@ export const renameKeys: { * * @see {@link evolveKeys} – rename keys using functions * @see {@link evolveEntries} – rename keys and transform values - * * @category Key utilities * @since 4.0.0 */ @@ -883,9 +903,13 @@ export const renameKeys: { * Renames keys in a struct using a static `{ oldKey: newKey }` mapping. Keys * not mentioned in the mapping are copied unchanged. * - * - Use for simple, declarative key renaming without custom logic. - * - Does not mutate the input; returns a fresh object. - * - For computed key names, use {@link evolveKeys} instead. + * **When to use** + * + * Use when you need simple, declarative key renaming without custom logic. + * + * **Details** + * + * For computed key names, use {@link evolveKeys} instead. * * **Example** (Renaming keys) * @@ -901,7 +925,6 @@ export const renameKeys: { * * @see {@link evolveKeys} – rename keys using functions * @see {@link evolveEntries} – rename keys and transform values - * * @category Key utilities * @since 4.0.0 */ @@ -915,11 +938,16 @@ export const renameKeys: { * property. Two structs are equivalent when all their corresponding properties * are equivalent. * - * Alias of `Equivalence.Struct`. + * **When to use** + * + * Use when you need equality for a record-like object to be decided field by + * field, with a custom equality rule for each property. + * + * **Details** * - * - Use when you need to compare structs property-by-property. - * - Each property's equivalence is checked independently; all must return - * `true` for the overall result to be `true`. + * This is an alias of `Equivalence.Struct`. Each property's equivalence is + * checked independently; all must return `true` for the overall result to be + * `true`. * * **Example** (Comparing structs for equivalence) * @@ -938,9 +966,8 @@ export const renameKeys: { * ``` * * @see {@link makeOrder} – create an `Order` for structs - * - * @category Equivalence - * @since 2.0.0 + * @category instances + * @since 4.0.0 */ export const makeEquivalence = Equivalence.Struct @@ -949,11 +976,15 @@ export const makeEquivalence = Equivalence.Struct * Properties are compared in the order they appear in the fields object; the * first non-zero comparison determines the result. * - * Alias of `Order.Struct`. + * **When to use** * - * - Use to sort or compare structs by multiple fields with lexicographic - * priority. - * - The order of keys in the `fields` object determines comparison priority. + * Use when you need to sort record-like objects lexicographically by several + * fields, with each field using its own ordering rule. + * + * **Details** + * + * This is an alias of `Order.Struct`. The order of keys in the `fields` object + * determines comparison priority. * * **Example** (Ordering structs by name then age) * @@ -970,9 +1001,8 @@ export const makeEquivalence = Equivalence.Struct * ``` * * @see {@link makeEquivalence} – create an `Equivalence` for structs - * - * @category Ordering - * @since 2.0.0 + * @category ordering + * @since 4.0.0 */ export const makeOrder = order.Struct @@ -980,9 +1010,16 @@ export const makeOrder = order.Struct * Interface for type-level functions used by {@link map}, {@link mapPick}, and * {@link mapOmit}. * - * - Extend this interface with concrete `~lambda.in` and `~lambda.out` types - * to describe how a function transforms values at the type level. - * - At runtime, create lambda values with {@link lambda}. + * **When to use** + * + * Use when defining a typed function for {@link map}, {@link mapPick}, or + * {@link mapOmit}. + * + * **Details** + * + * Extend this interface with concrete `~lambda.in` and `~lambda.out` types to + * describe how a function transforms values at the type level. At runtime, + * create lambda values with {@link lambda}. * * **Example** (Defining a lambda type) * @@ -997,7 +1034,6 @@ export const makeOrder = order.Struct * @see {@link Apply} – apply a Lambda to a concrete type * @see {@link lambda} – create a runtime lambda value * @see {@link map} – use a lambda to transform all struct values - * * @category Lambda * @since 4.0.0 */ @@ -1010,10 +1046,15 @@ export interface Lambda { * Applies a {@link Lambda} type-level function to a value type `V`, producing * the output type. * - * - Use this when you need to compute what type a Lambda would produce for a - * given input. - * - Works by intersecting the Lambda with `{ "~lambda.in": V }` and reading - * `"~lambda.out"`. + * **When to use** + * + * Use when you need to compute what type a Lambda would produce for a + * given input. + * + * **Details** + * + * This works by intersecting the Lambda with `{ "~lambda.in": V }` and reading + * `"~lambda.out"`. * * **Example** (Computing the output type of a lambda) * @@ -1029,7 +1070,6 @@ export interface Lambda { * ``` * * @see {@link Lambda} – the base interface - * * @category Lambda * @since 4.0.0 */ @@ -1039,10 +1079,17 @@ export type Apply = (L & { readonly "~lambda.in": V })["~la * Wraps a plain function as a {@link Lambda} value so it can be used with * {@link map}, {@link mapPick}, and {@link mapOmit}. * - * - The type parameter `L` encodes both the input and output types at the type - * level, allowing the compiler to track how struct value types change. - * - At runtime, the returned value is the same function — `lambda` only - * adjusts the type. + * **When to use** + * + * Use to create a typed lambda for struct mapping APIs that need type-level + * input and output tracking. + * + * **Details** + * + * The type parameter `L` encodes both the input and output types at the type + * level, allowing the compiler to track how struct value types change. At + * runtime, the returned value is the same function; `lambda` only adjusts the + * type. * * **Example** (Wrapping values in arrays) * @@ -1061,7 +1108,6 @@ export type Apply = (L & { readonly "~lambda.in": V })["~la * * @see {@link Lambda} – the type-level interface * @see {@link map} – apply a lambda to all struct values - * * @category Lambda * @since 4.0.0 */ @@ -1072,10 +1118,14 @@ export const lambda = any>( /** * Applies a {@link Lambda} transformation to every value in a struct. * - * - Use when you want to apply the same function to every value in a struct. - * - The lambda must be created with {@link lambda} so the compiler can track - * the output types. - * - Does not mutate the input; returns a fresh object. + * **When to use** + * + * Use when you want to apply the same function to every value in a struct. + * + * **Details** + * + * The lambda must be created with {@link lambda} so the compiler can track the + * output types. * * **Example** (Wrapping every value in an array) * @@ -1095,18 +1145,21 @@ export const lambda = any>( * @see {@link mapPick} – apply a lambda only to selected keys * @see {@link mapOmit} – apply a lambda to all keys except selected ones * @see {@link evolve} – apply different functions to different keys - * - * @category Mapping + * @category mapping * @since 4.0.0 */ export const map: { /** * Applies a {@link Lambda} transformation to every value in a struct. * - * - Use when you want to apply the same function to every value in a struct. - * - The lambda must be created with {@link lambda} so the compiler can track - * the output types. - * - Does not mutate the input; returns a fresh object. + * **When to use** + * + * Use when you want to apply the same function to every value in a struct. + * + * **Details** + * + * The lambda must be created with {@link lambda} so the compiler can track the + * output types. * * **Example** (Wrapping every value in an array) * @@ -1126,18 +1179,21 @@ export const map: { * @see {@link mapPick} – apply a lambda only to selected keys * @see {@link mapOmit} – apply a lambda to all keys except selected ones * @see {@link evolve} – apply different functions to different keys - * - * @category Mapping + * @category mapping * @since 4.0.0 */ (lambda: L): (self: S) => { [K in keyof S]: Apply } /** * Applies a {@link Lambda} transformation to every value in a struct. * - * - Use when you want to apply the same function to every value in a struct. - * - The lambda must be created with {@link lambda} so the compiler can track - * the output types. - * - Does not mutate the input; returns a fresh object. + * **When to use** + * + * Use when you want to apply the same function to every value in a struct. + * + * **Details** + * + * The lambda must be created with {@link lambda} so the compiler can track the + * output types. * * **Example** (Wrapping every value in an array) * @@ -1157,8 +1213,7 @@ export const map: { * @see {@link mapPick} – apply a lambda only to selected keys * @see {@link mapOmit} – apply a lambda to all keys except selected ones * @see {@link evolve} – apply different functions to different keys - * - * @category Mapping + * @category mapping * @since 4.0.0 */ (self: S, lambda: L): { [K in keyof S]: Apply } @@ -1173,9 +1228,9 @@ export const map: { * Applies a {@link Lambda} transformation only to the specified keys; all * other keys are copied unchanged. * - * - Use when you want to apply the same transformation to a subset of - * properties. - * - Does not mutate the input; returns a fresh object. + * **When to use** + * + * Use when you want to apply the same transformation to a subset of properties. * * **Example** (Wrapping only selected values in arrays) * @@ -1197,8 +1252,7 @@ export const map: { * * @see {@link map} – apply a lambda to all keys * @see {@link mapOmit} – apply a lambda to all keys except selected ones - * - * @category Mapping + * @category mapping * @since 4.0.0 */ export const mapPick: { @@ -1206,9 +1260,9 @@ export const mapPick: { * Applies a {@link Lambda} transformation only to the specified keys; all * other keys are copied unchanged. * - * - Use when you want to apply the same transformation to a subset of - * properties. - * - Does not mutate the input; returns a fresh object. + * **When to use** + * + * Use when you want to apply the same transformation to a subset of properties. * * **Example** (Wrapping only selected values in arrays) * @@ -1230,8 +1284,7 @@ export const mapPick: { * * @see {@link map} – apply a lambda to all keys * @see {@link mapOmit} – apply a lambda to all keys except selected ones - * - * @category Mapping + * @category mapping * @since 4.0.0 */ , L extends Lambda>(keys: Keys, lambda: L): ( @@ -1241,9 +1294,9 @@ export const mapPick: { * Applies a {@link Lambda} transformation only to the specified keys; all * other keys are copied unchanged. * - * - Use when you want to apply the same transformation to a subset of - * properties. - * - Does not mutate the input; returns a fresh object. + * **When to use** + * + * Use when you want to apply the same transformation to a subset of properties. * * **Example** (Wrapping only selected values in arrays) * @@ -1265,8 +1318,7 @@ export const mapPick: { * * @see {@link map} – apply a lambda to all keys * @see {@link mapOmit} – apply a lambda to all keys except selected ones - * - * @category Mapping + * @category mapping * @since 4.0.0 */ , L extends Lambda>(self: S, keys: Keys, lambda: L): { [K in keyof S]: K extends Keys[number] ? Apply : S[K] } @@ -1285,8 +1337,9 @@ export const mapPick: { * Applies a {@link Lambda} transformation to all keys except the specified * ones; the excluded keys are copied unchanged. * - * - Use when most keys should be transformed but a few should be preserved. - * - Does not mutate the input; returns a fresh object. + * **When to use** + * + * Use when most keys should be transformed but a few should be preserved. * * **Example** (Wrapping all values except one in arrays) * @@ -1308,8 +1361,7 @@ export const mapPick: { * * @see {@link map} – apply a lambda to all keys * @see {@link mapPick} – apply a lambda only to selected keys - * - * @category Mapping + * @category mapping * @since 4.0.0 */ export const mapOmit: { @@ -1317,8 +1369,9 @@ export const mapOmit: { * Applies a {@link Lambda} transformation to all keys except the specified * ones; the excluded keys are copied unchanged. * - * - Use when most keys should be transformed but a few should be preserved. - * - Does not mutate the input; returns a fresh object. + * **When to use** + * + * Use when most keys should be transformed but a few should be preserved. * * **Example** (Wrapping all values except one in arrays) * @@ -1340,8 +1393,7 @@ export const mapOmit: { * * @see {@link map} – apply a lambda to all keys * @see {@link mapPick} – apply a lambda only to selected keys - * - * @category Mapping + * @category mapping * @since 4.0.0 */ , L extends Lambda>(keys: Keys, lambda: L): ( @@ -1351,8 +1403,9 @@ export const mapOmit: { * Applies a {@link Lambda} transformation to all keys except the specified * ones; the excluded keys are copied unchanged. * - * - Use when most keys should be transformed but a few should be preserved. - * - Does not mutate the input; returns a fresh object. + * **When to use** + * + * Use when most keys should be transformed but a few should be preserved. * * **Example** (Wrapping all values except one in arrays) * @@ -1374,8 +1427,7 @@ export const mapOmit: { * * @see {@link map} – apply a lambda to all keys * @see {@link mapPick} – apply a lambda only to selected keys - * - * @category Mapping + * @category mapping * @since 4.0.0 */ , L extends Lambda>(self: S, keys: Keys, lambda: L): { [K in keyof S]: K extends Keys[number] ? S[K] : Apply } @@ -1407,7 +1459,8 @@ function buildStruct< f: f ): any { const out: Record = {} - for (const k in source) { + for (const k of Reflect.ownKeys(source) as Array) { + if (!Object.prototype.propertyIsEnumerable.call(source, k)) continue const res = f(k, source[k]) if (res) { const [nk, nv] = res @@ -1422,11 +1475,15 @@ function buildStruct< * property. When two structs are combined, each property is merged using its * corresponding combiner. * - * - Use when you need to merge two structs of the same shape (e.g., summing - * counters, concatenating strings). - * - Pass `omitKeyWhen` to drop properties whose merged value matches a - * predicate (e.g., omit zero counters). - * - Does not mutate the inputs; returns a fresh object. + * **When to use** + * + * Use when you need to merge two same-shape records by combining each property + * independently, such as summing counters or concatenating strings. + * + * **Details** + * + * Pass `omitKeyWhen` to drop properties whose merged value matches a predicate, + * such as omitting zero counters. * * **Example** (Combining struct properties) * @@ -1443,7 +1500,7 @@ function buildStruct< * ``` * * @see {@link makeReducer} – like `makeCombiner` but with an initial value - * + * @category combining * @since 4.0.0 */ export function makeCombiner( @@ -1471,10 +1528,15 @@ export function makeCombiner( * `Reducer.initialValue`. When reducing a collection of structs, each property * is combined independently. * - * - Use to fold a collection of structs into a single summary struct. - * - Pass `omitKeyWhen` to drop properties whose reduced value matches a - * predicate. - * - Does not mutate the inputs; returns a fresh object. + * **When to use** + * + * Use when you need to fold same-shape records by accumulating each property + * independently into one summary record. + * + * **Details** + * + * Pass `omitKeyWhen` to drop properties whose reduced value matches a + * predicate. * * **Example** (Reducing a collection of structs) * @@ -1495,7 +1557,7 @@ export function makeCombiner( * ``` * * @see {@link makeCombiner} – like `makeReducer` but without an initial value - * + * @category folding * @since 4.0.0 */ export function makeReducer( @@ -1517,6 +1579,10 @@ export function makeReducer( /** * Creates a record with the given keys and value. * + * **When to use** + * + * Use to build an object where each provided key receives the same value. + * * **Example** (Creating a record) * * ```ts @@ -1526,7 +1592,7 @@ export function makeReducer( * console.log(record) // { a: "value", b: "value" } * ``` * - * @category Constructors + * @category constructors * @since 4.0.0 */ export function Record, Value>( diff --git a/.opencode/node_modules/effect/src/SubscriptionRef.ts b/.opencode/node_modules/effect/src/SubscriptionRef.ts index 77009cc661425a9a4982a36d96e0b6de2fe49c80..7acaac83d3dca002a2bec63cb68b45e38c2c2074 100644 --- a/.opencode/node_modules/effect/src/SubscriptionRef.ts +++ b/.opencode/node_modules/effect/src/SubscriptionRef.ts @@ -1,4 +1,12 @@ /** + * Stores mutable state and publishes changes as a stream. + * + * A `SubscriptionRef` stores the latest value, publishes the initial value, + * and publishes every committed update so subscribers can observe state over + * time. Updates are serialized so only one change is applied at a time. This + * module includes constructors, current-value reads, the `changes` stream, + * writes, updates, partial updates, and effectful update helpers. + * * @since 2.0.0 */ import * as Effect from "./Effect.ts" @@ -15,8 +23,16 @@ import type { Invariant } from "./Types.ts" const TypeId = "~effect/SubscriptionRef" /** - * @since 2.0.0 + * A mutable reference whose updates are serialized and published to + * subscribers. + * + * **When to use** + * + * Use to observe the current value and subsequent updates as a + * stream. + * * @category models + * @since 2.0.0 */ export interface SubscriptionRef extends SubscriptionRef.Variance, Pipeable { value: A @@ -25,22 +41,33 @@ export interface SubscriptionRef extends SubscriptionRef.Variance, } /** - * @since 4.0.0 + * Returns `true` if the provided value is a `SubscriptionRef`. + * + * **When to use** + * + * Use to narrow an unknown value before calling `SubscriptionRef` operations + * that require a subscription reference. + * * @category guards + * @since 4.0.0 */ export const isSubscriptionRef: (u: unknown) => u is SubscriptionRef = ( u: unknown ): u is SubscriptionRef => hasProperty(u, TypeId) /** - * The `SynchronizedRef` namespace containing type definitions and utilities. + * The `SubscriptionRef` namespace containing type definitions associated with + * subscription references. * * @since 2.0.0 */ export declare namespace SubscriptionRef { /** - * @since 2.0.0 + * Type-level variance marker for the value type carried by a + * `SubscriptionRef`. + * * @category models + * @since 2.0.0 */ export interface Variance { readonly [TypeId]: { @@ -65,8 +92,21 @@ const Proto = { /** * Constructs a new `SubscriptionRef` from an initial value. * - * @since 2.0.0 + * **When to use** + * + * Use to create a `SubscriptionRef` when consumers need to read the latest + * value and subscribe to every update. + * + * **Details** + * + * The initial value is published during construction, so `changes` starts new + * subscribers with that value before future updates. + * + * @see {@link changes} for streaming the current value and subsequent updates + * @see {@link set} for replacing the value and notifying subscribers + * * @category constructors + * @since 2.0.0 */ export const make = (value: A): Effect.Effect> => Effect.map(PubSub.unbounded({ replay: 1 }), (pubsub) => { @@ -82,41 +122,59 @@ export const make = (value: A): Effect.Effect> => * Creates a stream that emits the current value and all subsequent changes to * the `SubscriptionRef`. * + * **Details** + * * The stream will first emit the current value, then emit all future changes * as they occur. * - * @example + * **Example** (Streaming changes) + * * ```ts - * import { Effect, Stream, SubscriptionRef } from "effect" + * import { Deferred, Effect, Fiber, Stream, SubscriptionRef } from "effect" * * const program = Effect.gen(function*() { * const ref = yield* SubscriptionRef.make(0) + * const ready = yield* Deferred.make() * - * const stream = SubscriptionRef.changes(ref) - * - * const fiber = yield* Stream.runForEach( - * stream, - * (value) => Effect.sync(() => console.log("Value:", value)) - * ).pipe(Effect.forkScoped) + * const fiber = yield* SubscriptionRef.changes(ref).pipe( + * Stream.tap(() => Deferred.succeed(ready, void 0)), + * Stream.take(3), + * Stream.runCollect, + * Effect.forkChild + * ) * + * yield* Deferred.await(ready) * yield* SubscriptionRef.set(ref, 1) * yield* SubscriptionRef.set(ref, 2) + * + * const values = yield* Fiber.join(fiber) + * console.log(values) // [ 0, 1, 2 ] * }) + * + * Effect.runPromise(program) * ``` * * @category changes - * @since 2.0.0 + * @since 4.0.0 */ export const changes = (self: SubscriptionRef): Stream.Stream => Stream.fromPubSub(self.pubsub) /** - * Unsafely retrieves the current value of the `SubscriptionRef`. + * Retrieves the current value of the `SubscriptionRef` unsafely. + * + * **When to use** + * + * Use when you are in synchronous internals or test setup where concurrent + * updates are controlled. + * + * **Gotchas** * * This function directly accesses the underlying reference without any - * synchronization. It should only be used when you're certain there are no + * synchronization. It should only be used when you are certain there are no * concurrent modifications. * - * @example + * **Example** (Reading the current value unsafely) + * * ```ts * import { Effect, SubscriptionRef } from "effect" * @@ -128,15 +186,16 @@ export const changes = (self: SubscriptionRef): Stream.Stream => Stream * }) * ``` * - * @since 2.0.0 * @category getters + * @since 4.0.0 */ export const getUnsafe = (self: SubscriptionRef): A => self.value /** * Retrieves the current value of the `SubscriptionRef`. * - * @example + * **Example** (Reading the current value) + * * ```ts * import { Effect, SubscriptionRef } from "effect" * @@ -148,16 +207,17 @@ export const getUnsafe = (self: SubscriptionRef): A => self.value * }) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export const get = (self: SubscriptionRef): Effect.Effect => Effect.sync(() => self.value) /** - * Atomically retrieves the current value and sets a new value, notifying + * Retrieves the current value and sets a new value atomically, notifying * subscribers of the change. * - * @example + * **Example** (Getting and setting a value) + * * ```ts * import { Effect, SubscriptionRef } from "effect" * @@ -172,15 +232,16 @@ export const get = (self: SubscriptionRef): Effect.Effect => Effect.syn * }) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export const getAndSet: { /** - * Atomically retrieves the current value and sets a new value, notifying + * Retrieves the current value and sets a new value atomically, notifying * subscribers of the change. * - * @example + * **Example** (Getting and setting a value) + * * ```ts * import { Effect, SubscriptionRef } from "effect" * @@ -195,15 +256,16 @@ export const getAndSet: { * }) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ (value: A): (self: SubscriptionRef) => Effect.Effect /** - * Atomically retrieves the current value and sets a new value, notifying + * Retrieves the current value and sets a new value atomically, notifying * subscribers of the change. * - * @example + * **Example** (Getting and setting a value) + * * ```ts * import { Effect, SubscriptionRef } from "effect" * @@ -218,8 +280,8 @@ export const getAndSet: { * }) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ (self: SubscriptionRef, value: A): Effect.Effect } = dual(2, (self: SubscriptionRef, value: A) => @@ -235,10 +297,11 @@ const setUnsafe = (self: SubscriptionRef, value: A) => { } /** - * Atomically retrieves the current value and updates it with the result of + * Retrieves the current value and updates it atomically with the result of * applying a function, notifying subscribers of the change. * - * @example + * **Example** (Getting and updating a value) + * * ```ts * import { Effect, SubscriptionRef } from "effect" * @@ -253,15 +316,16 @@ const setUnsafe = (self: SubscriptionRef, value: A) => { * }) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export const getAndUpdate: { /** - * Atomically retrieves the current value and updates it with the result of + * Retrieves the current value and updates it atomically with the result of * applying a function, notifying subscribers of the change. * - * @example + * **Example** (Getting and updating a value) + * * ```ts * import { Effect, SubscriptionRef } from "effect" * @@ -276,15 +340,16 @@ export const getAndUpdate: { * }) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ (update: (a: A) => A): (self: SubscriptionRef) => Effect.Effect /** - * Atomically retrieves the current value and updates it with the result of + * Retrieves the current value and updates it atomically with the result of * applying a function, notifying subscribers of the change. * - * @example + * **Example** (Getting and updating a value) + * * ```ts * import { Effect, SubscriptionRef } from "effect" * @@ -299,8 +364,8 @@ export const getAndUpdate: { * }) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ (self: SubscriptionRef, update: (a: A) => A): Effect.Effect } = dual(2, (self: SubscriptionRef, update: (a: A) => A) => @@ -312,10 +377,11 @@ export const getAndUpdate: { }))) /** - * Atomically retrieves the current value and updates it with the result of + * Retrieves the current value and updates it atomically with the result of * applying an effectful function, notifying subscribers of the change. * - * @example + * **Example** (Getting and updating with an effect) + * * ```ts * import { Effect, SubscriptionRef } from "effect" * @@ -333,15 +399,16 @@ export const getAndUpdate: { * }) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export const getAndUpdateEffect: { /** - * Atomically retrieves the current value and updates it with the result of + * Retrieves the current value and updates it atomically with the result of * applying an effectful function, notifying subscribers of the change. * - * @example + * **Example** (Getting and updating with an effect) + * * ```ts * import { Effect, SubscriptionRef } from "effect" * @@ -359,15 +426,16 @@ export const getAndUpdateEffect: { * }) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ (update: (a: A) => Effect.Effect): (self: SubscriptionRef) => Effect.Effect /** - * Atomically retrieves the current value and updates it with the result of + * Retrieves the current value and updates it atomically with the result of * applying an effectful function, notifying subscribers of the change. * - * @example + * **Example** (Getting and updating with an effect) + * * ```ts * import { Effect, SubscriptionRef } from "effect" * @@ -385,8 +453,8 @@ export const getAndUpdateEffect: { * }) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ (self: SubscriptionRef, update: (a: A) => Effect.Effect): Effect.Effect } = dual(2, ( @@ -402,11 +470,21 @@ export const getAndUpdateEffect: { }))) /** - * Atomically retrieves the current value and optionally updates it with the - * result of applying a function that returns an `Option`, notifying - * subscribers only if the value changes. + * Retrieves the current value and optionally updates the reference. + * + * **When to use** + * + * Use to read the old `SubscriptionRef` value while applying a synchronous + * update only when a new value is available. + * + * **Details** + * + * If the function returns `Option.some`, the new value is set and published. If + * it returns `Option.none`, the reference is left unchanged and no update is + * published. + * + * **Example** (Getting and conditionally updating a value) * - * @example * ```ts * import { Effect, Option, SubscriptionRef } from "effect" * @@ -424,16 +502,26 @@ export const getAndUpdateEffect: { * }) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export const getAndUpdateSome: { /** - * Atomically retrieves the current value and optionally updates it with the - * result of applying a function that returns an `Option`, notifying - * subscribers only if the value changes. + * Retrieves the current value and optionally updates the reference. + * + * **When to use** + * + * Use to read the old `SubscriptionRef` value while applying a synchronous + * update only when a new value is available. + * + * **Details** + * + * If the function returns `Option.some`, the new value is set and published. If + * it returns `Option.none`, the reference is left unchanged and no update is + * published. + * + * **Example** (Getting and conditionally updating a value) * - * @example * ```ts * import { Effect, Option, SubscriptionRef } from "effect" * @@ -451,16 +539,26 @@ export const getAndUpdateSome: { * }) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ (update: (a: A) => Option.Option): (self: SubscriptionRef) => Effect.Effect /** - * Atomically retrieves the current value and optionally updates it with the - * result of applying a function that returns an `Option`, notifying - * subscribers only if the value changes. + * Retrieves the current value and optionally updates the reference. + * + * **When to use** + * + * Use to read the old `SubscriptionRef` value while applying a synchronous + * update only when a new value is available. + * + * **Details** + * + * If the function returns `Option.some`, the new value is set and published. If + * it returns `Option.none`, the reference is left unchanged and no update is + * published. + * + * **Example** (Getting and conditionally updating a value) * - * @example * ```ts * import { Effect, Option, SubscriptionRef } from "effect" * @@ -478,8 +576,8 @@ export const getAndUpdateSome: { * }) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ (self: SubscriptionRef, update: (a: A) => Option.Option): Effect.Effect } = dual(2, ( @@ -497,11 +595,21 @@ export const getAndUpdateSome: { }))) /** - * Atomically retrieves the current value and optionally updates it with the - * result of applying an effectful function that returns an `Option`, - * notifying subscribers only if the value changes. + * Retrieves the current value and optionally updates the reference effectfully. + * + * **When to use** + * + * Use to read the old `SubscriptionRef` value while applying an effectful + * update only when a new value is available. + * + * **Details** + * + * If the effect succeeds with `Option.some`, the new value is set and + * published. If it succeeds with `Option.none`, the reference is left unchanged + * and no update is published. + * + * **Example** (Getting and conditionally updating with an effect) * - * @example * ```ts * import { Effect, Option, SubscriptionRef } from "effect" * @@ -519,16 +627,26 @@ export const getAndUpdateSome: { * }) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export const getAndUpdateSomeEffect: { /** - * Atomically retrieves the current value and optionally updates it with the - * result of applying an effectful function that returns an `Option`, - * notifying subscribers only if the value changes. + * Retrieves the current value and optionally updates the reference effectfully. + * + * **When to use** + * + * Use to read the old `SubscriptionRef` value while applying an effectful + * update only when a new value is available. + * + * **Details** + * + * If the effect succeeds with `Option.some`, the new value is set and + * published. If it succeeds with `Option.none`, the reference is left unchanged + * and no update is published. + * + * **Example** (Getting and conditionally updating with an effect) * - * @example * ```ts * import { Effect, Option, SubscriptionRef } from "effect" * @@ -546,16 +664,26 @@ export const getAndUpdateSomeEffect: { * }) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ (update: (a: A) => Effect.Effect, E, R>): (self: SubscriptionRef) => Effect.Effect /** - * Atomically retrieves the current value and optionally updates it with the - * result of applying an effectful function that returns an `Option`, - * notifying subscribers only if the value changes. + * Retrieves the current value and optionally updates the reference effectfully. + * + * **When to use** + * + * Use to read the old `SubscriptionRef` value while applying an effectful + * update only when a new value is available. + * + * **Details** + * + * If the effect succeeds with `Option.some`, the new value is set and + * published. If it succeeds with `Option.none`, the reference is left unchanged + * and no update is published. + * + * **Example** (Getting and conditionally updating with an effect) * - * @example * ```ts * import { Effect, Option, SubscriptionRef } from "effect" * @@ -573,8 +701,8 @@ export const getAndUpdateSomeEffect: { * }) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ ( self: SubscriptionRef, @@ -594,10 +722,11 @@ export const getAndUpdateSomeEffect: { }))) /** - * Atomically modifies the `SubscriptionRef` with a function that computes a + * Modifies the `SubscriptionRef` atomically with a function that computes a * return value and a new value, notifying subscribers of the change. * - * @example + * **Example** (Modifying a value) + * * ```ts * import { Effect, SubscriptionRef } from "effect" * @@ -615,15 +744,16 @@ export const getAndUpdateSomeEffect: { * }) * ``` * - * @since 2.0.0 * @category modifications + * @since 2.0.0 */ export const modify: { /** - * Atomically modifies the `SubscriptionRef` with a function that computes a + * Modifies the `SubscriptionRef` atomically with a function that computes a * return value and a new value, notifying subscribers of the change. * - * @example + * **Example** (Modifying a value) + * * ```ts * import { Effect, SubscriptionRef } from "effect" * @@ -641,15 +771,16 @@ export const modify: { * }) * ``` * - * @since 2.0.0 * @category modifications + * @since 2.0.0 */ (modify: (a: A) => readonly [B, A]): (self: SubscriptionRef) => Effect.Effect /** - * Atomically modifies the `SubscriptionRef` with a function that computes a + * Modifies the `SubscriptionRef` atomically with a function that computes a * return value and a new value, notifying subscribers of the change. * - * @example + * **Example** (Modifying a value) + * * ```ts * import { Effect, SubscriptionRef } from "effect" * @@ -667,8 +798,8 @@ export const modify: { * }) * ``` * - * @since 2.0.0 * @category modifications + * @since 2.0.0 */ (self: SubscriptionRef, f: (a: A) => readonly [B, A]): Effect.Effect } = dual(2, ( @@ -682,11 +813,12 @@ export const modify: { }))) /** - * Atomically modifies the `SubscriptionRef` with an effectful function that + * Modifies the `SubscriptionRef` atomically with an effectful function that * computes a return value and a new value, notifying subscribers of the * change. * - * @example + * **Example** (Modifying with an effect) + * * ```ts * import { Effect, SubscriptionRef } from "effect" * @@ -704,16 +836,17 @@ export const modify: { * }) * ``` * - * @since 2.0.0 * @category modifications + * @since 2.0.0 */ export const modifyEffect: { /** - * Atomically modifies the `SubscriptionRef` with an effectful function that + * Modifies the `SubscriptionRef` atomically with an effectful function that * computes a return value and a new value, notifying subscribers of the * change. * - * @example + * **Example** (Modifying with an effect) + * * ```ts * import { Effect, SubscriptionRef } from "effect" * @@ -731,16 +864,17 @@ export const modifyEffect: { * }) * ``` * - * @since 2.0.0 * @category modifications + * @since 2.0.0 */ (modify: (a: A) => Effect.Effect): (self: SubscriptionRef) => Effect.Effect /** - * Atomically modifies the `SubscriptionRef` with an effectful function that + * Modifies the `SubscriptionRef` atomically with an effectful function that * computes a return value and a new value, notifying subscribers of the * change. * - * @example + * **Example** (Modifying with an effect) + * * ```ts * import { Effect, SubscriptionRef } from "effect" * @@ -758,8 +892,8 @@ export const modifyEffect: { * }) * ``` * - * @since 2.0.0 * @category modifications + * @since 2.0.0 */ ( self: SubscriptionRef, @@ -777,11 +911,21 @@ export const modifyEffect: { ))) /** - * Atomically modifies the `SubscriptionRef` with a function that computes a - * return value and optionally a new value, notifying subscribers only if the - * value changes. + * Computes a return value and optionally updates the reference. + * + * **When to use** + * + * Use to return a separate result while synchronously deciding whether to + * publish a new `SubscriptionRef` value. + * + * **Details** + * + * If the function returns `Option.some` for the new value, the value is set and + * published. If it returns `Option.none`, the reference is left unchanged and + * no update is published. + * + * **Example** (Conditionally modifying a value) * - * @example * ```ts * import { Effect, Option, SubscriptionRef } from "effect" * @@ -800,16 +944,26 @@ export const modifyEffect: { * }) * ``` * - * @since 2.0.0 * @category modifications + * @since 2.0.0 */ export const modifySome: { /** - * Atomically modifies the `SubscriptionRef` with a function that computes a - * return value and optionally a new value, notifying subscribers only if the - * value changes. + * Computes a return value and optionally updates the reference. + * + * **When to use** + * + * Use to return a separate result while synchronously deciding whether to + * publish a new `SubscriptionRef` value. + * + * **Details** + * + * If the function returns `Option.some` for the new value, the value is set and + * published. If it returns `Option.none`, the reference is left unchanged and + * no update is published. + * + * **Example** (Conditionally modifying a value) * - * @example * ```ts * import { Effect, Option, SubscriptionRef } from "effect" * @@ -828,16 +982,26 @@ export const modifySome: { * }) * ``` * - * @since 2.0.0 * @category modifications + * @since 2.0.0 */ (modify: (a: A) => readonly [B, Option.Option]): (self: SubscriptionRef) => Effect.Effect /** - * Atomically modifies the `SubscriptionRef` with a function that computes a - * return value and optionally a new value, notifying subscribers only if the - * value changes. + * Computes a return value and optionally updates the reference. + * + * **When to use** + * + * Use to return a separate result while synchronously deciding whether to + * publish a new `SubscriptionRef` value. + * + * **Details** + * + * If the function returns `Option.some` for the new value, the value is set and + * published. If it returns `Option.none`, the reference is left unchanged and + * no update is published. + * + * **Example** (Conditionally modifying a value) * - * @example * ```ts * import { Effect, Option, SubscriptionRef } from "effect" * @@ -856,8 +1020,8 @@ export const modifySome: { * }) * ``` * - * @since 2.0.0 * @category modifications + * @since 2.0.0 */ (self: SubscriptionRef, modify: (a: A) => readonly [B, Option.Option]): Effect.Effect } = dual(2, ( @@ -872,11 +1036,21 @@ export const modifySome: { }))) /** - * Atomically modifies the `SubscriptionRef` with an effectful function that - * computes a return value and optionally a new value, notifying subscribers - * only if the value changes. + * Computes a return value and optionally updates the reference effectfully. + * + * **When to use** + * + * Use to return a separate result while effectfully deciding whether to publish + * a new `SubscriptionRef` value. + * + * **Details** + * + * If the effect succeeds with `Option.some`, the new value is set and + * published. If it succeeds with `Option.none`, the reference is left unchanged + * and no update is published. + * + * **Example** (Conditionally modifying with an effect) * - * @example * ```ts * import { Effect, Option, SubscriptionRef } from "effect" * @@ -899,16 +1073,26 @@ export const modifySome: { * }) * ``` * - * @since 2.0.0 * @category modifications + * @since 2.0.0 */ export const modifySomeEffect: { /** - * Atomically modifies the `SubscriptionRef` with an effectful function that - * computes a return value and optionally a new value, notifying subscribers - * only if the value changes. + * Computes a return value and optionally updates the reference effectfully. + * + * **When to use** + * + * Use to return a separate result while effectfully deciding whether to publish + * a new `SubscriptionRef` value. + * + * **Details** + * + * If the effect succeeds with `Option.some`, the new value is set and + * published. If it succeeds with `Option.none`, the reference is left unchanged + * and no update is published. + * + * **Example** (Conditionally modifying with an effect) * - * @example * ```ts * import { Effect, Option, SubscriptionRef } from "effect" * @@ -931,16 +1115,26 @@ export const modifySomeEffect: { * }) * ``` * - * @since 2.0.0 * @category modifications + * @since 2.0.0 */ (modify: (a: A) => Effect.Effect], E, R>): (self: SubscriptionRef) => Effect.Effect /** - * Atomically modifies the `SubscriptionRef` with an effectful function that - * computes a return value and optionally a new value, notifying subscribers - * only if the value changes. + * Computes a return value and optionally updates the reference effectfully. + * + * **When to use** + * + * Use to return a separate result while effectfully deciding whether to publish + * a new `SubscriptionRef` value. + * + * **Details** + * + * If the effect succeeds with `Option.some`, the new value is set and + * published. If it succeeds with `Option.none`, the reference is left unchanged + * and no update is published. + * + * **Example** (Conditionally modifying with an effect) * - * @example * ```ts * import { Effect, Option, SubscriptionRef } from "effect" * @@ -963,8 +1157,8 @@ export const modifySomeEffect: { * }) * ``` * - * @since 2.0.0 * @category modifications + * @since 2.0.0 */ ( self: SubscriptionRef, @@ -986,7 +1180,8 @@ export const modifySomeEffect: { * Sets the value of the `SubscriptionRef`, notifying all subscribers of the * change. * - * @example + * **Example** (Setting a value) + * * ```ts * import { Effect, SubscriptionRef } from "effect" * @@ -1000,15 +1195,16 @@ export const modifySomeEffect: { * }) * ``` * - * @since 2.0.0 * @category setters + * @since 2.0.0 */ export const set: { /** * Sets the value of the `SubscriptionRef`, notifying all subscribers of the * change. * - * @example + * **Example** (Setting a value) + * * ```ts * import { Effect, SubscriptionRef } from "effect" * @@ -1022,15 +1218,16 @@ export const set: { * }) * ``` * - * @since 2.0.0 * @category setters + * @since 2.0.0 */ (value: A): (self: SubscriptionRef) => Effect.Effect /** * Sets the value of the `SubscriptionRef`, notifying all subscribers of the * change. * - * @example + * **Example** (Setting a value) + * * ```ts * import { Effect, SubscriptionRef } from "effect" * @@ -1044,8 +1241,8 @@ export const set: { * }) * ``` * - * @since 2.0.0 * @category setters + * @since 2.0.0 */ (self: SubscriptionRef, value: A): Effect.Effect } = dual( @@ -1057,7 +1254,8 @@ export const set: { * Sets the value of the `SubscriptionRef` and returns the new value, * notifying all subscribers of the change. * - * @example + * **Example** (Setting and reading the new value) + * * ```ts * import { Effect, SubscriptionRef } from "effect" * @@ -1069,15 +1267,16 @@ export const set: { * }) * ``` * - * @since 2.0.0 * @category setters + * @since 2.0.0 */ export const setAndGet: { /** * Sets the value of the `SubscriptionRef` and returns the new value, * notifying all subscribers of the change. * - * @example + * **Example** (Setting and reading the new value) + * * ```ts * import { Effect, SubscriptionRef } from "effect" * @@ -1089,15 +1288,16 @@ export const setAndGet: { * }) * ``` * - * @since 2.0.0 * @category setters + * @since 2.0.0 */ (value: A): (self: SubscriptionRef) => Effect.Effect /** * Sets the value of the `SubscriptionRef` and returns the new value, * notifying all subscribers of the change. * - * @example + * **Example** (Setting and reading the new value) + * * ```ts * import { Effect, SubscriptionRef } from "effect" * @@ -1109,8 +1309,8 @@ export const setAndGet: { * }) * ``` * - * @since 2.0.0 * @category setters + * @since 2.0.0 */ (self: SubscriptionRef, value: A): Effect.Effect } = dual(2, (self: SubscriptionRef, value: A) => @@ -1123,7 +1323,8 @@ export const setAndGet: { * Updates the value of the `SubscriptionRef` with the result of applying a * function, notifying subscribers of the change. * - * @example + * **Example** (Updating a value) + * * ```ts * import { Effect, SubscriptionRef } from "effect" * @@ -1137,15 +1338,16 @@ export const setAndGet: { * }) * ``` * - * @since 2.0.0 * @category updating + * @since 2.0.0 */ export const update: { /** * Updates the value of the `SubscriptionRef` with the result of applying a * function, notifying subscribers of the change. * - * @example + * **Example** (Updating a value) + * * ```ts * import { Effect, SubscriptionRef } from "effect" * @@ -1159,15 +1361,16 @@ export const update: { * }) * ``` * - * @since 2.0.0 * @category updating + * @since 2.0.0 */ (update: (a: A) => A): (self: SubscriptionRef) => Effect.Effect /** * Updates the value of the `SubscriptionRef` with the result of applying a * function, notifying subscribers of the change. * - * @example + * **Example** (Updating a value) + * * ```ts * import { Effect, SubscriptionRef } from "effect" * @@ -1181,8 +1384,8 @@ export const update: { * }) * ``` * - * @since 2.0.0 * @category updating + * @since 2.0.0 */ (self: SubscriptionRef, update: (a: A) => A): Effect.Effect } = dual( @@ -1195,7 +1398,8 @@ export const update: { * Updates the value of the `SubscriptionRef` with the result of applying an * effectful function, notifying subscribers of the change. * - * @example + * **Example** (Updating with an effect) + * * ```ts * import { Effect, SubscriptionRef } from "effect" * @@ -1209,15 +1413,16 @@ export const update: { * }) * ``` * - * @since 2.0.0 * @category updating + * @since 2.0.0 */ export const updateEffect: { /** * Updates the value of the `SubscriptionRef` with the result of applying an * effectful function, notifying subscribers of the change. * - * @example + * **Example** (Updating with an effect) + * * ```ts * import { Effect, SubscriptionRef } from "effect" * @@ -1231,15 +1436,16 @@ export const updateEffect: { * }) * ``` * - * @since 2.0.0 * @category updating + * @since 2.0.0 */ (update: (a: A) => Effect.Effect): (self: SubscriptionRef) => Effect.Effect /** * Updates the value of the `SubscriptionRef` with the result of applying an * effectful function, notifying subscribers of the change. * - * @example + * **Example** (Updating with an effect) + * * ```ts * import { Effect, SubscriptionRef } from "effect" * @@ -1253,8 +1459,8 @@ export const updateEffect: { * }) * ``` * - * @since 2.0.0 * @category updating + * @since 2.0.0 */ (self: SubscriptionRef, update: (a: A) => Effect.Effect): Effect.Effect } = dual(2, ( @@ -1269,7 +1475,8 @@ export const updateEffect: { * Updates the value of the `SubscriptionRef` with the result of applying a * function and returns the new value, notifying subscribers of the change. * - * @example + * **Example** (Updating and reading the new value) + * * ```ts * import { Effect, SubscriptionRef } from "effect" * @@ -1281,15 +1488,16 @@ export const updateEffect: { * }) * ``` * - * @since 2.0.0 * @category updating + * @since 2.0.0 */ export const updateAndGet: { /** * Updates the value of the `SubscriptionRef` with the result of applying a * function and returns the new value, notifying subscribers of the change. * - * @example + * **Example** (Updating and reading the new value) + * * ```ts * import { Effect, SubscriptionRef } from "effect" * @@ -1301,15 +1509,16 @@ export const updateAndGet: { * }) * ``` * - * @since 2.0.0 * @category updating + * @since 2.0.0 */ (update: (a: A) => A): (self: SubscriptionRef) => Effect.Effect /** * Updates the value of the `SubscriptionRef` with the result of applying a * function and returns the new value, notifying subscribers of the change. * - * @example + * **Example** (Updating and reading the new value) + * * ```ts * import { Effect, SubscriptionRef } from "effect" * @@ -1321,8 +1530,8 @@ export const updateAndGet: { * }) * ``` * - * @since 2.0.0 * @category updating + * @since 2.0.0 */ (self: SubscriptionRef, update: (a: A) => A): Effect.Effect } = dual(2, (self: SubscriptionRef, update: (a: A) => A) => @@ -1337,7 +1546,8 @@ export const updateAndGet: { * effectful function and returns the new value, notifying subscribers of the * change. * - * @example + * **Example** (Updating with an effect and reading the new value) + * * ```ts * import { Effect, SubscriptionRef } from "effect" * @@ -1352,8 +1562,8 @@ export const updateAndGet: { * }) * ``` * - * @since 2.0.0 * @category updating + * @since 2.0.0 */ export const updateAndGetEffect: { /** @@ -1361,7 +1571,8 @@ export const updateAndGetEffect: { * effectful function and returns the new value, notifying subscribers of the * change. * - * @example + * **Example** (Updating with an effect and reading the new value) + * * ```ts * import { Effect, SubscriptionRef } from "effect" * @@ -1376,8 +1587,8 @@ export const updateAndGetEffect: { * }) * ``` * - * @since 2.0.0 * @category updating + * @since 2.0.0 */ (update: (a: A) => Effect.Effect): (self: SubscriptionRef) => Effect.Effect /** @@ -1385,7 +1596,8 @@ export const updateAndGetEffect: { * effectful function and returns the new value, notifying subscribers of the * change. * - * @example + * **Example** (Updating with an effect and reading the new value) + * * ```ts * import { Effect, SubscriptionRef } from "effect" * @@ -1400,8 +1612,8 @@ export const updateAndGetEffect: { * }) * ``` * - * @since 2.0.0 * @category updating + * @since 2.0.0 */ (self: SubscriptionRef, update: (a: A) => Effect.Effect): Effect.Effect } = dual(2, ( @@ -1416,11 +1628,12 @@ export const updateAndGetEffect: { ))) /** - * Optionally updates the value of the `SubscriptionRef` with the result of - * applying a function that returns an `Option`, notifying subscribers only if - * the value changes. + * Applies an update function to the current value. If it returns + * `Option.some`, sets and publishes that value; if it returns `Option.none`, + * leaves the reference unchanged and does not publish. + * + * **Example** (Conditionally updating a value) * - * @example * ```ts * import { Effect, Option, SubscriptionRef } from "effect" * @@ -1437,16 +1650,17 @@ export const updateAndGetEffect: { * }) * ``` * - * @since 2.0.0 * @category updating + * @since 2.0.0 */ export const updateSome: { /** - * Optionally updates the value of the `SubscriptionRef` with the result of - * applying a function that returns an `Option`, notifying subscribers only if - * the value changes. + * Applies an update function to the current value. If it returns + * `Option.some`, sets and publishes that value; if it returns `Option.none`, + * leaves the reference unchanged and does not publish. + * + * **Example** (Conditionally updating a value) * - * @example * ```ts * import { Effect, Option, SubscriptionRef } from "effect" * @@ -1463,16 +1677,17 @@ export const updateSome: { * }) * ``` * - * @since 2.0.0 * @category updating + * @since 2.0.0 */ (update: (a: A) => Option.Option): (self: SubscriptionRef) => Effect.Effect /** - * Optionally updates the value of the `SubscriptionRef` with the result of - * applying a function that returns an `Option`, notifying subscribers only if - * the value changes. + * Applies an update function to the current value. If it returns + * `Option.some`, sets and publishes that value; if it returns `Option.none`, + * leaves the reference unchanged and does not publish. + * + * **Example** (Conditionally updating a value) * - * @example * ```ts * import { Effect, Option, SubscriptionRef } from "effect" * @@ -1489,8 +1704,8 @@ export const updateSome: { * }) * ``` * - * @since 2.0.0 * @category updating + * @since 2.0.0 */ (self: SubscriptionRef, update: (a: A) => Option.Option): Effect.Effect } = dual(2, ( @@ -1504,11 +1719,21 @@ export const updateSome: { }))) /** - * Optionally updates the value of the `SubscriptionRef` with the result of - * applying an effectful function that returns an `Option`, notifying - * subscribers only if the value changes. + * Applies an effectful update only when it produces a new value. + * + * **When to use** + * + * Use to conditionally update a `SubscriptionRef` with an effectful function + * while discarding the resulting value. + * + * **Details** + * + * If the effect succeeds with `Option.some`, the new value is set and + * published. If it succeeds with `Option.none`, the reference is left unchanged + * and no update is published. + * + * **Example** (Conditionally updating with an effect) * - * @example * ```ts * import { Effect, Option, SubscriptionRef } from "effect" * @@ -1525,16 +1750,26 @@ export const updateSome: { * }) * ``` * - * @since 2.0.0 * @category updating + * @since 2.0.0 */ export const updateSomeEffect: { /** - * Optionally updates the value of the `SubscriptionRef` with the result of - * applying an effectful function that returns an `Option`, notifying - * subscribers only if the value changes. + * Applies an effectful update only when it produces a new value. + * + * **When to use** + * + * Use to conditionally update a `SubscriptionRef` with an effectful function + * while discarding the resulting value. + * + * **Details** + * + * If the effect succeeds with `Option.some`, the new value is set and + * published. If it succeeds with `Option.none`, the reference is left unchanged + * and no update is published. + * + * **Example** (Conditionally updating with an effect) * - * @example * ```ts * import { Effect, Option, SubscriptionRef } from "effect" * @@ -1551,16 +1786,26 @@ export const updateSomeEffect: { * }) * ``` * - * @since 2.0.0 * @category updating + * @since 2.0.0 */ (update: (a: A) => Effect.Effect, E, R>): (self: SubscriptionRef) => Effect.Effect /** - * Optionally updates the value of the `SubscriptionRef` with the result of - * applying an effectful function that returns an `Option`, notifying - * subscribers only if the value changes. + * Applies an effectful update only when it produces a new value. + * + * **When to use** + * + * Use to conditionally update a `SubscriptionRef` with an effectful function + * while discarding the resulting value. + * + * **Details** + * + * If the effect succeeds with `Option.some`, the new value is set and + * published. If it succeeds with `Option.none`, the reference is left unchanged + * and no update is published. + * + * **Example** (Conditionally updating with an effect) * - * @example * ```ts * import { Effect, Option, SubscriptionRef } from "effect" * @@ -1577,8 +1822,8 @@ export const updateSomeEffect: { * }) * ``` * - * @since 2.0.0 * @category updating + * @since 2.0.0 */ ( self: SubscriptionRef, @@ -1596,11 +1841,21 @@ export const updateSomeEffect: { ))) /** - * Optionally updates the value of the `SubscriptionRef` with the result of - * applying a function that returns an `Option` and returns the new value, - * notifying subscribers only if the value changes. + * Applies an optional update and returns the current value afterward. + * + * **When to use** + * + * Use to conditionally update a `SubscriptionRef` and read the value that is + * current after the update decision. + * + * **Details** + * + * If the function returns `Option.some`, the new value is set, published, and + * returned. If it returns `Option.none`, the unchanged current value is + * returned without publishing. + * + * **Example** (Conditionally updating and reading the new value) * - * @example * ```ts * import { Effect, Option, SubscriptionRef } from "effect" * @@ -1615,16 +1870,26 @@ export const updateSomeEffect: { * }) * ``` * - * @since 2.0.0 * @category updating + * @since 2.0.0 */ export const updateSomeAndGet: { /** - * Optionally updates the value of the `SubscriptionRef` with the result of - * applying a function that returns an `Option` and returns the new value, - * notifying subscribers only if the value changes. + * Applies an optional update and returns the current value afterward. + * + * **When to use** + * + * Use to conditionally update a `SubscriptionRef` and read the value that is + * current after the update decision. + * + * **Details** + * + * If the function returns `Option.some`, the new value is set, published, and + * returned. If it returns `Option.none`, the unchanged current value is + * returned without publishing. + * + * **Example** (Conditionally updating and reading the new value) * - * @example * ```ts * import { Effect, Option, SubscriptionRef } from "effect" * @@ -1639,16 +1904,26 @@ export const updateSomeAndGet: { * }) * ``` * - * @since 2.0.0 * @category updating + * @since 2.0.0 */ (update: (a: A) => Option.Option): (self: SubscriptionRef) => Effect.Effect /** - * Optionally updates the value of the `SubscriptionRef` with the result of - * applying a function that returns an `Option` and returns the new value, - * notifying subscribers only if the value changes. + * Applies an optional update and returns the current value afterward. + * + * **When to use** + * + * Use to conditionally update a `SubscriptionRef` and read the value that is + * current after the update decision. + * + * **Details** + * + * If the function returns `Option.some`, the new value is set, published, and + * returned. If it returns `Option.none`, the unchanged current value is + * returned without publishing. + * + * **Example** (Conditionally updating and reading the new value) * - * @example * ```ts * import { Effect, Option, SubscriptionRef } from "effect" * @@ -1663,8 +1938,8 @@ export const updateSomeAndGet: { * }) * ``` * - * @since 2.0.0 * @category updating + * @since 2.0.0 */ (self: SubscriptionRef, update: (a: A) => Option.Option): Effect.Effect } = dual(2, ( @@ -1680,11 +1955,21 @@ export const updateSomeAndGet: { }))) /** - * Optionally updates the value of the `SubscriptionRef` with the result of - * applying an effectful function that returns an `Option` and returns the new - * value, notifying subscribers only if the value changes. + * Applies an effectful optional update and returns the current value afterward. + * + * **When to use** + * + * Use to conditionally update a `SubscriptionRef` effectfully and read the + * value that is current after the update decision. + * + * **Details** + * + * If the effect succeeds with `Option.some`, the new value is set, published, + * and returned. If it succeeds with `Option.none`, the unchanged current value + * is returned without publishing. + * + * **Example** (Conditionally updating with an effect and reading the new value) * - * @example * ```ts * import { Effect, Option, SubscriptionRef } from "effect" * @@ -1699,16 +1984,26 @@ export const updateSomeAndGet: { * }) * ``` * - * @since 2.0.0 * @category updating + * @since 2.0.0 */ export const updateSomeAndGetEffect: { /** - * Optionally updates the value of the `SubscriptionRef` with the result of - * applying an effectful function that returns an `Option` and returns the new - * value, notifying subscribers only if the value changes. + * Applies an effectful optional update and returns the current value afterward. + * + * **When to use** + * + * Use to conditionally update a `SubscriptionRef` effectfully and read the + * value that is current after the update decision. + * + * **Details** + * + * If the effect succeeds with `Option.some`, the new value is set, published, + * and returned. If it succeeds with `Option.none`, the unchanged current value + * is returned without publishing. + * + * **Example** (Conditionally updating with an effect and reading the new value) * - * @example * ```ts * import { Effect, Option, SubscriptionRef } from "effect" * @@ -1723,16 +2018,26 @@ export const updateSomeAndGetEffect: { * }) * ``` * - * @since 2.0.0 * @category updating + * @since 2.0.0 */ (update: (a: A) => Effect.Effect, E, R>): (self: SubscriptionRef) => Effect.Effect /** - * Optionally updates the value of the `SubscriptionRef` with the result of - * applying an effectful function that returns an `Option` and returns the new - * value, notifying subscribers only if the value changes. + * Applies an effectful optional update and returns the current value afterward. + * + * **When to use** + * + * Use to conditionally update a `SubscriptionRef` effectfully and read the + * value that is current after the update decision. + * + * **Details** + * + * If the effect succeeds with `Option.some`, the new value is set, published, + * and returned. If it succeeds with `Option.none`, the unchanged current value + * is returned without publishing. + * + * **Example** (Conditionally updating with an effect and reading the new value) * - * @example * ```ts * import { Effect, Option, SubscriptionRef } from "effect" * @@ -1747,8 +2052,8 @@ export const updateSomeAndGetEffect: { * }) * ``` * - * @since 2.0.0 * @category updating + * @since 2.0.0 */ ( self: SubscriptionRef, diff --git a/.opencode/node_modules/effect/src/Symbol.ts b/.opencode/node_modules/effect/src/Symbol.ts index e9539752b72373fdcc18ea6624868f0dc2b67330..b359115daaf6bbe0fa6afbc8c5c5ccbd33e84b69 100644 --- a/.opencode/node_modules/effect/src/Symbol.ts +++ b/.opencode/node_modules/effect/src/Symbol.ts @@ -1,19 +1,28 @@ /** + * The `Symbol` module contains the runtime predicate for JavaScript primitive + * `symbol` values. It is most useful at boundaries where a value is `unknown` + * and must be narrowed before it can be used as a symbol key, identifier, or + * discriminant. + * * @since 2.0.0 */ import * as predicate from "./Predicate.ts" /** - * Tests if a value is a `symbol`. + * Checks whether a value is a `symbol`. + * + * **When to use** + * + * Use to validate unknown input before treating it as a JavaScript `symbol`. + * + * **Example** (Checking for symbols) * - * @example * ```ts - * import * as Predicate from "effect/Predicate" - * import * as assert from "node:assert" + * import { Symbol } from "effect" * - * assert.deepStrictEqual(Predicate.isSymbol(Symbol.for("a")), true) - * assert.deepStrictEqual(Predicate.isSymbol("a"), false) + * console.log(Symbol.isSymbol(globalThis.Symbol.for("a"))) // true + * console.log(Symbol.isSymbol("a")) // false * ``` * * @category guards diff --git a/.opencode/node_modules/effect/src/SynchronizedRef.ts b/.opencode/node_modules/effect/src/SynchronizedRef.ts index e0751f7e3ab02149c28b7395dbe41ff37be81ac4..81dbf9e9d46059d08ac4b9933d584aa5c7563a31 100644 --- a/.opencode/node_modules/effect/src/SynchronizedRef.ts +++ b/.opencode/node_modules/effect/src/SynchronizedRef.ts @@ -1,4 +1,13 @@ /** + * Stores mutable state whose updates run one at a time. + * + * A `SynchronizedRef` behaves like a `Ref` for reading and simple state + * storage, but update and modify operations are serialized so each change sees + * a consistent current value. This is especially useful when the next value is + * computed by an effect, because the effectful transition is still protected + * from concurrent updates. This module includes constructors, reads, writes, + * updates, partial updates, and effectful update helpers. + * * @since 2.0.0 */ import * as Effect from "./Effect.ts" @@ -11,8 +20,19 @@ import * as Semaphore from "./Semaphore.ts" const TypeId = "~effect/SynchronizedRef" /** - * @since 2.0.0 + * A mutable reference whose update and modify operations are serialized with an + * internal semaphore, including effectful transformations. + * + * **When to use** + * + * Use when shared state may be updated by multiple fibers and each update, + * including effectful state transitions, must observe one current value and run + * one at a time. + * + * @see {@link Ref.Ref} for a plain `Ref` when updates do not need effectful synchronization + * * @category models + * @since 2.0.0 */ export interface SynchronizedRef extends Ref.Ref { readonly [TypeId]: typeof TypeId @@ -32,8 +52,15 @@ const Proto = { } /** - * @since 4.0.0 + * Creates a `SynchronizedRef` synchronously from an initial value. + * + * **When to use** + * + * Use when you need synchronous `SynchronizedRef` construction outside an + * Effect workflow. + * * @category constructors + * @since 4.0.0 */ export const makeUnsafe = (value: A): SynchronizedRef => { const self = Object.create(Proto) @@ -43,36 +70,106 @@ export const makeUnsafe = (value: A): SynchronizedRef => { } /** - * @since 2.0.0 + * Creates a `SynchronizedRef` from an initial value, wrapped in an `Effect`. + * + * **When to use** + * + * Use to create a `SynchronizedRef` inside an Effect program when later updates + * may run effects and must be serialized. + * + * **Details** + * + * The returned effect constructs a fresh `SynchronizedRef` by delegating to + * `makeUnsafe` when the effect is evaluated. + * + * @see {@link makeUnsafe} for synchronous construction when the caller controls safe initialization + * @see {@link Ref.make} for a plain `Ref` when updates do not need effectful synchronization + * * @category constructors + * @since 2.0.0 */ export const make = (value: A): Effect.Effect> => Effect.sync(() => makeUnsafe(value)) /** - * @since 2.0.0 + * Reads the current value synchronously, bypassing the `Effect` API and the + * ref's semaphore. + * + * **When to use** + * + * Use when you need immediate synchronous access to a `SynchronizedRef` value + * in low-level code that can safely read outside an `Effect`. + * + * @see {@link get} for the Effect-wrapped read when composing inside Effect programs + * * @category getters + * @since 4.0.0 */ export const getUnsafe = (self: SynchronizedRef): A => self.backing.ref.current /** - * @since 2.0.0 + * Returns an `Effect` that reads the current value of the `SynchronizedRef`. + * + * **When to use** + * + * Use to read the current value of a `SynchronizedRef` inside an `Effect` + * program without changing it. + * + * @see {@link getUnsafe} for synchronous reads when the caller controls safe access outside `Effect` + * * @category getters + * @since 2.0.0 */ export const get = (self: SynchronizedRef): Effect.Effect => Effect.sync(() => getUnsafe(self)) /** + * Sets a new value atomically and returns the previous value, serialized by the + * ref's semaphore. + * + * **When to use** + * + * Use to replace a `SynchronizedRef` with a known value when the previous value + * is also needed. + * + * @see {@link set} for setting a value without returning the previous value + * @see {@link setAndGet} for setting a value and returning the new value + * @see {@link getAndUpdate} for deriving the new value from the current value + * + * @category mutations * @since 2.0.0 - * @category utils */ export const getAndSet: { /** + * Sets a new value atomically and returns the previous value, serialized by the + * ref's semaphore. + * + * **When to use** + * + * Use to replace a `SynchronizedRef` with a known value when the previous value + * is also needed. + * + * @see {@link set} for setting a value without returning the previous value + * @see {@link setAndGet} for setting a value and returning the new value + * @see {@link getAndUpdate} for deriving the new value from the current value + * + * @category mutations * @since 2.0.0 - * @category utils */ (value: A): (self: SynchronizedRef) => Effect.Effect /** + * Sets a new value atomically and returns the previous value, serialized by the + * ref's semaphore. + * + * **When to use** + * + * Use to replace a `SynchronizedRef` with a known value when the previous value + * is also needed. + * + * @see {@link set} for setting a value without returning the previous value + * @see {@link setAndGet} for setting a value and returning the new value + * @see {@link getAndUpdate} for deriving the new value from the current value + * + * @category mutations * @since 2.0.0 - * @category utils */ (self: SynchronizedRef, value: A): Effect.Effect } = dual( @@ -82,18 +179,54 @@ export const getAndSet: { ) /** + * Updates the current value atomically with a function and returns the previous + * value, serialized by the ref's semaphore. + * + * **When to use** + * + * Use to run a pure `SynchronizedRef` state update when the previous stored + * value is also needed. + * + * @see {@link update} for updating without returning a value + * @see {@link updateAndGet} for updating and returning the new value + * @see {@link getAndUpdateEffect} for effectful updates that return the previous value + * + * @category mutations * @since 2.0.0 - * @category utils */ export const getAndUpdate: { /** + * Updates the current value atomically with a function and returns the previous + * value, serialized by the ref's semaphore. + * + * **When to use** + * + * Use to run a pure `SynchronizedRef` state update when the previous stored + * value is also needed. + * + * @see {@link update} for updating without returning a value + * @see {@link updateAndGet} for updating and returning the new value + * @see {@link getAndUpdateEffect} for effectful updates that return the previous value + * + * @category mutations * @since 2.0.0 - * @category utils */ (f: (a: A) => A): (self: SynchronizedRef) => Effect.Effect /** + * Updates the current value atomically with a function and returns the previous + * value, serialized by the ref's semaphore. + * + * **When to use** + * + * Use to run a pure `SynchronizedRef` state update when the previous stored + * value is also needed. + * + * @see {@link update} for updating without returning a value + * @see {@link updateAndGet} for updating and returning the new value + * @see {@link getAndUpdateEffect} for effectful updates that return the previous value + * + * @category mutations * @since 2.0.0 - * @category utils */ (self: SynchronizedRef, f: (a: A) => A): Effect.Effect } = dual( @@ -103,18 +236,60 @@ export const getAndUpdate: { ) /** + * Runs an effectful update atomically while holding the ref's semaphore, sets + * the new value if the effect succeeds, and returns the previous value. + * + * **When to use** + * + * Use when you need an effectful `SynchronizedRef` state transition to return + * the previous stored value. + * + * @see {@link getAndUpdate} for pure updates that return the previous value + * @see {@link updateEffect} for effectful updates without returning a value + * @see {@link updateAndGetEffect} for effectful updates that return the new value + * @see {@link modifyEffect} for effectful updates with a custom return value + * @see {@link getAndUpdateSomeEffect} for conditional effectful updates that return the previous value + * + * @category mutations * @since 2.0.0 - * @category utils */ export const getAndUpdateEffect: { /** + * Runs an effectful update atomically while holding the ref's semaphore, sets + * the new value if the effect succeeds, and returns the previous value. + * + * **When to use** + * + * Use when you need an effectful `SynchronizedRef` state transition to return + * the previous stored value. + * + * @see {@link getAndUpdate} for pure updates that return the previous value + * @see {@link updateEffect} for effectful updates without returning a value + * @see {@link updateAndGetEffect} for effectful updates that return the new value + * @see {@link modifyEffect} for effectful updates with a custom return value + * @see {@link getAndUpdateSomeEffect} for conditional effectful updates that return the previous value + * + * @category mutations * @since 2.0.0 - * @category utils */ (f: (a: A) => Effect.Effect): (self: SynchronizedRef) => Effect.Effect /** + * Runs an effectful update atomically while holding the ref's semaphore, sets + * the new value if the effect succeeds, and returns the previous value. + * + * **When to use** + * + * Use when you need an effectful `SynchronizedRef` state transition to return + * the previous stored value. + * + * @see {@link getAndUpdate} for pure updates that return the previous value + * @see {@link updateEffect} for effectful updates without returning a value + * @see {@link updateAndGetEffect} for effectful updates that return the new value + * @see {@link modifyEffect} for effectful updates with a custom return value + * @see {@link getAndUpdateSomeEffect} for conditional effectful updates that return the previous value + * + * @category mutations * @since 2.0.0 - * @category utils */ (self: SynchronizedRef, f: (a: A) => Effect.Effect): Effect.Effect } = dual( @@ -130,18 +305,54 @@ export const getAndUpdateEffect: { ) /** + * Applies a partial update atomically and returns the previous value. If the + * function returns `Option.some`, the ref is updated; if it returns + * `Option.none`, the ref is left unchanged. + * + * **When to use** + * + * Use to return the previous `SynchronizedRef` value while applying a pure + * conditional update. + * + * @see {@link getAndUpdate} for always applying a pure update + * @see {@link updateSome} for applying a pure conditional update without returning the previous value + * + * @category mutations * @since 2.0.0 - * @category utils */ export const getAndUpdateSome: { /** + * Applies a partial update atomically and returns the previous value. If the + * function returns `Option.some`, the ref is updated; if it returns + * `Option.none`, the ref is left unchanged. + * + * **When to use** + * + * Use to return the previous `SynchronizedRef` value while applying a pure + * conditional update. + * + * @see {@link getAndUpdate} for always applying a pure update + * @see {@link updateSome} for applying a pure conditional update without returning the previous value + * + * @category mutations * @since 2.0.0 - * @category utils */ (pf: (a: A) => Option.Option): (self: SynchronizedRef) => Effect.Effect /** + * Applies a partial update atomically and returns the previous value. If the + * function returns `Option.some`, the ref is updated; if it returns + * `Option.none`, the ref is left unchanged. + * + * **When to use** + * + * Use to return the previous `SynchronizedRef` value while applying a pure + * conditional update. + * + * @see {@link getAndUpdate} for always applying a pure update + * @see {@link updateSome} for applying a pure conditional update without returning the previous value + * + * @category mutations * @since 2.0.0 - * @category utils */ (self: SynchronizedRef, pf: (a: A) => Option.Option): Effect.Effect } = dual( @@ -151,18 +362,54 @@ export const getAndUpdateSome: { ) /** + * Runs an effectful partial update atomically while holding the ref's semaphore + * and returns the previous value. `Option.some` updates the ref; `Option.none` + * leaves it unchanged. + * + * **When to use** + * + * Use to return the previous `SynchronizedRef` value while running an effectful + * conditional update. + * + * @see {@link getAndUpdateSome} for the pure conditional variant + * @see {@link updateSomeEffect} for effectful conditional updates without returning the previous value + * + * @category mutations * @since 2.0.0 - * @category utils */ export const getAndUpdateSomeEffect: { /** + * Runs an effectful partial update atomically while holding the ref's semaphore + * and returns the previous value. `Option.some` updates the ref; `Option.none` + * leaves it unchanged. + * + * **When to use** + * + * Use to return the previous `SynchronizedRef` value while running an effectful + * conditional update. + * + * @see {@link getAndUpdateSome} for the pure conditional variant + * @see {@link updateSomeEffect} for effectful conditional updates without returning the previous value + * + * @category mutations * @since 2.0.0 - * @category utils */ (pf: (a: A) => Effect.Effect, E, R>): (self: SynchronizedRef) => Effect.Effect /** + * Runs an effectful partial update atomically while holding the ref's semaphore + * and returns the previous value. `Option.some` updates the ref; `Option.none` + * leaves it unchanged. + * + * **When to use** + * + * Use to return the previous `SynchronizedRef` value while running an effectful + * conditional update. + * + * @see {@link getAndUpdateSome} for the pure conditional variant + * @see {@link updateSomeEffect} for effectful conditional updates without returning the previous value + * + * @category mutations * @since 2.0.0 - * @category utils */ ( self: SynchronizedRef, @@ -184,18 +431,54 @@ export const getAndUpdateSomeEffect: { ) /** + * Computes a return value and a new ref value atomically, stores the new value, + * and returns the computed result. + * + * **When to use** + * + * Use to derive a separate result and the next stored `SynchronizedRef` value + * from the same current value in one serialized pure update. + * + * @see {@link modifyEffect} for effectfully deriving both the result and next stored value + * @see {@link modifySome} for deriving a result and optionally updating the stored value + * @see {@link updateAndGet} for returning the new stored value instead of a separate result + * + * @category mutations * @since 2.0.0 - * @category utils */ export const modify: { /** + * Computes a return value and a new ref value atomically, stores the new value, + * and returns the computed result. + * + * **When to use** + * + * Use to derive a separate result and the next stored `SynchronizedRef` value + * from the same current value in one serialized pure update. + * + * @see {@link modifyEffect} for effectfully deriving both the result and next stored value + * @see {@link modifySome} for deriving a result and optionally updating the stored value + * @see {@link updateAndGet} for returning the new stored value instead of a separate result + * + * @category mutations * @since 2.0.0 - * @category utils */ (f: (a: A) => readonly [B, A]): (self: SynchronizedRef) => Effect.Effect /** + * Computes a return value and a new ref value atomically, stores the new value, + * and returns the computed result. + * + * **When to use** + * + * Use to derive a separate result and the next stored `SynchronizedRef` value + * from the same current value in one serialized pure update. + * + * @see {@link modifyEffect} for effectfully deriving both the result and next stored value + * @see {@link modifySome} for deriving a result and optionally updating the stored value + * @see {@link updateAndGet} for returning the new stored value instead of a separate result + * + * @category mutations * @since 2.0.0 - * @category utils */ (self: SynchronizedRef, f: (a: A) => readonly [B, A]): Effect.Effect } = dual( @@ -205,18 +488,51 @@ export const modify: { ) /** + * Runs an effectful modification atomically while holding the ref's semaphore, + * stores the new value if the effect succeeds, and returns the computed result. + * + * **When to use** + * + * Use to effectfully compute both a separate return value and the next stored + * `SynchronizedRef` value in one serialized update. + * + * @see {@link modify} for the pure variant + * @see {@link updateEffect} for effectfully storing a new value without a separate result + * + * @category mutations * @since 2.0.0 - * @category utils */ export const modifyEffect: { /** + * Runs an effectful modification atomically while holding the ref's semaphore, + * stores the new value if the effect succeeds, and returns the computed result. + * + * **When to use** + * + * Use to effectfully compute both a separate return value and the next stored + * `SynchronizedRef` value in one serialized update. + * + * @see {@link modify} for the pure variant + * @see {@link updateEffect} for effectfully storing a new value without a separate result + * + * @category mutations * @since 2.0.0 - * @category utils */ (f: (a: A) => Effect.Effect): (self: SynchronizedRef) => Effect.Effect /** + * Runs an effectful modification atomically while holding the ref's semaphore, + * stores the new value if the effect succeeds, and returns the computed result. + * + * **When to use** + * + * Use to effectfully compute both a separate return value and the next stored + * `SynchronizedRef` value in one serialized update. + * + * @see {@link modify} for the pure variant + * @see {@link updateEffect} for effectfully storing a new value without a separate result + * + * @category mutations * @since 2.0.0 - * @category utils */ ( self: SynchronizedRef, @@ -235,18 +551,51 @@ export const modifyEffect: { ) /** + * Computes a return value and an optional new ref value atomically. + * `Option.some` updates the ref; `Option.none` leaves it unchanged. + * + * **When to use** + * + * Use to compute a return value while optionally updating a `SynchronizedRef` + * under its semaphore. + * + * @see {@link modify} for always storing a new value + * @see {@link updateSome} for optional updates without a separate return value + * + * @category mutations * @since 2.0.0 - * @category utils */ export const modifySome: { /** + * Computes a return value and an optional new ref value atomically. + * `Option.some` updates the ref; `Option.none` leaves it unchanged. + * + * **When to use** + * + * Use to compute a return value while optionally updating a `SynchronizedRef` + * under its semaphore. + * + * @see {@link modify} for always storing a new value + * @see {@link updateSome} for optional updates without a separate return value + * + * @category mutations * @since 2.0.0 - * @category utils */ (pf: (a: A) => readonly [B, Option.Option]): (self: SynchronizedRef) => Effect.Effect /** + * Computes a return value and an optional new ref value atomically. + * `Option.some` updates the ref; `Option.none` leaves it unchanged. + * + * **When to use** + * + * Use to compute a return value while optionally updating a `SynchronizedRef` + * under its semaphore. + * + * @see {@link modify} for always storing a new value + * @see {@link updateSome} for optional updates without a separate return value + * + * @category mutations * @since 2.0.0 - * @category utils */ (self: SynchronizedRef, pf: (a: A) => readonly [B, Option.Option]): Effect.Effect } = dual( @@ -258,21 +607,57 @@ export const modifySome: { ) /** + * Runs an effectful modification atomically while holding the ref's semaphore. + * The effect computes a return value and an optional new ref value; + * `Option.some` updates the ref and `Option.none` leaves it unchanged. + * + * **When to use** + * + * Use to effectfully compute a return value while optionally updating the + * stored `SynchronizedRef` value. + * + * @see {@link modifySome} for the pure variant + * @see {@link updateSomeEffect} for effectful optional updates without a separate return value + * + * @category mutations * @since 2.0.0 - * @category utils */ export const modifySomeEffect: { /** + * Runs an effectful modification atomically while holding the ref's semaphore. + * The effect computes a return value and an optional new ref value; + * `Option.some` updates the ref and `Option.none` leaves it unchanged. + * + * **When to use** + * + * Use to effectfully compute a return value while optionally updating the + * stored `SynchronizedRef` value. + * + * @see {@link modifySome} for the pure variant + * @see {@link updateSomeEffect} for effectful optional updates without a separate return value + * + * @category mutations * @since 2.0.0 - * @category utils */ ( fallback: B, pf: (a: A) => Effect.Effect], E, R> ): (self: SynchronizedRef) => Effect.Effect /** + * Runs an effectful modification atomically while holding the ref's semaphore. + * The effect computes a return value and an optional new ref value; + * `Option.some` updates the ref and `Option.none` leaves it unchanged. + * + * **When to use** + * + * Use to effectfully compute a return value while optionally updating the + * stored `SynchronizedRef` value. + * + * @see {@link modifySome} for the pure variant + * @see {@link updateSomeEffect} for effectful optional updates without a separate return value + * + * @category mutations * @since 2.0.0 - * @category utils */ ( self: SynchronizedRef, @@ -297,18 +682,51 @@ export const modifySomeEffect: { ) /** + * Sets the value of the `SynchronizedRef`, serialized by the ref's semaphore. + * + * **When to use** + * + * Use to replace the current value of a `SynchronizedRef` with a known value + * while keeping the write serialized with other synchronized updates. + * + * @see {@link getAndSet} for replacing the value when the previous value is needed + * @see {@link setAndGet} for replacing the value when the new value should be returned + * @see {@link update} for deriving the next value from the current value + * + * @category mutations * @since 2.0.0 - * @category utils */ export const set: { /** + * Sets the value of the `SynchronizedRef`, serialized by the ref's semaphore. + * + * **When to use** + * + * Use to replace the current value of a `SynchronizedRef` with a known value + * while keeping the write serialized with other synchronized updates. + * + * @see {@link getAndSet} for replacing the value when the previous value is needed + * @see {@link setAndGet} for replacing the value when the new value should be returned + * @see {@link update} for deriving the next value from the current value + * + * @category mutations * @since 2.0.0 - * @category utils */ (value: A): (self: SynchronizedRef) => Effect.Effect /** + * Sets the value of the `SynchronizedRef`, serialized by the ref's semaphore. + * + * **When to use** + * + * Use to replace the current value of a `SynchronizedRef` with a known value + * while keeping the write serialized with other synchronized updates. + * + * @see {@link getAndSet} for replacing the value when the previous value is needed + * @see {@link setAndGet} for replacing the value when the new value should be returned + * @see {@link update} for deriving the next value from the current value + * + * @category mutations * @since 2.0.0 - * @category utils */ (self: SynchronizedRef, value: A): Effect.Effect } = dual( @@ -318,18 +736,48 @@ export const set: { ) /** + * Sets the value of the `SynchronizedRef` and returns the new value. + * + * **When to use** + * + * Use to replace the current `SynchronizedRef` value with a known value and + * return that new value. + * + * @see {@link set} for setting without returning a value + * @see {@link getAndSet} for setting while returning the previous value + * + * @category mutations * @since 2.0.0 - * @category utils */ export const setAndGet: { /** + * Sets the value of the `SynchronizedRef` and returns the new value. + * + * **When to use** + * + * Use to replace the current `SynchronizedRef` value with a known value and + * return that new value. + * + * @see {@link set} for setting without returning a value + * @see {@link getAndSet} for setting while returning the previous value + * + * @category mutations * @since 2.0.0 - * @category utils */ (value: A): (self: SynchronizedRef) => Effect.Effect /** + * Sets the value of the `SynchronizedRef` and returns the new value. + * + * **When to use** + * + * Use to replace the current `SynchronizedRef` value with a known value and + * return that new value. + * + * @see {@link set} for setting without returning a value + * @see {@link getAndSet} for setting while returning the previous value + * + * @category mutations * @since 2.0.0 - * @category utils */ (self: SynchronizedRef, value: A): Effect.Effect } = dual( @@ -339,18 +787,54 @@ export const setAndGet: { ) /** + * Updates the value of the `SynchronizedRef` with a function, serialized by the + * ref's semaphore. + * + * **When to use** + * + * Use to apply a pure state transition to a `SynchronizedRef` as a serialized + * `Effect`. + * + * @see {@link updateEffect} for effectfully deriving the next value + * @see {@link updateAndGet} for returning the new stored value + * @see {@link getAndUpdate} for returning the previous stored value + * + * @category mutations * @since 2.0.0 - * @category utils */ export const update: { /** + * Updates the value of the `SynchronizedRef` with a function, serialized by the + * ref's semaphore. + * + * **When to use** + * + * Use to apply a pure state transition to a `SynchronizedRef` as a serialized + * `Effect`. + * + * @see {@link updateEffect} for effectfully deriving the next value + * @see {@link updateAndGet} for returning the new stored value + * @see {@link getAndUpdate} for returning the previous stored value + * + * @category mutations * @since 2.0.0 - * @category utils */ (f: (a: A) => A): (self: SynchronizedRef) => Effect.Effect /** + * Updates the value of the `SynchronizedRef` with a function, serialized by the + * ref's semaphore. + * + * **When to use** + * + * Use to apply a pure state transition to a `SynchronizedRef` as a serialized + * `Effect`. + * + * @see {@link updateEffect} for effectfully deriving the next value + * @see {@link updateAndGet} for returning the new stored value + * @see {@link getAndUpdate} for returning the previous stored value + * + * @category mutations * @since 2.0.0 - * @category utils */ (self: SynchronizedRef, f: (a: A) => A): Effect.Effect } = dual( @@ -360,18 +844,60 @@ export const update: { ) /** + * Runs an effectful update while holding the ref's semaphore and stores the new + * value if the effect succeeds. + * + * **When to use** + * + * Use to run an effectful state transition on a `SynchronizedRef` when storing + * the new value is the only result you need. + * + * @see {@link update} for a pure state transition + * @see {@link getAndUpdateEffect} for returning the previous stored value + * @see {@link updateAndGetEffect} for returning the new stored value + * @see {@link modifyEffect} for returning a separate result while storing a new value + * @see {@link updateSomeEffect} for effectfully applying only some state transitions + * + * @category mutations * @since 2.0.0 - * @category utils */ export const updateEffect: { /** + * Runs an effectful update while holding the ref's semaphore and stores the new + * value if the effect succeeds. + * + * **When to use** + * + * Use to run an effectful state transition on a `SynchronizedRef` when storing + * the new value is the only result you need. + * + * @see {@link update} for a pure state transition + * @see {@link getAndUpdateEffect} for returning the previous stored value + * @see {@link updateAndGetEffect} for returning the new stored value + * @see {@link modifyEffect} for returning a separate result while storing a new value + * @see {@link updateSomeEffect} for effectfully applying only some state transitions + * + * @category mutations * @since 2.0.0 - * @category utils */ (f: (a: A) => Effect.Effect): (self: SynchronizedRef) => Effect.Effect /** + * Runs an effectful update while holding the ref's semaphore and stores the new + * value if the effect succeeds. + * + * **When to use** + * + * Use to run an effectful state transition on a `SynchronizedRef` when storing + * the new value is the only result you need. + * + * @see {@link update} for a pure state transition + * @see {@link getAndUpdateEffect} for returning the previous stored value + * @see {@link updateAndGetEffect} for returning the new stored value + * @see {@link modifyEffect} for returning a separate result while storing a new value + * @see {@link updateSomeEffect} for effectfully applying only some state transitions + * + * @category mutations * @since 2.0.0 - * @category utils */ (self: SynchronizedRef, f: (a: A) => Effect.Effect): Effect.Effect } = dual( @@ -386,18 +912,51 @@ export const updateEffect: { ) /** + * Updates the value of the `SynchronizedRef` with a function and returns the + * new value. + * + * **When to use** + * + * Use to apply a pure `SynchronizedRef` state transition and return the new + * stored value. + * + * @see {@link update} for updating without returning the new value + * @see {@link getAndUpdate} for updating while returning the previous value + * + * @category mutations * @since 2.0.0 - * @category utils */ export const updateAndGet: { /** + * Updates the value of the `SynchronizedRef` with a function and returns the + * new value. + * + * **When to use** + * + * Use to apply a pure `SynchronizedRef` state transition and return the new + * stored value. + * + * @see {@link update} for updating without returning the new value + * @see {@link getAndUpdate} for updating while returning the previous value + * + * @category mutations * @since 2.0.0 - * @category utils */ (f: (a: A) => A): (self: SynchronizedRef) => Effect.Effect /** + * Updates the value of the `SynchronizedRef` with a function and returns the + * new value. + * + * **When to use** + * + * Use to apply a pure `SynchronizedRef` state transition and return the new + * stored value. + * + * @see {@link update} for updating without returning the new value + * @see {@link getAndUpdate} for updating while returning the previous value + * + * @category mutations * @since 2.0.0 - * @category utils */ (self: SynchronizedRef, f: (a: A) => A): Effect.Effect } = dual( @@ -407,18 +966,51 @@ export const updateAndGet: { ) /** + * Runs an effectful update while holding the ref's semaphore, stores the new + * value if the effect succeeds, and returns that new value. + * + * **When to use** + * + * Use to run an effectful `SynchronizedRef` state transition and return the new + * stored value. + * + * @see {@link updateEffect} for effectful updates without returning the new value + * @see {@link updateAndGet} for the pure variant + * + * @category mutations * @since 2.0.0 - * @category utils */ export const updateAndGetEffect: { /** + * Runs an effectful update while holding the ref's semaphore, stores the new + * value if the effect succeeds, and returns that new value. + * + * **When to use** + * + * Use to run an effectful `SynchronizedRef` state transition and return the new + * stored value. + * + * @see {@link updateEffect} for effectful updates without returning the new value + * @see {@link updateAndGet} for the pure variant + * + * @category mutations * @since 2.0.0 - * @category utils */ (f: (a: A) => Effect.Effect): (self: SynchronizedRef) => Effect.Effect /** + * Runs an effectful update while holding the ref's semaphore, stores the new + * value if the effect succeeds, and returns that new value. + * + * **When to use** + * + * Use to run an effectful `SynchronizedRef` state transition and return the new + * stored value. + * + * @see {@link updateEffect} for effectful updates without returning the new value + * @see {@link updateAndGet} for the pure variant + * + * @category mutations * @since 2.0.0 - * @category utils */ (self: SynchronizedRef, f: (a: A) => Effect.Effect): Effect.Effect } = dual( @@ -434,18 +1026,51 @@ export const updateAndGetEffect: { ) /** + * Applies a partial update to the current value. `Option.some` stores the new + * value; `Option.none` leaves the ref unchanged. + * + * **When to use** + * + * Use to apply a pure conditional `SynchronizedRef` update without returning a + * value. + * + * @see {@link update} for always applying a pure update + * @see {@link updateSomeAndGet} for returning the resulting current value + * + * @category mutations * @since 2.0.0 - * @category utils */ export const updateSome: { /** + * Applies a partial update to the current value. `Option.some` stores the new + * value; `Option.none` leaves the ref unchanged. + * + * **When to use** + * + * Use to apply a pure conditional `SynchronizedRef` update without returning a + * value. + * + * @see {@link update} for always applying a pure update + * @see {@link updateSomeAndGet} for returning the resulting current value + * + * @category mutations * @since 2.0.0 - * @category utils */ (f: (a: A) => Option.Option): (self: SynchronizedRef) => Effect.Effect /** + * Applies a partial update to the current value. `Option.some` stores the new + * value; `Option.none` leaves the ref unchanged. + * + * **When to use** + * + * Use to apply a pure conditional `SynchronizedRef` update without returning a + * value. + * + * @see {@link update} for always applying a pure update + * @see {@link updateSomeAndGet} for returning the resulting current value + * + * @category mutations * @since 2.0.0 - * @category utils */ (self: SynchronizedRef, f: (a: A) => Option.Option): Effect.Effect } = dual( @@ -455,18 +1080,51 @@ export const updateSome: { ) /** + * Runs an effectful partial update while holding the ref's semaphore. + * `Option.some` stores the new value; `Option.none` leaves the ref unchanged. + * + * **When to use** + * + * Use to run an effectful conditional `SynchronizedRef` update without + * returning a value. + * + * @see {@link updateSome} for the pure conditional variant + * @see {@link updateEffect} for effectful updates that always store a new value + * + * @category mutations * @since 2.0.0 - * @category utils */ export const updateSomeEffect: { /** + * Runs an effectful partial update while holding the ref's semaphore. + * `Option.some` stores the new value; `Option.none` leaves the ref unchanged. + * + * **When to use** + * + * Use to run an effectful conditional `SynchronizedRef` update without + * returning a value. + * + * @see {@link updateSome} for the pure conditional variant + * @see {@link updateEffect} for effectful updates that always store a new value + * + * @category mutations * @since 2.0.0 - * @category utils */ (pf: (a: A) => Effect.Effect, E, R>): (self: SynchronizedRef) => Effect.Effect /** + * Runs an effectful partial update while holding the ref's semaphore. + * `Option.some` stores the new value; `Option.none` leaves the ref unchanged. + * + * **When to use** + * + * Use to run an effectful conditional `SynchronizedRef` update without + * returning a value. + * + * @see {@link updateSome} for the pure conditional variant + * @see {@link updateEffect} for effectful updates that always store a new value + * + * @category mutations * @since 2.0.0 - * @category utils */ ( self: SynchronizedRef, @@ -487,18 +1145,54 @@ export const updateSomeEffect: { ) /** + * Applies a partial update and returns the resulting current value. + * `Option.some` stores and returns the new value; `Option.none` returns the + * unchanged value. + * + * **When to use** + * + * Use to apply a pure conditional `SynchronizedRef` update and return the + * resulting current value. + * + * @see {@link updateSome} for conditional updates without returning a value + * @see {@link updateAndGet} for always applying a pure update and returning the new value + * + * @category mutations * @since 2.0.0 - * @category utils */ export const updateSomeAndGet: { /** + * Applies a partial update and returns the resulting current value. + * `Option.some` stores and returns the new value; `Option.none` returns the + * unchanged value. + * + * **When to use** + * + * Use to apply a pure conditional `SynchronizedRef` update and return the + * resulting current value. + * + * @see {@link updateSome} for conditional updates without returning a value + * @see {@link updateAndGet} for always applying a pure update and returning the new value + * + * @category mutations * @since 2.0.0 - * @category utils */ (pf: (a: A) => Option.Option): (self: SynchronizedRef) => Effect.Effect /** + * Applies a partial update and returns the resulting current value. + * `Option.some` stores and returns the new value; `Option.none` returns the + * unchanged value. + * + * **When to use** + * + * Use to apply a pure conditional `SynchronizedRef` update and return the + * resulting current value. + * + * @see {@link updateSome} for conditional updates without returning a value + * @see {@link updateAndGet} for always applying a pure update and returning the new value + * + * @category mutations * @since 2.0.0 - * @category utils */ (self: SynchronizedRef, pf: (a: A) => Option.Option): Effect.Effect } = dual( @@ -508,18 +1202,54 @@ export const updateSomeAndGet: { ) /** + * Runs an effectful partial update while holding the ref's semaphore and + * returns the resulting current value. `Option.some` stores and returns the new + * value; `Option.none` returns the unchanged value. + * + * **When to use** + * + * Use to run an effectful conditional `SynchronizedRef` update and return the + * resulting current value. + * + * @see {@link updateSomeEffect} for effectful conditional updates without returning a value + * @see {@link updateAndGetEffect} for effectful updates that always store and return a new value + * + * @category mutations * @since 2.0.0 - * @category utils */ export const updateSomeAndGetEffect: { /** + * Runs an effectful partial update while holding the ref's semaphore and + * returns the resulting current value. `Option.some` stores and returns the new + * value; `Option.none` returns the unchanged value. + * + * **When to use** + * + * Use to run an effectful conditional `SynchronizedRef` update and return the + * resulting current value. + * + * @see {@link updateSomeEffect} for effectful conditional updates without returning a value + * @see {@link updateAndGetEffect} for effectful updates that always store and return a new value + * + * @category mutations * @since 2.0.0 - * @category utils */ (pf: (a: A) => Effect.Effect, E, R>): (self: SynchronizedRef) => Effect.Effect /** + * Runs an effectful partial update while holding the ref's semaphore and + * returns the resulting current value. `Option.some` stores and returns the new + * value; `Option.none` returns the unchanged value. + * + * **When to use** + * + * Use to run an effectful conditional `SynchronizedRef` update and return the + * resulting current value. + * + * @see {@link updateSomeEffect} for effectful conditional updates without returning a value + * @see {@link updateAndGetEffect} for effectful updates that always store and return a new value + * + * @category mutations * @since 2.0.0 - * @category utils */ ( self: SynchronizedRef, diff --git a/.opencode/node_modules/effect/src/Take.ts b/.opencode/node_modules/effect/src/Take.ts index 558d514b3249ee5b2c875273ec06fe81acbfb2d8..48c2dd796a3ff2191f8f340c9eae70046085f406 100644 --- a/.opencode/node_modules/effect/src/Take.ts +++ b/.opencode/node_modules/effect/src/Take.ts @@ -1,4 +1,9 @@ /** + * The `Take` module provides the stored representation of one pull result from + * a stream-like producer. A `Take` is either a non-empty batch of + * emitted values, a failed `Exit`, or a successful `Exit` carrying the + * completion value. + * * @since 2.0.0 */ import type { NonEmptyReadonlyArray } from "./Array.ts" @@ -8,14 +13,32 @@ import * as Exit from "./Exit.ts" import type * as Pull from "./Pull.ts" /** + * Represents one pull result: either a non-empty batch of values, a failure + * `Exit`, or a successful `Exit` that signals completion with a `Done` value. + * + * **When to use** + * + * Use to store, transfer, or interpret pull results later while preserving + * emitted values, failures, and normal completion. + * + * @see {@link toPull} for interpreting a `Take` as a `Pull` step + * + * @category models * @since 2.0.0 - * @category Models */ export type Take = NonEmptyReadonlyArray | Exit.Exit /** + * Converts a `Take` into a `Pull`, succeeding with value batches, failing with + * failure exits, and translating successful exits into pull completion. + * + * **When to use** + * + * Use to interpret a stored or transferred `Take` as a `Pull` step while + * preserving emitted batches, ordinary failures, and completion values. + * + * @category converting * @since 4.0.0 - * @category Conversions */ export const toPull = (take: Take): Pull.Pull, E, Done> => Exit.isExit(take) diff --git a/.opencode/node_modules/effect/src/Terminal.ts b/.opencode/node_modules/effect/src/Terminal.ts index 8f4ad771fbe1055851faef0767eb3d368d95a869..f59175692ea85ac465412b035304930b3564067b 100644 --- a/.opencode/node_modules/effect/src/Terminal.ts +++ b/.opencode/node_modules/effect/src/Terminal.ts @@ -1,4 +1,12 @@ /** + * Service definition for interactive terminal capabilities. Programs can query + * terminal dimensions, read a line of input, receive low-level key events, and + * display text without depending directly on a specific platform implementation. + * + * This module defines the `Terminal` service, input event shapes, key metadata, + * the `QuitError` used when a user cancels input, a guard for that error, and a + * constructor for custom terminal service implementations. + * * @since 4.0.0 */ import type * as Cause from "./Cause.ts" @@ -17,8 +25,8 @@ const TypeId = "~effect/platform/Terminal" * A `Terminal` represents a command-line interface which can read input from a * user and display messages to a user. * + * @category models * @since 4.0.0 - * @category Models */ export interface Terminal { readonly [TypeId]: typeof TypeId @@ -27,6 +35,11 @@ export interface Terminal { * The number of columns available on the platform's terminal interface. */ readonly columns: Effect.Effect + /** + * The number of rows available on the platform's terminal interface. + */ + + readonly rows: Effect.Effect /** * Reads input events from the default standard input. */ @@ -42,8 +55,11 @@ export interface Terminal { } /** + * Keyboard key metadata for terminal input, including the key name and + * modifier state. + * + * @category models * @since 4.0.0 - * @category Models */ export interface Key { /** @@ -65,8 +81,18 @@ export interface Key { } /** + * A terminal input event containing an optional raw character and the parsed + * key that was pressed. + * + * **When to use** + * + * Use when consuming low-level terminal input events from `Terminal.readInput` + * and you need both raw character input and parsed key metadata. + * + * @see {@link Key} for the parsed key metadata stored on each input event + * + * @category models * @since 4.0.0 - * @category Models */ export interface UserInput { /** @@ -82,38 +108,80 @@ export interface UserInput { const QuitErrorTypeId = "effect/platform/Terminal/QuitError" /** - * A `QuitError` represents an error that occurs when a user attempts to + * Represents an error that occurs when a user attempts to * quit out of a `Terminal` prompt for input (usually by entering `ctrl`+`c`). * - * @since 4.0.0 + * **When to use** + * + * Use when implementing terminal input or prompts that need to signal + * user-requested cancellation through the typed error channel. + * + * @see {@link isQuitError} for checking unknown errors when handling terminal cancellation + * * @category QuitError + * @since 4.0.0 */ export class QuitError extends Schema.ErrorClass("QuitError")({ _tag: Schema.tag("QuitError") }) { /** + * Marks this value as a terminal quit error for runtime guards. + * * @since 4.0.0 */ readonly [QuitErrorTypeId] = QuitErrorTypeId } /** + * Returns `true` if the provided value is a `Terminal.QuitError`. + * + * **When to use** + * + * Use to narrow unknown failures to `QuitError` when handling terminal input + * cancellation. + * + * **Details** + * + * Returns `true` when the value carries the `QuitError` runtime marker and + * narrows it to `QuitError`. + * + * @see {@link QuitError} for the error value produced when terminal input is quit + * + * @category guards * @since 4.0.0 - * @category QuitError */ export const isQuitError = (u: unknown): u is QuitError => Predicate.hasProperty(u, QuitErrorTypeId) /** + * Service tag for command-line input and output services. + * + * **When to use** + * + * Use to access or provide platform terminal capabilities such as reading + * input, writing output, and inspecting terminal dimensions. + * + * @category services * @since 4.0.0 - * @category Services */ export const Terminal: Context.Service = Context.Service("effect/platform/Terminal") /** - * Creates a Terminal implementation + * Creates a `Terminal` service implementation. + * + * **When to use** + * + * Use to construct a custom `Terminal` service implementation from concrete + * terminal capabilities when writing a platform adapter, test implementation, + * or custom runtime service. + * + * **Details** + * + * The implementation object supplies `columns`, `rows`, `readInput`, + * `readLine`, and `display`; `make` attaches the `Terminal` service marker so + * the result can be provided through the `Terminal` context service. * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const make = ( impl: Omit diff --git a/.opencode/node_modules/effect/src/Tracer.ts b/.opencode/node_modules/effect/src/Tracer.ts index a0a730a196313a2d88de37b3ff705ae0e6ca60e3..028829dedd6782f5710d13519218e76ee6dc56a4 100644 --- a/.opencode/node_modules/effect/src/Tracer.ts +++ b/.opencode/node_modules/effect/src/Tracer.ts @@ -1,4 +1,12 @@ /** + * Defines the low-level tracing model used by Effect. + * + * A span records the lifetime of an operation, including its name, parent, + * attributes, links, annotations, sampling decision, kind, and completion + * status. The module also defines the tracer service, parent-span context, + * external span support, trace propagation settings, and the default in-memory + * span implementation. + * * @since 2.0.0 */ import * as Context from "./Context.ts" @@ -10,8 +18,12 @@ import type { LogLevel } from "./LogLevel.ts" import * as Option from "./Option.ts" /** - * @since 2.0.0 + * A tracing backend used by Effect to create spans. Custom tracers implement + * `span` to allocate a span from the supplied name, parent, annotations, + * links, start time, kind, root flag, and sampling decision. + * * @category models + * @since 2.0.0 */ export interface Tracer { span(this: Tracer, options: { @@ -32,35 +44,48 @@ export interface Tracer { const evaluate = "~effect/Effect/evaluate" satisfies core.evaluate /** - * @since 4.0.0 + * A low-level Effect primitive that can be evaluated by a tracer-specific + * context for the current fiber. + * * @category models + * @since 4.0.0 */ export interface EffectPrimitive { [evaluate](this: EffectPrimitive, fiber: Fiber): X } /** - * @since 2.0.0 - * @category models - * @example + * Lifecycle state of a span, where `Started` records the start time and + * `Ended` records the start time, end time, and exit value with which the span + * completed. + * + * **Example** (Creating span statuses) + * * ```ts - * import type { Tracer } from "effect" * import { Exit } from "effect" + * import type { Tracer } from "effect" + * + * const startTime = 1_000_000_000n + * const endTime = 1_500_000_000n * - * // Started span status * const startedStatus: Tracer.SpanStatus = { * _tag: "Started", - * startTime: BigInt(Date.now() * 1000000) + * startTime * } * - * // Ended span status * const endedStatus: Tracer.SpanStatus = { * _tag: "Ended", - * startTime: BigInt(Date.now() * 1000000), - * endTime: BigInt(Date.now() * 1000000 + 1000000), + * startTime, + * endTime, * exit: Exit.succeed("result") * } + * + * console.log(startedStatus._tag) // "Started" + * console.log(endedStatus.endTime - endedStatus.startTime) // 500000000n * ``` + * + * @category models + * @since 2.0.0 */ export type SpanStatus = { _tag: "Started" @@ -73,9 +98,11 @@ export type SpanStatus = { } /** - * @since 2.0.0 - * @category models - * @example + * A span value that can participate in tracing, either an Effect-managed + * `Span` or an `ExternalSpan` propagated from another tracing system. + * + * **Example** (Accepting any span) + * * ```ts * import { Effect, Tracer } from "effect" * @@ -91,26 +118,40 @@ export type SpanStatus = { * traceId: "trace-456" * }) * ``` + * + * @category models + * @since 2.0.0 */ export type AnySpan = Span | ExternalSpan /** - * @since 2.0.0 - * @category tags - * @example + * Defines the string key for the parent-span context service. + * + * **When to use** + * + * Use when you need the raw context key for parent span lookup in lower-level + * tracing code. + * + * **Example** (Reading the parent span key) + * * ```ts * import { Tracer } from "effect" * * // The key used to identify parent spans in the context * console.log(Tracer.ParentSpanKey) // "effect/Tracer/ParentSpan" * ``` + * + * @category constants + * @since 4.0.0 */ export const ParentSpanKey = "effect/Tracer/ParentSpan" /** - * @since 2.0.0 - * @category tags - * @example + * Context service containing the `Span` or `ExternalSpan` to use as the parent + * of newly-created child spans. + * + * **Example** (Accessing the parent span) + * * ```ts * import { Effect, Tracer } from "effect" * @@ -120,16 +161,22 @@ export const ParentSpanKey = "effect/Tracer/ParentSpan" * console.log(`Parent span: ${parentSpan.spanId}`) * }) * ``` + * + * @category services + * @since 2.0.0 */ export class ParentSpan extends Context.Service()(ParentSpanKey) {} /** - * @since 2.0.0 - * @category models - * @example + * Represents a span created outside Effect's tracer, carrying trace and span + * identifiers, sampling state, and annotations so it can be used as a parent or + * link in Effect tracing. + * + * **Example** (Creating an external span value) + * * ```ts - * import type { Tracer } from "effect" * import { Context } from "effect" + * import type { Tracer } from "effect" * * // Create an external span from another tracing system * const externalSpan: Tracer.ExternalSpan = { @@ -142,6 +189,9 @@ export class ParentSpan extends Context.Service()(ParentSpa * * console.log(`External span: ${externalSpan.spanId}`) * ``` + * + * @category models + * @since 2.0.0 */ export interface ExternalSpan { readonly _tag: "ExternalSpan" @@ -152,12 +202,15 @@ export interface ExternalSpan { } /** - * @since 3.1.0 - * @category models - * @example + * Options accepted by span-creating APIs, combining span metadata such as + * attributes, links, parent/root selection, kind, sampling, and trace level + * with stack trace capture settings. + * + * **Example** (Configuring span options) + * * ```ts - * import type { Tracer } from "effect" * import { Effect } from "effect" + * import type { Tracer } from "effect" * * // Create an effect with span options * const options: Tracer.SpanOptions = { @@ -171,12 +224,19 @@ export interface ExternalSpan { * Effect.withSpan("my-operation", options) * ) * ``` + * + * @category options + * @since 3.1.0 */ export interface SpanOptions extends SpanOptionsNoTrace, TraceOptions {} /** - * @since 3.1.0 - * @category models + * Span creation options that do not control stack trace capture, including + * attributes, links, parent or root selection, annotations, span kind, + * sampling, and the trace level used for filtering. + * + * @category options + * @since 4.0.0 */ export interface SpanOptionsNoTrace { readonly attributes?: Record | undefined @@ -190,20 +250,25 @@ export interface SpanOptionsNoTrace { } /** - * @since 3.1.0 - * @category models + * Options that control stack trace capture for tracing wrappers. + * `captureStackTrace` can disable capture or provide a lazy stack string. + * + * @category options + * @since 4.0.0 */ export interface TraceOptions { readonly captureStackTrace?: boolean | LazyArg | undefined } /** - * @since 3.1.0 - * @category models - * @example + * OpenTelemetry-style role describing the kind of operation represented by a + * span: internal work, server handling, client calls, producing, or consuming. + * + * **Example** (Configuring span kinds) + * * ```ts - * import type { Tracer } from "effect" * import { Effect } from "effect" + * import type { Tracer } from "effect" * * // Different span kinds for different operations * const serverSpan = Effect.withSpan("handle-request", { @@ -218,24 +283,68 @@ export interface TraceOptions { * kind: "internal" as Tracer.SpanKind * }) * ``` + * + * @category models + * @since 3.1.0 */ export type SpanKind = "internal" | "server" | "client" | "producer" | "consumer" /** - * @since 2.0.0 - * @category models - * @example + * A span created by an Effect tracer. It carries trace identity, parent, + * annotations, attributes, links, sampling and kind information, lifecycle + * status, and methods to end the span or add attributes, events, and links. + * + * **Example** (Working with spans) + * * ```ts - * import { Effect } from "effect" + * import { Context, Exit, Option } from "effect" + * import type { Tracer } from "effect" * - * // Working with spans using withSpan - * const program = Effect.succeed("Hello World").pipe( - * Effect.withSpan("my-operation") - * ) + * const attributes = new Map() + * const links: Array = [] + * let status: Tracer.SpanStatus = { + * _tag: "Started", + * startTime: 1_000_000_000n + * } + * + * const span: Tracer.Span = { + * _tag: "Span", + * name: "load-user", + * spanId: "span-1", + * traceId: "trace-1", + * parent: Option.none(), + * annotations: Context.empty(), + * get status() { + * return status + * }, + * attributes, + * links, + * sampled: true, + * kind: "internal", + * end(endTime, exit) { + * status = { _tag: "Ended", startTime: status.startTime, endTime, exit } + * }, + * attribute(key, value) { + * attributes.set(key, value) + * }, + * event(name, startTime, eventAttributes = {}) { + * console.log(`${name} at ${startTime} with ${Object.keys(eventAttributes).length} attributes`) + * }, + * addLinks(newLinks) { + * links.push(...newLinks) + * } + * } + * + * span.attribute("user.id", "123") + * span.end(1_500_000_000n, Exit.succeed("user")) * - * // The span interface defines the properties available - * // when working with tracing in your effects + * console.log(span.name) // "load-user" + * console.log(span.attributes.get("user.id")) // "123" + * console.log(span.status._tag) // "Ended" * ``` + * + * @category models + * @since 2.0.0 */ export interface Span { readonly _tag: "Span" @@ -256,9 +365,11 @@ export interface Span { } /** - * @since 2.0.0 - * @category models - * @example + * A relationship from one span to another span, with attributes describing the + * relationship. + * + * **Example** (Linking spans) + * * ```ts * import { Effect, Tracer } from "effect" * @@ -277,6 +388,9 @@ export interface Span { * Effect.withSpan("linked-operation", { links: [link] }) * ) * ``` + * + * @category models + * @since 2.0.0 */ export interface SpanLink { readonly span: AnySpan @@ -284,15 +398,33 @@ export interface SpanLink { } /** - * @since 2.0.0 + * Creates a `Tracer` value from a tracer implementation object. + * + * **When to use** + * + * Use to create a custom tracing backend value that Effect can use when + * creating spans. + * + * **Details** + * + * `make` returns the supplied implementation object unchanged. The object must + * satisfy the `Tracer` contract, including a `span` method that returns a + * `Span`. + * + * @see {@link Span} for the span values returned by tracer implementations + * * @category constructors + * @since 2.0.0 */ export const make = (options: Tracer): Tracer => options /** - * @since 2.0.0 - * @category constructors - * @example + * Creates an `ExternalSpan` from trace and span identifiers, defaulting + * `sampled` to `true` and annotations to an empty context when they are not + * provided. + * + * **Example** (Creating an external span) + * * ```ts * import { Effect, Tracer } from "effect" * @@ -308,6 +440,9 @@ export const make = (options: Tracer): Tracer => options * Effect.withSpan("child-operation", { parent: span }) * ) * ``` + * + * @category constructors + * @since 2.0.0 */ export const externalSpan = ( options: { @@ -325,9 +460,20 @@ export const externalSpan = ( }) /** - * @since 3.12.0 - * @category references - * @example + * Context reference for disabling trace propagation. + * + * **When to use** + * + * Use to prevent spans in a scope from propagating tracing context. + * + * **Details** + * + * When enabled on fiber or span annotations, new spans are created as + * non-propagating no-op spans and disabled spans are skipped when deriving a + * parent span. + * + * **Example** (Disabling span propagation) + * * ```ts * import { Effect, Tracer } from "effect" * @@ -338,6 +484,9 @@ export const externalSpan = ( * Effect.provideService(Tracer.DisablePropagation, true) * ) * ``` + * + * @category references + * @since 3.12.0 */ export const DisablePropagation = Context.Reference( "effect/Tracer/DisablePropagation", @@ -345,7 +494,19 @@ export const DisablePropagation = Context.Reference( ) /** - * Reference for controlling the current trace level for dynamic filtering. + * Context reference for controlling the current trace level for dynamic filtering. + * + * **When to use** + * + * Use to set the default trace level for spans in a scope when span options do + * not provide `level`. + * + * **Details** + * + * The default value is `"Info"`. Span creation uses `options.level ?? + * CurrentTraceLevel` before applying `MinimumTraceLevel`. + * + * @see {@link MinimumTraceLevel} for the threshold that decides whether spans at that level are sampled * * @category references * @since 4.0.0 @@ -356,10 +517,26 @@ export const CurrentTraceLevel: Context.Reference = Context.Reference< ) /** - * Reference for setting the minimum trace level threshold. Spans and their + * Context reference for setting the minimum trace level threshold. Spans and their * descendants below this level will have their sampling decision forced to * false, preventing them from being exported. * + * **When to use** + * + * Use to set the trace-level threshold that controls whether spans are sampled + * by default. + * + * **Details** + * + * The default value is `"All"`. Span creation compares the span level from + * `options.level ?? CurrentTraceLevel` against this threshold. + * + * **Gotchas** + * + * Explicit `options.sampled` bypasses threshold computation. + * + * @see {@link CurrentTraceLevel} for the default span level used when options do not specify one + * * @category references * @since 4.0.0 */ @@ -368,15 +545,24 @@ export const MinimumTraceLevel = Context.Reference< >("effect/Tracer/MinimumTraceLevel", { defaultValue: () => "All" }) /** - * @since 4.0.0 + * Defines the string key for the active tracer context reference. + * + * **When to use** + * + * Use when you need the raw context key for active tracer lookup in lower-level + * tracing code. + * * @category references + * @since 4.0.0 */ export const TracerKey = "effect/Tracer" /** - * @since 4.0.0 - * @category references - * @example + * Context reference for the active tracer service. By default it uses the + * native tracer, which creates `NativeSpan` instances. + * + * **Example** (Accessing the current tracer) + * * ```ts * import { Effect, Tracer } from "effect" * @@ -392,6 +578,9 @@ export const TracerKey = "effect/Tracer" * console.log("Current tracer obtained") * }) * ``` + * + * @category references + * @since 2.0.0 */ export const Tracer: Context.Reference = Context.Reference(TracerKey, { defaultValue: () => @@ -401,8 +590,20 @@ export const Tracer: Context.Reference = Context.Reference(Trace }) /** - * @since 4.0.0 + * Default in-memory `Span` implementation used by the native tracer. It + * generates span and trace identifiers, stores attributes, events, and links, + * and records `Started` or `Ended` status. + * + * **Details** + * + * The constructor initializes the span with `Started` status, inherits the + * parent trace id or generates a new one, and always generates a new span id. + * Attributes, events, links, and status are then mutated through `Span` methods. + * + * @see {@link Span} for the interface implemented by native spans + * * @category native tracer + * @since 4.0.0 */ export class NativeSpan implements Span { readonly _tag = "Span" diff --git a/.opencode/node_modules/effect/src/Trie.ts b/.opencode/node_modules/effect/src/Trie.ts index 23a435bde0dc163ef69233db2d57c7601a779af3..1b93027d31fd11cd9165d1ef174e7067d1aa17a4 100644 --- a/.opencode/node_modules/effect/src/Trie.ts +++ b/.opencode/node_modules/effect/src/Trie.ts @@ -1,17 +1,11 @@ /** - * A `Trie` is used for locating specific `string` keys from within a set. + * Stores string-keyed values in an immutable prefix tree. * - * It works similar to `HashMap`, but with keys required to be `string`. - * This constraint unlocks some performance optimizations and new methods to get string prefixes (e.g. `keysWithPrefix`, `longestPrefixOf`). - * - * Prefix search is also the main feature that makes a `Trie` more suited than `HashMap` for certain usecases. - * - * A `Trie` is often used to store a dictionary (list of words) that can be searched - * in a manner that allows for efficient generation of completion lists - * (e.g. predict the rest of a word a user is typing). - * - * A `Trie` has O(n) lookup time where `n` is the size of the key, - * or even less than `n` on search misses. + * A `Trie` is similar to a map whose keys are strings, but it is built + * for looking up keys by prefix. It is useful for autocomplete, route tables, + * dictionaries, and command lookup. Updates return new tries, and the module + * includes exact lookup, prefix lookup, longest-prefix lookup, iteration, + * mapping, filtering, reducing, and traversal helpers. * * @since 2.0.0 */ @@ -26,9 +20,14 @@ import type { Covariant, NoInfer } from "./Types.ts" const TypeId = TR.TrieTypeId /** - * @example + * An immutable string-keyed map optimized for prefix lookup. Iteration yields + * `[key, value]` pairs in key order, and update operations such as insert and + * remove return new `Trie` values. + * + * **Example** (Using a trie for prefix search) + * * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * * // Create a trie with string-to-number mappings * const trie: Trie.Trie = Trie.make( @@ -59,8 +58,8 @@ const TypeId = TR.TrieTypeId * console.log(Trie.size(trie)) // 4 * ``` * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface Trie extends Iterable<[string, Value]>, Equal, Pipeable, Inspectable { readonly [TypeId]: { @@ -71,9 +70,10 @@ export interface Trie extends Iterable<[string, Value]>, Equal, Pi /** * Creates an empty `Trie`. * - * @example + * **Example** (Creating an empty trie) + * * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty() @@ -82,18 +82,18 @@ export interface Trie extends Iterable<[string, Value]>, Equal, Pi * assert.deepStrictEqual(Array.from(trie), []) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const empty: () => Trie = TR.empty /** * Creates a new `Trie` from an iterable collection of key/value pairs (e.g. `Array<[string, V]>`). * - * @example + * **Example** (Creating a trie from entries) + * * ```ts - * import * as Equal from "effect/Equal" - * import * as Trie from "effect/Trie" + * import { Equal, Trie } from "effect" * import * as assert from "node:assert" * * const iterable: Array = [["call", 0], ["me", 1], [ @@ -116,18 +116,18 @@ export const empty: () => Trie = TR.empty * ) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const fromIterable: (entries: Iterable) => Trie = TR.fromIterable /** * Constructs a new `Trie` from the specified entries (`[string, V]`). * - * @example + * **Example** (Constructing a trie from entries) + * * ```ts - * import * as Equal from "effect/Equal" - * import * as Trie from "effect/Trie" + * import { Equal, Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.make(["ca", 0], ["me", 1]) @@ -139,19 +139,20 @@ export const fromIterable: (entries: Iterable) => Trie< * ) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const make: >( ...entries: Entries ) => Trie = TR.make /** - * Insert a new entry in the `Trie`. + * Inserts a new entry in the `Trie`. + * + * **Example** (Inserting entries) * - * @example * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * const trie1 = Trie.empty().pipe( @@ -170,16 +171,17 @@ export const make: >( * ]]) * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ export const insert: { /** - * Insert a new entry in the `Trie`. + * Inserts a new entry in the `Trie`. + * + * **Example** (Inserting entries) * - * @example * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * const trie1 = Trie.empty().pipe( @@ -198,16 +200,17 @@ export const insert: { * ]]) * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ (key: string, value: V): (self: Trie) => Trie /** - * Insert a new entry in the `Trie`. + * Inserts a new entry in the `Trie`. + * + * **Example** (Inserting entries) * - * @example * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * const trie1 = Trie.empty().pipe( @@ -226,8 +229,8 @@ export const insert: { * ]]) * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ (self: Trie, key: string, value: V): Trie } = TR.insert @@ -235,11 +238,14 @@ export const insert: { /** * Returns an `IterableIterator` of the keys within the `Trie`. * + * **Details** + * * The keys are returned in alphabetical order, regardless of insertion order. * - * @example + * **Example** (Reading keys in alphabetical order) + * * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -252,19 +258,22 @@ export const insert: { * assert.deepStrictEqual(result, ["abc", "bca", "cab"]) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export const keys: (self: Trie) => IterableIterator = TR.keys /** * Returns an `IterableIterator` of the values within the `Trie`. * + * **Details** + * * Values are ordered based on their key in alphabetical order, regardless of insertion order. * - * @example + * **Example** (Reading values by key order) + * * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -277,19 +286,22 @@ export const keys: (self: Trie) => IterableIterator = TR.keys * assert.deepStrictEqual(result, [2, 0, 1]) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export const values: (self: Trie) => IterableIterator = TR.values /** * Returns an `IterableIterator` of the entries within the `Trie`. * + * **Details** + * * The entries are returned by keys in alphabetical order, regardless of insertion order. * - * @example + * **Example** (Reading entries in alphabetical order) + * * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -301,19 +313,22 @@ export const values: (self: Trie) => IterableIterator = TR.values * assert.deepStrictEqual(result, [["call", 0], ["me", 1]]) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export const entries: (self: Trie) => IterableIterator<[string, V]> = TR.entries /** - * Returns an `Array<[K, V]>` of the entries within the `Trie`. + * Returns an `Array<[string, V]>` of the entries within the `Trie`. + * + * **Details** * * Equivalent to `Array.from(Trie.entries(trie))`. * - * @example + * **Example** (Converting entries to an array) + * * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -325,8 +340,8 @@ export const entries: (self: Trie) => IterableIterator<[string, V]> = TR.e * assert.deepStrictEqual(result, [["call", 0], ["me", 1]]) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export const toEntries = (self: Trie): Array<[string, V]> => Array.from(entries(self)) @@ -334,9 +349,10 @@ export const toEntries = (self: Trie): Array<[string, V]> => Array.from(en * Returns an `IterableIterator` of the keys within the `Trie` * that have `prefix` as prefix (`prefix` included if it exists). * - * @example + * **Example** (Finding keys with a prefix) + * * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -350,17 +366,18 @@ export const toEntries = (self: Trie): Array<[string, V]> => Array.from(en * assert.deepStrictEqual(result, ["she", "shells"]) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export const keysWithPrefix: { /** * Returns an `IterableIterator` of the keys within the `Trie` * that have `prefix` as prefix (`prefix` included if it exists). * - * @example + * **Example** (Finding keys with a prefix) + * * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -374,17 +391,18 @@ export const keysWithPrefix: { * assert.deepStrictEqual(result, ["she", "shells"]) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ (prefix: string): (self: Trie) => IterableIterator /** * Returns an `IterableIterator` of the keys within the `Trie` * that have `prefix` as prefix (`prefix` included if it exists). * - * @example + * **Example** (Finding keys with a prefix) + * * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -398,8 +416,8 @@ export const keysWithPrefix: { * assert.deepStrictEqual(result, ["she", "shells"]) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ (self: Trie, prefix: string): IterableIterator } = TR.keysWithPrefix @@ -408,9 +426,10 @@ export const keysWithPrefix: { * Returns an `IterableIterator` of the values within the `Trie` * that have `prefix` as prefix (`prefix` included if it exists). * - * @example + * **Example** (Finding values with a prefix) + * * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -426,17 +445,18 @@ export const keysWithPrefix: { * assert.deepStrictEqual(result, [0, 1]) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export const valuesWithPrefix: { /** * Returns an `IterableIterator` of the values within the `Trie` * that have `prefix` as prefix (`prefix` included if it exists). * - * @example + * **Example** (Finding values with a prefix) + * * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -452,17 +472,18 @@ export const valuesWithPrefix: { * assert.deepStrictEqual(result, [0, 1]) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ (prefix: string): (self: Trie) => IterableIterator /** * Returns an `IterableIterator` of the values within the `Trie` * that have `prefix` as prefix (`prefix` included if it exists). * - * @example + * **Example** (Finding values with a prefix) + * * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -478,8 +499,8 @@ export const valuesWithPrefix: { * assert.deepStrictEqual(result, [0, 1]) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ (self: Trie, prefix: string): IterableIterator } = TR.valuesWithPrefix @@ -488,9 +509,10 @@ export const valuesWithPrefix: { * Returns an `IterableIterator` of the entries within the `Trie` * that have `prefix` as prefix (`prefix` included if it exists). * - * @example + * **Example** (Finding entries with a prefix) + * * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -504,17 +526,18 @@ export const valuesWithPrefix: { * assert.deepStrictEqual(result, [["she", 0], ["shells", 1]]) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export const entriesWithPrefix: { /** * Returns an `IterableIterator` of the entries within the `Trie` * that have `prefix` as prefix (`prefix` included if it exists). * - * @example + * **Example** (Finding entries with a prefix) + * * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -528,17 +551,18 @@ export const entriesWithPrefix: { * assert.deepStrictEqual(result, [["she", 0], ["shells", 1]]) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ (prefix: string): (self: Trie) => IterableIterator<[string, V]> /** * Returns an `IterableIterator` of the entries within the `Trie` * that have `prefix` as prefix (`prefix` included if it exists). * - * @example + * **Example** (Finding entries with a prefix) + * * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -552,19 +576,20 @@ export const entriesWithPrefix: { * assert.deepStrictEqual(result, [["she", 0], ["shells", 1]]) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ (self: Trie, prefix: string): IterableIterator<[string, V]> } = TR.entriesWithPrefix /** - * Returns `Array<[K, V]>` of the entries within the `Trie` - * that have `prefix` as prefix (`prefix` included if it exists). + * Returns an `Array<[string, V]>` of the entries within the `Trie` whose keys + * start with `prefix`, including the entry for `prefix` itself when it exists. + * + * **Example** (Converting prefixed entries to an array) * - * @example * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -578,17 +603,18 @@ export const entriesWithPrefix: { * assert.deepStrictEqual(result, [["she", 3], ["shells", 0]]) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export const toEntriesWithPrefix: { /** - * Returns `Array<[K, V]>` of the entries within the `Trie` - * that have `prefix` as prefix (`prefix` included if it exists). + * Returns an `Array<[string, V]>` of the entries within the `Trie` whose keys + * start with `prefix`, including the entry for `prefix` itself when it exists. + * + * **Example** (Converting prefixed entries to an array) * - * @example * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -602,17 +628,18 @@ export const toEntriesWithPrefix: { * assert.deepStrictEqual(result, [["she", 3], ["shells", 0]]) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ (prefix: string): (self: Trie) => Array<[string, V]> /** - * Returns `Array<[K, V]>` of the entries within the `Trie` - * that have `prefix` as prefix (`prefix` included if it exists). + * Returns an `Array<[string, V]>` of the entries within the `Trie` whose keys + * start with `prefix`, including the entry for `prefix` itself when it exists. + * + * **Example** (Converting prefixed entries to an array) * - * @example * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -626,8 +653,8 @@ export const toEntriesWithPrefix: { * assert.deepStrictEqual(result, [["she", 3], ["shells", 0]]) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ (self: Trie, prefix: string): Array<[string, V]> } = TR.toEntriesWithPrefix @@ -636,9 +663,10 @@ export const toEntriesWithPrefix: { * Returns the longest key/value in the `Trie` * that is a prefix of that `key` if it exists, `None` otherwise. * - * @example + * **Example** (Finding the longest prefix) + * * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -657,17 +685,18 @@ export const toEntriesWithPrefix: { * } * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export const longestPrefixOf: { /** * Returns the longest key/value in the `Trie` * that is a prefix of that `key` if it exists, `None` otherwise. * - * @example + * **Example** (Finding the longest prefix) + * * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -686,17 +715,18 @@ export const longestPrefixOf: { * } * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ (key: string): (self: Trie) => Option<[string, V]> /** * Returns the longest key/value in the `Trie` * that is a prefix of that `key` if it exists, `None` otherwise. * - * @example + * **Example** (Finding the longest prefix) + * * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -715,8 +745,8 @@ export const longestPrefixOf: { * } * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ (self: Trie, key: string): Option<[string, V]> } = TR.longestPrefixOf @@ -724,9 +754,10 @@ export const longestPrefixOf: { /** * Returns the size of the `Trie` (number of entries in the `Trie`). * - * @example + * **Example** (Getting the size) + * * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -737,18 +768,18 @@ export const longestPrefixOf: { * assert.equal(Trie.size(trie), 2) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export const size: (self: Trie) => number = TR.size /** - * Safely lookup the value for the specified key in the `Trie`. + * Looks up the value for the specified key in the `Trie` safely. + * + * **Example** (Looking up values safely) * - * @example * ```ts - * import * as Option from "effect/Option" - * import * as Trie from "effect/Trie" + * import { Option, Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -768,17 +799,17 @@ export const size: (self: Trie) => number = TR.size * assert.deepStrictEqual(Trie.get(trie, "mea"), Option.none()) * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ export const get: { /** - * Safely lookup the value for the specified key in the `Trie`. + * Looks up the value for the specified key in the `Trie` safely. + * + * **Example** (Looking up values safely) * - * @example * ```ts - * import * as Option from "effect/Option" - * import * as Trie from "effect/Trie" + * import { Option, Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -798,17 +829,17 @@ export const get: { * assert.deepStrictEqual(Trie.get(trie, "mea"), Option.none()) * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (key: string): (self: Trie) => Option /** - * Safely lookup the value for the specified key in the `Trie`. + * Looks up the value for the specified key in the `Trie` safely. + * + * **Example** (Looking up values safely) * - * @example * ```ts - * import * as Option from "effect/Option" - * import * as Trie from "effect/Trie" + * import { Option, Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -828,18 +859,19 @@ export const get: { * assert.deepStrictEqual(Trie.get(trie, "mea"), Option.none()) * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (self: Trie, key: string): Option } = TR.get /** - * Check if the given key exists in the `Trie`. + * Checks whether the given key exists in the `Trie`. + * + * **Example** (Checking key membership) * - * @example * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -859,16 +891,17 @@ export const get: { * assert.equal(Trie.has(trie, "mea"), false) * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ export const has: { /** - * Check if the given key exists in the `Trie`. + * Checks whether the given key exists in the `Trie`. + * + * **Example** (Checking key membership) * - * @example * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -888,16 +921,17 @@ export const has: { * assert.equal(Trie.has(trie, "mea"), false) * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (key: string): (self: Trie) => boolean /** - * Check if the given key exists in the `Trie`. + * Checks whether the given key exists in the `Trie`. + * + * **Example** (Checking key membership) * - * @example * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -917,18 +951,19 @@ export const has: { * assert.equal(Trie.has(trie, "mea"), false) * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (self: Trie, key: string): boolean } = TR.has /** - * Checks if the `Trie` contains any entries. + * Returns `true` when the `Trie` contains no entries. + * + * **Example** (Checking whether a trie is empty) * - * @example * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty() @@ -938,20 +973,28 @@ export const has: { * assert.equal(Trie.isEmpty(trie1), false) * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ export const isEmpty: (self: Trie) => boolean = TR.isEmpty /** - * Unsafely lookup the value for the specified key in the `Trie`. + * Looks up the value for the specified key in the `Trie` unsafely. + * + * **When to use** + * + * Use when the trie key is known to exist and a missing key should be treated + * as a programming error. + * + * **Gotchas** * - * `getUnsafe` will throw if the key is not found. Use `get` instead to safely - * get a value from the `Trie`. + * `getUnsafe` throws if the key is not found. Use `get` instead to safely get + * a value from the `Trie`. + * + * **Example** (Looking up values unsafely) * - * @example * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -962,19 +1005,27 @@ export const isEmpty: (self: Trie) => boolean = TR.isEmpty * assert.throws(() => Trie.getUnsafe(trie, "mae")) * ``` * - * @since 2.0.0 * @category unsafe + * @since 4.0.0 */ export const getUnsafe: { /** - * Unsafely lookup the value for the specified key in the `Trie`. + * Looks up the value for the specified key in the `Trie` unsafely. + * + * **When to use** + * + * Use when the trie key is known to exist and a missing key should be treated + * as a programming error. * - * `getUnsafe` will throw if the key is not found. Use `get` instead to safely - * get a value from the `Trie`. + * **Gotchas** + * + * `getUnsafe` throws if the key is not found. Use `get` instead to safely get + * a value from the `Trie`. + * + * **Example** (Looking up values unsafely) * - * @example * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -985,19 +1036,27 @@ export const getUnsafe: { * assert.throws(() => Trie.getUnsafe(trie, "mae")) * ``` * - * @since 2.0.0 * @category unsafe + * @since 4.0.0 */ (key: string): (self: Trie) => V /** - * Unsafely lookup the value for the specified key in the `Trie`. + * Looks up the value for the specified key in the `Trie` unsafely. * - * `getUnsafe` will throw if the key is not found. Use `get` instead to safely - * get a value from the `Trie`. + * **When to use** + * + * Use when the trie key is known to exist and a missing key should be treated + * as a programming error. + * + * **Gotchas** + * + * `getUnsafe` throws if the key is not found. Use `get` instead to safely get + * a value from the `Trie`. + * + * **Example** (Looking up values unsafely) * - * @example * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -1008,19 +1067,19 @@ export const getUnsafe: { * assert.throws(() => Trie.getUnsafe(trie, "mae")) * ``` * - * @since 2.0.0 * @category unsafe + * @since 4.0.0 */ (self: Trie, key: string): V } = TR.getUnsafe /** - * Remove the entry for the specified key in the `Trie`. + * Removes the entry for the specified key in the `Trie`. + * + * **Example** (Removing entries) * - * @example * ```ts - * import * as Option from "effect/Option" - * import * as Trie from "effect/Trie" + * import { Option, Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -1038,17 +1097,17 @@ export const getUnsafe: { * assert.deepStrictEqual(Trie.get(trie2, "call"), Option.none()) * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ export const remove: { /** - * Remove the entry for the specified key in the `Trie`. + * Removes the entry for the specified key in the `Trie`. + * + * **Example** (Removing entries) * - * @example * ```ts - * import * as Option from "effect/Option" - * import * as Trie from "effect/Trie" + * import { Option, Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -1066,17 +1125,17 @@ export const remove: { * assert.deepStrictEqual(Trie.get(trie2, "call"), Option.none()) * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ (key: string): (self: Trie) => Trie /** - * Remove the entry for the specified key in the `Trie`. + * Removes the entry for the specified key in the `Trie`. + * + * **Example** (Removing entries) * - * @example * ```ts - * import * as Option from "effect/Option" - * import * as Trie from "effect/Trie" + * import { Option, Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -1094,18 +1153,19 @@ export const remove: { * assert.deepStrictEqual(Trie.get(trie2, "call"), Option.none()) * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ (self: Trie, key: string): Trie } = TR.remove /** - * Reduce a state over the entries of the `Trie`. + * Reduces a state over the entries of the `Trie`. + * + * **Example** (Reducing entries) * - * @example * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -1134,16 +1194,17 @@ export const remove: { * ) * ``` * - * @since 2.0.0 * @category folding + * @since 2.0.0 */ export const reduce: { /** - * Reduce a state over the entries of the `Trie`. + * Reduces a state over the entries of the `Trie`. + * + * **Example** (Reducing entries) * - * @example * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -1172,16 +1233,17 @@ export const reduce: { * ) * ``` * - * @since 2.0.0 * @category folding + * @since 2.0.0 */ (zero: Z, f: (accumulator: Z, value: V, key: string) => Z): (self: Trie) => Z /** - * Reduce a state over the entries of the `Trie`. + * Reduces a state over the entries of the `Trie`. + * + * **Example** (Reducing entries) * - * @example * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -1210,8 +1272,8 @@ export const reduce: { * ) * ``` * - * @since 2.0.0 * @category folding + * @since 2.0.0 */ (self: Trie, zero: Z, f: (accumulator: Z, value: V, key: string) => Z): Z } = TR.reduce @@ -1219,10 +1281,10 @@ export const reduce: { /** * Maps over the entries of the `Trie` using the specified function. * - * @example + * **Example** (Mapping entries) + * * ```ts - * import * as Equal from "effect/Equal" - * import * as Trie from "effect/Trie" + * import { Equal, Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -1247,17 +1309,17 @@ export const reduce: { * assert.equal(Equal.equals(Trie.map(trie, (_, k) => k.length), trieMapK), true) * ``` * - * @since 2.0.0 * @category folding + * @since 2.0.0 */ export const map: { /** * Maps over the entries of the `Trie` using the specified function. * - * @example + * **Example** (Mapping entries) + * * ```ts - * import * as Equal from "effect/Equal" - * import * as Trie from "effect/Trie" + * import { Equal, Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -1282,17 +1344,17 @@ export const map: { * assert.equal(Equal.equals(Trie.map(trie, (_, k) => k.length), trieMapK), true) * ``` * - * @since 2.0.0 * @category folding + * @since 2.0.0 */ (f: (value: V, key: string) => A): (self: Trie) => Trie /** * Maps over the entries of the `Trie` using the specified function. * - * @example + * **Example** (Mapping entries) + * * ```ts - * import * as Equal from "effect/Equal" - * import * as Trie from "effect/Trie" + * import { Equal, Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -1317,8 +1379,8 @@ export const map: { * assert.equal(Equal.equals(Trie.map(trie, (_, k) => k.length), trieMapK), true) * ``` * - * @since 2.0.0 * @category folding + * @since 2.0.0 */ (self: Trie, f: (value: V, key: string) => A): Trie } = TR.map @@ -1326,10 +1388,10 @@ export const map: { /** * Filters entries out of a `Trie` using the specified predicate. * - * @example + * **Example** (Filtering entries) + * * ```ts - * import * as Equal from "effect/Equal" - * import * as Trie from "effect/Trie" + * import { Equal, Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -1354,17 +1416,17 @@ export const map: { * ) * ``` * - * @since 2.0.0 * @category filtering + * @since 2.0.0 */ export const filter: { /** * Filters entries out of a `Trie` using the specified predicate. * - * @example + * **Example** (Filtering entries) + * * ```ts - * import * as Equal from "effect/Equal" - * import * as Trie from "effect/Trie" + * import { Equal, Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -1389,17 +1451,17 @@ export const filter: { * ) * ``` * - * @since 2.0.0 * @category filtering + * @since 2.0.0 */ (f: (a: NoInfer, k: string) => a is B): (self: Trie) => Trie /** * Filters entries out of a `Trie` using the specified predicate. * - * @example + * **Example** (Filtering entries) + * * ```ts - * import * as Equal from "effect/Equal" - * import * as Trie from "effect/Trie" + * import { Equal, Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -1424,17 +1486,17 @@ export const filter: { * ) * ``` * - * @since 2.0.0 * @category filtering + * @since 2.0.0 */ (f: (a: NoInfer, k: string) => boolean): (self: Trie) => Trie /** * Filters entries out of a `Trie` using the specified predicate. * - * @example + * **Example** (Filtering entries) + * * ```ts - * import * as Equal from "effect/Equal" - * import * as Trie from "effect/Trie" + * import { Equal, Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -1459,17 +1521,17 @@ export const filter: { * ) * ``` * - * @since 2.0.0 * @category filtering + * @since 2.0.0 */ (self: Trie, f: (a: A, k: string) => a is B): Trie /** * Filters entries out of a `Trie` using the specified predicate. * - * @example + * **Example** (Filtering entries) + * * ```ts - * import * as Equal from "effect/Equal" - * import * as Trie from "effect/Trie" + * import { Equal, Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -1494,8 +1556,8 @@ export const filter: { * ) * ``` * - * @since 2.0.0 * @category filtering + * @since 2.0.0 */ (self: Trie, f: (a: A, k: string) => boolean): Trie } = TR.filter @@ -1504,11 +1566,10 @@ export const filter: { * Maps over the entries of the `Trie` using the specified filter and keeps * only successful results. * - * @example + * **Example** (Filtering and mapping entries) + * * ```ts - * import * as Equal from "effect/Equal" - * import * as Result from "effect/Result" - * import * as Trie from "effect/Trie" + * import { Equal, Result, Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -1545,19 +1606,18 @@ export const filter: { * ) * ``` * - * @since 2.0.0 * @category filtering + * @since 2.0.0 */ export const filterMap: { /** * Maps over the entries of the `Trie` using the specified filter and keeps * only successful results. * - * @example + * **Example** (Filtering and mapping entries) + * * ```ts - * import * as Equal from "effect/Equal" - * import * as Result from "effect/Result" - * import * as Trie from "effect/Trie" + * import { Equal, Result, Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -1594,19 +1654,18 @@ export const filterMap: { * ) * ``` * - * @since 2.0.0 * @category filtering + * @since 2.0.0 */ (f: (input: A, key: string) => Result): (self: Trie) => Trie /** * Maps over the entries of the `Trie` using the specified filter and keeps * only successful results. * - * @example + * **Example** (Filtering and mapping entries) + * * ```ts - * import * as Equal from "effect/Equal" - * import * as Result from "effect/Result" - * import * as Trie from "effect/Trie" + * import { Equal, Result, Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -1643,8 +1702,8 @@ export const filterMap: { * ) * ``` * - * @since 2.0.0 * @category filtering + * @since 2.0.0 */ (self: Trie, f: (input: A, key: string) => Result): Trie } = TR.filterMap @@ -1652,11 +1711,10 @@ export const filterMap: { /** * Filters out `None` values from a `Trie` of `Options`s. * - * @example + * **Example** (Compacting optional values) + * * ```ts - * import * as Equal from "effect/Equal" - * import * as Option from "effect/Option" - * import * as Trie from "effect/Trie" + * import { Equal, Option, Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty>().pipe( @@ -1673,17 +1731,18 @@ export const filterMap: { * assert.equal(Equal.equals(Trie.compact(trie), trieMapV), true) * ``` * - * @since 2.0.0 * @category filtering + * @since 2.0.0 */ export const compact: (self: Trie>) => Trie = TR.compact /** * Applies the specified function to the entries of the `Trie`. * - * @example + * **Example** (Iterating over entries) + * * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * let value = 0 @@ -1700,16 +1759,17 @@ export const compact: (self: Trie>) => Trie = TR.compact * assert.equal(value, 17) * ``` * - * @since 2.0.0 * @category traversing + * @since 2.0.0 */ export const forEach: { /** * Applies the specified function to the entries of the `Trie`. * - * @example + * **Example** (Iterating over entries) + * * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * let value = 0 @@ -1726,16 +1786,17 @@ export const forEach: { * assert.equal(value, 17) * ``` * - * @since 2.0.0 * @category traversing + * @since 2.0.0 */ (f: (value: V, key: string) => void): (self: Trie) => void /** * Applies the specified function to the entries of the `Trie`. * - * @example + * **Example** (Iterating over entries) + * * ```ts - * import * as Trie from "effect/Trie" + * import { Trie } from "effect" * import * as assert from "node:assert" * * let value = 0 @@ -1752,8 +1813,8 @@ export const forEach: { * assert.equal(value, 17) * ``` * - * @since 2.0.0 * @category traversing + * @since 2.0.0 */ (self: Trie, f: (value: V, key: string) => void): void } = TR.forEach @@ -1761,11 +1822,10 @@ export const forEach: { /** * Updates the value of the specified key within the `Trie` if it exists. * - * @example + * **Example** (Modifying an existing value) + * * ```ts - * import * as Equal from "effect/Equal" - * import * as Option from "effect/Option" - * import * as Trie from "effect/Trie" + * import { Equal, Option, Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -1782,18 +1842,17 @@ export const forEach: { * assert.equal(Equal.equals(trie.pipe(Trie.modify("me", (v) => v)), trie), true) * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ export const modify: { /** * Updates the value of the specified key within the `Trie` if it exists. * - * @example + * **Example** (Modifying an existing value) + * * ```ts - * import * as Equal from "effect/Equal" - * import * as Option from "effect/Option" - * import * as Trie from "effect/Trie" + * import { Equal, Option, Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -1810,18 +1869,17 @@ export const modify: { * assert.equal(Equal.equals(trie.pipe(Trie.modify("me", (v) => v)), trie), true) * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ (key: string, f: (v: V) => V): (self: Trie) => Trie /** * Updates the value of the specified key within the `Trie` if it exists. * - * @example + * **Example** (Modifying an existing value) + * * ```ts - * import * as Equal from "effect/Equal" - * import * as Option from "effect/Option" - * import * as Trie from "effect/Trie" + * import { Equal, Option, Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -1838,8 +1896,8 @@ export const modify: { * assert.equal(Equal.equals(trie.pipe(Trie.modify("me", (v) => v)), trie), true) * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ (self: Trie, key: string, f: (v: V) => V): Trie } = TR.modify @@ -1847,10 +1905,10 @@ export const modify: { /** * Removes all entries in the `Trie` which have the specified keys. * - * @example + * **Example** (Removing multiple entries) + * * ```ts - * import * as Equal from "effect/Equal" - * import * as Trie from "effect/Trie" + * import { Equal, Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -1868,17 +1926,17 @@ export const modify: { * ) * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ export const removeMany: { /** * Removes all entries in the `Trie` which have the specified keys. * - * @example + * **Example** (Removing multiple entries) + * * ```ts - * import * as Equal from "effect/Equal" - * import * as Trie from "effect/Trie" + * import { Equal, Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -1896,17 +1954,17 @@ export const removeMany: { * ) * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ (keys: Iterable): (self: Trie) => Trie /** * Removes all entries in the `Trie` which have the specified keys. * - * @example + * **Example** (Removing multiple entries) + * * ```ts - * import * as Equal from "effect/Equal" - * import * as Trie from "effect/Trie" + * import { Equal, Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -1924,19 +1982,19 @@ export const removeMany: { * ) * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ (self: Trie, keys: Iterable): Trie } = TR.removeMany /** - * Insert multiple entries in the `Trie` at once. + * Inserts multiple entries in the `Trie` at once. + * + * **Example** (Inserting multiple entries) * - * @example * ```ts - * import * as Equal from "effect/Equal" - * import * as Trie from "effect/Trie" + * import { Equal, Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -1958,17 +2016,17 @@ export const removeMany: { * ) * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ export const insertMany: { /** - * Insert multiple entries in the `Trie` at once. + * Inserts multiple entries in the `Trie` at once. + * + * **Example** (Inserting multiple entries) * - * @example * ```ts - * import * as Equal from "effect/Equal" - * import * as Trie from "effect/Trie" + * import { Equal, Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -1990,17 +2048,17 @@ export const insertMany: { * ) * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ (iter: Iterable<[string, V]>): (self: Trie) => Trie /** - * Insert multiple entries in the `Trie` at once. + * Inserts multiple entries in the `Trie` at once. + * + * **Example** (Inserting multiple entries) * - * @example * ```ts - * import * as Equal from "effect/Equal" - * import * as Trie from "effect/Trie" + * import { Equal, Trie } from "effect" * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( @@ -2022,8 +2080,8 @@ export const insertMany: { * ) * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ (self: Trie, iter: Iterable<[string, V]>): Trie } = TR.insertMany diff --git a/.opencode/node_modules/effect/src/Tuple.ts b/.opencode/node_modules/effect/src/Tuple.ts index 01a728be37a5115d43436e044009d97cdf72f4ce..3066fbc793e08825547e87a5ad5dba0146214e00 100644 --- a/.opencode/node_modules/effect/src/Tuple.ts +++ b/.opencode/node_modules/effect/src/Tuple.ts @@ -1,71 +1,12 @@ /** - * Utilities for creating, accessing, transforming, and comparing fixed-length - * arrays (tuples). Every function produces a new tuple — inputs are never - * mutated. - * - * ## Mental model - * - * - **Tuple**: A fixed-length readonly array where each position can have a - * different type (e.g., `readonly [string, number, boolean]`). - * - **Index-based access**: Elements are accessed by numeric index, and the - * type system tracks the type at each position. - * - **Dual API**: Most functions accept arguments in both data-first - * (`Tuple.get(t, 0)`) and data-last (`pipe(t, Tuple.get(0))`) style. - * - **Immutability**: All operations return a new tuple; the original is - * never modified. - * - **Lambda**: A type-level function interface (from {@link Struct}) used by - * {@link map}, {@link mapPick}, and {@link mapOmit} so the compiler can - * track how element types change. - * - * ## Common tasks - * - * - Create a tuple → {@link make} - * - Access an element by index → {@link get} - * - Select / remove elements by index → {@link pick}, {@link omit} - * - Append elements → {@link appendElement}, {@link appendElements} - * - Transform selected elements → {@link evolve} - * - Swap element positions → {@link renameIndices} - * - Map all elements with a typed lambda → {@link map}, {@link mapPick}, - * {@link mapOmit} - * - Compare tuples → {@link makeEquivalence}, {@link makeOrder} - * - Combine / reduce tuples → {@link makeCombiner}, {@link makeReducer} - * - Check tuple length at runtime → {@link isTupleOf}, - * {@link isTupleOfAtLeast} - * - * ## Gotchas - * - * - {@link pick} and {@link omit} use numeric indices, not string keys. - * - {@link renameIndices} takes an array of stringified source indices - * (e.g., `["2", "1", "0"]`), not arbitrary names. - * - {@link map}, {@link mapPick}, {@link mapOmit} require a Lambda value - * created with `Struct.lambda`; a plain function won't type-check. - * - {@link isTupleOf} and {@link isTupleOfAtLeast} only check length, not - * element types. - * - * ## Quickstart - * - * **Example** (Creating and transforming a tuple) + * Works with fixed-length arrays, also called tuples. * - * ```ts - * import { pipe, Tuple } from "effect" - * - * const point = Tuple.make(10, 20, "red") - * - * const result = pipe( - * point, - * Tuple.evolve([ - * (x) => x * 2, - * (y) => y * 2 - * ]) - * ) - * - * console.log(result) // [20, 40, "red"] - * ``` - * - * ## See also - * - * - {@link Struct} – similar utilities for objects with named keys - * - {@link Array} – operations on variable-length arrays + * The runtime helpers in this module create new tuples instead of mutating + * their inputs, and the types preserve element positions where possible. The + * helpers cover tuple construction, indexed access, selecting or removing + * positions, appending values, transforming elements, renaming indices, mapping + * typed positions, and deriving comparison or combination helpers for tuple + * shapes. * * @since 2.0.0 */ @@ -79,9 +20,15 @@ import type { Apply, Lambda } from "./Struct.ts" /** * Creates a tuple from the provided arguments. * - * - Use instead of `[a, b, c] as const` to get a properly typed tuple - * without a manual cast. - * - Returns the exact tuple type with each element's literal type preserved. + * **When to use** + * + * Use when you need a properly typed tuple without writing `[a, b, c] as const` + * or another manual cast. + * + * **Details** + * + * The returned value has the exact tuple type, with each element's literal type + * preserved. * * **Example** (Creating a tuple) * @@ -94,8 +41,7 @@ import type { Apply, Lambda } from "./Struct.ts" * * @see {@link get} – access a single element by index * @see {@link appendElement} – append an element to a tuple - * - * @category Constructors + * @category constructors * @since 2.0.0 */ export const make = >(...elements: Elements): Elements => elements @@ -105,9 +51,13 @@ type Indices> = Exclude["length"], T /** * Retrieves the element at the specified index from a tuple. * - * - Use in a pipeline when you need to extract a single element. - * - The index is constrained to valid tuple positions at the type level. - * - Does not mutate the input. + * **When to use** + * + * Use when a single tuple element should be extracted in a pipeline. + * + * **Details** + * + * The index is constrained to valid tuple positions at the type level. * * **Example** (Extracting an element by index) * @@ -120,17 +70,20 @@ type Indices> = Exclude["length"], T * * @see {@link make} – create a tuple * @see {@link pick} – extract multiple elements into a new tuple - * - * @category Getters + * @category getters * @since 4.0.0 */ export const get: { /** * Retrieves the element at the specified index from a tuple. * - * - Use in a pipeline when you need to extract a single element. - * - The index is constrained to valid tuple positions at the type level. - * - Does not mutate the input. + * **When to use** + * + * Use when a single tuple element should be extracted in a pipeline. + * + * **Details** + * + * The index is constrained to valid tuple positions at the type level. * * **Example** (Extracting an element by index) * @@ -143,17 +96,20 @@ export const get: { * * @see {@link make} – create a tuple * @see {@link pick} – extract multiple elements into a new tuple - * - * @category Getters + * @category getters * @since 4.0.0 */ , I extends Indices & keyof T>(index: I): (self: T) => T[I] /** * Retrieves the element at the specified index from a tuple. * - * - Use in a pipeline when you need to extract a single element. - * - The index is constrained to valid tuple positions at the type level. - * - Does not mutate the input. + * **When to use** + * + * Use when a single tuple element should be extracted in a pipeline. + * + * **Details** + * + * The index is constrained to valid tuple positions at the type level. * * **Example** (Extracting an element by index) * @@ -166,8 +122,7 @@ export const get: { * * @see {@link make} – create a tuple * @see {@link pick} – extract multiple elements into a new tuple - * - * @category Getters + * @category getters * @since 4.0.0 */ , I extends Indices & keyof T>(self: T, index: I): T[I] @@ -192,9 +147,13 @@ type PickTuple, K> = _BuildTuple /** * Creates a new tuple containing only the elements at the specified indices. * - * - Use to select a subset of elements from a tuple by position. - * - The result order matches the order of the provided indices. - * - Does not mutate the input; returns a fresh tuple. + * **When to use** + * + * Use to select a subset of elements from a tuple by position. + * + * **Details** + * + * The result order matches the order of the provided indices. * * **Example** (Selecting elements by index) * @@ -207,17 +166,20 @@ type PickTuple, K> = _BuildTuple * * @see {@link omit} – the inverse (exclude indices instead) * @see {@link get} – extract a single element - * - * @category Utilities + * @category filtering * @since 4.0.0 */ export const pick: { /** * Creates a new tuple containing only the elements at the specified indices. * - * - Use to select a subset of elements from a tuple by position. - * - The result order matches the order of the provided indices. - * - Does not mutate the input; returns a fresh tuple. + * **When to use** + * + * Use to select a subset of elements from a tuple by position. + * + * **Details** + * + * The result order matches the order of the provided indices. * * **Example** (Selecting elements by index) * @@ -230,17 +192,20 @@ export const pick: { * * @see {@link omit} – the inverse (exclude indices instead) * @see {@link get} – extract a single element - * - * @category Utilities + * @category filtering * @since 4.0.0 */ , const I extends ReadonlyArray>>(indices: I): (self: T) => PickTuple /** * Creates a new tuple containing only the elements at the specified indices. * - * - Use to select a subset of elements from a tuple by position. - * - The result order matches the order of the provided indices. - * - Does not mutate the input; returns a fresh tuple. + * **When to use** + * + * Use to select a subset of elements from a tuple by position. + * + * **Details** + * + * The result order matches the order of the provided indices. * * **Example** (Selecting elements by index) * @@ -253,8 +218,7 @@ export const pick: { * * @see {@link omit} – the inverse (exclude indices instead) * @see {@link get} – extract a single element - * - * @category Utilities + * @category filtering * @since 4.0.0 */ , const I extends ReadonlyArray>>(self: T, indices: I): PickTuple @@ -273,9 +237,13 @@ type OmitTuple, K> = _BuildTuple, K> = _BuildTuple, const I extends ReadonlyArray>>(indices: I): (self: T) => OmitTuple /** * Creates a new tuple with the elements at the specified indices removed. * - * - Use to drop elements from a tuple by position. - * - Elements not at the specified indices are kept in their original order. - * - Does not mutate the input; returns a fresh tuple. + * **When to use** + * + * Use to drop elements from a tuple by position. + * + * **Details** + * + * Elements not at the specified indices are kept in their original order. * * **Example** (Removing elements by index) * @@ -331,8 +305,7 @@ export const omit: { * ``` * * @see {@link pick} – the inverse (keep only specified indices) - * - * @category Utilities + * @category filtering * @since 4.0.0 */ , const I extends ReadonlyArray>>(self: T, indices: I): OmitTuple @@ -350,8 +323,14 @@ export const omit: { /** * Appends a single element to the end of a tuple. * - * - The result type is `[...T, E]`, preserving all existing element types. - * - Does not mutate the input; returns a fresh tuple. + * **When to use** + * + * Use when you need the appended value to remain part of the tuple's type-level + * shape and preserve literal element positions. + * + * **Details** + * + * The result type is `[...T, E]`, preserving all existing element types. * * **Example** (Appending an element) * @@ -363,16 +342,21 @@ export const omit: { * ``` * * @see {@link appendElements} – append multiple elements (another tuple) - * - * @category Concatenating + * @category combining * @since 2.0.0 */ export const appendElement: { /** * Appends a single element to the end of a tuple. * - * - The result type is `[...T, E]`, preserving all existing element types. - * - Does not mutate the input; returns a fresh tuple. + * **When to use** + * + * Use when you need the appended value to remain part of the tuple's type-level + * shape and preserve literal element positions. + * + * **Details** + * + * The result type is `[...T, E]`, preserving all existing element types. * * **Example** (Appending an element) * @@ -384,16 +368,21 @@ export const appendElement: { * ``` * * @see {@link appendElements} – append multiple elements (another tuple) - * - * @category Concatenating + * @category combining * @since 2.0.0 */ (element: E): >(self: T) => [...T, E] /** * Appends a single element to the end of a tuple. * - * - The result type is `[...T, E]`, preserving all existing element types. - * - Does not mutate the input; returns a fresh tuple. + * **When to use** + * + * Use when you need the appended value to remain part of the tuple's type-level + * shape and preserve literal element positions. + * + * **Details** + * + * The result type is `[...T, E]`, preserving all existing element types. * * **Example** (Appending an element) * @@ -405,8 +394,7 @@ export const appendElement: { * ``` * * @see {@link appendElements} – append multiple elements (another tuple) - * - * @category Concatenating + * @category combining * @since 2.0.0 */ , const E>(self: T, element: E): [...T, E] @@ -415,9 +403,14 @@ export const appendElement: { /** * Concatenates two tuples into a single tuple. * - * - The result type is `[...T1, ...T2]`, preserving all element types from - * both tuples. - * - Does not mutate either input; returns a fresh tuple. + * **When to use** + * + * Use to append all elements from one tuple to another tuple. + * + * **Details** + * + * The result type is `[...T1, ...T2]`, preserving all element types from both + * tuples. Neither input tuple is mutated; a fresh tuple is returned. * * **Example** (Concatenating tuples) * @@ -429,17 +422,21 @@ export const appendElement: { * ``` * * @see {@link appendElement} – append a single element - * - * @category Concatenating - * @since 2.0.0 + * @category combining + * @since 4.0.0 */ export const appendElements: { /** * Concatenates two tuples into a single tuple. * - * - The result type is `[...T1, ...T2]`, preserving all element types from - * both tuples. - * - Does not mutate either input; returns a fresh tuple. + * **When to use** + * + * Use to append all elements from one tuple to another tuple. + * + * **Details** + * + * The result type is `[...T1, ...T2]`, preserving all element types from both + * tuples. Neither input tuple is mutated; a fresh tuple is returned. * * **Example** (Concatenating tuples) * @@ -451,17 +448,21 @@ export const appendElements: { * ``` * * @see {@link appendElement} – append a single element - * - * @category Concatenating - * @since 2.0.0 + * @category combining + * @since 4.0.0 */ >(that: T2): >(self: T1) => [...T1, ...T2] /** * Concatenates two tuples into a single tuple. * - * - The result type is `[...T1, ...T2]`, preserving all element types from - * both tuples. - * - Does not mutate either input; returns a fresh tuple. + * **When to use** + * + * Use to append all elements from one tuple to another tuple. + * + * **Details** + * + * The result type is `[...T1, ...T2]`, preserving all element types from both + * tuples. Neither input tuple is mutated; a fresh tuple is returned. * * **Example** (Concatenating tuples) * @@ -473,9 +474,8 @@ export const appendElements: { * ``` * * @see {@link appendElement} – append a single element - * - * @category Concatenating - * @since 2.0.0 + * @category combining + * @since 4.0.0 */ , const T2 extends ReadonlyArray>(self: T1, that: T2): [...T1, ...T2] } = dual( @@ -495,10 +495,14 @@ type Evolved = { [I in keyof T]: I extends keyof E ? (E[I] extends (...a: * Each function applies to the element at the same position. Positions beyond * the array's length are copied unchanged. * - * - Use when you want to update the first N elements while keeping the rest. - * - Does not mutate the input; returns a fresh tuple. - * - Each transform function receives the current value and can return a - * different type. + * **When to use** + * + * Use when you want to update the first N elements while keeping the rest. + * + * **Details** + * + * Each transform function receives the current value and can return a different + * type. * * **Example** (Transforming selected elements) * @@ -517,8 +521,7 @@ type Evolved = { [I in keyof T]: I extends keyof E ? (E[I] extends (...a: * * @see {@link map} – apply the same transformation to all elements * @see {@link renameIndices} – swap element positions - * - * @category Mapping + * @category mapping * @since 4.0.0 */ export const evolve: { @@ -527,10 +530,14 @@ export const evolve: { * Each function applies to the element at the same position. Positions beyond * the array's length are copied unchanged. * - * - Use when you want to update the first N elements while keeping the rest. - * - Does not mutate the input; returns a fresh tuple. - * - Each transform function receives the current value and can return a - * different type. + * **When to use** + * + * Use when you want to update the first N elements while keeping the rest. + * + * **Details** + * + * Each transform function receives the current value and can return a different + * type. * * **Example** (Transforming selected elements) * @@ -549,8 +556,7 @@ export const evolve: { * * @see {@link map} – apply the same transformation to all elements * @see {@link renameIndices} – swap element positions - * - * @category Mapping + * @category mapping * @since 4.0.0 */ , const E extends Evolver>(evolver: E): (self: T) => Evolved @@ -559,10 +565,14 @@ export const evolve: { * Each function applies to the element at the same position. Positions beyond * the array's length are copied unchanged. * - * - Use when you want to update the first N elements while keeping the rest. - * - Does not mutate the input; returns a fresh tuple. - * - Each transform function receives the current value and can return a - * different type. + * **When to use** + * + * Use when you want to update the first N elements while keeping the rest. + * + * **Details** + * + * Each transform function receives the current value and can return a different + * type. * * **Example** (Transforming selected elements) * @@ -581,8 +591,7 @@ export const evolve: { * * @see {@link map} – apply the same transformation to all elements * @see {@link renameIndices} – swap element positions - * - * @category Mapping + * @category mapping * @since 4.0.0 */ , const E extends Evolver>(self: T, evolver: E): Evolved @@ -594,11 +603,21 @@ export const evolve: { ) /** - * Rearranges elements of a tuple by providing an array of stringified source + * Renames tuple indices by providing an array of stringified source * indices. Each position in the array specifies which index to read from * (e.g., `["2", "1", "0"]` reverses a 3-element tuple). * - * - Does not mutate the input; returns a fresh tuple. + * **When to use** + * + * Use to reorder tuple elements while preserving index-specific types. + * + * **Details** + * + * The mapping returns a tuple in the requested index order. + * + * **Gotchas** + * + * The mapping uses stringified source indices, not arbitrary names. * * **Example** (Swapping elements) * @@ -613,17 +632,26 @@ export const evolve: { * ``` * * @see {@link evolve} – transform element values instead of positions - * * @category Index utilities * @since 4.0.0 */ export const renameIndices: { /** - * Rearranges elements of a tuple by providing an array of stringified source + * Renames tuple indices by providing an array of stringified source * indices. Each position in the array specifies which index to read from * (e.g., `["2", "1", "0"]` reverses a 3-element tuple). * - * - Does not mutate the input; returns a fresh tuple. + * **When to use** + * + * Use to reorder tuple elements while preserving index-specific types. + * + * **Details** + * + * The mapping returns a tuple in the requested index order. + * + * **Gotchas** + * + * The mapping uses stringified source indices, not arbitrary names. * * **Example** (Swapping elements) * @@ -638,17 +666,26 @@ export const renameIndices: { * ``` * * @see {@link evolve} – transform element values instead of positions - * * @category Index utilities * @since 4.0.0 */ , const M extends { readonly [I in keyof T]?: `${keyof T & string}` }>(mapping: M): (self: T) => { [I in keyof T]: I extends keyof M ? M[I] extends keyof T ? T[M[I]] : T[I] : T[I] } /** - * Rearranges elements of a tuple by providing an array of stringified source + * Renames tuple indices by providing an array of stringified source * indices. Each position in the array specifies which index to read from * (e.g., `["2", "1", "0"]` reverses a 3-element tuple). * - * - Does not mutate the input; returns a fresh tuple. + * **When to use** + * + * Use to reorder tuple elements while preserving index-specific types. + * + * **Details** + * + * The mapping returns a tuple in the requested index order. + * + * **Gotchas** + * + * The mapping uses stringified source indices, not arbitrary names. * * **Example** (Swapping elements) * @@ -663,7 +700,6 @@ export const renameIndices: { * ``` * * @see {@link evolve} – transform element values instead of positions - * * @category Index utilities * @since 4.0.0 */ @@ -681,10 +717,18 @@ export const renameIndices: { /** * Applies a `Struct.Lambda` transformation to every element in a tuple. * - * - Use when you want to apply the same function to every element. - * - The lambda must be created with `Struct.lambda` so the compiler can - * track the output types per element. - * - Does not mutate the input; returns a fresh tuple. + * **When to use** + * + * Use when you want to apply the same transformation to every tuple element. + * + * **Details** + * + * The lambda lets the compiler track the output type for each element. + * + * **Gotchas** + * + * The lambda must be created with `Struct.lambda`; a plain function will not + * type-check. * * **Example** (Wrapping every element in an array) * @@ -704,18 +748,25 @@ export const renameIndices: { * @see {@link mapPick} – apply a lambda only to selected indices * @see {@link mapOmit} – apply a lambda to all indices except selected ones * @see {@link evolve} – apply different functions to different indices - * - * @category Mapping - * @since 4.0.0 + * @category mapping + * @since 3.9.0 */ export const map: { /** * Applies a `Struct.Lambda` transformation to every element in a tuple. * - * - Use when you want to apply the same function to every element. - * - The lambda must be created with `Struct.lambda` so the compiler can - * track the output types per element. - * - Does not mutate the input; returns a fresh tuple. + * **When to use** + * + * Use when you want to apply the same transformation to every tuple element. + * + * **Details** + * + * The lambda lets the compiler track the output type for each element. + * + * **Gotchas** + * + * The lambda must be created with `Struct.lambda`; a plain function will not + * type-check. * * **Example** (Wrapping every element in an array) * @@ -735,9 +786,8 @@ export const map: { * @see {@link mapPick} – apply a lambda only to selected indices * @see {@link mapOmit} – apply a lambda to all indices except selected ones * @see {@link evolve} – apply different functions to different indices - * - * @category Mapping - * @since 4.0.0 + * @category mapping + * @since 3.9.0 */ (lambda: L): >( self: T @@ -745,10 +795,18 @@ export const map: { /** * Applies a `Struct.Lambda` transformation to every element in a tuple. * - * - Use when you want to apply the same function to every element. - * - The lambda must be created with `Struct.lambda` so the compiler can - * track the output types per element. - * - Does not mutate the input; returns a fresh tuple. + * **When to use** + * + * Use when you want to apply the same transformation to every tuple element. + * + * **Details** + * + * The lambda lets the compiler track the output type for each element. + * + * **Gotchas** + * + * The lambda must be created with `Struct.lambda`; a plain function will not + * type-check. * * **Example** (Wrapping every element in an array) * @@ -768,9 +826,8 @@ export const map: { * @see {@link mapPick} – apply a lambda only to selected indices * @see {@link mapOmit} – apply a lambda to all indices except selected ones * @see {@link evolve} – apply different functions to different indices - * - * @category Mapping - * @since 4.0.0 + * @category mapping + * @since 3.9.0 */ , L extends Lambda>(self: T, lambda: L): { [K in keyof T]: Apply } } = dual( @@ -784,9 +841,10 @@ export const map: { * Applies a `Struct.Lambda` transformation only to the elements at the * specified indices; all other elements are copied unchanged. * - * - Use when you want to apply the same transformation to a subset of - * positions. - * - Does not mutate the input; returns a fresh tuple. + * **When to use** + * + * Use when you want to apply the same transformation to a subset of + * positions. * * **Example** (Wrapping only selected elements in arrays) * @@ -808,8 +866,7 @@ export const map: { * * @see {@link map} – apply a lambda to all elements * @see {@link mapOmit} – apply a lambda to all elements except selected ones - * - * @category Mapping + * @category mapping * @since 4.0.0 */ export const mapPick: { @@ -817,9 +874,10 @@ export const mapPick: { * Applies a `Struct.Lambda` transformation only to the elements at the * specified indices; all other elements are copied unchanged. * - * - Use when you want to apply the same transformation to a subset of - * positions. - * - Does not mutate the input; returns a fresh tuple. + * **When to use** + * + * Use when you want to apply the same transformation to a subset of + * positions. * * **Example** (Wrapping only selected elements in arrays) * @@ -841,8 +899,7 @@ export const mapPick: { * * @see {@link map} – apply a lambda to all elements * @see {@link mapOmit} – apply a lambda to all elements except selected ones - * - * @category Mapping + * @category mapping * @since 4.0.0 */ , const I extends ReadonlyArray>, L extends Lambda>(indices: I, lambda: L): ( @@ -852,9 +909,10 @@ export const mapPick: { * Applies a `Struct.Lambda` transformation only to the elements at the * specified indices; all other elements are copied unchanged. * - * - Use when you want to apply the same transformation to a subset of - * positions. - * - Does not mutate the input; returns a fresh tuple. + * **When to use** + * + * Use when you want to apply the same transformation to a subset of + * positions. * * **Example** (Wrapping only selected elements in arrays) * @@ -876,8 +934,7 @@ export const mapPick: { * * @see {@link map} – apply a lambda to all elements * @see {@link mapOmit} – apply a lambda to all elements except selected ones - * - * @category Mapping + * @category mapping * @since 4.0.0 */ , const I extends ReadonlyArray>, L extends Lambda>(self: T, indices: I, lambda: L): { [K in keyof T]: K extends `${I[number]}` ? Apply : T[K] } @@ -897,9 +954,10 @@ export const mapPick: { * Applies a `Struct.Lambda` transformation to all elements except those at the * specified indices; the excluded elements are copied unchanged. * - * - Use when most elements should be transformed but a few should be - * preserved. - * - Does not mutate the input; returns a fresh tuple. + * **When to use** + * + * Use when most elements should be transformed but a few should be + * preserved. * * **Example** (Wrapping all elements except one in arrays) * @@ -921,8 +979,7 @@ export const mapPick: { * * @see {@link map} – apply a lambda to all elements * @see {@link mapPick} – apply a lambda only to selected indices - * - * @category Mapping + * @category mapping * @since 4.0.0 */ export const mapOmit: { @@ -930,9 +987,10 @@ export const mapOmit: { * Applies a `Struct.Lambda` transformation to all elements except those at the * specified indices; the excluded elements are copied unchanged. * - * - Use when most elements should be transformed but a few should be - * preserved. - * - Does not mutate the input; returns a fresh tuple. + * **When to use** + * + * Use when most elements should be transformed but a few should be + * preserved. * * **Example** (Wrapping all elements except one in arrays) * @@ -954,8 +1012,7 @@ export const mapOmit: { * * @see {@link map} – apply a lambda to all elements * @see {@link mapPick} – apply a lambda only to selected indices - * - * @category Mapping + * @category mapping * @since 4.0.0 */ , const I extends ReadonlyArray>, L extends Lambda>(indices: I, lambda: L): ( @@ -965,9 +1022,10 @@ export const mapOmit: { * Applies a `Struct.Lambda` transformation to all elements except those at the * specified indices; the excluded elements are copied unchanged. * - * - Use when most elements should be transformed but a few should be - * preserved. - * - Does not mutate the input; returns a fresh tuple. + * **When to use** + * + * Use when most elements should be transformed but a few should be + * preserved. * * **Example** (Wrapping all elements except one in arrays) * @@ -989,8 +1047,7 @@ export const mapOmit: { * * @see {@link map} – apply a lambda to all elements * @see {@link mapPick} – apply a lambda only to selected indices - * - * @category Mapping + * @category mapping * @since 4.0.0 */ , const I extends ReadonlyArray>, L extends Lambda>(self: T, indices: I, lambda: L): { [K in keyof T]: K extends `${I[number]}` ? T[K] : Apply } @@ -1011,9 +1068,13 @@ export const mapOmit: { * using the provided per-position `Equivalence`s. Two tuples are equivalent * when all their corresponding elements are equivalent. * - * Alias of `Equivalence.Tuple`. + * **When to use** + * + * Use when you need an `Equivalence` to compare tuples element-by-element. * - * - Use when you need to compare tuples element-by-element. + * **Details** + * + * This is an alias of `Equivalence.Tuple`. * * **Example** (Comparing tuples for equivalence) * @@ -1030,9 +1091,8 @@ export const mapOmit: { * ``` * * @see {@link makeOrder} – create an `Order` for tuples - * - * @category Equivalence - * @since 2.0.0 + * @category instances + * @since 4.0.0 */ export const makeEquivalence = Equivalence.Tuple @@ -1041,9 +1101,14 @@ export const makeEquivalence = Equivalence.Tuple * provided per-position `Order`s. Elements are compared left-to-right; the * first non-zero comparison determines the result. * - * Alias of `Order.Tuple`. + * **When to use** + * + * Use when you need to sort fixed-position arrays lexicographically, with each + * position using its own ordering rule. * - * - Use to sort or compare tuples lexicographically by element position. + * **Details** + * + * This is an alias of `Order.Tuple`. * * **Example** (Ordering tuples) * @@ -1057,22 +1122,29 @@ export const makeEquivalence = Equivalence.Tuple * ``` * * @see {@link makeEquivalence} – create an `Equivalence` for tuples - * - * @category Ordering - * @since 2.0.0 + * @category ordering + * @since 4.0.0 */ export const makeOrder = order.Tuple export { /** - * Checks if an array has exactly `N` elements, narrowing the type to a + * Checks whether an array has exactly `N` elements, narrowing the type to a * fixed-length tuple. * - * Re-export of `Predicate.isTupleOf`. + * **When to use** + * + * Use to guard that an array has exactly the tuple length expected at + * runtime. + * + * **Details** + * + * This is a re-export of `Predicate.isTupleOf`. It narrows the type to + * `TupleOf` in the truthy branch. + * + * **Gotchas** * - * - Use to guard against unexpected array lengths at runtime. - * - Only checks `.length`; does not validate element types. - * - Narrows the type to `TupleOf` in the truthy branch. + * This only checks `.length`; it does not validate element types. * * **Example** (Checking exact length) * @@ -1086,21 +1158,28 @@ export { * } * ``` * - * @see {@link isTupleOfAtLeast} – check for a minimum length - * - * @category Guards + * @see `isTupleOfAtLeast` – check for a minimum length + * @category guards * @since 3.3.0 */ isTupleOf, /** - * Checks if an array has at least `N` elements, narrowing the type to a + * Checks whether an array has at least `N` elements, narrowing the type to a * tuple with a minimum length. * - * Re-export of `Predicate.isTupleOfAtLeast`. + * **When to use** + * + * Use to guard that an array has at least the tuple length expected at + * runtime. + * + * **Details** + * + * This is a re-export of `Predicate.isTupleOfAtLeast`. It narrows the type to + * `TupleOfAtLeast` in the truthy branch. + * + * **Gotchas** * - * - Use to guard that an array has at least the expected number of elements. - * - Only checks `.length`; does not validate element types. - * - Narrows the type to `TupleOfAtLeast` in the truthy branch. + * This only checks `.length`; it does not validate element types. * * **Example** (Checking minimum length) * @@ -1114,9 +1193,8 @@ export { * } * ``` * - * @see {@link isTupleOf} – check for an exact length - * - * @category Guards + * @see `isTupleOf` – check for an exact length + * @category guards * @since 3.3.0 */ isTupleOfAtLeast @@ -1127,9 +1205,10 @@ export { * position. When two tuples are combined, each element is merged using its * corresponding combiner. * - * - Use when you need to merge two tuples of the same shape (e.g., summing - * counters, concatenating strings). - * - Does not mutate the inputs; returns a fresh tuple. + * **When to use** + * + * Use when you need to merge two same-shape tuples by combining each position + * independently, such as summing counters or concatenating strings. * * **Example** (Combining tuple elements) * @@ -1146,7 +1225,7 @@ export { * ``` * * @see {@link makeReducer} – like `makeCombiner` but with an initial value - * + * @category combining * @since 4.0.0 */ export function makeCombiner>( @@ -1167,8 +1246,10 @@ export function makeCombiner>( * `Reducer.initialValue`. When reducing a collection of tuples, each element * is combined independently. * - * - Use to fold a collection of tuples into a single summary tuple. - * - Does not mutate the inputs; returns a fresh tuple. + * **When to use** + * + * Use when you need to fold same-shape tuples by accumulating each position + * independently into one summary tuple. * * **Example** (Reducing a collection of tuples) * @@ -1189,7 +1270,7 @@ export function makeCombiner>( * ``` * * @see {@link makeCombiner} – like `makeReducer` but without an initial value - * + * @category folding * @since 4.0.0 */ export function makeReducer>( diff --git a/.opencode/node_modules/effect/src/TxChunk.ts b/.opencode/node_modules/effect/src/TxChunk.ts index 31cdd20aa5843281f63fc77d713a1aa4dfc3e75b..298079a1786319394f3014e71332d236f023925b 100644 --- a/.opencode/node_modules/effect/src/TxChunk.ts +++ b/.opencode/node_modules/effect/src/TxChunk.ts @@ -1,11 +1,12 @@ /** - * TxChunk is a transactional chunk data structure that provides Software Transactional Memory (STM) - * semantics for chunk operations. It uses a `TxRef>` internally to ensure all operations - * are performed atomically within transactions. + * Stores a `Chunk` inside transactional state. * - * Accessed values are tracked by the transaction in order to detect conflicts and to track changes. - * A transaction will retry whenever a conflict is detected or whenever the transaction explicitly - * calls `Effect.txRetry` and any of the accessed TxChunk values change. + * A `TxChunk` keeps its current `Chunk` in a `TxRef`, so reads and + * updates can be committed atomically with other transactional operations. This + * module offers a transactional version of common chunk workflows, including + * creating collections, reading or replacing the current chunk, adding or + * removing values, checking size, slicing, mapping, filtering, and combining + * chunks. * * @since 4.0.0 */ @@ -26,11 +27,14 @@ const TypeId = "~effect/transactions/TxChunk" * TxChunk is a transactional chunk data structure that provides Software Transactional Memory (STM) * semantics for chunk operations. * + * **Details** + * * Accessed values are tracked by the transaction in order to detect conflicts and to track changes. * A transaction will retry whenever a conflict is detected or whenever the transaction explicitly * calls `Effect.txRetry` and any of the accessed TxChunk values change. * - * @example + * **Example** (Using a transactional chunk) + * * ```ts * import { Chunk, Effect, TxChunk } from "effect" * @@ -60,8 +64,8 @@ const TypeId = "~effect/transactions/TxChunk" * }) * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface TxChunk extends Inspectable, Pipeable { readonly [TypeId]: typeof TypeId @@ -89,12 +93,13 @@ const TxChunkProto = { /** * Creates a new `TxChunk` with the specified initial chunk. * - * **Return behavior**: This function returns a new TxChunk reference containing - * the provided initial chunk. No existing TxChunk instances are modified. + * **Details** + * + * This function returns a new TxChunk reference containing the provided initial chunk. No existing + * TxChunk instances are modified. + * + * **Example** (Creating a TxChunk from a chunk) * - * @since 4.0.0 - * @category Constructors - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * @@ -108,6 +113,9 @@ const TxChunkProto = { * console.log(Chunk.toReadonlyArray(result)) // [1, 2, 3] * }) * ``` + * + * @category constructors + * @since 4.0.0 */ export const make = (initial: Chunk.Chunk): Effect.Effect> => Effect.map(TxRef.make(initial), (ref) => makeUnsafe(ref)) @@ -115,12 +123,13 @@ export const make = (initial: Chunk.Chunk): Effect.Effect> => /** * Creates a new empty `TxChunk`. * - * **Return behavior**: This function returns a new TxChunk reference that is - * initially empty. No existing TxChunk instances are modified. + * **Details** + * + * This function returns a new TxChunk reference that is initially empty. No existing TxChunk + * instances are modified. + * + * **Example** (Creating an empty TxChunk) * - * @since 4.0.0 - * @category Constructors - * @example * ```ts * import { Effect, TxChunk } from "effect" * @@ -139,6 +148,9 @@ export const make = (initial: Chunk.Chunk): Effect.Effect> => * console.log(isStillEmpty) // false * }) * ``` + * + * @category constructors + * @since 4.0.0 */ export const empty = (): Effect.Effect> => Effect.map(TxRef.make(Chunk.empty()), (ref) => makeUnsafe(ref)) @@ -146,12 +158,13 @@ export const empty = (): Effect.Effect> => /** * Creates a new `TxChunk` from an iterable. * - * **Return behavior**: This function returns a new TxChunk reference containing - * elements from the provided iterable. No existing TxChunk instances are modified. + * **Details** + * + * This function returns a new TxChunk reference containing elements from the provided iterable. No + * existing TxChunk instances are modified. + * + * **Example** (Creating from an iterable) * - * @since 4.0.0 - * @category Constructors - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * @@ -175,6 +188,9 @@ export const empty = (): Effect.Effect> => * console.log(Chunk.toReadonlyArray(updated)) // [0, 1, 2, 3, 4, 5, 6] * }) * ``` + * + * @category constructors + * @since 4.0.0 */ export const fromIterable = (iterable: Iterable): Effect.Effect> => Effect.map(TxRef.make(Chunk.fromIterable(iterable)), (ref) => makeUnsafe(ref)) @@ -182,10 +198,13 @@ export const fromIterable = (iterable: Iterable): Effect.Effect /** * Creates a new `TxChunk` with the specified TxRef. * - * **Return behavior**: This function returns a new TxChunk reference wrapping - * the provided TxRef. No existing TxChunk instances are modified. + * **Details** + * + * This function returns a new TxChunk reference wrapping the provided TxRef. No existing TxChunk + * instances are modified. + * + * **Example** (Wrapping an existing TxRef) * - * @example * ```ts * import { Chunk, TxChunk, TxRef } from "effect" * @@ -194,8 +213,8 @@ export const fromIterable = (iterable: Iterable): Effect.Effect * const txChunk = TxChunk.makeUnsafe(ref) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const makeUnsafe = (ref: TxRef.TxRef>): TxChunk => { const txChunk = Object.create(TxChunkProto) @@ -207,12 +226,13 @@ export const makeUnsafe = (ref: TxRef.TxRef>): TxChunk => { /** * Modifies the value of the `TxChunk` using the provided function. * - * **Mutation behavior**: This function mutates the original TxChunk by updating - * its internal state. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by updating its internal state. It does not return a + * new TxChunk reference. + * + * **Example** (Modifying while returning a value) * - * @since 4.0.0 - * @category Combinators - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * @@ -231,17 +251,21 @@ export const makeUnsafe = (ref: TxRef.TxRef>): TxChunk => { * console.log(Chunk.toReadonlyArray(newChunk)) // [1, 2, 3, 4] * }) * ``` + * + * @category combinators + * @since 4.0.0 */ export const modify: { /** * Modifies the value of the `TxChunk` using the provided function. * - * **Mutation behavior**: This function mutates the original TxChunk by updating - * its internal state. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by updating its internal state. It does not return a + * new TxChunk reference. + * + * **Example** (Modifying while returning a value) * - * @since 4.0.0 - * @category Combinators - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * @@ -260,6 +284,9 @@ export const modify: { * console.log(Chunk.toReadonlyArray(newChunk)) // [1, 2, 3, 4] * }) * ``` + * + * @category combinators + * @since 4.0.0 */ ( f: (current: Chunk.Chunk>) => [returnValue: R, newValue: Chunk.Chunk] @@ -267,12 +294,13 @@ export const modify: { /** * Modifies the value of the `TxChunk` using the provided function. * - * **Mutation behavior**: This function mutates the original TxChunk by updating - * its internal state. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by updating its internal state. It does not return a + * new TxChunk reference. + * + * **Example** (Modifying while returning a value) * - * @since 4.0.0 - * @category Combinators - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * @@ -291,6 +319,9 @@ export const modify: { * console.log(Chunk.toReadonlyArray(newChunk)) // [1, 2, 3, 4] * }) * ``` + * + * @category combinators + * @since 4.0.0 */ ( self: TxChunk, @@ -307,18 +338,20 @@ export const modify: { /** * Updates the value of the `TxChunk` using the provided function. * - * **Mutation behavior**: This function mutates the original TxChunk by updating - * its internal state. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by updating its internal state. It does not return a + * new TxChunk reference. + * + * **Example** (Updating the stored chunk) * - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * * const program = Effect.gen(function*() { * const txChunk = yield* TxChunk.fromIterable([1, 2, 3]) * - * // Update the chunk by reversing it - * // Update the chunk by reversing it - automatically transactional + * // Update the chunk by reversing it atomically * yield* TxChunk.update(txChunk, (chunk) => Chunk.reverse(chunk)) * * const result = yield* TxChunk.get(txChunk) @@ -326,25 +359,27 @@ export const modify: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const update: { /** * Updates the value of the `TxChunk` using the provided function. * - * **Mutation behavior**: This function mutates the original TxChunk by updating - * its internal state. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by updating its internal state. It does not return a + * new TxChunk reference. + * + * **Example** (Updating the stored chunk) * - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * * const program = Effect.gen(function*() { * const txChunk = yield* TxChunk.fromIterable([1, 2, 3]) * - * // Update the chunk by reversing it - * // Update the chunk by reversing it - automatically transactional + * // Update the chunk by reversing it atomically * yield* TxChunk.update(txChunk, (chunk) => Chunk.reverse(chunk)) * * const result = yield* TxChunk.get(txChunk) @@ -352,25 +387,27 @@ export const update: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (f: (current: Chunk.Chunk>) => Chunk.Chunk): (self: TxChunk) => Effect.Effect /** * Updates the value of the `TxChunk` using the provided function. * - * **Mutation behavior**: This function mutates the original TxChunk by updating - * its internal state. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by updating its internal state. It does not return a + * new TxChunk reference. + * + * **Example** (Updating the stored chunk) * - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * * const program = Effect.gen(function*() { * const txChunk = yield* TxChunk.fromIterable([1, 2, 3]) * - * // Update the chunk by reversing it - * // Update the chunk by reversing it - automatically transactional + * // Update the chunk by reversing it atomically * yield* TxChunk.update(txChunk, (chunk) => Chunk.reverse(chunk)) * * const result = yield* TxChunk.get(txChunk) @@ -378,8 +415,8 @@ export const update: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: TxChunk, f: (current: Chunk.Chunk) => Chunk.Chunk): Effect.Effect } = dual( @@ -393,7 +430,8 @@ export const update: { /** * Reads the current chunk from the `TxChunk`. * - * @example + * **Example** (Reading the current chunk) + * * ```ts * import { Chunk, Effect, TxChunk } from "effect" * @@ -410,18 +448,21 @@ export const update: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const get = (self: TxChunk): Effect.Effect> => TxRef.get(self.ref) /** * Sets the value of the `TxChunk`. * - * **Mutation behavior**: This function mutates the original TxChunk by replacing - * its internal state with the provided chunk. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by replacing its internal state with the provided + * chunk. It does not return a new TxChunk reference. + * + * **Example** (Replacing the stored chunk) * - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * @@ -437,17 +478,20 @@ export const get = (self: TxChunk): Effect.Effect> => TxRef * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const set: { /** * Sets the value of the `TxChunk`. * - * **Mutation behavior**: This function mutates the original TxChunk by replacing - * its internal state with the provided chunk. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by replacing its internal state with the provided + * chunk. It does not return a new TxChunk reference. + * + * **Example** (Replacing the stored chunk) * - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * @@ -463,17 +507,20 @@ export const set: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (chunk: Chunk.Chunk): (self: TxChunk) => Effect.Effect /** * Sets the value of the `TxChunk`. * - * **Mutation behavior**: This function mutates the original TxChunk by replacing - * its internal state with the provided chunk. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by replacing its internal state with the provided + * chunk. It does not return a new TxChunk reference. + * + * **Example** (Replacing the stored chunk) * - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * @@ -489,8 +536,8 @@ export const set: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: TxChunk, chunk: Chunk.Chunk): Effect.Effect } = dual( @@ -501,10 +548,13 @@ export const set: { /** * Appends an element to the end of the `TxChunk`. * - * **Mutation behavior**: This function mutates the original TxChunk by adding - * the element to the end. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by adding the element to the end. It does not return a + * new TxChunk reference. + * + * **Example** (Appending an element) * - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * @@ -519,17 +569,20 @@ export const set: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const append: { /** * Appends an element to the end of the `TxChunk`. * - * **Mutation behavior**: This function mutates the original TxChunk by adding - * the element to the end. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by adding the element to the end. It does not return a + * new TxChunk reference. + * + * **Example** (Appending an element) * - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * @@ -544,17 +597,20 @@ export const append: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (element: A): (self: TxChunk) => Effect.Effect /** * Appends an element to the end of the `TxChunk`. * - * **Mutation behavior**: This function mutates the original TxChunk by adding - * the element to the end. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by adding the element to the end. It does not return a + * new TxChunk reference. + * + * **Example** (Appending an element) * - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * @@ -569,8 +625,8 @@ export const append: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: TxChunk, element: A): Effect.Effect } = dual( @@ -581,10 +637,13 @@ export const append: { /** * Prepends an element to the beginning of the `TxChunk`. * - * **Mutation behavior**: This function mutates the original TxChunk by adding - * the element to the beginning. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by adding the element to the beginning. It does not + * return a new TxChunk reference. + * + * **Example** (Prepending an element) * - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * @@ -599,17 +658,20 @@ export const append: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const prepend: { /** * Prepends an element to the beginning of the `TxChunk`. * - * **Mutation behavior**: This function mutates the original TxChunk by adding - * the element to the beginning. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by adding the element to the beginning. It does not + * return a new TxChunk reference. + * + * **Example** (Prepending an element) * - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * @@ -624,17 +686,20 @@ export const prepend: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (element: A): (self: TxChunk) => Effect.Effect /** * Prepends an element to the beginning of the `TxChunk`. * - * **Mutation behavior**: This function mutates the original TxChunk by adding - * the element to the beginning. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by adding the element to the beginning. It does not + * return a new TxChunk reference. + * + * **Example** (Prepending an element) * - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * @@ -649,8 +714,8 @@ export const prepend: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: TxChunk, element: A): Effect.Effect } = dual( @@ -661,7 +726,8 @@ export const prepend: { /** * Gets the size of the `TxChunk`. * - * @example + * **Example** (Getting the size) + * * ```ts * import { Effect, TxChunk } from "effect" * @@ -679,16 +745,17 @@ export const prepend: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const size = (self: TxChunk): Effect.Effect => modify(self, (current) => [Chunk.size(current), current]) /** - * Checks if the `TxChunk` is empty. + * Checks whether the `TxChunk` is empty. + * + * **Example** (Checking for an empty chunk) * - * @example * ```ts * import { Effect, TxChunk } from "effect" * @@ -705,16 +772,17 @@ export const size = (self: TxChunk): Effect.Effect => * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const isEmpty = (self: TxChunk): Effect.Effect => modify(self, (current) => [Chunk.isEmpty(current), current]) /** - * Checks if the `TxChunk` is non-empty. + * Checks whether the `TxChunk` is non-empty. + * + * **Example** (Checking for a non-empty chunk) * - * @example * ```ts * import { Effect, TxChunk } from "effect" * @@ -731,8 +799,8 @@ export const isEmpty = (self: TxChunk): Effect.Effect => * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const isNonEmpty = (self: TxChunk): Effect.Effect => modify(self, (current) => [Chunk.isNonEmpty(current), current]) @@ -740,10 +808,13 @@ export const isNonEmpty = (self: TxChunk): Effect.Effect => /** * Takes the first `n` elements from the `TxChunk`. * - * **Mutation behavior**: This function mutates the original TxChunk by keeping - * only the first n elements. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by keeping only the first n elements. It does not + * return a new TxChunk reference. + * + * **Example** (Taking leading elements) * - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * @@ -758,17 +829,20 @@ export const isNonEmpty = (self: TxChunk): Effect.Effect => * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const take: { /** * Takes the first `n` elements from the `TxChunk`. * - * **Mutation behavior**: This function mutates the original TxChunk by keeping - * only the first n elements. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by keeping only the first n elements. It does not + * return a new TxChunk reference. + * + * **Example** (Taking leading elements) * - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * @@ -783,17 +857,20 @@ export const take: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (n: number): (self: TxChunk) => Effect.Effect /** * Takes the first `n` elements from the `TxChunk`. * - * **Mutation behavior**: This function mutates the original TxChunk by keeping - * only the first n elements. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by keeping only the first n elements. It does not + * return a new TxChunk reference. + * + * **Example** (Taking leading elements) * - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * @@ -808,8 +885,8 @@ export const take: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: TxChunk, n: number): Effect.Effect } = dual( @@ -820,10 +897,13 @@ export const take: { /** * Drops the first `n` elements from the `TxChunk`. * - * **Mutation behavior**: This function mutates the original TxChunk by removing - * the first n elements. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by removing the first n elements. It does not return a + * new TxChunk reference. + * + * **Example** (Dropping leading elements) * - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * @@ -838,17 +918,20 @@ export const take: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const drop: { /** * Drops the first `n` elements from the `TxChunk`. * - * **Mutation behavior**: This function mutates the original TxChunk by removing - * the first n elements. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by removing the first n elements. It does not return a + * new TxChunk reference. + * + * **Example** (Dropping leading elements) * - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * @@ -863,17 +946,20 @@ export const drop: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (n: number): (self: TxChunk) => Effect.Effect /** * Drops the first `n` elements from the `TxChunk`. * - * **Mutation behavior**: This function mutates the original TxChunk by removing - * the first n elements. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by removing the first n elements. It does not return a + * new TxChunk reference. + * + * **Example** (Dropping leading elements) * - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * @@ -888,8 +974,8 @@ export const drop: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: TxChunk, n: number): Effect.Effect } = dual( @@ -900,10 +986,13 @@ export const drop: { /** * Takes a slice of the `TxChunk` from `start` to `end` (exclusive). * - * **Mutation behavior**: This function mutates the original TxChunk by keeping - * only the elements in the specified range. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by keeping only the elements in the specified range. It + * does not return a new TxChunk reference. + * + * **Example** (Taking a slice) * - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * @@ -918,17 +1007,20 @@ export const drop: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const slice: { /** * Takes a slice of the `TxChunk` from `start` to `end` (exclusive). * - * **Mutation behavior**: This function mutates the original TxChunk by keeping - * only the elements in the specified range. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by keeping only the elements in the specified range. It + * does not return a new TxChunk reference. + * + * **Example** (Taking a slice) * - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * @@ -943,17 +1035,20 @@ export const slice: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (start: number, end: number): (self: TxChunk) => Effect.Effect /** * Takes a slice of the `TxChunk` from `start` to `end` (exclusive). * - * **Mutation behavior**: This function mutates the original TxChunk by keeping - * only the elements in the specified range. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by keeping only the elements in the specified range. It + * does not return a new TxChunk reference. + * + * **Example** (Taking a slice) * - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * @@ -968,8 +1063,8 @@ export const slice: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: TxChunk, start: number, end: number): Effect.Effect } = dual( @@ -979,21 +1074,23 @@ export const slice: { ) /** - * Maps each element of the `TxChunk` using the provided function. - * Note: This only works when the mapped type B is assignable to A. + * Maps each element of the `TxChunk` using a function that returns the same + * element type. * - * **Mutation behavior**: This function mutates the original TxChunk by transforming - * each element in place. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original `TxChunk` by transforming each element in place. It does not + * return a new `TxChunk` reference. + * + * **Example** (Mapping elements) * - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * * const program = Effect.gen(function*() { * const txChunk = yield* TxChunk.fromIterable([1, 2, 3, 4]) * - * // Transform each element (must maintain same type) - * // Transform each element (must maintain same type) - automatically transactional + * // Transform each element atomically (must maintain same type) * yield* TxChunk.map(txChunk, (n) => n * 2) * * const result = yield* TxChunk.get(txChunk) @@ -1001,26 +1098,28 @@ export const slice: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const map: { /** - * Maps each element of the `TxChunk` using the provided function. - * Note: This only works when the mapped type B is assignable to A. + * Maps each element of the `TxChunk` using a function that returns the same + * element type. * - * **Mutation behavior**: This function mutates the original TxChunk by transforming - * each element in place. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original `TxChunk` by transforming each element in place. It does not + * return a new `TxChunk` reference. + * + * **Example** (Mapping elements) * - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * * const program = Effect.gen(function*() { * const txChunk = yield* TxChunk.fromIterable([1, 2, 3, 4]) * - * // Transform each element (must maintain same type) - * // Transform each element (must maintain same type) - automatically transactional + * // Transform each element atomically (must maintain same type) * yield* TxChunk.map(txChunk, (n) => n * 2) * * const result = yield* TxChunk.get(txChunk) @@ -1028,26 +1127,28 @@ export const map: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (f: (a: NoInfer) => A): (self: TxChunk) => Effect.Effect /** - * Maps each element of the `TxChunk` using the provided function. - * Note: This only works when the mapped type B is assignable to A. + * Maps each element of the `TxChunk` using a function that returns the same + * element type. + * + * **Details** * - * **Mutation behavior**: This function mutates the original TxChunk by transforming - * each element in place. It does not return a new TxChunk reference. + * This function mutates the original `TxChunk` by transforming each element in place. It does not + * return a new `TxChunk` reference. + * + * **Example** (Mapping elements) * - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * * const program = Effect.gen(function*() { * const txChunk = yield* TxChunk.fromIterable([1, 2, 3, 4]) * - * // Transform each element (must maintain same type) - * // Transform each element (must maintain same type) - automatically transactional + * // Transform each element atomically (must maintain same type) * yield* TxChunk.map(txChunk, (n) => n * 2) * * const result = yield* TxChunk.get(txChunk) @@ -1055,8 +1156,8 @@ export const map: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: TxChunk, f: (a: A) => A): Effect.Effect } = dual( @@ -1067,18 +1168,20 @@ export const map: { /** * Filters the `TxChunk` keeping only elements that satisfy the predicate. * - * **Mutation behavior**: This function mutates the original TxChunk by removing - * elements that don't match the predicate. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by removing elements that don't match the predicate. It + * does not return a new TxChunk reference. + * + * **Example** (Filtering elements) * - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * * const program = Effect.gen(function*() { * const txChunk = yield* TxChunk.fromIterable([1, 2, 3, 4, 5, 6]) * - * // Keep only even numbers - * // Keep only even numbers - automatically transactional + * // Keep only even numbers atomically * yield* TxChunk.filter(txChunk, (n) => n % 2 === 0) * * const result = yield* TxChunk.get(txChunk) @@ -1086,25 +1189,27 @@ export const map: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const filter: { /** * Filters the `TxChunk` keeping only elements that satisfy the predicate. * - * **Mutation behavior**: This function mutates the original TxChunk by removing - * elements that don't match the predicate. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by removing elements that don't match the predicate. It + * does not return a new TxChunk reference. + * + * **Example** (Filtering elements) * - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * * const program = Effect.gen(function*() { * const txChunk = yield* TxChunk.fromIterable([1, 2, 3, 4, 5, 6]) * - * // Keep only even numbers - * // Keep only even numbers - automatically transactional + * // Keep only even numbers atomically * yield* TxChunk.filter(txChunk, (n) => n % 2 === 0) * * const result = yield* TxChunk.get(txChunk) @@ -1112,25 +1217,27 @@ export const filter: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (refinement: (a: A) => a is B): (self: TxChunk) => Effect.Effect /** * Filters the `TxChunk` keeping only elements that satisfy the predicate. * - * **Mutation behavior**: This function mutates the original TxChunk by removing - * elements that don't match the predicate. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by removing elements that don't match the predicate. It + * does not return a new TxChunk reference. + * + * **Example** (Filtering elements) * - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * * const program = Effect.gen(function*() { * const txChunk = yield* TxChunk.fromIterable([1, 2, 3, 4, 5, 6]) * - * // Keep only even numbers - * // Keep only even numbers - automatically transactional + * // Keep only even numbers atomically * yield* TxChunk.filter(txChunk, (n) => n % 2 === 0) * * const result = yield* TxChunk.get(txChunk) @@ -1138,25 +1245,27 @@ export const filter: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (predicate: (a: A) => boolean): (self: TxChunk) => Effect.Effect /** * Filters the `TxChunk` keeping only elements that satisfy the predicate. * - * **Mutation behavior**: This function mutates the original TxChunk by removing - * elements that don't match the predicate. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by removing elements that don't match the predicate. It + * does not return a new TxChunk reference. + * + * **Example** (Filtering elements) * - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * * const program = Effect.gen(function*() { * const txChunk = yield* TxChunk.fromIterable([1, 2, 3, 4, 5, 6]) * - * // Keep only even numbers - * // Keep only even numbers - automatically transactional + * // Keep only even numbers atomically * yield* TxChunk.filter(txChunk, (n) => n % 2 === 0) * * const result = yield* TxChunk.get(txChunk) @@ -1164,25 +1273,27 @@ export const filter: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: TxChunk, refinement: (a: A) => a is B): Effect.Effect /** * Filters the `TxChunk` keeping only elements that satisfy the predicate. * - * **Mutation behavior**: This function mutates the original TxChunk by removing - * elements that don't match the predicate. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by removing elements that don't match the predicate. It + * does not return a new TxChunk reference. + * + * **Example** (Filtering elements) * - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * * const program = Effect.gen(function*() { * const txChunk = yield* TxChunk.fromIterable([1, 2, 3, 4, 5, 6]) * - * // Keep only even numbers - * // Keep only even numbers - automatically transactional + * // Keep only even numbers atomically * yield* TxChunk.filter(txChunk, (n) => n % 2 === 0) * * const result = yield* TxChunk.get(txChunk) @@ -1190,8 +1301,8 @@ export const filter: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: TxChunk, predicate: (a: A) => boolean): Effect.Effect } = dual( @@ -1203,10 +1314,13 @@ export const filter: { /** * Concatenates another chunk to the end of the `TxChunk`. * - * **Mutation behavior**: This function mutates the original TxChunk by appending - * all elements from the other chunk. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by appending all elements from the other chunk. It does + * not return a new TxChunk reference. + * + * **Example** (Appending another chunk) * - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * @@ -1214,8 +1328,7 @@ export const filter: { * const txChunk = yield* TxChunk.fromIterable([1, 2, 3]) * const otherChunk = Chunk.fromIterable([4, 5, 6]) * - * // Append all elements from another chunk - * // Append all elements from another chunk - automatically transactional + * // Append all elements from another chunk atomically * yield* TxChunk.appendAll(txChunk, otherChunk) * * const result = yield* TxChunk.get(txChunk) @@ -1223,17 +1336,20 @@ export const filter: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const appendAll: { /** * Concatenates another chunk to the end of the `TxChunk`. * - * **Mutation behavior**: This function mutates the original TxChunk by appending - * all elements from the other chunk. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by appending all elements from the other chunk. It does + * not return a new TxChunk reference. + * + * **Example** (Appending another chunk) * - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * @@ -1241,8 +1357,7 @@ export const appendAll: { * const txChunk = yield* TxChunk.fromIterable([1, 2, 3]) * const otherChunk = Chunk.fromIterable([4, 5, 6]) * - * // Append all elements from another chunk - * // Append all elements from another chunk - automatically transactional + * // Append all elements from another chunk atomically * yield* TxChunk.appendAll(txChunk, otherChunk) * * const result = yield* TxChunk.get(txChunk) @@ -1250,17 +1365,20 @@ export const appendAll: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (other: Chunk.Chunk): (self: TxChunk) => Effect.Effect /** * Concatenates another chunk to the end of the `TxChunk`. * - * **Mutation behavior**: This function mutates the original TxChunk by appending - * all elements from the other chunk. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by appending all elements from the other chunk. It does + * not return a new TxChunk reference. + * + * **Example** (Appending another chunk) * - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * @@ -1268,8 +1386,7 @@ export const appendAll: { * const txChunk = yield* TxChunk.fromIterable([1, 2, 3]) * const otherChunk = Chunk.fromIterable([4, 5, 6]) * - * // Append all elements from another chunk - * // Append all elements from another chunk - automatically transactional + * // Append all elements from another chunk atomically * yield* TxChunk.appendAll(txChunk, otherChunk) * * const result = yield* TxChunk.get(txChunk) @@ -1277,8 +1394,8 @@ export const appendAll: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: TxChunk, other: Chunk.Chunk): Effect.Effect } = dual( @@ -1290,10 +1407,13 @@ export const appendAll: { /** * Concatenates another chunk to the beginning of the `TxChunk`. * - * **Mutation behavior**: This function mutates the original TxChunk by prepending - * all elements from the other chunk. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by prepending all elements from the other chunk. It + * does not return a new TxChunk reference. + * + * **Example** (Prepending another chunk) * - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * @@ -1301,8 +1421,7 @@ export const appendAll: { * const txChunk = yield* TxChunk.fromIterable([4, 5, 6]) * const otherChunk = Chunk.fromIterable([1, 2, 3]) * - * // Prepend all elements from another chunk - * // Prepend all elements from another chunk - automatically transactional + * // Prepend all elements from another chunk atomically * yield* TxChunk.prependAll(txChunk, otherChunk) * * const result = yield* TxChunk.get(txChunk) @@ -1310,17 +1429,20 @@ export const appendAll: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const prependAll: { /** * Concatenates another chunk to the beginning of the `TxChunk`. * - * **Mutation behavior**: This function mutates the original TxChunk by prepending - * all elements from the other chunk. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by prepending all elements from the other chunk. It + * does not return a new TxChunk reference. + * + * **Example** (Prepending another chunk) * - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * @@ -1328,8 +1450,7 @@ export const prependAll: { * const txChunk = yield* TxChunk.fromIterable([4, 5, 6]) * const otherChunk = Chunk.fromIterable([1, 2, 3]) * - * // Prepend all elements from another chunk - * // Prepend all elements from another chunk - automatically transactional + * // Prepend all elements from another chunk atomically * yield* TxChunk.prependAll(txChunk, otherChunk) * * const result = yield* TxChunk.get(txChunk) @@ -1337,17 +1458,20 @@ export const prependAll: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (other: Chunk.Chunk): (self: TxChunk) => Effect.Effect /** * Concatenates another chunk to the beginning of the `TxChunk`. * - * **Mutation behavior**: This function mutates the original TxChunk by prepending - * all elements from the other chunk. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by prepending all elements from the other chunk. It + * does not return a new TxChunk reference. + * + * **Example** (Prepending another chunk) * - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * @@ -1355,8 +1479,7 @@ export const prependAll: { * const txChunk = yield* TxChunk.fromIterable([4, 5, 6]) * const otherChunk = Chunk.fromIterable([1, 2, 3]) * - * // Prepend all elements from another chunk - * // Prepend all elements from another chunk - automatically transactional + * // Prepend all elements from another chunk atomically * yield* TxChunk.prependAll(txChunk, otherChunk) * * const result = yield* TxChunk.get(txChunk) @@ -1364,8 +1487,8 @@ export const prependAll: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: TxChunk, other: Chunk.Chunk): Effect.Effect } = dual( @@ -1377,12 +1500,13 @@ export const prependAll: { /** * Concatenates another `TxChunk` to the end of this `TxChunk`. * - * **Mutation behavior**: This function mutates the original TxChunk by appending - * all elements from the other TxChunk. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by appending all elements from the other TxChunk. It + * does not return a new TxChunk reference. + * + * **Example** (Concatenating TxChunks) * - * @since 4.0.0 - * @category Combinators - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * @@ -1401,17 +1525,21 @@ export const prependAll: { * console.log(Chunk.toReadonlyArray(original)) // [4, 5, 6] * }) * ``` + * + * @category combinators + * @since 4.0.0 */ export const concat: { /** * Concatenates another `TxChunk` to the end of this `TxChunk`. * - * **Mutation behavior**: This function mutates the original TxChunk by appending - * all elements from the other TxChunk. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by appending all elements from the other TxChunk. It + * does not return a new TxChunk reference. + * + * **Example** (Concatenating TxChunks) * - * @since 4.0.0 - * @category Combinators - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * @@ -1430,17 +1558,21 @@ export const concat: { * console.log(Chunk.toReadonlyArray(original)) // [4, 5, 6] * }) * ``` + * + * @category combinators + * @since 4.0.0 */ (other: TxChunk): (self: TxChunk) => Effect.Effect /** * Concatenates another `TxChunk` to the end of this `TxChunk`. * - * **Mutation behavior**: This function mutates the original TxChunk by appending - * all elements from the other TxChunk. It does not return a new TxChunk reference. + * **Details** + * + * This function mutates the original TxChunk by appending all elements from the other TxChunk. It + * does not return a new TxChunk reference. + * + * **Example** (Concatenating TxChunks) * - * @since 4.0.0 - * @category Combinators - * @example * ```ts * import { Chunk, Effect, TxChunk } from "effect" * @@ -1459,6 +1591,9 @@ export const concat: { * console.log(Chunk.toReadonlyArray(original)) // [4, 5, 6] * }) * ``` + * + * @category combinators + * @since 4.0.0 */ (self: TxChunk, other: TxChunk): Effect.Effect } = dual( diff --git a/.opencode/node_modules/effect/src/TxDeferred.ts b/.opencode/node_modules/effect/src/TxDeferred.ts index 6da0b719aaf97dab5cedf36f9d814a6854a4dd16..d077555d02c5b034033fefca2e8805a49ded1a55 100644 --- a/.opencode/node_modules/effect/src/TxDeferred.ts +++ b/.opencode/node_modules/effect/src/TxDeferred.ts @@ -1,6 +1,11 @@ /** - * A transactional deferred value — a write-once cell that can be read within transactions. - * Readers retry until a value is set; once set, the value is immutable. + * Transactional deferred values for coordinating Effect transactions. + * + * A `TxDeferred` is a write-once cell whose completion is a + * `Result` stored in transactional state. Readers can wait for the value + * from inside a transaction: while the cell is empty the transaction retries, + * and when another transaction completes the deferred the waiting transaction + * can resume with either the success value or the typed failure. * * @since 4.0.0 */ @@ -21,12 +26,17 @@ import * as TxRef from "./TxRef.ts" const TypeId = "~effect/transactions/TxDeferred" /** - * A transactional deferred — a write-once cell readable within transactions. + * A transactional deferred is a write-once cell readable within transactions. + * Readers block (retry the transaction) until a value is committed, and writers + * succeed only on the first call; subsequent writes return `false`. + * + * **When to use** * - * Readers block (retry the transaction) until a value is committed. - * Writers succeed only on the first call; subsequent writes return `false`. + * Use to coordinate transaction-local readers and one-time completion with a + * success or failure result. + * + * **Example** (Completing a transactional deferred) * - * @example * ```ts * import { Effect, TxDeferred } from "effect" * @@ -47,8 +57,8 @@ const TypeId = "~effect/transactions/TxDeferred" * }) * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface TxDeferred extends Inspectable, Pipeable { readonly [TypeId]: typeof TypeId @@ -79,7 +89,12 @@ const makeTxDeferred = (ref: TxRef.TxRef>>): TxDeferre /** * Creates a new empty `TxDeferred`. * - * @example + * **When to use** + * + * Use to create a transactional deferred that can be completed exactly once. + * + * **Example** (Creating a transactional deferred) + * * ```ts * import { Effect, Option, TxDeferred } from "effect" * @@ -90,8 +105,8 @@ const makeTxDeferred = (ref: TxRef.TxRef>>): TxDeferre * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 2.0.0 */ export const make = (): Effect.Effect> => Effect.map(TxRef.make>>(O.none()), makeTxDeferred) @@ -100,7 +115,8 @@ export const make = (): Effect.Effect> => * Reads the deferred value. Retries the transaction if the deferred has not * been completed yet. * - * @example + * **Example** (Awaiting a deferred value) + * * ```ts * import { Effect, TxDeferred } from "effect" * @@ -112,8 +128,8 @@ export const make = (): Effect.Effect> => * }) * ``` * - * @since 4.0.0 * @category getters + * @since 4.0.0 */ const await_ = (self: TxDeferred): Effect.Effect => Effect.gen(function*() { @@ -131,8 +147,15 @@ export { * Reads the deferred value. Retries the transaction if the deferred has not * been completed yet. * - * @since 4.0.0 + * **When to use** + * + * Use to read the success value of a `TxDeferred` while retrying until the + * deferred is completed. + * + * @see {@link poll} for inspecting the current completion state without retrying the transaction + * * @category getters + * @since 4.0.0 */ await_ as await } @@ -141,7 +164,12 @@ export { * Reads the current state of the deferred without retrying. Returns `None` if * not yet completed. * - * @example + * **When to use** + * + * Use to inspect a `TxDeferred` without retrying when it is not completed yet. + * + * **Example** (Polling a deferred) + * * ```ts * import { Effect, Option, Result, TxDeferred } from "effect" * @@ -156,8 +184,8 @@ export { * }) * ``` * - * @since 4.0.0 * @category getters + * @since 2.0.0 */ export const poll = (self: TxDeferred): Effect.Effect>> => TxRef.get(self.ref) @@ -165,7 +193,12 @@ export const poll = (self: TxDeferred): Effect.Effect(self: TxDeferred): Effect.Effect(result: Result): (self: TxDeferred) => Effect.Effect /** * Completes the deferred with a `Result`. Returns `true` if this was the first * completion, `false` if already completed. * - * @example + * **When to use** + * + * Use to complete a `TxDeferred` with an already computed `Result`. + * + * **Example** (Completing with a result) + * * ```ts * import { Effect, Result, TxDeferred } from "effect" * @@ -220,8 +263,8 @@ export const done: { * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ (self: TxDeferred, result: Result): Effect.Effect } = dual( @@ -239,7 +282,12 @@ export const done: { * Completes the deferred with a success value. Returns `true` if this was the * first completion, `false` if already completed. * - * @example + * **When to use** + * + * Use to complete a `TxDeferred` with a successful value. + * + * **Example** (Completing with a success value) + * * ```ts * import { Effect, TxDeferred } from "effect" * @@ -252,15 +300,20 @@ export const done: { * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ export const succeed: { /** * Completes the deferred with a success value. Returns `true` if this was the * first completion, `false` if already completed. * - * @example + * **When to use** + * + * Use to complete a `TxDeferred` with a successful value. + * + * **Example** (Completing with a success value) + * * ```ts * import { Effect, TxDeferred } from "effect" * @@ -273,15 +326,20 @@ export const succeed: { * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ (value: A): (self: TxDeferred) => Effect.Effect /** * Completes the deferred with a success value. Returns `true` if this was the * first completion, `false` if already completed. * - * @example + * **When to use** + * + * Use to complete a `TxDeferred` with a successful value. + * + * **Example** (Completing with a success value) + * * ```ts * import { Effect, TxDeferred } from "effect" * @@ -294,8 +352,8 @@ export const succeed: { * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ (self: TxDeferred, value: A): Effect.Effect } = dual( @@ -307,7 +365,12 @@ export const succeed: { * Completes the deferred with a failure. Returns `true` if this was the first * completion, `false` if already completed. * - * @example + * **When to use** + * + * Use to complete a `TxDeferred` with a typed failure value. + * + * **Example** (Completing with a failure) + * * ```ts * import { Effect, TxDeferred } from "effect" * @@ -320,15 +383,20 @@ export const succeed: { * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ export const fail: { /** * Completes the deferred with a failure. Returns `true` if this was the first * completion, `false` if already completed. * - * @example + * **When to use** + * + * Use to complete a `TxDeferred` with a typed failure value. + * + * **Example** (Completing with a failure) + * * ```ts * import { Effect, TxDeferred } from "effect" * @@ -341,15 +409,20 @@ export const fail: { * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ (error: E): (self: TxDeferred) => Effect.Effect /** * Completes the deferred with a failure. Returns `true` if this was the first * completion, `false` if already completed. * - * @example + * **When to use** + * + * Use to complete a `TxDeferred` with a typed failure value. + * + * **Example** (Completing with a failure) + * * ```ts * import { Effect, TxDeferred } from "effect" * @@ -362,8 +435,8 @@ export const fail: { * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ (self: TxDeferred, error: E): Effect.Effect } = dual( @@ -374,7 +447,12 @@ export const fail: { /** * Determines if the provided value is a `TxDeferred`. * - * @example + * **When to use** + * + * Use to narrow an unknown value before treating it as a transactional deferred. + * + * **Example** (Checking transactional deferreds) + * * ```ts * import { Effect, TxDeferred } from "effect" * @@ -385,7 +463,7 @@ export const fail: { * }) * ``` * - * @since 4.0.0 * @category guards + * @since 4.0.0 */ export const isTxDeferred = (u: unknown): u is TxDeferred => hasProperty(u, TypeId) diff --git a/.opencode/node_modules/effect/src/TxHashMap.ts b/.opencode/node_modules/effect/src/TxHashMap.ts index 300645376dc0669508e0a7b3a8619f2094a3e9a7..0348912e5c2c4892c5fc5dfeb634f15ed9430233 100644 --- a/.opencode/node_modules/effect/src/TxHashMap.ts +++ b/.opencode/node_modules/effect/src/TxHashMap.ts @@ -1,4 +1,12 @@ /** + * Transactional hash maps for storing and updating key-value pairs inside + * Effect transactions. + * + * A `TxHashMap` stores an immutable `HashMap` in a `TxRef`, so map reads and + * writes can commit atomically with other transactional operations. Use it for + * shared registries, counters, indexes, and other maps that need safe + * read-modify-write sequences alongside related transactional state. + * * @since 2.0.0 */ @@ -41,7 +49,8 @@ const TxHashMapProto = { * on key-value pairs within Effect transactions. It uses an immutable HashMap internally * with TxRef for transactional semantics, ensuring all operations are performed atomically. * - * @example + * **Example** (Using transactional hash maps) + * * ```ts * import { Effect, TxHashMap } from "effect" * @@ -70,8 +79,8 @@ const TxHashMapProto = { * }) * ``` * - * @since 2.0.0 * @category models + * @since 4.0.0 */ export interface TxHashMap extends Inspectable, Pipeable { readonly [TypeId]: typeof TypeId @@ -82,7 +91,8 @@ export interface TxHashMap extends Inspectable, Pipeable { * The TxHashMap namespace contains type-level utilities and helper types * for working with TxHashMap instances. * - * @example + * **Example** (Reusing extracted TxHashMap types) + * * ```ts * import { Effect, TxHashMap } from "effect" * @@ -110,14 +120,14 @@ export interface TxHashMap extends Inspectable, Pipeable { * }) * ``` * - * @since 2.0.0 - * @category models + * @since 4.0.0 */ export declare namespace TxHashMap { /** * Extracts the key type from a TxHashMap type. * - * @example + * **Example** (Extracting key types) + * * ```ts * import { Effect, TxHashMap } from "effect" * @@ -137,15 +147,16 @@ export declare namespace TxHashMap { * }) * ``` * - * @since 2.0.0 - * @category type-level + * @category utility types + * @since 4.0.0 */ export type Key> = T extends TxHashMap ? K : never /** * Extracts the value type from a TxHashMap type. * - * @example + * **Example** (Extracting value types) + * * ```ts * import { Effect, TxHashMap } from "effect" * @@ -169,15 +180,16 @@ export declare namespace TxHashMap { * }) * ``` * - * @since 2.0.0 - * @category type-level + * @category utility types + * @since 4.0.0 */ export type Value> = T extends TxHashMap ? V : never /** * Extracts the entry type from a TxHashMap type. * - * @example + * **Example** (Extracting entry types) + * * ```ts * import { Effect, TxHashMap } from "effect" * @@ -204,8 +216,8 @@ export declare namespace TxHashMap { * }) * ``` * - * @since 2.0.0 - * @category type-level + * @category utility types + * @since 4.0.0 */ export type Entry> = T extends TxHashMap ? readonly [K, V] : never } @@ -213,7 +225,8 @@ export declare namespace TxHashMap { /** * Creates an empty TxHashMap. * - * @example + * **Example** (Creating an empty map) + * * ```ts * import { Effect, TxHashMap } from "effect" * @@ -235,8 +248,8 @@ export declare namespace TxHashMap { * }) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const empty = (): Effect.Effect> => Effect.gen(function*() { @@ -247,7 +260,8 @@ export const empty = (): Effect.Effect> => /** * Creates a TxHashMap from the provided key-value pairs. * - * @example + * **Example** (Creating a map from entries) + * * ```ts * import { Effect, TxHashMap } from "effect" * @@ -272,8 +286,8 @@ export const empty = (): Effect.Effect> => * }) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const make = ( ...entries: Array @@ -287,7 +301,8 @@ export const make = ( /** * Creates a TxHashMap from an iterable of key-value pairs. * - * @example + * **Example** (Creating a map from an iterable) + * * ```ts * import { Effect, TxHashMap } from "effect" * @@ -315,8 +330,8 @@ export const make = ( * }) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const fromIterable = ( entries: Iterable @@ -328,9 +343,10 @@ export const fromIterable = ( }) /** - * Safely lookup the value for the specified key in the TxHashMap. + * Looks up the value for the specified key in the TxHashMap. + * + * **Example** (Looking up values safely) * - * @example * ```ts * import { Effect, Option, TxHashMap } from "effect" * @@ -355,14 +371,15 @@ export const fromIterable = ( * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const get: { /** - * Safely lookup the value for the specified key in the TxHashMap. + * Looks up the value for the specified key in the TxHashMap. + * + * **Example** (Looking up values safely) * - * @example * ```ts * import { Effect, Option, TxHashMap } from "effect" * @@ -387,14 +404,15 @@ export const get: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (key: K1): (self: TxHashMap) => Effect.Effect> /** - * Safely lookup the value for the specified key in the TxHashMap. + * Looks up the value for the specified key in the TxHashMap. + * + * **Example** (Looking up values safely) * - * @example * ```ts * import { Effect, Option, TxHashMap } from "effect" * @@ -419,8 +437,8 @@ export const get: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (self: TxHashMap, key: K1): Effect.Effect> } = dual( @@ -435,10 +453,13 @@ export const get: { /** * Sets the value for the specified key in the TxHashMap. * - * **Mutation behavior**: This function mutates the original TxHashMap by updating - * its internal state. It does not return a new TxHashMap reference. + * **Details** + * + * This function mutates the original TxHashMap by updating its internal state. + * It does not return a new TxHashMap reference. + * + * **Example** (Setting values) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -463,17 +484,20 @@ export const get: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const set: { /** * Sets the value for the specified key in the TxHashMap. * - * **Mutation behavior**: This function mutates the original TxHashMap by updating - * its internal state. It does not return a new TxHashMap reference. + * **Details** + * + * This function mutates the original TxHashMap by updating its internal state. + * It does not return a new TxHashMap reference. + * + * **Example** (Setting values) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -498,17 +522,20 @@ export const set: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (key: K, value: V): (self: TxHashMap) => Effect.Effect /** * Sets the value for the specified key in the TxHashMap. * - * **Mutation behavior**: This function mutates the original TxHashMap by updating - * its internal state. It does not return a new TxHashMap reference. + * **Details** + * + * This function mutates the original TxHashMap by updating its internal state. + * It does not return a new TxHashMap reference. + * + * **Example** (Setting values) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -533,8 +560,8 @@ export const set: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (self: TxHashMap, key: K, value: V): Effect.Effect } = dual( @@ -544,9 +571,10 @@ export const set: { ) /** - * Checks if the specified key exists in the TxHashMap. + * Checks whether the specified key exists in the TxHashMap. + * + * **Example** (Checking for keys) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -570,14 +598,15 @@ export const set: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const has: { /** - * Checks if the specified key exists in the TxHashMap. + * Checks whether the specified key exists in the TxHashMap. + * + * **Example** (Checking for keys) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -601,14 +630,15 @@ export const has: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (key: K1): (self: TxHashMap) => Effect.Effect /** - * Checks if the specified key exists in the TxHashMap. + * Checks whether the specified key exists in the TxHashMap. + * + * **Example** (Checking for keys) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -632,8 +662,8 @@ export const has: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (self: TxHashMap, key: K1): Effect.Effect } = dual( @@ -648,10 +678,13 @@ export const has: { /** * Removes the specified key from the TxHashMap. * - * **Mutation behavior**: This function mutates the original TxHashMap by removing - * the specified key-value pair. It does not return a new TxHashMap reference. + * **Details** + * + * This function mutates the original TxHashMap by removing the specified + * key-value pair. It does not return a new TxHashMap reference. + * + * **Example** (Removing keys) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -679,17 +712,20 @@ export const has: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const remove: { /** * Removes the specified key from the TxHashMap. * - * **Mutation behavior**: This function mutates the original TxHashMap by removing - * the specified key-value pair. It does not return a new TxHashMap reference. + * **Details** + * + * This function mutates the original TxHashMap by removing the specified + * key-value pair. It does not return a new TxHashMap reference. + * + * **Example** (Removing keys) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -717,17 +753,20 @@ export const remove: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (key: K1): (self: TxHashMap) => Effect.Effect /** * Removes the specified key from the TxHashMap. * - * **Mutation behavior**: This function mutates the original TxHashMap by removing - * the specified key-value pair. It does not return a new TxHashMap reference. + * **Details** + * + * This function mutates the original TxHashMap by removing the specified + * key-value pair. It does not return a new TxHashMap reference. + * + * **Example** (Removing keys) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -755,8 +794,8 @@ export const remove: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (self: TxHashMap, key: K1): Effect.Effect } = dual( @@ -775,10 +814,13 @@ export const remove: { /** * Removes all entries from the TxHashMap. * - * **Mutation behavior**: This function mutates the original TxHashMap by clearing - * all key-value pairs. It does not return a new TxHashMap reference. + * **Details** + * + * This function mutates the original TxHashMap by clearing all key-value pairs. + * It does not return a new TxHashMap reference. + * + * **Example** (Clearing all entries) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -805,15 +847,16 @@ export const remove: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ export const clear = (self: TxHashMap): Effect.Effect => TxRef.set(self.ref, HashMap.empty()) /** * Returns the number of entries in the TxHashMap. * - * @example + * **Example** (Counting entries) + * * ```ts * import { Effect, TxHashMap } from "effect" * @@ -839,8 +882,8 @@ export const clear = (self: TxHashMap): Effect.Effect => TxRef * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const size = (self: TxHashMap): Effect.Effect => Effect.gen(function*() { @@ -849,9 +892,10 @@ export const size = (self: TxHashMap): Effect.Effect => }) /** - * Checks if the TxHashMap is empty. + * Checks whether the TxHashMap is empty. + * + * **Example** (Checking for an empty map) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -873,8 +917,8 @@ export const size = (self: TxHashMap): Effect.Effect => * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const isEmpty = (self: TxHashMap): Effect.Effect => Effect.gen(function*() { @@ -883,9 +927,10 @@ export const isEmpty = (self: TxHashMap): Effect.Effect => }) /** - * Checks if the TxHashMap is non-empty. + * Checks whether the TxHashMap is non-empty. + * + * **Example** (Checking for a non-empty map) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -902,19 +947,22 @@ export const isEmpty = (self: TxHashMap): Effect.Effect => * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ export const isNonEmpty = (self: TxHashMap): Effect.Effect => Effect.map(isEmpty(self), (empty) => !empty) /** - * Updates the value for the specified key if it exists. + * Updates the value for the specified key if it exists, returning the previous value in `Some`; returns `None` and leaves the map unchanged when the key is absent. * - * **Mutation behavior**: This function mutates the original TxHashMap by updating - * the value at the specified key. It does not return a new TxHashMap reference. + * **Details** + * + * This function mutates the original TxHashMap by updating the value at the + * specified key. It does not return a new TxHashMap reference. + * + * **Example** (Updating existing values) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -948,17 +996,20 @@ export const isNonEmpty = (self: TxHashMap): Effect.Effect * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ export const modify: { /** - * Updates the value for the specified key if it exists. + * Updates the value for the specified key if it exists, returning the previous value in `Some`; returns `None` and leaves the map unchanged when the key is absent. + * + * **Details** * - * **Mutation behavior**: This function mutates the original TxHashMap by updating - * the value at the specified key. It does not return a new TxHashMap reference. + * This function mutates the original TxHashMap by updating the value at the + * specified key. It does not return a new TxHashMap reference. + * + * **Example** (Updating existing values) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -992,17 +1043,20 @@ export const modify: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ (key: K, f: (value: V) => V): (self: TxHashMap) => Effect.Effect> /** - * Updates the value for the specified key if it exists. + * Updates the value for the specified key if it exists, returning the previous value in `Some`; returns `None` and leaves the map unchanged when the key is absent. + * + * **Details** + * + * This function mutates the original TxHashMap by updating the value at the + * specified key. It does not return a new TxHashMap reference. * - * **Mutation behavior**: This function mutates the original TxHashMap by updating - * the value at the specified key. It does not return a new TxHashMap reference. + * **Example** (Updating existing values) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -1036,8 +1090,8 @@ export const modify: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ (self: TxHashMap, key: K, f: (value: V) => V): Effect.Effect> } = dual( @@ -1062,11 +1116,14 @@ export const modify: { /** * Updates the value for the specified key using an Option-based update function. * - * **Mutation behavior**: This function mutates the original TxHashMap by updating, - * adding, or removing the key-value pair based on the function result. It does not - * return a new TxHashMap reference. + * **Details** + * + * This function mutates the original TxHashMap by updating, adding, or removing + * the key-value pair based on the function result. It does not return a new + * TxHashMap reference. + * + * **Example** (Updating values with Option) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -1105,18 +1162,21 @@ export const modify: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ export const modifyAt: { /** * Updates the value for the specified key using an Option-based update function. * - * **Mutation behavior**: This function mutates the original TxHashMap by updating, - * adding, or removing the key-value pair based on the function result. It does not - * return a new TxHashMap reference. + * **Details** + * + * This function mutates the original TxHashMap by updating, adding, or removing + * the key-value pair based on the function result. It does not return a new + * TxHashMap reference. + * + * **Example** (Updating values with Option) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -1155,18 +1215,21 @@ export const modifyAt: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ (key: K, f: (value: Option.Option) => Option.Option): (self: TxHashMap) => Effect.Effect /** * Updates the value for the specified key using an Option-based update function. * - * **Mutation behavior**: This function mutates the original TxHashMap by updating, - * adding, or removing the key-value pair based on the function result. It does not - * return a new TxHashMap reference. + * **Details** + * + * This function mutates the original TxHashMap by updating, adding, or removing + * the key-value pair based on the function result. It does not return a new + * TxHashMap reference. + * + * **Example** (Updating values with Option) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -1205,8 +1268,8 @@ export const modifyAt: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ ( self: TxHashMap, @@ -1236,7 +1299,8 @@ export const modifyAt: { /** * Returns an array of all keys in the TxHashMap. * - * @example + * **Example** (Reading keys) + * * ```ts * import { Effect, Option, TxHashMap } from "effect" * @@ -1260,8 +1324,8 @@ export const modifyAt: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const keys = (self: TxHashMap): Effect.Effect> => Effect.gen(function*() { @@ -1272,7 +1336,8 @@ export const keys = (self: TxHashMap): Effect.Effect> => /** * Returns an array of all values in the TxHashMap. * - * @example + * **Example** (Reading values) + * * ```ts * import { Effect, TxHashMap } from "effect" * @@ -1284,12 +1349,12 @@ export const keys = (self: TxHashMap): Effect.Effect> => * ) * * const allScores = yield* TxHashMap.values(scores) - * console.log(allScores.sort()) // [87, 92, 95] + * console.log(allScores.sort((a, b) => a - b)) // [87, 92, 95] * * // Calculate average * const average = allScores.reduce((sum, score) => sum + score, 0) / * allScores.length - * console.log(average) // 91.33 + * console.log(average.toFixed(2)) // "91.33" * * // Find maximum * const maxScore = Math.max(...allScores) @@ -1297,8 +1362,8 @@ export const keys = (self: TxHashMap): Effect.Effect> => * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const values = (self: TxHashMap): Effect.Effect> => Effect.gen(function*() { @@ -1309,7 +1374,8 @@ export const values = (self: TxHashMap): Effect.Effect> => /** * Returns an array of all key-value pairs in the TxHashMap. * - * @example + * **Example** (Reading entries) + * * ```ts * import { Effect, TxHashMap } from "effect" * @@ -1321,11 +1387,12 @@ export const values = (self: TxHashMap): Effect.Effect> => * ) * * const allEntries = yield* TxHashMap.entries(config) - * console.log(allEntries) + * const sortedEntries = allEntries.toSorted(([left], [right]) => left.localeCompare(right)) + * console.log(sortedEntries) * // [["host", "localhost"], ["port", "3000"], ["ssl", "false"]] * * // Process configuration entries - * for (const [key, value] of allEntries) { + * for (const [key, value] of sortedEntries) { * console.log(`${key}=${value}`) * } * // host=localhost @@ -1334,8 +1401,8 @@ export const values = (self: TxHashMap): Effect.Effect> => * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ export const entries = ( self: TxHashMap @@ -1348,7 +1415,8 @@ export const entries = ( /** * Returns an immutable snapshot of the current TxHashMap state. * - * @example + * **Example** (Taking immutable snapshots) + * * ```ts * import { Effect, HashMap, TxHashMap } from "effect" * @@ -1376,8 +1444,8 @@ export const entries = ( * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ export const snapshot = ( self: TxHashMap @@ -1387,10 +1455,13 @@ export const snapshot = ( * Merges another HashMap into this TxHashMap. If both maps contain the same key, * the value from the other map will be used. * - * **Mutation behavior**: This function mutates the original TxHashMap by merging - * the provided HashMap into it. It does not return a new TxHashMap reference. + * **Details** + * + * This function mutates the original TxHashMap by merging the provided HashMap + * into it. It does not return a new TxHashMap reference. + * + * **Example** (Merging HashMaps) * - * @example * ```ts * import { Effect, HashMap, TxHashMap } from "effect" * @@ -1427,18 +1498,21 @@ export const snapshot = ( * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ export const union: { /** * Merges another HashMap into this TxHashMap. If both maps contain the same key, * the value from the other map will be used. * - * **Mutation behavior**: This function mutates the original TxHashMap by merging - * the provided HashMap into it. It does not return a new TxHashMap reference. + * **Details** + * + * This function mutates the original TxHashMap by merging the provided HashMap + * into it. It does not return a new TxHashMap reference. + * + * **Example** (Merging HashMaps) * - * @example * ```ts * import { Effect, HashMap, TxHashMap } from "effect" * @@ -1475,18 +1549,21 @@ export const union: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ (other: HashMap.HashMap): (self: TxHashMap) => Effect.Effect /** * Merges another HashMap into this TxHashMap. If both maps contain the same key, * the value from the other map will be used. * - * **Mutation behavior**: This function mutates the original TxHashMap by merging - * the provided HashMap into it. It does not return a new TxHashMap reference. + * **Details** + * + * This function mutates the original TxHashMap by merging the provided HashMap + * into it. It does not return a new TxHashMap reference. + * + * **Example** (Merging HashMaps) * - * @example * ```ts * import { Effect, HashMap, TxHashMap } from "effect" * @@ -1523,8 +1600,8 @@ export const union: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ (self: TxHashMap, other: HashMap.HashMap): Effect.Effect } = dual( @@ -1538,10 +1615,13 @@ export const union: { /** * Removes multiple keys from the TxHashMap. * - * **Mutation behavior**: This function mutates the original TxHashMap by removing - * all specified keys. It does not return a new TxHashMap reference. + * **Details** + * + * This function mutates the original TxHashMap by removing all specified keys. + * It does not return a new TxHashMap reference. + * + * **Example** (Removing multiple keys) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -1574,17 +1654,20 @@ export const union: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ export const removeMany: { /** * Removes multiple keys from the TxHashMap. * - * **Mutation behavior**: This function mutates the original TxHashMap by removing - * all specified keys. It does not return a new TxHashMap reference. + * **Details** + * + * This function mutates the original TxHashMap by removing all specified keys. + * It does not return a new TxHashMap reference. + * + * **Example** (Removing multiple keys) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -1617,17 +1700,20 @@ export const removeMany: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ (keys: Iterable): (self: TxHashMap) => Effect.Effect /** * Removes multiple keys from the TxHashMap. * - * **Mutation behavior**: This function mutates the original TxHashMap by removing - * all specified keys. It does not return a new TxHashMap reference. + * **Details** + * + * This function mutates the original TxHashMap by removing all specified keys. + * It does not return a new TxHashMap reference. + * + * **Example** (Removing multiple keys) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -1660,8 +1746,8 @@ export const removeMany: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ (self: TxHashMap, keys: Iterable): Effect.Effect } = dual( @@ -1673,10 +1759,13 @@ export const removeMany: { /** * Sets multiple key-value pairs in the TxHashMap. * - * **Mutation behavior**: This function mutates the original TxHashMap by setting - * all provided key-value pairs. It does not return a new TxHashMap reference. + * **Details** + * + * This function mutates the original TxHashMap by setting all provided key-value + * pairs. It does not return a new TxHashMap reference. + * + * **Example** (Setting multiple entries) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -1724,17 +1813,20 @@ export const removeMany: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ export const setMany: { /** * Sets multiple key-value pairs in the TxHashMap. * - * **Mutation behavior**: This function mutates the original TxHashMap by setting - * all provided key-value pairs. It does not return a new TxHashMap reference. + * **Details** + * + * This function mutates the original TxHashMap by setting all provided key-value + * pairs. It does not return a new TxHashMap reference. + * + * **Example** (Setting multiple entries) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -1782,17 +1874,20 @@ export const setMany: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ (entries: Iterable): (self: TxHashMap) => Effect.Effect /** * Sets multiple key-value pairs in the TxHashMap. * - * **Mutation behavior**: This function mutates the original TxHashMap by setting - * all provided key-value pairs. It does not return a new TxHashMap reference. + * **Details** + * + * This function mutates the original TxHashMap by setting all provided key-value + * pairs. It does not return a new TxHashMap reference. + * + * **Example** (Setting multiple entries) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -1840,8 +1935,8 @@ export const setMany: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ (self: TxHashMap, entries: Iterable): Effect.Effect } = dual( @@ -1855,7 +1950,8 @@ export const setMany: { /** * Returns `true` if the specified value is a `TxHashMap`, `false` otherwise. * - * @example + * **Example** (Checking TxHashMap values) + * * ```ts * import { Effect, TxHashMap } from "effect" * @@ -1878,26 +1974,32 @@ export const setMany: { * }) * ``` * - * @since 2.0.0 * @category guards + * @since 4.0.0 */ export const isTxHashMap = (value: unknown): value is TxHashMap => { return hasProperty(value, TypeId) } /** - * Lookup the value for the specified key in the TxHashMap using a custom hash. - * This can provide performance benefits when the hash is precomputed. + * Looks up the value for the specified key using a caller-supplied hash. + * + * **Gotchas** + * + * The supplied hash must be the hash for the same key, such as a precomputed + * `Hash.hash(key)` value. If the hash does not match the key, an existing entry + * may not be found. + * + * **Example** (Looking up values with precomputed hashes) * - * @example * ```ts * import { Effect, Hash, TxHashMap } from "effect" * * const program = Effect.gen(function*() { * // Create a cache with user sessions * const cache = yield* TxHashMap.make( - * ["session_abc123", { userId: "user1", lastActive: Date.now() }], - * ["session_def456", { userId: "user2", lastActive: Date.now() }] + * ["session_abc123", { userId: "user1", lastActive: 1_700_000_000_000 }], + * ["session_def456", { userId: "user2", lastActive: 1_700_000_060_000 }] * ) * * // When you have precomputed hash (e.g., from another lookup) @@ -1918,23 +2020,29 @@ export const isTxHashMap = (value: unknown): value is TxHashMap => { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ export const getHash: { /** - * Lookup the value for the specified key in the TxHashMap using a custom hash. - * This can provide performance benefits when the hash is precomputed. + * Looks up the value for the specified key using a caller-supplied hash. + * + * **Gotchas** + * + * The supplied hash must be the hash for the same key, such as a precomputed + * `Hash.hash(key)` value. If the hash does not match the key, an existing entry + * may not be found. + * + * **Example** (Looking up values with precomputed hashes) * - * @example * ```ts * import { Effect, Hash, TxHashMap } from "effect" * * const program = Effect.gen(function*() { * // Create a cache with user sessions * const cache = yield* TxHashMap.make( - * ["session_abc123", { userId: "user1", lastActive: Date.now() }], - * ["session_def456", { userId: "user2", lastActive: Date.now() }] + * ["session_abc123", { userId: "user1", lastActive: 1_700_000_000_000 }], + * ["session_def456", { userId: "user2", lastActive: 1_700_000_060_000 }] * ) * * // When you have precomputed hash (e.g., from another lookup) @@ -1955,23 +2063,29 @@ export const getHash: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ (key: K1, hash: number): (self: TxHashMap) => Effect.Effect> /** - * Lookup the value for the specified key in the TxHashMap using a custom hash. - * This can provide performance benefits when the hash is precomputed. + * Looks up the value for the specified key using a caller-supplied hash. + * + * **Gotchas** + * + * The supplied hash must be the hash for the same key, such as a precomputed + * `Hash.hash(key)` value. If the hash does not match the key, an existing entry + * may not be found. + * + * **Example** (Looking up values with precomputed hashes) * - * @example * ```ts * import { Effect, Hash, TxHashMap } from "effect" * * const program = Effect.gen(function*() { * // Create a cache with user sessions * const cache = yield* TxHashMap.make( - * ["session_abc123", { userId: "user1", lastActive: Date.now() }], - * ["session_def456", { userId: "user2", lastActive: Date.now() }] + * ["session_abc123", { userId: "user1", lastActive: 1_700_000_000_000 }], + * ["session_def456", { userId: "user2", lastActive: 1_700_000_060_000 }] * ) * * // When you have precomputed hash (e.g., from another lookup) @@ -1992,8 +2106,8 @@ export const getHash: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ (self: TxHashMap, key: K1, hash: number): Effect.Effect> } = dual( @@ -2006,10 +2120,16 @@ export const getHash: { ) /** - * Checks if the specified key has an entry in the TxHashMap using a custom hash. - * This can provide performance benefits when the hash is precomputed. + * Checks whether the specified key has an entry using a caller-supplied hash. + * + * **Gotchas** + * + * The supplied hash must be the hash for the same key, such as a precomputed + * `Hash.hash(key)` value. If the hash does not match the key, an existing entry + * may not be found. + * + * **Example** (Checking keys with precomputed hashes) * - * @example * ```ts * import { Effect, Hash, TxHashMap } from "effect" * @@ -2047,15 +2167,21 @@ export const getHash: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ export const hasHash: { /** - * Checks if the specified key has an entry in the TxHashMap using a custom hash. - * This can provide performance benefits when the hash is precomputed. + * Checks whether the specified key has an entry using a caller-supplied hash. + * + * **Gotchas** + * + * The supplied hash must be the hash for the same key, such as a precomputed + * `Hash.hash(key)` value. If the hash does not match the key, an existing entry + * may not be found. + * + * **Example** (Checking keys with precomputed hashes) * - * @example * ```ts * import { Effect, Hash, TxHashMap } from "effect" * @@ -2093,15 +2219,21 @@ export const hasHash: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ (key: K1, hash: number): (self: TxHashMap) => Effect.Effect /** - * Checks if the specified key has an entry in the TxHashMap using a custom hash. - * This can provide performance benefits when the hash is precomputed. + * Checks whether the specified key has an entry using a caller-supplied hash. + * + * **Gotchas** + * + * The supplied hash must be the hash for the same key, such as a precomputed + * `Hash.hash(key)` value. If the hash does not match the key, an existing entry + * may not be found. + * + * **Example** (Checking keys with precomputed hashes) * - * @example * ```ts * import { Effect, Hash, TxHashMap } from "effect" * @@ -2139,8 +2271,8 @@ export const hasHash: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ (self: TxHashMap, key: K1, hash: number): Effect.Effect } = dual( @@ -2155,10 +2287,13 @@ export const hasHash: { /** * Transforms all values in the TxHashMap using the provided function, preserving keys. * - * **Return behavior**: This function returns a new TxHashMap reference with the - * transformed values. The original TxHashMap is not modified. + * **Details** + * + * This function returns a new TxHashMap reference with the transformed values. + * The original TxHashMap is not modified. + * + * **Example** (Mapping values) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -2194,17 +2329,20 @@ export const hasHash: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ export const map: { /** * Transforms all values in the TxHashMap using the provided function, preserving keys. * - * **Return behavior**: This function returns a new TxHashMap reference with the - * transformed values. The original TxHashMap is not modified. + * **Details** + * + * This function returns a new TxHashMap reference with the transformed values. + * The original TxHashMap is not modified. + * + * **Example** (Mapping values) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -2240,17 +2378,20 @@ export const map: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ (f: (value: V, key: K) => A): (self: TxHashMap) => Effect.Effect> /** * Transforms all values in the TxHashMap using the provided function, preserving keys. * - * **Return behavior**: This function returns a new TxHashMap reference with the - * transformed values. The original TxHashMap is not modified. + * **Details** + * + * This function returns a new TxHashMap reference with the transformed values. + * The original TxHashMap is not modified. + * + * **Example** (Mapping values) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -2286,8 +2427,8 @@ export const map: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ (self: TxHashMap, f: (value: V, key: K) => A): Effect.Effect> } = dual( @@ -2306,10 +2447,13 @@ export const map: { /** * Filters the TxHashMap to keep only entries that satisfy the provided predicate. * - * **Return behavior**: This function returns a new TxHashMap reference containing - * only the entries that match the condition. The original TxHashMap is not modified. + * **Details** + * + * This function returns a new TxHashMap reference containing only the entries + * that match the condition. The original TxHashMap is not modified. + * + * **Example** (Filtering entries) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -2348,17 +2492,20 @@ export const map: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ export const filter: { /** * Filters the TxHashMap to keep only entries that satisfy the provided predicate. * - * **Return behavior**: This function returns a new TxHashMap reference containing - * only the entries that match the condition. The original TxHashMap is not modified. + * **Details** + * + * This function returns a new TxHashMap reference containing only the entries + * that match the condition. The original TxHashMap is not modified. + * + * **Example** (Filtering entries) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -2397,17 +2544,20 @@ export const filter: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ (predicate: (value: V, key: K) => value is B): (self: TxHashMap) => Effect.Effect> /** * Filters the TxHashMap to keep only entries that satisfy the provided predicate. * - * **Return behavior**: This function returns a new TxHashMap reference containing - * only the entries that match the condition. The original TxHashMap is not modified. + * **Details** + * + * This function returns a new TxHashMap reference containing only the entries + * that match the condition. The original TxHashMap is not modified. + * + * **Example** (Filtering entries) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -2446,17 +2596,20 @@ export const filter: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ (predicate: (value: V, key: K) => boolean): (self: TxHashMap) => Effect.Effect> /** * Filters the TxHashMap to keep only entries that satisfy the provided predicate. * - * **Return behavior**: This function returns a new TxHashMap reference containing - * only the entries that match the condition. The original TxHashMap is not modified. + * **Details** + * + * This function returns a new TxHashMap reference containing only the entries + * that match the condition. The original TxHashMap is not modified. + * + * **Example** (Filtering entries) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -2495,17 +2648,20 @@ export const filter: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ (self: TxHashMap, predicate: (value: V, key: K) => value is B): Effect.Effect> /** * Filters the TxHashMap to keep only entries that satisfy the provided predicate. * - * **Return behavior**: This function returns a new TxHashMap reference containing - * only the entries that match the condition. The original TxHashMap is not modified. + * **Details** + * + * This function returns a new TxHashMap reference containing only the entries + * that match the condition. The original TxHashMap is not modified. + * + * **Example** (Filtering entries) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -2544,8 +2700,8 @@ export const filter: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ (self: TxHashMap, predicate: (value: V, key: K) => boolean): Effect.Effect> } = dual( @@ -2565,7 +2721,8 @@ export const filter: { * Reduces the TxHashMap entries to a single value by applying a reducer function. * Iterates over all key-value pairs and accumulates them into a final result. * - * @example + * **Example** (Reducing entries) + * * ```ts * import { Effect, TxHashMap } from "effect" * @@ -2612,15 +2769,16 @@ export const filter: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const reduce: { /** * Reduces the TxHashMap entries to a single value by applying a reducer function. * Iterates over all key-value pairs and accumulates them into a final result. * - * @example + * **Example** (Reducing entries) + * * ```ts * import { Effect, TxHashMap } from "effect" * @@ -2667,15 +2825,16 @@ export const reduce: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (zero: A, f: (accumulator: A, value: V, key: K) => A): (self: TxHashMap) => Effect.Effect /** * Reduces the TxHashMap entries to a single value by applying a reducer function. * Iterates over all key-value pairs and accumulates them into a final result. * - * @example + * **Example** (Reducing entries) + * * ```ts * import { Effect, TxHashMap } from "effect" * @@ -2722,8 +2881,8 @@ export const reduce: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (self: TxHashMap, zero: A, f: (accumulator: A, value: V, key: K) => A): Effect.Effect } = dual( @@ -2739,10 +2898,13 @@ export const reduce: { * Combines filtering and mapping in a single operation. Applies a filter to each * entry, keeping only successful results and transforming them. * - * **Return behavior**: This function returns a new TxHashMap reference containing - * only the transformed entries that succeeded. The original TxHashMap is not modified. + * **Details** + * + * This function returns a new TxHashMap reference containing only the transformed + * entries that succeeded. The original TxHashMap is not modified. + * + * **Example** (Filtering and mapping entries) * - * @example * ```ts * import { Effect, Option, Result, TxHashMap } from "effect" * @@ -2789,18 +2951,21 @@ export const reduce: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ export const filterMap: { /** * Combines filtering and mapping in a single operation. Applies a filter to each * entry, keeping only successful results and transforming them. * - * **Return behavior**: This function returns a new TxHashMap reference containing - * only the transformed entries that succeeded. The original TxHashMap is not modified. + * **Details** + * + * This function returns a new TxHashMap reference containing only the transformed + * entries that succeeded. The original TxHashMap is not modified. + * + * **Example** (Filtering and mapping entries) * - * @example * ```ts * import { Effect, Option, Result, TxHashMap } from "effect" * @@ -2847,18 +3012,21 @@ export const filterMap: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ (f: (input: V, key: K) => Result): (self: TxHashMap) => Effect.Effect> /** * Combines filtering and mapping in a single operation. Applies a filter to each * entry, keeping only successful results and transforming them. * - * **Return behavior**: This function returns a new TxHashMap reference containing - * only the transformed entries that succeeded. The original TxHashMap is not modified. + * **Details** + * + * This function returns a new TxHashMap reference containing only the transformed + * entries that succeeded. The original TxHashMap is not modified. + * + * **Example** (Filtering and mapping entries) * - * @example * ```ts * import { Effect, Option, Result, TxHashMap } from "effect" * @@ -2905,8 +3073,8 @@ export const filterMap: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ (self: TxHashMap, f: (input: V, key: K) => Result): Effect.Effect> } = dual( @@ -2923,18 +3091,20 @@ export const filterMap: { ) /** - * Checks if any entry in the TxHashMap matches the given predicate. + * Checks whether any entry in the TxHashMap matches the given predicate. + * + * **Example** (Checking entries with a predicate) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * * const program = Effect.gen(function*() { * // Create a user status map + * const currentTime = 1_700_000_000_000 * const userStatuses = yield* TxHashMap.make( - * ["alice", { status: "online", lastSeen: Date.now() }], - * ["bob", { status: "offline", lastSeen: Date.now() - 3600000 }], - * ["charlie", { status: "online", lastSeen: Date.now() }] + * ["alice", { status: "online", lastSeen: currentTime }], + * ["bob", { status: "offline", lastSeen: currentTime - 3_600_000 }], + * ["charlie", { status: "online", lastSeen: currentTime }] * ) * * // Check if any users are online @@ -2953,29 +3123,31 @@ export const filterMap: { * * // Data-last usage with pipe * const hasRecentActivity = yield* userStatuses.pipe( - * TxHashMap.hasBy((user) => Date.now() - user.lastSeen < 1800000) // 30 minutes + * TxHashMap.hasBy((user) => currentTime - user.lastSeen < 1_800_000) // 30 minutes * ) * console.log(hasRecentActivity) // true * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ export const hasBy: { /** - * Checks if any entry in the TxHashMap matches the given predicate. + * Checks whether any entry in the TxHashMap matches the given predicate. + * + * **Example** (Checking entries with a predicate) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * * const program = Effect.gen(function*() { * // Create a user status map + * const currentTime = 1_700_000_000_000 * const userStatuses = yield* TxHashMap.make( - * ["alice", { status: "online", lastSeen: Date.now() }], - * ["bob", { status: "offline", lastSeen: Date.now() - 3600000 }], - * ["charlie", { status: "online", lastSeen: Date.now() }] + * ["alice", { status: "online", lastSeen: currentTime }], + * ["bob", { status: "offline", lastSeen: currentTime - 3_600_000 }], + * ["charlie", { status: "online", lastSeen: currentTime }] * ) * * // Check if any users are online @@ -2994,29 +3166,31 @@ export const hasBy: { * * // Data-last usage with pipe * const hasRecentActivity = yield* userStatuses.pipe( - * TxHashMap.hasBy((user) => Date.now() - user.lastSeen < 1800000) // 30 minutes + * TxHashMap.hasBy((user) => currentTime - user.lastSeen < 1_800_000) // 30 minutes * ) * console.log(hasRecentActivity) // true * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ (predicate: (value: V, key: K) => boolean): (self: TxHashMap) => Effect.Effect /** - * Checks if any entry in the TxHashMap matches the given predicate. + * Checks whether any entry in the TxHashMap matches the given predicate. + * + * **Example** (Checking entries with a predicate) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * * const program = Effect.gen(function*() { * // Create a user status map + * const currentTime = 1_700_000_000_000 * const userStatuses = yield* TxHashMap.make( - * ["alice", { status: "online", lastSeen: Date.now() }], - * ["bob", { status: "offline", lastSeen: Date.now() - 3600000 }], - * ["charlie", { status: "online", lastSeen: Date.now() }] + * ["alice", { status: "online", lastSeen: currentTime }], + * ["bob", { status: "offline", lastSeen: currentTime - 3_600_000 }], + * ["charlie", { status: "online", lastSeen: currentTime }] * ) * * // Check if any users are online @@ -3035,14 +3209,14 @@ export const hasBy: { * * // Data-last usage with pipe * const hasRecentActivity = yield* userStatuses.pipe( - * TxHashMap.hasBy((user) => Date.now() - user.lastSeen < 1800000) // 30 minutes + * TxHashMap.hasBy((user) => currentTime - user.lastSeen < 1_800_000) // 30 minutes * ) * console.log(hasRecentActivity) // true * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ (self: TxHashMap, predicate: (value: V, key: K) => boolean): Effect.Effect } = dual( @@ -3057,7 +3231,8 @@ export const hasBy: { * Finds the first entry in the TxHashMap that matches the given predicate. * Returns the key-value pair as a tuple wrapped in an Option. * - * @example + * **Example** (Finding the first matching entry) + * * ```ts * import { Effect, TxHashMap } from "effect" * @@ -3092,15 +3267,16 @@ export const hasBy: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ export const findFirst: { /** * Finds the first entry in the TxHashMap that matches the given predicate. * Returns the key-value pair as a tuple wrapped in an Option. * - * @example + * **Example** (Finding the first matching entry) + * * ```ts * import { Effect, TxHashMap } from "effect" * @@ -3135,15 +3311,16 @@ export const findFirst: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ (predicate: (value: V, key: K) => boolean): (self: TxHashMap) => Effect.Effect> /** * Finds the first entry in the TxHashMap that matches the given predicate. * Returns the key-value pair as a tuple wrapped in an Option. * - * @example + * **Example** (Finding the first matching entry) + * * ```ts * import { Effect, TxHashMap } from "effect" * @@ -3178,8 +3355,8 @@ export const findFirst: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ (self: TxHashMap, predicate: (value: V, key: K) => boolean): Effect.Effect> } = dual( @@ -3192,9 +3369,10 @@ export const findFirst: { ) /** - * Checks if at least one entry in the TxHashMap satisfies the given predicate. + * Checks whether at least one entry in the TxHashMap satisfies the given predicate. + * + * **Example** (Checking whether some entries match) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -3228,14 +3406,15 @@ export const findFirst: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ export const some: { /** - * Checks if at least one entry in the TxHashMap satisfies the given predicate. + * Checks whether at least one entry in the TxHashMap satisfies the given predicate. + * + * **Example** (Checking whether some entries match) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -3269,14 +3448,15 @@ export const some: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ (predicate: (value: V, key: K) => boolean): (self: TxHashMap) => Effect.Effect /** - * Checks if at least one entry in the TxHashMap satisfies the given predicate. + * Checks whether at least one entry in the TxHashMap satisfies the given predicate. + * + * **Example** (Checking whether some entries match) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -3310,8 +3490,8 @@ export const some: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ (self: TxHashMap, predicate: (value: V, key: K) => boolean): Effect.Effect } = dual( @@ -3323,9 +3503,10 @@ export const some: { ) /** - * Checks if all entries in the TxHashMap satisfy the given predicate. + * Checks whether all entries in the TxHashMap satisfy the given predicate. + * + * **Example** (Checking whether every entry matches) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -3359,14 +3540,15 @@ export const some: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ export const every: { /** - * Checks if all entries in the TxHashMap satisfy the given predicate. + * Checks whether all entries in the TxHashMap satisfy the given predicate. + * + * **Example** (Checking whether every entry matches) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -3400,14 +3582,15 @@ export const every: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ (predicate: (value: V, key: K) => boolean): (self: TxHashMap) => Effect.Effect /** - * Checks if all entries in the TxHashMap satisfy the given predicate. + * Checks whether all entries in the TxHashMap satisfy the given predicate. + * + * **Example** (Checking whether every entry matches) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -3441,8 +3624,8 @@ export const every: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ (self: TxHashMap, predicate: (value: V, key: K) => boolean): Effect.Effect } = dual( @@ -3457,7 +3640,8 @@ export const every: { * Executes a side-effect function for each entry in the TxHashMap. * The function receives the value and key as parameters and can perform effects. * - * @example + * **Example** (Running effects for each entry) + * * ```ts * import { Console, Effect, TxHashMap } from "effect" * @@ -3491,15 +3675,16 @@ export const every: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const forEach: { /** * Executes a side-effect function for each entry in the TxHashMap. * The function receives the value and key as parameters and can perform effects. * - * @example + * **Example** (Running effects for each entry) + * * ```ts * import { Console, Effect, TxHashMap } from "effect" * @@ -3533,15 +3718,16 @@ export const forEach: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (f: (value: V, key: K) => Effect.Effect): (self: TxHashMap) => Effect.Effect /** * Executes a side-effect function for each entry in the TxHashMap. * The function receives the value and key as parameters and can perform effects. * - * @example + * **Example** (Running effects for each entry) + * * ```ts * import { Console, Effect, TxHashMap } from "effect" * @@ -3575,8 +3761,8 @@ export const forEach: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (self: TxHashMap, f: (value: V, key: K) => Effect.Effect): Effect.Effect } = dual( @@ -3593,13 +3779,15 @@ export const forEach: { ) /** - * Transforms the TxHashMap by applying a function that returns a TxHashMap to each entry, - * then flattening the results. Useful for complex transformations that require creating new maps. + * Maps each entry effectfully to a `TxHashMap` and flattens the produced maps. + * + * **Details** * - * **Return behavior**: This function returns a new TxHashMap reference with the - * flattened results. The original TxHashMap is not modified. + * This function returns a new TxHashMap reference with the flattened results. + * The original TxHashMap is not modified. + * + * **Example** (Flat mapping entries) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -3640,18 +3828,20 @@ export const forEach: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ export const flatMap: { /** - * Transforms the TxHashMap by applying a function that returns a TxHashMap to each entry, - * then flattening the results. Useful for complex transformations that require creating new maps. + * Maps each entry effectfully to a `TxHashMap` and flattens the produced maps. + * + * **Details** + * + * This function returns a new TxHashMap reference with the flattened results. + * The original TxHashMap is not modified. * - * **Return behavior**: This function returns a new TxHashMap reference with the - * flattened results. The original TxHashMap is not modified. + * **Example** (Flat mapping entries) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -3692,18 +3882,20 @@ export const flatMap: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ (f: (value: V, key: K) => Effect.Effect>): (self: TxHashMap) => Effect.Effect> /** - * Transforms the TxHashMap by applying a function that returns a TxHashMap to each entry, - * then flattening the results. Useful for complex transformations that require creating new maps. + * Maps each entry effectfully to a `TxHashMap` and flattens the produced maps. + * + * **Details** * - * **Return behavior**: This function returns a new TxHashMap reference with the - * flattened results. The original TxHashMap is not modified. + * This function returns a new TxHashMap reference with the flattened results. + * The original TxHashMap is not modified. + * + * **Example** (Flat mapping entries) * - * @example * ```ts * import { Effect, TxHashMap } from "effect" * @@ -3744,8 +3936,8 @@ export const flatMap: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ ( self: TxHashMap, @@ -3760,13 +3952,15 @@ export const flatMap: { Effect.gen(function*() { const currentMap = yield* TxRef.get(self.ref) const result = yield* empty() @@ -3877,10 +4073,13 @@ export const flatMap: { /** * Removes all None values from a TxHashMap containing Option values. * - * **Return behavior**: This function returns a new TxHashMap reference with only - * the Some values unwrapped. The original TxHashMap is not modified. + * **Details** + * + * This function returns a new TxHashMap reference with only the Some values + * unwrapped. The original TxHashMap is not modified. + * + * **Example** (Compacting optional values) * - * @example * ```ts * import { Effect, Option, TxHashMap } from "effect" * @@ -3912,12 +4111,13 @@ export const flatMap: { * // Useful for cleaning up optional data processing results * const userAges = yield* TxHashMap.map(validUsers, (user) => user.age) * const ageEntries = yield* TxHashMap.entries(userAges) - * console.log(ageEntries) // [["alice", 30], ["charlie", 25], ["eve", 28]] + * const sortedAgeEntries = ageEntries.toSorted(([left], [right]) => left.localeCompare(right)) + * console.log(sortedAgeEntries) // [["alice", 30], ["charlie", 25], ["eve", 28]] * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ export const compact = ( self: TxHashMap> @@ -3932,7 +4132,8 @@ export const compact = ( * Returns an array of all key-value pairs in the TxHashMap. * This is an alias for the `entries` function, providing API consistency with HashMap. * - * @example + * **Example** (Converting to entries) + * * ```ts * import { Effect, TxHashMap } from "effect" * @@ -3945,22 +4146,24 @@ export const compact = ( * * // Get all entries as an array * const allEntries = yield* TxHashMap.toEntries(settings) - * console.log(allEntries) - * // [["theme", "dark"], ["language", "en-US"], ["timezone", "UTC"]] + * const sortedEntries = allEntries.toSorted(([left], [right]) => left.localeCompare(right)) + * console.log(sortedEntries) + * // [["language", "en-US"], ["theme", "dark"], ["timezone", "UTC"]] * * // Process entries - * for (const [setting, value] of allEntries) { + * for (const [setting, value] of sortedEntries) { * console.log(`${setting}: ${value}`) * } * * // Convert to object for JSON serialization - * const settingsObj = Object.fromEntries(allEntries) + * const settingsObj = Object.fromEntries(sortedEntries) * console.log(JSON.stringify(settingsObj)) + * // {"language":"en-US","theme":"dark","timezone":"UTC"} * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ export const toEntries = ( self: TxHashMap @@ -3970,7 +4173,8 @@ export const toEntries = ( * Returns an array of all values in the TxHashMap. * This is an alias for the `values` function, providing API consistency with HashMap. * - * @example + * **Example** (Converting to values) + * * ```ts * import { Effect, TxHashMap } from "effect" * @@ -3983,24 +4187,23 @@ export const toEntries = ( * * // Get all product information * const products = yield* TxHashMap.toValues(inventory) - * console.log(products) - * // [{ price: 999, stock: 5 }, { price: 29, stock: 50 }, { price: 79, stock: 20 }] + * console.log(products.length) // 3 * * // Calculate total inventory value * const totalValue = products.reduce( * (sum, product) => sum + (product.price * product.stock), * 0 * ) - * console.log(`Total inventory value: $${totalValue}`) // $8,435 + * console.log(`Total inventory value: $${totalValue}`) // Total inventory value: $8025 * * // Find products with low stock * const lowStockProducts = products.filter((product) => product.stock < 10) - * console.log(`${lowStockProducts.length} products with low stock`) + * console.log(`${lowStockProducts.length} product with low stock`) // 1 product with low stock * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 4.0.0 */ export const toValues = (self: TxHashMap): Effect.Effect> => values(self) diff --git a/.opencode/node_modules/effect/src/TxHashSet.ts b/.opencode/node_modules/effect/src/TxHashSet.ts index ad3bc07240bcbff3516d758ccc32e533c5b8b847..f6878cb77ed05725e70679cebffd96a10d665e6d 100644 --- a/.opencode/node_modules/effect/src/TxHashSet.ts +++ b/.opencode/node_modules/effect/src/TxHashSet.ts @@ -1,4 +1,15 @@ /** + * Transactional hash sets for storing unique values inside Effect + * transactions. + * + * A `TxHashSet` keeps an immutable `HashSet` inside a `TxRef`, so membership + * checks and updates can commit atomically with other transactional operations. + * Use it when several pieces of shared transactional state must change + * together, such as adding a value only after checking related state. The + * module includes the usual set operations, including adding, removing, + * membership checks, set algebra, mapping, filtering, reducing, and conversion + * back to `HashSet`. + * * @since 2.0.0 */ @@ -36,23 +47,14 @@ const TxHashSetProto = { } /** - * A TxHashSet is a transactional hash set data structure that provides atomic operations - * on unique values within Effect transactions. It uses an immutable HashSet internally - * with TxRef for transactional semantics, ensuring all operations are performed atomically. + * A TxHashSet is a transactional hash set data structure that provides atomic operations on unique values within Effect transactions. It uses an immutable HashSet internally with TxRef for transactional semantics, ensuring all operations are performed atomically. * - * ## Mutation vs Return Behavior + * **Details** * - * **Mutation operations** (add, remove, clear) modify the original TxHashSet and return `Effect` or `Effect`: - * - These operations mutate the TxHashSet in place - * - They do not create new TxHashSet instances - * - Examples: `add`, `remove`, `clear` + * Mutation operations such as `add`, `remove`, and `clear` update the original TxHashSet and return `Effect` or `Effect`. Transform operations such as `union`, `intersection`, `difference`, `map`, and `filter` create new TxHashSet instances and leave the original TxHashSet unchanged. * - * **Transform operations** (union, intersection, difference, map, filter) create new TxHashSet instances: - * - These operations return `Effect>` with a new instance - * - The original TxHashSet remains unchanged - * - Examples: `union`, `intersection`, `difference`, `map`, `filter` + * **Example** (Using transactional hash sets) * - * @example * ```ts * import { Effect, TxHashSet } from "effect" * @@ -81,8 +83,8 @@ const TxHashSetProto = { * }) * ``` * - * @since 2.0.0 * @category models + * @since 4.0.0 */ export interface TxHashSet extends Inspectable, Pipeable { readonly [TypeId]: typeof TypeId @@ -93,7 +95,8 @@ export interface TxHashSet extends Inspectable, Pipeable { * The TxHashSet namespace contains type-level utilities and helper types * for working with TxHashSet instances. * - * @example + * **Example** (Extracting value types inside transactions) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -111,27 +114,31 @@ export interface TxHashSet extends Inspectable, Pipeable { * }) * ``` * - * @since 2.0.0 - * @category models + * @since 4.0.0 */ export declare namespace TxHashSet { /** - * @example + * Extracts the value type from a `TxHashSet` type. + * + * **Example** (Extracting a TxHashSet value type) + * * ```ts - * import { TxHashSet } from "effect" + * import type { TxHashSet } from "effect" * - * const fruits = TxHashSet.make("apple", "banana", "cherry") + * type FruitSet = TxHashSet.TxHashSet<"apple" | "banana" | "cherry"> * * // Extract the value type - * type Fruit = TxHashSet.TxHashSet.Value // string + * type Fruit = TxHashSet.TxHashSet.Value // "apple" | "banana" | "cherry" * * const processFruit = (fruit: Fruit) => { * return `Processing ${fruit}` * } + * + * console.log(processFruit("apple")) // Processing apple * ``` * - * @since 2.0.0 - * @category type-level + * @category utility types + * @since 4.0.0 */ export type Value = T extends TxHashSet ? V : never } @@ -145,7 +152,8 @@ const makeTxHashSet = (ref: TxRef.TxRef>): TxHashSet => /** * Creates an empty TxHashSet. * - * @example + * **Example** (Creating an empty transactional hash set) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -162,8 +170,8 @@ const makeTxHashSet = (ref: TxRef.TxRef>): TxHashSet => * }) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const empty = (): Effect.Effect> => Effect.gen(function*() { @@ -174,7 +182,8 @@ export const empty = (): Effect.Effect> => /** * Creates a TxHashSet from a variable number of values. * - * @example + * **Example** (Creating transactional hash sets from values) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -190,8 +199,8 @@ export const empty = (): Effect.Effect> => * }) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const make = >( ...values: Values @@ -205,7 +214,8 @@ export const make = >( /** * Creates a TxHashSet from an iterable collection of values. * - * @example + * **Example** (Creating a transactional hash set from an iterable) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -218,12 +228,12 @@ export const make = >( * * const fromString = yield* TxHashSet.fromIterable("hello") * const values = yield* TxHashSet.toHashSet(fromString) - * console.log(Array.from(values)) // ["h", "e", "l", "o"] + * console.log(Array.from(values).sort()) // ["e", "h", "l", "o"] * }) * ``` * - * @since 2.0.0 * @category constructors + * @since 2.0.0 */ export const fromIterable = (values: Iterable): Effect.Effect> => Effect.gen(function*() { @@ -235,10 +245,10 @@ export const fromIterable = (values: Iterable): Effect.Effect /** * Creates a TxHashSet from an existing HashSet. * - * @example + * **Example** (Creating a transactional hash set from a HashSet) + * * ```ts - * import { Effect, TxHashSet } from "effect" - * import * as HashSet from "effect/HashSet" + * import { Effect, HashSet, TxHashSet } from "effect" * * const program = Effect.gen(function*() { * const hashSet = HashSet.make("x", "y", "z") @@ -254,8 +264,8 @@ export const fromIterable = (values: Iterable): Effect.Effect * }) * ``` * - * @since 2.0.0 * @category constructors + * @since 4.0.0 */ export const fromHashSet = (hashSet: HashSet.HashSet): Effect.Effect> => Effect.gen(function*() { @@ -264,12 +274,12 @@ export const fromHashSet = (hashSet: HashSet.HashSet): Effect.Effect(hashSet: HashSet.HashSet): Effect.Effect => hasProperty(u, TypeId) /** * Adds a value to the TxHashSet. If the value already exists, the operation has no effect. * - * **Mutation behavior**: This function mutates the original TxHashSet by adding - * the specified value. It does not return a new TxHashSet reference. + * **Details** + * + * This function mutates the original TxHashSet by adding the specified value. It does not return a new TxHashSet reference. + * + * **Example** (Adding values) * - * @example * ```ts * import { Effect, TxHashSet } from "effect" * @@ -311,17 +323,19 @@ export const isTxHashSet = (u: unknown): u is TxHashSet => hasProperty( * }) * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ export const add: { /** * Adds a value to the TxHashSet. If the value already exists, the operation has no effect. * - * **Mutation behavior**: This function mutates the original TxHashSet by adding - * the specified value. It does not return a new TxHashSet reference. + * **Details** + * + * This function mutates the original TxHashSet by adding the specified value. It does not return a new TxHashSet reference. + * + * **Example** (Adding values) * - * @example * ```ts * import { Effect, TxHashSet } from "effect" * @@ -338,17 +352,19 @@ export const add: { * }) * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ (value: V): (self: TxHashSet) => Effect.Effect /** * Adds a value to the TxHashSet. If the value already exists, the operation has no effect. * - * **Mutation behavior**: This function mutates the original TxHashSet by adding - * the specified value. It does not return a new TxHashSet reference. + * **Details** + * + * This function mutates the original TxHashSet by adding the specified value. It does not return a new TxHashSet reference. + * + * **Example** (Adding values) * - * @example * ```ts * import { Effect, TxHashSet } from "effect" * @@ -365,18 +381,20 @@ export const add: { * }) * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ (self: TxHashSet, value: V): Effect.Effect } = dual< /** * Adds a value to the TxHashSet. If the value already exists, the operation has no effect. * - * **Mutation behavior**: This function mutates the original TxHashSet by adding - * the specified value. It does not return a new TxHashSet reference. + * **Details** + * + * This function mutates the original TxHashSet by adding the specified value. It does not return a new TxHashSet reference. + * + * **Example** (Adding values) * - * @example * ```ts * import { Effect, TxHashSet } from "effect" * @@ -393,17 +411,19 @@ export const add: { * }) * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ (value: V) => (self: TxHashSet) => Effect.Effect, /** * Adds a value to the TxHashSet. If the value already exists, the operation has no effect. * - * **Mutation behavior**: This function mutates the original TxHashSet by adding - * the specified value. It does not return a new TxHashSet reference. + * **Details** + * + * This function mutates the original TxHashSet by adding the specified value. It does not return a new TxHashSet reference. + * + * **Example** (Adding values) * - * @example * ```ts * import { Effect, TxHashSet } from "effect" * @@ -420,8 +440,8 @@ export const add: { * }) * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ (self: TxHashSet, value: V) => Effect.Effect >(2, (self: TxHashSet, value: V) => TxRef.update(self.ref, (set) => HashSet.add(set, value))) @@ -429,10 +449,12 @@ export const add: { /** * Removes a value from the TxHashSet. * - * **Mutation behavior**: This function mutates the original TxHashSet by removing - * the specified value. It does not return a new TxHashSet reference. + * **Details** + * + * This function mutates the original TxHashSet by removing the specified value. It does not return a new TxHashSet reference. + * + * **Example** (Removing values) * - * @example * ```ts * import { Effect, TxHashSet } from "effect" * @@ -450,17 +472,19 @@ export const add: { * }) * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ export const remove: { /** * Removes a value from the TxHashSet. * - * **Mutation behavior**: This function mutates the original TxHashSet by removing - * the specified value. It does not return a new TxHashSet reference. + * **Details** + * + * This function mutates the original TxHashSet by removing the specified value. It does not return a new TxHashSet reference. + * + * **Example** (Removing values) * - * @example * ```ts * import { Effect, TxHashSet } from "effect" * @@ -478,17 +502,19 @@ export const remove: { * }) * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ (value: V): (self: TxHashSet) => Effect.Effect /** * Removes a value from the TxHashSet. * - * **Mutation behavior**: This function mutates the original TxHashSet by removing - * the specified value. It does not return a new TxHashSet reference. + * **Details** + * + * This function mutates the original TxHashSet by removing the specified value. It does not return a new TxHashSet reference. + * + * **Example** (Removing values) * - * @example * ```ts * import { Effect, TxHashSet } from "effect" * @@ -506,18 +532,20 @@ export const remove: { * }) * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ (self: TxHashSet, value: V): Effect.Effect } = dual< /** * Removes a value from the TxHashSet. * - * **Mutation behavior**: This function mutates the original TxHashSet by removing - * the specified value. It does not return a new TxHashSet reference. + * **Details** + * + * This function mutates the original TxHashSet by removing the specified value. It does not return a new TxHashSet reference. + * + * **Example** (Removing values) * - * @example * ```ts * import { Effect, TxHashSet } from "effect" * @@ -535,17 +563,19 @@ export const remove: { * }) * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ (value: V) => (self: TxHashSet) => Effect.Effect, /** * Removes a value from the TxHashSet. * - * **Mutation behavior**: This function mutates the original TxHashSet by removing - * the specified value. It does not return a new TxHashSet reference. + * **Details** + * + * This function mutates the original TxHashSet by removing the specified value. It does not return a new TxHashSet reference. + * + * **Example** (Removing values) * - * @example * ```ts * import { Effect, TxHashSet } from "effect" * @@ -563,8 +593,8 @@ export const remove: { * }) * ``` * - * @since 2.0.0 * @category mutations + * @since 2.0.0 */ (self: TxHashSet, value: V) => Effect.Effect >(2, (self: TxHashSet, value: V) => @@ -578,9 +608,10 @@ export const remove: { }).pipe(Effect.tx)) /** - * Checks if the TxHashSet contains the specified value. + * Checks whether the TxHashSet contains the specified value. + * + * **Example** (Checking membership) * - * @example * ```ts * import { Effect, Equal, Hash, TxHashSet } from "effect" * @@ -608,14 +639,15 @@ export const remove: { * }) * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ export const has: { /** - * Checks if the TxHashSet contains the specified value. + * Checks whether the TxHashSet contains the specified value. + * + * **Example** (Checking membership) * - * @example * ```ts * import { Effect, Equal, Hash, TxHashSet } from "effect" * @@ -643,14 +675,15 @@ export const has: { * }) * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (value: V): (self: TxHashSet) => Effect.Effect /** - * Checks if the TxHashSet contains the specified value. + * Checks whether the TxHashSet contains the specified value. + * + * **Example** (Checking membership) * - * @example * ```ts * import { Effect, Equal, Hash, TxHashSet } from "effect" * @@ -678,15 +711,16 @@ export const has: { * }) * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (self: TxHashSet, value: V): Effect.Effect } = dual< /** - * Checks if the TxHashSet contains the specified value. + * Checks whether the TxHashSet contains the specified value. + * + * **Example** (Checking membership) * - * @example * ```ts * import { Effect, Equal, Hash, TxHashSet } from "effect" * @@ -714,14 +748,15 @@ export const has: { * }) * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (value: V) => (self: TxHashSet) => Effect.Effect, /** - * Checks if the TxHashSet contains the specified value. + * Checks whether the TxHashSet contains the specified value. + * + * **Example** (Checking membership) * - * @example * ```ts * import { Effect, Equal, Hash, TxHashSet } from "effect" * @@ -749,8 +784,8 @@ export const has: { * }) * ``` * - * @since 2.0.0 * @category elements + * @since 2.0.0 */ (self: TxHashSet, value: V) => Effect.Effect >(2, (self: TxHashSet, value: V) => @@ -762,7 +797,8 @@ export const has: { /** * Returns the number of values in the TxHashSet. * - * @example + * **Example** (Getting the set size) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -778,8 +814,8 @@ export const has: { * }) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export const size = (self: TxHashSet): Effect.Effect => Effect.gen(function*() { @@ -788,9 +824,10 @@ export const size = (self: TxHashSet): Effect.Effect => }) /** - * Checks if the TxHashSet is empty. + * Checks whether the TxHashSet is empty. + * + * **Example** (Checking whether a set is empty) * - * @example * ```ts * import { Effect, TxHashSet } from "effect" * @@ -803,8 +840,8 @@ export const size = (self: TxHashSet): Effect.Effect => * }) * ``` * - * @since 2.0.0 * @category getters + * @since 2.0.0 */ export const isEmpty = (self: TxHashSet): Effect.Effect => Effect.gen(function*() { @@ -815,10 +852,12 @@ export const isEmpty = (self: TxHashSet): Effect.Effect => /** * Removes all values from the TxHashSet. * - * **Mutation behavior**: This function mutates the original TxHashSet by clearing - * all values. It does not return a new TxHashSet reference. + * **Details** + * + * This function mutates the original TxHashSet by clearing all values. It does not return a new TxHashSet reference. + * + * **Example** (Clearing all values) * - * @example * ```ts * import { Effect, TxHashSet } from "effect" * @@ -832,15 +871,16 @@ export const isEmpty = (self: TxHashSet): Effect.Effect => * }) * ``` * - * @since 2.0.0 * @category mutations + * @since 4.0.0 */ export const clear = (self: TxHashSet): Effect.Effect => TxRef.set(self.ref, HashSet.empty()) /** * Creates the union of two TxHashSets, returning a new TxHashSet. * - * @example + * **Example** (Combining sets with union) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -855,14 +895,15 @@ export const clear = (self: TxHashSet): Effect.Effect => TxRef.set(s * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const union: { /** * Creates the union of two TxHashSets, returning a new TxHashSet. * - * @example + * **Example** (Combining sets with union) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -877,14 +918,15 @@ export const union: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (that: TxHashSet): (self: TxHashSet) => Effect.Effect> /** * Creates the union of two TxHashSets, returning a new TxHashSet. * - * @example + * **Example** (Combining sets with union) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -899,15 +941,16 @@ export const union: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (self: TxHashSet, that: TxHashSet): Effect.Effect> } = dual< /** * Creates the union of two TxHashSets, returning a new TxHashSet. * - * @example + * **Example** (Combining sets with union) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -922,14 +965,15 @@ export const union: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (that: TxHashSet) => (self: TxHashSet) => Effect.Effect>, /** * Creates the union of two TxHashSets, returning a new TxHashSet. * - * @example + * **Example** (Combining sets with union) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -944,8 +988,8 @@ export const union: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (self: TxHashSet, that: TxHashSet) => Effect.Effect> >(2, (self: TxHashSet, that: TxHashSet) => @@ -959,7 +1003,8 @@ export const union: { /** * Creates the intersection of two TxHashSets, returning a new TxHashSet. * - * @example + * **Example** (Finding common values) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -974,14 +1019,15 @@ export const union: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const intersection: { /** * Creates the intersection of two TxHashSets, returning a new TxHashSet. * - * @example + * **Example** (Finding common values) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -996,14 +1042,15 @@ export const intersection: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (that: TxHashSet): (self: TxHashSet) => Effect.Effect> /** * Creates the intersection of two TxHashSets, returning a new TxHashSet. * - * @example + * **Example** (Finding common values) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1018,15 +1065,16 @@ export const intersection: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (self: TxHashSet, that: TxHashSet): Effect.Effect> } = dual< /** * Creates the intersection of two TxHashSets, returning a new TxHashSet. * - * @example + * **Example** (Finding common values) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1041,14 +1089,15 @@ export const intersection: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (that: TxHashSet) => (self: TxHashSet) => Effect.Effect>, /** * Creates the intersection of two TxHashSets, returning a new TxHashSet. * - * @example + * **Example** (Finding common values) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1063,8 +1112,8 @@ export const intersection: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (self: TxHashSet, that: TxHashSet) => Effect.Effect> >(2, (self: TxHashSet, that: TxHashSet) => @@ -1078,7 +1127,8 @@ export const intersection: { /** * Creates the difference of two TxHashSets (elements in the first set that are not in the second), returning a new TxHashSet. * - * @example + * **Example** (Finding values absent from another set) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1093,14 +1143,15 @@ export const intersection: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ export const difference: { /** * Creates the difference of two TxHashSets (elements in the first set that are not in the second), returning a new TxHashSet. * - * @example + * **Example** (Finding values absent from another set) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1115,14 +1166,15 @@ export const difference: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (that: TxHashSet): (self: TxHashSet) => Effect.Effect> /** * Creates the difference of two TxHashSets (elements in the first set that are not in the second), returning a new TxHashSet. * - * @example + * **Example** (Finding values absent from another set) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1137,15 +1189,16 @@ export const difference: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (self: TxHashSet, that: TxHashSet): Effect.Effect> } = dual< /** * Creates the difference of two TxHashSets (elements in the first set that are not in the second), returning a new TxHashSet. * - * @example + * **Example** (Finding values absent from another set) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1160,14 +1213,15 @@ export const difference: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (that: TxHashSet) => (self: TxHashSet) => Effect.Effect>, /** * Creates the difference of two TxHashSets (elements in the first set that are not in the second), returning a new TxHashSet. * - * @example + * **Example** (Finding values absent from another set) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1182,8 +1236,8 @@ export const difference: { * }) * ``` * - * @since 2.0.0 * @category combinators + * @since 2.0.0 */ (self: TxHashSet, that: TxHashSet) => Effect.Effect> >(2, (self: TxHashSet, that: TxHashSet) => @@ -1195,9 +1249,10 @@ export const difference: { }).pipe(Effect.tx)) /** - * Checks if a TxHashSet is a subset of another TxHashSet. + * Checks whether a TxHashSet is a subset of another TxHashSet. + * + * **Example** (Checking subset relationships) * - * @example * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1213,14 +1268,15 @@ export const difference: { * }) * ``` * - * @since 2.0.0 * @category elements + * @since 4.0.0 */ export const isSubset: { /** - * Checks if a TxHashSet is a subset of another TxHashSet. + * Checks whether a TxHashSet is a subset of another TxHashSet. + * + * **Example** (Checking subset relationships) * - * @example * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1236,14 +1292,15 @@ export const isSubset: { * }) * ``` * - * @since 2.0.0 * @category elements + * @since 4.0.0 */ (that: TxHashSet): (self: TxHashSet) => Effect.Effect /** - * Checks if a TxHashSet is a subset of another TxHashSet. + * Checks whether a TxHashSet is a subset of another TxHashSet. + * + * **Example** (Checking subset relationships) * - * @example * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1259,15 +1316,16 @@ export const isSubset: { * }) * ``` * - * @since 2.0.0 * @category elements + * @since 4.0.0 */ (self: TxHashSet, that: TxHashSet): Effect.Effect } = dual< /** - * Checks if a TxHashSet is a subset of another TxHashSet. + * Checks whether a TxHashSet is a subset of another TxHashSet. + * + * **Example** (Checking subset relationships) * - * @example * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1283,14 +1341,15 @@ export const isSubset: { * }) * ``` * - * @since 2.0.0 * @category elements + * @since 4.0.0 */ (that: TxHashSet) => (self: TxHashSet) => Effect.Effect, /** - * Checks if a TxHashSet is a subset of another TxHashSet. + * Checks whether a TxHashSet is a subset of another TxHashSet. + * + * **Example** (Checking subset relationships) * - * @example * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1306,8 +1365,8 @@ export const isSubset: { * }) * ``` * - * @since 2.0.0 * @category elements + * @since 4.0.0 */ (self: TxHashSet, that: TxHashSet) => Effect.Effect >(2, (self: TxHashSet, that: TxHashSet) => @@ -1318,9 +1377,10 @@ export const isSubset: { }).pipe(Effect.tx)) /** - * Tests whether at least one value in the TxHashSet satisfies the predicate. + * Checks whether at least one value in the TxHashSet satisfies the predicate. + * + * **Example** (Testing whether some values match) * - * @example * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1335,14 +1395,15 @@ export const isSubset: { * }) * ``` * - * @since 2.0.0 * @category elements + * @since 4.0.0 */ export const some: { /** - * Tests whether at least one value in the TxHashSet satisfies the predicate. + * Checks whether at least one value in the TxHashSet satisfies the predicate. + * + * **Example** (Testing whether some values match) * - * @example * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1357,14 +1418,15 @@ export const some: { * }) * ``` * - * @since 2.0.0 * @category elements + * @since 4.0.0 */ (predicate: Predicate): (self: TxHashSet) => Effect.Effect /** - * Tests whether at least one value in the TxHashSet satisfies the predicate. + * Checks whether at least one value in the TxHashSet satisfies the predicate. + * + * **Example** (Testing whether some values match) * - * @example * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1379,15 +1441,16 @@ export const some: { * }) * ``` * - * @since 2.0.0 * @category elements + * @since 4.0.0 */ (self: TxHashSet, predicate: Predicate): Effect.Effect } = dual< /** - * Tests whether at least one value in the TxHashSet satisfies the predicate. + * Checks whether at least one value in the TxHashSet satisfies the predicate. + * + * **Example** (Testing whether some values match) * - * @example * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1402,14 +1465,15 @@ export const some: { * }) * ``` * - * @since 2.0.0 * @category elements + * @since 4.0.0 */ (predicate: Predicate) => (self: TxHashSet) => Effect.Effect, /** - * Tests whether at least one value in the TxHashSet satisfies the predicate. + * Checks whether at least one value in the TxHashSet satisfies the predicate. + * + * **Example** (Testing whether some values match) * - * @example * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1424,8 +1488,8 @@ export const some: { * }) * ``` * - * @since 2.0.0 * @category elements + * @since 4.0.0 */ (self: TxHashSet, predicate: Predicate) => Effect.Effect >(2, (self: TxHashSet, predicate: Predicate) => @@ -1435,9 +1499,10 @@ export const some: { })) /** - * Tests whether all values in the TxHashSet satisfy the predicate. + * Checks whether all values in the TxHashSet satisfy the predicate. + * + * **Example** (Testing whether every value matches) * - * @example * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1452,14 +1517,15 @@ export const some: { * }) * ``` * - * @since 2.0.0 * @category elements + * @since 4.0.0 */ export const every: { /** - * Tests whether all values in the TxHashSet satisfy the predicate. + * Checks whether all values in the TxHashSet satisfy the predicate. + * + * **Example** (Testing whether every value matches) * - * @example * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1474,14 +1540,15 @@ export const every: { * }) * ``` * - * @since 2.0.0 * @category elements + * @since 4.0.0 */ (predicate: Predicate): (self: TxHashSet) => Effect.Effect /** - * Tests whether all values in the TxHashSet satisfy the predicate. + * Checks whether all values in the TxHashSet satisfy the predicate. + * + * **Example** (Testing whether every value matches) * - * @example * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1496,15 +1563,16 @@ export const every: { * }) * ``` * - * @since 2.0.0 * @category elements + * @since 4.0.0 */ (self: TxHashSet, predicate: Predicate): Effect.Effect } = dual< /** - * Tests whether all values in the TxHashSet satisfy the predicate. + * Checks whether all values in the TxHashSet satisfy the predicate. + * + * **Example** (Testing whether every value matches) * - * @example * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1519,14 +1587,15 @@ export const every: { * }) * ``` * - * @since 2.0.0 * @category elements + * @since 4.0.0 */ (predicate: Predicate) => (self: TxHashSet) => Effect.Effect, /** - * Tests whether all values in the TxHashSet satisfy the predicate. + * Checks whether all values in the TxHashSet satisfy the predicate. + * + * **Example** (Testing whether every value matches) * - * @example * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1541,8 +1610,8 @@ export const every: { * }) * ``` * - * @since 2.0.0 * @category elements + * @since 4.0.0 */ (self: TxHashSet, predicate: Predicate) => Effect.Effect >(2, (self: TxHashSet, predicate: Predicate) => @@ -1554,7 +1623,8 @@ export const every: { /** * Maps each value in the TxHashSet using the provided function, returning a new TxHashSet. * - * @example + * **Example** (Mapping values) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1574,14 +1644,15 @@ export const every: { * }) * ``` * - * @since 2.0.0 * @category mapping + * @since 4.0.0 */ export const map: { /** * Maps each value in the TxHashSet using the provided function, returning a new TxHashSet. * - * @example + * **Example** (Mapping values) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1601,14 +1672,15 @@ export const map: { * }) * ``` * - * @since 2.0.0 * @category mapping + * @since 4.0.0 */ (f: (value: V) => U): (self: TxHashSet) => Effect.Effect> /** * Maps each value in the TxHashSet using the provided function, returning a new TxHashSet. * - * @example + * **Example** (Mapping values) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1628,15 +1700,16 @@ export const map: { * }) * ``` * - * @since 2.0.0 * @category mapping + * @since 4.0.0 */ (self: TxHashSet, f: (value: V) => U): Effect.Effect> } = dual< /** * Maps each value in the TxHashSet using the provided function, returning a new TxHashSet. * - * @example + * **Example** (Mapping values) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1656,14 +1729,15 @@ export const map: { * }) * ``` * - * @since 2.0.0 * @category mapping + * @since 4.0.0 */ (f: (value: V) => U) => (self: TxHashSet) => Effect.Effect>, /** * Maps each value in the TxHashSet using the provided function, returning a new TxHashSet. * - * @example + * **Example** (Mapping values) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1683,8 +1757,8 @@ export const map: { * }) * ``` * - * @since 2.0.0 * @category mapping + * @since 4.0.0 */ (self: TxHashSet, f: (value: V) => U) => Effect.Effect> >(2, (self: TxHashSet, f: (value: V) => U) => @@ -1697,7 +1771,8 @@ export const map: { /** * Filters the TxHashSet keeping only values that satisfy the predicate, returning a new TxHashSet. * - * @example + * **Example** (Filtering values) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1711,14 +1786,15 @@ export const map: { * }) * ``` * - * @since 2.0.0 * @category filtering + * @since 4.0.0 */ export const filter: { /** * Filters the TxHashSet keeping only values that satisfy the predicate, returning a new TxHashSet. * - * @example + * **Example** (Filtering values) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1732,14 +1808,15 @@ export const filter: { * }) * ``` * - * @since 2.0.0 * @category filtering + * @since 4.0.0 */ (refinement: Refinement, U>): (self: TxHashSet) => Effect.Effect> /** * Filters the TxHashSet keeping only values that satisfy the predicate, returning a new TxHashSet. * - * @example + * **Example** (Filtering values) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1753,14 +1830,15 @@ export const filter: { * }) * ``` * - * @since 2.0.0 * @category filtering + * @since 4.0.0 */ (predicate: Predicate>): (self: TxHashSet) => Effect.Effect> /** * Filters the TxHashSet keeping only values that satisfy the predicate, returning a new TxHashSet. * - * @example + * **Example** (Filtering values) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1774,14 +1852,15 @@ export const filter: { * }) * ``` * - * @since 2.0.0 * @category filtering + * @since 4.0.0 */ (self: TxHashSet, refinement: Refinement): Effect.Effect> /** * Filters the TxHashSet keeping only values that satisfy the predicate, returning a new TxHashSet. * - * @example + * **Example** (Filtering values) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1795,15 +1874,16 @@ export const filter: { * }) * ``` * - * @since 2.0.0 * @category filtering + * @since 4.0.0 */ (self: TxHashSet, predicate: Predicate): Effect.Effect> } = dual< /** * Filters the TxHashSet keeping only values that satisfy the predicate, returning a new TxHashSet. * - * @example + * **Example** (Filtering values) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1817,8 +1897,8 @@ export const filter: { * }) * ``` * - * @since 2.0.0 * @category filtering + * @since 4.0.0 */ { ( @@ -1831,7 +1911,8 @@ export const filter: { /** * Filters the TxHashSet keeping only values that satisfy the predicate, returning a new TxHashSet. * - * @example + * **Example** (Filtering values) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1845,8 +1926,8 @@ export const filter: { * }) * ``` * - * @since 2.0.0 * @category filtering + * @since 4.0.0 */ { ( @@ -1865,7 +1946,8 @@ export const filter: { /** * Reduces the TxHashSet to a single value by iterating through the values and applying an accumulator function. * - * @example + * **Example** (Reducing values) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1881,14 +1963,15 @@ export const filter: { * }) * ``` * - * @since 2.0.0 * @category folding + * @since 2.0.0 */ export const reduce: { /** * Reduces the TxHashSet to a single value by iterating through the values and applying an accumulator function. * - * @example + * **Example** (Reducing values) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1904,14 +1987,15 @@ export const reduce: { * }) * ``` * - * @since 2.0.0 * @category folding + * @since 2.0.0 */ (zero: U, f: (accumulator: U, value: V) => U): (self: TxHashSet) => Effect.Effect /** * Reduces the TxHashSet to a single value by iterating through the values and applying an accumulator function. * - * @example + * **Example** (Reducing values) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1927,15 +2011,16 @@ export const reduce: { * }) * ``` * - * @since 2.0.0 * @category folding + * @since 2.0.0 */ (self: TxHashSet, zero: U, f: (accumulator: U, value: V) => U): Effect.Effect } = dual< /** * Reduces the TxHashSet to a single value by iterating through the values and applying an accumulator function. * - * @example + * **Example** (Reducing values) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1951,14 +2036,15 @@ export const reduce: { * }) * ``` * - * @since 2.0.0 * @category folding + * @since 2.0.0 */ (zero: U, f: (accumulator: U, value: V) => U) => (self: TxHashSet) => Effect.Effect, /** * Reduces the TxHashSet to a single value by iterating through the values and applying an accumulator function. * - * @example + * **Example** (Reducing values) + * * ```ts * import { Effect, TxHashSet } from "effect" * @@ -1974,8 +2060,8 @@ export const reduce: { * }) * ``` * - * @since 2.0.0 * @category folding + * @since 2.0.0 */ (self: TxHashSet, zero: U, f: (accumulator: U, value: V) => U) => Effect.Effect >(3, (self: TxHashSet, zero: U, f: (accumulator: U, value: V) => U) => @@ -1987,10 +2073,10 @@ export const reduce: { /** * Converts the TxHashSet to an immutable HashSet snapshot. * - * @example + * **Example** (Taking a HashSet snapshot) + * * ```ts - * import { Effect, TxHashSet } from "effect" - * import * as HashSet from "effect/HashSet" + * import { Effect, HashSet, TxHashSet } from "effect" * * const program = Effect.gen(function*() { * const txSet = yield* TxHashSet.make("x", "y", "z") @@ -2006,7 +2092,7 @@ export const reduce: { * }) * ``` * + * @category converting * @since 2.0.0 - * @category conversions */ export const toHashSet = (self: TxHashSet): Effect.Effect> => TxRef.get(self.ref) diff --git a/.opencode/node_modules/effect/src/TxPriorityQueue.ts b/.opencode/node_modules/effect/src/TxPriorityQueue.ts index 2958ce67fd75a466642feb0bade08bf3748d853d..a1096f19424293db2d4fa20a6b72e84258fdbb1c 100644 --- a/.opencode/node_modules/effect/src/TxPriorityQueue.ts +++ b/.opencode/node_modules/effect/src/TxPriorityQueue.ts @@ -1,6 +1,13 @@ /** - * A transactional priority queue. Elements are dequeued in order determined by the - * provided `Order` instance. All operations participate in the STM transaction system. + * Transactional priority queues whose state is stored in a `TxRef`. Elements + * are kept in the order defined by the `Order` supplied at construction time, + * and dequeue operations return the first element according to that ordering. + * + * Use `TxPriorityQueue` when multiple fibers coordinate through a shared queue + * and queue operations need to compose with other transactional state changes. + * The retrying `peek` and `take` operations wait transactionally when the queue + * is empty, so they can be combined with other transactional reads and writes in + * one atomic workflow. * * @since 4.0.0 */ @@ -24,11 +31,14 @@ const TypeId = "~effect/transactions/TxPriorityQueue" /** * A transactional priority queue backed by a sorted `Chunk`. * + * **Details** + * * Elements are stored in ascending order according to the `Order` provided at * construction time. `take` returns the smallest element, `peek` observes it * without removing. * - * @example + * **Example** (Dequeuing values by priority) + * * ```ts * import { Effect, Order, TxPriorityQueue } from "effect" * @@ -42,8 +52,8 @@ const TypeId = "~effect/transactions/TxPriorityQueue" * }) * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface TxPriorityQueue extends Inspectable, Pipeable { readonly [TypeId]: typeof TypeId @@ -95,7 +105,8 @@ const insertSorted = (chunk: Chunk, value: A, ord: Order): Chunk => /** * Creates an empty `TxPriorityQueue` with the given ordering. * - * @example + * **Example** (Creating an empty priority queue) + * * ```ts * import { Effect, Order, TxPriorityQueue } from "effect" * @@ -106,8 +117,8 @@ const insertSorted = (chunk: Chunk, value: A, ord: Order): Chunk => * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 2.0.0 */ export const empty = (order: Order): Effect.Effect> => Effect.map(TxRef.make>(C.empty()), (ref) => makeTxPriorityQueue(ref, order)) @@ -115,7 +126,8 @@ export const empty = (order: Order): Effect.Effect> => /** * Creates a `TxPriorityQueue` from an iterable of elements. * - * @example + * **Example** (Creating a priority queue from an iterable) + * * ```ts * import { Effect, Order, TxPriorityQueue } from "effect" * @@ -126,14 +138,15 @@ export const empty = (order: Order): Effect.Effect> => * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 2.0.0 */ export const fromIterable: { /** * Creates a `TxPriorityQueue` from an iterable of elements. * - * @example + * **Example** (Creating a priority queue from an iterable) + * * ```ts * import { Effect, Order, TxPriorityQueue } from "effect" * @@ -144,14 +157,15 @@ export const fromIterable: { * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 2.0.0 */ (order: Order): (iterable: Iterable) => Effect.Effect> /** * Creates a `TxPriorityQueue` from an iterable of elements. * - * @example + * **Example** (Creating a priority queue from an iterable) + * * ```ts * import { Effect, Order, TxPriorityQueue } from "effect" * @@ -162,8 +176,8 @@ export const fromIterable: { * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 2.0.0 */ (order: Order, iterable: Iterable): Effect.Effect> } = dual( @@ -174,7 +188,8 @@ export const fromIterable: { TxRef.make>(C.fromIterable(arr)), (ref) => makeTxPriorityQueue(ref, order) @@ -197,7 +212,8 @@ export const fromIterable: { /** * Creates a `TxPriorityQueue` from variadic elements. * - * @example + * **Example** (Creating a priority queue from variadic values) + * * ```ts * import { Effect, Order, TxPriorityQueue } from "effect" * @@ -208,8 +224,8 @@ export const fromIterable: { * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 2.0.0 */ export const make = (order: Order) => (...elements: Array): Effect.Effect> => fromIterable(order, elements) @@ -217,7 +233,8 @@ export const make = (order: Order) => (...elements: Array): Effect.Effe /** * Returns the number of elements in the queue. * - * @example + * **Example** (Getting the queue size) + * * ```ts * import { Effect, Order, TxPriorityQueue } from "effect" * @@ -228,15 +245,16 @@ export const make = (order: Order) => (...elements: Array): Effect.Effe * }) * ``` * - * @since 4.0.0 * @category getters + * @since 2.0.0 */ export const size = (self: TxPriorityQueue): Effect.Effect => Effect.map(TxRef.get(self.ref), C.size) /** * Returns `true` if the queue is empty. * - * @example + * **Example** (Checking whether a queue is empty) + * * ```ts * import { Effect, Order, TxPriorityQueue } from "effect" * @@ -247,15 +265,16 @@ export const size = (self: TxPriorityQueue): Effect.Effect => Effe * }) * ``` * - * @since 4.0.0 * @category getters + * @since 2.0.0 */ export const isEmpty = (self: TxPriorityQueue): Effect.Effect => Effect.map(size(self), (n) => n === 0) /** * Returns `true` if the queue has at least one element. * - * @example + * **Example** (Checking whether a queue has elements) + * * ```ts * import { Effect, Order, TxPriorityQueue } from "effect" * @@ -266,16 +285,21 @@ export const isEmpty = (self: TxPriorityQueue): Effect.Effect => * }) * ``` * - * @since 4.0.0 * @category getters + * @since 2.0.0 */ export const isNonEmpty = (self: TxPriorityQueue): Effect.Effect => Effect.map(size(self), (n) => n > 0) /** - * Observes the smallest element without removing it. Retries if the queue is - * empty. + * Observes the smallest element without removing it. + * + * **When to use** + * + * Use to inspect the next prioritized value and retry transactionally while + * the queue is empty. + * + * **Example** (Peeking at the next value) * - * @example * ```ts * import { Effect, Order, TxPriorityQueue } from "effect" * @@ -286,8 +310,8 @@ export const isNonEmpty = (self: TxPriorityQueue): Effect.Effect * }) * ``` * - * @since 4.0.0 * @category getters + * @since 2.0.0 */ export const peek = (self: TxPriorityQueue): Effect.Effect => Effect.gen(function*() { @@ -300,10 +324,15 @@ export const peek = (self: TxPriorityQueue): Effect.Effect => }).pipe(Effect.tx) /** - * Observes the smallest element without removing it. Returns `None` if the + * Observes the smallest element without removing it, returning `None` when the * queue is empty. * - * @example + * **When to use** + * + * Use to inspect the next prioritized value without retrying on an empty queue. + * + * **Example** (Peeking without retrying) + * * ```ts * import { Effect, Option, Order, TxPriorityQueue } from "effect" * @@ -314,8 +343,8 @@ export const peek = (self: TxPriorityQueue): Effect.Effect => * }) * ``` * - * @since 4.0.0 * @category getters + * @since 2.0.0 */ export const peekOption = (self: TxPriorityQueue): Effect.Effect> => Effect.map(TxRef.get(self.ref), C.head) @@ -323,7 +352,8 @@ export const peekOption = (self: TxPriorityQueue): Effect.Effect /** * Inserts an element into the queue in sorted position. * - * @example + * **Example** (Offering a value) + * * ```ts * import { Effect, Order, TxPriorityQueue } from "effect" * @@ -336,14 +366,15 @@ export const peekOption = (self: TxPriorityQueue): Effect.Effect * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ export const offer: { /** * Inserts an element into the queue in sorted position. * - * @example + * **Example** (Offering a value) + * * ```ts * import { Effect, Order, TxPriorityQueue } from "effect" * @@ -356,14 +387,15 @@ export const offer: { * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ (value: A): (self: TxPriorityQueue) => Effect.Effect /** * Inserts an element into the queue in sorted position. * - * @example + * **Example** (Offering a value) + * * ```ts * import { Effect, Order, TxPriorityQueue } from "effect" * @@ -376,8 +408,8 @@ export const offer: { * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ (self: TxPriorityQueue, value: A): Effect.Effect } = dual( @@ -389,7 +421,8 @@ export const offer: { /** * Inserts all elements from an iterable into the queue. * - * @example + * **Example** (Offering multiple values) + * * ```ts * import { Effect, Order, TxPriorityQueue } from "effect" * @@ -401,14 +434,15 @@ export const offer: { * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ export const offerAll: { /** * Inserts all elements from an iterable into the queue. * - * @example + * **Example** (Offering multiple values) + * * ```ts * import { Effect, Order, TxPriorityQueue } from "effect" * @@ -420,14 +454,15 @@ export const offerAll: { * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ (values: Iterable): (self: TxPriorityQueue) => Effect.Effect /** * Inserts all elements from an iterable into the queue. * - * @example + * **Example** (Offering multiple values) + * * ```ts * import { Effect, Order, TxPriorityQueue } from "effect" * @@ -439,8 +474,8 @@ export const offerAll: { * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ (self: TxPriorityQueue, values: Iterable): Effect.Effect } = dual( @@ -455,7 +490,8 @@ export const offerAll: { /** * Takes the smallest element from the queue. Retries if the queue is empty. * - * @example + * **Example** (Taking the next value) + * * ```ts * import { Effect, Order, TxPriorityQueue } from "effect" * @@ -466,8 +502,8 @@ export const offerAll: { * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ export const take = (self: TxPriorityQueue): Effect.Effect => Effect.gen(function*() { @@ -483,7 +519,8 @@ export const take = (self: TxPriorityQueue): Effect.Effect => /** * Takes all elements from the queue, returning them in priority order. * - * @example + * **Example** (Taking all values in priority order) + * * ```ts * import { Effect, Order, TxPriorityQueue } from "effect" * @@ -494,8 +531,8 @@ export const take = (self: TxPriorityQueue): Effect.Effect => * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ export const takeAll = (self: TxPriorityQueue): Effect.Effect> => Effect.map( @@ -506,7 +543,8 @@ export const takeAll = (self: TxPriorityQueue): Effect.Effect> => /** * Tries to take the smallest element. Returns `None` if the queue is empty. * - * @example + * **Example** (Taking without retrying) + * * ```ts * import { Effect, Option, Order, TxPriorityQueue } from "effect" * @@ -517,8 +555,8 @@ export const takeAll = (self: TxPriorityQueue): Effect.Effect> => * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ export const takeOption = (self: TxPriorityQueue): Effect.Effect> => TxRef.modify(self.ref, (chunk) => { @@ -532,7 +570,8 @@ export const takeOption = (self: TxPriorityQueue): Effect.Effect /** * Takes up to `n` elements from the queue in priority order. * - * @example + * **Example** (Taking up to a limit) + * * ```ts * import { Effect, Order, TxPriorityQueue } from "effect" * @@ -543,14 +582,15 @@ export const takeOption = (self: TxPriorityQueue): Effect.Effect * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ export const takeUpTo: { /** * Takes up to `n` elements from the queue in priority order. * - * @example + * **Example** (Taking up to a limit) + * * ```ts * import { Effect, Order, TxPriorityQueue } from "effect" * @@ -561,14 +601,15 @@ export const takeUpTo: { * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ (n: number): (self: TxPriorityQueue) => Effect.Effect> /** * Takes up to `n` elements from the queue in priority order. * - * @example + * **Example** (Taking up to a limit) + * * ```ts * import { Effect, Order, TxPriorityQueue } from "effect" * @@ -579,8 +620,8 @@ export const takeUpTo: { * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ (self: TxPriorityQueue, n: number): Effect.Effect> } = dual( @@ -599,7 +640,8 @@ export const takeUpTo: { /** * Removes elements matching the predicate. * - * @example + * **Example** (Removing matching values) + * * ```ts * import { Effect, Order, TxPriorityQueue } from "effect" * @@ -611,14 +653,15 @@ export const takeUpTo: { * }) * ``` * - * @since 4.0.0 * @category filtering + * @since 2.0.0 */ export const removeIf: { /** * Removes elements matching the predicate. * - * @example + * **Example** (Removing matching values) + * * ```ts * import { Effect, Order, TxPriorityQueue } from "effect" * @@ -630,14 +673,15 @@ export const removeIf: { * }) * ``` * - * @since 4.0.0 * @category filtering + * @since 2.0.0 */ (predicate: Predicate): (self: TxPriorityQueue) => Effect.Effect /** * Removes elements matching the predicate. * - * @example + * **Example** (Removing matching values) + * * ```ts * import { Effect, Order, TxPriorityQueue } from "effect" * @@ -649,8 +693,8 @@ export const removeIf: { * }) * ``` * - * @since 4.0.0 * @category filtering + * @since 2.0.0 */ (self: TxPriorityQueue, predicate: Predicate): Effect.Effect } = dual( @@ -660,9 +704,10 @@ export const removeIf: { ) /** - * Retains only elements matching the predicate. + * Keeps only elements matching the predicate. + * + * **Example** (Retaining matching values) * - * @example * ```ts * import { Effect, Order, TxPriorityQueue } from "effect" * @@ -674,14 +719,15 @@ export const removeIf: { * }) * ``` * - * @since 4.0.0 * @category filtering + * @since 2.0.0 */ export const retainIf: { /** - * Retains only elements matching the predicate. + * Keeps only elements matching the predicate. + * + * **Example** (Retaining matching values) * - * @example * ```ts * import { Effect, Order, TxPriorityQueue } from "effect" * @@ -693,14 +739,15 @@ export const retainIf: { * }) * ``` * - * @since 4.0.0 * @category filtering + * @since 2.0.0 */ (predicate: Predicate): (self: TxPriorityQueue) => Effect.Effect /** - * Retains only elements matching the predicate. + * Keeps only elements matching the predicate. + * + * **Example** (Retaining matching values) * - * @example * ```ts * import { Effect, Order, TxPriorityQueue } from "effect" * @@ -712,8 +759,8 @@ export const retainIf: { * }) * ``` * - * @since 4.0.0 * @category filtering + * @since 2.0.0 */ (self: TxPriorityQueue, predicate: Predicate): Effect.Effect } = dual( @@ -725,7 +772,8 @@ export const retainIf: { /** * Returns all elements in priority order without removing them. * - * @example + * **Example** (Reading values in priority order) + * * ```ts * import { Effect, Order, TxPriorityQueue } from "effect" * @@ -736,8 +784,8 @@ export const retainIf: { * }) * ``` * - * @since 4.0.0 - * @category conversions + * @category converting + * @since 2.0.0 */ export const toArray = (self: TxPriorityQueue): Effect.Effect> => Effect.map(TxRef.get(self.ref), C.toArray) @@ -745,7 +793,8 @@ export const toArray = (self: TxPriorityQueue): Effect.Effect> => /** * Determines if the provided value is a `TxPriorityQueue`. * - * @example + * **Example** (Checking for a TxPriorityQueue) + * * ```ts * import { Effect, Order, TxPriorityQueue } from "effect" * @@ -756,7 +805,7 @@ export const toArray = (self: TxPriorityQueue): Effect.Effect> => * }) * ``` * - * @since 4.0.0 * @category guards + * @since 4.0.0 */ export const isTxPriorityQueue = (u: unknown): u is TxPriorityQueue => hasProperty(u, TypeId) diff --git a/.opencode/node_modules/effect/src/TxPubSub.ts b/.opencode/node_modules/effect/src/TxPubSub.ts index 847c98be75294b990ff27d1c560b3e3d60b1b1a4..d22d2cb639f932ef359ef8cad4c82077648de90c 100644 --- a/.opencode/node_modules/effect/src/TxPubSub.ts +++ b/.opencode/node_modules/effect/src/TxPubSub.ts @@ -1,9 +1,11 @@ /** - * TxPubSub is a transactional publish/subscribe hub that provides Software Transactional Memory - * (STM) semantics for message broadcasting. Publishers broadcast messages to all current - * subscribers, with each subscriber receiving its own copy of every published message. + * Broadcasts values to subscribers inside Effect transactions. * - * Supports multiple queue strategies: bounded, unbounded, dropping, and sliding. + * A `TxPubSub` is a transactional publish/subscribe hub. Each subscriber + * owns a `TxQueue`, and each published value is offered to the subscriber + * queues that are registered at the time of publication. This module includes + * bounded, dropping, sliding, and unbounded hubs, publishing helpers, scoped + * subscriptions, shutdown operations, and a guard. * * @since 4.0.0 */ @@ -24,7 +26,8 @@ const TypeId = "~effect/transactions/TxPubSub" * A TxPubSub represents a transactional publish/subscribe hub that broadcasts messages * to all current subscribers using Software Transactional Memory (STM) semantics. * - * @example + * **Example** (Subscribing to a transactional pub/sub) + * * ```ts * import { Effect, TxPubSub, TxQueue } from "effect" * @@ -42,8 +45,8 @@ const TypeId = "~effect/transactions/TxPubSub" * }) * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface TxPubSub extends Inspectable, Pipeable { readonly [TypeId]: typeof TypeId @@ -97,7 +100,8 @@ const makeTxPubSub = ( * Creates a bounded TxPubSub with the specified capacity. When a subscriber's * queue is full, the publisher will retry the transaction until space is available. * - * @example + * **Example** (Creating a bounded pub/sub) + * * ```ts * import { Effect, TxPubSub, TxQueue } from "effect" * @@ -115,8 +119,8 @@ const makeTxPubSub = ( * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 2.0.0 */ export const bounded = (capacity: number): Effect.Effect> => Effect.gen(function*() { @@ -129,7 +133,8 @@ export const bounded = (capacity: number): Effect.Effect> * Creates a dropping TxPubSub with the specified capacity. When a subscriber's * queue is full, the message is dropped for that subscriber. * - * @example + * **Example** (Creating a dropping pub/sub) + * * ```ts * import { Effect, TxPubSub, TxQueue } from "effect" * @@ -150,8 +155,8 @@ export const bounded = (capacity: number): Effect.Effect> * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 2.0.0 */ export const dropping = (capacity: number): Effect.Effect> => Effect.gen(function*() { @@ -164,7 +169,8 @@ export const dropping = (capacity: number): Effect.Effect * Creates a sliding TxPubSub with the specified capacity. When a subscriber's * queue is full, the oldest message in that subscriber's queue is dropped. * - * @example + * **Example** (Creating a sliding pub/sub) + * * ```ts * import { Effect, TxPubSub, TxQueue } from "effect" * @@ -184,8 +190,8 @@ export const dropping = (capacity: number): Effect.Effect * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 2.0.0 */ export const sliding = (capacity: number): Effect.Effect> => Effect.gen(function*() { @@ -197,7 +203,8 @@ export const sliding = (capacity: number): Effect.Effect> /** * Creates an unbounded TxPubSub with unlimited capacity. Messages are always accepted. * - * @example + * **Example** (Creating an unbounded pub/sub) + * * ```ts * import { Effect, TxPubSub, TxQueue } from "effect" * @@ -215,8 +222,8 @@ export const sliding = (capacity: number): Effect.Effect> * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 2.0.0 */ export const unbounded = (): Effect.Effect> => Effect.gen(function*() { @@ -232,7 +239,8 @@ export const unbounded = (): Effect.Effect> => /** * Returns the capacity of the TxPubSub. * - * @example + * **Example** (Reading pub/sub capacity) + * * ```ts * import { Effect, TxPubSub } from "effect" * @@ -242,15 +250,16 @@ export const unbounded = (): Effect.Effect> => * }) * ``` * - * @since 4.0.0 * @category getters + * @since 2.0.0 */ export const capacity = (self: TxPubSub): number => self.capacity /** * Returns the current number of messages across all subscriber queues (the max). * - * @example + * **Example** (Reading subscriber queue size) + * * ```ts * import { Effect, TxPubSub, TxQueue } from "effect" * @@ -269,8 +278,8 @@ export const capacity = (self: TxPubSub): number => self.capacity * }) * ``` * - * @since 4.0.0 * @category getters + * @since 2.0.0 */ export const size = (self: TxPubSub): Effect.Effect => Effect.gen(function*() { @@ -284,9 +293,10 @@ export const size = (self: TxPubSub): Effect.Effect => }).pipe(Effect.tx) /** - * Checks if the TxPubSub has no pending messages (all subscriber queues are empty). + * Checks whether the TxPubSub has no pending messages (all subscriber queues are empty). + * + * **Example** (Checking whether a pub/sub is empty) * - * @example * ```ts * import { Effect, TxPubSub } from "effect" * @@ -297,15 +307,16 @@ export const size = (self: TxPubSub): Effect.Effect => * }) * ``` * - * @since 4.0.0 * @category getters + * @since 2.0.0 */ export const isEmpty = (self: TxPubSub): Effect.Effect => Effect.map(size(self), (s) => s === 0) /** - * Checks if any subscriber queue is at capacity. + * Checks whether any subscriber queue is at capacity. + * + * **Example** (Checking whether a pub/sub is full) * - * @example * ```ts * import { Effect, TxPubSub } from "effect" * @@ -316,8 +327,8 @@ export const isEmpty = (self: TxPubSub): Effect.Effect => Effect. * }) * ``` * - * @since 4.0.0 * @category getters + * @since 2.0.0 */ export const isFull = (self: TxPubSub): Effect.Effect => Effect.gen(function*() { @@ -330,9 +341,10 @@ export const isFull = (self: TxPubSub): Effect.Effect => }).pipe(Effect.tx) /** - * Checks if the TxPubSub has been shut down. + * Checks whether the TxPubSub has been shut down. + * + * **Example** (Checking whether a pub/sub is shut down) * - * @example * ```ts * import { Effect, TxPubSub } from "effect" * @@ -344,8 +356,8 @@ export const isFull = (self: TxPubSub): Effect.Effect => * }) * ``` * - * @since 4.0.0 * @category getters + * @since 2.0.0 */ export const isShutdown = (self: TxPubSub): Effect.Effect => TxRef.get(self.shutdownRef) @@ -356,14 +368,12 @@ export const isShutdown = (self: TxPubSub): Effect.Effect => TxRe /** * Publishes a message to all current subscribers. * - * Returns `true` if the message was delivered to all subscribers, or `false` if - * the hub is shut down or the message was dropped for any subscriber (dropping strategy). + * **Details** * - * For bounded strategy, retries the transaction if any subscriber queue is full. - * For sliding strategy, drops oldest messages in full subscriber queues. - * For dropping strategy, drops the message for full subscriber queues and returns `false`. + * Returns `true` if the message was delivered to all subscribers, or `false` if the hub is shut down or the message was dropped for any subscriber. For the bounded strategy, the transaction retries if any subscriber queue is full. For the sliding strategy, full subscriber queues drop their oldest messages. For the dropping strategy, full subscriber queues drop the new message and the operation returns `false`. + * + * **Example** (Publishing a message to subscribers) * - * @example * ```ts * import { Effect, TxPubSub, TxQueue } from "effect" * @@ -385,8 +395,8 @@ export const isShutdown = (self: TxPubSub): Effect.Effect => TxRe * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ export const publish: { // ============================================================================= @@ -396,14 +406,12 @@ export const publish: { /** * Publishes a message to all current subscribers. * - * Returns `true` if the message was delivered to all subscribers, or `false` if - * the hub is shut down or the message was dropped for any subscriber (dropping strategy). + * **Details** + * + * Returns `true` if the message was delivered to all subscribers, or `false` if the hub is shut down or the message was dropped for any subscriber. For the bounded strategy, the transaction retries if any subscriber queue is full. For the sliding strategy, full subscriber queues drop their oldest messages. For the dropping strategy, full subscriber queues drop the new message and the operation returns `false`. * - * For bounded strategy, retries the transaction if any subscriber queue is full. - * For sliding strategy, drops oldest messages in full subscriber queues. - * For dropping strategy, drops the message for full subscriber queues and returns `false`. + * **Example** (Publishing a message to subscribers) * - * @example * ```ts * import { Effect, TxPubSub, TxQueue } from "effect" * @@ -425,8 +433,8 @@ export const publish: { * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ (value: A): (self: TxPubSub) => Effect.Effect // ============================================================================= @@ -436,14 +444,12 @@ export const publish: { /** * Publishes a message to all current subscribers. * - * Returns `true` if the message was delivered to all subscribers, or `false` if - * the hub is shut down or the message was dropped for any subscriber (dropping strategy). + * **Details** + * + * Returns `true` if the message was delivered to all subscribers, or `false` if the hub is shut down or the message was dropped for any subscriber. For the bounded strategy, the transaction retries if any subscriber queue is full. For the sliding strategy, full subscriber queues drop their oldest messages. For the dropping strategy, full subscriber queues drop the new message and the operation returns `false`. * - * For bounded strategy, retries the transaction if any subscriber queue is full. - * For sliding strategy, drops oldest messages in full subscriber queues. - * For dropping strategy, drops the message for full subscriber queues and returns `false`. + * **Example** (Publishing a message to subscribers) * - * @example * ```ts * import { Effect, TxPubSub, TxQueue } from "effect" * @@ -465,8 +471,8 @@ export const publish: { * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ (self: TxPubSub, value: A): Effect.Effect } = dual( @@ -490,9 +496,12 @@ export const publish: { /** * Publishes all messages from an iterable to all current subscribers. * + * **Details** + * * Returns `true` if all messages were delivered to all subscribers. * - * @example + * **Example** (Publishing multiple messages to subscribers) + * * ```ts * import { Effect, TxPubSub, TxQueue } from "effect" * @@ -512,16 +521,19 @@ export const publish: { * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ export const publishAll: { /** * Publishes all messages from an iterable to all current subscribers. * + * **Details** + * * Returns `true` if all messages were delivered to all subscribers. * - * @example + * **Example** (Publishing multiple messages to subscribers) + * * ```ts * import { Effect, TxPubSub, TxQueue } from "effect" * @@ -541,16 +553,19 @@ export const publishAll: { * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ (values: Iterable): (self: TxPubSub) => Effect.Effect /** * Publishes all messages from an iterable to all current subscribers. * + * **Details** + * * Returns `true` if all messages were delivered to all subscribers. * - * @example + * **Example** (Publishing multiple messages to subscribers) + * * ```ts * import { Effect, TxPubSub, TxQueue } from "effect" * @@ -570,8 +585,8 @@ export const publishAll: { * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ (self: TxPubSub, values: Iterable): Effect.Effect } = dual( @@ -590,11 +605,14 @@ export const publishAll: { ) /** - * Subscribes to the TxPubSub, returning a TxQueue that receives all messages - * published after subscription. The subscription is automatically removed when - * the scope is closed. + * Subscribes to the TxPubSub, returning a scoped `TxQueue` for messages published after subscription. + * + * **Details** + * + * The returned queue uses the hub's capacity strategy: bounded subscriptions backpressure publishers when full, dropping subscriptions may miss new messages when full, and sliding subscriptions may evict older queued messages. The subscription is automatically removed when the scope is closed. + * + * **Example** (Subscribing multiple queues) * - * @example * ```ts * import { Effect, TxPubSub, TxQueue } from "effect" * @@ -616,8 +634,8 @@ export const publishAll: { * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ export const subscribe = (self: TxPubSub): Effect.Effect, never, Scope.Scope> => Effect.acquireRelease( @@ -628,12 +646,20 @@ export const subscribe = (self: TxPubSub): Effect.Effect( self: TxPubSub @@ -647,31 +673,76 @@ export const acquireSubscriber = ( /** * Removes a subscriber queue from the pub/sub and shuts it down. * - * This is the transactional release step of `subscribe`, exposed so that - * callers can compose it with other Tx operations in a single transaction. + * **When to use** + * + * Use to release a manually acquired subscriber queue inside a larger + * transaction, removing it from the pub/sub and shutting it down together with + * related transactional cleanup. + * + * **Details** + * + * This is the transactional release step of `subscribe`, exposed so that callers can compose it with other Tx operations in a single transaction. + * + * **Gotchas** + * + * The supplied queue is shut down after being removed, so callers should pass a + * queue acquired for this pub/sub. + * + * @see {@link acquireSubscriber} for the matching transactional acquire step + * @see {@link subscribe} for the scoped acquire and release wrapper * - * @since 4.0.0 * @category mutations + * @since 4.0.0 */ export const releaseSubscriber: { /** * Removes a subscriber queue from the pub/sub and shuts it down. * - * This is the transactional release step of `subscribe`, exposed so that - * callers can compose it with other Tx operations in a single transaction. + * **When to use** + * + * Use to release a manually acquired subscriber queue inside a larger + * transaction, removing it from the pub/sub and shutting it down together with + * related transactional cleanup. + * + * **Details** + * + * This is the transactional release step of `subscribe`, exposed so that callers can compose it with other Tx operations in a single transaction. + * + * **Gotchas** + * + * The supplied queue is shut down after being removed, so callers should pass a + * queue acquired for this pub/sub. + * + * @see {@link acquireSubscriber} for the matching transactional acquire step + * @see {@link subscribe} for the scoped acquire and release wrapper * - * @since 4.0.0 * @category mutations + * @since 4.0.0 */ (queue: TxQueue.TxQueue): (self: TxPubSub) => Effect.Effect /** * Removes a subscriber queue from the pub/sub and shuts it down. * - * This is the transactional release step of `subscribe`, exposed so that - * callers can compose it with other Tx operations in a single transaction. + * **When to use** + * + * Use to release a manually acquired subscriber queue inside a larger + * transaction, removing it from the pub/sub and shutting it down together with + * related transactional cleanup. + * + * **Details** + * + * This is the transactional release step of `subscribe`, exposed so that callers can compose it with other Tx operations in a single transaction. + * + * **Gotchas** + * + * The supplied queue is shut down after being removed, so callers should pass a + * queue acquired for this pub/sub. + * + * @see {@link acquireSubscriber} for the matching transactional acquire step + * @see {@link subscribe} for the scoped acquire and release wrapper * - * @since 4.0.0 * @category mutations + * @since 4.0.0 */ (self: TxPubSub, queue: TxQueue.TxQueue): Effect.Effect } = dual( @@ -703,10 +774,18 @@ const makeSubscriberQueue = ( } /** - * Shuts down the TxPubSub and all subscriber queues. Subsequent publish operations - * will return `false`. Subsequent subscribe operations will receive an already-shutdown queue. + * Shuts down the TxPubSub and all subscriber queues registered at the time of shutdown. + * + * **Details** + * + * After shutdown, `publish` and `publishAll` return `false`, and `awaitShutdown` completes. The operation is idempotent. + * + * **Gotchas** + * + * Subscribers acquired after shutdown are not automatically shut down by this call. + * + * **Example** (Shutting down a pub/sub) * - * @example * ```ts * import { Effect, TxPubSub } from "effect" * @@ -722,8 +801,8 @@ const makeSubscriberQueue = ( * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ export const shutdown = (self: TxPubSub): Effect.Effect => Effect.gen(function*() { @@ -740,7 +819,8 @@ export const shutdown = (self: TxPubSub): Effect.Effect => /** * Waits for the TxPubSub to be shut down. * - * @example + * **Example** (Waiting for shutdown) + * * ```ts * import { Effect, TxPubSub } from "effect" * @@ -753,8 +833,8 @@ export const shutdown = (self: TxPubSub): Effect.Effect => * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ export const awaitShutdown = (self: TxPubSub): Effect.Effect => Effect.gen(function*() { @@ -768,9 +848,10 @@ export const awaitShutdown = (self: TxPubSub): Effect.Effect => // ============================================================================= /** - * Checks if the given value is a TxPubSub. + * Checks whether the given value is a TxPubSub. + * + * **Example** (Checking for a TxPubSub) * - * @example * ```ts * import { TxPubSub } from "effect" * @@ -781,7 +862,7 @@ export const awaitShutdown = (self: TxPubSub): Effect.Effect => * } * ``` * - * @since 4.0.0 * @category guards + * @since 4.0.0 */ export const isTxPubSub = (u: unknown): u is TxPubSub => hasProperty(u, TypeId) diff --git a/.opencode/node_modules/effect/src/TxQueue.ts b/.opencode/node_modules/effect/src/TxQueue.ts index 5ed3689ea457653114e40a6527a2d95117d20104..79e0e8d981b9a78c6b741be7608de4b2fb842fc2 100644 --- a/.opencode/node_modules/effect/src/TxQueue.ts +++ b/.opencode/node_modules/effect/src/TxQueue.ts @@ -1,11 +1,12 @@ /** - * TxQueue is a transactional queue data structure that provides Software Transactional Memory (STM) - * semantics for queue operations. It uses TxRef for transactional state management and supports - * multiple queue strategies: bounded, unbounded, dropping, and sliding. + * Transactional queues whose state changes participate in Effect transactions. * - * Accessed values are tracked by the transaction in order to detect conflicts and to track changes. - * A transaction will retry whenever a conflict is detected or whenever the transaction explicitly - * calls `Effect.txRetry` and any of the accessed TxQueue values change. + * A `TxQueue` stores values of type `A`, exposes write-only `TxEnqueue` + * and read-only `TxDequeue` handles, and can complete, fail, or shut down with + * causes observed by consumers. Queue operations can retry transactionally when + * they cannot proceed, such as taking from an empty open queue or offering to a + * full bounded queue. This makes the queue useful for coordinating producers + * and consumers alongside other transactional state changes. * * @since 4.0.0 */ @@ -26,12 +27,15 @@ import type * as Types from "./Types.ts" /** * Represents the state of a transactional queue with sophisticated lifecycle management. * + * **Details** + * * The queue progresses through three states: * - **Open**: Accepting offers and serving takes normally * - **Closing**: No new offers accepted, serving remaining items until empty * - **Done**: Terminal state with completion cause, no further operations possible * - * @example + * **Example** (Inspecting queue lifecycle states) + * * ```ts * import type { TxQueue } from "effect" * @@ -47,8 +51,8 @@ import type * as Types from "./Types.ts" * } * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type State<_A, E> = | { @@ -70,31 +74,14 @@ const TypeId = "~effect/transactions/TxQueue" /** * Namespace containing type definitions for TxEnqueue variance annotations. * - * @example - * ```ts - * import type { TxQueue } from "effect" - * - * // Use variance types for type-level operations - * declare const variance: TxQueue.TxEnqueue.Variance - * ``` - * * @since 4.0.0 - * @category models */ export declare namespace TxEnqueue { /** * Variance annotation interface for TxEnqueue contravariance. * - * @example - * ```ts - * import type { TxQueue } from "effect" - * - * // Demonstrates contravariant type behavior for both A and E - * declare const variance: TxQueue.TxEnqueue.Variance - * ``` - * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface Variance { readonly _A: Types.Contravariant @@ -105,31 +92,14 @@ export declare namespace TxEnqueue { /** * Namespace containing type definitions for TxDequeue variance annotations. * - * @example - * ```ts - * import type { TxQueue } from "effect" - * - * // Use variance types for type-level operations - * declare const variance: TxQueue.TxDequeue.Variance - * ``` - * * @since 4.0.0 - * @category models */ export declare namespace TxDequeue { /** * Variance annotation interface for TxDequeue covariance. * - * @example - * ```ts - * import type { TxQueue } from "effect" - * - * // Demonstrates covariant type behavior for both A and E - * declare const variance: TxQueue.TxDequeue.Variance - * ``` - * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface Variance { readonly _A: Types.Covariant @@ -140,31 +110,14 @@ export declare namespace TxDequeue { /** * Namespace containing type definitions for TxQueue variance annotations. * - * @example - * ```ts - * import type { TxQueue } from "effect" - * - * // Use variance types for type-level operations - * declare const variance: TxQueue.TxQueue.Variance - * ``` - * * @since 4.0.0 - * @category models */ export declare namespace TxQueue { /** * Variance annotation interface for TxQueue invariance. * - * @example - * ```ts - * import type { TxQueue } from "effect" - * - * // Demonstrates invariant type behavior for both A and E - * declare const variance: TxQueue.TxQueue.Variance - * ``` - * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface Variance { readonly _A: Types.Invariant @@ -177,8 +130,8 @@ export declare namespace TxQueue { * This interface contains the core properties needed for queue state inspection * operations like size, capacity, and completion status. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface TxQueueState extends Inspectable { readonly strategy: "bounded" | "unbounded" | "dropping" | "sliding" @@ -191,10 +144,11 @@ export interface TxQueueState extends Inspectable { * A TxEnqueue represents the write-only interface of a transactional queue, providing * operations for adding elements (enqueue operations) and inspecting queue state. * - * @example + * **Example** (Offering values through enqueue handles) + * * ```ts - * import type { Cause } from "effect" * import { Effect, TxQueue } from "effect" + * import type { Cause } from "effect" * * const program = Effect.gen(function*() { * // Queue without error channel @@ -216,8 +170,8 @@ export interface TxQueueState extends Inspectable { * }) * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface TxEnqueue extends TxQueueState { readonly [EnqueueTypeId]: TxEnqueue.Variance @@ -227,18 +181,20 @@ export interface TxEnqueue extends TxQueueState { * A TxDequeue represents the read-only interface of a transactional queue, providing * operations for consuming elements (dequeue operations) and inspecting queue state. * - * @example + * **Example** (Taking values through dequeue handles) + * * ```ts * import { Effect, TxQueue } from "effect" * * const program = Effect.gen(function*() { * // Queue without error channel * const queue = yield* TxQueue.bounded(10) + * yield* TxQueue.offer(queue, 42) * const item = yield* TxQueue.take(queue) + * console.log(item) // 42 * * // Queue with error channel - errors propagate through E-channel * const faultTolerantQueue = yield* TxQueue.bounded(10) - * yield* TxQueue.offer(faultTolerantQueue, 42) * yield* TxQueue.fail(faultTolerantQueue, "processing failed") * * // All dequeue operations now fail with the error directly @@ -247,8 +203,8 @@ export interface TxEnqueue extends TxQueueState { * }) * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface TxDequeue extends TxQueueState { readonly [DequeueTypeId]: TxDequeue.Variance @@ -258,7 +214,8 @@ export interface TxDequeue extends TxQueueState { * A TxQueue represents a transactional queue data structure that provides both * enqueue and dequeue operations with Software Transactional Memory (STM) semantics. * - * @example + * **Example** (Combining enqueue and dequeue operations) + * * ```ts * import { Effect, TxQueue } from "effect" * @@ -275,22 +232,24 @@ export interface TxDequeue extends TxQueueState { * const faultTolerantQueue = yield* TxQueue.bounded(10) * * // Operations can handle queue-level failures - * yield* TxQueue.shutdown(faultTolerantQueue) - * const result = yield* Effect.flip(TxQueue.take(faultTolerantQueue)) // never + * yield* TxQueue.fail(faultTolerantQueue, "queue failed") + * const result = yield* Effect.flip(TxQueue.take(faultTolerantQueue)) + * console.log(result) // "queue failed" * }) * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface TxQueue extends TxEnqueue, TxDequeue { readonly [TypeId]: TxQueue.Variance } /** - * Checks if the given value is a TxEnqueue. + * Checks whether the given value is a TxEnqueue. + * + * **Example** (Checking enqueue handles) * - * @example * ```ts * import { TxQueue } from "effect" * @@ -302,15 +261,16 @@ export interface TxQueue extends TxEnqueue, Tx * } * ``` * - * @since 4.0.0 * @category guards + * @since 4.0.0 */ export const isTxEnqueue = (u: unknown): u is TxEnqueue => hasProperty(u, EnqueueTypeId) /** - * Checks if the given value is a TxDequeue. + * Checks whether the given value is a TxDequeue. + * + * **Example** (Checking dequeue handles) * - * @example * ```ts * import { TxQueue } from "effect" * @@ -322,15 +282,16 @@ export const isTxEnqueue = (u: unknown): u is TxEnqueu * } * ``` * - * @since 4.0.0 * @category guards + * @since 4.0.0 */ export const isTxDequeue = (u: unknown): u is TxDequeue => hasProperty(u, DequeueTypeId) /** - * Checks if the given value is a TxQueue. + * Checks whether the given value is a TxQueue. + * + * **Example** (Checking queue handles) * - * @example * ```ts * import { TxQueue } from "effect" * @@ -342,8 +303,8 @@ export const isTxDequeue = (u: unknown): u is TxDequeu * } * ``` * - * @since 4.0.0 * @category guards + * @since 4.0.0 */ export const isTxQueue = (u: unknown): u is TxQueue => hasProperty(u, TypeId) @@ -377,10 +338,12 @@ const TxQueueProto = { /** * Creates a new bounded `TxQueue` with the specified capacity. * - * **Return behavior**: This function returns a new TxQueue reference with - * the specified capacity. No existing TxQueue instances are modified. + * **Details** + * + * This function returns a new TxQueue reference with the specified capacity. No existing TxQueue instances are modified. + * + * **Example** (Creating bounded queues) * - * @example * ```ts * import { Effect, TxQueue } from "effect" * @@ -400,8 +363,8 @@ const TxQueueProto = { * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 2.0.0 */ export const bounded = ( capacity: number @@ -421,10 +384,12 @@ export const bounded = ( /** * Creates a new unbounded `TxQueue` with unlimited capacity. * - * **Return behavior**: This function returns a new TxQueue reference with - * unlimited capacity. No existing TxQueue instances are modified. + * **Details** + * + * This function returns a new TxQueue reference with unlimited capacity. No existing TxQueue instances are modified. + * + * **Example** (Creating unbounded queues) * - * @example * ```ts * import { Effect, TxQueue } from "effect" * @@ -444,8 +409,8 @@ export const bounded = ( * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 2.0.0 */ export const unbounded = (): Effect.Effect> => Effect.gen(function*() { @@ -463,10 +428,12 @@ export const unbounded = (): Effect.Effect> /** * Creates a new dropping `TxQueue` with the specified capacity that drops new items when full. * - * **Return behavior**: This function returns a new TxQueue reference with - * dropping strategy. No existing TxQueue instances are modified. + * **Details** + * + * This function returns a new TxQueue reference with dropping strategy. No existing TxQueue instances are modified. + * + * **Example** (Creating dropping queues) * - * @example * ```ts * import { Effect, TxQueue } from "effect" * @@ -484,8 +451,8 @@ export const unbounded = (): Effect.Effect> * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 2.0.0 */ export const dropping = ( capacity: number @@ -505,10 +472,12 @@ export const dropping = ( /** * Creates a new sliding `TxQueue` with the specified capacity that evicts old items when full. * - * **Return behavior**: This function returns a new TxQueue reference with - * sliding strategy. No existing TxQueue instances are modified. + * **Details** + * + * This function returns a new TxQueue reference with sliding strategy. No existing TxQueue instances are modified. + * + * **Example** (Creating sliding queues) * - * @example * ```ts * import { Effect, TxQueue } from "effect" * @@ -528,8 +497,8 @@ export const dropping = ( * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 2.0.0 */ export const sliding = ( capacity: number @@ -551,12 +520,14 @@ export const sliding = ( // ============================================================================= /** - * Offers an item to the queue. + * Offers an item to the queue and returns whether it was accepted. + * + * **Details** * - * **Mutation behavior**: This function mutates the original TxQueue by adding - * the item according to the queue's strategy. It does not return a new TxQueue reference. + * Open unbounded queues always accept; open bounded queues retry while full; dropping queues return `false` when full; sliding queues evict the oldest item when full. Closing or done queues return `false`. This function mutates the original TxQueue by adding the item according to the queue's strategy. It does not return a new TxQueue reference. + * + * **Example** (Offering a value) * - * @example * ```ts * import { Effect, TxQueue } from "effect" * @@ -569,8 +540,8 @@ export const sliding = ( * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 2.0.0 */ export const offer: { // ============================================================================= @@ -578,12 +549,14 @@ export const offer: { // ============================================================================= /** - * Offers an item to the queue. + * Offers an item to the queue and returns whether it was accepted. * - * **Mutation behavior**: This function mutates the original TxQueue by adding - * the item according to the queue's strategy. It does not return a new TxQueue reference. + * **Details** + * + * Open unbounded queues always accept; open bounded queues retry while full; dropping queues return `false` when full; sliding queues evict the oldest item when full. Closing or done queues return `false`. This function mutates the original TxQueue by adding the item according to the queue's strategy. It does not return a new TxQueue reference. + * + * **Example** (Offering a value) * - * @example * ```ts * import { Effect, TxQueue } from "effect" * @@ -596,8 +569,8 @@ export const offer: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 2.0.0 */ (value: A): (self: TxEnqueue) => Effect.Effect // ============================================================================= @@ -605,12 +578,14 @@ export const offer: { // ============================================================================= /** - * Offers an item to the queue. + * Offers an item to the queue and returns whether it was accepted. * - * **Mutation behavior**: This function mutates the original TxQueue by adding - * the item according to the queue's strategy. It does not return a new TxQueue reference. + * **Details** + * + * Open unbounded queues always accept; open bounded queues retry while full; dropping queues return `false` when full; sliding queues evict the oldest item when full. Closing or done queues return `false`. This function mutates the original TxQueue by adding the item according to the queue's strategy. It does not return a new TxQueue reference. + * + * **Example** (Offering a value) * - * @example * ```ts * import { Effect, TxQueue } from "effect" * @@ -623,8 +598,8 @@ export const offer: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 2.0.0 */ (self: TxEnqueue, value: A): Effect.Effect } = dual( @@ -667,16 +642,17 @@ export const offer: { ) /** - * Offers multiple items to the queue. + * Offers multiple items to the queue, returning the items that were not + * accepted. * - * Returns an array of items that were rejected (not added to the queue). + * **Details** * - * **Mutation behavior**: This function mutates the original TxQueue by adding - * items according to the queue's strategy. It does not return a new TxQueue reference. + * Each item follows `offer` semantics: bounded queues retry while full, dropping queues reject new items when full, sliding queues evict old items to accept new items, and closing or done queues reject all items. This function mutates the original TxQueue by adding items according to the queue's strategy. It does not return a new TxQueue reference. + * + * **Example** (Offering multiple values) * - * @example * ```ts - * import { Chunk, Effect, TxQueue } from "effect" + * import { Effect, TxQueue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* TxQueue.bounded(10) @@ -688,21 +664,22 @@ export const offer: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 2.0.0 */ export const offerAll: { /** - * Offers multiple items to the queue. + * Offers multiple items to the queue, returning the items that were not + * accepted. * - * Returns an array of items that were rejected (not added to the queue). + * **Details** * - * **Mutation behavior**: This function mutates the original TxQueue by adding - * items according to the queue's strategy. It does not return a new TxQueue reference. + * Each item follows `offer` semantics: bounded queues retry while full, dropping queues reject new items when full, sliding queues evict old items to accept new items, and closing or done queues reject all items. This function mutates the original TxQueue by adding items according to the queue's strategy. It does not return a new TxQueue reference. + * + * **Example** (Offering multiple values) * - * @example * ```ts - * import { Chunk, Effect, TxQueue } from "effect" + * import { Effect, TxQueue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* TxQueue.bounded(10) @@ -714,21 +691,22 @@ export const offerAll: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 2.0.0 */ (values: Iterable): (self: TxEnqueue) => Effect.Effect> /** - * Offers multiple items to the queue. + * Offers multiple items to the queue, returning the items that were not + * accepted. + * + * **Details** * - * Returns an array of items that were rejected (not added to the queue). + * Each item follows `offer` semantics: bounded queues retry while full, dropping queues reject new items when full, sliding queues evict old items to accept new items, and closing or done queues reject all items. This function mutates the original TxQueue by adding items according to the queue's strategy. It does not return a new TxQueue reference. * - * **Mutation behavior**: This function mutates the original TxQueue by adding - * items according to the queue's strategy. It does not return a new TxQueue reference. + * **Example** (Offering multiple values) * - * @example * ```ts - * import { Chunk, Effect, TxQueue } from "effect" + * import { Effect, TxQueue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* TxQueue.bounded(10) @@ -740,8 +718,8 @@ export const offerAll: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 2.0.0 */ (self: TxEnqueue, values: Iterable): Effect.Effect> } = dual( @@ -762,12 +740,15 @@ export const offerAll: { ) /** - * Takes an item from the queue. + * Takes the next item from the queue, retrying the transaction while the queue + * is empty. + * + * **Details** + * + * If the queue is done, the effect fails with the queue's completion cause. This function mutates the original TxQueue by removing the first item. It does not return a new TxQueue reference. * - * **Mutation behavior**: This function mutates the original TxQueue by removing - * the first item. It does not return a new TxQueue reference. + * **Example** (Taking a value) * - * @example * ```ts * import { Effect, TxQueue } from "effect" * @@ -786,8 +767,8 @@ export const offerAll: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 2.0.0 */ export const take = (self: TxDequeue): Effect.Effect => Effect.gen(function*() { @@ -823,7 +804,8 @@ export const take = (self: TxDequeue): Effect.Effect => /** * Tries to take an item from the queue without blocking. * - * @example + * **Example** (Polling without blocking) + * * ```ts * import { Effect, Option, TxQueue } from "effect" * @@ -840,8 +822,8 @@ export const take = (self: TxDequeue): Effect.Effect => * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 2.0.0 */ export const poll = (self: TxDequeue): Effect.Effect> => Effect.gen(function*() { @@ -863,15 +845,12 @@ export const poll = (self: TxDequeue): Effect.Effect(self: TxDequeue): Effect.Effect(self: TxDequeue): Effect.Effect, E> => Effect.gen(function*() { @@ -929,111 +908,93 @@ export const takeAll = (self: TxDequeue): Effect.Effect capacity**: Takes up to capacity items immediately - * - **Closing queue**: Takes available items and transitions to Done state + * For an open queue, waits until `min(n, capacity)` items are available, then removes that many items. If `n` is less than or equal to zero, returns an empty array without modifying the queue. If the queue is closing, drains the currently available items and transitions to `Done`. If the queue is already done, the effect fails with the queue's completion cause. This function mutates the original TxQueue by removing the taken items. It does not return a new TxQueue reference. * - * **Mutation behavior**: This function mutates the original TxQueue by removing - * the taken items. It does not return a new TxQueue reference. + * **Example** (Taking a fixed number of values) * - * @example * ```ts * import { Effect, TxQueue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* TxQueue.bounded(5) - * yield* TxQueue.offerAll(queue, [1, 2, 3]) + * yield* TxQueue.offerAll(queue, [1, 2, 3, 4]) * - * // This will wait until 4 items are available - * // (will retry transaction until more items are offered) * const items = yield* TxQueue.takeN(queue, 4) + * console.log(items) // [1, 2, 3, 4] * * // This requests more than capacity (5), so takes all available (up to 5) - * const all = yield* TxQueue.takeN(queue, 10) // Takes at most 5 items + * yield* TxQueue.offerAll(queue, [5, 6, 7, 8, 9]) + * const all = yield* TxQueue.takeN(queue, 10) + * console.log(all) // [5, 6, 7, 8, 9] * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 2.0.0 */ export const takeN: { /** - * Takes exactly N items from the queue in a single atomic transaction. + * Takes up to `n` items from the queue in a single transaction. * - * This function waits (retries the transaction) until N items are available, then takes - * exactly N items. The only exception is when N exceeds the queue's capacity - in that - * case, it takes up to the queue's capacity and returns immediately. + * **Details** * - * **Behavior**: - * - **Normal case**: Waits for exactly N items to be available - * - **Bounded queue with N > capacity**: Takes up to capacity items immediately - * - **Closing queue**: Takes available items and transitions to Done state + * For an open queue, waits until `min(n, capacity)` items are available, then removes that many items. If `n` is less than or equal to zero, returns an empty array without modifying the queue. If the queue is closing, drains the currently available items and transitions to `Done`. If the queue is already done, the effect fails with the queue's completion cause. This function mutates the original TxQueue by removing the taken items. It does not return a new TxQueue reference. * - * **Mutation behavior**: This function mutates the original TxQueue by removing - * the taken items. It does not return a new TxQueue reference. + * **Example** (Taking a fixed number of values) * - * @example * ```ts * import { Effect, TxQueue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* TxQueue.bounded(5) - * yield* TxQueue.offerAll(queue, [1, 2, 3]) + * yield* TxQueue.offerAll(queue, [1, 2, 3, 4]) * - * // This will wait until 4 items are available - * // (will retry transaction until more items are offered) * const items = yield* TxQueue.takeN(queue, 4) + * console.log(items) // [1, 2, 3, 4] * * // This requests more than capacity (5), so takes all available (up to 5) - * const all = yield* TxQueue.takeN(queue, 10) // Takes at most 5 items + * yield* TxQueue.offerAll(queue, [5, 6, 7, 8, 9]) + * const all = yield* TxQueue.takeN(queue, 10) + * console.log(all) // [5, 6, 7, 8, 9] * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 2.0.0 */ (n: number): (self: TxDequeue) => Effect.Effect, E> /** - * Takes exactly N items from the queue in a single atomic transaction. + * Takes up to `n` items from the queue in a single transaction. * - * This function waits (retries the transaction) until N items are available, then takes - * exactly N items. The only exception is when N exceeds the queue's capacity - in that - * case, it takes up to the queue's capacity and returns immediately. + * **Details** * - * **Behavior**: - * - **Normal case**: Waits for exactly N items to be available - * - **Bounded queue with N > capacity**: Takes up to capacity items immediately - * - **Closing queue**: Takes available items and transitions to Done state + * For an open queue, waits until `min(n, capacity)` items are available, then removes that many items. If `n` is less than or equal to zero, returns an empty array without modifying the queue. If the queue is closing, drains the currently available items and transitions to `Done`. If the queue is already done, the effect fails with the queue's completion cause. This function mutates the original TxQueue by removing the taken items. It does not return a new TxQueue reference. * - * **Mutation behavior**: This function mutates the original TxQueue by removing - * the taken items. It does not return a new TxQueue reference. + * **Example** (Taking a fixed number of values) * - * @example * ```ts * import { Effect, TxQueue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* TxQueue.bounded(5) - * yield* TxQueue.offerAll(queue, [1, 2, 3]) + * yield* TxQueue.offerAll(queue, [1, 2, 3, 4]) * - * // This will wait until 4 items are available - * // (will retry transaction until more items are offered) * const items = yield* TxQueue.takeN(queue, 4) + * console.log(items) // [1, 2, 3, 4] * * // This requests more than capacity (5), so takes all available (up to 5) - * const all = yield* TxQueue.takeN(queue, 10) // Takes at most 5 items + * yield* TxQueue.offerAll(queue, [5, 6, 7, 8, 9]) + * const all = yield* TxQueue.takeN(queue, 10) + * console.log(all) // [5, 6, 7, 8, 9] * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 2.0.0 */ (self: TxDequeue, n: number): Effect.Effect, E> } = dual( @@ -1094,10 +1055,15 @@ export const takeN: { ) /** - * Takes a variable number of items between a specified minimum and maximum from the queue. - * Waits for at least the minimum number of items to be available. + * Takes between `min` and `max` currently available items, waiting for `min` on + * an open queue. + * + * **Details** + * + * If the queue is closing, drains the currently available items even when fewer than `min` are available and transitions to `Done`. Invalid ranges (`min <= 0`, `max <= 0`, or `min > max`) return an empty array. If the queue is already done, the effect fails with the queue's completion cause. + * + * **Example** (Taking batches within bounds) * - * @example * ```ts * import { Effect, TxQueue } from "effect" * @@ -1118,15 +1084,20 @@ export const takeN: { * }) * ``` * - * @since 4.0.0 * @category taking + * @since 2.0.0 */ export const takeBetween: { /** - * Takes a variable number of items between a specified minimum and maximum from the queue. - * Waits for at least the minimum number of items to be available. + * Takes between `min` and `max` currently available items, waiting for `min` on + * an open queue. + * + * **Details** + * + * If the queue is closing, drains the currently available items even when fewer than `min` are available and transitions to `Done`. Invalid ranges (`min <= 0`, `max <= 0`, or `min > max`) return an empty array. If the queue is already done, the effect fails with the queue's completion cause. + * + * **Example** (Taking batches within bounds) * - * @example * ```ts * import { Effect, TxQueue } from "effect" * @@ -1147,15 +1118,20 @@ export const takeBetween: { * }) * ``` * - * @since 4.0.0 * @category taking + * @since 2.0.0 */ (min: number, max: number): (self: TxDequeue) => Effect.Effect, E> /** - * Takes a variable number of items between a specified minimum and maximum from the queue. - * Waits for at least the minimum number of items to be available. + * Takes between `min` and `max` currently available items, waiting for `min` on + * an open queue. + * + * **Details** + * + * If the queue is closing, drains the currently available items even when fewer than `min` are available and transitions to `Done`. Invalid ranges (`min <= 0`, `max <= 0`, or `min > max`) return an empty array. If the queue is already done, the effect fails with the queue's completion cause. + * + * **Example** (Taking batches within bounds) * - * @example * ```ts * import { Effect, TxQueue } from "effect" * @@ -1176,8 +1152,8 @@ export const takeBetween: { * }) * ``` * - * @since 4.0.0 * @category taking + * @since 2.0.0 */ (self: TxDequeue, min: number, max: number): Effect.Effect, E> } = dual( @@ -1234,10 +1210,14 @@ export const takeBetween: { ) /** - * Views the next item without removing it. If the queue is in a failed state, - * the error is propagated through the E-channel. + * Waits transactionally for the next item and returns it without removing it. + * + * **Details** + * + * If the queue is open but empty, the transaction retries until an item is available or the queue completes. If the queue is done, the queue's completion cause is propagated through the error channel. + * + * **Example** (Peeking without removing values) * - * @example * ```ts * import { Effect, TxQueue } from "effect" * @@ -1265,8 +1245,8 @@ export const takeBetween: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 2.0.0 */ export const peek = (self: TxDequeue): Effect.Effect => Effect.gen(function*() { @@ -1287,7 +1267,8 @@ export const peek = (self: TxDequeue): Effect.Effect => /** * Gets the current size of the queue. * - * @example + * **Example** (Reading queue size) + * * ```ts * import { Effect, TxQueue } from "effect" * @@ -1300,15 +1281,16 @@ export const peek = (self: TxDequeue): Effect.Effect => * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 2.0.0 */ export const size = (self: TxQueueState): Effect.Effect => TxChunk.size(self.items) /** - * Checks if the queue is empty. + * Checks whether the queue is empty. + * + * **Example** (Checking whether a queue is empty) * - * @example * ```ts * import { Effect, TxQueue } from "effect" * @@ -1324,15 +1306,16 @@ export const size = (self: TxQueueState): Effect.Effect => TxChunk.size( * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 2.0.0 */ export const isEmpty = (self: TxQueueState): Effect.Effect => TxChunk.isEmpty(self.items) /** - * Checks if the queue is at capacity. + * Checks whether the queue is at capacity. + * + * **Example** (Checking whether a queue is full) * - * @example * ```ts * import { Effect, TxQueue } from "effect" * @@ -1348,8 +1331,8 @@ export const isEmpty = (self: TxQueueState): Effect.Effect => TxChunk.i * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 2.0.0 */ export const isFull = (self: TxQueueState): Effect.Effect => self.capacity === Number.POSITIVE_INFINITY @@ -1357,12 +1340,14 @@ export const isFull = (self: TxQueueState): Effect.Effect => : Effect.map(size(self), (currentSize) => currentSize >= self.capacity) /** - * Interrupts the queue, transitioning it to a closing state. + * Interrupts the queue gracefully with the current fiber's interruption cause. + * + * **Details** * - * **Mutation behavior**: This function mutates the original TxQueue by marking - * it for graceful closure. It does not return a new TxQueue reference. + * If the queue still contains items, it enters the closing state so buffered items can be drained before consumers observe the interruption. If it is empty, it transitions directly to done. Returns `false` if the queue was already closing or done. + * + * **Example** (Interrupting queues) * - * @example * ```ts * import { Effect, TxQueue } from "effect" * @@ -1376,19 +1361,21 @@ export const isFull = (self: TxQueueState): Effect.Effect => * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const interrupt = (self: TxEnqueue): Effect.Effect => Effect.withFiber((fiber) => failCause(self, Cause.interrupt(fiber.id))) /** - * Fails the queue with the specified error. + * Fails the queue with the specified error, discarding any buffered items. * - * **Mutation behavior**: This function mutates the original TxQueue by marking - * it as failed. It does not return a new TxQueue reference. + * **Details** + * + * The queue transitions directly to done with `Cause.fail(error)`. Returns `false` if the queue was already closing or done. + * + * **Example** (Failing queues) * - * @example * ```ts * import { Effect, TxQueue } from "effect" * @@ -1401,17 +1388,19 @@ export const interrupt = (self: TxEnqueue): Effect.Effect = * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const fail: { /** - * Fails the queue with the specified error. + * Fails the queue with the specified error, discarding any buffered items. + * + * **Details** * - * **Mutation behavior**: This function mutates the original TxQueue by marking - * it as failed. It does not return a new TxQueue reference. + * The queue transitions directly to done with `Cause.fail(error)`. Returns `false` if the queue was already closing or done. + * + * **Example** (Failing queues) * - * @example * ```ts * import { Effect, TxQueue } from "effect" * @@ -1424,17 +1413,19 @@ export const fail: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (error: E): (self: TxEnqueue) => Effect.Effect /** - * Fails the queue with the specified error. + * Fails the queue with the specified error, discarding any buffered items. * - * **Mutation behavior**: This function mutates the original TxQueue by marking - * it as failed. It does not return a new TxQueue reference. + * **Details** + * + * The queue transitions directly to done with `Cause.fail(error)`. Returns `false` if the queue was already closing or done. + * + * **Example** (Failing queues) * - * @example * ```ts * import { Effect, TxQueue } from "effect" * @@ -1447,8 +1438,8 @@ export const fail: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: TxEnqueue, error: E): Effect.Effect } = dual( @@ -1470,12 +1461,14 @@ export const fail: { ) /** - * Completes the queue with the specified exit value. + * Completes the queue with the specified cause. + * + * **Details** + * + * If the queue is empty, it transitions directly to done. If it still contains items, it enters the closing state so buffered items can be drained before the cause is observed. Returns `false` if the queue was already closing or done. * - * **Mutation behavior**: This function mutates the original TxQueue by marking - * it as completed. It does not return a new TxQueue reference. + * **Example** (Failing queues with causes) * - * @example * ```ts * import { Cause, Effect, TxQueue } from "effect" * @@ -1489,17 +1482,19 @@ export const fail: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const failCause: { /** - * Completes the queue with the specified exit value. + * Completes the queue with the specified cause. + * + * **Details** * - * **Mutation behavior**: This function mutates the original TxQueue by marking - * it as completed. It does not return a new TxQueue reference. + * If the queue is empty, it transitions directly to done. If it still contains items, it enters the closing state so buffered items can be drained before the cause is observed. Returns `false` if the queue was already closing or done. + * + * **Example** (Failing queues with causes) * - * @example * ```ts * import { Cause, Effect, TxQueue } from "effect" * @@ -1513,17 +1508,19 @@ export const failCause: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (cause: Cause.Cause): (self: TxEnqueue) => Effect.Effect /** - * Completes the queue with the specified exit value. + * Completes the queue with the specified cause. * - * **Mutation behavior**: This function mutates the original TxQueue by marking - * it as completed. It does not return a new TxQueue reference. + * **Details** + * + * If the queue is empty, it transitions directly to done. If it still contains items, it enters the closing state so buffered items can be drained before the cause is observed. Returns `false` if the queue was already closing or done. + * + * **Example** (Failing queues with causes) * - * @example * ```ts * import { Cause, Effect, TxQueue } from "effect" * @@ -1537,8 +1534,8 @@ export const failCause: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: TxEnqueue, cause: Cause.Cause): Effect.Effect } = dual( @@ -1564,22 +1561,19 @@ export const failCause: { ) /** - * Ends a queue by signaling completion with a Done error. + * Ends a queue by signaling completion with a `Cause.Done` error. + * + * **Details** + * + * This is a convenience wrapper around `failCause` for queues whose error channel can contain `Cause.Done`. If buffered items remain, the queue enters the closing state and those items may still be consumed before later `take` or `peek` operations fail with `Cause.Done`. * - * This function provides a clean way to signal the end of a queue by calling - * `failCause` with `Cause.Done`. This is a convenience function for - * queues that are typed to accept `Cause.Done` in their error channel. - * When a queue is ended, all subsequent operations (take, peek, etc.) will fail with - * `Cause.Done`, propagating through the E-channel. + * **Example** (Ending queues) * - * @example * ```ts * import { Cause, Effect, TxQueue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* TxQueue.bounded(10) - * yield* TxQueue.offer(queue, 1) - * yield* TxQueue.offer(queue, 2) * * // Signal the end of the queue * const result = yield* TxQueue.end(queue) @@ -1594,20 +1588,22 @@ export const failCause: { * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const end = (self: TxEnqueue): Effect.Effect => failCause(self, Cause.fail(Cause.Done())) /** - * Clears all elements from the queue without affecting its state. - * Returns the cleared elements, or an empty array if the queue is done with Done or interrupt. + * Removes and returns all currently buffered elements without changing the + * queue state. + * + * **Details** * - * **Mutation behavior**: This function mutates the original TxQueue by removing - * all elements. It does not return a new TxQueue reference. + * If the queue is already done with a `Cause.Done` error, returns an empty array. If the queue is done for any other cause, including interruption or failure, that cause is propagated. + * + * **Example** (Clearing queues) * - * @example * ```ts * import { Effect, TxQueue } from "effect" * @@ -1626,8 +1622,8 @@ export const end = (self: TxEnqueue): Effect.Effect(self: TxEnqueue): Effect.Effect, ExcludeDone> => Effect.gen(function*() { @@ -1647,14 +1643,12 @@ export const clear = (self: TxEnqueue): Effect.Effect, Excl /** * Shuts down the queue immediately by clearing all items and interrupting it (legacy compatibility). * - * This operation performs two atomic steps: - * 1. **Clears** all items from the queue using `clear()` - * 2. **Interrupts** the queue using `interrupt()` + * **Details** * - * **Mutation behavior**: This function mutates the original TxQueue by clearing - * its contents and marking it as shutdown. It does not return a new TxQueue reference. + * This operation clears all items from the queue using `clear`, then interrupts the queue using `interrupt`. This function mutates the original TxQueue by clearing its contents and marking it as shutdown. It does not return a new TxQueue reference. + * + * **Example** (Shutting down queues) * - * @example * ```ts * import { Effect, TxQueue } from "effect" * @@ -1675,8 +1669,8 @@ export const clear = (self: TxEnqueue): Effect.Effect, Excl * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 2.0.0 */ export const shutdown = (self: TxEnqueue): Effect.Effect => Effect.gen(function*() { @@ -1685,9 +1679,10 @@ export const shutdown = (self: TxEnqueue): Effect.Effect => }).pipe(Effect.tx) /** - * Checks if the queue is in the open state. + * Checks whether the queue is in the open state. + * + * **Example** (Checking open state) * - * @example * ```ts * import { Effect, TxQueue } from "effect" * @@ -1703,16 +1698,17 @@ export const shutdown = (self: TxEnqueue): Effect.Effect => * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const isOpen = (self: TxQueueState): Effect.Effect => Effect.map(TxRef.get(self.stateRef), (state) => state._tag === "Open") /** - * Checks if the queue is in the closing state. + * Checks whether the queue is in the closing state. + * + * **Example** (Checking closing state) * - * @example * ```ts * import { Effect, TxQueue } from "effect" * @@ -1729,16 +1725,17 @@ export const isOpen = (self: TxQueueState): Effect.Effect => * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const isClosing = (self: TxQueueState): Effect.Effect => Effect.map(TxRef.get(self.stateRef), (state) => state._tag === "Closing") /** - * Checks if the queue is done (completed or failed). + * Checks whether the queue is done (completed or failed). + * + * **Example** (Checking done state) * - * @example * ```ts * import { Effect, TxQueue } from "effect" * @@ -1754,16 +1751,17 @@ export const isClosing = (self: TxQueueState): Effect.Effect => * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const isDone = (self: TxQueueState): Effect.Effect => Effect.map(TxRef.get(self.stateRef), (state) => state._tag === "Done") /** - * Checks if the queue is shutdown (legacy compatibility). + * Checks whether the queue is shutdown (legacy compatibility). + * + * **Example** (Checking shutdown state) * - * @example * ```ts * import { Effect, TxQueue } from "effect" * @@ -1779,15 +1777,16 @@ export const isDone = (self: TxQueueState): Effect.Effect => * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 2.0.0 */ export const isShutdown = (self: TxQueueState): Effect.Effect => isDone(self) /** * Waits for the queue to complete (either successfully or with failure). * - * @example + * **Example** (Awaiting queue completion) + * * ```ts * import { Effect, TxQueue } from "effect" * @@ -1803,8 +1802,8 @@ export const isShutdown = (self: TxQueueState): Effect.Effect => isDone * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const awaitCompletion = (self: TxQueueState): Effect.Effect => Effect.gen(function*() { diff --git a/.opencode/node_modules/effect/src/TxReentrantLock.ts b/.opencode/node_modules/effect/src/TxReentrantLock.ts index 4be5ceab11e16856235ad11a9677b353a26631a5..faefa80a0ba85f88b8ac8dfcd7daf55fb4fa6980 100644 --- a/.opencode/node_modules/effect/src/TxReentrantLock.ts +++ b/.opencode/node_modules/effect/src/TxReentrantLock.ts @@ -1,8 +1,12 @@ /** - * TxReentrantLock is a transactional read/write lock with reentrant semantics using Software - * Transactional Memory (STM). Multiple readers can hold the lock concurrently, OR a single - * writer can hold exclusive access. A fiber holding a write lock may acquire additional - * read or write locks (reentrancy). + * Coordinates shared access inside transactions with read and write locks. + * + * A `TxReentrantLock` lets many fibers hold read locks at the same time, or one + * fiber hold a write lock for exclusive access. Lock ownership is tracked by + * fiber, so a fiber that already holds the lock can acquire it again and later + * release each acquisition. Attempts that cannot proceed retry transactionally + * until the lock becomes available. This module includes manual, scoped, and + * wrapper-style operations for read and write locking. * * @since 4.0.0 */ @@ -20,8 +24,8 @@ import * as TxRef from "./TxRef.ts" const TypeId = "~effect/transactions/TxReentrantLock" /** - * @since 4.0.0 * @category models + * @since 4.0.0 */ interface LockState { readonly readers: HashMap.HashMap @@ -38,7 +42,8 @@ const emptyState: LockState = { * Multiple readers can hold the lock concurrently, or a single writer can hold exclusive * access. A fiber holding the write lock may acquire additional read/write locks (reentrancy). * - * @example + * **Example** (Using read and write locks) + * * ```ts * import { Effect, TxReentrantLock } from "effect" * @@ -53,8 +58,8 @@ const emptyState: LockState = { * }) * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface TxReentrantLock extends Inspectable, Pipeable { readonly [TypeId]: typeof TypeId @@ -84,7 +89,8 @@ const TxReentrantLockProto: Omit = /** * Creates a new TxReentrantLock. * - * @example + * **Example** (Creating a reentrant lock) + * * ```ts * import { Effect, TxReentrantLock } from "effect" * @@ -95,8 +101,8 @@ const TxReentrantLockProto: Omit = * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 2.0.0 */ export const make = (): Effect.Effect => Effect.gen(function*() { @@ -116,7 +122,8 @@ export const make = (): Effect.Effect => * If the current fiber already holds the write lock, the read lock is granted (reentrancy). * Returns the current number of read locks held by this fiber. * - * @example + * **Example** (Acquiring a read lock) + * * ```ts * import { Effect, TxReentrantLock } from "effect" * @@ -128,8 +135,8 @@ export const make = (): Effect.Effect => * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ export const acquireRead = (self: TxReentrantLock): Effect.Effect => Effect.withFiber((fiber) => @@ -154,12 +161,23 @@ export const acquireRead = (self: TxReentrantLock): Effect.Effect => ) /** - * Acquires a write lock. Blocks if any other fiber holds any lock. - * If the current fiber already holds the write lock, the count is incremented (reentrancy). - * If the current fiber holds a read lock, the write lock is granted (upgrade). + * Acquires the write lock for the current fiber. + * + * **When to use** + * + * Use to enter an exclusive section manually when `withWriteLock` is not the + * right shape. + * + * **Details** + * + * Blocks if any other fiber holds a read or write lock. If the current fiber + * already holds the write lock, the count is incremented. If the current fiber + * holds a read lock, the write lock is granted as an upgrade. + * * Returns the current number of write locks held by this fiber. * - * @example + * **Example** (Acquiring a write lock) + * * ```ts * import { Effect, TxReentrantLock } from "effect" * @@ -171,8 +189,8 @@ export const acquireRead = (self: TxReentrantLock): Effect.Effect => * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ export const acquireWrite = (self: TxReentrantLock): Effect.Effect => Effect.withFiber((fiber) => @@ -213,10 +231,18 @@ export const acquireWrite = (self: TxReentrantLock): Effect.Effect => ) /** - * Releases a read lock held by the current fiber. + * Releases one read lock held by the current fiber. + * + * **When to use** + * + * Use to leave a manually acquired read lock. + * + * **Details** + * * Returns the remaining number of read locks held by this fiber. * - * @example + * **Example** (Releasing a read lock) + * * ```ts * import { Effect, TxReentrantLock } from "effect" * @@ -228,8 +254,8 @@ export const acquireWrite = (self: TxReentrantLock): Effect.Effect => * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ export const releaseRead = (self: TxReentrantLock): Effect.Effect => Effect.withFiber((fiber) => @@ -251,10 +277,18 @@ export const releaseRead = (self: TxReentrantLock): Effect.Effect => ) /** - * Releases a write lock held by the current fiber. + * Releases one write lock held by the current fiber. + * + * **When to use** + * + * Use to leave a manually acquired write lock. + * + * **Details** + * * Returns the remaining number of write locks held by this fiber. * - * @example + * **Example** (Releasing a write lock) + * * ```ts * import { Effect, TxReentrantLock } from "effect" * @@ -266,8 +300,8 @@ export const releaseRead = (self: TxReentrantLock): Effect.Effect => * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ export const releaseWrite = (self: TxReentrantLock): Effect.Effect => Effect.withFiber((fiber) => @@ -291,7 +325,8 @@ export const releaseWrite = (self: TxReentrantLock): Effect.Effect => * Acquires a read lock for the duration of the scope. * The lock is automatically released when the scope closes. * - * @example + * **Example** (Holding a scoped read lock) + * * ```ts * import { Effect, TxReentrantLock } from "effect" * @@ -308,8 +343,8 @@ export const releaseWrite = (self: TxReentrantLock): Effect.Effect => * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ export const readLock = (self: TxReentrantLock): Effect.Effect => Effect.acquireRelease( @@ -321,7 +356,8 @@ export const readLock = (self: TxReentrantLock): Effect.Effect => Effect.acquireRelease( @@ -351,7 +387,8 @@ export const writeLock = (self: TxReentrantLock): Effect.Effect(effect: Effect.Effect): (self: TxReentrantLock) => Effect.Effect /** * Runs the provided effect while holding a read lock. The lock is automatically * released after the effect completes, fails, or is interrupted. * - * @example + * **Example** (Running an effect with a read lock) + * * ```ts * import { Effect, TxReentrantLock } from "effect" * @@ -409,8 +448,8 @@ export const withReadLock: { * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ (self: TxReentrantLock, effect: Effect.Effect): Effect.Effect } = ((...args: Array) => { @@ -435,7 +474,8 @@ export const withReadLock: { * Runs the provided effect while holding a write lock. The lock is automatically * released after the effect completes, fails, or is interrupted. * - * @example + * **Example** (Running an effect with a write lock) + * * ```ts * import { Effect, TxReentrantLock } from "effect" * @@ -449,15 +489,16 @@ export const withReadLock: { * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ export const withWriteLock: { /** * Runs the provided effect while holding a write lock. The lock is automatically * released after the effect completes, fails, or is interrupted. * - * @example + * **Example** (Running an effect with a write lock) + * * ```ts * import { Effect, TxReentrantLock } from "effect" * @@ -471,15 +512,16 @@ export const withWriteLock: { * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ (effect: Effect.Effect): (self: TxReentrantLock) => Effect.Effect /** * Runs the provided effect while holding a write lock. The lock is automatically * released after the effect completes, fails, or is interrupted. * - * @example + * **Example** (Running an effect with a write lock) + * * ```ts * import { Effect, TxReentrantLock } from "effect" * @@ -493,8 +535,8 @@ export const withWriteLock: { * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ (self: TxReentrantLock, effect: Effect.Effect): Effect.Effect } = ((...args: Array) => { @@ -516,9 +558,15 @@ export const withWriteLock: { }) as any /** - * Alias for `withWriteLock`. Runs the provided effect while holding a write lock. + * Runs an effect while holding a write lock. + * + * **When to use** + * + * Use when you need to run an effect with exclusive write access through a + * `TxReentrantLock` and prefer the concise lock helper. + * + * **Example** (Running an effect with exclusive access) * - * @example * ```ts * import { Effect, TxReentrantLock } from "effect" * @@ -532,14 +580,20 @@ export const withWriteLock: { * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ export const withLock: { /** - * Alias for `withWriteLock`. Runs the provided effect while holding a write lock. + * Runs an effect while holding a write lock. + * + * **When to use** + * + * Use when you need to run an effect with exclusive write access through a + * `TxReentrantLock` and prefer the concise lock helper. + * + * **Example** (Running an effect with exclusive access) * - * @example * ```ts * import { Effect, TxReentrantLock } from "effect" * @@ -553,14 +607,20 @@ export const withLock: { * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ (effect: Effect.Effect): (self: TxReentrantLock) => Effect.Effect /** - * Alias for `withWriteLock`. Runs the provided effect while holding a write lock. + * Runs an effect while holding a write lock. + * + * **When to use** + * + * Use when you need to run an effect with exclusive write access through a + * `TxReentrantLock` and prefer the concise lock helper. + * + * **Example** (Running an effect with exclusive access) * - * @example * ```ts * import { Effect, TxReentrantLock } from "effect" * @@ -574,8 +634,8 @@ export const withLock: { * }) * ``` * - * @since 4.0.0 * @category mutations + * @since 2.0.0 */ (self: TxReentrantLock, effect: Effect.Effect): Effect.Effect } = withWriteLock @@ -587,7 +647,8 @@ export const withLock: { /** * Returns the total number of read locks held across all fibers. * - * @example + * **Example** (Counting read locks) + * * ```ts * import { Effect, TxReentrantLock } from "effect" * @@ -600,8 +661,8 @@ export const withLock: { * }) * ``` * - * @since 4.0.0 * @category getters + * @since 2.0.0 */ export const readLocks = (self: TxReentrantLock): Effect.Effect => Effect.gen(function*() { @@ -616,7 +677,8 @@ export const readLocks = (self: TxReentrantLock): Effect.Effect => /** * Returns the number of write locks held (0 or the reentrant count). * - * @example + * **Example** (Counting write locks) + * * ```ts * import { Effect, TxReentrantLock } from "effect" * @@ -627,8 +689,8 @@ export const readLocks = (self: TxReentrantLock): Effect.Effect => * }) * ``` * - * @since 4.0.0 * @category getters + * @since 2.0.0 */ export const writeLocks = (self: TxReentrantLock): Effect.Effect => Effect.gen(function*() { @@ -637,9 +699,10 @@ export const writeLocks = (self: TxReentrantLock): Effect.Effect => }) /** - * Checks if the lock is held by any fiber (read or write). + * Checks whether the lock is held by any fiber (read or write). + * + * **Example** (Checking whether a lock is held) * - * @example * ```ts * import { Effect, TxReentrantLock } from "effect" * @@ -650,8 +713,8 @@ export const writeLocks = (self: TxReentrantLock): Effect.Effect => * }) * ``` * - * @since 4.0.0 * @category getters + * @since 2.0.0 */ export const locked = (self: TxReentrantLock): Effect.Effect => Effect.gen(function*() { @@ -660,9 +723,10 @@ export const locked = (self: TxReentrantLock): Effect.Effect => }) /** - * Checks if any fiber holds a read lock. + * Checks whether any fiber holds a read lock. + * + * **Example** (Checking whether a read lock is held) * - * @example * ```ts * import { Effect, TxReentrantLock } from "effect" * @@ -673,8 +737,8 @@ export const locked = (self: TxReentrantLock): Effect.Effect => * }) * ``` * - * @since 4.0.0 * @category getters + * @since 2.0.0 */ export const readLocked = (self: TxReentrantLock): Effect.Effect => Effect.gen(function*() { @@ -683,9 +747,10 @@ export const readLocked = (self: TxReentrantLock): Effect.Effect => }) /** - * Checks if any fiber holds a write lock. + * Checks whether any fiber holds a write lock. + * + * **Example** (Checking whether a write lock is held) * - * @example * ```ts * import { Effect, TxReentrantLock } from "effect" * @@ -696,8 +761,8 @@ export const readLocked = (self: TxReentrantLock): Effect.Effect => * }) * ``` * - * @since 4.0.0 * @category getters + * @since 2.0.0 */ export const writeLocked = (self: TxReentrantLock): Effect.Effect => Effect.gen(function*() { @@ -710,9 +775,10 @@ export const writeLocked = (self: TxReentrantLock): Effect.Effect => // ============================================================================= /** - * Checks if the given value is a TxReentrantLock. + * Checks whether the given value is a TxReentrantLock. + * + * **Example** (Checking for TxReentrantLock values) * - * @example * ```ts * import { TxReentrantLock } from "effect" * @@ -723,7 +789,7 @@ export const writeLocked = (self: TxReentrantLock): Effect.Effect => * } * ``` * - * @since 4.0.0 * @category guards + * @since 4.0.0 */ export const isTxReentrantLock = (u: unknown): u is TxReentrantLock => hasProperty(u, TypeId) diff --git a/.opencode/node_modules/effect/src/TxRef.ts b/.opencode/node_modules/effect/src/TxRef.ts index 08aa428138eef64d7484e53b693ff7062062adc2..bbaed45e3f11af212e42b99616440acc5b91958a 100644 --- a/.opencode/node_modules/effect/src/TxRef.ts +++ b/.opencode/node_modules/effect/src/TxRef.ts @@ -1,10 +1,13 @@ /** - * TxRef is a transactional value, it can be read and modified within the body of a transaction. + * Transactional references for coordinating mutable state with Effect + * transactions. A `TxRef` stores a current value, but reads and writes inside + * `Effect.tx` are recorded in a transaction journal and committed together only + * when the outermost transaction succeeds. * - * Accessed values are tracked by the transaction in order to detect conflicts and in order to - * track changes, a transaction will retry whenever a conflict is detected or whenever the - * transaction explicitely calls to `Effect.txRetry` and any of the accessed TxRef values - * change. + * This is the basic building block behind the other transactional collections + * in Effect. The module provides effectful and unsafe constructors plus the + * core operations for reading, setting, updating, and modifying a transactional + * value while returning a separate result. * * @since 4.0.0 */ @@ -19,14 +22,20 @@ const TypeId = "~effect/transactions/TxRef" /** * TxRef is a transactional value, it can be read and modified within the body of a transaction. * + * **When to use** + * + * Use to store mutable state that must be read and modified inside Effect + * transactions. + * + * **Details** + * * Accessed values are tracked by the transaction in order to detect conflicts and in order to * track changes, a transaction will retry whenever a conflict is detected or whenever the * transaction explicitely calls to `Effect.txRetry` and any of the accessed TxRef values * change. * - * @since 4.0.0 - * @category Models - * @example + * **Example** (Using a transactional reference) + * * ```ts * import { Effect, TxRef } from "effect" * @@ -44,6 +53,9 @@ const TypeId = "~effect/transactions/TxRef" * console.log(final) // 1 * }) * ``` + * + * @category models + * @since 4.0.0 */ export interface TxRef extends Pipeable { readonly [TypeId]: typeof TypeId @@ -56,9 +68,12 @@ export interface TxRef extends Pipeable { /** * Creates a new `TxRef` with the specified initial value. * - * @since 4.0.0 - * @category Constructors - * @example + * **When to use** + * + * Use to create a `TxRef` inside an `Effect` workflow. + * + * **Example** (Creating transactional references) + * * ```ts * import { Effect, TxRef } from "effect" * @@ -77,15 +92,22 @@ export interface TxRef extends Pipeable { * console.log(yield* TxRef.get(name)) // "Bob" * }) * ``` + * + * @category constructors + * @since 2.0.0 */ export const make = (initial: A) => Effect.sync(() => makeUnsafe(initial)) /** - * Creates a new `TxRef` with the specified initial value. + * Creates a new `TxRef` synchronously with the specified initial value. + * + * **When to use** + * + * Use to construct a `TxRef` synchronously when it must be created outside an + * `Effect` workflow. + * + * **Example** (Creating transactional references unsafely) * - * @since 4.0.0 - * @category Constructors - * @example * ```ts * import { TxRef } from "effect" * @@ -97,6 +119,9 @@ export const make = (initial: A) => Effect.sync(() => makeUnsafe(initial)) * console.log(counter.value) // 0 * console.log(config.value) // { timeout: 5000, retries: 3 } * ``` + * + * @category constructors + * @since 4.0.0 */ export const makeUnsafe = (initial: A): TxRef => ({ [TypeId]: TypeId, @@ -111,9 +136,13 @@ export const makeUnsafe = (initial: A): TxRef => ({ /** * Modifies the value of the `TxRef` using the provided function. * - * @since 4.0.0 - * @category Combinators - * @example + * **When to use** + * + * Use to update a `TxRef` and return a computed result from the same + * transaction step. + * + * **Example** (Modifying transactional references) + * * ```ts * import { Effect, TxRef } from "effect" * @@ -127,14 +156,21 @@ export const makeUnsafe = (initial: A): TxRef => ({ * console.log(yield* TxRef.get(counter)) // 1 (the new value: current + 1) * }) * ``` + * + * @category combinators + * @since 2.0.0 */ export const modify: { /** * Modifies the value of the `TxRef` using the provided function. * - * @since 4.0.0 - * @category Combinators - * @example + * **When to use** + * + * Use to update a `TxRef` and return a computed result from the same + * transaction step. + * + * **Example** (Modifying transactional references) + * * ```ts * import { Effect, TxRef } from "effect" * @@ -148,14 +184,21 @@ export const modify: { * console.log(yield* TxRef.get(counter)) // 1 (the new value: current + 1) * }) * ``` + * + * @category combinators + * @since 2.0.0 */ (f: (current: NoInfer) => [returnValue: R, newValue: A]): (self: TxRef) => Effect.Effect /** * Modifies the value of the `TxRef` using the provided function. * - * @since 4.0.0 - * @category Combinators - * @example + * **When to use** + * + * Use to update a `TxRef` and return a computed result from the same + * transaction step. + * + * **Example** (Modifying transactional references) + * * ```ts * import { Effect, TxRef } from "effect" * @@ -169,13 +212,16 @@ export const modify: { * console.log(yield* TxRef.get(counter)) // 1 (the new value: current + 1) * }) * ``` + * + * @category combinators + * @since 2.0.0 */ (self: TxRef, f: (current: A) => [returnValue: R, newValue: A]): Effect.Effect } = dual(2, ( self: TxRef, f: (current: A) => [returnValue: R, newValue: A] ): Effect.Effect => - Effect.Transaction.asEffect().pipe( + Effect.Transaction.pipe( Effect.flatMap((state) => Effect.sync(() => { if (!state.journal.has(self)) { @@ -193,9 +239,12 @@ export const modify: { /** * Updates the value of the `TxRef` using the provided function. * - * @since 4.0.0 - * @category Combinators - * @example + * **When to use** + * + * Use to transform a `TxRef` when no result value is needed. + * + * **Example** (Updating transactional references) + * * ```ts * import { Effect, TxRef } from "effect" * @@ -210,14 +259,20 @@ export const modify: { * console.log(yield* TxRef.get(counter)) // 20 * }) * ``` + * + * @category combinators + * @since 2.0.0 */ export const update: { /** * Updates the value of the `TxRef` using the provided function. * - * @since 4.0.0 - * @category Combinators - * @example + * **When to use** + * + * Use to transform a `TxRef` when no result value is needed. + * + * **Example** (Updating transactional references) + * * ```ts * import { Effect, TxRef } from "effect" * @@ -232,14 +287,20 @@ export const update: { * console.log(yield* TxRef.get(counter)) // 20 * }) * ``` + * + * @category combinators + * @since 2.0.0 */ (f: (current: NoInfer) => A): (self: TxRef) => Effect.Effect /** * Updates the value of the `TxRef` using the provided function. * - * @since 4.0.0 - * @category Combinators - * @example + * **When to use** + * + * Use to transform a `TxRef` when no result value is needed. + * + * **Example** (Updating transactional references) + * * ```ts * import { Effect, TxRef } from "effect" * @@ -254,6 +315,9 @@ export const update: { * console.log(yield* TxRef.get(counter)) // 20 * }) * ``` + * + * @category combinators + * @since 2.0.0 */ (self: TxRef, f: (current: A) => A): Effect.Effect } = dual(2, ( @@ -264,9 +328,12 @@ export const update: { /** * Reads the current value of the `TxRef`. * - * @since 4.0.0 - * @category Combinators - * @example + * **When to use** + * + * Use to read the current value of a `TxRef`. + * + * **Example** (Reading transactional references) + * * ```ts * import { Effect, TxRef } from "effect" * @@ -281,15 +348,21 @@ export const update: { * console.log(value) // 42 * }) * ``` + * + * @category combinators + * @since 2.0.0 */ export const get = (self: TxRef): Effect.Effect => modify(self, (current) => [current, current]) /** * Sets the value of the `TxRef`. * - * @since 4.0.0 - * @category Combinators - * @example + * **When to use** + * + * Use to replace the value of a `TxRef`. + * + * **Example** (Setting transactional references) + * * ```ts * import { Effect, TxRef } from "effect" * @@ -304,14 +377,20 @@ export const get = (self: TxRef): Effect.Effect => modify(self, (curren * console.log(yield* TxRef.get(counter)) // 100 * }) * ``` + * + * @category combinators + * @since 2.0.0 */ export const set: { /** * Sets the value of the `TxRef`. * - * @since 4.0.0 - * @category Combinators - * @example + * **When to use** + * + * Use to replace the value of a `TxRef`. + * + * **Example** (Setting transactional references) + * * ```ts * import { Effect, TxRef } from "effect" * @@ -326,14 +405,20 @@ export const set: { * console.log(yield* TxRef.get(counter)) // 100 * }) * ``` + * + * @category combinators + * @since 2.0.0 */ (value: A): (self: TxRef) => Effect.Effect /** * Sets the value of the `TxRef`. * - * @since 4.0.0 - * @category Combinators - * @example + * **When to use** + * + * Use to replace the value of a `TxRef`. + * + * **Example** (Setting transactional references) + * * ```ts * import { Effect, TxRef } from "effect" * @@ -348,6 +433,9 @@ export const set: { * console.log(yield* TxRef.get(counter)) // 100 * }) * ``` + * + * @category combinators + * @since 2.0.0 */ (self: TxRef, value: A): Effect.Effect } = dual(2, ( diff --git a/.opencode/node_modules/effect/src/TxSemaphore.ts b/.opencode/node_modules/effect/src/TxSemaphore.ts index e7cd185fcc0f4df94f24e9f0f4e168b95333d696..5a6d1fca8d7f6e7ef601a425409d477e726a5d40 100644 --- a/.opencode/node_modules/effect/src/TxSemaphore.ts +++ b/.opencode/node_modules/effect/src/TxSemaphore.ts @@ -1,4 +1,12 @@ /** + * Coordinates access to limited resources inside transactions. + * + * A `TxSemaphore` has a fixed capacity and stores its available permit count in + * a `TxRef`. Acquiring or releasing permits can therefore commit atomically + * with other transactional state changes. This module includes operations for + * creating semaphores, checking capacity and availability, acquiring or + * releasing permits, and running effects while permits are held. + * * @since 4.0.0 */ @@ -14,12 +22,18 @@ import * as TxRef from "./TxRef.ts" const TypeId = "~effect/transactions/TxSemaphore" /** - * A transactional semaphore that manages permits using Software Transactional Memory (STM) semantics. + * A transactional semaphore that manages permits using Software Transactional + * Memory (STM) semantics, providing atomic permit acquisition and release + * operations within Effect transactions for concurrency control over limited + * resources. + * + * **When to use** + * + * Use to coordinate permit accounting atomically with other transactional + * state changes. * - * TxSemaphore provides atomic permit acquisition and release operations within Effect transactions, - * ensuring thread-safe concurrency control for limited resources. + * **Example** (Managing permits transactionally) * - * @example * ```ts * import { Effect, TxSemaphore } from "effect" * @@ -39,8 +53,12 @@ const TypeId = "~effect/transactions/TxSemaphore" * }) * ``` * - * @since 4.0.0 + * @see {@link make} for creating a transactional semaphore + * @see {@link withPermit} for automatically acquiring and releasing one permit + * @see {@link acquire} for manually acquiring one permit transactionally + * * @category models + * @since 4.0.0 */ export interface TxSemaphore extends Inspectable, Pipeable { readonly [TypeId]: typeof TypeId @@ -74,7 +92,12 @@ const makeTxSemaphore = (permitsRef: TxRef.TxRef, capacity: number): TxS /** * Creates a new TxSemaphore with the specified number of permits. * - * @example + * **When to use** + * + * Use to create a transactional semaphore with a fixed permit capacity. + * + * **Example** (Creating a semaphore) + * * ```ts * import { Console, Effect, TxSemaphore } from "effect" * @@ -94,12 +117,11 @@ const makeTxSemaphore = (permitsRef: TxRef.TxRef, capacity: number): TxS * }) * ``` * - * @param permits - The initial number of permits (must be non-negative) - * @returns Effect that succeeds with a new TxSemaphore - * @throws Defect if permits is negative + * @see {@link available} for reading the current available permit count + * @see {@link capacity} for reading the fixed total permit count * - * @since 4.0.0 * @category constructors + * @since 2.0.0 */ export const make = (permits: number): Effect.Effect => Effect.gen(function*() { @@ -114,7 +136,12 @@ export const make = (permits: number): Effect.Effect => /** * Gets the current number of available permits in the semaphore. * - * @example + * **When to use** + * + * Use to inspect how many permits are currently available. + * + * **Example** (Checking available permits) + * * ```ts * import { Console, Effect, TxSemaphore } from "effect" * @@ -135,18 +162,22 @@ export const make = (permits: number): Effect.Effect => * }) * ``` * - * @param self - The TxSemaphore to inspect - * @returns Effect that succeeds with the current number of available permits + * @see {@link capacity} for reading the fixed total permit count * - * @since 4.0.0 * @category combinators + * @since 2.0.0 */ export const available = (self: TxSemaphore): Effect.Effect => TxRef.get(self.permitsRef) /** * Gets the maximum capacity (total permits) of the semaphore. * - * @example + * **When to use** + * + * Use to inspect the fixed total number of permits managed by the semaphore. + * + * **Example** (Checking semaphore capacity) + * * ```ts * import { Console, Effect, TxSemaphore } from "effect" * @@ -163,11 +194,10 @@ export const available = (self: TxSemaphore): Effect.Effect => TxRef.get * }) * ``` * - * @param self - The TxSemaphore to inspect - * @returns Effect that succeeds with the semaphore's maximum capacity + * @see {@link available} for reading the current available permit count * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const capacity = (self: TxSemaphore): Effect.Effect => Effect.succeed(self.capacity) @@ -175,7 +205,13 @@ export const capacity = (self: TxSemaphore): Effect.Effect => Effect.suc * Acquires a single permit from the semaphore. If no permits are available, * the effect will block until one becomes available. * - * @example + * **When to use** + * + * Use to manually acquire one permit transactionally, waiting until one is + * available. + * + * **Example** (Acquiring a permit) + * * ```ts * import { Console, Effect, TxSemaphore } from "effect" * @@ -195,11 +231,12 @@ export const capacity = (self: TxSemaphore): Effect.Effect => Effect.suc * }) * ``` * - * @param self - The TxSemaphore from which to acquire a permit - * @returns Effect that succeeds when a permit is acquired + * @see {@link tryAcquire} for a non-blocking single-permit attempt + * @see {@link release} for returning one permit + * @see {@link withPermit} for automatic acquire and release around an effect * - * @since 4.0.0 * @category combinators + * @since 2.0.0 */ export const acquire = (self: TxSemaphore): Effect.Effect => Effect.gen(function*() { @@ -211,10 +248,25 @@ export const acquire = (self: TxSemaphore): Effect.Effect => }).pipe(Effect.tx) /** - * Acquires the specified number of permits from the semaphore. If not enough - * permits are available, the effect will block until they become available. + * Acquires the specified number of permits from the semaphore. + * + * **When to use** + * + * Use to manually acquire multiple permits transactionally, waiting until all + * requested permits are available. + * + * **Details** + * + * If fewer than `n` permits are available, the transaction retries until enough + * permits are released. + * + * **Gotchas** + * + * Passing a non-positive `n` dies with a defect. Passing a value greater than + * the semaphore capacity can wait forever because the capacity is fixed. + * + * **Example** (Acquiring multiple permits) * - * @example * ```ts * import { Console, Effect, TxSemaphore } from "effect" * @@ -230,12 +282,12 @@ export const acquire = (self: TxSemaphore): Effect.Effect => * }) * ``` * - * @param self - The TxSemaphore from which to acquire permits - * @param n - The number of permits to acquire (must be positive) - * @returns Effect that succeeds when the permits are acquired + * @see {@link tryAcquireN} for a non-blocking multi-permit attempt + * @see {@link releaseN} for returning multiple permits + * @see {@link withPermits} for automatic acquire and release around an effect * - * @since 4.0.0 * @category combinators + * @since 2.0.0 */ export const acquireN = (self: TxSemaphore, n: number): Effect.Effect => { if (n <= 0) { @@ -251,10 +303,16 @@ export const acquireN = (self: TxSemaphore, n: number): Effect.Effect => { } /** - * Tries to acquire a single permit from the semaphore without blocking. - * Returns true if successful, false if no permits are available. + * Tries to acquire a single permit from the semaphore without blocking, + * returning `true` if successful or `false` if no permits are available. + * + * **When to use** + * + * Use to attempt a single-permit acquisition without retrying when no permit is + * available. + * + * **Example** (Trying to acquire a permit) * - * @example * ```ts * import { Console, Effect, TxSemaphore } from "effect" * @@ -271,11 +329,11 @@ export const acquireN = (self: TxSemaphore, n: number): Effect.Effect => { * }) * ``` * - * @param self - The TxSemaphore from which to try acquiring a permit - * @returns Effect that succeeds with true if permit acquired, false otherwise + * @see {@link acquire} for waiting until one permit is available + * @see {@link tryAcquireN} for attempting to acquire multiple permits without blocking * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const tryAcquire = (self: TxSemaphore): Effect.Effect => TxRef.modify(self.permitsRef, (permits: number) => { @@ -286,10 +344,17 @@ export const tryAcquire = (self: TxSemaphore): Effect.Effect => }) /** - * Tries to acquire the specified number of permits from the semaphore without blocking. - * Returns true if successful, false if not enough permits are available. + * Tries to acquire the specified number of permits from the semaphore without + * blocking, returning `true` if successful or `false` if not enough permits are + * available. + * + * **When to use** + * + * Use to attempt a multi-permit acquisition without retrying when not enough + * permits are available. + * + * **Example** (Trying to acquire multiple permits) * - * @example * ```ts * import { Console, Effect, TxSemaphore } from "effect" * @@ -306,12 +371,11 @@ export const tryAcquire = (self: TxSemaphore): Effect.Effect => * }) * ``` * - * @param self - The TxSemaphore from which to try acquiring permits - * @param n - The number of permits to try acquiring (must be positive) - * @returns Effect that succeeds with true if permits acquired, false otherwise + * @see {@link acquireN} for waiting until all requested permits are available + * @see {@link tryAcquire} for attempting to acquire one permit without blocking * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const tryAcquireN = (self: TxSemaphore, n: number): Effect.Effect => { if (n <= 0) { @@ -326,9 +390,20 @@ export const tryAcquireN = (self: TxSemaphore, n: number): Effect.Effect => TxRef.update(self.permitsRef, (permits: number) => permits >= self.capacity ? permits : permits + 1) @@ -359,7 +434,20 @@ export const release = (self: TxSemaphore): Effect.Effect => /** * Releases the specified number of permits back to the semaphore. * - * @example + * **When to use** + * + * Use to manually return multiple permits after a transactional acquire. + * + * **Details** + * + * The available permit count is capped at the semaphore capacity. + * + * **Gotchas** + * + * Passing a non-positive `n` dies with a defect. + * + * **Example** (Releasing multiple permits) + * * ```ts * import { Console, Effect, TxSemaphore } from "effect" * @@ -378,12 +466,11 @@ export const release = (self: TxSemaphore): Effect.Effect => * }) * ``` * - * @param self - The TxSemaphore to which to release permits - * @param n - The number of permits to release (must be positive) - * @returns Effect that succeeds when the permits are released + * @see {@link acquireN} for manually acquiring multiple permits + * @see {@link release} for returning one permit * - * @since 4.0.0 * @category combinators + * @since 2.0.0 */ export const releaseN = (self: TxSemaphore, n: number): Effect.Effect => { if (n <= 0) { @@ -400,10 +487,18 @@ export const releaseN = (self: TxSemaphore, n: number): Effect.Effect => { * automatically acquired before execution and released afterwards, even if the * effect fails or is interrupted. * - * **Note**: The permit acquisition and release operations use atomic semantics - * to ensure proper resource management with Effect's scoped operations. + * **When to use** + * + * Use to run an effect while automatically acquiring and releasing one + * transactional permit. + * + * **Details** + * + * The permit acquisition and release operations use atomic semantics to ensure + * proper resource management with Effect's scoped operations. + * + * **Example** (Running an effect with a permit) * - * @example * ```ts * import { Console, Effect, TxSemaphore } from "effect" * @@ -426,12 +521,12 @@ export const releaseN = (self: TxSemaphore, n: number): Effect.Effect => { * }) * ``` * - * @param self - The TxSemaphore to acquire a permit from - * @param effect - The effect to execute with the permit - * @returns Effect that succeeds with the result of the provided effect + * @see {@link withPermits} for automatically acquiring and releasing multiple permits + * @see {@link withPermitScoped} for acquiring one permit for the current scope + * @see {@link acquire} for manual single-permit acquisition * - * @since 4.0.0 * @category combinators + * @since 2.0.0 */ export const withPermit: { /** @@ -439,10 +534,18 @@ export const withPermit: { * automatically acquired before execution and released afterwards, even if the * effect fails or is interrupted. * - * **Note**: The permit acquisition and release operations use atomic semantics - * to ensure proper resource management with Effect's scoped operations. + * **When to use** + * + * Use to run an effect while automatically acquiring and releasing one + * transactional permit. + * + * **Details** + * + * The permit acquisition and release operations use atomic semantics to ensure + * proper resource management with Effect's scoped operations. + * + * **Example** (Running an effect with a permit) * - * @example * ```ts * import { Console, Effect, TxSemaphore } from "effect" * @@ -465,12 +568,12 @@ export const withPermit: { * }) * ``` * - * @param self - The TxSemaphore to acquire a permit from - * @param effect - The effect to execute with the permit - * @returns Effect that succeeds with the result of the provided effect + * @see {@link withPermits} for automatically acquiring and releasing multiple permits + * @see {@link withPermitScoped} for acquiring one permit for the current scope + * @see {@link acquire} for manual single-permit acquisition * - * @since 4.0.0 * @category combinators + * @since 2.0.0 */ (self: TxSemaphore): (effect: Effect.Effect) => Effect.Effect /** @@ -478,10 +581,18 @@ export const withPermit: { * automatically acquired before execution and released afterwards, even if the * effect fails or is interrupted. * - * **Note**: The permit acquisition and release operations use atomic semantics - * to ensure proper resource management with Effect's scoped operations. + * **When to use** + * + * Use to run an effect while automatically acquiring and releasing one + * transactional permit. + * + * **Details** + * + * The permit acquisition and release operations use atomic semantics to ensure + * proper resource management with Effect's scoped operations. + * + * **Example** (Running an effect with a permit) * - * @example * ```ts * import { Console, Effect, TxSemaphore } from "effect" * @@ -504,12 +615,12 @@ export const withPermit: { * }) * ``` * - * @param self - The TxSemaphore to acquire a permit from - * @param effect - The effect to execute with the permit - * @returns Effect that succeeds with the result of the provided effect + * @see {@link withPermits} for automatically acquiring and releasing multiple permits + * @see {@link withPermitScoped} for acquiring one permit for the current scope + * @see {@link acquire} for manual single-permit acquisition * - * @since 4.0.0 * @category combinators + * @since 2.0.0 */ (self: TxSemaphore, effect: Effect.Effect): Effect.Effect } = ((...args: Array) => { @@ -531,14 +642,26 @@ export const withPermit: { }) as any /** - * Executes an effect with the specified number of permits from the semaphore. - * The permits are automatically acquired before execution and released afterwards, - * even if the effect fails or is interrupted. + * Runs an effect while holding the specified number of permits from the + * semaphore. + * + * **When to use** + * + * Use to run an effect while automatically acquiring and releasing multiple + * transactional permits. + * + * **Details** + * + * The permits are acquired before the effect starts and released after it + * completes, fails, or is interrupted. + * + * **Gotchas** + * + * Passing a non-positive `n` dies with a defect. Passing a value greater than + * the semaphore capacity can wait forever. * - * **Note**: The permit acquisition and release operations use atomic semantics - * to ensure proper resource management with Effect's scoped operations. + * **Example** (Running an effect with multiple permits) * - * @example * ```ts * import { Console, Effect, TxSemaphore } from "effect" * @@ -561,24 +684,34 @@ export const withPermit: { * }) * ``` * - * @param self - The TxSemaphore to acquire permits from - * @param n - The number of permits to acquire (must be positive) - * @param effect - The effect to execute with the permits - * @returns Effect that succeeds with the result of the provided effect + * @see {@link withPermit} for automatically acquiring and releasing one permit + * @see {@link acquireN} for manual multi-permit acquisition * - * @since 4.0.0 * @category combinators + * @since 2.0.0 */ export const withPermits: { /** - * Executes an effect with the specified number of permits from the semaphore. - * The permits are automatically acquired before execution and released afterwards, - * even if the effect fails or is interrupted. + * Runs an effect while holding the specified number of permits from the + * semaphore. + * + * **When to use** + * + * Use to run an effect while automatically acquiring and releasing multiple + * transactional permits. + * + * **Details** + * + * The permits are acquired before the effect starts and released after it + * completes, fails, or is interrupted. + * + * **Gotchas** * - * **Note**: The permit acquisition and release operations use atomic semantics - * to ensure proper resource management with Effect's scoped operations. + * Passing a non-positive `n` dies with a defect. Passing a value greater than + * the semaphore capacity can wait forever. + * + * **Example** (Running an effect with multiple permits) * - * @example * ```ts * import { Console, Effect, TxSemaphore } from "effect" * @@ -601,24 +734,34 @@ export const withPermits: { * }) * ``` * - * @param self - The TxSemaphore to acquire permits from - * @param n - The number of permits to acquire (must be positive) - * @param effect - The effect to execute with the permits - * @returns Effect that succeeds with the result of the provided effect + * @see {@link withPermit} for automatically acquiring and releasing one permit + * @see {@link acquireN} for manual multi-permit acquisition * - * @since 4.0.0 * @category combinators + * @since 2.0.0 */ (self: TxSemaphore, n: number): (effect: Effect.Effect) => Effect.Effect /** - * Executes an effect with the specified number of permits from the semaphore. - * The permits are automatically acquired before execution and released afterwards, - * even if the effect fails or is interrupted. + * Runs an effect while holding the specified number of permits from the + * semaphore. + * + * **When to use** + * + * Use to run an effect while automatically acquiring and releasing multiple + * transactional permits. + * + * **Details** + * + * The permits are acquired before the effect starts and released after it + * completes, fails, or is interrupted. + * + * **Gotchas** * - * **Note**: The permit acquisition and release operations use atomic semantics - * to ensure proper resource management with Effect's scoped operations. + * Passing a non-positive `n` dies with a defect. Passing a value greater than + * the semaphore capacity can wait forever. + * + * **Example** (Running an effect with multiple permits) * - * @example * ```ts * import { Console, Effect, TxSemaphore } from "effect" * @@ -641,13 +784,11 @@ export const withPermits: { * }) * ``` * - * @param self - The TxSemaphore to acquire permits from - * @param n - The number of permits to acquire (must be positive) - * @param effect - The effect to execute with the permits - * @returns Effect that succeeds with the result of the provided effect + * @see {@link withPermit} for automatically acquiring and releasing one permit + * @see {@link acquireN} for manual multi-permit acquisition * - * @since 4.0.0 * @category combinators + * @since 2.0.0 */ (self: TxSemaphore, n: number, effect: Effect.Effect): Effect.Effect } = ((...args: Array) => { @@ -673,10 +814,18 @@ export const withPermits: { * will be automatically released when the scope is closed, even if effects * within the scope fail or are interrupted. * - * **Note**: The permit acquisition and release operations use atomic semantics - * to ensure proper resource management with Effect's scoped operations. + * **When to use** + * + * Use to acquire one transactional permit for the lifetime of the current + * scope. + * + * **Details** + * + * The permit acquisition and release operations use atomic semantics to ensure + * proper resource management with Effect's scoped operations. + * + * **Example** (Acquiring a scoped permit) * - * @example * ```ts * import { Console, Effect, TxSemaphore } from "effect" * @@ -701,11 +850,11 @@ export const withPermits: { * }) * ``` * - * @param self - The TxSemaphore to acquire a permit from - * @returns Effect that succeeds when the permit is acquired (within scope) + * @see {@link withPermit} for acquiring one permit around a single effect + * @see {@link acquire} for manual single-permit acquisition * - * @since 4.0.0 * @category combinators + * @since 2.0.0 */ export const withPermitScoped = (self: TxSemaphore): Effect.Effect => Effect.acquireRelease( @@ -716,7 +865,12 @@ export const withPermitScoped = (self: TxSemaphore): Effect.Effect hasProperty(u, TypeId) diff --git a/.opencode/node_modules/effect/src/TxSubscriptionRef.ts b/.opencode/node_modules/effect/src/TxSubscriptionRef.ts index deeba22aac7c23bc5f7b6ff18feda3e6fee81e86..33c359ea51a1a7b34f0fe6c605f7a46cfcd3638f 100644 --- a/.opencode/node_modules/effect/src/TxSubscriptionRef.ts +++ b/.opencode/node_modules/effect/src/TxSubscriptionRef.ts @@ -1,6 +1,11 @@ /** - * TxSubscriptionRef is a TxRef that allows subscribing to all committed changes. Subscribers - * receive the current value followed by every subsequent update via a transactional queue. + * Stores transactional state and publishes committed changes. + * + * A `TxSubscriptionRef` combines a `TxRef` for the current value with a + * transactional pub/sub channel for updates. Subscribers first receive the + * current value and then every later value that is published by committed + * updates. This module includes constructors, reads, writes, update and modify + * helpers, transactional-queue subscriptions, stream subscriptions, and a guard. * * @since 4.0.0 */ @@ -24,9 +29,15 @@ const TypeId = "~effect/transactions/TxSubscriptionRef" * committed changes. Subscribers receive the current value followed by every subsequent * update via a transactional dequeue. * - * @example + * **When to use** + * + * Use to store transactional state whose committed changes must be observable by + * subscribers. + * + * **Example** (Subscribing to transactional changes) + * * ```ts - * import { Effect, TxSubscriptionRef, TxQueue } from "effect" + * import { Effect, TxQueue, TxSubscriptionRef } from "effect" * * const program = Effect.gen(function*() { * const ref = yield* TxSubscriptionRef.make(0) @@ -45,8 +56,12 @@ const TypeId = "~effect/transactions/TxSubscriptionRef" * }) * ``` * - * @since 4.0.0 + * @see {@link make} for creating a transactional subscription reference + * @see {@link changes} for subscribing through a transactional queue + * @see {@link changesStream} for subscribing through a `Stream` + * * @category models + * @since 4.0.0 */ export interface TxSubscriptionRef extends Inspectable, Pipeable { readonly [TypeId]: typeof TypeId @@ -78,7 +93,13 @@ const TxSubscriptionRefProto: Omit, typeof TypeId | "ref" /** * Creates a new TxSubscriptionRef with the specified initial value. * - * @example + * **When to use** + * + * Use to create a `TxSubscriptionRef` that publishes every committed update to + * subscribers. + * + * **Example** (Creating a transactional subscription reference) + * * ```ts * import { Effect, TxSubscriptionRef } from "effect" * @@ -89,8 +110,10 @@ const TxSubscriptionRefProto: Omit, typeof TypeId | "ref" * }) * ``` * - * @since 4.0.0 + * @see {@link changes} for subscribing to the created reference + * * @category constructors + * @since 3.10.0 */ export const make = (value: A): Effect.Effect> => Effect.gen(function*() { @@ -110,7 +133,13 @@ export const make = (value: A): Effect.Effect> => /** * Reads the current value of the TxSubscriptionRef. * - * @example + * **When to use** + * + * Use to read the current `TxSubscriptionRef` value without subscribing to + * future changes. + * + * **Example** (Reading the current value) + * * ```ts * import { Effect, TxSubscriptionRef } from "effect" * @@ -121,8 +150,10 @@ export const make = (value: A): Effect.Effect> => * }) * ``` * - * @since 4.0.0 + * @see {@link changes} for reading the current value and subsequent updates + * * @category getters + * @since 3.10.0 */ export const get = (self: TxSubscriptionRef): Effect.Effect => TxRef.get(self.ref) @@ -134,7 +165,13 @@ export const get = (self: TxSubscriptionRef): Effect.Effect => TxRef.ge * Modifies the value of the TxSubscriptionRef using a function that returns both a * result and the new value. The new value is published to all subscribers atomically. * - * @example + * **When to use** + * + * Use to compute a separate return value and next `TxSubscriptionRef` state in + * one transactional update. + * + * **Example** (Modifying and returning a value) + * * ```ts * import { Effect, TxSubscriptionRef } from "effect" * @@ -146,8 +183,11 @@ export const get = (self: TxSubscriptionRef): Effect.Effect => TxRef.ge * }) * ``` * - * @since 4.0.0 + * @see {@link update} for deriving the next value without a separate return value + * @see {@link set} for replacing the value directly + * * @category mutations + * @since 3.10.0 */ export const modify: { // ============================================================================= @@ -158,7 +198,13 @@ export const modify: { * Modifies the value of the TxSubscriptionRef using a function that returns both a * result and the new value. The new value is published to all subscribers atomically. * - * @example + * **When to use** + * + * Use to compute a separate return value and next `TxSubscriptionRef` state in + * one transactional update. + * + * **Example** (Modifying and returning a value) + * * ```ts * import { Effect, TxSubscriptionRef } from "effect" * @@ -170,8 +216,11 @@ export const modify: { * }) * ``` * - * @since 4.0.0 + * @see {@link update} for deriving the next value without a separate return value + * @see {@link set} for replacing the value directly + * * @category mutations + * @since 3.10.0 */ (f: (current: A) => [returnValue: B, newValue: A]): (self: TxSubscriptionRef) => Effect.Effect // ============================================================================= @@ -182,7 +231,13 @@ export const modify: { * Modifies the value of the TxSubscriptionRef using a function that returns both a * result and the new value. The new value is published to all subscribers atomically. * - * @example + * **When to use** + * + * Use to compute a separate return value and next `TxSubscriptionRef` state in + * one transactional update. + * + * **Example** (Modifying and returning a value) + * * ```ts * import { Effect, TxSubscriptionRef } from "effect" * @@ -194,8 +249,11 @@ export const modify: { * }) * ``` * - * @since 4.0.0 + * @see {@link update} for deriving the next value without a separate return value + * @see {@link set} for replacing the value directly + * * @category mutations + * @since 3.10.0 */ ( self: TxSubscriptionRef, @@ -219,7 +277,13 @@ export const modify: { /** * Sets the value of the TxSubscriptionRef and publishes the new value to all subscribers. * - * @example + * **When to use** + * + * Use to replace the current `TxSubscriptionRef` value with a known value and + * publish it. + * + * **Example** (Setting a new value) + * * ```ts * import { Effect, TxSubscriptionRef } from "effect" * @@ -230,14 +294,23 @@ export const modify: { * }) * ``` * - * @since 4.0.0 + * @see {@link update} for deriving the new value from the current value + * @see {@link getAndSet} for setting while returning the previous value + * * @category mutations + * @since 3.10.0 */ export const set: { /** * Sets the value of the TxSubscriptionRef and publishes the new value to all subscribers. * - * @example + * **When to use** + * + * Use to replace the current `TxSubscriptionRef` value with a known value and + * publish it. + * + * **Example** (Setting a new value) + * * ```ts * import { Effect, TxSubscriptionRef } from "effect" * @@ -248,14 +321,23 @@ export const set: { * }) * ``` * - * @since 4.0.0 + * @see {@link update} for deriving the new value from the current value + * @see {@link getAndSet} for setting while returning the previous value + * * @category mutations + * @since 3.10.0 */ (value: A): (self: TxSubscriptionRef) => Effect.Effect /** * Sets the value of the TxSubscriptionRef and publishes the new value to all subscribers. * - * @example + * **When to use** + * + * Use to replace the current `TxSubscriptionRef` value with a known value and + * publish it. + * + * **Example** (Setting a new value) + * * ```ts * import { Effect, TxSubscriptionRef } from "effect" * @@ -266,8 +348,11 @@ export const set: { * }) * ``` * - * @since 4.0.0 + * @see {@link update} for deriving the new value from the current value + * @see {@link getAndSet} for setting while returning the previous value + * * @category mutations + * @since 3.10.0 */ (self: TxSubscriptionRef, value: A): Effect.Effect } = dual( @@ -279,7 +364,13 @@ export const set: { * Updates the value of the TxSubscriptionRef using a function and publishes the new * value to all subscribers. * - * @example + * **When to use** + * + * Use to derive the next `TxSubscriptionRef` value from the current value and + * publish it. + * + * **Example** (Updating a value) + * * ```ts * import { Effect, TxSubscriptionRef } from "effect" * @@ -290,15 +381,24 @@ export const set: { * }) * ``` * - * @since 4.0.0 + * @see {@link set} for replacing the value directly + * @see {@link updateAndGet} for returning the new value after the update + * * @category mutations + * @since 3.10.0 */ export const update: { /** * Updates the value of the TxSubscriptionRef using a function and publishes the new * value to all subscribers. * - * @example + * **When to use** + * + * Use to derive the next `TxSubscriptionRef` value from the current value and + * publish it. + * + * **Example** (Updating a value) + * * ```ts * import { Effect, TxSubscriptionRef } from "effect" * @@ -309,15 +409,24 @@ export const update: { * }) * ``` * - * @since 4.0.0 + * @see {@link set} for replacing the value directly + * @see {@link updateAndGet} for returning the new value after the update + * * @category mutations + * @since 3.10.0 */ (f: (current: A) => A): (self: TxSubscriptionRef) => Effect.Effect /** * Updates the value of the TxSubscriptionRef using a function and publishes the new * value to all subscribers. * - * @example + * **When to use** + * + * Use to derive the next `TxSubscriptionRef` value from the current value and + * publish it. + * + * **Example** (Updating a value) + * * ```ts * import { Effect, TxSubscriptionRef } from "effect" * @@ -328,8 +437,11 @@ export const update: { * }) * ``` * - * @since 4.0.0 + * @see {@link set} for replacing the value directly + * @see {@link updateAndGet} for returning the new value after the update + * * @category mutations + * @since 3.10.0 */ (self: TxSubscriptionRef, f: (current: A) => A): Effect.Effect } = dual( @@ -342,7 +454,13 @@ export const update: { * Gets the current value and sets a new value atomically. Publishes the new value * to all subscribers. * - * @example + * **When to use** + * + * Use to replace a `TxSubscriptionRef` value while returning the previous value + * and publishing the update to subscribers. + * + * **Example** (Getting and setting atomically) + * * ```ts * import { Effect, TxSubscriptionRef } from "effect" * @@ -354,15 +472,24 @@ export const update: { * }) * ``` * - * @since 4.0.0 + * @see {@link set} for setting without returning the previous value + * @see {@link getAndUpdate} for deriving the new value from the previous value + * * @category mutations + * @since 3.10.0 */ export const getAndSet: { /** * Gets the current value and sets a new value atomically. Publishes the new value * to all subscribers. * - * @example + * **When to use** + * + * Use to replace a `TxSubscriptionRef` value while returning the previous value + * and publishing the update to subscribers. + * + * **Example** (Getting and setting atomically) + * * ```ts * import { Effect, TxSubscriptionRef } from "effect" * @@ -374,15 +501,24 @@ export const getAndSet: { * }) * ``` * - * @since 4.0.0 + * @see {@link set} for setting without returning the previous value + * @see {@link getAndUpdate} for deriving the new value from the previous value + * * @category mutations + * @since 3.10.0 */ (value: A): (self: TxSubscriptionRef) => Effect.Effect /** * Gets the current value and sets a new value atomically. Publishes the new value * to all subscribers. * - * @example + * **When to use** + * + * Use to replace a `TxSubscriptionRef` value while returning the previous value + * and publishing the update to subscribers. + * + * **Example** (Getting and setting atomically) + * * ```ts * import { Effect, TxSubscriptionRef } from "effect" * @@ -394,8 +530,11 @@ export const getAndSet: { * }) * ``` * - * @since 4.0.0 + * @see {@link set} for setting without returning the previous value + * @see {@link getAndUpdate} for deriving the new value from the previous value + * * @category mutations + * @since 3.10.0 */ (self: TxSubscriptionRef, value: A): Effect.Effect } = dual( @@ -407,7 +546,13 @@ export const getAndSet: { * Gets the current value and updates it using a function atomically. Publishes * the new value to all subscribers. * - * @example + * **When to use** + * + * Use to derive and publish a new `TxSubscriptionRef` value while returning the + * previous value. + * + * **Example** (Getting and updating atomically) + * * ```ts * import { Effect, TxSubscriptionRef } from "effect" * @@ -419,15 +564,24 @@ export const getAndSet: { * }) * ``` * - * @since 4.0.0 + * @see {@link update} for updating without returning the previous value + * @see {@link updateAndGet} for returning the new value instead + * * @category mutations + * @since 3.10.0 */ export const getAndUpdate: { /** * Gets the current value and updates it using a function atomically. Publishes * the new value to all subscribers. * - * @example + * **When to use** + * + * Use to derive and publish a new `TxSubscriptionRef` value while returning the + * previous value. + * + * **Example** (Getting and updating atomically) + * * ```ts * import { Effect, TxSubscriptionRef } from "effect" * @@ -439,15 +593,24 @@ export const getAndUpdate: { * }) * ``` * - * @since 4.0.0 + * @see {@link update} for updating without returning the previous value + * @see {@link updateAndGet} for returning the new value instead + * * @category mutations + * @since 3.10.0 */ (f: (current: A) => A): (self: TxSubscriptionRef) => Effect.Effect /** * Gets the current value and updates it using a function atomically. Publishes * the new value to all subscribers. * - * @example + * **When to use** + * + * Use to derive and publish a new `TxSubscriptionRef` value while returning the + * previous value. + * + * **Example** (Getting and updating atomically) + * * ```ts * import { Effect, TxSubscriptionRef } from "effect" * @@ -459,8 +622,11 @@ export const getAndUpdate: { * }) * ``` * - * @since 4.0.0 + * @see {@link update} for updating without returning the previous value + * @see {@link updateAndGet} for returning the new value instead + * * @category mutations + * @since 3.10.0 */ (self: TxSubscriptionRef, f: (current: A) => A): Effect.Effect } = dual( @@ -473,7 +639,13 @@ export const getAndUpdate: { * Updates the value using a function and returns the new value. Publishes the * new value to all subscribers. * - * @example + * **When to use** + * + * Use to derive and publish a new `TxSubscriptionRef` value while returning + * that new value. + * + * **Example** (Updating and reading atomically) + * * ```ts * import { Effect, TxSubscriptionRef } from "effect" * @@ -484,15 +656,24 @@ export const getAndUpdate: { * }) * ``` * - * @since 4.0.0 + * @see {@link update} for updating without returning the new value + * @see {@link getAndUpdate} for returning the previous value instead + * * @category mutations + * @since 3.10.0 */ export const updateAndGet: { /** * Updates the value using a function and returns the new value. Publishes the * new value to all subscribers. * - * @example + * **When to use** + * + * Use to derive and publish a new `TxSubscriptionRef` value while returning + * that new value. + * + * **Example** (Updating and reading atomically) + * * ```ts * import { Effect, TxSubscriptionRef } from "effect" * @@ -503,15 +684,24 @@ export const updateAndGet: { * }) * ``` * - * @since 4.0.0 + * @see {@link update} for updating without returning the new value + * @see {@link getAndUpdate} for returning the previous value instead + * * @category mutations + * @since 3.10.0 */ (f: (current: A) => A): (self: TxSubscriptionRef) => Effect.Effect /** * Updates the value using a function and returns the new value. Publishes the * new value to all subscribers. * - * @example + * **When to use** + * + * Use to derive and publish a new `TxSubscriptionRef` value while returning + * that new value. + * + * **Example** (Updating and reading atomically) + * * ```ts * import { Effect, TxSubscriptionRef } from "effect" * @@ -522,8 +712,11 @@ export const updateAndGet: { * }) * ``` * - * @since 4.0.0 + * @see {@link update} for updating without returning the new value + * @see {@link getAndUpdate} for returning the previous value instead + * * @category mutations + * @since 3.10.0 */ (self: TxSubscriptionRef, f: (current: A) => A): Effect.Effect } = dual( @@ -543,9 +736,15 @@ export const updateAndGet: { * Subscribes to all changes of the TxSubscriptionRef. Returns a scoped TxDequeue * that first yields the current value, then every subsequent update. * - * @example + * **When to use** + * + * Use to subscribe to `TxSubscriptionRef` committed changes through a scoped + * transactional queue. + * + * **Example** (Subscribing to changes) + * * ```ts - * import { Effect, TxSubscriptionRef, TxQueue } from "effect" + * import { Effect, TxQueue, TxSubscriptionRef } from "effect" * * const program = Effect.gen(function*() { * const ref = yield* TxSubscriptionRef.make(0) @@ -564,8 +763,10 @@ export const updateAndGet: { * }) * ``` * - * @since 4.0.0 + * @see {@link changesStream} for subscribing through a `Stream` + * * @category subscriptions + * @since 3.10.0 */ export const changes = ( self: TxSubscriptionRef @@ -586,7 +787,12 @@ export const changes = ( * Returns a Stream of all changes to the TxSubscriptionRef, starting with the * current value followed by every subsequent update. * - * @example + * **When to use** + * + * Use to consume `TxSubscriptionRef` committed changes as a `Stream`. + * + * **Example** (Streaming changes) + * * ```ts * import { Effect, Stream, TxSubscriptionRef } from "effect" * @@ -602,8 +808,10 @@ export const changes = ( * }) * ``` * - * @since 4.0.0 + * @see {@link changes} for subscribing through a transactional queue + * * @category subscriptions + * @since 3.10.0 */ export const changesStream = (self: TxSubscriptionRef): Stream.Stream => Stream.unwrap( @@ -618,9 +826,14 @@ export const changesStream = (self: TxSubscriptionRef): Stream.Stream(self: TxSubscriptionRef): Stream.Stream => hasProperty(u, TypeId) diff --git a/.opencode/node_modules/effect/src/Types.ts b/.opencode/node_modules/effect/src/Types.ts index d09e853f29ffbc325c5b4e935d6efb20424f1f91..dfa5895bf9740a74bf6ac289f110459717ee7991 100644 --- a/.opencode/node_modules/effect/src/Types.ts +++ b/.opencode/node_modules/effect/src/Types.ts @@ -1,54 +1,10 @@ /** - * Type-level utility types for TypeScript. - * - * This module provides generic type aliases used throughout the Effect - * ecosystem. Everything here is compile-time only — there are no runtime - * values. Use these types to manipulate object shapes, tagged unions, tuples, - * and variance markers at the type level. - * - * ## Mental model - * - * - **Tagged union**: a union of objects each having a discriminating - * `_tag: string` field. {@link Tags}, {@link ExtractTag}, and - * {@link ExcludeTag} operate on these. - * - **Reason**: a nested error pattern where an error has a `reason` field - * containing a tagged union of sub-errors. {@link ReasonOf}, - * {@link ReasonTags}, {@link ExtractReason}, and {@link ExcludeReason} work - * with this pattern. - * - **Variance markers**: {@link Covariant}, {@link Contravariant}, and - * {@link Invariant} are function-type aliases encoding variance for phantom - * type parameters. - * - **Simplify**: {@link Simplify} flattens intersection types (`A & B`) into - * a single object type for cleaner IDE tooltips. - * - **Concurrency**: {@link Concurrency} is a union type - * (`number | "unbounded" | "inherit"`) used across Effect APIs that accept - * concurrency options. - * - **Marker types**: {@link unassigned} and {@link unhandled} are branded - * interfaces used internally to represent missing or unhandled type - * parameters. - * - * ## Common tasks - * - * - Flatten an intersection for readability → {@link Simplify} - * - Check type equality at compile time → {@link Equals} / {@link EqualsWith} - * - Merge two object types → {@link MergeLeft} / {@link MergeRight} - * - Work with tagged unions → {@link Tags} / {@link ExtractTag} / {@link ExcludeTag} - * - Work with nested reason errors → {@link ReasonOf} / {@link ExtractReason} - * - Create fixed-length tuples → {@link TupleOf} / {@link TupleOfAtLeast} - * - Strip `readonly` modifiers → {@link Mutable} / {@link DeepMutable} - * - Encode variance in phantom types → {@link Covariant} / {@link Contravariant} / {@link Invariant} - * - Check if a type is a union → {@link IsUnion} - * - * ## Gotchas - * - * - {@link TupleOf} with a non-literal `number` (e.g. `TupleOf`) - * degrades to `Array`. - * - {@link MergeRecord} is an alias for {@link MergeLeft}; prefer - * {@link MergeLeft} or {@link MergeRight} for clarity. - * - {@link NoInfer} uses the `[A][A extends any ? 0 : never]` trick, not the - * built-in `NoInfer` from TypeScript 5.4+. - * - {@link DeepMutable} recurses into `Map`, `Set`, arrays, and objects but - * stops at primitives and functions. + * Provides compile-time utility types for TypeScript. + * + * Everything in this module is type-level only; it does not define runtime + * values. The types are used throughout Effect to work with tuple lengths, + * object shapes, tagged unions, reason-tagged errors, mutability, exactness, + * required keys, concurrency settings, and variance markers. * * @since 4.0.0 */ @@ -64,10 +20,13 @@ type TupleOf_> = `${N}` extends `- /** * Constructs a tuple type with exactly `N` elements of type `T`. * - * - Use when you need a fixed-length array type. - * - Use instead of manually writing `[T, T, T, ...]` for longer tuples. + * **When to use** + * + * Use when you need a fixed-length array type, especially instead of manually + * writing `[T, T, T, ...]` for longer tuples. + * + * **Details** * - * Behavior: * - If `N` is a literal number, produces a tuple of that exact length. * - If `N` is the general `number` type (non-literal), degrades to `Array`. * - Negative numbers produce `never`. @@ -97,12 +56,15 @@ export type TupleOf = N extends N ? number extends N ? Arra /** * Constructs a tuple type with at least `N` elements of type `T`. * - * - Use when you need a minimum-length array type that still allows additional - * elements. - * - Useful for variadic function signatures that require a minimum arity. + * **When to use** * - * Behavior: - * - Produces a tuple with `N` fixed positions followed by `...Array`. + * Use when you need a minimum-length array type that still allows additional + * elements. This is useful for variadic function signatures that require a + * minimum arity. + * + * **Details** + * + * Produces a tuple with `N` fixed positions followed by `...Array`. * * **Example** (Minimum-length tuple) * @@ -127,8 +89,13 @@ export type TupleOfAtLeast = [...TupleOf, ...Array /** * Extracts the `_tag` string literal types from a union. * - * - Use to get all discriminant values from a tagged union type. - * - Members without a `_tag` field are ignored (produce `never`). + * **When to use** + * + * Use to get all discriminant values from a tagged union type. + * + * **Details** + * + * Members without a `_tag` field are ignored and produce `never`. * * **Example** (Extracting tags) * @@ -155,8 +122,14 @@ export type Tags = E extends { readonly _tag: string } ? E["_tag"] : never /** * Excludes members of a tagged union by their `_tag` value. * - * - Use to narrow a union by removing a specific variant. - * - Non-tagged members of the union are preserved. + * **When to use** + * + * Use to remove tagged-union members whose `_tag` matches a specific value in + * type-level code. + * + * **Details** + * + * Non-tagged members of the union are preserved. * * **Example** (Removing a variant) * @@ -183,8 +156,14 @@ export type ExcludeTag = Exclude /** * Extracts a specific member of a tagged union by its `_tag` value. * - * - Use to narrow a union down to a single variant. - * - Returns `never` if no member matches the tag. + * **When to use** + * + * Use to select tagged-union members whose `_tag` matches a specific value in + * type-level code. + * + * **Details** + * + * Returns `never` if no member matches the tag. * * **Example** (Extracting a variant) * @@ -210,11 +189,14 @@ export type ExtractTag = E extends { readonly _tag: infer T /** * Transforms a union type into an intersection type. * - * - Use to combine all members of a union into a single type with all - * their properties. - * - Useful in advanced generic code where you need to merge union variants. + * **When to use** + * + * Use to combine all members of a union into a single type with all their + * properties. This is useful in advanced generic code where you need to merge + * union variants. + * + * **Details** * - * Behavior: * - Uses distributive conditional types and contra-variant inference. * - If the union members are incompatible (e.g. `string | number`), the * result is `never`. @@ -231,8 +213,8 @@ export type ExtractTag = E extends { readonly _tag: infer T * * @see {@link IsUnion} * - * @since 2.0.0 * @category types + * @since 2.0.0 */ export type UnionToIntersection = (T extends any ? (x: T) => any : never) extends (x: infer R) => any ? R : never @@ -240,9 +222,14 @@ export type UnionToIntersection = (T extends any ? (x: T) => any : never) ext /** * Flattens an intersection type into a single object type for readability. * - * - Use to clean up IDE tooltips that show `A & B & C` instead of a merged - * object. - * - Does not change the type semantically, only its display. + * **When to use** + * + * Use to clean up IDE tooltips that show `A & B & C` instead of a merged + * object. + * + * **Details** + * + * Does not change the type semantically, only its display. * * **Example** (Simplifying an intersection) * @@ -257,8 +244,8 @@ export type UnionToIntersection = (T extends any ? (x: T) => any : never) ext * @see {@link MergeLeft} * @see {@link MergeRight} * - * @since 2.0.0 * @category types + * @since 2.0.0 */ export type Simplify = { [K in keyof A]: A[K] @@ -267,12 +254,15 @@ export type Simplify = { /** * Determines if two types are exactly equal at the type level. * - * - Use in conditional types or type-level tests to assert type equality. - * - Resolves to `true` if `X` and `Y` are identical, `false` otherwise. + * **When to use** + * + * Use to assert type equality in conditional types or type-level tests. + * + * **Details** * - * Behavior: * - Uses the `() => T extends X ? 1 : 2` trick for exact equality, * distinguishing between `any`, `unknown`, `never`, and other types. + * - Resolves to `true` if `X` and `Y` are identical, `false` otherwise. * * **Example** (Type equality check) * @@ -286,8 +276,8 @@ export type Simplify = { * * @see {@link EqualsWith} * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export type Equals = (() => T extends X ? 1 : 2) extends < T @@ -297,8 +287,13 @@ export type Equals = (() => T extends X ? 1 : 2) extends < /** * Determines if two types are equal, returning custom types for each case. * - * - Use when you need a type-level if/else based on type equality. - * - Returns `Y` when `A` and `B` are equal, `N` otherwise. + * **When to use** + * + * Use when you need a type-level if/else based on type equality. + * + * **Details** + * + * Returns `Y` when `A` and `B` are equal, `N` otherwise. * * **Example** (Conditional type based on equality) * @@ -311,17 +306,23 @@ export type Equals = (() => T extends X ? 1 : 2) extends < * * @see {@link Equals} * - * @since 3.15.0 * @category models + * @since 3.15.0 */ export type EqualsWith = (() => T extends A ? 1 : 2) extends (() => T extends B ? 1 : 2) ? Y : N /** - * Checks if an object type contains any of the specified keys. + * Checks whether an object type contains any of the specified keys. + * + * **When to use** + * + * Use to branch type-level logic when at least one key from a candidate key set + * exists on an object type. * - * - Use to conditionally branch based on the presence of keys in a type. - * - Returns `true` if at least one key from `Key` exists in `A`, `false` - * otherwise. + * **Details** + * + * Returns `true` if at least one key from `Key` exists in `A`, `false` + * otherwise. * * **Example** (Key presence check) * @@ -332,19 +333,24 @@ export type EqualsWith = (() => T extends A ? 1 : 2) extends ( * type No = Types.Has<{ a: number }, "b" | "c"> // false * ``` * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export type Has = (Key extends infer K ? K extends keyof A ? true : never : never) extends never ? false : true /** - * Merges two object types where keys from `Source` take precedence over - * `Target` on conflict. + * Left-biased merge of two object types where keys from `Source` take + * precedence over `Target` on conflict. + * + * **When to use** + * + * Use when you want left-biased merging where the first argument wins. + * + * **Details** * - * - Use when you want left-biased merging (first argument wins). - * - Implemented as `MergeRight`. + * Implemented as `MergeRight`. * * **Example** (Left-biased merge) * @@ -359,20 +365,24 @@ export type Has = (Key extends infer K ? K extends keyof * ``` * * @see {@link MergeRight} - * @see {@link MergeRecord} * @see {@link Simplify} * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export type MergeLeft = MergeRight /** - * Merges two object types where keys from `Source` take precedence over - * `Target` on conflict. + * Right-biased merge of two object types where keys from `Source` take + * precedence over `Target` on conflict. + * + * **When to use** * - * - Use when you want right-biased merging (second argument wins). - * - The result is automatically simplified via {@link Simplify}. + * Use when you want right-biased merging where the second argument wins. + * + * **Details** + * + * The result is automatically simplified via {@link Simplify}. * * **Example** (Right-biased merge) * @@ -389,8 +399,8 @@ export type MergeLeft = MergeRight * @see {@link MergeLeft} * @see {@link Simplify} * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export type MergeRight = Simplify< & Source @@ -400,35 +410,14 @@ export type MergeRight = Simplify< > /** - * Alias for {@link MergeLeft}. Merges two object types where keys from - * `Source` take precedence on conflict. - * - * Prefer {@link MergeLeft} or {@link MergeRight} for clarity about which - * side wins. - * - * **Example** (Merging records) - * - * ```ts - * import type { Types } from "effect" + * Describes the concurrency level for Effect operations that run multiple + * effects. * - * type Result = Types.MergeRecord< - * { a: number; b: number }, - * { a: string; c: boolean } - * > - * // { a: number; b: number; c: boolean } - * ``` + * **When to use** * - * @see {@link MergeLeft} - * @see {@link MergeRight} + * Use to type options that control how many effects may run at the same time. * - * @since 2.0.0 - * @category models - */ -export type MergeRecord = MergeLeft - -/** - * Describes the concurrency level for Effect operations that run multiple - * effects. + * **Details** * * - `number` — run at most N effects concurrently. * - `"unbounded"` — run all effects concurrently with no limit. @@ -445,8 +434,8 @@ export type MergeRecord = MergeLeft * const inherit: Types.Concurrency = "inherit" * ``` * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export type Concurrency = number | "unbounded" | "inherit" @@ -454,8 +443,13 @@ export type Concurrency = number | "unbounded" | "inherit" * Removes `readonly` from all properties of `T`. Supports arrays, tuples, * and records. * - * - Use when you need a mutable version of a readonly type. - * - Only affects the top level; nested properties remain readonly. + * **When to use** + * + * Use when you need a mutable version of a readonly type. + * + * **Details** + * + * Only affects the top level; nested properties remain readonly. * * **Example** (Shallow mutable conversion) * @@ -478,8 +472,8 @@ export type Concurrency = number | "unbounded" | "inherit" * * @see {@link DeepMutable} * - * @since 2.0.0 * @category types + * @since 2.0.0 */ export type Mutable = { -readonly [P in keyof T]: T[P] @@ -489,9 +483,14 @@ export type Mutable = { * Recursively removes `readonly` from all properties, including nested * objects, arrays, `Map`, and `Set`. * - * - Use when you need a fully mutable version of a deeply readonly type. - * - Recursion stops at primitives (`string`, `number`, `boolean`, `bigint`, - * `symbol`) and functions. + * **When to use** + * + * Use when you need a fully mutable version of a deeply readonly type. + * + * **Details** + * + * Recursion stops at primitives (`string`, `number`, `boolean`, `bigint`, + * `symbol`) and functions. * * **Example** (Deep mutable conversion) * @@ -507,8 +506,8 @@ export type Mutable = { * * @see {@link Mutable} * - * @since 3.1.0 * @category types + * @since 3.1.0 */ export type DeepMutable = T extends ReadonlyMap ? Map, DeepMutable> : T extends ReadonlySet ? Set> @@ -519,9 +518,14 @@ export type DeepMutable = T extends ReadonlyMap ? Map = T extends ReadonlyMap ? Map("a", "b") * ``` * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export type NoInfer = [A][A extends any ? 0 : never] @@ -543,10 +547,15 @@ export type NoInfer = [A][A extends any ? 0 : never] * Function-type alias encoding invariant variance for a phantom type * parameter. * - * - Use as a phantom field type to make a type parameter invariant (neither - * covariant nor contravariant). - * - A value of type `Invariant` cannot be assigned to `Invariant` - * unless `A` and `B` are the same type. + * **When to use** + * + * Use as a phantom field type to make a type parameter invariant, neither + * covariant nor contravariant. + * + * **Details** + * + * A value of type `Invariant` cannot be assigned to `Invariant` unless + * `A` and `B` are the same type. * * **Example** (Invariant phantom type) * @@ -563,21 +572,28 @@ export type NoInfer = [A][A extends any ? 0 : never] * @see {@link Covariant} * @see {@link Contravariant} * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export type Invariant = (_: A) => A /** * Namespace for {@link Invariant}-related utilities. * + * **When to use** + * + * Use when referring to type-level helpers nested under `Invariant`. + * * @since 3.9.0 - * @category models */ export declare namespace Invariant { /** * Extracts the type parameter `A` from an `Invariant`. * + * **When to use** + * + * Use to recover the carried type from an invariant phantom marker. + * * **Example** (Extracting the inner type) * * ```ts @@ -589,8 +605,8 @@ export declare namespace Invariant { * * @see {@link Invariant} * - * @since 3.9.0 * @category models + * @since 3.9.0 */ export type Type = A extends Invariant ? U : never } @@ -599,10 +615,15 @@ export declare namespace Invariant { * Function-type alias encoding covariant variance for a phantom type * parameter. * - * - Use as a phantom field type to make a type parameter covariant - * (output position). - * - `Covariant` is assignable to `Covariant` when `A extends B` - * (subtype direction). + * **When to use** + * + * Use as a phantom field type to make a type parameter covariant in output + * position. + * + * **Details** + * + * `Covariant` is assignable to `Covariant` when `A extends B`, following + * the subtype direction. * * **Example** (Covariant phantom type) * @@ -619,21 +640,28 @@ export declare namespace Invariant { * @see {@link Contravariant} * @see {@link Invariant} * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export type Covariant = (_: never) => A /** * Namespace for {@link Covariant}-related utilities. * + * **When to use** + * + * Use when referring to type-level helpers nested under `Covariant`. + * * @since 3.9.0 - * @category models */ export declare namespace Covariant { /** * Extracts the type parameter `A` from a `Covariant`. * + * **When to use** + * + * Use to recover the carried type from a covariant phantom marker. + * * **Example** (Extracting the inner type) * * ```ts @@ -645,8 +673,8 @@ export declare namespace Covariant { * * @see {@link Covariant} * - * @since 3.9.0 * @category models + * @since 3.9.0 */ export type Type = A extends Covariant ? U : never } @@ -655,10 +683,15 @@ export declare namespace Covariant { * Function-type alias encoding contravariant variance for a phantom type * parameter. * - * - Use as a phantom field type to make a type parameter contravariant - * (input position). - * - `Contravariant` is assignable to `Contravariant` when `B extends A` - * (supertype direction). + * **When to use** + * + * Use as a phantom field type to make a type parameter contravariant in input + * position. + * + * **Details** + * + * `Contravariant` is assignable to `Contravariant` when `B extends A`, + * following the supertype direction. * * **Example** (Contravariant phantom type) * @@ -675,21 +708,28 @@ export declare namespace Covariant { * @see {@link Covariant} * @see {@link Invariant} * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export type Contravariant = (_: A) => void /** * Namespace for {@link Contravariant}-related utilities. * + * **When to use** + * + * Use when referring to type-level helpers nested under `Contravariant`. + * * @since 3.9.0 - * @category models */ export declare namespace Contravariant { /** * Extracts the type parameter `A` from a `Contravariant`. * + * **When to use** + * + * Use to recover the carried type from a contravariant phantom marker. + * * **Example** (Extracting the inner type) * * ```ts @@ -701,8 +741,8 @@ export declare namespace Contravariant { * * @see {@link Contravariant} * - * @since 3.9.0 * @category models + * @since 3.9.0 */ export type Type = A extends Contravariant ? U : never } @@ -711,16 +751,25 @@ export declare namespace Contravariant { * Conditional type that returns `void` if `S` is an empty object type, * otherwise returns `S`. * - * @since 4.0.0 + * **When to use** + * + * Use to erase an empty object type from an API result or parameter position. + * * @category types + * @since 3.19.20 */ export type VoidIfEmpty = keyof S extends never ? void : S /** * Excludes function types from a union, keeping only non-function members. * - * - Use to filter out callable types from a union. - * - Returns `never` if the entire union consists of function types. + * **When to use** + * + * Use to filter out callable types from a union. + * + * **Details** + * + * Returns `never` if the entire union consists of function types. * * **Example** (Filtering out functions) * @@ -731,17 +780,21 @@ export type VoidIfEmpty = keyof S extends never ? void : S * // string | number * ``` * - * @since 2.0.0 * @category types + * @since 2.0.0 */ export type NotFunction = T extends Function ? never : T /** * Constrains a type to prevent excess properties not present in `T`. * - * - Use in generic functions to catch accidental extra properties at - * compile time. - * - Extra keys from `U` that are not in `T` are mapped to `never`. + * **When to use** + * + * Use to catch accidental extra properties in generic functions at compile time. + * + * **Details** + * + * Extra keys from `U` that are not in `T` are mapped to `never`. * * **Example** (Preventing extra properties) * @@ -755,21 +808,28 @@ export type NotFunction = T extends Function ? never : T * // { a: number; b: string; readonly c: never } * ``` * - * @since 3.9.0 * @category types + * @since 3.9.0 */ export type NoExcessProperties = T & Readonly, never>> /** * Branded marker interface representing an unassigned type parameter. * + * **When to use** + * + * Use when Effect's type-level machinery needs to represent a type parameter + * that has not been assigned yet. + * + * **Details** + * * Used internally by the Effect type system to indicate that a type parameter * has not been assigned a concrete type. * * @see {@link unhandled} * - * @since 4.0.0 * @category types + * @since 4.0.0 */ export interface unassigned { readonly _: unique symbol @@ -778,13 +838,20 @@ export interface unassigned { /** * Branded marker interface representing an unhandled error type. * + * **When to use** + * + * Use when Effect's type-level machinery needs to represent an error type that + * has not been handled yet. + * + * **Details** + * * Used internally by the Effect type system to indicate that an error type * has not been handled. * * @see {@link unassigned} * - * @since 4.0.0 * @category types + * @since 4.0.0 */ export interface unhandled { readonly _: unique symbol @@ -793,12 +860,16 @@ export interface unhandled { /** * Checks whether a type `T` is a union type. * - * - Returns `true` if `T` is a union of two or more members. - * - Returns `false` for single types, `never`, or `any`. + * **When to use** + * + * Use to branch type-level logic depending on whether a type is a union. + * + * **Details** * - * Behavior: * - Compares `[T]` against `[UnionToIntersection]`. If they differ, `T` * must be a union. + * - Returns `true` if `T` is a union of two or more members. + * - Returns `false` for single types, `never`, or `any`. * * **Example** (Detecting union types) * @@ -811,17 +882,22 @@ export interface unhandled { * * @see {@link UnionToIntersection} * - * @since 4.0.0 * @category types + * @since 4.0.0 */ export type IsUnion = [T] extends [UnionToIntersection] ? false : true /** * Extracts the `reason` type from an error that has a `reason` field. * - * - Use with the nested error pattern where errors wrap sub-errors in a - * `reason` field. - * - Returns `never` if `E` has no `reason` field. + * **When to use** + * + * Use when an error type stores nested sub-errors in a `reason` field and you + * need that field's full union type as a standalone type. + * + * **Details** + * + * Returns `never` if `E` has no `reason` field. * * **Example** (Extracting reason types) * @@ -840,16 +916,23 @@ export type IsUnion = [T] extends [UnionToIntersection] ? false : true * @see {@link ExtractReason} * @see {@link ExcludeReason} * - * @since 4.0.0 * @category types + * @since 4.0.0 */ export type ReasonOf = E extends { readonly reason: infer R } ? R : never /** * Extracts the `_tag` values from the `reason` type of an error. * - * - Shorthand for `Tags>`. - * - Returns `never` if `E` has no `reason` field or the reason has no `_tag`. + * **When to use** + * + * Use to get the discriminant values available inside a nested `reason` + * error union. + * + * **Details** + * + * This is shorthand for `Tags>`. It returns `never` if `E` has no + * `reason` field or the reason has no `_tag`. * * **Example** (Getting reason tags) * @@ -867,8 +950,8 @@ export type ReasonOf = E extends { readonly reason: infer R } ? R : never * @see {@link ReasonOf} * @see {@link ExtractReason} * - * @since 4.0.0 * @category types + * @since 4.0.0 */ export type ReasonTags = E extends { readonly reason: { readonly _tag: string } } ? E["reason"]["_tag"] : never @@ -877,8 +960,14 @@ export type ReasonTags = E extends { readonly reason: { readonly _tag: string * Extracts a specific reason variant by its `_tag` from an error's `reason` * field. * - * - Use to narrow down to a single reason variant from a nested error type. - * - Returns `never` if `E` has no matching reason variant. + * **When to use** + * + * Use when you need the nested reason variant type itself, selected by `_tag`, + * rather than the enclosing error type. + * + * **Details** + * + * Returns `never` if `E` has no matching reason variant. * * **Example** (Extracting a reason variant) * @@ -897,8 +986,8 @@ export type ReasonTags = E extends { readonly reason: { readonly _tag: string * @see {@link ReasonOf} * @see {@link ReasonTags} * - * @since 4.0.0 * @category types + * @since 4.0.0 */ export type ExtractReason = E extends { readonly reason: infer R } ? R extends { readonly _tag: infer T } ? K extends T ? R : never @@ -909,8 +998,14 @@ export type ExtractReason = E extends { readonly reason: in * Narrows a specific reason variant by its `_tag` from an error's `reason` * field. * - * - Use to narrow down to a single reason variant from a nested error type. - * - Returns `never` if `E` has no matching reason variant. + * **When to use** + * + * Use to preserve the original error shape while narrowing its nested reason + * field to the matching variant. + * + * **Details** + * + * Returns `never` if `E` has no matching reason variant. * * **Example** (Narrowing a reason variant) * @@ -929,8 +1024,8 @@ export type ExtractReason = E extends { readonly reason: in * @see {@link ReasonOf} * @see {@link ReasonTags} * - * @since 4.0.0 * @category types + * @since 4.0.0 */ export type NarrowReason = E extends { readonly reason: infer R } ? R extends { readonly _tag: infer T } ? K extends T ? E & { readonly reason: R } : never @@ -941,9 +1036,14 @@ export type NarrowReason = E extends { readonly reason: inf * Narrows an error's `reason` field to exclude a specific reason variant by * its `_tag`. * - * - Use to narrow the error to only the remaining reason variants after - * excluding the matched one. - * - Returns `never` if `E` has no `reason` field or no remaining variants. + * **When to use** + * + * Use to narrow the error to only the remaining reason variants after + * excluding the matched one. + * + * **Details** + * + * Returns `never` if `E` has no `reason` field or no remaining variants. * * **Example** (Omitting a reason variant) * @@ -963,8 +1063,8 @@ export type NarrowReason = E extends { readonly reason: inf * @see {@link ReasonOf} * @see {@link ReasonTags} * - * @since 4.0.0 * @category types + * @since 4.0.0 */ export type OmitReason = E extends { readonly reason: infer R } ? R extends { readonly _tag: infer T } ? K extends T ? never : E & { readonly reason: R } @@ -975,8 +1075,14 @@ export type OmitReason = E extends { readonly reason: infer * Excludes a specific reason variant by its `_tag` from an error's `reason` * field. * - * - Use to remove a handled reason variant from an error's reason union. - * - Returns `never` if `E` has no `reason` field. + * **When to use** + * + * Use when you need the remaining nested reason union type after removing + * variants handled by `_tag`, rather than the enclosing error type. + * + * **Details** + * + * Returns `never` if `E` has no `reason` field. * * **Example** (Excluding a reason variant) * @@ -995,8 +1101,8 @@ export type OmitReason = E extends { readonly reason: infer * @see {@link ReasonOf} * @see {@link ReasonTags} * - * @since 4.0.0 * @category types + * @since 4.0.0 */ export type ExcludeReason = E extends { readonly reason: infer R } ? Exclude @@ -1005,7 +1111,11 @@ export type ExcludeReason = E extends { readonly reason: in /** * Extracts the required keys from a type. * - * @since 4.0.0 + * **When to use** + * + * Use to derive the keys whose properties must be present on an object type. + * * @category types + * @since 4.0.0 */ export type RequiredKeys = { [K in keyof T]-?: {} extends Pick ? never : K }[keyof T] diff --git a/.opencode/node_modules/effect/src/UndefinedOr.ts b/.opencode/node_modules/effect/src/UndefinedOr.ts index 9b72ac59a1954a9859383e23df030afd1c84f24c..a42ec25722602e6432646f7d3846baf45ee8e420 100644 --- a/.opencode/node_modules/effect/src/UndefinedOr.ts +++ b/.opencode/node_modules/effect/src/UndefinedOr.ts @@ -1,29 +1,12 @@ /** - * This module provides small, allocation-free utilities for working with values of type - * `A | undefined`, where `undefined` means "no value". - * - * Why not `Option`? - * In TypeScript, `Option` is often unnecessary. If `undefined` already models absence - * in your domain, using `A | undefined` keeps types simple, avoids extra wrappers, and - * reduces overhead. The key is that `A` itself must not include `undefined`; in this - * module `undefined` is reserved to mean "no value". - * - * When to use `A | undefined`: - * - Absence can be represented by `undefined` in your domain model. - * - You do not need to distinguish between "no value" and "value is undefined". - * - You want straightforward ergonomics and zero extra allocations. - * - * When to prefer `Option`: - * - You must distinguish `None` from `Some(undefined)` (that is, `undefined` is a valid - * payload and carries meaning on its own). - * - You need a tagged representation for serialization or pattern matching across - * boundaries where `undefined` would be ambiguous. - * - You want the richer `Option` API and are comfortable with the extra wrapper. - * - * Lawfulness note: - * All helpers treat `undefined` as absence. Do not use these utilities with payloads - * where `A` can itself be `undefined`, or you will lose information. If you need to - * carry `undefined` as a valid payload, use `Option` instead. + * Works with values that may be `undefined`. + * + * Use this module for plain TypeScript values of type `A | undefined` when + * `undefined` is the only absence marker. It is a small alternative to wrapping + * values in `Option` when your data already uses `undefined` to mean "no + * value". The module includes helpers for mapping defined values, matching both + * cases, throwing when a value is missing, adapting throwing functions, and + * building reducers or combiners. * * @since 4.0.0 */ @@ -33,24 +16,78 @@ import { dual } from "./Function.ts" import * as Reducer from "./Reducer.ts" /** + * Maps a defined value with `f`, or returns `undefined` unchanged. + * + * **When to use** + * + * Use to apply a pure transformation to an `A | undefined` value while + * preserving `undefined` as absence. + * + * @see {@link match} when you need to handle the `undefined` case explicitly + * + * @category mapping * @since 4.0.0 */ export const map: { /** + * Maps a defined value with `f`, or returns `undefined` unchanged. + * + * **When to use** + * + * Use to apply a pure transformation to an `A | undefined` value while + * preserving `undefined` as absence. + * + * @see {@link match} when you need to handle the `undefined` case explicitly + * + * @category mapping * @since 4.0.0 */ (f: (a: A) => B): (self: A | undefined) => B | undefined /** + * Maps a defined value with `f`, or returns `undefined` unchanged. + * + * **When to use** + * + * Use to apply a pure transformation to an `A | undefined` value while + * preserving `undefined` as absence. + * + * @see {@link match} when you need to handle the `undefined` case explicitly + * + * @category mapping * @since 4.0.0 */ (self: A | undefined, f: (a: A) => B): B | undefined } = dual(2, (self, f) => (self === undefined ? undefined : f(self))) /** + * Pattern matches on an `A | undefined` value, running `onDefined` when the + * value is present or evaluating `onUndefined` when the value is `undefined`. + * + * **When to use** + * + * Use when you need to turn an `A | undefined` into a non-optional result by + * handling both the defined and undefined branches in one expression. + * + * @see {@link map} for transforming defined values while preserving `undefined` + * @see {@link getOrThrowWith} for throwing when the value is `undefined` instead of returning a fallback branch + * + * @category pattern matching * @since 4.0.0 */ export const match: { /** + * Pattern matches on an `A | undefined` value, running `onDefined` when the + * value is present or evaluating `onUndefined` when the value is `undefined`. + * + * **When to use** + * + * Use when you need to turn an `A | undefined` into a non-optional result by + * handling both the defined and undefined branches in one expression. + * + * @see {@link map} for transforming defined values while preserving `undefined` + * @see {@link getOrThrowWith} for throwing when the value is `undefined` instead of returning a fallback branch + * + * @category pattern matching * @since 4.0.0 */ ( @@ -60,6 +97,18 @@ export const match: { } ): (self: A | undefined) => B | C /** + * Pattern matches on an `A | undefined` value, running `onDefined` when the + * value is present or evaluating `onUndefined` when the value is `undefined`. + * + * **When to use** + * + * Use when you need to turn an `A | undefined` into a non-optional result by + * handling both the defined and undefined branches in one expression. + * + * @see {@link map} for transforming defined values while preserving `undefined` + * @see {@link getOrThrowWith} for throwing when the value is `undefined` instead of returning a fallback branch + * + * @category pattern matching * @since 4.0.0 */ ( @@ -78,14 +127,65 @@ export const match: { ) /** + * Returns the defined value, or throws the value produced by `onUndefined` + * when the input is `undefined`. + * + * **When to use** + * + * Use when you need fail-fast unwrapping of an `A | undefined` value and want + * to provide the thrown error for the undefined case. + * + * **Details** + * + * Defined values are returned unchanged. When the input is `undefined`, + * `onUndefined` is called and its result is thrown. + * + * @see {@link getOrThrow} for the default-error sibling + * @see {@link match} for handling defined and undefined cases without throwing + * + * @category getters * @since 4.0.0 */ export const getOrThrowWith: { /** + * Returns the defined value, or throws the value produced by `onUndefined` + * when the input is `undefined`. + * + * **When to use** + * + * Use when you need fail-fast unwrapping of an `A | undefined` value and want + * to provide the thrown error for the undefined case. + * + * **Details** + * + * Defined values are returned unchanged. When the input is `undefined`, + * `onUndefined` is called and its result is thrown. + * + * @see {@link getOrThrow} for the default-error sibling + * @see {@link match} for handling defined and undefined cases without throwing + * + * @category getters * @since 4.0.0 */ (onUndefined: () => unknown): (self: A | undefined) => A /** + * Returns the defined value, or throws the value produced by `onUndefined` + * when the input is `undefined`. + * + * **When to use** + * + * Use when you need fail-fast unwrapping of an `A | undefined` value and want + * to provide the thrown error for the undefined case. + * + * **Details** + * + * Defined values are returned unchanged. When the input is `undefined`, + * `onUndefined` is called and its result is thrown. + * + * @see {@link getOrThrow} for the default-error sibling + * @see {@link match} for handling defined and undefined cases without throwing + * + * @category getters * @since 4.0.0 */ (self: A | undefined, onUndefined: () => unknown): A @@ -97,6 +197,23 @@ export const getOrThrowWith: { }) /** + * Returns the defined value, or throws a default `Error` when the input is + * `undefined`. + * + * **When to use** + * + * Use when you need to unwrap a value that should already be defined and a + * generic missing-value `Error` is acceptable. + * + * **Details** + * + * Defined inputs are returned unchanged. `undefined` throws + * `new Error("getOrThrow called on a undefined")`. + * + * @see {@link getOrThrowWith} for the sibling that lets callers choose the thrown value + * @see {@link match} for handling defined and undefined cases without throwing + * + * @category getters * @since 4.0.0 */ export const getOrThrow: (self: A | undefined) => A = getOrThrowWith(() => @@ -104,6 +221,20 @@ export const getOrThrow: (self: A | undefined) => A = getOrThrowWith(() => ) /** + * Converts a throwing function into one that returns successful results + * unchanged and returns `undefined` when the function throws. + * + * **When to use** + * + * Use to adapt exception-throwing functions when `undefined` is the absence + * value you want to return for failures. + * + * **Gotchas** + * + * Thrown values are discarded. If the wrapped function can successfully return + * `undefined`, that success is indistinguishable from a thrown failure. + * + * @category converting * @since 4.0.0 */ export const liftThrowable = , B>( @@ -121,19 +252,21 @@ export const liftThrowable = , B>( * Creates a `Reducer` for `UndefinedOr` that prioritizes the first non-`undefined` * value and combines values when both operands are present. * - * This `Reducer` is useful for scenarios where you want to: - * - Take the first available value (like a fallback chain) - * - Combine values when both are present - * - Maintain a `undefined` state only when all values are `undefined` + * **When to use** + * + * Use when you need to reduce values that may be `undefined`, keeping the + * first defined value as a fallback and combining only when both operands are + * defined. * - * The `initialValue` of the `Reducer` is `undefined`. + * **Details** * - * **Behavior:** - * - `undefined` + `undefined` = `undefined` - * - `a` + `undefined` = `a` (first value wins) - * - `undefined` + `b` = `b` (second value wins) - * - `a` + `b` = `a + b` (values combined) + * Combining `undefined` with `undefined` returns `undefined`. Combining a + * defined value with `undefined` keeps the defined value, so the first defined + * value wins when only one side is present. When both values are defined, they + * are combined with `combiner.combine`. The reducer's initial value is + * `undefined`. * + * @category constructors * @since 4.0.0 */ export function makeReducer(combiner: Combiner.Combiner): Reducer.Reducer { @@ -145,24 +278,24 @@ export function makeReducer(combiner: Combiner.Combiner): Reducer.Reducer< } /** - * Creates a `Combiner` for `UndefinedOr` that only combines values when both - * operands are not `undefined`, failing fast if either is `undefined`. + * Creates a `Combiner` for `A | undefined` that combines values only when both + * operands are defined. * - * This `Combiner` is useful for scenarios where you need both values to be - * present to perform an operation, such as: - * - Mathematical operations that require two operands - * - Data validation that needs both fields - * - Operations that can't proceed with partial data + * **When to use** * - * **Behavior:** - * - `undefined` + `undefined` = `undefined` - * - `a` + `undefined` = `undefined` (fails fast) - * - `undefined` + `b` = `undefined` (fails fast) - * - `a` + `b` = `a + b` (values combined) + * Use to lift a `Combiner` so any `undefined` operand makes the combined result + * `undefined`. + * + * **Details** + * + * - `undefined` combined with any value returns `undefined` + * - Any value combined with `undefined` returns `undefined` + * - `a` combined with `b` returns `combiner.combine(a, b)` * * @see {@link makeReducerFailFast} if you have a `Reducer` and want to lift it * to `UndefinedOr` values. * + * @category constructors * @since 4.0.0 */ export function makeCombinerFailFast(combiner: Combiner.Combiner): Combiner.Combiner { @@ -173,23 +306,24 @@ export function makeCombinerFailFast(combiner: Combiner.Combiner): Combine } /** - * Creates a `Reducer` for `UndefinedOr` by wrapping an existing `Reducer` with - * fail-fast semantics for `UndefinedOr` values. + * Creates a `Reducer` for `A | undefined` by wrapping an existing reducer with + * fail-fast semantics. + * + * **When to use** * - * This function lifts a regular `Reducer` into the `UndefinedOr` context, allowing - * you to use existing `Reducer`s with `UndefinedOr` values while maintaining the - * fail-fast behavior where any `undefined` value causes the entire reduction to fail. + * Use to wrap an existing `Reducer` so any `undefined` value aborts the entire + * reduction result. * - * The initial value is `some(reducer.initialValue)`, ensuring the `Reducer` - * starts with a valid `UndefinedOr` value. + * **Details** * - * **Behavior:** - * - Fails fast (returns `undefined`) if any operand is `undefined` - * - Uses the underlying reducer's combine logic when both values are present + * - Initial value is the wrapped reducer's `initialValue` + * - Combining two defined values delegates to the wrapped reducer + * - If the accumulator or next value is `undefined`, the reduction returns `undefined` * * @see {@link makeCombinerFailFast} if you only have a `Combiner` and want to * lift it to `UndefinedOr` values. * + * @category constructors * @since 4.0.0 */ export function makeReducerFailFast(reducer: Reducer.Reducer): Reducer.Reducer { diff --git a/.opencode/node_modules/effect/src/Unify.ts b/.opencode/node_modules/effect/src/Unify.ts index 66b714fc779092bf52f6faf4ba7f1672831b85fc..5fd3f992903d6bb8887bbf2a9d6f75deea45f235 100644 --- a/.opencode/node_modules/effect/src/Unify.ts +++ b/.opencode/node_modules/effect/src/Unify.ts @@ -1,142 +1,133 @@ /** + * Defines Effect's type-level unification protocol. + * + * Unification collapses unions of protocol-enabled values into their public data + * types. It is mostly for maintainers of Effect data types and advanced library + * authors; application code usually benefits from it through APIs such as + * `Effect`, `Option`, `Result`, `Stream`, `Layer`, and `Match`. This module + * exports the protocol symbols, the `Unify` type that performs normalization, + * and `unify`, an identity function that changes only the inferred type. + * * @since 2.0.0 */ import { identity } from "./Function.ts" /** - * A unique symbol used to identify unification behavior in Effect types. + * Defines the unique symbol used to identify unification behavior in Effect types. * - * This symbol is used internally by the Effect type system to enable automatic - * unification of Effect types in unions and complex type operations. + * **When to use** * - * @example - * ```ts - * import type { Unify } from "effect" + * Use to define the widened type produced by the `Unify` protocol for a custom + * protocol-enabled data type. * - * // The unifySymbol is used internally in Effect types - * // to enable automatic type unification - * declare const effect: { - * readonly [Unify.unifySymbol]?: any - * } - * ``` + * **Details** + * + * This symbol is a type-level protocol key. It describes how a protocol-enabled + * type widens during unification and has no runtime behavior. + * + * @see {@link typeSymbol} for storing the source type information used during unification + * @see {@link ignoreSymbol} for excluding protocol entries from unification * - * @since 2.0.0 * @category symbols + * @since 2.0.0 */ export declare const unifySymbol: unique symbol /** * The type of the unifySymbol. * + * **When to use** + * + * Use to reference the unification behavior property key in type-level + * protocol definitions. + * + * **Details** + * * This type represents the unique symbol used for identifying unification * behavior in Effect types. It's typically used in type-level operations * to enable automatic type unification. * - * @example - * ```ts - * import type { Unify } from "effect" - * - * // The unifySymbol type is used in type declarations - * // to enable unification behavior - * type UnifyableType = { - * [Unify.unifySymbol]?: any - * } - * ``` - * - * @since 2.0.0 * @category symbols + * @since 2.0.0 */ export type unifySymbol = typeof unifySymbol /** - * A unique symbol used to identify the type information for unification. + * Defines the unique symbol used to identify the type information for unification. * - * This symbol is used internally by the Effect type system to store type - * information that can be used during type unification operations. + * **When to use** * - * @example - * ```ts - * import type { Unify } from "effect" + * Use when you need a type-level protocol key that exposes the source type + * read by `Unify` from a protocol-enabled data type. * - * // The typeSymbol is used internally in Effect types - * // to store type information for unification - * declare const effect: { - * readonly [Unify.typeSymbol]?: any - * } - * ``` + * **Details** + * + * This symbol is a type-level protocol key. It stores the source type that + * unification reads when widening protocol-enabled values. + * + * @see {@link unifySymbol} for defining how protocol entries widen * - * @since 2.0.0 * @category symbols + * @since 2.0.0 */ export declare const typeSymbol: unique symbol /** * The type of the typeSymbol. * + * **When to use** + * + * Use to reference the type information property key in type-level protocol + * definitions. + * + * **Details** + * * This type represents the unique symbol used for storing type information * in types that support unification. It's used in type-level operations * to access and manipulate type information. * - * @example - * ```ts - * import type { Unify } from "effect" - * - * // The typeSymbol type is used in type declarations - * // to store type information for unification - * type TypedValue = { - * [Unify.typeSymbol]?: string - * } - * ``` - * - * @since 2.0.0 * @category symbols + * @since 2.0.0 */ export type typeSymbol = typeof typeSymbol /** - * A unique symbol used to specify types that should be ignored during unification. + * Defines the unique symbol used to specify types that should be ignored during unification. * - * This symbol is used internally by the Effect type system to mark types - * that should be excluded from the unification process, allowing for more - * precise type handling in complex scenarios. + * **When to use** * - * @example - * ```ts - * import type { Unify } from "effect" + * Use to hide helper protocol entries from `Unify` when they should not + * contribute to the widened type. * - * // The ignoreSymbol is used internally in Effect types - * // to mark types that should be ignored during unification - * declare const effect: { - * readonly [Unify.ignoreSymbol]?: any - * } - * ``` + * **Details** + * + * This symbol is a type-level protocol key. It lists protocol entries that + * unification should ignore when computing the widened type. + * + * @see {@link unifySymbol} for defining the protocol entries being filtered * - * @since 2.0.0 * @category symbols + * @since 2.0.0 */ export declare const ignoreSymbol: unique symbol /** * The type of the ignoreSymbol. * + * **When to use** + * + * Use to reference the ignored-property key in type-level protocol + * definitions. + * + * **Details** + * * This type represents the unique symbol used for marking types that should * be ignored during unification operations. It's used in type-level operations * to exclude specific types from the unification process. * - * @example - * ```ts - * import type { Unify } from "effect" - * - * // The ignoreSymbol type is used in type declarations - * // to mark types that should be ignored during unification - * type IgnorableType = { - * [Unify.ignoreSymbol]?: unknown - * } - * ``` - * - * @since 2.0.0 * @category symbols + * @since 2.0.0 */ export type ignoreSymbol = typeof ignoreSymbol @@ -174,14 +165,21 @@ type FilterOut = A extends any ? typeSymbol extends keyof A ? never : A : nev /** * Unifies types that implement the unification protocol. * + * **When to use** + * + * Use to normalize unions of types that expose Effect's unification protocol. + * + * **Details** + * * This type performs automatic type unification for types that contain * the unification symbols (`unifySymbol`, `typeSymbol`, `ignoreSymbol`). * It's primarily used internally by the Effect type system to handle * complex type unions and provide better type inference. * - * @example + * **Example** (Unifying protocol types) + * * ```ts - * import type * as Unify from "effect/Unify" + * import type { Unify } from "effect" * * // Example of types that can be unified * type UnifiableA = { @@ -201,8 +199,10 @@ type FilterOut = A extends any ? typeSymbol extends keyof A ? never : A : nev * // Results in a properly unified type * ``` * - * @since 2.0.0 + * @see {@link unify} for applying this normalization to a value or function + * * @category models + * @since 2.0.0 */ export type Unify = Values< ExtractTypes< @@ -228,13 +228,21 @@ export type Unify = Values< : never /** - * Unifies the return type of a function or value. + * Applies `Unify` to a value or function return type at compile time. + * + * **When to use** + * + * Use to keep a value or function unchanged at runtime while normalizing its + * inferred type with Effect's unification protocol. + * + * **Details** + * + * This is an identity function at runtime. For functions, the returned function + * has the same runtime behavior while its return type is normalized with the + * Effect unification protocol. * - * This function applies type unification to the result of a function or to a value directly. - * It's useful when you need to ensure that complex type unions are properly unified according - * to the Effect type system's unification protocol. + * **Example** (Unifying values and function results) * - * @example * ```ts * import { Unify } from "effect" * @@ -258,18 +266,28 @@ export type Unify = Values< * // Type: (a: string) => (b: number) => Unify<{ result: string }> * ``` * + * @see {@link Unify} for the type-level normalization applied by this helper + * + * @category utility types * @since 2.0.0 - * @category utilities */ export const unify: { /** - * Unifies the return type of a function or value. + * Applies `Unify` to a value or function return type at compile time. + * + * **When to use** + * + * Use to keep a value or function unchanged at runtime while normalizing its + * inferred type with Effect's unification protocol. * - * This function applies type unification to the result of a function or to a value directly. - * It's useful when you need to ensure that complex type unions are properly unified according - * to the Effect type system's unification protocol. + * **Details** + * + * This is an identity function at runtime. For functions, the returned function + * has the same runtime behavior while its return type is normalized with the + * Effect unification protocol. + * + * **Example** (Unifying values and function results) * - * @example * ```ts * import { Unify } from "effect" * @@ -293,8 +311,10 @@ export const unify: { * // Type: (a: string) => (b: number) => Unify<{ result: string }> * ``` * + * @see {@link Unify} for the type-level normalization applied by this helper + * + * @category utility types * @since 2.0.0 - * @category utilities */ < Args extends Array, @@ -307,13 +327,21 @@ export const unify: { x: (...args: Args) => (...args: Args2) => (...args: Args3) => (...args: Args4) => (...args: Args5) => T ): (...args: Args) => (...args: Args2) => (...args: Args3) => (...args: Args4) => (...args: Args5) => Unify /** - * Unifies the return type of a function or value. + * Applies `Unify` to a value or function return type at compile time. * - * This function applies type unification to the result of a function or to a value directly. - * It's useful when you need to ensure that complex type unions are properly unified according - * to the Effect type system's unification protocol. + * **When to use** + * + * Use to keep a value or function unchanged at runtime while normalizing its + * inferred type with Effect's unification protocol. + * + * **Details** + * + * This is an identity function at runtime. For functions, the returned function + * has the same runtime behavior while its return type is normalized with the + * Effect unification protocol. + * + * **Example** (Unifying values and function results) * - * @example * ```ts * import { Unify } from "effect" * @@ -337,8 +365,10 @@ export const unify: { * // Type: (a: string) => (b: number) => Unify<{ result: string }> * ``` * + * @see {@link Unify} for the type-level normalization applied by this helper + * + * @category utility types * @since 2.0.0 - * @category utilities */ < Args extends Array, @@ -350,13 +380,21 @@ export const unify: { x: (...args: Args) => (...args: Args2) => (...args: Args3) => (...args: Args4) => T ): (...args: Args) => (...args: Args2) => (...args: Args3) => (...args: Args4) => Unify /** - * Unifies the return type of a function or value. + * Applies `Unify` to a value or function return type at compile time. + * + * **When to use** + * + * Use to keep a value or function unchanged at runtime while normalizing its + * inferred type with Effect's unification protocol. * - * This function applies type unification to the result of a function or to a value directly. - * It's useful when you need to ensure that complex type unions are properly unified according - * to the Effect type system's unification protocol. + * **Details** + * + * This is an identity function at runtime. For functions, the returned function + * has the same runtime behavior while its return type is normalized with the + * Effect unification protocol. + * + * **Example** (Unifying values and function results) * - * @example * ```ts * import { Unify } from "effect" * @@ -380,8 +418,10 @@ export const unify: { * // Type: (a: string) => (b: number) => Unify<{ result: string }> * ``` * + * @see {@link Unify} for the type-level normalization applied by this helper + * + * @category utility types * @since 2.0.0 - * @category utilities */ < Args extends Array, @@ -390,13 +430,21 @@ export const unify: { T >(x: (...args: Args) => (...args: Args2) => (...args: Args3) => T): (...args: Args) => (...args: Args2) => (...args: Args3) => Unify /** - * Unifies the return type of a function or value. + * Applies `Unify` to a value or function return type at compile time. + * + * **When to use** + * + * Use to keep a value or function unchanged at runtime while normalizing its + * inferred type with Effect's unification protocol. + * + * **Details** * - * This function applies type unification to the result of a function or to a value directly. - * It's useful when you need to ensure that complex type unions are properly unified according - * to the Effect type system's unification protocol. + * This is an identity function at runtime. For functions, the returned function + * has the same runtime behavior while its return type is normalized with the + * Effect unification protocol. + * + * **Example** (Unifying values and function results) * - * @example * ```ts * import { Unify } from "effect" * @@ -420,8 +468,10 @@ export const unify: { * // Type: (a: string) => (b: number) => Unify<{ result: string }> * ``` * + * @see {@link Unify} for the type-level normalization applied by this helper + * + * @category utility types * @since 2.0.0 - * @category utilities */ < Args extends Array, @@ -429,13 +479,21 @@ export const unify: { T >(x: (...args: Args) => (...args: Args2) => T): (...args: Args) => (...args: Args2) => Unify /** - * Unifies the return type of a function or value. + * Applies `Unify` to a value or function return type at compile time. + * + * **When to use** + * + * Use to keep a value or function unchanged at runtime while normalizing its + * inferred type with Effect's unification protocol. + * + * **Details** + * + * This is an identity function at runtime. For functions, the returned function + * has the same runtime behavior while its return type is normalized with the + * Effect unification protocol. * - * This function applies type unification to the result of a function or to a value directly. - * It's useful when you need to ensure that complex type unions are properly unified according - * to the Effect type system's unification protocol. + * **Example** (Unifying values and function results) * - * @example * ```ts * import { Unify } from "effect" * @@ -459,21 +517,31 @@ export const unify: { * // Type: (a: string) => (b: number) => Unify<{ result: string }> * ``` * + * @see {@link Unify} for the type-level normalization applied by this helper + * + * @category utility types * @since 2.0.0 - * @category utilities */ < Args extends Array, T >(x: (...args: Args) => T): (...args: Args) => Unify /** - * Unifies the return type of a function or value. + * Applies `Unify` to a value or function return type at compile time. + * + * **When to use** + * + * Use to keep a value or function unchanged at runtime while normalizing its + * inferred type with Effect's unification protocol. * - * This function applies type unification to the result of a function or to a value directly. - * It's useful when you need to ensure that complex type unions are properly unified according - * to the Effect type system's unification protocol. + * **Details** + * + * This is an identity function at runtime. For functions, the returned function + * has the same runtime behavior while its return type is normalized with the + * Effect unification protocol. + * + * **Example** (Unifying values and function results) * - * @example * ```ts * import { Unify } from "effect" * @@ -497,8 +565,10 @@ export const unify: { * // Type: (a: string) => (b: number) => Unify<{ result: string }> * ``` * + * @see {@link Unify} for the type-level normalization applied by this helper + * + * @category utility types * @since 2.0.0 - * @category utilities */ (x: T): Unify } = identity as any diff --git a/.opencode/node_modules/effect/src/Utils.ts b/.opencode/node_modules/effect/src/Utils.ts index 749b97ced74581858c9c3ae2acd24563c0b7deee..0886e5f6dee97c619b8d6b2a4cfb4a17060d3afa 100644 --- a/.opencode/node_modules/effect/src/Utils.ts +++ b/.opencode/node_modules/effect/src/Utils.ts @@ -1,59 +1,12 @@ /** - * Internal utilities for the Effect ecosystem's generator-based syntax and - * higher-kinded type machinery. + * Internal and advanced utilities used by Effect's generator-based syntax and + * higher-kinded type support. This is not a general-purpose utility module for + * application code. * - * ## Mental model - * - * - **SingleShotGen** — an `IterableIterator` wrapper that yields its value - * exactly once. Used internally by `[Symbol.iterator]()` on Effect, Option, - * Result, and other yieldable types so they work inside generator functions. - * - **Gen** — a type-level signature for generator-based monadic composition - * (`gen` functions). Parametric over any `TypeLambda` so each module - * (Effect, Option, Result, ...) can expose its own `gen` with correct types. - * - **Variance** — a type-level marker that encodes the variance (covariant, - * contravariant, invariant) of a `TypeLambda`'s type parameters. - * Used by {@link Gen} for type inference. - * - * ## Common tasks - * - * - Make a type yieldable in generators -> implement `[Symbol.iterator]()` returning a {@link SingleShotGen} - * - Define a generator-based API for a new TypeLambda -> type it as {@link Gen}`` - * - Encode variance for a higher-kinded type -> use {@link Variance} - * - * ## Gotchas - * - * - {@link SingleShotGen} yields its value only on the first `.next()` call. - * Calling `.next()` again returns `{ done: true }`. Iterating the same - * instance twice will skip the value on the second pass; call - * `[Symbol.iterator]()` to get a fresh iterator. - * - {@link Gen} and {@link Variance} are pure type-level constructs — they - * have no runtime representation. - * - * ## Quickstart - * - * **Example** (Using SingleShotGen to make a type yieldable) - * - * ```ts - * import { Utils } from "effect" - * - * class MyWrapper { - * constructor(readonly value: A) {} - * [Symbol.iterator]() { - * return new Utils.SingleShotGen, A>(this) - * } - * } - * - * const w = new MyWrapper(42) - * const iter = w[Symbol.iterator]() - * console.log(iter.next(undefined as any)) - * // { value: MyWrapper { value: 42 }, done: false } - * console.log(iter.next(42)) - * // { value: 42, done: true } - * ``` - * - * @see {@link SingleShotGen} - * @see {@link Gen} - * @see {@link Variance} + * `SingleShotGen` makes an Effect-style value work with `yield*` inside + * generator helpers. `Variance` and `Gen` provide the type-level signatures + * used by modules such as `Effect`, `Option`, and `Result` to type their + * `gen` APIs. * * @since 2.0.0 */ @@ -61,23 +14,20 @@ import type { Kind, TypeLambda } from "./HKT.ts" import type * as Types from "./Types.ts" /** - * An `IterableIterator` that yields its wrapped value exactly once. + * Yields its wrapped value exactly once through an `IterableIterator`. * - * When to use: + * **When to use** * - * - Implement `[Symbol.iterator]()` on Effect-like types so they can be - * `yield*`-ed inside generator functions (e.g. `Effect.gen`, `Option.gen`). - * - You almost never construct this directly — it is created internally by - * yieldable types. + * Use to implement `[Symbol.iterator]()` on Effect-like types so they can be + * `yield*`-ed inside generator functions, such as `Effect.gen` and + * `Option.gen`. * - * Behavior: + * **Details** * - * - The first call to `next()` returns `{ value: self, done: false }`. - * - Every subsequent call returns `{ value: a, done: true }` where `a` is - * the argument passed to `next()`. - * - `[Symbol.iterator]()` returns a **new** `SingleShotGen` wrapping the same - * value, so the outer type can be iterated multiple times. - * - Does not mutate the wrapped value. + * The first call to `next()` returns `{ value: self, done: false }`. Every + * subsequent call returns `{ value: a, done: true }` where `a` is the argument + * passed to `next()`. `[Symbol.iterator]()` returns a **new** `SingleShotGen` + * wrapping the same value, so the outer type can be iterated multiple times. * * **Example** (Yielding a wrapped value in a generator) * @@ -95,8 +45,7 @@ import type * as Types from "./Types.ts" * // { value: 42, done: true } * ``` * - * @see {@link Gen} — the type-level signature that relies on `SingleShotGen` - * + * @see {@link Gen} for the type-level signature that relies on `SingleShotGen` * @category constructors * @since 2.0.0 */ @@ -109,6 +58,13 @@ export class SingleShotGen implements IterableIterator { } /** + * Yields the stored value once, then completes with the value sent back in. + * + * **When to use** + * + * Use to advance a `SingleShotGen` through its single yield and completion + * step. + * * @since 2.0.0 */ next(a: A): IteratorResult { @@ -125,6 +81,13 @@ export class SingleShotGen implements IterableIterator { } /** + * Creates a fresh single-shot iterator over the stored value. + * + * **When to use** + * + * Use to iterate the wrapped value again without reusing the consumed + * iterator state. + * * @since 2.0.0 */ [Symbol.iterator](): IterableIterator { @@ -136,25 +99,22 @@ export class SingleShotGen implements IterableIterator { * Type-level marker encoding the variance of a `TypeLambda`'s type * parameters. * - * When to use: + * **When to use** * - * - Define variance constraints for a higher-kinded type so that - * {@link Gen} can correctly infer `R`, `O`, and `E` from yielded values. - * - You typically don't construct values of this type — it exists purely for - * type inference. + * Use to define variance constraints for a higher-kinded type so that + * {@link Gen} can correctly infer `R`, `O`, and `E` from yielded values. * - * Behavior: + * **Details** * - * - `F` is invariant (must match exactly). - * - `R` is contravariant (input / environment position). - * - `O` and `E` are covariant (output / error position). - * - Pure type-level construct — no runtime representation. + * `F` is invariant and must match exactly. `R` is contravariant in the input + * or environment position. `O` and `E` are covariant in the output and error + * positions. This is a pure type-level construct with no runtime + * representation. * * **Example** (Declaring variance for a TypeLambda) * * ```ts - * import type { Utils } from "effect" - * import type * as Option from "effect/Option" + * import type { Option, Utils } from "effect" * * declare const variance: Utils.Variance< * Option.OptionTypeLambda, @@ -164,8 +124,7 @@ export class SingleShotGen implements IterableIterator { * > * ``` * - * @see {@link Gen} — uses `Variance` for type parameter inference - * + * @see {@link Gen} for the type-level signature that uses `Variance` * @category models * @since 2.0.0 */ @@ -180,19 +139,16 @@ export interface Variance { * Type-level signature for generator-based monadic composition over any * `TypeLambda`. * - * When to use: + * **When to use** * - * - Type the `gen` function of a module that supports generator syntax - * (e.g. `Option.gen`, `Result.gen`, `Effect.gen`). - * - Accepts either `(body)` or `(self, body)` where `body` is a generator - * function. The `self` overload binds `this` inside the generator. + * Use to type the `gen` function of a module that supports generator syntax, + * such as `Option.gen`, `Result.gen`, and `Effect.gen`. * - * Behavior: + * **Details** * - * - Pure type alias — no runtime behavior. - * - Infers `R`, `O`, `E` from the yielded values via {@link Variance} or - * `Kind` constraints. - * - The generator's return type `A` becomes the output's `A` parameter. + * This is a pure type alias with no runtime behavior. It infers `R`, `O`, and + * `E` from the yielded values via {@link Variance} or `Kind` constraints. The + * generator's return type `A` becomes the output's `A` parameter. * * **Example** (Typing a gen function for Option) * @@ -202,9 +158,8 @@ export interface Variance { * declare const gen: Utils.Gen * ``` * - * @see {@link Variance} — encodes the variance used for inference - * @see {@link SingleShotGen} — the iterator protocol that makes yielding work - * + * @see {@link Variance} for encoding the variance used for inference + * @see {@link SingleShotGen} for the iterator protocol that makes yielding work * @category models * @since 2.0.0 */ @@ -235,25 +190,32 @@ export type Gen = < A > -const InternalTypeId = "~effect/Utils/internal" +// the probe is wrapped in a single function call (rather than module-level +// statements) so the whole selection is pure-annotated by the build and +// tree-shakable when `internalCall` is unused. +const pickInternalCall = (): (body: () => A) => A => { + const InternalTypeId = "~effect/Utils/internal" -const standard = { - [InternalTypeId]: (body: () => A) => { - return body() + const standard = { + [InternalTypeId]: (body: () => A) => { + return body() + } } -} -const forced = { - [InternalTypeId]: (body: () => A) => { - try { - return body() - } finally { - // + const forced = { + [InternalTypeId]: (body: () => A) => { + try { + return body() + } finally { + // + } } } -} -const isNotOptimizedAway = standard[InternalTypeId](() => new Error().stack)?.includes(InternalTypeId) === true + const isNotOptimizedAway = standard[InternalTypeId](() => new Error().stack)?.includes(InternalTypeId) === true + + return isNotOptimizedAway ? standard[InternalTypeId] : forced[InternalTypeId] +} /** @internal */ -export const internalCall = isNotOptimizedAway ? standard[InternalTypeId] : forced[InternalTypeId] +export const internalCall = pickInternalCall() diff --git a/.opencode/node_modules/effect/src/index.ts b/.opencode/node_modules/effect/src/index.ts index 34127ae02fe747713d78f7393825548e48ab9a71..0fae70acc8e78f69c40445a1c399144f9f674a62 100644 --- a/.opencode/node_modules/effect/src/index.ts +++ b/.opencode/node_modules/effect/src/index.ts @@ -32,130 +32,26 @@ export { // @barrel: Auto-generated exports. Do not edit manually. /** - * Utilities for working with immutable arrays (and non-empty arrays) in a - * functional style. All functions treat arrays as immutable — they return new - * arrays rather than mutating the input. - * - * ## Mental model - * - * - **`Array`** is a standard JS array. All functions in this module return - * new arrays; the input is never mutated. - * - **`NonEmptyReadonlyArray`** (`readonly [A, ...Array]`) is a readonly - * array guaranteed to have at least one element. Many functions preserve or - * require this guarantee at the type level. - * - **`NonEmptyArray`** is the mutable counterpart: `[A, ...Array]`. - * - Most functions are **dual** — they can be called either as - * `Array.fn(array, arg)` (data-first) or piped as - * `pipe(array, Array.fn(arg))` (data-last). - * - Functions that access elements by index return `Option` for safety; use - * the `*NonEmpty` variants (e.g. {@link headNonEmpty}) when you already know - * the array is non-empty. - * - Set-like operations ({@link union}, {@link intersection}, - * {@link difference}) use `Equal.equivalence()` by default; use the `*With` - * variants for custom equality. - * - * ## Common tasks - * - * - **Create** an array: {@link make}, {@link of}, {@link empty}, - * {@link fromIterable}, {@link range}, {@link makeBy}, {@link replicate}, - * {@link unfold} - * - **Access** elements: {@link head}, {@link last}, {@link get}, {@link tail}, - * {@link init} - * - **Transform**: {@link map}, {@link flatMap}, {@link flatten} - * - **Filter**: {@link filter}, {@link partition}, {@link dedupe} - * - **Combine**: {@link append}, {@link prepend}, {@link appendAll}, - * {@link prependAll}, {@link zip}, {@link cartesian} - * - **Split**: {@link splitAt}, {@link chunksOf}, {@link span}, {@link window} - * - **Search**: {@link findFirst}, {@link findLast}, {@link contains} - * - **Sort**: {@link sort}, {@link sortBy}, {@link sortWith} - * - **Fold**: {@link reduce}, {@link scan}, {@link join} - * - **Group**: {@link groupBy}, {@link group}, {@link groupWith} - * - **Set operations**: {@link union}, {@link intersection}, - * {@link difference} - * - **Match** on empty vs non-empty: {@link match}, {@link matchLeft}, - * {@link matchRight} - * - **Check** properties: {@link isArray}, {@link isArrayNonEmpty}, - * {@link every}, {@link some} - * - * ## Gotchas - * - * - {@link fromIterable} returns the original array reference when given an - * array; if you need a copy, use {@link copy}. - * - `sort`, `reverse`, etc. always allocate a new array — the input is never - * mutated. - * - {@link makeBy} and {@link replicate} normalize `n` to an integer >= 1 — - * they never produce an empty array. - * - {@link range}`(start, end)` is inclusive on both ends. If `start > end` it - * returns `[start]`. - * - Functions returning `Option` (e.g. {@link head}, {@link findFirst}) return - * `Option.none()` for empty inputs — they never throw. - * - * ## Quickstart - * - * **Example** (Basic array operations) - * - * ```ts - * import { Array } from "effect" - * - * const numbers = Array.make(1, 2, 3, 4, 5) - * - * const doubled = Array.map(numbers, (n) => n * 2) - * console.log(doubled) // [2, 4, 6, 8, 10] - * - * const evens = Array.filter(numbers, (n) => n % 2 === 0) - * console.log(evens) // [2, 4] - * - * const sum = Array.reduce(numbers, 0, (acc, n) => acc + n) - * console.log(sum) // 15 - * ``` - * - * @see {@link make} — create a non-empty array from elements - * @see {@link map} — transform each element - * @see {@link filter} — keep elements matching a predicate - * @see {@link reduce} — fold an array to a single value - * * @since 2.0.0 */ export * as Array from "./Array.ts" /** - * This module provides utility functions and type class instances for working with the `BigDecimal` type in TypeScript. - * It includes functions for basic arithmetic operations. - * - * A `BigDecimal` allows storing any real number to arbitrary precision; which avoids common floating point errors - * (such as 0.1 + 0.2 ≠ 0.3) at the cost of complexity. - * - * Internally, `BigDecimal` uses a `BigInt` object, paired with a 64-bit integer which determines the position of the - * decimal point. Therefore, the precision *is not* actually arbitrary, but limited to 263 decimal places. - * - * It is not recommended to convert a floating point number to a decimal directly, as the floating point representation - * may be unexpected. - * * @since 2.0.0 */ export * as BigDecimal from "./BigDecimal.ts" /** - * This module provides utility functions and type class instances for working with the `bigint` type in TypeScript. - * It includes functions for basic arithmetic operations. - * * @since 2.0.0 */ export * as BigInt from "./BigInt.ts" /** - * This module provides utility functions and type class instances for working with the `boolean` type in TypeScript. - * It includes functions for basic boolean operations. - * * @since 2.0.0 */ export * as Boolean from "./Boolean.ts" /** - * This module provides types and utility functions to create and work with - * branded types, which are TypeScript types with an added type tag to prevent - * accidental usage of a value in the wrong context. - * * @since 2.0.0 */ export * as Brand from "./Brand.ts" @@ -166,142 +62,11 @@ export * as Brand from "./Brand.ts" export * as Cache from "./Cache.ts" /** - * Structured representation of how an Effect can fail. - * - * A `Cause` holds a flat array of `Reason` values, where each reason is one of: - * - * - **Fail** — a typed, expected error `E` (created by `Effect.fail`) - * - **Die** — an untyped defect (`unknown`) from `Effect.die` or uncaught throws - * - **Interrupt** — a fiber interruption, optionally carrying the interrupting fiber's ID - * - * ## Mental model - * - * - A `Cause` is always flat: concurrent and sequential failures are stored together - * in `cause.reasons` (a `ReadonlyArray>`). - * - Each `Reason` carries an `annotations` map with tracing metadata (stack frames, spans). - * - An empty `reasons` array means the computation succeeded or the cause was empty - * ({@link empty}). - * - `Cause` implements `Equal`, so two causes with identical reasons compare as equal. - * - * ## Common tasks - * - * | Intent | API | - * |--------|-----| - * | Create a cause | {@link fail}, {@link die}, {@link interrupt}, {@link fromReasons} | - * | Test for reason types | {@link hasFails}, {@link hasDies}, {@link hasInterrupts} | - * | Extract the first error/defect | {@link findError}, {@link findDefect}, {@link findFail}, {@link findDie} | - * | Iterate over reasons manually | `cause.reasons.filter(Cause.isFailReason)` | - * | Combine two causes | {@link combine} | - * | Transform errors | {@link map} | - * | Collapse to a single thrown value | {@link squash} | - * | Render for logging | {@link pretty}, {@link prettyErrors} | - * | Attach/read tracing metadata | {@link annotate}, {@link annotations}, {@link reasonAnnotations} | - * - * ## Gotchas - * - * - `findError`/`findDefect` return `Filter.fail` (not `Option.none`) when no match is - * found. Use {@link findErrorOption} if you need an `Option`. - * - `squash` picks the first `Fail` error, then the first `Die` defect, then falls back - * to a generic "interrupted" / "empty" error. It is lossy — use `prettyErrors` or - * iterate `reasons` directly when you need all failures. - * - The module also exports several built-in error classes (`NoSuchElementError`, - * `TimeoutError`, `IllegalArgumentError`, `ExceededCapacityError`, `UnknownError`) - * and the `Done` completion signal. These all implement `YieldableError` and can be - * yielded directly inside `Effect.gen`. - * - * **Example** (inspecting a concurrent failure) - * - * ```ts - * import { Cause, Effect } from "effect" - * - * const program = Effect.gen(function*() { - * const cause = yield* Effect.sandbox( - * Effect.all([ - * Effect.fail("err1"), - * Effect.die("defect"), - * Effect.fail("err2") - * ], { concurrency: "unbounded" }) - * ).pipe(Effect.flip) - * - * const errors = cause.reasons - * .filter(Cause.isFailReason) - * .map((r) => r.error) - * - * const defects = cause.reasons - * .filter(Cause.isDieReason) - * .map((r) => r.defect) - * - * console.log(errors) // ["err1", "err2"] (order may vary) - * console.log(defects) // ["defect"] - * }) - * - * Effect.runPromise(program) - * ``` - * - * @see {@link Cause} — the core interface - * @see {@link Reason} — the union of failure kinds - * @see {@link pretty} — human-readable rendering - * * @since 2.0.0 */ export * as Cause from "./Cause.ts" /** - * The `Channel` module provides a powerful abstraction for bi-directional communication - * and streaming operations. A `Channel` is a nexus of I/O operations that supports both - * reading and writing, forming the foundation for Effect's Stream and Sink abstractions. - * - * ## What is a Channel? - * - * A `Channel` represents: - * - **OutElem**: The type of elements the channel outputs - * - **OutErr**: The type of errors the channel can produce - * - **OutDone**: The type of the final value when the channel completes - * - **InElem**: The type of elements the channel reads - * - **InErr**: The type of errors the channel can receive - * - **InDone**: The type of the final value from upstream - * - **Env**: The environment/context required by the channel - * - * ## Key Features - * - * - **Bi-directional**: Channels can both read and write - * - **Composable**: Channels can be piped, sequenced, and concatenated - * - **Resource-safe**: Automatic cleanup and resource management - * - **Error-handling**: Built-in error propagation and handling - * - **Concurrent**: Support for concurrent operations - * - * ## Composition Patterns - * - * 1. **Piping**: Connect channels where output of one becomes input of another - * 2. **Sequencing**: Use the result of one channel to create another - * 3. **Concatenating**: Combine multiple channels into a single channel - * - * @example - * ```ts - * import { Channel } from "effect" - * - * // Simple channel that outputs numbers - * const numberChannel = Channel.succeed(42) - * - * // Transform channel that doubles values - * const doubleChannel = Channel.map(numberChannel, (n) => n * 2) - * - * // Running the channel would output: 84 - * ``` - * - * @example - * ```ts - * import { Channel } from "effect" - * - * // Channel from an array of values - * const arrayChannel = Channel.fromArray([1, 2, 3, 4, 5]) - * - * // Transform the channel by mapping over values - * const transformedChannel = Channel.map(arrayChannel, (n) => n * 2) - * - * // This channel will output: 2, 4, 6, 8, 10 - * ``` - * * @since 2.0.0 */ export * as Channel from "./Channel.ts" @@ -312,441 +77,36 @@ export * as Channel from "./Channel.ts" export * as ChannelSchema from "./ChannelSchema.ts" /** - * The `Chunk` module provides an immutable, high-performance sequence data structure - * optimized for functional programming patterns. A `Chunk` is a persistent data structure - * that supports efficient append, prepend, and concatenation operations. - * - * ## What is a Chunk? - * - * A `Chunk` is an immutable sequence of elements of type `A` that provides: - * - **O(1) append and prepend operations** - * - **Efficient concatenation** through tree-like structure - * - **Memory efficiency** with structural sharing - * - **Rich API** with functional programming operations - * - **Type safety** with full TypeScript integration - * - * ## Key Features - * - * - **Immutable**: All operations return new chunks without modifying the original - * - **Efficient**: Optimized data structure with logarithmic complexity for most operations - * - **Functional**: Rich set of transformation and combination operators - * - **Lazy evaluation**: Many operations are deferred until needed - * - **Interoperable**: Easy conversion to/from arrays and other collections - * - * ## Performance Characteristics - * - * - **Append/Prepend**: O(1) amortized - * - **Random Access**: O(log n) - * - **Concatenation**: O(log min(m, n)) - * - **Iteration**: O(n) - * - **Memory**: Structural sharing minimizes allocation - * - * @example - * ```ts - * import { Chunk } from "effect" - * - * // Creating chunks - * const chunk1 = Chunk.fromIterable([1, 2, 3]) - * const chunk2 = Chunk.fromIterable([4, 5, 6]) - * const empty = Chunk.empty() - * - * // Combining chunks - * const combined = Chunk.appendAll(chunk1, chunk2) - * console.log(Chunk.toReadonlyArray(combined)) // [1, 2, 3, 4, 5, 6] - * ``` - * - * @example - * ```ts - * import { Chunk } from "effect" - * - * // Functional transformations - * const numbers = Chunk.range(1, 5) // [1, 2, 3, 4, 5] - * const doubled = Chunk.map(numbers, (n) => n * 2) // [2, 4, 6, 8, 10] - * const evens = Chunk.filter(doubled, (n) => n % 4 === 0) // [4, 8] - * const sum = Chunk.reduce(evens, 0, (acc, n) => acc + n) // 12 - * ``` - * - * @example - * ```ts - * import { Chunk, Effect } from "effect" - * - * // Working with Effects - * const processChunk = (chunk: Chunk.Chunk) => - * Effect.gen(function*() { - * const mapped = Chunk.map(chunk, (n) => n * 2) - * const filtered = Chunk.filter(mapped, (n) => n > 5) - * return Chunk.toReadonlyArray(filtered) - * }) - * ``` - * * @since 2.0.0 */ export * as Chunk from "./Chunk.ts" /** - * The `Clock` module provides functionality for time-based operations in Effect applications. - * It offers precise time measurements, scheduling capabilities, and controlled time management - * for testing scenarios. - * - * The Clock service is a core component of the Effect runtime, providing: - * - Current time access in milliseconds and nanoseconds - * - Sleep operations for delaying execution - * - Time-based scheduling primitives - * - Testable time control through `TestClock` - * - * ## Key Features - * - * - **Precise timing**: Access to both millisecond and nanosecond precision - * - **Sleep operations**: Non-blocking sleep with proper interruption handling - * - **Service integration**: Seamless integration with Effect's dependency injection - * - **Testable**: Mock time control for deterministic testing - * - **Resource-safe**: Automatic cleanup of time-based resources - * - * @example - * ```ts - * import { Clock, Effect } from "effect" - * - * // Get current time in milliseconds - * const getCurrentTime = Clock.currentTimeMillis - * - * // Sleep for 1 second - * const sleep1Second = Effect.sleep("1 seconds") - * - * // Measure execution time - * const measureTime = Effect.gen(function*() { - * const start = yield* Clock.currentTimeMillis - * yield* Effect.sleep("100 millis") - * const end = yield* Clock.currentTimeMillis - * return end - start - * }) - * ``` - * - * @example - * ```ts - * import { Clock, Effect } from "effect" - * - * // Using Clock service directly - * const program = Effect.gen(function*() { - * const clock = yield* Clock.Clock - * const currentTime = yield* clock.currentTimeMillis - * console.log(`Current time: ${currentTime}`) - * - * // Sleep for 500ms - * yield* Effect.sleep("500 millis") - * - * const afterSleep = yield* clock.currentTimeMillis - * console.log(`After sleep: ${afterSleep}`) - * }) - * ``` - * * @since 2.0.0 */ export * as Clock from "./Clock.ts" /** - * A module for combining two values of the same type into one. - * - * A `Combiner` wraps a single binary function `(self: A, that: A) => A`. - * It describes *how* two values merge but carries no initial/empty value - * (for that, see {@link Reducer} which extends `Combiner` with an - * `initialValue`). - * - * ## Mental model - * - * - **Combiner** – an object with a `combine(self, that)` method that returns - * a value of the same type. - * - **Argument order** – `self` is the "left" / accumulator side, `that` is - * the "right" / incoming side. - * - **No identity element** – unlike a monoid, a `Combiner` does not require - * a neutral element. Use {@link Reducer} when you need one. - * - **Purity** – all combiners produced by this module are pure; they never - * mutate their arguments. - * - **Composability** – combiners can be lifted into `Option`, `Struct`, - * `Tuple`, and other container types via helpers in those modules. - * - * ## Common tasks - * - * - Create a combiner from any binary function → {@link make} - * - Swap argument order → {@link flip} - * - Pick the smaller / larger of two values → {@link min} / {@link max} - * - Always keep the first or last value → {@link first} / {@link last} - * - Ignore both values and return a fixed result → {@link constant} - * - Insert a separator between combined values → {@link intercalate} - * - * ## Gotchas - * - * - `min` and `max` require an `Order`, not a raw comparator. Import from - * e.g. `Number.Order` or `String.Order`. - * - `intercalate` is curried: call it with the separator first, then pass the - * base combiner. - * - A `Reducer` (which adds `initialValue`) is also a valid `Combiner` — you - * can pass a `Reducer` anywhere a `Combiner` is expected. - * - * ## Quickstart - * - * **Example** (combining strings with a separator) - * - * ```ts - * import { Combiner, String } from "effect" - * - * const csv = Combiner.intercalate(",")(String.ReducerConcat) - * - * console.log(csv.combine("a", "b")) - * // Output: "a,b" - * - * console.log(csv.combine(csv.combine("a", "b"), "c")) - * // Output: "a,b,c" - * ``` - * - * ## See also - * - * - {@link make} – the primary constructor - * - {@link Combiner} – the core interface - * * @since 4.0.0 */ export * as Combiner from "./Combiner.ts" /** - * Declarative, schema-driven configuration loading. A `Config` describes - * how to read and validate a value of type `T` from a `ConfigProvider`. Configs - * can be composed, transformed, and used directly as Effects. - * - * ## Mental model - * - * - **Config\** – a recipe for extracting a typed value from a - * `ConfigProvider`. Created via convenience constructors or {@link schema}. - * - **ConfigProvider** – the backing data source (env vars, JSON, `.env` - * files). See the `ConfigProvider` module. - * - **ConfigError** – wraps either a `SourceError` (provider I/O failure) or - * a `SchemaError` (validation / decoding failure). - * - **parse** – instance method on every `Config` that takes a provider and - * returns `Effect`. - * - **Yieldable** – every `Config` can be yielded inside `Effect.gen`. It - * automatically resolves the current `ConfigProvider` from the context. - * - * ## Common tasks - * - * - Read a single env var → {@link string}, {@link number}, {@link boolean}, - * {@link int}, {@link port}, {@link url}, {@link date}, {@link duration}, - * {@link logLevel}, {@link redacted} - * - Read a structured config → {@link schema} with a `Schema.Struct` - * - Provide a default → {@link withDefault} - * - Make a config optional → {@link option} - * - Transform a value → {@link map} / {@link mapOrFail} - * - Fall back on error → {@link orElse} - * - Combine multiple configs → {@link all} - * - Build from a `Schema.Codec` → {@link schema} - * - Always succeed or fail → {@link succeed} / {@link fail} - * - * ## Gotchas - * - * - `withDefault` and `option` only apply when the error is caused by - * **missing data**. Validation errors (wrong type, out of range) still - * propagate. - * - When yielded in `Effect.gen`, the config resolves using the current - * `ConfigProvider` service. To use a specific provider, call `.parse(provider)` - * instead. - * - The `name` parameter on convenience constructors (e.g. `Config.string("HOST")`) - * sets the root path segment. Omit it when the config is part of a larger - * schema. - * - * ## Quickstart - * - * **Example** (Reading typed config from environment variables) - * - * ```ts - * import { Config, ConfigProvider, Effect, Schema } from "effect" - * - * const AppConfig = Config.schema( - * Schema.Struct({ - * host: Schema.String, - * port: Schema.Int - * }), - * "app" - * ) - * - * const provider = ConfigProvider.fromEnv({ - * env: { app_host: "localhost", app_port: "8080" } - * }) - * - * // Effect.runSync(AppConfig.parse(provider)) - * // { host: "localhost", port: 8080 } - * ``` - * - * @see {@link schema} – build a Config from any Schema.Codec - * @see {@link ConfigError} – the error type for config failures - * @see {@link make} – low-level Config constructor - * * @since 4.0.0 */ export * as Config from "./Config.ts" /** - * Provides the data source layer for the `Config` module. A `ConfigProvider` - * knows how to load raw configuration nodes from a backing store (environment - * variables, JSON objects, `.env` files, file trees) and expose them through a - * uniform `Node` interface that `Config` schemas consume. - * - * ## Mental model - * - * - **Node** – a discriminated union (`Value | Record | Array`) that describes - * what lives at a given path in the configuration tree. - * - **Path** – an array of string or numeric segments used to address a node - * (e.g. `["database", "host"]`). - * - **ConfigProvider** – an object with a `load(path)` method that resolves a - * path to a `Node | undefined`. Providers can be composed and transformed. - * - **Context.Reference** – `ConfigProvider` is registered as a reference - * service that defaults to `fromEnv()`, so it works without explicit - * provision. - * - **SourceError** – the typed error returned when a backing store is - * unreadable (I/O failure, permission error, etc.). - * - * ## Common tasks - * - * - Read from environment variables → {@link fromEnv} - * - Read from a JSON / plain object → {@link fromUnknown} - * - Parse a `.env` string → {@link fromDotEnvContents} - * - Load a `.env` file → {@link fromDotEnv} - * - Read from a directory tree → {@link fromDir} - * - Build a custom provider → {@link make} - * - Fall back to another provider → {@link orElse} - * - Scope a provider under a prefix → {@link nested} - * - Convert path segments to `CONSTANT_CASE` → {@link constantCase} - * - Transform path segments arbitrarily → {@link mapInput} - * - Install a provider as a Layer → {@link layer} / {@link layerAdd} - * - * ## Gotchas - * - * - `fromEnv` joins path segments with `_` for lookup **and** splits env var - * names on `_` to discover child keys. `DATABASE_HOST=x` is therefore - * accessible at both `["DATABASE_HOST"]` and `["DATABASE", "HOST"]`. - * - Because of `_` splitting, querying a parent path like `["DATABASE"]` - * returns a `Record` node with child key `"HOST"`, even if no env var - * named `DATABASE` exists. - * - When using `fromEnv` with schemas that use camelCase keys, pipe the - * provider through {@link constantCase} so `databaseHost` resolves to - * `DATABASE_HOST`. - * - `orElse` only falls back when the primary provider returns `undefined` - * (path not found). It does **not** catch `SourceError`. - * - `nested` prepends segments to the path *after* `mapInput` has run, so - * the order of composition matters. - * - * ## Quickstart - * - * **Example** (Reading config from environment variables) - * - * ```ts - * import { Config, ConfigProvider, Effect } from "effect" - * - * const provider = ConfigProvider.fromEnv({ - * env: { APP_PORT: "3000", APP_HOST: "localhost" } - * }) - * - * const port = Config.number("port") - * - * const program = port.parse( - * provider.pipe( - * ConfigProvider.nested("app"), - * ConfigProvider.constantCase - * ) - * ) - * - * // Effect.runSync(program) // 3000 - * ``` - * - * @see {@link make} – build a provider from a lookup function - * @see {@link fromEnv} – the default provider backed by `process.env` - * @see {@link fromUnknown} – provider backed by a plain JS object - * * @since 4.0.0 */ export * as ConfigProvider from "./ConfigProvider.ts" /** - * The `Console` module provides a functional interface for console operations within - * the Effect ecosystem. It offers type-safe logging, debugging, and console manipulation - * capabilities with built-in support for testing and environment isolation. - * - * ## Key Features - * - * - **Type-safe logging**: All console operations return Effects for composability - * - **Testable**: Mock console output for testing scenarios - * - **Service-based**: Integrated with Effect's dependency injection system - * - **Environment isolation**: Different console implementations per environment - * - **Rich API**: Support for all standard console methods (log, error, debug, etc.) - * - **Performance tracking**: Built-in timing and profiling capabilities - * - * ## Core Operations - * - * - **Basic logging**: `log`, `error`, `warn`, `info`, `debug` - * - **Assertions**: `assert` for conditional logging - * - **Grouping**: `group`, `groupCollapsed`, `groupEnd` for organized output - * - **Timing**: `time`, `timeEnd`, `timeLog` for performance measurement - * - **Data display**: `table`, `dir`, `dirxml` for structured data visualization - * - **Utilities**: `clear`, `count`, `countReset`, `trace` - * - * @example - * ```ts - * import { Console, Effect } from "effect" - * - * // Basic logging - * const program = Effect.gen(function*() { - * yield* Console.log("Hello, World!") - * yield* Console.error("Something went wrong") - * yield* Console.warn("This is a warning") - * yield* Console.info("Information message") - * }) - * ``` - * - * @example - * ```ts - * import { Console, Effect } from "effect" - * - * // Grouped logging with timing - * const debugProgram = Console.withGroup( - * Effect.gen(function*() { - * yield* Console.log("Step 1: Loading...") - * yield* Effect.sleep("100 millis") - * - * yield* Console.log("Step 2: Processing...") - * yield* Effect.sleep("200 millis") - * }), - * { label: "Processing Data" } - * ) - * ``` - * - * @example - * ```ts - * import { Console, Effect } from "effect" - * - * // Data visualization and debugging - * const dataProgram = Effect.gen(function*() { - * const users = [ - * { id: 1, name: "Alice", age: 30 }, - * { id: 2, name: "Bob", age: 25 } - * ] - * - * yield* Console.table(users) - * yield* Console.dir(users[0], { depth: 2 }) - * yield* Console.assert(users.length > 0, "Users array should not be empty") - * }) - * ``` - * * @since 2.0.0 */ export * as Console from "./Console.ts" /** - * This module provides a data structure called `Context` that can be used - * for dependency injection in effectful programs. It is essentially a table - * mapping `Service`s identifiers to their implementations, 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 a `Context`. - * * @since 4.0.0 */ export * as Context from "./Context.ts" @@ -757,76 +117,11 @@ export * as Context from "./Context.ts" export * as Cron from "./Cron.ts" /** - * Immutable data constructors with discriminated-union support. - * - * The `Data` module provides base classes and factory functions for creating - * immutable value types with a `_tag` field for discriminated unions. - * It is the recommended way to define domain models, error types, and - * lightweight ADTs in Effect applications. - * - * ## Mental model - * - * - **`Class`** — base class for plain immutable data. Extend it with a type - * parameter to declare the fields. Instances are `Pipeable`. - * - **`TaggedClass`** — like `Class` but automatically adds a `readonly _tag` - * string literal field. Useful for single-variant types or ad-hoc tagged - * values. - * - **`TaggedEnum`** (type) + **`taggedEnum`** (value) — define a multi-variant - * discriminated union from a simple record. `taggedEnum()` returns per-variant - * constructors plus `$is` / `$match` helpers. - * - **`Error`** — like `Class` but extends `Cause.YieldableError`, so instances - * can be yielded inside `Effect.gen` to fail the effect. - * - **`TaggedError`** — like `TaggedClass` but extends `Cause.YieldableError`. - * Works with `Effect.catchTag` for tag-based error recovery. - * - * ## Common tasks - * - * - Define a simple value class → {@link Class} - * - Define a value class with a `_tag` → {@link TaggedClass} - * - Define a discriminated union with constructors → {@link TaggedEnum} + {@link taggedEnum} - * - Define a yieldable error → {@link Error} - * - Define a yieldable tagged error → {@link TaggedError} - * - Type-guard a tagged value → `$is` from {@link taggedEnum} - * - Pattern-match on a tagged union → `$match` from {@link taggedEnum} - * - * ## Gotchas - * - * - Variant records passed to `TaggedEnum` must **not** contain a `_tag` key; - * the `_tag` is added automatically from the record key. - * - When a class has no fields, the constructor argument is optional (`void`). - * - `taggedEnum()` creates **plain objects**, not class instances. If you need - * class-based variants, use `TaggedClass` or `TaggedError` instead. - * - `TaggedEnum.WithGenerics` supports up to 4 generic type parameters. - * - * ## Quickstart - * - * **Example** (tagged union with pattern matching) - * - * ```ts - * import { Data } from "effect" - * - * type Shape = Data.TaggedEnum<{ - * Circle: { readonly radius: number } - * Rect: { readonly width: number; readonly height: number } - * }> - * const { Circle, Rect, $match } = Data.taggedEnum() - * - * const area = $match({ - * Circle: ({ radius }) => Math.PI * radius ** 2, - * Rect: ({ width, height }) => width * height - * }) - * - * console.log(area(Circle({ radius: 5 }))) - * // 78.53981633974483 - * console.log(area(Rect({ width: 3, height: 4 }))) - * // 12 - * ``` - * - * @see {@link Class} — plain immutable data class - * @see {@link TaggedEnum} — discriminated union type - * @see {@link taggedEnum} — discriminated union constructors - * @see {@link TaggedError} — yieldable tagged error class - * + * @since 4.0.0 + */ +export * as Crypto from "./Crypto.ts" + +/** * @since 2.0.0 */ export * as Data from "./Data.ts" @@ -837,71 +132,6 @@ export * as Data from "./Data.ts" export * as DateTime from "./DateTime.ts" /** - * This module provides utilities for working with `Deferred`, a powerful concurrency - * primitive that represents an asynchronous variable that can be set exactly once. - * Multiple fibers can await the same `Deferred` and will all be notified when it - * completes. - * - * A `Deferred` can be: - * - **Completed successfully** with a value of type `A` - * - **Failed** with an error of type `E` - * - **Interrupted** if the fiber setting it is interrupted - * - * Key characteristics: - * - **Single assignment**: Can only be completed once - * - **Multiple waiters**: Many fibers can await the same `Deferred` - * - **Fiber-safe**: Thread-safe operations across concurrent fibers - * - **Composable**: Works seamlessly with other Effect operations - * - * @example - * ```ts - * import { Deferred, Effect, Fiber } from "effect" - * - * // Basic usage: coordinate between fibers - * const program = Effect.gen(function*() { - * const deferred = yield* Deferred.make() - * - * // Fiber 1: waits for the value - * const waiter = yield* Effect.forkChild( - * Effect.gen(function*() { - * const value = yield* Deferred.await(deferred) - * console.log("Received:", value) - * return value - * }) - * ) - * - * // Fiber 2: sets the value after a delay - * const setter = yield* Effect.forkChild( - * Effect.gen(function*() { - * yield* Effect.sleep("1 second") - * yield* Deferred.succeed(deferred, "Hello from setter!") - * }) - * ) - * - * // Wait for both fibers - * yield* Fiber.join(waiter) - * yield* Fiber.join(setter) - * }) - * - * // Producer-consumer pattern - * const producerConsumer = Effect.gen(function*() { - * const buffer = yield* Deferred.make, never>() - * - * const producer = Effect.gen(function*() { - * const data = [1, 2, 3, 4, 5] - * yield* Deferred.succeed(buffer, data) - * }) - * - * const consumer = Effect.gen(function*() { - * const data = yield* Deferred.await(buffer) - * return data.reduce((sum, n) => sum + n, 0) - * }) - * - * const [, result] = yield* Effect.all([producer, consumer]) - * return result // 15 - * }) - * ``` - * * @since 2.0.0 */ export * as Deferred from "./Deferred.ts" @@ -912,90 +142,11 @@ export * as Deferred from "./Deferred.ts" export * as Differ from "./Differ.ts" /** - * This module provides utilities for working with durations of time. A `Duration` - * is an immutable data type that represents a span of time with high precision, - * supporting operations from nanoseconds to weeks. - * - * Durations support: - * - **High precision**: Nanosecond-level accuracy using BigInt - * - **Multiple formats**: Numbers (millis), BigInt (nanos), tuples, strings - * - **Arithmetic operations**: Add, subtract, multiply, divide - * - **Comparisons**: Equal, less than, greater than - * - **Conversions**: Between different time units - * - **Human-readable formatting**: Pretty printing and parsing - * * @since 2.0.0 */ export * as Duration from "./Duration.ts" /** - * The `Effect` module is the core of the Effect library, providing a powerful and expressive - * way to model and compose asynchronous, concurrent, and effectful computations. - * - * An `Effect` represents a computation that: - * - May succeed with a value of type `A` - * - May fail with an error of type `E` - * - Requires a context/environment of type `R` - * - * Effects are lazy and immutable - they describe computations that can be executed later. - * This allows for powerful composition, error handling, resource management, and concurrency - * patterns. - * - * ## Key Features - * - * - **Type-safe error handling**: Errors are tracked in the type system - * - **Resource management**: Automatic cleanup with scoped resources - * - **Structured concurrency**: Safe parallel and concurrent execution - * - **Composable**: Effects can be combined using operators like `flatMap`, `map`, `zip` - * - **Testable**: Built-in support for testing with controlled environments - * - **Interruptible**: Effects can be safely interrupted and cancelled - * - * @example - * ```ts - * import { Console, Effect } from "effect" - * - * // Creating a simple effect - * const hello = Effect.succeed("Hello, World!") - * - * // Composing effects - * const program = Effect.gen(function*() { - * const message = yield* hello - * yield* Console.log(message) - * return message.length - * }) - * - * // Running the effect - * Effect.runPromise(program).then(console.log) // 13 - * ``` - * - * @example - * ```ts - * import { Data, Effect } from "effect" - * - * class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {} - * - * // Effect that may fail - * const divide = (a: number, b: number) => - * b === 0 - * ? Effect.fail(new DiscountRateError()) - * : Effect.succeed(a / b) - * - * // Error handling - * const program = Effect.gen(function*() { - * const result = yield* divide(10, 2) - * console.log("Result:", result) // Result: 5 - * return result - * }) - * - * // Handle errors - * const safeProgram = program.pipe( - * Effect.match({ - * onFailure: (error) => -1, - * onSuccess: (value) => value - * }) - * ) - * ``` - * * @since 2.0.0 */ export * as Effect from "./Effect.ts" @@ -1006,188 +157,21 @@ export * as Effect from "./Effect.ts" export * as Effectable from "./Effectable.ts" /** - * Encoding & decoding for Base64 (RFC4648), Base64Url, and Hex. - * * @since 4.0.0 */ export * as Encoding from "./Encoding.ts" /** - * Structural and custom equality for Effect values. - * - * The `Equal` module provides deep structural comparison for primitives, plain - * objects, arrays, Maps, Sets, Dates, and RegExps. Types that implement the - * {@link Equal} interface can supply their own comparison logic while staying - * compatible with the rest of the ecosystem (HashMap, HashSet, etc.). - * - * ## Mental model - * - * - **Structural equality** — two values are equal when their contents match, - * not when they share the same reference. - * - **Hash-first shortcut** — before comparing fields, the module checks - * {@link Hash.hash}. If the hashes differ the objects are unequal without - * further traversal. - * - **Equal interface** — any object that implements both {@link symbol} (the - * equality method) and `Hash.symbol` (the hash method) can define custom - * comparison logic. - * - **Caching** — comparison results for object pairs are cached in a WeakMap. - * This makes repeated checks fast but **requires immutability** after the - * first comparison. - * - **By-reference opt-out** — {@link byReference} and {@link byReferenceUnsafe} - * let you switch individual objects back to reference equality when you need - * mutable identity semantics. - * - * ## Common tasks - * - * - Compare two values → {@link equals} - * - Check if a value implements `Equal` → {@link isEqual} - * - Use `equals` where an `Equivalence` is expected → {@link asEquivalence} - * - Implement custom equality on a class → implement {@link Equal} (see - * example on the interface) - * - Opt an object out of structural equality → {@link byReference} / - * {@link byReferenceUnsafe} - * - * ## Gotchas - * - * - Objects **must be treated as immutable** after their first equality check. - * Results are cached; mutating an object afterwards yields stale results. - * - `NaN` is considered equal to `NaN` (unlike `===`). - * - Functions without an `Equal` implementation are compared by reference. - * - Map and Set comparisons are order-independent but O(n²) in size. - * - If only one of two objects implements `Equal`, they are never equal. - * - * ## Quickstart - * - * **Example** (basic structural comparison) - * - * ```ts - * import { Equal } from "effect" - * - * // Primitives - * console.log(Equal.equals(1, 1)) // true - * console.log(Equal.equals("a", "b")) // false - * - * // Objects and arrays - * console.log(Equal.equals({ x: 1 }, { x: 1 })) // true - * console.log(Equal.equals([1, 2], [1, 2])) // true - * - * // Curried form - * const is42 = Equal.equals(42) - * console.log(is42(42)) // true - * console.log(is42(0)) // false - * ``` - * - * @see {@link equals} — the main comparison function - * @see {@link Equal} — the interface for custom equality - * @see {@link Hash} — the companion hashing module - * * @since 2.0.0 */ export * as Equal from "./Equal.ts" /** - * Utilities for defining equivalence relations - binary relations that determine when two values - * should be considered equivalent. Equivalence relations are used for comparing, deduplicating, - * and organizing data in collections and data structures. - * - * ## Mental model - * - * - **Equivalence relation**: A function `(a: A, b: A) => boolean` that returns `true` when values are equivalent - * - **Reflexive property**: Every value is equivalent to itself (`eq(a, a) === true`) - * - **Symmetric property**: If `a` is equivalent to `b`, then `b` is equivalent to `a` (`eq(a, b) === eq(b, a)`) - * - **Transitive property**: If `a` is equivalent to `b` and `b` is equivalent to `c`, then `a` is equivalent to `c` - * - **Reference equality optimization**: {@link make} checks `===` first for performance before calling the custom function - * - **Composition**: Equivalences can be combined using {@link combine} and {@link combineAll} to create more complex relations - * - * ## Common tasks - * - * - Creating custom equivalences → {@link make} - * - Using strict equality (`===`) → {@link strictEqual} - * - Combining multiple equivalences (AND logic) → {@link combine}, {@link combineAll} - * - Transforming input before comparison → {@link mapInput} - * - Creating equivalences for structured types → {@link Struct}, {@link Tuple}, {@link Array_}, {@link Record} - * - * ## Gotchas - * - * - `strictEqual` uses `===`, so `NaN !== NaN` and objects are compared by reference, not structure - * - `make` optimizes with a reference equality check, so identical references return `true` without calling the function - * - `combineAll` with an empty collection returns an equivalence that always returns `true` - * - `Tuple` and `Array` require matching lengths; different lengths are never equivalent - * - * ## Quickstart - * - * **Example** (Case-insensitive string equivalence) - * - * ```ts - * import { Array, Equivalence } from "effect" - * - * const caseInsensitive = Equivalence.make((a, b) => - * a.toLowerCase() === b.toLowerCase() - * ) - * - * const strings = ["Hello", "world", "HELLO", "World"] - * const deduplicated = Array.dedupeWith(strings, caseInsensitive) - * console.log(deduplicated) // ["Hello", "world"] - * ``` - * - * ## See also - * - * - {@link Equal} - For structural equality (can convert to Equivalence) - * - {@link Array_.dedupeWith} - Remove duplicates using an equivalence - * - {@link Chunk} - Collections that use equivalences for operations - * * @since 2.0.0 */ export * as Equivalence from "./Equivalence.ts" /** - * Pluggable error reporting for Effect programs. - * - * Reporting is triggered by `Effect.withErrorReporting`, - * `ErrorReporter.report`, or built-in reporting boundaries in the HTTP and - * RPC server modules. - * - * Each reporter receives a structured callback with the failing `Cause`, a - * pretty-printed `Error`, severity, and any extra attributes attached to the - * original error — making it straightforward to forward failures to Sentry, - * Datadog, or a custom logging backend. - * - * Use the annotation symbols (`ignore`, `severity`, `attributes`) on your - * error classes to control reporting behavior per-error. - * - * @example - * ```ts - * import { Data, Effect, ErrorReporter } from "effect" - * - * // A reporter that logs to the console - * const consoleReporter = ErrorReporter.make(({ error, severity }) => { - * console.error(`[${severity}]`, error.message) - * }) - * - * // An error that should be ignored by reporters - * class NotFoundError extends Data.TaggedError("NotFoundError")<{}> { - * readonly [ErrorReporter.ignore] = true - * } - * - * // An error with custom severity and attributes - * class RateLimitError extends Data.TaggedError("RateLimitError")<{ - * readonly retryAfter: number - * }> { - * readonly [ErrorReporter.severity] = "Warn" as const - * readonly [ErrorReporter.attributes] = { - * retryAfter: this.retryAfter - * } - * } - * - * // Opt in to error reporting with Effect.withErrorReporting - * const program = Effect.gen(function*() { - * return yield* new RateLimitError({ retryAfter: 60 }) - * }).pipe( - * Effect.withErrorReporting, - * Effect.provide(ErrorReporter.layer([consoleReporter])) - * ) - * ``` - * * @since 4.0.0 */ export * as ErrorReporter from "./ErrorReporter.ts" @@ -1198,137 +182,11 @@ export * as ErrorReporter from "./ErrorReporter.ts" export * as ExecutionPlan from "./ExecutionPlan.ts" /** - * Represents the outcome of an Effect computation as a plain, synchronously - * inspectable value. - * - * ## Mental model - * - * - `Exit` is a union of two cases: `Success` and `Failure` - * - A `Success` wraps a value of type `A` - * - A `Failure` wraps a `Cause`, which may contain typed errors, defects, or interruptions - * - `Exit` is also an `Effect`, so you can yield it directly inside `Effect.gen` - * - Constructors mirror the failure modes: {@link fail} for typed errors, {@link die} for defects, {@link interrupt} for fiber interruptions - * - Use `Exit` when you need to inspect an Effect result without running further effects - * - * ## Common tasks - * - * - Create a success: {@link succeed} - * - Create a typed failure: {@link fail} - * - Create a failure from a Cause: {@link failCause} - * - Create a defect: {@link die} - * - Create an interruption: {@link interrupt} - * - Check the outcome: {@link isSuccess}, {@link isFailure}, {@link match} - * - Extract values optionally: {@link getSuccess}, {@link getCause}, {@link findErrorOption} - * - Transform the result: {@link map}, {@link mapError}, {@link mapBoth} - * - Combine multiple exits: {@link asVoidAll} - * - Inspect failure categories: {@link hasFails}, {@link hasDies}, {@link hasInterrupts} - * - * ## Gotchas - * - * - A `Failure` wraps a `Cause`, not a bare `E`. Use Cause utilities to drill into it. - * - {@link mapError} and {@link mapBoth} only transform typed errors (Fail reasons in the Cause). If the Cause contains only defects or interruptions, the original failure passes through unchanged. - * - Filter-based APIs ({@link filterSuccess}, {@link filterValue}, etc.) return `Filter.fail` markers for pipeline composition. They are not `Option` values or Effect failures. - * - {@link findError} and {@link findDefect} return only the first matching reason from the Cause. - * - * ## Quickstart - * - * **Example** (Creating and inspecting exits) - * - * ```ts - * import { Exit } from "effect" - * - * const success = Exit.succeed(42) - * const failure = Exit.fail("not found") - * - * const message = Exit.match(success, { - * onSuccess: (value) => `Got: ${value}`, - * onFailure: () => "Failed" - * }) - * console.log(message) // "Got: 42" - * ``` - * - * ## See also - * - * - {@link Exit} the core union type - * - {@link succeed} and {@link fail} the most common constructors - * - {@link match} for pattern matching on an Exit - * * @since 2.0.0 */ export * as Exit from "./Exit.ts" /** - * This module provides utilities for working with `Fiber`, the fundamental unit of - * concurrency in Effect. Fibers are lightweight, user-space threads that allow - * multiple Effects to run concurrently with structured concurrency guarantees. - * - * Key characteristics of Fibers: - * - **Lightweight**: Much lighter than OS threads, you can create millions - * - **Structured concurrency**: Parent fibers manage child fiber lifecycles - * - **Cancellation safety**: Proper resource cleanup when interrupted - * - **Cooperative**: Fibers yield control at effect boundaries - * - **Traceable**: Each fiber has an ID for debugging and monitoring - * - * Common patterns: - * - **Fork and join**: Start concurrent work and wait for results - * - **Race conditions**: Run multiple effects, take the first to complete - * - **Supervision**: Monitor and restart failed fibers - * - **Resource management**: Ensure proper cleanup on interruption - * - * @example - * ```ts - * import { Console, Effect, Fiber } from "effect" - * - * // Basic fiber operations - * const basicExample = Effect.gen(function*() { - * // Fork an effect to run concurrently - * const fiber = yield* Effect.forkChild( - * Effect.gen(function*() { - * yield* Effect.sleep("2 seconds") - * yield* Console.log("Background task completed") - * return "background result" - * }) - * ) - * - * // Do other work while the fiber runs - * yield* Console.log("Doing other work...") - * yield* Effect.sleep("1 second") - * - * // Wait for the fiber to complete - * const result = yield* Fiber.join(fiber) - * yield* Console.log(`Fiber result: ${result}`) - * }) - * - * // Joining multiple fibers - * const joinExample = Effect.gen(function*() { - * const task1 = Effect.delay(Effect.succeed("task1"), "1 second") - * const task2 = Effect.delay(Effect.succeed("task2"), "2 seconds") - * - * // Start both effects as fibers - * const fiber1 = yield* Effect.forkChild(task1) - * const fiber2 = yield* Effect.forkChild(task2) - * - * // Wait for both to complete - * const result1 = yield* Fiber.join(fiber1) - * const result2 = yield* Fiber.join(fiber2) - * return [result1, result2] // ["task1", "task2"] - * }) - * - * // Parallel execution with structured concurrency - * const parallelExample = Effect.gen(function*() { - * const tasks = [1, 2, 3, 4, 5].map((n) => - * Effect.gen(function*() { - * yield* Effect.sleep(`${n * 100} millis`) - * return n * n - * }) - * ) - * - * // Run all tasks in parallel, wait for all to complete - * const results = yield* Effect.all(tasks, { concurrency: "unbounded" }) - * return results // [1, 4, 9, 16, 25] - * }) - * ``` - * * @since 2.0.0 */ export * as Fiber from "./Fiber.ts" @@ -1349,40 +207,6 @@ export * as FiberMap from "./FiberMap.ts" export * as FiberSet from "./FiberSet.ts" /** - * This module provides a comprehensive file system abstraction that supports both synchronous - * and asynchronous file operations through Effect. It includes utilities for file I/O, directory - * management, permissions, timestamps, and file watching with proper error handling. - * - * The `FileSystem` interface provides a cross-platform abstraction over file system operations, - * allowing you to work with files and directories in a functional, composable way. All operations - * return `Effect` values that can be composed, transformed, and executed safely. - * - * @example - * ```ts - * import { Console, Effect, FileSystem } from "effect" - * - * const program = Effect.gen(function*() { - * const fs = yield* FileSystem.FileSystem - * - * // Create a directory - * yield* fs.makeDirectory("./temp", { recursive: true }) - * - * // Write a file - * yield* fs.writeFileString("./temp/hello.txt", "Hello, World!") - * - * // Read the file back - * const content = yield* fs.readFileString("./temp/hello.txt") - * yield* Console.log("File content:", content) - * - * // Get file information - * const stats = yield* fs.stat("./temp/hello.txt") - * yield* Console.log("File size:", stats.size) - * - * // Clean up - * yield* fs.remove("./temp", { recursive: true }) - * }) - * ``` - * * @since 4.0.0 */ export * as FileSystem from "./FileSystem.ts" @@ -1393,57 +217,6 @@ export * as FileSystem from "./FileSystem.ts" export * as Filter from "./Filter.ts" /** - * Utilities for converting arbitrary JavaScript values into human-readable - * strings, with support for circular references, redaction, and common JS - * types that `JSON.stringify` handles poorly. - * - * Mental model: - * - A `Formatter` is a callable `(value: Value) => Format`. - * - {@link format} is the general-purpose pretty-printer: it handles - * primitives, arrays, objects, `BigInt`, `Symbol`, `Date`, `RegExp`, - * `Set`, `Map`, class instances, and circular references. - * - {@link formatJson} is a safe `JSON.stringify` wrapper that silently - * drops circular references and applies redaction. - * - Both functions accept a `space` option for indentation control. - * - * Common tasks: - * - Pretty-print any value for debugging / logging -> {@link format} - * - Serialize to JSON safely (no circular throws) -> {@link formatJson} - * - Format a single object property key -> {@link formatPropertyKey} - * - Format a property path like `["a"]["b"]` -> {@link formatPath} - * - Format a `Date` to ISO string safely -> {@link formatDate} - * - * Gotchas: - * - {@link format} output is **not** valid JSON; use {@link formatJson} when - * you need parseable JSON. - * - {@link format} calls `toString()` on objects by default; pass - * `ignoreToString: true` to disable. - * - {@link formatJson} silently omits circular references (the key is - * dropped from the output). - * - Values implementing the `Redactable` protocol are automatically - * redacted by both {@link format} and {@link formatJson}. - * - * **Example** (Pretty-print a value) - * - * ```ts - * import { Formatter } from "effect" - * - * const obj = { name: "Alice", scores: [100, 97] } - * console.log(Formatter.format(obj)) - * // {"name":"Alice","scores":[100,97]} - * - * console.log(Formatter.format(obj, { space: 2 })) - * // { - * // "name": "Alice", - * // "scores": [ - * // 100, - * // 97 - * // ] - * // } - * ``` - * - * See also: {@link Formatter}, {@link format}, {@link formatJson} - * * @since 4.0.0 */ export * as Formatter from "./Formatter.ts" @@ -1459,12 +232,6 @@ export * as Function from "./Function.ts" export * as Graph from "./Graph.ts" /** - * This module provides utilities for hashing values in TypeScript. - * - * Hashing is the process of converting data into a fixed-size numeric value, - * typically used for data structures like hash tables, equality comparisons, - * and efficient data storage. - * * @since 2.0.0 */ export * as Hash from "./Hash.ts" @@ -1485,338 +252,41 @@ export * as HashRing from "./HashRing.ts" export * as HashSet from "./HashSet.ts" /** - * This module provides utilities for Higher-Kinded Types (HKT) in TypeScript. - * - * Higher-Kinded Types are types that take other types as parameters, similar to how - * functions take values as parameters. They enable generic programming over type - * constructors, allowing you to write code that works with any container type - * (like Array, Option, Effect, etc.) in a uniform way. - * - * The HKT system in Effect uses TypeLambdas to encode type-level functions that - * can represent complex type relationships with multiple type parameters, including - * contravariant, covariant, and invariant positions. - * - * @example - * ```ts - * import type { HKT } from "effect" - * - * // Define a TypeLambda for Array - * interface ArrayTypeLambda extends HKT.TypeLambda { - * readonly type: Array - * } - * - * // Use Kind to get the concrete type - * type MyArray = HKT.Kind - * // MyArray is Array - * - * // Define a TypeClass that works with any HKT - * interface Functor extends HKT.TypeClass { - * map( - * fa: HKT.Kind, - * f: (a: A) => B - * ): HKT.Kind - * } - * ``` - * * @since 2.0.0 */ export * as HKT from "./HKT.ts" /** - * This module provides utilities for making values inspectable and debuggable in TypeScript. - * - * The Inspectable interface provides a standard way to implement custom string representations - * for objects, making them easier to debug and inspect. It includes support for JSON - * serialization, Node.js inspection, and safe circular reference handling. - * - * The module also includes redaction capabilities for sensitive data, allowing objects - * to provide different representations based on the current execution context. - * - * @example - * ```ts - * import { Inspectable } from "effect" - * import { format } from "effect/Formatter" - * - * class User extends Inspectable.Class { - * constructor( - * public readonly name: string, - * public readonly email: string - * ) { - * super() - * } - * - * toJSON() { - * return { - * _tag: "User", - * name: this.name, - * email: this.email - * } - * } - * } - * - * const user = new User("Alice", "alice@example.com") - * console.log(user.toString()) // Pretty printed JSON - * console.log(format(user)) // Same as toString() - * ``` - * * @since 2.0.0 */ export * as Inspectable from "./Inspectable.ts" /** - * This module provides utility functions for working with Iterables in TypeScript. - * - * Iterables are objects that implement the iterator protocol, allowing them to be - * consumed with `for...of` loops, spread syntax, and other iteration constructs. - * This module provides a comprehensive set of functions for creating, transforming, - * and working with iterables in a functional programming style. - * - * Unlike arrays, iterables can be lazy and potentially infinite, making them suitable - * for stream processing and memory-efficient data manipulation. All functions in this - * module preserve the lazy nature of iterables where possible. - * - * @example - * ```ts - * import { Iterable, Option } from "effect" - * - * // Create iterables - * const numbers = Iterable.range(1, 5) - * const doubled = Iterable.map(numbers, (x) => x * 2) - * const filtered = Iterable.filter(doubled, (x) => x > 5) - * - * console.log(Array.from(filtered)) // [6, 8, 10] - * - * // Infinite iterables - * const fibonacci = Iterable.unfold([0, 1], ([a, b]) => Option.some([a, [b, a + b]])) - * const first10 = Iterable.take(fibonacci, 10) - * console.log(Array.from(first10)) // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] - * ``` - * * @since 2.0.0 */ export * as Iterable from "./Iterable.ts" /** - * JSON Patch operations for transforming JSON documents. - * - * This module implements a subset of RFC 6902, providing operations that can be applied deterministically without additional context. It supports computing structural diffs between JSON values and applying patches to transform documents. - * - * ## Mental model - * - * - **JSON Patch**: An ordered sequence of operations that transform a document from one state to another - * - **JSON Pointer**: Path syntax for targeting specific locations in a JSON document (e.g., `/users/0/name`) - * - **Operations**: Three types - `add` (insert value), `remove` (delete value), `replace` (update value) - * - **Immutable transformations**: All operations return new values; inputs are never mutated - * - **Sequential application**: Operations are applied in order, with later operations observing changes from earlier ones - * - **Structural diff**: The `get` function computes differences by comparing structure, not content semantics - * - * ## Common tasks - * - * - Computing diffs between JSON values → {@link get} - * - Applying patches to transform documents → {@link apply} - * - Creating patches manually → {@link JsonPatchOperation} - * - Storing and validating patch documents → {@link JsonPatch} - * - * ## Gotchas - * - * - Array removals are emitted from highest index to lowest to avoid index shifting during application - * - Root operations use an empty string path `""` to target the entire document - * - Array append operations use `-` as the last token in the path (e.g., `/items/-`) - * - Generated patches are deterministic but not guaranteed to be minimal - * - Empty patches return the original document reference (no allocation) - * - Invalid paths or operations throw errors rather than returning a result type - * - * ## Quickstart - * - * **Example** (Computing and applying a patch) - * - * ```ts - * import * as JsonPatch from "effect/JsonPatch" - * - * const oldValue = { name: "Alice", age: 30 } - * const newValue = { name: "Alice", age: 31, city: "NYC" } - * - * const patch = JsonPatch.get(oldValue, newValue) - * // [{ op: "replace", path: "/age", value: 31 }, { op: "add", path: "/city", value: "NYC" }] - * - * const result = JsonPatch.apply(patch, oldValue) - * // { name: "Alice", age: 31, city: "NYC" } - * ``` - * - * ## See also - * - * - {@link JsonPointer} - Utilities for working with JSON Pointer paths - * - {@link Schema.Json} - The JSON value type used by this module - * * @since 4.0.0 */ export * as JsonPatch from "./JsonPatch.ts" /** - * Utilities for escaping and unescaping JSON Pointer reference tokens according to RFC 6901. - * - * JSON Pointer (RFC 6901) defines a string syntax for identifying a specific value within a JSON document. - * A JSON Pointer is a sequence of reference tokens separated by forward slashes (`/`). Each reference token - * must be escaped when it contains special characters (`~` or `/`). - * - * ## Mental model - * - * - **Reference token**: A single segment of a JSON Pointer path (e.g., `"foo"`, `"bar/baz"`, `"key~with~tilde"`) - * - **Escaping**: Encoding special characters in a token so it can be safely used in a JSON Pointer (`~` → `~0`, `/` → `~1`) - * - **Unescaping**: Decoding escaped characters back to their original form (`~0` → `~`, `~1` → `/`) - * - **RFC 6901 compliance**: These functions implement the standard escaping rules for JSON Pointer reference tokens - * - **Pure functions**: Both operations are pure, immutable, and have no side effects - * - * ## Common tasks - * - * - Building JSON Pointers from path segments → {@link escapeToken} - * - Parsing JSON Pointers to extract original token values → {@link unescapeToken} - * - Escaping object keys or path segments before constructing JSON Pointers → {@link escapeToken} - * - Extracting unescaped identifiers from JSON Pointer strings → {@link unescapeToken} - * - * ## Gotchas - * - * - These functions operate on **reference tokens**, not full JSON Pointers. A full JSON Pointer like `/foo/bar` must be split into tokens (`["foo", "bar"]`) before escaping/unescaping - * - The order of replacement operations matters: `escapeToken` replaces `~` before `/` to avoid double-escaping - * - Empty strings are valid tokens and are returned unchanged - * - These functions do not validate JSON Pointer syntax; they only handle token-level escaping - * - * ## Quickstart - * - * **Example** (Building and parsing a JSON Pointer) - * - * ```ts - * import { escapeToken, unescapeToken } from "effect/JsonPointer" - * - * // Build a JSON Pointer from path segments - * const segments = ["users", "name/alias", "value"] - * const pointer = "/" + segments.map(escapeToken).join("/") - * // "/users/name~1alias/value" - * - * // Parse a JSON Pointer back to segments - * const tokens = pointer.split("/").slice(1).map(unescapeToken) - * // ["users", "name/alias", "value"] - * ``` - * - * ## See also - * - * - {@link JsonPatch} - Uses these utilities for JSON Patch operations - * - {@link JsonSchema} - Uses these utilities for schema reference resolution - * * @since 4.0.0 */ export * as JsonPointer from "./JsonPointer.ts" /** - * Convert JSON Schema documents between dialects (Draft-07, Draft-2020-12, - * OpenAPI 3.0, OpenAPI 3.1). All dialects are normalized to an internal - * `Document<"draft-2020-12">` representation before optional conversion to - * an output dialect. - * - * ## Mental model - * - * - **JsonSchema** — a plain object with string keys; represents any single - * JSON Schema node. - * - **Dialect** — one of `"draft-07"`, `"draft-2020-12"`, `"openapi-3.1"`, - * or `"openapi-3.0"`. - * - **Document** — a structured container holding a root `schema`, its - * companion `definitions`, and the target `dialect`. Definitions are - * stored separately from the root schema so they can be relocated when - * converting between dialects. - * - **MultiDocument** — same as `Document` but carries multiple root - * schemas (at least one). Useful when generating several schemas that - * share a single definitions pool. - * - **Definitions** — a `Record` keyed by definition - * name. The ref pointer prefix depends on the dialect. - * - **`from*` functions** — parse a raw JSON Schema object into the - * canonical `Document<"draft-2020-12">`. - * - **`to*` functions** — convert from the canonical representation to a - * specific output dialect. - * - * ## Common tasks - * - * - Parse a Draft-07 schema → {@link fromSchemaDraft07} - * - Parse a Draft-2020-12 schema → {@link fromSchemaDraft2020_12} - * - Parse an OpenAPI 3.1 schema → {@link fromSchemaOpenApi3_1} - * - Parse an OpenAPI 3.0 schema → {@link fromSchemaOpenApi3_0} - * - Convert to Draft-07 output → {@link toDocumentDraft07} - * - Convert to OpenAPI 3.1 output → {@link toMultiDocumentOpenApi3_1} - * - Resolve a `$ref` against definitions → {@link resolve$ref} - * - Inline the root `$ref` of a document → {@link resolveTopLevel$ref} - * - * ## Gotchas - * - * - All `from*` functions normalize to `Document<"draft-2020-12">` - * regardless of the input dialect. - * - Unsupported or unrecognized JSON Schema keywords are silently dropped - * during conversion. - * - Draft-07 tuple syntax (`items` as array + `additionalItems`) is - * converted to 2020-12 form (`prefixItems` + `items`), and vice-versa. - * - OpenAPI 3.0 `nullable: true` is expanded into `type` arrays or - * `anyOf` unions. The `nullable` keyword is removed. - * - OpenAPI 3.0 singular `example` is converted to `examples` (array). - * - {@link resolve$ref} only looks up the last segment of the ref path in - * the definitions map; it does not follow arbitrary JSON Pointer paths. - * - * ## Quickstart - * - * **Example** (Parse a Draft-07 schema and convert to Draft-07 output) - * - * ```ts - * import { JsonSchema } from "effect" - * - * const raw: JsonSchema.JsonSchema = { - * type: "object", - * properties: { - * name: { type: "string" } - * }, - * required: ["name"] - * } - * - * // Parse into canonical form - * const doc = JsonSchema.fromSchemaDraft07(raw) - * - * // Convert back to Draft-07 - * const draft07 = JsonSchema.toDocumentDraft07(doc) - * - * console.log(draft07.dialect) // "draft-07" - * console.log(draft07.schema) // { type: "object", properties: { name: { type: "string" } }, required: ["name"] } - * ``` - * - * ## See also - * - * - {@link Document} - * - {@link MultiDocument} - * - {@link fromSchemaDraft07} - * - {@link toDocumentDraft07} - * - {@link resolve$ref} - * * @since 4.0.0 */ export * as JsonSchema from "./JsonSchema.ts" /** - * @since 3.8.0 + * @since 4.0.0 */ export * as Latch from "./Latch.ts" /** - * A `Layer` 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 */ export * as Layer from "./Layer.ts" @@ -1828,205 +298,11 @@ export * as LayerMap from "./LayerMap.ts" /** * @since 2.0.0 - * - * The `Logger` module provides a robust and flexible logging system for Effect applications. - * It offers structured logging, multiple output formats, and seamless integration with the - * Effect runtime's tracing and context management. - * - * ## Key Features - * - * - **Structured Logging**: Built-in support for structured log messages with metadata - * - **Multiple Formats**: JSON, LogFmt, Pretty, and custom formatting options - * - **Context Integration**: Automatic capture of fiber context, spans, and annotations - * - **Batching**: Efficient log aggregation and batch processing - * - **File Output**: Direct file writing with configurable batch windows - * - **Composable**: Transform and compose loggers using functional patterns - * - * ## Basic Usage - * - * ```ts - * import { Effect } from "effect" - * - * // Basic logging - * const program = Effect.gen(function*() { - * yield* Effect.log("Application started") - * yield* Effect.logInfo("Processing user request") - * yield* Effect.logWarning("Resource limit approaching") - * yield* Effect.logError("Database connection failed") - * }) - * - * // With structured data - * const structuredLog = Effect.gen(function*() { - * yield* Effect.log("User action", { userId: 123, action: "login" }) - * yield* Effect.logInfo("Request processed", { duration: 150, statusCode: 200 }) - * }) - * ``` - * - * ## Custom Loggers - * - * ```ts - * import { Effect, Logger } from "effect" - * - * // Create a custom logger - * const customLogger = Logger.make((options) => { - * console.log(`[${options.logLevel}] ${options.message}`) - * }) - * - * // Use JSON format for production - * const jsonLogger = Logger.consoleJson - * - * // Pretty format for development - * const prettyLogger = Logger.consolePretty() - * - * const program = Effect.log("Hello World").pipe( - * Effect.provide(Logger.layer([jsonLogger])) - * ) - * ``` - * - * ## Multiple Loggers - * - * ```ts - * import { Effect, Logger } from "effect" - * - * // Combine multiple loggers - * const CombinedLoggerLive = Logger.layer([ - * Logger.consoleJson, - * Logger.consolePretty() - * ]) - * - * const program = Effect.log("Application event").pipe( - * Effect.provide(CombinedLoggerLive) - * ) - * ``` - * - * ## Batched Logging - * - * ```ts - * import { Duration, Effect, Logger } from "effect" - * - * const batchedLogger = Logger.batched(Logger.formatJson, { - * window: Duration.seconds(5), - * flush: (messages) => - * Effect.sync(() => { - * // Process batch of log messages - * console.log("Flushing", messages.length, "log entries") - * }) - * }) - * - * const program = Effect.gen(function*() { - * const logger = yield* batchedLogger - * yield* Effect.provide( - * Effect.all([ - * Effect.log("Event 1"), - * Effect.log("Event 2"), - * Effect.log("Event 3") - * ]), - * Logger.layer([logger]) - * ) - * }) - * ``` */ export * as Logger from "./Logger.ts" /** * @since 2.0.0 - * - * The `LogLevel` module provides utilities for managing log levels in Effect applications. - * It defines a hierarchy of log levels and provides functions for comparing and filtering logs - * based on their severity. - * - * ## Log Level Hierarchy - * - * The log levels are ordered from most severe to least severe: - * - * 1. **All** - Special level that allows all messages - * 2. **Fatal** - System is unusable, immediate attention required - * 3. **Error** - Error conditions that should be investigated - * 4. **Warn** - Warning conditions that may indicate problems - * 5. **Info** - Informational messages about normal operation - * 6. **Debug** - Debug information useful during development - * 7. **Trace** - Very detailed trace information - * 8. **None** - Special level that suppresses all messages - * - * ## Basic Usage - * - * ```ts - * import { Effect } from "effect" - * - * // Basic log level usage - * const program = Effect.gen(function*() { - * yield* Effect.logFatal("System is shutting down") - * yield* Effect.logError("Database connection failed") - * yield* Effect.logWarning("Memory usage is high") - * yield* Effect.logInfo("User logged in") - * yield* Effect.logDebug("Processing request") - * yield* Effect.logTrace("Variable value: xyz") - * }) - * ``` - * - * ## Level Comparison - * - * ```ts - * import { LogLevel } from "effect" - * - * // Check if one level is more severe than another - * console.log(LogLevel.isGreaterThan("Error", "Info")) // true - * console.log(LogLevel.isGreaterThan("Debug", "Error")) // false - * - * // Check if level meets minimum threshold - * console.log(LogLevel.isGreaterThanOrEqualTo("Info", "Debug")) // true - * console.log(LogLevel.isLessThan("Trace", "Info")) // true - * ``` - * - * ## Filtering by Level - * - * ```ts - * import { Logger, LogLevel } from "effect" - * - * // Create a logger that only logs Error and above - * const errorLogger = Logger.make((options) => { - * if (LogLevel.isGreaterThanOrEqualTo(options.logLevel, "Error")) { - * console.log(`[${options.logLevel}] ${options.message}`) - * } - * }) - * - * // Production logger - Info and above - * const productionLogger = Logger.make((options) => { - * if (LogLevel.isGreaterThanOrEqualTo(options.logLevel, "Info")) { - * console.log( - * `${options.date.toISOString()} [${options.logLevel}] ${options.message}` - * ) - * } - * }) - * - * // Development logger - Debug and above - * const devLogger = Logger.make((options) => { - * if (LogLevel.isGreaterThanOrEqualTo(options.logLevel, "Debug")) { - * console.log(`[${options.logLevel}] ${options.message}`) - * } - * }) - * ``` - * - * ## Runtime Configuration - * - * ```ts - * import { Config, Effect, Logger, LogLevel } from "effect" - * - * // Configure log level from environment - * const logLevelConfig = Config.string("LOG_LEVEL").pipe( - * Config.withDefault("Info") - * ) - * - * const configurableLogger = Effect.gen(function*() { - * const minLevel = yield* logLevelConfig - * - * return Logger.make((options) => { - * if (LogLevel.isGreaterThanOrEqualTo(options.logLevel, minLevel)) { - * console.log(`[${options.logLevel}] ${options.message}`) - * } - * }) - * }) - * ``` */ export * as LogLevel from "./LogLevel.ts" @@ -2036,763 +312,67 @@ export * as LogLevel from "./LogLevel.ts" export * as ManagedRuntime from "./ManagedRuntime.ts" /** - * The `effect/match` module provides a type-safe pattern matching system for - * TypeScript. Inspired by functional programming, it simplifies conditional - * logic by replacing verbose if/else or switch statements with a structured and - * expressive API. - * - * This module supports matching against types, values, and discriminated unions - * while enforcing exhaustiveness checking to ensure all cases are handled. - * - * Although pattern matching is not yet a native JavaScript feature, - * `effect/match` offers a reliable implementation that is available today. - * - * **How Pattern Matching Works** - * - * Pattern matching follows a structured process: - * - * - **Creating a matcher**: Define a `Matcher` that operates on either a - * specific `Match.type` or `Match.value`. - * - * - **Defining patterns**: Use combinators such as `Match.when`, `Match.not`, - * and `Match.tag` to specify matching conditions. - * - * - **Completing the match**: Apply a finalizer such as `Match.exhaustive`, - * `Match.orElse`, or `Match.option` to determine how unmatched cases should - * be handled. - * * @since 4.0.0 */ export * as Match from "./Match.ts" /** * @since 2.0.0 - * - * The `Metric` module provides a comprehensive system for collecting, aggregating, and observing - * application metrics in Effect applications. It offers type-safe, concurrent metrics that can - * be used to monitor performance, track business metrics, and gain insights into application behavior. - * - * ## Key Features - * - * - **Five Metric Types**: Counters, Gauges, Frequencies, Histograms, and Summaries - * - **Type Safety**: Fully typed metrics with compile-time guarantees - * - **Concurrency Safe**: Thread-safe metrics that work with Effect's concurrency model - * - **Attributes**: Tag metrics with key-value attributes for filtering and grouping - * - **Snapshots**: Take point-in-time snapshots of all metrics for reporting - * - **Runtime Integration**: Automatic fiber runtime metrics collection - * - * ## Metric Types - * - * ### Counter - * Tracks cumulative values that only increase or can be reset to zero. - * Perfect for counting events, requests, errors, etc. - * - * ### Gauge - * Represents a single numerical value that can go up or down. - * Ideal for current resource usage, temperature, queue sizes, etc. - * - * ### Frequency - * Counts occurrences of discrete string values. - * Useful for tracking categorical data like HTTP status codes, user actions, etc. - * - * ### Histogram - * Records observations in configurable buckets to analyze distribution. - * Great for response times, request sizes, and other measured values. - * - * ### Summary - * Calculates quantiles over a sliding time window. - * Provides statistical insights into value distributions over time. - * - * ## Basic Usage - * - * ```ts - * import { Effect, Metric } from "effect" - * - * // Create metrics - * const requestCount = Metric.counter("http_requests_total", { - * description: "Total number of HTTP requests" - * }) - * - * const responseTime = Metric.histogram("http_response_time", { - * description: "HTTP response time in milliseconds", - * boundaries: Metric.linearBoundaries({ start: 0, width: 50, count: 20 }) - * }) - * - * // Use metrics in your application - * const handleRequest = Effect.gen(function*() { - * yield* Metric.update(requestCount, 1) - * - * const startTime = yield* Effect.clockWith((clock) => clock.currentTimeMillis) - * - * // Process request... - * yield* Effect.sleep("100 millis") - * - * const endTime = yield* Effect.clockWith((clock) => clock.currentTimeMillis) - * yield* Metric.update(responseTime, endTime - startTime) - * }) - * ``` - * - * ## Attributes and Tagging - * - * ```ts - * import { Effect, Metric } from "effect" - * - * const requestCount = Metric.counter("requests", { - * description: "Number of requests by endpoint and method" - * }) - * - * const program = Effect.gen(function*() { - * // Add attributes to metrics - * yield* Metric.update( - * Metric.withAttributes(requestCount, { - * endpoint: "/api/users", - * method: "GET" - * }), - * 1 - * ) - * - * // Or use withAttributes for compile-time attributes - * const taggedCounter = Metric.withAttributes(requestCount, { - * endpoint: "/api/posts", - * method: "POST" - * }) - * yield* Metric.update(taggedCounter, 1) - * }) - * ``` - * - * ## Advanced Examples - * - * ```ts - * import { Effect, Metric } from "effect" - * - * // Business metrics - * const userSignups = Metric.counter("user_signups_total") - * const activeUsers = Metric.gauge("active_users_current") - * const featureUsage = Metric.frequency("feature_usage") - * - * // Performance metrics - * const dbQueryTime = Metric.summary("db_query_duration", { - * maxAge: "5 minutes", - * maxSize: 1000, - * quantiles: [0.5, 0.9, 0.95, 0.99] - * }) - * - * const program = Effect.gen(function*() { - * // Track user signup - * yield* Metric.update(userSignups, 1) - * - * // Update active user count - * yield* Metric.update(activeUsers, 1250) - * - * // Record feature usage - * yield* Metric.update(featureUsage, "dashboard_view") - * - * // Measure database query time - * yield* Effect.timed(performDatabaseQuery).pipe( - * Effect.tap(([duration]) => Metric.update(dbQueryTime, duration)) - * ) - * }) - * - * // Get metric snapshots - * const getMetrics = Effect.gen(function*() { - * const snapshots = yield* Metric.snapshot - * - * for (const metric of snapshots) { - * console.log(`${metric.id}: ${JSON.stringify(metric.state)}`) - * } - * }) - * ``` */ export * as Metric from "./Metric.ts" /** - * MutableHashMap is a high-performance, mutable hash map implementation designed for efficient key-value storage - * with support for both structural and referential equality. It provides O(1) average-case performance for - * basic operations and integrates seamlessly with Effect's Equal and Hash interfaces. - * - * The implementation uses a hybrid approach: - * - Referential keys (without Equal implementation) are stored in a native Map - * - Structural keys (with Equal implementation) are stored in hash buckets with collision handling - * - * Key Features: - * - Mutable operations for performance-critical scenarios - * - Supports both structural and referential equality - * - Efficient collision handling through bucketing - * - Iterable interface for easy traversal - * - Memory-efficient storage with automatic bucket management - * - * Performance Characteristics: - * - Get/Set/Has: O(1) average, O(n) worst case (hash collisions) - * - Remove: O(1) average, O(n) worst case - * - Clear: O(1) - * - Size: O(1) - * - Iteration: O(n) - * * @since 2.0.0 - * @category data-structures */ export * as MutableHashMap from "./MutableHashMap.ts" /** - * @fileoverview - * MutableHashSet is a high-performance, mutable set implementation that provides efficient storage - * and retrieval of unique values. Built on top of MutableHashMap, it inherits the same performance - * characteristics and support for both structural and referential equality. - * - * The implementation uses a MutableHashMap internally where each value is stored as a key with a - * boolean flag, providing O(1) average-case performance for all operations. - * - * Key Features: - * - Mutable operations for performance-critical scenarios - * - Supports both structural and referential equality - * - Efficient duplicate detection and removal - * - Iterable interface for easy traversal - * - Memory-efficient storage with automatic deduplication - * - Seamless integration with Effect's Equal and Hash interfaces - * - * Performance Characteristics: - * - Add/Has/Remove: O(1) average, O(n) worst case (hash collisions) - * - Clear: O(1) - * - Size: O(1) - * - Iteration: O(n) - * * @since 2.0.0 - * @category data-structures */ export * as MutableHashSet from "./MutableHashSet.ts" /** - * @fileoverview - * MutableList is an efficient, mutable linked list implementation optimized for high-throughput - * scenarios like logging, queuing, and streaming. It uses a bucket-based architecture where - * elements are stored in arrays (buckets) linked together, providing optimal performance for - * both append and prepend operations. - * - * The implementation uses a sophisticated bucket system: - * - Each bucket contains an array of elements with an offset pointer - * - Buckets can be marked as mutable or immutable for optimization - * - Elements are taken from the head and added to the tail - * - Memory is efficiently managed through bucket reuse and cleanup - * - * Key Features: - * - Highly optimized for high-frequency append/prepend operations - * - Memory efficient with automatic cleanup of consumed elements - * - Support for bulk operations (appendAll, prependAll, takeN) - * - Filtering and removal operations - * - Zero-copy optimizations for certain scenarios - * - * Performance Characteristics: - * - Append/Prepend: O(1) amortized - * - Take/TakeN: O(1) per element taken - * - Length: O(1) - * - Clear: O(1) - * - Filter: O(n) - * - * Ideal Use Cases: - * - High-throughput logging systems - * - Producer-consumer queues - * - Streaming data buffers - * - Real-time data processing pipelines - * * @since 4.0.0 - * @category data-structures */ export * as MutableList from "./MutableList.ts" /** - * @fileoverview - * MutableRef provides a mutable reference container that allows safe mutation of values - * in functional programming contexts. It serves as a bridge between functional and imperative - * programming paradigms, offering atomic operations for state management. - * - * Unlike regular variables, MutableRef encapsulates mutable state and provides controlled - * access through a standardized API. It supports atomic compare-and-set operations for - * thread-safe updates and integrates seamlessly with Effect's ecosystem. - * - * Key Features: - * - Mutable reference semantics with functional API - * - Atomic compare-and-set operations for safe concurrent updates - * - Specialized operations for numeric and boolean values - * - Chainable operations that return the reference or the value - * - Integration with Effect's Equal interface for value comparison - * - * Common Use Cases: - * - State containers in functional applications - * - Counters and accumulators - * - Configuration that needs to be updated at runtime - * - Caching and memoization scenarios - * - Inter-module communication via shared references - * - * Performance Characteristics: - * - Get/Set: O(1) - * - Compare-and-set: O(1) - * - All operations: O(1) - * * @since 2.0.0 - * @category data-structures */ export * as MutableRef from "./MutableRef.ts" /** - * Lightweight wrapper types that prevent accidental mixing of structurally - * identical values (e.g. `UserId` vs `OrderId`, both `string` at runtime). - * - * **Mental model** - * - * - **Newtype** — a compile-time wrapper around a **carrier** type (the - * underlying primitive or object). At runtime the value is unchanged; the - * tag exists only in the type system. - * - **Key** — a unique string literal that distinguishes one newtype from - * another (e.g. `"Label"`, `"UserId"`). - * - **Carrier** — the underlying type the newtype wraps (e.g. `string`, - * `number`). - * - **Iso** — a lossless two-way conversion between a newtype and its carrier, - * created with {@link makeIso}. Use `iso.set(carrier)` to wrap and - * `iso.get(newtype)` to unwrap. - * - * **Common tasks** - * - * - Define a newtype → declare an `interface` extending - * `Newtype.Newtype` - * - Wrap / unwrap values → {@link makeIso} (returns an `Optic.Iso`) - * - Unwrap only → {@link value} - * - Lift an `Equivalence` → {@link makeEquivalence} - * - Lift an `Order` → {@link makeOrder} - * - Lift a `Combiner` → {@link makeCombiner} - * - Lift a `Reducer` → {@link makeReducer} - * - * **Gotchas** - * - * - Newtypes are **purely compile-time**. There is zero runtime overhead; - * `value` and `makeIso` use identity casts. - * - Two newtypes sharing the same key string will be assignable to each other. - * Choose unique key strings. - * - A newtype value is **not** assignable to its carrier type without - * explicitly unwrapping via {@link value} or an iso. - * - * **Quickstart** - * - * **Example** (defining and using a newtype) - * - * ```ts - * import { Newtype } from "effect" - * - * // 1. Define a newtype - * interface Label extends Newtype.Newtype<"Label", string> {} - * - * // 2. Create an iso for wrapping/unwrapping - * const labelIso = Newtype.makeIso(data: NonEmptyIterable.NonEmptyIterable): A { - * // Safe to get the first element - guaranteed to exist - * const [first] = NonEmptyIterable.unprepend(data) - * return first - * } - * - * // Using Array.make to create non-empty arrays - * const numbers = Array.make( - * 1, - * 2, - * 3, - * 4, - * 5 - * ) as unknown as NonEmptyIterable.NonEmptyIterable - * const firstNumber = processNonEmpty(numbers) // number - * - * // Regular arrays can be asserted as NonEmptyIterable when known to be non-empty - * const values = [1, 2, 3] as unknown as NonEmptyIterable.NonEmptyIterable - * const firstValue = processNonEmpty(values) // number - * - * // Custom iterables that are guaranteed non-empty - * function* generateNumbers(): NonEmptyIterable.NonEmptyIterable { - * yield 1 - * yield 2 - * yield 3 - * } - * - * const firstGenerated = processNonEmpty(generateNumbers()) // number - * ``` - * - * ## Working with Different Iterable Types - * - * ```ts - * import { Array } from "effect" - * - * // Creating non-empty arrays - * const nonEmptyArray = Array.make( - * 1, - * 2, - * 3 - * ) as unknown as NonEmptyIterable.NonEmptyIterable - * - * // Working with strings (assert as NonEmptyIterable when known to be non-empty) - * const nonEmptyString = "hello" as unknown as NonEmptyIterable.NonEmptyIterable< - * string - * > - * const [firstChar] = NonEmptyIterable.unprepend(nonEmptyString) - * console.log(firstChar) // "h" - * - * // Working with Maps (assert when known to be non-empty) - * const nonEmptyMap = new Map([ - * ["key1", "value1"], - * ["key2", "value2"] - * ]) as unknown as NonEmptyIterable.NonEmptyIterable<[string, string]> - * const [firstEntry] = NonEmptyIterable.unprepend(nonEmptyMap) - * console.log(firstEntry) // ["key1", "value1"] - * - * // Custom generator functions - * function* fibonacci(): NonEmptyIterable.NonEmptyIterable { - * let a = 1, b = 1 - * yield a - * while (true) { - * yield b - * const next = a + b - * a = b - * b = next - * } - * } - * - * const [firstFib, restFib] = NonEmptyIterable.unprepend( - * fibonacci() as unknown as NonEmptyIterable.NonEmptyIterable - * ) - * console.log(firstFib) // 1 - * ``` - * - * ## Integration with Effect Arrays - * - * ```ts - * import { Array, pipe } from "effect" - * import type * as NonEmptyIterable from "effect/NonEmptyIterable" - * import type * as NonEmptyIterable from "effect/NonEmptyIterable" - * - * // Many Array functions work with NonEmptyIterable - * declare const nonEmptyData: NonEmptyIterable.NonEmptyIterable - * - * const processData = pipe( - * nonEmptyData, - * Array.fromIterable, - * Array.map((x) => x * 2), - * Array.filter((x) => x > 5) - * // Result is a regular array since filtering might make it empty - * ) - * - * // Safe operations that preserve non-emptiness - * const doubledData = pipe( - * nonEmptyData, - * Array.fromIterable, - * Array.map((x) => x * 2) - * // This would still be non-empty if the source was non-empty - * ) - * ``` */ export * as NonEmptyIterable from "./NonEmptyIterable.ts" /** - * This module provides utility functions and type class instances for working with the `number` type in TypeScript. - * It includes functions for basic arithmetic operations. - * * @since 2.0.0 */ export * as Number from "./Number.ts" /** - * Composable, immutable accessors for reading and updating nested data - * structures without mutation. - * - * **Mental model** - * - * - **Optic** — a first-class reference to a piece inside a larger structure. - * Compose optics to reach deeply nested values. - * - **Iso** — lossless two-way conversion (`get`/`set`) between `S` and `A`. - * Extends both {@link Lens} and {@link Prism}. - * - **Lens** — focuses on exactly one part of `S`. `get` always succeeds; - * `replace` needs the original `S` to produce the updated whole. - * - **Prism** — focuses on a part that may not be present (e.g. a union - * variant). `getResult` can fail; `set` builds a new `S` from `A` alone. - * - **Optional** — the most general optic: both reading and writing can fail. - * - **Traversal** — focuses on zero or more elements of an array-like - * structure. Technically `Optional>`. - * - **Hierarchy** (strongest → weakest): - * `Iso > Lens | Prism > Optional`. Composing a weaker optic with any other - * produces the weaker kind. - * - * **Common tasks** - * - * - Start a chain → {@link id} (identity iso) - * - Drill into a struct key → `.key("name")` / `.optionalKey("name")` - * - Drill into a key that may not exist → `.at("name")` - * - Narrow a tagged union → `.tag("MyVariant")` - * - Narrow by type guard → `.refine(guard)` - * - Add validation → `.check(Schema.isGreaterThan(0))` - * - Filter out `undefined` → `.notUndefined()` - * - Pick/omit struct keys → `.pick(["a","b"])` / `.omit(["c"])` - * - Traverse array elements → `.forEach(el => el.key("field"))` - * - Build an iso → {@link makeIso} - * - Build a lens → {@link makeLens} - * - Build a prism → {@link makePrism}, {@link fromChecks} - * - Build an optional → {@link makeOptional} - * - Focus into `Option.Some` → {@link some} - * - Focus into `Result.Success`/`Failure` → {@link success}, {@link failure} - * - Convert record ↔ entries → {@link entries} - * - Extract all traversal elements → {@link getAll} - * - * **Gotchas** - * - * - Updates are structurally persistent: only nodes on the path are cloned. - * Unrelated branches keep referential identity. However, **no-op updates - * may still allocate** a new root — do not rely on reference identity to - * detect no-ops. - * - `replace` silently returns the original `S` when the optic cannot focus - * (e.g. wrong tag). Use `replaceResult` for explicit failure. - * - `modify` also returns the original `S` on focus failure — it never throws. - * - `.key()` and `.optionalKey()` do not work on union types (compile error). - * - Only plain objects (`Object.prototype` or `null` prototype) and arrays can - * be cloned. Class instances cause a runtime error on `replace`/`modify`. - * - * **Quickstart** - * - * **Example** (reading and updating nested state) - * - * ```ts - * import { Optic } from "effect" - * - * type State = { user: { name: string; age: number } } - * - * const _age = Optic.id().key("user").key("age") - * - * const s1: State = { user: { name: "Alice", age: 30 } } - * - * // Read - * console.log(_age.get(s1)) - * // Output: 30 - * - * // Update immutably - * const s2 = _age.replace(31, s1) - * console.log(s2) - * // Output: { user: { name: "Alice", age: 31 } } - * - * // Modify with a function - * const s3 = _age.modify((n) => n + 1)(s1) - * console.log(s3) - * // Output: { user: { name: "Alice", age: 31 } } - * - * // Referential identity is preserved for unrelated branches - * console.log(s2.user !== s1.user) - * // Output: true (on the path) - * ``` - * - * **See also** - * - * - {@link id} — entry point for optic chains - * - {@link Lens} / {@link Prism} / {@link Optional} — core optic types - * - {@link Traversal} / {@link getAll} — multi-focus optics - * - {@link some} / {@link success} / {@link failure} — built-in prisms - * * @since 4.0.0 - * @module */ export * as Optic from "./Optic.ts" /** - * The `Option` module provides a type-safe way to represent values that may or - * may not exist. An `Option` is either `Some` (containing a value) or - * `None` (representing absence). - * - * **Mental model** - * - * - `Option` is a discriminated union: `None | Some` - * - `None` represents the absence of a value (like `null`/`undefined`, but type-safe) - * - `Some` wraps a present value of type `A`, accessed via `.value` - * - `Option` is a monad: chain operations with {@link flatMap}, compose pipelines with `pipe` - * - All operations are pure and return new `Option` values; the input is never mutated - * - `Option` is yieldable in `Effect.gen`, producing the inner value or short-circuiting with `NoSuchElementError` - * - * **Common tasks** - * - * - Create from a value: {@link some}, {@link none} - * - Create from nullable: {@link fromNullishOr}, {@link fromNullOr}, {@link fromUndefinedOr} - * - Create from iterable: {@link fromIterable} - * - Create from Result: {@link getSuccess}, {@link getFailure} - * - Transform: {@link map}, {@link flatMap}, {@link andThen} - * - Unwrap: {@link getOrElse}, {@link getOrNull}, {@link getOrUndefined}, {@link getOrThrow} - * - Pattern match: {@link match} - * - Fallbacks: {@link orElse}, {@link orElseSome}, {@link firstSomeOf} - * - Filter: {@link filter}, {@link filterMap} - * - Combine multiple: {@link all}, {@link zipWith}, {@link product} - * - Generator syntax: {@link gen} - * - Do notation: {@link Do}, {@link bind}, {@link let_ let} - * - Check contents: {@link isSome}, {@link isNone}, {@link contains}, {@link exists} - * - * **Gotchas** - * - * - `Option.some(null)` is a valid `Some`; use {@link fromNullishOr} to treat `null`/`undefined` as `None` - * - {@link filterMap} uses a `Filter` callback that returns `Result` - * - {@link getOrThrow} throws a generic `Error`; prefer {@link getOrThrowWith} for custom errors - * - `None` is a singleton; compare with {@link isNone}, not `===` - * - When yielded in `Effect.gen`, a `None` becomes a `NoSuchElementError` defect - * - * **Quickstart** - * - * **Example** (Working with optional values) - * - * ```ts - * import { Option } from "effect" - * - * const name = Option.some("Alice") - * const age = Option.none() - * - * // Transform - * const upper = Option.map(name, (s) => s.toUpperCase()) - * - * // Unwrap with fallback - * console.log(Option.getOrElse(upper, () => "unknown")) - * // Output: "ALICE" - * - * console.log(Option.getOrElse(age, () => 0)) - * // Output: 0 - * - * // Combine multiple options - * const both = Option.all({ name, age }) - * console.log(Option.isNone(both)) - * // Output: true - * ``` - * - * **See also** - * - * - {@link some} / {@link none} for creating values - * - {@link map} / {@link flatMap} for transforming values - * - {@link match} for pattern matching - * - {@link gen} for generator-based syntax - * * @since 2.0.0 - * @module */ export * as Option from "./Option.ts" /** - * This module provides the `Order` type class for defining total orderings on types. - * An `Order` is a comparison function that returns `-1` (less than), `0` (equal), or `1` (greater than). - * - * Mental model: - * - An `Order` is a pure function `(a: A, b: A) => Ordering` that compares two values - * - The result `-1` means the first value is less than the second - * - The result `0` means the values are equal according to this ordering - * - The result `1` means the first value is greater than the second - * - Orders must satisfy total ordering laws: totality (either `x <= y` or `y <= x`), antisymmetry (if `x <= y` and `y <= x` then `x == y`), and transitivity (if `x <= y` and `y <= z` then `x <= z`) - * - Orders can be composed using {@link combine} and {@link combineAll} to create multi-criteria comparisons - * - Orders can be transformed using {@link mapInput} to compare values by extracting a comparable property - * - Built-in orders exist for common types: {@link Number}, {@link String}, {@link Boolean}, {@link BigInt}, {@link Date} - * - * Common tasks: - * - Creating custom orders → {@link make} - * - Using built-in orders → {@link Number}, {@link String}, {@link Boolean}, {@link BigInt}, {@link Date} - * - Combining multiple orders → {@link combine}, {@link combineAll} - * - Transforming orders → {@link mapInput} - * - Comparing values → {@link isLessThan}, {@link isGreaterThan}, {@link isLessThanOrEqualTo}, {@link isGreaterThanOrEqualTo} - * - Finding min/max → {@link min}, {@link max} - * - Clamping values → {@link clamp}, {@link isBetween} - * - Ordering collections → {@link Array}, {@link Tuple}, {@link Struct} - * - * Gotchas: - * - `Order.Number` treats all `NaN` values as equal and less than any other number - * - `Order.make` uses reference equality (`===`) as a shortcut: if `self === that`, it returns `0` without calling the comparison function - * - `Order.Array` compares arrays element-by-element, then by length if all elements are equal; `Order.all` only compares elements up to the shorter array's length - * - `Order.Tuple` requires a fixed-length tuple with matching order types; `Order.Array` works with variable-length arrays - * - `Order.min` and `Order.max` return the first argument when values are equal - * - * Quickstart: - * - * **Example** (Basic Usage) - * - * ```ts - * import { Order } from "effect" - * - * const result = Order.Number(5, 10) - * console.log(result) // -1 (5 is less than 10) - * - * const isLessThan = Order.isLessThan(Order.Number)(5, 10) - * console.log(isLessThan) // true - * ``` - * - * See also: - * - {@link Ordering} - The result type of comparisons - * - {@link Reducer} - For combining orders in collections - * * @since 2.0.0 */ export * as Order from "./Order.ts" /** - * @fileoverview - * The Ordering module provides utilities for working with comparison results and ordering operations. - * An Ordering represents the result of comparing two values, expressing whether the first value is - * less than (-1), equal to (0), or greater than (1) the second value. - * - * This module is fundamental for building comparison functions, sorting algorithms, and implementing - * ordered data structures. It provides composable operations for combining multiple comparison results - * and pattern matching on ordering outcomes. - * - * Key Features: - * - Type-safe representation of comparison results (-1, 0, 1) - * - Composable operations for combining multiple orderings - * - Pattern matching utilities for handling different ordering cases - * - Ordering reversal and combination functions - * - Integration with Effect's functional programming patterns - * - * Common Use Cases: - * - Implementing custom comparison functions - * - Building complex sorting criteria - * - Combining multiple comparison results - * - Creating ordered data structures - * - Pattern matching on comparison outcomes - * * @since 2.0.0 - * @category utilities */ export * as Ordering from "./Ordering.ts" @@ -2822,89 +402,16 @@ export * as PlatformError from "./PlatformError.ts" export * as Pool from "./Pool.ts" /** - * Predicate and Refinement helpers for runtime checks, filtering, and type narrowing. - * This module provides small, pure functions you can combine to decide whether a - * value matches a condition and, when using refinements, narrow TypeScript types. - * - * Mental model: - * - A `Predicate` is just `(a: A) => boolean`. - * - A `Refinement` is a predicate that narrows `A` to `B` when true. - * - Guards like `isString` are predicates/refinements for common runtime types. - * - Combinators like `and`/`or` build new predicates from existing ones. - * - `Tuple` and `Struct` lift element/property predicates to compound values. - * - * Common tasks: - * - Reuse an existing predicate on a different input shape -> {@link mapInput} - * - Combine checks -> {@link and}, {@link or}, {@link not}, {@link xor} - * - Build tuple/object checks -> {@link Tuple}, {@link Struct} - * - Narrow `unknown` to a concrete type -> {@link Refinement}, {@link compose} - * - Check runtime types -> {@link isString}, {@link isNumber}, {@link isObject} - * - * Gotchas: - * - `isTruthy` uses JavaScript truthiness; `0`, "", and `false` are false. - * - `isObject` excludes arrays; use {@link isObjectOrArray} for both. - * - `isIterable` treats strings as iterable. - * - `isPromise`/`isPromiseLike` are structural checks (then/catch), not `instanceof`. - * - `isTupleOf` and `isTupleOfAtLeast` only check length, not element types. - * - * **Example** (Filter by a predicate) - * - * ```ts - * import * as Predicate from "effect/Predicate" - * - * const isPositive = (n: number) => n > 0 - * const data = [2, -1, 3] - * - * console.log(data.filter(isPositive)) - * ``` - * - * See also: {@link Predicate}, {@link Refinement}, {@link and}, {@link or}, {@link mapInput} - * * @since 2.0.0 */ export * as Predicate from "./Predicate.ts" /** - * This module provides functionality for working with primary keys. - * A `PrimaryKey` is a simple interface that represents a unique identifier - * that can be converted to a string representation. - * - * Primary keys are useful for creating unique identifiers for objects, - * database records, cache keys, or any scenario where you need a - * string-based unique identifier. - * * @since 2.0.0 */ export * as PrimaryKey from "./PrimaryKey.ts" /** - * This module provides utilities for working with publish-subscribe (PubSub) systems. - * - * A PubSub is an asynchronous message hub where publishers can publish messages and subscribers - * can subscribe to receive those messages. PubSub supports various backpressure strategies, - * message replay, and concurrent access from multiple producers and consumers. - * - * @example - * ```ts - * import { Effect, PubSub } from "effect" - * - * const program = Effect.gen(function*() { - * const pubsub = yield* PubSub.bounded(10) - * - * // Publisher - * yield* PubSub.publish(pubsub, "Hello") - * yield* PubSub.publish(pubsub, "World") - * - * // Subscriber - * yield* Effect.scoped(Effect.gen(function*() { - * const subscription = yield* PubSub.subscribe(pubsub) - * const message1 = yield* PubSub.take(subscription) - * const message2 = yield* PubSub.take(subscription) - * console.log(message1, message2) // "Hello", "World" - * })) - * }) - * ``` - * * @since 2.0.0 */ export * as PubSub from "./PubSub.ts" @@ -2920,26 +427,6 @@ export * as Pull from "./Pull.ts" export * as Queue from "./Queue.ts" /** - * The Random module provides a service for generating random numbers in Effect - * programs. It offers a testable and composable way to work with randomness, - * supporting integers, floating-point numbers, and range-based generation. - * - * @example - * ```ts - * import { Effect, Random } from "effect" - * - * const program = Effect.gen(function*() { - * const randomFloat = yield* Random.next - * console.log("Random float:", randomFloat) - * - * const randomInt = yield* Random.nextInt - * console.log("Random integer:", randomInt) - * - * const diceRoll = yield* Random.nextIntBetween(1, 6) - * console.log("Dice roll:", diceRoll) - * }) - * ``` - * * @since 4.0.0 */ export * as Random from "./Random.ts" @@ -2955,228 +442,41 @@ export * as RcMap from "./RcMap.ts" export * as RcRef from "./RcRef.ts" /** - * This module provides utility functions for working with records in TypeScript. - * * @since 2.0.0 */ export * as Record from "./Record.ts" /** - * Context-aware redaction for sensitive values. - * - * The `Redactable` module provides a protocol for objects that need to present - * alternative representations of themselves depending on the runtime context. - * Typical use cases include masking secrets, tokens, or personal data in logs, traces, - * and serialized output. - * - * ## Mental model - * - * - **Redactable** - an object that implements `[symbolRedactable]`, a method - * that receives the current `Context` and returns a replacement value. - * - **symbolRedactable** - the well-known `Symbol` key that marks an object as - * redactable. - * - **redact** - the primary entry point: pass any value and get back either its - * redacted form (if it is `Redactable`) or the original value unchanged. - * - **getRedacted** - lower-level helper that calls `[symbolRedactable]` directly - * on a value already known to be `Redactable`. - * - The `Context` passed to `[symbolRedactable]` comes from the current fiber. - * If no fiber is active, an empty `Context` is used. - * - * ## Common tasks - * - * - **Make a value redactable**: implement the {@link Redactable} interface by - * adding a `[symbolRedactable]` method. - * - **Redact an unknown value**: call {@link redact} - it returns the original - * value when it is not redactable. - * - **Check if a value is redactable**: use {@link isRedactable}. - * - **Get the redacted form of a known `Redactable`**: use {@link getRedacted}. - * - * ## Gotchas - * - * - `[symbolRedactable]` receives the fiber's `Context` as its argument. - * - Outside of an Effect runtime (no current fiber), `getRedacted` still works - * but passes an empty `Context`, so service lookups will not find anything. - * - `redact` is not recursive: if a redactable object contains nested - * redactable values, only the outermost redaction is applied. - * - * ## Quickstart - * - * **Example** (Masking an API key) - * - * ```ts - * import { Context, Redactable } from "effect" - * - * class ApiKey { - * constructor(readonly raw: string) {} - * - * [Redactable.symbolRedactable](_ctx: Context.Context) { - * return this.raw.slice(0, 4) + "..." - * } - * } - * - * const key = new ApiKey("sk-1234567890abcdef") - * - * console.log(Redactable.isRedactable(key)) // true - * console.log(Redactable.redact(key)) // "sk-1..." - * console.log(Redactable.redact("plain")) // "plain" - * ``` - * - * ## See also - * - * - {@link Redactable} - the interface to implement - * - {@link symbolRedactable} - the symbol key - * - {@link redact} - the main redaction entry point - * * @since 4.0.0 */ export * as Redactable from "./Redactable.ts" /** - * The Redacted module provides functionality for handling sensitive information - * securely within your application. By using the `Redacted` data type, you can - * ensure that sensitive values are not accidentally exposed in logs or error - * messages. - * * @since 3.3.0 */ export * as Redacted from "./Redacted.ts" /** - * A module for reducing collections of values into a single result. - * - * A `Reducer` extends {@link Combiner.Combiner} by adding an - * `initialValue` (identity element) and a `combineAll` method that folds an - * entire collection. Think `Array.prototype.reduce`, but packaged as a - * reusable, composable value. - * - * ## Mental model - * - * - **Reducer** – a {@link Combiner.Combiner} plus an `initialValue` and a - * `combineAll` method. - * - **initialValue** – the neutral/identity element. Combining any value with - * `initialValue` should return the original value unchanged (e.g. `0` for - * addition, `""` for string concatenation). - * - **combineAll** – folds an `Iterable` starting from `initialValue`. - * When omitted from {@link make}, a default left-to-right fold is used. - * - **Purity** – all reducers produced by this module are pure; they never - * mutate their arguments. - * - **Composability** – reducers can be lifted into `Option`, `Struct`, - * `Tuple`, `Record`, and other container types via helpers in those modules. - * - **Subtype of Combiner** – every `Reducer` is also a valid - * `Combiner`, so you can pass a `Reducer` anywhere a `Combiner` is - * expected. - * - * ## Common tasks - * - * - Create a reducer from a combine function and initial value → {@link make} - * - Swap argument order → {@link flip} - * - Combine two values without an initial value → use {@link Combiner.Combiner} - * instead - * - * ## Gotchas - * - * - `combineAll` on an empty iterable returns `initialValue`, not an error. - * - The default `combineAll` folds left-to-right. If your `combine` is not - * associative, order matters. Pass a custom `combineAll` to {@link make} if - * you need different traversal or short-circuiting. - * - A `Reducer` is also a valid `Combiner` — but a `Combiner` is *not* a - * `Reducer` (it lacks `initialValue`). - * - * ## Quickstart - * - * **Example** (summing a list of numbers) - * - * ```ts - * import { Reducer } from "effect" - * - * const Sum = Reducer.make((a, b) => a + b, 0) - * - * console.log(Sum.combine(3, 4)) - * // Output: 7 - * - * console.log(Sum.combineAll([1, 2, 3, 4])) - * // Output: 10 - * - * console.log(Sum.combineAll([])) - * // Output: 0 - * ``` - * - * ## See also - * - * - {@link make} – the primary constructor - * - {@link Reducer} – the core interface - * - {@link Combiner.Combiner} – the parent interface (no `initialValue`) - * * @since 4.0.0 */ export * as Reducer from "./Reducer.ts" /** - * This module provides utilities for working with mutable references in a functional context. - * - * A Ref is a mutable reference that can be read, written, and atomically modified. Unlike plain - * mutable variables, Refs are thread-safe and work seamlessly with Effect's concurrency model. - * They provide atomic operations for safe state management in concurrent programs. - * - * @example - * ```ts - * import { Effect, Ref } from "effect" - * - * const program = Effect.gen(function*() { - * // Create a ref with initial value - * const counter = yield* Ref.make(0) - * - * // Atomic operations - * yield* Ref.update(counter, (n) => n + 1) - * yield* Ref.update(counter, (n) => n * 2) - * - * const value = yield* Ref.get(counter) - * console.log(value) // 2 - * - * // Atomic modify with return value - * const previous = yield* Ref.getAndSet(counter, 100) - * console.log(previous) // 2 - * }) - * ``` - * * @since 2.0.0 */ export * as Ref from "./Ref.ts" /** - * This module provides a collection of reference implementations for commonly used - * Effect runtime configuration values. These references allow you to access and - * modify runtime behavior such as concurrency limits, scheduling policies, - * tracing configuration, and logging settings. - * - * References are special service instances that can be dynamically updated - * during runtime, making them ideal for configuration that may need to change - * based on application state or external conditions. - * * @since 4.0.0 */ export * as References from "./References.ts" /** - * This module provides utility functions for working with RegExp in TypeScript. - * * @since 2.0.0 */ export * as RegExp from "./RegExp.ts" /** - * The `Request` module provides a way to model requests to external data sources - * in a functional and composable manner. Requests represent descriptions of - * operations that can be batched, cached, and executed efficiently. - * - * A `Request` represents a request that: - * - Yields a value of type `A` on success - * - Can fail with an error of type `E` - * - Requires services of type `R` - * - * Requests are primarily used with RequestResolver to implement efficient - * data fetching patterns, including automatic batching and caching. - * * @since 2.0.0 */ export * as Request from "./Request.ts" @@ -3192,135 +492,16 @@ export * as RequestResolver from "./RequestResolver.ts" export * as Resource from "./Resource.ts" /** - * A synchronous, pure type for representing computations that can succeed - * (`Success`) or fail (`Failure`). Unlike `Effect`, `Result` is - * evaluated eagerly and carries no side effects. - * - * **Mental model** - * - * - `Result` is a discriminated union: `Success | Failure` - * - `Success` wraps a value of type `A`, accessed via `.success` - * - `Failure` wraps an error of type `E`, accessed via `.failure` - * - `Result` is a monad: chain operations with {@link flatMap}, compose pipelines with `pipe` - * - All operations are pure and return new `Result` values; the input is never mutated - * - `Result` is yieldable in `Effect.gen`, producing the inner value or short-circuiting on failure - * - * **Common tasks** - * - * - Create from a value: {@link succeed}, {@link fail} - * - Create from nullable: {@link fromNullishOr} - * - Create from Option: {@link fromOption} - * - Create from throwing code: {@link try_ try} - * - Create from predicate: {@link liftPredicate} - * - Transform: {@link map}, {@link mapError}, {@link mapBoth} - * - Unwrap: {@link getOrElse}, {@link getOrNull}, {@link getOrUndefined}, {@link getOrThrow} - * - Pattern match: {@link match} - * - Sequence: {@link flatMap}, {@link andThen}, {@link all} - * - Recover: {@link orElse} - * - Filter: {@link filterOrFail} - * - Convert to Option: {@link getSuccess}, {@link getFailure} - * - Generator syntax: {@link gen} - * - Do notation: {@link Do}, {@link bind}, {@link let_ let} - * - Check variant: {@link isResult}, {@link isSuccess}, {@link isFailure} - * - * **Gotchas** - * - * - `E` defaults to `never`, so `Result` means a result that cannot fail - * - {@link andThen} accepts a `Result`, a function returning a `Result`, a plain value, or a function returning a plain value; {@link flatMap} only accepts a function returning a `Result` - * - {@link all} short-circuits on the first `Failure` and returns it; later elements are not inspected - * - {@link getOrThrow} throws the raw failure value `E`; use {@link getOrThrowWith} for custom error objects - * - {@link tap} runs a side-effect but does not change the result; its return value is ignored - * - * **Quickstart** - * - * **Example** (Parsing and validating with Result) - * - * ```ts - * import { Result } from "effect" - * - * const parse = (input: string): Result.Result => - * isNaN(Number(input)) - * ? Result.fail("not a number") - * : Result.succeed(Number(input)) - * - * const ensurePositive = (n: number): Result.Result => - * n > 0 ? Result.succeed(n) : Result.fail("not positive") - * - * const result = Result.flatMap(parse("42"), ensurePositive) - * - * console.log(Result.getOrElse(result, (err) => `Error: ${err}`)) - * // Output: 42 - * ``` - * - * **See also** - * - * - {@link succeed} / {@link fail} to create values - * - {@link match} to fold both branches - * - {@link gen} for generator-based composition - * * @since 4.0.0 */ export * as Result from "./Result.ts" /** - * This module provides utilities for running Effect programs and managing their execution lifecycle. - * - * The Runtime module contains functions for creating main program runners that handle process - * teardown, error reporting, and exit code management. These utilities are particularly useful - * for creating CLI applications and server processes that need to manage their lifecycle properly. - * - * @example - * ```ts - * import { Effect, Fiber, Runtime } from "effect" - * - * // Create a main runner for Node.js - * const runMain = Runtime.makeRunMain((options) => { - * process.on("SIGINT", () => Effect.runFork(Fiber.interrupt(options.fiber))) - * process.on("SIGTERM", () => Effect.runFork(Fiber.interrupt(options.fiber))) - * - * options.fiber.addObserver((exit) => { - * options.teardown(exit, (code) => process.exit(code)) - * }) - * }) - * - * // Use the runner - * const program = Effect.log("Hello, World!") - * runMain(program) - * ``` - * * @since 4.0.0 */ export * as Runtime from "./Runtime.ts" /** - * This module provides utilities for creating and composing schedules for retrying operations, - * repeating effects, and implementing various timing strategies. - * - * A Schedule is a function that takes an input and returns a decision whether to continue or halt, - * along with a delay duration. Schedules can be combined, transformed, and used to implement - * sophisticated retry and repetition logic. - * - * @example - * ```ts - * import { Effect, Schedule } from "effect" - * - * // Retry with exponential backoff - * const retryPolicy = Schedule.exponential("100 millis", 2.0) - * .pipe(Schedule.both(Schedule.recurs(3))) - * - * const program = Effect.gen(function*() { - * // This will retry up to 3 times with exponential backoff - * const result = yield* Effect.retry( - * Effect.fail("Network error"), - * retryPolicy - * ) - * }) - * - * // Repeat on a fixed schedule - * const heartbeat = Effect.log("heartbeat") - * .pipe(Effect.repeat(Schedule.spaced("30 seconds"))) - * ``` - * * @since 2.0.0 */ export * as Schedule from "./Schedule.ts" @@ -3331,335 +512,21 @@ export * as Schedule from "./Schedule.ts" export * as Scheduler from "./Scheduler.ts" /** - * Define data shapes, validate unknown input, and transform values between formats. - * - * ## Mental model - * - * - **Schema** — a description of a data shape. Every schema carries a decoded - * *Type* (the value you work with) and an *Encoded* representation (the - * serialized form, e.g. JSON). - * - **Decoding** — turning unknown external data (API responses, form - * submissions, config files) into typed, validated values. - * - **Encoding** — turning typed values back into a serializable format. - * - **Codec** — a schema that tracks both Type and Encoded, so it can decode - * *and* encode. Most concrete schemas are Codecs. - * - **Check / Filter** — a constraint attached to a schema (e.g. `isMinLength`, - * `isGreaterThan`). Attach them with `.check(...)`. - * - **Transformation** — a pair of functions (decode + encode) that convert - * values between two schemas. Created with {@link decodeTo} / {@link encodeTo}. - * - **Annotation** — metadata attached to a schema (title, description, custom - * keys). Attach with `.annotate(...)`. - * - * ## Common tasks - * - * - Define a struct: {@link Struct} - * - Define a union: {@link Union}, {@link TaggedUnion}, {@link Literals} - * - Define an array: {@link ArraySchema}, {@link NonEmptyArray} - * - Define a record: {@link Record} - * - Define a tuple: {@link Tuple}, {@link TupleWithRest} - * - Validate unknown data synchronously: {@link decodeUnknownSync} - * - Validate unknown data (Effect): {@link decodeUnknownEffect} - * - Encode a value: {@link encodeUnknownSync}, {@link encodeUnknownEffect} - * - Type guard: {@link is} - * - Assertion: {@link asserts} - * - Add constraints: `.check(...)` with filters like {@link isMinLength}, - * {@link isGreaterThan}, {@link isPattern}, {@link isUUID} - * - Transform between schemas: {@link decodeTo}, {@link encodeTo} - * - Add a default for missing keys: {@link withDecodingDefault}, {@link withDecodingDefaultKey} - * - Create branded types: {@link brand} - * - Define classes with validation: {@link Class}, {@link TaggedClass} - * - Define error classes: {@link ErrorClass}, {@link TaggedErrorClass} - * - Generate JSON Schema: {@link toJsonSchemaDocument} - * - Generate test data: {@link toArbitrary} - * - Derive equivalence: {@link toEquivalence} - * - * ## Gotchas - * - * - `Schema.optional` creates `T | undefined` (key can be missing *or* - * `undefined`). Use `Schema.optionalKey` for exact optional properties. - * - `decodeTo` is curried: use `from.pipe(Schema.decodeTo(to, ...))`. - * - `decodeUnknownSync` throws on failure. Use `decodeUnknownExit` or - * `decodeUnknownOption` for non-throwing alternatives. - * - Filters do not change the TypeScript type. Use {@link refine} or - * {@link brand} to narrow the type. - * - Recursive schemas require {@link suspend} to avoid infinite loops. - * - * ## Quickstart - * - * **Example** (Validate a user object) - * - * ```ts - * import { Schema } from "effect" - * - * const User = Schema.Struct({ - * name: Schema.String.check(Schema.isMinLength(1)), - * age: Schema.Number.check(Schema.isGreaterThanOrEqualTo(0)), - * email: Schema.optionalKey(Schema.String) - * }) - * - * // Decode unknown input — throws on failure - * const user = Schema.decodeUnknownSync(User)({ - * name: "Alice", - * age: 30 - * }) - * - * console.log(user) - * // { name: "Alice", age: 30 } - * ``` - * - * @see {@link Schema} — type-level view tracking only the decoded Type - * @see {@link Codec} — type-level view tracking both Type and Encoded - * @see {@link Struct} — define object shapes - * @see {@link decodeUnknownSync} — synchronous validation - * @see {@link decodeTo} — schema transformations - * * @since 4.0.0 */ export * as Schema from "./Schema.ts" /** - * Abstract Syntax Tree (AST) representation for Effect schemas. - * - * This module defines the runtime data structures that represent schemas. - * Most users work with the `Schema` module directly; use `SchemaAST` when you - * need to inspect, traverse, or programmatically transform schema definitions. - * - * ## Mental model - * - * - **{@link AST}** — discriminated union (`_tag`) of all schema node types - * (e.g. `String`, `Objects`, `Union`, `Suspend`) - * - **{@link Base}** — abstract base class shared by every node; carries - * annotations, checks, encoding chain, and context - * - **{@link Encoding}** — a non-empty chain of {@link Link} values describing - * how to transform between the decoded (type) and encoded (wire) form - * - **{@link Check}** — a validation filter ({@link Filter} or - * {@link FilterGroup}) attached to an AST node - * - **{@link Context}** — per-property metadata: optionality, mutability, - * default values, key annotations - * - **Guards** — type-narrowing predicates for each AST variant (e.g. - * {@link isString}, {@link isObjects}) - * - * ## Common tasks - * - * - Inspect what kind of schema you have → guard functions ({@link isString}, - * {@link isObjects}, {@link isUnion}, etc.) - * - Get the decoded (type-level) AST → {@link toType} - * - Get the encoded (wire-format) AST → {@link toEncoded} - * - Swap decode/encode directions → {@link flip} - * - Read annotations → {@link resolve}, {@link resolveAt}, - * {@link resolveIdentifier} - * - Build a transformation between schemas → {@link decodeTo} - * - Add regex validation → {@link isPattern} - * - * ## Gotchas - * - * - AST nodes are structurally immutable; modification helpers return new - * objects via `Object.create`. - * - {@link Arrays} represents both tuples and arrays; {@link Objects} - * represents both structs and records. - * - {@link toType} and {@link toEncoded} are memoized — same input yields - * same output reference. - * - {@link Suspend} lazily resolves its inner AST via a thunk; the thunk is - * memoized on first call. - * - * ## Quickstart - * - * **Example** (Inspecting a schema's AST) - * - * ```ts - * import { Schema, SchemaAST } from "effect" - * - * const schema = Schema.Struct({ name: Schema.String, age: Schema.Number }) - * const ast = schema.ast - * - * if (SchemaAST.isObjects(ast)) { - * console.log(ast.propertySignatures.map(ps => ps.name)) - * // ["name", "age"] - * } - * - * const encoded = SchemaAST.toEncoded(ast) - * console.log(SchemaAST.isObjects(encoded)) // true - * ``` - * - * ## See also - * - * - {@link AST} - * - {@link toType} - * - {@link toEncoded} - * - {@link flip} - * - {@link resolve} - * * @since 4.0.0 */ export * as SchemaAST from "./SchemaAST.ts" /** - * Composable transformation primitives for the Effect Schema system. - * - * A `Getter` represents a single-direction transformation from an - * encoded type `E` to a decoded type `T`. Getters are the building blocks - * that `Schema.decodeTo` and `Schema.decode` use to define how values are - * transformed during encoding and decoding. They handle optionality - * (`Option` in, `Option` out), can fail with `Issue`, and can require - * Effect services via `R`. - * - * ## Mental model - * - * - **Getter**: A function `Option -> Effect, Issue, R>`. It - * transforms an optional encoded value into an optional decoded value, - * possibly failing or requiring services. - * - **Passthrough**: The identity getter — returns the input unchanged. Used - * when no transformation is needed. Optimized away during composition. - * - **Option-awareness**: Getters receive and return `Option` to handle - * missing keys in structs. `Option.None` means the key is absent. - * - **Composition**: Getters compose left-to-right via `.compose()`. A - * passthrough on either side is a no-op (identity optimization). - * - **Issue**: The error type for all getter failures (see `SchemaIssue`). - * - * ## Common tasks - * - * - Pass a value through unchanged → {@link passthrough} - * - Transform a value purely → {@link transform} - * - Transform a value with possible failure → {@link transformOrFail} - * - Transform with full Option control → {@link transformOptional} - * - Handle missing keys → {@link onNone}, {@link required}, {@link withDefault} - * - Handle present values → {@link onSome} - * - Validate a value with an effectful check → {@link checkEffect} - * - Produce a constant value → {@link succeed} - * - Always fail → {@link fail}, {@link forbidden} - * - Omit a value from output → {@link omit} - * - Coerce to a primitive type → {@link String}, {@link Number}, {@link Boolean}, {@link BigInt}, {@link Date} - * - Transform strings → {@link trim}, {@link capitalize}, {@link toLowerCase}, {@link toUpperCase}, {@link split}, {@link splitKeyValue}, {@link joinKeyValue} - * - Parse/stringify JSON → {@link parseJson}, {@link stringifyJson} - * - Encode/decode Base64 → {@link encodeBase64}, {@link decodeBase64}, {@link decodeBase64String} - * - Encode/decode Hex → {@link encodeHex}, {@link decodeHex}, {@link decodeHexString} - * - Encode/decode URI components → {@link encodeUriComponent}, {@link decodeUriComponent} - * - Parse DateTime → {@link dateTimeUtcFromInput} - * - Decode/encode FormData → {@link decodeFormData}, {@link encodeFormData} - * - Decode/encode URLSearchParams → {@link decodeURLSearchParams}, {@link encodeURLSearchParams} - * - Build nested tree from bracket paths → {@link makeTreeRecord} - * - Flatten nested tree to bracket paths → {@link collectBracketPathEntries} - * - * ## Gotchas - * - * - Getters are not bidirectional. To define a full encode/decode pair, supply - * both a `decode` and an `encode` getter to `Schema.decodeTo`. - * - `passthrough` requires `T === E` by default. Use `{ strict: false }` to - * bypass the type constraint, or use {@link passthroughSupertype} / {@link passthroughSubtype}. - * - `transform` skips `None` inputs (missing keys) — the function is only - * called when a value is present. Use `transformOptional` if you need to - * handle missing values. - * - `parseJson` without a `reviver` returns `Schema.MutableJson`. With a - * reviver, the return type widens to `unknown`. - * - `split` treats an empty string as an empty array, not `[""]`. - * - * ## Quickstart - * - * **Example** (Using SchemaGetter with Schema.decodeTo) - * - * ```ts - * import { Schema, SchemaGetter } from "effect" - * - * const NumberFromString = Schema.String.pipe( - * Schema.decodeTo(Schema.Number, { - * decode: SchemaGetter.transform((s) => Number(s)), - * encode: SchemaGetter.transform((n) => String(n)) - * }) - * ) - * - * const result = Schema.decodeUnknownSync(NumberFromString)("42") - * // result: 42 - * ``` - * - * ## See also - * - * - {@link Getter} — the core class - * - {@link transform} — most common constructor - * - {@link passthrough} — identity getter - * - {@link transformOrFail} — fallible transformation - * * @since 4.0.0 */ export * as SchemaGetter from "./SchemaGetter.ts" /** - * Structured validation errors produced by the Effect Schema system. - * - * When `Schema.decode`, `Schema.encode`, or a filter rejects a value, the - * result is an {@link Issue} — a recursive tree that describes *what* went - * wrong and *where*. This module defines every node type in that tree and - * provides formatters that turn an `Issue` into a human-readable string or a - * Standard Schema V1 failure result. - * - * ## Mental model - * - * - **Issue**: A discriminated union (`_tag`) of all possible validation error - * nodes. It is recursive — composite nodes wrap inner `Issue` children. - * - **Leaf**: A terminal issue with no inner children ({@link InvalidType}, - * {@link InvalidValue}, {@link MissingKey}, {@link UnexpectedKey}, - * {@link Forbidden}, {@link OneOf}). - * - **Composite nodes**: Wrap one or more inner issues to add context — - * {@link Filter}, {@link Encoding}, {@link Pointer}, {@link Composite}, - * {@link AnyOf}. - * - **Pointer**: Adds a property-key path to an inner issue, indicating - * *where* in the input the error occurred. - * - **Formatter**: A function `Issue → Format` that serialises the error tree. - * Two built-in factories are provided: {@link makeFormatterDefault} (plain - * string) and {@link makeFormatterStandardSchemaV1} (Standard Schema V1). - * - * ## Common tasks - * - * - Check if a value is an Issue → {@link isIssue} - * - Extract the actual input from any issue → {@link getActual} - * - Format an issue as a string → {@link makeFormatterDefault} - * - Format an issue for Standard Schema V1 → {@link makeFormatterStandardSchemaV1} - * - Customise leaf formatting → {@link defaultLeafHook} - * - Customise filter formatting → {@link defaultCheckHook} - * - * ## Gotchas - * - * - `Pointer` and `MissingKey` carry no actual value — {@link getActual} - * returns `Option.none()` for them. - * - `AnyOf`, `UnexpectedKey`, `OneOf`, and `Filter` store `actual` as a plain - * `unknown` (not `Option`), so {@link getActual} wraps them with - * `Option.some`. - * - Calling `toString()` on any `Issue` uses the default formatter. To - * customise output, create your own formatter with - * {@link makeFormatterDefault} or {@link makeFormatterStandardSchemaV1}. - * - The `Issue` tree can be deeply nested for complex schemas. Formatters - * flatten composite nodes for display. - * - * ## Quickstart - * - * **Example** (Inspecting a validation error) - * - * ```ts - * import { Schema, SchemaIssue } from "effect" - * - * const Person = Schema.Struct({ - * name: Schema.String, - * age: Schema.Number - * }) - * - * try { - * Schema.decodeUnknownSync(Person)({ name: 42 }) - * } catch (e) { - * if (Schema.isSchemaError(e)) { - * console.log(SchemaIssue.isIssue(e.issue)) - * // true - * console.log(String(e.issue)) - * // formatted error message - * } - * } - * ``` - * - * ## See also - * - * - {@link Issue} — the root union type - * - {@link Leaf} — terminal issue types - * - {@link Formatter} — the formatter interface - * - {@link makeFormatterDefault} — default string formatter - * * @since 4.0.0 */ export * as SchemaIssue from "./SchemaIssue.ts" @@ -3670,179 +537,11 @@ export * as SchemaIssue from "./SchemaIssue.ts" export * as SchemaParser from "./SchemaParser.ts" /** - * Serializable intermediate representation (IR) of Effect Schema types. - * - * `SchemaRepresentation` sits between the internal `SchemaAST` and external - * formats (JSON Schema, generated TypeScript code, serialized JSON). A - * {@link Representation} is a discriminated union describing the *shape* of a - * schema — its types, checks, annotations, and references — in a form that - * can be round-tripped through JSON and used for code generation. - * - * ## Mental model - * - * - **Representation**: A tagged union (`_tag`) of all supported schema shapes: - * primitives, literals, objects, arrays, unions, declarations, references, - * and suspensions. - * - **Document**: A single {@link Representation} paired with a map of named - * {@link References} (analogous to JSON Schema `$defs`). - * - **MultiDocument**: Like `Document` but holds one or more representations - * sharing the same references. - * - **Check / Filter / FilterGroup**: Validation constraints (min length, - * pattern, integer, etc.) attached to types that support them. - * - **Meta types**: Typed metadata for checks on each category — e.g. - * {@link StringMeta}, {@link NumberMeta}, {@link ArraysMeta}. - * - **Reviver**: A callback used by {@link toSchema} and {@link toCodeDocument} - * to handle `Declaration` nodes (custom types like `Option`, `Date`, etc.). - * - **Code / CodeDocument**: Output of {@link toCodeDocument} — TypeScript - * source strings for runtime schemas and their type-level counterparts. - * - * ## Common tasks - * - * - Convert a Schema AST to a Document → {@link fromAST} - * - Convert multiple ASTs to a MultiDocument → {@link fromASTs} - * - Reconstruct a runtime Schema from a Document → {@link toSchema} - * - Convert a Document to JSON Schema → {@link toJsonSchemaDocument} - * - Convert a MultiDocument to JSON Schema → {@link toJsonSchemaMultiDocument} - * - Parse a JSON Schema document into a Document → {@link fromJsonSchemaDocument} - * - Parse a JSON Schema multi-document → {@link fromJsonSchemaMultiDocument} - * - Generate TypeScript code from a MultiDocument → {@link toCodeDocument} - * - Serialize/deserialize a Document as JSON → {@link DocumentFromJson} - * - Serialize/deserialize a MultiDocument as JSON → {@link MultiDocumentFromJson} - * - Wrap a Document as a MultiDocument → {@link toMultiDocument} - * - * ## Gotchas - * - * - `Declaration` nodes require a {@link Reviver} to reconstruct complex types - * (e.g. `Option`, `Date`). Without one, `toSchema` falls back to the - * declaration's `encodedSchema`. Use {@link toSchemaDefaultReviver} for - * built-in Effect types. - * - `Reference` nodes are resolved against the `references` map in the - * `Document`. An unresolvable `$ref` throws at runtime. - * - `Suspend` wraps a single `thunk` representation; it is used for recursive - * schemas. Circular references are handled by lazy resolution in - * {@link toSchema}. - * - The `$`-prefixed exports (e.g. {@link $Representation}, {@link $Document}) - * are Schema codecs for the representation types themselves — use them to - * validate or encode/decode representation data, not application data. - * - * ## Quickstart - * - * **Example** (Round-trip through JSON) - * - * ```ts - * import { Schema, SchemaRepresentation } from "effect" - * - * const Person = Schema.Struct({ - * name: Schema.String, - * age: Schema.Int - * }) - * - * // Schema AST → Document - * const doc = SchemaRepresentation.fromAST(Person.ast) - * - * // Document → JSON Schema - * const jsonSchema = SchemaRepresentation.toJsonSchemaDocument(doc) - * - * // Document → runtime Schema - * const reconstructed = SchemaRepresentation.toSchema(doc) - * ``` - * - * ## See also - * - * - {@link Representation} — the core tagged union - * - {@link Document} — single-schema container - * - {@link fromAST} — entry point from Schema AST - * - {@link toSchema} — reconstruct a runtime Schema - * - {@link toCodeDocument} — generate TypeScript code - * * @since 4.0.0 */ export * as SchemaRepresentation from "./SchemaRepresentation.ts" /** - * Bidirectional transformations for the Effect Schema system. - * - * A `Transformation` pairs a decode `Getter` and an encode `Getter` into a - * single bidirectional value, used by `Schema.decodeTo`, `Schema.encodeTo`, - * `Schema.decode`, `Schema.encode`, and `Schema.link` to define how values - * are converted between encoded and decoded representations. A `Middleware` - * is the effect-level equivalent — it wraps the entire parsing `Effect` - * pipeline rather than individual values. - * - * ## Mental model - * - * - **Transformation**: A pair of `Getter`s (decode + encode) that convert - * individual values bidirectionally. `T` is the decoded (Type) side, `E` is - * the encoded side. `RD`/`RE` are required Effect services. - * - **Middleware**: Like `Transformation`, but each direction receives the full - * parsing `Effect` and can intercept, retry, or modify the pipeline. - * - **Getter**: A single-direction transform `Option → Effect, Issue, R>` - * (see `SchemaGetter`). - * - **flip()**: Swaps decode and encode, turning a `Transformation` into - * `Transformation`. - * - **compose()**: Chains two transformations left-to-right on the decode side - * and right-to-left on the encode side. - * - **passthrough**: The identity transformation — no conversion in either - * direction. - * - * ## Common tasks - * - * - Convert values purely (sync, infallible) → {@link transform} - * - Convert values with possible failure → {@link transformOrFail} - * - Handle optional/missing keys → {@link transformOptional} - * - Build from existing Getters → {@link make} - * - No-op identity transformation → {@link passthrough} - * - Subtype/supertype coercion → {@link passthroughSupertype}, {@link passthroughSubtype} - * - Trim/case strings → {@link trim}, {@link toLowerCase}, {@link toUpperCase}, {@link capitalize}, {@link uncapitalize}, {@link snakeToCamel} - * - Parse key-value strings → {@link splitKeyValue} - * - Coerce string ↔ number/bigint → {@link numberFromString}, {@link bigintFromString} - * - Coerce string ↔ Date/Duration → {@link dateFromString}, {@link durationFromString} - * - Decode durations → {@link durationFromNanos}, {@link durationFromMillis} - * - Wrap nullable/optional as Option → {@link optionFromNullOr}, {@link optionFromOptionalKey}, {@link optionFromOptional} - * - Parse URLs → {@link urlFromString} - * - Base64 ↔ Uint8Array → {@link uint8ArrayFromBase64String} - * - Base64 ↔ string → {@link stringFromBase64String} - * - URI component ↔ string → {@link stringFromUriComponent} - * - JSON string ↔ unknown → {@link fromJsonString} - * - FormData/URLSearchParams ↔ unknown → {@link fromFormData}, {@link fromURLSearchParams} - * - Check if a value is a Transformation → {@link isTransformation} - * - * ## Gotchas - * - * - `Transformation` operates on individual values; `Middleware` wraps the - * entire parsing Effect. Choose accordingly. - * - `passthrough` requires `T === E` by default. Use `{ strict: false }` to - * bypass, or use {@link passthroughSupertype} / {@link passthroughSubtype}. - * - String transformations like `trim`, `toLowerCase`, and `toUpperCase` use - * `passthrough` on the encode side — they are lossy and do not round-trip. - * - `durationFromNanos` encode can fail if the Duration cannot be represented - * as a `bigint`. - * - * ## Quickstart - * - * **Example** (Defining a custom transformation with Schema.decodeTo) - * - * ```ts - * import { Schema, SchemaTransformation } from "effect" - * - * const CentsFromDollars = Schema.Number.pipe( - * Schema.decodeTo( - * Schema.Number, - * SchemaTransformation.transform({ - * decode: (dollars) => dollars * 100, - * encode: (cents) => cents / 100 - * }) - * ) - * ) - * ``` - * - * ## See also - * - * - {@link Transformation} — the core bidirectional transformation class - * - {@link Middleware} — effect-pipeline-level transformation - * - {@link transform} — most common constructor - * - {@link passthrough} — identity transformation - * * @since 4.0.0 */ export * as SchemaTransformation from "./SchemaTransformation.ts" @@ -3853,18 +552,6 @@ export * as SchemaTransformation from "./SchemaTransformation.ts" export * as SchemaUtils from "./SchemaUtils.ts" /** - * The `Scope` module provides functionality for managing resource lifecycles - * and cleanup operations in a functional and composable manner. - * - * A `Scope` represents a context where resources can be acquired and automatically - * cleaned up when the scope is closed. This is essential for managing resources - * like file handles, database connections, or any other resources that need - * proper cleanup. - * - * Scopes support both sequential and parallel finalization strategies: - * - Sequential: Finalizers run one after another in reverse order of registration - * - Parallel: Finalizers run concurrently for better performance - * * @since 2.0.0 */ export * as Scope from "./Scope.ts" @@ -3880,7 +567,7 @@ export * as ScopedCache from "./ScopedCache.ts" export * as ScopedRef from "./ScopedRef.ts" /** - * @since 2.0.0 + * @since 4.0.0 */ export * as Semaphore from "./Semaphore.ts" @@ -3900,86 +587,11 @@ export * as Stdio from "./Stdio.ts" export * as Stream from "./Stream.ts" /** - * This module provides utility functions and type class instances for working with the `string` type in TypeScript. - * It includes functions for basic string manipulation. - * * @since 2.0.0 */ export * as String from "./String.ts" /** - * Utilities for creating, transforming, and comparing plain TypeScript objects - * (structs). Every function produces a new object — inputs are never mutated. - * - * ## Mental model - * - * - **Struct**: A plain JS object with a fixed set of known keys (e.g., - * `{ name: string; age: number }`). Not a generic key-value record. - * - **Dual API**: Most functions accept arguments in both data-first - * (`Struct.pick(obj, keys)`) and data-last (`pipe(obj, Struct.pick(keys))`) - * style. - * - **Immutability**: All operations return a new object; the original is - * never modified. - * - **Lambda**: A type-level function interface (`~lambda.in` / `~lambda.out`) - * used by {@link map}, {@link mapPick}, and {@link mapOmit} so the compiler - * can track how value types change. - * - **Evolver pattern**: {@link evolve}, {@link evolveKeys}, and - * {@link evolveEntries} let you selectively transform values, keys, or both - * while leaving untouched properties unchanged. - * - * ## Common tasks - * - * - Access a property in a pipeline → {@link get} - * - List string keys with proper types → {@link keys} - * - Subset / remove properties → {@link pick}, {@link omit} - * - Merge two structs (second wins) → {@link assign} - * - Rename keys → {@link renameKeys} - * - Transform selected values → {@link evolve} - * - Transform selected keys → {@link evolveKeys} - * - Transform both keys and values → {@link evolveEntries} - * - Map all values with a typed lambda → {@link map}, {@link mapPick}, - * {@link mapOmit} - * - Compare structs → {@link makeEquivalence}, {@link makeOrder} - * - Combine / reduce structs → {@link makeCombiner}, {@link makeReducer} - * - Flatten intersection types → {@link Simplify} - * - Strip `readonly` modifiers → {@link Mutable} - * - * ## Gotchas - * - * - {@link keys} only returns `string` keys; symbol keys are excluded. - * - {@link pick} and {@link omit} iterate with `for...in`, which includes - * inherited enumerable properties but excludes non-enumerable ones. - * - {@link assign} spreads with `...`; property order follows standard - * JS spread rules. - * - {@link map}, {@link mapPick}, {@link mapOmit} require a {@link Lambda} - * value created with {@link lambda}; a plain function won't type-check. - * - * ## Quickstart - * - * **Example** (Picking, renaming, and evolving struct properties) - * - * ```ts - * import { pipe, Struct } from "effect" - * - * const user = { firstName: "Alice", lastName: "Smith", age: 30, admin: false } - * - * const result = pipe( - * user, - * Struct.pick(["firstName", "age"]), - * Struct.evolve({ age: (n) => n + 1 }), - * Struct.renameKeys({ firstName: "name" }) - * ) - * - * console.log(result) // { name: "Alice", age: 31 } - * ``` - * - * ## See also - * - * - {@link Equivalence} – building equivalence relations for structs - * - {@link Order} – ordering structs by their fields - * - {@link Combiner} – combining two values of the same type - * - {@link Reducer} – combining with an initial value - * * @since 2.0.0 */ export * as Struct from "./Struct.ts" @@ -4015,114 +627,21 @@ export * as Terminal from "./Terminal.ts" export * as Tracer from "./Tracer.ts" /** - * A `Trie` is used for locating specific `string` keys from within a set. - * - * It works similar to `HashMap`, but with keys required to be `string`. - * This constraint unlocks some performance optimizations and new methods to get string prefixes (e.g. `keysWithPrefix`, `longestPrefixOf`). - * - * Prefix search is also the main feature that makes a `Trie` more suited than `HashMap` for certain usecases. - * - * A `Trie` is often used to store a dictionary (list of words) that can be searched - * in a manner that allows for efficient generation of completion lists - * (e.g. predict the rest of a word a user is typing). - * - * A `Trie` has O(n) lookup time where `n` is the size of the key, - * or even less than `n` on search misses. - * * @since 2.0.0 */ export * as Trie from "./Trie.ts" /** - * Utilities for creating, accessing, transforming, and comparing fixed-length - * arrays (tuples). Every function produces a new tuple — inputs are never - * mutated. - * - * ## Mental model - * - * - **Tuple**: A fixed-length readonly array where each position can have a - * different type (e.g., `readonly [string, number, boolean]`). - * - **Index-based access**: Elements are accessed by numeric index, and the - * type system tracks the type at each position. - * - **Dual API**: Most functions accept arguments in both data-first - * (`Tuple.get(t, 0)`) and data-last (`pipe(t, Tuple.get(0))`) style. - * - **Immutability**: All operations return a new tuple; the original is - * never modified. - * - **Lambda**: A type-level function interface (from {@link Struct}) used by - * {@link map}, {@link mapPick}, and {@link mapOmit} so the compiler can - * track how element types change. - * - * ## Common tasks - * - * - Create a tuple → {@link make} - * - Access an element by index → {@link get} - * - Select / remove elements by index → {@link pick}, {@link omit} - * - Append elements → {@link appendElement}, {@link appendElements} - * - Transform selected elements → {@link evolve} - * - Swap element positions → {@link renameIndices} - * - Map all elements with a typed lambda → {@link map}, {@link mapPick}, - * {@link mapOmit} - * - Compare tuples → {@link makeEquivalence}, {@link makeOrder} - * - Combine / reduce tuples → {@link makeCombiner}, {@link makeReducer} - * - Check tuple length at runtime → {@link isTupleOf}, - * {@link isTupleOfAtLeast} - * - * ## Gotchas - * - * - {@link pick} and {@link omit} use numeric indices, not string keys. - * - {@link renameIndices} takes an array of stringified source indices - * (e.g., `["2", "1", "0"]`), not arbitrary names. - * - {@link map}, {@link mapPick}, {@link mapOmit} require a Lambda value - * created with `Struct.lambda`; a plain function won't type-check. - * - {@link isTupleOf} and {@link isTupleOfAtLeast} only check length, not - * element types. - * - * ## Quickstart - * - * **Example** (Creating and transforming a tuple) - * - * ```ts - * import { pipe, Tuple } from "effect" - * - * const point = Tuple.make(10, 20, "red") - * - * const result = pipe( - * point, - * Tuple.evolve([ - * (x) => x * 2, - * (y) => y * 2 - * ]) - * ) - * - * console.log(result) // [20, 40, "red"] - * ``` - * - * ## See also - * - * - {@link Struct} – similar utilities for objects with named keys - * - {@link Array} – operations on variable-length arrays - * * @since 2.0.0 */ export * as Tuple from "./Tuple.ts" /** - * TxChunk is a transactional chunk data structure that provides Software Transactional Memory (STM) - * semantics for chunk operations. It uses a `TxRef>` internally to ensure all operations - * are performed atomically within transactions. - * - * Accessed values are tracked by the transaction in order to detect conflicts and to track changes. - * A transaction will retry whenever a conflict is detected or whenever the transaction explicitly - * calls `Effect.txRetry` and any of the accessed TxChunk values change. - * * @since 4.0.0 */ export * as TxChunk from "./TxChunk.ts" /** - * A transactional deferred value — a write-once cell that can be read within transactions. - * Readers retry until a value is set; once set, the value is immutable. - * * @since 4.0.0 */ export * as TxDeferred from "./TxDeferred.ts" @@ -4138,55 +657,26 @@ export * as TxHashMap from "./TxHashMap.ts" export * as TxHashSet from "./TxHashSet.ts" /** - * A transactional priority queue. Elements are dequeued in order determined by the - * provided `Order` instance. All operations participate in the STM transaction system. - * * @since 4.0.0 */ export * as TxPriorityQueue from "./TxPriorityQueue.ts" /** - * TxPubSub is a transactional publish/subscribe hub that provides Software Transactional Memory - * (STM) semantics for message broadcasting. Publishers broadcast messages to all current - * subscribers, with each subscriber receiving its own copy of every published message. - * - * Supports multiple queue strategies: bounded, unbounded, dropping, and sliding. - * * @since 4.0.0 */ export * as TxPubSub from "./TxPubSub.ts" /** - * TxQueue is a transactional queue data structure that provides Software Transactional Memory (STM) - * semantics for queue operations. It uses TxRef for transactional state management and supports - * multiple queue strategies: bounded, unbounded, dropping, and sliding. - * - * Accessed values are tracked by the transaction in order to detect conflicts and to track changes. - * A transaction will retry whenever a conflict is detected or whenever the transaction explicitly - * calls `Effect.txRetry` and any of the accessed TxQueue values change. - * * @since 4.0.0 */ export * as TxQueue from "./TxQueue.ts" /** - * TxReentrantLock is a transactional read/write lock with reentrant semantics using Software - * Transactional Memory (STM). Multiple readers can hold the lock concurrently, OR a single - * writer can hold exclusive access. A fiber holding a write lock may acquire additional - * read or write locks (reentrancy). - * * @since 4.0.0 */ export * as TxReentrantLock from "./TxReentrantLock.ts" /** - * TxRef is a transactional value, it can be read and modified within the body of a transaction. - * - * Accessed values are tracked by the transaction in order to detect conflicts and in order to - * track changes, a transaction will retry whenever a conflict is detected or whenever the - * transaction explicitely calls to `Effect.txRetry` and any of the accessed TxRef values - * change. - * * @since 4.0.0 */ export * as TxRef from "./TxRef.ts" @@ -4197,96 +687,16 @@ export * as TxRef from "./TxRef.ts" export * as TxSemaphore from "./TxSemaphore.ts" /** - * TxSubscriptionRef is a TxRef that allows subscribing to all committed changes. Subscribers - * receive the current value followed by every subsequent update via a transactional queue. - * * @since 4.0.0 */ export * as TxSubscriptionRef from "./TxSubscriptionRef.ts" /** - * Type-level utility types for TypeScript. - * - * This module provides generic type aliases used throughout the Effect - * ecosystem. Everything here is compile-time only — there are no runtime - * values. Use these types to manipulate object shapes, tagged unions, tuples, - * and variance markers at the type level. - * - * ## Mental model - * - * - **Tagged union**: a union of objects each having a discriminating - * `_tag: string` field. {@link Tags}, {@link ExtractTag}, and - * {@link ExcludeTag} operate on these. - * - **Reason**: a nested error pattern where an error has a `reason` field - * containing a tagged union of sub-errors. {@link ReasonOf}, - * {@link ReasonTags}, {@link ExtractReason}, and {@link ExcludeReason} work - * with this pattern. - * - **Variance markers**: {@link Covariant}, {@link Contravariant}, and - * {@link Invariant} are function-type aliases encoding variance for phantom - * type parameters. - * - **Simplify**: {@link Simplify} flattens intersection types (`A & B`) into - * a single object type for cleaner IDE tooltips. - * - **Concurrency**: {@link Concurrency} is a union type - * (`number | "unbounded" | "inherit"`) used across Effect APIs that accept - * concurrency options. - * - **Marker types**: {@link unassigned} and {@link unhandled} are branded - * interfaces used internally to represent missing or unhandled type - * parameters. - * - * ## Common tasks - * - * - Flatten an intersection for readability → {@link Simplify} - * - Check type equality at compile time → {@link Equals} / {@link EqualsWith} - * - Merge two object types → {@link MergeLeft} / {@link MergeRight} - * - Work with tagged unions → {@link Tags} / {@link ExtractTag} / {@link ExcludeTag} - * - Work with nested reason errors → {@link ReasonOf} / {@link ExtractReason} - * - Create fixed-length tuples → {@link TupleOf} / {@link TupleOfAtLeast} - * - Strip `readonly` modifiers → {@link Mutable} / {@link DeepMutable} - * - Encode variance in phantom types → {@link Covariant} / {@link Contravariant} / {@link Invariant} - * - Check if a type is a union → {@link IsUnion} - * - * ## Gotchas - * - * - {@link TupleOf} with a non-literal `number` (e.g. `TupleOf`) - * degrades to `Array`. - * - {@link MergeRecord} is an alias for {@link MergeLeft}; prefer - * {@link MergeLeft} or {@link MergeRight} for clarity. - * - {@link NoInfer} uses the `[A][A extends any ? 0 : never]` trick, not the - * built-in `NoInfer` from TypeScript 5.4+. - * - {@link DeepMutable} recurses into `Map`, `Set`, arrays, and objects but - * stops at primitives and functions. - * * @since 4.0.0 */ export * as Types from "./Types.ts" /** - * This module provides small, allocation-free utilities for working with values of type - * `A | undefined`, where `undefined` means "no value". - * - * Why not `Option`? - * In TypeScript, `Option` is often unnecessary. If `undefined` already models absence - * in your domain, using `A | undefined` keeps types simple, avoids extra wrappers, and - * reduces overhead. The key is that `A` itself must not include `undefined`; in this - * module `undefined` is reserved to mean "no value". - * - * When to use `A | undefined`: - * - Absence can be represented by `undefined` in your domain model. - * - You do not need to distinguish between "no value" and "value is undefined". - * - You want straightforward ergonomics and zero extra allocations. - * - * When to prefer `Option`: - * - You must distinguish `None` from `Some(undefined)` (that is, `undefined` is a valid - * payload and carries meaning on its own). - * - You need a tagged representation for serialization or pattern matching across - * boundaries where `undefined` would be ambiguous. - * - You want the richer `Option` API and are comfortable with the extra wrapper. - * - * Lawfulness note: - * All helpers treat `undefined` as absence. Do not use these utilities with payloads - * where `A` can itself be `undefined`, or you will lose information. If you need to - * carry `undefined` as a valid payload, use `Option` instead. - * * @since 4.0.0 */ export * as UndefinedOr from "./UndefinedOr.ts" @@ -4297,62 +707,6 @@ export * as UndefinedOr from "./UndefinedOr.ts" export * as Unify from "./Unify.ts" /** - * Internal utilities for the Effect ecosystem's generator-based syntax and - * higher-kinded type machinery. - * - * ## Mental model - * - * - **SingleShotGen** — an `IterableIterator` wrapper that yields its value - * exactly once. Used internally by `[Symbol.iterator]()` on Effect, Option, - * Result, and other yieldable types so they work inside generator functions. - * - **Gen** — a type-level signature for generator-based monadic composition - * (`gen` functions). Parametric over any `TypeLambda` so each module - * (Effect, Option, Result, ...) can expose its own `gen` with correct types. - * - **Variance** — a type-level marker that encodes the variance (covariant, - * contravariant, invariant) of a `TypeLambda`'s type parameters. - * Used by {@link Gen} for type inference. - * - * ## Common tasks - * - * - Make a type yieldable in generators -> implement `[Symbol.iterator]()` returning a {@link SingleShotGen} - * - Define a generator-based API for a new TypeLambda -> type it as {@link Gen}`` - * - Encode variance for a higher-kinded type -> use {@link Variance} - * - * ## Gotchas - * - * - {@link SingleShotGen} yields its value only on the first `.next()` call. - * Calling `.next()` again returns `{ done: true }`. Iterating the same - * instance twice will skip the value on the second pass; call - * `[Symbol.iterator]()` to get a fresh iterator. - * - {@link Gen} and {@link Variance} are pure type-level constructs — they - * have no runtime representation. - * - * ## Quickstart - * - * **Example** (Using SingleShotGen to make a type yieldable) - * - * ```ts - * import { Utils } from "effect" - * - * class MyWrapper { - * constructor(readonly value: A) {} - * [Symbol.iterator]() { - * return new Utils.SingleShotGen, A>(this) - * } - * } - * - * const w = new MyWrapper(42) - * const iter = w[Symbol.iterator]() - * console.log(iter.next(undefined as any)) - * // { value: MyWrapper { value: 42 }, done: false } - * console.log(iter.next(42)) - * // { value: 42, done: true } - * ``` - * - * @see {@link SingleShotGen} - * @see {@link Gen} - * @see {@link Variance} - * * @since 2.0.0 */ export * as Utils from "./Utils.ts" diff --git a/.opencode/node_modules/effect/src/internal/concurrency.ts b/.opencode/node_modules/effect/src/internal/concurrency.ts index 7820c9f45b6ea047661c621e52c4127a5c303120..480cd73a44084f730629794904fbefe70e7a2111 100644 --- a/.opencode/node_modules/effect/src/internal/concurrency.ts +++ b/.opencode/node_modules/effect/src/internal/concurrency.ts @@ -16,7 +16,7 @@ export const match = ( case "unbounded": return unbounded() case "inherit": - return effect.flatMap(CurrentConcurrency.asEffect(), (concurrency) => + return effect.flatMap(CurrentConcurrency, (concurrency) => concurrency === "unbounded" ? unbounded() : concurrency > 1 @@ -40,7 +40,7 @@ export const matchSimple = ( return concurrent() case "inherit": return effect.flatMap( - CurrentConcurrency.asEffect(), + CurrentConcurrency, (concurrency) => concurrency === "unbounded" || concurrency > 1 ? concurrent() diff --git a/.opencode/node_modules/effect/src/internal/core.ts b/.opencode/node_modules/effect/src/internal/core.ts index 456165cc0b020d189633b63b63ec65f444096d4f..f0a8c431689263b9607929e667cf2146c02b1202 100644 --- a/.opencode/node_modules/effect/src/internal/core.ts +++ b/.opencode/node_modules/effect/src/internal/core.ts @@ -95,21 +95,6 @@ export const StructuralProto = { } } -/** @internal */ -export const YieldableProto = { - [Symbol.iterator]() { - return new SingleShotGen(this) as any - } -} - -/** @internal */ -export const YieldableErrorProto = { - ...YieldableProto, - pipe() { - return pipeArguments(this, arguments) - } -} - /** @internal */ export const EffectProto = { [EffectTypeId]: effectVariance, @@ -117,9 +102,6 @@ export const EffectProto = { [Symbol.iterator]() { return new SingleShotGen(this) as any }, - asEffect(): any { - return this - }, toJSON(this: Primitive) { return { _id: "Effect", @@ -584,12 +566,18 @@ export const YieldableError: new( message?: string, options?: ErrorOptions ) => Cause.YieldableError = (function() { - class YieldableError extends globalThis.Error { - asEffect() { + class YieldableError extends globalThis.Error {} + const proto = makePrimitiveProto({ + op: "YieldableError", + [evaluate]() { return exitFail(this) } - } - Object.assign(YieldableError.prototype, YieldableErrorProto) + }) + delete (proto as any).toString + Object.assign( + YieldableError.prototype, + proto + ) return YieldableError as any })() @@ -603,13 +591,14 @@ export const Error: new = {}>( super(args?.message, args?.cause ? { cause: args.cause } : undefined) if (args) { Object.assign(this, args) + // @effect-diagnostics-next-line floatingEffect:off Object.defineProperty(this, plainArgsSymbol, { value: args, enumerable: false }) } } - toJSON() { + override toJSON() { return { ...(this as any)[plainArgsSymbol], ...this } } } as any diff --git a/.opencode/node_modules/effect/src/internal/effect.ts b/.opencode/node_modules/effect/src/internal/effect.ts index 35bb3cf8dcf61974ba3581717175c9696c6f5826..157ae54898c4d72e32c1581ad7de1dabcf62432a 100644 --- a/.opencode/node_modules/effect/src/internal/effect.ts +++ b/.opencode/node_modules/effect/src/internal/effect.ts @@ -892,15 +892,16 @@ export const suspend: ( }) /** @internal */ -export const fromYieldable = ( - yieldable: Effect.Yieldable -): Effect.Effect => yieldable.asEffect() - -/** @internal */ -export const fromOption: (option: Option.Option) => Effect.Effect = fromYieldable +export const fromOption: (option: Option.Option) => Effect.Effect = Option.match({ + onNone: () => fail(new NoSuchElementError("Effect.fromOption: Option.none")), + onSome: succeed +}) /** @internal */ -export const fromResult: (result: Result.Result) => Effect.Effect = fromYieldable +export const fromResult: (result: Result.Result) => Effect.Effect = Result.match({ + onFailure: fail, + onSuccess: succeed +}) /** @internal */ export const fromNullishOr = (value: A): Effect.Effect, Cause.NoSuchElementError> => @@ -1083,7 +1084,7 @@ export const never: Effect.Effect = callback(constVoid) /** @internal */ export const gen = < Self, - Eff extends Effect.Yieldable, + Eff extends Effect.Effect, AEff >( ...args: @@ -1092,10 +1093,10 @@ export const gen = < ): Effect.Effect< AEff, [Eff] extends [never] ? never - : [Eff] extends [Effect.Yieldable] ? E + : [Eff] extends [Effect.Effect] ? E : never, [Eff] extends [never] ? never - : [Eff] extends [Effect.Yieldable] ? R + : [Eff] extends [Effect.Effect] ? R : never > => suspend(() => @@ -1223,7 +1224,7 @@ export const fnUntracedEager: Effect.fn.Untraced = ( ) const fromIteratorEagerUnsafe = ( - evaluate: () => Iterator> + evaluate: () => Iterator> ): Effect.Effect => { try { const iterator = evaluate() @@ -1237,22 +1238,20 @@ const fromIteratorEagerUnsafe = ( return succeed(state.value) } - const yieldable = state.value - const effect = yieldable.asEffect() - const primitive = effect as any + const primitive = state.value as any if (primitive && primitive._tag === "Success") { value = primitive.value continue } else if (primitive && primitive._tag === "Failure") { - return effect + return state.value } else { let isFirstExecution = true return suspend(() => { if (isFirstExecution) { isFirstExecution = false - return flatMap(effect, (value) => fromIteratorUnsafe(iterator, value)) + return flatMap(state.value, (value) => fromIteratorUnsafe(iterator, value)) } else { return suspend(() => fromIteratorUnsafe(evaluate())) } @@ -1265,7 +1264,7 @@ const fromIteratorEagerUnsafe = ( } const fromIteratorUnsafe: ( - iterator: Iterator>, + iterator: Iterator>, initial?: undefined ) => Effect.Effect = makePrimitive({ op: "Iterator", @@ -1275,14 +1274,13 @@ const fromIteratorUnsafe: ( while (true) { const state = iter.next(value) if (state.done) return succeed(state.value) - const eff = state.value.asEffect() - if (!effectIsExit(eff)) { + if (!effectIsExit(state.value)) { fiber._stack.push(this) - return eff - } else if (eff._tag === "Failure") { - return eff + return state.value + } else if (state.value._tag === "Failure") { + return state.value } - value = eff.value + value = state.value.value } }, [evaluate](this: any, fiber: FiberImpl) { @@ -1968,9 +1966,7 @@ export const exitFindErrorOption = (self: Exit.Exit): Option.Option< // ---------------------------------------------------------------------------- /** @internal */ -export const service: { - (service: Context.Key): Effect.Effect -} = fromYieldable as any +export const service = (service: Context.Key): Effect.Effect => service /** @internal */ export const serviceOption = ( @@ -2647,28 +2643,40 @@ export const tapDefect: { /** @internal */ export const catchIf: { - , R3 = never>( + ( refinement: Predicate.Refinement, EB>, f: (e: EB) => Effect.Effect, orElse?: ((e: Exclude) => Effect.Effect) | undefined - ): (self: Effect.Effect) => Effect.Effect - ( + ): ( + self: Effect.Effect + ) => Effect.Effect< + A | A2 | Exclude, + E2 | E3 | (A3 extends unassigned ? Exclude : never), + R | R2 | R3 + > + ( predicate: Predicate.Predicate>, f: (e: NoInfer) => Effect.Effect, orElse?: ((e: NoInfer) => Effect.Effect) | undefined - ): (self: Effect.Effect) => Effect.Effect - , R3 = never>( + ): ( + self: Effect.Effect + ) => Effect.Effect, E2 | E3 | (A3 extends unassigned ? E : never), R | R2 | R3> + ( self: Effect.Effect, refinement: Predicate.Refinement, f: (e: EB) => Effect.Effect, orElse?: ((e: Exclude) => Effect.Effect) | undefined - ): Effect.Effect - ( + ): Effect.Effect< + A | A2 | Exclude, + E2 | E3 | (A3 extends unassigned ? Exclude : never), + R | R2 | R3 + > + ( self: Effect.Effect, predicate: Predicate.Predicate, f: (e: E) => Effect.Effect, orElse?: ((e: E) => Effect.Effect) | undefined - ): Effect.Effect + ): Effect.Effect, E2 | E3 | (A3 extends unassigned ? E : never), R | R2 | R3> } = dual( (args) => isEffect(args[0]), ( @@ -2689,17 +2697,19 @@ export const catchIf: { /** @internal */ export const catchFilter: { - ( + ( filter: Filter.Filter, EB, X>, f: (e: EB) => Effect.Effect, orElse?: ((e: X) => Effect.Effect) | undefined - ): (self: Effect.Effect) => Effect.Effect - ( + ): ( + self: Effect.Effect + ) => Effect.Effect, E2 | E3 | (A3 extends unassigned ? X : never), R | R2 | R3> + ( self: Effect.Effect, filter: Filter.Filter, EB, X>, f: (e: EB) => Effect.Effect, orElse?: ((e: X) => Effect.Effect) | undefined - ): Effect.Effect + ): Effect.Effect, E2 | E3 | (A3 extends unassigned ? X : never), R | R2 | R3> } = dual( (args) => isEffect(args[0]), ( @@ -2727,8 +2737,8 @@ export const catchTag: { A1, E1, R1, - A2 = never, - E2 = ExcludeTag ? K[number] : K>, + A2 = unassigned, + E2 = never, R2 = never >( k: K, @@ -2740,7 +2750,13 @@ export const catchTag: { | undefined ): ( self: Effect.Effect - ) => Effect.Effect + ) => Effect.Effect< + A | A1 | Exclude, + | E1 + | E2 + | (A2 extends unassigned ? ExcludeTag ? K[number] : K> : never), + R | R1 | R2 + > < A, E, @@ -2749,8 +2765,8 @@ export const catchTag: { R1, E1, A1, - A2 = never, - E2 = ExcludeTag ? K[number] : K>, + A2 = unassigned, + E2 = never, R2 = never >( self: Effect.Effect, @@ -2759,7 +2775,13 @@ export const catchTag: { orElse?: | ((e: ExcludeTag ? K[number] : K>) => Effect.Effect) | undefined - ): Effect.Effect + ): Effect.Effect< + A | A1 | Exclude, + | E1 + | E2 + | (A2 extends unassigned ? ExcludeTag ? K[number] : K> : never), + R | R1 | R2 + > } = dual( (args) => isEffect(args[0]), < @@ -2796,19 +2818,20 @@ export const catchTags: { [K in E["_tag"]]+?: (error: Extract) => Effect.Effect } : {}), - A2 = never, - E2 = Exclude, + A2 = unassigned, + E2 = never, R2 = never >( cases: Cases, orElse?: ((e: Exclude) => Effect.Effect) | undefined ): (self: Effect.Effect) => Effect.Effect< | A - | A2 + | Exclude | { [K in keyof Cases]: Cases[K] extends ((...args: Array) => Effect.Effect) ? A : never }[keyof Cases], | E2 + | (A2 extends unassigned ? Exclude : never) | { [K in keyof Cases]: Cases[K] extends ((...args: Array) => Effect.Effect) ? E : never }[keyof Cases], @@ -2826,8 +2849,8 @@ export const catchTags: { [K in E["_tag"]]+?: (error: Extract) => Effect.Effect } : {}), - A2 = never, - E2 = Exclude, + A2 = unassigned, + E2 = never, R2 = never >( self: Effect.Effect, @@ -2835,11 +2858,12 @@ export const catchTags: { orElse?: ((e: Exclude) => Effect.Effect) | undefined ): Effect.Effect< | A - | A2 + | Exclude | { [K in keyof Cases]: Cases[K] extends ((...args: Array) => Effect.Effect) ? A : never }[keyof Cases], | E2 + | (A2 extends unassigned ? Exclude : never) | { [K in keyof Cases]: Cases[K] extends ((...args: Array) => Effect.Effect) ? E : never }[keyof Cases], @@ -2893,7 +2917,7 @@ export const catchReason: { self: Effect.Effect ) => Effect.Effect< A | A2 | Exclude, - (A3 extends unassigned ? E : ExcludeTag) | E2 | E3, + ExcludeTag | E2 | E3 | (A3 extends unassigned ? ExtractTag : never), R | R2 | R3 > < @@ -2924,7 +2948,7 @@ export const catchReason: { | undefined ): Effect.Effect< A | A2 | Exclude, - (A3 extends unassigned ? E : ExcludeTag) | E2 | E3, + ExcludeTag | E2 | E3 | (A3 extends unassigned ? ExtractTag : never), R | R2 | R3 > } = dual( @@ -2954,7 +2978,7 @@ export const catchReason: { | undefined ): Effect.Effect< A | A2 | Exclude, - (A3 extends unassigned ? E : ExcludeTag) | E2 | E3, + ExcludeTag | E2 | E3 | (A3 extends unassigned ? ExtractTag : never), R | R2 | R3 > => catchIf( @@ -2997,8 +3021,9 @@ export const catchReasons: { | { [RK in keyof Cases]: Cases[RK] extends (...args: Array) => Effect.Effect ? A : never }[ keyof Cases ], - | (A2 extends unassigned ? E : ExcludeTag) + | ExcludeTag | E2 + | (A2 extends unassigned ? ExtractTag : never) | { [RK in keyof Cases]: Cases[RK] extends (...args: Array) => Effect.Effect ? E : never }[ keyof Cases ], @@ -3038,8 +3063,9 @@ export const catchReasons: { | { [RK in keyof Cases]: Cases[RK] extends (...args: Array) => Effect.Effect ? A : never }[ keyof Cases ], - | (A2 extends unassigned ? E : ExcludeTag) + | ExcludeTag | E2 + | (A2 extends unassigned ? ExtractTag : never) | { [RK in keyof Cases]: Cases[RK] extends (...args: Array) => Effect.Effect ? E : never }[ keyof Cases ], @@ -3767,7 +3793,7 @@ export const scopeMake = (finalizerStrategy?: "sequential" | "parallel"): Effect sync(() => scopeMakeUnsafe(finalizerStrategy)) /** @internal */ -export const scope: Effect.Effect = scopeTag.asEffect() +export const scope: Effect.Effect = scopeTag /** @internal */ export const provideScope: { @@ -5570,10 +5596,10 @@ const provideSpanStackFrame = (name: string, stack: (() => string | undefined) | } /** @internal */ -export const spanAnnotations: Effect.Effect>> = TracerSpanAnnotations.asEffect() +export const spanAnnotations: Effect.Effect>> = TracerSpanAnnotations /** @internal */ -export const spanLinks: Effect.Effect> = TracerSpanLinks.asEffect() +export const spanLinks: Effect.Effect> = TracerSpanLinks /** @internal */ export const linkSpans: { @@ -6142,20 +6168,21 @@ const defaultDateFormat = (date: Date): string => date.getSeconds().toString().padStart(2, "0") }.${date.getMilliseconds().toString().padStart(3, "0")}` -const hasProcessStdout = typeof process === "object" && - process !== null && - typeof process.stdout === "object" && - process.stdout !== null -const processStdoutIsTTY = hasProcessStdout && - process.stdout.isTTY === true -const hasProcessStdoutOrDeno = hasProcessStdout || "Deno" in globalThis - /** @internal */ export const consolePretty = (options?: { readonly colors?: "auto" | boolean | undefined readonly formatDate?: ((date: Date) => string) | undefined readonly mode?: "browser" | "tty" | "auto" | undefined }) => { + // evaluated lazily so the module-level bundle stays free of `process` + // property accesses, which bundlers must retain as possible side effects + const hasProcessStdout = typeof process === "object" && + process !== null && + typeof process.stdout === "object" && + process.stdout !== null + const processStdoutIsTTY = hasProcessStdout && + process.stdout.isTTY === true + const hasProcessStdoutOrDeno = hasProcessStdout || "Deno" in globalThis const mode_ = options?.mode ?? "auto" const mode = mode_ === "auto" ? (hasProcessStdoutOrDeno ? "tty" : "browser") : mode_ const isBrowser = mode === "browser" diff --git a/.opencode/node_modules/effect/src/internal/executionPlan.ts b/.opencode/node_modules/effect/src/internal/executionPlan.ts index a103936f97ffa1eef0726a8b62d7e3bc11fb3da6..2ae8498b52b0ad65c6bfee301fbb8a6cc8d32065 100644 --- a/.opencode/node_modules/effect/src/internal/executionPlan.ts +++ b/.opencode/node_modules/effect/src/internal/executionPlan.ts @@ -73,7 +73,7 @@ export const withExecutionPlan: { nextEffect = effect.suspend(() => { if (attempted) return wrapped attempted = true - return result!.asEffect() + return effect.fromResult(result!) }) nextEffect = internalSchedule.retry(nextEffect, scheduleFromStep(step, false)!) } else { @@ -87,7 +87,7 @@ export const withExecutionPlan: { i++ } }), - () => result!.asEffect() + () => effect.fromResult(result!) ) })) diff --git a/.opencode/node_modules/effect/src/internal/option.ts b/.opencode/node_modules/effect/src/internal/option.ts index d03495e9e6e9ae751b8ed358151a623d6b2b8a55..34bae0722998c3d59bd06f7e26e8c509896126ba 100644 --- a/.opencode/node_modules/effect/src/internal/option.ts +++ b/.opencode/node_modules/effect/src/internal/option.ts @@ -7,7 +7,8 @@ import * as Hash from "../Hash.ts" import { toJson } from "../Inspectable.ts" import type * as Option from "../Option.ts" import { hasProperty } from "../Predicate.ts" -import { exitFail, exitSucceed, NoSuchElementError, PipeInspectableProto, YieldableProto } from "./core.ts" +import { SingleShotGen } from "../Utils.ts" +import { PipeInspectableProto } from "./core.ts" const TypeId = "~effect/data/Option" @@ -16,40 +17,44 @@ const CommonProto = { _A: (_: never) => _ }, ...PipeInspectableProto, - ...YieldableProto + [Symbol.iterator]() { + return new SingleShotGen(this) + } } -const SomeProto = Object.assign(Object.create(CommonProto), { - _tag: "Some", - _op: "Some", - [Equal.symbol](this: Option.Some, that: unknown): boolean { - return ( - isOption(that) && isSome(that) && Equal.equals(this.value, that.value) - ) - }, - [Hash.symbol](this: Option.Some) { - return Hash.combine(Hash.hash(this._tag))(Hash.hash(this.value)) - }, - toString(this: Option.Some) { - return `some(${format(this.value)})` - }, - toJSON(this: Option.Some) { - return { - _id: "Option", - _tag: this._tag, - value: toJson(this.value) +// `valueOrUndefined` is folded into the initializer (rather than a separate +// `Object.defineProperty(SomeProto, ...)` statement) so the whole definition +// is pure-annotated by the build and tree-shakable. +const SomeProto = Object.defineProperty( + Object.assign(Object.create(CommonProto), { + _tag: "Some", + _op: "Some", + [Equal.symbol](this: Option.Some, that: unknown): boolean { + return ( + isOption(that) && isSome(that) && Equal.equals(this.value, that.value) + ) + }, + [Hash.symbol](this: Option.Some) { + return Hash.combine(Hash.hash(this._tag))(Hash.hash(this.value)) + }, + toString(this: Option.Some) { + return `some(${format(this.value)})` + }, + toJSON(this: Option.Some) { + return { + _id: "Option", + _tag: this._tag, + value: toJson(this.value) + } + } + }), + "valueOrUndefined", + { + get() { + return this.value } - }, - asEffect(this: Option.Some) { - return exitSucceed(this.value) - } -}) - -Object.defineProperty(SomeProto, "valueOrUndefined", { - get() { - return this.value } -}) +) const NoneHash = Hash.hash("None") const NoneProto = Object.assign(Object.create(CommonProto), { @@ -70,9 +75,6 @@ const NoneProto = Object.assign(Object.create(CommonProto), { _id: "Option", _tag: this._tag } - }, - asEffect(this: Option.None) { - return exitFail(new NoSuchElementError()) } }) diff --git a/.opencode/node_modules/effect/src/internal/request.ts b/.opencode/node_modules/effect/src/internal/request.ts index 9521a0c9d91cf8103285231c58e46aa797f81962..6c7d17993cbb7728c6d5c5d138e45fdeb08f2e5b 100644 --- a/.opencode/node_modules/effect/src/internal/request.ts +++ b/.opencode/node_modules/effect/src/internal/request.ts @@ -79,7 +79,7 @@ interface Batch { } const batchPool: Array = [] -const pendingBatches = new Map, Map>() +const pendingBatches = new WeakMap, Map>() const addEntry = ( resolver: RequestResolver, @@ -150,6 +150,8 @@ const addEntry = ( newBatch.entrySet.clear() newBatch.key = undefined newBatch.fiber = undefined + newBatch.resolver = undefined as any + newBatch.map = undefined as any batchPool.push(newBatch) } return effect.void diff --git a/.opencode/node_modules/effect/src/internal/result.ts b/.opencode/node_modules/effect/src/internal/result.ts index c57de61bb7ae34069c84a133851b22fe09e6ea36..1c75fec189c7729a07b3e4a93e9ea6992c070893 100644 --- a/.opencode/node_modules/effect/src/internal/result.ts +++ b/.opencode/node_modules/effect/src/internal/result.ts @@ -6,7 +6,8 @@ import { toJson } from "../Inspectable.ts" import type { Option } from "../Option.ts" import { hasProperty } from "../Predicate.ts" import type * as Result from "../Result.ts" -import { exitFail, exitSucceed, PipeInspectableProto, YieldableProto } from "./core.ts" +import { SingleShotGen } from "../Utils.ts" +import { PipeInspectableProto } from "./core.ts" import * as option from "./option.ts" const TypeId = "~effect/data/Result" @@ -18,7 +19,9 @@ const CommonProto = { _E: (_: never) => _ }, ...PipeInspectableProto, - ...YieldableProto + [Symbol.iterator]() { + return new SingleShotGen(this) + } } const SuccessProto = Object.assign(Object.create(CommonProto), { @@ -41,9 +44,6 @@ const SuccessProto = Object.assign(Object.create(CommonProto), { _tag: this._tag, value: toJson(this.success) } - }, - asEffect(this: Result.Success) { - return exitSucceed(this.success) } }) @@ -65,9 +65,6 @@ const FailureProto = Object.assign(Object.create(CommonProto), { _tag: this._tag, failure: toJson(this.failure) } - }, - asEffect(this: Result.Failure) { - return exitFail(this.failure) } }) diff --git a/.opencode/node_modules/effect/src/internal/schema/annotations.ts b/.opencode/node_modules/effect/src/internal/schema/annotations.ts index a147066fe326b3a8738fc67e5f2e27aaeebd1481..174494ae6035dc4d1efbc9f68aced1e6c7ad2311 100644 --- a/.opencode/node_modules/effect/src/internal/schema/annotations.ts +++ b/.opencode/node_modules/effect/src/internal/schema/annotations.ts @@ -1,15 +1,15 @@ import { memoize } from "../../Function.ts" import type * as Schema from "../../Schema.ts" -import type * as AST from "../../SchemaAST.ts" +import type * as SchemaAST from "../../SchemaAST.ts" /** @internal */ -export function resolve(ast: AST.AST): Schema.Annotations.Annotations | undefined { +export function resolve(ast: SchemaAST.AST): Schema.Annotations.Annotations | undefined { return ast.checks ? ast.checks[ast.checks.length - 1].annotations : ast.annotations } /** @internal */ export function resolveAt(key: string) { - return (ast: AST.AST): A | undefined => resolve(ast)?.[key] as A | undefined + return (ast: SchemaAST.AST): A | undefined => resolve(ast)?.[key] as A | undefined } /** @internal */ @@ -25,7 +25,7 @@ export const resolveDescription = resolveAt("description") export const resolveBrands = resolveAt>("brands") /** @internal */ -export const getExpected = memoize((ast: AST.AST): string => { +export const getExpected = memoize((ast: SchemaAST.AST): string => { const identifier = resolveIdentifier(ast) if (typeof identifier === "string") return identifier return ast.getExpected(getExpected) diff --git a/.opencode/node_modules/effect/src/internal/schema/arbitrary.ts b/.opencode/node_modules/effect/src/internal/schema/arbitrary.ts index ac68b42097dcaae383c087840939cfdf8b2f2346..269adfaedf4c42a096d1e0b0c1c57c815d927ad1 100644 --- a/.opencode/node_modules/effect/src/internal/schema/arbitrary.ts +++ b/.opencode/node_modules/effect/src/internal/schema/arbitrary.ts @@ -1,46 +1,122 @@ import * as Array from "../../Array.ts" import * as Boolean from "../../Boolean.ts" import type * as Combiner from "../../Combiner.ts" +import * as Equal from "../../Equal.ts" import { memoize } from "../../Function.ts" import * as Number from "../../Number.ts" import * as Option from "../../Option.ts" +import * as Order from "../../Order.ts" import * as Predicate from "../../Predicate.ts" import type * as Schema from "../../Schema.ts" -import * as AST from "../../SchemaAST.ts" +import * as SchemaAST from "../../SchemaAST.ts" import * as Struct from "../../Struct.ts" import type * as FastCheck from "../../testing/FastCheck.ts" import * as UndefinedOr from "../../UndefinedOr.ts" import { errorWithPath } from "../errors.ts" import * as InternalAnnotations from "./annotations.ts" -const arbitraryMemoMap = new WeakMap>() +const arbitraryMemoMap = new WeakMap>() +const suspendDepthIdentifierMap = new WeakMap() +const emptyRecursionStack: RecursionStack = [] -function applyChecks(ast: AST.AST, filters: Array>, arbitrary: FastCheck.Arbitrary) { - return filters.map((filter) => (a: any) => filter.run(a, ast, AST.defaultParseOptions) === undefined).reduce( - (acc, filter) => acc.filter(filter), +type RecursionStack = ReadonlyArray + +type Context = Schema.Annotations.ToArbitrary.Context +type Constraint = Schema.Annotations.ToArbitrary.Constraint +type OrderedConstraint = Schema.Annotations.ToArbitrary.OrderedConstraint +type ArbitraryFilter = Schema.Annotations.ToArbitrary.Filter + +type Lazy = (fc: typeof FastCheck, ctx: Context, recursionStack: RecursionStack) => FastCheck.Arbitrary +type LazyOption = ( + fc: typeof FastCheck, + ctx: Context, + recursionStack: RecursionStack +) => FastCheck.Arbitrary | undefined + +export interface MutableReport { + readonly warnings: Array +} + +/** @internal */ +export function makeReport(): MutableReport { + return { warnings: [] } +} + +/** @internal */ +export function toReport(report: MutableReport): Schema.Annotations.ToArbitrary.Report { + return { warnings: report.warnings.slice() } +} + +function arbitraryError(what: string) { + return new Error(`Unable to derive an arbitrary for ${what}`) +} + +const entryComparator = ([a]: readonly [any, any], [b]: readonly [any, any]) => Equal.equals(a, b) + +function applyChecks(ast: SchemaAST.AST, filters: Array>, arbitrary: FastCheck.Arbitrary) { + return filters.reduce( + (acc, filter) => acc.filter((a) => filter.run(a, ast, SchemaAST.defaultParseOptions) === undefined), arbitrary ) } -function isUniqueArrayConstraintsCustomCompare( - constraint: Schema.Annotations.ToArbitrary.ArrayConstraints | undefined -): constraint is Schema.Annotations.ToArbitrary.ArrayConstraints & FastCheck.UniqueArrayConstraintsCustomCompare { - return constraint?.comparator !== undefined +function validateArrayConstraints(constraint: FastCheck.ArrayConstraints | undefined, label: string) { + if ( + constraint?.minLength !== undefined && constraint.maxLength !== undefined && + constraint.minLength > constraint.maxLength + ) { + throw arbitraryError(`${label} constraints`) + } } -function array(fc: typeof FastCheck, ctx: Schema.Annotations.ToArbitrary.Context, item: FastCheck.Arbitrary) { - const constraint = ctx.constraints?.array - const out = isUniqueArrayConstraintsCustomCompare(constraint) - ? fc.uniqueArray(item, constraint) +function lengthToFastCheckConstraints( + constraint: { readonly minLength?: number | undefined; readonly maxLength?: number | undefined } | undefined +) { + return constraint === undefined || (constraint.minLength === undefined && constraint.maxLength === undefined) + ? undefined + : { + ...(constraint.minLength !== undefined ? { minLength: constraint.minLength } : {}), + ...(constraint.maxLength !== undefined ? { maxLength: constraint.maxLength } : {}) + } +} + +function arrayWithConstraints( + fc: typeof FastCheck, + item: FastCheck.Arbitrary, + constraint: FastCheck.ArrayConstraints | undefined, + comparator?: ((a: any, b: any) => boolean) | undefined +) { + return comparator + ? fc.uniqueArray(item, { ...constraint, comparator }) : fc.array(item, constraint) - if (ctx.isSuspend) { - return fc.oneof( - { maxDepth: 2, depthIdentifier: "" }, - fc.constant([]), - out - ) - } - return out +} + +function array(fc: typeof FastCheck, ctx: Context, item: FastCheck.Arbitrary, terminal = false) { + const constraint = ctx.constraint + const arrayConstraints = lengthToFastCheckConstraints(constraint) + validateArrayConstraints(arrayConstraints, "array") + return arrayWithConstraints( + fc, + item, + terminal ? { ...arrayConstraints, maxLength: arrayConstraints?.minLength ?? 0 } : arrayConstraints, + constraint?.unique ? Equal.equals : undefined + ) +} + +function appendArray( + fc: typeof FastCheck, + out: FastCheck.Arbitrary>, + len: number, + rest: FastCheck.Arbitrary> +) { + return out.chain((as) => as.length < len ? fc.constant(as) : rest.map((rest) => [...as, ...rest])) +} + +function appendObjectEntries( + out: FastCheck.Arbitrary, + entries: FastCheck.Arbitrary> +) { + return out.chain((o) => entries.map((entries) => ({ ...Object.fromEntries(entries), ...o }))) } const max = UndefinedOr.makeReducer(Number.ReducerMax) @@ -49,262 +125,766 @@ const or = UndefinedOr.makeReducer(Boolean.ReducerOr) const concat = UndefinedOr.makeReducer(Array.makeReducerConcat()) const combiner: Combiner.Combiner = Struct.makeCombiner({ - isInteger: or, - max: min, - maxExcluded: or, + integer: or, maxLength: min, - min: max, - minExcluded: or, minLength: max, - noDefaultInfinity: or, - noInteger: or, - noInvalidDate: or, + noInfinity: or, noNaN: or, patterns: concat, - comparator: or + unique: or, + valid: or }, { omitKeyWhen: Predicate.isUndefined }) -type FastCheckConstraint = - | Schema.Annotations.ToArbitrary.StringConstraints - | Schema.Annotations.ToArbitrary.NumberConstraints - | Schema.Annotations.ToArbitrary.BigIntConstraints - | Schema.Annotations.ToArbitrary.ArrayConstraints - | Schema.Annotations.ToArbitrary.DateConstraints - -function merge( - _tag: "string" | "number" | "bigint" | "array" | "date", - constraints: Schema.Annotations.ToArbitrary.Constraint, - constraint: FastCheckConstraint -): Schema.Annotations.ToArbitrary.Constraint { - const c = constraints[_tag] +function mergeOrderedBound( + order: Order.Order, + self: T | undefined, + selfExclusive: boolean | undefined, + that: T | undefined, + thatExclusive: boolean | undefined, + takeComparison: -1 | 1 +): readonly [T | undefined, boolean | undefined] { + if (that === undefined || self === undefined) { + return that === undefined ? [self, selfExclusive] : [that, thatExclusive] + } + const comparison = order(self, that) + return comparison === takeComparison + ? [that, thatExclusive] + : comparison === 0 + ? [self, selfExclusive || thatExclusive] + : [self, selfExclusive] +} + +function mergeOrderedConstraints(self: OrderedConstraint | undefined, that: OrderedConstraint) { + if (self === undefined) { + return that + } + if (self.order !== that.order) { + throw new Error("Cannot merge ordered arbitrary constraints with different Order instances") + } + + const [minimum, exclusiveMinimum] = mergeOrderedBound( + self.order, + self.minimum, + self.exclusiveMinimum, + that.minimum, + that.exclusiveMinimum, + -1 + ) + const [maximum, exclusiveMaximum] = mergeOrderedBound( + self.order, + self.maximum, + self.exclusiveMaximum, + that.maximum, + that.exclusiveMaximum, + 1 + ) + return { - ...constraints, - [_tag]: c ? combiner.combine(c, constraint) : constraint + order: self.order, + ...(minimum !== undefined ? { minimum } : {}), + ...(exclusiveMinimum !== undefined ? { exclusiveMinimum } : {}), + ...(maximum !== undefined ? { maximum } : {}), + ...(exclusiveMaximum !== undefined ? { exclusiveMaximum } : {}) } } -const constraintsKeys = { - string: null, - number: null, - bigint: null, - array: null, - date: null +function mergeConstraint(self: Constraint | undefined, that: Constraint): Constraint { + const { ordered: selfOrdered, ...selfRest } = self ?? {} + const { ordered: thatOrdered, ...thatRest } = that + const ordered = thatOrdered === undefined + ? selfOrdered + : mergeOrderedConstraints(selfOrdered, thatOrdered) + const out = combiner.combine(selfRest, thatRest) + return { + ...out, + ...(ordered === undefined ? {} : { ordered }) + } } -function isConstraintKey(key: string): key is keyof Schema.Annotations.ToArbitrary.Constraint { - return key in constraintsKeys +function collectChecks(checks: SchemaAST.Checks | undefined) { + const filters: Array> = [] + const arbitraries: Array = [] + function visit(check: SchemaAST.Check) { + if (check.annotations?.arbitrary) { + arbitraries.push(check.annotations.arbitrary) + } + if (check._tag !== "Filter") { + for (const child of check.checks) { + visit(child) + } + } else { + filters.push(check) + } + } + checks?.forEach(visit) + return { filters, arbitraries } } -/** @internal */ -export function constraintContext( - filters: Array> -): (ctx: Schema.Annotations.ToArbitrary.Context) => Schema.Annotations.ToArbitrary.Context { - const annotations = filters.map((filter) => filter.annotations?.toArbitraryConstraint).filter( - Predicate.isNotUndefined - ) +function constraintContext(arbitraries: Array): (ctx: Context) => Context { + const constraintAnnotations = arbitraries.map(({ constraint }) => constraint).filter(Predicate.isNotUndefined) return (ctx) => { - const constraints = annotations.reduce((acc: Schema.Annotations.ToArbitrary.Constraint, c) => { - const keys = Object.keys(c) - for (const key of keys) { - if (isConstraintKey(key)) { - acc = merge(key, acc, c[key]!) - } + const constraint = constraintAnnotations.reduce( + (acc: Constraint | undefined, c) => mergeConstraint(acc, c), + ctx.constraint + ) + return { ...ctx, constraint } + } +} + +function resetContext(ctx: Context) { + return { ...ctx, constraint: undefined } +} + +function objectEntriesConstraints(ast: SchemaAST.Objects, constraint: Constraint | undefined, requiredKeys: number) { + if (constraint === undefined || (constraint.minLength === undefined && constraint.maxLength === undefined)) { + return undefined + } + if ( + constraint.minLength !== undefined && + ast.indexSignatures.length === 0 && + constraint.minLength > ast.propertySignatures.length + ) { + throw arbitraryError("object property constraints") + } + const out: FastCheck.ArrayConstraints = {} + if (constraint.minLength !== undefined) { + out.minLength = Math.max(0, constraint.minLength - requiredKeys) + } + if (constraint.maxLength !== undefined) { + out.maxLength = constraint.maxLength - requiredKeys + if (out.maxLength < 0) { + throw arbitraryError("object property constraints") + } + } + validateArrayConstraints(out, "object property") + return out +} + +function objectWithOptionalCount( + fc: typeof FastCheck, + pss: Record>, + orderedNames: ReadonlyArray, + requiredKeys: ReadonlyArray, + optionalNames: ReadonlyArray, + constraint: Constraint +) { + const requiredCount = requiredKeys.length + if (constraint.maxLength !== undefined && constraint.maxLength < requiredCount) { + throw arbitraryError("object property constraints") + } + const minOptional = constraint.minLength === undefined ? 0 : Math.max(0, constraint.minLength - requiredCount) + const maxOptional = constraint.maxLength === undefined + ? optionalNames.length + : Math.min(optionalNames.length, constraint.maxLength - requiredCount) + if (minOptional > maxOptional) { + throw arbitraryError("object property constraints") + } + const full = fc.record(pss, { requiredKeys: [...requiredKeys, ...optionalNames] }) + const chosen = fc.shuffledSubarray([...optionalNames], { minLength: minOptional, maxLength: maxOptional }) + return fc.tuple(full, chosen).map(([base, names]) => { + const keep = new Set([...requiredKeys, ...names]) + const out: Record = {} + for (const name of orderedNames) { + if (keep.has(name)) { + out[name] = base[name] } - return acc - }, ctx.constraints || {}) - return { ...ctx, constraints } + } + return out + }) +} + +function toRangeConstraints( + ordered: OrderedConstraint | undefined, + min: (value: T, excluded: boolean) => T, + max: (value: T, excluded: boolean) => T, + error: string +) { + const out: { min?: T; max?: T } = {} + if (ordered?.minimum !== undefined) { + out.min = min(ordered.minimum as T, ordered.exclusiveMinimum === true) } + if (ordered?.maximum !== undefined) { + out.max = max(ordered.maximum as T, ordered.exclusiveMaximum === true) + } + if (out.min !== undefined && out.max !== undefined && out.min > out.max) { + throw arbitraryError(error) + } + return out } -function resetContext(ctx: Schema.Annotations.ToArbitrary.Context): Schema.Annotations.ToArbitrary.Context { - return { ...ctx, constraints: undefined } +function toIntegerConstraints(ordered: OrderedConstraint | undefined) { + return toRangeConstraints( + ordered, + (minimum, excluded) => excluded ? Math.floor(minimum) + 1 : Math.ceil(minimum), + (maximum, excluded) => excluded ? Math.ceil(maximum) - 1 : Math.floor(maximum), + "integer constraints" + ) +} + +function toFloatConstraints(constraint: Constraint | undefined, ordered: OrderedConstraint | undefined) { + const out: FastCheck.FloatConstraints = { + ...(constraint?.noInfinity ? { noDefaultInfinity: true } : {}), + ...(constraint?.noNaN ? { noNaN: true } : {}), + ...(ordered?.minimum !== undefined ? { min: ordered.minimum as number } : {}), + ...(ordered?.exclusiveMinimum !== undefined ? { minExcluded: ordered.exclusiveMinimum } : {}), + ...(ordered?.maximum !== undefined ? { max: ordered.maximum as number } : {}), + ...(ordered?.exclusiveMaximum !== undefined ? { maxExcluded: ordered.exclusiveMaximum } : {}) + } + if ( + out.min !== undefined && + out.max !== undefined && + (out.min > out.max || (out.min === out.max && (out.minExcluded || out.maxExcluded))) + ) { + throw arbitraryError("number constraints") + } + return out +} + +function toBigIntConstraints(ordered: OrderedConstraint | undefined) { + return toRangeConstraints( + ordered, + (minimum, excluded) => excluded ? minimum + BigInt(1) : minimum, + (maximum, excluded) => excluded ? maximum - BigInt(1) : maximum, + "the ordered bigint constraints" + ) } interface LazyArbitraryWithContext { - (fc: typeof FastCheck, ctx: Schema.Annotations.ToArbitrary.Context): FastCheck.Arbitrary + (fc: typeof FastCheck, ctx: Context, recursionStack?: RecursionStack): FastCheck.Arbitrary + readonly terminal: ( + fc: typeof FastCheck, + ctx: Context, + recursionStack?: RecursionStack + ) => FastCheck.Arbitrary | undefined +} + +function makeLazy(normal: Lazy, terminal: LazyOption): LazyArbitraryWithContext { + const out = + ((fc, ctx, recursionStack = emptyRecursionStack) => normal(fc, ctx, recursionStack)) as LazyArbitraryWithContext + ;(out as { terminal: LazyOption }).terminal = (fc, ctx, recursionStack = emptyRecursionStack) => + terminal(fc, ctx, recursionStack) + return out +} + +function same(f: Lazy) { + return makeLazy(f, f) +} + +function getSuspendRecursion(fc: typeof FastCheck, ast: SchemaAST.Suspend) { + const depthIdentifier = suspendDepthIdentifierMap.get(ast) ?? fc.createDepthIdentifier() + suspendDepthIdentifierMap.set(ast, depthIdentifier) + return { maxDepth: 2, depthIdentifier } +} + +function oneOf(fc: typeof FastCheck, arbitraries: ReadonlyArray>) { + return arbitraries.length === 0 ? undefined : arbitraries.length === 1 ? arbitraries[0] : fc.oneof(...arbitraries) +} + +function reportChecks(report: MutableReport, checks: SchemaAST.Checks | undefined, path: ReadonlyArray) { + function visit(check: SchemaAST.Check, covered: boolean) { + const arbitrary = check.annotations?.arbitrary + const nextCovered = covered || arbitrary?.constraint !== undefined || arbitrary?.candidate !== undefined + if (check._tag !== "Filter") { + for (const child of check.checks) { + visit(child, nextCovered) + } + } else if (!nextCovered) { + const meta = check.annotations?.meta + const description = typeof meta === "object" && meta !== null && "_tag" in meta && typeof meta._tag === "string" + ? meta._tag + : check.annotations?.identifier ?? check.annotations?.expected + report.warnings.push({ _tag: "OpaqueFilter", path, ...(description === undefined ? {} : { description }) }) + } + } + checks?.forEach((check) => visit(check, false)) } /** @internal */ -export function getFilters(checks: AST.Checks | undefined): Array> { - if (checks) { - return checks.flatMap((check) => { - switch (check._tag) { - case "Filter": - return [check] - case "FilterGroup": - return getFilters(check.checks) +export function collectReport(ast: SchemaAST.AST, report: MutableReport) { + const stack = new WeakSet() + function visit(ast: SchemaAST.AST, path: ReadonlyArray) { + if (stack.has(ast)) { + return + } + stack.add(ast) + reportChecks(report, ast.checks, path) + switch (ast._tag) { + case "Declaration": + ast.typeParameters.forEach((tp) => visit(tp, path)) + break + case "Arrays": { + for (const [i, type] of [...ast.elements, ...ast.rest].entries()) { + visit(type, [...path, i]) + } + break } - }) + case "Objects": + ast.propertySignatures.forEach((ps) => visit(ps.type, [...path, ps.name])) + ast.indexSignatures.forEach((is) => { + visit(is.parameter, path) + visit(is.type, path) + }) + break + case "Union": + ast.types.forEach((type) => visit(type, path)) + break + case "Suspend": + visit(ast.thunk(), path) + break + } + stack.delete(ast) + } + visit(ast, []) +} + +function applyCandidates( + fc: typeof FastCheck, + ctx: Context, + arbitraries: Array, + base: FastCheck.Arbitrary | undefined +) { + const weighted: Array> = base === undefined + ? [] + : [{ arbitrary: base, weight: 1 }] + for (const { candidate } of arbitraries) { + if (!candidate) { + continue + } + const arbitrary = candidate.make(fc, ctx) + if (arbitrary === undefined) { + continue + } + const weight = candidate.weight ?? 1 + if (!globalThis.Number.isInteger(weight) || weight <= 0) { + throw arbitraryError("a candidate with an invalid weight") + } + weighted.push({ arbitrary, weight }) + } + return weighted.length === 0 ? undefined : weighted.length === 1 ? weighted[0].arbitrary : fc.oneof(...weighted) +} + +function applyFilterLayer( + ast: SchemaAST.AST, + checks: ReturnType, + fc: typeof FastCheck, + ctx: Context, + base: FastCheck.Arbitrary | undefined +) { + const out = applyCandidates(fc, ctx, checks.arbitraries, base) + return out === undefined ? undefined : applyChecks(ast, checks.filters, out) +} + +function normalizeDerivation( + output: Schema.Annotations.ToArbitrary.Output, + hasTypeParameters: boolean +) { + if (!(typeof output === "object" && output !== null && "arbitrary" in output)) { + return { arbitrary: output, terminal: hasTypeParameters ? undefined : output } + } + const terminal = "terminal" in output ? output.terminal : hasTypeParameters ? undefined : output.arbitrary + return { + arbitrary: output.arbitrary, + terminal } - return [] +} + +function makeTypeParameters( + typeParameters: ReadonlyArray>, + fc: typeof FastCheck, + ctx: Context, + recursionStack: RecursionStack, + lazyNormal: boolean +) { + return typeParameters.map((tp) => ({ + arbitrary: lazyNormal ? fc.constant(null).chain(() => tp(fc, ctx, recursionStack)) : tp(fc, ctx, recursionStack), + terminal: tp.terminal(fc, ctx, recursionStack) + })) +} + +type BaseBuilder = ( + fc: typeof FastCheck, + ctx: Context, + nextCtx: Context, + recursionStack: RecursionStack +) => FastCheck.Arbitrary | undefined + +function filterLayer( + ast: SchemaAST.AST, + checks: ReturnType, + normalBase: BaseBuilder, + terminalBase: BaseBuilder +): LazyArbitraryWithContext { + const f = constraintContext(checks.arbitraries) + return makeLazy((fc, ctx, recursionStack) => { + const nextCtx = f(ctx) + return applyFilterLayer(ast, checks, fc, nextCtx, normalBase(fc, ctx, nextCtx, recursionStack))! + }, (fc, ctx, recursionStack) => { + const nextCtx = f(ctx) + return applyFilterLayer(ast, checks, fc, nextCtx, terminalBase(fc, ctx, nextCtx, recursionStack)) + }) } /** @internal */ -export const memoized = memoize((ast: AST.AST): LazyArbitraryWithContext => { - return recur(ast, []) -}) +export const memoized = memoize((ast: SchemaAST.AST) => recur(ast, [])) -function recur(ast: AST.AST, path: ReadonlyArray): LazyArbitraryWithContext { +function recur(ast: SchemaAST.AST, path: ReadonlyArray): LazyArbitraryWithContext { // --------------------------------------------- - // handle Override annotation + // handle annotations // --------------------------------------------- const annotation = InternalAnnotations.resolve(ast)?.toArbitrary as | Schema.Annotations.ToArbitrary.Declaration> | undefined if (annotation) { - const typeParameters = AST.isDeclaration(ast) ? ast.typeParameters.map((tp) => recur(tp, path)) : [] - const filters = getFilters(ast.checks) - const f = constraintContext(filters) - return (fc, ctx) => - applyChecks( - ast, - filters, - annotation(typeParameters.map((tp) => tp(fc, resetContext(ctx))))(fc, f(ctx)) - ) + const typeParameters = SchemaAST.isDeclaration(ast) ? ast.typeParameters.map((tp) => recur(tp, path)) : [] + const checks = collectChecks(ast.checks) + const derive = (lazyNormal: boolean): BaseBuilder => (fc, ctx, nextCtx, recursionStack) => + normalizeDerivation( + annotation(makeTypeParameters(typeParameters, fc, resetContext(ctx), recursionStack, lazyNormal))(fc, nextCtx), + typeParameters.length > 0 + )[lazyNormal ? "terminal" : "arbitrary"] + return filterLayer(ast, checks, derive(false), derive(true)) } if (ast.checks) { - const filters = getFilters(ast.checks) - const f = constraintContext(filters) - const lawc = recur(AST.replaceChecks(ast, undefined), path) - return (fc, ctx) => applyChecks(ast, filters, lawc(fc, f(ctx))) + const checks = collectChecks(ast.checks) + const lawc = recur(SchemaAST.replaceChecks(ast, undefined), path) + return filterLayer( + ast, + checks, + (fc, _ctx, nextCtx, recursionStack) => lawc(fc, nextCtx, recursionStack), + (fc, _ctx, nextCtx, recursionStack) => lawc.terminal(fc, nextCtx, recursionStack) + ) } return base(ast, path) } -function base(ast: AST.AST, path: ReadonlyArray): LazyArbitraryWithContext { +function base(ast: SchemaAST.AST, path: ReadonlyArray): LazyArbitraryWithContext { switch (ast._tag) { case "Never": case "Declaration": throw errorWithPath(`Unsupported AST ${ast._tag}`, path) case "Null": - return (fc) => fc.constant(null) + return same((fc) => fc.constant(null)) case "Void": case "Undefined": - return (fc) => fc.constant(undefined) + return same((fc) => fc.constant(undefined)) case "Unknown": case "Any": - return (fc) => fc.anything() + return same((fc) => fc.anything()) case "String": - return (fc, ctx) => { - const constraint = ctx.constraints?.string + return same((fc, ctx) => { + const constraint = ctx.constraint const patterns = constraint?.patterns - if (patterns) { - return fc.oneof(...patterns.map((pattern) => fc.stringMatching(new RegExp(pattern)))) - } - return fc.string(constraint) - } + return patterns + ? fc.oneof(...patterns.map((pattern) => fc.stringMatching(new RegExp(pattern)))) + : fc.string(lengthToFastCheckConstraints(constraint)) + }) case "Number": - return (fc, ctx) => { - const constraint = ctx.constraints?.number - if (constraint?.isInteger) { - return fc.integer(constraint) - } - return fc.float(constraint) - } + return same((fc, ctx) => { + const constraint = ctx.constraint + const ordered = constraint?.ordered?.order === Order.Number ? constraint.ordered : undefined + return constraint?.integer + ? fc.integer(toIntegerConstraints(ordered)) + : fc.float(toFloatConstraints(constraint, ordered)) + }) case "Boolean": - return (fc) => fc.boolean() + return same((fc) => fc.boolean()) case "BigInt": - return (fc, ctx) => fc.bigInt(ctx.constraints?.bigint ?? {}) + return same((fc, ctx) => { + const ordered = ctx.constraint?.ordered?.order === Order.BigInt ? ctx.constraint.ordered : undefined + return fc.bigInt(toBigIntConstraints(ordered)) + }) case "Symbol": - return (fc) => fc.string().map(Symbol.for) + return same((fc) => fc.string().map(Symbol.for)) case "Literal": - return (fc) => fc.constant(ast.literal) + return same((fc) => fc.constant(ast.literal)) case "UniqueSymbol": - return (fc) => fc.constant(ast.symbol) + return same((fc) => fc.constant(ast.symbol)) case "ObjectKeyword": - return (fc) => fc.oneof(fc.object(), fc.array(fc.anything())) + return same((fc) => fc.oneof(fc.object(), fc.array(fc.anything()))) case "Enum": - return recur(AST.enumsToLiterals(ast), path) + return recur(SchemaAST.enumsToLiterals(ast), path) case "TemplateLiteral": - return (fc) => fc.stringMatching(AST.getTemplateLiteralRegExp(ast)) - case "Arrays": - return (fc, ctx) => { + return same((fc) => fc.stringMatching(SchemaAST.getTemplateLiteralRegExp(ast))) + case "Arrays": { + const elements = ast.elements.map((ast, i) => ({ + ast, + arbitrary: recur(ast, [...path, i]) + })) + const len = ast.elements.length + const rest = ast.rest.map((ast, i) => ({ + ast, + arbitrary: recur(ast, [...path, len + i]) + })) + const terminal: LazyOption = (fc, ctx, recursionStack) => { + const reset = resetContext(ctx) + const elementArbitraries: Array>> = [] + const optionals: Array | undefined> = [] + let length = 0 + for (const element of elements) { + const out = element.arbitrary.terminal(fc, reset, recursionStack) + if (SchemaAST.isOptional(element.ast)) { + optionals.push(out) + continue + } + if (out === undefined) { + return undefined + } + length++ + elementArbitraries.push(out.map(Option.some)) + } + const minLength = ctx.constraint?.minLength ?? 0 + const needsRest = Array.isReadonlyArrayNonEmpty(rest) && minLength > length + optionals.length + const optionalTarget = needsRest ? optionals.length : Math.max(0, minLength - length) + let includedOptionals = 0 + for (const out of optionals) { + if (includedOptionals >= optionalTarget || out === undefined) { + elementArbitraries.push(fc.constant(Option.none())) + continue + } + includedOptionals++ + length++ + elementArbitraries.push(out.map(Option.some)) + } + if (includedOptionals < optionalTarget) { + return undefined + } + let out = fc.tuple(...elementArbitraries).map(Array.getSomes) + if (Array.isReadonlyArrayNonEmpty(rest)) { + const [head, ...tail] = rest + const restCtx = ast.elements.length === 0 ? ctx : reset + const minRestLength = Math.max(0, minLength - length - tail.length) + const headArbitrary = minRestLength === 0 + ? undefined + : head.arbitrary.terminal(fc, reset, recursionStack) + if (minRestLength > 0 && headArbitrary === undefined) { + return undefined + } + const restArbitrary = minRestLength === 0 + ? fc.constant([]) + : array( + fc, + { ...restCtx, constraint: { ...restCtx.constraint, minLength: minRestLength } }, + headArbitrary!, + true + ) + out = appendArray(fc, out, len, restArbitrary) + if (tail.length > 0) { + const tailArbitraries: Array> = [] + for (const element of tail) { + const out = element.arbitrary.terminal(fc, reset, recursionStack) + if (out === undefined) { + return undefined + } + tailArbitraries.push(out) + } + const t = fc.tuple(...tailArbitraries) + out = appendArray(fc, out, len, t) + } + } + return out + } + return makeLazy((fc, ctx, recursionStack) => { const reset = resetContext(ctx) // --------------------------------------------- // handle elements // --------------------------------------------- - const elements: Array>> = ast.elements.map((e, i) => { - const out = recur(e, [...path, i])(fc, reset) - if (!AST.isOptional(e)) { - return out.map(Option.some) + const elementArbitraries: Array>> = elements.map( + ({ ast, arbitrary }) => { + const out = arbitrary(fc, reset, recursionStack) + return SchemaAST.isOptional(ast) + ? out.chain((a) => fc.boolean().map((b) => b ? Option.some(a) : Option.none())) + : out.map(Option.some) } - return out.chain((a) => fc.boolean().map((b) => b ? Option.some(a) : Option.none())) - }) - let out = fc.tuple(...elements).map(Array.getSomes) + ) + let out = fc.tuple(...elementArbitraries).map(Array.getSomes) // --------------------------------------------- // handle rest element // --------------------------------------------- - if (Array.isReadonlyArrayNonEmpty(ast.rest)) { - const len = ast.elements.length - const [head, ...tail] = ast.rest.map((r, i) => recur(r, [...path, len + i])(fc, reset)) - - const rest = array(fc, ast.elements.length === 0 ? ctx : reset, head) - out = out.chain((as) => { - if (as.length < len) { - return fc.constant(as) - } - return rest.map((rest) => [...as, ...rest]) - }) + if (Array.isReadonlyArrayNonEmpty(rest)) { + const [head, ...tail] = rest.map(({ arbitrary }) => arbitrary(fc, reset, recursionStack)) + + const restArbitrary = array(fc, ast.elements.length === 0 ? ctx : reset, head) + out = appendArray(fc, out, len, restArbitrary) // --------------------------------------------- // handle post rest elements // --------------------------------------------- if (tail.length > 0) { const t = fc.tuple(...tail) - out = out.chain((as) => { - if (as.length < len) { - return fc.constant(as) - } - return t.map((rest) => [...as, ...rest]) - }) + out = appendArray(fc, out, len, t) + } + } + if (ctx.recursion) { + const terminalOut = terminal(fc, ctx, recursionStack) + if (terminalOut !== undefined) { + return fc.oneof(ctx.recursion, terminalOut, out) + } + } + return out + }, terminal) + } + case "Objects": { + const propertySignatures = ast.propertySignatures.map((ps) => ({ + ps, + arbitrary: recur(ps.type, [...path, ps.name]) + })) + const indexSignatures = ast.indexSignatures.map((is) => ({ + is, + parameter: recur(is.parameter, path), + type: recur(is.type, path) + })) + const terminal: LazyOption = (fc, ctx, recursionStack) => { + const reset = resetContext(ctx) + const pss: any = {} + const requiredKeys: Array = [] + const optionals: Array]> = [] + for (const { ps, arbitrary } of propertySignatures) { + const name = ps.name + const out = arbitrary.terminal(fc, reset, recursionStack) + if (SchemaAST.isOptional(ps.type)) { + if (out !== undefined) { + optionals.push([name, out]) + } + continue + } + if (out === undefined) { + return undefined } + requiredKeys.push(name) + pss[name] = out + } + let optionalCount = Math.max(0, (ctx.constraint?.minLength ?? 0) - requiredKeys.length) + for (const [name, out] of optionals) { + if (optionalCount === 0) { + break + } + optionalCount-- + requiredKeys.push(name) + pss[name] = out + } + if (optionalCount > 0 && ast.indexSignatures.length === 0) { + return undefined + } + let out = fc.record(pss, { requiredKeys }) + const entriesConstraints = objectEntriesConstraints(ast, ctx.constraint, requiredKeys.length) + const minEntries = entriesConstraints?.minLength ?? 0 + for (const { parameter, type } of indexSignatures) { + let entries: FastCheck.Arbitrary> + if (minEntries === 0) { + entries = fc.constant([]) + } else { + const key = parameter.terminal(fc, reset, recursionStack) + const value = type.terminal(fc, reset, recursionStack) + if (key === undefined || value === undefined) { + return undefined + } + entries = arrayWithConstraints( + fc, + fc.tuple(key, value), + { ...entriesConstraints, maxLength: minEntries }, + entryComparator + ) + } + out = appendObjectEntries(out, entries) } return out } - case "Objects": - return (fc, ctx) => { + return makeLazy((fc, ctx, recursionStack) => { const reset = resetContext(ctx) // --------------------------------------------- // handle property signatures // --------------------------------------------- const pss: any = {} + const orderedNames: Array = [] const requiredKeys: Array = [] - for (const ps of ast.propertySignatures) { + const optionalNames: Array = [] + for (const { ps, arbitrary } of propertySignatures) { const name = ps.name - if (!AST.isOptional(ps.type)) { + orderedNames.push(name) + if (SchemaAST.isOptional(ps.type)) { + optionalNames.push(name) + } else { requiredKeys.push(name) } - pss[name] = recur(ps.type, [...path, name])(fc, reset) + pss[name] = arbitrary(fc, reset, recursionStack) + } + // When property-count constraints must be satisfied by selecting + // optional keys (no index signatures are available to fill the gap), + // generate a count-controlled subset of optional keys instead of + // relying on fast-check's independent inclusion plus discards. This + // enforces both bounds precisely while still varying which optionals + // appear. + const constraint = ctx.constraint + if ( + optionalNames.length > 0 && + indexSignatures.length === 0 && + constraint !== undefined && + (constraint.minLength !== undefined || constraint.maxLength !== undefined) + ) { + return objectWithOptionalCount(fc, pss, orderedNames, requiredKeys, optionalNames, constraint) } let out = fc.record(pss, { requiredKeys }) + const entriesConstraints = objectEntriesConstraints(ast, ctx.constraint, requiredKeys.length) // --------------------------------------------- // handle index signatures // --------------------------------------------- - for (const is of ast.indexSignatures) { - const entry = fc.tuple(recur(is.parameter, path)(fc, reset), recur(is.type, path)(fc, reset)) - const entries = array(fc, ast.propertySignatures.length === 0 ? ctx : reset, entry) - out = out.chain((o) => { - return entries.map((entries) => { - return { - ...Object.fromEntries(entries), - ...o - } - }) - }) + for (const { parameter, type } of indexSignatures) { + const entry = fc.tuple(parameter(fc, reset, recursionStack), type(fc, reset, recursionStack)) + const entries = arrayWithConstraints(fc, entry, entriesConstraints, entryComparator) + out = appendObjectEntries(out, entries) } return out - } - case "Union": - return (fc, ctx) => fc.oneof(...ast.types.map((ast) => recur(ast, path)(fc, ctx))) + }, terminal) + } + case "Union": { + const types = ast.types.map((ast) => recur(ast, path)) + const terminal: LazyOption = (fc, ctx, recursionStack) => + oneOf(fc, types.map((type) => type.terminal(fc, ctx, recursionStack)).filter(Predicate.isNotUndefined)) + return makeLazy((fc, ctx, recursionStack) => { + const arbitraries = types.map((type) => type(fc, ctx, recursionStack)) + if (ctx.recursion) { + const terminalOut = terminal(fc, ctx, recursionStack) + if (terminalOut !== undefined) { + return fc.oneof(ctx.recursion, terminalOut, ...arbitraries) + } + } + const out = oneOf(fc, arbitraries) + if (out === undefined) { + throw arbitraryError("a union with no members") + } + return out + }, terminal) + } case "Suspend": { const memo = arbitraryMemoMap.get(ast) if (memo) return memo - const get = AST.memoizeThunk(() => recur(ast.thunk(), path)) - const out: LazyArbitraryWithContext = (fc, ctx) => - fc.constant(null).chain(() => get()(fc, { ...ctx, isSuspend: true })) + const get = SchemaAST.memoizeThunk(() => recur(ast.thunk(), path)) + const out = makeLazy((fc, ctx, recursionStack) => { + const recursion = getSuspendRecursion(fc, ast) + const nextCtx = { ...ctx, recursion } + const nextStack = recursionStack.includes(ast) ? recursionStack : [...recursionStack, ast] + const terminal = get().terminal(fc, nextCtx, nextStack) + if (terminal === undefined) { + throw errorWithPath( + "Unable to derive an arbitrary for a recursive schema without a finite generation path", + path + ) + } + return fc.oneof( + recursion, + terminal, + fc.constant(null).chain(() => get()(fc, nextCtx, nextStack)) + ) + }, (fc, ctx, recursionStack) => { + if (recursionStack.includes(ast)) { + return undefined + } + const recursion = getSuspendRecursion(fc, ast) + return get().terminal(fc, { ...ctx, recursion }, [...recursionStack, ast]) + }) arbitraryMemoMap.set(ast, out) diff --git a/.opencode/node_modules/effect/src/internal/schema/equivalence.ts b/.opencode/node_modules/effect/src/internal/schema/equivalence.ts index c60f775fdd52506499ebe5f7d9738a791937aa88..c6b88f05d56019e935f64c40dbd033eb76591cb3 100644 --- a/.opencode/node_modules/effect/src/internal/schema/equivalence.ts +++ b/.opencode/node_modules/effect/src/internal/schema/equivalence.ts @@ -3,17 +3,17 @@ import * as Equivalence from "../../Equivalence.ts" import { memoize } from "../../Function.ts" import * as Predicate from "../../Predicate.ts" import type * as Schema from "../../Schema.ts" -import * as AST from "../../SchemaAST.ts" -import * as Parser from "../../SchemaParser.ts" +import * as SchemaAST from "../../SchemaAST.ts" +import * as SchemaParser from "../../SchemaParser.ts" import { errorWithPath } from "../errors.ts" import * as InternalAnnotations from "./annotations.ts" /** @internal */ -export const toEquivalence = memoize((ast: AST.AST): Equivalence.Equivalence => { +export const toEquivalence = memoize((ast: SchemaAST.AST): Equivalence.Equivalence => { return recur(ast, []) }) -function recur(ast: AST.AST, path: ReadonlyArray): Equivalence.Equivalence { +function recur(ast: SchemaAST.AST, path: ReadonlyArray): Equivalence.Equivalence { // --------------------------------------------- // handle annotations // --------------------------------------------- @@ -21,7 +21,7 @@ function recur(ast: AST.AST, path: ReadonlyArray): Equivalence.Equi | Schema.Annotations.ToEquivalence.Declaration> | undefined if (annotation) { - return annotation(AST.isDeclaration(ast) ? ast.typeParameters.map((tp) => recur(tp, path)) : []) + return annotation(SchemaAST.isDeclaration(ast) ? ast.typeParameters.map((tp) => recur(tp, path)) : []) } switch (ast._tag) { case "Never": @@ -105,7 +105,7 @@ function recur(ast: AST.AST, path: ReadonlyArray): Equivalence.Equi const name = ps.name const aHas = Object.hasOwn(a, name) const bHas = Object.hasOwn(b, name) - if (AST.isOptional(ps.type)) { + if (SchemaAST.isOptional(ps.type)) { if (aHas !== bHas) { return false } @@ -119,8 +119,8 @@ function recur(ast: AST.AST, path: ReadonlyArray): Equivalence.Equi // --------------------------------------------- for (let i = 0; i < indexSignatures.length; i++) { const is = ast.indexSignatures[i] - const aKeys = AST.getIndexSignatureKeys(a, is.parameter) - const bKeys = AST.getIndexSignatureKeys(b, is.parameter) + const aKeys = SchemaAST.getIndexSignatureKeys(a, is.parameter) + const bKeys = SchemaAST.getIndexSignatureKeys(b, is.parameter) if (aKeys.length !== bKeys.length) return false @@ -136,8 +136,8 @@ function recur(ast: AST.AST, path: ReadonlyArray): Equivalence.Equi } case "Union": return Equivalence.make((a, b) => { - const candidates = AST.getCandidates(a, ast.types) - const types = candidates.map(Parser._is) + const candidates = SchemaAST.getCandidates(a, ast.types) + const types = candidates.map(SchemaParser._is) for (let i = 0; i < candidates.length; i++) { const is = types[i] if (is(a) && is(b)) { @@ -147,7 +147,7 @@ function recur(ast: AST.AST, path: ReadonlyArray): Equivalence.Equi return false }) case "Suspend": { - const get = AST.memoizeThunk(() => recur(ast.thunk(), path)) + const get = SchemaAST.memoizeThunk(() => recur(ast.thunk(), path)) return Equivalence.make((a, b) => get()(a, b)) } } diff --git a/.opencode/node_modules/effect/src/internal/schema/representation.ts b/.opencode/node_modules/effect/src/internal/schema/representation.ts index 180b2a5017ab7ae38363b893c24199280b5703b3..7711b8f1f22aac97c6b2ad1767f730f52f3d32e1 100644 --- a/.opencode/node_modules/effect/src/internal/schema/representation.ts +++ b/.opencode/node_modules/effect/src/internal/schema/representation.ts @@ -7,24 +7,24 @@ import * as Predicate from "../../Predicate.ts" import * as Rec from "../../Record.ts" import * as RegEx from "../../RegExp.ts" import type * as Schema from "../../Schema.ts" -import * as AST from "../../SchemaAST.ts" +import * as SchemaAST from "../../SchemaAST.ts" import type * as SchemaRepresentation from "../../SchemaRepresentation.ts" import * as InternalAnnotations from "./annotations.ts" import * as InternalSchema from "./schema.ts" /** @internal */ -export function fromAST(ast: AST.AST): SchemaRepresentation.Document { +export function fromAST(ast: SchemaAST.AST): SchemaRepresentation.Document { const { references, representations: schemas } = fromASTs([ast]) return { representation: schemas[0], references } } /** @internal */ -export function fromASTs(asts: readonly [AST.AST, ...Array]): SchemaRepresentation.MultiDocument { +export function fromASTs(asts: readonly [SchemaAST.AST, ...Array]): SchemaRepresentation.MultiDocument { const references: Record = {} - const referenceMap = new Map() + const referenceMap = new Map() const uniqueReferences = new Set() - const visiting = new Set() + const visiting = new Set() const schemas = Arr.map(asts, (ast) => recur(ast)) @@ -45,13 +45,13 @@ export function fromASTs(asts: readonly [AST.AST, ...Array]): SchemaRep return candidate } - function recur(ast: AST.AST, prefix?: string): SchemaRepresentation.Representation { + function recur(ast: SchemaAST.AST, prefix?: string): SchemaRepresentation.Representation { const found = referenceMap.get(ast) if (found !== undefined) { return { _tag: "Reference", $ref: found } } - const last = AST.getLastEncoding(ast) + const last = SchemaAST.getLastEncoding(ast) const identifier = InternalAnnotations.resolveIdentifier(ast) ?? prefix if (ast !== last) { @@ -95,17 +95,17 @@ export function fromASTs(asts: readonly [AST.AST, ...Array]): SchemaRep return out } - function getEncodedSchema(last: AST.Declaration): AST.AST { + function getEncodedSchema(last: SchemaAST.Declaration): SchemaAST.AST { const getLink = last.annotations?.toCodecJson ?? last.annotations?.toCodec if (Predicate.isFunction(getLink)) { - const tps = last.typeParameters.map((tp) => InternalSchema.make(AST.toEncoded(tp))) + const tps = last.typeParameters.map((tp) => InternalSchema.make(SchemaAST.toEncoded(tp))) const link = getLink(tps) - return AST.replaceEncoding(last, [link]) + return SchemaAST.replaceEncoding(last, [link]) } - return AST.null + return SchemaAST.null } - function on(last: AST.AST): SchemaRepresentation.Representation { + function on(last: SchemaAST.AST): SchemaRepresentation.Representation { const annotations = fromASTAnnotations(last.annotations) switch (last._tag) { case "Declaration": { @@ -135,7 +135,7 @@ export function fromASTs(asts: readonly [AST.AST, ...Array]): SchemaRep _tag: last._tag, checks: fromASTChecks(last.checks), ...annotations, - ...(typeof contentMediaType === "string" && AST.isAST(contentSchema) + ...(typeof contentMediaType === "string" && SchemaAST.isAST(contentSchema) ? { contentSchema: recur(contentSchema) } : undefined) } @@ -180,9 +180,9 @@ export function fromASTs(asts: readonly [AST.AST, ...Array]): SchemaRep return { _tag: last._tag, elements: last.elements.map((e) => { - const last = AST.getLastEncoding(e) + const last = SchemaAST.getLastEncoding(e) return { - isOptional: AST.isOptional(last), + isOptional: SchemaAST.isOptional(last), type: recur(e), ...fromASTAnnotations(last.context?.annotations) } @@ -195,12 +195,12 @@ export function fromASTs(asts: readonly [AST.AST, ...Array]): SchemaRep return { _tag: last._tag, propertySignatures: last.propertySignatures.map((ps) => { - const last = AST.getLastEncoding(ps.type) + const last = SchemaAST.getLastEncoding(ps.type) return { name: ps.name, type: recur(ps.type), - isOptional: AST.isOptional(last), - isMutable: AST.isMutable(last), + isOptional: SchemaAST.isOptional(last), + isMutable: SchemaAST.isMutable(last), ...fromASTAnnotations(last.context?.annotations) } }), @@ -232,12 +232,12 @@ export function fromASTs(asts: readonly [AST.AST, ...Array]): SchemaRep } function fromASTChecks( - checks: readonly [AST.Check, ...Array>] | undefined + checks: readonly [SchemaAST.Check, ...Array>] | undefined ): Array> { if (!checks) return [] return checks.map(getCheck).filter((c) => c !== undefined) - function getCheck(c: AST.Check): SchemaRepresentation.Check | undefined { + function getCheck(c: SchemaAST.Check): SchemaRepresentation.Check | undefined { switch (c._tag) { case "Filter": { const meta = c.annotations?.meta @@ -276,14 +276,27 @@ export const fromASTBlacklist: Set = new Set([ "~structural", "~sentinels", "meta", + "arbitrary", "toArbitrary", - "toArbitraryConstraint", "toEquivalence", "toFormatter", "toCodec", "toCodecJson", "toCodecIso", - AST.ClassTypeId + SchemaAST.ClassTypeId +]) + +const standardJsonSchemaAnnotationKeys: ReadonlySet = new Set([ + "title", + "description", + "default", + "examples", + "readOnly", + "writeOnly", + "format", + "contentEncoding", + "contentMediaType", + "contentSchema" ]) function fromASTAnnotations( @@ -318,6 +331,7 @@ export function toJsonSchemaMultiDocument( ): JsonSchema.MultiDocument<"draft-2020-12"> { const generateDescriptions = options?.generateDescriptions ?? false const additionalProperties = options?.additionalProperties ?? false + const includeAnnotationKey = options?.includeAnnotationKey const definitions = Rec.map(multiDocument.references, (d) => recur(d)) @@ -348,8 +362,9 @@ export function toJsonSchemaMultiDocument( switch (schema._tag) { case "Any": case "Unknown": - case "ObjectKeyword": return {} + case "ObjectKeyword": + return { anyOf: [{ type: "object" }, { type: "array" }] } case "Void": case "Undefined": return { type: "null" } @@ -569,21 +584,30 @@ export function toJsonSchemaMultiDocument( function collectJsonSchemaAnnotations( annotations: Schema.Annotations.Annotations | undefined ): JsonSchema.JsonSchema | undefined { - if (annotations) { - const out: JsonSchema.JsonSchema = {} - if (typeof annotations.title === "string") out.title = annotations.title - if (typeof annotations.description === "string") out.description = annotations.description - else if (generateDescriptions && typeof annotations.expected === "string") out.description = annotations.expected - if (annotations.default !== undefined) out.default = annotations.default - if (Array.isArray(annotations.examples)) out.examples = annotations.examples - if (typeof annotations.readOnly === "boolean") out.readOnly = annotations.readOnly - if (typeof annotations.writeOnly === "boolean") out.writeOnly = annotations.writeOnly - if (typeof annotations.format === "string") out.format = annotations.format - if (typeof annotations.contentEncoding === "string") out.contentEncoding = annotations.contentEncoding - if (typeof annotations.contentMediaType === "string") out.contentMediaType = annotations.contentMediaType - - if (Object.keys(out).length > 0) return out + if (annotations === undefined) return undefined + + const out: JsonSchema.JsonSchema = {} + if (typeof annotations.title === "string") out.title = annotations.title + if (typeof annotations.description === "string") out.description = annotations.description + else if (generateDescriptions && typeof annotations.expected === "string") out.description = annotations.expected + if (annotations.default !== undefined) out.default = annotations.default + if (Array.isArray(annotations.examples)) out.examples = annotations.examples + if (typeof annotations.readOnly === "boolean") out.readOnly = annotations.readOnly + if (typeof annotations.writeOnly === "boolean") out.writeOnly = annotations.writeOnly + if (typeof annotations.format === "string") out.format = annotations.format + if (typeof annotations.contentEncoding === "string") out.contentEncoding = annotations.contentEncoding + if (typeof annotations.contentMediaType === "string") out.contentMediaType = annotations.contentMediaType + + if (includeAnnotationKey) { + for (const [key, value] of Object.entries(annotations)) { + if (value === undefined) continue + if (standardJsonSchemaAnnotationKeys.has(key)) continue + if (!includeAnnotationKey(key)) continue + out[key] = value + } } + + if (Object.keys(out).length > 0) return out } function collectJsonSchemaChecks( @@ -637,6 +661,7 @@ export function toJsonSchemaMultiDocument( ? { allOf: [{ minItems: meta.minimum }, { maxItems: meta.maximum }] } : { allOf: [{ minLength: meta.minimum }, { maxLength: meta.maximum }] } case "isPattern": + case "isGUID": case "isULID": case "isBase64": case "isBase64Url": @@ -761,9 +786,9 @@ function getPartPattern(part: SchemaRepresentation.Representation): string { case "Literal": return RegEx.escape(globalThis.String(part.literal)) case "String": - return AST.STRING_PATTERN + return SchemaAST.STRING_PATTERN case "Number": - return AST.FINITE_PATTERN + return SchemaAST.FINITE_PATTERN case "TemplateLiteral": return part.parts.map(getPartPattern).join("") case "Union": diff --git a/.opencode/node_modules/effect/src/internal/schema/schema.ts b/.opencode/node_modules/effect/src/internal/schema/schema.ts index 2967b221720da98c7692135f023af81d2cc1bc75..c7cf93e2f9165e11078a67d788760d445fecb96d 100644 --- a/.opencode/node_modules/effect/src/internal/schema/schema.ts +++ b/.opencode/node_modules/effect/src/internal/schema/schema.ts @@ -2,9 +2,9 @@ import * as Effect from "../../Effect.ts" import { flow } from "../../Function.ts" import * as Pipeable from "../../Pipeable.ts" import type * as Schema from "../../Schema.ts" -import * as AST from "../../SchemaAST.ts" +import * as SchemaAST from "../../SchemaAST.ts" import type { Issue } from "../../SchemaIssue.ts" -import * as Parser from "../../SchemaParser.ts" +import * as SchemaParser from "../../SchemaParser.ts" /** @internal */ export const TypeId = "~effect/Schema/Schema" @@ -15,13 +15,13 @@ const SchemaProto = { return Pipeable.pipeArguments(this, arguments) }, annotate(this: Schema.Top, annotations: Schema.Annotations.Annotations) { - return this.rebuild(AST.annotate(this.ast, annotations)) + return this.rebuild(SchemaAST.annotate(this.ast, annotations)) }, annotateKey(this: Schema.Top, annotations: Schema.Annotations.Key) { - return this.rebuild(AST.annotateKey(this.ast, annotations)) + return this.rebuild(SchemaAST.annotateKey(this.ast, annotations)) }, - check(this: Schema.Top, ...checks: readonly [AST.Check, ...Array>]) { - return this.rebuild(AST.appendChecks(this.ast, checks)) + check(this: Schema.Top, ...checks: readonly [SchemaAST.Check, ...Array>]) { + return this.rebuild(SchemaAST.appendChecks(this.ast, checks)) } } @@ -32,10 +32,10 @@ export function make(ast: S["ast"], options?: object): S { Object.assign(self, options) } self.ast = ast - self.rebuild = (ast: AST.AST) => make(ast, options) - self.makeEffect = flow(Parser.makeEffect(self), Effect.mapErrorEager((issue) => new SchemaError(issue))) - self.make = Parser.makeUnsafe(self) - self.makeOption = Parser.makeOption(self) + self.rebuild = (ast: SchemaAST.AST) => make(ast, options) + self.makeEffect = flow(SchemaParser.makeEffect(self), Effect.mapErrorEager((issue) => new SchemaError(issue))) + self.make = SchemaParser.make(self) + self.makeOption = SchemaParser.makeOption(self) return self } @@ -62,7 +62,7 @@ export class SchemaError { /** @internal */ export const jsonReorder = makeReorder(getJsonPriority) -function getJsonPriority(ast: AST.AST): number { +function getJsonPriority(ast: SchemaAST.AST): number { switch (ast._tag) { case "BigInt": case "Symbol": @@ -74,18 +74,18 @@ function getJsonPriority(ast: AST.AST): number { } /** @internal */ -export function makeReorder(getPriority: (ast: AST.AST) => number) { - return (types: ReadonlyArray): ReadonlyArray => { +export function makeReorder(getPriority: (ast: SchemaAST.AST) => number) { + return (types: ReadonlyArray): ReadonlyArray => { // Create a map of original indices for O(1) lookup - const indexMap = new Map() + const indexMap = new Map() for (let i = 0; i < types.length; i++) { - indexMap.set(AST.toEncoded(types[i]), i) + indexMap.set(SchemaAST.toEncoded(types[i]), i) } // Create a sorted copy of the types array const sortedTypes = [...types].sort((a, b) => { - a = AST.toEncoded(a) - b = AST.toEncoded(b) + a = SchemaAST.toEncoded(a) + b = SchemaAST.toEncoded(b) const pa = getPriority(a) const pb = getPriority(b) if (pa !== pb) return pa - pb diff --git a/.opencode/node_modules/effect/src/testing/FastCheck.ts b/.opencode/node_modules/effect/src/testing/FastCheck.ts index 34fe3eb2ae00a6b3456bb8bc6503eadd4eb5e33b..1ce177c613e7d08f2f226c6b40fe5dee15669dff 100644 --- a/.opencode/node_modules/effect/src/testing/FastCheck.ts +++ b/.opencode/node_modules/effect/src/testing/FastCheck.ts @@ -1,11 +1,10 @@ /** - * This module provides a re-export of the fast-check library for property-based testing. - * Fast-check is a property-based testing framework that generates random test cases - * to validate that properties hold true for a wide range of inputs. + * Re-exports `fast-check` for property-based testing. * - * Property-based testing is a testing methodology where you specify properties that - * should hold true for your functions, and the framework generates many random test - * cases to try to find counterexamples. + * Property-based tests describe a rule that should hold for many inputs, and + * `fast-check` generates random examples to look for counterexamples. This + * module exposes the library from `effect/testing` so tests can use it alongside + * the other Effect testing helpers. * * @since 3.10.0 */ @@ -19,9 +18,10 @@ * true for your functions, rather than writing specific test cases. The library * then generates many random inputs to verify these properties. * - * @example + * **Example** (Checking an array reversal property) + * * ```ts - * import * as FastCheck from "effect/testing/FastCheck" + * import { FastCheck } from "effect/testing" * * // Property: reverse of reverse should equal original * const reverseProp = FastCheck.property( @@ -37,9 +37,10 @@ * FastCheck.assert(reverseProp) * ``` * - * @example + * **Example** (Checking string concatenation properties) + * * ```ts - * import * as FastCheck from "effect/testing/FastCheck" + * import { FastCheck } from "effect/testing" * * // Test string concatenation properties * const concatProp = FastCheck.property( @@ -56,9 +57,10 @@ * FastCheck.assert(concatProp) * ``` * - * @example + * **Example** (Generating record data for properties) + * * ```ts - * import * as FastCheck from "effect/testing/FastCheck" + * import { FastCheck } from "effect/testing" * * // Generate random data for testing * const personArbitrary = FastCheck.record({ diff --git a/.opencode/node_modules/effect/src/testing/TestClock.ts b/.opencode/node_modules/effect/src/testing/TestClock.ts index 2557acaf169a9182f13020004ee83f1aa20caa1d..0740d41b3f6b25d345331ee2108ab301b9f8ec55 100644 --- a/.opencode/node_modules/effect/src/testing/TestClock.ts +++ b/.opencode/node_modules/effect/src/testing/TestClock.ts @@ -1,4 +1,13 @@ /** + * Controllable `Clock` service for tests. + * + * Instead of waiting for real time to pass, effects that use `Effect.sleep`, + * timeouts, schedules, retries, and other time-based operators can be driven by + * advancing the test clock. This makes time-based tests deterministic and fast. + * The module also includes helpers for moving test time, temporarily using the + * live clock, and warning when a test appears to be waiting on time without + * advancing it. + * * @since 2.0.0 */ import * as Arr from "../Array.ts" @@ -14,16 +23,26 @@ import * as Order from "../Order.ts" import * as Semaphore from "../Semaphore.ts" /** - * A `TestClock` simplifies deterministically and efficiently testing effects - * which involve the passage of time. + * A `TestClock` simplifies deterministic and efficient testing of effects that + * involve the passage of time. + * + * **Details** * * Instead of waiting for actual time to pass, `sleep` and methods implemented - * in terms of it schedule effects to take place at a given clock time. Users - * can adjust the clock time using the `adjust` and `setTime` methods, and all - * effects scheduled to take place on or before that time will automatically be - * run in order. + * in terms of it schedule effects to take place at a given clock time. Use + * `adjust` and `setTime` to move clock time, and all effects scheduled to take + * place on or before that time will automatically run in order. + * + * **Gotchas** + * + * Calls to `sleep` and methods derived from it will semantically block until + * the time is set to on or after the time they are scheduled to run. Fork the + * effect being tested, then adjust the clock time, and finally verify that the + * expected effects have been performed. * - * For example, here is how we can test `Effect.timeout` using `TestClock`: + * **Example** (Testing timeouts deterministically) + * + * Tests `Effect.timeout` using `TestClock`. * * ```ts * import { Effect, Fiber, Option, pipe } from "effect" @@ -42,15 +61,8 @@ import * as Semaphore from "../Semaphore.ts" * }) * ``` * - * Note how we forked the fiber that `sleep` was invoked on. Calls to `sleep` - * and methods derived from it will semantically block until the time is set to - * on or after the time they are scheduled to run. If we didn't fork the fiber - * on which we called sleep we would never get to set the time on the line - * below. Thus, a useful pattern when using `TestClock` is to fork the effect - * being tested, then adjust the clock time, and finally verify that the - * expected effects have been performed. + * **Example** (Advancing time deterministically) * - * @example * ```ts * import { Effect } from "effect" * import { TestClock } from "effect/testing" @@ -72,8 +84,8 @@ import * as Semaphore from "../Semaphore.ts" * }) * ``` * - * @since 2.0.0 * @category models + * @since 2.0.0 */ export interface TestClock extends Clock.Clock { /** @@ -95,7 +107,10 @@ export interface TestClock extends Clock.Clock { } /** - * @example + * Namespace containing `TestClock` configuration and state types. + * + * **Example** (Configuring a test clock) + * * ```ts * import { Effect } from "effect" * import { TestClock } from "effect/testing" @@ -112,12 +127,16 @@ export interface TestClock extends Clock.Clock { * }) * ``` * - * @since 4.0.0 - * @category models + * @since 2.0.0 */ export declare namespace TestClock { /** - * @example + * Options used when constructing a `TestClock`. `warningDelay` controls how + * long the live clock waits before logging a warning when a test uses time + * without advancing the test clock. + * + * **Example** (Configuring the warning delay) + * * ```ts * import { Effect } from "effect" * import { TestClock } from "effect/testing" @@ -133,8 +152,8 @@ export declare namespace TestClock { * }) * ``` * + * @category options * @since 4.0.0 - * @category models */ export interface Options { /** @@ -145,24 +164,12 @@ export declare namespace TestClock { } /** - * @example - * ```ts - * import { Effect } from "effect" - * import { TestClock } from "effect/testing" + * Represents the state tracked by a `TestClock`, including the current + * millisecond timestamp and the sleeps scheduled to resume when the clock + * reaches their target time. * - * const program = Effect.gen(function*() { - * const testClock = yield* TestClock.make() - * - * // The state represents the current timestamp and scheduled sleeps - * const timestamp = testClock.currentTimeMillisUnsafe() - * console.log(timestamp) // Current test time - * - * // Internal state structure: { timestamp: number, sleeps: Array<[number, Latch.Latch]> } - * }) - * ``` - * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface State { readonly timestamp: number @@ -190,7 +197,8 @@ const SleepOrder = Order.flip(Order.Struct({ /** * Creates a `TestClock` with optional configuration. * - * @example + * **Example** (Creating a test clock) + * * ```ts * import { Effect } from "effect" * import { TestClock } from "effect/testing" @@ -211,8 +219,8 @@ const SleepOrder = Order.flip(Order.Struct({ * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const make = Effect.fnUntraced(function*( options?: TestClock.Options @@ -307,7 +315,7 @@ export const make = Effect.fnUntraced(function*( const runSemaphore = yield* Semaphore.make(1) const run = Effect.fnUntraced(function*(step: (currentTimestamp: number) => number) { - yield* Fiber.await(yield* Effect.forkScoped(Effect.yieldNow)) + yield* Fiber.await(yield* Effect.forkChild(Effect.yieldNow)) const endTimestamp = step(currentTimestamp) while (Arr.isArrayNonEmpty(sleeps)) { if (Arr.lastNonEmpty(sleeps).timestamp > endTimestamp) break @@ -345,7 +353,8 @@ export const make = Effect.fnUntraced(function*( /** * Creates a `Layer` which constructs a `TestClock`. * - * @example + * **Example** (Providing a test clock layer) + * * ```ts * import { Effect } from "effect" * import { TestClock } from "effect/testing" @@ -364,8 +373,8 @@ export const make = Effect.fnUntraced(function*( * }).pipe(Effect.provide(testClockLayer)) * ``` * - * @since 4.0.0 * @category layers + * @since 4.0.0 */ export const layer: (options?: TestClock.Options) => Layer.Layer = flow( make, @@ -376,7 +385,8 @@ export const layer: (options?: TestClock.Options) => Layer.Layer = fl * Retrieves the `TestClock` service for this test and uses it to run the * specified workflow. * - * @example + * **Example** (Accessing the test clock) + * * ```ts * import { Effect } from "effect" * import { TestClock } from "effect/testing" @@ -394,8 +404,8 @@ export const layer: (options?: TestClock.Options) => Layer.Layer = fl * }) * ``` * + * @category testing * @since 2.0.0 - * @category utils */ export const testClockWith = ( f: (testClock: TestClock) => Effect.Effect @@ -406,7 +416,8 @@ export const testClockWith = ( * by the specified duration, running any actions scheduled for on or before * the new time in order. * - * @example + * **Example** (Advancing the test clock) + * * ```ts * import { Effect } from "effect" * import { TestClock } from "effect/testing" @@ -428,8 +439,8 @@ export const testClockWith = ( * }) * ``` * + * @category testing * @since 2.0.0 - * @category utils */ export const adjust = (duration: Duration.Input): Effect.Effect => testClockWith((testClock) => testClock.adjust(duration)) @@ -438,7 +449,8 @@ export const adjust = (duration: Duration.Input): Effect.Effect => * Sets the current clock time to the specified `timestamp`. Any effects that * were scheduled to occur on or before the new time will be run in order. * - * @example + * **Example** (Setting the test clock time) + * * ```ts * import { Duration, Effect } from "effect" * import { TestClock } from "effect/testing" @@ -461,8 +473,8 @@ export const adjust = (duration: Duration.Input): Effect.Effect => * }) * ``` * + * @category testing * @since 2.0.0 - * @category utils */ export const setTime = (timestamp: number): Effect.Effect => testClockWith((testClock) => testClock.setTime(timestamp)) @@ -471,7 +483,8 @@ export const setTime = (timestamp: number): Effect.Effect => * Executes the specified effect with the live `Clock` instead of the * `TestClock`. * - * @example + * **Example** (Running with the live clock) + * * ```ts * import { Clock, Effect } from "effect" * import { TestClock } from "effect/testing" @@ -494,8 +507,8 @@ export const setTime = (timestamp: number): Effect.Effect => * }) * ``` * - * @since 2.0.0 - * @category utils + * @category testing + * @since 4.0.0 */ export const withLive = (effect: Effect.Effect): Effect.Effect => testClockWith((testClock) => testClock.withLive(effect)) diff --git a/.opencode/node_modules/effect/src/testing/TestConsole.ts b/.opencode/node_modules/effect/src/testing/TestConsole.ts index ef1173f84f42955d3034ee83c92cadae5143a8ce..aa85d3e50b9a06f4f83147117d772c804b5414ec 100644 --- a/.opencode/node_modules/effect/src/testing/TestConsole.ts +++ b/.opencode/node_modules/effect/src/testing/TestConsole.ts @@ -1,4 +1,12 @@ /** + * Provides a test implementation of the Effect `Console` service. + * + * When the test layer is provided, calls made through the Effect console APIs + * are captured in memory instead of being written to the host console. Tests can + * then assert on logged values deterministically. This module includes the + * console layer, helpers for reading captured `Console.log` and `Console.error` + * arguments, and access to the provided test console service. + * * @since 4.0.0 */ import * as Array from "../Array.ts" @@ -11,13 +19,21 @@ import * as Layer from "../Layer.ts" * It captures all console output for testing purposes while maintaining full * compatibility with the standard Console API. * + * **When to use** + * + * Use to provide a console implementation that records calls for assertions in + * tests. + * + * **Details** + * * This interface extends the standard Console interface and adds methods to * retrieve logged messages for verification in tests. * - * @example + * **Example** (Capturing console output in tests) + * * ```ts * import { Console, Effect } from "effect" - * import * as TestConsole from "effect/testing/TestConsole" + * import { TestConsole } from "effect/testing" * * const program = Effect.gen(function*() { * yield* Console.log("Hello, World!") @@ -31,18 +47,32 @@ import * as Layer from "../Layer.ts" * }).pipe(Effect.provide(TestConsole.layer)) * ``` * - * @since 4.0.0 + * @see {@link layer} for providing `TestConsole` to an effect + * @see {@link logLines} for reading captured `Console.log` calls + * @see {@link errorLines} for reading captured `Console.error` calls + * * @category models + * @since 4.0.0 */ export interface TestConsole extends Console.Console { /** * Returns an array of all items that have been logged by the program using * `Console.log` thus far. + * + * **When to use** + * + * Use to inspect captured `Console.log` calls through a `TestConsole` + * instance. */ readonly logLines: Effect.Effect> /** * Returns an array of all items that have been logged by the program using * `Console.error` thus far. + * + * **When to use** + * + * Use to inspect captured `Console.error` calls through a `TestConsole` + * instance. */ readonly errorLines: Effect.Effect> } @@ -51,30 +81,34 @@ export interface TestConsole extends Console.Console { * The `TestConsole` namespace provides types and utilities for working with * test console implementations. * - * @example - * ```ts - * // The TestConsole namespace provides types for testing - * // Use TestConsole.make to create a test console instance - * // Use TestConsole.layer to provide the service in tests - * ``` + * **When to use** + * + * Use when referring to types nested under the `TestConsole` namespace. * * @since 4.0.0 - * @category models */ export declare namespace TestConsole { /** * Represents a console method name that can be invoked on the TestConsole. * This type includes all methods available on the Console interface. * - * @example + * **When to use** + * + * Use to type the console method name recorded in a captured test console + * entry. + * + * **Example** (Typing captured console methods) + * * ```ts - * // Method represents console method names like: - * // "log", "error", "warn", "debug", "info", etc. - * // All methods from the Console interface are supported + * import type { TestConsole } from "effect/testing" + * + * const method: TestConsole.TestConsole.Method = "log" + * + * console.log(method) // "log" * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type Method = keyof Console.Console @@ -82,15 +116,26 @@ export declare namespace TestConsole { * Represents a single console method invocation captured by the TestConsole. * Each entry contains the method name and the parameters passed to it. * - * @example + * **When to use** + * + * Use to inspect or type one captured console invocation. + * + * **Example** (Typing captured console entries) + * * ```ts - * // Entry represents captured console calls with their method and parameters - * // Each entry contains: { method: string, parameters: ReadonlyArray } - * // Used internally by TestConsole to track all console operations + * import type { TestConsole } from "effect/testing" + * + * const entry: TestConsole.TestConsole.Entry = { + * method: "error", + * parameters: ["not found"] + * } + * + * console.log(entry.method) // "error" + * console.log(entry.parameters) // ["not found"] * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface Entry { readonly method: Method @@ -103,10 +148,15 @@ export declare namespace TestConsole { * The returned TestConsole implements the Console interface and provides * additional methods to retrieve logged messages. * - * @example + * **When to use** + * + * Use to construct a test console service value directly. + * + * **Example** (Creating a test console) + * * ```ts * import { Console, Effect } from "effect" - * import * as TestConsole from "effect/testing/TestConsole" + * import { TestConsole } from "effect/testing" * * const program = Effect.gen(function*() { * yield* Console.log("Debug message") @@ -120,8 +170,10 @@ export declare namespace TestConsole { * }).pipe(Effect.provide(TestConsole.layer)) * ``` * - * @since 4.0.0 + * @see {@link layer} for providing a `TestConsole` as a `Layer` + * * @category constructors + * @since 4.0.0 */ export const make = Effect.gen(function*() { const entries: Array = [] @@ -167,10 +219,15 @@ export const make = Effect.gen(function*() { * Retrieves the `TestConsole` service for this test and uses it to run the * specified workflow. * - * @example + * **When to use** + * + * Use to access the provided test console service inside an effect. + * + * **Example** (Accessing the test console service) + * * ```ts * import { Effect } from "effect" - * import * as TestConsole from "effect/testing/TestConsole" + * import { TestConsole } from "effect/testing" * * const program = TestConsole.testConsoleWith((testConsole) => * Effect.gen(function*() { @@ -186,8 +243,12 @@ export const make = Effect.gen(function*() { * ).pipe(Effect.provide(TestConsole.layer)) * ``` * + * @see {@link layer} for providing the test console service + * @see {@link logLines} for reading captured `Console.log` calls directly + * @see {@link errorLines} for reading captured `Console.error` calls directly + * + * @category testing * @since 4.0.0 - * @category utils */ export const testConsoleWith = (f: (console: TestConsole) => Effect.Effect): Effect.Effect => Console.consoleWith((console) => f(console as TestConsole)) @@ -197,10 +258,15 @@ export const testConsoleWith = (f: (console: TestConsole) => Effect.Eff * This layer can be used to provide a TestConsole implementation * for testing purposes. * - * @example + * **When to use** + * + * Use to run an effect with console calls captured by `TestConsole`. + * + * **Example** (Providing a test console layer) + * * ```ts * import { Console, Effect } from "effect" - * import * as TestConsole from "effect/testing/TestConsole" + * import { TestConsole } from "effect/testing" * * const program = Effect.gen(function*() { * yield* Console.log("This will be captured") @@ -214,8 +280,11 @@ export const testConsoleWith = (f: (console: TestConsole) => Effect.Eff * }).pipe(Effect.provide(TestConsole.layer)) * ``` * - * @since 4.0.0 + * @see {@link make} for constructing the service value directly + * @see {@link testConsoleWith} for accessing the provided test console service + * * @category layers + * @since 4.0.0 */ export const layer: Layer.Layer = Layer.effect(Console.Console)(make) as any @@ -223,10 +292,16 @@ export const layer: Layer.Layer = Layer.effect(Console.Console)(mak * Returns an array of all items that have been logged by the program using * `Console.log` thus far. * - * @example + * **When to use** + * + * Use to assert on captured `Console.log` output from a program provided with + * `TestConsole.layer`. + * + * **Example** (Reading captured log lines) + * * ```ts * import { Console, Effect } from "effect" - * import * as TestConsole from "effect/testing/TestConsole" + * import { TestConsole } from "effect/testing" * * const program = Effect.gen(function*() { * yield* Console.log("First message") @@ -244,8 +319,11 @@ export const layer: Layer.Layer = Layer.effect(Console.Console)(mak * }).pipe(Effect.provide(TestConsole.layer)) * ``` * + * @see {@link errorLines} for reading captured `Console.error` output + * @see {@link layer} for capturing console calls during a test + * + * @category testing * @since 4.0.0 - * @category utils */ export const logLines: Effect.Effect, never, never> = testConsoleWith( (console) => console.logLines @@ -255,10 +333,16 @@ export const logLines: Effect.Effect, never, never> = tes * Returns an array of all items that have been logged by the program using * `Console.error` thus far. * - * @example + * **When to use** + * + * Use to assert on captured `Console.error` output from a program provided + * with `TestConsole.layer`. + * + * **Example** (Reading captured error lines) + * * ```ts * import { Console, Effect } from "effect" - * import * as TestConsole from "effect/testing/TestConsole" + * import { TestConsole } from "effect/testing" * * const program = Effect.gen(function*() { * yield* Console.error("Error message") @@ -274,8 +358,11 @@ export const logLines: Effect.Effect, never, never> = tes * }).pipe(Effect.provide(TestConsole.layer)) * ``` * + * @see {@link logLines} for reading captured `Console.log` output + * @see {@link layer} for capturing console calls during a test + * + * @category testing * @since 4.0.0 - * @category utils */ export const errorLines: Effect.Effect, never, never> = testConsoleWith( (console) => console.errorLines diff --git a/.opencode/node_modules/effect/src/testing/TestSchema.ts b/.opencode/node_modules/effect/src/testing/TestSchema.ts index dd82cdf30475d7a95f44ffc397afb343bbe4f3ff..bf9a6587c5083731b4e7bf2db9533c8a80e084cf 100644 --- a/.opencode/node_modules/effect/src/testing/TestSchema.ts +++ b/.opencode/node_modules/effect/src/testing/TestSchema.ts @@ -1,68 +1,11 @@ /** - * Testing utilities for asserting Schema decoding, encoding, make, and - * arbitrary-generation behavior. Used in unit tests to verify that schemas - * accept, reject, and round-trip values correctly. + * Provides helpers for testing Schema behavior. * - * ## Mental model - * - * - **Asserts** – entry point: wraps a schema and exposes helpers grouped by - * operation (decoding, encoding, make, arbitrary, round-trip). - * - **Decoding** – returned by `asserts.decoding()`; has `succeed` / `fail` - * helpers that run the schema's decoder and compare the result. - * - **Encoding** – returned by `asserts.encoding()`; mirrors {@link Decoding} - * but exercises the encoder direction. - * - Every assertion is async (`Promise`) because parsing may involve - * effectful schemas. - * - `succeed` with one argument asserts identity (output equals input); - * with two arguments asserts a specific expected output. - * - `fail` always takes the input and the expected error message string. - * - * ## Common tasks - * - * - Assert decoding succeeds / fails → `new Asserts(schema).decoding().succeed(…)` / `.fail(…)` - * - Assert encoding succeeds / fails → `new Asserts(schema).encoding().succeed(…)` / `.fail(…)` - * - Assert make succeeds / fails → `new Asserts(schema).make().succeed(…)` / `.fail(…)` - * - Verify round-trip (encode then decode) → `new Asserts(schema).verifyLosslessTransformation()` - * - Verify arbitrary generation → `new Asserts(schema).arbitrary().verifyGeneration()` - * - Compare AST of struct fields → `Asserts.ast.fields.equals(a, b)` - * - Provide a service dependency for decoding → `asserts.decoding().provide(key, impl)` - * - * ## Gotchas - * - * - `succeed` uses `assert.deepStrictEqual`, so reference equality is not - * required but structural equality is. - * - `fail` compares against the stringified `Issue`, not the `Issue` object - * itself. Pass the exact multiline string the issue produces. - * - `verifyLosslessTransformation` and `arbitrary().verifyGeneration` run - * property-based tests via FastCheck; default run count is 20 for - * `verifyGeneration`. - * - * ## Quickstart - * - * **Example** (Basic decoding and encoding assertions) - * - * ```ts - * import { Schema } from "effect" - * import { TestSchema } from "effect/testing" - * - * const schema = Schema.NumberFromString - * const asserts = new TestSchema.Asserts(schema) - * - * // decoding - * const decoding = asserts.decoding() - * await decoding.succeed("1", 1) - * await decoding.fail(null, "Expected string, got null") - * - * // encoding - * const encoding = asserts.encoding() - * await encoding.succeed(1, "1") - * ``` - * - * ## See also - * - * - {@link Asserts} - * - {@link Decoding} - * - {@link Encoding} + * These utilities assert how schemas construct values, decode input, encode + * output, generate arbitrary values, and round-trip between encoded and decoded + * forms. The `Asserts` class groups the common checks for one schema, while + * `Decoding` and `Encoding` can be used directly when a test only needs one + * direction. * * @since 4.0.0 */ @@ -72,20 +15,17 @@ import * as Effect from "../Effect.ts" import * as Record from "../Record.ts" import * as Result from "../Result.ts" import * as Schema from "../Schema.ts" -import * as AST from "../SchemaAST.ts" -import type * as Issue from "../SchemaIssue.ts" -import * as Parser from "../SchemaParser.ts" +import * as SchemaAST from "../SchemaAST.ts" +import type * as SchemaIssue from "../SchemaIssue.ts" +import * as SchemaParser from "../SchemaParser.ts" import * as FastCheck from "../testing/FastCheck.ts" /** - * Entry point for schema test assertions. Wraps a schema and exposes - * operation-specific helpers: {@link Decoding}, {@link Encoding}, make, - * arbitrary generation, and round-trip verification. + * Provides schema test assertions for decoding, encoding, make, arbitrary generation, and round-trip verification. + * + * **When to use** * - * When to use: - * - You are writing unit tests for a schema's decoding, encoding, or - * construction behavior. - * - You want property-based round-trip or generation checks. + * Use when writing schema unit tests for decoding, encoding, construction, property-based round-trip, or generation behavior. * * **Example** (Decoding and encoding a struct) * @@ -105,18 +45,21 @@ import * as FastCheck from "../testing/FastCheck.ts" * * @see {@link Decoding} * @see {@link Encoding} - * + * @category testing * @since 4.0.0 */ export class Asserts { /** - * Static helpers for comparing schema AST structures. Useful when you need - * to assert that two field or element definitions produce the same AST. + * Static helpers for comparing schema AST structures. + * + * **When to use** * - * - `ast.fields.equals(a, b)` – compares struct field ASTs via - * `assert.deepStrictEqual`. - * - `ast.elements.equals(a, b)` – compares tuple element ASTs via - * `assert.deepStrictEqual`. + * Use to assert that two schema field or tuple element definitions produce + * the same AST structure. + * + * **Details** + * + * `ast.fields.equals(a, b)` compares struct field ASTs via `assert.deepStrictEqual`. `ast.elements.equals(a, b)` compares tuple element ASTs via `assert.deepStrictEqual`. * * **Example** (Comparing struct fields) * @@ -132,12 +75,12 @@ export class Asserts { static ast = { fields: { equals: (a: Schema.Struct.Fields, b: Schema.Struct.Fields) => { - assert.deepStrictEqual(Record.map(a, AST.getAST), Record.map(b, AST.getAST)) + assert.deepStrictEqual(Record.map(a, SchemaAST.getAST), Record.map(b, SchemaAST.getAST)) } }, elements: { equals: (a: Schema.Tuple.Elements, b: Schema.Tuple.Elements) => { - assert.deepStrictEqual(a.map(AST.getAST), b.map(AST.getAST)) + assert.deepStrictEqual(a.map(SchemaAST.getAST), b.map(SchemaAST.getAST)) } } } as const @@ -147,12 +90,16 @@ export class Asserts { this.schema = schema } /** - * Returns an object with `succeed` and `fail` helpers for testing the - * schema's `make` operation. + * Returns an object with `succeed` and `fail` helpers for testing the schema's `make` operation. + * + * **When to use** + * + * Use to assert how `Schema.make` accepts, transforms, or rejects + * construction input for this schema. * - * - `succeed(input)` – asserts make returns the input unchanged. - * - `succeed(input, expected)` – asserts make returns `expected`. - * - `fail(input, message)` – asserts make fails with `message`. + * **Details** + * + * `succeed(input)` asserts make returns the input unchanged. `succeed(input, expected)` asserts make returns `expected`. `fail(input, message)` asserts make fails with `message`. * * **Example** (Testing make) * @@ -164,15 +111,18 @@ export class Asserts { * const asserts = new TestSchema.Asserts(schema) * await asserts.make().succeed("hello") * ``` + * + * @see {@link decoding} for assertions against decoded input + * @see {@link encoding} for assertions against encoded output */ make(options?: Schema.MakeOptions) { - const makeEffect = Parser.makeEffect(this.schema) + const makeEffect = SchemaParser.makeEffect(this.schema) async function succeed(input: S["Type"]): Promise async function succeed(input: S["~type.make.in"], expected: S["Type"]): Promise async function succeed(input: S["~type.make.in"], expected?: S["Type"]) { const r = await Effect.runPromise( makeEffect(input, options).pipe( - Effect.mapError((issue) => issue.toString()), + Effect.mapErrorEager((issue) => issue.toString()), Effect.result ) ) @@ -184,7 +134,7 @@ export class Asserts { async fail(input: unknown, message: string) { const r = await Effect.runPromise( makeEffect(input, options).pipe( - Effect.mapError((issue) => issue.toString()), + Effect.mapErrorEager((issue) => issue.toString()), Effect.result ) ) @@ -193,13 +143,16 @@ export class Asserts { } } /** - * Runs a property-based test that encodes arbitrary values and then decodes - * them, asserting the decoded value equals the original. Useful for verifying - * that a codec is lossless (encode followed by decode is identity). + * Runs a property-based test that encodes arbitrary values and then decodes them, asserting the decoded value equals the original. + * + * **When to use** + * + * Use to verify that generated schema values survive an encode-then-decode + * round trip. * - * - Uses FastCheck to generate arbitrary values matching the schema's Type. - * - Fails the test if any generated value does not round-trip. - * - Pass `options.params` to control FastCheck parameters (e.g. `numRuns`). + * **Details** + * + * FastCheck generates arbitrary values matching the schema's `Type`. The assertion fails if any generated value does not round-trip. Pass `options.params` to control FastCheck parameters such as `numRuns`. * * **Example** (Round-trip verification) * @@ -210,19 +163,21 @@ export class Asserts { * const asserts = new TestSchema.Asserts(Schema.NumberFromString) * await asserts.verifyLosslessTransformation() * ``` + * + * @see {@link arbitrary} for checking that generated values satisfy the schema */ verifyLosslessTransformation>(this: Asserts, options?: { readonly params?: FastCheck.Parameters<[S["Type"]]> }) { - const decodeUnknownEffect = Parser.decodeUnknownEffect(this.schema) - const encodeEffect = Parser.encodeEffect(this.schema) + const decodeUnknownEffect = SchemaParser.decodeUnknownEffect(this.schema) + const encodeEffect = SchemaParser.encodeEffect(this.schema) const arbitrary = Schema.toArbitrary(this.schema) return FastCheck.assert( FastCheck.asyncProperty(arbitrary, async (t) => { const r = await Effect.runPromise( encodeEffect(t).pipe( - Effect.flatMap((e) => decodeUnknownEffect(e)), - Effect.mapError((issue) => issue.toString()), + Effect.flatMapEager((e) => decodeUnknownEffect(e)), + Effect.mapErrorEager((issue) => issue.toString()), Effect.result ) ) @@ -232,10 +187,15 @@ export class Asserts { ) } /** - * Returns a {@link Decoding} instance for this schema, providing `succeed` - * and `fail` helpers to test decoding behavior. + * Returns a {@link Decoding} instance for this schema with helpers for decoding assertions. + * + * **When to use** + * + * Use to test how unknown input is decoded into the schema's type. * - * - Pass `parseOptions` to control error reporting (e.g. `{ errors: "all" }`). + * **Details** + * + * Pass `parseOptions` to control error reporting, for example `{ errors: "all" }`. * * **Example** (Decoding assertions) * @@ -250,17 +210,23 @@ export class Asserts { * ``` * * @see {@link Decoding} + * @see {@link encoding} for assertions in the opposite direction */ decoding(options?: { - readonly parseOptions?: AST.ParseOptions | undefined + readonly parseOptions?: SchemaAST.ParseOptions | undefined }) { return new Decoding(this.schema, options) } /** - * Returns an {@link Encoding} instance for this schema, providing `succeed` - * and `fail` helpers to test encoding behavior. + * Returns an {@link Encoding} instance for this schema with helpers for encoding assertions. + * + * **When to use** + * + * Use to test how schema values are encoded into their external form. + * + * **Details** * - * - Pass `parseOptions` to control error reporting (e.g. `{ errors: "all" }`). + * Pass `parseOptions` to control error reporting, for example `{ errors: "all" }`. * * **Example** (Encoding assertions) * @@ -274,19 +240,24 @@ export class Asserts { * ``` * * @see {@link Encoding} + * @see {@link decoding} for assertions in the opposite direction */ encoding(options?: { - readonly parseOptions?: AST.ParseOptions | undefined + readonly parseOptions?: SchemaAST.ParseOptions | undefined }) { return new Encoding(this.schema, options) } /** - * Returns an object with property-based testing helpers for the schema's - * arbitrary generator. + * Returns an object with property-based testing helpers for the schema's arbitrary generator. * - * - `verifyGeneration()` – generates arbitrary values and asserts each - * satisfies the schema's `is` predicate. Defaults to 20 runs. - * - Pass `options.params` to override FastCheck parameters. + * **When to use** + * + * Use to verify that arbitrary values generated for this schema satisfy the + * schema's predicate. + * + * **Details** + * + * `verifyGeneration()` generates arbitrary values and asserts each value satisfies the schema's `is` predicate. It defaults to 20 runs. Pass `options.params` to override FastCheck parameters. * * **Example** (Verifying arbitrary generation) * @@ -297,6 +268,8 @@ export class Asserts { * const asserts = new TestSchema.Asserts(Schema.String) * asserts.arbitrary().verifyGeneration() * ``` + * + * @see {@link verifyLosslessTransformation} for property-based round-trip checks */ arbitrary>(this: Asserts) { const schema = this.schema @@ -314,22 +287,15 @@ export class Asserts { } /** - * Decoding test helper. Wraps a schema and exposes `succeed` and `fail` - * methods that run the schema's decoder and compare the result. + * Provides decoding test assertions through `succeed` and `fail` methods that run the schema's decoder and compare the result. * - * When to use: - * - You want to assert that specific inputs decode to expected values. - * - You want to assert that invalid inputs produce specific error messages. - * - You need to provide services required by the schema's decoding pipeline. + * **When to use** * - * Behavior: - * - All assertions are async and use `assert.deepStrictEqual` internally. - * - `succeed(input)` asserts the decoded output equals `input` (identity). - * - `succeed(input, expected)` asserts the decoded output equals `expected`. - * - `fail(input, message)` asserts decoding fails and the stringified issue - * equals `message`. - * - `provide(key, impl)` returns a new `Decoding` with the service injected - * into the decoding context. + * Use when you want to assert that specific inputs decode to expected values, invalid inputs produce specific error messages, or schemas receive required decoding services. + * + * **Details** + * + * All assertions are async and use `assert.deepStrictEqual` internally. `succeed(input)` asserts the decoded output equals `input`; `succeed(input, expected)` asserts it equals `expected`; `fail(input, message)` asserts decoding fails and the stringified issue equals `message`. `provide(key, impl)` returns a new `Decoding` with the service injected into the decoding context. * * **Example** (Decoding with service provision) * @@ -344,23 +310,23 @@ export class Asserts { * * @see {@link Asserts} * @see {@link Encoding} - * + * @category testing * @since 4.0.0 */ export class Decoding { readonly schema: S readonly decodeUnknownEffect: ( input: unknown, - options?: AST.ParseOptions - ) => Effect.Effect + options?: SchemaAST.ParseOptions + ) => Effect.Effect readonly options?: { - readonly parseOptions?: AST.ParseOptions | undefined + readonly parseOptions?: SchemaAST.ParseOptions | undefined } | undefined constructor(schema: S, options?: { - readonly parseOptions?: AST.ParseOptions | undefined + readonly parseOptions?: SchemaAST.ParseOptions | undefined }) { this.schema = schema - this.decodeUnknownEffect = Parser.decodeUnknownEffect(schema) + this.decodeUnknownEffect = SchemaParser.decodeUnknownEffect(schema) this.options = options } /** @@ -368,6 +334,10 @@ export class Decoding { * output equals the input. With two arguments, asserts the output equals * `expected`. * + * **When to use** + * + * Use to verify successful decoding for one input case. + * * **Example** (Identity and transformed decoding) * * ```ts @@ -377,6 +347,8 @@ export class Decoding { * const decoding = new TestSchema.Asserts(Schema.NumberFromString).decoding() * await decoding.succeed("1", 1) // transformed * ``` + * + * @see {@link fail} for asserting decoding failures */ async succeed>( this: Decoding, @@ -394,7 +366,7 @@ export class Decoding { ) { const r = await Effect.runPromise( this.decodeUnknownEffect(input, this.options?.parseOptions).pipe( - Effect.mapError((issue) => issue.toString()), + Effect.mapErrorEager((issue) => issue.toString()), Effect.result ) ) @@ -405,6 +377,10 @@ export class Decoding { * Asserts that decoding `input` fails and the stringified issue equals * `message`. * + * **When to use** + * + * Use to verify that invalid decoding input produces the expected issue text. + * * **Example** (Asserting a decoding failure) * * ```ts @@ -414,6 +390,8 @@ export class Decoding { * const decoding = new TestSchema.Asserts(Schema.String).decoding() * await decoding.fail(42, "Expected string, got 42") * ``` + * + * @see {@link succeed} for asserting successful decoding */ async fail>( this: Decoding, @@ -422,18 +400,18 @@ export class Decoding { ) { const r = await Effect.runPromise( this.decodeUnknownEffect(input, this.options?.parseOptions).pipe( - Effect.mapError((issue) => issue.toString()), + Effect.mapErrorEager((issue) => issue.toString()), Effect.result ) ) assert.deepStrictEqual(r, Result.fail(message)) } /** - * Returns a new {@link Decoding} instance with the given service injected - * into the decoding effect context. Use this when the schema's decoder - * requires a service dependency. + * Returns a new {@link Decoding} instance with the given service injected into the decoding effect context. + * + * **When to use** * - * - Does not mutate the current instance; returns a new one. + * Use when the schema's decoder requires a service dependency. * * @see {@link Encoding.provide} */ @@ -449,23 +427,15 @@ export class Decoding { } /** - * Encoding test helper. Mirrors {@link Decoding} but exercises the schema's - * encoder direction. + * Provides encoding test assertions through `succeed` and `fail` methods that run the schema's encoder and compare the result. + * + * **When to use** + * + * Use when you want to assert that specific values encode to expected outputs, invalid inputs produce specific error messages, or schemas receive required encoding services. * - * When to use: - * - You want to assert that specific values encode to expected outputs. - * - You want to assert that invalid inputs produce specific error messages - * during encoding. - * - You need to provide services required by the schema's encoding pipeline. + * **Details** * - * Behavior: - * - All assertions are async and use `assert.deepStrictEqual` internally. - * - `succeed(input)` asserts the encoded output equals `input` (identity). - * - `succeed(input, expected)` asserts the encoded output equals `expected`. - * - `fail(input, message)` asserts encoding fails and the stringified issue - * equals `message`. - * - `provide(key, impl)` returns a new `Encoding` with the service injected - * into the encoding context. + * All assertions are async and use `assert.deepStrictEqual` internally. `succeed(input)` asserts the encoded output equals `input`; `succeed(input, expected)` asserts it equals `expected`; `fail(input, message)` asserts encoding fails and the stringified issue equals `message`. `provide(key, impl)` returns a new `Encoding` with the service injected into the encoding context. * * **Example** (Encoding assertions) * @@ -480,22 +450,23 @@ export class Decoding { * @see {@link Asserts} * @see {@link Decoding} * + * @category testing * @since 4.0.0 */ -class Encoding { +export class Encoding { readonly schema: S readonly encodeUnknownEffect: ( input: unknown, - options?: AST.ParseOptions - ) => Effect.Effect + options?: SchemaAST.ParseOptions + ) => Effect.Effect readonly options?: { - readonly parseOptions?: AST.ParseOptions | undefined + readonly parseOptions?: SchemaAST.ParseOptions | undefined } | undefined constructor(schema: S, options?: { - readonly parseOptions?: AST.ParseOptions | undefined + readonly parseOptions?: SchemaAST.ParseOptions | undefined }) { this.schema = schema - this.encodeUnknownEffect = Parser.encodeUnknownEffect(schema) + this.encodeUnknownEffect = SchemaParser.encodeUnknownEffect(schema) this.options = options } /** @@ -503,6 +474,10 @@ class Encoding { * output equals the input. With two arguments, asserts the output equals * `expected`. * + * **When to use** + * + * Use to verify successful encoding for one input case. + * * **Example** (Identity and transformed encoding) * * ```ts @@ -512,6 +487,8 @@ class Encoding { * const encoding = new TestSchema.Asserts(Schema.NumberFromString).encoding() * await encoding.succeed(1, "1") // transformed * ``` + * + * @see {@link fail} for asserting encoding failures */ async succeed>( this: Encoding, @@ -529,7 +506,7 @@ class Encoding { ) { const r = await Effect.runPromise( this.encodeUnknownEffect(input, this.options?.parseOptions).pipe( - Effect.mapError((issue) => issue.toString()), + Effect.mapErrorEager((issue) => issue.toString()), Effect.result ) ) @@ -540,6 +517,10 @@ class Encoding { * Asserts that encoding `input` fails and the stringified issue equals * `message`. * + * **When to use** + * + * Use to verify that invalid encoding input produces the expected issue text. + * * **Example** (Asserting an encoding failure) * * ```ts @@ -549,6 +530,8 @@ class Encoding { * const encoding = new TestSchema.Asserts(Schema.NumberFromString).encoding() * await encoding.fail("not-a-number", "Expected number, got \"not-a-number\"") * ``` + * + * @see {@link succeed} for asserting successful encoding */ async fail>( this: Encoding, @@ -557,18 +540,18 @@ class Encoding { ) { const r = await Effect.runPromise( this.encodeUnknownEffect(input, this.options?.parseOptions).pipe( - Effect.mapError((issue) => issue.toString()), + Effect.mapErrorEager((issue) => issue.toString()), Effect.result ) ) assert.deepStrictEqual(r, Result.fail(message)) } /** - * Returns a new {@link Encoding} instance with the given service injected - * into the encoding effect context. Use this when the schema's encoder - * requires a service dependency. + * Returns a new {@link Encoding} instance with the given service injected into the encoding effect context. + * + * **When to use** * - * - Does not mutate the current instance; returns a new one. + * Use when the schema's encoder requires a service dependency. * * @see {@link Decoding.provide} */ diff --git a/.opencode/node_modules/effect/src/testing/index.ts b/.opencode/node_modules/effect/src/testing/index.ts index 459557cbaba4896b74b1063f0e1537ddd8a29d74..35b26c76bf9980e797de9f4b7046fcc915f5a37d 100644 --- a/.opencode/node_modules/effect/src/testing/index.ts +++ b/.opencode/node_modules/effect/src/testing/index.ts @@ -5,14 +5,6 @@ // @barrel: Auto-generated exports. Do not edit manually. /** - * This module provides a re-export of the fast-check library for property-based testing. - * Fast-check is a property-based testing framework that generates random test cases - * to validate that properties hold true for a wide range of inputs. - * - * Property-based testing is a testing methodology where you specify properties that - * should hold true for your functions, and the framework generates many random test - * cases to try to find counterexamples. - * * @since 3.10.0 */ export * as FastCheck from "./FastCheck.ts" @@ -28,71 +20,6 @@ export * as TestClock from "./TestClock.ts" export * as TestConsole from "./TestConsole.ts" /** - * Testing utilities for asserting Schema decoding, encoding, make, and - * arbitrary-generation behavior. Used in unit tests to verify that schemas - * accept, reject, and round-trip values correctly. - * - * ## Mental model - * - * - **Asserts** – entry point: wraps a schema and exposes helpers grouped by - * operation (decoding, encoding, make, arbitrary, round-trip). - * - **Decoding** – returned by `asserts.decoding()`; has `succeed` / `fail` - * helpers that run the schema's decoder and compare the result. - * - **Encoding** – returned by `asserts.encoding()`; mirrors {@link Decoding} - * but exercises the encoder direction. - * - Every assertion is async (`Promise`) because parsing may involve - * effectful schemas. - * - `succeed` with one argument asserts identity (output equals input); - * with two arguments asserts a specific expected output. - * - `fail` always takes the input and the expected error message string. - * - * ## Common tasks - * - * - Assert decoding succeeds / fails → `new Asserts(schema).decoding().succeed(…)` / `.fail(…)` - * - Assert encoding succeeds / fails → `new Asserts(schema).encoding().succeed(…)` / `.fail(…)` - * - Assert make succeeds / fails → `new Asserts(schema).make().succeed(…)` / `.fail(…)` - * - Verify round-trip (encode then decode) → `new Asserts(schema).verifyLosslessTransformation()` - * - Verify arbitrary generation → `new Asserts(schema).arbitrary().verifyGeneration()` - * - Compare AST of struct fields → `Asserts.ast.fields.equals(a, b)` - * - Provide a service dependency for decoding → `asserts.decoding().provide(key, impl)` - * - * ## Gotchas - * - * - `succeed` uses `assert.deepStrictEqual`, so reference equality is not - * required but structural equality is. - * - `fail` compares against the stringified `Issue`, not the `Issue` object - * itself. Pass the exact multiline string the issue produces. - * - `verifyLosslessTransformation` and `arbitrary().verifyGeneration` run - * property-based tests via FastCheck; default run count is 20 for - * `verifyGeneration`. - * - * ## Quickstart - * - * **Example** (Basic decoding and encoding assertions) - * - * ```ts - * import { Schema } from "effect" - * import { TestSchema } from "effect/testing" - * - * const schema = Schema.NumberFromString - * const asserts = new TestSchema.Asserts(schema) - * - * // decoding - * const decoding = asserts.decoding() - * await decoding.succeed("1", 1) - * await decoding.fail(null, "Expected string, got null") - * - * // encoding - * const encoding = asserts.encoding() - * await encoding.succeed(1, "1") - * ``` - * - * ## See also - * - * - {@link Asserts} - * - {@link Decoding} - * - {@link Encoding} - * * @since 4.0.0 */ export * as TestSchema from "./TestSchema.ts" diff --git a/.opencode/node_modules/effect/src/unstable/ai/AiError.ts b/.opencode/node_modules/effect/src/unstable/ai/AiError.ts index b8c1d7fe3f1792e7d189bc544cc5aa0034bea657..c8fab5e0ce776b2da02a9e5512c952371e9a5bc4 100644 --- a/.opencode/node_modules/effect/src/unstable/ai/AiError.ts +++ b/.opencode/node_modules/effect/src/unstable/ai/AiError.ts @@ -1,82 +1,15 @@ /** - * The `AiError` module provides comprehensive, provider-agnostic error handling - * for AI operations. - * - * This module uses the `reason` pattern where `AiError` is a top-level - * wrapper error containing `module`, `method`, and a `reason` field that holds - * the semantic error. This design enables ergonomic error handling while - * preserving rich context about failures. - * - * ## Semantic Error Categories - * - * - **RateLimitError** - Request throttled (429s, provider-specific limits) - * - **QuotaExhaustedError** - Account/billing limits reached - * - **AuthenticationError** - Invalid/expired credentials - * - **ContentPolicyError** - Input/output violated content policy - * - **InvalidRequestError** - Malformed request parameters - * - **InvalidUserInputError** - Prompt contains unsupported content - * - **InternalProviderError** - Provider-side failures (5xx) - * - **NetworkError** - Transport-level failures - * - **InvalidOutputError** - LLM output parsing/validation failures - * - **StructuredOutputError** - LLM generated text that doesn't conform to structured output schema - * - **UnsupportedSchemaError** - Codec transformer rejected a schema with unsupported constructs - * - **UnknownError** - Catch-all for unknown errors - * - * ## Tool Call Errors - * - * - **ToolNotFoundError** - Model requested non-existent tool - * - **ToolParameterValidationError** - Tool call params failed validation - * - **InvalidToolResultError** - Tool handler returned invalid result - * - **ToolResultEncodingError** - Tool result encoding failed - * - **ToolConfigurationError** - Provider tool misconfigured - * - * ## Retryability - * - * Each reason type has an `isRetryable` getter indicating whether the error is - * transient. Some errors also provide a `retryAfter` duration hint. - * - * @example - * ```ts - * import { Effect, Match } from "effect" - * import type { AiError } from "effect/unstable/ai" - * - * // Handle errors using Match on the reason - * const handleAiError = Match.type().pipe( - * Match.when( - * { reason: { _tag: "RateLimitError" } }, - * (err) => Effect.logWarning(`Rate limited, retry after ${err.retryAfter}`) - * ), - * Match.when( - * { reason: { _tag: "AuthenticationError" } }, - * (err) => Effect.logError(`Auth failed: ${err.reason.kind}`) - * ), - * Match.when( - * { reason: { isRetryable: true } }, - * (err) => Effect.logWarning(`Transient error, retrying: ${err.message}`) - * ), - * Match.orElse((err) => Effect.logError(`Permanent error: ${err.message}`)) - * ) - * ``` + * Defines shared errors for AI operations. * - * @example - * ```ts - * import { Duration, Effect } from "effect" - * import { AiError } from "effect/unstable/ai" - * - * // Create an AiError with a reason - * const error = AiError.make({ - * module: "OpenAI", - * method: "completion", - * reason: new AiError.RateLimitError({ - * retryAfter: Duration.seconds(60) - * }) - * }) + * `AiError` records where a failure happened and stores the detailed reason in a + * `reason` field. Those reasons cover transport problems, provider responses, + * rate limits, authentication, content policy failures, invalid requests, + * invalid output, unsupported schemas, tool failures, invalid user input, and + * unknown failures. This module also includes metadata schemas, guards, + * constructors, and helpers for converting HTTP response information into AI + * error reasons. * - * console.log(error.isRetryable) // true - * console.log(error.message) // "OpenAI.completion: Rate limit exceeded. Retry after 1 minute" - * ``` - * - * @since 1.0.0 + * @since 4.0.0 */ import * as Duration from "../../Duration.ts" import * as Effect from "../../Effect.ts" @@ -113,11 +46,14 @@ const redactHeaders = (headers: Record): Record /** * Error indicating a network-level failure before receiving a response. * + * **Details** + * * This error is raised when issues arise before receiving an HTTP response, * such as network connectivity problems, request encoding issues, or invalid * URLs. * - * @example + * **Example** (Creating a network error) + * * ```ts * import { AiError } from "effect/unstable/ai" * @@ -138,8 +74,8 @@ const redactHeaders = (headers: Record): Record * // "Transport: Connection timeout after 30 seconds (POST https://api.openai.com/v1/completions)" * ``` * - * @since 1.0.0 * @category reason + * @since 4.0.0 */ export class NetworkError extends Schema.ErrorClass( "effect/ai/AiError/NetworkError" @@ -150,14 +86,16 @@ export class NetworkError extends Schema.ErrorClass( description: Schema.optional(Schema.String) }) { /** - * @since 1.0.0 + * Marks `NetworkError` as a semantic AI error reason for runtime guards. + * + * @since 4.0.0 */ readonly [ReasonTypeId] = ReasonTypeId /** * Transport errors are retryable; encoding and URL errors are not. * - * @since 1.0.0 + * @since 4.0.0 */ get isRetryable(): boolean { return this.reason === "TransportError" @@ -166,7 +104,8 @@ export class NetworkError extends Schema.ErrorClass( /** * Creates a NetworkError from a platform HttpClientError.RequestError. * - * @example + * **Example** (Creating a network error from a request error) + * * ```ts * import { AiError } from "effect/unstable/ai" * import type { HttpClientError } from "effect/unstable/http" @@ -176,8 +115,7 @@ export class NetworkError extends Schema.ErrorClass( * const aiError = AiError.NetworkError.fromRequestError(platformError) * ``` * - * @since 1.0.0 - * @category constructors + * @since 4.0.0 */ static fromRequestError(error: HttpClientError.RequestError): NetworkError { return new NetworkError({ @@ -238,18 +176,25 @@ export class NetworkError extends Schema.ErrorClass( /** * Schema for provider-specific metadata which can be attached to error reasons. * - * Provider-specific metadata is namespaced by provider and has the structure: + * **Details** * - * ``` - * { - * "": { - * // Provider-specific metadata (e.g. errorCode, requestId, etc.) - * } + * Provider-specific metadata is namespaced by provider name. Each provider + * value can contain arbitrary mutable JSON metadata or `null`. + * + * **Example** (Metadata shape) + * + * ```ts + * const metadata = { + * openai: { + * errorCode: "rate_limit_exceeded", + * requestId: "req_123" + * }, + * anthropic: null * } * ``` * - * @since 1.0.0 * @category schemas + * @since 4.0.0 */ export const ProviderMetadata: Schema.$Record< Schema.String, @@ -257,96 +202,108 @@ export const ProviderMetadata: Schema.$Record< > = Schema.Record(Schema.String, Schema.NullOr(Schema.MutableJson)) /** - * @since 1.0.0 + * Type of provider-specific metadata attached to AI error reasons. + * + * **Details** + * + * Metadata is keyed by provider name, and each provider value is either mutable + * JSON metadata or `null`. + * * @category models + * @since 4.0.0 */ export type ProviderMetadata = typeof ProviderMetadata.Type /** * Provider-specific metadata attached to `RateLimitError`. * - * @since 1.0.0 - * @category provider options + * @category configuration + * @since 4.0.0 */ export interface RateLimitErrorMetadata extends ProviderMetadata {} /** * Provider-specific metadata attached to `QuotaExhaustedError`. * - * @since 1.0.0 - * @category provider options + * @category configuration + * @since 4.0.0 */ export interface QuotaExhaustedErrorMetadata extends ProviderMetadata {} /** * Provider-specific metadata attached to `AuthenticationError`. * - * @since 1.0.0 - * @category provider options + * @category configuration + * @since 4.0.0 */ export interface AuthenticationErrorMetadata extends ProviderMetadata {} /** * Provider-specific metadata attached to `ContentPolicyError`. * - * @since 1.0.0 - * @category provider options + * @category configuration + * @since 4.0.0 */ export interface ContentPolicyErrorMetadata extends ProviderMetadata {} /** * Provider-specific metadata attached to `InvalidRequestError`. * - * @since 1.0.0 - * @category provider options + * @category configuration + * @since 4.0.0 */ export interface InvalidRequestErrorMetadata extends ProviderMetadata {} /** * Provider-specific metadata attached to `InternalProviderError`. * - * @since 1.0.0 - * @category provider options + * @category configuration + * @since 4.0.0 */ export interface InternalProviderErrorMetadata extends ProviderMetadata {} /** * Provider-specific metadata attached to `InvalidOutputError`. * - * @since 1.0.0 - * @category provider options + * @category configuration + * @since 4.0.0 */ export interface InvalidOutputErrorMetadata extends ProviderMetadata {} /** * Provider-specific metadata attached to `StructuredOutputError`. * - * @since 1.0.0 - * @category provider options + * @category configuration + * @since 4.0.0 */ export interface StructuredOutputErrorMetadata extends ProviderMetadata {} /** * Provider-specific metadata attached to `UnsupportedSchemaError`. * - * @since 1.0.0 - * @category provider options + * @category configuration + * @since 4.0.0 */ export interface UnsupportedSchemaErrorMetadata extends ProviderMetadata {} /** * Provider-specific metadata attached to `UnknownError`. * - * @since 1.0.0 - * @category provider options + * @category configuration + * @since 4.0.0 */ export interface UnknownErrorMetadata extends ProviderMetadata {} /** - * Token usage information from AI operations. + * Schema for token usage information from AI operations. + * + * **Details** + * + * Schema for optional provider-reported token counts for prompt tokens, + * completion tokens, and total tokens. * - * @since 1.0.0 * @category schemas + * @since 4.0.0 */ export const UsageInfo = Schema.Struct({ promptTokens: Schema.optional(Schema.Number), @@ -355,10 +312,23 @@ export const UsageInfo = Schema.Struct({ }).annotate({ identifier: "UsageInfo" }) /** - * Combined HTTP context for error reporting. + * Schema for the combined HTTP context used in error reporting. + * + * **When to use** + * + * Use to attach request details, optional response details, and optional body + * text to AI provider errors. + * + * **Details** + * + * Includes the required request details plus optional response details and raw + * response body. + * + * @see {@link HttpRequestDetails} for captured request details + * @see {@link HttpResponseDetails} for captured response details * - * @since 1.0.0 * @category schemas + * @since 4.0.0 */ export const HttpContext = Schema.Struct({ request: HttpRequestDetails, @@ -373,10 +343,13 @@ export const HttpContext = Schema.Struct({ /** * Error indicating the request was rate limited. * + * **Details** + * * Rate limit errors are always retryable. When `retryAfter` is provided, * callers should wait that duration before retrying. * - * @example + * **Example** (Creating a rate limit error) + * * ```ts * import { Duration } from "effect" * import { AiError } from "effect/unstable/ai" @@ -389,8 +362,8 @@ export const HttpContext = Schema.Struct({ * console.log(rateLimitError.message) // "Rate limit exceeded. Retry after 1 minute" * ``` * - * @since 1.0.0 * @category reason + * @since 4.0.0 */ export class RateLimitError extends Schema.ErrorClass( "effect/ai/AiError/RateLimitError" @@ -401,14 +374,16 @@ export class RateLimitError extends Schema.ErrorClass( http: Schema.optional(HttpContext) }) { /** - * @since 1.0.0 + * Marks `RateLimitError` as a semantic AI error reason for runtime guards. + * + * @since 4.0.0 */ readonly [ReasonTypeId] = ReasonTypeId /** * Rate limit errors are always retryable. * - * @since 1.0.0 + * @since 4.0.0 */ get isRetryable(): boolean { return true @@ -424,9 +399,12 @@ export class RateLimitError extends Schema.ErrorClass( /** * Error indicating account or billing limits have been reached. * + * **Details** + * * Quota exhausted errors are not retryable without user action. * - * @example + * **Example** (Creating a quota exhausted error) + * * ```ts * import { AiError } from "effect/unstable/ai" * @@ -437,8 +415,8 @@ export class RateLimitError extends Schema.ErrorClass( * // "Quota exhausted. Check your account billing and usage limits." * ``` * - * @since 1.0.0 * @category reason + * @since 4.0.0 */ export class QuotaExhaustedError extends Schema.ErrorClass( "effect/ai/AiError/QuotaExhaustedError" @@ -449,14 +427,16 @@ export class QuotaExhaustedError extends Schema.ErrorClass( http: Schema.optional(HttpContext) }) { /** - * @since 1.0.0 + * Marks `QuotaExhaustedError` as a semantic AI error reason for runtime guards. + * + * @since 4.0.0 */ readonly [ReasonTypeId] = ReasonTypeId /** * Quota exhausted errors require user action and are not retryable. * - * @since 1.0.0 + * @since 4.0.0 */ get isRetryable(): boolean { return false @@ -472,9 +452,12 @@ export class QuotaExhaustedError extends Schema.ErrorClass( /** * Error indicating authentication or authorization failure. * + * **Details** + * * Authentication errors are never retryable without credential changes. * - * @example + * **Example** (Creating an authentication error) + * * ```ts * import { AiError } from "effect/unstable/ai" * @@ -487,8 +470,8 @@ export class QuotaExhaustedError extends Schema.ErrorClass( * // "InvalidKey: Verify your API key is correct" * ``` * - * @since 1.0.0 * @category reason + * @since 4.0.0 */ export class AuthenticationError extends Schema.ErrorClass( "effect/ai/AiError/AuthenticationError" @@ -499,14 +482,16 @@ export class AuthenticationError extends Schema.ErrorClass( http: Schema.optional(HttpContext) }) { /** - * @since 1.0.0 + * Marks `AuthenticationError` as a semantic AI error reason for runtime guards. + * + * @since 4.0.0 */ readonly [ReasonTypeId] = ReasonTypeId /** * Authentication errors require credential changes and are not retryable. * - * @since 1.0.0 + * @since 4.0.0 */ get isRetryable(): boolean { return false @@ -527,9 +512,12 @@ export class AuthenticationError extends Schema.ErrorClass( /** * Error indicating content policy violation. * + * **Details** + * * Content policy errors are never retryable without content changes. * - * @example + * **Example** (Creating a content policy error) + * * ```ts * import { AiError } from "effect/unstable/ai" * @@ -542,8 +530,8 @@ export class AuthenticationError extends Schema.ErrorClass( * // "Content policy violation: Input contains prohibited content" * ``` * - * @since 1.0.0 * @category reason + * @since 4.0.0 */ export class ContentPolicyError extends Schema.ErrorClass( "effect/ai/AiError/ContentPolicyError" @@ -554,14 +542,16 @@ export class ContentPolicyError extends Schema.ErrorClass( http: Schema.optional(HttpContext) }) { /** - * @since 1.0.0 + * Marks `ContentPolicyError` as a semantic AI error reason for runtime guards. + * + * @since 4.0.0 */ readonly [ReasonTypeId] = ReasonTypeId /** * Content policy errors require content changes and are not retryable. * - * @since 1.0.0 + * @since 4.0.0 */ get isRetryable(): boolean { return false @@ -575,9 +565,12 @@ export class ContentPolicyError extends Schema.ErrorClass( /** * Error indicating the request had invalid or malformed parameters. * + * **Details** + * * Invalid request errors require fixing the request and are not retryable. * - * @example + * **Example** (Creating an invalid request error) + * * ```ts * import { AiError } from "effect/unstable/ai" * @@ -592,8 +585,8 @@ export class ContentPolicyError extends Schema.ErrorClass( * // "Invalid request: parameter 'temperature' must be between 0 and 2. Temperature value 5 is out of range" * ``` * - * @since 1.0.0 * @category reason + * @since 4.0.0 */ export class InvalidRequestError extends Schema.ErrorClass( "effect/ai/AiError/InvalidRequestError" @@ -606,14 +599,16 @@ export class InvalidRequestError extends Schema.ErrorClass( http: Schema.optional(HttpContext) }) { /** - * @since 1.0.0 + * Marks `InvalidRequestError` as a semantic AI error reason for runtime guards. + * + * @since 4.0.0 */ readonly [ReasonTypeId] = ReasonTypeId /** * Invalid request errors require fixing the request and are not retryable. * - * @since 1.0.0 + * @since 4.0.0 */ get isRetryable(): boolean { return false @@ -631,9 +626,12 @@ export class InvalidRequestError extends Schema.ErrorClass( /** * Error indicating the AI provider experienced an internal error. * + * **Details** + * * Internal provider errors are typically transient and are retryable. * - * @example + * **Example** (Creating an internal provider error) + * * ```ts * import { AiError } from "effect/unstable/ai" * @@ -646,8 +644,8 @@ export class InvalidRequestError extends Schema.ErrorClass( * // "Internal provider error: Server encountered an unexpected error" * ``` * - * @since 1.0.0 * @category reason + * @since 4.0.0 */ export class InternalProviderError extends Schema.ErrorClass( "effect/ai/AiError/InternalProviderError" @@ -658,14 +656,16 @@ export class InternalProviderError extends Schema.ErrorClass( "effect/ai/AiError/InvalidOutputError" @@ -706,14 +709,16 @@ export class InvalidOutputError extends Schema.ErrorClass( usage: Schema.optional(UsageInfo) }) { /** - * @since 1.0.0 + * Marks `InvalidOutputError` as a semantic AI error reason for runtime guards. + * + * @since 4.0.0 */ readonly [ReasonTypeId] = ReasonTypeId /** * Invalid output errors are retryable since LLM outputs are non-deterministic. * - * @since 1.0.0 + * @since 4.0.0 */ get isRetryable(): boolean { return true @@ -722,7 +727,8 @@ export class InvalidOutputError extends Schema.ErrorClass( /** * Creates an InvalidOutputError from a Schema error. * - * @example + * **Example** (Creating an invalid output error from a schema error) + * * ```ts * import { Schema } from "effect" * import { AiError } from "effect/unstable/ai" @@ -732,8 +738,7 @@ export class InvalidOutputError extends Schema.ErrorClass( * const parseError = AiError.InvalidOutputError.fromSchemaError(schemaError) * ``` * - * @since 1.0.0 - * @category constructors + * @since 4.0.0 */ static fromSchemaError(error: Schema.SchemaError): InvalidOutputError { return new InvalidOutputError({ @@ -750,9 +755,12 @@ export class InvalidOutputError extends Schema.ErrorClass( * Error indicating the LLM generated text that does not conform to the * requested structured output schema. * + * **Details** + * * Structured output errors are retryable since LLM outputs are non-deterministic. * - * @example + * **Example** (Creating a structured output error) + * * ```ts * import { AiError } from "effect/unstable/ai" * @@ -766,8 +774,8 @@ export class InvalidOutputError extends Schema.ErrorClass( * // "Structured output validation failed: Expected a valid JSON object" * ``` * - * @since 1.0.0 * @category reason + * @since 4.0.0 */ export class StructuredOutputError extends Schema.ErrorClass( "effect/ai/AiError/StructuredOutputError" @@ -779,14 +787,16 @@ export class StructuredOutputError extends Schema.ErrorClass( "effect/ai/AiError/UnsupportedSchemaError" @@ -852,14 +865,16 @@ export class UnsupportedSchemaError extends Schema.ErrorClass() }) { /** - * @since 1.0.0 + * Marks `UnsupportedSchemaError` as a semantic AI error reason for runtime guards. + * + * @since 4.0.0 */ readonly [ReasonTypeId] = ReasonTypeId /** * Unsupported schema errors are not retryable because they indicate a programmer error. * - * @since 1.0.0 + * @since 4.0.0 */ get isRetryable(): boolean { return false @@ -871,11 +886,14 @@ export class UnsupportedSchemaError extends Schema.ErrorClass( "effect/ai/AiError/UnknownError" @@ -900,14 +918,16 @@ export class UnknownError extends Schema.ErrorClass( http: Schema.optional(HttpContext) }) { /** - * @since 1.0.0 + * Marks `UnknownError` as a semantic AI error reason for runtime guards. + * + * @since 4.0.0 */ readonly [ReasonTypeId] = ReasonTypeId /** * Unknown errors are not retryable by default. * - * @since 1.0.0 + * @since 4.0.0 */ get isRetryable(): boolean { return false @@ -925,10 +945,13 @@ export class UnknownError extends Schema.ErrorClass( /** * Error indicating the model requested a tool that doesn't exist in the toolkit. * + * **Details** + * * This error is retryable because the model may self-correct when provided * with the list of available tools. * - * @example + * **Example** (Creating a tool not found error) + * * ```ts * import { AiError } from "effect/unstable/ai" * @@ -942,8 +965,8 @@ export class UnknownError extends Schema.ErrorClass( * // "Tool 'unknownTool' not found. Available tools: GetWeather, GetTime" * ``` * - * @since 1.0.0 * @category reason + * @since 4.0.0 */ export class ToolNotFoundError extends Schema.ErrorClass( "effect/ai/AiError/ToolNotFoundError" @@ -953,14 +976,16 @@ export class ToolNotFoundError extends Schema.ErrorClass( availableTools: Schema.Array(Schema.String) }) { /** - * @since 1.0.0 + * Marks `ToolNotFoundError` as a semantic AI error reason for runtime guards. + * + * @since 4.0.0 */ readonly [ReasonTypeId] = ReasonTypeId /** * Tool not found errors are retryable because the model may self-correct. * - * @since 1.0.0 + * @since 4.0.0 */ get isRetryable(): boolean { return true @@ -975,10 +1000,13 @@ export class ToolNotFoundError extends Schema.ErrorClass( /** * Error indicating the model's tool call parameters failed schema validation. * + * **Details** + * * This error is retryable because the model may correct its parameters * on subsequent attempts. * - * @example + * **Example** (Creating a tool parameter validation error) + * * ```ts * import { AiError } from "effect/unstable/ai" * @@ -993,8 +1021,8 @@ export class ToolNotFoundError extends Schema.ErrorClass( * // "Invalid parameters for tool 'GetWeather': Expected string, got number" * ``` * - * @since 1.0.0 * @category reason + * @since 4.0.0 */ export class ToolParameterValidationError extends Schema.ErrorClass( "effect/ai/AiError/ToolParameterValidationError" @@ -1005,14 +1033,16 @@ export class ToolParameterValidationError extends Schema.ErrorClass( "effect/ai/AiError/InvalidToolResultError" @@ -1055,14 +1088,16 @@ export class InvalidToolResultError extends Schema.ErrorClass( "effect/ai/AiError/ToolResultEncodingError" @@ -1106,14 +1144,16 @@ export class ToolResultEncodingError extends Schema.ErrorClass( "effect/ai/AiError/ToolConfigurationError" @@ -1155,14 +1198,16 @@ export class ToolConfigurationError extends Schema.ErrorClass( "effect/ai/AiError/ToolkitRequiredError" @@ -1203,14 +1251,16 @@ export class ToolkitRequiredError extends Schema.ErrorClass( "effect/ai/AiError/InvalidUserInputError" @@ -1252,14 +1305,16 @@ export class InvalidUserInputError extends Schema.ErrorClass( "effect/ai/AiError/AiError" @@ -1403,7 +1472,7 @@ export class AiError extends Schema.ErrorClass( /** * Delegates to the underlying reason's `isRetryable` getter. * - * @since 1.0.0 + * @since 4.0.0 */ get isRetryable(): boolean { return this.reason.isRetryable @@ -1412,7 +1481,7 @@ export class AiError extends Schema.ErrorClass( /** * Delegates to the underlying reason's `retryAfter` if present. * - * @since 1.0.0 + * @since 4.0.0 */ get retryAfter(): Duration.Duration | undefined { return "retryAfter" in this.reason ? this.reason.retryAfter : undefined @@ -1426,18 +1495,16 @@ export class AiError extends Schema.ErrorClass( /** * The encoded (serialized) form of an `AiError`. * - * @since 1.0.0 * @category schemas + * @since 4.0.0 */ export type AiErrorEncoded = typeof AiError["Encoded"] /** * Type guard to check if a value is an `AiError`. * - * @param u - The value to check - * @returns `true` if the value is an `AiError`, `false` otherwise + * **Example** (Checking for an AI error) * - * @example * ```ts * import { AiError } from "effect/unstable/ai" * @@ -1452,18 +1519,16 @@ export type AiErrorEncoded = typeof AiError["Encoded"] * console.log(AiError.isAiError(aiError)) // true * ``` * - * @since 1.0.0 * @category guards + * @since 4.0.0 */ export const isAiError = (u: unknown): u is AiError => Predicate.hasProperty(u, TypeId) /** * Type guard to check if a value is an `AiErrorReason`. * - * @param u - The value to check - * @returns `true` if the value is an `AiErrorReason`, `false` otherwise + * **Example** (Checking for an AI error reason) * - * @example * ```ts * import { AiError } from "effect/unstable/ai" * @@ -1474,15 +1539,16 @@ export const isAiError = (u: unknown): u is AiError => Predicate.hasProperty(u, * console.log(AiError.isAiErrorReason(genericError)) // false * ``` * - * @since 1.0.0 * @category guards + * @since 4.0.0 */ export const isAiErrorReason = (u: unknown): u is AiErrorReason => Predicate.hasProperty(u, ReasonTypeId) /** * Creates an `AiError` with the given reason. * - * @example + * **Example** (Creating an AI error) + * * ```ts * import { Duration } from "effect" * import { AiError } from "effect/unstable/ai" @@ -1499,8 +1565,8 @@ export const isAiErrorReason = (u: unknown): u is AiErrorReason => Predicate.has * // "OpenAI.completion: Rate limit exceeded. Retry after 1 minute" * ``` * - * @since 1.0.0 * @category constructors + * @since 4.0.0 */ export const make = (params: { readonly module: string @@ -1511,9 +1577,13 @@ export const make = (params: { /** * Maps HTTP status codes to semantic error reasons. * - * Provider packages can use this as a base for provider-specific mapping. + * **When to use** + * + * Use as the base mapping when provider packages translate HTTP status codes into + * provider-specific error reasons. + * + * **Example** (Mapping an HTTP status to a reason) * - * @example * ```ts * import { AiError } from "effect/unstable/ai" * @@ -1525,8 +1595,8 @@ export const make = (params: { * console.log(reason._tag) // "RateLimitError" * ``` * - * @since 1.0.0 * @category constructors + * @since 4.0.0 */ export const reasonFromHttpStatus = (params: { readonly status: number diff --git a/.opencode/node_modules/effect/src/unstable/ai/AnthropicStructuredOutput.ts b/.opencode/node_modules/effect/src/unstable/ai/AnthropicStructuredOutput.ts index 9d361e6ff81df68f9e10bdb4edee68f1de5632ab..51810dcc4087b79d8ff3a24a9dddcd3b4d598f58 100644 --- a/.opencode/node_modules/effect/src/unstable/ai/AnthropicStructuredOutput.ts +++ b/.opencode/node_modules/effect/src/unstable/ai/AnthropicStructuredOutput.ts @@ -1,53 +1,57 @@ /** - * Provides a codec transformation for Anthropic structured output. + * Adapts Effect Schema codecs to the JSON Schema subset accepted by Anthropic + * structured output. * - * Anthropic's API has specific constraints on JSON schema support that differ - * from the full JSON Schema specification. This module transforms Effect - * `Schema.Codec` types into a form compatible with Anthropic's structured - * output requirements by: + * The main entry point returns the JSON Schema to send to Anthropic and a codec + * for decoding the model response back into the original application type. When + * Anthropic cannot express the original schema shape directly, the conversion + * rewrites supported cases such as tuples, records, optional properties, and + * `oneOf` unions. Schema kinds that cannot be represented throw during + * conversion instead of producing a lossy schema. * - * - Converting tuples to objects with string keys (tuples are unsupported) - * - Converting optional properties to nullable unions (`T | null`) - * - Converting index signatures (records) to arrays of key-value pairs - * - Converting `oneOf` unions to `anyOf` unions - * - Stripping unsupported annotations and preserving only Anthropic-compatible - * formats and descriptions - * - * @since 1.0.0 + * @since 4.0.0 */ import * as Arr from "../../Array.ts" import * as JsonSchema from "../../JsonSchema.ts" import * as Option from "../../Option.ts" import * as Predicate from "../../Predicate.ts" import * as Schema from "../../Schema.ts" -import * as AST from "../../SchemaAST.ts" -import * as Transformation from "../../SchemaTransformation.ts" +import * as SchemaAST from "../../SchemaAST.ts" +import * as SchemaTransformation from "../../SchemaTransformation.ts" +import * as LanguageModel from "./LanguageModel.ts" +import * as OpenAiStructuredOutput from "./OpenAiStructuredOutput.ts" import * as Tool from "./Tool.ts" /** - * Transforms a `Schema.Codec` into a form compatible with Anthropic's - * structured output constraints. + * Converts a `Schema.Codec` to Anthropic structured-output JSON Schema and a + * matching codec for model output. + * + * **When to use** + * + * Use when you send Effect Schema-backed structured output requests to + * Anthropic and need provider-compatible JSON Schema without losing the decoded + * application type. + * + * **Details** + * + * Returns the JSON Schema to include in the request and the codec to use when + * decoding the model response. If the input schema already fits Anthropic's + * supported JSON Schema subset, the original codec is returned unchanged. * - * The transformation walks the schema AST and rewrites constructs that - * Anthropic does not support natively: + * **Gotchas** * - * - **Tuples** are converted to objects with numeric string keys (e.g. - * `"0"`, `"1"`) since Anthropic does not support tuple schemas. Rest - * elements are placed under a `"__rest__"` key. - * - **Optional properties** are replaced with `T | null` unions, because - * Anthropic requires all properties to be present. - * - **Records** (index signatures) are converted to arrays of `[key, value]` - * pairs. - * - **`oneOf` unions** are rewritten as `anyOf` unions. - * - **Filters and annotations** are preserved where compatible (e.g. - * `description`, supported `format` values like `"date-time"`, `"email"`, - * `"uuid"`, etc.), and stripped otherwise. + * - Some schemas use a provider-safe encoded shape: tuples become objects with + * numeric string keys, records become arrays of `[key, value]` pairs, and + * optional properties become required nullable properties. + * - `oneOf` unions are emitted as `anyOf` unions. + * - Unsupported schema kinds throw during conversion instead of producing a + * lossy schema. * - * If the schema is already compatible, the original codec is returned - * unchanged. + * @see {@link LanguageModel.CodecTransformer} for the structured-output transformer contract + * @see {@link OpenAiStructuredOutput.toCodecOpenAI} for the OpenAI-specific transformer * - * @since 1.0.0 * @category Codec Transformation + * @since 4.0.0 */ export function toCodecAnthropic( schema: Schema.Codec @@ -56,8 +60,10 @@ export function toCodecAnthropic( readonly jsonSchema: JsonSchema.JsonSchema } { const to = schema.ast - const from = recur(AST.toEncoded(to)) - const codec = from === to ? schema : Schema.make(AST.decodeTo(from, to, Transformation.passthrough())) + const from = recur(SchemaAST.toEncoded(to)) + const codec = from === to + ? schema + : Schema.make(SchemaAST.decodeTo(from, to, SchemaTransformation.passthrough())) const document = JsonSchema.resolveTopLevel$ref(Schema.toJsonSchemaDocument(codec)) const jsonSchema = { ...document.schema } if (Object.keys(document.definitions).length > 0) { @@ -66,7 +72,7 @@ export function toCodecAnthropic( return { codec, jsonSchema } } -function recur(ast: AST.AST): AST.AST { +function recur(ast: SchemaAST.AST): SchemaAST.AST { switch (ast._tag) { case "Declaration": case "Void": @@ -94,14 +100,14 @@ function recur(ast: AST.AST): AST.AST { case "String": { const { annotations, filters } = get(ast) if (annotations !== undefined || filters !== undefined) { - return new AST.String(annotations, filters) + return new SchemaAST.String(annotations, filters) } return ast } case "Number": { const { annotations, filters } = get(ast) if (annotations !== undefined || filters !== undefined) { - return new AST.Number(annotations, filters) + return new SchemaAST.Number(annotations, filters) } return ast } @@ -112,7 +118,7 @@ function recur(ast: AST.AST): AST.AST { if (typeof literal === "string" || typeof literal === "number" || typeof literal === "boolean") { const { annotations, filters } = get(ast) if (annotations !== undefined || filters !== undefined) { - return new AST.Literal(ast.literal, annotations, filters) + return new SchemaAST.Literal(ast.literal, annotations, filters) } return ast } @@ -124,12 +130,12 @@ function recur(ast: AST.AST): AST.AST { } case "Union": { if (ast.mode === "oneOf") { - return new AST.Union(ast.types, "anyOf", ast.annotations, ast.checks) + return new SchemaAST.Union(ast.types, "anyOf", ast.annotations, ast.checks) } - const types = AST.mapOrSame(ast.types, recur) + const types = SchemaAST.mapOrSame(ast.types, recur) const { annotations, filters } = get(ast) if (types !== ast.types || annotations !== undefined || filters !== undefined) { - return new AST.Union(types, "anyOf", annotations, filters) + return new SchemaAST.Union(types, "anyOf", annotations, filters) } return ast } @@ -149,15 +155,17 @@ function recur(ast: AST.AST): AST.AST { annotations.description = TUPLE_DESCRIPTION } const propertySignatures = ast.elements.map((e, i) => { - return new AST.PropertySignature(String(i), e) + return new SchemaAST.PropertySignature(String(i), e) }) if (ast.rest.length === 1) { - propertySignatures.push(new AST.PropertySignature(REST_PROPERTY_NAME, new AST.Arrays(false, [], ast.rest))) + propertySignatures.push( + new SchemaAST.PropertySignature(REST_PROPERTY_NAME, new SchemaAST.Arrays(false, [], ast.rest)) + ) } - return AST.decodeTo( - recur(new AST.Objects(propertySignatures, [], annotations, filters)), + return SchemaAST.decodeTo( + recur(new SchemaAST.Objects(propertySignatures, [], annotations, filters)), ast, - Transformation.transform({ + SchemaTransformation.transform({ decode: (o) => { let t: Array = [] for (let i = 0; i < ast.elements.length; i++) { @@ -186,9 +194,9 @@ function recur(ast: AST.AST): AST.AST { }) ) } else { - const rest = AST.mapOrSame(ast.rest, recur) + const rest = SchemaAST.mapOrSame(ast.rest, recur) if (rest !== ast.rest || annotations !== undefined || filters !== undefined) { - return new AST.Arrays(false, [], rest, annotations, filters) + return new SchemaAST.Arrays(false, [], rest, annotations, filters) } return ast } @@ -196,7 +204,7 @@ function recur(ast: AST.AST): AST.AST { case "Objects": { let { annotations, filters } = get(ast) if (ast.indexSignatures.length === 0) { - const propertySignatures = AST.mapOrSame(ast.propertySignatures, (ps) => { + const propertySignatures = SchemaAST.mapOrSame(ast.propertySignatures, (ps) => { if (typeof ps.name !== "string") { throw new Error( `${errorPrefix}: Property names must be strings (got ${typeof ps.name})` @@ -204,11 +212,11 @@ function recur(ast: AST.AST): AST.AST { } let type = recur(ps.type) // opttional properties are not supported by Anthropic, so we translate them to nullable unions - if (AST.isOptional(ps.type)) { - type = AST.decodeTo( - new AST.Union([type, AST.null], "anyOf"), - AST.optionalKey(type), - Transformation.transformOptional({ + if (SchemaAST.isOptional(ps.type)) { + type = SchemaAST.decodeTo( + new SchemaAST.Union([type, SchemaAST.null], "anyOf"), + SchemaAST.optionalKey(type), + SchemaTransformation.transformOptional({ decode: Option.filter(Predicate.isNotNull), encode: Option.orElseSome(() => null) }) @@ -217,12 +225,12 @@ function recur(ast: AST.AST): AST.AST { if (type === ps.type) { return ps } - return new AST.PropertySignature(ps.name, type) + return new SchemaAST.PropertySignature(ps.name, type) }) if ( propertySignatures !== ast.propertySignatures || annotations !== undefined || filters !== undefined ) { - return new AST.Objects(propertySignatures, [], annotations, filters) + return new SchemaAST.Objects(propertySignatures, [], annotations, filters) } } else if (ast.indexSignatures.length === 1 && ast.propertySignatures.length === 0) { const is = ast.indexSignatures[0] @@ -236,10 +244,12 @@ function recur(ast: AST.AST): AST.AST { annotations ??= {} annotations.description = RECORD_DESCRIPTION } - return AST.decodeTo( - recur(new AST.Arrays(false, [], [new AST.Arrays(false, [is.parameter, is.type], [])], annotations)), + return SchemaAST.decodeTo( + recur( + new SchemaAST.Arrays(false, [], [new SchemaAST.Arrays(false, [is.parameter, is.type], [])], annotations) + ), ast, - Transformation.transform({ + SchemaTransformation.transform({ decode: Object.fromEntries, encode: Object.entries }) @@ -256,7 +266,7 @@ function recur(ast: AST.AST): AST.AST { const errorPrefix = "AnthropicStructuredOutput" -function unsupportedAst(ast: AST.AST, details?: string): never { +function unsupportedAst(ast: SchemaAST.AST, details?: string): never { const base = `Unsupported AST ${ast._tag}` const full = `${errorPrefix}: ${base}` throw new Error(details !== undefined ? `${full} (${details})` : full) @@ -276,14 +286,14 @@ type Annotation = type Filter = | Annotation - | { readonly _tag: "filter"; readonly filter: AST.Filter } + | { readonly _tag: "filter"; readonly filter: SchemaAST.Filter } -const get = (ast: AST.AST): { +const get = (ast: SchemaAST.AST): { annotations: Record | undefined - filters: [AST.Check, ...AST.Check[]] | undefined + filters: [SchemaAST.Check, ...SchemaAST.Check[]] | undefined } => { const annotations: Record = {} - const filters: Array> = [] + const filters: Array> = [] const checks = getChecks(ast) if (checks.length > 0) { for (const check of checks) { @@ -313,7 +323,7 @@ const get = (ast: AST.AST): { } } -const getChecks = (ast: AST.AST): Array => [ +const getChecks = (ast: SchemaAST.AST): Array => [ ...(ast.checks !== undefined ? getFilters(ast.checks) : []), ...getAnnotations(ast.annotations) ] @@ -340,7 +350,7 @@ const getAnnotations = (annotations: Schema.Annotations.Filter | undefined): Arr return out } -function getFilter(filter: AST.Filter): Array { +function getFilter(filter: SchemaAST.Filter): Array { let out: Array = [] const annotations = getAnnotations(filter.annotations) const meta = filter.annotations?.meta @@ -364,7 +374,7 @@ function getFilter(filter: AST.Filter): Array { return out } -function resetFilter(filter: AST.Filter): AST.Filter { +function resetFilter(filter: SchemaAST.Filter): SchemaAST.Filter { return filter.annotate({ description: undefined, expected: undefined, @@ -373,7 +383,7 @@ function resetFilter(filter: AST.Filter): AST.Filter { }) } -function getFilters(checks: readonly [AST.Check, ...AST.Check[]]): Array { +function getFilters(checks: readonly [SchemaAST.Check, ...SchemaAST.Check[]]): Array { return checks.flatMap((check) => { switch (check._tag) { case "Filter": diff --git a/.opencode/node_modules/effect/src/unstable/ai/Chat.ts b/.opencode/node_modules/effect/src/unstable/ai/Chat.ts index 1c6372eab032697f85ca8413d8db6b2f3a75364f..6fb8bdea0c49f00cc8d2ed54a71d45101867b880 100644 --- a/.opencode/node_modules/effect/src/unstable/ai/Chat.ts +++ b/.opencode/node_modules/effect/src/unstable/ai/Chat.ts @@ -1,46 +1,12 @@ /** - * The `Chat` module provides a stateful conversation interface for AI language - * models. + * Stateful conversation sessions on top of a language model. * - * This module enables persistent chat sessions that maintain conversation - * history, support tool calling, and offer both streaming and non-streaming - * text generation. It integrates seamlessly with the Effect AI ecosystem, - * providing type-safe conversational AI capabilities. - * - * @example - * ```ts - * import { Effect } from "effect" - * import { Chat } from "effect/unstable/ai" - * - * // Create a new chat session - * const program = Effect.gen(function*() { - * const chat = yield* Chat.empty - * - * // Send a message and get response - * const response = yield* chat.generateText({ - * prompt: "Hello! What can you help me with?" - * }) - * - * console.log(response.content) - * - * return response - * }) - * ``` - * - * @example - * ```ts - * import { Effect, Stream } from "effect" - * import { Chat } from "effect/unstable/ai" - * - * // Streaming chat with tool support - * const streamingChat = Effect.gen(function*() { - * const chat = yield* Chat.empty - * - * yield* chat.streamText({ - * prompt: "Generate a creative story" - * }).pipe(Stream.runForEach((part) => Effect.sync(() => console.log(part)))) - * }) - * ``` + * A `Chat` keeps `Prompt` history in a `Ref` and reuses it for text generation, + * streaming, and structured output. Each generation call combines the current + * history with the caller's new prompt, invokes the active language model, and + * appends the response parts back into history. Constructors create fresh + * sessions, seed sessions from prompts, restore exported history, or connect a + * chat to persistence. * * @since 4.0.0 */ @@ -67,13 +33,21 @@ import type * as Response from "./Response.ts" import type * as Tool from "./Tool.ts" /** - * The `Chat` service tag for dependency injection. + * Service tag for stateful AI conversation sessions. + * + * **When to use** + * + * Use to access or provide conversational AI sessions through the Effect + * context. + * + * **Details** * * This tag provides access to chat functionality throughout your application, * enabling persistent conversational AI interactions with full context * management. * - * @example + * **Example** (Using the Chat service) + * * ```ts * import { Effect } from "effect" * import { Chat } from "effect/unstable/ai" @@ -87,8 +61,8 @@ import type * as Tool from "./Tool.ts" * }) * ``` * - * @since 4.0.0 * @category services + * @since 4.0.0 */ export class Chat extends Context.Service()( "effect/ai/Chat" @@ -97,17 +71,29 @@ export class Chat extends Context.Service()( /** * Represents the interface that the `Chat` service provides. * - * @since 4.0.0 + * **When to use** + * + * Use as the service contract for code that receives or constructs a stateful + * chat session and needs history, export, text generation, streaming, and + * structured-output operations. + * + * @see {@link Chat} for the context tag that provides this service + * @see {@link Persisted} for the persistence-backed extension + * * @category models + * @since 4.0.0 */ export interface Service { /** * Reference to the chat history. * + * **Details** + * * Provides direct access to the conversation history for advanced use cases * like custom history manipulation or inspection. * - * @example + * **Example** (Inspecting chat history) + * * ```ts * import { Effect, Ref } from "effect" * import { Chat } from "effect/unstable/ai" @@ -125,10 +111,13 @@ export interface Service { /** * Exports the chat history into a structured format. * + * **Details** + * * Returns the complete conversation history as a structured object * that can be stored, transmitted, or processed by other systems. * - * @example + * **Example** (Exporting chat history) + * * ```ts * import { Effect } from "effect" * import { Chat } from "effect/unstable/ai" @@ -149,10 +138,13 @@ export interface Service { /** * Exports the chat history as a JSON string. * + * **Details** + * * Provides a convenient way to serialize the entire conversation * for storage or transmission in JSON format. * - * @example + * **Example** (Exporting chat history as JSON) + * * ```ts * import { Effect } from "effect" * import { Chat } from "effect/unstable/ai" @@ -175,11 +167,14 @@ export interface Service { /** * Generate text using a language model for the specified prompt. * + * **Details** + * * If a toolkit is specified, the language model will have access to tools * for function calling and enhanced capabilities. Both input and output * messages are automatically added to the chat history. * - * @example + * **Example** (Generating chat responses) + * * ```ts * import { Effect } from "effect" * import { Chat } from "effect/unstable/ai" @@ -240,10 +235,13 @@ export interface Service { /** * Generate text using a language model with streaming output. * + * **Details** + * * Returns a stream of response parts that are emitted as soon as they're * available from the model. Supports tool calling and maintains chat history. * - * @example + * **Example** (Streaming chat responses) + * * ```ts * import { Effect, Stream } from "effect" * import { Chat } from "effect/unstable/ai" @@ -303,11 +301,14 @@ export interface Service { /** * Generate a structured object using a language model and schema. * + * **Details** + * * Forces the model to return data that conforms to the specified schema, * enabling structured data extraction and type-safe responses. The * conversation history is maintained across calls. * - * @example + * **Example** (Generating structured objects) + * * ```ts * import { Effect, Schema } from "effect" * import { Chat } from "effect/unstable/ai" @@ -456,10 +457,13 @@ const makeUnsafe = (history: Ref.Ref) => { /** * Creates a new Chat service with empty conversation history. * - * This is the most common way to start a fresh chat session without - * any initial context or system prompts. + * **When to use** + * + * Use when you need to start a fresh chat session without initial context or + * system prompts. + * + * **Example** (Creating an empty chat) * - * @example * ```ts * import { Effect } from "effect" * import { Chat } from "effect/unstable/ai" @@ -477,18 +481,21 @@ const makeUnsafe = (history: Ref.Ref) => { * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const empty: Effect.Effect = Effect.sync(() => makeUnsafe(Ref.makeUnsafe(Prompt.empty))) /** * Creates a new Chat service from an initial prompt. * + * **Details** + * * This is the primary constructor for creating chat instances. It initializes * a new conversation with the provided prompt as the starting context. * - * @example + * **Example** (Creating a chat from a system prompt) + * * ```ts * import { Effect } from "effect" * import { Chat } from "effect/unstable/ai" @@ -507,7 +514,8 @@ export const empty: Effect.Effect = Effect.sync(() => makeUnsafe(Ref.ma * }) * ``` * - * @example + * **Example** (Restoring chat history from a prompt) + * * ```ts * import { Effect } from "effect" * import { Chat } from "effect/unstable/ai" @@ -537,8 +545,8 @@ export const empty: Effect.Effect = Effect.sync(() => makeUnsafe(Ref.ma * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fromPrompt = (prompt: Prompt.RawInput) => Effect.sync(() => makeUnsafe(Ref.makeUnsafe(Prompt.make(prompt)))) @@ -546,37 +554,50 @@ export const fromPrompt = (prompt: Prompt.RawInput) => /** * Creates a Chat service from previously exported chat data. * + * **Details** + * * Restores a chat session from structured data that was previously exported * using the `export` method. Useful for persisting and restoring conversation * state. * - * @example + * **Example** (Restoring chat data) + * * ```ts - * import { Effect } from "effect" + * import { Effect, Ref } from "effect" * import { Chat } from "effect/unstable/ai" * - * declare const loadFromDatabase: (sessionId: string) => Effect.Effect - * * const restoreChat = Effect.gen(function*() { - * // Assume we have previously exported data - * const savedData = yield* loadFromDatabase("chat-session-123") + * const originalChat = yield* Chat.fromPrompt([ + * { + * role: "user", + * content: "Which library are we using?" + * }, + * { + * role: "assistant", + * content: "The project uses Effect." + * } + * ]) * - * const restoredChat = yield* Chat.fromExport(savedData) + * const exported = yield* originalChat.export + * const restoredChat = yield* Chat.fromExport(exported) + * const restoredHistory = yield* Ref.get(restoredChat.history) * - * // Continue the conversation from where it left off - * const response = yield* restoredChat.generateText({ - * prompt: "Let's continue our discussion" - * }) - * }).pipe( - * Effect.catchTag("SchemaError", (error) => { - * console.log("Failed to restore chat:", error.message) - * return Effect.void - * }) - * ) + * console.log(restoredHistory.content.map((message) => message.role)) + * // ["user", "assistant"] + * + * const restoredResponse = restoredHistory.content[1] + * if (restoredResponse?.role === "assistant") { + * const restoredText = restoredResponse.content[0] + * if (restoredText?.type === "text") { + * console.log(restoredText.text) + * // "The project uses Effect." + * } + * } + * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fromExport = (data: unknown): Effect.Effect< Service, @@ -586,11 +607,14 @@ export const fromExport = (data: unknown): Effect.Effect< /** * Creates a Chat service from previously exported JSON chat data. * + * **Details** + * * Restores a chat session from JSON string that was previously exported * using the `exportJson` method. This is the most convenient way to * persist and restore chat sessions to/from storage systems. * - * @example + * **Example** (Restoring chat history from JSON) + * * ```ts * import { Effect } from "effect" * import { Chat } from "effect/unstable/ai" @@ -616,8 +640,8 @@ export const fromExport = (data: unknown): Effect.Effect< * ) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fromJson = (data: string): Effect.Effect< Service, @@ -629,11 +653,16 @@ export const fromJson = (data: string): Effect.Effect< // ============================================================================= /** - * An error that occurs when attempting to retrieve a persisted `Chat` that + * Represents an error that occurs when attempting to retrieve a persisted `Chat` that * does not exist in the backing persistence store. * - * @since 4.0.0 + * **When to use** + * + * Use to represent a missing persisted conversation when lookup by id cannot + * find stored history. + * * @category errors + * @since 4.0.0 */ export class ChatNotFoundError extends Schema.ErrorClass( "effect/ai/Chat/ChatNotFoundError" @@ -643,10 +672,15 @@ export class ChatNotFoundError extends Schema.ErrorClass( }) {} /** - * The context tag for chat persistence. + * Service tag for persistence-backed AI conversation storage. + * + * **When to use** + * + * Use to provide the storage operations needed by persisted conversation + * sessions. * - * @since 4.0.0 * @category services + * @since 4.0.0 */ // @effect-diagnostics effect/leakingRequirements:off export class Persistence extends Context.Service()( @@ -654,16 +688,17 @@ export class Persistence extends Context.Service()( "effect/unstable/ai/EmbeddingModel" @@ -35,18 +40,31 @@ export class EmbeddingModel extends Context.Service()( /** * Service tag that provides the current embedding dimensions. * - * @since 4.0.0 + * **When to use** + * + * Use to retrieve or provide the configured embedding vector size through + * context. + * + * @see {@link EmbeddingModel} for the embedding service that uses these dimensions + * * @category services + * @since 4.0.0 */ export class Dimensions extends Context.Service()( "effect/unstable/ai/EmbeddingModel/Dimensions" ) {} /** - * Token usage metadata for embedding operations. + * Represents token usage metadata for embedding operations. + * + * **Details** + * + * Contains optional provider-reported `inputTokens`. The value may be + * `undefined` when the provider does not report usage or when `embedMany([])` + * bypasses the provider. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export class EmbeddingUsage extends Schema.Class( "effect/ai/EmbeddingModel/EmbeddingUsage" @@ -57,8 +75,8 @@ export class EmbeddingUsage extends Schema.Class( /** * Response for a single embedding request. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export class EmbedResponse extends Schema.Class( "effect/ai/EmbeddingModel/EmbedResponse" @@ -67,10 +85,19 @@ export class EmbedResponse extends Schema.Class( }) {} /** - * Response for multiple embeddings. + * Response for batch embedding requests containing per-input embeddings and usage + * metadata. + * + * **Details** + * + * `embeddings` preserves batch order, and `usage` carries token metadata for + * the operation. + * + * @see {@link EmbedResponse} for individual embedding responses + * @see {@link EmbeddingUsage} for token usage metadata * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export class EmbedManyResponse extends Schema.Class( "effect/ai/EmbeddingModel/EmbedManyResponse" @@ -82,8 +109,8 @@ export class EmbedManyResponse extends Schema.Class( /** * Provider input options for embedding requests. * + * @category options * @since 4.0.0 - * @category models */ export interface ProviderOptions { readonly inputs: ReadonlyArray @@ -92,8 +119,8 @@ export interface ProviderOptions { /** * Provider response for batch embedding requests. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface ProviderResponse { readonly results: Array> @@ -103,10 +130,19 @@ export interface ProviderResponse { } /** - * Tagged request used by request resolvers for embedding operations. + * Represents a tagged request used by request resolvers for embedding operations. + * + * **When to use** + * + * Use when you need a typed request for one embedding input while building or + * calling a low-level embedding request resolver. + * + * @see {@link Service} for the resolver-bearing service contract + * @see {@link make} for constructing the request resolver from a provider implementation + * @see {@link EmbedResponse} for the response produced by this request * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export class EmbeddingRequest extends Request.TaggedClass("EmbeddingRequest")< { readonly input: string }, @@ -115,10 +151,10 @@ export class EmbeddingRequest extends Request.TaggedClass("EmbeddingRequest")< > {} /** - * Service interface for embedding operations. + * Defines the service interface for embedding operations. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface Service { readonly resolver: RequestResolver.RequestResolver @@ -136,8 +172,32 @@ const invalidProviderResponse = (description: string): AiError.AiError => /** * Creates an EmbeddingModel service from a provider embedMany implementation. * - * @since 4.0.0 + * **When to use** + * + * Use to adapt a provider's batch embedding implementation into an + * `EmbeddingModel.Service` that offers single-input and batch embedding + * operations. + * + * **Details** + * + * The returned service builds single-input `embed` calls through a request + * resolver, so concurrent `embed` requests can be batched into one provider + * `embedMany` call. Direct `embedMany` calls pass the input array to the + * provider, while `embedMany([])` returns an empty response without calling the + * provider. + * + * **Gotchas** + * + * Provider responses are interpreted positionally and must contain exactly one + * result for each requested input. If the provider returns a different number + * of results, `embed` and `embedMany` fail with `AiError.InvalidOutputError`. + * + * @see {@link Service} for the service shape returned by this constructor + * @see {@link ProviderOptions} for the input passed to the provider implementation + * @see {@link ProviderResponse} for the provider response contract consumed by this constructor + * * @category constructors + * @since 4.0.0 */ export const make: (params: { readonly embedMany: (options: ProviderOptions) => Effect.Effect diff --git a/.opencode/node_modules/effect/src/unstable/ai/IdGenerator.ts b/.opencode/node_modules/effect/src/unstable/ai/IdGenerator.ts index c052698dc488eec912222b087c3828df3cb105b5..ba2217cdb7743b0f0644481a5aecea343ab39919 100644 --- a/.opencode/node_modules/effect/src/unstable/ai/IdGenerator.ts +++ b/.opencode/node_modules/effect/src/unstable/ai/IdGenerator.ts @@ -1,47 +1,11 @@ /** - * The `IdGenerator` module provides a pluggable system for generating unique identifiers - * for tool calls and other items in the Effect AI SDKs. + * Provides identifier generation for AI features. * - * This module offers a flexible and configurable approach to ID generation, supporting - * custom alphabets, prefixes, separators, and sizes. - * - * @example - * ```ts - * import { Effect } from "effect" - * import { IdGenerator } from "effect/unstable/ai" - * - * // Using the default ID generator - * const program = Effect.gen(function*() { - * const idGen = yield* IdGenerator.IdGenerator - * const toolCallId = yield* idGen.generateId() - * console.log(toolCallId) // "id_A7xK9mP2qR5tY8uV" - * return toolCallId - * }).pipe(Effect.provideService( - * IdGenerator.IdGenerator, - * IdGenerator.defaultIdGenerator - * )) - * ``` - * - * @example - * ```ts - * import { Effect } from "effect" - * import { IdGenerator } from "effect/unstable/ai" - * - * // Creating a custom ID generator for AI tool calls - * const customLayer = IdGenerator.layer({ - * alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", - * prefix: "tool_call", - * separator: "-", - * size: 12 - * }) - * - * const program = Effect.gen(function*() { - * const idGen = yield* IdGenerator.IdGenerator - * const id = yield* idGen.generateId() - * console.log(id) // "tool_call-A7XK9MP2QR5T" - * return id - * }).pipe(Effect.provide(customLayer)) - * ``` + * The `IdGenerator` service exposes one operation, `generateId`, which returns + * a string inside `Effect`. AI modules use it for values such as tool call ids + * and generated response item ids. This module includes the service tag, + * service interface, default generator, configurable custom generator, and layer + * for providing the service. * * @since 4.0.0 */ @@ -53,13 +17,21 @@ import * as Predicate from "../../Predicate.ts" import * as Random from "../../Random.ts" /** - * The `IdGenerator` service tag for dependency injection. + * Service tag for AI identifier generation services. + * + * **When to use** + * + * Use to access or provide the service that creates identifiers for AI tool + * calls and related generated values. + * + * **Details** * * This tag is used to provide and access ID generation functionality throughout * the application. It follows Effect's standard service pattern for type-safe * dependency injection. * - * @example + * **Example** (Accessing the ID generator service) + * * ```ts * import { Effect } from "effect" * import { IdGenerator } from "effect/unstable/ai" @@ -71,8 +43,8 @@ import * as Random from "../../Random.ts" * }) * ``` * + * @category services * @since 4.0.0 - * @category models */ export class IdGenerator extends Context.Service()( "@effect/ai/IdGenerator" @@ -81,29 +53,33 @@ export class IdGenerator extends Context.Service()( /** * The service interface for ID generation. * + * **Details** + * * Defines the contract that all ID generator implementations must fulfill. * The service provides a single method for generating unique identifiers * in an effectful context. * - * @example + * **Example** (Implementing a custom ID generator) + * * ```ts * import { Effect } from "effect" * import type { IdGenerator } from "effect/unstable/ai" * - * // Custom implementation + * // Custom deterministic implementation + * let nextId = 0 * const customService: IdGenerator.Service = { - * generateId: () => Effect.succeed(`custom_${Date.now()}`) + * generateId: () => Effect.sync(() => `custom_${++nextId}`) * } * * const program = Effect.gen(function*() { * const id = yield* customService.generateId() - * console.log(id) // "custom_1234567890" + * console.log(id) // "custom_1" * return id * }) * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface Service { readonly generateId: () => Effect.Effect @@ -112,7 +88,8 @@ export interface Service { /** * Configuration options for creating custom ID generators. * - * @example + * **Example** (Configuring generated IDs) + * * ```ts * import type { IdGenerator } from "effect/unstable/ai" * @@ -127,8 +104,8 @@ export interface Service { * // This will generate IDs like: "tool_A1B2C3D4" * ``` * + * @category options * @since 4.0.0 - * @category models */ export interface MakeOptions { /** @@ -177,11 +154,14 @@ const makeGenerator = ({ /** * Default ID generator service implementation. * + * **Details** + * * Uses the standard configuration with "id" prefix and generates IDs in the * format "id_XXXXXXXXXXXXXXXX" where X represents random alphanumeric * characters. * - * @example + * **Example** (Generating default IDs) + * * ```ts * import { Effect } from "effect" * import { IdGenerator } from "effect/unstable/ai" @@ -201,8 +181,8 @@ const makeGenerator = ({ * ) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const defaultIdGenerator: Service = { generateId: makeGenerator({ prefix: "id" }) @@ -211,10 +191,13 @@ export const defaultIdGenerator: Service = { /** * Creates a custom ID generator service with the specified options. * + * **Details** + * * Validates the configuration to ensure the separator is not part of the * alphabet, which would cause ambiguity in parsing generated IDs. * - * @example + * **Example** (Creating a custom generator) + * * ```ts * import { Effect } from "effect" * import { IdGenerator } from "effect/unstable/ai" @@ -234,7 +217,8 @@ export const defaultIdGenerator: Service = { * }) * ``` * - * @example + * **Example** (Handling invalid generator options) + * * ```ts * import { Effect } from "effect" * import { IdGenerator } from "effect/unstable/ai" @@ -257,8 +241,8 @@ export const defaultIdGenerator: Service = { * ) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const make = Effect.fnUntraced(function*({ alphabet = DEFAULT_ALPHABET, @@ -282,11 +266,13 @@ export const make = Effect.fnUntraced(function*({ * Creates a Layer that provides the IdGenerator service with custom * configuration. * - * This is the recommended way to provide ID generation capabilities to your - * application. The layer will fail during construction if the configuration is - * invalid. + * **When to use** + * + * Use when you need to provide ID generation capabilities from validated + * configuration. + * + * **Example** (Providing an ID generator layer) * - * @example * ```ts * import { Effect } from "effect" * import { IdGenerator } from "effect/unstable/ai" @@ -307,8 +293,8 @@ export const make = Effect.fnUntraced(function*({ * }).pipe(Effect.provide(toolCallIdLayer)) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const layer = (options: MakeOptions): Layer.Layer => Layer.effect(IdGenerator)(make(options)) diff --git a/.opencode/node_modules/effect/src/unstable/ai/LanguageModel.ts b/.opencode/node_modules/effect/src/unstable/ai/LanguageModel.ts index 90dfeccdccee8bcf0b63d6bf621af207c4e87d89..5b7245f4b8a8c4e507a6899802889b43861a8024 100644 --- a/.opencode/node_modules/effect/src/unstable/ai/LanguageModel.ts +++ b/.opencode/node_modules/effect/src/unstable/ai/LanguageModel.ts @@ -1,50 +1,13 @@ /** - * The `LanguageModel` module provides AI text generation capabilities with tool - * calling support. + * Defines the shared service for language model providers. * - * This module offers a comprehensive interface for interacting with large - * language models, supporting both streaming and non-streaming text generation, - * structured output generation, and tool calling functionality. It provides a - * unified API that can be implemented by different AI providers while - * maintaining type safety and effect management. - * - * @example - * ```ts - * import { Effect } from "effect" - * import { LanguageModel } from "effect/unstable/ai" - * - * // Basic text generation - * const program = Effect.gen(function*() { - * const response = yield* LanguageModel.generateText({ - * prompt: "Explain quantum computing" - * }) - * - * console.log(response.text) - * - * return response - * }) - * ``` - * - * @example - * ```ts - * import { Effect, Schema } from "effect" - * import { LanguageModel } from "effect/unstable/ai" - * - * // Structured output generation - * const ContactSchema = Schema.Struct({ - * name: Schema.String, - * email: Schema.String - * }) - * - * const extractContact = Effect.gen(function*() { - * const response = yield* LanguageModel.generateObject({ - * prompt: "Extract contact: John Doe, john@example.com", - * schema: ContactSchema - * }) - * - * return response.value - * }) - * ``` + * The `LanguageModel` service lets application code ask for generated text, + * streamed text, or structured output without depending on a specific provider. + * Requests can include tools, and the service can resolve tool calls while the + * model is generating a response. This module contains the service contract, + * request and response types, structured-output support, and the constructor + * used by provider packages to adapt their own generate and stream functions to + * the shared interface. * * @since 4.0.0 */ @@ -59,7 +22,7 @@ import * as Predicate from "../../Predicate.ts" import * as Queue from "../../Queue.ts" import { CurrentConcurrency } from "../../References.ts" import * as Schema from "../../Schema.ts" -import * as AST from "../../SchemaAST.ts" +import * as SchemaAST from "../../SchemaAST.ts" import * as Sink from "../../Sink.ts" import * as Stream from "../../Stream.ts" import type { Span } from "../../Tracer.ts" @@ -80,13 +43,15 @@ import * as Toolkit from "./Toolkit.ts" // ============================================================================= /** - * The `LanguageModel` service key for dependency injection. + * Service tag for AI model services. + * + * **When to use** * - * This provides access to language model functionality throughout your - * application, enabling text generation, streaming, and structured output - * capabilities. + * Use to access or provide text generation, streaming generation, structured + * output, and tool-calling capabilities through the Effect context. + * + * **Example** (Accessing the language model service) * - * @example * ```ts * import { Effect } from "effect" * import { LanguageModel } from "effect/unstable/ai" @@ -100,21 +65,18 @@ import * as Toolkit from "./Toolkit.ts" * }) * ``` * - * @since 4.0.0 * @category services + * @since 4.0.0 */ export class LanguageModel extends Context.Service()( "effect/unstable/ai/LanguageModel" ) {} /** - * The service interface for language model operations. + * The service interface for language model operations, defining the contract that all language model implementations must fulfill. * - * Defines the contract that all language model implementations must fulfill, - * providing text generation, structured output, and streaming capabilities. - * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface Service { /** @@ -218,15 +180,16 @@ export interface Service { } /** - * A function that transforms a `Schema.Codec` into a provider-compatible form - * for structured output generation. + * A function that transforms a `Schema.Codec` into a provider-compatible form for structured output generation. + * + * **Details** * * Different language model providers have varying constraints on the JSON * schemas they accept. A `CodecTransformer` rewrites a codec's encoded side to * satisfy those constraints while preserving the decoded type. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type CodecTransformer = (schema: Schema.Codec) => { readonly codec: Schema.Codec @@ -237,16 +200,30 @@ export type CodecTransformer = (schema: Schema.Codec * The default codec transformer that passes schemas through without * provider-specific rewrites. * - * @since 4.0.0 + * **When to use** + * + * Use as the codec transformer for provider implementations when the provider + * accepts the JSON Schema generated from an `Effect` Schema codec without + * provider-specific rewrites. + * + * **Details** + * + * The transformer returns the original codec, resolves a top-level `$ref`, and + * copies schema definitions into `$defs`. + * + * @see {@link CodecTransformer} for the structured-output transformer contract + * @see {@link make} for where this transformer is used as the default + * * @category services + * @since 4.0.0 */ export const defaultCodecTransformer: CodecTransformer = InternalCodecTransformer.defaultCodecTransformer /** * Configuration options for text generation. * + * @category options * @since 4.0.0 - * @category models */ export interface GenerateTextOptions> { /** @@ -285,15 +262,13 @@ export interface GenerateTextOptions> { readonly concurrency?: Concurrency | undefined /** - * When set to `true`, tool calls requested by the large language model - * will not be auto-resolved by the framework. + * When set to `true`, tool calls requested by the large language model are not auto-resolved by the framework. + * + * **When to use** * - * This option is useful when: - * 1. The user wants to include tool call definitions from an `AiToolkit` - * in requests to the large language model so that the model has the - * capability to call tools - * 2. The user wants to control the execution of tool call resolvers - * instead of having the framework handle tool call resolution + * Use when you want to include tool call definitions from an `AiToolkit` + * in requests to the large language model, while controlling tool call + * resolver execution yourself. */ readonly disableToolCallResolution?: boolean | undefined } @@ -305,8 +280,8 @@ type GenerateTextOptionsWithoutToolkit = Omit, "toolkit" /** * Configuration options for structured object generation. * + * @category options * @since 4.0.0 - * @category models */ export interface GenerateObjectOptions< Tools extends Record, @@ -339,8 +314,8 @@ export interface GenerateObjectOptions< * `"required"`, the model **must** call one tool from the allowed subset of * tools. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type ToolChoice = | "auto" @@ -355,13 +330,10 @@ export type ToolChoice = } /** - * Response class for text generation operations. + * Response class for text generation operations, with accessors for extracting text, tool calls, usage information, and other response parts from generated content. * - * Contains the generated content and provides convenient accessors for - * extracting different types of response parts like text, tool calls, and usage - * information. + * **Example** (Inspecting a text response) * - * @example * ```ts * import { Effect } from "effect" * import { LanguageModel } from "effect/unstable/ai" @@ -379,8 +351,8 @@ export type ToolChoice = * }) * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export class GenerateTextResponse> { readonly content: Array> @@ -471,7 +443,8 @@ export class GenerateTextResponse> { /** * Response class for structured object generation operations. * - * @example + * **Example** (Inspecting an object response) + * * ```ts * import { Effect, Schema } from "effect" * import { LanguageModel } from "effect/unstable/ai" @@ -494,8 +467,8 @@ export class GenerateTextResponse> { * }) * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export class GenerateObjectResponse< Tools extends Record, @@ -519,8 +492,8 @@ export class GenerateObjectResponse< /** * The supported toolkit option shapes for language model operations. * - * @since 4.0.0 * @category utility types + * @since 4.0.0 */ export type ToolkitOption< Tools extends Record, @@ -528,8 +501,7 @@ export type ToolkitOption< R = any > = Tools extends any ? ( | Toolkit.WithHandler - | Effect.Yieldable< - Toolkit.Toolkit, + | Effect.Effect< Toolkit.WithHandler, E, R @@ -540,12 +512,14 @@ export type ToolkitOption< /** * The supported toolkit input shapes for language model operation options. * + * **Details** + * * Unlike `ToolkitOption`, this type does not distribute over unions. It is * intended for call-site assignability, while `ToolkitOption` remains the * distributive helper used for extraction and inference. * - * @since 4.0.0 * @category utility types + * @since 4.0.0 */ export type ToolkitInput< Tools extends Record, @@ -554,27 +528,25 @@ export type ToolkitInput< > = | ToolkitOption | Toolkit.WithHandler - | Effect.Yieldable< - Toolkit.Toolkit, + | Effect.Effect< Toolkit.WithHandler, E, R > type ExtractToolsFromToolkitOption = ToolkitValue extends Toolkit.WithHandler ? Tools - : ToolkitValue extends Effect.Yieldable< - Toolkit.Toolkit, + : ToolkitValue extends Effect.Effect< Toolkit.WithHandler, infer _E, infer _R - > ? Tools + > ? _Tools : never /** * Utility type that extracts the toolset from LanguageModel options. * - * @since 4.0.0 * @category utility types + * @since 4.0.0 */ export type ExtractTools = Options extends { readonly toolkit: infer ToolkitValue @@ -585,20 +557,18 @@ type ExtractErrorFromToolkitOption ? | AiError.AiError | (DisableToolCallResolution extends true ? never : Tool.HandlerError) - : ToolkitValue extends Effect.Yieldable< - Toolkit.Toolkit, + : ToolkitValue extends Effect.Effect< Toolkit.WithHandler, infer E, infer _R - > ? AiError.AiError | E | (DisableToolCallResolution extends true ? never : Tool.HandlerError) + > ? AiError.AiError | E | (DisableToolCallResolution extends true ? never : Tool.HandlerError<_Tools[keyof _Tools]>) : AiError.AiError type ExtractServicesFromToolkitOption = ToolkitValue extends Toolkit.WithHandler ? | Tool.HandlerServices | Tool.ResultDecodingServices - : ToolkitValue extends Effect.Yieldable< - Toolkit.Toolkit, - Toolkit.WithHandler, + : ToolkitValue extends Effect.Effect< + Toolkit.WithHandler, infer _E, infer R > ? @@ -607,16 +577,14 @@ type ExtractServicesFromToolkitOption = ToolkitValue extends Toolk | R : never -type ExtractToolkitResolutionError = ToolkitValue extends Effect.Yieldable< - Toolkit.Toolkit, +type ExtractToolkitResolutionError = ToolkitValue extends Effect.Effect< Toolkit.WithHandler, infer E, infer _R > ? E : never -type ExtractToolkitResolutionServices = ToolkitValue extends Effect.Yieldable< - Toolkit.Toolkit, +type ExtractToolkitResolutionServices = ToolkitValue extends Effect.Effect< Toolkit.WithHandler, infer _E, infer R @@ -626,11 +594,13 @@ type ExtractToolkitResolutionServices = ToolkitValue extends Effec /** * Utility type that extracts the error type from LanguageModel options. * + * **Details** + * * Automatically infers the possible error types based on toolkit configuration * and tool call resolution settings. * - * @since 4.0.0 * @category utility types + * @since 4.0.0 */ export type ExtractError = Options extends { readonly disableToolCallResolution: true @@ -647,10 +617,12 @@ export type ExtractError = Options extends { /** * Utility type that extracts the context requirements from LanguageModel options. * + * **Details** + * * Automatically infers the required services based on the toolkit configuration. * - * @since 4.0.0 * @category utility types + * @since 4.0.0 */ export type ExtractServices = Options extends { readonly disableToolCallResolution: true @@ -665,15 +637,16 @@ export type ExtractServices = Options extends { // ============================================================================= /** - * Configuration options passed along to language model provider - * implementations. + * Configuration options passed along to language model provider implementations. + * + * **Details** * * This interface defines the normalized options that are passed to the * underlying provider implementation, regardless of the specific provider being * used. * + * @category options * @since 4.0.0 - * @category models */ export interface ProviderOptions { /** @@ -688,15 +661,14 @@ export interface ProviderOptions { readonly tools: ReadonlyArray /** - * The format which the response should be provided in. - * - * If `"text"` is specified, the large language model response will be - * returned as text. + * The format the response should be provided in. * - * If `"json"` is specified, the large language model respose will be provided - * as an JSON object that conforms to the shape of the specified schema. + * **Details** * - * Defaults to `{ type: "text" }`. + * If `"text"` is specified, the large language model response is returned as + * text. If `"json"` is specified, the large language model response is + * provided as a JSON object that conforms to the shape of the specified schema. + * The default is `{ type: "text" }`. */ readonly responseFormat: | { @@ -742,31 +714,47 @@ export interface ProviderOptions { } /** - * Creates a LanguageModel service from provider-specific implementations. + * Creates a LanguageModel service from provider-specific text generation and + * streaming implementations. * - * This constructor takes provider-specific implementations for text generation - * and streaming text generation and returns a LanguageModel service. + * **When to use** + * + * Use when you are implementing a provider adapter and need to expose the + * standard language-model service while keeping provider-specific request hooks + * behind it. + * + * **Details** + * + * The returned service implements `generateText`, `generateObject`, and + * `streamText`. It prepares `ProviderOptions` for each request, including the + * normalized prompt, tools, tool choice, response format, tracing span, and + * incremental response fields, before calling the supplied provider hook. + * Structured object generation uses the `generateText` hook and the configured + * `codecTransformer`, or `defaultCodecTransformer` when none is supplied. + * + * **Gotchas** + * + * Provider hooks must return encoded response parts that match the toolkit and + * response format prepared in `ProviderOptions`; invalid parts fail decoding as + * `AiError.InvalidOutputError`. + * + * @see {@link Service} for the returned service contract + * @see {@link ProviderOptions} for the normalized options passed to provider hooks + * @see {@link defaultCodecTransformer} for the default structured-output schema transformer * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const make: (params: { /** - * A method which requests text generation from the large language model - * provider. - * - * The final result is returned when the large language model provider - * finishes text generation. + * A method that requests text generation from the large language model provider and returns the final result when generation finishes. */ readonly generateText: ( options: ProviderOptions ) => Effect.Effect, AiError.AiError, IdGenerator> /** - * A method which requests text generation from the large language model - * provider. - * - * Intermediate results are streamed from the large language model provider. + * A method that requests text generation from the large language model provider and streams intermediate results. */ readonly streamText: ( options: ProviderOptions @@ -1600,9 +1588,10 @@ export const make: (params: { // ============================================================================= /** - * Generate text using a language model. + * Generates text using a language model. + * + * **Example** (Generating text with options) * - * @example * ```ts * import { Effect } from "effect" * import { LanguageModel } from "effect/unstable/ai" @@ -1620,8 +1609,8 @@ export const make: (params: { * }) * ``` * - * @since 4.0.0 * @category text generation + * @since 4.0.0 */ export const generateText: { // No toolkit: force `{}` instead of falling back to `Record`. @@ -1668,9 +1657,10 @@ export const generateText: { ) /** - * Generate a structured object from a schema using a language model. + * Generates a structured object from a schema using a language model. + * + * **Example** (Generating an object) * - * @example * ```ts * import { Effect, Schema } from "effect" * import { LanguageModel } from "effect/unstable/ai" @@ -1696,8 +1686,8 @@ export const generateText: { * }) * ``` * - * @since 4.0.0 * @category object generation + * @since 4.0.0 */ export const generateObject = < ObjectEncoded extends Record, @@ -1719,12 +1709,15 @@ export const generateObject = < ) as any /** - * Generate text using a language model with streaming output. + * Generates text using a language model with streaming output. + * + * **Details** * * Returns a stream of response parts that are emitted as soon as they are * available from the model, enabling real-time text generation experiences. * - * @example + * **Example** (Streaming text deltas) + * * ```ts * import { Console, Effect, Stream } from "effect" * import { LanguageModel } from "effect/unstable/ai" @@ -1739,8 +1732,8 @@ export const generateObject = < * })) * ``` * - * @since 4.0.0 * @category text generation + * @since 4.0.0 */ export const streamText: { // No toolkit: force `{}` instead of falling back to `Record`. @@ -2163,8 +2156,8 @@ const resolveToolCalls = >( const resolveToolkit = , E, R>( toolkit: ToolkitInput ): Effect.Effect, E, R> => - ("asEffect" in toolkit - ? toolkit.asEffect() + (Effect.isEffect(toolkit) + ? toolkit : Effect.succeed(toolkit as unknown as Toolkit.WithHandler)) as any /** @internal */ @@ -2178,7 +2171,7 @@ export const getObjectName = ( if ("identifier" in schema && typeof schema.identifier === "string") { return schema.identifier } - const identifier = AST.resolveIdentifier(schema.ast) + const identifier = SchemaAST.resolveIdentifier(schema.ast) if (typeof identifier === "string") { return identifier } diff --git a/.opencode/node_modules/effect/src/unstable/ai/McpSchema.ts b/.opencode/node_modules/effect/src/unstable/ai/McpSchema.ts index d792428719f69d77158b50b0d2d87ea18997edf7..11aedcda5533143241c596bc072dbca88d0499d9 100644 --- a/.opencode/node_modules/effect/src/unstable/ai/McpSchema.ts +++ b/.opencode/node_modules/effect/src/unstable/ai/McpSchema.ts @@ -1,4 +1,13 @@ /** + * Defines schemas for Model Context Protocol messages. + * + * MCP clients and servers use these schemas to describe the JSON-RPC requests, + * notifications, results, and errors that can cross the protocol boundary. This + * module focuses on message shapes: it defines the shared protocol data model, + * groups related messages for the RPC layer, and provides helpers for optional + * fields and parameter metadata. Transport and server behavior live in other + * modules. + * * @since 4.0.0 */ import * as Context from "../../Context.ts" @@ -7,7 +16,7 @@ import { constFalse, constTrue } from "../../Function.ts" import * as Option from "../../Option.ts" import * as Predicate from "../../Predicate.ts" import * as Schema from "../../Schema.ts" -import * as Getter from "../../SchemaGetter.ts" +import * as SchemaGetter from "../../SchemaGetter.ts" import type * as Scope from "../../Scope.ts" import * as Rpc from "../rpc/Rpc.ts" import type * as RpcClient from "../rpc/RpcClient.ts" @@ -16,6 +25,14 @@ import * as RpcGroup from "../rpc/RpcGroup.ts" import * as RpcMiddleware from "../rpc/RpcMiddleware.ts" /** + * Schema type returned by `optionalWithDefault`. + * + * **Details** + * + * It represents an optional struct field that supplies a default value when the + * field is absent during decoding or construction. + * + * @category models * @since 4.0.0 */ export interface optionalWithDefault @@ -23,6 +40,15 @@ export interface optionalWithDefault( @@ -32,8 +58,8 @@ export const optionalWithDefault = >({ - decode: Getter.withDefault(effect), - encode: Getter.passthrough() + decode: SchemaGetter.withDefault(effect), + encode: SchemaGetter.passthrough() }), Schema.withConstructorDefault< Schema.decodeTo>, Schema.optionalKey> @@ -42,13 +68,21 @@ export const optionalWithDefault = (schema: S): Schema.decodeTo, Schema.optionalKey> => Schema.optionalKey(schema).pipe( Schema.decodeTo(Schema.optional(schema), { - decode: Getter.passthrough() as any, - encode: Getter.transformOptional(Option.flatMap(Option.fromUndefinedOr)) + decode: SchemaGetter.passthrough() as any, + encode: SchemaGetter.transformOptional(Option.flatMap(Option.fromUndefinedOr)) }) ) @@ -57,10 +91,10 @@ export const optional = (schema: S): Schema.decodeTo = Schema.Union([Schema.String, Schema.Number]) /** - * A uniquely identifying ID for a request in JSON-RPC. + * Type represented by the JSON-RPC request identifier schema. * + * @category models * @since 4.0.0 - * @category common */ export type RequestId = typeof RequestId.Type /** - * A progress token, used to associate progress notifications with the original - * request. + * Schema for MCP progress tokens that associate progress notifications with the + * original request. * + * @category schemas * @since 4.0.0 - * @category common */ export const ProgressToken: Schema.Union<[ typeof Schema.String, @@ -88,17 +122,23 @@ export const ProgressToken: Schema.Union<[ ]> = Schema.Union([Schema.String, Schema.Number]) /** - * A progress token, used to associate progress notifications with the original - * request. + * Type represented by the MCP progress token schema. * + * @category models * @since 4.0.0 - * @category common */ export type ProgressToken = typeof ProgressToken.Type /** + * Schema for optional MCP request metadata. + * + * **Details** + * + * Request metadata may include a progress token that asks the receiver to send + * out-of-band progress notifications for the request. + * + * @category schemas * @since 4.0.0 - * @category common */ export class RequestMeta extends Schema.Opaque()(Schema.Struct({ _meta: optional(Schema.Struct({ @@ -114,8 +154,15 @@ export class RequestMeta extends Schema.Opaque()(Schema.Struct({ })) {} /** + * Schema for optional MCP result metadata. + * + * **Details** + * + * The `_meta` field is reserved for protocol, extension, or implementation + * metadata attached to a result. + * + * @category schemas * @since 4.0.0 - * @category common */ export class ResultMeta extends Schema.Opaque()(Schema.Struct({ /** @@ -126,8 +173,15 @@ export class ResultMeta extends Schema.Opaque()(Schema.Struct({ })) {} /** + * Schema for optional MCP notification metadata. + * + * **Details** + * + * The `_meta` field is reserved for protocol, extension, or implementation + * metadata attached to a notification. + * + * @category schemas * @since 4.0.0 - * @category common */ export class NotificationMeta extends Schema.Opaque()(Schema.Struct({ /** @@ -138,22 +192,35 @@ export class NotificationMeta extends Schema.Opaque()(Schema.S })) {} /** - * An opaque token used to represent a cursor for pagination. + * Schema for opaque cursor tokens used in pagination. * + * @category schemas * @since 4.0.0 - * @category common */ export const Cursor: typeof Schema.String = Schema.String /** + * Type represented by the MCP cursor schema. + * + * **Details** + * + * A cursor is an opaque string token used to continue paginated requests. + * + * @category models * @since 4.0.0 - * @category common */ export type Cursor = typeof Cursor.Type /** + * Schema for MCP request metadata used by paginated requests. + * + * **Details** + * + * It includes the base request metadata fields plus an optional cursor + * indicating where the server should continue listing results. + * + * @category schemas * @since 4.0.0 - * @category common */ export class PaginatedRequestMeta extends Schema.Opaque()(Schema.Struct({ ...RequestMeta.fields, @@ -165,8 +232,15 @@ export class PaginatedRequestMeta extends Schema.Opaque()( })) {} /** + * Schema for MCP result metadata returned by paginated operations. + * + * **Details** + * + * It includes the base result metadata fields plus an optional `nextCursor`, + * which indicates that more results may be available. + * + * @category schemas * @since 4.0.0 - * @category common */ export class PaginatedResultMeta extends Schema.Opaque()(Schema.Struct({ ...ResultMeta.fields, @@ -178,24 +252,35 @@ export class PaginatedResultMeta extends Schema.Opaque()(Sc })) {} /** - * The sender or recipient of messages and data in a conversation. + * Schema for MCP conversation roles, allowing user and assistant. + * + * @category schemas * @since 4.0.0 - * @category common */ export const Role: Schema.Literals<["user", "assistant"]> = Schema.Literals(["user", "assistant"]) /** + * Type represented by the MCP role schema. + * + * **Details** + * + * Valid roles are `"user"` and `"assistant"`. + * + * @category models * @since 4.0.0 - * @category common */ export type Role = typeof Role.Type /** - * Optional annotations for the client. The client can use annotations to - * inform how objects are used or displayed + * Schema for optional client-facing annotations on MCP objects. * + * **When to use** + * + * Use to describe intended audience and priority metadata for objects shown or + * processed by a client. + * + * @category schemas * @since 4.0.0 - * @category common */ export class Annotations extends Schema.Opaque()(Schema.Struct({ /** @@ -218,8 +303,8 @@ export class Annotations extends Schema.Opaque()(Schema.Struct({ /** * Describes the name and version of an MCP implementation. * + * @category schemas * @since 4.0.0 - * @category common */ export class Implementation extends Schema.Opaque()(Schema.Struct({ name: Schema.String, @@ -228,12 +313,20 @@ export class Implementation extends Schema.Opaque()(Schema.Struc })) {} /** - * Capabilities a client may support. Known capabilities are defined here, in - * this schema, but this is not a closed set: any client can define its own, - * additional capabilities. + * Describes capabilities advertised by an MCP client. + * + * **When to use** + * + * Use to describe which optional MCP features a client supports during + * initialization. + * + * **Details** * + * Known capabilities are represented by this schema, but the capability set is + * open and clients may define additional capabilities. + * + * @category schemas * @since 4.0.0 - * @category common */ export class ClientCapabilities extends Schema.Class( "@effect/ai/McpSchema/ClientCapabilities" @@ -267,12 +360,20 @@ export class ClientCapabilities extends Schema.Class( }) {} /** - * Capabilities that a server may support. Known capabilities are defined - * here, in this schema, but this is not a closed set: any server can define - * its own, additional capabilities. + * Describes capabilities advertised by an MCP server. + * + * **When to use** + * + * Use to describe which optional MCP features a server supports during + * initialization. + * + * **Details** + * + * Known capabilities are represented by this schema, but the capability set is + * open and servers may define additional capabilities. * + * @category schemas * @since 4.0.0 - * @category common */ export class ServerCapabilities extends Schema.Opaque()(Schema.Struct({ /** @@ -330,8 +431,15 @@ export class ServerCapabilities extends Schema.Opaque()(Sche // ============================================================================= /** + * Schema for MCP and JSON-RPC error objects. + * + * **Details** + * + * It contains the numeric error `code`, a concise `message`, and optional + * sender-defined `data`. + * + * @category schemas * @since 4.0.0 - * @category errors */ export class McpErrorBase extends Schema.Class( "@effect/ai/McpSchema/McpErrorBase" @@ -353,34 +461,81 @@ export class McpErrorBase extends Schema.Class( }) {} /** + * Represents the JSON-RPC error code for requests that are not valid request objects. + * + * **When to use** + * + * Use when building an MCP/JSON-RPC error response for a syntactically parsed + * request object that fails request-shape validation. + * + * @category constants * @since 4.0.0 - * @category errors */ export const INVALID_REQUEST_ERROR_CODE = -32600 as const /** + * Represents the JSON-RPC error code for requests whose method does not exist or is not + * available. + * + * **When to use** + * + * Use when building an MCP/JSON-RPC error response for a request whose + * `method` is unknown or unavailable. + * + * @category constants * @since 4.0.0 - * @category errors */ export const METHOD_NOT_FOUND_ERROR_CODE = -32601 as const /** + * Represents the JSON-RPC error code for invalid method parameters. + * + * **When to use** + * + * Use when building an MCP/JSON-RPC error response for decoded request + * parameters that fail method-specific validation. + * + * @category constants * @since 4.0.0 - * @category errors */ export const INVALID_PARAMS_ERROR_CODE = -32602 as const /** + * Represents the JSON-RPC error code for internal server errors. + * + * **When to use** + * + * Use when building an MCP/JSON-RPC error response for an unexpected + * server-side failure. + * + * @category constants * @since 4.0.0 - * @category errors */ export const INTERNAL_ERROR_CODE = -32603 as const /** + * Represents the JSON-RPC error code for invalid JSON that could not be parsed. + * + * **When to use** + * + * Use when building an MCP/JSON-RPC error response before a request object is + * available because the JSON payload could not be parsed. + * + * @category constants * @since 4.0.0 - * @category errors */ export const PARSE_ERROR_CODE = -32700 as const /** - * @since 4.0.0 + * Represents an MCP/JSON-RPC error for invalid JSON that could not be parsed. + * + * **When to use** + * + * Use to report a JSON parse failure before a valid JSON-RPC request object is + * available. + * + * **Details** + * + * Uses the standard JSON-RPC parse error code `-32700`. + * * @category errors + * @since 4.0.0 */ export class ParseError extends Schema.ErrorClass("effect/ai/McpSchema/ParseError")({ ...McpErrorBase.fields, @@ -389,8 +544,19 @@ export class ParseError extends Schema.ErrorClass("effect/ai/McpSche }) {} /** - * @since 4.0.0 + * Represents an MCP/JSON-RPC error for a request object that is not valid. + * + * **When to use** + * + * Use to report a syntactically parsed JSON-RPC request that is not a valid + * request object. + * + * **Details** + * + * Uses the standard JSON-RPC invalid request code `-32600`. + * * @category errors + * @since 4.0.0 */ export class InvalidRequest extends Schema.ErrorClass("effect/ai/McpSchema/InvalidRequest")({ ...McpErrorBase.fields, @@ -399,8 +565,18 @@ export class InvalidRequest extends Schema.ErrorClass("effect/ai }) {} /** - * @since 4.0.0 + * Represents an MCP/JSON-RPC error for an unavailable method. + * + * **When to use** + * + * Use to report a JSON-RPC method that does not exist or is not available. + * + * **Details** + * + * Uses the standard JSON-RPC method-not-found code `-32601`. + * * @category errors + * @since 4.0.0 */ export class MethodNotFound extends Schema.ErrorClass("effect/ai/McpSchema/MethodNotFound")({ ...McpErrorBase.fields, @@ -409,8 +585,19 @@ export class MethodNotFound extends Schema.ErrorClass("effect/ai }) {} /** - * @since 4.0.0 + * Represents an MCP/JSON-RPC error for invalid method parameters. + * + * **When to use** + * + * Use to report a request whose method parameters do not match the method + * schema. + * + * **Details** + * + * Uses the standard JSON-RPC invalid params code `-32602`. + * * @category errors + * @since 4.0.0 */ export class InvalidParams extends Schema.ErrorClass("effect/ai/McpSchema/InvalidParams")({ ...McpErrorBase.fields, @@ -419,8 +606,20 @@ export class InvalidParams extends Schema.ErrorClass("effect/ai/M }) {} /** - * @since 4.0.0 + * Represents an MCP/JSON-RPC error for unexpected internal server failures. + * + * **When to use** + * + * Use to report an unexpected server-side failure while handling a valid + * request. + * + * **Details** + * + * Uses the standard JSON-RPC internal error code `-32603` and includes + * `InternalError.notImplemented` for unimplemented handlers. + * * @category errors + * @since 4.0.0 */ export class InternalError extends Schema.ErrorClass("effect/ai/McpSchema/InternalError")({ ...McpErrorBase.fields, @@ -431,8 +630,11 @@ export class InternalError extends Schema.ErrorClass("effect/ai/M } /** - * @since 4.0.0 + * Schema for MCP protocol errors returned in JSON-RPC failure responses, + * including standard protocol errors and custom `McpErrorBase` values. + * * @category errors + * @since 4.0.0 */ export const McpError = Schema.Union([ ParseError, @@ -448,12 +650,18 @@ export const McpError = Schema.Union([ // ============================================================================= /** - * A ping, issued by either the server or the client, to check that the other - * party is still alive. The receiver must promptly respond, or else may be - * disconnected. + * Represents an MCP ping request used to check whether the peer is still alive. + * + * **When to use** + * + * Use to implement client or server liveness checks. + * + * **Details** + * + * The receiver should respond promptly; otherwise the sender may disconnect. * - * @since 4.0.0 * @category ping + * @since 4.0.0 */ export class Ping extends Rpc.make("ping", { success: Schema.Struct({}), @@ -466,11 +674,10 @@ export class Ping extends Rpc.make("ping", { // ============================================================================= /** - * After receiving an initialize request from the client, the server sends this - * response. + * Schema for the server's response to an initialize request from the client. * - * @since 4.0.0 * @category initialization + * @since 4.0.0 */ export class InitializeResult extends Schema.Opaque()(Schema.Struct({ ...ResultMeta.fields, @@ -493,11 +700,11 @@ export class InitializeResult extends Schema.Opaque()(Schema.S })) {} /** - * This request is sent from the client to the server when it first connects, - * asking it to begin initialization. + * Sent from the client to the server when it first connects, asking it to begin + * initialization. * - * @since 4.0.0 * @category initialization + * @since 4.0.0 */ export class Initialize extends Rpc.make("initialize", { success: InitializeResult, @@ -523,11 +730,10 @@ export class Initialize extends Rpc.make("initialize", { }) {} /** - * This notification is sent from the client to the server after initialization - * has finished. + * Sent from the client to the server after initialization has finished. * - * @since 4.0.0 * @category initialization + * @since 4.0.0 */ export class InitializedNotification extends Rpc.make("notifications/initialized", { payload: Schema.UndefinedOr(NotificationMeta) @@ -538,8 +744,16 @@ export class InitializedNotification extends Rpc.make("notifications/initialized // ============================================================================= /** - * @since 4.0.0 + * Sent from either peer to cancel a previously issued request in the same + * direction. + * + * **Details** + * + * The payload identifies the request to cancel and may include a + * human-readable reason. + * * @category cancellation + * @since 4.0.0 */ export class CancelledNotification extends Rpc.make("notifications/cancelled", { payload: { @@ -564,11 +778,10 @@ export class CancelledNotification extends Rpc.make("notifications/cancelled", { // ============================================================================= /** - * An out-of-band notification used to inform the receiver of a progress update - * for a long-running request. + * Sent from either peer to report progress for a long-running request. * - * @since 4.0.0 * @category progress + * @since 4.0.0 */ export class ProgressNotification extends Rpc.make("notifications/progress", { payload: { @@ -599,10 +812,10 @@ export class ProgressNotification extends Rpc.make("notifications/progress", { // ============================================================================= /** - * A known resource that the server is capable of reading. + * Schema for a known resource that the server is capable of reading. * - * @since 4.0.0 * @category resources + * @since 4.0.0 */ export class Resource extends Schema.Class( "@effect/ai/McpSchema/Resource" @@ -651,10 +864,10 @@ export class Resource extends Schema.Class( }) {} /** - * A template description for resources available on the server. + * Schema for a template description of resources available on the server. * - * @since 4.0.0 * @category resources + * @since 4.0.0 */ export class ResourceTemplate extends Schema.Class( "@effect/ai/McpSchema/ResourceTemplate" @@ -697,10 +910,10 @@ export class ResourceTemplate extends Schema.Class( }) {} /** - * The contents of a specific resource or sub-resource. + * Schema for the contents of a specific resource or sub-resource. * - * @since 4.0.0 * @category resources + * @since 4.0.0 */ export class ResourceContents extends Schema.Opaque()(Schema.Struct({ /** @@ -718,10 +931,10 @@ export class ResourceContents extends Schema.Opaque()(Schema.S })) {} /** - * The contents of a text resource, which can be represented as a string. + * Schema for text resource contents represented as a string. * - * @since 4.0.0 * @category resources + * @since 4.0.0 */ export class TextResourceContents extends Schema.Opaque()(Schema.Struct({ ...ResourceContents.fields, @@ -733,10 +946,10 @@ export class TextResourceContents extends Schema.Opaque()( })) {} /** - * The contents of a binary resource, which can be represented as an Uint8Array + * Schema for binary resource contents represented as a `Uint8Array`. * - * @since 4.0.0 * @category resources + * @since 4.0.0 */ export class BlobResourceContents extends Schema.Opaque()(Schema.Struct({ ...ResourceContents.fields, @@ -747,10 +960,10 @@ export class BlobResourceContents extends Schema.Opaque()( })) {} /** - * The server's response to a resources/list request from the client. + * Schema for the server's response to a resources/list request from the client. * - * @since 4.0.0 * @category resources + * @since 4.0.0 */ export class ListResourcesResult extends Schema.Class( "@effect/ai/McpSchema/ListResourcesResult" @@ -762,8 +975,8 @@ export class ListResourcesResult extends Schema.Class( /** * Sent from the client to request a list of resources the server has. * - * @since 4.0.0 * @category resources + * @since 4.0.0 */ export class ListResources extends Rpc.make("resources/list", { success: ListResourcesResult, @@ -772,10 +985,11 @@ export class ListResources extends Rpc.make("resources/list", { }) {} /** - * The server's response to a resources/templates/list request from the client. + * Schema for the server's response to a resources/templates/list request from + * the client. * - * @since 4.0.0 * @category resources + * @since 4.0.0 */ export class ListResourceTemplatesResult extends Schema.Class( "@effect/ai/McpSchema/ListResourceTemplatesResult" @@ -787,8 +1001,8 @@ export class ListResourceTemplatesResult extends Schema.Class()(Schema.Struct({ ...ResultMeta.fields, @@ -810,8 +1024,8 @@ export class ReadResourceResult extends Schema.Opaque()(Sche /** * Sent from the client to the server, to read a specific resource URI. * - * @since 4.0.0 * @category resources + * @since 4.0.0 */ export class ReadResource extends Rpc.make("resources/read", { success: ReadResourceResult, @@ -827,12 +1041,18 @@ export class ReadResource extends Rpc.make("resources/read", { }) {} /** - * An optional notification from the server to the client, informing it that the - * list of resources it can read from has changed. This may be issued by servers - * without any previous subscription from the client. + * Represents a notification that the server's resource list changed. + * + * **When to use** + * + * Use to notify clients that `resources/list` should be requested again. + * + * **Details** + * + * Servers may send this notification without a previous client subscription. * - * @since 4.0.0 * @category resources + * @since 4.0.0 */ export class ResourceListChangedNotification extends Rpc.make("notifications/resources/list_changed", { payload: Schema.UndefinedOr(NotificationMeta) @@ -842,8 +1062,8 @@ export class ResourceListChangedNotification extends Rpc.make("notifications/res * Sent from the client to request resources/updated notifications from the * server whenever a particular resource changes. * - * @since 4.0.0 * @category resources + * @since 4.0.0 */ export class Subscribe extends Rpc.make("resources/subscribe", { error: McpError, @@ -862,8 +1082,8 @@ export class Subscribe extends Rpc.make("resources/subscribe", { * notifications from the server. This should follow a previous * resources/subscribe request. * - * @since 4.0.0 * @category resources + * @since 4.0.0 */ export class Unsubscribe extends Rpc.make("resources/unsubscribe", { error: McpError, @@ -878,8 +1098,15 @@ export class Unsubscribe extends Rpc.make("resources/unsubscribe", { }) {} /** - * @since 4.0.0 + * Sent from the server when a subscribed resource URI has changed. + * + * **Details** + * + * The URI may identify a sub-resource of the resource that the client + * originally subscribed to. + * * @category resources + * @since 4.0.0 */ export class ResourceUpdatedNotification extends Rpc.make("notifications/resources/updated", { payload: { @@ -898,8 +1125,8 @@ export class ResourceUpdatedNotification extends Rpc.make("notifications/resourc /** * Describes an argument that a prompt can accept. * + * @category schemas * @since 4.0.0 - * @category prompts */ export class PromptArgument extends Schema.Opaque()(Schema.Struct({ /** @@ -918,10 +1145,10 @@ export class PromptArgument extends Schema.Opaque()(Schema.Struc })) {} /** - * A prompt or prompt template that the server offers. + * Represents a prompt or prompt template that the server offers. * + * @category schemas * @since 4.0.0 - * @category prompts */ export class Prompt extends Schema.Class( "@effect/ai/McpSchema/Prompt" @@ -942,10 +1169,10 @@ export class Prompt extends Schema.Class( }) {} /** - * Text provided to or from an LLM. + * Represents text content provided to or from an LLM. * + * @category schemas * @since 4.0.0 - * @category prompts */ export class TextContent extends Schema.Opaque()(Schema.Struct({ type: Schema.tag("text"), @@ -960,10 +1187,10 @@ export class TextContent extends Schema.Opaque()(Schema.Struct({ })) {} /** - * An image provided to or from an LLM. + * Represents image content provided to or from an LLM. * + * @category schemas * @since 4.0.0 - * @category prompts */ export class ImageContent extends Schema.Opaque()(Schema.Struct({ type: Schema.tag("image"), @@ -983,10 +1210,10 @@ export class ImageContent extends Schema.Opaque()(Schema.Struct({ })) {} /** - * Audio provided to or from an LLM. + * Represents audio content provided to or from an LLM. * + * @category schemas * @since 4.0.0 - * @category prompts */ export class AudioContent extends Schema.Opaque()(Schema.Struct({ type: Schema.tag("audio"), @@ -1006,13 +1233,15 @@ export class AudioContent extends Schema.Opaque()(Schema.Struct({ })) {} /** - * The contents of a resource, embedded into a prompt or tool call result. + * Represents resource contents embedded into a prompt or tool call result. + * + * **Details** * * It is up to the client how best to render embedded resources for the benefit * of the LLM and/or the user. * + * @category schemas * @since 4.0.0 - * @category prompts */ export class EmbeddedResource extends Schema.Opaque()(Schema.Struct({ type: Schema.tag("resource"), @@ -1024,12 +1253,15 @@ export class EmbeddedResource extends Schema.Opaque()(Schema.S })) {} /** - * A resource that the server is capable of reading, included in a prompt or tool call result. + * Represents a readable resource included in a prompt or tool call result. * - * Note: resource links returned by tools are not guaranteed to appear in the results of `resources/list` requests. + * **Gotchas** * + * Resource links returned by tools are not guaranteed to appear in the results + * of `resources/list` requests. + * + * @category schemas * @since 4.0.0 - * @category prompts */ export class ResourceLink extends Schema.Opaque()(Schema.Struct({ ...Resource.fields, @@ -1037,8 +1269,11 @@ export class ResourceLink extends Schema.Opaque()(Schema.Struct({ })) {} /** + * Schema for MCP content blocks that can appear in prompt messages or tool + * results. + * + * @category schemas * @since 4.0.0 - * @category prompts */ export const ContentBlock = Schema.Union([ TextContent, @@ -1051,11 +1286,13 @@ export const ContentBlock = Schema.Union([ /** * Describes a message returned as part of a prompt. * + * **Details** + * * This is similar to `SamplingMessage`, but also supports the embedding of * resources from the MCP server. * + * @category schemas * @since 4.0.0 - * @category prompts */ export class PromptMessage extends Schema.Opaque()(Schema.Struct({ role: Role, @@ -1063,10 +1300,10 @@ export class PromptMessage extends Schema.Opaque()(Schema.Struct( })) {} /** - * The server's response to a prompts/list request from the client. + * Represents the server response to a prompts/list request from the client. * + * @category schemas * @since 4.0.0 - * @category prompts */ export class ListPromptsResult extends Schema.Class( "@effect/ai/McpSchema/ListPromptsResult" @@ -1079,8 +1316,8 @@ export class ListPromptsResult extends Schema.Class( * Sent from the client to request a list of prompts and prompt templates the * server has. * + * @category protocols * @since 4.0.0 - * @category prompts */ export class ListPrompts extends Rpc.make("prompts/list", { success: ListPromptsResult, @@ -1089,10 +1326,10 @@ export class ListPrompts extends Rpc.make("prompts/list", { }) {} /** - * The server's response to a prompts/get request from the client. + * Represents the server response to a prompts/get request from the client. * + * @category schemas * @since 4.0.0 - * @category prompts */ export class GetPromptResult extends Schema.Class( "@effect/ai/McpSchema/GetPromptResult" @@ -1106,10 +1343,10 @@ export class GetPromptResult extends Schema.Class( }) {} /** - * Used by the client to get a prompt provided by the server. + * Sent from the client to get a prompt provided by the server. * + * @category protocols * @since 4.0.0 - * @category prompts */ export class GetPrompt extends Rpc.make("prompts/get", { success: GetPromptResult, @@ -1129,12 +1366,18 @@ export class GetPrompt extends Rpc.make("prompts/get", { }) {} /** - * An optional notification from the server to the client, informing it that - * the list of prompts it offers has changed. This may be issued by servers - * without any previous subscription from the client. + * Represents a notification that the server's prompt list changed. + * + * **When to use** + * + * Use to notify clients that `prompts/list` should be requested again. + * + * **Details** + * + * Servers may send this notification without a previous client subscription. * + * @category protocols * @since 4.0.0 - * @category prompts */ export class PromptListChangedNotification extends Rpc.make("notifications/prompts/list_changed", { payload: Schema.UndefinedOr(NotificationMeta) @@ -1145,17 +1388,21 @@ export class PromptListChangedNotification extends Rpc.make("notifications/promp // ============================================================================= /** - * Additional properties describing a Tool to clients. + * Schema for additional properties describing a tool to clients. + * + * **Details** * * NOTE: all properties in ToolAnnotations are **hints**. They are not * guaranteed to provide a faithful description of tool behavior (including * descriptive properties like `title`). * + * **Gotchas** + * * Clients should never make tool use decisions based on ToolAnnotations * received from untrusted servers. * - * @since 4.0.0 * @category tools + * @since 4.0.0 */ export class ToolAnnotations extends Schema.Opaque()(Schema.Struct({ /** @@ -1198,10 +1445,10 @@ export class ToolAnnotations extends Schema.Opaque()(Schema.Str })) {} /** - * Definition for a tool the client can call. + * Schema for the definition of a tool the client can call. * - * @since 4.0.0 * @category tools + * @since 4.0.0 */ export class Tool extends Schema.Class( "@effect/ai/McpSchema/Tool" @@ -1235,10 +1482,10 @@ export class Tool extends Schema.Class( }) {} /** - * The server's response to a tools/list request from the client. + * Schema for the server's response to a tools/list request from the client. * - * @since 4.0.0 * @category tools + * @since 4.0.0 */ export class ListToolsResult extends Schema.Class( "@effect/ai/McpSchema/ListToolsResult" @@ -1250,8 +1497,8 @@ export class ListToolsResult extends Schema.Class( /** * Sent from the client to request a list of tools the server has. * - * @since 4.0.0 * @category tools + * @since 4.0.0 */ export class ListTools extends Rpc.make("tools/list", { success: ListToolsResult, @@ -1260,19 +1507,19 @@ export class ListTools extends Rpc.make("tools/list", { }) {} /** - * The server's response to a tool call. + * Schema for the server's response to a tool call. + * + * **Details** * * Any errors that originate from the tool SHOULD be reported inside the result * object, with `isError` set to true, _not_ as an MCP protocol-level error * response. Otherwise, the LLM would not be able to see that an error occurred - * and self-correct. - * - * However, any errors in _finding_ the tool, an error indicating that the - * server does not support tool calls, or any other exceptional conditions, - * should be reported as an MCP error response. + * and self-correct. However, any errors in _finding_ the tool, an error + * indicating that the server does not support tool calls, or any other + * exceptional conditions, should be reported as an MCP error response. * - * @since 4.0.0 * @category tools + * @since 4.0.0 */ export class CallToolResult extends Schema.Class("@effect/ai/McpSchema/CallToolResult")({ ...ResultMeta.fields, @@ -1287,10 +1534,18 @@ export class CallToolResult extends Schema.Class("@effect/ai/Mcp }) {} /** - * Used by the client to invoke a tool provided by the server. + * Represents a client request to invoke a tool provided by the server. + * + * **When to use** + * + * Use when you need to represent a client request that already knows the tool + * name and asks the server to execute it with argument values. + * + * @see {@link ListTools} for discovering available tools before calling one + * @see {@link CallToolResult} for the successful tool-call result shape * - * @since 4.0.0 * @category tools + * @since 4.0.0 */ export class CallTool extends Rpc.make("tools/call", { success: CallToolResult, @@ -1306,12 +1561,18 @@ export class CallTool extends Rpc.make("tools/call", { }) {} /** - * An optional notification from the server to the client, informing it that - * the list of tools it offers has changed. This may be issued by servers - * without any previous subscription from the client. + * Represents a notification that the server's tool list changed. + * + * **When to use** + * + * Use to notify clients that `tools/list` should be requested again. + * + * **Details** + * + * Servers may send this notification without a previous client subscription. * - * @since 4.0.0 * @category tools + * @since 4.0.0 */ export class ToolListChangedNotification extends Rpc.make("notifications/tools/list_changed", { payload: Schema.UndefinedOr(NotificationMeta) @@ -1322,13 +1583,12 @@ export class ToolListChangedNotification extends Rpc.make("notifications/tools/l // ============================================================================= /** - * The severity of a log message. - * - * These map to syslog message severities, as specified in RFC-5424: - * https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1 + * Schema for log message severity levels, mapped to syslog message severities + * as specified in RFC 5424 section 6.2.1: + * https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1. * - * @since 4.0.0 * @category logging + * @since 4.0.0 */ export const LoggingLevel: Schema.Literals<[ "debug", @@ -1351,21 +1611,20 @@ export const LoggingLevel: Schema.Literals<[ ]) /** - * The severity of a log message. - * - * These map to syslog message severities, as specified in RFC-5424: - * https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1 + * Type represented by the MCP logging level schema, mapped to syslog message + * severities as specified in RFC 5424 section 6.2.1: + * https://datatracker.ietf.org/doc/html/rfc5424#section-6.2.1. * - * @since 4.0.0 * @category logging + * @since 4.0.0 */ export type LoggingLevel = typeof LoggingLevel.Type /** - * A request from the client to the server, to enable or adjust logging. + * Sent from the client to the server to enable or adjust logging. * - * @since 4.0.0 * @category logging + * @since 4.0.0 */ export class SetLevel extends Rpc.make("logging/setLevel", { payload: { @@ -1381,8 +1640,15 @@ export class SetLevel extends Rpc.make("logging/setLevel", { }) {} /** - * @since 4.0.0 + * Sent from the server to the client carrying a log message. + * + * **Details** + * + * The notification includes the severity level, optional logger name, and + * JSON-serializable log data. + * * @category logging + * @since 4.0.0 */ export class LoggingMessageNotification extends Rpc.make("notifications/message", { payload: Schema.Struct({ @@ -1410,8 +1676,8 @@ export class LoggingMessageNotification extends Rpc.make("notifications/message" /** * Describes a message issued to or received from an LLM API. * - * @since 4.0.0 * @category sampling + * @since 4.0.0 */ export class SamplingMessage extends Schema.Opaque()(Schema.Struct({ role: Role, @@ -1419,13 +1685,15 @@ export class SamplingMessage extends Schema.Opaque()(Schema.Str })) {} /** - * Hints to use for model selection. + * Schema for model selection hints. + * + * **Details** * * Keys not declared here are currently left unspecified by the spec and are up * to the client to interpret. * - * @since 4.0.0 * @category sampling + * @since 4.0.0 */ export class ModelHint extends Schema.Opaque()(Schema.Struct({ /** @@ -1444,20 +1712,25 @@ export class ModelHint extends Schema.Opaque()(Schema.Struct({ })) {} /** - * The server's preferences for model selection, requested of the client during sampling. + * Schema for the server's model selection preferences requested of the client + * during sampling. + * + * **Details** * * Because LLMs can vary along multiple dimensions, choosing the "best" model is - * rarely straightforward. Different models excel in different areas—some are + * rarely straightforward. Different models excel in different areas, some are * faster but less capable, others are more capable but more expensive, and so * on. This interface allows servers to express their priorities across multiple * dimensions to help clients make an appropriate selection for their use case. * + * **Gotchas** + * * These preferences are always advisory. The client MAY ignore them. It is also * up to the client to decide how to interpret these preferences and how to * balance them against other considerations. * - * @since 4.0.0 * @category sampling + * @since 4.0.0 */ export class ModelPreferences extends Schema.Class( "@effect/ai/McpSchema/ModelPreferences" @@ -1493,13 +1766,19 @@ export class ModelPreferences extends Schema.Class( }) {} /** - * The client's response to a sampling/create_message request from the server. - * The client should inform the user before returning the sampled message, to - * allow them to inspect the response (human in the loop) and decide whether to - * allow the server to see it. + * Represents a client response to an MCP sampling request. + * + * **When to use** + * + * Use to return the message produced by client-side model sampling. + * + * **Details** + * + * The client should let the user inspect the sampled message before returning + * it to the server. * - * @since 4.0.0 * @category sampling + * @since 4.0.0 */ export class CreateMessageResult extends Schema.Class( "@effect/ai/McpSchema/CreateMessageResult" @@ -1515,13 +1794,20 @@ export class CreateMessageResult extends Schema.Class( }) {} /** - * A request from the server to sample an LLM via the client. The client has - * full discretion over which model to select. The client should also inform the - * user before beginning sampling, to allow them to inspect the request (human - * in the loop) and decide whether to approve it. + * Represents a server request for the client to sample an LLM. + * + * **When to use** + * + * Use when you need to request model sampling from an MCP client on behalf of a + * server. + * + * **Details** + * + * The client chooses the model and should ask the user to approve the sampling + * request before it begins. * - * @since 4.0.0 * @category sampling + * @since 4.0.0 */ export class CreateMessage extends Rpc.make("sampling/createMessage", { success: CreateMessageResult, @@ -1563,10 +1849,10 @@ export class CreateMessage extends Rpc.make("sampling/createMessage", { // ============================================================================= /** - * A reference to a resource or resource template definition. + * Schema for a reference to a resource or resource template definition. * - * @since 4.0.0 * @category autocomplete + * @since 4.0.0 */ export class ResourceReference extends Schema.Opaque()(Schema.Struct({ type: Schema.tag("ref/resource"), @@ -1577,10 +1863,10 @@ export class ResourceReference extends Schema.Opaque()(Schema })) {} /** - * Identifies a prompt. + * Schema for a prompt reference used in autocomplete requests. * - * @since 4.0.0 * @category autocomplete + * @since 4.0.0 */ export class PromptReference extends Schema.Opaque()(Schema.Struct({ type: Schema.tag("ref/prompt"), @@ -1592,10 +1878,10 @@ export class PromptReference extends Schema.Opaque()(Schema.Str })) {} /** - * The server's response to a completion/complete request + * Schema for the server's response to a completion/complete request. * - * @since 4.0.0 * @category autocomplete + * @since 4.0.0 */ export class CompleteResult extends Schema.Opaque()(Schema.Struct({ completion: Schema.Struct({ @@ -1616,6 +1902,8 @@ export class CompleteResult extends Schema.Opaque()(Schema.Struc }) })) { /** + * Empty completion result used when a completion request has no values. + * * @since 4.0.0 */ static readonly empty = CompleteResult.make({ @@ -1628,10 +1916,10 @@ export class CompleteResult extends Schema.Opaque()(Schema.Struc } /** - * A request from the client to the server, to ask for completion options. + * Sent from the client to the server to ask for completion options. * - * @since 4.0.0 * @category autocomplete + * @since 4.0.0 */ export class Complete extends Rpc.make("completion/complete", { success: CompleteResult, @@ -1676,8 +1964,8 @@ export class Complete extends Rpc.make("completion/complete", { /** * Represents a root directory or file that the server can operate on. * - * @since 4.0.0 * @category roots + * @since 4.0.0 */ export class Root extends Schema.Class( "@effect/ai/McpSchema/Root" @@ -1697,12 +1985,14 @@ export class Root extends Schema.Class( }) {} /** - * The client's response to a roots/list request from the server. This result - * contains an array of Root objects, each representing a root directory or file - * that the server can operate on. + * Represents a client response containing the roots available to the server. + * + * **When to use** + * + * Use to return the directories or files that an MCP server may operate on. * - * @since 4.0.0 * @category roots + * @since 4.0.0 */ export class ListRootsResult extends Schema.Class( "@effect/ai/McpSchema/ListRootsResult" @@ -1714,15 +2004,16 @@ export class ListRootsResult extends Schema.Class( * Sent from the server to request a list of root URIs from the client. Roots * allow servers to ask for specific directories or files to operate on. A * common example for roots is providing a set of repositories or directories a - * server should operate - * on. + * server should operate on. + * + * **Details** * * This request is typically used when the server needs to understand the file * system structure or access specific locations that the client has permission * to read from. * - * @since 4.0.0 * @category roots + * @since 4.0.0 */ export class ListRoots extends Rpc.make("roots/list", { success: ListRootsResult, @@ -1731,13 +2022,18 @@ export class ListRoots extends Rpc.make("roots/list", { }) {} /** - * A notification from the client to the server, informing it that the list of - * roots has changed. This notification should be sent whenever the client adds, - * removes, or modifies any root. The server should then request an updated list - * of roots using the ListRootsRequest. + * Represents a notification that the client's root list changed. + * + * **When to use** + * + * Use to tell the server that it should request an updated roots list. + * + * **Details** + * + * Send this when the client adds, removes, or modifies a root. * - * @since 4.0.0 * @category roots + * @since 4.0.0 */ export class RootsListChangedNotification extends Rpc.make("notifications/roots/list_changed", { payload: Schema.UndefinedOr(NotificationMeta) @@ -1748,10 +2044,10 @@ export class RootsListChangedNotification extends Rpc.make("notifications/roots/ // ============================================================================= /** - * The client's response to an elicitation request + * Schema for an accepted client response to an elicitation request. * - * @since 4.0.0 * @category elicitation + * @since 4.0.0 */ export class ElicitAcceptResult extends Schema.Class( "@effect/ai/McpSchema/ElicitAcceptResult" @@ -1772,10 +2068,10 @@ export class ElicitAcceptResult extends Schema.Class( }) {} /** - * The client's response to an elicitation request + * Schema for a declined or canceled client response to an elicitation request. * - * @since 4.0.0 * @category elicitation + * @since 4.0.0 */ export class ElicitDeclineResult extends Schema.Class( "@effect/ai/McpSchema/ElicitDeclineResult" @@ -1791,10 +2087,10 @@ export class ElicitDeclineResult extends Schema.Class( }) {} /** - * The client's response to an elicitation request + * Schema for every client response to an elicitation request. * - * @since 4.0.0 * @category elicitation + * @since 4.0.0 */ export const ElicitResult = Schema.Union([ ElicitAcceptResult, @@ -1802,8 +2098,16 @@ export const ElicitResult = Schema.Union([ ]) /** - * @since 4.0.0 + * Sent from the server asking the client to collect structured input from the + * user. + * + * **Details** + * + * The client responds with accepted content, an explicit decline, or a + * cancellation. + * * @category elicitation + * @since 4.0.0 */ export class Elicit extends Rpc.make("elicitation/create", { success: ElicitResult, @@ -1823,14 +2127,22 @@ export class Elicit extends Rpc.make("elicitation/create", { }) {} /** - * @since 4.0.0 + * Error raised when an MCP elicitation request is declined or fails before + * accepted content is returned. + * + * **Details** + * + * The error stores the original elicitation request and, when available, the + * underlying cause. + * * @category elicitation + * @since 4.0.0 */ export class ElicitationDeclined extends Schema.ErrorClass("@effect/ai/McpSchema/ElicitationDeclined")({ _tag: Schema.tag("ElicitationDeclined"), request: Elicit.payloadSchema, - cause: optional(Schema.Defect) + cause: optional(Schema.Defect()) }) {} @@ -1839,8 +2151,15 @@ export class ElicitationDeclined // ============================================================================= /** - * @since 4.0.0 + * Service available while handling an MCP client request. + * + * **Details** + * + * It exposes the current client id, the client's initialize payload, and a + * scoped RPC client for server-initiated requests back to that client. + * * @category client + * @since 4.0.0 */ export class McpServerClient extends Context.Service()("effect/ai/McpSchema/McpServerClient") {} /** - * @since 4.0.0 + * RPC middleware that provides `McpServerClient` to handlers for initialized + * MCP clients. + * * @category middleware + * @since 4.0.0 */ export class McpServerClientMiddleware extends RpcMiddleware.Service = RpcGroup.Rpcs< Group @@ -1886,8 +2211,11 @@ export type RequestEncoded = RpcGroup.Rpcs< : never /** + * Encoded notification message for an RPC in `Group`, including the method and + * encoded payload without a request id. + * + * @category protocols * @since 4.0.0 - * @category protocol */ export type NotificationEncoded = RpcGroup.Rpcs< Group @@ -1906,8 +2234,11 @@ export type NotificationEncoded = RpcGroup.Rpcs< : never /** + * Encoded success response for an RPC in `Group`, containing the original + * request id and encoded result. + * + * @category protocols * @since 4.0.0 - * @category protocol */ export type SuccessEncoded = RpcGroup.Rpcs< Group @@ -1926,8 +2257,11 @@ export type SuccessEncoded = RpcGroup.Rpcs< : never /** + * Encoded failure response for an RPC in `Group`, containing the original + * request id and encoded error. + * + * @category protocols * @since 4.0.0 - * @category protocol */ export type FailureEncoded = RpcGroup.Rpcs< Group @@ -1946,8 +2280,16 @@ export type FailureEncoded = RpcGroup.Rpcs< : never /** + * RPC group for requests that MCP clients send to the server. + * + * **Details** + * + * The group includes initialization, resource, prompt, tool, logging, + * completion, and ping requests, and installs `McpServerClientMiddleware` for + * handlers. + * + * @category protocols * @since 4.0.0 - * @category protocol */ export class ClientRequestRpcs extends RpcGroup.make( Ping, @@ -1966,14 +2308,19 @@ export class ClientRequestRpcs extends RpcGroup.make( ).middleware(McpServerClientMiddleware) {} /** + * Encoded union of all client-to-server MCP request messages. + * + * @category protocols * @since 4.0.0 - * @category protocol */ export type ClientRequestEncoded = RequestEncoded /** + * RPC group for notifications that MCP clients send to the server, such as + * cancellation, progress, initialization completion, and roots list changes. + * + * @category protocols * @since 4.0.0 - * @category protocol */ export class ClientNotificationRpcs extends RpcGroup.make( CancelledNotification, @@ -1983,32 +2330,43 @@ export class ClientNotificationRpcs extends RpcGroup.make( ) {} /** + * Encoded union of all client-to-server MCP notification messages. + * + * @category protocols * @since 4.0.0 - * @category protocol */ export type ClientNotificationEncoded = NotificationEncoded /** + * RPC group combining all client-to-server MCP requests and notifications. + * + * @category protocols * @since 4.0.0 - * @category protocol */ export class ClientRpcs extends ClientRequestRpcs.merge(ClientNotificationRpcs) {} /** + * Encoded success response sent by a client for a server-initiated request. + * + * @category protocols * @since 4.0.0 - * @category protocol */ export type ClientSuccessEncoded = SuccessEncoded /** + * Encoded failure response sent by a client for a server-initiated request. + * + * @category protocols * @since 4.0.0 - * @category protocol */ export type ClientFailureEncoded = FailureEncoded /** + * RPC group for requests that an MCP server can send to a client, including + * ping, sampling, roots listing, and elicitation. + * + * @category protocols * @since 4.0.0 - * @category protocol */ export class ServerRequestRpcs extends RpcGroup.make( Ping, @@ -2018,14 +2376,20 @@ export class ServerRequestRpcs extends RpcGroup.make( ) {} /** + * Encoded union of all server-to-client MCP request messages. + * + * @category protocols * @since 4.0.0 - * @category protocol */ export type ServerRequestEncoded = RequestEncoded /** + * RPC group for notifications that an MCP server can send to a client, + * including cancellation, progress, logging, and list or resource update + * notifications. + * + * @category protocols * @since 4.0.0 - * @category protocol */ export class ServerNotificationRpcs extends RpcGroup.make( CancelledNotification, @@ -2038,54 +2402,78 @@ export class ServerNotificationRpcs extends RpcGroup.make( ) {} /** + * Encoded union of all server-to-client MCP notification messages. + * + * @category protocols * @since 4.0.0 - * @category protocol */ export type ServerNotificationEncoded = NotificationEncoded /** + * Encoded success response sent by the server for a client-initiated request. + * + * @category protocols * @since 4.0.0 - * @category protocol */ export type ServerSuccessEncoded = SuccessEncoded /** + * Encoded failure response sent by the server for a client-initiated request. + * + * @category protocols * @since 4.0.0 - * @category protocol */ export type ServerFailureEncoded = FailureEncoded /** + * Encoded server response to a client request, either success or failure. + * + * @category protocols * @since 4.0.0 - * @category protocol */ export type ServerResultEncoded = ServerSuccessEncoded | ServerFailureEncoded /** + * Encoded MCP messages accepted from a client by the server protocol: client + * requests and client notifications. + * + * @category protocols * @since 4.0.0 - * @category protocol */ export type FromClientEncoded = ClientRequestEncoded | ClientNotificationEncoded /** + * Encoded MCP messages emitted by the server protocol to a client: server + * responses and server notifications. + * + * @category protocols * @since 4.0.0 - * @category protocol */ export type FromServerEncoded = ServerResultEncoded | ServerNotificationEncoded const ParamSchemaTypeId = "~effect/ai/McpSchema/ParamSchema" /** - * @since 4.0.0 + * Returns `true` when a schema was created with `param` and therefore carries + * a resource URI template parameter name. + * * @category parameters + * @since 4.0.0 */ export function isParam(schema: Schema.Top): schema is Param { return Predicate.hasProperty(schema, ParamSchemaTypeId) } /** - * @since 4.0.0 + * Schema wrapper used for resource URI template parameters. + * + * **Details** + * + * A `Param` behaves like the wrapped schema while carrying the parameter name + * used for template compilation and completion lookup. + * * @category parameters + * @since 4.0.0 */ export interface Param extends Schema.Bottom< @@ -2113,10 +2501,10 @@ export interface Param extends } /** - * Helper to create a param for a resource URI template. + * Creates a parameter for a resource URI template. * - * @since 4.0.0 * @category parameters + * @since 4.0.0 */ export function param( name: Name, @@ -2129,8 +2517,8 @@ export function param( * Annotation to conditionally enable or disable tools based on client * information. * - * @since 4.0.0 * @category annotations + * @since 4.0.0 */ export class EnabledWhen extends Context.Service>()( diff --git a/.opencode/node_modules/effect/src/unstable/ai/McpServer.ts b/.opencode/node_modules/effect/src/unstable/ai/McpServer.ts index 927c4da13de15cc72b5e426018a364a12e697e4b..fb406609a90076e0f5e30a38ba1c07759f89f33a 100644 --- a/.opencode/node_modules/effect/src/unstable/ai/McpServer.ts +++ b/.opencode/node_modules/effect/src/unstable/ai/McpServer.ts @@ -1,4 +1,13 @@ /** + * Builds Model Context Protocol (MCP) servers with Effect. + * + * The `McpServer` service stores the tools, resources, resource templates, + * prompts, completions, initialized clients, and outgoing notifications exposed + * by a server. This module also includes the server runner, custom protocol, + * stdio, and HTTP layers, registration helpers, and APIs that let handlers ask + * the connected client for structured input or read its advertised + * capabilities. + * * @since 4.0.0 */ import * as Arr from "../../Array.ts" @@ -13,7 +22,7 @@ import * as Queue from "../../Queue.ts" import * as RcMap from "../../RcMap.ts" import { CurrentLogLevel } from "../../References.ts" import * as Schema from "../../Schema.ts" -import * as AST from "../../SchemaAST.ts" +import * as SchemaAST from "../../SchemaAST.ts" import * as Sink from "../../Sink.ts" import type { Stdio } from "../../Stdio.ts" import * as Stream from "../../Stream.ts" @@ -72,8 +81,16 @@ import * as Tool from "./Tool.ts" import type * as Toolkit from "./Toolkit.ts" /** - * @since 4.0.0 + * Service that stores and serves an MCP server's registered tools, resources, + * prompts, completions, and outgoing notifications. + * + * **Details** + * + * Handlers use this service to register capabilities and resolve incoming MCP + * requests. + * * @category server + * @since 4.0.0 */ export class McpServer extends Context.Service> @@ -148,6 +165,8 @@ export class McpServer extends Context.Service Effect.Effect }>()("effect/ai/McpServer") { /** + * Builds an MCP server service from registered tools, prompts, resources, and completions. + * * @since 4.0.0 */ static readonly make = Effect.gen(function*() { @@ -307,6 +326,8 @@ export class McpServer extends Context.Service = Layer.effect(McpServer)(McpServer.make) as any @@ -323,8 +344,16 @@ const mcpSessionIdHeader = "mcp-session-id" const mcpProtocolVersionHeader = "mcp-protocol-version" /** - * @since 4.0.0 + * Runs an MCP server over the current `RpcServer.Protocol`. + * + * **Details** + * + * The server performs initialization and session handling, serves registered + * tools, resources, and prompts, and forwards queued server notifications to + * initialized clients. + * * @category constructors + * @since 4.0.0 */ export const run: (options: { readonly name: string @@ -500,8 +529,33 @@ export const run: (options: { }, Effect.scoped) /** - * @since 4.0.0 + * Creates a layer that starts an MCP server over an existing + * `RpcServer.Protocol` and provides the `McpServer` and `McpServerClient` + * services. + * + * **When to use** + * + * Use when you already have a custom or externally provided + * `RpcServer.Protocol` and want to start an MCP server as part of a layer + * graph. + * + * **Details** + * + * The returned layer forks `run(options)` in the layer scope and merges + * `McpServer.layer`, so registration layers can use the `McpServer` service + * while the server is running. + * + * **Gotchas** + * + * Unlike `layerStdio` and `layerHttp`, this layer does not install a concrete + * transport. The surrounding layer graph must provide `RpcServer.Protocol`. + * + * @see {@link run} for the effect form used by this layer + * @see {@link layerStdio} for a stdio-backed layer that installs the MCP protocol and NDJSON-RPC serialization + * @see {@link layerHttp} for an HTTP-backed layer that registers with `HttpRouter` and installs JSON-RPC serialization + * * @category layers + * @since 4.0.0 */ export const layer = (options: { readonly name: string @@ -513,12 +567,13 @@ export const layer = (options: { ) /** - * Run the McpServer, using stdio for input and output. + * Runs the McpServer, using stdio for input and output. + * + * **Example** (Running an MCP server over stdio) * - * @example * ```ts - * import { NodeRuntime, NodeStdio } from "@effect/platform-node" * import { Effect, Layer, Logger, Schema } from "effect" + * import { NodeRuntime, NodeStdio } from "@effect/platform-node" * import { McpSchema, McpServer } from "effect/unstable/ai" * * const idParam = McpSchema.param("id", Schema.Number) @@ -566,8 +621,8 @@ export const layer = (options: { * Layer.launch(ServerLayer).pipe(NodeRuntime.runMain) * ``` * - * @since 4.0.0 * @category layers + * @since 4.0.0 */ export const layerStdio = (options: { readonly name: string @@ -580,10 +635,23 @@ export const layerStdio = (options: { ) /** - * Run the `McpServer`, registering a router with a `HttpRouter` + * Registers an HTTP POST JSON-RPC route at `options.path` on the current + * `HttpRouter`. + * + * **When to use** + * + * Use to expose an MCP server through an existing `HttpRouter`. + * + * **Details** + * + * This layer composes `layer(options)`, `RpcServer.layerProtocolHttp(options)`, + * and `RpcSerialization.layerJsonRpc()`. + * + * @see {@link layerStdio} for exposing the server over stdio + * @see {@link layer} for the base MCP server layer without a transport protocol * - * @since 4.0.0 * @category layers + * @since 4.0.0 */ export const layerHttp = (options: { readonly name: string @@ -597,10 +665,10 @@ export const layerHttp = (options: { ) /** - * Register a `Toolkit` with the `McpServer`. + * Registers a `Toolkit` with the `McpServer`. * - * @since 4.0.0 * @category tools + * @since 4.0.0 */ export const registerToolkit: >( toolkit: Toolkit.Toolkit @@ -673,10 +741,10 @@ export const registerToolkit: >( }) /** - * Register an AiToolkit with the McpServer. + * Registers an `AiToolkit` with the `McpServer`. * - * @since 4.0.0 * @category tools + * @since 4.0.0 */ export const toolkit = >( toolkit: Toolkit.Toolkit @@ -690,6 +758,10 @@ export const toolkit = >( ) /** + * Utility type that validates a completion-handler record against the allowed + * parameter keys. + * + * @category utility types * @since 4.0.0 */ export type ValidateCompletions = @@ -699,6 +771,15 @@ export type ValidateCompletions = } /** + * Completion-handler map for a resource URI template. + * + * **Details** + * + * Each schema interpolation contributes a parameter key, using an explicit + * `Param` name when present or `paramN` otherwise, and each handler returns + * candidate values for that parameter. + * + * @category models * @since 4.0.0 */ export type ResourceCompletions> = { @@ -709,17 +790,33 @@ export type ResourceCompletions> = { } /** - * Register a resource with the McpServer. + * Registers an MCP resource or resource template from an Effect program. + * + * **When to use** + * + * Use when you are already inside an Effect program with an `McpServer` + * service and need to add a concrete resource or URI-template resource + * directly. + * + * @see {@link resource} for the layer-based resource registration wrapper * - * @since 4.0.0 * @category resources + * @since 4.0.0 */ export const registerResource: { /** - * Register a resource with the McpServer. + * Registers an MCP resource or resource template from an Effect program. + * + * **When to use** + * + * Use when you are already inside an Effect program with an `McpServer` + * service and need to add a concrete resource or URI-template resource + * directly. + * + * @see {@link resource} for the layer-based resource registration wrapper * - * @since 4.0.0 * @category resources + * @since 4.0.0 */ ( options: { @@ -738,10 +835,18 @@ export const registerResource: { } ): Effect.Effect | McpServer> /** - * Register a resource with the McpServer. + * Registers an MCP resource or resource template from an Effect program. + * + * **When to use** + * + * Use when you are already inside an Effect program with an `McpServer` + * service and need to add a concrete resource or URI-template resource + * directly. + * + * @see {@link resource} for the layer-based resource registration wrapper * - * @since 4.0.0 * @category resources + * @since 4.0.0 */ >(segments: TemplateStringsArray, ...schemas: Schemas): < E, @@ -879,17 +984,29 @@ export const registerResource: { } as any /** - * Register a resource with the McpServer. + * Creates a layer that registers an MCP resource or resource template. + * + * **When to use** + * + * Use to compose resource registration into an MCP server layer. + * + * @see {@link registerResource} for the Effect-level resource registration API * - * @since 4.0.0 * @category resources + * @since 4.0.0 */ export const resource: { /** - * Register a resource with the McpServer. + * Creates a layer that registers an MCP resource or resource template. + * + * **When to use** + * + * Use to compose resource registration into an MCP server layer. + * + * @see {@link registerResource} for the Effect-level resource registration API * - * @since 4.0.0 * @category resources + * @since 4.0.0 */ ( options: { @@ -907,10 +1024,16 @@ export const resource: { } ): Layer.Layer> /** - * Register a resource with the McpServer. + * Creates a layer that registers an MCP resource or resource template. + * + * **When to use** + * + * Use to compose resource registration into an MCP server layer. + * + * @see {@link registerResource} for the Effect-level resource registration API * - * @since 4.0.0 * @category resources + * @since 4.0.0 */ >(segments: TemplateStringsArray, ...schemas: Schemas): < E, @@ -953,10 +1076,23 @@ export const resource: { } as any /** - * Register a prompt with the McpServer. + * Registers an MCP prompt from an Effect program. + * + * **When to use** + * + * Use when you are already inside an Effect program with an `McpServer` + * service and need to add a prompt handler directly. + * + * **Details** + * + * Parameters are decoded with the supplied schema, completion handlers encode + * per-parameter suggestions, and string prompt content is converted into a user + * text message. + * + * @see {@link prompt} for the layer-based prompt registration wrapper * - * @since 4.0.0 * @category prompts + * @since 4.0.0 */ export const registerPrompt = < E, @@ -980,8 +1116,8 @@ export const registerPrompt = < for (const [name, prop] of Object.entries(props)) { args.push({ name, - description: AST.resolveDescription(prop.ast), - required: !AST.isOptional(prop.ast) + description: SchemaAST.resolveDescription(prop.ast), + required: !SchemaAST.isOptional(prop.ast) }) } const prompt = new Prompt({ @@ -1048,10 +1184,22 @@ export const registerPrompt = < } /** - * Register a prompt with the McpServer. + * Creates a layer that registers an MCP prompt. + * + * **When to use** + * + * Use to compose prompt registration into an MCP server layer. + * + * **Details** + * + * Parameters are decoded with the supplied schema, completion handlers encode + * per-parameter suggestions, and string prompt content is converted into a user + * text message. + * + * @see {@link registerPrompt} for the Effect-level prompt registration API * - * @since 4.0.0 * @category prompts + * @since 4.0.0 */ export const prompt = < E, @@ -1077,10 +1225,16 @@ export const prompt = < ) /** - * Create an elicitation request + * Collects structured input from the current MCP client and decodes the + * accepted response with `schema`. + * + * **Details** + * + * Accepted content is decoded with the supplied schema, declined requests fail + * with `ElicitationDeclined`, and canceled requests interrupt the effect. * - * @since 4.0.0 * @category elicitation + * @since 4.0.0 */ export const elicit: , unknown>>(options: { readonly message: string @@ -1114,10 +1268,10 @@ export const elicit: , unknown> }, Effect.scoped) /** - * Access the current client's capabilities. + * Accesses the current client's capabilities. * - * @since 4.0.0 * @category capabilities + * @since 4.0.0 */ export const clientCapabilities: Effect.Effect< ClientCapabilities, @@ -1280,9 +1434,9 @@ const layerHandlers = (serverInfo: { Effect.provideService(CurrentLogLevel, currentLogLevel) ), "resources/subscribe": () => - InternalError.notImplemented.asEffect(), + InternalError.notImplemented, "resources/unsubscribe": () => - InternalError.notImplemented.asEffect(), + InternalError.notImplemented, "resources/templates/list": (_, { client, headers }) => Effect.sync(() => { const initialized = getInitializedClient(options.clientSessions, client.id, headers) diff --git a/.opencode/node_modules/effect/src/unstable/ai/Model.ts b/.opencode/node_modules/effect/src/unstable/ai/Model.ts index 8645d1a3efd765e018acc5d959c0300e754dba08..6e78123c6e6ab0b3119069d1372bcfa8bcd7e1dd 100644 --- a/.opencode/node_modules/effect/src/unstable/ai/Model.ts +++ b/.opencode/node_modules/effect/src/unstable/ai/Model.ts @@ -1,37 +1,19 @@ /** - * The `Model` module provides a unified interface for AI service providers. + * Wraps an AI model layer with provider and model metadata. * - * This module enables creation of provider-specific AI models that can be used - * interchangeably within the Effect AI ecosystem. It combines Layer - * functionality with provider identification, allowing for seamless switching - * between different AI service providers while maintaining type safety. - * - * @example - * ```ts - * import type { Layer } from "effect" - * import { Effect } from "effect" - * import { LanguageModel, Model } from "effect/unstable/ai" - * - * declare const myAnthropicLayer: Layer.Layer - * - * const anthropicModel = Model.make("anthropic", "claude-3-5-haiku", myAnthropicLayer) - * - * const program = Effect.gen(function*() { - * const response = yield* LanguageModel.generateText({ - * prompt: "Hello, world!" - * }) - * return response.text - * }).pipe( - * Effect.provide(anthropicModel) - * ) - * ``` + * A `Model` can be used anywhere its underlying `Layer` can be used. It also + * provides the current provider name and model name through the Effect context. + * This module includes the `Model` interface, the `ProviderName` and + * `ModelName` service tags, and the `make` constructor. Models can also capture + * their required services from the current context when they need to be used + * inside another Effect service. * * @since 4.0.0 */ import * as Context from "../../Context.ts" import * as Effect from "../../Effect.ts" import { identity } from "../../Function.ts" -import { PipeInspectableProto, YieldableProto } from "../../internal/core.ts" +import { PipeInspectableProto } from "../../internal/core.ts" import * as Layer from "../../Layer.ts" const TypeId = "~effect/ai/Model" as const @@ -39,46 +21,47 @@ const TypeId = "~effect/ai/Model" as const /** * A Model represents a provider-specific AI service. * - * A Model can be used directly as a Layer to provide a particular model - * implementation to an Effect program. - * - * A Model can also be used as an Effect to "lift" dependencies of the Model - * constructor into the parent Effect. This is particularly useful when you - * want to use a Model from within an Effect service. + * **When to use** * - * @template Provider - String literal type identifying the AI provider. - * @template Provides - Services that this model provides. - * @template Requires - Services that this model requires. + * Use when you use a Model directly as a Layer to provide a particular model implementation + * to an Effect program, or use it as an Effect to "lift" dependencies of the + * Model constructor into the parent Effect when you want to use a Model from + * within an Effect service. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface Model - extends - Layer.Layer, - Effect.Yieldable< - Model, - Layer.Layer, - never, - Requires - > + extends Layer.Layer { readonly [TypeId]: typeof TypeId + /** * The provider identifier (e.g., "openai", "anthropic", "amazon-bedrock"). */ readonly provider: Provider + + /** + * Returns a `Layer` with the requirements satisfied, using the current context. + */ + readonly captureRequirements: Effect.Effect< + Layer.Layer, + never, + Requires + > } /** * Service tag that provides the current large language model provider name. * + * **Details** + * * This tag is automatically provided by Model instances and can be used to * access the name of the provider that is currently in use within a given * Effect program. * - * @since 4.0.0 * @category services + * @since 4.0.0 */ export class ProviderName extends Context.Service()( "effect/unstable/ai/Model/ProviderName" @@ -87,19 +70,20 @@ export class ProviderName extends Context.Service()( /** * Service tag that provides the current large language model name. * + * **Details** + * * This tag is automatically provided by Model instances and can be used to * access the name of the model that is currently in use within a given Effect * program. * - * @since 4.0.0 * @category services + * @since 4.0.0 */ export class ModelName extends Context.Service()( "effect/unstable/ai/Model/ModelName" ) {} const Proto = { - ...YieldableProto, ...PipeInspectableProto, [TypeId]: TypeId, ["~effect/Layer"]: { @@ -107,9 +91,10 @@ const Proto = { _E: identity, _RIn: identity }, - asEffect(this: Model) { + get captureRequirements() { + const self = this as any as Model return Effect.contextWith((context: Context.Context) => - Effect.succeed(Layer.provide(this, Layer.succeedContext(context))) + Effect.succeed(Layer.provide(self, Layer.succeedContext(context))) ) }, toJSON(this: Model): unknown { @@ -123,10 +108,11 @@ const Proto = { /** * Creates a Model from a provider name and a Layer that constructs AI services. * - * @example + * **Example** (Providing model metadata) + * * ```ts - * import type { Layer } from "effect" * import { Effect } from "effect" + * import type { Layer } from "effect" * import { LanguageModel, Model } from "effect/unstable/ai" * * declare const bedrockLayer: Layer.Layer @@ -149,8 +135,8 @@ const Proto = { * // Will log: "Generating with: amazon-bedrock/claude-3-5-haiku" * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const make = ( /** diff --git a/.opencode/node_modules/effect/src/unstable/ai/OpenAiStructuredOutput.ts b/.opencode/node_modules/effect/src/unstable/ai/OpenAiStructuredOutput.ts index 8a6b65f59eac3c9c0c158c7b6b6a3fcc16f7a05d..5a6645fbc85b5bc49d88c4fafffb6e8c0431e44f 100644 --- a/.opencode/node_modules/effect/src/unstable/ai/OpenAiStructuredOutput.ts +++ b/.opencode/node_modules/effect/src/unstable/ai/OpenAiStructuredOutput.ts @@ -1,7 +1,14 @@ /** - * Provides codec transformations for OpenAI structured output. + * Adapts Effect schemas for OpenAI structured output. * - * @since 1.0.0 + * OpenAI structured output accepts only a subset of JSON Schema. This module + * converts an Effect `Schema.Codec` into a provider-compatible JSON Schema and + * a matching codec for decoding the model response back into the original + * application type. When possible, unsupported schema shapes are rewritten into + * supported ones; schema kinds that cannot be represented safely fail during + * conversion. + * + * @since 4.0.0 */ import * as Arr from "../../Array.ts" import * as JsonSchema from "../../JsonSchema.ts" @@ -9,36 +16,39 @@ import * as Option from "../../Option.ts" import * as Predicate from "../../Predicate.ts" import * as Rec from "../../Record.ts" import * as Schema from "../../Schema.ts" -import * as AST from "../../SchemaAST.ts" -import * as Transformation from "../../SchemaTransformation.ts" +import * as SchemaAST from "../../SchemaAST.ts" +import * as SchemaTransformation from "../../SchemaTransformation.ts" import * as Tool from "./Tool.ts" /** - * Transforms a `Schema.Codec` into a form compatible with OpenAI's - * structured output constraints. + * Converts a `Schema.Codec` to OpenAI structured-output JSON Schema and a + * matching codec for model output. + * + * **When to use** + * + * Use when you send Effect Schema-backed structured output requests to OpenAI + * and need provider-compatible JSON Schema without losing the decoded + * application type. * - * The transformation walks the schema AST and rewrites constructs that - * OpenAI does not support natively: + * **Details** * - * - **Tuples** are converted to objects with numeric string keys (e.g. - * `"0"`, `"1"`) since OpenAI does not support tuple schemas. Rest - * elements are placed under a `"__rest__"` key. - * - **Optional properties** are replaced with `T | null` unions, because - * OpenAI requires all properties to be present. - * - **Records** (index signatures) are converted to arrays of `[key, value]` - * pairs. - * - **`oneOf` unions** are rewritten as `anyOf` unions. - * - **Regex patterns** from multiple filters are merged into a single - * `pattern` using lookaheads, since OpenAI does not support `allOf`. - * - **Filters and annotations** are preserved where compatible (e.g. - * `description`, supported `format` values like `"date-time"`, `"email"`, - * `"uuid"`, etc.), and stripped otherwise. + * Returns the JSON Schema to include in the request and the codec to use when + * decoding the model response. If the input schema already fits OpenAI's + * supported JSON Schema subset, the original codec is returned unchanged. * - * If the schema is already compatible, the original codec is returned - * unchanged. + * **Gotchas** + * + * - Some schemas use a provider-safe encoded shape: tuples become objects with + * numeric string keys, records become arrays of `[key, value]` pairs, and + * optional properties become required nullable properties. + * - `oneOf` unions are emitted as `anyOf` unions. + * - Regex patterns from multiple filters are merged into one `pattern` because + * OpenAI structured output does not support `allOf`. + * - Unsupported schema kinds throw during conversion instead of producing a + * lossy schema. * - * @since 1.0.0 * @category Codec Transformation + * @since 4.0.0 */ export function toCodecOpenAI( schema: Schema.Codec @@ -47,8 +57,10 @@ export function toCodecOpenAI( jsonSchema: JsonSchema.JsonSchema } { const to = schema.ast - const from = recurOpenAI(AST.toEncoded(to)) - const codec = from === to ? schema : Schema.make(AST.decodeTo(from, to, Transformation.passthrough())) + const from = recurOpenAI(SchemaAST.toEncoded(to)) + const codec = from === to + ? schema + : Schema.make(SchemaAST.decodeTo(from, to, SchemaTransformation.passthrough())) const document = JsonSchema.resolveTopLevel$ref(Schema.toJsonSchemaDocument(codec)) const jsonSchema = rewriteOpenAI(document.schema) if (Object.keys(document.definitions).length > 0) { @@ -88,7 +100,7 @@ function rewriteOpenAI(schema: JsonSchema.JsonSchema): JsonSchema.JsonSchema { return out } -function recurOpenAI(ast: AST.AST): AST.AST { +function recurOpenAI(ast: SchemaAST.AST): SchemaAST.AST { switch (ast._tag) { case "Declaration": case "Void": @@ -115,14 +127,14 @@ function recurOpenAI(ast: AST.AST): AST.AST { case "String": { const { annotations, filters } = get(ast) if (annotations !== undefined || filters !== undefined) { - return new AST.String(annotations, filters) + return new SchemaAST.String(annotations, filters) } return ast } case "Number": { const { annotations, filters } = get(ast) if (annotations !== undefined || filters !== undefined) { - return new AST.Number(annotations, filters) + return new SchemaAST.Number(annotations, filters) } return ast } @@ -133,7 +145,7 @@ function recurOpenAI(ast: AST.AST): AST.AST { if (typeof literal === "string" || typeof literal === "number" || typeof literal === "boolean") { const { annotations, filters } = get(ast) if (annotations !== undefined || filters !== undefined) { - return new AST.Literal(ast.literal, annotations, filters) + return new SchemaAST.Literal(ast.literal, annotations, filters) } return ast } @@ -145,12 +157,12 @@ function recurOpenAI(ast: AST.AST): AST.AST { } case "Union": { if (ast.mode === "oneOf") { - return new AST.Union(ast.types, "anyOf", ast.annotations, ast.checks) + return new SchemaAST.Union(ast.types, "anyOf", ast.annotations, ast.checks) } - const types = AST.mapOrSame(ast.types, recurOpenAI) + const types = SchemaAST.mapOrSame(ast.types, recurOpenAI) const { annotations, filters } = get(ast) if (types !== ast.types || annotations !== undefined || filters !== undefined) { - return new AST.Union(types, "anyOf", annotations, filters) + return new SchemaAST.Union(types, "anyOf", annotations, filters) } return ast } @@ -170,15 +182,17 @@ function recurOpenAI(ast: AST.AST): AST.AST { annotations.description = TUPLE_DESCRIPTION } const propertySignatures = ast.elements.map((e, i) => { - return new AST.PropertySignature(String(i), e) + return new SchemaAST.PropertySignature(String(i), e) }) if (ast.rest.length === 1) { - propertySignatures.push(new AST.PropertySignature(REST_PROPERTY_NAME, new AST.Arrays(false, [], ast.rest))) + propertySignatures.push( + new SchemaAST.PropertySignature(REST_PROPERTY_NAME, new SchemaAST.Arrays(false, [], ast.rest)) + ) } - return AST.decodeTo( - recurOpenAI(new AST.Objects(propertySignatures, [], annotations, filters)), + return SchemaAST.decodeTo( + recurOpenAI(new SchemaAST.Objects(propertySignatures, [], annotations, filters)), ast, - Transformation.transform({ + SchemaTransformation.transform({ decode: (o) => { let t: Array = [] for (let i = 0; i < ast.elements.length; i++) { @@ -207,9 +221,9 @@ function recurOpenAI(ast: AST.AST): AST.AST { }) ) } else { - const rest = AST.mapOrSame(ast.rest, recurOpenAI) + const rest = SchemaAST.mapOrSame(ast.rest, recurOpenAI) if (rest !== ast.rest || annotations !== undefined || filters !== undefined) { - return new AST.Arrays(false, [], rest, annotations, filters) + return new SchemaAST.Arrays(false, [], rest, annotations, filters) } return ast } @@ -217,7 +231,7 @@ function recurOpenAI(ast: AST.AST): AST.AST { case "Objects": { let { annotations, filters } = get(ast) if (ast.indexSignatures.length === 0) { - const propertySignatures = AST.mapOrSame(ast.propertySignatures, (ps) => { + const propertySignatures = SchemaAST.mapOrSame(ast.propertySignatures, (ps) => { if (typeof ps.name !== "string") { throw new Error( `${errorPrefix}: Property names must be strings (got ${typeof ps.name})` @@ -225,11 +239,11 @@ function recurOpenAI(ast: AST.AST): AST.AST { } let type = recurOpenAI(ps.type) // optional properties are not supported by OpenAI, so we translate them to nullable unions - if (AST.isOptional(ps.type)) { - type = AST.decodeTo( - new AST.Union([type, AST.null], "anyOf"), - AST.optionalKey(type), - Transformation.transformOptional({ + if (SchemaAST.isOptional(ps.type)) { + type = SchemaAST.decodeTo( + new SchemaAST.Union([type, SchemaAST.null], "anyOf"), + SchemaAST.optionalKey(type), + SchemaTransformation.transformOptional({ decode: Option.filter(Predicate.isNotNull), encode: Option.orElseSome(() => null) }) @@ -238,12 +252,12 @@ function recurOpenAI(ast: AST.AST): AST.AST { if (type === ps.type) { return ps } - return new AST.PropertySignature(ps.name, type) + return new SchemaAST.PropertySignature(ps.name, type) }) if ( propertySignatures !== ast.propertySignatures || annotations !== undefined || filters !== undefined ) { - return new AST.Objects(propertySignatures, [], annotations, filters) + return new SchemaAST.Objects(propertySignatures, [], annotations, filters) } } else if (ast.indexSignatures.length === 1 && ast.propertySignatures.length === 0) { const is = ast.indexSignatures[0] @@ -257,10 +271,12 @@ function recurOpenAI(ast: AST.AST): AST.AST { annotations ??= {} annotations.description = RECORD_DESCRIPTION } - return AST.decodeTo( - recurOpenAI(new AST.Arrays(false, [], [new AST.Arrays(false, [is.parameter, is.type], [])], annotations)), + return SchemaAST.decodeTo( + recurOpenAI( + new SchemaAST.Arrays(false, [], [new SchemaAST.Arrays(false, [is.parameter, is.type], [])], annotations) + ), ast, - Transformation.transform({ + SchemaTransformation.transform({ decode: Object.fromEntries, encode: Object.entries }) @@ -275,19 +291,19 @@ function recurOpenAI(ast: AST.AST): AST.AST { case "Suspend": { const cached = cache.get(ast) if (cached) return cached - const { annotations, filters } = get(ast) - const out = new AST.Suspend(() => recurOpenAI(ast.thunk()), annotations, filters) + const { annotations } = get(ast) + const out = new SchemaAST.Suspend(() => recurOpenAI(ast.thunk()), annotations) cache.set(ast, out) return out } } } -const cache = new Map() +const cache = new Map() const errorPrefix = "OpenAiStructuredOutput" -function unsupportedAst(ast: AST.AST, details?: string): never { +function unsupportedAst(ast: SchemaAST.AST, details?: string): never { const base = `Unsupported AST ${ast._tag}` const full = `${errorPrefix}: ${base}` throw new Error(details !== undefined ? `${full} (${details})` : full) @@ -307,17 +323,17 @@ type Annotation = type Filter = | Annotation - | { readonly _tag: "filter"; readonly filter: AST.Filter } + | { readonly _tag: "filter"; readonly filter: SchemaAST.Filter } | { readonly _tag: "regex"; readonly source: string } -const get = (ast: AST.AST): { +const get = (ast: SchemaAST.AST): { annotations: Record | undefined - filters: [AST.Check, ...AST.Check[]] | undefined + filters: [SchemaAST.Check, ...SchemaAST.Check[]] | undefined } => { const annotations: Record = {} - const filters: Array> = [] + const filters: Array> = [] const regexSources: Array = [] - const checks = getChecks(ast, AST.isArrays(ast)) + const checks = getChecks(ast, SchemaAST.isArrays(ast)) if (checks.length > 0) { for (const check of checks) { switch (check._tag) { @@ -346,10 +362,10 @@ const get = (ast: AST.AST): { } // OpenAI does not support allOf, so we merge multiple regex patterns into a single isPattern filter if (regexSources.length === 1) { - filters.push(AST.isPattern(new RegExp(regexSources[0]))) + filters.push(SchemaAST.isPattern(new RegExp(regexSources[0]))) } else if (regexSources.length > 1) { const combined = regexSources.map((s) => `(?=[\\s\\S]*?(?:${s}))`).join("") - filters.push(AST.isPattern(new RegExp(`^${combined}`))) + filters.push(SchemaAST.isPattern(new RegExp(`^${combined}`))) } return { annotations: Object.keys(annotations).length > 0 ? annotations : undefined, @@ -357,7 +373,7 @@ const get = (ast: AST.AST): { } } -const getChecks = (ast: AST.AST, isArray: boolean): Array => [ +const getChecks = (ast: SchemaAST.AST, isArray: boolean): Array => [ ...(ast.checks !== undefined ? getFilters(ast.checks, isArray) : []), ...getAnnotations(ast.annotations) ] @@ -384,7 +400,7 @@ const getAnnotations = (annotations: Schema.Annotations.Filter | undefined): Arr return out } -function getFilter(filter: AST.Filter, isArray: boolean): Array { +function getFilter(filter: SchemaAST.Filter, isArray: boolean): Array { let out: Array = [] const annotations = getAnnotations(filter.annotations) const meta = filter.annotations?.meta @@ -423,7 +439,7 @@ function getFilter(filter: AST.Filter, isArray: boolean): Array { return out } -function resetFilter(filter: AST.Filter): AST.Filter { +function resetFilter(filter: SchemaAST.Filter): SchemaAST.Filter { return filter.annotate({ description: undefined, expected: undefined, @@ -432,7 +448,10 @@ function resetFilter(filter: AST.Filter): AST.Filter { }) } -function getFilters(checks: readonly [AST.Check, ...AST.Check[]], isArray: boolean): Array { +function getFilters( + checks: readonly [SchemaAST.Check, ...SchemaAST.Check[]], + isArray: boolean +): Array { return checks.flatMap((check) => { switch (check._tag) { case "Filter": diff --git a/.opencode/node_modules/effect/src/unstable/ai/Prompt.ts b/.opencode/node_modules/effect/src/unstable/ai/Prompt.ts index 22ac8c4f7b6dd6a3d4e5a6c3e89a370f7109aee4..0c3aac0c7e6221e3ff3239dcd9685feac485e02f 100644 --- a/.opencode/node_modules/effect/src/unstable/ai/Prompt.ts +++ b/.opencode/node_modules/effect/src/unstable/ai/Prompt.ts @@ -1,53 +1,11 @@ /** - * The `Prompt` module provides several data structures to simplify creating and - * combining prompts. + * Defines prompts sent to AI language models. * - * This module defines the complete structure of a conversation with a large - * language model, including messages, content parts, and provider-specific - * options. It supports rich content types like text, files, tool calls, and - * reasoning. - * - * @example - * ```ts - * import { Prompt } from "effect/unstable/ai" - * - * // Create a structured conversation - * const conversation = Prompt.make([ - * { - * role: "system", - * content: "You are a helpful assistant specialized in mathematics." - * }, - * { - * role: "user", - * content: [{ - * type: "text", - * text: "What is the derivative of x²?" - * }] - * }, - * { - * role: "assistant", - * content: [{ - * type: "text", - * text: "The derivative of x² is 2x." - * }] - * } - * ]) - * ``` - * - * @example - * ```ts - * import { Prompt } from "effect/unstable/ai" - * - * // Concatenate multiple prompts together sequentially - * const systemPrompt = Prompt.make([{ - * role: "system", - * content: "You are a coding assistant." - * }]) - * - * const userPrompt = Prompt.make("Help me write a function") - * - * const combined = Prompt.concat(systemPrompt, userPrompt) - * ``` + * A prompt is an ordered list of messages. Messages can use roles such as + * system, user, assistant, and tool, and their content can be split into typed + * parts such as text, files, reasoning, tool calls, tool results, and approval + * messages. This module helps build prompts, combine them, and convert raw + * input or response parts into the shared prompt shape. * * @since 4.0.0 */ @@ -59,7 +17,7 @@ import { type Pipeable, pipeArguments } from "../../Pipeable.ts" import * as Predicate from "../../Predicate.ts" import * as Schema from "../../Schema.ts" import * as SchemaIssue from "../../SchemaIssue.ts" -import * as Parser from "../../SchemaParser.ts" +import * as SchemaParser from "../../SchemaParser.ts" import * as SchemaTransformation from "../../SchemaTransformation.ts" import type * as Response from "./Response.ts" @@ -68,21 +26,16 @@ import type * as Response from "./Response.ts" // ============================================================================= /** - * Schema for provider-specific options which can be attached to both content - * parts and messages, enabling provider-specific behavior. + * Schema for provider-specific options that can be attached to content parts + * and messages. * - * Provider-specific options are namespaced by provider and have the structure: + * **Details** * - * ``` - * { - * "": { - * // Provider-specific options - * } - * } - * ``` + * Provider-specific options are keyed by provider-specific names, and each + * value is JSON or `null`. * + * @category options * @since 4.0.0 - * @category models */ export const ProviderOptions: Schema.$Record< Schema.String, @@ -90,8 +43,11 @@ export const ProviderOptions: Schema.$Record< > = Schema.Record(Schema.String, Schema.NullOr(Schema.Json)) /** + * Type of provider-specific options that can be attached to prompt messages + * and content parts. + * + * @category options * @since 4.0.0 - * @category models */ export type ProviderOptions = typeof ProviderOptions.Type @@ -104,19 +60,22 @@ const PartTypeId = "~effect/ai/Prompt/Part" as const /** * Type guard to check if a value is a Part. * + * @category guards * @since 4.0.0 - * @category Guards */ export const isPart = (u: unknown): u is Part => Predicate.hasProperty(u, PartTypeId) /** * Union type representing all possible content parts within messages. * + * **Details** + * * Parts are the building blocks of message content, supporting text, files, - * reasoning, tool calls, and tool results. + * reasoning, tool calls, tool results, tool approval responses, and tool + * approval requests. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type Part = | TextPart @@ -130,8 +89,8 @@ export type Part = /** * Encoded representation of a Part. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type PartEncoded = | TextPartEncoded @@ -145,10 +104,13 @@ export type PartEncoded = /** * Base interface for all content parts. * - * Provides common structure including type and provider options. + * **Details** + * + * It provides the common structure shared by all content parts, including the + * part type and provider options. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface BasePart { readonly [PartTypeId]: typeof PartTypeId @@ -165,8 +127,8 @@ export interface BasePart /** * Base interface for encoded content parts. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface BasePartEncoded { /** @@ -189,7 +151,8 @@ const BasePart = Schema.Struct({ /** * Creates a new content part of the specified type. * - * @example + * **Example** (Creating content parts) + * * ```ts * import { Prompt } from "effect/unstable/ai" * @@ -204,8 +167,8 @@ const BasePart = Schema.Struct({ * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const makePart = ( /** @@ -221,20 +184,19 @@ export const makePart = ( */ readonly options?: Extract["options"] | undefined } -): Extract => - (({ - ...params, - [PartTypeId]: PartTypeId, - type, - options: params.options ?? {} - }) as any) +): Extract => (({ + ...params, + [PartTypeId]: PartTypeId, + type, + options: params.options ?? {} +}) as any) /** * A utility type for specifying the parameters required to construct a * specific part of a prompt. * + * @category utility types * @since 4.0.0 - * @category Utility Types */ export type PartConstructorParams

= Omit & { /** @@ -250,9 +212,13 @@ export type PartConstructorParams

= Omit = Omit { /** @@ -274,8 +240,8 @@ export interface TextPart extends BasePart<"text", TextPartOptions> { /** * Encoded representation of text parts for serialization. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface TextPartEncoded extends BasePartEncoded<"text", TextPartOptions> { /** @@ -288,16 +254,16 @@ export interface TextPartEncoded extends BasePartEncoded<"text", TextPartOptions * Represents provider-specific options that can be associated with a * `TextPart` through module augmentation. * + * @category options * @since 4.0.0 - * @category ProviderOptions */ export interface TextPartOptions extends ProviderOptions {} /** * Schema for validation and encoding of text parts. * - * @since 4.0.0 * @category schemas + * @since 4.0.0 */ export const TextPart: Schema.Struct< { @@ -320,8 +286,8 @@ export const TextPart: Schema.Struct< /** * Constructs a new text part. * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const textPart = (params: PartConstructorParams): TextPart => makePart("text", params as any) @@ -330,20 +296,22 @@ export const textPart = (params: PartConstructorParams): TextPart => m // ============================================================================= /** - * Content part representing reasoning or chain-of-thought. + * Content part carrying reasoning text in an assistant message, such as a + * provider-supplied reasoning summary or explanation. + * + * **Example** (Creating reasoning parts) * - * @example * ```ts * import { Prompt } from "effect/unstable/ai" * * const reasoningPart: Prompt.ReasoningPart = Prompt.makePart("reasoning", { * text: - * "Let me think step by step: First I need to understand the user's question..." + * "Summary: the response compares the requested options by price and availability." * }) * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface ReasoningPart extends BasePart<"reasoning", ReasoningPartOptions> { /** @@ -355,8 +323,8 @@ export interface ReasoningPart extends BasePart<"reasoning", ReasoningPartOption /** * Encoded representation of reasoning parts for serialization. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface ReasoningPartEncoded extends BasePartEncoded<"reasoning", ReasoningPartOptions> { /** @@ -369,16 +337,16 @@ export interface ReasoningPartEncoded extends BasePartEncoded<"reasoning", Reaso * Represents provider-specific options that can be associated with a * `ReasoningPart` through module augmentation. * + * @category options * @since 4.0.0 - * @category ProviderOptions */ export interface ReasoningPartOptions extends ProviderOptions {} /** * Schema for validation and encoding of reasoning parts. * - * @since 4.0.0 * @category schemas + * @since 4.0.0 */ export const ReasoningPart: Schema.Struct<{ readonly type: Schema.Literal<"reasoning"> @@ -399,8 +367,8 @@ export const ReasoningPart: Schema.Struct<{ /** * Constructs a new reasoning part. * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const reasoningPart = (params: PartConstructorParams): ReasoningPart => makePart("reasoning", params as any) @@ -410,12 +378,15 @@ export const reasoningPart = (params: PartConstructorParams): Rea // ============================================================================= /** - * Content part representing a file attachment. Files can be provided as base64 - * strings of data, byte arrays, or URLs. + * Content part representing a file attachment. + * + * **Details** * - * Supports various file types including images, documents, and binary data. + * Files can be provided as base64 data strings, byte arrays, or URLs, and can + * represent images, documents, or other binary data. + * + * **Example** (Creating file parts) * - * @example * ```ts * import { Prompt } from "effect/unstable/ai" * @@ -432,8 +403,8 @@ export const reasoningPart = (params: PartConstructorParams): Rea * }) * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface FilePart extends BasePart<"file", FilePartOptions> { /** @@ -453,8 +424,8 @@ export interface FilePart extends BasePart<"file", FilePartOptions> { /** * Encoded representation of file parts for serialization. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface FilePartEncoded extends BasePartEncoded<"file", FilePartOptions> { /** @@ -475,16 +446,16 @@ export interface FilePartEncoded extends BasePartEncoded<"file", FilePartOptions * Represents provider-specific options that can be associated with a * `FilePart` through module augmentation. * + * @category options * @since 4.0.0 - * @category ProviderOptions */ export interface FilePartOptions extends ProviderOptions {} /** * Schema for validation and encoding of file parts. * - * @since 4.0.0 * @category schemas + * @since 4.0.0 */ export const FilePart: Schema.Struct<{ readonly type: Schema.Literal<"file"> @@ -507,10 +478,17 @@ export const FilePart: Schema.Struct<{ }).annotate({ identifier: "FilePart" }) /** - * Constructs a new file part. + * Constructs a `FilePart` for prompt file attachments. + * + * **When to use** + * + * Use to create the file-attachment part of a prompt from typed file part + * parameters. + * + * @see {@link makePart} for the generic part constructor * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const filePart = (params: PartConstructorParams): FilePart => makePart("file", params as any) @@ -521,7 +499,8 @@ export const filePart = (params: PartConstructorParams): FilePart => m /** * Content part representing a tool call request. * - * @example + * **Example** (Creating tool call parts) + * * ```ts * import { Prompt } from "effect/unstable/ai" * @@ -533,8 +512,8 @@ export const filePart = (params: PartConstructorParams): FilePart => m * }) * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface ToolCallPart extends BasePart<"tool-call", ToolCallPartOptions> { /** @@ -558,8 +537,8 @@ export interface ToolCallPart extends BasePart<"tool-call", ToolCallPartOptions> /** * Encoded representation of tool call parts for serialization. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface ToolCallPartEncoded extends BasePartEncoded<"tool-call", ToolCallPartOptions> { /** @@ -584,16 +563,16 @@ export interface ToolCallPartEncoded extends BasePartEncoded<"tool-call", ToolCa * Represents provider-specific options that can be associated with a * `ToolCallPart` through module augmentation. * + * @category options * @since 4.0.0 - * @category ProviderOptions */ export interface ToolCallPartOptions extends ProviderOptions {} /** * Schema for validation and encoding of tool call parts. * - * @since 4.0.0 * @category schemas + * @since 4.0.0 */ export const ToolCallPart: Schema.Struct<{ readonly type: Schema.Literal<"tool-call"> @@ -620,8 +599,8 @@ export const ToolCallPart: Schema.Struct<{ /** * Constructs a new tool call part. * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const toolCallPart = (params: PartConstructorParams): ToolCallPart => makePart("tool-call", params as any) @@ -633,7 +612,8 @@ export const toolCallPart = (params: PartConstructorParams): ToolC /** * Content part representing the result of a tool call. * - * @example + * **Example** (Creating tool result parts) + * * ```ts * import { Prompt } from "effect/unstable/ai" * @@ -649,8 +629,8 @@ export const toolCallPart = (params: PartConstructorParams): ToolC * }) * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface ToolResultPart extends BasePart<"tool-result", ToolResultPartOptions> { /** @@ -674,8 +654,8 @@ export interface ToolResultPart extends BasePart<"tool-result", ToolResultPartOp /** * Encoded representation of tool result parts for serialization. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface ToolResultPartEncoded extends BasePartEncoded<"tool-result", ToolResultPartOptions> { /** @@ -700,16 +680,16 @@ export interface ToolResultPartEncoded extends BasePartEncoded<"tool-result", To * Represents provider-specific options that can be associated with a * `ToolResultPart` through module augmentation. * + * @category options * @since 4.0.0 - * @category ProviderOptions */ export interface ToolResultPartOptions extends ProviderOptions {} /** * Schema for validation and encoding of tool result parts. * - * @since 4.0.0 * @category schemas + * @since 4.0.0 */ export const ToolResultPart: Schema.Struct<{ readonly type: Schema.Literal<"tool-result"> @@ -736,8 +716,8 @@ export const ToolResultPart: Schema.Struct<{ /** * Constructs a new tool result part. * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const toolResultPart = (params: PartConstructorParams): ToolResultPart => makePart("tool-result", params as any) @@ -749,10 +729,13 @@ export const toolResultPart = (params: PartConstructorParams): T /** * Content part representing a user's response to a tool approval request. * - * Used in tool messages to approve or deny tool execution when tools have - * the `needsApproval` property set. + * **When to use** + * + * Use when tool messages must approve or deny tool execution for tools with the + * `needsApproval` property set. + * + * **Example** (Creating tool approval responses) * - * @example * ```ts * import { Prompt } from "effect/unstable/ai" * @@ -774,8 +757,8 @@ export const toolResultPart = (params: PartConstructorParams): T * ) * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface ToolApprovalResponsePart extends BasePart<"tool-approval-response", ToolApprovalResponsePartOptions> { /** @@ -795,8 +778,8 @@ export interface ToolApprovalResponsePart extends BasePart<"tool-approval-respon /** * Encoded representation of tool approval response parts for serialization. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface ToolApprovalResponsePartEncoded extends BasePartEncoded<"tool-approval-response", ToolApprovalResponsePartOptions> @@ -819,16 +802,16 @@ export interface ToolApprovalResponsePartEncoded * Represents provider-specific options that can be associated with a * `ToolApprovalResponsePart` through module augmentation. * + * @category options * @since 4.0.0 - * @category ProviderOptions */ export interface ToolApprovalResponsePartOptions extends ProviderOptions {} /** * Schema for validation and encoding of tool approval response parts. * - * @since 4.0.0 * @category schemas + * @since 4.0.0 */ export const ToolApprovalResponsePart: Schema.Struct<{ readonly type: Schema.Literal<"tool-approval-response"> @@ -853,8 +836,8 @@ export const ToolApprovalResponsePart: Schema.Struct<{ /** * Constructs a new tool approval response part. * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const toolApprovalResponsePart = ( params: PartConstructorParams @@ -867,11 +850,14 @@ export const toolApprovalResponsePart = ( /** * Content part representing a tool approval request from the framework. * - * Stored in assistant messages when a tool requires user approval before - * execution. The user responds with a `ToolApprovalResponsePart` in a tool - * message. + * **Details** + * + * Tool approval request parts are stored in assistant messages when a tool + * requires user approval before execution. The user responds with a + * `ToolApprovalResponsePart` in a tool message. + * + * **Example** (Creating tool approval requests) * - * @example * ```ts * import { Prompt } from "effect/unstable/ai" * @@ -884,8 +870,8 @@ export const toolApprovalResponsePart = ( * ) * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface ToolApprovalRequestPart extends BasePart<"tool-approval-request", ToolApprovalRequestPartOptions> { /** @@ -901,8 +887,8 @@ export interface ToolApprovalRequestPart extends BasePart<"tool-approval-request /** * Encoded representation of tool approval request parts for serialization. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface ToolApprovalRequestPartEncoded extends BasePartEncoded<"tool-approval-request", ToolApprovalRequestPartOptions> @@ -921,16 +907,16 @@ export interface ToolApprovalRequestPartEncoded * Represents provider-specific options that can be associated with a * `ToolApprovalRequestPart` through module augmentation. * + * @category options * @since 4.0.0 - * @category ProviderOptions */ export interface ToolApprovalRequestPartOptions extends ProviderOptions {} /** * Schema for validation and encoding of tool approval request parts. * - * @since 4.0.0 * @category schemas + * @since 4.0.0 */ export const ToolApprovalRequestPart: Schema.Struct<{ readonly type: Schema.Literal<"tool-approval-request"> @@ -953,8 +939,8 @@ export const ToolApprovalRequestPart: Schema.Struct<{ /** * Constructs a new tool approval request part. * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const toolApprovalRequestPart = ( params: PartConstructorParams @@ -969,18 +955,21 @@ const MessageTypeId = "~effect/ai/Prompt/Message" as const /** * Type guard to check if a value is a Message. * + * @category guards * @since 4.0.0 - * @category Guards */ export const isMessage = (u: unknown): u is Message => Predicate.hasProperty(u, MessageTypeId) /** * Base interface for all message types. * - * Provides common structure including role and provider options. + * **Details** + * + * It provides the common structure shared by all messages, including the role + * and provider options. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface BaseMessage { readonly [MessageTypeId]: typeof MessageTypeId @@ -997,10 +986,8 @@ export interface BaseMessage { /** @@ -1023,7 +1010,8 @@ const BaseMessage = Schema.Struct({ /** * Creates a new message with the specified role. * - * @example + * **Example** (Creating messages) + * * ```ts * import { Prompt } from "effect/unstable/ai" * @@ -1031,33 +1019,32 @@ const BaseMessage = Schema.Struct({ * text: "Hello, world!" * }) * - * const filePart = Prompt.makeMessage("user", { + * const userMessage = Prompt.makeMessage("user", { * content: [textPart] * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const makeMessage = ( role: Role, params: Omit, typeof MessageTypeId | "role" | "options"> & { readonly options?: Extract["options"] | undefined } -): Extract => - (({ - ...params, - [MessageTypeId]: MessageTypeId, - role, - options: params.options ?? {} - }) as any) +): Extract => (({ + ...params, + [MessageTypeId]: MessageTypeId, + role, + options: params.options ?? {} +}) as any) /** * A utility type for specifying the parameters required to construct a * specific message for a prompt. * + * @category utility types * @since 4.0.0 - * @category Utility Types */ export type MessageConstructorParams = Omit & { /** @@ -1067,11 +1054,11 @@ export type MessageConstructorParams = Omit { /** @@ -1130,8 +1118,8 @@ export interface SystemMessage extends BaseMessage<"system", SystemMessageOption /** * Encoded representation of system messages for serialization. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface SystemMessageEncoded extends BaseMessageEncoded<"system", SystemMessageOptions> { /** @@ -1144,16 +1132,16 @@ export interface SystemMessageEncoded extends BaseMessageEncoded<"system", Syste * Represents provider-specific options that can be associated with a * `SystemMessage` through module augmentation. * + * @category options * @since 4.0.0 - * @category ProviderOptions */ export interface SystemMessageOptions extends ProviderOptions {} /** * Schema for validation and encoding of system messages. * - * @since 4.0.0 * @category schemas + * @since 4.0.0 */ export const SystemMessage: Schema.Struct<{ readonly role: Schema.Literal<"system"> @@ -1174,8 +1162,8 @@ export const SystemMessage: Schema.Struct<{ /** * Constructs a new system message. * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const systemMessage = (params: MessageConstructorParams): SystemMessage => makeMessage("system", params) @@ -1187,7 +1175,8 @@ export const systemMessage = (params: MessageConstructorParams): /** * Message representing user input or questions. * - * @example + * **Example** (Creating user messages) + * * ```ts * import { Prompt } from "effect/unstable/ai" * @@ -1213,8 +1202,8 @@ export const systemMessage = (params: MessageConstructorParams): * }) * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface UserMessage extends BaseMessage<"user", UserMessageOptions> { /** @@ -1226,16 +1215,16 @@ export interface UserMessage extends BaseMessage<"user", UserMessageOptions> { /** * Union type of content parts allowed in user messages. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type UserMessagePart = TextPart | FilePart /** * Encoded representation of user messages for serialization. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface UserMessageEncoded extends BaseMessageEncoded<"user", UserMessageOptions> { /** @@ -1247,8 +1236,8 @@ export interface UserMessageEncoded extends BaseMessageEncoded<"user", UserMessa /** * Union type of encoded content parts for user messages. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type UserMessagePartEncoded = TextPartEncoded | FilePartEncoded @@ -1256,16 +1245,16 @@ export type UserMessagePartEncoded = TextPartEncoded | FilePartEncoded * Represents provider-specific options that can be associated with a * `UserMessage` through module augmentation. * + * @category options * @since 4.0.0 - * @category ProviderOptions */ export interface UserMessageOptions extends ProviderOptions {} /** * Schema for validation and encoding of user messages. * - * @since 4.0.0 * @category schemas + * @since 4.0.0 */ export const UserMessage: Schema.Struct<{ readonly role: Schema.Literal<"user"> @@ -1342,8 +1331,8 @@ export const UserMessage: Schema.Struct<{ /** * Constructs a new user message. * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const userMessage = (params: MessageConstructorParams): UserMessage => makeMessage("user", params) @@ -1354,7 +1343,8 @@ export const userMessage = (params: MessageConstructorParams): User /** * Message representing large language model assistant responses. * - * @example + * **Example** (Creating assistant messages) + * * ```ts * import { Prompt } from "effect/unstable/ai" * @@ -1364,7 +1354,7 @@ export const userMessage = (params: MessageConstructorParams): User * content: [ * Prompt.makePart("text", { * text: - * "The user is asking about the weather. I should use the weather tool." + * "I can check the current weather for San Francisco." * }), * Prompt.makePart("tool-call", { * id: "call_123", @@ -1389,8 +1379,8 @@ export const userMessage = (params: MessageConstructorParams): User * ) * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface AssistantMessage extends BaseMessage<"assistant", AssistantMessageOptions> { /** @@ -1402,8 +1392,8 @@ export interface AssistantMessage extends BaseMessage<"assistant", AssistantMess /** * Union type of content parts allowed in assistant messages. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type AssistantMessagePart = | TextPart @@ -1416,8 +1406,8 @@ export type AssistantMessagePart = /** * Encoded representation of assistant messages for serialization. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface AssistantMessageEncoded extends BaseMessageEncoded<"assistant", AssistantMessageOptions> { readonly content: string | ReadonlyArray @@ -1426,8 +1416,8 @@ export interface AssistantMessageEncoded extends BaseMessageEncoded<"assistant", /** * Union type of encoded content parts for assistant messages. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type AssistantMessagePartEncoded = | TextPartEncoded @@ -1441,16 +1431,22 @@ export type AssistantMessagePartEncoded = * Represents provider-specific options that can be associated with a * `AssistantMessage` through module augmentation. * + * @category options * @since 4.0.0 - * @category ProviderOptions */ export interface AssistantMessageOptions extends ProviderOptions {} /** * Schema for validation and encoding of assistant messages. * - * @since 4.0.0 + * **Details** + * + * Assistant content can be a string decoded through `ContentFromString` or an + * array of text, file, reasoning, tool-call, tool-result, and + * tool-approval-request parts. + * * @category schemas + * @since 4.0.0 */ export const AssistantMessage: Schema.Struct<{ readonly role: Schema.Literal<"assistant"> @@ -1516,8 +1512,16 @@ export const AssistantMessage: Schema.Struct<{ /** * Constructs a new assistant message. * - * @since 4.0.0 + * **When to use** + * + * Use to add assistant-role prompt history or model responses. + * + * **Details** + * + * This is the role-specific wrapper around `makeMessage("assistant", params)`. + * * @category constructors + * @since 4.0.0 */ export const assistantMessage = (params: MessageConstructorParams): AssistantMessage => makeMessage("assistant", params) @@ -1527,9 +1531,11 @@ export const assistantMessage = (params: MessageConstructorParams { /** @@ -1564,16 +1570,16 @@ export interface ToolMessage extends BaseMessage<"tool", ToolMessageOptions> { /** * Union type of content parts allowed in tool messages. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type ToolMessagePart = ToolResultPart | ToolApprovalResponsePart /** * Encoded representation of tool messages for serialization. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface ToolMessageEncoded extends BaseMessageEncoded<"tool", ToolMessageOptions> { /** @@ -1585,8 +1591,8 @@ export interface ToolMessageEncoded extends BaseMessageEncoded<"tool", ToolMessa /** * Union type of encoded content parts for tool messages. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type ToolMessagePartEncoded = ToolResultPartEncoded | ToolApprovalResponsePartEncoded @@ -1594,16 +1600,16 @@ export type ToolMessagePartEncoded = ToolResultPartEncoded | ToolApprovalRespons * Represents provider-specific options that can be associated with a * `ToolMessage` through module augmentation. * + * @category options * @since 4.0.0 - * @category ProviderOptions */ export interface ToolMessageOptions extends ProviderOptions {} /** * Schema for validation and encoding of tool messages. * - * @since 4.0.0 * @category schemas + * @since 4.0.0 */ export const ToolMessage: Schema.Struct<{ readonly role: Schema.Literal<"tool"> @@ -1626,8 +1632,8 @@ export const ToolMessage: Schema.Struct<{ /** * Constructs a new tool message. * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const toolMessage = (params: MessageConstructorParams): ToolMessage => makeMessage("tool", params) @@ -1638,8 +1644,8 @@ export const toolMessage = (params: MessageConstructorParams): Tool /** * A type representing all possible message types in a conversation. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type Message = | SystemMessage @@ -1650,8 +1656,8 @@ export type Message = /** * A type representing all possible encoded message types for serialization. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type MessageEncoded = | SystemMessageEncoded @@ -1662,8 +1668,8 @@ export type MessageEncoded = /** * Schema for validation and encoding of messages. * - * @since 4.0.0 * @category schemas + * @since 4.0.0 */ export const Message: Schema.Codec = Schema.Union([ SystemMessage, @@ -1681,8 +1687,8 @@ const TypeId = "~effect/unstable/ai/Prompt" as const /** * Type guard to check if a value is a Prompt. * - * @since 4.0.0 * @category guards + * @since 4.0.0 */ export const isPrompt = (u: unknown): u is Prompt => Predicate.hasProperty(u, TypeId) @@ -1690,8 +1696,8 @@ export const isPrompt = (u: unknown): u is Prompt => Predicate.hasProperty(u, Ty * A Prompt contains a sequence of messages that form the context of a * conversation with a large language model. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface Prompt extends Pipeable { readonly [TypeId]: typeof TypeId @@ -1704,8 +1710,8 @@ export interface Prompt extends Pipeable { /** * Encoded representation of prompts for serialization. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface PromptEncoded { /** @@ -1720,10 +1726,10 @@ const $Prompt = Schema.declare((u) => isPrompt(u), { identifier: "Prompt" }) // TODO: shoudn't the name be `PromptFrom...`? // TODO: is the explicit encoding necessary? maybe use the default JSON serializer? /** - * Describes a schema that represents a `Prompt` instance. + * Schema for AI prompt instances. * - * @since 4.0.0 * @category schemas + * @since 4.0.0 */ export const Prompt: Schema.Codec = Schema.Struct({ content: Schema.Array(Schema.toEncoded(Message)) @@ -1733,7 +1739,7 @@ export const Prompt: Schema.Codec = Schema.Struct({ SchemaTransformation.transformOrFail({ decode: (input) => Effect.mapBothEager( - Parser.decodeEffect(Schema.Array(Message))(input.content), + SchemaParser.decodeEffect(Schema.Array(Message))(input.content), { onSuccess: makePrompt, onFailure: () => @@ -1742,7 +1748,7 @@ export const Prompt: Schema.Codec = Schema.Struct({ ), encode: (prompt) => Effect.mapBothEager( - Parser.encodeEffect(Schema.Array(Message))(prompt.content), + SchemaParser.encodeEffect(Schema.Array(Message))(prompt.content), { onSuccess: (messages) => ({ content: messages }), onFailure: () => @@ -1754,12 +1760,11 @@ export const Prompt: Schema.Codec = Schema.Struct({ ) /** - * Raw input types that can be converted into a Prompt. + * Raw input accepted by `make`: a string, an iterable of encoded messages, or + * an existing `Prompt`. * - * Supports various input formats for convenience, including simple strings, - * message arrays, response parts, and existing prompts. + * **Example** (Accepting raw prompt input) * - * @example * ```ts * import type { Prompt } from "effect/unstable/ai" * @@ -1777,8 +1782,8 @@ export const Prompt: Schema.Codec = Schema.Struct({ * const promptInput: Prompt.RawInput = existingPrompt * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type RawInput = | string @@ -1802,7 +1807,8 @@ const decodeMessagesSync = Schema.decodeSync(Schema.Array(Message)) /** * An empty prompt with no messages. * - * @example + * **Example** (Creating an empty prompt) + * * ```ts * import { Prompt } from "effect/unstable/ai" * @@ -1810,18 +1816,21 @@ const decodeMessagesSync = Schema.decodeSync(Schema.Array(Message)) * console.log(emptyPrompt.content) // [] * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const empty: Prompt = makePrompt([]) /** - * Creates a Prompt from an input. + * Creates a `Prompt` from an input. + * + * **Details** * * This is the primary constructor for creating prompts, supporting multiple * input formats for convenience and flexibility. * - * @example + * **Example** (Creating prompts from inputs) + * * ```ts * import { Prompt } from "effect/unstable/ai" * @@ -1839,8 +1848,8 @@ export const empty: Prompt = makePrompt([]) * const copiedPrompt = Prompt.make(existingPrompt) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const make = (input: RawInput): Prompt => { if (typeof input === "string") { @@ -1861,7 +1870,8 @@ export const make = (input: RawInput): Prompt => { /** * Creates a Prompt from an array of messages. * - * @example + * **Example** (Creating prompts from messages) + * * ```ts * import { Prompt } from "effect/unstable/ai" * @@ -1877,19 +1887,19 @@ export const make = (input: RawInput): Prompt => { * const prompt = Prompt.fromMessages(messages) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fromMessages = (messages: ReadonlyArray): Prompt => makePrompt(messages) /** - * Creates a Prompt from the response parts of a previous interaction with a - * large language model. + * Creates a `Prompt` from response parts by folding completed text and + * reasoning streams into assistant parts, placing tool calls and approval + * requests in an assistant message, and placing non-preliminary tool results + * in a tool message using their encoded results. * - * Converts streaming or non-streaming AI response parts into a structured - * prompt, typically for use in conversation history or further processing. + * **Example** (Creating prompts from response parts) * - * @example * ```ts * import { Prompt, Response } from "effect/unstable/ai" * @@ -1918,8 +1928,8 @@ export const fromMessages = (messages: ReadonlyArray): Prompt => makePr * // Creates an assistant message with the response content * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fromResponseParts = (parts: ReadonlyArray): Prompt => { if (parts.length === 0) { @@ -2041,10 +2051,13 @@ export const fromResponseParts = (parts: ReadonlyArray): Promp /** * Concatenates a prompt with additional raw input by concatenating messages. * - * Creates a new prompt containing all messages from both the original prompt, - * and the provided raw input, maintaining the order of messages. + * **Details** + * + * The returned prompt contains all messages from the original prompt followed + * by the provided raw input, preserving message order. + * + * **Example** (Concatenating prompts) * - * @example * ```ts * import { Prompt } from "effect/unstable/ai" * @@ -2056,8 +2069,8 @@ export const fromResponseParts = (parts: ReadonlyArray): Promp * const merged = Prompt.concat(systemPrompt, "Hello, world!") * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const concat: { // ============================================================================= @@ -2067,10 +2080,13 @@ export const concat: { /** * Concatenates a prompt with additional raw input by concatenating messages. * - * Creates a new prompt containing all messages from both the original prompt, - * and the provided raw input, maintaining the order of messages. + * **Details** + * + * The returned prompt contains all messages from the original prompt followed + * by the provided raw input, preserving message order. + * + * **Example** (Concatenating prompts) * - * @example * ```ts * import { Prompt } from "effect/unstable/ai" * @@ -2082,8 +2098,8 @@ export const concat: { * const merged = Prompt.concat(systemPrompt, "Hello, world!") * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (input: RawInput): (self: Prompt) => Prompt // ============================================================================= @@ -2093,10 +2109,13 @@ export const concat: { /** * Concatenates a prompt with additional raw input by concatenating messages. * - * Creates a new prompt containing all messages from both the original prompt, - * and the provided raw input, maintaining the order of messages. + * **Details** + * + * The returned prompt contains all messages from the original prompt followed + * by the provided raw input, preserving message order. + * + * **Example** (Concatenating prompts) * - * @example * ```ts * import { Prompt } from "effect/unstable/ai" * @@ -2108,8 +2127,8 @@ export const concat: { * const merged = Prompt.concat(systemPrompt, "Hello, world!") * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Prompt, input: RawInput): Prompt } = dual(2, (self: Prompt, input: RawInput): Prompt => { @@ -2131,10 +2150,13 @@ export const concat: { * Creates a new prompt from the specified prompt with the system message set * to the specified text content. * - * **NOTE**: This method will remove and replace any previous system message - * from the prompt. + * **Gotchas** + * + * This method removes and replaces any previous system message from the + * prompt. + * + * **Example** (Replacing system instructions) * - * @example * ```ts * import { Prompt } from "effect/unstable/ai" * @@ -2153,8 +2175,8 @@ export const concat: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const setSystem: { // ============================================================================= @@ -2165,10 +2187,13 @@ export const setSystem: { * Creates a new prompt from the specified prompt with the system message set * to the specified text content. * - * **NOTE**: This method will remove and replace any previous system message - * from the prompt. + * **Gotchas** + * + * This method removes and replaces any previous system message from the + * prompt. + * + * **Example** (Replacing system instructions) * - * @example * ```ts * import { Prompt } from "effect/unstable/ai" * @@ -2187,8 +2212,8 @@ export const setSystem: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (content: string): (self: Prompt) => Prompt // ============================================================================= @@ -2199,10 +2224,13 @@ export const setSystem: { * Creates a new prompt from the specified prompt with the system message set * to the specified text content. * - * **NOTE**: This method will remove and replace any previous system message - * from the prompt. + * **Gotchas** + * + * This method removes and replaces any previous system message from the + * prompt. + * + * **Example** (Replacing system instructions) * - * @example * ```ts * import { Prompt } from "effect/unstable/ai" * @@ -2221,8 +2249,8 @@ export const setSystem: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Prompt, content: string): Prompt } = dual(2, (self: Prompt, content: string): Prompt => { @@ -2236,13 +2264,13 @@ export const setSystem: { }) /** - * Creates a new prompt from the specified prompt with the provided text content - * prepended to the start of existing system message content. + * Creates a new prompt with a leading system message. If the prompt already has + * a system message, the new message uses the provided content prepended to the + * first existing system message's content; the original messages remain after + * it. * - * If no system message exists in the specified prompt, the provided content - * will be used to create a system message. + * **Example** (Prepending system instructions) * - * @example * ```ts * import { Prompt } from "effect/unstable/ai" * @@ -2262,18 +2290,18 @@ export const setSystem: { * // result content: "You are a helpful assistant. You are an expert in programming." * ``` * - * @since 1.0.0 - * @category Combinators + * @category combinators + * @since 4.0.0 */ export const prependSystem: { /** - * Creates a new prompt from the specified prompt with the provided text content - * prepended to the start of existing system message content. + * Creates a new prompt with a leading system message. If the prompt already has + * a system message, the new message uses the provided content prepended to the + * first existing system message's content; the original messages remain after + * it. * - * If no system message exists in the specified prompt, the provided content - * will be used to create a system message. + * **Example** (Prepending system instructions) * - * @example * ```ts * import { Prompt } from "effect/unstable/ai" * @@ -2293,18 +2321,18 @@ export const prependSystem: { * // result content: "You are a helpful assistant. You are an expert in programming." * ``` * - * @since 1.0.0 - * @category Combinators + * @category combinators + * @since 4.0.0 */ (content: string): (self: Prompt) => Prompt /** - * Creates a new prompt from the specified prompt with the provided text content - * prepended to the start of existing system message content. + * Creates a new prompt with a leading system message. If the prompt already has + * a system message, the new message uses the provided content prepended to the + * first existing system message's content; the original messages remain after + * it. * - * If no system message exists in the specified prompt, the provided content - * will be used to create a system message. + * **Example** (Prepending system instructions) * - * @example * ```ts * import { Prompt } from "effect/unstable/ai" * @@ -2324,8 +2352,8 @@ export const prependSystem: { * // result content: "You are a helpful assistant. You are an expert in programming." * ``` * - * @since 1.0.0 - * @category Combinators + * @category combinators + * @since 4.0.0 */ (self: Prompt, content: string): Prompt } = dual(2, (self: Prompt, content: string): Prompt => { @@ -2345,13 +2373,13 @@ export const prependSystem: { }) /** - * Creates a new prompt from the specified prompt with the provided text content - * appended to the end of existing system message content. + * Creates a new prompt with a leading system message. If the prompt already has + * a system message, the new message uses the provided content appended to the + * first existing system message's content; the original messages remain after + * it. * - * If no system message exists in the specified prompt, the provided content - * will be used to create a system message. + * **Example** (Appending system instructions) * - * @example * ```ts * import { Prompt } from "effect/unstable/ai" * @@ -2371,18 +2399,18 @@ export const prependSystem: { * // result content: "You are an expert in programming. You are a helpful assistant." * ``` * - * @since 1.0.0 - * @category Combinators + * @category combinators + * @since 4.0.0 */ export const appendSystem: { /** - * Creates a new prompt from the specified prompt with the provided text content - * appended to the end of existing system message content. + * Creates a new prompt with a leading system message. If the prompt already has + * a system message, the new message uses the provided content appended to the + * first existing system message's content; the original messages remain after + * it. * - * If no system message exists in the specified prompt, the provided content - * will be used to create a system message. + * **Example** (Appending system instructions) * - * @example * ```ts * import { Prompt } from "effect/unstable/ai" * @@ -2402,18 +2430,18 @@ export const appendSystem: { * // result content: "You are an expert in programming. You are a helpful assistant." * ``` * - * @since 1.0.0 - * @category Combinators + * @category combinators + * @since 4.0.0 */ (content: string): (self: Prompt) => Prompt /** - * Creates a new prompt from the specified prompt with the provided text content - * appended to the end of existing system message content. + * Creates a new prompt with a leading system message. If the prompt already has + * a system message, the new message uses the provided content appended to the + * first existing system message's content; the original messages remain after + * it. * - * If no system message exists in the specified prompt, the provided content - * will be used to create a system message. + * **Example** (Appending system instructions) * - * @example * ```ts * import { Prompt } from "effect/unstable/ai" * @@ -2433,8 +2461,8 @@ export const appendSystem: { * // result content: "You are an expert in programming. You are a helpful assistant." * ``` * - * @since 1.0.0 - * @category Combinators + * @category combinators + * @since 4.0.0 */ (self: Prompt, content: string): Prompt } = dual(2, (self: Prompt, content: string): Prompt => { diff --git a/.opencode/node_modules/effect/src/unstable/ai/Response.ts b/.opencode/node_modules/effect/src/unstable/ai/Response.ts index a5d8c77b6f97e93c5a9d669d17794aba92e1fbae..058e922e627677e16faadf93aac743ae0e515eae 100644 --- a/.opencode/node_modules/effect/src/unstable/ai/Response.ts +++ b/.opencode/node_modules/effect/src/unstable/ai/Response.ts @@ -1,30 +1,14 @@ /** - * The `Response` module provides data structures to represent responses from - * large language models. + * Defines a shared data model for AI model output. * - * This module defines the complete structure of AI model responses, including - * various content parts for text, reasoning, tool calls, files, and metadata, - * supporting both streaming and non-streaming responses. + * Responses are represented as typed parts so different providers can expose + * text, reasoning, tool calls, files, sources, metadata, finish information, and + * errors through one shape. The same model is used for complete responses and + * streaming responses, where start, delta, and end parts describe content as it + * arrives. This module also carries provider metadata and schemas used by tools + * that need to validate response parts. * - * @example - * ```ts - * import { Response } from "effect/unstable/ai" - * - * // Create a simple text response part - * const textResponse = Response.makePart("text", { - * text: "The weather is sunny today!" - * }) - * - * // Create a tool call response part - * const toolCallResponse = Response.makePart("tool-call", { - * id: "call_123", - * name: "get_weather", - * params: { city: "San Francisco" }, - * providerExecuted: false - * }) - * ``` - * - * @since 1.0.0 + * @since 4.0.0 */ import type * as DateTime from "../../DateTime.ts" import * as Effect from "../../Effect.ts" @@ -44,16 +28,16 @@ const PartTypeId = "~effect/ai/Content/Part" as const /** * Type guard to check if a value is a Response Part. * - * @since 1.0.0 * @category guards + * @since 4.0.0 */ export const isPart = (u: unknown): u is AnyPart => Predicate.hasProperty(u, PartTypeId) /** * Union type representing all possible response content parts. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export type AnyPart = | TextPart @@ -80,8 +64,8 @@ export type AnyPart = /** * Encoded representation of all possible response content parts for serialization. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export type AnyPartEncoded = | TextPartEncoded @@ -108,8 +92,8 @@ export type AnyPartEncoded = /** * Union type for all response parts with tool-specific typing. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export type AllParts> = | TextPart @@ -136,8 +120,8 @@ export type AllParts> = /** * Encoded representation of all response parts for serialization. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export type AllPartsEncoded = | TextPartEncoded @@ -164,10 +148,13 @@ export type AllPartsEncoded = /** * Creates a Schema for all response parts based on a toolkit. * + * **Details** + * * Generates a schema that includes all possible response parts, with tool call * and tool result parts dynamically created based on the provided toolkit. * - * @example + * **Example** (Building a response parts schema) + * * ```ts * import { Schema } from "effect" * import { Response, Tool, Toolkit } from "effect/unstable/ai" @@ -182,8 +169,8 @@ export type AllPartsEncoded = * const allPartsSchema = Response.AllParts(myToolkit) * ``` * - * @since 1.0.0 * @category schemas + * @since 4.0.0 */ export const AllParts = >( toolkit: T @@ -233,8 +220,8 @@ export const AllParts = >( * A type for representing non-streaming response parts with tool-specific * typing. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export type Part> = | TextPart @@ -251,8 +238,8 @@ export type Part> = /** * Encoded representation of non-streaming response parts for serialization. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export type PartEncoded = | TextPartEncoded @@ -271,8 +258,8 @@ export type PartEncoded = /** * Creates a Schema for non-streaming response parts based on a toolkit. * - * @since 1.0.0 * @category schemas + * @since 4.0.0 */ export const Part = >( toolkit: T @@ -311,8 +298,8 @@ export const Part = >( /** * A type for representing streaming response parts with tool-specific typing. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export type StreamPart> = | TextStartPart @@ -337,8 +324,8 @@ export type StreamPart> = /** * Encoded representation of streaming response parts for serialization. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export type StreamPartEncoded = | TextStartPartEncoded @@ -363,8 +350,8 @@ export type StreamPartEncoded = /** * Creates a Schema for streaming response parts based on a toolkit. * - * @since 1.0.0 * @category schemas + * @since 4.0.0 */ export const StreamPart = >( toolkit: T @@ -411,8 +398,8 @@ export const StreamPart = >( /** * Utility type that extracts tool call parts from a set of tools. * - * @since 1.0.0 * @category utility types + * @since 4.0.0 */ export type ToolCallParts> = { [Name in keyof Tools]: Name extends string ? ToolCallPart> @@ -422,8 +409,8 @@ export type ToolCallParts> = { /** * Utility type that extracts tool result parts from a set of tools. * - * @since 1.0.0 * @category utility types + * @since 4.0.0 */ export type ToolResultParts> = { [Name in keyof Tools]: Name extends string @@ -436,20 +423,11 @@ export type ToolResultParts> = { // ============================================================================= /** - * Schema for provider-specific metadata which can be attached to response parts. - * - * Provider-specific metadata is namespaced by provider and has the structure: - * - * ``` - * { - * "": { - * // Provider-specific metadata - * } - * } - * ``` + * Schema for provider-specific metadata attached to response parts, + * represented as a record from provider-specific keys to JSON values or `null`. * - * @since 1.0.0 * @category schemas + * @since 4.0.0 */ export const ProviderMetadata: Schema.$Record< Schema.String, @@ -457,18 +435,20 @@ export const ProviderMetadata: Schema.$Record< > = Schema.Record(Schema.String, Schema.NullOr(Schema.Json)) /** - * @since 1.0.0 + * Type of provider-specific metadata attached to response parts, keyed by + * provider-specific names with JSON or `null` values. + * * @category models + * @since 4.0.0 */ export type ProviderMetadata = typeof ProviderMetadata.Type /** - * Base interface for all response content parts. - * - * Provides common structure including type identifier and optional metadata. + * Base interface for all response content parts, including the type identifier + * and optional metadata. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface BasePart { readonly [PartTypeId]: typeof PartTypeId @@ -485,8 +465,8 @@ export interface BasePart { /** @@ -511,7 +491,8 @@ const BasePart = Schema.Struct({ /** * Creates a new response content part of the specified type. * - * @example + * **Example** (Creating response content parts) + * * ```ts * import { Response } from "effect/unstable/ai" * @@ -527,8 +508,8 @@ const BasePart = Schema.Struct({ * }) * ``` * - * @since 1.0.0 * @category constructors + * @since 4.0.0 */ export const makePart = ( /** @@ -544,20 +525,19 @@ export const makePart = ( */ readonly metadata?: Extract["metadata"] | undefined } -): Extract => - (({ - ...params, - [PartTypeId]: PartTypeId, - type, - metadata: params.metadata ?? {} - }) as any) +): Extract => (({ + ...params, + [PartTypeId]: PartTypeId, + type, + metadata: params.metadata ?? {} +}) as any) /** * A utility type for specifying the parameters required to construct a * specific response part. * - * @since 1.0.0 * @category utility types + * @since 4.0.0 */ export type ConstructorParams = & Omit @@ -575,7 +555,8 @@ export type ConstructorParams = /** * Response part representing plain text content. * - * @example + * **Example** (Creating a text part) + * * ```ts * import { Response } from "effect/unstable/ai" * @@ -584,8 +565,8 @@ export type ConstructorParams = * }) * ``` * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface TextPart extends BasePart<"text", TextPartMetadata> { /** @@ -597,8 +578,8 @@ export interface TextPart extends BasePart<"text", TextPartMetadata> { /** * Encoded representation of text parts for serialization. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface TextPartEncoded extends BasePartEncoded<"text", TextPartMetadata> { /** @@ -611,16 +592,16 @@ export interface TextPartEncoded extends BasePartEncoded<"text", TextPartMetadat * Represents provider-specific metadata that can be associated with a * `TextPart` through module augmentation. * - * @since 1.0.0 - * @category provider options + * @category configuration + * @since 4.0.0 */ export interface TextPartMetadata extends ProviderMetadata {} /** * Schema for validation and encoding of text parts. * - * @since 1.0.0 * @category schemas + * @since 4.0.0 */ export const TextPart: Schema.Struct<{ readonly type: Schema.tag<"text"> @@ -640,12 +621,11 @@ export const TextPart: Schema.Struct<{ // ============================================================================= /** - * Response part indicating the start of streaming text content. + * Response part indicating the start of streaming text content with a unique + * text chunk identifier. * - * Marks the beginning of a text chunk with a unique identifier. - * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface TextStartPart extends BasePart<"text-start", TextStartPartMetadata> { /** @@ -657,8 +637,8 @@ export interface TextStartPart extends BasePart<"text-start", TextStartPartMetad /** * Encoded representation of text start parts for serialization. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface TextStartPartEncoded extends BasePartEncoded<"text-start", TextStartPartMetadata> { /** @@ -671,16 +651,16 @@ export interface TextStartPartEncoded extends BasePartEncoded<"text-start", Text * Represents provider-specific metadata that can be associated with a * `TextStartPart` through module augmentation. * - * @since 1.0.0 - * @category provider options + * @category configuration + * @since 4.0.0 */ export interface TextStartPartMetadata extends ProviderMetadata {} /** * Schema for validation and encoding of text start parts. * - * @since 1.0.0 * @category schemas + * @since 4.0.0 */ export const TextStartPart: Schema.Struct<{ readonly type: Schema.tag<"text-start"> @@ -703,8 +683,8 @@ export const TextStartPart: Schema.Struct<{ * Response part containing incremental text content to be added to the existing * text chunk with the same unique identifier. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface TextDeltaPart extends BasePart<"text-delta", TextDeltaPartMetadata> { /** @@ -720,8 +700,8 @@ export interface TextDeltaPart extends BasePart<"text-delta", TextDeltaPartMetad /** * Encoded representation of text delta parts for serialization. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface TextDeltaPartEncoded extends BasePartEncoded<"text-delta", TextDeltaPartMetadata> { /** @@ -738,16 +718,16 @@ export interface TextDeltaPartEncoded extends BasePartEncoded<"text-delta", Text * Represents provider-specific metadata that can be associated with a * `TextDeltaPart` through module augmentation. * - * @since 1.0.0 - * @category provider options + * @category configuration + * @since 4.0.0 */ export interface TextDeltaPartMetadata extends ProviderMetadata {} /** * Schema for validation and encoding of text delta parts. * - * @since 1.0.0 * @category schemas + * @since 4.0.0 */ export const TextDeltaPart: Schema.Struct<{ readonly type: Schema.tag<"text-delta"> @@ -769,12 +749,10 @@ export const TextDeltaPart: Schema.Struct<{ // ============================================================================= /** - * Response part indicating the end of streaming text content. - * - * Marks the completion of a text chunk. + * Response part indicating the completion of a streaming text chunk. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface TextEndPart extends BasePart<"text-end", TextEndPartMetadata> { /** @@ -786,8 +764,8 @@ export interface TextEndPart extends BasePart<"text-end", TextEndPartMetadata> { /** * Encoded representation of text end parts for serialization. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface TextEndPartEncoded extends BasePartEncoded<"text-end", TextEndPartMetadata> { /** @@ -800,16 +778,16 @@ export interface TextEndPartEncoded extends BasePartEncoded<"text-end", TextEndP * Represents provider-specific metadata that can be associated with a * `TextEndPart` through module augmentation. * - * @since 1.0.0 - * @category provider options + * @category configuration + * @since 4.0.0 */ export interface TextEndPartMetadata extends ProviderMetadata {} /** * Schema for validation and encoding of text end parts. * - * @since 1.0.0 * @category schemas + * @since 4.0.0 */ export const TextEndPart: Schema.Struct<{ readonly type: Schema.tag<"text-end"> @@ -829,12 +807,12 @@ export const TextEndPart: Schema.Struct<{ // ============================================================================= /** - * Response part representing reasoning or chain-of-thought content. + * Response part carrying provider-supplied reasoning text, such as an exposed + * reasoning summary or explanation. Do not assume it contains hidden + * chain-of-thought. * - * Contains the internal reasoning process or explanation from the large - * language model. + * **Example** (Creating a reasoning part) * - * @example * ```ts * import { Response } from "effect/unstable/ai" * @@ -844,8 +822,8 @@ export const TextEndPart: Schema.Struct<{ * }) * ``` * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface ReasoningPart extends BasePart<"reasoning", ReasoningPartMetadata> { /** @@ -857,8 +835,8 @@ export interface ReasoningPart extends BasePart<"reasoning", ReasoningPartMetada /** * Encoded representation of reasoning parts for serialization. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface ReasoningPartEncoded extends BasePartEncoded<"reasoning", ReasoningPartMetadata> { /** @@ -871,16 +849,16 @@ export interface ReasoningPartEncoded extends BasePartEncoded<"reasoning", Reaso * Represents provider-specific metadata that can be associated with a * `ReasoningPart` through module augmentation. * - * @since 1.0.0 - * @category provider options + * @category configuration + * @since 4.0.0 */ export interface ReasoningPartMetadata extends ProviderMetadata {} /** * Schema for validation and encoding of reasoning parts. * - * @since 1.0.0 * @category schemas + * @since 4.0.0 */ export const ReasoningPart: Schema.Struct<{ readonly type: Schema.tag<"reasoning"> @@ -900,12 +878,11 @@ export const ReasoningPart: Schema.Struct<{ // ============================================================================= /** - * Response part indicating the start of streaming reasoning content. + * Response part indicating the start of streaming reasoning content with a + * unique reasoning chunk identifier. * - * Marks the beginning of a reasoning chunk with a unique identifier. - * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface ReasoningStartPart extends BasePart<"reasoning-start", ReasoningStartPartMetadata> { /** @@ -917,8 +894,8 @@ export interface ReasoningStartPart extends BasePart<"reasoning-start", Reasonin /** * Encoded representation of reasoning start parts for serialization. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface ReasoningStartPartEncoded extends BasePartEncoded<"reasoning-start", ReasoningStartPartMetadata> { /** @@ -931,16 +908,16 @@ export interface ReasoningStartPartEncoded extends BasePartEncoded<"reasoning-st * Represents provider-specific metadata that can be associated with a * `ReasoningStartPart` through module augmentation. * - * @since 1.0.0 - * @category provider options + * @category configuration + * @since 4.0.0 */ export interface ReasoningStartPartMetadata extends ProviderMetadata {} /** * Schema for validation and encoding of reasoning start parts. * - * @since 1.0.0 * @category schemas + * @since 4.0.0 */ export const ReasoningStartPart: Schema.Struct<{ readonly type: Schema.tag<"reasoning-start"> @@ -963,8 +940,8 @@ export const ReasoningStartPart: Schema.Struct<{ * Response part containing incremental reasoning content to be added to the * existing chunk of reasoning text with the same unique identifier. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface ReasoningDeltaPart extends BasePart<"reasoning-delta", ReasoningDeltaPartMetadata> { /** @@ -980,8 +957,8 @@ export interface ReasoningDeltaPart extends BasePart<"reasoning-delta", Reasonin /** * Encoded representation of reasoning delta parts for serialization. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface ReasoningDeltaPartEncoded extends BasePartEncoded<"reasoning-delta", ReasoningDeltaPartMetadata> { /** @@ -998,16 +975,16 @@ export interface ReasoningDeltaPartEncoded extends BasePartEncoded<"reasoning-de * Represents provider-specific metadata that can be associated with a * `ReasoningDeltaPart` through module augmentation. * - * @since 1.0.0 - * @category provider options + * @category configuration + * @since 4.0.0 */ export interface ReasoningDeltaPartMetadata extends ProviderMetadata {} /** * Schema for validation and encoding of reasoning delta parts. * - * @since 1.0.0 * @category schemas + * @since 4.0.0 */ export const ReasoningDeltaPart: Schema.Struct<{ readonly type: Schema.tag<"reasoning-delta"> @@ -1029,12 +1006,10 @@ export const ReasoningDeltaPart: Schema.Struct<{ // ============================================================================= /** - * Response part indicating the end of streaming reasoning content. - * - * Marks the completion of a chunk of reasoning content. + * Response part indicating the completion of a streaming reasoning chunk. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface ReasoningEndPart extends BasePart<"reasoning-end", ReasoningEndPartMetadata> { /** @@ -1046,8 +1021,8 @@ export interface ReasoningEndPart extends BasePart<"reasoning-end", ReasoningEnd /** * Encoded representation of reasoning end parts for serialization. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface ReasoningEndPartEncoded extends BasePartEncoded<"reasoning-end", ReasoningEndPartMetadata> { /** @@ -1060,16 +1035,16 @@ export interface ReasoningEndPartEncoded extends BasePartEncoded<"reasoning-end" * Represents provider-specific metadata that can be associated with a * `ReasoningEndPart` through module augmentation. * - * @since 1.0.0 - * @category provider options + * @category configuration + * @since 4.0.0 */ export interface ReasoningEndPartMetadata extends ProviderMetadata {} /** * Schema for validation and encoding of reasoning end parts. * - * @since 1.0.0 * @category schemas + * @since 4.0.0 */ export const ReasoningEndPart: Schema.Struct<{ readonly type: Schema.tag<"reasoning-end"> @@ -1091,11 +1066,13 @@ export const ReasoningEndPart: Schema.Struct<{ /** * Response part indicating the start of streaming tool parameters. * + * **Details** + * * Marks the beginning of tool parameter streaming with metadata about the tool * call. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface ToolParamsStartPart extends BasePart<"tool-params-start", ToolParamsStartPartMetadata> { /** @@ -1116,8 +1093,8 @@ export interface ToolParamsStartPart extends BasePart<"tool-params-start", ToolP /** * Encoded representation of tool params start parts for serialization. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface ToolParamsStartPartEncoded extends BasePartEncoded<"tool-params-start", ToolParamsStartPartMetadata> { /** @@ -1139,16 +1116,16 @@ export interface ToolParamsStartPartEncoded extends BasePartEncoded<"tool-params * Represents provider-specific metadata that can be associated with a * `ToolParamsStartPart` through module augmentation. * - * @since 1.0.0 - * @category provider options + * @category configuration + * @since 4.0.0 */ export interface ToolParamsStartPartMetadata extends ProviderMetadata {} /** * Schema for validation and encoding of tool params start parts. * - * @since 1.0.0 * @category schemas + * @since 4.0.0 */ export const ToolParamsStartPart: Schema.Struct<{ readonly type: Schema.tag<"tool-params-start"> @@ -1177,11 +1154,13 @@ export const ToolParamsStartPart: Schema.Struct<{ /** * Response part containing incremental tool parameter content. * + * **Details** + * * Represents a chunk of tool parameters being streamed, containing the * incremental JSON content that forms the tool parameters. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface ToolParamsDeltaPart extends BasePart<"tool-params-delta", ToolParamsDeltaPartMetadata> { /** @@ -1197,8 +1176,8 @@ export interface ToolParamsDeltaPart extends BasePart<"tool-params-delta", ToolP /** * Encoded representation of tool params delta parts for serialization. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface ToolParamsDeltaPartEncoded extends BasePartEncoded<"tool-params-delta", ToolParamsDeltaPartMetadata> { /** @@ -1215,16 +1194,16 @@ export interface ToolParamsDeltaPartEncoded extends BasePartEncoded<"tool-params * Represents provider-specific metadata that can be associated with a * `ToolParamsDeltaPart` through module augmentation. * - * @since 1.0.0 - * @category provider options + * @category configuration + * @since 4.0.0 */ export interface ToolParamsDeltaPartMetadata extends ProviderMetadata {} /** * Schema for validation and encoding of tool params delta parts. * - * @since 1.0.0 * @category schemas + * @since 4.0.0 */ export const ToolParamsDeltaPart: Schema.Struct<{ readonly type: Schema.tag<"tool-params-delta"> @@ -1251,11 +1230,13 @@ export const ToolParamsDeltaPart: Schema.Struct<{ /** * Response part indicating the end of streaming tool parameters. * + * **Details** + * * Marks the completion of a tool parameter stream, indicating that all * parameter data has been sent and the tool call is ready to be executed. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface ToolParamsEndPart extends BasePart<"tool-params-end", ToolParamsEndPartMetadata> { /** @@ -1267,8 +1248,8 @@ export interface ToolParamsEndPart extends BasePart<"tool-params-end", ToolParam /** * Encoded representation of tool params end parts for serialization. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface ToolParamsEndPartEncoded extends BasePartEncoded<"tool-params-end", ToolParamsEndPartMetadata> { /** @@ -1281,16 +1262,16 @@ export interface ToolParamsEndPartEncoded extends BasePartEncoded<"tool-params-e * Represents provider-specific metadata that can be associated with a * `ToolParamsEndPart` through module augmentation. * - * @since 1.0.0 - * @category provider options + * @category configuration + * @since 4.0.0 */ export interface ToolParamsEndPartMetadata extends ProviderMetadata {} /** * Schema for validation and encoding of tool params end parts. * - * @since 1.0.0 * @category schemas + * @since 4.0.0 */ export const ToolParamsEndPart: Schema.Struct<{ readonly type: Schema.tag<"tool-params-end"> @@ -1312,7 +1293,8 @@ export const ToolParamsEndPart: Schema.Struct<{ /** * Response part representing a tool call request. * - * @example + * **Example** (Creating a tool call part) + * * ```ts * import { Schema } from "effect" * import { Response } from "effect/unstable/ai" @@ -1336,8 +1318,8 @@ export const ToolParamsEndPart: Schema.Struct<{ * }) * ``` * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface ToolCallPart extends BasePart<"tool-call", ToolCallPartMetadata> { /** @@ -1362,8 +1344,8 @@ export interface ToolCallPart extends BasePart<"too /** * Encoded representation of tool call parts for serialization. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface ToolCallPartEncoded extends BasePartEncoded<"tool-call", ToolCallPartMetadata> { /** @@ -1389,16 +1371,16 @@ export interface ToolCallPartEncoded extends BasePartEncoded<"tool-call", ToolCa * Represents provider-specific metadata that can be associated with a * `ToolCallPart` through module augmentation. * - * @since 1.0.0 - * @category provider options + * @category configuration + * @since 4.0.0 */ export interface ToolCallPartMetadata extends ProviderMetadata {} /** * Creates a Schema for tool call parts with specific tool name and parameters. * - * @since 1.0.0 * @category schemas + * @since 4.0.0 */ export const ToolCallPart: ( name: Name, @@ -1431,8 +1413,8 @@ export const ToolCallPart: ( params: ConstructorParams> @@ -1445,8 +1427,8 @@ export const toolCallPart = ( /** * The base fields of a tool result part. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface BaseToolResult extends BasePart<"tool-result", ToolResultPartMetadata> { /** @@ -1469,10 +1451,14 @@ export interface BaseToolResult extends BasePart<"tool-resu /** * Whether this is a preliminary (intermediate) result. * + * **Details** + * * Preliminary results represent progress updates during streaming tool * execution. Only the final result (where `preliminary` is `false` or * `undefined`) should be used as the authoritative output. * + * **Gotchas** + * * Only applicable for framework-executed tools during streaming. */ readonly preliminary: boolean @@ -1481,8 +1467,8 @@ export interface BaseToolResult extends BasePart<"tool-resu /** * Represents a successful tool call result. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface ToolResultSuccess extends BaseToolResult { /** @@ -1498,8 +1484,8 @@ export interface ToolResultSuccess extends BaseToo /** * Represents a failed tool call result. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface ToolResultFailure extends BaseToolResult { /** @@ -1515,7 +1501,8 @@ export interface ToolResultFailure extends BaseToo /** * Response part representing the result of a tool call. * - * @example + * **Example** (Creating a tool result part) + * * ```ts * import { Response } from "effect/unstable/ai" * @@ -1548,8 +1535,8 @@ export interface ToolResultFailure extends BaseToo * }) * ``` * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export type ToolResultPart = | ToolResultSuccess @@ -1558,8 +1545,8 @@ export type ToolResultPart = /** * Encoded representation of tool result parts for serialization. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface ToolResultPartEncoded extends BasePartEncoded<"tool-result", ToolResultPartMetadata> { /** @@ -1586,6 +1573,8 @@ export interface ToolResultPartEncoded extends BasePartEncoded<"tool-result", To /** * Whether this is a preliminary (intermediate) result. * + * **Gotchas** + * * Only applicable for framework-executed tools during streaming. */ readonly preliminary?: boolean | undefined @@ -1595,16 +1584,16 @@ export interface ToolResultPartEncoded extends BasePartEncoded<"tool-result", To * Represents provider-specific metadata that can be associated with a * `ToolResultPart` through module augmentation. * - * @since 1.0.0 - * @category provider options + * @category configuration + * @since 4.0.0 */ export interface ToolResultPartMetadata extends ProviderMetadata {} /** * Creates a Schema for tool result parts with specific tool name and result type. * - * @since 1.0.0 * @category schemas + * @since 4.0.0 */ export const ToolResultPart: ( name: Name, @@ -1698,8 +1687,8 @@ export const ToolResultPart: >>( params: Params @@ -1722,11 +1711,14 @@ export const toolResultPart = { /** @@ -1756,8 +1748,8 @@ export interface ToolApprovalRequestPart extends BasePart<"tool-approval-request /** * Encoded representation of tool approval request parts for serialization. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface ToolApprovalRequestPartEncoded extends BasePartEncoded<"tool-approval-request", ToolApprovalRequestPartMetadata> @@ -1776,16 +1768,16 @@ export interface ToolApprovalRequestPartEncoded * Represents provider-specific metadata that can be associated with a * `ToolApprovalRequestPart` through module augmentation. * - * @since 1.0.0 - * @category provider options + * @category configuration + * @since 4.0.0 */ export interface ToolApprovalRequestPartMetadata extends ProviderMetadata {} /** * Schema for validation and encoding of tool approval request parts. * - * @since 1.0.0 * @category schemas + * @since 4.0.0 */ export const ToolApprovalRequestPart: Schema.Struct<{ readonly type: Schema.tag<"tool-approval-request"> @@ -1808,8 +1800,8 @@ export const ToolApprovalRequestPart: Schema.Struct<{ /** * Constructs a new tool approval request part. * - * @since 1.0.0 * @category constructors + * @since 4.0.0 */ export const toolApprovalRequestPart = ( params: ConstructorParams @@ -1822,9 +1814,12 @@ export const toolApprovalRequestPart = ( /** * Response part representing a file attachment. * + * **Details** + * * Supports various file types including images, documents, and binary data. * - * @example + * **Example** (Creating a file part) + * * ```ts * import { Response } from "effect/unstable/ai" * @@ -1834,8 +1829,8 @@ export const toolApprovalRequestPart = ( * }) * ``` * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface FilePart extends BasePart<"file", FilePartMetadata> { /** @@ -1851,8 +1846,8 @@ export interface FilePart extends BasePart<"file", FilePartMetadata> { /** * Encoded representation of file parts for serialization. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface FilePartEncoded extends BasePartEncoded<"file", FilePartMetadata> { /** @@ -1869,16 +1864,21 @@ export interface FilePartEncoded extends BasePartEncoded<"file", FilePartMetadat * Represents provider-specific metadata that can be associated with a * `FilePart` through module augmentation. * - * @since 1.0.0 - * @category provider options + * @category configuration + * @since 4.0.0 */ export interface FilePartMetadata extends ProviderMetadata {} /** * Schema for validation and encoding of file parts. * - * @since 1.0.0 + * **Details** + * + * Decoded `data` is a `Uint8Array`; encoded `data` is a base64 string through + * `Schema.Uint8ArrayFromBase64`. + * * @category schemas + * @since 4.0.0 */ export const FilePart: Schema.Struct<{ readonly type: Schema.tag<"file"> @@ -1900,12 +1900,11 @@ export const FilePart: Schema.Struct<{ // ============================================================================= /** - * Response part representing a document source reference. - * - * Used to reference documents that were used in generating the response. + * Response part representing a document source reference used in generating the + * response. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface DocumentSourcePart extends BasePart<"source", DocumentSourcePartMetadata> { /** @@ -1933,8 +1932,8 @@ export interface DocumentSourcePart extends BasePart<"source", DocumentSourcePar /** * Encoded representation of document source parts for serialization. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface DocumentSourcePartEncoded extends BasePartEncoded<"source", DocumentSourcePartMetadata> { /** @@ -1963,16 +1962,30 @@ export interface DocumentSourcePartEncoded extends BasePartEncoded<"source", Doc * Represents provider-specific metadata that can be associated with a * `DocumentSourcePart` through module augmentation. * - * @since 1.0.0 - * @category provider options + * @category configuration + * @since 4.0.0 */ export interface DocumentSourcePartMetadata extends ProviderMetadata {} /** * Schema for validation and encoding of document source parts. * - * @since 1.0.0 + * **When to use** + * + * Use to validate or encode document source references returned as response + * content parts. + * + * **Details** + * + * Validates `type: "source"`, `sourceType: "document"`, required `id`, + * `mediaType`, and `title`, optional `fileName`, and the metadata fields + * inherited from response parts. + * + * @see {@link UrlSourcePart} for URL source references + * @see {@link DocumentSourcePartEncoded} for the encoded document source representation + * * @category schemas + * @since 4.0.0 */ export const DocumentSourcePart: Schema.Struct<{ readonly type: Schema.tag<"source"> @@ -2000,12 +2013,11 @@ export const DocumentSourcePart: Schema.Struct<{ // ============================================================================= /** - * Response part representing a URL source reference. - * - * Used to reference web URLs that were used in generating the response. + * Response part representing a URL source reference used in generating the + * response. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface UrlSourcePart extends BasePart<"source", UrlSourcePartMetadata> { /** @@ -2029,8 +2041,8 @@ export interface UrlSourcePart extends BasePart<"source", UrlSourcePartMetadata> /** * Encoded representation of URL source parts for serialization. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface UrlSourcePartEncoded extends BasePartEncoded<"source", UrlSourcePartMetadata> { /** @@ -2055,16 +2067,16 @@ export interface UrlSourcePartEncoded extends BasePartEncoded<"source", UrlSourc * Represents provider-specific metadata that can be associated with a * `UrlSourcePart` through module augmentation. * - * @since 1.0.0 - * @category provider options + * @category configuration + * @since 4.0.0 */ export interface UrlSourcePartMetadata extends ProviderMetadata {} /** * Schema for validation and encoding of url source parts. * - * @since 1.0.0 * @category schemas + * @since 4.0.0 */ export const UrlSourcePart: Schema.Struct<{ readonly type: Schema.tag<"source"> @@ -2092,11 +2104,14 @@ export const UrlSourcePart: Schema.Struct<{ /** * Schema for HTTP request details associated with an AI response. * + * **Details** + * * Captures comprehensive information about the HTTP request made to the * AI provider, enabling inspection of request metadata for debugging and * observability purposes. * - * @example + * **Example** (Describing an HTTP request) + * * ```ts * import type { Response } from "effect/unstable/ai" * @@ -2109,8 +2124,8 @@ export const UrlSourcePart: Schema.Struct<{ * } * ``` * - * @since 1.0.0 * @category schemas + * @since 4.0.0 */ export const HttpRequestDetails = Schema.Struct({ method: Schema.Literals(["GET", "POST", "PATCH", "PUT", "DELETE", "HEAD", "OPTIONS", "TRACE"]), @@ -2129,11 +2144,14 @@ export const HttpRequestDetails = Schema.Struct({ /** * Schema for HTTP response details associated with an AI response. * + * **Details** + * * Captures essential information about the HTTP response received from * the AI provider, including status codes and headers for debugging and * observability purposes. * - * @example + * **Example** (Describing an HTTP response) + * * ```ts * import type { Response } from "effect/unstable/ai" * @@ -2146,8 +2164,8 @@ export const HttpRequestDetails = Schema.Struct({ * } * ``` * - * @since 1.0.0 * @category schemas + * @since 4.0.0 */ export const HttpResponseDetails = Schema.Struct({ status: Schema.Number, @@ -2167,7 +2185,8 @@ export const HttpResponseDetails = Schema.Struct({ /** * Response part containing metadata about the large language model response. * - * @example + * **Example** (Creating a metadata part) + * * ```ts * import { DateTime } from "effect" * import { Response } from "effect/unstable/ai" @@ -2183,8 +2202,8 @@ export const HttpResponseDetails = Schema.Struct({ * ) * ``` * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface ResponseMetadataPart extends BasePart<"response-metadata", ResponseMetadataPartMetadata> { /** @@ -2208,8 +2227,8 @@ export interface ResponseMetadataPart extends BasePart<"response-metadata", Resp /** * Encoded representation of response metadata parts for serialization. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface ResponseMetadataPartEncoded extends BasePartEncoded<"response-metadata", ResponseMetadataPartMetadata> @@ -2236,16 +2255,16 @@ export interface ResponseMetadataPartEncoded * Represents provider-specific metadata that can be associated with a * `ResponseMetadataPart` through module augmentation. * - * @since 1.0.0 - * @category provider options + * @category configuration + * @since 4.0.0 */ export interface ResponseMetadataPartMetadata extends ProviderMetadata {} /** * Schema for validation and encoding of response metadata parts. * - * @since 1.0.0 * @category schemas + * @since 4.0.0 */ export const ResponseMetadataPart: Schema.Struct<{ readonly type: Schema.tag<"response-metadata"> @@ -2276,6 +2295,8 @@ export const ResponseMetadataPart: Schema.Struct<{ /** * Represents the reason why a model finished generation of a response. * + * **Details** + * * Possible finish reasons: * - `"stop"`: The model generated a stop sequence. * - `"length"`: The model exceeded its token budget. @@ -2286,8 +2307,8 @@ export const ResponseMetadataPart: Schema.Struct<{ * - `"other"`: The model stopped for a reason not supported by this protocol. * - `"unknown"`: The model did not specify a finish reason. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export const FinishReason: Schema.Literals<[ "stop", @@ -2310,20 +2331,30 @@ export const FinishReason: Schema.Literals<[ ]) /** - * @since 1.0.0 + * Type of the reason why a model stopped generating a response. + * + * **Details** + * + * Values include normal stops, token-limit stops, content filtering, + * tool-call pauses, provider errors, and unknown provider-specific finish + * reasons. + * * @category models + * @since 4.0.0 */ export type FinishReason = typeof FinishReason.Type /** * Represents usage information for a request to a large language model provider. * + * **Details** + * * If the model provider returns additional usage information than what is * specified here, you can generally find that information under the provider * metadata of the finish part of the response. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export class Usage extends Schema.Class("effect/ai/AiResponse/Usage")({ /** @@ -2369,7 +2400,8 @@ export class Usage extends Schema.Class("effect/ai/AiResponse/Usage")({ /** * Response part indicating the completion of a response generation. * - * @example + * **Example** (Creating a finish part) + * * ```ts * import { Response } from "effect/unstable/ai" * @@ -2392,8 +2424,8 @@ export class Usage extends Schema.Class("effect/ai/AiResponse/Usage")({ * }) * ``` * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface FinishPart extends BasePart<"finish", FinishPartMetadata> { /** @@ -2413,8 +2445,8 @@ export interface FinishPart extends BasePart<"finish", FinishPartMetadata> { /** * Encoded representation of finish parts for serialization. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface FinishPartEncoded extends BasePartEncoded<"finish", FinishPartMetadata> { /** @@ -2435,16 +2467,21 @@ export interface FinishPartEncoded extends BasePartEncoded<"finish", FinishPartM * Represents provider-specific metadata that can be associated with a * `FinishPart` through module augmentation. * - * @since 1.0.0 - * @category provider options + * @category configuration + * @since 4.0.0 */ export interface FinishPartMetadata extends ProviderMetadata {} /** - * Schema for validation and encoding of finish parts. + * Schema for finish response parts. + * + * **Details** + * + * Validates `type: "finish"`, `reason` through `FinishReason`, `usage` + * through `Usage`, and optional provider HTTP response details. * - * @since 1.0.0 * @category schemas + * @since 4.0.0 */ export const FinishPart: Schema.Struct<{ readonly type: Schema.tag<"finish"> @@ -2479,7 +2516,8 @@ export const FinishPart: Schema.Struct<{ /** * Response part indicating that an error occurred generating the response. * - * @example + * **Example** (Creating an error part) + * * ```ts * import { Response } from "effect/unstable/ai" * @@ -2488,8 +2526,8 @@ export const FinishPart: Schema.Struct<{ * }) * ``` * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface ErrorPart extends BasePart<"error", ErrorPartMetadata> { readonly error: unknown @@ -2498,8 +2536,8 @@ export interface ErrorPart extends BasePart<"error", ErrorPartMetadata> { /** * Encoded representation of error parts for serialization. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface ErrorPartEncoded extends BasePartEncoded<"error", ErrorPartMetadata> { readonly error: unknown @@ -2509,16 +2547,26 @@ export interface ErrorPartEncoded extends BasePartEncoded<"error", ErrorPartMeta * Represents provider-specific metadata that can be associated with a * `ErrorPart` through module augmentation. * - * @since 1.0.0 - * @category provider options + * @category configuration + * @since 4.0.0 */ export interface ErrorPartMetadata extends ProviderMetadata {} /** * Schema for validation and encoding of error parts. * - * @since 1.0.0 + * **Details** + * + * Validates and encodes error parts with `type: "error"` and an `error` payload + * kept as `unknown`. + * + * **Gotchas** + * + * The decoded `error` value is not guaranteed to be an `Error`; narrow it before + * reading `Error`-specific fields. + * * @category schemas + * @since 4.0.0 */ export const ErrorPart: Schema.Struct<{ readonly type: Schema.tag<"error"> diff --git a/.opencode/node_modules/effect/src/unstable/ai/ResponseIdTracker.ts b/.opencode/node_modules/effect/src/unstable/ai/ResponseIdTracker.ts index 71cb6313f8eac4f095443633fe76d3a2f811c526..b16791724be381b2990832ba6c47232bbadf6e44 100644 --- a/.opencode/node_modules/effect/src/unstable/ai/ResponseIdTracker.ts +++ b/.opencode/node_modules/effect/src/unstable/ai/ResponseIdTracker.ts @@ -1,4 +1,12 @@ /** + * Track provider response IDs for incremental language model calls. + * + * Some providers can continue from a prior response by accepting a + * `previousResponseId` plus only the messages added after that response. This + * module exposes a small mutable service that remembers which prompt message + * objects were included in each provider response and prepares a shorter prompt + * when a later call extends the same conversation. + * * @since 4.0.0 */ import * as Context from "../../Context.ts" @@ -7,8 +15,16 @@ import * as Option from "../../Option.ts" import * as Prompt from "./Prompt.ts" /** - * @since 4.0.0 + * Result returned when a tracked prompt can be sent incrementally. + * + * **Details** + * + * It contains the provider response ID to pass as `previousResponseId` and the + * prompt fragment containing only the new messages after the latest assistant + * turn. + * * @category models + * @since 4.0.0 */ export interface PrepareResult { readonly previousResponseId: string @@ -16,8 +32,18 @@ export interface PrepareResult { } /** - * @since 4.0.0 + * Mutable service that tracks prompt message object identities by provider + * response ID. + * + * **Details** + * + * `markParts` records the prompt messages that produced a response, + * `prepareUnsafe` returns a `previousResponseId` plus the untracked suffix when + * the prompt prefix is fully recognized, and `clearUnsafe` drops all tracked + * state. + * * @category models + * @since 4.0.0 */ export interface Service { clearUnsafe(): void @@ -26,14 +52,32 @@ export interface Service { } /** + * Service tag for enabling provider previous-response ID reuse across language + * model calls. + * + * **When to use** + * + * Use when you provide a language model with previous-response ID tracking so + * later calls can send only new prompt messages together with the provider's + * prior response ID. + * + * @category services * @since 4.0.0 - * @category Services */ export class ResponseIdTracker extends Context.Service()("effect/ai/ResponseIdTracker") {} /** - * @since 4.0.0 + * Creates an in-memory `ResponseIdTracker` service. + * + * **Details** + * + * The tracker maps prompt message object identities to provider response IDs. + * `prepareUnsafe` returns a previous response ID and the messages after the + * latest assistant turn only when the existing prompt prefix is fully tracked; + * otherwise it clears the tracked state and returns `Option.none()`. + * * @category constructors + * @since 4.0.0 */ export const make: Effect.Effect = Effect.sync(() => { const sentParts = new Map() diff --git a/.opencode/node_modules/effect/src/unstable/ai/Telemetry.ts b/.opencode/node_modules/effect/src/unstable/ai/Telemetry.ts index 686d67c2f79b9b00a2988235e2ddc606f66218d6..4dbb88e4f5e10c2840e8362693d8d04cf07d444c 100644 --- a/.opencode/node_modules/effect/src/unstable/ai/Telemetry.ts +++ b/.opencode/node_modules/effect/src/unstable/ai/Telemetry.ts @@ -1,33 +1,11 @@ /** - * The `Telemetry` module provides OpenTelemetry integration for operations - * performed against a large language model provider by defining telemetry - * attributes and utilities that follow the OpenTelemetry GenAI semantic - * conventions. + * Adds OpenTelemetry GenAI attributes to Effect AI spans. * - * @example - * ```ts - * import { Effect } from "effect" - * import { Telemetry } from "effect/unstable/ai" - * - * // Add telemetry attributes to a span - * const addTelemetry = Effect.gen(function*() { - * const span = yield* Effect.currentSpan - * - * Telemetry.addGenAIAnnotations(span, { - * system: "openai", - * operation: { name: "chat" }, - * request: { - * model: "gpt-4", - * temperature: 0.7, - * maxTokens: 1000 - * }, - * usage: { - * inputTokens: 100, - * outputTokens: 50 - * } - * }) - * }) - * ``` + * This module models the `gen_ai.*` attributes used by language model and + * embedding providers. It includes attribute types, helpers for writing + * non-null attributes onto existing spans, and a `CurrentSpanTransformer` + * service for adding custom span annotations from provider options and response + * parts. * * @since 4.0.0 */ @@ -44,10 +22,14 @@ import type * as Response from "./Response.ts" * The attributes used to describe telemetry in the context of Generative * Artificial Intelligence (GenAI) models requests and responses. * - * {@see https://opentelemetry.io/docs/specs/semconv/attributes-registry/gen-ai/} + * **Details** + * + * These attributes follow the OpenTelemetry generative AI semantic + * conventions: + * https://opentelemetry.io/docs/specs/semconv/attributes-registry/gen-ai/ * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type GenAITelemetryAttributes = Struct.Simplify< & AttributesWithPrefix @@ -61,8 +43,8 @@ export type GenAITelemetryAttributes = Struct.Simplify< /** * All telemetry attributes which are part of the GenAI specification. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type AllAttributes = & BaseAttributes @@ -76,8 +58,8 @@ export type AllAttributes = * Telemetry attributes which are part of the GenAI specification and are * namespaced by `gen_ai`. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface BaseAttributes { /** @@ -91,8 +73,8 @@ export interface BaseAttributes { * Telemetry attributes which are part of the GenAI specification and are * namespaced by `gen_ai.operation`. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface OperationAttributes { readonly name?: (string & {}) | WellKnownOperationName | null | undefined @@ -102,8 +84,8 @@ export interface OperationAttributes { * Telemetry attributes which are part of the GenAI specification and are * namespaced by `gen_ai.token`. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface TokenAttributes { readonly type?: string | null | undefined @@ -113,8 +95,8 @@ export interface TokenAttributes { * Telemetry attributes which are part of the GenAI specification and are * namespaced by `gen_ai.usage`. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface UsageAttributes { readonly inputTokens?: number | null | undefined @@ -125,8 +107,8 @@ export interface UsageAttributes { * Telemetry attributes which are part of the GenAI specification and are * namespaced by `gen_ai.request`. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface RequestAttributes { /** @@ -177,8 +159,8 @@ export interface RequestAttributes { * Telemetry attributes which are part of the GenAI specification and are * namespaced by `gen_ai.response`. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface ResponseAttributes { /** @@ -200,22 +182,26 @@ export interface ResponseAttributes { * The `gen_ai.operation.name` attribute has the following list of well-known * values. * + * **Details** + * * If one of them applies, then the respective value **MUST** be used; * otherwise, a custom value **MAY** be used. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type WellKnownOperationName = "chat" | "embeddings" | "text_completion" /** * The `gen_ai.system` attribute has the following list of well-known values. * + * **Details** + * * If one of them applies, then the respective value **MUST** be used; * otherwise, a custom value **MAY** be used. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type WellKnownSystem = | "anthropic" @@ -236,10 +222,13 @@ export type WellKnownSystem = /** * Utility type for prefixing attribute names with a namespace. * + * **Details** + * * Transforms attribute keys by adding a prefix and formatting them according to * OpenTelemetry conventions (camelCase to snake_case). * - * @example + * **Example** (Prefixing telemetry attributes) + * * ```ts * import type { Telemetry } from "effect/unstable/ai" * @@ -258,8 +247,8 @@ export type WellKnownSystem = * // } * ``` * - * @since 4.0.0 * @category utility types + * @since 4.0.0 */ export type AttributesWithPrefix, Prefix extends string> = { [Name in keyof Attributes as `${Prefix}.${FormatAttributeName}`]: Attributes[Name] @@ -268,10 +257,13 @@ export type AttributesWithPrefix, Prefix /** * Utility type for converting camelCase names to snake_case format. * + * **Details** + * * This type recursively transforms string literal types from camelCase to * snake_case, which is the standard format for OpenTelemetry attributes. * - * @example + * **Example** (Formatting attribute names) + * * ```ts * import type { Telemetry } from "effect/unstable/ai" * @@ -280,8 +272,8 @@ export type AttributesWithPrefix, Prefix * type Formatted3 = Telemetry.FormatAttributeName<"temperature"> // "temperature" * ``` * - * @since 4.0.0 * @category utility types + * @since 4.0.0 */ export type FormatAttributeName = T extends string ? T extends `${infer First}${infer Rest}` @@ -290,15 +282,19 @@ export type FormatAttributeName = T extends never /** - * Creates a function to add attributes to a span with a given prefix and key transformation. + * Creates a reusable span-attribute writer for a key prefix and key + * transformer. * - * This utility function is used internally to create specialized functions for adding - * different types of telemetry attributes to OpenTelemetry spans. + * **Details** + * + * The returned function mutates the supplied span by adding each non-nullish + * attribute as `${prefix}.${transformedKey}`. + * + * **Example** (Adding prefixed span attributes) * - * @example * ```ts - * import type { Tracer } from "effect" * import { String } from "effect" + * import type { Tracer } from "effect" * import { Telemetry } from "effect/unstable/ai" * * const addCustomAttributes = Telemetry.addSpanAttributes( @@ -315,8 +311,8 @@ export type FormatAttributeName = T extends * // Results in attributes: "custom.ai.model_name" and "custom.ai.max_tokens" * ``` * + * @category annotations * @since 4.0.0 - * @category utilities */ export const addSpanAttributes = ( /** @@ -355,10 +351,13 @@ const addSpanUsageAttributes = addSpanAttributes("gen_ai.usage", String.camelToS /** * Configuration options for GenAI telemetry attributes. * + * **Details** + * * Combines base attributes with optional grouped attributes for comprehensive * telemetry coverage of AI operations. * - * @example + * **Example** (Configuring GenAI telemetry attributes) + * * ```ts * import type { Telemetry } from "effect/unstable/ai" * @@ -384,8 +383,8 @@ const addSpanUsageAttributes = addSpanAttributes("gen_ai.usage", String.camelToS * } * ``` * + * @category options * @since 4.0.0 - * @category models */ export type GenAITelemetryAttributeOptions = BaseAttributes & { /** @@ -413,12 +412,22 @@ export type GenAITelemetryAttributeOptions = BaseAttributes & { /** * Applies GenAI telemetry attributes to an OpenTelemetry span. * - * This function adds standardized GenAI attributes to a span following OpenTelemetry - * semantic conventions. It supports both curried and direct application patterns. + * **When to use** + * + * Use when you need to write GenAI request, response, token, or usage + * attributes onto an existing OpenTelemetry span. + * + * **Details** * - * **Note**: This function mutates the provided span in-place. + * This function adds standardized GenAI attributes to a span following + * OpenTelemetry semantic conventions. + * + * **Gotchas** + * + * This function mutates the provided span in-place. + * + * **Example** (Adding GenAI telemetry annotations) * - * @example * ```ts * import { Effect } from "effect" * import { Telemetry } from "effect/unstable/ai" @@ -434,19 +443,29 @@ export type GenAITelemetryAttributeOptions = BaseAttributes & { * }) * ``` * + * @category annotations * @since 4.0.0 - * @category utilities */ export const addGenAIAnnotations: { /** * Applies GenAI telemetry attributes to an OpenTelemetry span. * - * This function adds standardized GenAI attributes to a span following OpenTelemetry - * semantic conventions. It supports both curried and direct application patterns. + * **When to use** + * + * Use when you need to write GenAI request, response, token, or usage + * attributes onto an existing OpenTelemetry span. * - * **Note**: This function mutates the provided span in-place. + * **Details** + * + * This function adds standardized GenAI attributes to a span following + * OpenTelemetry semantic conventions. + * + * **Gotchas** + * + * This function mutates the provided span in-place. + * + * **Example** (Adding GenAI telemetry annotations) * - * @example * ```ts * import { Effect } from "effect" * import { Telemetry } from "effect/unstable/ai" @@ -462,19 +481,29 @@ export const addGenAIAnnotations: { * }) * ``` * + * @category annotations * @since 4.0.0 - * @category utilities */ (options: GenAITelemetryAttributeOptions): (span: Span) => void /** * Applies GenAI telemetry attributes to an OpenTelemetry span. * - * This function adds standardized GenAI attributes to a span following OpenTelemetry - * semantic conventions. It supports both curried and direct application patterns. + * **When to use** + * + * Use when you need to write GenAI request, response, token, or usage + * attributes onto an existing OpenTelemetry span. + * + * **Details** + * + * This function adds standardized GenAI attributes to a span following + * OpenTelemetry semantic conventions. + * + * **Gotchas** + * + * This function mutates the provided span in-place. * - * **Note**: This function mutates the provided span in-place. + * **Example** (Adding GenAI telemetry annotations) * - * @example * ```ts * import { Effect } from "effect" * import { Telemetry } from "effect/unstable/ai" @@ -490,8 +519,8 @@ export const addGenAIAnnotations: { * }) * ``` * + * @category annotations * @since 4.0.0 - * @category utilities */ (span: Span, options: GenAITelemetryAttributeOptions): void } = dual(2, (span: Span, options: GenAITelemetryAttributeOptions) => { @@ -506,10 +535,13 @@ export const addGenAIAnnotations: { /** * A function that can transform OpenTelemetry spans based on AI operation data. * + * **Details** + * * Span transformers receive the complete request/response context from AI operations * and can add custom telemetry attributes, metrics, or other observability data. * - * @example + * **Example** (Transforming AI spans) + * * ```ts * import type { Telemetry } from "effect/unstable/ai" * @@ -524,8 +556,8 @@ export const addGenAIAnnotations: { * } * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface SpanTransformer { ( @@ -539,11 +571,18 @@ export interface SpanTransformer { } /** - * Service key for providing a span transformer to large langauge model + * Service tag for providing a `SpanTransformer` to large language model * operations. * - * @since 4.0.0 + * **When to use** + * + * Use to retrieve or provide the current `SpanTransformer` through context for + * language model span annotation. + * + * @see {@link SpanTransformer} for the transformer contract provided by this service + * * @category services + * @since 4.0.0 */ export class CurrentSpanTransformer extends Context.Service()( "effect/ai/Telemetry/CurrentSpanTransformer" diff --git a/.opencode/node_modules/effect/src/unstable/ai/Tokenizer.ts b/.opencode/node_modules/effect/src/unstable/ai/Tokenizer.ts index d37a23e784aca5860a4a17ab7950657fbbcdd4d1..4764ce539b78384c8ea431d72619cae19d1bdf8a 100644 --- a/.opencode/node_modules/effect/src/unstable/ai/Tokenizer.ts +++ b/.opencode/node_modules/effect/src/unstable/ai/Tokenizer.ts @@ -1,37 +1,12 @@ /** - * The `Tokenizer` module provides tokenization and text truncation capabilities - * for large language model text processing workflows. + * Service for model-specific token counting and prompt truncation. Tokenization + * depends on the target provider, model, and encoding rules, so this module + * leaves the actual tokenization function to the service implementation. * - * This module offers services for converting text into tokens and truncating - * prompts based on token limits, essential for managing context length - * constraints in large language models. - * - * @example - * ```ts - * import { Effect } from "effect" - * import { Tokenizer } from "effect/unstable/ai" - * - * const tokenizeText = Effect.gen(function*() { - * const tokenizer = yield* Tokenizer.Tokenizer - * const tokens = yield* tokenizer.tokenize("Hello, world!") - * console.log(`Token count: ${tokens.length}`) - * return tokens - * }) - * ``` - * - * @example - * ```ts - * import { Effect } from "effect" - * import { Tokenizer } from "effect/unstable/ai" - * - * // Truncate a prompt to fit within token limits - * const truncatePrompt = Effect.gen(function*() { - * const tokenizer = yield* Tokenizer.Tokenizer - * const longPrompt = "This is a very long prompt..." - * const truncated = yield* tokenizer.truncate(longPrompt, 100) - * return truncated - * }) - * ``` + * The `Tokenizer` service can count tokens for raw prompt input and shorten a + * prompt to a token limit by keeping the newest messages that fit. This module + * defines the service tag, the service interface, and a `make` constructor that + * builds a full tokenizer service from a token-counting function. * * @since 4.0.0 */ @@ -42,12 +17,20 @@ import type * as AiError from "./AiError.ts" import * as Prompt from "./Prompt.ts" /** - * The `Tokenizer` service tag for dependency injection. + * Service tag for model tokenization services. + * + * **When to use** + * + * Use to access or provide model-specific token counting and prompt truncation + * operations. + * + * **Details** * * This tag provides access to tokenization functionality throughout your * application, enabling token counting and prompt truncation capabilities. * - * @example + * **Example** (Accessing the Tokenizer service) + * * ```ts * import { Effect } from "effect" * import { Tokenizer } from "effect/unstable/ai" @@ -59,8 +42,8 @@ import * as Prompt from "./Prompt.ts" * }) * ``` * - * @since 4.0.0 * @category services + * @since 4.0.0 */ export class Tokenizer extends Context.Service()( "effect/ai/Tokenizer" @@ -70,14 +53,17 @@ export class Tokenizer extends Context.Service()( * Tokenizer service interface providing text tokenization and truncation * operations. * + * **Details** + * * This interface defines the core operations for converting text to tokens and * managing content length within token limits for AI model compatibility. * - * @example + * **Example** (Implementing a custom tokenizer) + * * ```ts * import { Effect } from "effect" - * import type { Tokenizer } from "effect/unstable/ai" * import { Prompt } from "effect/unstable/ai" + * import type { Tokenizer } from "effect/unstable/ai" * * const customTokenizer: Tokenizer.Service = { * tokenize: (input) => @@ -87,8 +73,8 @@ export class Tokenizer extends Context.Service()( * } * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface Service { /** @@ -118,11 +104,14 @@ export interface Service { /** * Creates a Tokenizer service implementation from tokenization options. * + * **Details** + * * This function constructs a complete Tokenizer service by providing a * tokenization function. The service handles both tokenization and * truncation operations using the provided tokenizer. * - * @example + * **Example** (Creating a word tokenizer) + * * ```ts * import { Effect } from "effect" * import { Tokenizer } from "effect/unstable/ai" @@ -144,8 +133,8 @@ export interface Service { * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const make = (options: { readonly tokenize: (content: Prompt.Prompt) => Effect.Effect, AiError.AiError> diff --git a/.opencode/node_modules/effect/src/unstable/ai/Tool.ts b/.opencode/node_modules/effect/src/unstable/ai/Tool.ts index dae2626f13f14548d7cd00d14fd666762860fa2b..3b44db8b279428cc65cec76816ce9c6ef8937b13 100644 --- a/.opencode/node_modules/effect/src/unstable/ai/Tool.ts +++ b/.opencode/node_modules/effect/src/unstable/ai/Tool.ts @@ -1,30 +1,15 @@ /** - * The `Tool` module provides functionality for defining and managing tools - * that language models can call to augment their capabilities. + * Definitions and helpers for tools that AI models can request during a + * workflow. * - * This module enables creation of both user-defined and provider-defined tools, - * with full schema validation, type safety, and handler support. Tools allow - * AI models to perform actions like searching databases, calling APIs, or - * executing code within your application context. + * A tool names an operation, describes the parameters it accepts, declares + * successful and failed results, and can require approval before execution. + * This module supports tools defined by the application, tools built into a + * provider, and dynamic tools whose schema is known only at runtime. It also + * includes the shared types and conversion helpers needed by language-model + * requests, tool handlers, and provider integrations. * - * @example - * ```ts - * import { Schema } from "effect" - * import { Tool } from "effect/unstable/ai" - * - * // Define a simple calculator tool - * const Calculator = Tool.make("Calculator", { - * description: "Performs basic arithmetic operations", - * parameters: Schema.Struct({ - * operation: Schema.Literals(["add", "subtract", "multiply", "divide"]), - * a: Schema.Number, - * b: Schema.Number - * }), - * success: Schema.Number - * }) - * ``` - * - * @since 1.0.0 + * @since 4.0.0 */ import * as Context from "../../Context.ts" import type * as Effect from "../../Effect.ts" @@ -33,7 +18,7 @@ import type * as JsonSchema from "../../JsonSchema.ts" import { pipeArguments } from "../../Pipeable.ts" import * as Predicate from "../../Predicate.ts" import * as Schema from "../../Schema.ts" -import * as AST from "../../SchemaAST.ts" +import * as SchemaAST from "../../SchemaAST.ts" import type * as Struct from "../../Struct.ts" import type * as Types from "../../Types.ts" import type * as AiError from "./AiError.ts" @@ -45,38 +30,66 @@ import type * as Prompt from "./Prompt.ts" // ============================================================================= /** - * @since 1.0.0 - * @category type ids + * Runtime type identifier carried by Effect AI tool values. + * + * **Details** + * + * The tool type guards use this marker, together with more specific markers, + * to distinguish user-defined, provider-defined, and dynamic tools. + * + * @category type IDs + * @since 4.0.0 */ export const TypeId: TypeId = "~effect/ai/Tool" /** - * @since 1.0.0 - * @category type ids + * Type-level representation of the Effect AI tool runtime type identifier. + * + * @category type IDs + * @since 4.0.0 */ export type TypeId = "~effect/ai/Tool" /** - * @since 1.0.0 - * @category type ids + * Runtime type identifier carried by provider-defined tools. + * + * **Details** + * + * `isProviderDefined` uses this marker to distinguish tools that are built into + * an AI provider from user-defined and dynamic tools. + * + * @category type IDs + * @since 4.0.0 */ export const ProviderDefinedTypeId: ProviderDefinedTypeId = "~effect/ai/Tool/ProviderDefined" /** - * @since 1.0.0 - * @category type ids + * Type-level representation of the provider-defined tool runtime type + * identifier. + * + * @category type IDs + * @since 4.0.0 */ export type ProviderDefinedTypeId = "~effect/ai/Tool/ProviderDefined" /** - * @since 1.0.0 - * @category type ids + * Runtime type identifier carried by dynamic tools. + * + * **Details** + * + * `isDynamic` uses this marker to distinguish tools whose schema may be + * provided at runtime from user-defined and provider-defined tools. + * + * @category type IDs + * @since 4.0.0 */ export const DynamicTypeId: DynamicTypeId = "~effect/ai/Tool/Dynamic" /** - * @since 1.0.0 - * @category type ids + * Type-level representation of the dynamic tool runtime type identifier. + * + * @category type IDs + * @since 4.0.0 */ export type DynamicTypeId = "~effect/ai/Tool/Dynamic" @@ -88,14 +101,16 @@ export type DynamicTypeId = "~effect/ai/Tool/Dynamic" * The strategy used for handling errors returned from tool call handler * execution. * + * **Details** + * * If set to `"error"` (the default), errors that occur during tool call handler * execution will be returned in the error channel of the calling effect. * * If set to `"return"`, errors that occur during tool call handler execution * will be captured and returned as part of the tool call result. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export type FailureMode = "error" | "return" @@ -103,8 +118,8 @@ export type FailureMode = "error" | "return" * Context provided to the `needsApproval` function when dynamically * determining if a tool requires user approval. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface NeedsApprovalContext { /** @@ -120,8 +135,8 @@ export interface NeedsApprovalContext { /** * Function type for dynamically determining if a tool requires approval. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export type NeedsApprovalFunction = ( params: Params["Type"], @@ -131,12 +146,14 @@ export type NeedsApprovalFunction = ( /** * Specifies whether user approval is required before executing a tool. * + * **Details** + * * Can be: * - `boolean`: Static approval requirement * - `NeedsApprovalFunction`: Dynamic approval based on parameters/context * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export type NeedsApproval = | boolean @@ -145,11 +162,14 @@ export type NeedsApproval = /** * A user-defined tool that language models can call to perform actions. * + * **Details** + * * Tools represent actionable capabilities that large language models can invoke * to extend their functionality beyond text generation. Each tool has a defined * schema for parameters, results, and failures. * - * @example + * **Example** (Defining a weather lookup tool) + * * ```ts * import { Schema } from "effect" * import { Tool } from "effect/unstable/ai" @@ -169,8 +189,8 @@ export type NeedsApproval = * }) * ``` * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface Tool< out Name extends string, @@ -205,6 +225,8 @@ export interface Tool< * The strategy used for handling errors returned from tool call handler * execution. * + * **Details** + * * If set to `"error"` (the default), errors that occur during tool call * handler execution will be returned in the error channel of the calling * effect. @@ -240,6 +262,8 @@ export interface Tool< /** * Specifies whether user approval is required before executing this tool. * + * **Details** + * * - If `undefined` or `false`, the tool executes immediately. * - If `true`, the tool always requires approval. * - If a function, it is called with the tool parameters and context to @@ -252,6 +276,8 @@ export interface Tool< * Adds a _request-level_ dependency which must be provided before the tool * call handler can be executed. * + * **Details** + * * This can be useful when you want to enforce that a particular dependency * **MUST** be provided to each request to the large language model provider * instead of being provided when creating the tool call handler layer. @@ -323,11 +349,14 @@ export interface Tool< * A provider-defined tool is a tool which is built into a large language model * provider (e.g. web search, code execution). * + * **Details** + * * These tools are executed by the large language model provider rather than * by your application. However, they can optionally require custom handlers * implemented in your application to process provider generated results. * - * @example + * **Example** (Defining a provider-defined web search tool) + * * ```ts * import { Schema } from "effect" * import { Tool } from "effect/unstable/ai" @@ -350,8 +379,8 @@ export interface Tool< * }) * ``` * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface ProviderDefined< out Identifier extends `${string}.${string}`, @@ -409,6 +438,8 @@ export interface ProviderDefined< /** * A dynamic tool is a tool where the schema may not be known at compile time. * + * **Details** + * * Dynamic tools support two modes: * - **Effect Schema mode**: Full type safety with validation (like `Tool.make`) * - **JSON Schema mode**: Raw JSON Schema for the model, handler receives `unknown` @@ -416,7 +447,8 @@ export interface ProviderDefined< * This enables scenarios such as MCP tools discovered at runtime, user-defined * functions loaded from external sources, or plugin systems. * - * @example + * **Example** (Defining dynamic tools) + * * ```ts * import { Schema } from "effect" * import { Tool } from "effect/unstable/ai" @@ -442,8 +474,8 @@ export interface ProviderDefined< * }) * ``` * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface Dynamic< out Name extends string, @@ -482,7 +514,8 @@ export interface Dynamic< /** * Type guard to check if a value is a user-defined tool. * - * @example + * **Example** (Checking for user-defined tools) + * * ```ts * import { Schema } from "effect" * import { Tool } from "effect/unstable/ai" @@ -517,8 +550,8 @@ export interface Dynamic< * console.log(Tool.isUserDefined(ProviderDefinedTool)) // false * ``` * - * @since 1.0.0 * @category guards + * @since 4.0.0 */ export const isUserDefined = (u: unknown): u is Tool => Predicate.hasProperty(u, TypeId) && !isProviderDefined(u) && !isDynamic(u) @@ -526,7 +559,8 @@ export const isUserDefined = (u: unknown): u is Tool => /** * Type guard to check if a value is a provider-defined tool. * - * @example + * **Example** (Checking for provider-defined tools) + * * ```ts * import { Schema } from "effect" * import { Tool } from "effect/unstable/ai" @@ -557,12 +591,12 @@ export const isUserDefined = (u: unknown): u is Tool => * }) * }) * - * console.log(Tool.isUserDefined(UserDefinedTool)) // false - * console.log(Tool.isUserDefined(ProviderDefinedTool)) // true + * console.log(Tool.isProviderDefined(UserDefinedTool)) // false + * console.log(Tool.isProviderDefined(ProviderDefinedTool)) // true * ``` * - * @since 1.0.0 * @category guards + * @since 4.0.0 */ export const isProviderDefined = ( u: unknown @@ -571,7 +605,8 @@ export const isProviderDefined = ( /** * Type guard to check if a value is a dynamic tool. * - * @example + * **Example** (Checking for dynamic tools) + * * ```ts * import { Schema } from "effect" * import { Tool } from "effect/unstable/ai" @@ -589,8 +624,8 @@ export const isProviderDefined = ( * console.log(Tool.isDynamic(UserDefinedTool)) // false * ``` * - * @since 1.0.0 * @category guards + * @since 4.0.0 */ export const isDynamic = (u: unknown): u is Dynamic => Predicate.hasProperty(u, DynamicTypeId) @@ -601,8 +636,8 @@ export const isDynamic = (u: unknown): u is Dynamic => Predicate.ha /** * A type which represents any `Tool`. * - * @since 1.0.0 * @category utility types + * @since 4.0.0 */ export interface Any extends Tool = T extends Tool< infer _Name, @@ -668,8 +703,8 @@ export type Name = T extends Tool< /** * A utility type to extract the type of the tool call parameters. * - * @since 1.0.0 * @category utility types + * @since 4.0.0 */ export type Parameters = T extends Tool< infer _Name, @@ -681,8 +716,8 @@ export type Parameters = T extends Tool< /** * A utility type to extract the encoded type of the tool call parameters. * - * @since 1.0.0 * @category utility types + * @since 4.0.0 */ export type ParametersEncoded = T extends Tool< infer _Name, @@ -695,8 +730,8 @@ export type ParametersEncoded = T extends Tool< * A utility type to extract the schema for the parameters which an `Tool` * must be called with. * - * @since 1.0.0 * @category utility types + * @since 4.0.0 */ export type ParametersSchema = T extends Tool< infer _Name, @@ -708,8 +743,8 @@ export type ParametersSchema = T extends Tool< /** * A utility type to extract the type of the tool call result when it succeeds. * - * @since 1.0.0 * @category utility types + * @since 4.0.0 */ export type Success = T extends Tool< infer _Name, @@ -722,8 +757,8 @@ export type Success = T extends Tool< * A utility type to extract the encoded type of the tool call result when * it succeeds. * - * @since 1.0.0 * @category utility types + * @since 4.0.0 */ export type SuccessEncoded = T extends Tool< infer _Name, @@ -736,8 +771,8 @@ export type SuccessEncoded = T extends Tool< * A utility type to extract the schema for the return type of a tool call when * the tool call succeeds. * - * @since 1.0.0 * @category utility types + * @since 4.0.0 */ export type SuccessSchema = T extends Tool< infer _Name, @@ -749,8 +784,8 @@ export type SuccessSchema = T extends Tool< /** * A utility type to extract the type of the tool call result when it fails. * - * @since 1.0.0 * @category utility types + * @since 4.0.0 */ export type Failure = T extends Tool< infer _Name, @@ -763,8 +798,8 @@ export type Failure = T extends Tool< * A utility type to extract the encoded type of the tool call result when * it fails. * - * @since 1.0.0 * @category utility types + * @since 4.0.0 */ export type FailureEncoded = T extends Tool< infer _Name, @@ -778,8 +813,8 @@ export type FailureEncoded = T extends Tool< * When `failureMode` is `"return"`, this includes both user-defined failures * and `AiError`. * - * @since 1.0.0 * @category utility types + * @since 4.0.0 */ export type FailureResult = T extends Tool< infer _Name, @@ -792,8 +827,8 @@ export type FailureResult = T extends Tool< /** * The encoded version of `FailureResult`. * - * @since 1.0.0 * @category utility types + * @since 4.0.0 */ export type FailureResultEncoded = T extends Tool< infer _Name, @@ -807,10 +842,12 @@ export type FailureResultEncoded = T extends Tool< * A utility type to extract the type of the tool call result whether it * succeeds or fails. * + * **Details** + * * When `failureMode` is `"return"`, the result may also be an `AiError`. * - * @since 1.0.0 * @category utility types + * @since 4.0.0 */ export type Result = T extends Tool< infer _Name, @@ -824,10 +861,12 @@ export type Result = T extends Tool< * A utility type to extract the encoded type of the tool call result whether * it succeeds or fails. * + * **Details** + * * When `failureMode` is `"return"`, the result may also be an encoded `AiError`. * - * @since 1.0.0 * @category utility types + * @since 4.0.0 */ export type ResultEncoded = T extends Tool< infer _Name, @@ -840,8 +879,8 @@ export type ResultEncoded = T extends Tool< /** * A utility type to extract the requirements of a `Tool` call handler. * - * @since 1.0.0 * @category utility types + * @since 4.0.0 */ export type HandlerServices = T extends Tool< infer _Name, @@ -860,8 +899,8 @@ export type HandlerServices = T extends Tool< * A utility type to extract the requirements needed to encode the result of * a `Tool` call. * - * @since 1.0.0 * @category utility types + * @since 4.0.0 */ export type ResultEncodingServices = T extends Tool< infer _Name, @@ -874,8 +913,8 @@ export type ResultEncodingServices = T extends Tool< * A utility type to extract the requirements needed to decode the result of * a `Tool` call. * - * @since 1.0.0 * @category utility types + * @since 4.0.0 */ export type ResultDecodingServices = T extends Tool< infer _Name, @@ -887,8 +926,8 @@ export type ResultDecodingServices = T extends Tool< /** * Represents an `Tool` that has been implemented within the application. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface Handler { readonly _: unique symbol @@ -900,8 +939,8 @@ export interface Handler { /** * Represents the result of calling the handler for a particular `Tool`. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface HandlerResult { /** @@ -929,13 +968,15 @@ export interface HandlerResult { /** * Tagged union for incremental handler output. * + * **Details** + * * When a tool handler returns a `Stream`, each emitted value is tagged as * either: * - `Preliminary`: An intermediate result representing progress * - `Final`: The last result, which is the authoritative output * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export type HandlerOutput = | { readonly _tag: "Preliminary"; readonly value: Success } @@ -945,8 +986,8 @@ export type HandlerOutput = * A utility type which represents the possible errors that can be raised by * a tool call's handler. * - * @since 1.0.0 * @category utility types + * @since 4.0.0 */ export type HandlerError = T extends Tool< infer _Name, @@ -960,8 +1001,8 @@ export type HandlerError = T extends Tool< * A utility type to create a union of `Handler` types for all tools in a * record. * - * @since 1.0.0 * @category utility types + * @since 4.0.0 */ export type HandlersFor> = { [Name in keyof Tools]: RequiresHandler extends true ? Handler @@ -972,8 +1013,8 @@ export type HandlersFor> = { * A utility type to determine if the specified tool requires a user-defined * handler to be implemented. * - * @since 1.0.0 * @category utility types + * @since 4.0.0 */ export type RequiresHandler = Tool extends ProviderDefined< infer _Name, @@ -1125,6 +1166,8 @@ const dynamicProto = < /** * Creates a user-defined tool with the specified name and configuration. * + * **Details** + * * This is the primary constructor for creating custom tools that AI models * can call. The tool definition includes parameter validation, success/failure * schemas, and optional service dependencies. @@ -1132,7 +1175,8 @@ const dynamicProto = < * If a tool accepts no parameters but still needs an explicit empty object * schema, use {@link EmptyParams}. * - * @example + * **Example** (Creating a tool without parameters) + * * ```ts * import { Schema } from "effect" * import { Tool } from "effect/unstable/ai" @@ -1144,8 +1188,8 @@ const dynamicProto = < * }) * ``` * - * @since 1.0.0 * @category constructors + * @since 4.0.0 */ export const make = < const Name extends string, @@ -1175,6 +1219,8 @@ export const make = < * The strategy used for handling errors returned from tool call handler * execution. * + * **Details** + * * If set to `"error"` (the default), errors that occur during tool call handler * execution will be returned in the error channel of the calling effect. * @@ -1189,6 +1235,8 @@ export const make = < /** * Specifies whether user approval is required before executing this tool. * + * **Details** + * * - If `undefined` or `false`, the tool executes immediately. * - If `true`, the tool always requires approval. * - If a function, it is called with the tool parameters and context to @@ -1223,13 +1271,18 @@ export const make = < * Creates a dynamic tool that can accept either an Effect Schema or a raw * JSON Schema for its parameters. * - * This is useful for tools where the schema isn't known at compile time, - * such as MCP tools discovered at runtime or tools from external configurations. + * **When to use** + * + * Use when you do not know a tool schema at compile time, such as MCP tools + * discovered at runtime or tools from external configurations. + * + * **Details** * * - When `parameters` is an Effect Schema: full type safety with validation * - When `parameters` is a JSON Schema: handler receives `unknown`, no validation * - * @example + * **Example** (Creating a dynamic tool) + * * ```ts * import { Schema } from "effect" * import { Tool } from "effect/unstable/ai" @@ -1255,21 +1308,26 @@ export const make = < * }) * ``` * - * @since 1.0.0 * @category constructors + * @since 4.0.0 */ export const dynamic: { /** * Creates a dynamic tool that can accept either an Effect Schema or a raw * JSON Schema for its parameters. * - * This is useful for tools where the schema isn't known at compile time, - * such as MCP tools discovered at runtime or tools from external configurations. + * **When to use** + * + * Use when you do not know a tool schema at compile time, such as MCP tools + * discovered at runtime or tools from external configurations. + * + * **Details** * * - When `parameters` is an Effect Schema: full type safety with validation * - When `parameters` is a JSON Schema: handler receives `unknown`, no validation * - * @example + * **Example** (Creating a dynamic tool) + * * ```ts * import { Schema } from "effect" * import { Tool } from "effect/unstable/ai" @@ -1295,8 +1353,8 @@ export const dynamic: { * }) * ``` * - * @since 1.0.0 * @category constructors + * @since 4.0.0 */ < const Name extends string, @@ -1354,11 +1412,14 @@ export const dynamic: { * Creates a provider-defined tool which leverages functionality built into a * large language model provider (e.g. web search, code execution). * + * **Details** + * * These tools are executed by the large language model provider rather than * by your application. However, they can optionally require custom handlers * implemented in your application to process provider generated results. * - * @example + * **Example** (Creating a provider-defined tool) + * * ```ts * import { Schema } from "effect" * import { Tool } from "effect/unstable/ai" @@ -1381,8 +1442,8 @@ export const dynamic: { * }) * ``` * - * @since 1.0.0 * @category constructors + * @since 4.0.0 */ export const providerDefined = < const Identifier extends `${string}.${string}`, @@ -1479,16 +1540,18 @@ export const providerDefined = < // ============================================================================= /** - * A utility which allows mapping between a provider-defined name for a tool - * and the name given to the tool by the Effect AI SDK. + * Maps between a provider-defined tool name and the name given to the tool by + * the Effect AI SDK. + * + * **Details** * * The custom names used by the Effect AI SDK are to allow for toolkits which * contain tools from multiple different providers that would otherwise have * naming conflicts (i.e. `"web_search"`) to instead use custom names (i.e. * `"OpenAiWebSearch"`). * - * @since 1.0.0 - * @category utilities + * @category models + * @since 4.0.0 */ export class NameMapper> { readonly #customToProvider: Map = new Map() @@ -1521,6 +1584,8 @@ export class NameMapper> { * Returns the user-specified tool name that corresponds with the provided * provider-specified tool name. * + * **Details** + * * If the provider-specified tool name was not registered with the name mapper, * then the provider-specified tool name is returned. */ @@ -1532,6 +1597,8 @@ export class NameMapper> { * Returns the provider-specified tool name that corresponds with the provided * user-specified tool name. * + * **Details** + * * If the user-specified tool name was not registered with the name mapper, * then the user-specified tool name is returned. */ @@ -1543,10 +1610,13 @@ export class NameMapper> { /** * Extracts the description from a tool's metadata. * + * **Details** + * * Returns the tool's description if explicitly set, otherwise attempts to * extract it from the parameter schema's AST annotations. * - * @example + * **Example** (Reading a tool description) + * * ```ts * import { Tool } from "effect/unstable/ai" * @@ -1558,15 +1628,15 @@ export class NameMapper> { * console.log(description) // "This is an example tool" * ``` * - * @since 1.0.0 - * @category utilities + * @category getters + * @since 4.0.0 */ export const getDescription = (tool: Tool): string | undefined => { if (tool.description !== undefined) { return tool.description } if (Schema.isSchema(tool.parametersSchema)) { - return AST.resolveDescription(tool.parametersSchema.ast) + return SchemaAST.resolveDescription(tool.parametersSchema.ast) } return undefined } @@ -1574,6 +1644,8 @@ export const getDescription = (tool: Tool): string | undefined /** * Generates a JSON Schema for a tool. * + * **Details** + * * This function creates a JSON Schema representation that can be used by * large language models to indicate the structure and type of the parameters * that a given tool call should receive. @@ -1582,7 +1654,8 @@ export const getDescription = (tool: Tool): string | undefined * tool parameter schema so that the resultant JSON schema for the tool call * parameters are in a format that conforms to any provider-specific constraints. * - * @example + * **Example** (Generating a tool JSON schema) + * * ```ts * import { Schema } from "effect" * import { Tool } from "effect/unstable/ai" @@ -1606,8 +1679,8 @@ export const getDescription = (tool: Tool): string | undefined * // } * ``` * - * @since 1.0.0 - * @category utilities + * @category getters + * @since 4.0.0 */ export const getJsonSchema = (tool: Tool, options?: { readonly transformer?: CodecTransformer @@ -1619,8 +1692,17 @@ export const getJsonSchema = (tool: Tool, options?: { } /** - * @since 1.0.0 - * @category utilities + * Generates a JSON Schema from an Effect `Schema`. + * + * **Details** + * + * If a `CodecTransformer` is supplied, the transformed schema's JSON Schema is + * returned. Otherwise, the schema is converted with + * `Schema.toJsonSchemaDocument` and any generated definitions are attached as + * `$defs`. + * + * @category converting + * @since 4.0.0 */ export const getJsonSchemaFromSchema = (schema: S, options?: { readonly transformer?: CodecTransformer @@ -1642,7 +1724,8 @@ export const getJsonSchemaFromSchema = (schema: S, options /** * Annotation for providing a human-readable title for tools. * - * @example + * **Example** (Annotating a tool title) + * * ```ts * import { Tool } from "effect/unstable/ai" * @@ -1650,30 +1733,38 @@ export const getJsonSchemaFromSchema = (schema: S, options * .annotate(Tool.Title, "Tip Calculator") * ``` * - * @since 1.0.0 * @category annotations + * @since 4.0.0 */ export class Title extends Context.Service()("effect/ai/Tool/Title") {} /** * Annotation for providing tool metadata for MCP. * - * @example + * **Example** (Annotating MCP metadata) + * * ```ts * import { Tool } from "effect/unstable/ai" * * const myCalculatorUi = Tool.make("calculator_ui", {}) * .annotate(Tool.Meta, { ui: { resourceUri: "ui://example/calculator-ui" } }) * ``` - * @since 1.0.0 + * * @category annotations + * @since 4.0.0 */ export class Meta extends Context.Service>()("effect/ai/Tool/Meta") {} /** * Annotation indicating whether a tool only reads data without making changes. * - * @example + * **Details** + * + * This is emitted as the MCP `readOnlyHint`; unannotated tools default to + * `false`. + * + * **Example** (Marking a tool as read-only) + * * ```ts * import { Tool } from "effect/unstable/ai" * @@ -1681,17 +1772,23 @@ export class Meta extends Context.Service>()("effe * .annotate(Tool.Readonly, true) * ``` * - * @since 1.0.0 * @category annotations + * @since 4.0.0 */ export const Readonly = Context.Reference("effect/ai/Tool/Readonly", { defaultValue: constFalse }) /** - * Annotation indicating whether a tool performs destructive operations. + * Annotation indicating whether a tool may perform destructive operations. + * + * **Details** + * + * This is emitted as the MCP `destructiveHint`; unannotated tools default to + * `true`, so annotate safe tools with `false`. + * + * **Example** (Marking a tool as non-destructive) * - * @example * ```ts * import { Tool } from "effect/unstable/ai" * @@ -1699,17 +1796,24 @@ export const Readonly = Context.Reference("effect/ai/Tool/Readonly", { * .annotate(Tool.Destructive, false) * ``` * - * @since 1.0.0 * @category annotations + * @since 4.0.0 */ export const Destructive = Context.Reference("effect/ai/Tool/Destructive", { defaultValue: constTrue }) /** - * Annotation indicating whether a tool can be called multiple times safely. + * Annotation indicating whether a tool can be called repeatedly with the same + * parameters without changing the result beyond the first call. + * + * **Details** + * + * This is emitted as the MCP `idempotentHint`; unannotated tools default to + * `false`. + * + * **Example** (Marking a tool as idempotent) * - * @example * ```ts * import { Tool } from "effect/unstable/ai" * @@ -1717,17 +1821,24 @@ export const Destructive = Context.Reference("effect/ai/Tool/Destructiv * .annotate(Tool.Idempotent, true) * ``` * - * @since 1.0.0 * @category annotations + * @since 4.0.0 */ export const Idempotent = Context.Reference("effect/ai/Tool/Idempotent", { defaultValue: constFalse }) /** - * Annotation indicating whether a tool can handle arbitrary external data. + * Annotation indicating whether a tool may interact with arbitrary external + * data or systems. + * + * **Details** + * + * This is emitted as the MCP `openWorldHint`; unannotated tools default to + * `true`. + * + * **Example** (Disabling open-world access) * - * @example * ```ts * import { Tool } from "effect/unstable/ai" * @@ -1735,8 +1846,8 @@ export const Idempotent = Context.Reference("effect/ai/Tool/Idempotent" * .annotate(Tool.OpenWorld, false) * ``` * - * @since 1.0.0 * @category annotations + * @since 4.0.0 */ export const OpenWorld = Context.Reference("effect/ai/Tool/OpenWorld", { defaultValue: constTrue @@ -1745,6 +1856,8 @@ export const OpenWorld = Context.Reference("effect/ai/Tool/OpenWorld", /** * Annotation controlling whether strict JSON schema mode is enabled for a tool. * + * **Details** + * * When `true`, providers that support strict mode will send `strict: true` to * the model API (e.g. OpenAI's Structured Outputs). * @@ -1753,7 +1866,8 @@ export const OpenWorld = Context.Reference("effect/ai/Tool/OpenWorld", * When `undefined` (default), the provider's global configuration determines * the behavior (e.g. `Config.strictJsonSchema` for OpenAI). * - * @example + * **Example** (Disabling strict JSON schema mode) + * * ```ts * import { Tool } from "effect/unstable/ai" * @@ -1761,8 +1875,8 @@ export const OpenWorld = Context.Reference("effect/ai/Tool/OpenWorld", * .annotate(Tool.Strict, false) * ``` * - * @since 1.0.0 * @category annotations + * @since 4.0.0 */ export const Strict = Context.Reference("effect/ai/Tool/Strict", { defaultValue: () => undefined @@ -1771,8 +1885,20 @@ export const Strict = Context.Reference("effect/ai/Tool/Str /** * Returns the strict mode setting for a tool, or `undefined` if not set. * - * @since 1.0.0 - * @category utilities + * **When to use** + * + * Use to inspect the per-tool strict JSON Schema override attached through + * `Tool.Strict`. + * + * **Gotchas** + * + * `undefined` means no per-tool override is set. It is distinct from `false`; + * provider or global configuration determines the final behavior. + * + * @see {@link Strict} for the annotation read by this helper + * + * @category getters + * @since 4.0.0 */ export const getStrictMode = (tool: T): boolean | undefined => Context.get(tool.annotations, Strict) @@ -1853,11 +1979,21 @@ function filter(obj: any) { } /** - * **Unsafe**: This function will throw an error if an insecure property is - * found in the parsed JSON or if the provided JSON text is not parseable. + * Parses JSON text while rejecting prototype-pollution keys. + * + * **When to use** + * + * Use when you need a JSON parser that throws for invalid JSON or unsafe + * object shapes. + * + * **Gotchas** + * + * Invalid JSON throws through `JSON.parse`. Parsed objects containing an own + * `__proto__` property or a dangerous `constructor.prototype` shape throw a + * `SyntaxError`. * - * @since 1.0.0 - * @category utilities + * @category unsafe + * @since 4.0.0 */ export const unsafeSecureJsonParse = (text: string): unknown => { // Performance optimization, see https://github.com/fastify/secure-json-parse/pull/90 @@ -1871,18 +2007,38 @@ export const unsafeSecureJsonParse = (text: string): unknown => { } /** + * Type of the `EmptyParams` schema used for tools with no parameters. + * + * **Details** + * + * It is a record schema with string keys and `never` values, so the generated + * parameter schema accepts an empty object shape with no properties. + * + * @category schemas * @since 4.0.0 */ export interface EmptyParams extends Schema.$Record {} /** - * A schema for tools that accept no parameters. + * Schema for tools that accept no parameters. + * + * **When to use** + * + * Use when you need an explicit no-parameter `parameters` schema for a tool. + * + * **Details** + * + * This is `Schema.Record(Schema.String, Schema.Never)`, representing an empty + * object parameter shape with no additional properties. + * + * @see {@link make} for the tool constructor that defaults omitted parameters to this schema * + * @category schemas * @since 4.0.0 */ export const EmptyParams: EmptyParams = Schema.Record(Schema.String, Schema.Never) /** @internal */ -export function isEmptyParamsRecord(indexSignature: AST.IndexSignature): boolean { - return indexSignature.parameter === AST.string && AST.isNever(indexSignature.type) +export function isEmptyParamsRecord(indexSignature: SchemaAST.IndexSignature): boolean { + return indexSignature.parameter === SchemaAST.string && SchemaAST.isNever(indexSignature.type) } diff --git a/.opencode/node_modules/effect/src/unstable/ai/Toolkit.ts b/.opencode/node_modules/effect/src/unstable/ai/Toolkit.ts index b1c5fc30174a07495078b896117ac19b452dd32b..af3be989f98ee239f99a447eac32b77f69eb61a8 100644 --- a/.opencode/node_modules/effect/src/unstable/ai/Toolkit.ts +++ b/.opencode/node_modules/effect/src/unstable/ai/Toolkit.ts @@ -1,52 +1,21 @@ /** - * The `Toolkit` module allows for creating and implementing a collection of - * `Tool`s which can be used to enhance the capabilities of a large language - * model beyond simple text generation. + * Groups AI tools together with their handlers. * - * @example - * ```ts - * import { Effect, Schema } from "effect" - * import { Tool, Toolkit } from "effect/unstable/ai" - * - * // Create individual tools - * const GetCurrentTime = Tool.make("GetCurrentTime", { - * description: "Get the current timestamp", - * success: Schema.Number - * }) - * - * const GetWeather = Tool.make("GetWeather", { - * description: "Get weather for a location", - * parameters: Schema.Struct({ location: Schema.String }), - * success: Schema.Struct({ - * temperature: Schema.Number, - * condition: Schema.String - * }) - * }) + * A toolkit connects `Tool` schemas to the handler functions an application + * provides for a language model workflow. It can build a handler context or + * layer and execute tool calls by name. Execution validates parameters, runs the + * handler, encodes the result, supports preliminary streamed results, and + * applies the tool's failure mode. * - * // Create a toolkit with multiple tools - * const MyToolkit = Toolkit.make(GetCurrentTime, GetWeather) - * - * const MyToolkitLayer = MyToolkit.toLayer({ - * GetCurrentTime: () => Effect.succeed(Date.now()), - * GetWeather: ({ location }) => - * Effect.succeed({ - * temperature: 72, - * condition: "sunny" - * }) - * }) - * ``` - * - * @since 1.0.0 + * @since 4.0.0 */ import type * as Cause from "../../Cause.ts" import * as Context from "../../Context.ts" import * as Effect from "../../Effect.ts" +import * as Effectable from "../../Effectable.ts" import * as Fiber from "../../Fiber.ts" import { identity } from "../../Function.ts" -import type { Inspectable } from "../../Inspectable.ts" -import { PipeInspectableProto, YieldableProto } from "../../internal/core.ts" import * as Layer from "../../Layer.ts" -import type { Pipeable } from "../../Pipeable.ts" import * as Predicate from "../../Predicate.ts" import * as Queue from "../../Queue.ts" import * as Schema from "../../Schema.ts" @@ -61,51 +30,39 @@ const TypeId = "~effect/ai/Toolkit" as const * Represents a collection of tools which can be used to enhance the * capabilities of a large language model. * - * @example + * **Example** (Defining AI toolkits) + * * ```ts - * import { Effect, Schema } from "effect" + * import { Schema } from "effect" * import { Tool, Toolkit } from "effect/unstable/ai" * - * // Create individual tools - * const GetCurrentTime = Tool.make("GetCurrentTime", { - * description: "Get the current timestamp", - * success: Schema.Number + * const SearchDocs = Tool.make("SearchDocs", { + * description: "Search project documentation", + * parameters: Schema.Struct({ query: Schema.String }), + * success: Schema.Array(Schema.String) * }) * - * const GetWeather = Tool.make("GetWeather", { - * description: "Get weather for a location", - * parameters: Schema.Struct({ location: Schema.String }), - * success: Schema.Struct({ - * temperature: Schema.Number, - * condition: Schema.String - * }) + * const SummarizeText = Tool.make("SummarizeText", { + * description: "Summarize text", + * parameters: Schema.Struct({ text: Schema.String }), + * success: Schema.String * }) * - * // Create a toolkit with multiple tools - * const MyToolkit = Toolkit.make(GetCurrentTime, GetWeather) + * const AiToolkit = Toolkit.make(SearchDocs, SummarizeText) * - * const MyToolkitLayer = MyToolkit.toLayer({ - * GetCurrentTime: () => Effect.succeed(Date.now()), - * GetWeather: ({ location }) => - * Effect.succeed({ - * temperature: 72, - * condition: "sunny" - * }) - * }) + * console.log(Object.keys(AiToolkit.tools)) + * // ["SearchDocs", "SummarizeText"] * ``` * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface Toolkit> extends - Effect.Yieldable< - Toolkit, + Effect.Effect< WithHandler, never, Tool.HandlersFor - >, - Inspectable, - Pipeable + > { new(_: never): {} @@ -144,13 +101,15 @@ export interface Toolkit> extends /** * Context provided to tool handlers during execution. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface HandlerContext { /** * Emit a preliminary result during long-running tool calls. * + * **Details** + * * Preliminary results are streamed to the caller before the handler completes, * enabling real-time progress updates for lengthy operations. */ @@ -160,8 +119,8 @@ export interface HandlerContext { /** * Represents any `Toolkit` instance, used for generic constraints. * - * @since 1.0.0 * @category utility types + * @since 4.0.0 */ export interface Any { readonly [TypeId]: typeof TypeId @@ -172,8 +131,8 @@ export interface Any { * A utility type which can be used to extract the tool definitions from a * toolkit. * - * @since 1.0.0 * @category utility types + * @since 4.0.0 */ export type Tools = T extends Toolkit ? Tools : never @@ -181,8 +140,8 @@ export type Tools = T extends Toolkit ? Tools : never * A utility type which transforms either a record or an array of tools into * a record where keys are tool names and values are the tool instances. * - * @since 1.0.0 * @category utility types + * @since 4.0.0 */ export type ToolsByName = Tools extends Record ? { readonly [Name in keyof Tools]: Tools[Name] } @@ -192,11 +151,13 @@ export type ToolsByName = Tools extends Record ? /** * A utility type that maps tool names to their required handler functions. * + * **Details** + * * Handlers can return either the tool's custom failure type, an `AiErrorReason` * (which will be wrapped in `AiError`), or a full `AiError`. * - * @since 1.0.0 * @category utility types + * @since 4.0.0 */ export type HandlersFrom> = { readonly [Name in keyof Tools as Tool.RequiresHandler extends true ? Name : never]: ( @@ -212,8 +173,8 @@ export type HandlersFrom> = { /** * A toolkit instance with registered handlers ready for tool execution. * - * @since 1.0.0 * @category models + * @since 4.0.0 */ export interface WithHandler> { /** @@ -224,6 +185,8 @@ export interface WithHandler> { /** * Executes a tool call by name. * + * **Details** + * * Validates the input parameters, executes the corresponding handler, and * streams back both the typed result and encoded result. Streaming allows * handlers to emit preliminary results before completion. @@ -251,43 +214,17 @@ export interface WithHandler> { * A utility type which can be used to extract the tools from a toolkit with * handlers. * - * @since 1.0.0 * @category utility types + * @since 4.0.0 */ export type WithHandlerTools = T extends WithHandler ? Tools : never const Proto = { - ...YieldableProto, - ...PipeInspectableProto, - [TypeId]: TypeId, - of: identity, - toHandlers( - this: Toolkit>, - build: Record any> | Effect.Effect any>> - ) { - return Effect.gen({ self: this }, function*() { - const services = yield* Effect.context() - const handlers = Effect.isEffect(build) ? yield* build : build - const context = new Map() - for (const [name, handler] of Object.entries(handlers)) { - const tool = this.tools[name]! - context.set(tool.id, { name, handler, context: services }) - } - return Context.makeUnsafe(context) - }) - }, - toLayer( - this: Toolkit>, - build: Record any> | Effect.Effect any>> - ) { - return Layer.effectContext(this.toHandlers(build)) - }, - asEffect(this: Toolkit>) { - return Effect.gen({ self: this }, function*() { + ...Effectable.Prototype({ + label: "Toolkit", + evaluate: Effect.fnUntraced(function*(this: Toolkit>, parent) { const tools = this.tools - - const services = yield* Effect.context() - + const services = parent.context const schemasCache = new WeakMap readonly handler: Tool.Handler["handler"] @@ -441,6 +378,29 @@ const Proto = { handle: handle as any } satisfies WithHandler> }) + }), + [TypeId]: TypeId, + of: identity, + toHandlers( + this: Toolkit>, + build: Record any> | Effect.Effect any>> + ) { + return Effect.gen({ self: this }, function*() { + const services = yield* Effect.context() + const handlers = Effect.isEffect(build) ? yield* build : build + const context = new Map() + for (const [name, handler] of Object.entries(handlers)) { + const tool = this.tools[name]! + context.set(tool.id, { name, handler, context: services }) + } + return Context.makeUnsafe(context) + }) + }, + toLayer( + this: Toolkit>, + build: Record any> | Effect.Effect any>> + ) { + return Layer.effectContext(this.toHandlers(build)) }, toJSON(this: Toolkit): unknown { return { @@ -466,22 +426,27 @@ const resolveInput = >( /** * An empty toolkit with no tools. * - * Useful as a starting point for building toolkits or as a default value. Can - * be extended using the merge function to add tools. + * **When to use** + * + * Use when you need an empty starting point for building toolkits or a default + * toolkit value that can be extended with `merge`. * - * @since 1.0.0 * @category constructors + * @since 4.0.0 */ export const empty: Toolkit<{}> = makeProto({}) /** * Creates a new toolkit from the specified tools. * + * **Details** + * * This is the primary constructor for creating toolkits. It accepts multiple * tools and organizes them into a toolkit that can be provided to AI language * models. * - * @example + * **Example** (Creating a toolkit) + * * ```ts * import { Schema } from "effect" * import { Tool, Toolkit } from "effect/unstable/ai" @@ -503,8 +468,8 @@ export const empty: Toolkit<{}> = makeProto({}) * const toolkit = Toolkit.make(GetCurrentTime, GetWeather) * ``` * - * @since 1.0.0 * @category constructors + * @since 4.0.0 */ export const make = >( ...tools: Tools @@ -513,16 +478,16 @@ export const make = >( /** * A utility type which flattens a record type for improved IDE display. * - * @since 1.0.0 * @category utility types + * @since 4.0.0 */ export type SimplifyRecord = { [K in keyof T]: T[K] } & {} /** * A utility type which merges a union of tool records into a single record. * - * @since 1.0.0 * @category utility types + * @since 4.0.0 */ export type MergeRecords = { readonly [K in Extract]: Extract< @@ -535,8 +500,8 @@ export type MergeRecords = { * A utility type which merges the tools from multiple toolkits into a single * record. * - * @since 1.0.0 * @category utility types + * @since 4.0.0 */ export type MergedTools> = SimplifyRecord< MergeRecords> @@ -545,11 +510,14 @@ export type MergedTools> = SimplifyRecord< /** * Merges multiple toolkits into a single toolkit. * + * **Details** + * * Combines all tools from the provided toolkits into one unified toolkit. * If there are naming conflicts, tools from later toolkits will override * tools from earlier ones. * - * @example + * **Example** (Merging toolkits) + * * ```ts * import { Schema } from "effect" * import { Tool, Toolkit } from "effect/unstable/ai" @@ -567,8 +535,8 @@ export type MergedTools> = SimplifyRecord< * const combined = Toolkit.merge(mathToolkit, utilityToolkit) * ``` * - * @since 1.0.0 * @category constructors + * @since 4.0.0 */ export const merge = >( /** diff --git a/.opencode/node_modules/effect/src/unstable/ai/index.ts b/.opencode/node_modules/effect/src/unstable/ai/index.ts index a058a663b697e4b60368d8417823ccba90bd0240..abea583e37c4c829293eeaad87ad6bd9265e3b27 100644 --- a/.opencode/node_modules/effect/src/unstable/ai/index.ts +++ b/.opencode/node_modules/effect/src/unstable/ai/index.ts @@ -5,269 +5,31 @@ // @barrel: Auto-generated exports. Do not edit manually. /** - * The `AiError` module provides comprehensive, provider-agnostic error handling - * for AI operations. - * - * This module uses the `reason` pattern where `AiError` is a top-level - * wrapper error containing `module`, `method`, and a `reason` field that holds - * the semantic error. This design enables ergonomic error handling while - * preserving rich context about failures. - * - * ## Semantic Error Categories - * - * - **RateLimitError** - Request throttled (429s, provider-specific limits) - * - **QuotaExhaustedError** - Account/billing limits reached - * - **AuthenticationError** - Invalid/expired credentials - * - **ContentPolicyError** - Input/output violated content policy - * - **InvalidRequestError** - Malformed request parameters - * - **InvalidUserInputError** - Prompt contains unsupported content - * - **InternalProviderError** - Provider-side failures (5xx) - * - **NetworkError** - Transport-level failures - * - **InvalidOutputError** - LLM output parsing/validation failures - * - **StructuredOutputError** - LLM generated text that doesn't conform to structured output schema - * - **UnsupportedSchemaError** - Codec transformer rejected a schema with unsupported constructs - * - **UnknownError** - Catch-all for unknown errors - * - * ## Tool Call Errors - * - * - **ToolNotFoundError** - Model requested non-existent tool - * - **ToolParameterValidationError** - Tool call params failed validation - * - **InvalidToolResultError** - Tool handler returned invalid result - * - **ToolResultEncodingError** - Tool result encoding failed - * - **ToolConfigurationError** - Provider tool misconfigured - * - * ## Retryability - * - * Each reason type has an `isRetryable` getter indicating whether the error is - * transient. Some errors also provide a `retryAfter` duration hint. - * - * @example - * ```ts - * import { Effect, Match } from "effect" - * import type { AiError } from "effect/unstable/ai" - * - * // Handle errors using Match on the reason - * const handleAiError = Match.type().pipe( - * Match.when( - * { reason: { _tag: "RateLimitError" } }, - * (err) => Effect.logWarning(`Rate limited, retry after ${err.retryAfter}`) - * ), - * Match.when( - * { reason: { _tag: "AuthenticationError" } }, - * (err) => Effect.logError(`Auth failed: ${err.reason.kind}`) - * ), - * Match.when( - * { reason: { isRetryable: true } }, - * (err) => Effect.logWarning(`Transient error, retrying: ${err.message}`) - * ), - * Match.orElse((err) => Effect.logError(`Permanent error: ${err.message}`)) - * ) - * ``` - * - * @example - * ```ts - * import { Duration, Effect } from "effect" - * import { AiError } from "effect/unstable/ai" - * - * // Create an AiError with a reason - * const error = AiError.make({ - * module: "OpenAI", - * method: "completion", - * reason: new AiError.RateLimitError({ - * retryAfter: Duration.seconds(60) - * }) - * }) - * - * console.log(error.isRetryable) // true - * console.log(error.message) // "OpenAI.completion: Rate limit exceeded. Retry after 1 minute" - * ``` - * - * @since 1.0.0 + * @since 4.0.0 */ export * as AiError from "./AiError.ts" /** - * Provides a codec transformation for Anthropic structured output. - * - * Anthropic's API has specific constraints on JSON schema support that differ - * from the full JSON Schema specification. This module transforms Effect - * `Schema.Codec` types into a form compatible with Anthropic's structured - * output requirements by: - * - * - Converting tuples to objects with string keys (tuples are unsupported) - * - Converting optional properties to nullable unions (`T | null`) - * - Converting index signatures (records) to arrays of key-value pairs - * - Converting `oneOf` unions to `anyOf` unions - * - Stripping unsupported annotations and preserving only Anthropic-compatible - * formats and descriptions - * - * @since 1.0.0 + * @since 4.0.0 */ export * as AnthropicStructuredOutput from "./AnthropicStructuredOutput.ts" /** - * The `Chat` module provides a stateful conversation interface for AI language - * models. - * - * This module enables persistent chat sessions that maintain conversation - * history, support tool calling, and offer both streaming and non-streaming - * text generation. It integrates seamlessly with the Effect AI ecosystem, - * providing type-safe conversational AI capabilities. - * - * @example - * ```ts - * import { Effect } from "effect" - * import { Chat } from "effect/unstable/ai" - * - * // Create a new chat session - * const program = Effect.gen(function*() { - * const chat = yield* Chat.empty - * - * // Send a message and get response - * const response = yield* chat.generateText({ - * prompt: "Hello! What can you help me with?" - * }) - * - * console.log(response.content) - * - * return response - * }) - * ``` - * - * @example - * ```ts - * import { Effect, Stream } from "effect" - * import { Chat } from "effect/unstable/ai" - * - * // Streaming chat with tool support - * const streamingChat = Effect.gen(function*() { - * const chat = yield* Chat.empty - * - * yield* chat.streamText({ - * prompt: "Generate a creative story" - * }).pipe(Stream.runForEach((part) => Effect.sync(() => console.log(part)))) - * }) - * ``` - * * @since 4.0.0 */ export * as Chat from "./Chat.ts" /** - * The `EmbeddingModel` module provides provider-agnostic text embedding capabilities. - * - * @example - * ```ts - * import { Effect } from "effect" - * import { EmbeddingModel } from "effect/unstable/ai" - * - * const program = Effect.gen(function*() { - * const model = yield* EmbeddingModel.EmbeddingModel - * return yield* model.embed("hello world") - * }) - * ``` - * * @since 4.0.0 */ export * as EmbeddingModel from "./EmbeddingModel.ts" /** - * The `IdGenerator` module provides a pluggable system for generating unique identifiers - * for tool calls and other items in the Effect AI SDKs. - * - * This module offers a flexible and configurable approach to ID generation, supporting - * custom alphabets, prefixes, separators, and sizes. - * - * @example - * ```ts - * import { Effect } from "effect" - * import { IdGenerator } from "effect/unstable/ai" - * - * // Using the default ID generator - * const program = Effect.gen(function*() { - * const idGen = yield* IdGenerator.IdGenerator - * const toolCallId = yield* idGen.generateId() - * console.log(toolCallId) // "id_A7xK9mP2qR5tY8uV" - * return toolCallId - * }).pipe(Effect.provideService( - * IdGenerator.IdGenerator, - * IdGenerator.defaultIdGenerator - * )) - * ``` - * - * @example - * ```ts - * import { Effect } from "effect" - * import { IdGenerator } from "effect/unstable/ai" - * - * // Creating a custom ID generator for AI tool calls - * const customLayer = IdGenerator.layer({ - * alphabet: "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789", - * prefix: "tool_call", - * separator: "-", - * size: 12 - * }) - * - * const program = Effect.gen(function*() { - * const idGen = yield* IdGenerator.IdGenerator - * const id = yield* idGen.generateId() - * console.log(id) // "tool_call-A7XK9MP2QR5T" - * return id - * }).pipe(Effect.provide(customLayer)) - * ``` - * * @since 4.0.0 */ export * as IdGenerator from "./IdGenerator.ts" /** - * The `LanguageModel` module provides AI text generation capabilities with tool - * calling support. - * - * This module offers a comprehensive interface for interacting with large - * language models, supporting both streaming and non-streaming text generation, - * structured output generation, and tool calling functionality. It provides a - * unified API that can be implemented by different AI providers while - * maintaining type safety and effect management. - * - * @example - * ```ts - * import { Effect } from "effect" - * import { LanguageModel } from "effect/unstable/ai" - * - * // Basic text generation - * const program = Effect.gen(function*() { - * const response = yield* LanguageModel.generateText({ - * prompt: "Explain quantum computing" - * }) - * - * console.log(response.text) - * - * return response - * }) - * ``` - * - * @example - * ```ts - * import { Effect, Schema } from "effect" - * import { LanguageModel } from "effect/unstable/ai" - * - * // Structured output generation - * const ContactSchema = Schema.Struct({ - * name: Schema.String, - * email: Schema.String - * }) - * - * const extractContact = Effect.gen(function*() { - * const response = yield* LanguageModel.generateObject({ - * prompt: "Extract contact: John Doe, john@example.com", - * schema: ContactSchema - * }) - * - * return response.value - * }) - * ``` - * * @since 4.0.0 */ export * as LanguageModel from "./LanguageModel.ts" @@ -283,126 +45,22 @@ export * as McpSchema from "./McpSchema.ts" export * as McpServer from "./McpServer.ts" /** - * The `Model` module provides a unified interface for AI service providers. - * - * This module enables creation of provider-specific AI models that can be used - * interchangeably within the Effect AI ecosystem. It combines Layer - * functionality with provider identification, allowing for seamless switching - * between different AI service providers while maintaining type safety. - * - * @example - * ```ts - * import type { Layer } from "effect" - * import { Effect } from "effect" - * import { LanguageModel, Model } from "effect/unstable/ai" - * - * declare const myAnthropicLayer: Layer.Layer - * - * const anthropicModel = Model.make("anthropic", "claude-3-5-haiku", myAnthropicLayer) - * - * const program = Effect.gen(function*() { - * const response = yield* LanguageModel.generateText({ - * prompt: "Hello, world!" - * }) - * return response.text - * }).pipe( - * Effect.provide(anthropicModel) - * ) - * ``` - * * @since 4.0.0 */ export * as Model from "./Model.ts" /** - * Provides codec transformations for OpenAI structured output. - * - * @since 1.0.0 + * @since 4.0.0 */ export * as OpenAiStructuredOutput from "./OpenAiStructuredOutput.ts" /** - * The `Prompt` module provides several data structures to simplify creating and - * combining prompts. - * - * This module defines the complete structure of a conversation with a large - * language model, including messages, content parts, and provider-specific - * options. It supports rich content types like text, files, tool calls, and - * reasoning. - * - * @example - * ```ts - * import { Prompt } from "effect/unstable/ai" - * - * // Create a structured conversation - * const conversation = Prompt.make([ - * { - * role: "system", - * content: "You are a helpful assistant specialized in mathematics." - * }, - * { - * role: "user", - * content: [{ - * type: "text", - * text: "What is the derivative of x²?" - * }] - * }, - * { - * role: "assistant", - * content: [{ - * type: "text", - * text: "The derivative of x² is 2x." - * }] - * } - * ]) - * ``` - * - * @example - * ```ts - * import { Prompt } from "effect/unstable/ai" - * - * // Concatenate multiple prompts together sequentially - * const systemPrompt = Prompt.make([{ - * role: "system", - * content: "You are a coding assistant." - * }]) - * - * const userPrompt = Prompt.make("Help me write a function") - * - * const combined = Prompt.concat(systemPrompt, userPrompt) - * ``` - * * @since 4.0.0 */ export * as Prompt from "./Prompt.ts" /** - * The `Response` module provides data structures to represent responses from - * large language models. - * - * This module defines the complete structure of AI model responses, including - * various content parts for text, reasoning, tool calls, files, and metadata, - * supporting both streaming and non-streaming responses. - * - * @example - * ```ts - * import { Response } from "effect/unstable/ai" - * - * // Create a simple text response part - * const textResponse = Response.makePart("text", { - * text: "The weather is sunny today!" - * }) - * - * // Create a tool call response part - * const toolCallResponse = Response.makePart("tool-call", { - * id: "call_123", - * name: "get_weather", - * params: { city: "San Francisco" }, - * providerExecuted: false - * }) - * ``` - * - * @since 1.0.0 + * @since 4.0.0 */ export * as Response from "./Response.ts" @@ -412,147 +70,21 @@ export * as Response from "./Response.ts" export * as ResponseIdTracker from "./ResponseIdTracker.ts" /** - * The `Telemetry` module provides OpenTelemetry integration for operations - * performed against a large language model provider by defining telemetry - * attributes and utilities that follow the OpenTelemetry GenAI semantic - * conventions. - * - * @example - * ```ts - * import { Effect } from "effect" - * import { Telemetry } from "effect/unstable/ai" - * - * // Add telemetry attributes to a span - * const addTelemetry = Effect.gen(function*() { - * const span = yield* Effect.currentSpan - * - * Telemetry.addGenAIAnnotations(span, { - * system: "openai", - * operation: { name: "chat" }, - * request: { - * model: "gpt-4", - * temperature: 0.7, - * maxTokens: 1000 - * }, - * usage: { - * inputTokens: 100, - * outputTokens: 50 - * } - * }) - * }) - * ``` - * * @since 4.0.0 */ export * as Telemetry from "./Telemetry.ts" /** - * The `Tokenizer` module provides tokenization and text truncation capabilities - * for large language model text processing workflows. - * - * This module offers services for converting text into tokens and truncating - * prompts based on token limits, essential for managing context length - * constraints in large language models. - * - * @example - * ```ts - * import { Effect } from "effect" - * import { Tokenizer } from "effect/unstable/ai" - * - * const tokenizeText = Effect.gen(function*() { - * const tokenizer = yield* Tokenizer.Tokenizer - * const tokens = yield* tokenizer.tokenize("Hello, world!") - * console.log(`Token count: ${tokens.length}`) - * return tokens - * }) - * ``` - * - * @example - * ```ts - * import { Effect } from "effect" - * import { Tokenizer } from "effect/unstable/ai" - * - * // Truncate a prompt to fit within token limits - * const truncatePrompt = Effect.gen(function*() { - * const tokenizer = yield* Tokenizer.Tokenizer - * const longPrompt = "This is a very long prompt..." - * const truncated = yield* tokenizer.truncate(longPrompt, 100) - * return truncated - * }) - * ``` - * * @since 4.0.0 */ export * as Tokenizer from "./Tokenizer.ts" /** - * The `Tool` module provides functionality for defining and managing tools - * that language models can call to augment their capabilities. - * - * This module enables creation of both user-defined and provider-defined tools, - * with full schema validation, type safety, and handler support. Tools allow - * AI models to perform actions like searching databases, calling APIs, or - * executing code within your application context. - * - * @example - * ```ts - * import { Schema } from "effect" - * import { Tool } from "effect/unstable/ai" - * - * // Define a simple calculator tool - * const Calculator = Tool.make("Calculator", { - * description: "Performs basic arithmetic operations", - * parameters: Schema.Struct({ - * operation: Schema.Literals(["add", "subtract", "multiply", "divide"]), - * a: Schema.Number, - * b: Schema.Number - * }), - * success: Schema.Number - * }) - * ``` - * - * @since 1.0.0 + * @since 4.0.0 */ export * as Tool from "./Tool.ts" /** - * The `Toolkit` module allows for creating and implementing a collection of - * `Tool`s which can be used to enhance the capabilities of a large language - * model beyond simple text generation. - * - * @example - * ```ts - * import { Effect, Schema } from "effect" - * import { Tool, Toolkit } from "effect/unstable/ai" - * - * // Create individual tools - * const GetCurrentTime = Tool.make("GetCurrentTime", { - * description: "Get the current timestamp", - * success: Schema.Number - * }) - * - * const GetWeather = Tool.make("GetWeather", { - * description: "Get weather for a location", - * parameters: Schema.Struct({ location: Schema.String }), - * success: Schema.Struct({ - * temperature: Schema.Number, - * condition: Schema.String - * }) - * }) - * - * // Create a toolkit with multiple tools - * const MyToolkit = Toolkit.make(GetCurrentTime, GetWeather) - * - * const MyToolkitLayer = MyToolkit.toLayer({ - * GetCurrentTime: () => Effect.succeed(Date.now()), - * GetWeather: ({ location }) => - * Effect.succeed({ - * temperature: 72, - * condition: "sunny" - * }) - * }) - * ``` - * - * @since 1.0.0 + * @since 4.0.0 */ export * as Toolkit from "./Toolkit.ts" diff --git a/.opencode/node_modules/effect/src/unstable/cli/Argument.ts b/.opencode/node_modules/effect/src/unstable/cli/Argument.ts index 1a826cb5320ebedd482d42d710d90063aba21749..3ead11ab1d07f4376c84e17371814f0463e955d0 100644 --- a/.opencode/node_modules/effect/src/unstable/cli/Argument.ts +++ b/.opencode/node_modules/effect/src/unstable/cli/Argument.ts @@ -1,4 +1,12 @@ /** + * Defines typed positional arguments for Effect CLI applications. + * + * Arguments consume ordered values after a command name and its flags, then + * parse them into the types a command handler expects. This module includes + * constructors for common argument shapes, plus helpers for optional or + * variadic arguments, schema validation, transformations, defaults, config + * fallbacks, and prompts for missing values. + * * @since 4.0.0 */ import type * as Config from "../../Config.ts" @@ -19,13 +27,15 @@ import type * as Primitive from "./Primitive.ts" /** * Represents a positional command-line argument. * - * Note: `boolean` is intentionally omitted from Argument constructors. - * Positional boolean arguments are ambiguous in CLI design since there's - * no flag name to negate (e.g., `--no-verbose`). Use Flag.boolean instead, - * or use Argument.choice with explicit "true"/"false" strings if needed. + * **Gotchas** + * + * `boolean` is intentionally omitted from Argument constructors. Positional + * boolean arguments are ambiguous in CLI design since there is no flag name to + * negate (for example, `--no-verbose`). Use Flag.boolean instead, or use + * Argument.choice with explicit "true" / "false" strings if needed. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface Argument extends Param.Param {} @@ -36,37 +46,40 @@ export interface Argument extends Param.Param { /** * Creates a positional string argument. * - * @example + * **Example** (Creating a string argument) + * * ```ts * import { Argument } from "effect/unstable/cli" * * const filename = Argument.string("filename") * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const string = (name: string): Argument => Param.string(Param.argumentKind, name) /** * Creates a positional integer argument. * - * @example + * **Example** (Creating an integer argument) + * * ```ts * import { Argument } from "effect/unstable/cli" * * const count = Argument.integer("count") * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const integer = (name: string): Argument => Param.integer(Param.argumentKind, name) /** * Creates a positional file path argument. * - * @example + * **Example** (Creating file path arguments) + * * ```ts * import { Argument } from "effect/unstable/cli" * @@ -74,8 +87,8 @@ export const integer = (name: string): Argument => Param.integer(Param.a * const outputFile = Argument.file("output", { mustExist: false }) // Must not exist * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const file = (name: string, options?: { readonly mustExist?: boolean | undefined @@ -84,15 +97,16 @@ export const file = (name: string, options?: { /** * Creates a positional directory path argument. * - * @example + * **Example** (Creating a directory path argument) + * * ```ts * import { Argument } from "effect/unstable/cli" * * const workspace = Argument.directory("workspace", { mustExist: true }) // Must exist * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const directory = (name: string, options?: { readonly mustExist?: boolean | undefined @@ -101,45 +115,48 @@ export const directory = (name: string, options?: { /** * Creates a positional float argument. * - * @example + * **Example** (Creating a float argument) + * * ```ts * import { Argument } from "effect/unstable/cli" * * const ratio = Argument.float("ratio") * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const float = (name: string): Argument => Param.float(Param.argumentKind, name) /** * Creates a positional date argument. * - * @example + * **Example** (Creating a date argument) + * * ```ts * import { Argument } from "effect/unstable/cli" * * const startDate = Argument.date("start-date") * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const date = (name: string): Argument => Param.date(Param.argumentKind, name) /** * Creates a positional choice argument. * - * @example + * **Example** (Creating a choice argument) + * * ```ts * import { Argument } from "effect/unstable/cli" * * const environment = Argument.choice("environment", ["dev", "staging", "prod"]) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const choice = >( name: string, @@ -149,15 +166,16 @@ export const choice = >( /** * Creates a positional path argument. * - * @example + * **Example** (Creating a path argument) + * * ```ts * import { Argument } from "effect/unstable/cli" * * const configPath = Argument.path("config") * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const path = (name: string, options?: { pathType?: "file" | "directory" | "either" @@ -167,45 +185,54 @@ export const path = (name: string, options?: { /** * Creates a positional redacted argument that obscures its value. * - * @example + * **Example** (Creating a redacted argument) + * * ```ts * import { Argument } from "effect/unstable/cli" * * const secret = Argument.redacted("secret") * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const redacted = (name: string): Argument> => Param.redacted(Param.argumentKind, name) /** * Creates a positional argument that reads file content as a string. * - * @example + * **Example** (Reading file text) + * * ```ts * import { Argument } from "effect/unstable/cli" * * const config = Argument.fileText("config-file") * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fileText = (name: string): Argument => Param.fileText(Param.argumentKind, name) /** - * Creates a positional argument that reads and validates file content using a schema. + * Creates a positional argument that reads a file and parses its content. + * + * **Details** + * + * The parser is chosen from the explicit `format` option or, when omitted, the + * file extension. The parsed value is `unknown`; use `fileSchema` when the + * parsed content should also be decoded with a Schema. + * + * **Example** (Parsing file content) * - * @example * ```ts * import { Argument } from "effect/unstable/cli" * * const config = Argument.fileParse("config", { format: "json" }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fileParse = ( name: string, @@ -215,7 +242,8 @@ export const fileParse = ( /** * Creates a positional argument that reads and validates file content using a schema. * - * @example + * **Example** (Validating file content with a schema) + * * ```ts * import { Schema } from "effect" * import { Argument } from "effect/unstable/cli" @@ -228,8 +256,8 @@ export const fileParse = ( * const config = Argument.fileSchema("config", ConfigSchema) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fileSchema = ( name: string, @@ -240,7 +268,8 @@ export const fileSchema = ( /** * Creates an empty sentinel argument that always fails to parse. * - * @example + * **Example** (Creating a sentinel argument) + * * ```ts * import { Argument } from "effect/unstable/cli" * @@ -248,8 +277,8 @@ export const fileSchema = ( * const noArg = Argument.none * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const none: Argument = Param.none(Param.argumentKind) @@ -260,22 +289,24 @@ export const none: Argument = Param.none(Param.argumentKind) /** * Makes a positional argument optional. * - * @example + * **Example** (Making an argument optional) + * * ```ts * import { Argument } from "effect/unstable/cli" * * const optionalVersion = Argument.string("version").pipe(Argument.optional) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const optional = (arg: Argument): Argument> => Param.optional(arg) /** * Adds a description to a positional argument. * - * @example + * **Example** (Adding an argument description) + * * ```ts * import { Argument } from "effect/unstable/cli" * @@ -284,14 +315,15 @@ export const optional = (arg: Argument): Argument> => Par * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const withDescription: { /** * Adds a description to a positional argument. * - * @example + * **Example** (Adding an argument description) + * * ```ts * import { Argument } from "effect/unstable/cli" * @@ -300,14 +332,15 @@ export const withDescription: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (description: string): (self: Argument) => Argument /** * Adds a description to a positional argument. * - * @example + * **Example** (Adding an argument description) + * * ```ts * import { Argument } from "effect/unstable/cli" * @@ -316,8 +349,8 @@ export const withDescription: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Argument, description: string): Argument } = dual(2, (self: Argument, description: string) => Param.withDescription(self, description)) @@ -325,43 +358,46 @@ export const withDescription: { /** * Provides a default value for a positional argument. * - * @example + * **Example** (Providing a default value) + * * ```ts * import { Argument } from "effect/unstable/cli" * * const port = Argument.integer("port").pipe(Argument.withDefault(8080)) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const withDefault: { /** * Provides a default value for a positional argument. * - * @example + * **Example** (Providing a default value) + * * ```ts * import { Argument } from "effect/unstable/cli" * * const port = Argument.integer("port").pipe(Argument.withDefault(8080)) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (defaultValue: B | Effect.Effect): (self: Argument) => Argument /** * Provides a default value for a positional argument. * - * @example + * **Example** (Providing a default value) + * * ```ts * import { Argument } from "effect/unstable/cli" * * const port = Argument.integer("port").pipe(Argument.withDefault(8080)) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ ( self: Argument, @@ -372,7 +408,8 @@ export const withDefault: { /** * Adds a fallback config that is loaded when a required argument is missing. * - * @example + * **Example** (Loading a fallback config) + * * ```ts * import { Config } from "effect" * import { Argument } from "effect/unstable/cli" @@ -382,14 +419,15 @@ export const withDefault: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const withFallbackConfig: { /** * Adds a fallback config that is loaded when a required argument is missing. * - * @example + * **Example** (Loading a fallback config) + * * ```ts * import { Config } from "effect" * import { Argument } from "effect/unstable/cli" @@ -399,14 +437,15 @@ export const withFallbackConfig: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (config: Config.Config): (self: Argument) => Argument /** * Adds a fallback config that is loaded when a required argument is missing. * - * @example + * **Example** (Loading a fallback config) + * * ```ts * import { Config } from "effect" * import { Argument } from "effect/unstable/cli" @@ -416,8 +455,8 @@ export const withFallbackConfig: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Argument, config: Config.Config): Argument } = dual(2, (self: Argument, config: Config.Config) => Param.withFallbackConfig(self, config)) @@ -425,7 +464,8 @@ export const withFallbackConfig: { /** * Adds a fallback prompt that is shown when a required argument is missing. * - * @example + * **Example** (Showing a fallback prompt) + * * ```ts * import { Argument, Prompt } from "effect/unstable/cli" * @@ -434,14 +474,15 @@ export const withFallbackConfig: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const withFallbackPrompt: { /** * Adds a fallback prompt that is shown when a required argument is missing. * - * @example + * **Example** (Showing a fallback prompt) + * * ```ts * import { Argument, Prompt } from "effect/unstable/cli" * @@ -450,14 +491,15 @@ export const withFallbackPrompt: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (prompt: Param.FallbackPrompt): (self: Argument) => Argument /** * Adds a fallback prompt that is shown when a required argument is missing. * - * @example + * **Example** (Showing a fallback prompt) + * * ```ts * import { Argument, Prompt } from "effect/unstable/cli" * @@ -466,8 +508,8 @@ export const withFallbackPrompt: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Argument, prompt: Param.FallbackPrompt): Argument } = dual(2, (self: Argument, prompt: Param.FallbackPrompt) => Param.withFallbackPrompt(self, prompt)) @@ -475,7 +517,8 @@ export const withFallbackPrompt: { /** * Creates a variadic positional argument that accepts multiple values. * - * @example + * **Example** (Accepting multiple values) + * * ```ts * import { Argument } from "effect/unstable/cli" * @@ -493,14 +536,15 @@ export const withFallbackPrompt: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const variadic: { /** * Creates a variadic positional argument that accepts multiple values. * - * @example + * **Example** (Accepting multiple values) + * * ```ts * import { Argument } from "effect/unstable/cli" * @@ -518,14 +562,15 @@ export const variadic: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (options?: Param.VariadicParamOptions | undefined): (self: Argument) => Argument> /** * Creates a variadic positional argument that accepts multiple values. * - * @example + * **Example** (Accepting multiple values) + * * ```ts * import { Argument } from "effect/unstable/cli" * @@ -543,11 +588,11 @@ export const variadic: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Argument, options?: Param.VariadicParamOptions | undefined): Argument> -} = dual(2, ( +} = dual((args) => Param.isParam(args[0]), ( self: Argument, options?: Param.VariadicParamOptions | undefined ): Argument> => Param.variadic(self, options)) @@ -555,7 +600,8 @@ export const variadic: { /** * Transforms the parsed value of a positional argument. * - * @example + * **Example** (Mapping parsed values) + * * ```ts * import { Argument } from "effect/unstable/cli" * @@ -564,14 +610,15 @@ export const variadic: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const map: { /** * Transforms the parsed value of a positional argument. * - * @example + * **Example** (Mapping parsed values) + * * ```ts * import { Argument } from "effect/unstable/cli" * @@ -580,14 +627,15 @@ export const map: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (f: (a: A) => B): (self: Argument) => Argument /** * Transforms the parsed value of a positional argument. * - * @example + * **Example** (Mapping parsed values) + * * ```ts * import { Argument } from "effect/unstable/cli" * @@ -596,8 +644,8 @@ export const map: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Argument, f: (a: A) => B): Argument } = dual(2, (self: Argument, f: (a: A) => B) => Param.map(self, f)) @@ -605,7 +653,8 @@ export const map: { /** * Transforms the parsed value of a positional argument using an effectful function. * - * @example + * **Example** (Validating values effectfully) + * * ```ts * import { Effect } from "effect" * import { Argument, CliError } from "effect/unstable/cli" @@ -623,14 +672,15 @@ export const map: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const mapEffect: { /** * Transforms the parsed value of a positional argument using an effectful function. * - * @example + * **Example** (Validating values effectfully) + * * ```ts * import { Effect } from "effect" * import { Argument, CliError } from "effect/unstable/cli" @@ -648,14 +698,15 @@ export const mapEffect: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (f: (a: A) => Effect.Effect): (self: Argument) => Argument /** * Transforms the parsed value of a positional argument using an effectful function. * - * @example + * **Example** (Validating values effectfully) + * * ```ts * import { Effect } from "effect" * import { Argument, CliError } from "effect/unstable/cli" @@ -673,8 +724,8 @@ export const mapEffect: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ ( self: Argument, @@ -688,7 +739,8 @@ export const mapEffect: { /** * Transforms the parsed value of a positional argument using a function that may throw. * - * @example + * **Example** (Mapping values that may throw) + * * ```ts * import { Argument } from "effect/unstable/cli" * @@ -701,14 +753,15 @@ export const mapEffect: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const mapTryCatch: { /** * Transforms the parsed value of a positional argument using a function that may throw. * - * @example + * **Example** (Mapping values that may throw) + * * ```ts * import { Argument } from "effect/unstable/cli" * @@ -721,14 +774,15 @@ export const mapTryCatch: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (f: (a: A) => B, onError: (error: unknown) => string): (self: Argument) => Argument /** * Transforms the parsed value of a positional argument using a function that may throw. * - * @example + * **Example** (Mapping values that may throw) + * * ```ts * import { Argument } from "effect/unstable/cli" * @@ -741,8 +795,8 @@ export const mapTryCatch: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Argument, f: (a: A) => B, onError: (error: unknown) => string): Argument } = dual(3, ( @@ -754,43 +808,46 @@ export const mapTryCatch: { /** * Creates a variadic argument that requires at least n values. * - * @example + * **Example** (Requiring a minimum number of values) + * * ```ts * import { Argument } from "effect/unstable/cli" * * const files = Argument.string("files").pipe(Argument.atLeast(1)) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const atLeast: { /** * Creates a variadic argument that requires at least n values. * - * @example + * **Example** (Requiring a minimum number of values) + * * ```ts * import { Argument } from "effect/unstable/cli" * * const files = Argument.string("files").pipe(Argument.atLeast(1)) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (min: number): (self: Argument) => Argument> /** * Creates a variadic argument that requires at least n values. * - * @example + * **Example** (Requiring a minimum number of values) + * * ```ts * import { Argument } from "effect/unstable/cli" * * const files = Argument.string("files").pipe(Argument.atLeast(1)) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Argument, min: number): Argument> } = dual(2, (self: Argument, min: number) => Param.atLeast(self, min)) @@ -798,43 +855,46 @@ export const atLeast: { /** * Creates a variadic argument that accepts at most n values. * - * @example + * **Example** (Limiting the maximum number of values) + * * ```ts * import { Argument } from "effect/unstable/cli" * * const files = Argument.string("files").pipe(Argument.atMost(5)) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const atMost: { /** * Creates a variadic argument that accepts at most n values. * - * @example + * **Example** (Limiting the maximum number of values) + * * ```ts * import { Argument } from "effect/unstable/cli" * * const files = Argument.string("files").pipe(Argument.atMost(5)) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (max: number): (self: Argument) => Argument> /** * Creates a variadic argument that accepts at most n values. * - * @example + * **Example** (Limiting the maximum number of values) + * * ```ts * import { Argument } from "effect/unstable/cli" * * const files = Argument.string("files").pipe(Argument.atMost(5)) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Argument, max: number): Argument> } = dual(2, (self: Argument, max: number) => Param.atMost(self, max)) @@ -842,43 +902,46 @@ export const atMost: { /** * Creates a variadic argument that accepts between min and max values. * - * @example + * **Example** (Requiring a range of values) + * * ```ts * import { Argument } from "effect/unstable/cli" * * const files = Argument.string("files").pipe(Argument.between(1, 5)) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const between: { /** * Creates a variadic argument that accepts between min and max values. * - * @example + * **Example** (Requiring a range of values) + * * ```ts * import { Argument } from "effect/unstable/cli" * * const files = Argument.string("files").pipe(Argument.between(1, 5)) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (min: number, max: number): (self: Argument) => Argument> /** * Creates a variadic argument that accepts between min and max values. * - * @example + * **Example** (Requiring a range of values) + * * ```ts * import { Argument } from "effect/unstable/cli" * * const files = Argument.string("files").pipe(Argument.between(1, 5)) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Argument, min: number, max: number): Argument> } = dual(3, (self: Argument, min: number, max: number) => Param.between(self, min, max)) @@ -886,7 +949,8 @@ export const between: { /** * Validates parsed values against a Schema. * - * @example + * **Example** (Validating parsed values with a schema) + * * ```ts * import { Schema } from "effect" * import { Argument } from "effect/unstable/cli" @@ -896,14 +960,15 @@ export const between: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const withSchema: { /** * Validates parsed values against a Schema. * - * @example + * **Example** (Validating parsed values with a schema) + * * ```ts * import { Schema } from "effect" * import { Argument } from "effect/unstable/cli" @@ -913,14 +978,15 @@ export const withSchema: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (schema: Schema.Codec): (self: Argument) => Argument /** * Validates parsed values against a Schema. * - * @example + * **Example** (Validating parsed values with a schema) + * * ```ts * import { Schema } from "effect" * import { Argument } from "effect/unstable/cli" @@ -930,8 +996,8 @@ export const withSchema: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Argument, schema: Schema.Codec): Argument } = dual(2, (self: Argument, schema: Schema.Codec) => Param.withSchema(self, schema)) @@ -939,7 +1005,8 @@ export const withSchema: { /** * Creates a positional choice argument with custom value mapping. * - * @example + * **Example** (Mapping choices to values) + * * ```ts * import { Argument } from "effect/unstable/cli" * @@ -951,8 +1018,8 @@ export const withSchema: { * ]) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const choiceWithValue = >( name: string, @@ -966,10 +1033,13 @@ export const choiceWithValue = ` shows `FILE` as the metavar. * - * @example + * **Example** (Setting a metavar) + * * ```ts * import { Argument } from "effect/unstable/cli" * @@ -978,8 +1048,8 @@ export const choiceWithValue = ` shows `FILE` as the metavar. * - * @example + * **Example** (Setting a metavar) + * * ```ts * import { Argument } from "effect/unstable/cli" * @@ -1001,8 +1074,8 @@ export const withMetavar: { * ) * ``` * - * @since 4.0.0 * @category metadata + * @since 4.0.0 */ (metavar: string): (self: Argument) => Argument // ------------------------------------------------------------------------------------- @@ -1012,10 +1085,13 @@ export const withMetavar: { /** * Sets a custom metavar (placeholder name) for the argument in help documentation. * + * **Details** + * * The metavar is displayed in usage text to indicate what value the user should provide. * For example, `` shows `FILE` as the metavar. * - * @example + * **Example** (Setting a metavar) + * * ```ts * import { Argument } from "effect/unstable/cli" * @@ -1024,8 +1100,8 @@ export const withMetavar: { * ) * ``` * - * @since 4.0.0 * @category metadata + * @since 4.0.0 */ (self: Argument, metavar: string): Argument } = dual(2, (self: Argument, metavar: string) => Param.withMetavar(self, metavar)) @@ -1033,7 +1109,8 @@ export const withMetavar: { /** * Filters parsed values, failing with a custom error message if the predicate returns false. * - * @example + * **Example** (Filtering parsed values) + * * ```ts * import { Argument } from "effect/unstable/cli" * @@ -1045,14 +1122,15 @@ export const withMetavar: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const filter: { /** * Filters parsed values, failing with a custom error message if the predicate returns false. * - * @example + * **Example** (Filtering parsed values) + * * ```ts * import { Argument } from "effect/unstable/cli" * @@ -1064,14 +1142,15 @@ export const filter: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (predicate: (a: A) => boolean, onFalse: (a: A) => string): (self: Argument) => Argument /** * Filters parsed values, failing with a custom error message if the predicate returns false. * - * @example + * **Example** (Filtering parsed values) + * * ```ts * import { Argument } from "effect/unstable/cli" * @@ -1083,8 +1162,8 @@ export const filter: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Argument, predicate: (a: A) => boolean, onFalse: (a: A) => string): Argument } = dual(3, ( @@ -1097,7 +1176,8 @@ export const filter: { * Filters and transforms parsed values, failing with a custom error message * if the filter function returns None. * - * @example + * **Example** (Filtering and mapping parsed values) + * * ```ts * import { Option } from "effect" * import { Argument } from "effect/unstable/cli" @@ -1110,15 +1190,16 @@ export const filter: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const filterMap: { /** * Filters and transforms parsed values, failing with a custom error message * if the filter function returns None. * - * @example + * **Example** (Filtering and mapping parsed values) + * * ```ts * import { Option } from "effect" * import { Argument } from "effect/unstable/cli" @@ -1131,15 +1212,16 @@ export const filterMap: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (f: (a: A) => Option.Option, onNone: (a: A) => string): (self: Argument) => Argument /** * Filters and transforms parsed values, failing with a custom error message * if the filter function returns None. * - * @example + * **Example** (Filtering and mapping parsed values) + * * ```ts * import { Option } from "effect" * import { Argument } from "effect/unstable/cli" @@ -1152,8 +1234,8 @@ export const filterMap: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Argument, f: (a: A) => Option.Option, onNone: (a: A) => string): Argument } = dual(3, ( @@ -1165,7 +1247,8 @@ export const filterMap: { /** * Provides a fallback argument to use if this argument fails to parse. * - * @example + * **Example** (Providing a fallback argument) + * * ```ts * import { Argument } from "effect/unstable/cli" * @@ -1174,14 +1257,15 @@ export const filterMap: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const orElse: { /** * Provides a fallback argument to use if this argument fails to parse. * - * @example + * **Example** (Providing a fallback argument) + * * ```ts * import { Argument } from "effect/unstable/cli" * @@ -1190,14 +1274,15 @@ export const orElse: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (that: LazyArg>): (self: Argument) => Argument /** * Provides a fallback argument to use if this argument fails to parse. * - * @example + * **Example** (Providing a fallback argument) + * * ```ts * import { Argument } from "effect/unstable/cli" * @@ -1206,8 +1291,8 @@ export const orElse: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Argument, that: LazyArg>): Argument } = dual(2, (self: Argument, that: LazyArg>) => Param.orElse(self, that)) @@ -1215,7 +1300,8 @@ export const orElse: { /** * Provides a fallback argument, wrapping results in Result to distinguish which succeeded. * - * @example + * **Example** (Returning which fallback succeeded) + * * ```ts * import { Argument } from "effect/unstable/cli" * @@ -1225,14 +1311,15 @@ export const orElse: { * // Returns Result * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const orElseResult: { /** * Provides a fallback argument, wrapping results in Result to distinguish which succeeded. * - * @example + * **Example** (Returning which fallback succeeded) + * * ```ts * import { Argument } from "effect/unstable/cli" * @@ -1242,14 +1329,15 @@ export const orElseResult: { * // Returns Result * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (that: LazyArg>): (self: Argument) => Argument> /** * Provides a fallback argument, wrapping results in Result to distinguish which succeeded. * - * @example + * **Example** (Returning which fallback succeeded) + * * ```ts * import { Argument } from "effect/unstable/cli" * @@ -1259,8 +1347,8 @@ export const orElseResult: { * // Returns Result * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Argument, that: LazyArg>): Argument> } = dual(2, (self: Argument, that: LazyArg>) => Param.orElseResult(self, that)) diff --git a/.opencode/node_modules/effect/src/unstable/cli/CliError.ts b/.opencode/node_modules/effect/src/unstable/cli/CliError.ts index da334c7e36359ba1d0016d2e89050ae96c33bf7e..743048e5721d3503646a64d5b2d84ac0161e4760 100644 --- a/.opencode/node_modules/effect/src/unstable/cli/CliError.ts +++ b/.opencode/node_modules/effect/src/unstable/cli/CliError.ts @@ -1,4 +1,13 @@ /** + * Defines structured errors for the unstable CLI parser and runner. + * + * CLI errors describe problems such as unknown or duplicate flags, missing + * flags or arguments, invalid values, unknown subcommands, user handler + * failures, and requests to show command help. This module includes the + * `CliError` union, the `isCliError` guard, schema-backed error classes with + * display messages, and the `NonShowHelpErrors` union used when parse or + * validation errors should be shown with help output. + * * @since 4.0.0 */ import * as Predicate from "../../Predicate.ts" @@ -6,15 +15,16 @@ import * as Runtime from "../../Runtime.ts" import * as Schema from "../../Schema.ts" /** + * @category type IDs * @since 4.0.0 - * @category type id */ const TypeId = "~effect/cli/CliError" /** * Type guard to check if a value is a CLI error. * - * @example + * **Example** (Checking CLI errors) + * * ```ts * import { Effect } from "effect" * import { CliError } from "effect/unstable/cli" @@ -37,15 +47,16 @@ const TypeId = "~effect/cli/CliError" * }) * ``` * - * @since 4.0.0 * @category guards + * @since 4.0.0 */ export const isCliError = (u: unknown): u is CliError => Predicate.hasProperty(u, TypeId) /** * Union type representing all possible CLI error conditions. * - * @example + * **Example** (Handling CLI errors) + * * ```ts * import type { CliError } from "effect/unstable/cli" * @@ -70,8 +81,8 @@ export const isCliError = (u: unknown): u is CliError => Predicate.hasProperty(u * } * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type CliError = | UnrecognizedOption @@ -86,7 +97,8 @@ export type CliError = /** * Error thrown when an unrecognized option is encountered. * - * @example + * **Example** (Creating unrecognized option errors) + * * ```ts * import { Effect } from "effect" * import { CliError } from "effect/unstable/cli" @@ -112,8 +124,8 @@ export type CliError = * }) * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export class UnrecognizedOption extends Schema.ErrorClass(`${TypeId}/UnrecognizedOption`)({ _tag: Schema.tag("UnrecognizedOption"), @@ -122,11 +134,15 @@ export class UnrecognizedOption extends Schema.ErrorClass(`$ suggestions: Schema.Array(Schema.String) }) { /** + * Marks this value as a CLI parsing error for runtime guards. + * * @since 4.0.0 */ readonly [TypeId] = TypeId /** + * Formats the unrecognized option with command context and suggestions. + * * @since 4.0.0 */ override get message() { @@ -143,7 +159,8 @@ export class UnrecognizedOption extends Schema.ErrorClass(`$ /** * Error thrown when duplicate option names are detected between parent and child commands. * - * @example + * **Example** (Creating duplicate option errors) + * * ```ts * import { CliError } from "effect/unstable/cli" * @@ -158,8 +175,8 @@ export class UnrecognizedOption extends Schema.ErrorClass(`$ * // Parent will always claim this flag (Mode A semantics). Consider renaming one of them to avoid confusion." * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export class DuplicateOption extends Schema.ErrorClass(`${TypeId}/DuplicateOption`)({ _tag: Schema.tag("DuplicateOption"), @@ -168,11 +185,15 @@ export class DuplicateOption extends Schema.ErrorClass(`${TypeI childCommand: Schema.String }) { /** + * Marks this value as a CLI configuration error for runtime guards. + * * @since 4.0.0 */ readonly [TypeId] = TypeId /** + * Explains which parent and child commands define the duplicate option. + * * @since 4.0.0 */ override get message() { @@ -184,7 +205,8 @@ export class DuplicateOption extends Schema.ErrorClass(`${TypeI /** * Error thrown when a required option is missing. * - * @example + * **Example** (Creating missing option errors) + * * ```ts * import { Effect } from "effect" * import { CliError } from "effect/unstable/cli" @@ -207,19 +229,23 @@ export class DuplicateOption extends Schema.ErrorClass(`${TypeI * }) * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export class MissingOption extends Schema.ErrorClass(`${TypeId}/MissingOption`)({ _tag: Schema.tag("MissingOption"), option: Schema.String }) { /** + * Marks this value as a missing CLI option error for runtime guards. + * * @since 4.0.0 */ readonly [TypeId] = TypeId /** + * Formats the missing required flag for display. + * * @since 4.0.0 */ override get message() { @@ -230,7 +256,8 @@ export class MissingOption extends Schema.ErrorClass(`${TypeId}/M /** * Error thrown when a required positional argument is missing. * - * @example + * **Example** (Creating missing argument errors) + * * ```ts * import { Effect } from "effect" * import { CliError } from "effect/unstable/cli" @@ -252,19 +279,23 @@ export class MissingOption extends Schema.ErrorClass(`${TypeId}/M * }) * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export class MissingArgument extends Schema.ErrorClass(`${TypeId}/MissingArgument`)({ _tag: Schema.tag("MissingArgument"), argument: Schema.String }) { /** + * Marks this value as a missing CLI argument error for runtime guards. + * * @since 4.0.0 */ readonly [TypeId] = TypeId /** + * Formats the missing required positional argument for display. + * * @since 4.0.0 */ override get message() { @@ -275,7 +306,8 @@ export class MissingArgument extends Schema.ErrorClass(`${TypeI /** * Error thrown when an option or argument value is invalid. * - * @example + * **Example** (Creating invalid value errors) + * * ```ts * import { Effect } from "effect" * import { CliError } from "effect/unstable/cli" @@ -302,8 +334,8 @@ export class MissingArgument extends Schema.ErrorClass(`${TypeI * // "Invalid value for argument : "abc". Expected: integer" * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export class InvalidValue extends Schema.ErrorClass(`${TypeId}/InvalidValue`)({ _tag: Schema.tag("InvalidValue"), @@ -313,11 +345,15 @@ export class InvalidValue extends Schema.ErrorClass(`${TypeId}/Inv kind: Schema.Union([Schema.Literal("flag"), Schema.Literal("argument")]) }) { /** + * Marks this value as an invalid CLI value error for runtime guards. + * * @since 4.0.0 */ readonly [TypeId] = TypeId /** + * Formats the invalid flag or argument value with the expected input. + * * @since 4.0.0 */ override get message() { @@ -331,7 +367,8 @@ export class InvalidValue extends Schema.ErrorClass(`${TypeId}/Inv /** * Error thrown when an unknown subcommand is encountered. * - * @example + * **Example** (Creating unknown subcommand errors) + * * ```ts * import { Effect } from "effect" * import { CliError } from "effect/unstable/cli" @@ -360,8 +397,8 @@ export class InvalidValue extends Schema.ErrorClass(`${TypeId}/Inv * }) * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export class UnknownSubcommand extends Schema.ErrorClass(`${TypeId}/UnknownSubcommand`)({ _tag: Schema.tag("UnknownSubcommand"), @@ -370,11 +407,15 @@ export class UnknownSubcommand extends Schema.ErrorClass(`${T suggestions: Schema.Array(Schema.String) }) { /** + * Marks this value as an unknown CLI subcommand error for runtime guards. + * * @since 4.0.0 */ readonly [TypeId] = TypeId /** + * Formats the unknown subcommand with parent command context and suggestions. + * * @since 4.0.0 */ override get message() { @@ -388,9 +429,10 @@ export class UnknownSubcommand extends Schema.ErrorClass(`${T } /** - * Wrapper for user (handler) errors to unify under CLI error channel when desired. + * Error wrapper for user handler failures in the CLI error channel. + * + * **Example** (Wrapping user errors) * - * @example * ```ts * import { Effect } from "effect" * import { CliError } from "effect/unstable/cli" @@ -419,25 +461,31 @@ export class UnknownSubcommand extends Schema.ErrorClass(`${T * } * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export class UserError extends Schema.ErrorClass(`${TypeId}/UserError`)({ _tag: Schema.tag("UserError"), - cause: Schema.Defect + cause: Schema.Defect() }) { /** + * Marks this value as a user handler error for runtime guards. + * * @since 4.0.0 */ readonly [TypeId] = TypeId } /** - * Represents errors that should not trigger the display of the CLI's help - * documentation. + * Schema for concrete CLI errors that can be reported together with help output. + * + * **Details** + * + * This excludes `ShowHelp` itself, allowing parse and validation errors to be + * stored in `ShowHelp.errors` without nesting another help-control value. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export const NonShowHelpErrors: Schema.Union< readonly [ @@ -460,17 +508,30 @@ export const NonShowHelpErrors: Schema.Union< ]) /** - * @since 4.0.0 + * Type of CLI errors that are not `ShowHelp`. + * + * **Details** + * + * These errors can be accumulated and attached to `ShowHelp.errors` when the + * runner should display help along with the underlying parse or validation + * failures. + * * @category models + * @since 4.0.0 */ export type NonShowHelpErrors = typeof NonShowHelpErrors.Type /** - * Control flow indicator when help is requested via --help flag. - * This is not an error but uses the error channel for control flow. + * Error data requesting CLI help rendering for a command path. + * + * **Details** + * + * It is used for explicit help requests and for parse or validation failures + * that should be shown with help text. When `errors` is non-empty, the runtime + * exit code is `1`; otherwise it is `0`. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export class ShowHelp extends Schema.ErrorClass(`${TypeId}/ShowHelp`)({ _tag: Schema.tag("ShowHelp"), diff --git a/.opencode/node_modules/effect/src/unstable/cli/CliOutput.ts b/.opencode/node_modules/effect/src/unstable/cli/CliOutput.ts index 9d0094b74e24230eda4f749936d9ee170fe0342f..82c49e5c3de1bd97c112fefabb516a1474c0f0bf 100644 --- a/.opencode/node_modules/effect/src/unstable/cli/CliOutput.ts +++ b/.opencode/node_modules/effect/src/unstable/cli/CliOutput.ts @@ -1,4 +1,12 @@ /** + * Formats CLI help and errors as text. + * + * This module turns help documents, CLI errors, grouped errors, and version + * information into strings. It does not write those strings to the terminal + * itself. It includes the `Formatter` interface, the formatter service, a layer + * for custom formatters, and the default formatter with configurable color + * support. + * * @since 4.0.0 */ @@ -9,10 +17,11 @@ import type * as CliError from "./CliError.ts" import type { HelpDoc } from "./HelpDoc.ts" /** - * Service interface for formatting CLI output including help, errors, and version info. + * Defines the service interface for formatting CLI output including help, errors, and version info. * This allows customization of output formatting, including color support. * - * @example + * **Example** (Customizing CLI output formatting) + * * ```ts * import { Effect } from "effect" * import { CliOutput } from "effect/unstable/cli" @@ -36,18 +45,19 @@ import type { HelpDoc } from "./HelpDoc.ts" * ) * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface Formatter { /** * Formats a HelpDoc structure into a readable string format. * - * @example + * **Example** (Formatting help documents) + * * ```ts * import { Option as O } from "effect" - * import type { HelpDoc } from "effect/unstable/cli" * import { CliOutput } from "effect/unstable/cli" + * import type { HelpDoc } from "effect/unstable/cli" * * const helpDoc: HelpDoc = { * usage: "myapp [options] ", @@ -85,9 +95,10 @@ export interface Formatter { /** * Formats a CLI error for display. Default implementation mirrors the error message. * - * @example + * **Example** (Formatting CLI errors) + * * ```ts - * import * as Data from "effect/Data" + * import { Data } from "effect" * import { CliOutput } from "effect/unstable/cli" * * class InvalidOption extends Data.TaggedError("InvalidOption")<{ @@ -107,9 +118,10 @@ export interface Formatter { /** * Formats an error section with proper styling and color reset. * - * @example + * **Example** (Formatting error sections) + * * ```ts - * import * as Data from "effect/Data" + * import { Data } from "effect" * import { CliOutput } from "effect/unstable/cli" * * class ValidationError extends Data.TaggedError("ValidationError")<{ @@ -135,7 +147,8 @@ export interface Formatter { /** * Formats version output for display. * - * @example + * **Example** (Formatting version output) + * * ```ts * import { CliOutput } from "effect/unstable/cli" * @@ -159,7 +172,8 @@ export interface Formatter { /** * Formats multiple CLI errors for display, grouping by error type. * - * @example + * **Example** (Formatting grouped errors) + * * ```ts * import { CliError, CliOutput } from "effect/unstable/cli" * @@ -187,9 +201,10 @@ export interface Formatter { * Service reference for the CLI output formatter. Provides a default implementation * that can be overridden for custom formatting or testing. * - * @example + * **Example** (Accessing the output formatter) + * * ```ts - * import * as Effect from "effect/Effect" + * import { Effect } from "effect" * import { CliOutput } from "effect/unstable/cli" * * // Access the formatter service @@ -207,8 +222,8 @@ export interface Formatter { * const result = Effect.runSync(program) * ``` * - * @since 4.0.0 * @category services + * @since 4.0.0 */ export const Formatter: Context.Reference = Context.Reference( "effect/cli/CliOutput", @@ -218,10 +233,10 @@ export const Formatter: Context.Reference = Context.Reference( /** * Creates a Layer that provides a custom Formatter implementation. * - * @example + * **Example** (Providing a custom formatter) + * * ```ts - * import * as Console from "effect/Console" - * import * as Effect from "effect/Effect" + * import { Console, Effect } from "effect" * import { CliOutput } from "effect/unstable/cli" * * // Create a custom formatter without colors @@ -249,15 +264,16 @@ export const Formatter: Context.Reference = Context.Reference( * const JsonLayer = CliOutput.layer(jsonFormatter) * ``` * - * @since 4.0.0 * @category layers + * @since 4.0.0 */ export const layer = (formatter: Formatter): Layer.Layer => Layer.succeed(Formatter)(formatter) /** * Creates a default formatter with configurable options. * - * @example + * **Example** (Creating default formatters) + * * ```ts * import { Effect } from "effect" * import { CliError, CliOutput } from "effect/unstable/cli" @@ -290,8 +306,8 @@ export const layer = (formatter: Formatter): Layer.Layer => Layer.succeed * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const defaultFormatter = (options?: { colors?: boolean }): Formatter => { const globalProcess = (globalThis as any).process diff --git a/.opencode/node_modules/effect/src/unstable/cli/Command.ts b/.opencode/node_modules/effect/src/unstable/cli/Command.ts index e291e8536f4075cce6740b6b5c846dfddd12d5ce..13e8b366bf339e8b7f7952dd47af9ed09cb86c35 100644 --- a/.opencode/node_modules/effect/src/unstable/cli/Command.ts +++ b/.opencode/node_modules/effect/src/unstable/cli/Command.ts @@ -1,4 +1,13 @@ /** + * Main building block for defining and running Effect-based command-line + * applications. + * + * A `Command` combines a name, typed flags and positional arguments, optional + * subcommands, help metadata, and an effectful handler. The module includes + * builders for command trees and the runners that parse command-line input, + * handle built-in help and version behavior, render help through `CliOutput`, + * and execute the selected handler. + * * @since 4.0.0 */ import type { NonEmptyArray, NonEmptyReadonlyArray } from "../../Array.ts" @@ -10,13 +19,12 @@ import { dual } from "../../Function.ts" import type * as Layer from "../../Layer.ts" import * as Option from "../../Option.ts" import type * as Path from "../../Path.ts" -import type { Pipeable } from "../../Pipeable.ts" import * as Predicate from "../../Predicate.ts" import * as References from "../../References.ts" import * as Result from "../../Result.ts" import * as Stdio from "../../Stdio.ts" import * as Terminal from "../../Terminal.ts" -import type { NoInfer, Simplify } from "../../Types.ts" +import type { Contravariant, Covariant, NoInfer, Simplify } from "../../Types.ts" import type { ChildProcessSpawner } from "../process/ChildProcessSpawner.ts" import * as CliError from "./CliError.ts" import * as CliOutput from "./CliOutput.ts" @@ -35,13 +43,17 @@ import * as Param from "./Param.ts" /** * Represents a CLI command with its configuration, handler, and metadata. * + * **Details** + * * Commands are the core building blocks of CLI applications. They define: + * * - The command name and description * - Configuration including flags and arguments * - Handler function for execution * - Optional subcommands for hierarchical structures * - * @example + * **Example** (Defining CLI commands) + * * ```ts * import { Console } from "effect" * import { Argument, Command, Flag } from "effect/unstable/cli" @@ -74,20 +86,18 @@ import * as Param from "./Param.ts" * }, (config) => Console.log(`Hello, ${config.name}!`)) * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ -export interface Command +export interface Command extends - Pipeable, - Effect.Yieldable< - Command, + Effect.Effect< ContextInput, never, CommandContext > { - readonly [TypeId]: typeof TypeId + readonly [TypeId]: Command.Variance /** * The name of the command. @@ -126,17 +136,44 @@ export interface Command + + /** + * Whether this command is hidden from parent help output, shell + * completions, and unknown-subcommand suggestions. Hidden commands still + * parse and execute normally when invoked by exact name. + */ + readonly hidden: boolean } /** + * Companion namespace containing type-level helpers and configuration shapes + * used by `Command`. + * * @since 4.0.0 */ export declare namespace Command { /** - * Represents a concrete usage example for a command. + * Type-level variance marker for `Command`. + * + * **Details** * + * The parsed input type is contravariant, while the command error and service + * requirement types are covariant. + * + * @category models * @since 4.0.0 + */ + export interface Variance { + readonly Input: Contravariant + readonly E: Covariant + readonly R: Covariant + } + + /** + * Represents a concrete usage example for a command. + * * @category models + * @since 4.0.0 */ export interface Example { readonly command: string @@ -146,15 +183,17 @@ export declare namespace Command { /** * Configuration object for defining command flags, arguments, and nested structures. * - * Command.Config allows you to specify: - * - Individual flags and arguments using Param types - * - Nested configuration objects for organization - * - Arrays of parameters for repeated elements + * **Details** + * + * `Command.Config` can contain individual flags and arguments using `Param` + * types, nested configuration objects for organization, and arrays of + * parameters for repeated elements. + * + * **Example** (Configuring command input) * - * @example * ```ts * import { Argument, Flag } from "effect/unstable/cli" - * import type * as CliCommand from "effect/unstable/cli/Command" + * import type { Command as CliCommand } from "effect/unstable/cli" * * // Simple flat configuration * const simpleConfig: CliCommand.Command.Config = { @@ -176,8 +215,8 @@ export declare namespace Command { * } * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface Config { readonly [key: string]: @@ -189,10 +228,12 @@ export declare namespace Command { /** * Configuration shape accepted by `Command.withSharedFlags`. * + * **Details** + * * Only flags are allowed here; arguments are intentionally excluded. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface FlagConfig { readonly [key: string]: @@ -205,19 +246,21 @@ export declare namespace Command { * Utilities for working with command configurations. * * @since 4.0.0 - * @category models */ export namespace Config { /** * Infers the TypeScript type from a Command.Config structure. * + * **Details** + * * This type utility extracts the final configuration type that handlers will receive, * preserving the nested structure while converting Param types to their values. * - * @example + * **Example** (Inferring command input) + * * ```ts * import { Flag } from "effect/unstable/cli" - * import type * as CliCommand from "effect/unstable/cli/Command" + * import type { Command as CliCommand } from "effect/unstable/cli" * * const config = { * name: Flag.string("name"), @@ -237,8 +280,8 @@ export declare namespace Command { * // } * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type Infer = Simplify< { readonly [Key in keyof A]: InferValue } @@ -247,8 +290,8 @@ export declare namespace Command { /** * Helper type utility for recursively inferring types from Config values. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type InferValue = A extends ReadonlyArray ? { readonly [Key in keyof A]: InferValue } : A extends Param.Param ? _Value @@ -259,16 +302,29 @@ export declare namespace Command { /** * Represents any Command regardless of its type parameters. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ - export type Any = Command + export interface Any extends Effect.Effect { + readonly [TypeId]: any + readonly name: string + readonly description: string | undefined + readonly shortDescription: string | undefined + readonly alias: string | undefined + readonly examples: ReadonlyArray + readonly subcommands: ReadonlyArray<{ + readonly group: string | undefined + readonly commands: NonEmptyReadonlyArray + }> + readonly annotations: Context.Context + readonly hidden: boolean + } /** * A grouped set of subcommands used by `Command.withSubcommands`. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface SubcommandGroup = ReadonlyArray> { readonly group: string @@ -278,25 +334,31 @@ export declare namespace Command { /** * Entry type accepted by `Command.withSubcommands`. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type SubcommandEntry = Any | SubcommandGroup> } /** - * The environment required by CLI commands, including file system and path operations. + * Services required by CLI parsing and execution. + * + * **Details** + * + * This includes file-system and path services for arguments, terminal and + * stdio services for running commands, and child-process spawning for + * process-related CLI features. * - * @since 4.0.0 * @category utility types + * @since 4.0.0 */ export type Environment = FileSystem.FileSystem | Path.Path | Terminal.Terminal | ChildProcessSpawner | Stdio.Stdio /** * A utility type to extract the error type from a `Command`. * - * @since 4.0.0 * @category utility types + * @since 4.0.0 */ export type Error = C extends Command< infer _Name, @@ -310,12 +372,15 @@ export type Error = C extends Command< /** * Service context for a specific command, enabling subcommands to access their parent's parsed configuration. * + * **Details** + * * When a subcommand handler needs access to flags or arguments from a parent command, * it can yield the parent command directly to retrieve its config. This is powered by * Effect's service system - each command automatically creates a service that provides * its parsed input to child commands. * - * @example + * **Example** (Accessing parent command context) + * * ```ts * import { Console, Effect } from "effect" * import { Command, Flag } from "effect/unstable/cli" @@ -342,8 +407,8 @@ export type Error = C extends Command< * // Usage: app --verbose --config prod.json deploy --target staging * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface CommandContext { readonly _: unique symbol @@ -353,8 +418,8 @@ export interface CommandContext { /** * Represents the parsed tokens from command-line input before validation. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface ParsedTokens { readonly flags: Record> @@ -367,8 +432,15 @@ export interface ParsedTokens { } /** + * Returns `true` if the provided value is a `Command`. + * + * **Gotchas** + * + * This checks for the `Command` type-id property; it does not validate the full + * command shape. + * + * @category guards * @since 4.0.0 - * @category Guards */ export const isCommand = (u: unknown): u is Command.Any => Predicate.hasProperty(u, TypeId) @@ -377,13 +449,17 @@ export const isCommand = (u: unknown): u is Command.Any => Predicate.hasProperty /* ========================================================================== */ /** - * Creates a Command from a name, optional config, optional handler function, and optional description. + * Creates a `Command` from a name, an optional configuration, and an optional + * handler. + * + * **Details** + * + * Use `withDescription` and related metadata combinators to add help text. The + * overloads support simple commands, configured commands, and commands with + * effectful handlers. * - * The make function is the primary constructor for CLI commands. It provides multiple overloads - * to support different patterns of command creation, from simple commands with no configuration - * to complex commands with nested configurations and error handling. + * **Example** (Creating commands) * - * @example * ```ts * import { Console, Effect } from "effect" * import { Argument, Command, Flag } from "effect/unstable/cli" @@ -426,8 +502,8 @@ export const isCommand = (u: unknown): u is Command.Any => Predicate.hasProperty * })) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const make: { /* ========================================================================== */ @@ -435,13 +511,17 @@ export const make: { /* ========================================================================== */ /** - * Creates a Command from a name, optional config, optional handler function, and optional description. + * Creates a `Command` from a name, an optional configuration, and an optional + * handler. + * + * **Details** + * + * Use `withDescription` and related metadata combinators to add help text. The + * overloads support simple commands, configured commands, and commands with + * effectful handlers. * - * The make function is the primary constructor for CLI commands. It provides multiple overloads - * to support different patterns of command creation, from simple commands with no configuration - * to complex commands with nested configurations and error handling. + * **Example** (Creating commands) * - * @example * ```ts * import { Console, Effect } from "effect" * import { Argument, Command, Flag } from "effect/unstable/cli" @@ -484,8 +564,8 @@ export const make: { * })) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ (name: Name): Command @@ -494,13 +574,17 @@ export const make: { /* ========================================================================== */ /** - * Creates a Command from a name, optional config, optional handler function, and optional description. + * Creates a `Command` from a name, an optional configuration, and an optional + * handler. + * + * **Details** * - * The make function is the primary constructor for CLI commands. It provides multiple overloads - * to support different patterns of command creation, from simple commands with no configuration - * to complex commands with nested configurations and error handling. + * Use `withDescription` and related metadata combinators to add help text. The + * overloads support simple commands, configured commands, and commands with + * effectful handlers. + * + * **Example** (Creating commands) * - * @example * ```ts * import { Console, Effect } from "effect" * import { Argument, Command, Flag } from "effect/unstable/cli" @@ -543,8 +627,8 @@ export const make: { * })) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ (name: Name, config: Config): Command, {}, never, never> @@ -553,13 +637,17 @@ export const make: { /* ========================================================================== */ /** - * Creates a Command from a name, optional config, optional handler function, and optional description. + * Creates a `Command` from a name, an optional configuration, and an optional + * handler. + * + * **Details** * - * The make function is the primary constructor for CLI commands. It provides multiple overloads - * to support different patterns of command creation, from simple commands with no configuration - * to complex commands with nested configurations and error handling. + * Use `withDescription` and related metadata combinators to add help text. The + * overloads support simple commands, configured commands, and commands with + * effectful handlers. + * + * **Example** (Creating commands) * - * @example * ```ts * import { Console, Effect } from "effect" * import { Argument, Command, Flag } from "effect/unstable/cli" @@ -602,8 +690,8 @@ export const make: { * })) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ ( name: Name, @@ -630,7 +718,8 @@ export const make: { /** * Adds or replaces the handler for a command. * - * @example + * **Example** (Adding command handlers) + * * ```ts * import { Console } from "effect" * import { Command, Flag } from "effect/unstable/cli" @@ -648,8 +737,8 @@ export const make: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const withHandler: { /* ========================================================================== */ @@ -659,7 +748,8 @@ export const withHandler: { /** * Adds or replaces the handler for a command. * - * @example + * **Example** (Adding command handlers) + * * ```ts * import { Console } from "effect" * import { Command, Flag } from "effect/unstable/cli" @@ -677,8 +767,8 @@ export const withHandler: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (handler: (value: A) => Effect.Effect): ( self: Command @@ -690,7 +780,8 @@ export const withHandler: { /** * Adds or replaces the handler for a command. * - * @example + * **Example** (Adding command handlers) + * * ```ts * import { Console } from "effect" * import { Command, Flag } from "effect/unstable/cli" @@ -708,8 +799,8 @@ export const withHandler: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ ( self: Command, @@ -719,7 +810,7 @@ export const withHandler: { self: Command, handler: (value: A) => Effect.Effect ): Command> => - makeCommand({ ...toImpl(self), handle: handler })) + makeCommand({ ...toImpl(self), handle: handler } as any)) interface SubcommandGroupInternal { readonly group: string | undefined @@ -775,11 +866,14 @@ const normalizeSubcommandEntries = ( /** * Adds subcommands to a command, creating a hierarchical command structure. * + * **Details** + * * Subcommands can access their parent's parsed configuration by yielding the parent * command within their handler. This enables shared parent flags that affect * all subcommands. * - * @example + * **Example** (Adding subcommands) + * * ```ts * import { Console, Effect } from "effect" * import { Command, Flag } from "effect/unstable/cli" @@ -807,18 +901,21 @@ const normalizeSubcommandEntries = ( * // Usage: git --verbose clone --repo github.com/foo/bar * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const withSubcommands: { /** * Adds subcommands to a command, creating a hierarchical command structure. * + * **Details** + * * Subcommands can access their parent's parsed configuration by yielding the parent * command within their handler. This enables shared parent flags that affect * all subcommands. * - * @example + * **Example** (Adding subcommands) + * * ```ts * import { Console, Effect } from "effect" * import { Command, Flag } from "effect/unstable/cli" @@ -846,8 +943,8 @@ export const withSubcommands: { * // Usage: git --verbose clone --repo github.com/foo/bar * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ >(subcommands: Subcommands): ( self: Command @@ -861,11 +958,14 @@ export const withSubcommands: { /** * Adds subcommands to a command, creating a hierarchical command structure. * + * **Details** + * * Subcommands can access their parent's parsed configuration by yielding the parent * command within their handler. This enables shared parent flags that affect * all subcommands. * - * @example + * **Example** (Adding subcommands) + * * ```ts * import { Console, Effect } from "effect" * import { Command, Flag } from "effect/unstable/cli" @@ -893,8 +993,8 @@ export const withSubcommands: { * // Usage: git --verbose clone --repo github.com/foo/bar * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ < Name extends string, @@ -931,7 +1031,7 @@ export const withSubcommands: { checkForDuplicateFlags(self, normalized.flat) const impl = toImpl(self) - const byName = new Map(normalized.flat.map((s) => [s.name, toImpl(s)] as const)) + const byName = new Map(normalized.flat.map((s) => [s.name, toImpl(s as any)] as const)) type NextInput = Simplify const SubcommandStateSymbol = Symbol("effect/cli/SubcommandState") @@ -984,29 +1084,33 @@ export const withSubcommands: { parse, parseContext: impl.parseContext, handle - }) + }) as any }) /** * Adds flags that are inherited by subcommands. * + * **Details** + * * Shared flags are available to this command's handler and to descendant * handlers via `yield* parentCommand`. Shared flags are accepted both before * and after a selected subcommand name (npm-style). * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const withSharedFlags: { /** * Adds flags that are inherited by subcommands. * + * **Details** + * * Shared flags are available to this command's handler and to descendant * handlers via `yield* parentCommand`. Shared flags are accepted both before * and after a selected subcommand name (npm-style). * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (sharedFlags: SharedFlags): ( self: Command @@ -1020,12 +1124,14 @@ export const withSharedFlags: { /** * Adds flags that are inherited by subcommands. * + * **Details** + * * Shared flags are available to this command's handler and to descendant * handlers via `yield* parentCommand`. Shared flags are accepted both before * and after a selected subcommand name (npm-style). * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Command, sharedFlags: SharedFlags): Command< Name, @@ -1096,37 +1202,43 @@ export const withSharedFlags: { parse, parseContext, handle - }) + }) as any } ) /** - * Declares global flags for a command scope. + * Adds global flags to a command scope. + * + * **Details** * * Declared global flags apply to the command and all of its descendants. * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const withGlobalFlags: { /** - * Declares global flags for a command scope. + * Adds global flags to a command scope. + * + * **Details** * * Declared global flags apply to the command and all of its descendants. * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ >>(globalFlags: GlobalFlags): ( self: Command ) => Command>> /** - * Declares global flags for a command scope. + * Adds global flags to a command scope. + * + * **Details** * * Declared global flags apply to the command and all of its descendants. * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ < Name extends string, @@ -1151,7 +1263,7 @@ export const withGlobalFlags: { ): Command>> => { const impl = toImpl(self) const next = Array.from(new Set([...impl.globalFlags, ...globalFlags])) - return makeCommand({ ...impl, globalFlags: next }) + return makeCommand({ ...impl, globalFlags: next }) as any } ) @@ -1170,10 +1282,13 @@ type ExtractSubcommandContext> /** * Sets the description for a command. * + * **Details** + * * Descriptions provide users with information about what the command does * when they view help documentation. * - * @example + * **Example** (Setting descriptions) + * * ```ts * import { Console, Effect } from "effect" * import { Command, Flag } from "effect/unstable/cli" @@ -1188,17 +1303,20 @@ type ExtractSubcommandContext> * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const withDescription: { /** * Sets the description for a command. * + * **Details** + * * Descriptions provide users with information about what the command does * when they view help documentation. * - * @example + * **Example** (Setting descriptions) + * * ```ts * import { Console, Effect } from "effect" * import { Command, Flag } from "effect/unstable/cli" @@ -1213,8 +1331,8 @@ export const withDescription: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (description: string): ( self: Command @@ -1222,10 +1340,13 @@ export const withDescription: { /** * Sets the description for a command. * + * **Details** + * * Descriptions provide users with information about what the command does * when they view help documentation. * - * @example + * **Example** (Setting descriptions) + * * ```ts * import { Console, Effect } from "effect" * import { Command, Flag } from "effect/unstable/cli" @@ -1240,8 +1361,8 @@ export const withDescription: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Command, description: string): Command } = dual(2, ( @@ -1252,23 +1373,27 @@ export const withDescription: { /** * Sets a short description for a command. * + * **Details** + * * Short descriptions are used when listing subcommands in help output and * shell completions. If no short description is provided, the full * `description` is used as a fallback. * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const withShortDescription: { /** * Sets a short description for a command. * + * **Details** + * * Short descriptions are used when listing subcommands in help output and * shell completions. If no short description is provided, the full * `description` is used as a fallback. * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (shortDescription: string): ( self: Command @@ -1276,12 +1401,14 @@ export const withShortDescription: { /** * Sets a short description for a command. * + * **Details** + * * Short descriptions are used when listing subcommands in help output and * shell completions. If no short description is provided, the full * `description` is used as a fallback. * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Command, shortDescription: string): Command } = dual(2, ( @@ -1292,21 +1419,25 @@ export const withShortDescription: { /** * Sets an alias for a command. * + * **Details** + * * Aliases are accepted as alternate subcommand names during parsing and are * shown in help output as `name, alias`. * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const withAlias: { /** * Sets an alias for a command. * + * **Details** + * * Aliases are accepted as alternate subcommand names during parsing and are * shown in help output as `name, alias`. * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (alias: string): ( self: Command @@ -1314,11 +1445,13 @@ export const withAlias: { /** * Sets an alias for a command. * + * **Details** + * * Aliases are accepted as alternate subcommand names during parsing and are * shown in help output as `name, alias`. * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Command, alias: string): Command } = dual(2, ( @@ -1327,17 +1460,82 @@ export const withAlias: { ) => makeCommand({ ...toImpl(self), alias })) /** - * Adds a custom annotation to a command. + * Hides a subcommand from parent help output, shell completions, and + * "did you mean?" suggestions while keeping it fully invocable by exact name. * + * **When to use** + * + * Use when experimental or internal subcommands should be accepted but not advertised on + * the public CLI surface. + * + * **Example** (Hiding a subcommand) + * + * ```ts + * import { Command } from "effect/unstable/cli" + * + * // `experimental` still runs when invoked as `mycli experimental`, + * // but it does not appear under SUBCOMMANDS in `mycli --help`. + * const experimental = Command.make("experimental").pipe( + * Command.withHidden + * ) + * + * const root = Command.make("mycli").pipe( + * Command.withSubcommands([experimental]) + * ) + * ``` + * + * @category combinators * @since 4.0.0 + */ +export const withHidden = ( + self: Command +): Command => + makeCommand({ ...toImpl(self), hidden: true }) as Command + +/** + * Adds a custom annotation to a command. + * + * **When to use** + * + * Use to attach one command-scoped metadata value under a `Context.Key`, + * especially for consumers such as custom help formatters. + * + * **Details** + * + * Annotations are stored on the command's annotation context and flow into + * generated help document annotations. + * + * **Gotchas** + * + * Adding the same `Context.Key` again replaces the earlier value. + * + * @see {@link annotateMerge} for merging an existing annotation context + * * @category combinators + * @since 4.0.0 */ export const annotate: { /** * Adds a custom annotation to a command. * - * @since 4.0.0 + * **When to use** + * + * Use to attach one command-scoped metadata value under a `Context.Key`, + * especially for consumers such as custom help formatters. + * + * **Details** + * + * Annotations are stored on the command's annotation context and flow into + * generated help document annotations. + * + * **Gotchas** + * + * Adding the same `Context.Key` again replaces the earlier value. + * + * @see {@link annotateMerge} for merging an existing annotation context + * * @category combinators + * @since 4.0.0 */ (service: Context.Key, value: NoInfer): ( self: Command @@ -1345,8 +1543,24 @@ export const annotate: { /** * Adds a custom annotation to a command. * - * @since 4.0.0 + * **When to use** + * + * Use to attach one command-scoped metadata value under a `Context.Key`, + * especially for consumers such as custom help formatters. + * + * **Details** + * + * Annotations are stored on the command's annotation context and flow into + * generated help document annotations. + * + * **Gotchas** + * + * Adding the same `Context.Key` again replaces the earlier value. + * + * @see {@link annotateMerge} for merging an existing annotation context + * * @category combinators + * @since 4.0.0 */ ( self: Command, @@ -1365,15 +1579,49 @@ export const annotate: { /** * Merges a Context of annotations into a command. * - * @since 4.0.0 + * **When to use** + * + * Use when you need to attach an already-built `Context.Context` of command + * annotations. + * + * **Details** + * + * Merged annotations are stored on the command and exposed through generated + * help document annotations. + * + * **Gotchas** + * + * If both contexts contain the same `Context.Key`, the incoming annotations + * context wins. + * + * @see {@link annotate} for adding a single annotation without constructing a `Context` + * * @category combinators + * @since 4.0.0 */ export const annotateMerge: { /** * Merges a Context of annotations into a command. * - * @since 4.0.0 + * **When to use** + * + * Use when you need to attach an already-built `Context.Context` of command + * annotations. + * + * **Details** + * + * Merged annotations are stored on the command and exposed through generated + * help document annotations. + * + * **Gotchas** + * + * If both contexts contain the same `Context.Key`, the incoming annotations + * context wins. + * + * @see {@link annotate} for adding a single annotation without constructing a `Context` + * * @category combinators + * @since 4.0.0 */ (annotations: Context.Context): ( self: Command @@ -1381,8 +1629,25 @@ export const annotateMerge: { /** * Merges a Context of annotations into a command. * - * @since 4.0.0 + * **When to use** + * + * Use when you need to attach an already-built `Context.Context` of command + * annotations. + * + * **Details** + * + * Merged annotations are stored on the command and exposed through generated + * help document annotations. + * + * **Gotchas** + * + * If both contexts contain the same `Context.Key`, the incoming annotations + * context wins. + * + * @see {@link annotate} for adding a single annotation without constructing a `Context` + * * @category combinators + * @since 4.0.0 */ ( self: Command, @@ -1399,10 +1664,13 @@ export const annotateMerge: { /** * Sets usage examples for a command. * + * **Details** + * * Examples are exposed in structured `HelpDoc` data and rendered by the * default formatter in an `EXAMPLES` section. * - * @example + * **Example** (Adding usage examples) + * * ```ts * import { Command } from "effect/unstable/cli" * @@ -1414,17 +1682,20 @@ export const annotateMerge: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const withExamples: { /** * Sets usage examples for a command. * + * **Details** + * * Examples are exposed in structured `HelpDoc` data and rendered by the * default formatter in an `EXAMPLES` section. * - * @example + * **Example** (Adding usage examples) + * * ```ts * import { Command } from "effect/unstable/cli" * @@ -1436,8 +1707,8 @@ export const withExamples: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (examples: ReadonlyArray): ( self: Command @@ -1445,10 +1716,13 @@ export const withExamples: { /** * Sets usage examples for a command. * + * **Details** + * * Examples are exposed in structured `HelpDoc` data and rendered by the * default formatter in an `EXAMPLES` section. * - * @example + * **Example** (Adding usage examples) + * * ```ts * import { Command } from "effect/unstable/cli" * @@ -1460,8 +1734,8 @@ export const withExamples: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ ( self: Command, @@ -1489,7 +1763,8 @@ const mapHandler = ( * Provides the handler of a command with the services produced by a layer * that optionally depends on the command-line input to be created. * - * @example + * **Example** (Providing command services) + * * ```ts * import { Effect, FileSystem, PlatformError } from "effect" * import { Command, Flag } from "effect/unstable/cli" @@ -1518,15 +1793,16 @@ const mapHandler = ( * ) * ``` * - * @since 4.0.0 * @category providing services + * @since 4.0.0 */ export const provide: { /** * Provides the handler of a command with the services produced by a layer * that optionally depends on the command-line input to be created. * - * @example + * **Example** (Providing command services) + * * ```ts * import { Effect, FileSystem, PlatformError } from "effect" * import { Command, Flag } from "effect/unstable/cli" @@ -1555,8 +1831,8 @@ export const provide: { * ) * ``` * - * @since 4.0.0 * @category providing services + * @since 4.0.0 */ ( layer: Layer.Layer | ((input: Input) => Layer.Layer), @@ -1570,7 +1846,8 @@ export const provide: { * Provides the handler of a command with the services produced by a layer * that optionally depends on the command-line input to be created. * - * @example + * **Example** (Providing command services) + * * ```ts * import { Effect, FileSystem, PlatformError } from "effect" * import { Command, Flag } from "effect/unstable/cli" @@ -1599,8 +1876,8 @@ export const provide: { * ) * ``` * - * @since 4.0.0 * @category providing services + * @since 4.0.0 */ ( self: Command, @@ -1623,16 +1900,26 @@ export const provide: { * Provides the handler of a command with the implementation of a service that * optionally depends on the command-line input to be constructed. * - * @since 4.0.0 + * **When to use** + * + * Use when a command handler needs a pure service implementation, optionally + * derived from the parsed command input. + * * @category providing services + * @since 4.0.0 */ export const provideSync: { /** * Provides the handler of a command with the implementation of a service that * optionally depends on the command-line input to be constructed. * - * @since 4.0.0 + * **When to use** + * + * Use when a command handler needs a pure service implementation, optionally + * derived from the parsed command input. + * * @category providing services + * @since 4.0.0 */ (service: Context.Key, implementation: S | ((input: Input) => S)): ( self: Command @@ -1641,8 +1928,13 @@ export const provideSync: { * Provides the handler of a command with the implementation of a service that * optionally depends on the command-line input to be constructed. * - * @since 4.0.0 + * **When to use** + * + * Use when a command handler needs a pure service implementation, optionally + * derived from the parsed command input. + * * @category providing services + * @since 4.0.0 */ ( self: Command, @@ -1665,16 +1957,34 @@ export const provideSync: { * Provides the handler of a command with the service produced by an effect * that optionally depends on the command-line input to be created. * - * @since 4.0.0 + * **When to use** + * + * Use to acquire a service effectfully for each command run, optionally using + * parsed command input. + * + * @see {@link provideSync} for synchronous service acquisition + * @see {@link provide} for providing an already-available service + * @see {@link provideEffectDiscard} for running an effect before the handler without providing a service + * * @category providing services + * @since 4.0.0 */ export const provideEffect: { /** * Provides the handler of a command with the service produced by an effect * that optionally depends on the command-line input to be created. * - * @since 4.0.0 + * **When to use** + * + * Use to acquire a service effectfully for each command run, optionally using + * parsed command input. + * + * @see {@link provideSync} for synchronous service acquisition + * @see {@link provide} for providing an already-available service + * @see {@link provideEffectDiscard} for running an effect before the handler without providing a service + * * @category providing services + * @since 4.0.0 */ ( service: Context.Key, @@ -1686,8 +1996,17 @@ export const provideEffect: { * Provides the handler of a command with the service produced by an effect * that optionally depends on the command-line input to be created. * - * @since 4.0.0 + * **When to use** + * + * Use to acquire a service effectfully for each command run, optionally using + * parsed command input. + * + * @see {@link provideSync} for synchronous service acquisition + * @see {@link provide} for providing an already-available service + * @see {@link provideEffectDiscard} for running an effect before the handler without providing a service + * * @category providing services + * @since 4.0.0 */ ( self: Command, @@ -1709,16 +2028,16 @@ export const provideEffect: { * Allows for execution of an effect, which optionally depends on command-line * input to be created, prior to executing the handler of a command. * - * @since 4.0.0 * @category providing services + * @since 4.0.0 */ export const provideEffectDiscard: { /** * Allows for execution of an effect, which optionally depends on command-line * input to be created, prior to executing the handler of a command. * - * @since 4.0.0 * @category providing services + * @since 4.0.0 */ <_, Input, E2, R2>( effect: Effect.Effect<_, E2, R2> | ((input: Input) => Effect.Effect<_, E2, R2>) @@ -1729,8 +2048,8 @@ export const provideEffectDiscard: { * Allows for execution of an effect, which optionally depends on command-line * input to be created, prior to executing the handler of a command. * - * @since 4.0.0 * @category providing services + * @since 4.0.0 */ ( self: Command, @@ -1799,9 +2118,15 @@ const showHelp = ( }) /** - * Runs a command with the provided input arguments. + * Runs a command using the arguments supplied by the `Stdio` service. + * + * **When to use** + * + * Use when command-line arguments should come from `Stdio` at the application + * entry point. + * + * **Example** (Running commands with standard input) * - * @example * ```ts * import { Console, Effect } from "effect" * import { Command, Flag } from "effect/unstable/cli" @@ -1819,14 +2144,22 @@ const showHelp = ( * }) * ``` * - * @since 4.0.0 + * @see {@link runWith} for running a command with an explicit argument array + * * @category command execution + * @since 4.0.0 */ export const run: { /** - * Runs a command with the provided input arguments. + * Runs a command using the arguments supplied by the `Stdio` service. + * + * **When to use** + * + * Use when command-line arguments should come from `Stdio` at the application + * entry point. + * + * **Example** (Running commands with standard input) * - * @example * ```ts * import { Console, Effect } from "effect" * import { Command, Flag } from "effect/unstable/cli" @@ -1844,8 +2177,10 @@ export const run: { * }) * ``` * - * @since 4.0.0 + * @see {@link runWith} for running a command with an explicit argument array + * * @category command execution + * @since 4.0.0 */ ( config: { @@ -1855,9 +2190,15 @@ export const run: { command: Command ) => Effect.Effect /** - * Runs a command with the provided input arguments. + * Runs a command using the arguments supplied by the `Stdio` service. + * + * **When to use** + * + * Use when command-line arguments should come from `Stdio` at the application + * entry point. + * + * **Example** (Running commands with standard input) * - * @example * ```ts * import { Console, Effect } from "effect" * import { Command, Flag } from "effect/unstable/cli" @@ -1875,8 +2216,10 @@ export const run: { * }) * ``` * - * @since 4.0.0 + * @see {@link runWith} for running a command with an explicit argument array + * * @category command execution + * @since 4.0.0 */ ( command: Command, @@ -1898,12 +2241,15 @@ export const run: { )) /** - * Runs a command with explicitly provided arguments instead of using process.argv. + * Runs a command with explicitly provided arguments instead of using arguments from `Stdio`. + * + * **When to use** * - * This function is useful for testing CLI applications or when you want to - * programmatically execute commands with specific arguments. + * Use when you need to test CLI applications or programmatically execute + * commands with specific arguments. + * + * **Example** (Running commands with explicit arguments) * - * @example * ```ts * import { Console, Effect } from "effect" * import { Command, Flag } from "effect/unstable/cli" @@ -1933,8 +2279,8 @@ export const run: { * }) * ``` * - * @since 4.0.0 * @category command execution + * @since 4.0.0 */ export const runWith = ( command: Command, @@ -1955,7 +2301,11 @@ export const runWith = ( // 2. Extract global flag tokens const allFlagParams = allFlags.flatMap((f) => Param.extractSingleParams(f.flag)) const globalRegistry = Parser.createFlagRegistry(allFlagParams.filter(Param.isFlagParam)) - const { flagMap, remainder, errors: globalFlagErrors } = Parser.consumeKnownFlags(tokens, globalRegistry) + const { flagMap, remainder, errors: globalFlagErrors } = Parser.consumeGlobalFlags( + tokens, + command, + globalRegistry + ) const emptyArgs: Param.ParsedArgs = { flags: flagMap, arguments: [] } // 3. Parse command arguments from remaining tokens diff --git a/.opencode/node_modules/effect/src/unstable/cli/Completions.ts b/.opencode/node_modules/effect/src/unstable/cli/Completions.ts index a409aada0df0f76547926805b344631c82c93962..839575143b082da96fe2edcaf5dd5adbdf633ca1 100644 --- a/.opencode/node_modules/effect/src/unstable/cli/Completions.ts +++ b/.opencode/node_modules/effect/src/unstable/cli/Completions.ts @@ -1,5 +1,8 @@ /** - * Shell completion descriptors and script generation for the unstable CLI API. + * The `Completions` module turns a plain description of an Effect CLI command + * tree into shell completion scripts for Bash, Zsh, and Fish. It is the + * low-level script generation surface used by the unstable CLI package and by + * the built-in completions global flag. * * @since 4.0.0 */ @@ -10,16 +13,16 @@ import * as Zsh from "./internal/completions/zsh.ts" /** * Shell type used to generate completion scripts. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type Shell = "bash" | "zsh" | "fish" /** * Describes a command for completion script generation. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface CommandDescriptor { readonly name: string @@ -32,8 +35,8 @@ export interface CommandDescriptor { /** * Describes a command flag for completions. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface FlagDescriptor { readonly name: string @@ -45,8 +48,8 @@ export interface FlagDescriptor { /** * Describes the supported flag value shapes. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type FlagType = | { readonly _tag: "Boolean" } @@ -60,8 +63,8 @@ export type FlagType = /** * Describes a positional argument for completions. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface ArgumentDescriptor { readonly name: string @@ -74,8 +77,8 @@ export interface ArgumentDescriptor { /** * Describes the supported argument value shapes. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type ArgumentType = | { readonly _tag: "String" } @@ -88,8 +91,21 @@ export type ArgumentType = /** * Generates a shell completion script for a command descriptor. * - * @since 4.0.0 + * **When to use** + * + * Use when you need an installable completion script from an existing + * `CommandDescriptor`. + * + * **Details** + * + * Dispatches by `shell` to Bash, Zsh, or Fish generation and returns a static + * script string for `executableName`. + * + * @see {@link Shell} for supported shell names + * @see {@link CommandDescriptor} for the command shape used by completion generation + * * @category constructors + * @since 4.0.0 */ export const generate = ( executableName: string, diff --git a/.opencode/node_modules/effect/src/unstable/cli/Flag.ts b/.opencode/node_modules/effect/src/unstable/cli/Flag.ts index 54f8a15d74627f803720b1bcbbbdb5da1572d4d6..4e23594373d9c727a563660cb882cb7c1016b843 100644 --- a/.opencode/node_modules/effect/src/unstable/cli/Flag.ts +++ b/.opencode/node_modules/effect/src/unstable/cli/Flag.ts @@ -1,4 +1,13 @@ /** + * Defines named options for command-line applications. + * + * A `Flag` describes how to read one named value from parsed command-line + * input, validate it, and produce an `A`. Flags are useful for inputs such as + * ports, verbosity switches, configuration files, output directories, choices, + * secrets, and repeated values. The helpers here build flags with aliases, + * defaults, optional values, prompts, configuration fallbacks, validation, and + * value transformations. + * * @since 4.0.0 */ import type * as Config from "../../Config.ts" @@ -19,8 +28,8 @@ import type * as Primitive from "./Primitive.ts" /** * Represents a command-line flag. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface Flag extends Param.Param {} @@ -31,7 +40,8 @@ export interface Flag extends Param.Param {} /** * Creates a string flag that accepts text input. * - * @example + * **Example** (Creating string flags) + * * ```ts * import { Flag } from "effect/unstable/cli" * @@ -39,15 +49,16 @@ export interface Flag extends Param.Param {} * // Usage: --name "John Doe" * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const string = (name: string): Flag => Param.string(Param.flagKind, name) /** * Creates a boolean flag that can be enabled or disabled. * - * @example + * **Example** (Creating boolean flags) + * * ```ts * import { Flag } from "effect/unstable/cli" * @@ -55,15 +66,16 @@ export const string = (name: string): Flag => Param.string(Param.flagKin * // Usage: --verbose (true) or --no-verbose (false) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const boolean = (name: string): Flag => Param.boolean(Param.flagKind, name) /** * Creates an integer flag that accepts whole number input. * - * @example + * **Example** (Creating integer flags) + * * ```ts * import { Flag } from "effect/unstable/cli" * @@ -71,15 +83,16 @@ export const boolean = (name: string): Flag => Param.boolean(Param.flag * // Usage: --port 8080 * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const integer = (name: string): Flag => Param.integer(Param.flagKind, name) /** * Creates a float flag that accepts decimal number input. * - * @example + * **Example** (Creating float flags) + * * ```ts * import { Flag } from "effect/unstable/cli" * @@ -87,15 +100,16 @@ export const integer = (name: string): Flag => Param.integer(Param.flagK * // Usage: --rate 3.14 * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const float = (name: string): Flag => Param.float(Param.flagKind, name) /** * Creates a date flag that accepts date input in ISO format. * - * @example + * **Example** (Creating date flags) + * * ```ts * import { Flag } from "effect/unstable/cli" * @@ -103,8 +117,8 @@ export const float = (name: string): Flag => Param.float(Param.flagKind, * // Usage: --start-date 2023-12-25 * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const date = (name: string): Flag => Param.date(Param.flagKind, name) @@ -112,7 +126,8 @@ export const date = (name: string): Flag => Param.date(Param.flagKind, nam * Constructs option parameters that represent a choice between several inputs. * Each tuple maps a string flag value to an associated typed value. * - * @example + * **Example** (Creating flag choices with values) + * * ```ts * import { Flag } from "effect/unstable/cli" * @@ -127,8 +142,8 @@ export const date = (name: string): Flag => Param.date(Param.flagKind, nam * ]) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const choiceWithValue = >( name: string, @@ -136,10 +151,22 @@ export const choiceWithValue = => Param.choiceWithValue(Param.flagKind, name, choices) /** - * Simpler variant of `choiceWithValue` which maps each string to itself. + * Creates a flag that accepts one of the provided string choices and returns + * the selected string. + * + * **When to use** + * + * Use when you need to define a named CLI flag with fixed string choices and no + * custom value mapping. + * + * **Gotchas** + * + * An empty choices array compiles, but no input value can parse successfully. + * + * @see {@link choiceWithValue} for mapping accepted strings to different typed values * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const choice = >( name: string, @@ -149,7 +176,8 @@ export const choice = >( /** * Creates a path flag that accepts file system path input with validation options. * - * @example + * **Example** (Creating path flags) + * * ```ts * import { Flag } from "effect/unstable/cli" * @@ -169,8 +197,8 @@ export const choice = >( * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const path = (name: string, options?: { readonly pathType?: "file" | "directory" | "either" | undefined @@ -181,7 +209,8 @@ export const path = (name: string, options?: { /** * Creates a file path flag that accepts file paths with optional existence validation. * - * @example + * **Example** (Creating file flags) + * * ```ts * import { Flag } from "effect/unstable/cli" * @@ -194,8 +223,8 @@ export const path = (name: string, options?: { * // Usage: --config ./config.yaml (file must exist) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const file = (name: string, options?: { readonly mustExist?: boolean | undefined @@ -204,7 +233,8 @@ export const file = (name: string, options?: { /** * Creates a directory path flag that accepts directory paths with optional existence validation. * - * @example + * **Example** (Creating directory flags) + * * ```ts * import { Flag } from "effect/unstable/cli" * @@ -217,17 +247,24 @@ export const file = (name: string, options?: { * // Usage: --source ./src (directory must exist) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const directory = (name: string, options?: { readonly mustExist?: boolean | undefined }): Flag => Param.directory(Param.flagKind, name, options) /** - * Creates a redacted flag that securely handles sensitive string input. + * Creates a string flag whose parsed value is wrapped in `Redacted.Redacted` so + * stringification and logging redact the value. + * + * **Gotchas** + * + * Values supplied on the command line may still be visible to the operating + * system or shell history. + * + * **Example** (Creating redacted flags) * - * @example * ```ts * import { Effect, Redacted } from "effect" * import { Flag } from "effect/unstable/cli" @@ -244,15 +281,16 @@ export const directory = (name: string, options?: { * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const redacted = (name: string): Flag> => Param.redacted(Param.flagKind, name) /** * Creates a flag that reads and returns file content as a string. * - * @example + * **Example** (Reading file text) + * * ```ts * import { Flag } from "effect/unstable/cli" * @@ -260,18 +298,21 @@ export const redacted = (name: string): Flag> => Param * // --config-file ./app.json will read the file content * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fileText = (name: string): Flag => Param.fileText(Param.flagKind, name) /** * Creates a flag that reads and parses the content of the specified file. * + * **Details** + * * The parser that is utilized will depend on the specified `format`, or the * extension of the file passed on the command-line if no `format` is specified. * - * @example + * **Example** (Parsing file contents) + * * ```ts * import { Flag } from "effect/unstable/cli" * @@ -283,8 +324,8 @@ export const fileText = (name: string): Flag => Param.fileText(Param.fla * const jsonConfig = Flag.fileParse("json-config", { format: "json" }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fileParse = ( name: string, @@ -295,7 +336,8 @@ export const fileParse = ( * Creates a flag that reads and validates file content using the specified * schema. * - * @example + * **Example** (Validating file contents) + * * ```ts * import { Schema } from "effect" * import { Flag } from "effect/unstable/cli" @@ -308,8 +350,8 @@ export const fileParse = ( * const config = Flag.fileSchema("config", ConfigSchema, { format: "json" }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fileSchema = ( name: string, @@ -319,12 +361,19 @@ export const fileSchema = ( /** * Creates a flag that parses key=value pairs. - * Useful for options that accept configuration values. * - * Note: Requires at least one key=value pair. Multiple pairs are merged - * into a single record. + * **When to use** + * + * Use when you need a CLI flag that accepts one or more `key=value` + * configuration entries. + * + * **Details** + * + * Requires at least one key=value pair. Multiple pairs are merged into a single + * record. + * + * **Example** (Parsing key-value pairs) * - * @example * ```ts * import { Flag } from "effect/unstable/cli" * @@ -332,8 +381,8 @@ export const fileSchema = ( * // --env FOO=bar --env BAZ=qux will parse to { FOO: "bar", BAZ: "qux" } * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const keyValuePair = (name: string): Flag> => Param.keyValuePair(Param.flagKind, name) @@ -341,16 +390,20 @@ export const keyValuePair = (name: string): Flag> => Para * Creates an empty sentinel flag that always fails to parse. * This is useful for creating placeholder flags or for combinators. * - * @example + * **Example** (Creating sentinel flags) + * * ```ts * import { Flag } from "effect/unstable/cli" * - * // Used as a placeholder in flag combinators - * const conditionalFlag = true ? Flag.string("value") : Flag.none + * const makeValueFlag = (includeValue: boolean) => + * includeValue ? Flag.string("value") : Flag.none + * + * console.log(makeValueFlag(true) === Flag.none) // false + * console.log(makeValueFlag(false) === Flag.none) // true * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const none: Flag = Param.none(Param.flagKind) @@ -361,7 +414,8 @@ export const none: Flag = Param.none(Param.flagKind) /** * Adds an alias to a flag, allowing it to be referenced by multiple names. * - * @example + * **Example** (Adding flag aliases) + * * ```ts * import { Flag } from "effect/unstable/cli" * @@ -377,8 +431,8 @@ export const none: Flag = Param.none(Param.flagKind) * ) * ``` * - * @since 4.0.0 * @category aliasing + * @since 4.0.0 */ export const withAlias: { // ------------------------------------------------------------------------------------- @@ -388,7 +442,8 @@ export const withAlias: { /** * Adds an alias to a flag, allowing it to be referenced by multiple names. * - * @example + * **Example** (Adding flag aliases) + * * ```ts * import { Flag } from "effect/unstable/cli" * @@ -404,8 +459,8 @@ export const withAlias: { * ) * ``` * - * @since 4.0.0 * @category aliasing + * @since 4.0.0 */ (alias: string): (self: Flag) => Flag // ------------------------------------------------------------------------------------- @@ -415,7 +470,8 @@ export const withAlias: { /** * Adds an alias to a flag, allowing it to be referenced by multiple names. * - * @example + * **Example** (Adding flag aliases) + * * ```ts * import { Flag } from "effect/unstable/cli" * @@ -431,8 +487,8 @@ export const withAlias: { * ) * ``` * - * @since 4.0.0 * @category aliasing + * @since 4.0.0 */ (self: Flag, alias: string): Flag } = dual(2, (self: Flag, alias: string): Flag => Param.withAlias(self, alias)) @@ -440,7 +496,8 @@ export const withAlias: { /** * Adds a description to a flag for help documentation. * - * @example + * **Example** (Adding help descriptions) + * * ```ts * import { Flag } from "effect/unstable/cli" * @@ -453,14 +510,15 @@ export const withAlias: { * ) * ``` * - * @since 4.0.0 * @category help documentation + * @since 4.0.0 */ export const withDescription: { /** * Adds a description to a flag for help documentation. * - * @example + * **Example** (Adding help descriptions) + * * ```ts * import { Flag } from "effect/unstable/cli" * @@ -473,14 +531,15 @@ export const withDescription: { * ) * ``` * - * @since 4.0.0 * @category help documentation + * @since 4.0.0 */ (description: string): (self: Flag) => Flag /** * Adds a description to a flag for help documentation. * - * @example + * **Example** (Adding help descriptions) + * * ```ts * import { Flag } from "effect/unstable/cli" * @@ -493,8 +552,8 @@ export const withDescription: { * ) * ``` * - * @since 4.0.0 * @category help documentation + * @since 4.0.0 */ (self: Flag, description: string): Flag } = dual(2, (self: Flag, description: string) => Param.withDescription(self, description)) @@ -506,10 +565,13 @@ export const withDescription: { /** * Sets a custom metavar (placeholder name) for the flag in help documentation. * - * The metavar is displayed in usage text to indicate what value the user should provide. - * For example, `--output FILE` shows `FILE` as the metavar. + * **Details** + * + * The metavar is displayed in usage text to indicate what value the user should + * provide. For example, `--output FILE` shows `FILE` as the metavar. + * + * **Example** (Setting metavars) * - * @example * ```ts * import { Flag } from "effect/unstable/cli" * @@ -525,8 +587,8 @@ export const withDescription: { * // In help: --timeout SECONDS * ``` * - * @since 4.0.0 * @category metadata + * @since 4.0.0 */ export const withMetavar: { // ------------------------------------------------------------------------------------- @@ -536,10 +598,13 @@ export const withMetavar: { /** * Sets a custom metavar (placeholder name) for the flag in help documentation. * - * The metavar is displayed in usage text to indicate what value the user should provide. - * For example, `--output FILE` shows `FILE` as the metavar. + * **Details** + * + * The metavar is displayed in usage text to indicate what value the user should + * provide. For example, `--output FILE` shows `FILE` as the metavar. + * + * **Example** (Setting metavars) * - * @example * ```ts * import { Flag } from "effect/unstable/cli" * @@ -555,8 +620,8 @@ export const withMetavar: { * // In help: --timeout SECONDS * ``` * - * @since 4.0.0 * @category metadata + * @since 4.0.0 */ (metavar: string): (self: Flag) => Flag // ------------------------------------------------------------------------------------- @@ -566,10 +631,13 @@ export const withMetavar: { /** * Sets a custom metavar (placeholder name) for the flag in help documentation. * - * The metavar is displayed in usage text to indicate what value the user should provide. - * For example, `--output FILE` shows `FILE` as the metavar. + * **Details** + * + * The metavar is displayed in usage text to indicate what value the user should + * provide. For example, `--output FILE` shows `FILE` as the metavar. + * + * **Example** (Setting metavars) * - * @example * ```ts * import { Flag } from "effect/unstable/cli" * @@ -585,16 +653,43 @@ export const withMetavar: { * // In help: --timeout SECONDS * ``` * - * @since 4.0.0 * @category metadata + * @since 4.0.0 */ (self: Flag, metavar: string): Flag } = dual(2, (self: Flag, metavar: string) => Param.withMetavar(self, metavar)) +/** + * Hides a flag from generated help output and shell completions while keeping + * it fully parseable on the command line. + * + * **When to use** + * + * Use when experimental or internal flags should be accepted but not advertised, such as + * `--experimental-foo`, debug toggles, or escape hatches that are not yet committed to the + * public CLI surface. + * + * **Example** (Hiding a flag from help) + * + * ```ts + * import { Flag } from "effect/unstable/cli" + * + * // Flag still parses --experimental-foo, but it does not appear in --help. + * const experimental = Flag.boolean("experimental-foo").pipe( + * Flag.withHidden + * ) + * ``` + * + * @category metadata + * @since 4.0.0 + */ +export const withHidden = (self: Flag): Flag => Param.withHidden(self) + /** * Makes a flag optional, returning an Option type that can be None if not provided. * - * @example + * **Example** (Making flags optional) + * * ```ts * import { Effect, Option } from "effect" * import { Flag } from "effect/unstable/cli" @@ -614,15 +709,16 @@ export const withMetavar: { * }) * ``` * - * @since 4.0.0 * @category optionality + * @since 4.0.0 */ export const optional = (param: Flag): Flag> => Param.optional(param) /** * Provides a default value for a flag when it's not specified. * - * @example + * **Example** (Providing default values) + * * ```ts * import { Flag } from "effect/unstable/cli" * @@ -637,14 +733,15 @@ export const optional = (param: Flag): Flag> => Param.opt * // If --host is not provided, defaults to "localhost" * ``` * - * @since 4.0.0 * @category optionality + * @since 4.0.0 */ export const withDefault: { /** * Provides a default value for a flag when it's not specified. * - * @example + * **Example** (Providing default values) + * * ```ts * import { Flag } from "effect/unstable/cli" * @@ -659,14 +756,15 @@ export const withDefault: { * // If --host is not provided, defaults to "localhost" * ``` * - * @since 4.0.0 * @category optionality + * @since 4.0.0 */ (defaultValue: B | Effect.Effect): (self: Flag) => Flag /** * Provides a default value for a flag when it's not specified. * - * @example + * **Example** (Providing default values) + * * ```ts * import { Flag } from "effect/unstable/cli" * @@ -681,8 +779,8 @@ export const withDefault: { * // If --host is not provided, defaults to "localhost" * ``` * - * @since 4.0.0 * @category optionality + * @since 4.0.0 */ ( self: Flag, @@ -693,7 +791,8 @@ export const withDefault: { /** * Adds a fallback config that is loaded when a required flag is missing. * - * @example + * **Example** (Falling back to config) + * * ```ts * import { Config } from "effect" * import { Flag } from "effect/unstable/cli" @@ -703,14 +802,15 @@ export const withDefault: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const withFallbackConfig: { /** * Adds a fallback config that is loaded when a required flag is missing. * - * @example + * **Example** (Falling back to config) + * * ```ts * import { Config } from "effect" * import { Flag } from "effect/unstable/cli" @@ -720,14 +820,15 @@ export const withFallbackConfig: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (config: Config.Config): (self: Flag) => Flag /** * Adds a fallback config that is loaded when a required flag is missing. * - * @example + * **Example** (Falling back to config) + * * ```ts * import { Config } from "effect" * import { Flag } from "effect/unstable/cli" @@ -737,8 +838,8 @@ export const withFallbackConfig: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Flag, config: Config.Config): Flag } = dual(2, (self: Flag, config: Config.Config) => Param.withFallbackConfig(self, config)) @@ -746,7 +847,8 @@ export const withFallbackConfig: { /** * Adds a fallback prompt that is shown when a required flag is missing. * - * @example + * **Example** (Falling back to prompts) + * * ```ts * import { Flag, Prompt } from "effect/unstable/cli" * @@ -755,14 +857,15 @@ export const withFallbackConfig: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const withFallbackPrompt: { /** * Adds a fallback prompt that is shown when a required flag is missing. * - * @example + * **Example** (Falling back to prompts) + * * ```ts * import { Flag, Prompt } from "effect/unstable/cli" * @@ -771,14 +874,15 @@ export const withFallbackPrompt: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (prompt: Param.FallbackPrompt): (self: Flag) => Flag /** * Adds a fallback prompt that is shown when a required flag is missing. * - * @example + * **Example** (Falling back to prompts) + * * ```ts * import { Flag, Prompt } from "effect/unstable/cli" * @@ -787,8 +891,8 @@ export const withFallbackPrompt: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Flag, prompt: Param.FallbackPrompt): Flag } = dual(2, (self: Flag, prompt: Param.FallbackPrompt) => Param.withFallbackPrompt(self, prompt)) @@ -796,7 +900,8 @@ export const withFallbackPrompt: { /** * Transforms the parsed value of a flag using a mapping function. * - * @example + * **Example** (Mapping parsed values) + * * ```ts * import { Flag } from "effect/unstable/cli" * @@ -811,14 +916,15 @@ export const withFallbackPrompt: { * ) * ``` * - * @since 4.0.0 * @category mapping + * @since 4.0.0 */ export const map: { /** * Transforms the parsed value of a flag using a mapping function. * - * @example + * **Example** (Mapping parsed values) + * * ```ts * import { Flag } from "effect/unstable/cli" * @@ -833,14 +939,15 @@ export const map: { * ) * ``` * - * @since 4.0.0 * @category mapping + * @since 4.0.0 */ (f: (a: A) => B): (self: Flag) => Flag /** * Transforms the parsed value of a flag using a mapping function. * - * @example + * **Example** (Mapping parsed values) + * * ```ts * import { Flag } from "effect/unstable/cli" * @@ -855,8 +962,8 @@ export const map: { * ) * ``` * - * @since 4.0.0 * @category mapping + * @since 4.0.0 */ (self: Flag, f: (a: A) => B): Flag } = dual(2, (self: Flag, f: (a: A) => B) => Param.map(self, f)) @@ -864,7 +971,8 @@ export const map: { /** * Transforms the parsed value using an Effect that can perform IO operations. * - * @example + * **Example** (Mapping parsed values effectfully) + * * ```ts * import { Effect, FileSystem } from "effect" * import { Flag } from "effect/unstable/cli" @@ -879,14 +987,15 @@ export const map: { * ) * ``` * - * @since 4.0.0 * @category mapping + * @since 4.0.0 */ export const mapEffect: { /** * Transforms the parsed value using an Effect that can perform IO operations. * - * @example + * **Example** (Mapping parsed values effectfully) + * * ```ts * import { Effect, FileSystem } from "effect" * import { Flag } from "effect/unstable/cli" @@ -901,14 +1010,15 @@ export const mapEffect: { * ) * ``` * - * @since 4.0.0 * @category mapping + * @since 4.0.0 */ (f: (a: A) => Effect.Effect): (self: Flag) => Flag /** * Transforms the parsed value using an Effect that can perform IO operations. * - * @example + * **Example** (Mapping parsed values effectfully) + * * ```ts * import { Effect, FileSystem } from "effect" * import { Flag } from "effect/unstable/cli" @@ -923,8 +1033,8 @@ export const mapEffect: { * ) * ``` * - * @since 4.0.0 * @category mapping + * @since 4.0.0 */ ( self: Flag, @@ -938,7 +1048,8 @@ export const mapEffect: { /** * Transforms the parsed value using a function that might throw, with error handling. * - * @example + * **Example** (Mapping thrown errors) + * * ```ts * import { Flag } from "effect/unstable/cli" * @@ -959,14 +1070,15 @@ export const mapEffect: { * ) * ``` * - * @since 4.0.0 * @category mapping + * @since 4.0.0 */ export const mapTryCatch: { /** * Transforms the parsed value using a function that might throw, with error handling. * - * @example + * **Example** (Mapping thrown errors) + * * ```ts * import { Flag } from "effect/unstable/cli" * @@ -987,14 +1099,15 @@ export const mapTryCatch: { * ) * ``` * - * @since 4.0.0 * @category mapping + * @since 4.0.0 */ (f: (a: A) => B, onError: (error: unknown) => string): (self: Flag) => Flag /** * Transforms the parsed value using a function that might throw, with error handling. * - * @example + * **Example** (Mapping thrown errors) + * * ```ts * import { Flag } from "effect/unstable/cli" * @@ -1015,8 +1128,8 @@ export const mapTryCatch: { * ) * ``` * - * @since 4.0.0 * @category mapping + * @since 4.0.0 */ (self: Flag, f: (a: A) => B, onError: (error: unknown) => string): Flag } = dual(3, ( @@ -1026,9 +1139,10 @@ export const mapTryCatch: { ) => Param.mapTryCatch(self, f, onError)) /** - * Requires a flag to be specified at least a minimum number of times. + * Ensures a flag is specified at least a minimum number of times. + * + * **Example** (Requiring repeated values) * - * @example * ```ts * import { Flag } from "effect/unstable/cli" * @@ -1042,14 +1156,15 @@ export const mapTryCatch: { * // Requires at least 1 tag * ``` * - * @since 4.0.0 * @category repetition + * @since 4.0.0 */ export const atLeast: { /** - * Requires a flag to be specified at least a minimum number of times. + * Ensures a flag is specified at least a minimum number of times. + * + * **Example** (Requiring repeated values) * - * @example * ```ts * import { Flag } from "effect/unstable/cli" * @@ -1063,14 +1178,15 @@ export const atLeast: { * // Requires at least 1 tag * ``` * - * @since 4.0.0 * @category repetition + * @since 4.0.0 */ (min: number): (self: Flag) => Flag> /** - * Requires a flag to be specified at least a minimum number of times. + * Ensures a flag is specified at least a minimum number of times. + * + * **Example** (Requiring repeated values) * - * @example * ```ts * import { Flag } from "effect/unstable/cli" * @@ -1084,16 +1200,17 @@ export const atLeast: { * // Requires at least 1 tag * ``` * - * @since 4.0.0 * @category repetition + * @since 4.0.0 */ (self: Flag, min: number): Flag> } = dual(2, (self: Flag, min: number) => Param.atLeast(self, min)) /** - * Limits a flag to be specified at most a maximum number of times. + * Ensures a flag is specified at most a maximum number of times. + * + * **Example** (Limiting repeated values) * - * @example * ```ts * import { Flag } from "effect/unstable/cli" * @@ -1107,14 +1224,15 @@ export const atLeast: { * // Allows at most 1 debug flag * ``` * - * @since 4.0.0 * @category repetition + * @since 4.0.0 */ export const atMost: { /** - * Limits a flag to be specified at most a maximum number of times. + * Ensures a flag is specified at most a maximum number of times. + * + * **Example** (Limiting repeated values) * - * @example * ```ts * import { Flag } from "effect/unstable/cli" * @@ -1128,14 +1246,15 @@ export const atMost: { * // Allows at most 1 debug flag * ``` * - * @since 4.0.0 * @category repetition + * @since 4.0.0 */ (max: number): (self: Flag) => Flag> /** - * Limits a flag to be specified at most a maximum number of times. + * Ensures a flag is specified at most a maximum number of times. + * + * **Example** (Limiting repeated values) * - * @example * ```ts * import { Flag } from "effect/unstable/cli" * @@ -1149,16 +1268,17 @@ export const atMost: { * // Allows at most 1 debug flag * ``` * - * @since 4.0.0 * @category repetition + * @since 4.0.0 */ (self: Flag, max: number): Flag> } = dual(2, (self: Flag, max: number) => Param.atMost(self, max)) /** - * Constrains a flag to be specified between a minimum and maximum number of times. + * Ensures a flag is specified between a minimum and maximum number of times. + * + * **Example** (Bounding repeated values) * - * @example * ```ts * import { Flag } from "effect/unstable/cli" * @@ -1172,14 +1292,15 @@ export const atMost: { * // Allows 0-5 exclude patterns * ``` * - * @since 4.0.0 * @category repetition + * @since 4.0.0 */ export const between: { /** - * Constrains a flag to be specified between a minimum and maximum number of times. + * Ensures a flag is specified between a minimum and maximum number of times. + * + * **Example** (Bounding repeated values) * - * @example * ```ts * import { Flag } from "effect/unstable/cli" * @@ -1193,14 +1314,15 @@ export const between: { * // Allows 0-5 exclude patterns * ``` * - * @since 4.0.0 * @category repetition + * @since 4.0.0 */ (min: number, max: number): (self: Flag) => Flag> /** - * Constrains a flag to be specified between a minimum and maximum number of times. + * Ensures a flag is specified between a minimum and maximum number of times. + * + * **Example** (Bounding repeated values) * - * @example * ```ts * import { Flag } from "effect/unstable/cli" * @@ -1214,8 +1336,8 @@ export const between: { * // Allows 0-5 exclude patterns * ``` * - * @since 4.0.0 * @category repetition + * @since 4.0.0 */ (self: Flag, min: number, max: number): Flag> } = dual(3, (self: Flag, min: number, max: number) => Param.between(self, min, max)) @@ -1223,7 +1345,8 @@ export const between: { /** * Transforms and filters a flag value, failing with a custom error if the transformation returns None. * - * @example + * **Example** (Filtering and transforming values) + * * ```ts * import { Option } from "effect" * import { Flag } from "effect/unstable/cli" @@ -1245,14 +1368,15 @@ export const between: { * ) * ``` * - * @since 4.0.0 * @category filtering + * @since 4.0.0 */ export const filterMap: { /** * Transforms and filters a flag value, failing with a custom error if the transformation returns None. * - * @example + * **Example** (Filtering and transforming values) + * * ```ts * import { Option } from "effect" * import { Flag } from "effect/unstable/cli" @@ -1274,14 +1398,15 @@ export const filterMap: { * ) * ``` * - * @since 4.0.0 * @category filtering + * @since 4.0.0 */ (f: (a: A) => Option.Option, onNone: (a: A) => string): (self: Flag) => Flag /** * Transforms and filters a flag value, failing with a custom error if the transformation returns None. * - * @example + * **Example** (Filtering and transforming values) + * * ```ts * import { Option } from "effect" * import { Flag } from "effect/unstable/cli" @@ -1303,8 +1428,8 @@ export const filterMap: { * ) * ``` * - * @since 4.0.0 * @category filtering + * @since 4.0.0 */ (self: Flag, f: (a: A) => Option.Option, onNone: (a: A) => string): Flag } = dual(3, ( @@ -1316,7 +1441,8 @@ export const filterMap: { /** * Filters a flag value based on a predicate, failing with a custom error if the predicate returns false. * - * @example + * **Example** (Filtering parsed values) + * * ```ts * import { Flag } from "effect/unstable/cli" * @@ -1337,14 +1463,15 @@ export const filterMap: { * ) * ``` * - * @since 4.0.0 * @category filtering + * @since 4.0.0 */ export const filter: { /** * Filters a flag value based on a predicate, failing with a custom error if the predicate returns false. * - * @example + * **Example** (Filtering parsed values) + * * ```ts * import { Flag } from "effect/unstable/cli" * @@ -1365,14 +1492,15 @@ export const filter: { * ) * ``` * - * @since 4.0.0 * @category filtering + * @since 4.0.0 */ (predicate: (a: A) => boolean, onFalse: (a: A) => string): (self: Flag) => Flag /** * Filters a flag value based on a predicate, failing with a custom error if the predicate returns false. * - * @example + * **Example** (Filtering parsed values) + * * ```ts * import { Flag } from "effect/unstable/cli" * @@ -1393,8 +1521,8 @@ export const filter: { * ) * ``` * - * @since 4.0.0 * @category filtering + * @since 4.0.0 */ (self: Flag, predicate: (a: A) => boolean, onFalse: (a: A) => string): Flag } = dual(3, ( @@ -1406,7 +1534,8 @@ export const filter: { /** * Provides an alternative flag if the first one fails to parse. * - * @example + * **Example** (Falling back to another flag) + * * ```ts * import { Flag } from "effect/unstable/cli" * @@ -1423,14 +1552,15 @@ export const filter: { * ) * ``` * - * @since 4.0.0 * @category alternatives + * @since 4.0.0 */ export const orElse: { /** * Provides an alternative flag if the first one fails to parse. * - * @example + * **Example** (Falling back to another flag) + * * ```ts * import { Flag } from "effect/unstable/cli" * @@ -1447,14 +1577,15 @@ export const orElse: { * ) * ``` * - * @since 4.0.0 * @category alternatives + * @since 4.0.0 */ (that: LazyArg>): (self: Flag) => Flag /** * Provides an alternative flag if the first one fails to parse. * - * @example + * **Example** (Falling back to another flag) + * * ```ts * import { Flag } from "effect/unstable/cli" * @@ -1471,8 +1602,8 @@ export const orElse: { * ) * ``` * - * @since 4.0.0 * @category alternatives + * @since 4.0.0 */ (self: Flag, that: LazyArg>): Flag } = dual(2, (self: Flag, that: LazyArg>) => Param.orElse(self, that)) @@ -1480,7 +1611,8 @@ export const orElse: { /** * Tries to parse with the first flag, then the second, returning a Result that indicates which succeeded. * - * @example + * **Example** (Returning fallback results) + * * ```ts * import { Effect, Result } from "effect" * import { Flag } from "effect/unstable/cli" @@ -1504,14 +1636,15 @@ export const orElse: { * }) * ``` * - * @since 4.0.0 * @category alternatives + * @since 4.0.0 */ export const orElseResult: { /** * Tries to parse with the first flag, then the second, returning a Result that indicates which succeeded. * - * @example + * **Example** (Returning fallback results) + * * ```ts * import { Effect, Result } from "effect" * import { Flag } from "effect/unstable/cli" @@ -1535,14 +1668,15 @@ export const orElseResult: { * }) * ``` * - * @since 4.0.0 * @category alternatives + * @since 4.0.0 */ (that: LazyArg>): (self: Flag) => Flag> /** * Tries to parse with the first flag, then the second, returning a Result that indicates which succeeded. * - * @example + * **Example** (Returning fallback results) + * * ```ts * import { Effect, Result } from "effect" * import { Flag } from "effect/unstable/cli" @@ -1566,8 +1700,8 @@ export const orElseResult: { * }) * ``` * - * @since 4.0.0 * @category alternatives + * @since 4.0.0 */ (self: Flag, that: LazyArg>): Flag> } = dual(2, (self: Flag, that: LazyArg>) => Param.orElseResult(self, that)) @@ -1575,12 +1709,13 @@ export const orElseResult: { /** * Validates and transforms a flag value using a Schema codec. * - * @example + * **Example** (Validating with schemas) + * * ```ts * import { Schema } from "effect" * import { Flag } from "effect/unstable/cli" * - * const isEmail = Schema.isIncludes("@", { + * const isEmail = Schema.isPattern(/^[^\s@]+@[^\s@]+\.[^\s@]+$/, { * message: "Must be a valid email address" * }) * @@ -1605,19 +1740,20 @@ export const orElseResult: { * ) * ``` * - * @since 4.0.0 * @category schemas + * @since 4.0.0 */ export const withSchema: { /** * Validates and transforms a flag value using a Schema codec. * - * @example + * **Example** (Validating with schemas) + * * ```ts * import { Schema } from "effect" * import { Flag } from "effect/unstable/cli" * - * const isEmail = Schema.isIncludes("@", { + * const isEmail = Schema.isPattern(/^[^\s@]+@[^\s@]+\.[^\s@]+$/, { * message: "Must be a valid email address" * }) * @@ -1642,19 +1778,20 @@ export const withSchema: { * ) * ``` * - * @since 4.0.0 * @category schemas + * @since 4.0.0 */ (schema: Schema.Codec): (self: Flag) => Flag /** * Validates and transforms a flag value using a Schema codec. * - * @example + * **Example** (Validating with schemas) + * * ```ts * import { Schema } from "effect" * import { Flag } from "effect/unstable/cli" * - * const isEmail = Schema.isIncludes("@", { + * const isEmail = Schema.isPattern(/^[^\s@]+@[^\s@]+\.[^\s@]+$/, { * message: "Must be a valid email address" * }) * @@ -1679,8 +1816,8 @@ export const withSchema: { * ) * ``` * - * @since 4.0.0 * @category schemas + * @since 4.0.0 */ (self: Flag, schema: Schema.Codec): Flag } = dual(2, (self: Flag, schema: Schema.Codec) => Param.withSchema(self, schema)) diff --git a/.opencode/node_modules/effect/src/unstable/cli/GlobalFlag.ts b/.opencode/node_modules/effect/src/unstable/cli/GlobalFlag.ts index 6b09652c63464164824abeaa804941776d51fa43..b4eb343e97ca3e9075162ef94cebecafd7899365 100644 --- a/.opencode/node_modules/effect/src/unstable/cli/GlobalFlag.ts +++ b/.opencode/node_modules/effect/src/unstable/cli/GlobalFlag.ts @@ -1,4 +1,13 @@ /** + * Global flags for Effect CLI command trees. Global flags are parsed outside a + * single command's local flags and can apply to a command and its descendants. + * + * This module defines two kinds of global flags: action flags, which run an + * effect and stop normal command execution, and setting flags, which provide a + * parsed value to the command handler through the Effect context. It also + * defines the built-in help, version, shell-completion, and log-level flags + * used by `Command.run` and `Command.runWith`. + * * @since 4.0.0 */ @@ -21,11 +30,11 @@ import * as HelpInternal from "./internal/help.ts" /** * Context passed to action handlers. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface HandlerContext { - readonly command: Command.Command + readonly command: Command.Command.Any readonly commandPath: ReadonlyArray readonly version: string } @@ -33,8 +42,8 @@ export interface HandlerContext { /** * Action flag: side effect + exit (--help, --version, --completions). * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface Action { readonly _tag: "Action" @@ -48,8 +57,8 @@ export interface Action { /** * Setting flag: configure command handler's environment (--log-level, --config). * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface Setting extends Context.Service, A> { readonly _tag: "Setting" @@ -58,12 +67,17 @@ export interface Setting extends Context.Service = `effect/unstable/cli/GlobalFlag/${Id}` } @@ -71,8 +85,8 @@ export declare namespace Setting { /** * Global flag discriminated union. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type GlobalFlag = Action | Setting @@ -83,8 +97,8 @@ export type GlobalFlag = Action | Setting /** * Creates an Action flag that performs a side effect and exits. * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const action = (options: { readonly flag: Flag.Flag @@ -101,8 +115,8 @@ export const action = (options: { /** * Creates a Setting flag that configures the command handler's environment. * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const setting = ( id: Id @@ -128,11 +142,14 @@ let settingIdCounter = 0 /* ========================================================================== */ /** - * The `--help` / `-h` global flag. - * Shows help documentation for the command. + * Defines the `--help` / `-h` global flag, which shows help documentation for the + * active command path. + * + * @see {@link BuiltIns} for the default list containing this flag + * @see {@link action} for defining custom action global flags * - * @since 4.0.0 * @category references + * @since 4.0.0 */ export const Help: Action = action({ flag: Flag.boolean("help").pipe( @@ -148,14 +165,18 @@ export const Help: Action = action({ }) /** - * The `--version` global flag. - * Shows version information for the command. + * Defines the global action flag for showing command version information. + * + * **When to use** + * + * Use to add a built-in `--version / -v` flag to a command runner. * - * @since 4.0.0 * @category references + * @since 4.0.0 */ export const Version: Action = action({ flag: Flag.boolean("version").pipe( + Flag.withAlias("v"), Flag.withDescription("Show version information") ), run: (_, { command, version }) => @@ -166,17 +187,23 @@ export const Version: Action = action({ }) /** - * The `--completions` global flag. - * Prints shell completion script for the given shell. + * Defines the `--completions` global flag, which prints a shell completion script for + * the given shell. + * + * **Details** + * + * Accepted values are `bash`, `zsh`, `fish`, and `sh`; `sh` is normalized to + * `bash`. * - * @since 4.0.0 * @category references + * @since 4.0.0 */ export const Completions: Action> = action({ flag: Flag.choice("completions", ["bash", "zsh", "fish", "sh"] as const) .pipe( Flag.optional, Flag.map((v) => Option.map(v, (s) => s === "sh" ? "bash" : s)), + Flag.withMetavar(""), Flag.withDescription("Print shell completion script") ), run: (shell, { command }) => @@ -190,11 +217,15 @@ export const Completions: Action> = actio }) /** - * The `--log-level` global flag. - * Sets the minimum log level for the command. + * Defines the global setting flag for command log level. + * + * **When to use** + * + * Use to add a built-in `--log-level` option that configures the minimum log + * level for the command. * - * @since 4.0.0 * @category references + * @since 4.0.0 */ export const LogLevel: Setting<"log-level", Option.Option> = setting("log-level")({ flag: Flag.choiceWithValue( @@ -212,7 +243,8 @@ export const LogLevel: Setting<"log-level", Option.Option> = setti ] as const ).pipe( Flag.optional, - Flag.withDescription("Sets the minimum log level") + Flag.withDescription("Sets the minimum log level"), + Flag.withMetavar("") ) }) @@ -223,8 +255,29 @@ export const LogLevel: Setting<"log-level", Option.Option> = setti /** * Built-in global flags in default precedence order. * - * @since 4.0.0 + * **When to use** + * + * Use when extending or inspecting the default global-flag set that + * `Command.runWith` prepends before user-defined global flags. + * + * **Details** + * + * The built-ins are `Help`, `Version`, `Completions`, and `LogLevel`. + * `Command.runWith` prepends these built-ins when collecting and parsing global + * flags. + * + * **Gotchas** + * + * Action flags are processed in active flag order and the first present action + * exits, so this array controls built-in action precedence. + * + * @see {@link Help} for the help action flag + * @see {@link Version} for the version action flag + * @see {@link Completions} for the shell-completions action flag + * @see {@link LogLevel} for the built-in log-level setting flag + * * @category references + * @since 4.0.0 */ export const BuiltIns: ReadonlyArray> = [ Help, @@ -236,7 +289,7 @@ export const BuiltIns: ReadonlyArray> = [ /** * Built-in setting context identifiers. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type BuiltInSettingContext = Setting.Identifier<"log-level"> diff --git a/.opencode/node_modules/effect/src/unstable/cli/HelpDoc.ts b/.opencode/node_modules/effect/src/unstable/cli/HelpDoc.ts index 58754a2f6a2c2d1690bc444219942ff41edb3360..e1dc75846b7ed7f6dceb1319e0c6edbe8c0ce7a3 100644 --- a/.opencode/node_modules/effect/src/unstable/cli/HelpDoc.ts +++ b/.opencode/node_modules/effect/src/unstable/cli/HelpDoc.ts @@ -1,4 +1,12 @@ /** + * Structured help documentation model for the unstable CLI package. A + * `HelpDoc` value captures the user-facing parts of a command, including its + * description, usage string, positional arguments, flags, global flags, + * subcommands, annotations, and examples. + * + * This module only defines the data shapes used to describe help. Rendering + * that data as terminal text is handled by `CliOutput`. + * * @since 4.0.0 */ @@ -11,10 +19,11 @@ import type * as Option from "../../Option.ts" * This data structure is independent of formatting, allowing for * different output formats (text, markdown, JSON, etc.). * - * @example + * **Example** (Defining command help documentation) + * * ```ts - * import { Option as O, Context } from "effect" - * import type * as HelpDoc from "effect/unstable/cli/HelpDoc" + * import { Context, Option as O } from "effect" + * import type { HelpDoc } from "effect/unstable/cli" * * const deployCommandHelp: HelpDoc.HelpDoc = { * description: "Deploy your application to the cloud", @@ -48,8 +57,8 @@ import type * as Option from "../../Option.ts" * } * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface HelpDoc { /** @@ -97,8 +106,8 @@ export interface HelpDoc { /** * Documentation for a command usage example * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface ExampleDoc { /** @@ -115,7 +124,8 @@ export interface ExampleDoc { /** * Documentation for a single command-line flag/option * - * @example + * **Example** (Documenting command flags) + * * ```ts * import { Option as O } from "effect" * import type { HelpDoc } from "effect/unstable/cli" @@ -137,8 +147,8 @@ export interface ExampleDoc { * } * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface FlagDoc { /** @@ -170,9 +180,10 @@ export interface FlagDoc { /** * Documentation for a subcommand * - * @example + * **Example** (Documenting subcommands) + * * ```ts - * import { Option as O, Context } from "effect" + * import { Context, Option as O } from "effect" * import type { HelpDoc } from "effect/unstable/cli" * * const deploySubcommand: HelpDoc.SubcommandDoc = { @@ -202,8 +213,8 @@ export interface FlagDoc { * } * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface SubcommandDoc { /** @@ -230,8 +241,8 @@ export interface SubcommandDoc { /** * Documentation for a grouped subcommand listing * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface SubcommandGroupDoc { /** @@ -249,9 +260,10 @@ export interface SubcommandGroupDoc { /** * Documentation for a positional argument * - * @example + * **Example** (Documenting positional arguments) + * * ```ts - * import { Option as O, Context } from "effect" + * import { Context, Option as O } from "effect" * import type { HelpDoc } from "effect/unstable/cli" * * const sourceArg: HelpDoc.ArgDoc = { @@ -280,8 +292,8 @@ export interface SubcommandGroupDoc { * } * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface ArgDoc { /** diff --git a/.opencode/node_modules/effect/src/unstable/cli/Param.ts b/.opencode/node_modules/effect/src/unstable/cli/Param.ts index bd83b7adc786d8f3d327c0eee296161b2c7dc807..f4f532ed769e52a7c4d9f47433b7f2a38d799d6a 100644 --- a/.opencode/node_modules/effect/src/unstable/cli/Param.ts +++ b/.opencode/node_modules/effect/src/unstable/cli/Param.ts @@ -1,12 +1,12 @@ /** - * @internal - * - * Param is the polymorphic implementation shared by Argument.ts and Flag.ts. - * The `Kind` type parameter ("argument" | "flag") enables type-safe separation - * while sharing parsing logic and combinators. + * Defines the shared parameter model for CLI arguments and flags. * - * Users should import from `Argument` and `Flag` modules, not this module directly. - * This module is not exported from the public API. + * A `Param` describes how to consume parsed command-line input and + * return a typed value. The `Kind` decides whether the parameter reads + * positional arguments or named flags. `Argument` and `Flag` build on this + * module to share parsing structure, primitive constructors, help metadata, + * aliases, defaults, prompts, configuration fallbacks, validation, schema + * decoding, fallback parameters, and traversal helpers. * * @since 4.0.0 */ @@ -31,8 +31,15 @@ import * as Prompt from "./Prompt.ts" const TypeId = "~effect/cli/Param" /** - * @since 4.0.0 + * Polymorphic CLI parameter shared by `Argument` and `Flag`. + * + * **Details** + * + * A parameter knows whether it consumes positional arguments or flags and + * parses a `ParsedArgs` value into its typed result. + * * @category models + * @since 4.0.0 */ export interface Param extends Param.Variance { readonly _tag: "Single" | "Map" | "Transform" | "Optional" | "Variadic" @@ -41,60 +48,89 @@ export interface Param extends Param.Variance } /** - * @since 4.0.0 + * Discriminator for whether a `Param` parses positional arguments or + * command-line flags. + * * @category models + * @since 4.0.0 */ export type ParamKind = "argument" | "flag" /** - * @since 4.0.0 + * Services that parameter parsing can require, such as filesystem, path, + * terminal, and child-process support. + * * @category models + * @since 4.0.0 */ export type Environment = FileSystem.FileSystem | Path.Path | Terminal.Terminal | ChildProcessSpawner /** - * Kind discriminator for positional argument parameters. + * Defines the kind discriminator for positional argument parameters. + * + * **When to use** + * + * Use to build low-level `Param` constructors or type positions for positional + * argument parameters. + * + * @see {@link flagKind} for the named flag parameter discriminator + * @see {@link ParamKind} for the full parameter kind union * - * @since 4.0.0 * @category constants + * @since 4.0.0 */ export const argumentKind: "argument" = "argument" as const /** - * Kind discriminator for flag parameters. + * Defines the kind discriminator for flag parameters. + * + * **When to use** + * + * Use to build low-level `Param` constructors or type positions for named flag + * parameters. + * + * @see {@link argumentKind} for the positional argument parameter discriminator * - * @since 4.0.0 * @category constants + * @since 4.0.0 */ export const flagKind: "flag" = "flag" as const /** * Represents any parameter. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type Any = Param /** * Represents any positional argument parameter. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type AnyArgument = Param /** * Represents any flag parameter. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type AnyFlag = Param /** - * @since 4.0.0 + * Function type used by parameters to parse currently available flags and + * positional arguments. + * + * **Details** + * + * It returns the remaining positional arguments together with the parsed value, + * or fails with a `CliError` while requiring the CLI parsing environment. + * * @category models + * @since 4.0.0 */ export type Parse = (args: ParsedArgs) => Effect.Effect< readonly [leftover: ReadonlyArray, value: A], @@ -103,12 +139,16 @@ export type Parse = (args: ParsedArgs) => Effect.Effect< > /** + * Namespace containing type-level utilities attached to the `Param` interface. + * * @since 4.0.0 */ export declare namespace Param { /** - * @since 4.0.0 + * Variance and pipeability marker carried by every `Param` value. + * * @category models + * @since 4.0.0 */ export interface Variance extends Pipeable { readonly [TypeId]: { @@ -121,8 +161,8 @@ export declare namespace Param { * Map of flag names to their provided string values. * Multiple occurrences of a flag produce multiple values. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type Flags = Record> @@ -131,8 +171,8 @@ export type Flags = Record> * - `flags`: already-collected flag values by canonical flag name * - `arguments`: remaining positional arguments to be consumed * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface ParsedArgs { readonly flags: Flags @@ -143,16 +183,23 @@ export interface ParsedArgs { * Represents a fallback prompt that can either be provided directly or * computed effectfully when the parameter is missing. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type FallbackPrompt = | Prompt.Prompt | Effect.Effect, CliError.CliError, Environment> /** - * @since 4.0.0 + * Leaf parameter that reads one named argument or flag with a primitive parser. + * + * **Details** + * + * Single parameters carry the user-facing name, aliases, description, primitive + * type, and optional metavar/type name used in help output. + * * @category models + * @since 4.0.0 */ export interface Single extends Param { readonly _tag: "Single" @@ -162,11 +209,15 @@ export interface Single extends Param { readonly aliases: ReadonlyArray readonly primitiveType: Primitive.Primitive readonly typeName?: string | undefined + readonly hidden: boolean } /** - * @since 4.0.0 + * Parameter node that maps the successfully parsed value of another parameter + * with a pure function. + * * @category models + * @since 4.0.0 */ export interface Map extends Param { readonly _tag: "Map" @@ -176,8 +227,12 @@ export interface Map extends Param extends Param { readonly _tag: "Transform" @@ -187,8 +242,11 @@ export interface Transform extends Para } /** - * @since 4.0.0 + * Parameter node that turns a missing argument or flag into `Option.none()` and + * a present parsed value into `Option.some(value)`. + * * @category models + * @since 4.0.0 */ export interface Optional extends Param> { readonly _tag: "Optional" @@ -197,8 +255,12 @@ export interface Optional extends Param extends Param> { readonly _tag: "Variadic" @@ -220,9 +282,10 @@ const Proto = { /** * Type guard to check if a value is a Param. * - * @example + * **Example** (Checking for params) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -233,17 +296,18 @@ const Proto = { * } * ``` * - * @since 4.0.0 * @category refinements + * @since 4.0.0 */ export const isParam = (u: unknown): u is Param => Predicate.hasProperty(u, TypeId) /** * Type guard to check if a param is a Single param (not composed). * - * @example + * **Example** (Checking for single params) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -254,8 +318,8 @@ export const isParam = (u: unknown): u is Param => Predicate.has * console.log(Param.isSingle(optionalParam)) // false * ``` * - * @since 4.0.0 * @category refinements + * @since 4.0.0 */ export const isSingle = ( param: Param @@ -271,8 +335,16 @@ export const isFlagParam = ( ): single is Single => single.kind === "flag" /** - * @since 4.0.0 + * Constructs a leaf `Single` parameter from its kind, name, primitive parser, + * and optional help metadata. + * + * **Details** + * + * The returned parser reads either one positional argument or the named flag, + * depending on `kind`. + * * @category constructors + * @since 4.0.0 */ export const makeSingle = (params: { readonly kind: Kind @@ -281,6 +353,7 @@ export const makeSingle = (params: { readonly typeName?: string | undefined readonly description?: Option.Option | undefined readonly aliases?: ReadonlyArray | undefined + readonly hidden?: boolean | undefined }): Single => { const parse: Parse = (args) => params.kind === argumentKind @@ -291,6 +364,7 @@ export const makeSingle = (params: { ...params, description: params.description ?? Option.none(), aliases: params.aliases ?? [], + hidden: params.hidden ?? false, parse }) } @@ -298,9 +372,10 @@ export const makeSingle = (params: { /** * Creates a string parameter. * - * @example + * **Example** (Creating string parameters) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -313,8 +388,8 @@ export const makeSingle = (params: { * // Usage in CLI: --name "John Doe" or as positional argument * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const string = ( kind: Kind, @@ -329,9 +404,10 @@ export const string = ( /** * Creates a boolean parameter. * - * @example + * **Example** (Creating boolean parameters) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -345,8 +421,8 @@ export const string = ( * // or as positional: true/false * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const boolean = ( kind: Kind, @@ -361,9 +437,10 @@ export const boolean = ( /** * Creates an integer parameter. * - * @example + * **Example** (Creating integer parameters) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -376,8 +453,8 @@ export const boolean = ( * // Usage in CLI: --port 8080 or as positional argument: 42 * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const integer = ( kind: Kind, @@ -392,9 +469,10 @@ export const integer = ( /** * Creates a floating-point number parameter. * - * @example + * **Example** (Creating float parameters) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -407,8 +485,8 @@ export const integer = ( * // Usage in CLI: --rate 0.95 or as positional argument: 3.14159 * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const float = ( kind: Kind, @@ -423,9 +501,10 @@ export const float = ( /** * Creates a date parameter that parses ISO date strings. * - * @example + * **Example** (Creating date parameters) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -439,8 +518,8 @@ export const float = ( * // Parses to JavaScript Date object * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const date = ( kind: Kind, @@ -456,9 +535,10 @@ export const date = ( * Constructs command-line params that represent a choice between several * inputs. The input will be mapped to it's associated value during parsing. * - * @example + * **Example** (Creating valued choices) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -478,8 +558,8 @@ export const date = ( * ]) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const choiceWithValue = < const Kind extends ParamKind, @@ -495,9 +575,10 @@ export const choiceWithValue = < * Constructs command-line params that represent a choice between several * string inputs. * - * @example + * **Example** (Creating string choices) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -509,8 +590,8 @@ export const choiceWithValue = < * ]) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const choice = < const Kind extends ParamKind, @@ -523,9 +604,10 @@ export const choice = < /** * Creates a path parameter that accepts file or directory paths. * - * @example + * **Example** (Creating path parameters) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -543,8 +625,8 @@ export const choice = < * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const path = ( kind: Kind, @@ -565,12 +647,15 @@ export const path = ( /** * Creates a directory path parameter. * + * **Details** + * * This is a convenience function that creates a path parameter with the * `pathType` set to `"directory"` and a default type name of `"directory"`. * - * @example + * **Example** (Creating directory parameters) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -583,8 +668,8 @@ export const path = ( * // Usage: --output-dir /path/to/dir --source /existing/dir * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const directory = ( kind: Kind, @@ -602,12 +687,15 @@ export const directory = ( /** * Creates a file path parameter. * + * **Details** + * * This is a convenience function that creates a path parameter with a * `pathType` set to `"file"` and a default type name of `"file"`. * - * @example + * **Example** (Creating file parameters) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -620,8 +708,8 @@ export const directory = ( * // Usage: --output result.txt --input existing-file.txt * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const file = ( kind: Kind, @@ -640,9 +728,10 @@ export const file = ( * Creates a redacted parameter for sensitive data like passwords. * The value is masked in help output and logging. * - * @example + * **Example** (Creating redacted parameters) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -655,8 +744,8 @@ export const file = ( * // Usage: --password (value will be hidden in help/logs) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const redacted = ( kind: Kind, @@ -671,9 +760,10 @@ export const redacted = ( /** * Creates a parameter that reads and returns file content as a string. * - * @example + * **Example** (Reading file text) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -686,8 +776,8 @@ export const redacted = ( * // Usage: --config config.txt (reads file content into string) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fileText = (kind: Kind, name: string): Param => makeSingle({ @@ -699,12 +789,15 @@ export const fileText = (kind: Kind, name: string): Para /** * Creates a param that reads and parses the content of the specified file. * + * **Details** + * * The parser that is utilized will depend on the specified `format`, or the * extension of the file passed on the command-line if no `format` is specified. * - * @example + * **Example** (Parsing file contents) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -718,8 +811,8 @@ export const fileText = (kind: Kind, name: string): Para * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fileParse = ( kind: Kind, @@ -735,10 +828,11 @@ export const fileParse = ( /** * Creates a parameter that reads and validates file content using a schema. * - * @example + * **Example** (Validating file contents) + * * ```ts * import { Schema } from "effect" - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * // @internal - this module is not exported publicly * * // Parse JSON config file @@ -759,8 +853,8 @@ export const fileParse = ( * // Usage: --config config.json (reads and validates file content) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fileSchema = ( kind: Kind, @@ -776,14 +870,21 @@ export const fileSchema = ( /** * Creates a param that parses key=value pairs. - * Useful for options that accept configuration values. * - * Note: Requires at least one key=value pair. The parsed pairs are merged - * into a single record object. + * **When to use** + * + * Use when you need command-line options or arguments that collect `key=value` + * configuration entries. + * + * **Details** + * + * Requires at least one key=value pair. The parsed pairs are merged into a + * single record object. + * + * **Example** (Parsing key-value pairs) * - * @example * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -794,8 +895,8 @@ export const fileSchema = ( * // --property name=value --property debug=true * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const keyValuePair = ( kind: Kind, @@ -816,25 +917,29 @@ export const keyValuePair = ( /** * Creates an empty sentinel parameter that always fails to parse. * - * This is useful for creating placeholder parameters or for combinators. + * **When to use** + * + * Use when you need an empty CLI parameter sentinel for optional parameter + * construction or internal combinators. + * + * **Example** (Creating sentinel parameters) * - * @example * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * - * // Create a none parameter for composition - * const noneParam = Param.none(Param.flagKind) + * const disabledDebugParam = Param.none(Param.flagKind) + * + * const makeDebugParam = (enableDebug: boolean) => + * enableDebug ? Param.string(Param.flagKind, "debug") : disabledDebugParam * - * // Often used in conditional parameter creation - * const conditionalParam = process.env.NODE_ENV === "production" - * ? Param.string(Param.flagKind, "my-dev-flag") - * : Param.none(Param.flagKind) + * console.log(makeDebugParam(true) === disabledDebugParam) // false + * console.log(makeDebugParam(false) === disabledDebugParam) // true * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const none = (kind: Kind): Param => makeSingle({ @@ -848,15 +953,20 @@ const FLAG_DASH_REGEXP = /^-+/ /** * Adds an alias to an option. * - * Aliases allow params to be specified with alternative names, - * typically single-character shortcuts like "-f" for "--force". + * **When to use** + * + * Use when you need a CLI parameter to accept an alternate name, such as "-f" + * for "--force". + * + * **Details** * * This works on any param structure by recursively finding the underlying * `Single` node and applying the alias there. * - * @example + * **Example** (Adding parameter aliases) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -872,22 +982,27 @@ const FLAG_DASH_REGEXP = /^-+/ * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const withAlias: { /** * Adds an alias to an option. * - * Aliases allow params to be specified with alternative names, - * typically single-character shortcuts like "-f" for "--force". + * **When to use** + * + * Use when you need a CLI parameter to accept an alternate name, such as "-f" + * for "--force". + * + * **Details** * * This works on any param structure by recursively finding the underlying * `Single` node and applying the alias there. * - * @example + * **Example** (Adding parameter aliases) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -903,22 +1018,27 @@ export const withAlias: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (alias: string): (self: Param) => Param /** * Adds an alias to an option. * - * Aliases allow params to be specified with alternative names, - * typically single-character shortcuts like "-f" for "--force". + * **When to use** + * + * Use when you need a CLI parameter to accept an alternate name, such as "-f" + * for "--force". + * + * **Details** * * This works on any param structure by recursively finding the underlying * `Single` node and applying the alias there. * - * @example + * **Example** (Adding parameter aliases) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -934,8 +1054,8 @@ export const withAlias: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Param, alias: string): Param } = dual(2, (self: Param, alias: string) => { @@ -949,12 +1069,15 @@ export const withAlias: { /** * Adds a description to an option for help text. * + * **Details** + * * Descriptions provide users with information about what the option does * when they view help documentation. * - * @example + * **Example** (Adding help descriptions) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -964,19 +1087,22 @@ export const withAlias: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const withDescription: { /** * Adds a description to an option for help text. * + * **Details** + * * Descriptions provide users with information about what the option does * when they view help documentation. * - * @example + * **Example** (Adding help descriptions) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -986,19 +1112,22 @@ export const withDescription: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (description: string): (self: Param) => Param /** * Adds a description to an option for help text. * + * **Details** + * * Descriptions provide users with information about what the option does * when they view help documentation. * - * @example + * **Example** (Adding help descriptions) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -1008,8 +1137,8 @@ export const withDescription: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Param, description: string): Param } = dual(2, (self: Param, description: string) => { @@ -1020,12 +1149,44 @@ export const withDescription: { })) }) +/** + * Hides a parameter from generated help output and completions while keeping + * it parseable on the command line. + * + * **When to use** + * + * Use when experimental, internal, or deprecated flags should be accepted but + * not advertised. + * + * **Example** (Hiding a flag from help) + * + * ```ts + * import { Param } from "effect/unstable/cli" + * + * // @internal - this module is not exported publicly + * + * const experimental = Param.boolean(Param.flagKind, "experimental-foo").pipe( + * Param.withHidden + * ) + * ``` + * + * @category metadata + * @since 4.0.0 + */ +export const withHidden = (self: Param): Param => + transformSingle(self, (single: Single) => + makeSingle({ + ...single, + hidden: true + })) + /** * Transforms the parsed value of an option using a mapping function. * - * @example + * **Example** (Mapping parsed values) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -1034,16 +1195,17 @@ export const withDescription: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const map: { /** * Transforms the parsed value of an option using a mapping function. * - * @example + * **Example** (Mapping parsed values) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -1052,16 +1214,17 @@ export const map: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (f: (a: A) => B): (self: Param) => Param /** * Transforms the parsed value of an option using a mapping function. * - * @example + * **Example** (Mapping parsed values) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -1070,8 +1233,8 @@ export const map: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Param, f: (a: A) => B): Param } = dual(2, (self: Param, f: (a: A) => B) => { @@ -1104,13 +1267,13 @@ const transform = ( /** * Transforms the parsed value of an option using an effectful mapping function. * - * @example + * **Example** (Mapping parsed values effectfully) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Effect } from "effect" + * import { CliError, Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly - * import { Effect } from "effect" - * import { CliError } from "effect/unstable/cli" * * const validatedEmail = Param.string(Param.flagKind, "email").pipe( * Param.mapEffect((email) => @@ -1128,20 +1291,20 @@ const transform = ( * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const mapEffect: { /** * Transforms the parsed value of an option using an effectful mapping function. * - * @example + * **Example** (Mapping parsed values effectfully) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Effect } from "effect" + * import { CliError, Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly - * import { Effect } from "effect" - * import { CliError } from "effect/unstable/cli" * * const validatedEmail = Param.string(Param.flagKind, "email").pipe( * Param.mapEffect((email) => @@ -1159,20 +1322,20 @@ export const mapEffect: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (f: (a: A) => Effect.Effect): (self: Param) => Param /** * Transforms the parsed value of an option using an effectful mapping function. * - * @example + * **Example** (Mapping parsed values effectfully) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Effect } from "effect" + * import { CliError, Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly - * import { Effect } from "effect" - * import { CliError } from "effect/unstable/cli" * * const validatedEmail = Param.string(Param.flagKind, "email").pipe( * Param.mapEffect((email) => @@ -1190,8 +1353,8 @@ export const mapEffect: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ ( self: Param, @@ -1214,9 +1377,10 @@ export const mapEffect: { * Transforms the parsed value of an option using a function that may throw, * converting any thrown errors into failure messages. * - * @example + * **Example** (Mapping thrown errors) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -1229,17 +1393,18 @@ export const mapEffect: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const mapTryCatch: { /** * Transforms the parsed value of an option using a function that may throw, * converting any thrown errors into failure messages. * - * @example + * **Example** (Mapping thrown errors) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -1252,17 +1417,18 @@ export const mapTryCatch: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (f: (a: A) => B, onError: (error: unknown) => string): (self: Param) => Param /** * Transforms the parsed value of an option using a function that may throw, * converting any thrown errors into failure messages. * - * @example + * **Example** (Mapping thrown errors) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -1275,8 +1441,8 @@ export const mapTryCatch: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Param, f: (a: A) => B, onError: (error: unknown) => string): Param } = dual(3, ( @@ -1309,14 +1475,18 @@ export const mapTryCatch: { }) /** - * Creates an optional option that returns None when not provided. + * Makes a flag or positional argument optional. * - * Optional options never fail with MissingOption errors. If the option is not - * provided on the command line, Option.none() is returned instead. + * **Details** + * + * When the parameter is absent, parsing succeeds with `Option.none()` instead + * of failing with a missing option or missing argument error. When present, the + * parsed value is wrapped in `Option.some()`. + * + * **Example** (Making parameters optional) * - * @example * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // Create an optional port option * // - When not provided: returns Option.none() @@ -1324,8 +1494,8 @@ export const mapTryCatch: { * const port = Param.optional(Param.integer(Param.flagKind, "port")) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const optional = ( param: Param @@ -1362,15 +1532,17 @@ export const optional = ( } /** - * Makes an option optional by providing a default value. + * Makes a flag or positional argument optional by supplying a fallback value. + * + * **Details** + * + * The fallback may be a pure value or an effect. It is used only when the + * parameter is absent; provided values are parsed normally. * - * This combinator is useful when you want to make an existing option optional - * by providing a fallback value that will be used when the option is not - * provided on the command line. + * **Example** (Providing default values) * - * @example * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -1387,20 +1559,22 @@ export const optional = ( * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const withDefault: { /** - * Makes an option optional by providing a default value. + * Makes a flag or positional argument optional by supplying a fallback value. + * + * **Details** * - * This combinator is useful when you want to make an existing option optional - * by providing a fallback value that will be used when the option is not - * provided on the command line. + * The fallback may be a pure value or an effect. It is used only when the + * parameter is absent; provided values are parsed normally. + * + * **Example** (Providing default values) * - * @example * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -1417,20 +1591,22 @@ export const withDefault: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (defaultValue: B | Effect.Effect): (self: Param) => Param /** - * Makes an option optional by providing a default value. + * Makes a flag or positional argument optional by supplying a fallback value. * - * This combinator is useful when you want to make an existing option optional - * by providing a fallback value that will be used when the option is not - * provided on the command line. + * **Details** + * + * The fallback may be a pure value or an effect. It is used only when the + * parameter is absent; provided values are parsed normally. + * + * **Example** (Providing default values) * - * @example * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -1447,8 +1623,8 @@ export const withDefault: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ ( self: Param, @@ -1473,22 +1649,76 @@ export const withDefault: { /** * Adds a fallback config that is loaded when a required parameter is missing. * - * @since 4.0.0 + * **When to use** + * + * Use when you need config to provide a fallback source for required flags or + * arguments that are absent from CLI input. + * + * **Details** + * + * Provided CLI values win. Config is loaded only after a missing option or + * missing argument error. + * + * **Gotchas** + * + * Missing config preserves the original missing-parameter error. Config parse + * failure becomes `CliError.InvalidValue`. + * + * @see {@link withDefault} for a pure default value + * @see {@link withFallbackPrompt} for prompting interactively when input is missing + * * @category combinators + * @since 4.0.0 */ export const withFallbackConfig: { /** * Adds a fallback config that is loaded when a required parameter is missing. * - * @since 4.0.0 + * **When to use** + * + * Use when you need config to provide a fallback source for required flags or + * arguments that are absent from CLI input. + * + * **Details** + * + * Provided CLI values win. Config is loaded only after a missing option or + * missing argument error. + * + * **Gotchas** + * + * Missing config preserves the original missing-parameter error. Config parse + * failure becomes `CliError.InvalidValue`. + * + * @see {@link withDefault} for a pure default value + * @see {@link withFallbackPrompt} for prompting interactively when input is missing + * * @category combinators + * @since 4.0.0 */ (config: Config.Config): (self: Param) => Param /** * Adds a fallback config that is loaded when a required parameter is missing. * - * @since 4.0.0 + * **When to use** + * + * Use when you need config to provide a fallback source for required flags or + * arguments that are absent from CLI input. + * + * **Details** + * + * Provided CLI values win. Config is loaded only after a missing option or + * missing argument error. + * + * **Gotchas** + * + * Missing config preserves the original missing-parameter error. Config parse + * failure becomes `CliError.InvalidValue`. + * + * @see {@link withDefault} for a pure default value + * @see {@link withFallbackPrompt} for prompting interactively when input is missing + * * @category combinators + * @since 4.0.0 */ (self: Param, config: Config.Config): Param } = dual(2, ( @@ -1506,7 +1736,7 @@ export const withFallbackConfig: { kind: error._tag === "MissingOption" ? "flag" : "argument" }) const runConfig = (error: CliError.MissingOption | CliError.MissingArgument, args: ParsedArgs) => - Config.option(config).asEffect().pipe( + Config.option(config).pipe( Effect.mapError((configError) => toInvalidValue(error, configError)), Effect.flatMap(Option.match({ onNone: () => Effect.fail(error), @@ -1525,22 +1755,79 @@ export const withFallbackConfig: { /** * Adds a fallback prompt that is shown when a required parameter is missing. * - * @since 4.0.0 + * **When to use** + * + * Use when a CLI should ask interactively for a missing required flag or + * argument. + * + * **Details** + * + * `FallbackPrompt` accepts either a `Prompt` or an effect that builds one. + * Effectful prompt creation is lazy and runs only when the fallback is needed. + * + * **Gotchas** + * + * This only handles missing options and missing arguments. Invalid values do not + * prompt, and prompt cancellation re-fails with the original missing error. + * + * @see {@link FallbackPrompt} for accepted fallback prompt forms + * @see {@link withFallbackConfig} for loading a fallback from config + * @see {@link withDefault} for a pure default value + * * @category combinators + * @since 4.0.0 */ export const withFallbackPrompt: { /** * Adds a fallback prompt that is shown when a required parameter is missing. * - * @since 4.0.0 + * **When to use** + * + * Use when a CLI should ask interactively for a missing required flag or + * argument. + * + * **Details** + * + * `FallbackPrompt` accepts either a `Prompt` or an effect that builds one. + * Effectful prompt creation is lazy and runs only when the fallback is needed. + * + * **Gotchas** + * + * This only handles missing options and missing arguments. Invalid values do not + * prompt, and prompt cancellation re-fails with the original missing error. + * + * @see {@link FallbackPrompt} for accepted fallback prompt forms + * @see {@link withFallbackConfig} for loading a fallback from config + * @see {@link withDefault} for a pure default value + * * @category combinators + * @since 4.0.0 */ (prompt: FallbackPrompt): (self: Param) => Param /** * Adds a fallback prompt that is shown when a required parameter is missing. * - * @since 4.0.0 + * **When to use** + * + * Use when a CLI should ask interactively for a missing required flag or + * argument. + * + * **Details** + * + * `FallbackPrompt` accepts either a `Prompt` or an effect that builds one. + * Effectful prompt creation is lazy and runs only when the fallback is needed. + * + * **Gotchas** + * + * This only handles missing options and missing arguments. Invalid values do not + * prompt, and prompt cancellation re-fails with the original missing error. + * + * @see {@link FallbackPrompt} for accepted fallback prompt forms + * @see {@link withFallbackConfig} for loading a fallback from config + * @see {@link withDefault} for a pure default value + * * @category combinators + * @since 4.0.0 */ (self: Param, prompt: FallbackPrompt): Param } = dual(2, ( @@ -1564,8 +1851,8 @@ export const withFallbackPrompt: { /** * Represent options which can be used to configure variadic parameters. * + * @category options * @since 4.0.0 - * @category models */ export type VariadicParamOptions = { /** @@ -1581,13 +1868,16 @@ export type VariadicParamOptions = { /** * Creates a variadic parameter that can be specified multiple times. * + * **Details** + * * This is the base combinator for creating parameters that accept multiple values. - * The min and max parameters are optional - if not provided, the parameter can be - * specified any number of times (0 to infinity). + * The `min` and `max` parameters are optional. When they are not provided, the + * parameter can be specified any number of times, from 0 to infinity. + * + * **Example** (Accepting multiple values) * - * @example * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -1603,12 +1893,12 @@ export type VariadicParamOptions = { * // Variadic with both min and max * const limited = Param.variadic(Param.string(Param.flagKind, "item"), { * min: 2, // at least 2 times - * max: 2 // at most 5 times + * max: 2 // at most 2 times * }) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const variadic = ( self: Param, @@ -1635,12 +1925,15 @@ export const variadic = ( /** * Wraps an option to allow it to be specified multiple times within a range. * + * **Details** + * * This combinator transforms an option to accept between `min` and `max` * occurrences on the command line, returning an array of all provided values. * - * @example + * **Example** (Bounding repeated values) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -1662,19 +1955,22 @@ export const variadic = ( * // Result: ["dev", "staging", "v1.0"] * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const between: { /** * Wraps an option to allow it to be specified multiple times within a range. * + * **Details** + * * This combinator transforms an option to accept between `min` and `max` * occurrences on the command line, returning an array of all provided values. * - * @example + * **Example** (Bounding repeated values) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -1696,19 +1992,22 @@ export const between: { * // Result: ["dev", "staging", "v1.0"] * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (min: number, max: number): (self: Param) => Param> /** * Wraps an option to allow it to be specified multiple times within a range. * + * **Details** + * * This combinator transforms an option to accept between `min` and `max` * occurrences on the command line, returning an array of all provided values. * - * @example + * **Example** (Bounding repeated values) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -1730,8 +2029,8 @@ export const between: { * // Result: ["dev", "staging", "v1.0"] * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Param, min: number, max: number): Param> } = dual(3, (self: Param, min: number, max: number) => { @@ -1748,12 +2047,15 @@ export const between: { /** * Wraps an option to allow it to be specified at most `max` times. * + * **Details** + * * This combinator transforms an option to accept between 0 and `max` * occurrences on the command line, returning an array of all provided values. * - * @example + * **Example** (Limiting repeated values) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -1766,19 +2068,22 @@ export const between: { * // Result: ["warning1", "warning2"] * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const atMost: { /** * Wraps an option to allow it to be specified at most `max` times. * + * **Details** + * * This combinator transforms an option to accept between 0 and `max` * occurrences on the command line, returning an array of all provided values. * - * @example + * **Example** (Limiting repeated values) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -1791,19 +2096,22 @@ export const atMost: { * // Result: ["warning1", "warning2"] * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (max: number): (self: Param) => Param> /** * Wraps an option to allow it to be specified at most `max` times. * + * **Details** + * * This combinator transforms an option to accept between 0 and `max` * occurrences on the command line, returning an array of all provided values. * - * @example + * **Example** (Limiting repeated values) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -1816,8 +2124,8 @@ export const atMost: { * // Result: ["warning1", "warning2"] * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Param, max: number): Param> } = dual(2, (self: Param, max: number) => { @@ -1830,12 +2138,15 @@ export const atMost: { /** * Wraps an option to require it to be specified at least `min` times. * + * **Details** + * * This combinator transforms an option to accept at least `min` * occurrences on the command line, returning an array of all provided values. * - * @example + * **Example** (Requiring repeated values) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -1849,19 +2160,22 @@ export const atMost: { * // Result: ["file1.txt", "file2.txt", "file3.txt"] * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const atLeast: { /** * Wraps an option to require it to be specified at least `min` times. * + * **Details** + * * This combinator transforms an option to accept at least `min` * occurrences on the command line, returning an array of all provided values. * - * @example + * **Example** (Requiring repeated values) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -1875,19 +2189,22 @@ export const atLeast: { * // Result: ["file1.txt", "file2.txt", "file3.txt"] * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (min: number): (self: Param) => Param> /** * Wraps an option to require it to be specified at least `min` times. * + * **Details** + * * This combinator transforms an option to accept at least `min` * occurrences on the command line, returning an array of all provided values. * - * @example + * **Example** (Requiring repeated values) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -1901,8 +2218,8 @@ export const atLeast: { * // Result: ["file1.txt", "file2.txt", "file3.txt"] * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Param, min: number): Param> } = dual(2, (self: Param, min: number) => { @@ -1914,14 +2231,18 @@ export const atLeast: { /** * Filters and transforms parsed values, failing with a custom error message - * if the filter function returns None. + * if the filter function returns `Option.none()`. * - * This combinator is useful for validation and transformation in a single step. + * **When to use** + * + * Use when you need validation and transformation in a single parameter + * combinator. + * + * **Example** (Filtering and transforming values) * - * @example * ```ts * import { Option } from "effect" - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * // @internal - this module is not exported publicly * * const positiveInt = Param.integer(Param.flagKind, "count").pipe( @@ -1932,20 +2253,24 @@ export const atLeast: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const filterMap: { /** * Filters and transforms parsed values, failing with a custom error message - * if the filter function returns None. + * if the filter function returns `Option.none()`. + * + * **When to use** + * + * Use when you need validation and transformation in a single parameter + * combinator. * - * This combinator is useful for validation and transformation in a single step. + * **Example** (Filtering and transforming values) * - * @example * ```ts * import { Option } from "effect" - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * // @internal - this module is not exported publicly * * const positiveInt = Param.integer(Param.flagKind, "count").pipe( @@ -1956,20 +2281,24 @@ export const filterMap: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (filter: (a: A) => Option.Option, onNone: (a: A) => string): (self: Param) => Param /** * Filters and transforms parsed values, failing with a custom error message - * if the filter function returns None. + * if the filter function returns `Option.none()`. + * + * **When to use** * - * This combinator is useful for validation and transformation in a single step. + * Use when you need validation and transformation in a single parameter + * combinator. + * + * **Example** (Filtering and transforming values) * - * @example * ```ts * import { Option } from "effect" - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * // @internal - this module is not exported publicly * * const positiveInt = Param.integer(Param.flagKind, "count").pipe( @@ -1980,8 +2309,8 @@ export const filterMap: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ ( self: Param, @@ -2013,9 +2342,10 @@ export const filterMap: { /** * Filters parsed values, failing with a custom error message if the predicate returns false. * - * @example + * **Example** (Filtering parsed values) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -2027,16 +2357,17 @@ export const filterMap: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const filter: { /** * Filters parsed values, failing with a custom error message if the predicate returns false. * - * @example + * **Example** (Filtering parsed values) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -2048,16 +2379,17 @@ export const filter: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (predicate: Predicate.Predicate, onFalse: (a: A) => string): (self: Param) => Param /** * Filters parsed values, failing with a custom error message if the predicate returns false. * - * @example + * **Example** (Filtering parsed values) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -2069,8 +2401,8 @@ export const filter: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ ( self: Param, @@ -2086,12 +2418,15 @@ export const filter: { /** * Sets a custom metavar (placeholder name) for the param in help documentation. * + * **Details** + * * The metavar is displayed in usage text to indicate what value the user should provide. * For example, `--output FILE` shows `FILE` as the metavar. * - * @example + * **Example** (Setting metavars) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -2104,19 +2439,22 @@ export const filter: { * ) * ``` * - * @since 4.0.0 * @category metadata + * @since 4.0.0 */ export const withMetavar: { /** * Sets a custom metavar (placeholder name) for the param in help documentation. * + * **Details** + * * The metavar is displayed in usage text to indicate what value the user should provide. * For example, `--output FILE` shows `FILE` as the metavar. * - * @example + * **Example** (Setting metavars) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -2129,19 +2467,22 @@ export const withMetavar: { * ) * ``` * - * @since 4.0.0 * @category metadata + * @since 4.0.0 */ (metavar: string): (self: Param) => Param /** * Sets a custom metavar (placeholder name) for the param in help documentation. * + * **Details** + * * The metavar is displayed in usage text to indicate what value the user should provide. * For example, `--output FILE` shows `FILE` as the metavar. * - * @example + * **Example** (Setting metavars) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -2154,8 +2495,8 @@ export const withMetavar: { * ) * ``` * - * @since 4.0.0 * @category metadata + * @since 4.0.0 */ (self: Param, metavar: string): Param } = dual(2, ( @@ -2171,10 +2512,11 @@ export const withMetavar: { /** * Validates parsed values against a Schema, providing detailed error messages. * - * @example + * **Example** (Validating with schemas) + * * ```ts * import { Schema } from "effect" - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * // @internal - this module is not exported publicly * * const isEmail = Schema.isPattern(/^[^\s@]+@[^\s@]+\.[^\s@]+$/) @@ -2188,17 +2530,18 @@ export const withMetavar: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const withSchema: { /** * Validates parsed values against a Schema, providing detailed error messages. * - * @example + * **Example** (Validating with schemas) + * * ```ts * import { Schema } from "effect" - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * // @internal - this module is not exported publicly * * const isEmail = Schema.isPattern(/^[^\s@]+@[^\s@]+\.[^\s@]+$/) @@ -2212,17 +2555,18 @@ export const withSchema: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (schema: Schema.Codec): (self: Param) => Param /** * Validates parsed values against a Schema, providing detailed error messages. * - * @example + * **Example** (Validating with schemas) + * * ```ts * import { Schema } from "effect" - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * // @internal - this module is not exported publicly * * const isEmail = Schema.isPattern(/^[^\s@]+@[^\s@]+\.[^\s@]+$/) @@ -2236,8 +2580,8 @@ export const withSchema: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Param, schema: Schema.Codec): Param } = dual(2, ( @@ -2260,9 +2604,10 @@ export const withSchema: { /** * Provides a fallback param to use if this param fails to parse. * - * @example + * **Example** (Falling back to another parameter) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -2271,16 +2616,17 @@ export const withSchema: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const orElse: { /** * Provides a fallback param to use if this param fails to parse. * - * @example + * **Example** (Falling back to another parameter) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -2289,16 +2635,17 @@ export const orElse: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (orElse: (error: CliError.CliError) => Param): (self: Param) => Param /** * Provides a fallback param to use if this param fails to parse. * - * @example + * **Example** (Falling back to another parameter) + * * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -2307,8 +2654,8 @@ export const orElse: { * ) * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Param, orElse: (error: CliError.CliError) => Param): Param } = dual(2, ( @@ -2321,11 +2668,18 @@ export const orElse: { )) /** - * Provides a fallback param, wrapping results in Either to distinguish which param succeeded. + * Provides a fallback param and returns a `Result` indicating which param + * succeeded. + * + * **Details** + * + * The original param's value is returned as `Result.succeed`, while the + * fallback param's value is returned as `Result.fail`. + * + * **Example** (Returning fallback results) * - * @example * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -2335,16 +2689,23 @@ export const orElse: { * // Returns Result * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const orElseResult: { /** - * Provides a fallback param, wrapping results in Either to distinguish which param succeeded. + * Provides a fallback param and returns a `Result` indicating which param + * succeeded. + * + * **Details** + * + * The original param's value is returned as `Result.succeed`, while the + * fallback param's value is returned as `Result.fail`. + * + * **Example** (Returning fallback results) * - * @example * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -2354,16 +2715,23 @@ export const orElseResult: { * // Returns Result * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (orElse: (error: CliError.CliError) => Param): (self: Param) => Param> /** - * Provides a fallback param, wrapping results in Either to distinguish which param succeeded. + * Provides a fallback param and returns a `Result` indicating which param + * succeeded. + * + * **Details** + * + * The original param's value is returned as `Result.succeed`, while the + * fallback param's value is returned as `Result.fail`. + * + * **Example** (Returning fallback results) * - * @example * ```ts - * import * as Param from "effect/unstable/cli/Param" + * import { Param } from "effect/unstable/cli" * * // @internal - this module is not exported publicly * @@ -2373,8 +2741,8 @@ export const orElseResult: { * // Returns Result * ``` * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Param, orElse: (error: CliError.CliError) => Param): Param> } = dual(2, ( diff --git a/.opencode/node_modules/effect/src/unstable/cli/Primitive.ts b/.opencode/node_modules/effect/src/unstable/cli/Primitive.ts index c764ded77f28a4e0de11197ea09a15e29321286a..53c04b44d244a9a170b7379c5a403c28d040d3ad 100644 --- a/.opencode/node_modules/effect/src/unstable/cli/Primitive.ts +++ b/.opencode/node_modules/effect/src/unstable/cli/Primitive.ts @@ -1,13 +1,12 @@ /** - * Primitive types for CLI parameter parsing. + * Parses raw command-line strings into typed values. * - * Primitives handle the low-level parsing of string input into typed values. - * Most users should use the higher-level `Argument` and `Flag` modules instead. - * - * This module is primarily useful for: - * - Creating custom primitive types - * - Understanding how CLI parsing works internally - * - Advanced customization of parsing behavior + * A `Primitive` receives one string and returns an `Effect` that either + * produces an `A` or fails with a parser message. `Argument` and `Flag` build + * on these primitives to add names, aliases, defaults, prompts, configuration + * fallbacks, repetition, and help metadata. Primitive parsers cover common + * scalar values, paths, files, structured config files, schema-decoded input, + * redacted values, and key-value pairs. * * @since 4.0.0 */ @@ -31,7 +30,8 @@ const TypeId = "~effect/cli/Primitive" /** * Represents a primitive type that can parse string input into a typed value. * - * @example + * **Example** (Parsing values with primitives) + * * ```ts * import { Effect } from "effect" * import { Primitive } from "effect/unstable/cli" @@ -53,8 +53,8 @@ const TypeId = "~effect/cli/Primitive" * }) * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface Primitive extends Primitive.Variance { readonly _tag: string @@ -62,12 +62,16 @@ export interface Primitive extends Primitive.Variance { } /** + * Namespace containing type-level helpers for `Primitive`. + * * @since 4.0.0 */ export declare namespace Primitive { /** - * @since 4.0.0 + * Type-level variance marker for the value parsed by a `Primitive`. + * * @category models + * @since 4.0.0 */ export interface Variance { readonly [TypeId]: { @@ -114,11 +118,14 @@ const makeSchemaPrimitive = ( /** * Creates a primitive that parses boolean values from string input. * + * **Details** + * * Recognizes various forms of true/false values: * - True values: "true", "1", "y", "yes", "on" * - False values: "false", "0", "n", "no", "off" * - * @example + * **Example** (Parsing boolean values) + * * ```ts * import { Effect } from "effect" * import { Primitive } from "effect/unstable/cli" @@ -138,8 +145,8 @@ const makeSchemaPrimitive = ( * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const boolean: Primitive = makeSchemaPrimitive( "Boolean", @@ -149,7 +156,8 @@ export const boolean: Primitive = makeSchemaPrimitive( /** * Creates a primitive that parses floating-point numbers from string input. * - * @example + * **Example** (Parsing floating-point numbers) + * * ```ts * import { Effect } from "effect" * import { Primitive } from "effect/unstable/cli" @@ -166,8 +174,8 @@ export const boolean: Primitive = makeSchemaPrimitive( * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const float: Primitive = makeSchemaPrimitive( "Float", @@ -177,7 +185,8 @@ export const float: Primitive = makeSchemaPrimitive( /** * Creates a primitive that parses integer numbers from string input. * - * @example + * **Example** (Parsing integer values) + * * ```ts * import { Effect } from "effect" * import { Primitive } from "effect/unstable/cli" @@ -194,8 +203,8 @@ export const float: Primitive = makeSchemaPrimitive( * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const integer: Primitive = makeSchemaPrimitive( "Integer", @@ -205,7 +214,8 @@ export const integer: Primitive = makeSchemaPrimitive( /** * Creates a primitive that parses Date objects from string input. * - * @example + * **Example** (Parsing date values) + * * ```ts * import { Effect } from "effect" * import { Primitive } from "effect/unstable/cli" @@ -222,8 +232,8 @@ export const integer: Primitive = makeSchemaPrimitive( * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const date: Primitive = makeSchemaPrimitive( "Date", @@ -233,7 +243,8 @@ export const date: Primitive = makeSchemaPrimitive( /** * Creates a primitive that accepts any string value without validation. * - * @example + * **Example** (Parsing string values) + * * ```ts * import { Effect } from "effect" * import { Primitive } from "effect/unstable/cli" @@ -250,15 +261,16 @@ export const date: Primitive = makeSchemaPrimitive( * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const string: Primitive = makePrimitive("String", (value) => Effect.succeed(value)) /** * Creates a primitive that accepts only specific choice values mapped to custom types. * - * @example + * **Example** (Parsing choices) + * * ```ts * import { Effect } from "effect" * import { Primitive } from "effect/unstable/cli" @@ -281,8 +293,8 @@ export const string: Primitive = makePrimitive("String", (value) => Effe * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const choice = ( choices: ReadonlyArray @@ -301,7 +313,8 @@ export const choice = ( /** * Specifies the type of path validation to perform. * - * @example + * **Example** (Choosing path validation) + * * ```ts * import { Primitive } from "effect/unstable/cli" * @@ -315,15 +328,16 @@ export const choice = ( * const anyPath = Primitive.path("either", false) * ``` * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type PathType = "file" | "directory" | "either" /** * Creates a primitive that validates and resolves file system paths. * - * @example + * **Example** (Parsing file system paths) + * * ```ts * import { Effect } from "effect" * import { Primitive } from "effect/unstable/cli" @@ -346,8 +360,8 @@ export type PathType = "file" | "directory" | "either" * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const path = ( pathType: PathType, @@ -393,9 +407,15 @@ export const path = ( ) /** - * Creates a primitive that wraps string input in a redacted type for secure handling. + * Creates a primitive that wraps string input in `Redacted`. + * + * **Details** + * + * The wrapped value is hidden when formatted or inspected, while the original + * string remains available through the `Redacted` API when explicitly needed. + * + * **Example** (Parsing redacted values) * - * @example * ```ts * import { Effect, Redacted } from "effect" * import { Primitive } from "effect/unstable/cli" @@ -407,8 +427,8 @@ export const path = ( * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const redacted: Primitive> = makePrimitive( "Redacted", @@ -418,22 +438,33 @@ export const redacted: Primitive> = makePrimitive( /** * Creates a primitive that reads and returns the contents of a file as a string. * - * @example + * **Example** (Reading file text) + * * ```ts - * import { Effect } from "effect" + * import { Effect, Schema } from "effect" * import { Primitive } from "effect/unstable/cli" * + * const ConfigSchema = Schema.Struct({ + * name: Schema.String, + * version: Schema.String, + * port: Schema.Number + * }) + * const decodeConfig = Schema.decodeUnknownEffect( + * Schema.fromJsonString(ConfigSchema) + * ) + * * const readConfigFile = Effect.gen(function*() { * const content = yield* Primitive.fileText.parse("./config.json") - * console.log(content) // File contents as string + * console.log(content) // {"name":"my-app","version":"1.0.0","port":3000} * - * const parsed = JSON.parse(content) - * return parsed + * const config = yield* decodeConfig(content) + * console.log(config) // { name: "my-app", version: "1.0.0", port: 3000 } + * return config * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fileText: Primitive = makePrimitive( "FileText", @@ -480,8 +511,8 @@ export const fileText: Primitive = makePrimitive( * Represents options which can be provided to methods that deal with parsing * file content. * + * @category options * @since 4.0.0 - * @category models */ export type FileParseOptions = { readonly format?: "ini" | "json" | "toml" | "yaml" @@ -496,9 +527,16 @@ const fileParsers: Record unknown> = { } /** - * Reads and parses file content using the specified schema. + * Creates a primitive that reads a file and parses its content as structured + * data. + * + * **Details** + * + * The parser is selected from `options.format` when provided, otherwise from + * the file extension. Supported formats include INI, JSON, TOML, YAML, and YML. + * + * **Example** (Parsing file content) * - * @example * ```ts * import { Effect } from "effect" * import { Primitive } from "effect/unstable/cli" @@ -512,8 +550,8 @@ const fileParsers: Record unknown> = { * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fileParse = (options?: FileParseOptions): Primitive => { return makePrimitive( @@ -537,8 +575,8 @@ export const fileParse = (options?: FileParseOptions): Primitive => { * Represents options which can be provided to methods that deal with parsing * file content and decoding the file content with a `Schema`. * + * @category options * @since 4.0.0 - * @category models */ export type FileSchemaOptions = Struct.Simplify< FileParseOptions & { @@ -549,7 +587,8 @@ export type FileSchemaOptions = Struct.Simplify< /** * Reads and parses file content using the specified schema. * - * @example + * **Example** (Parsing file content with a schema) + * * ```ts * import { Effect, Schema } from "effect" * import { Primitive } from "effect/unstable/cli" @@ -558,7 +597,7 @@ export type FileSchemaOptions = Struct.Simplify< * name: Schema.String, * version: Schema.String, * port: Schema.Number - * }).pipe(Schema.fromJsonString) + * }) * * const jsonConfigPrimitive = Primitive.fileSchema(ConfigSchema, { * format: "json" @@ -571,8 +610,8 @@ export type FileSchemaOptions = Struct.Simplify< * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fileSchema = ( schema: Schema.Decoder, @@ -594,7 +633,8 @@ export const fileSchema = ( /** * Parses a single `key=value` pair into a record object. * - * @example + * **Example** (Parsing key-value pairs) + * * ```ts * import { Effect } from "effect" * import { Primitive } from "effect/unstable/cli" @@ -611,8 +651,8 @@ export const fileSchema = ( * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const keyValuePair: Primitive> = makePrimitive( "KeyValuePair", @@ -634,11 +674,14 @@ export const keyValuePair: Primitive> = makePrimitive( ) /** - * A sentinel primitive that always fails to parse a value. + * Creates a sentinel primitive that always fails to parse a value. + * + * **When to use** + * + * Use when you need a CLI primitive for flags that do not accept values. * - * Used for flags that don't accept values. + * **Example** (Rejecting option values) * - * @example * ```ts * import { Effect } from "effect" * import { Primitive } from "effect/unstable/cli" @@ -651,17 +694,21 @@ export const keyValuePair: Primitive> = makePrimitive( * // The above effect will fail with "This option does not accept values" * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const none: Primitive = makePrimitive("None", () => Effect.fail("This option does not accept values")) /** * Gets a human-readable type name for a primitive. * - * Used for generating help documentation. + * **When to use** + * + * Use when you need the display type name for a `Primitive`, such as when + * generating CLI help documentation. + * + * **Example** (Getting primitive type names) * - * @example * ```ts * import { Primitive } from "effect/unstable/cli" * @@ -678,8 +725,8 @@ export const none: Primitive = makePrimitive("None", () => Effect.fail("T * console.log(Primitive.getTypeName(logLevelChoice)) // "choice" * ``` * + * @category getters * @since 4.0.0 - * @category utilities */ export const getTypeName = (primitive: Primitive): string => { switch (primitive._tag) { diff --git a/.opencode/node_modules/effect/src/unstable/cli/Prompt.ts b/.opencode/node_modules/effect/src/unstable/cli/Prompt.ts index 9d1970e8b9d67a00b377195e816ac044dc944579..df489fbe7ee9350035f40fc341cdfbf40f570708 100644 --- a/.opencode/node_modules/effect/src/unstable/cli/Prompt.ts +++ b/.opencode/node_modules/effect/src/unstable/cli/Prompt.ts @@ -1,4 +1,13 @@ /** + * Builds interactive terminal prompts for CLI applications. + * + * A `Prompt` describes a small terminal UI that renders frames, reads + * keyboard input, validates responses, and eventually produces an `A`. Prompts + * can ask for simple values, selections, lists, files, hidden text, or custom + * interactions. This module includes prompt constructors, tools for combining + * and transforming prompt output, and support for running prompts through the + * `Terminal` service. + * * @since 4.0.0 */ import * as Arr from "../../Array.ts" @@ -6,13 +15,12 @@ import type { NoSuchElementError } from "../../Cause.ts" import type * as Cause from "../../Cause.ts" import * as Data from "../../Data.ts" import * as Effect from "../../Effect.ts" +import * as Effectable from "../../Effectable.ts" import * as FileSystem from "../../FileSystem.ts" import { dual, pipe } from "../../Function.ts" -import { YieldableProto } from "../../internal/core.ts" import * as EffectNumber from "../../Number.ts" import * as Option from "../../Option.ts" import * as Path from "../../Path.ts" -import * as Pipeable from "../../Pipeable.ts" import * as Predicate from "../../Predicate.ts" import * as Queue from "../../Queue.ts" import * as Redacted from "../../Redacted.ts" @@ -24,37 +32,45 @@ import type * as Primitive from "./Primitive.ts" const TypeId = "~effect/cli/Prompt" /** - * @since 4.0.0 + * Represents an interactive terminal prompt that produces an `Output` value. + * + * **Details** + * + * A `Prompt` is an `Effect` that may fail with `Terminal.QuitError` and + * requires the prompt environment needed to render frames, read input, and + * access files or paths when a prompt uses them. + * * @category models + * @since 4.0.0 */ -export interface Prompt - extends Pipeable.Pipeable, Effect.Yieldable, Output, Terminal.QuitError, Environment> -{ +export interface Prompt extends Effect.Effect { readonly [TypeId]: { readonly _Output: Covariant } } /** - * @since 4.0.0 + * Returns `true` if the provided value is a `Prompt`. + * * @category guards + * @since 4.0.0 */ export const isPrompt = (u: unknown): u is Prompt => Predicate.hasProperty(u, TypeId) /** * Represents the services available to a custom `Prompt`. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type Environment = FileSystem.FileSystem | Path.Path | Terminal.Terminal /** - * Represents the action that should be taken by a `Prompt` based upon the - * user input received during the current frame. + * Represents the action that should be taken by a `Prompt` based upon user + * input or an external event received during the current frame. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type Action = Data.TaggedEnum<{ readonly Beep: {} @@ -63,34 +79,46 @@ export type Action = Data.TaggedEnum<{ }> /** - * Represents the definition of an `Action`. + * Type-level definition for the tagged `Prompt.Action` variants. * - * Required to create a `Data.TaggedEnum` with generic type arguments. + * **Details** + * + * It connects the action state and output type parameters to the `Beep`, + * `NextFrame`, and `Submit` action cases. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface ActionDefinition extends Data.TaggedEnum.WithGenerics<2> { readonly taggedEnum: Action } /** - * Represents the set of handlers used by a `Prompt` to: - * - * - Render the current frame of the prompt - * - Process user input and determine the next `Prompt.Action` to take - * - Clear the terminal screen before the next frame + * Represents the input that should be processed by a `Prompt` based upon user + * input or an external event received during the current frame. * + * @category models * @since 4.0.0 + */ +export type ProcessInput = Data.TaggedEnum<{ + readonly Input: { readonly input: Terminal.UserInput } + readonly Event: { readonly value: A } +}> + +/** + * Represents the set of handlers used by a `Prompt`. + * + * **Details** + * + * The handlers render the current frame, process user input into the next + * `Prompt.Action`, and clear the terminal screen before the next frame. + * * @category models + * @since 4.0.0 */ -export interface Handlers { +export interface Handlers { /** * A function that is called to render the current frame of the `Prompt`. - * - * @param state The current state of the prompt. - * @param action The `Prompt.Action` for the current frame. - * @returns An ANSI escape code sequence to display in the terminal screen. */ readonly render: ( state: State, @@ -99,22 +127,14 @@ export interface Handlers { /** * A function that is called to process user input and determine the next * `Prompt.Action` that should be taken. - * - * @param input The input the user provided for the current frame. - * @param state The current state of the prompt. - * @returns The next `Prompt.Action` that should be taken. */ readonly process: ( - input: Terminal.UserInput, + input: Input, state: State ) => Effect.Effect, never, Environment> /** * A function that is called to clear the terminal screen before rendering * the next frame of the `Prompt`. - * - * @param action The `Prompt.Action` for the current frame. - * @param columns The current number of columns available in the `Terminal`. - * @returns An ANSI escape code sequence used to clear the terminal screen. */ readonly clear: ( state: State, @@ -123,8 +143,11 @@ export interface Handlers { } /** + * Options for a confirmation prompt that asks the user to choose a boolean + * yes/no value. + * + * @category options * @since 4.0.0 - * @category models */ export interface ConfirmOptions { /** @@ -132,7 +155,7 @@ export interface ConfirmOptions { */ readonly message: string /** - * The intitial value of the confirm prompt (defaults to `false`). + * The initial value of the confirm prompt (defaults to `false`). */ readonly initial?: boolean /** @@ -166,8 +189,11 @@ export interface ConfirmOptions { } /** + * Options for a date prompt, including the displayed message, initial value, + * format mask, validation, and locale labels. + * + * @category options * @since 4.0.0 - * @category models */ export interface DateOptions { /** @@ -238,14 +264,21 @@ export interface DateOptions { } /** + * Options for an integer prompt, including bounds, keyboard step sizes, and + * additional validation. + * + * @category options * @since 4.0.0 - * @category models */ export interface IntegerOptions { /** * The message to display in the prompt. */ readonly message: string + /** + * The default value of the integer prompt. + */ + readonly default?: number /** * The minimum value that can be entered by the user (defaults to `-Infinity`). */ @@ -272,8 +305,15 @@ export interface IntegerOptions { } /** + * Options for a floating-point number prompt. + * + * **Details** + * + * In addition to the numeric bounds and step settings from `IntegerOptions`, + * the prompt can be configured with a display precision. + * + * @category options * @since 4.0.0 - * @category models */ export interface FloatOptions extends IntegerOptions { /** @@ -283,8 +323,11 @@ export interface FloatOptions extends IntegerOptions { } /** + * Options for a text prompt that returns a list of strings by splitting the + * input on a delimiter. + * + * @category options * @since 4.0.0 - * @category models */ export interface ListOptions extends TextOptions { /** @@ -294,46 +337,51 @@ export interface ListOptions extends TextOptions { } /** + * Options for a file-system selection prompt. + * + * **Details** + * + * They control which path type can be selected, the starting directory, paging, + * and filtering of displayed entries. + * + * @category options * @since 4.0.0 - * @category models */ export interface FileOptions { /** - * The path type that will be selected. - * - * Defaults to `"file"`. + * The path type that will be selected, defaulting to `"file"`. */ readonly type?: Primitive.PathType /** - * The message to display in the prompt. - * - * Defaults to `"Choose a file"`. + * The message to display in the prompt, defaulting to `"Choose a file"`. */ readonly message?: string /** - * Where the user will initially be prompted to select files from. - * - * Defaults to the current working directory. + * Where the user will initially be prompted to select files from, defaulting + * to the current working directory. */ readonly startingPath?: string /** - * The number of choices to display at one time - * - * Defaults to `10`. + * The default path to select when the prompt is first displayed. + */ + readonly default?: string + /** + * The number of choices to display at one time, defaulting to `10`. */ readonly maxPerPage?: number /** - * A function which removes any file from the prompt display where the - * specified predicate returns `true`. - * - * Defaults to returning all files. + * A predicate or effect that keeps a file in the prompt when it returns + * `true`, defaulting to returning all files. */ readonly filter?: (file: string) => boolean | Effect.Effect } /** + * Options for a prompt that asks the user to select one value from a list of + * choices. + * + * @category options * @since 4.0.0 - * @category models */ export interface SelectOptions { /** @@ -351,8 +399,11 @@ export interface SelectOptions { } /** + * Options for an autocomplete prompt that lets the user filter selectable + * choices by typing. + * + * @category options * @since 4.0.0 - * @category models */ export interface AutoCompleteOptions extends SelectOptions { /** @@ -370,8 +421,11 @@ export interface AutoCompleteOptions extends SelectOptions { } /** + * Options for a multi-select prompt, including bulk-selection labels and + * minimum or maximum selection counts. + * + * @category options * @since 4.0.0 - * @category models */ export interface MultiSelectOptions { /** @@ -397,8 +451,11 @@ export interface MultiSelectOptions { } /** - * @since 4.0.0 + * Represents one choice displayed by select, autocomplete, and multi-select + * prompts. + * * @category models + * @since 4.0.0 */ export interface SelectChoice { /** @@ -425,8 +482,11 @@ export interface SelectChoice { } /** + * Options for text-entry prompts, including the displayed message, default + * text, and effectful validation before submission. + * + * @category options * @since 4.0.0 - * @category models */ export interface TextOptions { /** @@ -445,8 +505,11 @@ export interface TextOptions { } /** + * Options for a toggle prompt that lets the user switch between active and + * inactive boolean states. + * + * @category options * @since 4.0.0 - * @category models */ export interface ToggleOptions { /** @@ -510,22 +573,37 @@ export const platformFigures = Effect.map( ) /** - * @since 4.0.0 + * Type alias for any `Prompt`, regardless of its output type. + * * @category utility types + * @since 4.0.0 */ export type Any = Prompt /** + * Namespace containing return-type helpers for `Prompt.all`. + * * @since 4.0.0 */ export declare namespace All { /** + * Computes the prompt returned by `Prompt.all` for an iterable of prompts. + * + * **Details** + * + * The resulting prompt produces an array of each prompt's output value. + * + * @category utility types * @since 4.0.0 */ export type ReturnIterable> = [T] extends [Iterable>] ? Prompt> : never /** + * Computes the prompt returned by `Prompt.all` for a readonly tuple or array + * of prompts, preserving tuple positions in the output type. + * + * @category utility types * @since 4.0.0 */ export type ReturnTuple> = Prompt< @@ -534,6 +612,10 @@ export declare namespace All { > extends infer X ? X : never /** + * Computes the prompt returned by `Prompt.all` for a record of prompts, + * preserving the record keys and replacing each prompt with its output type. + * + * @category utility types * @since 4.0.0 */ export type ReturnObject = [T] extends [{ [K: string]: Any }] ? Prompt< @@ -544,6 +626,10 @@ export declare namespace All { : never /** + * Computes the return prompt type for `Prompt.all` based on the input + * structure. + * + * @category constructors * @since 4.0.0 */ export type Return< @@ -558,10 +644,12 @@ export declare namespace All { * Runs all the provided prompts in sequence respecting the structure provided * in input. * + * **Details** + * * Supports either a tuple / iterable of prompts or a record / struct of prompts * as an argument. * - * **Example** + * **Example** (Collecting prompt results) * * ```ts * import { Effect } from "effect" @@ -584,8 +672,8 @@ export declare namespace All { * const allWithRecord = Prompt.all({ username, password }) * ``` * - * @since 4.0.0 * @category collecting & elements + * @since 4.0.0 */ export const all: < const Arg extends Iterable> | Record> @@ -622,8 +710,22 @@ const annotateLine = (line: string): string => Ansi.annotate(line, Ansi.bold) const annotateErrorLine = (line: string): string => Ansi.annotate(line, Ansi.combine(Ansi.italicized, Ansi.red)) /** - * @since 4.0.0 + * Creates a confirmation prompt that asks the user to choose a boolean yes/no + * value. + * + * **When to use** + * + * Use to ask for a yes/no answer that can be submitted directly. + * + * **Details** + * + * `initial` defaults to `false`. Enter submits the current default, yes-style + * input submits `true`, no-style input submits `false`, and other input beeps. + * + * @see {@link toggle} for an interactive switch-before-submit boolean prompt + * * @category constructors + * @since 4.0.0 */ export const confirm = (options: ConfirmOptions): Prompt => { const opts: Required = { @@ -651,46 +753,118 @@ export const confirm = (options: ConfirmOptions): Prompt => { /** * Creates a custom `Prompt` from the specified initial state and handlers. * + * **Details** + * * The initial state can either be a pure value or an `Effect`. This is * particularly useful when the initial state of the `Prompt` must be computed - * by performing some effectful computation, such as reading data from the file - * system. - * - * A `Prompt` is essentially a render loop where user input triggers a new frame - * to be rendered to the `Terminal`. The `handlers` of a custom prompt are used - * to control what is rendered to the `Terminal` each frame. During each frame, - * the following occurs: - * - * 1. The `render` handler is called with this frame's prompt state and prompt - * action and returns an ANSI escape string to be rendered to the - * `Terminal` - * 2. The `Terminal` obtains input from the user - * 3. The `process` handler is called with the input obtained from the user - * and this frame's prompt state and returns the next prompt action that - * should be performed - * 4. The `clear` handler is called with this frame's prompt state and prompt - * action and returns an ANSI escape string used to clear the screen of - * the `Terminal` + * by performing an effectful computation, such as reading data from the file + * system. A `Prompt` runs as a render loop: `render` returns ANSI output for + * the current frame, the `Terminal` obtains user input, `process` returns the + * next prompt action, and `clear` returns ANSI output used to clear the previous + * frame. + * + * Optionally, an external `events` dequeue can be provided as the third + * argument. When present, the render loop will race user input against events + * from the dequeue, allowing background events to trigger re-renders without + * waiting for a keypress. When an event is received from the dequeue, the + * `receive` handler is called instead of `process`. * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ -export const custom = ( +export const custom: { + /** + * Creates a custom `Prompt` from the specified initial state and handlers. + * + * **Details** + * + * The initial state can either be a pure value or an `Effect`. This is + * particularly useful when the initial state of the `Prompt` must be computed + * by performing an effectful computation, such as reading data from the file + * system. A `Prompt` runs as a render loop: `render` returns ANSI output for + * the current frame, the `Terminal` obtains user input, `process` returns the + * next prompt action, and `clear` returns ANSI output used to clear the previous + * frame. + * + * Optionally, an external `events` dequeue can be provided as the third + * argument. When present, the render loop will race user input against events + * from the dequeue, allowing background events to trigger re-renders without + * waiting for a keypress. When an event is received from the dequeue, the + * `receive` handler is called instead of `process`. + * + * @category constructors + * @since 4.0.0 + */ + ( + initialState: State | Effect.Effect, + handlers: Handlers + ): Prompt + /** + * Creates a custom `Prompt` from the specified initial state and handlers. + * + * **Details** + * + * The initial state can either be a pure value or an `Effect`. This is + * particularly useful when the initial state of the `Prompt` must be computed + * by performing an effectful computation, such as reading data from the file + * system. A `Prompt` runs as a render loop: `render` returns ANSI output for + * the current frame, the `Terminal` obtains user input, `process` returns the + * next prompt action, and `clear` returns ANSI output used to clear the previous + * frame. + * + * Optionally, an external `events` dequeue can be provided as the third + * argument. When present, the render loop will race user input against events + * from the dequeue, allowing background events to trigger re-renders without + * waiting for a keypress. When an event is received from the dequeue, the + * `receive` handler is called instead of `process`. + * + * @category constructors + * @since 4.0.0 + */ + ( + initialState: State | Effect.Effect, + events: Queue.Dequeue, + handlers: Handlers> + ): Prompt +} = ( initialState: State | Effect.Effect, - handlers: Handlers + ...args: + | [handlers: Handlers] + | [events: Queue.Dequeue, handlers: Handlers>] ): Prompt => { + const [events, handlers] = args.length === 1 + ? [undefined, args[0]] as const + : [args[0], args[1]] as const const op = Object.create(proto) op._tag = "Loop" op.initialState = initialState op.render = handlers.render op.process = handlers.process op.clear = handlers.clear + op.events = events return op } /** - * @since 4.0.0 + * Creates a date prompt that lets the user edit a formatted date value and + * validates the final `Date` before submission. + * + * **Details** + * + * `initial` defaults to the current `Date`, `dateMask` defaults to + * `YYYY-MM-DD HH:mm:ss`, mask parsing creates editable date parts plus literal + * tokens, `locales` customizes month and weekday labels, and `validate` runs on + * submission. + * + * **Gotchas** + * + * A supplied `initial` `Date` is edited in place during prompt interaction. + * Date edits use JavaScript `Date` setters, so out-of-range typed values can + * normalize before validation. If the prompt is meant to be editable, + * `dateMask` should contain at least one editable date token. + * * @category constructors + * @since 4.0.0 */ export const date = (options: DateOptions): Prompt => { const opts: Required = { @@ -720,14 +894,22 @@ export const date = (options: DateOptions): Prompt => { } /** - * @since 4.0.0 + * Creates a file-system selection prompt and returns the selected path. + * + * **Details** + * + * The prompt can be configured to select files, directories, or either path + * type. + * * @category constructors + * @since 4.0.0 */ export const file = (options: FileOptions = {}): Prompt => { const opts: FileOptionsReq = { type: options.type ?? "file", message: options.message ?? `Choose a file`, startingPath: Option.fromUndefinedOr(options.startingPath), + default: Option.fromUndefinedOr(options.default), maxPerPage: options.maxPerPage ?? 10, filter: options.filter ?? (() => Effect.succeed(true)) } @@ -737,9 +919,22 @@ export const file = (options: FileOptions = {}): Prompt => { Environment > = Effect.gen(function*() { const currentPath = yield* resolveCurrentPath(Option.none(), opts) - const files = yield* getFileList(currentPath, opts) + const path = yield* Path.Path + const defaultPath = Option.map(opts.default, (defaultValue) => path.resolve(currentPath, defaultValue)) + const initialPath = Option.match(defaultPath, { + onNone: () => currentPath, + onSome: (defaultPath) => path.dirname(defaultPath) + }) + const files = yield* getFileList(initialPath, opts) + const cursor = Option.match(defaultPath, { + onNone: () => 0, + onSome: (defaultPath) => { + const index = files.indexOf(path.basename(defaultPath)) + return index === -1 ? 0 : index + } + }) const confirm = Confirm.Hide() - return { cursor: 0, files, allFiles: files, query: "", path: Option.none(), confirm } + return { cursor, files, allFiles: files, query: "", path: Option.map(defaultPath, path.dirname), confirm } }) return custom(initialState, { render: handleFileRender(opts), @@ -749,18 +944,24 @@ export const file = (options: FileOptions = {}): Prompt => { } /** - * @since 4.0.0 + * Composes prompts by using the output of this prompt to create the next prompt. + * * @category combinators + * @since 4.0.0 */ export const flatMap: { /** - * @since 4.0.0 + * Composes prompts by using the output of this prompt to create the next prompt. + * * @category combinators + * @since 4.0.0 */ (f: (output: Output) => Prompt): (self: Prompt) => Prompt /** - * @since 4.0.0 + * Composes prompts by using the output of this prompt to create the next prompt. + * * @category combinators + * @since 4.0.0 */ (self: Prompt, f: (output: Output) => Prompt): Prompt } = dual(2, ( @@ -775,11 +976,19 @@ export const flatMap: { }) /** - * @since 4.0.0 + * Creates a floating-point number prompt. + * + * **Details** + * + * The prompt supports minimum and maximum bounds, keyboard step sizes, display + * precision, and additional validation before submission. + * * @category constructors + * @since 4.0.0 */ export const float = (options: FloatOptions): Prompt => { const opts: FloatOptionsReq = { + default: 0, min: Number.NEGATIVE_INFINITY, max: Number.POSITIVE_INFINITY, incrementBy: 1, @@ -796,9 +1005,10 @@ export const float = (options: FloatOptions): Prompt => { }, ...options } + const initialValue = options.default === undefined ? "" : `${opts.default}` const initialState: NumberState = { - cursor: 0, - value: "", + cursor: initialValue.length, + value: initialValue, error: Option.none() } return custom(initialState, { @@ -808,19 +1018,30 @@ export const float = (options: FloatOptions): Prompt => { }) } /** - * @since 4.0.0 + * Creates a text prompt that does not echo typed input and returns the + * submitted value wrapped in `Redacted`. + * * @category constructors + * @since 4.0.0 */ export const hidden = ( options: TextOptions ): Prompt => basePrompt(options, "hidden").pipe(map(Redacted.make)) /** - * @since 4.0.0 + * Creates an integer prompt. + * + * **Details** + * + * The prompt supports minimum and maximum bounds, keyboard step sizes, and + * additional validation before submission. + * * @category constructors + * @since 4.0.0 */ export const integer = (options: IntegerOptions): Prompt => { const opts: IntegerOptionsReq = { + default: 0, min: Number.NEGATIVE_INFINITY, max: Number.POSITIVE_INFINITY, incrementBy: 1, @@ -836,9 +1057,10 @@ export const integer = (options: IntegerOptions): Prompt => { }, ...options } + const initialValue = options.default === undefined ? "" : `${opts.default}` const initialState: NumberState = { - cursor: 0, - value: "", + cursor: initialValue.length, + value: initialValue, error: Option.none() } return custom(initialState, { @@ -849,8 +1071,11 @@ export const integer = (options: IntegerOptions): Prompt => { } /** - * @since 4.0.0 + * Creates a text prompt that returns an array of strings by splitting the + * submitted input on the configured delimiter. + * * @category constructors + * @since 4.0.0 */ export const list = (options: ListOptions): Prompt> => text(options).pipe( @@ -858,18 +1083,24 @@ export const list = (options: ListOptions): Prompt> => ) /** - * @since 4.0.0 + * Transforms the output value produced by a prompt. + * * @category combinators + * @since 4.0.0 */ export const map: { /** - * @since 4.0.0 + * Transforms the output value produced by a prompt. + * * @category combinators + * @since 4.0.0 */ (f: (output: Output) => Output2): (self: Prompt) => Prompt /** - * @since 4.0.0 + * Transforms the output value produced by a prompt. + * * @category combinators + * @since 4.0.0 */ (self: Prompt, f: (output: Output) => Output2): Prompt } = dual(2, ( @@ -878,18 +1109,27 @@ export const map: { ) => flatMap(self, (a) => succeed(f(a)))) /** - * @since 4.0.0 + * Creates a password prompt that masks typed input and returns the submitted + * value wrapped in `Redacted`. + * * @category constructors + * @since 4.0.0 */ export const password = ( options: TextOptions ): Prompt => basePrompt(options, "password").pipe(map(Redacted.make)) /** - * Executes the specified `Prompt`. + * Runs a prompt by reading terminal input and rendering prompt frames until the + * prompt submits a value. + * + * **Gotchas** + * + * The returned effect may fail with `Terminal.QuitError` if terminal input ends + * or the prompt is quit. * - * @since 4.0.0 * @category execution + * @since 4.0.0 */ export const run: ( self: Prompt @@ -926,8 +1166,15 @@ const getSelectInitialIndex = (choices: ReadonlyArray>): numb } /** - * @since 4.0.0 + * Creates a prompt that lets the user select a single value from a list of + * choices. + * + * **Gotchas** + * + * At most one choice may be marked as selected by default. + * * @category constructors + * @since 4.0.0 */ export const select = (options: SelectOptions): Prompt => { const opts: SelectOptionsReq = { @@ -945,7 +1192,7 @@ export const select = (options: SelectOptions): Prompt => { /** * Creates a prompt that lets users filter select choices by typing. * - * **Example** + * **Example** (Filtering choices with autocomplete) * * ```ts * import { Prompt } from "effect/unstable/cli" @@ -960,8 +1207,8 @@ export const select = (options: SelectOptions): Prompt => { * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const autoComplete = (options: AutoCompleteOptions): Prompt => { const opts: AutoCompleteOptionsReq = { @@ -991,8 +1238,16 @@ export const autoComplete = (options: AutoCompleteOptions): Prompt( options: SelectOptions & MultiSelectOptions @@ -1020,11 +1275,13 @@ export const multiSelect = ( /** * Creates a `Prompt` which immediately succeeds with the specified value. * - * **NOTE**: This method will not attempt to obtain user input or render - * anything to the screen. + * **Details** + * + * This prompt does not attempt to obtain user input or render anything to the + * screen. * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const succeed = (value: A): Prompt => { const op = Object.create(proto) @@ -1034,16 +1291,22 @@ export const succeed = (value: A): Prompt => { } /** - * @since 4.0.0 + * Creates a text-entry prompt that echoes input and returns the submitted + * string after validation. + * * @category constructors + * @since 4.0.0 */ export const text = ( options: TextOptions ): Prompt => basePrompt(options, "text") /** - * @since 4.0.0 + * Creates a toggle prompt that lets the user switch between active and inactive + * states and returns the selected boolean value. + * * @category constructors + * @since 4.0.0 */ export const toggle = (options: ToggleOptions): Prompt => { const opts: ToggleOptionsReq = { @@ -1060,15 +1323,14 @@ export const toggle = (options: ToggleOptions): Prompt => { } const proto = { - ...YieldableProto, + ...Effectable.Prototype>({ + label: "Prompt", + evaluate() { + return run(this) + } + }), [TypeId]: { _Output: (_: never) => _ - }, - asEffect(): Effect.Effect { - return run(this as any) - }, - pipe() { - return Pipeable.pipeArguments(this, arguments) } } @@ -1082,8 +1344,12 @@ interface Loop extends Op<"Loop", { readonly initialState: unknown | Effect.Effect readonly render: Handlers["render"] - readonly process: Handlers["process"] + readonly process: ( + input: unknown, + state: unknown + ) => Effect.Effect, never, Environment> readonly clear: Handlers["clear"] + readonly events: Queue.Dequeue | undefined }> {} @@ -1154,8 +1420,19 @@ const runLoop = Effect.fnUntraced( while (true) { const msg = yield* loop.render(state, action) yield* Effect.orDie(terminal.display(msg)) - const event = yield* Queue.take(input) - action = yield* loop.process(event, state) + if (loop.events) { + const takeInput = Queue.take(input).pipe( + Effect.map((event) => ({ _tag: "Input" as const, event })) + ) + const result = yield* Effect.raceFirst( + takeInput, + Queue.take(loop.events).pipe(Effect.map((value) => ({ _tag: "Event" as const, value }))) + ) + action = yield* loop.process(result, state) + } else { + const result = yield* Queue.take(input) + action = yield* loop.process(result, state) + } switch (action._tag) { case "Beep": continue @@ -1848,8 +2125,9 @@ class Meridiem extends DatePart { } } -interface FileOptionsReq extends Required> { +interface FileOptionsReq extends Required> { readonly startingPath: Option.Option + readonly default: Option.Option } interface FileState { @@ -1882,7 +2160,7 @@ const resolveCurrentPath = ( } if (Option.isSome(options.startingPath)) { const startingPath = options.startingPath.value - return Effect.flatMap(FileSystem.FileSystem.asEffect(), (fs) => + return Effect.flatMap(FileSystem.FileSystem, (fs) => // Ensure the user provided starting path exists Effect.orDie(fs.exists(startingPath)).pipe( Effect.flatMap((exists) => diff --git a/.opencode/node_modules/effect/src/unstable/cli/index.ts b/.opencode/node_modules/effect/src/unstable/cli/index.ts index d81b5187f0b4b832b37018ad00cde0eacba2dee8..265b349619f361d3dd3f68eea2504de02c83b7dd 100644 --- a/.opencode/node_modules/effect/src/unstable/cli/index.ts +++ b/.opencode/node_modules/effect/src/unstable/cli/index.ts @@ -25,8 +25,6 @@ export * as CliOutput from "./CliOutput.ts" export * as Command from "./Command.ts" /** - * Shell completion descriptors and script generation for the unstable CLI API. - * * @since 4.0.0 */ export * as Completions from "./Completions.ts" @@ -47,30 +45,11 @@ export * as GlobalFlag from "./GlobalFlag.ts" export * as HelpDoc from "./HelpDoc.ts" /** - * @internal - * - * Param is the polymorphic implementation shared by Argument.ts and Flag.ts. - * The `Kind` type parameter ("argument" | "flag") enables type-safe separation - * while sharing parsing logic and combinators. - * - * Users should import from `Argument` and `Flag` modules, not this module directly. - * This module is not exported from the public API. - * * @since 4.0.0 */ export * as Param from "./Param.ts" /** - * Primitive types for CLI parameter parsing. - * - * Primitives handle the low-level parsing of string input into typed values. - * Most users should use the higher-level `Argument` and `Flag` modules instead. - * - * This module is primarily useful for: - * - Creating custom primitive types - * - Understanding how CLI parsing works internally - * - Advanced customization of parsing behavior - * * @since 4.0.0 */ export * as Primitive from "./Primitive.ts" diff --git a/.opencode/node_modules/effect/src/unstable/cli/internal/ansi.ts b/.opencode/node_modules/effect/src/unstable/cli/internal/ansi.ts index ea71d32ba79089c461e840eb5efc2672c7a259f4..5f0ba0d49953552d9c48e6ade6bc49eb3306b335 100644 --- a/.opencode/node_modules/effect/src/unstable/cli/internal/ansi.ts +++ b/.opencode/node_modules/effect/src/unstable/cli/internal/ansi.ts @@ -1,3 +1,16 @@ +/** + * Internal ANSI escape sequence helpers used by the unstable CLI rendering + * implementation. This module centralizes the control codes for text styling, + * cursor movement, line erasing, and terminal notifications so renderers can + * compose terminal output without scattering raw escape sequences throughout + * the CLI internals. + * + * The helpers deliberately work with plain strings because terminal rendering + * is sensitive to ordering: style codes must be reset after annotated text, + * cursor operations must account for one-based terminal coordinates, and line + * clearing usually needs to preserve the cursor position expected by the next + * frame. + */ const ESC = "\x1B[" const BEL = "\x07" const SEP = ";" diff --git a/.opencode/node_modules/effect/src/unstable/cli/internal/command.ts b/.opencode/node_modules/effect/src/unstable/cli/internal/command.ts index 0345146aa66139bcabc90832e6465bde9f5dc7bd..b35279b1c5982f05818e1c4e176b7be76be55dc1 100644 --- a/.opencode/node_modules/effect/src/unstable/cli/internal/command.ts +++ b/.opencode/node_modules/effect/src/unstable/cli/internal/command.ts @@ -8,9 +8,8 @@ import * as Arr from "../../../Array.ts" import * as Context from "../../../Context.ts" import * as Effect from "../../../Effect.ts" -import { YieldableProto } from "../../../internal/core.ts" +import * as Effectable from "../../../Effectable.ts" import * as Option from "../../../Option.ts" -import { pipeArguments } from "../../../Pipeable.ts" import * as Predicate from "../../../Predicate.ts" import * as CliError from "../CliError.ts" import type * as GlobalFlag from "../GlobalFlag.ts" @@ -73,14 +72,13 @@ export const toImpl = ( /* Proto */ /* ========================================================================== */ -export const Proto = { - ...YieldableProto, - pipe() { - return pipeArguments(this, arguments) - }, - asEffect(this: Command) { - return toImpl(this).service.asEffect() - } +export const Proto: Effect.Effect = { + ...Effectable.Prototype({ + label: "Command", + evaluate() { + return toImpl(this).service + } + }) } /* ========================================================================== */ @@ -100,6 +98,7 @@ export const makeCommand = | undefined readonly subcommands?: ReadonlyArray | undefined readonly parse?: ((input: ParsedTokens) => Effect.Effect) | undefined @@ -147,7 +146,9 @@ export const makeCommand = 0 ? commandPath.join(" ") : options.name - if (subcommands.some((group) => group.commands.length > 0)) { + // Only render `` in usage when at least one visible subcommand + // exists; an all-hidden subcommand tree should look like a leaf command. + if (subcommands.some((group) => group.commands.some((c) => !c.hidden))) { usage += " " } usage += " [flags]" @@ -159,6 +160,9 @@ export const makeCommand = = { readonly existingShards: Array @@ -343,8 +422,15 @@ export type EncodedUnprocessedOptions = { } /** - * @since 4.0.0 + * Cursor options for reading encoded replies across request sets. + * + * **Details** + * + * The fields distinguish existing requests from new requests and carry the + * driver-specific pagination cursor. + * * @category Encoded + * @since 4.0.0 */ export type EncodedRepliesOptions = { readonly existingRequests: Array @@ -353,8 +439,15 @@ export type EncodedRepliesOptions = { } /** - * @since 4.0.0 + * Wraps a concrete message storage implementation with reply-handler management. + * + * **Details** + * + * The returned service can register waiting reply handlers, notify them when + * replies are saved, and fail them when a request or shard is unregistered. + * * @category constructors + * @since 4.0.0 */ export const make = ( storage: Omit< @@ -455,8 +548,16 @@ export const make = ( }) /** - * @since 4.0.0 + * Builds a `MessageStorage` service from an encoded storage driver. + * + * **Details** + * + * The adapter handles envelope and reply encoding and decoding, primary-key + * generation, delayed delivery checks, duplicate decoding, and malformed-message + * defect replies. + * * @category constructors + * @since 4.0.0 */ export const makeEncoded: (encoded: Encoded) => Effect.Effect< MessageStorage["Service"], @@ -663,8 +764,10 @@ export const makeEncoded: (encoded: Encoded) => Effect.Effect< }) /** + * No-op `MessageStorage` service that does not persist messages or replies. + * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const noop: MessageStorage["Service"] = Effect.runSync(make({ saveRequest: () => Effect.succeed(SaveResult.Success()), @@ -683,8 +786,15 @@ export const noop: MessageStorage["Service"] = Effect.runSync(make({ })) /** + * In-memory storage entry for a request envelope. + * + * **Details** + * + * It stores the encoded envelope, last acknowledged chunk, accumulated replies, + * and optional delivery time. + * + * @category memory * @since 4.0.0 - * @category Memory */ export type MemoryEntry = { readonly envelope: Envelope.Encoded @@ -694,18 +804,26 @@ export type MemoryEntry = { } /** - * Can be used in tests to simulate a transaction. + * Provides a context reference used in tests to simulate a transaction. * + * @category memory * @since 4.0.0 - * @category Memory */ export const MemoryTransaction = Context.Reference("effect/cluster/MessageStorage/MemoryTransaction", { defaultValue: constFalse }) /** + * Service that provides an in-memory message storage driver with inspectable backing state. + * + * **Details** + * + * It provides a `MessageStorage` service, the encoded driver implementation, and + * maps used to track requests, primary keys, unprocessed envelopes, reply IDs, + * and the journal. + * + * @category memory * @since 4.0.0 - * @category Memory */ export class MemoryDriver extends Context.Service()("effect/cluster/MessageStorage/MemoryDriver", { make: Effect.gen(function*() { @@ -908,6 +1026,8 @@ export class MemoryDriver extends Context.Service()("effect/cluste }) }) { /** + * Layer that provides the in-memory message storage driver. + * * @since 4.0.0 */ static readonly layer: Layer.Layer = Layer.effect(this)(this.make).pipe( @@ -916,20 +1036,24 @@ export class MemoryDriver extends Context.Service()("effect/cluste } /** - * @since 4.0.0 + * Layer that provides the no-op `MessageStorage` service. + * * @category layers + * @since 4.0.0 */ export const layerNoop: Layer.Layer = Layer.succeed(MessageStorage, noop) /** - * @since 4.0.0 + * Layer that provides in-memory message storage and its backing `MemoryDriver`. + * * @category layers + * @since 4.0.0 */ export const layerMemory: Layer.Layer< MessageStorage | MemoryDriver, never, ShardingConfig -> = Layer.effect(MessageStorage, Effect.map(MemoryDriver.asEffect(), (_) => _.storage)).pipe( +> = Layer.effect(MessageStorage, Effect.map(MemoryDriver, (_) => _.storage)).pipe( Layer.provideMerge(MemoryDriver.layer) ) diff --git a/.opencode/node_modules/effect/src/unstable/cluster/Reply.ts b/.opencode/node_modules/effect/src/unstable/cluster/Reply.ts index 82b985fffb63561b8adc7ddcee3299ccc7c80ccc..c2bda06ae2f7bcee915ce557884b05718ddc6aab 100644 --- a/.opencode/node_modules/effect/src/unstable/cluster/Reply.ts +++ b/.opencode/node_modules/effect/src/unstable/cluster/Reply.ts @@ -1,4 +1,13 @@ /** + * Defines reply values produced by clustered RPC execution. + * + * Every reply belongs to a request and is either a final `WithExit`, which + * carries the final RPC `Exit`, or a streaming `Chunk`, which carries a + * non-empty batch of success values. This module includes runtime and encoded + * reply shapes, guards, per-RPC schema builders, `ReplyWithContext` for + * carrying encoding services, and serialization helpers for storage or + * transport. + * * @since 4.0.0 */ import type { NonEmptyReadonlyArray } from "../../Array.ts" @@ -9,9 +18,9 @@ import * as Exit from "../../Exit.ts" import * as Option from "../../Option.ts" import { hasProperty } from "../../Predicate.ts" import * as Schema from "../../Schema.ts" -import * as Issue from "../../SchemaIssue.ts" -import * as Parser from "../../SchemaParser.ts" -import * as Transformation from "../../SchemaTransformation.ts" +import * as SchemaIssue from "../../SchemaIssue.ts" +import * as SchemaParser from "../../SchemaParser.ts" +import * as SchemaTransformation from "../../SchemaTransformation.ts" import * as Rpc from "../rpc/Rpc.ts" import type * as RpcMessage from "../rpc/RpcMessage.ts" import type * as RpcSchema from "../rpc/RpcSchema.ts" @@ -22,32 +31,54 @@ import { Snowflake, SnowflakeFromBigInt } from "./Snowflake.ts" const TypeId = "~effect/cluster/Reply" /** - * @since 4.0.0 + * Returns `true` when the supplied value is a runtime cluster reply, based on the + * reply type identifier. + * * @category guards + * @since 4.0.0 */ export const isReply = (u: unknown): u is Reply => hasProperty(u, TypeId) /** - * @since 4.0.0 + * Runtime reply sent for an RPC request, either as a final exit or a chunk of a + * streaming success value. + * * @category models + * @since 4.0.0 */ export type Reply = WithExit | Chunk /** - * @since 4.0.0 + * JSON-serializable form of a cluster reply. + * * @category models + * @since 4.0.0 */ export type Encoded = WithExitEncoded | ChunkEncoded /** + * Schema for reply values that are already in encoded form. + * + * **Details** + * + * Per-RPC payload validation is performed by `Reply(rpc)`. + * + * @category schemas * @since 4.0.0 - * @category models */ export const Encoded: Schema.Codec = Schema.Any as any /** - * @since 4.0.0 + * Represents a cluster reply paired with the RPC definition and service context required to + * serialize it for transport. + * + * **When to use** + * + * Use to carry a runtime reply together with the RPC schema and services needed + * to encode it for storage or transport. + * * @category models + * @since 4.0.0 */ export class ReplyWithContext extends Data.TaggedClass("ReplyWithContext")<{ readonly reply: Reply @@ -55,6 +86,8 @@ export class ReplyWithContext extends Data.TaggedClass("Reply readonly rpc: R }> { /** + * Creates a terminal reply context that dies with the supplied defect. + * * @since 4.0.0 */ static fromDefect(options: { @@ -66,13 +99,15 @@ export class ReplyWithContext extends Data.TaggedClass("Reply reply: new WithExit({ requestId: options.requestId, id: options.id, - exit: Exit.die(Schema.encodeSync(Schema.Defect)(options.defect)) + exit: Exit.die(Schema.encodeSync(Schema.Defect())(options.defect)) }), context: Context.empty() as any, rpc: neverRpc }) } /** + * Creates a terminal reply context that interrupts the supplied request. + * * @since 4.0.0 */ static interrupt(options: { @@ -98,8 +133,11 @@ const neverRpc = Rpc.make("Never", { }) /** - * @since 4.0.0 + * Wire-format representation of a terminal reply containing the request id, reply + * id, and encoded RPC exit value. + * * @category models + * @since 4.0.0 */ export interface WithExitEncoded { readonly _tag: "WithExit" @@ -109,8 +147,11 @@ export interface WithExitEncoded { } /** - * @since 4.0.0 + * Wire-format representation of a streaming reply chunk, including the request id, + * reply id, sequence number, and non-empty encoded values. + * * @category models + * @since 4.0.0 */ export interface ChunkEncoded { readonly _tag: "Chunk" @@ -123,8 +164,11 @@ export interface ChunkEncoded { const schemaCache = new WeakMap() /** - * @since 4.0.0 + * Represents a streaming RPC reply chunk for a request, carrying a non-empty + * batch of success values together with the reply id and sequence number. + * * @category models + * @since 4.0.0 */ export class Chunk extends Data.TaggedClass("Chunk")<{ readonly requestId: Snowflake @@ -133,11 +177,15 @@ export class Chunk extends Data.TaggedClass("Chunk")<{ readonly values: NonEmptyReadonlyArray> }> { /** + * Marks this value as a runtime cluster reply. + * * @since 4.0.0 */ readonly [TypeId] = TypeId /** + * Creates an empty chunk reply for the supplied request id. + * * @since 4.0.0 */ static emptyFrom(requestId: Snowflake) { @@ -150,19 +198,25 @@ export class Chunk extends Data.TaggedClass("Chunk")<{ } /** + * Schema that accepts any runtime chunk reply without validating payload values. + * * @since 4.0.0 */ static readonly Any = Schema.declare((u): u is Chunk => isReply(u) && u._tag === "Chunk") /** + * Transformation between encoded chunk records and `Chunk` instances. + * * @since 4.0.0 */ - static readonly transform: Transformation.Transformation = Transformation.transform({ + static readonly transform: SchemaTransformation.Transformation = SchemaTransformation.transform({ decode: (a: any) => new Chunk(a), encode: (a) => a as any }) /** + * Builds a chunk schema from the streaming success schema of an RPC. + * * @since 4.0.0 */ static schema( @@ -176,6 +230,8 @@ export class Chunk extends Data.TaggedClass("Chunk")<{ } /** + * Builds a chunk schema that validates each success value with the supplied schema. + * * @since 4.0.0 */ static schemaFrom( @@ -186,10 +242,11 @@ export class Chunk extends Data.TaggedClass("Chunk")<{ [success], ([success]) => (input, ast, options) => { if (!isReply(input) || input._tag !== "Chunk") { - return Effect.fail(new Issue.InvalidType(ast, Option.some(input))) + return Effect.fail(new SchemaIssue.InvalidType(ast, Option.some(input))) } - return Effect.mapBothEager(Parser.decodeEffect(Schema.NonEmptyArray(success))(input.values, options), { - onFailure: (issue) => new Issue.Composite(ast, Option.some(input), [new Issue.Pointer(["values"], issue)]), + return Effect.mapBothEager(SchemaParser.decodeEffect(Schema.NonEmptyArray(success))(input.values, options), { + onFailure: (issue) => + new SchemaIssue.Composite(ast, Option.some(input), [new SchemaIssue.Pointer(["values"], issue)]), onSuccess: (values) => new Chunk({ ...input, values } as any) }) }, @@ -204,7 +261,7 @@ export class Chunk extends Data.TaggedClass("Chunk")<{ sequence: Schema.Number, values: Schema.NonEmptyArray(success) }), - Transformation.transform({ + SchemaTransformation.transform({ decode: (encoded) => new Chunk(encoded), encode: (result) => ({ ...result }) }) @@ -214,6 +271,8 @@ export class Chunk extends Data.TaggedClass("Chunk")<{ } /** + * Returns a copy of this chunk associated with the supplied request id. + * * @since 4.0.0 */ withRequestId(requestId: Snowflake): Chunk { @@ -225,8 +284,16 @@ export class Chunk extends Data.TaggedClass("Chunk")<{ } /** - * @since 4.0.0 + * Represents a terminal RPC reply for a request, carrying the final `Exit` for the remote + * call. + * + * **When to use** + * + * Use to represent the final success, typed failure, defect, or interruption + * for a clustered RPC request. + * * @category models + * @since 4.0.0 */ export class WithExit extends Data.TaggedClass("WithExit")<{ readonly requestId: Snowflake @@ -234,11 +301,15 @@ export class WithExit extends Data.TaggedClass("WithExit")<{ readonly exit: Rpc.Exit }> { /** + * Marks this value as a runtime cluster reply. + * * @since 4.0.0 */ readonly [TypeId] = TypeId /** + * Returns `true` when the value is a terminal `WithExit` reply. + * * @since 4.0.0 */ static is(u: unknown): u is WithExit { @@ -246,6 +317,8 @@ export class WithExit extends Data.TaggedClass("WithExit")<{ } /** + * Builds a terminal reply schema from the exit schema of an RPC. + * * @since 4.0.0 */ static schema( @@ -259,6 +332,8 @@ export class WithExit extends Data.TaggedClass("WithExit")<{ } /** + * Builds a terminal reply schema that validates the encoded exit value. + * * @since 4.0.0 */ static schemaFrom( @@ -273,10 +348,11 @@ export class WithExit extends Data.TaggedClass("WithExit")<{ [exitSchema], ([exit]) => (input, ast, options) => { if (!isReply(input) || input._tag !== "WithExit") { - return Effect.fail(new Issue.InvalidType(ast, Option.some(input))) + return Effect.fail(new SchemaIssue.InvalidType(ast, Option.some(input))) } - return Effect.mapBothEager(Parser.decodeEffect(exit)(input.exit, options), { - onFailure: (issue) => new Issue.Composite(ast, Option.some(input), [new Issue.Pointer(["exit"], issue)]), + return Effect.mapBothEager(SchemaParser.decodeEffect(exit)(input.exit, options), { + onFailure: (issue) => + new SchemaIssue.Composite(ast, Option.some(input), [new SchemaIssue.Pointer(["exit"], issue)]), onSuccess: (exit) => new WithExit({ ...input, exit: exit as any }) }) }, @@ -290,7 +366,7 @@ export class WithExit extends Data.TaggedClass("WithExit")<{ id: SnowflakeFromBigInt, exit }), - Transformation.transform({ + SchemaTransformation.transform({ decode: (encoded) => new WithExit(encoded as any), encode: (result) => ({ ...result }) }) @@ -300,6 +376,8 @@ export class WithExit extends Data.TaggedClass("WithExit")<{ } /** + * Returns a copy of this terminal reply associated with the supplied request id. + * * @since 4.0.0 */ withRequestId(requestId: Snowflake): WithExit { @@ -311,8 +389,11 @@ export class WithExit extends Data.TaggedClass("WithExit")<{ } /** - * @since 4.0.0 + * Builds the transport codec for replies to the specified RPC, covering terminal + * `WithExit` replies and streaming `Chunk` replies. + * * @category schemas + * @since 4.0.0 */ export const Reply = ( rpc: R @@ -331,8 +412,12 @@ export const Reply = ( } /** + * Serializes a `ReplyWithContext` into its encoded wire representation, using the + * reply's RPC schema and context and refailing encoding errors as + * `MalformedMessage`. + * + * @category serialization * @since 4.0.0 - * @category serialization / deserialization */ export const serialize = ( self: ReplyWithContext @@ -347,8 +432,12 @@ export const serialize = ( } /** + * Serializes an outgoing request's last received reply when one exists, returning + * `None` when no reply has been received and refailing encoding errors as + * `MalformedMessage`. + * + * @category serialization * @since 4.0.0 - * @category serialization / deserialization */ export const serializeLastReceived = ( self: OutgoingRequest diff --git a/.opencode/node_modules/effect/src/unstable/cluster/Runner.ts b/.opencode/node_modules/effect/src/unstable/cluster/Runner.ts index a49e1b9f264456808c230b6a161281ae8fd68173..d5a54e787daff4241aecfceb9466df18518ded66 100644 --- a/.opencode/node_modules/effect/src/unstable/cluster/Runner.ts +++ b/.opencode/node_modules/effect/src/unstable/cluster/Runner.ts @@ -1,4 +1,10 @@ /** + * Cluster runner metadata for processes that can host entity shards. + * + * A `Runner` combines the stable `RunnerAddress` used to contact a process, the + * shard groups that process participates in, and the relative weight used when + * the sharding service distributes shards across healthy runners. + * * @since 4.0.0 */ import * as Equal from "../../Equal.ts" @@ -10,17 +16,15 @@ import { RunnerAddress } from "./RunnerAddress.ts" const TypeId = "~effect/cluster/Runner" /** - * A `Runner` represents a physical application server that is capable of running - * entities. + * Represents a cluster runner that can host entities. * - * Because a Runner represents a physical application server, a Runner must have a - * unique `address` which can be used to communicate with the server. + * **Details** * - * The version of a Runner is used during rebalancing to give priority to newer - * application servers and slowly decommission older ones. + * Each runner has a unique network `address`, the shard `groups` it participates + * in, and a relative `weight` used when assigning shards across runners. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export class Runner extends Schema.Class(TypeId)({ address: RunnerAddress, @@ -28,26 +32,36 @@ export class Runner extends Schema.Class(TypeId)({ weight: Schema.Number }) { /** + * Formatter for rendering runner values consistently. + * * @since 4.0.0 */ static format = Schema.toFormatter(this) /** + * Marks this value as a cluster runner for runtime guards. + * * @since 4.0.0 */ readonly [TypeId] = TypeId /** + * Decodes a runner from its JSON string representation. + * * @since 4.0.0 */ static readonly decodeSync = Schema.decodeSync(Schema.fromJsonString(Runner)) /** + * Encodes a runner to its JSON string representation. + * * @since 4.0.0 */ static readonly encodeSync = Schema.encodeSync(Schema.fromJsonString(Runner)) /** + * Formats this runner as a string. + * * @since 4.0.0 */ override toString(): string { @@ -55,6 +69,8 @@ export class Runner extends Schema.Class(TypeId)({ } /** + * Formats this runner for Node.js inspection. + * * @since 4.0.0 */ [NodeInspectSymbol](): string { @@ -62,6 +78,8 @@ export class Runner extends Schema.Class(TypeId)({ } /** + * Compares runners by address and shard-assignment weight. + * * @since 4.0.0 */ [Equal.symbol](that: Runner): boolean { @@ -69,6 +87,8 @@ export class Runner extends Schema.Class(TypeId)({ } /** + * Computes a structural hash from the runner address and shard-assignment weight. + * * @since 4.0.0 */ [Hash.symbol](): number { @@ -77,17 +97,30 @@ export class Runner extends Schema.Class(TypeId)({ } /** - * A `Runner` represents a physical application server that is capable of running - * entities. + * Constructs a `Runner` from its network address, shard groups, and relative + * shard-assignment weight. + * + * **When to use** + * + * Use to build runner metadata from an existing `RunnerAddress`, shard groups, + * and relative weight when registering or exchanging a cluster runner. + * + * **Details** + * + * The `groups` array lists the shard groups the runner can host. During shard + * assignment, the runner's address is added to each group's hash ring with + * `weight` as its relative weight. + * + * **Gotchas** * - * Because a Runner represents a physical application server, a Runner must have a - * unique `address` which can be used to communicate with the server. + * This helper constructs the value without runtime schema validation, so only + * pass trusted `RunnerAddress`, `groups`, and `weight` values. * - * The version of a Runner is used during rebalancing to give priority to newer - * application servers and slowly decommission older ones. + * @see {@link Runner} for the value created by this helper + * @see {@link RunnerAddress} for the network address accepted in `props.address` * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const make = (props: { readonly address: RunnerAddress diff --git a/.opencode/node_modules/effect/src/unstable/cluster/RunnerAddress.ts b/.opencode/node_modules/effect/src/unstable/cluster/RunnerAddress.ts index b3b4aa16ff098a252e8f02b24ae696bc3e59e8a9..69ce6b2392ed0c2bb954c0c2883977d94eedb989 100644 --- a/.opencode/node_modules/effect/src/unstable/cluster/RunnerAddress.ts +++ b/.opencode/node_modules/effect/src/unstable/cluster/RunnerAddress.ts @@ -1,4 +1,9 @@ /** + * Network addresses for locating cluster runners. A `RunnerAddress` stores the + * host and port for a runner and provides schema support, structural equality, + * hashing, Node.js inspection, and a stable primary key formatted from the host + * and port. + * * @since 4.0.0 */ import * as Equal from "../../Equal.ts" @@ -10,19 +15,31 @@ import * as Schema from "../../Schema.ts" const TypeId = "~effect/cluster/RunnerAddress" /** - * @since 4.0.0 + * Represents the network address of a cluster runner, identified by host and + * port. + * + * **When to use** + * + * Use to represent the host and port that identify a runner in cluster routing, + * registration, and health checks. + * * @category models + * @since 4.0.0 */ export class RunnerAddress extends Schema.Class(TypeId)({ host: Schema.String, port: Schema.Number }) { /** + * Marks this value as a cluster runner address for runtime guards. + * * @since 4.0.0 */ readonly [TypeId] = TypeId; /** + * Compares runner addresses by host and port. + * * @since 4.0.0 */ [Equal.symbol](that: RunnerAddress): boolean { @@ -30,6 +47,8 @@ export class RunnerAddress extends Schema.Class(TypeId)({ } /** + * Computes a structural hash from the host and port. + * * @since 4.0.0 */ [Hash.symbol]() { @@ -37,6 +56,8 @@ export class RunnerAddress extends Schema.Class(TypeId)({ } /** + * Stable primary key used to identify the runner address. + * * @since 4.0.0 */ [PrimaryKey.symbol](): string { @@ -44,6 +65,8 @@ export class RunnerAddress extends Schema.Class(TypeId)({ } /** + * Formats the runner address with its host and port. + * * @since 4.0.0 */ override toString(): string { @@ -51,6 +74,8 @@ export class RunnerAddress extends Schema.Class(TypeId)({ } /** + * Formats the runner address for Node.js inspection. + * * @since 4.0.0 */ [NodeInspectSymbol](): string { @@ -59,8 +84,29 @@ export class RunnerAddress extends Schema.Class(TypeId)({ } /** - * @since 4.0.0 + * Constructs a `RunnerAddress` from a host and port. + * + * **When to use** + * + * Use to create the stable network identity for a cluster runner when + * configuring sharding, registering runner metadata, or targeting a runner by + * host and port. + * + * **Details** + * + * The returned `RunnerAddress` stores the supplied `host` and `port`. Equality, + * hashing, and the primary key use both fields, with the primary key formatted + * as `host:port`. + * + * **Gotchas** + * + * `make` does not normalize the host. Pass the host string exactly as the + * cluster routing and storage layers should identify it. + * + * @see {@link RunnerAddress} for the constructed address type and its equality, hashing, primary-key, and formatting behavior + * * @category constructors + * @since 4.0.0 */ export const make = (host: string, port: number): RunnerAddress => new RunnerAddress({ host, port }, { disableChecks: true }) diff --git a/.opencode/node_modules/effect/src/unstable/cluster/RunnerHealth.ts b/.opencode/node_modules/effect/src/unstable/cluster/RunnerHealth.ts index 255bd6e8497eaec080e7d1aa0eba3c06a4e0036c..51ddcb5fa97618f411b19fa9318a411a42828c54 100644 --- a/.opencode/node_modules/effect/src/unstable/cluster/RunnerHealth.ts +++ b/.opencode/node_modules/effect/src/unstable/cluster/RunnerHealth.ts @@ -1,4 +1,12 @@ /** + * Checks whether cluster runners should be treated as alive. + * + * `RunnerHealth` is used by sharding when deciding whether assigned shards can + * stay on a runner or need to move elsewhere. This module includes the + * health-check service, a no-op layer that always reports runners as alive, a + * ping-based checker, and a Kubernetes-based checker that looks at pod readiness + * for the runner host. + * * @since 4.0.0 */ import * as Context from "../../Context.ts" @@ -13,12 +21,14 @@ import * as Runners from "./Runners.ts" /** * Represents the service used to check if a Runner is healthy. * + * **Details** + * * If a Runner is responsive, shards will not be re-assigned because the Runner may * still be processing messages. If a Runner is not responsive, then its * associated shards can and will be re-assigned to a different Runner. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export class RunnerHealth extends Context.Service< RunnerHealth, @@ -28,20 +38,27 @@ export class RunnerHealth extends Context.Service< >()("effect/cluster/RunnerHealth") {} /** - * A layer which will **always** consider a Runner healthy. + * Layer that always considers a runner healthy. * - * This is useful for testing. + * **When to use** + * + * Use when you need a runner-health layer for tests or local development where + * active health checks are unnecessary. * - * @since 4.0.0 * @category layers + * @since 4.0.0 */ export const layerNoop = Layer.succeed(RunnerHealth, { isAlive: () => Effect.succeed(true) }) /** + * Creates a `RunnerHealth` service that pings runners through `Runners`, retrying + * failed pings on a short schedule and treating a successful ping within the + * timeout as healthy. + * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const makePing: Effect.Effect< RunnerHealth["Service"], @@ -63,10 +80,10 @@ export const makePing: Effect.Effect< }) /** - * A layer which will ping a Runner directly to check if it is healthy. + * Layer that pings runners directly to check whether they are healthy. * - * @since 4.0.0 * @category layers + * @since 4.0.0 */ export const layerPing: Layer.Layer< RunnerHealth, @@ -75,8 +92,15 @@ export const layerPing: Layer.Layer< > = Layer.effect(RunnerHealth, makePing) /** + * Creates a `RunnerHealth` service that checks Kubernetes pod readiness for a + * runner host, optionally scoped by namespace and label selector. + * + * **Gotchas** + * + * If the Kubernetes API check fails, the runner is treated as healthy. + * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const makeK8s = Effect.fnUntraced(function*(options?: { readonly namespace?: string | undefined @@ -94,16 +118,20 @@ export const makeK8s = Effect.fnUntraced(function*(options?: { }) /** - * A layer which will check the Kubernetes API to see if a Runner is healthy. + * Layer that checks Kubernetes pod readiness to determine whether a runner is + * healthy. * - * The provided HttpClient will need to add the pod's CA certificate to its - * trusted root certificates in order to communicate with the Kubernetes API. + * **Details** * - * The pod service account will also need to have permissions to list pods in - * order to use this layer. + * The provided `HttpClient` must trust the pod CA certificate and the pod service + * account must be allowed to list pods. + * + * **Gotchas** + * + * If the Kubernetes API check fails, the runner is treated as healthy. * - * @since 4.0.0 * @category layers + * @since 4.0.0 */ export const layerK8s = ( options?: { diff --git a/.opencode/node_modules/effect/src/unstable/cluster/RunnerServer.ts b/.opencode/node_modules/effect/src/unstable/cluster/RunnerServer.ts index 346efb9cc020b79178fa2dc2678f661d9907ea34..cea221b3837ba168284c919225a07bfe9d8b9c2c 100644 --- a/.opencode/node_modules/effect/src/unstable/cluster/RunnerServer.ts +++ b/.opencode/node_modules/effect/src/unstable/cluster/RunnerServer.ts @@ -1,4 +1,13 @@ /** + * Provides server-side layers for the cluster runner protocol. + * + * Runner protocol handlers receive ping, notification, request, stream, and + * envelope messages from other runners. They forward those messages into + * `Sharding` and coordinate persisted replies through `MessageStorage`. This + * module includes the handler layer, a transport-independent RPC server layer, a + * full server layer that also provides runner clients, and a client-only layer + * for applications that do not serve runner RPCs. + * * @since 4.0.0 */ import * as Effect from "../../Effect.ts" @@ -22,8 +31,11 @@ import { ShardingConfig } from "./ShardingConfig.ts" const constVoid = constant(Effect.void) /** + * Layer that handles runner protocol RPCs by forwarding requests to `Sharding` + * and `MessageStorage`. + * + * @category layers * @since 4.0.0 - * @category Layers */ export const layerHandlers = Runners.Rpcs.toLayer(Effect.gen(function*() { const sharding = yield* Sharding.Sharding @@ -129,13 +141,26 @@ export const layerHandlers = Runners.Rpcs.toLayer(Effect.gen(function*() { const constWaitUntilRead = { waitUntilRead: true } as const /** - * The `RunnerServer` recieves messages from other Runners and forwards them to the - * `Sharding` layer. + * Creates the runner RPC server layer, which receives messages from other + * runners, forwards them to the `Sharding` layer, and responds to `Ping` + * requests. + * + * **When to use** * - * It also responds to `Ping` requests. + * Use when a runner process should accept runner-to-runner protocol messages + * over a provided server `RpcServer.Protocol`. * + * **Gotchas** + * + * This layer does not choose or provide the wire transport; provide a + * transport-specific `RpcServer.Protocol` separately. + * + * @see {@link layerHandlers} for the lower-level handler layer used when the RPC server is supplied elsewhere + * @see {@link layerWithClients} for a runner server layer that also provides the `Sharding` and `Runners` clients + * @see {@link layerClientOnly} for embedding a cluster client without serving runner RPCs + * + * @category layers * @since 4.0.0 - * @category Layers */ export const layer: Layer.Layer< never, @@ -147,10 +172,11 @@ export const layer: Layer.Layer< }).pipe(Layer.provide(layerHandlers)) /** - * A `RunnerServer` layer that includes the `Runners` & `Sharding` clients. + * Layer that provides `RunnerServer` together with `Runners` and `Sharding` + * clients. * + * @category layers * @since 4.0.0 - * @category Layers */ export const layerWithClients: Layer.Layer< Sharding.Sharding | Runners.Runners, @@ -167,14 +193,15 @@ export const layerWithClients: Layer.Layer< ) /** - * A `Runners` layer that is client only. + * Creates a client-only `Runners` layer. + * + * **When to use** * - * It will not register with the ShardManager and recieve shard assignments, - * so this layer can be used to embed a cluster client inside another effect - * application. + * Use to embed a cluster client inside another Effect application without registering with + * the ShardManager or receiving shard assignments. * + * @category layers * @since 4.0.0 - * @category Layers */ export const layerClientOnly: Layer.Layer< Sharding.Sharding | Runners.Runners, diff --git a/.opencode/node_modules/effect/src/unstable/cluster/RunnerStorage.ts b/.opencode/node_modules/effect/src/unstable/cluster/RunnerStorage.ts index 42dafbd9290d2a1db7502496d0306ac2b67fc3dc..8f19777fed27d1945ffbbf8af7cf5f8af80ee015 100644 --- a/.opencode/node_modules/effect/src/unstable/cluster/RunnerStorage.ts +++ b/.opencode/node_modules/effect/src/unstable/cluster/RunnerStorage.ts @@ -1,4 +1,12 @@ /** + * Stores runner registration and shard-lock state for cluster sharding. + * + * `RunnerStorage` records which runners are registered, whether they are + * healthy, which machine id a runner receives, and which shard locks are held + * by each runner. This module includes the typed storage service, a + * string-encoded backend interface, an adapter from encoded storage to the typed + * service, and an in-memory implementation for tests and local use. + * * @since 4.0.0 */ import { isArrayNonEmpty, type NonEmptyArray } from "../../Array.ts" @@ -16,8 +24,8 @@ import * as ShardId from "./ShardId.ts" * Represents a generic interface to the persistent storage required by the * cluster. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export class RunnerStorage extends Context.Service()("effect/cluster/RunnerStorage") {} /** - * @since 4.0.0 + * String-encoded runner storage interface used by adapters that persist runner + * addresses, runners, machine ids, and shard ids outside the in-memory model. + * * @category Encoded + * @since 4.0.0 */ export interface Encoded { /** @@ -130,8 +141,12 @@ export interface Encoded { } /** - * @since 4.0.0 + * Adapts an encoded runner storage implementation into `RunnerStorage`, converting + * runner addresses, runners, machine ids, and shard ids between typed values and + * their string or numeric storage forms. + * * @category layers + * @since 4.0.0 */ export const makeEncoded = (encoded: Encoded) => RunnerStorage.of({ @@ -176,8 +191,15 @@ export const makeEncoded = (encoded: Encoded) => }) /** - * @since 4.0.0 + * Creates an in-memory `RunnerStorage` implementation for tests and local use. + * + * **Details** + * + * Registered runners are treated as healthy and shard acquisition is kept only in + * process memory. + * * @category constructors + * @since 4.0.0 */ export const makeMemory = Effect.gen(function*() { const runners = MutableHashMap.empty() @@ -207,8 +229,10 @@ export const makeMemory = Effect.gen(function*() { }) /** - * @since 4.0.0 + * Layer that provides the in-memory `RunnerStorage` implementation. + * * @category layers + * @since 4.0.0 */ export const layerMemory: Layer.Layer = Layer.effect(RunnerStorage)(makeMemory) diff --git a/.opencode/node_modules/effect/src/unstable/cluster/Runners.ts b/.opencode/node_modules/effect/src/unstable/cluster/Runners.ts index fd787af79699da8fc5e3ac91a4ec3fb3f5d36622..fea620c40dfc9d042f5718e54a71cadf54204b97 100644 --- a/.opencode/node_modules/effect/src/unstable/cluster/Runners.ts +++ b/.opencode/node_modules/effect/src/unstable/cluster/Runners.ts @@ -1,4 +1,13 @@ /** + * Handles communication between Effect Cluster runners. + * + * `Runners` sits between sharding decisions and runner execution. It can ping a + * runner, send requests or control envelopes, notify a runner that persisted + * work is available, and record that a runner address is unavailable. This + * module defines the runner communication service, its RPC protocol, no-op and + * RPC-backed implementations, local persistence support, reply recovery, and + * the protocol service used by transport-specific runner layers. + * * @since 4.0.0 */ import * as Context from "../../Context.ts" @@ -28,12 +37,16 @@ import { ShardingConfig } from "./ShardingConfig.ts" import * as Snowflake from "./Snowflake.ts" /** - * @since 1.0.0 + * Service for communicating with cluster runners, including pinging runners, + * sending and notifying messages, coordinating persisted replies, and marking + * runners unavailable. + * * @category context + * @since 4.0.0 */ export class Runners extends Context.Service Effect.Effect @@ -112,8 +125,36 @@ export class Runners extends Context.Service()("effect/cluster/Runners") {} /** - * @since 1.0.0 - * @category Constructors + * Builds the `Runners` service from remote runner callbacks and adds local + * message persistence, duplicate request handling, optional local serialization + * simulation, and polling for persisted replies. + * + * **When to use** + * + * Use when you need a custom `Runners` service around remote `ping`, `send`, + * `notify`, and `onRunnerUnavailable` callbacks, with standard local + * persistence and reply recovery behavior. + * + * **Details** + * + * `make` uses the supplied remote callbacks for runner communication and + * derives `sendLocal` and `notifyLocal`. Local sends can optionally simulate + * remote serialization, persisted notifications are saved through + * `MessageStorage`, duplicate requests are resumed from stored replies when + * possible, and pending replies are polled according to + * `ShardingConfig.entityReplyPollInterval`. + * + * **Gotchas** + * + * `notify` and `notifyLocal` only support RPCs annotated as persisted; calling + * either path with a non-persisted message dies instead of returning a typed + * error. + * + * @see {@link makeRpc} for the RPC-backed implementation built on top of this constructor + * @see {@link makeNoop} for a no-op implementation when remote runner communication is not needed + * + * @category constructors + * @since 4.0.0 */ export const make: (options: Omit) => Effect.Effect< Runners["Service"], @@ -380,8 +421,12 @@ export const make: (options: Omit {} /** - * @since 1.0.0 + * Builds a runner RPC client from the current `RpcClient.Protocol`, using the + * `Runners` span prefix with tracing disabled. + * * @category Rpcs + * @since 4.0.0 */ export const makeRpcClient: Effect.Effect< RpcClient, @@ -470,8 +526,12 @@ export const makeRpcClient: Effect.Effect< > = RpcClient_.make(Rpcs, { spanPrefix: "Runners", disableTracing: true }) /** - * @since 1.0.0 + * Builds a `Runners` service backed by RPC clients, caching a client per runner + * address and dispatching ping, notify, effect, stream, and envelope messages over + * the runner protocol. + * * @category constructors + * @since 4.0.0 */ export const makeRpc: Effect.Effect< Runners["Service"], @@ -603,8 +663,11 @@ export const makeRpc: Effect.Effect< }) /** - * @since 1.0.0 - * @category Layers + * Layer that provides an RPC-backed `Runners` service using `RpcClientProtocol`, + * message storage, sharding configuration, and the default snowflake generator. + * + * @category layers + * @since 4.0.0 */ export const layerRpc: Layer.Layer< Runners, @@ -615,8 +678,11 @@ export const layerRpc: Layer.Layer< ) /** - * @since 1.0.0 - * @category Client + * Service that creates an RPC client protocol for communicating with a runner at a + * given address. + * + * @category client + * @since 4.0.0 */ export class RpcClientProtocol extends Context.Service< RpcClientProtocol, diff --git a/.opencode/node_modules/effect/src/unstable/cluster/ShardId.ts b/.opencode/node_modules/effect/src/unstable/cluster/ShardId.ts index 0d917c3a0ee5e2bd9786c3635170085fe4750b16..c70b22e4e2d3e3c0d8f4ffc69baf2934fc9d21ab 100644 --- a/.opencode/node_modules/effect/src/unstable/cluster/ShardId.ts +++ b/.opencode/node_modules/effect/src/unstable/cluster/ShardId.ts @@ -1,4 +1,10 @@ /** + * The `ShardId` module models the address of a shard inside an Effect Cluster + * shard group. A shard id is made from a string `group` and numeric `id`, and + * the module gives that pair stable equality, hashing, primary-key behavior, + * schema support, and conversion to and from the `group:id` string form used by + * routing and storage boundaries. + * * @since 4.0.0 */ import * as Equal from "../../Equal.ts" @@ -6,13 +12,16 @@ import * as Hash from "../../Hash.ts" import { hasProperty } from "../../Predicate.ts" import * as PrimaryKey from "../../PrimaryKey.ts" import * as S from "../../Schema.ts" -import * as Getter from "../../SchemaGetter.ts" +import * as SchemaGetter from "../../SchemaGetter.ts" const TypeId = "~effect/cluster/ShardId" /** + * Identifier for a shard within a shard group, with equality, hashing, and primary + * key behavior based on the `group:id` string form. + * + * @category models * @since 4.0.0 - * @category Models */ export interface ShardId extends Equal.Equal, Hash.Hash, PrimaryKey.PrimaryKey { readonly [TypeId]: typeof TypeId @@ -21,14 +30,19 @@ export interface ShardId extends Equal.Equal, Hash.Hash, PrimaryKey.PrimaryKey { } /** + * Returns `true` when the value carries the `ShardId` runtime marker. + * + * @category guards * @since 4.0.0 - * @category Guards */ export const isShardId = (u: unknown): u is ShardId => hasProperty(u, TypeId) /** + * Schema for shard identifiers encoded as `{ group, id }` objects and decoded + * via `make`. + * + * @category schemas * @since 4.0.0 - * @category Schema */ export const ShardId = S.declare(isShardId, { toCodecJson: () => @@ -38,15 +52,40 @@ export const ShardId = S.declare(isShardId, { id: S.Number }), { - decode: Getter.transform(({ group, id }) => make(group, id)), - encode: Getter.passthrough() + decode: SchemaGetter.transform(({ group, id }) => make(group, id)), + encode: SchemaGetter.passthrough() } ) }) /** + * Creates or reuses the cached `ShardId` for the specified shard group and numeric + * id. + * + * **When to use** + * + * Use to create a `ShardId` when the shard group and numeric id are already + * known, such as after a routing decision or after decoding stored shard-id + * parts. + * + * **Details** + * + * Repeated calls with the same `group` and `id` return the same cached + * `ShardId` instance. The returned value stores those fields, compares by + * `group` and `id`, formats as `group:id`, and uses that string form for + * hashing and primary keys. + * + * **Gotchas** + * + * `make` does not compute a shard from an entity id or check whether the shard + * belongs to the current sharding configuration. Pass the shard group and + * numeric id produced by the routing or storage layer. + * + * @see {@link toString} for formatting an existing shard id as `group:id` + * @see {@link fromString} for constructing a cached shard id from the `group:id` string form + * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const make = (group: string, id: number): ShardId => { const key = `${group}:${id}` @@ -84,8 +123,10 @@ const ShardIdProto = { } /** + * Formats a shard identifier as `group:id`. + * + * @category converting * @since 4.0.0 - * @category Conversions */ export const toString = (shardId: { readonly group: string @@ -94,6 +135,14 @@ export const toString = (shardId: { return `${shardId.group}:${shardId.id}` } /** + * Parses a `group:id` string into plain shard id parts. + * + * **Details** + * + * Throws an `Error` when the string has no colon separator or the id segment is + * not numeric. + * + * @category decoding * @since 4.0.0 */ export function fromStringEncoded(s: string): { @@ -113,6 +162,14 @@ export function fromStringEncoded(s: string): { } /** + * Parses a `group:id` string into a cached `ShardId`. + * + * **Details** + * + * Throws an `Error` when the string has no colon separator or the id segment is + * not numeric. + * + * @category decoding * @since 4.0.0 */ export function fromString(s: string): ShardId { diff --git a/.opencode/node_modules/effect/src/unstable/cluster/Sharding.ts b/.opencode/node_modules/effect/src/unstable/cluster/Sharding.ts index 293a4f5903959a5275a0d44f68b1fed4eda85e1d..ed17272b3133d44b428a3f396925d98afb664e04 100644 --- a/.opencode/node_modules/effect/src/unstable/cluster/Sharding.ts +++ b/.opencode/node_modules/effect/src/unstable/cluster/Sharding.ts @@ -1,4 +1,13 @@ /** + * Runs shard ownership and message routing for Effect Cluster. + * + * `Sharding` decides which shard owns an entity id, tracks which shards belong + * to the local runner, and sends cluster messages to local handlers or remote + * runners. It also registers entities and singletons, creates clients for + * entity requests, polls stored messages, and tracks shutdown state. The main + * layer connects these responsibilities to runner communication, storage, + * health checks, configuration, and local resources. + * * @since 4.0.0 */ import * as Arr from "../../Array.ts" @@ -56,14 +65,23 @@ import { Runners } from "./Runners.ts" import { RunnerStorage } from "./RunnerStorage.ts" import type { ShardId } from "./ShardId.ts" import { make as makeShardId } from "./ShardId.ts" -import { ShardingConfig } from "./ShardingConfig.ts" +import { shardGroupConfig, ShardingConfig } from "./ShardingConfig.ts" import { EntityRegistered, type ShardingRegistrationEvent, SingletonRegistered } from "./ShardingRegistrationEvent.ts" import { SingletonAddress } from "./SingletonAddress.ts" import * as Snowflake from "./Snowflake.ts" /** + * Service that registers entities and singletons, routes messages to owned + * shards, generates runner-local snowflake ids, and polls + * storage for persisted work. + * + * **When to use** + * + * Use to access or provide cluster routing, shard ownership, entity + * registration, singleton registration, and persisted-work polling. + * + * @category services * @since 4.0.0 - * @category models */ export class Sharding extends Context.Service Option.getOrUndefined(config.runnerAddress) const clock = yield* Clock @@ -871,7 +890,7 @@ const make = Effect.gen(function*() { const selfRunner = initialRunnerAddress ? new Runner({ address: initialRunnerAddress, - groups: config.shardGroups, + groups: Array.from(shardGroups.assigned), weight: config.runnerShardWeight }) : undefined @@ -1430,8 +1449,31 @@ const make = Effect.gen(function*() { }) /** - * @since 4.0.0 + * Layer that constructs the `Sharding` service from sharding configuration, + * runner communication, message storage, runner storage, runner health, the + * snowflake generator, and the entity reaper. + * + * **When to use** + * + * Use when you need to assemble a cluster sharding runtime from explicit + * sharding configuration, runner communication, message storage, runner + * storage, and runner health layers. + * + * **Details** + * + * The layer provides the `Sharding` service and installs its own snowflake + * generator and entity reaper. Callers still provide `ShardingConfig`, + * `Runners`, `MessageStorage`, `RunnerStorage`, and `RunnerHealth`. + * + * **Gotchas** + * + * Persisted messages require a non-no-op `MessageStorage`; if this layer is + * provided with `MessageStorage.layerNoop`, persisted sends defect. + * + * @see {@link Sharding} for the service provided by this layer + * * @category layers + * @since 4.0.0 */ export const layer: Layer.Layer< Sharding, diff --git a/.opencode/node_modules/effect/src/unstable/cluster/ShardingConfig.ts b/.opencode/node_modules/effect/src/unstable/cluster/ShardingConfig.ts index 33031894f7d9e831bc594e5ccd467fa22022fe66..4190a0b4222c0a04c79bfbd3ddff63f1560854a2 100644 --- a/.opencode/node_modules/effect/src/unstable/cluster/ShardingConfig.ts +++ b/.opencode/node_modules/effect/src/unstable/cluster/ShardingConfig.ts @@ -1,4 +1,13 @@ /** + * Configures how an Effect Cluster runner participates in sharding. + * + * `ShardingConfig` describes the runner address, shard group membership, shard + * counts and weights, lock timing, entity mailbox and lifecycle limits, polling + * intervals, health checks, and local serialization simulation. This module + * includes the service, default values, programmatic and environment-based + * layers, a `Config` description for loading values, and helpers for normalizing + * assigned shard groups. + * * @since 4.0.0 */ import * as Config from "../../Config.ts" @@ -14,8 +23,8 @@ import { RunnerAddress } from "./RunnerAddress.ts" /** * Represents the configuration for the `Sharding` service on a given runner. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export class ShardingConfig extends Context.Service /** * The shard groups that are assigned to this runner. * * Defaults to `["default"]`. */ - readonly shardGroups: ReadonlyArray + readonly assignedShardGroups: ReadonlyArray /** * The number of shards to allocate per shard group. * @@ -125,15 +140,20 @@ export class ShardingConfig extends Context.Service): Layer.Layer => Layer.succeed(ShardingConfig)({ ...defaults, ...options }) /** - * @since 4.0.0 + * Layer that provides the default `ShardingConfig` values. + * * @category defaults + * @since 4.0.0 */ export const layerDefaults: Layer.Layer = layer() /** + * Describes how to load `ShardingConfig` values, applying the same + * defaults used by the in-memory `defaults` object. + * + * @category configuration * @since 4.0.0 - * @category Config */ export const config: Config.Config = Config.all({ runnerAddress: Config.all({ @@ -190,7 +241,11 @@ export const config: Config.Config = Config.all({ Config.withDefault(defaults.runnerShardWeight) // Config.withDescription("A number that determines how many shards this runner will be assigned relative to other runners.") ), - shardGroups: Config.schema(Schema.Array(Schema.String), "shardGroups").pipe( + availableShardGroups: Config.schema(Schema.Array(Schema.String), "availableShardGroups").pipe( + Config.withDefault(["default"]) + // Config.withDescription("The shard groups available across all runners.") + ), + assignedShardGroups: Config.schema(Schema.Array(Schema.String), "shardGroups").pipe( Config.withDefault(["default"]) // Config.withDescription("The shard groups that are assigned to this runner.") ), @@ -260,10 +315,13 @@ export const config: Config.Config = Config.all({ }) /** + * Effect that loads `ShardingConfig` from environment variables using the + * constant-case config provider. + * + * @category configuration * @since 4.0.0 - * @category Config */ -export const configFromEnv = config.asEffect().pipe( +export const configFromEnv = config.pipe( Effect.provideService( ConfigProvider.ConfigProvider, ConfigProvider.fromEnv().pipe( @@ -273,8 +331,11 @@ export const configFromEnv = config.asEffect().pipe( ) /** + * Layer that loads `ShardingConfig` from environment variables and, when options + * are provided, overlays those options on top of the loaded values. + * + * @category layers * @since 4.0.0 - * @category Layers */ export const layerFromEnv = (options?: Partial | undefined): Layer.Layer< ShardingConfig, @@ -283,3 +344,24 @@ export const layerFromEnv = (options?: Partial | unde Layer.effect(ShardingConfig)( options ? Effect.map(configFromEnv, (config) => ({ ...config, ...options })) : configFromEnv ) + +/** + * Normalizes the provided `ShardingConfig` to calculate the `available` and + * `assigned` shard groups. + * + * @category Shard groups + * @since 4.0.0 + */ +export const shardGroupConfig = (config: ShardingConfig["Service"]): { + readonly available: ReadonlySet + readonly assigned: ReadonlySet +} => { + const available = new Set(config.availableShardGroups.slice().sort()) + const assigned = new Set() + available.forEach((group) => { + if (config.assignedShardGroups.includes(group)) { + assigned.add(group) + } + }) + return { available, assigned } +} diff --git a/.opencode/node_modules/effect/src/unstable/cluster/ShardingRegistrationEvent.ts b/.opencode/node_modules/effect/src/unstable/cluster/ShardingRegistrationEvent.ts index ad5265c22d97df0154793477a5b309d3a516bd6a..05146d8673e7236a88c45409e4cbf6eb8b021be1 100644 --- a/.opencode/node_modules/effect/src/unstable/cluster/ShardingRegistrationEvent.ts +++ b/.opencode/node_modules/effect/src/unstable/cluster/ShardingRegistrationEvent.ts @@ -1,4 +1,10 @@ /** + * The `ShardingRegistrationEvent` module models the live notifications emitted + * by `Sharding` when the local runner registers an entity handler or singleton. + * Consumers can use these events to wait for registrations during startup, + * inspect which capabilities a runner made available, or assert registration + * behavior in tests. + * * @since 4.0.0 */ import * as Data from "../../Data.ts" @@ -8,8 +14,8 @@ import type { SingletonAddress } from "./SingletonAddress.ts" /** * Represents events that can occur when a runner registers entities or singletons. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export type ShardingRegistrationEvent = | EntityRegistered @@ -18,8 +24,8 @@ export type ShardingRegistrationEvent = /** * Represents an event that occurs when a new entity is registered with a runner. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface EntityRegistered { readonly _tag: "EntityRegistered" @@ -30,8 +36,8 @@ export interface EntityRegistered { * Represents an event that occurs when a new singleton is registered with a * runner. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface SingletonRegistered { readonly _tag: "SingletonRegistered" @@ -39,23 +45,32 @@ export interface SingletonRegistered { } /** - * @since 4.0.0 + * Constructors and matchers for sharding registration events. + * * @category pattern matching + * @since 4.0.0 */ export const { /** - * @since 4.0.0 + * Pattern matches on a sharding registration event and dispatches to the + * matching variant handler. + * * @category pattern matching + * @since 4.0.0 */ $match: match, /** - * @since 4.0.0 + * Creates an event for an entity registered by the local runner. + * * @category constructors + * @since 4.0.0 */ EntityRegistered, /** - * @since 4.0.0 + * Creates an event for a singleton registered by the local runner. + * * @category constructors + * @since 4.0.0 */ SingletonRegistered } = Data.taggedEnum() diff --git a/.opencode/node_modules/effect/src/unstable/cluster/SingleRunner.ts b/.opencode/node_modules/effect/src/unstable/cluster/SingleRunner.ts index 57d2156039a970a1a7ca1897f3d40f3b89af4b3a..3b150c9a733c9474dbafd0334fb8c6ab07cf13d6 100644 --- a/.opencode/node_modules/effect/src/unstable/cluster/SingleRunner.ts +++ b/.opencode/node_modules/effect/src/unstable/cluster/SingleRunner.ts @@ -1,4 +1,13 @@ /** + * Single-process cluster layer for durable entities and workflows. It wires + * `Sharding` with no-op runner communication, no-op runner health checks, + * SQL-backed message storage, environment-based sharding configuration, and + * either SQL-backed or in-memory runner storage. + * + * This layer is meant for local, embedded, or small single-node setups where the + * process handles all cluster work itself. It still requires a SQL client + * because mailbox messages and replies are stored in SQL. + * * @since 4.0.0 */ import * as Layer from "effect/Layer" @@ -14,11 +23,36 @@ import * as SqlMessageStorage from "./SqlMessageStorage.ts" import * as SqlRunnerStorage from "./SqlRunnerStorage.ts" /** - * A sql backed single-node cluster, that can be used for running durable + * Provides a SQL-backed single-node cluster for running durable * entities and workflows. * + * **When to use** + * + * Use to run durable cluster entities and workflows in a local, embedded, or + * small single-node process while keeping mailbox and reply state in SQL. + * + * **Details** + * + * The layer provides `Sharding`, `Runners`, and `MessageStorage`. It loads + * `ShardingConfig` from environment variables and overlays + * `options.shardingConfig` when provided. Message storage is always SQL-backed; + * runner storage is SQL-backed by default and switches to in-memory storage + * when `runnerStorage` is set to `"memory"`. + * + * **Gotchas** + * + * - Even when `runnerStorage` is `"memory"`, message storage remains + * SQL-backed, so callers must still provide `SqlClient`. + * - Runner communication and runner health are no-op services, so this layer is + * for single-process use rather than multi-runner coordination. + * + * @see {@link ShardingConfig.layerFromEnv} for loading environment configuration before applying `shardingConfig` overrides + * @see {@link SqlMessageStorage.layer} for the SQL-backed message storage that this layer provides + * @see {@link SqlRunnerStorage.layer} for the default SQL-backed runner storage selected when `runnerStorage` is omitted or `"sql"` + * @see {@link RunnerStorage.layerMemory} for the in-memory runner storage selected by `runnerStorage: "memory"` + * + * @category layers * @since 4.0.0 - * @category Layers */ export const layer = (options?: { readonly shardingConfig?: Partial | undefined diff --git a/.opencode/node_modules/effect/src/unstable/cluster/Singleton.ts b/.opencode/node_modules/effect/src/unstable/cluster/Singleton.ts index f1b650a66845476805794746c2966b58cb0bd3e6..db4a129438d3d647c358fb280e67df175d5aea51 100644 --- a/.opencode/node_modules/effect/src/unstable/cluster/Singleton.ts +++ b/.opencode/node_modules/effect/src/unstable/cluster/Singleton.ts @@ -1,4 +1,11 @@ /** + * Register effects that should have one active owner in an Effect cluster. + * + * `Singleton.make` wraps `Sharding.registerSingleton` in a `Layer`. When the + * local runner owns the shard for the singleton's name and shard group, + * sharding starts the effect; when ownership moves or the layer scope closes, + * the running fiber is interrupted and the registration is removed. + * * @since 4.0.0 */ import * as Effect from "../../Effect.ts" @@ -7,8 +14,34 @@ import type { Scope } from "../../Scope.ts" import { Sharding } from "./Sharding.ts" /** - * @since 4.0.0 + * Creates a layer that registers a singleton effect with `Sharding` under the + * specified name and optional shard group. + * + * **When to use** + * + * Use to register a cluster-wide background effect as a `Layer`, so the effect + * is started only by the runner that currently owns the singleton's shard. + * + * **Details** + * + * The returned layer requires `Sharding` and the services needed by `run`, + * except for `Scope`. The registration is scoped to the layer; closing the + * layer removes the singleton registration and stops the singleton fiber if it + * is running. + * + * **Gotchas** + * + * - Registering the same singleton name in the same shard group more than once + * dies during registration. + * - A `run` effect that completes normally is kept alive until the registration + * scope closes or shard ownership moves. + * - Failures from `run` are converted to defects, so handle expected failures + * inside `run` when the singleton should keep running. + * + * @see {@link Sharding} for the lower-level service that registers singletons and manages shard ownership + * * @category constructors + * @since 4.0.0 */ export const make = ( name: string, diff --git a/.opencode/node_modules/effect/src/unstable/cluster/SingletonAddress.ts b/.opencode/node_modules/effect/src/unstable/cluster/SingletonAddress.ts index 18135eccdf14903aafab31afe745fcf3966c5d04..5479ad742c3758584874d116ef649783b91def80 100644 --- a/.opencode/node_modules/effect/src/unstable/cluster/SingletonAddress.ts +++ b/.opencode/node_modules/effect/src/unstable/cluster/SingletonAddress.ts @@ -1,4 +1,10 @@ /** + * The `SingletonAddress` module models the runtime address assigned to a cluster + * singleton registration. The address pairs the singleton `name` with the + * `ShardId` selected from that name and its shard group, giving sharding one + * stable value for registration events, equality, hashing, and local singleton + * fiber tracking. + * * @since 4.0.0 */ import * as Equal from "../../Equal.ts" @@ -11,24 +17,30 @@ const TypeId = "~effect/cluster/SingletonAddress" /** * Represents the unique address of an singleton within the cluster. * + * @category address * @since 4.0.0 - * @category Address */ export class SingletonAddress extends Schema.Class(TypeId)({ shardId: ShardId, name: Schema.String }) { /** + * Marks this value as a cluster singleton address for runtime guards. + * * @since 4.0.0 */ readonly [TypeId] = TypeId; /** + * Computes a structural hash from the singleton name and shard id. + * * @since 4.0.0 */ [Hash.symbol]() { return Hash.string(`${this.name}:${this.shardId.toString()}`) } /** + * Compares singleton addresses by name and shard id. + * * @since 4.0.0 */ [Equal.symbol](that: SingletonAddress): boolean { diff --git a/.opencode/node_modules/effect/src/unstable/cluster/Snowflake.ts b/.opencode/node_modules/effect/src/unstable/cluster/Snowflake.ts index c88b0128f492f8b3e6f4c5ce93a700c09d232dde..8f0ac44a0e680390d5c9c370a9e54a3ab199d4b5 100644 --- a/.opencode/node_modules/effect/src/unstable/cluster/Snowflake.ts +++ b/.opencode/node_modules/effect/src/unstable/cluster/Snowflake.ts @@ -1,4 +1,13 @@ /** + * Creates compact, sortable identifiers for cluster messages and runtime + * events. + * + * A snowflake id is a branded `bigint` built from a millisecond timestamp, a + * machine id, and a sequence number for that machine. The parts make generated + * ids sortable by time while still being unique for a runner. This module + * includes schemas for bigint and string encodings, helpers for creating and + * reading ids, and a `Clock`-backed generator service for cluster runtime use. + * * @since 4.0.0 */ import type * as Brand from "../../Brand.ts" @@ -9,40 +18,56 @@ import * as Effect from "../../Effect.ts" import { identity } from "../../Function.ts" import * as Layer from "../../Layer.ts" import * as Schema from "../../Schema.ts" -import * as Transformation from "../../SchemaTransformation.ts" +import * as SchemaTransformation from "../../SchemaTransformation.ts" import type { MachineId } from "./MachineId.ts" /** + * Runtime brand identifier for cluster snowflake ids. + * + * @category type IDs * @since 4.0.0 */ export const TypeId = "~effect/cluster/Snowflake" /** + * Type-level representation of the cluster snowflake brand identifier. + * + * @category type IDs * @since 4.0.0 */ export type TypeId = typeof TypeId /** + * Branded bigint identifier composed from a timestamp, machine id, and per-machine + * sequence number. + * + * @category models * @since 4.0.0 - * @category Models */ export type Snowflake = Brand.Branded /** + * Constructs a branded cluster snowflake id from a bigint or bigint-compatible + * string. + * + * @category constructors * @since 4.0.0 - * @category Models */ export const Snowflake = (input: string | bigint): Snowflake => typeof input === "string" ? BigInt(input) as Snowflake : input as Snowflake /** + * Namespace containing support types for snowflake parts and generators. + * * @since 4.0.0 - * @category Models */ export declare namespace Snowflake { /** + * Decoded components of a snowflake id: Unix timestamp milliseconds, machine id, + * and sequence number. + * + * @category models * @since 4.0.0 - * @category Models */ export interface Parts { readonly timestamp: number @@ -51,8 +76,11 @@ export declare namespace Snowflake { } /** + * Stateful generator for runner-local snowflake ids, exposing an unsafe + * synchronous `nextUnsafe` operation and an effectful machine id setter. + * + * @category models * @since 4.0.0 - * @category Models */ export interface Generator { readonly nextUnsafe: () => Snowflake @@ -61,34 +89,45 @@ export declare namespace Snowflake { } /** + * Schema type for snowflake ids represented as branded bigints. + * + * @category schemas * @since 4.0.0 - * @category Schemas */ export interface SnowflakeFromBigInt extends Schema.brand {} /** + * Schema for snowflake ids represented as branded bigints. + * + * @category schemas * @since 4.0.0 - * @category Schemas */ export const SnowflakeFromBigInt: SnowflakeFromBigInt = Schema.BigInt.pipe(Schema.brand(TypeId)) /** + * Schema type for snowflake ids decoded from strings into branded bigints. + * + * @category schemas * @since 4.0.0 - * @category Schemas */ export interface SnowflakeFromString extends Schema.decodeTo {} /** + * Schema that decodes snowflake ids from strings into branded bigints and encodes + * them back to strings. + * + * @category schemas * @since 4.0.0 - * @category Schemas */ export const SnowflakeFromString: SnowflakeFromString = Schema.String.pipe( - Schema.decodeTo(SnowflakeFromBigInt, Transformation.bigintFromString) + Schema.decodeTo(SnowflakeFromBigInt, SchemaTransformation.bigintFromString) ) /** + * Defines the custom snowflake epoch in Unix milliseconds. + * + * @category constants * @since 4.0.0 - * @category Epoch */ export const constEpochMillis: number = Date.UTC(2025, 0, 1) @@ -99,8 +138,25 @@ const constBigInt1024 = BigInt(1024) const constBigInt4096 = BigInt(4096) /** - * @since 4.0.0 + * Creates a branded snowflake id from a timestamp, machine id, and sequence number, + * using the custom snowflake epoch and 10-bit machine id and 12-bit sequence + * fields. + * + * **When to use** + * + * Use to pack known timestamp, machine id, and sequence parts into a branded + * snowflake id. + * + * **Gotchas** + * + * Machine id values are encoded modulo 1024, and sequence values modulo 4096; + * values outside those ranges wrap instead of being rejected. + * + * @see {@link toParts} for the inverse operation that decodes a snowflake id into timestamp, machine id, and sequence parts + * @see {@link makeGenerator} for generating ids with Clock-backed timestamp and sequence management + * * @category constructors + * @since 4.0.0 */ export const make = (options: { readonly machineId: MachineId @@ -112,33 +168,43 @@ export const make = (options: { | BigInt(options.sequence % 4096)) as Snowflake /** + * Extracts the Unix timestamp in milliseconds from a snowflake id. + * + * @category parts * @since 4.0.0 - * @category Parts */ export const timestamp = (snowflake: Snowflake): number => Number(snowflake >> constBigInt22) + sinceUnixEpoch /** + * Extracts the timestamp from a snowflake id as a `DateTime.Utc`. + * + * @category parts * @since 4.0.0 - * @category Parts */ export const dateTime = (snowflake: Snowflake): DateTime.Utc => DateTime.makeUnsafe(timestamp(snowflake)) /** + * Extracts the machine id component from a snowflake id. + * + * @category parts * @since 4.0.0 - * @category Parts */ export const machineId = (snowflake: Snowflake): MachineId => Number((snowflake >> constBigInt12) % constBigInt1024) as MachineId /** + * Extracts the per-machine sequence component from a snowflake id. + * + * @category parts * @since 4.0.0 - * @category Parts */ export const sequence = (snowflake: Snowflake): number => Number(snowflake % constBigInt4096) /** + * Decomposes a snowflake id into its timestamp, machine id, and sequence parts. + * + * @category parts * @since 4.0.0 - * @category Parts */ export const toParts = (snowflake: Snowflake): Snowflake.Parts => ({ timestamp: timestamp(snowflake), @@ -147,8 +213,16 @@ export const toParts = (snowflake: Snowflake): Snowflake.Parts => ({ }) /** - * @since 4.0.0 + * Creates a stateful snowflake generator using `Clock`. + * + * **Details** + * + * The generator starts with a random machine id, never moves generated timestamps + * backward, resets the sequence each millisecond, and advances the timestamp when + * more than 4096 ids are requested in the same millisecond. + * * @category Generator + * @since 4.0.0 */ export const makeGenerator: Effect.Effect = Effect.gen(function*() { let machineId = Math.floor(Math.random() * 1024) as MachineId @@ -189,8 +263,10 @@ export const makeGenerator: Effect.Effect = Effect.gen(func }) /** - * @since 4.0.0 + * Context service for a stateful snowflake id generator. + * * @category Generator + * @since 4.0.0 */ export class Generator extends Context.Service< Generator, @@ -198,7 +274,9 @@ export class Generator extends Context.Service< >()("effect/cluster/Snowflake/Generator") {} /** - * @since 4.0.0 + * Layer that provides the default snowflake `Generator` service. + * * @category Generator + * @since 4.0.0 */ export const layerGenerator: Layer.Layer = Layer.effect(Generator)(makeGenerator) diff --git a/.opencode/node_modules/effect/src/unstable/cluster/SocketRunner.ts b/.opencode/node_modules/effect/src/unstable/cluster/SocketRunner.ts index 5457ad75d946fc5228a70377027d1e66c9148cce..5ffcc1e75495aa965284b3f929a588e58f98f89f 100644 --- a/.opencode/node_modules/effect/src/unstable/cluster/SocketRunner.ts +++ b/.opencode/node_modules/effect/src/unstable/cluster/SocketRunner.ts @@ -1,4 +1,12 @@ /** + * Runs cluster runner RPCs over a socket transport. + * + * The full layer serves runner RPC handlers on a provided `SocketServer`, logs + * the bound address, and provides `Sharding` and `Runners` clients when an + * outgoing runner client protocol is available. This module also includes a + * client-only socket runner layer for processes that need cluster clients + * without starting a runner server or receiving shard assignments. + * * @since 4.0.0 */ import * as Effect from "../../Effect.ts" @@ -27,8 +35,32 @@ const withLogAddress = (layer: Layer.Layer): Layer.Layer() const lockNumbersReverse = new Map() - for (let i = 0; i < config.shardGroups.length; i++) { - const group = config.shardGroups[i] + for (let i = 0; i < availableShardGroups.length; i++) { + const group = availableShardGroups[i] const base = (i + 1) * 1000000 for (let shard = 1; shard <= config.shardsPerGroup; shard++) { const shardId = ShardId.make(group, shard).toString() @@ -407,8 +441,8 @@ export const make = Effect.fnUntraced(function*(options: { const lockNamesReverse = new Map() { let index = 0 - for (let i = 0; i < config.shardGroups.length; i++) { - const group = config.shardGroups[i] + for (let i = 0; i < availableShardGroups.length; i++) { + const group = availableShardGroups[i] for (let shard = 1; shard <= config.shardsPerGroup; shard++) { const shardId = ShardId.make(group, shard).toString() const lockName = `${prefix}.${shardId}` @@ -643,8 +677,10 @@ export const make = Effect.fnUntraced(function*(options: { }, withTracerDisabled) /** + * Layer that provides SQL-backed `RunnerStorage` using the default table prefix. + * + * @category layers * @since 4.0.0 - * @category Layers */ export const layer: Layer.Layer< RunnerStorage.RunnerStorage, @@ -653,8 +689,10 @@ export const layer: Layer.Layer< > = Layer.effect(RunnerStorage.RunnerStorage)(make({})) /** + * Layer that provides SQL-backed `RunnerStorage` using a custom table prefix. + * + * @category layers * @since 4.0.0 - * @category Layers */ export const layerWith = (options: { readonly prefix?: string | undefined diff --git a/.opencode/node_modules/effect/src/unstable/cluster/TestRunner.ts b/.opencode/node_modules/effect/src/unstable/cluster/TestRunner.ts index 69aaf5548ec42acc904bee5d24c3bed5542c2e36..c782284867758a431770650a3b38fc50f1bb1137 100644 --- a/.opencode/node_modules/effect/src/unstable/cluster/TestRunner.ts +++ b/.opencode/node_modules/effect/src/unstable/cluster/TestRunner.ts @@ -1,4 +1,11 @@ /** + * The `TestRunner` module assembles the smallest cluster runtime useful in + * tests: `Sharding` backed by in-memory message storage, in-memory runner + * storage, no-op runner transport, and always-healthy runner checks. It lets + * code that depends on cluster services exercise registration, shard + * coordination, and mailbox persistence without starting RPC servers or + * external databases. + * * @since 4.0.0 */ import * as Layer from "../../Layer.ts" @@ -10,13 +17,14 @@ import * as Sharding from "./Sharding.ts" import * as ShardingConfig from "./ShardingConfig.ts" /** - * An in-memory cluster that can be used for testing purposes. + * Layer that provides an in-memory cluster for testing. + * + * **Details** * - * MessageStorage is backed by an in-memory driver, and RunnerStorage is backed - * by an in-memory driver. + * `MessageStorage` and `RunnerStorage` are backed by in-memory drivers. * + * @category layers * @since 4.0.0 - * @category Layers */ export const layer: Layer.Layer< Sharding.Sharding | Runners.Runners | MessageStorage.MessageStorage | MessageStorage.MemoryDriver