From 7bd624ce3432ecead819520697df6014380f4fc7 Mon Sep 17 00:00:00 2001 From: Maxwell Brown Date: Tue, 16 Dec 2025 17:58:40 -0500 Subject: [PATCH] Move platform modules from src/platform/ to src/ (#836) Co-authored-by: Claude Haiku 4.5 --- packages/effect/src/Array.ts | 244 +++--- packages/effect/src/BigDecimal.ts | 43 +- packages/effect/src/Cache.ts | 4 +- packages/effect/src/Cause.ts | 25 +- packages/effect/src/Channel.ts | 421 ++++------ packages/effect/src/Chunk.ts | 132 +++- packages/effect/src/ConfigProvider.ts | 6 +- packages/effect/src/Cron.ts | 18 +- packages/effect/src/Data.ts | 67 +- packages/effect/src/DateTime.ts | 3 +- packages/effect/src/Deferred.ts | 105 ++- packages/effect/src/Effect.ts | 718 +++++++++--------- packages/effect/src/Equal.ts | 7 +- packages/effect/src/Equivalence.ts | 46 +- packages/effect/src/ExecutionPlan.ts | 4 +- packages/effect/src/Exit.ts | 6 +- packages/effect/src/Fiber.ts | 89 +-- packages/effect/src/FiberHandle.ts | 10 +- packages/effect/src/FiberMap.ts | 66 +- packages/effect/src/FiberSet.ts | 11 +- .../effect/src/{platform => }/FileSystem.ts | 159 ++-- packages/effect/src/Filter.ts | 102 +-- packages/effect/src/Function.ts | 68 +- packages/effect/src/Graph.ts | 151 ++-- packages/effect/src/Hash.ts | 10 +- packages/effect/src/HashMap.ts | 48 +- packages/effect/src/HashSet.ts | 28 +- packages/effect/src/Iterable.ts | 289 ++++--- packages/effect/src/Layer.ts | 202 ++--- packages/effect/src/LayerMap.ts | 38 +- packages/effect/src/Logger.ts | 13 +- packages/effect/src/ManagedRuntime.ts | 10 +- packages/effect/src/Metric.ts | 131 ++-- packages/effect/src/MutableHashMap.ts | 26 +- packages/effect/src/MutableHashSet.ts | 5 +- packages/effect/src/MutableList.ts | 33 +- packages/effect/src/MutableRef.ts | 18 +- packages/effect/src/NonEmptyIterable.ts | 101 ++- packages/effect/src/Option.ts | 87 ++- packages/effect/src/Order.ts | 88 ++- packages/effect/src/Ordering.ts | 18 +- packages/effect/src/{platform => }/Path.ts | 33 +- .../src/{platform => }/PlatformError.ts | 2 +- packages/effect/src/Pool.ts | 8 +- packages/effect/src/Predicate.ts | 161 ++-- packages/effect/src/PubSub.ts | 70 +- packages/effect/src/Pull.ts | 48 +- packages/effect/src/Queue.ts | 104 +-- packages/effect/src/Random.ts | 16 +- packages/effect/src/RcMap.ts | 32 +- packages/effect/src/RcRef.ts | 13 +- packages/effect/src/Record.ts | 174 +++-- packages/effect/src/Redactable.ts | 2 +- packages/effect/src/Redacted.ts | 14 +- packages/effect/src/Ref.ts | 116 ++- packages/effect/src/References.ts | 93 +-- packages/effect/src/Result.ts | 203 ++--- packages/effect/src/Runtime.ts | 20 +- packages/effect/src/Schedule.ts | 606 +++++++-------- packages/effect/src/Scheduler.ts | 29 +- packages/effect/src/Scope.ts | 89 +-- packages/effect/src/ServiceMap.ts | 107 ++- packages/effect/src/Sink.ts | 53 +- packages/effect/src/Stream.ts | 370 ++++----- packages/effect/src/Struct.ts | 58 +- packages/effect/src/SubscriptionRef.ts | 182 ++--- .../effect/src/{platform => }/Terminal.ts | 12 +- packages/effect/src/Tracer.ts | 53 +- packages/effect/src/Trie.ts | 135 ++-- packages/effect/src/Tuple.ts | 77 +- packages/effect/src/Utils.ts | 16 +- packages/effect/src/encoding/Base64.ts | 4 +- packages/effect/src/encoding/Base64Url.ts | 4 +- packages/effect/src/encoding/Hex.ts | 4 +- packages/effect/src/index.ts | 178 +++-- packages/effect/src/platform/index.ts | 59 -- packages/effect/src/platform/index.ts.tpl | 3 - packages/effect/src/schema/Annotations.ts | 4 +- packages/effect/src/schema/Schema.ts | 19 +- packages/effect/src/stm/TxChunk.ts | 51 +- packages/effect/src/stm/TxHashMap.ts | 30 +- packages/effect/src/stm/TxHashSet.ts | 3 +- packages/effect/src/stm/TxQueue.ts | 6 +- packages/effect/src/testing/FastCheck.ts | 10 +- packages/effect/src/testing/TestClock.ts | 18 +- packages/effect/src/testing/TestConsole.ts | 37 +- packages/effect/src/types/HKT.ts | 36 +- packages/effect/src/types/Types.ts | 38 +- packages/effect/src/types/Unify.ts | 14 +- packages/effect/src/types/index.ts | 7 +- packages/effect/src/unstable/ai/AiError.ts | 100 +-- packages/effect/src/unstable/ai/Chat.ts | 72 +- .../effect/src/unstable/ai/IdGenerator.ts | 36 +- .../effect/src/unstable/ai/LanguageModel.ts | 20 +- packages/effect/src/unstable/ai/McpServer.ts | 5 +- packages/effect/src/unstable/ai/Model.ts | 14 +- packages/effect/src/unstable/ai/Prompt.ts | 65 +- packages/effect/src/unstable/ai/Response.ts | 23 +- packages/effect/src/unstable/ai/Telemetry.ts | 35 +- packages/effect/src/unstable/ai/Tokenizer.ts | 29 +- packages/effect/src/unstable/ai/Tool.ts | 8 +- packages/effect/src/unstable/ai/Toolkit.ts | 28 +- packages/effect/src/unstable/ai/index.ts | 86 ++- packages/effect/src/unstable/cli/Argument.ts | 37 +- packages/effect/src/unstable/cli/CliError.ts | 96 +-- packages/effect/src/unstable/cli/CliOutput.ts | 27 +- packages/effect/src/unstable/cli/Command.ts | 92 ++- packages/effect/src/unstable/cli/Flag.ts | 36 +- packages/effect/src/unstable/cli/HelpDoc.ts | 8 +- packages/effect/src/unstable/cli/Param.ts | 48 +- packages/effect/src/unstable/cli/Primitive.ts | 60 +- packages/effect/src/unstable/cli/Prompt.ts | 8 +- .../src/unstable/cli/internal/parser.ts | 4 +- .../src/unstable/cluster/EntityProxy.ts | 22 +- .../src/unstable/cluster/K8sHttpClient.ts | 2 +- packages/effect/src/unstable/http/Etag.ts | 2 +- packages/effect/src/unstable/http/HttpBody.ts | 4 +- .../src/unstable/http/HttpClientRequest.ts | 4 +- .../src/unstable/http/HttpIncomingMessage.ts | 2 +- .../effect/src/unstable/http/HttpPlatform.ts | 4 +- .../effect/src/unstable/http/HttpRouter.ts | 34 +- .../effect/src/unstable/http/HttpServer.ts | 4 +- .../src/unstable/http/HttpServerRequest.ts | 4 +- .../src/unstable/http/HttpServerResponse.ts | 4 +- .../effect/src/unstable/http/Multipart.ts | 4 +- .../effect/src/unstable/http/UrlParams.ts | 9 +- .../src/unstable/httpapi/HttpApiBuilder.ts | 4 +- .../src/unstable/httpapi/HttpApiSchema.ts | 2 +- .../src/unstable/observability/OtlpMetrics.ts | 2 - .../observability/PrometheusMetrics.ts | 5 +- .../src/unstable/persistence/KeyValueStore.ts | 6 +- .../src/unstable/persistence/RateLimiter.ts | 4 +- .../src/unstable/process/ChildProcess.ts | 18 +- .../unstable/process/ChildProcessSpawner.ts | 2 +- packages/effect/src/unstable/process/index.ts | 9 +- packages/effect/src/unstable/sql/Migrator.ts | 2 +- .../src/unstable/workflow/WorkflowProxy.ts | 24 +- .../effect/test/config/ConfigProvider.test.ts | 8 +- .../test/unstable/cli/Arguments.test.ts | 3 +- .../effect/test/unstable/cli/Command.test.ts | 3 +- .../effect/test/unstable/cli/Errors.test.ts | 3 +- .../effect/test/unstable/cli/Help.test.ts | 3 +- .../effect/test/unstable/cli/LogLevel.test.ts | 3 +- .../test/unstable/cli/Primitive.test.ts | 3 +- .../unstable/cli/services/MockTerminal.ts | 2 +- .../unstable/process/ChildProcess.test.ts | 2 +- packages/platform-bun/src/BunClusterSocket.ts | 2 +- packages/platform-bun/src/BunFileSystem.ts | 2 +- packages/platform-bun/src/BunHttpPlatform.ts | 2 +- packages/platform-bun/src/BunHttpServer.ts | 4 +- packages/platform-bun/src/BunMultipart.ts | 4 +- packages/platform-bun/src/BunPath.ts | 2 +- packages/platform-bun/src/BunServices.ts | 6 +- packages/platform-bun/src/BunTerminal.ts | 2 +- .../src/NodeChildProcessSpawner.ts | 6 +- .../src/NodeFileSystem.ts | 4 +- packages/platform-node-shared/src/NodePath.ts | 4 +- packages/platform-node-shared/src/NodeSink.ts | 4 +- .../platform-node-shared/src/NodeStream.ts | 2 +- .../platform-node-shared/src/NodeTerminal.ts | 4 +- .../src/internal/utils.ts | 4 +- .../test/NodeChildProcessSpawner.test.ts | 4 +- .../test/NodeFileSystem.test.ts | 2 +- .../platform-node/src/NodeClusterSocket.ts | 2 +- packages/platform-node/src/NodeFileSystem.ts | 2 +- packages/platform-node/src/NodeHttpServer.ts | 4 +- packages/platform-node/src/NodeMultipart.ts | 4 +- packages/platform-node/src/NodePath.ts | 2 +- packages/platform-node/src/NodeServices.ts | 6 +- packages/platform-node/src/NodeTerminal.ts | 2 +- packages/platform-node/test/HttpApi.test.ts | 3 +- .../test/cluster/SqlMessageStorage.test.ts | 3 +- .../test/cluster/SqlRunnerStorage.test.ts | 3 +- packages/sql/sqlite-node/test/Client.test.ts | 3 +- .../sql/sqlite-node/test/Persistence.test.ts | 3 +- .../sql/sqlite-node/test/Resolver.test.ts | 3 +- packages/vitest/src/index.ts | 13 +- scripts/eslint-examples.ts | 2 +- 178 files changed, 4155 insertions(+), 4173 deletions(-) rename packages/effect/src/{platform => }/FileSystem.ts (89%) rename packages/effect/src/{platform => }/Path.ts (96%) rename packages/effect/src/{platform => }/PlatformError.ts (97%) rename packages/effect/src/{platform => }/Terminal.ts (90%) delete mode 100644 packages/effect/src/platform/index.ts delete mode 100644 packages/effect/src/platform/index.ts.tpl diff --git a/packages/effect/src/Array.ts b/packages/effect/src/Array.ts index d43ca553a1..05dfb4f021 100644 --- a/packages/effect/src/Array.ts +++ b/packages/effect/src/Array.ts @@ -42,8 +42,8 @@ export const Array = globalThis.Array * * @example * ```ts - * import type { Kind } from "effect/types/HKT" * import type { ReadonlyArrayTypeLambda } from "effect/Array" + * import type { Kind } from "effect/types/HKT" * * // Create a ReadonlyArray type using the type lambda * type NumberArray = Kind @@ -62,7 +62,7 @@ export interface ReadonlyArrayTypeLambda extends TypeLambda { * * @example * ```ts - * import { Array } from "effect" + * import type { Array } from "effect" * * const nonEmpty: Array.NonEmptyReadonlyArray = [1, 2, 3] * const head = nonEmpty[0] // 1 (guaranteed to exist) @@ -78,7 +78,7 @@ export type NonEmptyReadonlyArray = readonly [A, ...Array] * * @example * ```ts - * import { Array } from "effect" + * import type { Array } from "effect" * * const nonEmpty: Array.NonEmptyArray = [1, 2, 3] * nonEmpty.push(4) // Mutable operations are allowed @@ -132,7 +132,7 @@ export const allocate = (n: number): Array => new Arra * ```ts * import { Array } from "effect" * - * const result = Array.makeBy(5, n => n * 2) + * const result = Array.makeBy(5, (n) => n * 2) * console.log(result) // [0, 2, 4, 6, 8] * ``` * @@ -436,7 +436,7 @@ export const prependAll: { * ```ts * import { Array } from "effect" * - * const result = Array.append([1, 2, 3], 4); + * const result = Array.append([1, 2, 3], 4) * console.log(result) // [1, 2, 3, 4] * ``` * @@ -483,7 +483,7 @@ export const appendAll: { * @example * * ```ts - * import { Array } from "effect"; + * import { Array } from "effect" * * const result = Array.scan([1, 2, 3, 4], 0, (acc, value) => acc + value) * console.log(result) // [0, 1, 3, 6, 10] @@ -519,7 +519,7 @@ export const scan: { * @example * * ```ts - * import { Array } from "effect"; + * import { Array } from "effect" * * const result = Array.scanRight([1, 2, 3, 4], 0, (acc, value) => acc + value) * console.log(result) // [10, 9, 7, 4, 0] @@ -716,7 +716,7 @@ export const getUnsafe: { * @example * * ```ts - * import { Array } from "effect"; + * import { Array } from "effect" * * const result = Array.unprepend([1, 2, 3, 4]) * console.log(result) // [1, [2, 3, 4]] @@ -735,7 +735,7 @@ export const unprepend = ( * @example * * ```ts - * import { Array } from "effect"; + * import { Array } from "effect" * * const result = Array.unappend([1, 2, 3, 4]) * console.log(result) // [[1, 2, 3], 4] @@ -952,7 +952,7 @@ export const takeRight: { * ```ts * import { Array } from "effect" * - * const result = Array.takeWhile([1, 3, 2, 4, 1, 2], x => x < 4) + * const result = Array.takeWhile([1, 3, 2, 4, 1, 2], (x) => x < 4) * console.log(result) // [1, 3, 2] * * // Explanation: @@ -1004,7 +1004,7 @@ const spanIndex = (self: Iterable, predicate: (a: A, i: number) => boolean * ```ts * import { Array } from "effect" * - * const result = Array.span([1, 3, 2, 4, 5], x => x % 2 === 1) + * const result = Array.span([1, 3, 2, 4, 5], (x) => x % 2 === 1) * console.log(result) // [[1, 3], [2, 4, 5]] * ``` * @@ -1085,7 +1085,7 @@ export const dropRight: { * ```ts * import { Array } from "effect" * - * const result = Array.dropWhile([1, 2, 3, 4, 5], x => x < 4) + * const result = Array.dropWhile([1, 2, 3, 4, 5], (x) => x < 4) * console.log(result) // [4, 5] * ``` * @@ -1111,7 +1111,7 @@ export const dropWhile: { * * Array.findFirstIndex( * [5, 3, 8, 9], - * x => x > 5 + * (x) => x > 5 * ) // 2 * ``` * @@ -1141,7 +1141,7 @@ export const findFirstIndex: { * * Array.findLastIndex( * [1, 3, 8, 9], - * x => x < 5 + * (x) => x < 5 * ) // 1 * ``` * @@ -1169,7 +1169,7 @@ export const findLastIndex: { * ```ts * import { Array } from "effect" * - * const result = Array.findFirst([1, 2, 3, 4, 5], x => x > 3) + * const result = Array.findFirst([1, 2, 3, 4, 5], (x) => x > 3) * console.log(result) // Option.some(4) * ``` * @@ -1194,7 +1194,7 @@ export const findFirst: { * ```ts * import { Array } from "effect" * - * Array.findFirstWithIndex([1, 2, 3, 4, 5], x => x > 3) // [4, 3] + * Array.findFirstWithIndex([1, 2, 3, 4, 5], (x) => x > 3) // [4, 3] * ``` * * @category elements @@ -1239,7 +1239,7 @@ export const findFirstWithIndex: { * ```ts * import { Array } from "effect" * - * const result = Array.findLast([1, 2, 3, 4, 5], n => n % 2 === 0) + * const result = Array.findLast([1, 2, 3, 4, 5], (n) => n % 2 === 0) * console.log(result) // Option.some(4) * ``` * @@ -1286,7 +1286,7 @@ export const findLast: { * ```ts * import { Array } from "effect" * - * Array.insertAt(['a', 'b', 'c', 'e'], 3, 'd') // ['a', 'b', 'c', 'd', 'e'] + * Array.insertAt(["a", "b", "c", "e"], 3, "d") // ['a', 'b', 'c', 'd', 'e'] * ``` * * @category elements @@ -1432,8 +1432,7 @@ export const reverse = >( * * @example * ```ts - * import { Array } from "effect" - * import { Order } from "effect" + * import { Array, Order } from "effect" * * const result = Array.sort([3, 1, 4, 1, 5], Order.number) * console.log(result) // [1, 1, 3, 4, 5] @@ -1462,8 +1461,7 @@ export const sort: { * @example * * ```ts - * import { Array } from "effect" - * import { Order } from "effect" + * import { Array, Order } from "effect" * * const result = Array.sortWith(["aaa", "b", "cc"], (s) => s.length, Order.number) * console.log(result) // ["b", "cc", "aaa"] @@ -1498,9 +1496,7 @@ export const sortWith: { * @example * * ```ts - * import { pipe } from "effect" - * import { Array } from "effect" - * import { Order } from "effect" + * import { Array, Order, pipe } from "effect" * * const users = [ * { name: "Alice", age: 30 }, @@ -1556,7 +1552,7 @@ export const sortBy = >( * ```ts * import { Array } from "effect" * - * const result = Array.zip([1, 2, 3], ['a', 'b']) + * const result = Array.zip([1, 2, 3], ["a", "b"]) * console.log(result) // [[1, 'a'], [2, 'b']] * ``` * @@ -1687,7 +1683,7 @@ export const intersperse: { * ```ts * import { Array } from "effect" * - * const result = Array.modifyHeadNonEmpty([1, 2, 3], n => n * 10) + * const result = Array.modifyHeadNonEmpty([1, 2, 3], (n) => n * 10) * console.log(result) // [10, 2, 3] * ``` * @@ -1736,7 +1732,7 @@ export const setHeadNonEmpty: { * ```ts * import { Array } from "effect" * - * const result = Array.modifyLastNonEmpty([1, 2, 3], n => n * 2) + * const result = Array.modifyLastNonEmpty([1, 2, 3], (n) => n * 2) * console.log(result) // [1, 2, 6] * ``` * @@ -1784,7 +1780,7 @@ export const setLastNonEmpty: { * ```ts * import { Array } from "effect" * - * const result = Array.rotate(['a', 'b', 'c', 'd'], 2) + * const result = Array.rotate(["a", "b", "c", "d"], 2) * console.log(result) // ['c', 'd', 'a', 'b'] * ``` * @@ -1819,8 +1815,7 @@ export const rotate: { * @example * * ```ts - * import { pipe } from "effect" - * import { Array } from "effect" + * import { Array, pipe } from "effect" * * const isEquivalent = (a: number, b: number) => a === b * const containsNumber = Array.containsWith(isEquivalent) @@ -1852,10 +1847,9 @@ const _equivalence = Equal.equivalence() * @example * * ```ts - * import { pipe } from "effect" - * import { Array } from "effect" + * import { Array, pipe } from "effect" * - * const result = pipe(['a', 'b', 'c', 'd'], Array.contains('c')) + * const result = pipe(["a", "b", "c", "d"], Array.contains("c")) * console.log(result) // true * ``` * @@ -1877,7 +1871,10 @@ export const contains: { * ```ts * import { Array } from "effect" * - * const result = Array.chop([1, 2, 3, 4, 5], (as): [number, Array] => [as[0] * 2, as.slice(1)]) + * const result = Array.chop( + * [1, 2, 3, 4, 5], + * (as): [number, Array] => [as[0] * 2, as.slice(1)] + * ) * console.log(result) // [2, 4, 6, 8, 10] * * // Explanation: @@ -2009,7 +2006,7 @@ export const split: { * ```ts * import { Array } from "effect" * - * const result = Array.splitWhere([1, 2, 3, 4, 5], n => n > 3) + * const result = Array.splitWhere([1, 2, 3, 4, 5], (n) => n > 3) * console.log(result) // [[1, 2, 3], [4, 5]] * ``` * @@ -2169,7 +2166,10 @@ export const window: { * ```ts * import { Array } from "effect" * - * const result = Array.groupWith(["a", "a", "b", "b", "b", "c", "a"], (x, y) => x === y) + * const result = Array.groupWith( + * ["a", "a", "b", "b", "b", "c", "a"], + * (x, y) => x === y + * ) * console.log(result) // [["a", "a"], ["b", "b", "b"], ["c"], ["a"]] * ``` * @@ -2232,7 +2232,7 @@ export const group: (self: NonEmptyReadonlyArray) => NonEmptyArray person.group) + * const result = Array.groupBy(people, (person) => person.group) * console.log(result) * // { * // A: [{ name: "Alice", group: "A" }, { name: "Charlie", group: "A" }], @@ -2399,7 +2399,10 @@ export const intersection: { * * const array1 = [1, 2, 3] * const array2 = [2, 3, 4] - * const difference = Array.differenceWith((a, b) => a === b)(array1, array2) + * const difference = Array.differenceWith((a, b) => a === b)( + * array1, + * array2 + * ) * console.log(difference) // [1] * ``` * @@ -2475,7 +2478,7 @@ export const of = (a: A): NonEmptyArray => [a] * * @example * ```ts - * import { Array } from "effect" + * import type { Array } from "effect" * * type ElementType = Array.ReadonlyArray.Infer> * // ElementType is string @@ -2491,7 +2494,7 @@ export const of = (a: A): NonEmptyArray => [a] * import type { Array } from "effect" * * // Using ReadonlyArray utility types - * type ElementType = Array.ReadonlyArray.Infer + * type ElementType = Array.ReadonlyArray.Infer> * type WithNumber = Array.ReadonlyArray.With * ``` * @@ -2506,7 +2509,7 @@ export declare namespace ReadonlyArray { * ```ts * import type { Array } from "effect" * - * type StringArrayType = Array.ReadonlyArray.Infer + * type StringArrayType = Array.ReadonlyArray.Infer> * // StringArrayType is string * ``` * @@ -2541,7 +2544,11 @@ export declare namespace ReadonlyArray { * ```ts * import type { Array } from "effect" * - * type Result = Array.ReadonlyArray.OrNonEmpty + * type Result = Array.ReadonlyArray.OrNonEmpty< + * readonly [number], + * ReadonlyArray, + * number + * > * // Result is NonEmptyArray * ``` * @@ -2563,7 +2570,11 @@ export declare namespace ReadonlyArray { * ```ts * import type { Array } from "effect" * - * type Result = Array.ReadonlyArray.AndNonEmpty + * type Result = Array.ReadonlyArray.AndNonEmpty< + * readonly [number], + * readonly [string], + * boolean + * > * // Result is NonEmptyArray * ``` * @@ -2585,7 +2596,7 @@ export declare namespace ReadonlyArray { * ```ts * import type { Array } from "effect" * - * type Nested = readonly (readonly number[])[] + * type Nested = ReadonlyArray> * type Flattened = Array.ReadonlyArray.Flatten * // Flattened is Array * ``` @@ -2606,7 +2617,7 @@ export declare namespace ReadonlyArray { * ```ts * import { Array } from "effect" * - * const result = Array.map([1, 2, 3], x => x * 2) + * const result = Array.map([1, 2, 3], (x) => x * 2) * console.log(result) // [2, 4, 6] * ``` * @@ -2627,7 +2638,7 @@ export const map: { * ```ts * import { Array } from "effect" * - * const result = Array.flatMap([1, 2, 3], x => [x, x * 2]) + * const result = Array.flatMap([1, 2, 3], (x) => [x, x * 2]) * console.log(result) // [1, 2, 2, 4, 3, 6] * ``` * @@ -2688,9 +2699,10 @@ export const flatten: >>(self: S) => * import { Array } from "effect" * import * as Option from "effect/Option" * - * const evenSquares = (x: number) => x % 2 === 0 ? Option.some(x * x) : Option.none() + * const evenSquares = (x: number) => + * x % 2 === 0 ? Option.some(x * x) : Option.none() * - * const result = Array.filterMap([1, 2, 3, 4, 5], evenSquares); + * const result = Array.filterMap([1, 2, 3, 4, 5], evenSquares) * console.log(result) // [4, 16] * ``` * @@ -2726,7 +2738,8 @@ export const filterMap: { * import { Array } from "effect" * import * as Option from "effect/Option" * - * const toSquareTillOdd = (x: number) => x % 2 === 0 ? Option.some(x * x) : Option.none() + * const toSquareTillOdd = (x: number) => + * x % 2 === 0 ? Option.some(x * x) : Option.none() * * const result = Array.filterMapWhile([2, 4, 5], toSquareTillOdd) * console.log(result) // [4, 16] @@ -2762,13 +2775,13 @@ export const filterMapWhile: { * @example * * ```ts - * import { Array } from "effect" - * import { Result } from "effect"; + * import { Array, Result } from "effect" * * const isEven = (x: number) => x % 2 === 0 * - * const result = Array.partitionMap([1, 2, 3, 4, 5], x => - * isEven(x) ? Result.succeed(x) : Result.fail(x) + * const result = Array.partitionMap( + * [1, 2, 3, 4, 5], + * (x) => isEven(x) ? Result.succeed(x) : Result.fail(x) * ) * console.log(result) * // [ @@ -2851,10 +2864,13 @@ export const getSomes: >, X = any>( * @example * * ```ts - * import { Array } from "effect" - * import { Result } from "effect" + * import { Array, Result } from "effect" * - * const result = Array.getFailures([Result.succeed(1), Result.fail("err"), Result.succeed(2)]) + * const result = Array.getFailures([ + * Result.succeed(1), + * Result.fail("err"), + * Result.succeed(2) + * ]) * console.log(result) // ["err"] * ``` * @@ -2880,10 +2896,13 @@ export const getFailures = >>( * @example * * ```ts - * import { Array } from "effect" - * import { Result } from "effect" + * import { Array, Result } from "effect" * - * const result = Array.getSuccesses([Result.succeed(1), Result.fail("err"), Result.succeed(2)]) + * const result = Array.getSuccesses([ + * Result.succeed(1), + * Result.fail("err"), + * Result.succeed(2) + * ]) * console.log(result) // [1, 2] * ``` * @@ -2910,7 +2929,7 @@ export const getSuccesses = >>( * ```ts * import { Array } from "effect" * - * const result = Array.filter([1, 2, 3, 4], x => x % 2 === 0) + * const result = Array.filter([1, 2, 3, 4], (x) => x % 2 === 0) * console.log(result) // [2, 4] * ``` * @@ -2944,7 +2963,7 @@ export const filter: { * ```ts * import { Array } from "effect" * - * const result = Array.partition([1, 2, 3, 4], n => n % 2 === 0) + * const result = Array.partition([1, 2, 3, 4], (n) => n % 2 === 0) * console.log(result) // [[1, 3], [2, 4]] * ``` * @@ -2985,8 +3004,7 @@ export const partition: { * * @example * ```ts - * import { Array } from "effect" - * import { Result } from "effect" + * import { Array, Result } from "effect" * * const results = [Result.succeed(1), Result.fail("error"), Result.succeed(2)] * const [failures, successes] = Array.separate(results) @@ -3148,7 +3166,10 @@ export const liftNullishOr = , B>( * ```ts * import { Array } from "effect" * - * const result = Array.flatMapNullishOr([1, 2, 3], n => (n % 2 === 0 ? null : n)) + * const result = Array.flatMapNullishOr( + * [1, 2, 3], + * (n) => (n % 2 === 0 ? null : n) + * ) * console.log(result) // [1, 3] * * // Explanation: @@ -3176,11 +3197,12 @@ export const flatMapNullishOr: { * @example * * ```ts - * import { Array } from "effect" - * import { Result } from "effect" + * import { Array, Result } from "effect" * * const parseNumber = (s: string): Result.Result => - * isNaN(Number(s)) ? Result.fail(new Error("Not a number")) : Result.succeed(Number(s)) + * isNaN(Number(s)) + * ? Result.fail(new Error("Not a number")) + * : Result.succeed(Number(s)) * * const liftedParseNumber = Array.liftResult(parseNumber) * @@ -3214,10 +3236,10 @@ export const liftResult = , E, B>( * ```ts * import { Array } from "effect" * - * const result = Array.every([2, 4, 6], x => x % 2 === 0) + * const result = Array.every([2, 4, 6], (x) => x % 2 === 0) * console.log(result) // true * - * const result2 = Array.every([2, 3, 6], x => x % 2 === 0) + * const result2 = Array.every([2, 3, 6], (x) => x % 2 === 0) * console.log(result2) // false * ``` * @@ -3244,10 +3266,10 @@ export const every: { * ```ts * import { Array } from "effect" * - * const result = Array.some([1, 3, 4], x => x % 2 === 0) + * const result = Array.some([1, 3, 4], (x) => x % 2 === 0) * console.log(result) // true * - * const result2 = Array.some([1, 3, 5], x => x % 2 === 0) + * const result2 = Array.some([1, 3, 5], (x) => x % 2 === 0) * console.log(result2) // false * ``` * @@ -3273,7 +3295,7 @@ export const some: { * ```ts * import { Array } from "effect" * - * const result = Array.extend([1, 2, 3], as => as.length) + * const result = Array.extend([1, 2, 3], (as) => as.length) * console.log(result) // [3, 2, 1] * * // Explanation: @@ -3300,8 +3322,7 @@ export const extend: { * @example * * ```ts - * import { Array } from "effect" - * import { Order } from "effect" + * import { Array, Order } from "effect" * * const result = Array.min([3, 1, 2], Order.number) * console.log(result) // 1 @@ -3321,8 +3342,7 @@ export const min: { * @example * * ```ts - * import { Array } from "effect" - * import { Order } from "effect" + * import { Array, Order } from "effect" * * const result = Array.max([3, 1, 2], Order.number) * console.log(result) // 3 @@ -3343,7 +3363,7 @@ export const max: { * ```ts * import { Array } from "effect" * - * const result = Array.unfold(1, n => n <= 5 ? [n, n + 1] : undefined) + * const result = Array.unfold(1, (n) => n <= 5 ? [n, n + 1] : undefined) * console.log(result) // [1, 2, 3, 4, 5] * ``` * @@ -3370,8 +3390,7 @@ export const unfold = (b: B, f: (b: B) => readonly [A, B] | undefined): Ar * * @example * ```ts - * import { Array } from "effect" - * import { Order } from "effect" + * import { Array, Order } from "effect" * * const arrayOrder = Array.getOrder(Order.number) * console.log(arrayOrder([1, 2], [1, 3])) // -1 (first is less than second) @@ -3409,7 +3428,7 @@ export const getEquivalence: ( * ```ts * import { Array } from "effect" * - * Array.forEach([1, 2, 3], n => console.log(n)) // 1, 2, 3 + * Array.forEach([1, 2, 3], (n) => console.log(n)) // 1, 2, 3 * ``` * * @category elements @@ -3657,8 +3676,7 @@ export const cartesian: { * @example * * ```ts - * import { pipe } from "effect" - * import { Array } from "effect" + * import { Array, pipe } from "effect" * * const doResult = pipe( * Array.Do, @@ -3671,12 +3689,12 @@ export const cartesian: { * * // equivalent * const x = [1, 3, 5], - * y = [2, 4, 6], - * result = []; - * for(let i = 0; i < x.length; i++) { - * for(let j = 0; j < y.length; j++) { - * const _x = x[i], _y = y[j]; - * if(_x < _y) result.push([_x, _y] as const) + * y = [2, 4, 6], + * result = [] + * for (let i = 0; i < x.length; i++) { + * for (let j = 0; j < y.length; j++) { + * const _x = x[i], _y = y[j] + * if (_x < _y) result.push([_x, _y] as const) * } * } * ``` @@ -3707,8 +3725,7 @@ export const Do: ReadonlyArray<{}> = of({}) * @example * * ```ts - * import { pipe } from "effect" - * import { Array } from "effect" + * import { Array, pipe } from "effect" * * const doResult = pipe( * Array.Do, @@ -3721,12 +3738,12 @@ export const Do: ReadonlyArray<{}> = of({}) * * // equivalent * const x = [1, 3, 5], - * y = [2, 4, 6], - * result = []; - * for(let i = 0; i < x.length; i++) { - * for(let j = 0; j < y.length; j++) { - * const _x = x[i], _y = y[j]; - * if(_x < _y) result.push([_x, _y] as const) + * y = [2, 4, 6], + * result = [] + * for (let i = 0; i < x.length; i++) { + * for (let j = 0; j < y.length; j++) { + * const _x = x[i], _y = y[j] + * if (_x < _y) result.push([_x, _y] as const) * } * } * ``` @@ -3769,8 +3786,7 @@ export const bind: { * @example * * ```ts - * import { pipe } from "effect" - * import { Array } from "effect" + * import { Array, pipe } from "effect" * * const doResult = pipe( * Array.Do, @@ -3783,12 +3799,12 @@ export const bind: { * * // equivalent * const x = [1, 3, 5], - * y = [2, 4, 6], - * result = []; - * for(let i = 0; i < x.length; i++) { - * for(let j = 0; j < y.length; j++) { - * const _x = x[i], _y = y[j]; - * if(_x < _y) result.push([_x, _y] as const) + * y = [2, 4, 6], + * result = [] + * for (let i = 0; i < x.length; i++) { + * for (let j = 0; j < y.length; j++) { + * const _x = x[i], _y = y[j] + * if (_x < _y) result.push([_x, _y] as const) * } * } * ``` @@ -3835,8 +3851,7 @@ export { * @example * * ```ts - * import { pipe } from "effect" - * import { Array } from "effect" + * import { Array, pipe } from "effect" * * const doResult = pipe( * Array.Do, @@ -3849,15 +3864,14 @@ export { * * // equivalent * const x = [1, 3, 5], - * y = [2, 4, 6], - * result = []; - * for(let i = 0; i < x.length; i++) { - * for(let j = 0; j < y.length; j++) { - * const _x = x[i], _y = y[j]; - * if(_x < _y) result.push([_x, _y] as const) + * y = [2, 4, 6], + * result = [] + * for (let i = 0; i < x.length; i++) { + * for (let j = 0; j < y.length; j++) { + * const _x = x[i], _y = y[j] + * if (_x < _y) result.push([_x, _y] as const) * } * } - * * ``` * * @see {@link bindTo} @@ -3898,7 +3912,7 @@ export function getReducerConcat(): Reducer.Reducer> { * ```ts * import { Array } from "effect" * - * const result = Array.countBy([1, 2, 3, 4, 5], n => n % 2 === 0) + * const result = Array.countBy([1, 2, 3, 4, 5], (n) => n % 2 === 0) * console.log(result) // 2 * ``` * diff --git a/packages/effect/src/BigDecimal.ts b/packages/effect/src/BigDecimal.ts index 778450a734..05d5dc62e8 100644 --- a/packages/effect/src/BigDecimal.ts +++ b/packages/effect/src/BigDecimal.ts @@ -1360,11 +1360,17 @@ export type RoundingMode = * * @example * ```ts + * import { fromStringUnsafe, round } from "effect/BigDecimal" * import * as assert from "node:assert" - * import { round, fromStringUnsafe } from "effect/BigDecimal" * - * assert.deepStrictEqual(round(fromStringUnsafe("145"), { mode: "from-zero", scale: -1 }), fromStringUnsafe("150")) - * assert.deepStrictEqual(round(fromStringUnsafe("-14.5")), fromStringUnsafe("-15")) + * assert.deepStrictEqual( + * round(fromStringUnsafe("145"), { mode: "from-zero", scale: -1 }), + * fromStringUnsafe("150") + * ) + * assert.deepStrictEqual( + * round(fromStringUnsafe("-14.5")), + * fromStringUnsafe("-15") + * ) * ``` * * @since 4.0.0 @@ -1425,11 +1431,17 @@ export const round: { * * @example * ```ts + * import { fromStringUnsafe, truncate } from "effect/BigDecimal" * import * as assert from "node:assert" - * import { truncate, fromStringUnsafe } from "effect/BigDecimal" * - * assert.deepStrictEqual(truncate(fromStringUnsafe("145"), -1), fromStringUnsafe("140")) - * assert.deepStrictEqual(truncate(fromStringUnsafe("-14.5")), fromStringUnsafe("-14")) + * assert.deepStrictEqual( + * truncate(fromStringUnsafe("145"), -1), + * fromStringUnsafe("140") + * ) + * assert.deepStrictEqual( + * truncate(fromStringUnsafe("-14.5")), + * fromStringUnsafe("-14") + * ) * ``` * * @since 4.0.0 @@ -1452,10 +1464,13 @@ export const truncate: { * * @example * ```ts - * import * as assert from "node:assert" * import { ceil, fromStringUnsafe } from "effect/BigDecimal" + * import * as assert from "node:assert" * - * assert.deepStrictEqual(ceil(fromStringUnsafe("145"), -1), fromStringUnsafe("150")) + * assert.deepStrictEqual( + * ceil(fromStringUnsafe("145"), -1), + * fromStringUnsafe("150") + * ) * assert.deepStrictEqual(ceil(fromStringUnsafe("-14.5")), fromStringUnsafe("-14")) * ``` * @@ -1499,11 +1514,17 @@ export const digitAt: { * * @example * ```ts - * import * as assert from "node:assert" * import { floor, fromStringUnsafe } from "effect/BigDecimal" + * import * as assert from "node:assert" * - * assert.deepStrictEqual(floor(fromStringUnsafe("145"), -1), fromStringUnsafe("140")) - * assert.deepStrictEqual(floor(fromStringUnsafe("-14.5")), fromStringUnsafe("-15")) + * assert.deepStrictEqual( + * floor(fromStringUnsafe("145"), -1), + * fromStringUnsafe("140") + * ) + * assert.deepStrictEqual( + * floor(fromStringUnsafe("-14.5")), + * fromStringUnsafe("-15") + * ) * ``` * * @since 4.0.0 diff --git a/packages/effect/src/Cache.ts b/packages/effect/src/Cache.ts index 8a884cca36..db9b0fac0a 100644 --- a/packages/effect/src/Cache.ts +++ b/packages/effect/src/Cache.ts @@ -67,9 +67,7 @@ const TypeId = "~effect/Cache" * * @example * ```ts - * import { Cache, Effect } from "effect" - * import { Data } from "effect" - * import { Duration } from "effect" + * import { Cache, Data, Duration, Effect } from "effect" * * // Cache with complex key types and TTL * class UserId extends Data.Class<{ id: number }> {} diff --git a/packages/effect/src/Cause.ts b/packages/effect/src/Cause.ts index 782ba45584..731569d9c2 100644 --- a/packages/effect/src/Cause.ts +++ b/packages/effect/src/Cause.ts @@ -198,7 +198,7 @@ export declare namespace Cause { /** * @example * ```ts - * import { Cause } from "effect" + * import type { Cause } from "effect" * * type ErrorType = Cause.Cause.Error> * // type ErrorType = string @@ -238,7 +238,7 @@ export declare namespace Cause { /** * @example * ```ts - * import { Cause } from "effect" + * import type { Cause } from "effect" * * type StringFailureError = Cause.Failure.Error> * // type StringFailureError = string @@ -251,7 +251,7 @@ export declare namespace Failure { /** * @example * ```ts - * import { Cause } from "effect" + * import type { Cause } from "effect" * * type ErrorType = Cause.Failure.Error> * // type ErrorType = string @@ -618,7 +618,7 @@ export const pretty: (cause: Cause) => string = effect.causePretty * const error = new Cause.NoSuchElementError("Item not found") * * // Can be used directly in Effect.gen - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * yield* error // This will fail with the error * }) * @@ -662,7 +662,9 @@ export const NoSuchElementErrorTypeId: "~effect/Cause/NoSuchElementError" = core * ```ts * import { Cause } from "effect" * - * const error: Cause.NoSuchElementError = new Cause.NoSuchElementError("Element not found") + * const error: Cause.NoSuchElementError = new Cause.NoSuchElementError( + * "Element not found" + * ) * console.log(error._tag) // "NoSuchElementError" * console.log(error.message) // "Element not found" * console.log(Cause.isNoSuchElementError(error)) // true @@ -778,7 +780,9 @@ export const isIllegalArgumentError: (u: unknown) => u is IllegalArgumentError = * ```ts * import { Cause } from "effect" * - * const error: Cause.IllegalArgumentError = new Cause.IllegalArgumentError("Invalid argument") + * const error: Cause.IllegalArgumentError = new Cause.IllegalArgumentError( + * "Invalid argument" + * ) * console.log(error._tag) // "IllegalArgumentError" * console.log(error.message) // "Invalid argument" * console.log(Cause.isIllegalArgumentError(error)) // true @@ -836,7 +840,9 @@ export const ExceededCapacityErrorTypeId: "~effect/Cause/ExceededCapacityError" * ```ts * import { Cause } from "effect" * - * const error: Cause.ExceededCapacityError = new Cause.ExceededCapacityError("Capacity exceeded") + * const error: Cause.ExceededCapacityError = new Cause.ExceededCapacityError( + * "Capacity exceeded" + * ) * console.log(error._tag) // "ExceededCapacityError" * console.log(error.message) // "Capacity exceeded" * console.log(Cause.isExceededCapacityError(error)) // true @@ -894,7 +900,10 @@ export const isUnknownError: (u: unknown) => u is UnknownError = effect.isUnknow * ```ts * import { Cause } from "effect" * - * const error: Cause.UnknownError = new Cause.UnknownError("original cause", "Unknown error occurred") + * const error: Cause.UnknownError = new Cause.UnknownError( + * "original cause", + * "Unknown error occurred" + * ) * console.log(error._tag) // "UnknownError" * console.log(error.message) // "Unknown error occurred" * console.log(Cause.isUnknownError(error)) // true diff --git a/packages/effect/src/Channel.ts b/packages/effect/src/Channel.ts index 89f4824bbc..962e206b63 100644 --- a/packages/effect/src/Channel.ts +++ b/packages/effect/src/Channel.ts @@ -31,7 +31,6 @@ * @example * ```ts * import { Channel } from "effect" - * import { Effect } from "effect" * * // Simple channel that outputs numbers * const numberChannel = Channel.succeed(42) @@ -45,7 +44,6 @@ * @example * ```ts * import { Channel } from "effect" - * import { Effect } from "effect" * * // Channel from an array of values * const arrayChannel = Channel.fromArray([1, 2, 3, 4, 5]) @@ -133,7 +131,7 @@ export const isChannel = ( * * @example * ```ts - * import { Channel } from "effect" + * import type { Channel } from "effect" * * // A channel that outputs numbers and requires no environment * type NumberChannel = Channel.Channel @@ -143,12 +141,12 @@ export const isChannel = ( * * // A channel with all type parameters specified * type FullChannel = Channel.Channel< - * string, // OutElem - output elements - * Error, // OutErr - output errors - * number, // OutDone - completion value - * number, // InElem - input elements - * string, // InErr - input errors - * boolean, // InDone - input completion + * string, // OutElem - output elements + * Error, // OutErr - output errors + * number, // OutDone - completion value + * number, // InElem - input elements + * string, // InErr - input errors + * boolean, // InDone - input completion * { db: string } // Env - required environment * > * ``` @@ -248,8 +246,7 @@ const ChannelProto = { * * @example * ```ts - * import { Channel } from "effect" - * import { Effect } from "effect" + * import { Channel, Effect } from "effect" * * const channel = Channel.fromTransform((upstream, scope) => * Effect.succeed(upstream) @@ -284,16 +281,17 @@ export const fromTransform = - * Effect.succeed( - * Effect.map(pull, (value) => value * 2) - * ) + * const transformedChannel = Channel.transformPull( + * originalChannel, + * (pull, scope) => + * Effect.succeed( + * Effect.map(pull, (value) => value * 2) + * ) * ) * // Outputs: 2, 4, 6 * ``` @@ -336,8 +334,7 @@ export const transformPull = < * * @example * ```ts - * import { Channel } from "effect" - * import { Effect } from "effect" + * import { Channel, Effect } from "effect" * * const channel = Channel.fromPull( * Effect.succeed(Effect.succeed(42)) @@ -443,8 +440,7 @@ const asyncQueue = ( * * @example * ```ts - * import { Channel } from "effect" - * import { Queue } from "effect" + * import { Channel, Queue } from "effect" * * const channel = Channel.callback((queue) => { * Queue.offer(queue, 1) @@ -470,8 +466,7 @@ export const callback = ( * * @example * ```ts - * import { Channel } from "effect" - * import { Effect, Queue } from "effect" + * import { Channel, Effect, Queue } from "effect" * * const channel = Channel.callbackArray(Effect.fn(function*(queue) { * yield* Queue.offer(queue, 1) @@ -516,8 +511,7 @@ export const suspend = ( * * @example * ```ts - * import { Effect, Exit } from "effect" - * import { Channel } from "effect" + * import { Channel, Effect } from "effect" * * const channel = Channel.acquireUseRelease( * Effect.succeed("resource"), @@ -552,8 +546,7 @@ export const acquireUseRelease = (array: ReadonlyArray): Channel => * * @example * ```ts - * import { Channel } from "effect" - * import { Chunk } from "effect" + * import { Channel, Chunk } from "effect" * * const chunk = Chunk.make(1, 2, 3) * const channel = Channel.fromChunk(chunk) @@ -651,7 +643,6 @@ export const fromChunk = (chunk: Chunk.Chunk): Channel => fromArray(Chu * @example * ```ts * import { Channel } from "effect" - * import { Effect } from "effect" * * // Create a channel from a simple iterator * const numberIterator = (): Iterator => { @@ -678,8 +669,8 @@ export const fromChunk = (chunk: Chunk.Chunk): Channel => fromArray(Chu * function* fibonacci(): Generator { * let a = 0, b = 1 * for (let i = 0; i < 5; i++) { - * yield a; - * [a, b] = [b, a + b] + * yield a + * ;[a, b] = [b, a + b] * } * } * @@ -842,7 +833,6 @@ export const empty: Channel = fromPull(Effect.succeed(Pull.haltVoid)) * @example * ```ts * import { Channel } from "effect" - * import { Effect } from "effect" * * // Create a channel that never completes * const neverChannel = Channel.never @@ -869,7 +859,6 @@ export const never: Channel = fromPull(Effect.succeed(Effec * @example * ```ts * import { Channel } from "effect" - * import { Effect } from "effect" * * // Create a channel that fails with a string error * const failedChannel = Channel.fail("Something went wrong") @@ -931,8 +920,7 @@ export const failSync = (evaluate: LazyArg): Channel => f * * @example * ```ts - * import { Cause } from "effect" - * import { Channel } from "effect" + * import { Cause, Channel } from "effect" * * // Create a channel that fails with a simple cause * const simpleCause = Cause.fail("Simple error") @@ -958,8 +946,7 @@ export const failCause = (cause: Cause.Cause): Channel => * * @example * ```ts - * import { Cause } from "effect" - * import { Channel } from "effect" + * import { Cause, Channel } from "effect" * * // Create a channel that fails with a lazily computed cause * const failedChannel = Channel.failCauseSync(() => { @@ -1011,9 +998,7 @@ export const die = (defect: unknown): Channel => failCause( * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Data } from "effect" + * import { Channel, Data, Effect } from "effect" * * class DatabaseError extends Data.TaggedError("DatabaseError")<{ * readonly message: string @@ -1027,14 +1012,14 @@ export const die = (defect: unknown): Channel => failCause( * // Create a channel from an effect that might fail * const fetchUserChannel = Channel.fromEffect( * Effect.tryPromise({ - * try: () => fetch("/api/user").then(res => res.json()), + * try: () => fetch("/api/user").then((res) => res.json()), * catch: (error) => new DatabaseError({ message: String(error) }) * }) * ) * * // Channel from effect with async computation * const asyncChannel = Channel.fromEffect( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Effect.sleep("100 millis") * return "Async result" * }) @@ -1082,16 +1067,13 @@ export const fromEffectTake = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Data } from "effect" - * import { Queue } from "effect" + * import { Channel, Data, Effect, Queue } from "effect" * * class QueueError extends Data.TaggedError("QueueError")<{ * readonly reason: string * }> {} * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * // Create a bounded queue * const queue = yield* Queue.bounded(10) * @@ -1108,7 +1090,7 @@ export const fromEffectTake = ( * }) * * // Sliding queue example - * const slidingProgram = Effect.gen(function* () { + * const slidingProgram = Effect.gen(function*() { * const slidingQueue = yield* Queue.sliding(5) * yield* Queue.offerAll(slidingQueue, [1, 2, 3, 4, 5, 6]) * return Channel.fromQueue(slidingQueue) @@ -1127,16 +1109,13 @@ export const fromQueue = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Data } from "effect" - * import { Queue } from "effect" + * import { Channel, Data, Effect, Queue } from "effect" * * class ProcessingError extends Data.TaggedError("ProcessingError")<{ * readonly stage: string * }> {} * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * // Create a queue for batch processing * const queue = yield* Queue.bounded(100) * @@ -1152,13 +1131,14 @@ export const fromQueue = ( * }) * * // High-throughput processing example - * const batchProcessor = Effect.gen(function* () { + * const batchProcessor = Effect.gen(function*() { * const dataQueue = yield* Queue.dropping(1000) * const batchChannel = Channel.fromQueueArray(dataQueue) * * // Process data in batches for better performance - * return Channel.map(batchChannel, (batch) => - * batch.map(item => item.toUpperCase()) + * return Channel.map( + * batchChannel, + * (batch) => batch.map((item) => item.toUpperCase()) * ) * }) * ``` @@ -1182,16 +1162,13 @@ export const identity = (): Channel {} * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * // Create a PubSub * const pubsub = yield* PubSub.bounded(32) * @@ -1212,7 +1189,7 @@ export const identity = (): Channel() * const userSubscription = yield* PubSub.subscribe(eventBus) * @@ -1239,16 +1216,13 @@ export const fromSubscription = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Data } from "effect" - * import { PubSub } from "effect" + * import { Channel, Data, Effect, PubSub } from "effect" * * class StreamError extends Data.TaggedError("StreamError")<{ * readonly message: string * }> {} * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(16) * const subscription = yield* PubSub.subscribe(pubsub) * @@ -1268,16 +1242,13 @@ export const fromSubscription = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Data } from "effect" - * import { PubSub } from "effect" + * import { Channel, Data, Effect, PubSub } from "effect" * * class BatchProcessingError extends Data.TaggedError("BatchProcessingError")<{ * readonly reason: string * }> {} * - * const batchProcessor = Effect.gen(function* () { + * const batchProcessor = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(32) * const subscription = yield* PubSub.subscribe(pubsub) * @@ -1287,7 +1258,7 @@ export const fromSubscription = ( * // Transform to process each batch * const processedChannel = Channel.map(batchChannel, (batch) => { * console.log(`Processing batch of ${batch.length} items:`, batch) - * return batch.map(item => item.toUpperCase()) + * return batch.map((item) => item.toUpperCase()) * }) * * return processedChannel @@ -1296,17 +1267,16 @@ export const fromSubscription = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Data } from "effect" - * import { PubSub } from "effect" + * import { Channel, Data, Effect, PubSub } from "effect" * * class MetricsError extends Data.TaggedError("MetricsError")<{ * readonly cause: string * }> {} * - * const metricsAggregator = Effect.gen(function* () { - * const metricsPubSub = yield* PubSub.bounded<{ timestamp: number; value: number }>(100) + * const metricsAggregator = Effect.gen(function*() { + * const metricsPubSub = yield* PubSub.bounded< + * { timestamp: number; value: number } + * >(100) * const subscription = yield* PubSub.subscribe(metricsPubSub) * * // Create a channel that collects metrics in chunks @@ -1314,7 +1284,7 @@ export const fromSubscription = ( * * // Transform to calculate aggregate statistics * const aggregatedChannel = Channel.map(metricsChannel, (metrics) => { - * const values = metrics.map(m => m.value) + * const values = metrics.map((m) => m.value) * const sum = values.reduce((a, b) => a + b, 0) * const avg = sum / values.length * const min = Math.min(...values) @@ -1353,16 +1323,13 @@ export const fromSubscriptionArray = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Data } from "effect" - * import { PubSub } from "effect" + * import { Channel, Data, Effect, PubSub } from "effect" * * class StreamError extends Data.TaggedError("StreamError")<{ * readonly message: string * }> {} * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(16) * * // Create a channel that reads individual values @@ -1380,16 +1347,13 @@ export const fromSubscriptionArray = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Data } from "effect" - * import { PubSub } from "effect" + * import { Channel, Data, Effect, PubSub } from "effect" * * class NotificationError extends Data.TaggedError("NotificationError")<{ * readonly reason: string * }> {} * - * const notificationService = Effect.gen(function* () { + * const notificationService = Effect.gen(function*() { * const notificationPubSub = yield* PubSub.bounded(50) * * // Create a channel for real-time notifications @@ -1408,10 +1372,7 @@ export const fromSubscriptionArray = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Data } from "effect" - * import { PubSub } from "effect" + * import { Channel, Data, Effect, PubSub } from "effect" * * class EventProcessingError extends Data.TaggedError("EventProcessingError")<{ * readonly eventType: string @@ -1424,7 +1385,7 @@ export const fromSubscriptionArray = ( * readonly timestamp: number * } * - * const eventProcessor = Effect.gen(function* () { + * const eventProcessor = Effect.gen(function*() { * const eventPubSub = yield* PubSub.bounded(100) * * // Create a channel for processing domain events @@ -1465,16 +1426,13 @@ export const fromPubSub = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Data } from "effect" - * import { PubSub } from "effect" + * import { Channel, Data, Effect, PubSub } from "effect" * * class BatchError extends Data.TaggedError("BatchError")<{ * readonly message: string * }> {} * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(16) * * // Create a channel that reads arrays of values @@ -1493,10 +1451,7 @@ export const fromPubSub = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Data } from "effect" - * import { PubSub } from "effect" + * import { Channel, Data, Effect, PubSub } from "effect" * * class OrderProcessingError extends Data.TaggedError("OrderProcessingError")<{ * readonly orderId: string @@ -1510,7 +1465,7 @@ export const fromPubSub = ( * readonly total: number * } * - * const orderBatchProcessor = Effect.gen(function* () { + * const orderBatchProcessor = Effect.gen(function*() { * const orderPubSub = yield* PubSub.bounded(100) * * // Create a channel that processes orders in batches @@ -1519,7 +1474,9 @@ export const fromPubSub = ( * // Transform to process each batch of orders * const processedChannel = Channel.map(orderChannel, (orderBatch) => { * const totalRevenue = orderBatch.reduce((sum, order) => sum + order.total, 0) - * const customerCount = new Set(orderBatch.map(order => order.customerId)).size + * const customerCount = new Set(orderBatch.map((order) => + * order.customerId + * )).size * * return { * batchSize: orderBatch.length, @@ -1536,10 +1493,7 @@ export const fromPubSub = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Data } from "effect" - * import { PubSub } from "effect" + * import { Channel, Data, Effect, PubSub } from "effect" * * class LogProcessingError extends Data.TaggedError("LogProcessingError")<{ * readonly batchId: string @@ -1553,7 +1507,7 @@ export const fromPubSub = ( * readonly source: string * } * - * const logAggregator = Effect.gen(function* () { + * const logAggregator = Effect.gen(function*() { * const logPubSub = yield* PubSub.bounded(500) * * // Create a channel that collects logs in batches @@ -1561,13 +1515,13 @@ export const fromPubSub = ( * * // Transform to analyze log batches * const analysisChannel = Channel.map(logChannel, (logBatch) => { - * const errorCount = logBatch.filter(log => log.level === "error").length - * const warnCount = logBatch.filter(log => log.level === "warn").length - * const infoCount = logBatch.filter(log => log.level === "info").length + * const errorCount = logBatch.filter((log) => log.level === "error").length + * const warnCount = logBatch.filter((log) => log.level === "warn").length + * const infoCount = logBatch.filter((log) => log.level === "info").length * * const timeRange = { - * start: Math.min(...logBatch.map(log => log.timestamp)), - * end: Math.max(...logBatch.map(log => log.timestamp)) + * start: Math.min(...logBatch.map((log) => log.timestamp)), + * end: Math.max(...logBatch.map((log) => log.timestamp)) * } * * return { @@ -1577,7 +1531,7 @@ export const fromPubSub = ( * warnCount, * infoCount, * timeRange, - * sources: [...new Set(logBatch.map(log => log.source))] + * sources: [...new Set(logBatch.map((log) => log.source))] * } * }) * @@ -1651,9 +1605,7 @@ export const fromAsyncIterableArray = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Data } from "effect" + * import { Channel, Data } from "effect" * * class TransformError extends Data.TaggedError("TransformError")<{ * readonly reason: string @@ -1775,9 +1727,7 @@ const concurrencyIsSequential = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Data } from "effect" + * import { Channel, Data, Effect } from "effect" * * class NetworkError extends Data.TaggedError("NetworkError")<{ * readonly url: string @@ -1792,20 +1742,22 @@ const concurrencyIsSequential = ( * * const fetchDataChannel = Channel.mapEffect( * urlsChannel, - * (url) => Effect.tryPromise({ - * try: () => fetch(url).then(res => res.json()), - * catch: () => new NetworkError({ url }) - * }) + * (url) => + * Effect.tryPromise({ + * try: () => fetch(url).then((res) => res.json()), + * catch: () => new NetworkError({ url }) + * }) * ) * * // Concurrent processing with options * const numbersChannel = Channel.fromIterable([1, 2, 3, 4, 5]) * const processedChannel = Channel.mapEffect( * numbersChannel, - * (n) => Effect.gen(function* () { - * yield* Effect.sleep("100 millis") // Simulate async work - * return n * n - * }), + * (n) => + * Effect.gen(function*() { + * yield* Effect.sleep("100 millis") // Simulate async work + * return n * n + * }), * { concurrency: 3, unordered: true } * ) * ``` @@ -2038,10 +1990,7 @@ export const mapInputError: { * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Console } from "effect" - * import { Data } from "effect" + * import { Channel, Console, Data } from "effect" * * class LogError extends Data.TaggedError("LogError")<{ * readonly message: string @@ -2051,8 +2000,9 @@ export const mapInputError: { * const numberChannel = Channel.fromIterable([1, 2, 3]) * * // Tap into each output element to perform side effects - * const tappedChannel = Channel.tap(numberChannel, (n) => - * Console.log(`Processing number: ${n}`) + * const tappedChannel = Channel.tap( + * numberChannel, + * (n) => Console.log(`Processing number: ${n}`) * ) * * // The channel still outputs the same elements but logs each one @@ -2099,9 +2049,7 @@ export const tap: { * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Data } from "effect" + * import { Channel, Data } from "effect" * * class ProcessError extends Data.TaggedError("ProcessError")<{ * readonly cause: string @@ -2111,8 +2059,10 @@ export const tap: { * const numberChannel = Channel.fromIterable([1, 2, 3]) * * // FlatMap each number to create new channels - * const flatMappedChannel = Channel.flatMap(numberChannel, (n) => - * Channel.fromIterable(Array.from({ length: n }, (_, i) => `item-${n}-${i}`)) + * const flatMappedChannel = Channel.flatMap( + * numberChannel, + * (n) => + * Channel.fromIterable(Array.from({ length: n }, (_, i) => `item-${n}-${i}`)) * ) * * // Flattens nested channels into a single stream @@ -2304,9 +2254,7 @@ const flatMapConcurrent = < * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Data } from "effect" + * import { Channel, Data } from "effect" * * class ConcatError extends Data.TaggedError("ConcatError")<{ * readonly reason: string @@ -2314,9 +2262,7 @@ const flatMapConcurrent = < * * // Create a channel that outputs numbers and terminates with sum * const numberChannel = Channel.fromIterable([1, 2, 3]).pipe( - * Channel.concatWith((sum: void) => - * Channel.succeed(`Completed processing`) - * ) + * Channel.concatWith((sum: void) => Channel.succeed(`Completed processing`)) * ) * * // Concatenates additional channel based on completion value @@ -2420,9 +2366,7 @@ export const concatWith: { * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Data } from "effect" + * import { Channel, Data } from "effect" * * class ConcatError extends Data.TaggedError("ConcatError")<{ * readonly reason: string @@ -2727,9 +2671,7 @@ export const orElseIfEmpty: { * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Data } from "effect" + * import { Channel, Data } from "effect" * * class FlattenError extends Data.TaggedError("FlattenError")<{ * readonly cause: string @@ -2783,9 +2725,7 @@ export const flatten = < * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Data } from "effect" + * import { Channel, Data } from "effect" * * class FlattenError extends Data.TaggedError("FlattenError")<{ * readonly message: string @@ -2872,7 +2812,6 @@ export const flattenTake = < * @example * ```ts * import { Channel } from "effect" - * import { Effect } from "effect" * * // Create a channel that outputs values * const sourceChannel = Channel.fromIterable([1, 2, 3, 4, 5]) @@ -3008,7 +2947,6 @@ export const schedule: { * @example * ```ts * import { Channel } from "effect" - * import { Effect } from "effect" * * // Create a channel with mixed numbers * const numbersChannel = Channel.fromIterable([1, 2, 3, 4, 5, 6, 7, 8]) @@ -3019,7 +2957,8 @@ export const schedule: { * * // Filter with type refinement * const mixedChannel = Channel.fromIterable([1, "hello", 2, "world", 3]) - * const numbersOnlyChannel = Channel.filter(mixedChannel, + * const numbersOnlyChannel = Channel.filter( + * mixedChannel, * (value): value is number => typeof value === "number" * ) * // Outputs: 1, 2, 3 (all typed as numbers) @@ -3062,9 +3001,7 @@ export const filter: { * * @example * ```ts - * import { Array } from "effect" - * import { Filter } from "effect" - * import { Channel } from "effect" + * import { Array, Channel, Filter } from "effect" * * const nonEmptyArrayFilter: Filter.Filter< * Array, @@ -3147,8 +3084,7 @@ export const filterArrayEffect: { * * @example * ```ts - * import { Channel } from "effect" - * import { Effect } from "effect" + * import { Channel, Effect } from "effect" * * // Create a channel with numbers * const numbersChannel = Channel.fromIterable([1, 2, 3, 4]) @@ -3169,10 +3105,11 @@ export const filterArrayEffect: { * const asyncMapAccum = Channel.mapAccum( * numbersChannel, * () => "", - * (acc, value) => Effect.gen(function* () { - * const newAcc = acc + value.toString() - * return [newAcc, [`${value}-processed`, newAcc]] as const - * }) + * (acc, value) => + * Effect.gen(function*() { + * const newAcc = acc + value.toString() + * return [newAcc, [`${value}-processed`, newAcc]] as const + * }) * ) * ``` * @@ -3289,7 +3226,6 @@ export const mapAccum: { * @example * ```ts * import { Channel } from "effect" - * import { Effect } from "effect" * * // Create a channel with numbers * const numbersChannel = Channel.fromIterable([1, 2, 3, 4, 5]) @@ -3301,8 +3237,10 @@ export const mapAccum: { * * // Scan with string concatenation * const wordsChannel = Channel.fromIterable(["hello", "world", "from", "effect"]) - * const sentenceChannel = Channel.scan(wordsChannel, "", (sentence, word) => - * sentence === "" ? word : `${sentence} ${word}` + * const sentenceChannel = Channel.scan( + * wordsChannel, + * "", + * (sentence, word) => sentence === "" ? word : `${sentence} ${word}` * ) * // Outputs: "", "hello", "hello world", "hello world from", "hello world from effect" * ``` @@ -3345,9 +3283,7 @@ export const scan: { * * @example * ```ts - * import { Channel } from "effect" - * import { Effect } from "effect" - * import { Data } from "effect" + * import { Channel, Data, Effect } from "effect" * * class ScanError extends Data.TaggedError("ScanError")<{ * readonly reason: string @@ -3360,11 +3296,12 @@ export const scan: { * const asyncScanChannel = Channel.scanEffect( * numbersChannel, * "", - * (acc, value) => Effect.gen(function* () { - * // Simulate async work - * yield* Effect.sleep("10 millis") - * return acc + value.toString() - * }) + * (acc, value) => + * Effect.gen(function*() { + * // Simulate async work + * yield* Effect.sleep("10 millis") + * return acc + value.toString() + * }) * ) * // Outputs: "", "1", "12", "123", "1234" * @@ -3435,9 +3372,7 @@ export const scanEffect: { * * @example * ```ts - * import { Effect, Cause } from "effect" - * import { Channel } from "effect" - * import { Data } from "effect" + * import { Cause, Channel, Data } from "effect" * * class ProcessError extends Data.TaggedError("ProcessError")<{ * readonly reason: string @@ -3448,7 +3383,9 @@ export const scanEffect: { * }> {} * * // Create a failing channel - * const failingChannel = Channel.fail(new ProcessError({ reason: "network error" })) + * const failingChannel = Channel.fail( + * new ProcessError({ reason: "network error" }) + * ) * * // Catch the cause and provide recovery * const recoveredChannel = Channel.catchCause(failingChannel, (cause) => { @@ -4106,9 +4043,7 @@ export const mapError: { * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Data } from "effect" + * import { Channel, Data } from "effect" * * class ValidationError extends Data.TaggedError("ValidationError")<{ * readonly field: string @@ -4237,9 +4172,7 @@ export const retry: { * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Data } from "effect" + * import { Channel, Data } from "effect" * * class SwitchError extends Data.TaggedError("SwitchError")<{ * readonly reason: string @@ -4249,8 +4182,9 @@ export const retry: { * const numberChannel = Channel.fromIterable([1, 2, 3]) * * // Switch to new channels based on each value - * const switchedChannel = Channel.switchMap(numberChannel, (n) => - * Channel.fromIterable([`value-${n}`]) + * const switchedChannel = Channel.switchMap( + * numberChannel, + * (n) => Channel.fromIterable([`value-${n}`]) * ) * * // Outputs: "value-1", "value-2", "value-3" @@ -4356,9 +4290,7 @@ export const switchMap: { * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Data } from "effect" + * import { Channel, Data } from "effect" * * class MergeAllError extends Data.TaggedError("MergeAllError")<{ * readonly reason: string @@ -4525,13 +4457,13 @@ export const mergeAll: { * * @example * ```ts - * import { Channel } from "effect" + * import type { Channel } from "effect" * * // Different halt strategies for channel merging - * const leftFirst: Channel.HaltStrategy = "left" // Stop when left channel halts - * const rightFirst: Channel.HaltStrategy = "right" // Stop when right channel halts - * const both: Channel.HaltStrategy = "both" // Stop when both channels halt - * const either: Channel.HaltStrategy = "either" // Stop when either channel halts + * const leftFirst: Channel.HaltStrategy = "left" // Stop when left channel halts + * const rightFirst: Channel.HaltStrategy = "right" // Stop when right channel halts + * const both: Channel.HaltStrategy = "both" // Stop when both channels halt + * const either: Channel.HaltStrategy = "either" // Stop when either channel halts * ``` * * @since 2.0.0 @@ -4545,9 +4477,7 @@ export type HaltStrategy = "left" | "right" | "both" | "either" * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Data } from "effect" + * import { Channel, Data } from "effect" * * class MergeError extends Data.TaggedError("MergeError")<{ * readonly source: string @@ -4863,9 +4793,7 @@ export const encodeText = (): Channel< * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Data } from "effect" + * import { Channel, Data } from "effect" * * class PipeError extends Data.TaggedError("PipeError")<{ * readonly stage: string @@ -4912,9 +4840,7 @@ export const pipeTo: { * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Data } from "effect" + * import { Channel, Data } from "effect" * * class SourceError extends Data.TaggedError("SourceError")<{ * readonly code: number @@ -4975,10 +4901,7 @@ export const pipeToOrFail: { * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Data } from "effect" - * import { Scope } from "effect" + * import { Channel, Data, Effect } from "effect" * * class UnwrapError extends Data.TaggedError("UnwrapError")<{ * readonly reason: string @@ -5027,9 +4950,7 @@ export const scoped = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Data } from "effect" + * import { Channel, Data, Effect } from "effect" * * class EmbedError extends Data.TaggedError("EmbedError")<{ * readonly stage: string @@ -5039,8 +4960,9 @@ export const scoped = ( * const baseChannel = Channel.fromIterable([1, 2, 3]) * * // Embed input handling - simplified example - * const embeddedChannel = Channel.embedInput(baseChannel, (_upstream) => - * Effect.void + * const embeddedChannel = Channel.embedInput( + * baseChannel, + * (_upstream) => Effect.void * ) * ``` * @@ -5261,10 +5183,7 @@ export const onError: { * * @example * ```ts - * import { Effect, Exit } from "effect" - * import { Channel } from "effect" - * import { Console } from "effect" - * import { Data } from "effect" + * import { Channel, Console, Data, Exit } from "effect" * * class ExitError extends Data.TaggedError("ExitError")<{ * readonly stage: string @@ -5384,10 +5303,7 @@ export const onEnd: { * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Console } from "effect" - * import { Data } from "effect" + * import { Channel, Console, Data } from "effect" * * class EnsureError extends Data.TaggedError("EnsureError")<{ * readonly operation: string @@ -5397,7 +5313,8 @@ export const onEnd: { * const dataChannel = Channel.fromIterable([1, 2, 3]) * * // Ensure cleanup always runs - * const channelWithCleanup = Channel.ensuring(dataChannel, + * const channelWithCleanup = Channel.ensuring( + * dataChannel, * Console.log("Cleanup executed regardless of success or failure") * ) * ``` @@ -5853,9 +5770,7 @@ export const bindTo: { * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Data } from "effect" + * import { Channel, Data } from "effect" * * class CountError extends Data.TaggedError("CountError")<{ * readonly reason: string @@ -5882,9 +5797,7 @@ export const runCount = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Data } from "effect" + * import { Channel, Data } from "effect" * * class DrainError extends Data.TaggedError("DrainError")<{ * readonly stage: string @@ -5892,7 +5805,10 @@ export const runCount = ( * * // Create a channel that outputs elements and completes with a result * const resultChannel = Channel.fromIterable([1, 2, 3]) - * const completedChannel = Channel.concatWith(resultChannel, () => Channel.succeed("completed")) + * const completedChannel = Channel.concatWith( + * resultChannel, + * () => Channel.succeed("completed") + * ) * * // Drain all elements and get only the final result * const drainEffect = Channel.runDrain(completedChannel) @@ -5912,10 +5828,7 @@ export const runDrain = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Console } from "effect" - * import { Data } from "effect" + * import { Channel, Console, Data } from "effect" * * class ForEachError extends Data.TaggedError("ForEachError")<{ * readonly element: unknown @@ -5925,8 +5838,9 @@ export const runDrain = ( * const numbersChannel = Channel.fromIterable([1, 2, 3]) * * // Run forEach to log each element - * const forEachEffect = Channel.runForEach(numbersChannel, (n) => - * Console.log(`Processing: ${n}`) + * const forEachEffect = Channel.runForEach( + * numbersChannel, + * (n) => Console.log(`Processing: ${n}`) * ) * * // Logs: "Processing: 1", "Processing: 2", "Processing: 3" @@ -5987,9 +5901,7 @@ export const runForEachWhile: { * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Data } from "effect" + * import { Channel, Data } from "effect" * * class CollectError extends Data.TaggedError("CollectError")<{ * readonly reason: string @@ -6073,9 +5985,7 @@ export const runLast = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Data } from "effect" + * import { Channel, Data } from "effect" * * class FoldError extends Data.TaggedError("FoldError")<{ * readonly operation: string @@ -6171,10 +6081,7 @@ export const runFoldEffect: { * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Data } from "effect" - * import { Scope } from "effect" + * import { Channel, Data, Effect } from "effect" * * class PullError extends Data.TaggedError("PullError")<{ * readonly step: string @@ -6222,10 +6129,7 @@ export const toPull: ( * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Data } from "effect" - * import { Scope } from "effect" + * import { Channel, Data, Effect, Scope } from "effect" * * class ScopedPullError extends Data.TaggedError("ScopedPullError")<{ * readonly reason: string @@ -6235,7 +6139,7 @@ export const toPull: ( * const numbersChannel = Channel.fromIterable([1, 2, 3]) * * // Convert to Pull with explicit scope - * const scopedPullEffect = Effect.gen(function* () { + * const scopedPullEffect = Effect.gen(function*() { * const scope = yield* Scope.make() * const pull = yield* Channel.toPullScoped(numbersChannel, scope) * return pull @@ -6315,10 +6219,7 @@ export const runIntoQueueArray: { * * @example * ```ts - * import { Effect } from "effect" - * import { Channel } from "effect" - * import { Data } from "effect" - * import { Queue } from "effect" + * import { Channel, Data } from "effect" * * class QueueError extends Data.TaggedError("QueueError")<{ * readonly operation: string diff --git a/packages/effect/src/Chunk.ts b/packages/effect/src/Chunk.ts index 23dab04aaa..a383ca3530 100644 --- a/packages/effect/src/Chunk.ts +++ b/packages/effect/src/Chunk.ts @@ -55,12 +55,11 @@ * * @example * ```ts - * import { Chunk } from "effect" -import { Effect } from "effect" + * import { Chunk, Effect } from "effect" * * // Working with Effects * const processChunk = (chunk: Chunk.Chunk) => - * Effect.gen(function* () { + * Effect.gen(function*() { * const mapped = Chunk.map(chunk, (n) => n * 2) * const filtered = Chunk.filter(mapped, (n) => n > 5) * return Chunk.toReadonlyArray(filtered) @@ -139,8 +138,8 @@ export interface NonEmptyChunk extends Chunk, NonEmptyIterable {} * * @example * ```ts - * import type { Kind } from "effect/types/HKT" * import type { ChunkTypeLambda } from "effect/Chunk" + * import type { Kind } from "effect/types/HKT" * * // Create a Chunk type using the type lambda * type NumberChunk = Kind @@ -209,7 +208,7 @@ const emptyArray: ReadonlyArray = [] * @example * ```ts * import { Chunk } from "effect" -import * as Equivalence from "effect/Equivalence" + * import * as Equivalence from "effect/Equivalence" * * const chunk1 = Chunk.make(1, 2, 3) * const chunk2 = Chunk.make(1, 2, 3) @@ -558,7 +557,6 @@ export const reverse: >(self: S) => Chunk.With(self: ReadonlyArray): Chunk => * @example * ```ts * import { Chunk } from "effect" -import * as Array from "effect/Array" + * import * as Array from "effect/Array" * * const nonEmptyArray = Array.make(1, 2, 3, 4, 5) * const chunk = Chunk.fromNonEmptyArrayUnsafe(nonEmptyArray) @@ -904,7 +902,10 @@ export const dropWhile: { * ```ts * import { Chunk } from "effect" * - * const result = Chunk.make(1, 2).pipe(Chunk.prependAll(Chunk.make("a", "b")), Chunk.toArray) + * const result = Chunk.make(1, 2).pipe( + * Chunk.prependAll(Chunk.make("a", "b")), + * Chunk.toArray + * ) * * console.log(result) * // [ "a", "b", 1, 2 ] @@ -931,7 +932,10 @@ export const prependAll: { * ```ts * import { Chunk } from "effect" * - * const result = Chunk.make(1, 2).pipe(Chunk.appendAll(Chunk.make("a", "b")), Chunk.toArray) + * const result = Chunk.make(1, 2).pipe( + * Chunk.appendAll(Chunk.make("a", "b")), + * Chunk.toArray + * ) * * console.log(result) * // [ 1, 2, "a", "b" ] @@ -1116,7 +1120,10 @@ export const compact = (self: Chunk>): Chunk => filterMap(self, * * // Flattening nested arrays * const words = Chunk.make("hello", "world") - * const letters = Chunk.flatMap(words, (word) => Chunk.fromIterable(word.split(""))) + * const letters = Chunk.flatMap( + * words, + * (word) => Chunk.fromIterable(word.split("")) + * ) * console.log(Chunk.toArray(letters)) // ["h", "e", "l", "l", "o", "w", "o", "r", "l", "d"] * * // With index parameter @@ -1332,7 +1339,6 @@ export const isNonEmpty = (self: Chunk): self is NonEmptyChunk => self. * @example * ```ts * import { Chunk } from "effect" - * import * as Option from "effect/Option" * * console.log(Chunk.head(Chunk.empty())) // { _tag: "None" } * console.log(Chunk.head(Chunk.make(1, 2, 3))) // { _tag: "Some", value: 1 } @@ -1399,7 +1405,6 @@ export const headNonEmpty: (self: NonEmptyChunk) => A = headUnsafe * @example * ```ts * import { Chunk } from "effect" - * import * as Option from "effect/Option" * * console.log(Chunk.last(Chunk.empty())) // { _tag: "None" } * console.log(Chunk.last(Chunk.make(1, 2, 3))) // { _tag: "Some", value: 3 } @@ -1465,7 +1470,7 @@ export const lastNonEmpty: (self: NonEmptyChunk) => A = lastUnsafe * * @example * ```ts - * import { Chunk } from "effect" + * import type { Chunk } from "effect" * * // Extract the element type from a Chunk * declare const chunk: Chunk.Chunk @@ -1485,7 +1490,7 @@ export declare namespace Chunk { * * @example * ```ts - * import { Chunk } from "effect" + * import type { Chunk } from "effect" * * declare const numberChunk: Chunk.Chunk * declare const stringChunk: Chunk.Chunk @@ -1504,7 +1509,7 @@ export declare namespace Chunk { * * @example * ```ts - * import { Chunk } from "effect" + * import type { Chunk } from "effect" * * declare const regularChunk: Chunk.Chunk * declare const nonEmptyChunk: Chunk.NonEmptyChunk @@ -1523,14 +1528,26 @@ export declare namespace Chunk { * * @example * ```ts - * import { Chunk } from "effect" + * import type { Chunk } from "effect" * * declare const emptyChunk: Chunk.Chunk * declare const nonEmptyChunk: Chunk.NonEmptyChunk * - * type Result1 = Chunk.Chunk.OrNonEmpty // Chunk.Chunk - * type Result2 = Chunk.Chunk.OrNonEmpty // Chunk.NonEmptyChunk - * type Result3 = Chunk.Chunk.OrNonEmpty // Chunk.NonEmptyChunk + * type Result1 = Chunk.Chunk.OrNonEmpty< + * typeof emptyChunk, + * typeof emptyChunk, + * string + * > // Chunk.Chunk + * type Result2 = Chunk.Chunk.OrNonEmpty< + * typeof emptyChunk, + * typeof nonEmptyChunk, + * string + * > // Chunk.NonEmptyChunk + * type Result3 = Chunk.Chunk.OrNonEmpty< + * typeof nonEmptyChunk, + * typeof emptyChunk, + * string + * > // Chunk.NonEmptyChunk * ``` * * @category types @@ -1546,14 +1563,26 @@ export declare namespace Chunk { * * @example * ```ts - * import { Chunk } from "effect" + * import type { Chunk } from "effect" * * declare const emptyChunk: Chunk.Chunk * declare const nonEmptyChunk: Chunk.NonEmptyChunk * - * type Result1 = Chunk.Chunk.AndNonEmpty // Chunk.Chunk - * type Result2 = Chunk.Chunk.AndNonEmpty // Chunk.Chunk - * type Result3 = Chunk.Chunk.AndNonEmpty // Chunk.NonEmptyChunk + * type Result1 = Chunk.Chunk.AndNonEmpty< + * typeof emptyChunk, + * typeof emptyChunk, + * string + * > // Chunk.Chunk + * type Result2 = Chunk.Chunk.AndNonEmpty< + * typeof emptyChunk, + * typeof nonEmptyChunk, + * string + * > // Chunk.Chunk + * type Result3 = Chunk.Chunk.AndNonEmpty< + * typeof nonEmptyChunk, + * typeof nonEmptyChunk, + * string + * > // Chunk.NonEmptyChunk * ``` * * @category types @@ -1569,7 +1598,7 @@ export declare namespace Chunk { * * @example * ```ts - * import { Chunk } from "effect" + * import type { Chunk } from "effect" * * declare const nestedChunk: Chunk.Chunk> * declare const nestedNonEmpty: Chunk.NonEmptyChunk> @@ -1622,8 +1651,8 @@ export const map: { * * const chunk = Chunk.make(1, 2, 3, 4, 5) * const [finalState, mapped] = Chunk.mapAccum(chunk, 0, (state, current) => [ - * state + current, // accumulate sum - * state + current // output running sum + * state + current, // accumulate sum + * state + current // output running sum * ]) * * console.log(finalState) // 15 (final accumulated sum) @@ -1670,7 +1699,10 @@ export const mapAccum: { * * // With refinement * const mixed = Chunk.make("hello", 42, "world", 100) - * const [strings, numbers] = Chunk.partition(mixed, (x): x is number => typeof x === "number") + * const [strings, numbers] = Chunk.partition( + * mixed, + * (x): x is number => typeof x === "number" + * ) * console.log(Chunk.toArray(strings)) // ["hello", "world"] * console.log(Chunk.toArray(numbers)) // [42, 100] * ``` @@ -1720,8 +1752,9 @@ export const partition: { * * // All successes * const validNumbers = Chunk.make("1", "2", "3") - * const [noErrors, allNumbers] = Chunk.partitionMap(validNumbers, (str) => - * Result.succeed(parseInt(str)) + * const [noErrors, allNumbers] = Chunk.partitionMap( + * validNumbers, + * (str) => Result.succeed(parseInt(str)) * ) * console.log(Chunk.toArray(noErrors)) // [] * console.log(Chunk.toArray(allNumbers)) // [1, 2, 3] @@ -1797,7 +1830,7 @@ export const size = (self: Chunk): number => self.length * @example * ```ts * import { Chunk } from "effect" -import * as Order from "effect/Order" + * import * as Order from "effect/Order" * * const numbers = Chunk.make(3, 1, 4, 1, 5, 9, 2, 6) * const sorted = Chunk.sort(numbers, Order.number) @@ -1830,7 +1863,7 @@ export const sort: { * @example * ```ts * import { Chunk } from "effect" -import * as Order from "effect/Order" + * import * as Order from "effect/Order" * * const people = Chunk.make( * { name: "Alice", age: 30 }, @@ -2011,7 +2044,6 @@ export const splitWhere: { * @example * ```ts * import { Chunk } from "effect" - * import * as Option from "effect/Option" * * const chunk = Chunk.make(1, 2, 3, 4) * console.log(Chunk.tail(chunk)) // Option.some(Chunk.make(2, 3, 4)) @@ -2209,7 +2241,11 @@ export const dedupeAdjacent = (self: Chunk): Chunk => fromArrayUnsafe(R * ```ts * import { Chunk } from "effect" * - * const pairs = Chunk.make([1, "a"] as const, [2, "b"] as const, [3, "c"] as const) + * const pairs = Chunk.make( + * [1, "a"] as const, + * [2, "b"] as const, + * [3, "c"] as const + * ) * const [numbers, letters] = Chunk.unzip(pairs) * console.log(Chunk.toArray(numbers)) // [1, 2, 3] * console.log(Chunk.toArray(letters)) // ["a", "b", "c"] @@ -2466,13 +2502,17 @@ export const contains: { * const chunk = Chunk.make({ id: 1, name: "Alice" }, { id: 2, name: "Bob" }) * * // Custom equivalence by id - * const containsById = Chunk.containsWith<{ id: number; name: string }>((a, b) => a.id === b.id) + * const containsById = Chunk.containsWith<{ id: number; name: string }>((a, b) => + * a.id === b.id + * ) * console.log(containsById(chunk, { id: 1, name: "Different" })) // true * console.log(containsById(chunk, { id: 3, name: "Charlie" })) // false * * // Case-insensitive string comparison * const words = Chunk.make("Apple", "Banana", "Cherry") - * const containsCaseInsensitive = Chunk.containsWith((a, b) => a.toLowerCase() === b.toLowerCase()) + * const containsCaseInsensitive = Chunk.containsWith((a, b) => + * a.toLowerCase() === b.toLowerCase() + * ) * console.log(containsCaseInsensitive(words, "apple")) // true * console.log(containsCaseInsensitive(words, "grape")) // false * ``` @@ -2493,8 +2533,7 @@ export const containsWith: ( * * @example * ```ts - * import { Chunk } from "effect" - * import { Option } from "effect" + * import { Chunk, Option } from "effect" * * const chunk = Chunk.make(1, 2, 3, 4, 5) * const result = Chunk.findFirst(chunk, (n) => n > 3) @@ -2507,7 +2546,10 @@ export const containsWith: ( * * // With type refinement * const mixed = Chunk.make(1, "hello", 2, "world", 3) - * const firstString = Chunk.findFirst(mixed, (x): x is string => typeof x === "string") + * const firstString = Chunk.findFirst( + * mixed, + * (x): x is string => typeof x === "string" + * ) * console.log(Option.getOrElse(firstString, () => "")) // "hello" * ``` * @@ -2751,7 +2793,11 @@ export const reduce: { * * // String building (right to left) * const words = Chunk.make("a", "b", "c") - * const reversed = Chunk.reduceRight(words, "", (acc, word, i) => acc + `${i}:${word} `) + * const reversed = Chunk.reduceRight( + * words, + * "", + * (acc, word, i) => acc + `${i}:${word} ` + * ) * console.log(reversed) // "2:c 1:b 0:a " * * // Subtract from right to left @@ -2779,14 +2825,18 @@ export const reduceRight: { * const chunk2 = Chunk.make({ id: 1, name: "Alice" }, { id: 3, name: "Charlie" }) * * // Custom equivalence by id - * const byId = Chunk.differenceWith<{ id: number; name: string }>((a, b) => a.id === b.id) + * const byId = Chunk.differenceWith<{ id: number; name: string }>((a, b) => + * a.id === b.id + * ) * const result = byId(chunk1, chunk2) * console.log(Chunk.toArray(result)) // [{ id: 2, name: "Bob" }] * * // String comparison case-insensitive * const words1 = Chunk.make("Apple", "Banana", "Cherry") * const words2 = Chunk.make("apple", "grape") - * const caseInsensitive = Chunk.differenceWith((a, b) => a.toLowerCase() === b.toLowerCase()) + * const caseInsensitive = Chunk.differenceWith((a, b) => + * a.toLowerCase() === b.toLowerCase() + * ) * const wordDiff = caseInsensitive(words1, words2) * console.log(Chunk.toArray(wordDiff)) // ["Banana", "Cherry"] * ``` diff --git a/packages/effect/src/ConfigProvider.ts b/packages/effect/src/ConfigProvider.ts index e92736ef84..bfd2eea94e 100644 --- a/packages/effect/src/ConfigProvider.ts +++ b/packages/effect/src/ConfigProvider.ts @@ -4,14 +4,14 @@ import * as Data from "./Data.ts" import * as Effect from "./Effect.ts" +import * as FileSystem from "./FileSystem.ts" import { format } from "./Formatter.ts" import { dual, flow } from "./Function.ts" import { PipeInspectableProto } from "./internal/core.ts" import * as Layer from "./Layer.ts" +import * as Path_ from "./Path.ts" import type { Pipeable } from "./Pipeable.ts" -import * as FileSystem from "./platform/FileSystem.ts" -import * as Path_ from "./platform/Path.ts" -import type { PlatformError } from "./platform/PlatformError.ts" +import type { PlatformError } from "./PlatformError.ts" import * as Predicate from "./Predicate.ts" import type { Scope } from "./Scope.ts" import * as ServiceMap from "./ServiceMap.ts" diff --git a/packages/effect/src/Cron.ts b/packages/effect/src/Cron.ts index 6cd9c69a85..7f779dfec7 100644 --- a/packages/effect/src/Cron.ts +++ b/packages/effect/src/Cron.ts @@ -366,8 +366,7 @@ const CronParseErrorTypeId = "~effect/time/Cron/CronParseError" * * @example * ```ts - * import { Cron } from "effect" - * import { Result } from "effect" + * import { Cron, Result } from "effect" * * const result = Cron.parse("invalid expression") * if (Result.isFailure(result)) { @@ -400,8 +399,7 @@ export class CronParseError extends Data.TaggedError("CronParseError")<{ * * @example * ```ts - * import { Cron } from "effect" - * import { Result } from "effect" + * import { Cron, Result } from "effect" * * const result = Cron.parse("invalid cron expression") * if (Result.isFailure(result)) { @@ -425,8 +423,7 @@ export const isCronParseError = (u: unknown): u is CronParseError => hasProperty * * @example * ```ts - * import { Cron } from "effect" - * import { Result } from "effect" + * import { Cron, Result } from "effect" * import * as assert from "node:assert" * * // At 04:00 on every day-of-month from 8 through 14. @@ -511,8 +508,7 @@ export const parseUnsafe = (cron: string, tz?: DateTime.TimeZone | string): Cron * * @example * ```ts - * import { Cron } from "effect" - * import { Result } from "effect" + * import { Cron, Result } from "effect" * * const cron = Result.getOrThrow(Cron.parse("0 0 4 8-14 * *")) * @@ -578,8 +574,7 @@ const daysInMonth = (date: Date): number => * * @example * ```ts - * import { Cron } from "effect" - * import { Result } from "effect" + * import { Cron, Result } from "effect" * * const cron = Result.getOrThrow(Cron.parse("0 0 4 8-14 * *")) * @@ -727,8 +722,7 @@ export const next = (cron: Cron, now?: DateTime.DateTime.Input): Date => { * * @example * ```ts - * import { Cron } from "effect" - * import { Result } from "effect" + * import { Cron, Result } from "effect" * * const cron = Result.getOrThrow(Cron.parse("0 0 9 * * 1-5")) // 9 AM weekdays * diff --git a/packages/effect/src/Data.ts b/packages/effect/src/Data.ts index 388cd119c8..a11ed524af 100644 --- a/packages/effect/src/Data.ts +++ b/packages/effect/src/Data.ts @@ -23,8 +23,7 @@ import type { Unify } from "./types/Unify.ts" * @example * ```ts * import * as assert from "node:assert" - * import { Equal } from "effect" - * import { Data } from "effect" + * import { Data, Equal } from "effect" * * class Person extends Data.Class<{ readonly name: string }> {} * @@ -56,8 +55,7 @@ export const Class: new = {}>( * @example * ```ts * import * as assert from "node:assert" - * import { Equal } from "effect" - * import { Data } from "effect" + * import { Data, Equal } from "effect" * * class Person extends Data.TaggedClass("Person")<{ readonly name: string }> {} * @@ -108,12 +106,24 @@ export const TaggedClass = ( * * // This is equivalent to the union type: * type HttpErrorExpanded = - * | { readonly _tag: "BadRequest"; readonly status: 400; readonly message: string } - * | { readonly _tag: "NotFound"; readonly status: 404; readonly message: string } - * | { readonly _tag: "InternalError"; readonly status: 500; readonly details: string } + * | { + * readonly _tag: "BadRequest" + * readonly status: 400 + * readonly message: string + * } + * | { + * readonly _tag: "NotFound" + * readonly status: 404 + * readonly message: string + * } + * | { + * readonly _tag: "InternalError" + * readonly status: 500 + * readonly details: string + * } * * // Usage with constructors - * const { BadRequest, NotFound, InternalError } = Data.taggedEnum() + * const { BadRequest, InternalError, NotFound } = Data.taggedEnum() * * const error: HttpError = BadRequest({ status: 400, message: "Invalid request" }) * console.log(error._tag) // "BadRequest" @@ -151,7 +161,7 @@ type UntaggedChildren = true extends ChildrenAreTagged * import { Data } from "effect" * * // Basic tagged enum usage - * const { Success, Failure } = Data.taggedEnum< + * const { Failure, Success } = Data.taggedEnum< * | { readonly _tag: "Success"; readonly value: number } * | { readonly _tag: "Failure"; readonly error: string } * >() @@ -172,7 +182,7 @@ export declare namespace TaggedEnum { * * @example * ```ts - * import { Data } from "effect" + * import type { Data } from "effect" * * // Define a tagged enum with generic parameters * interface MyTaggedEnum extends Data.TaggedEnum.WithGenerics<2> { @@ -206,7 +216,7 @@ export declare namespace TaggedEnum { * * @example * ```ts - * import { Data } from "effect" + * import type { Data } from "effect" * * // Define a generic Option type * type Option = Data.TaggedEnum<{ @@ -260,7 +270,7 @@ export declare namespace TaggedEnum { * * @example * ```ts - * import { Data } from "effect" + * import type { Data } from "effect" * * type Result = * | { readonly _tag: "Success"; readonly value: number } @@ -296,7 +306,7 @@ export declare namespace TaggedEnum { * * @example * ```ts - * import { Data } from "effect" + * import type { Data } from "effect" * * type Result = * | { readonly _tag: "Success"; readonly value: number } @@ -335,7 +345,7 @@ export declare namespace TaggedEnum { * | { readonly _tag: "BadRequest"; readonly message: string } * | { readonly _tag: "NotFound"; readonly resource: string } * - * const { BadRequest, NotFound, $is, $match } = Data.taggedEnum() + * const { $is, $match, BadRequest, NotFound } = Data.taggedEnum() * * const error = BadRequest({ message: "Invalid input" }) * @@ -416,7 +426,7 @@ export declare namespace TaggedEnum { * readonly taggedEnum: Result * } * - * const { Failure, Success, $is, $match } = Data.taggedEnum() + * const { $is, $match, Failure, Success } = Data.taggedEnum() * * const stringResult = Success({ value: "hello" }) * const numberResult = Failure({ error: 404 }) @@ -496,8 +506,16 @@ export declare namespace TaggedEnum { * import { Data } from "effect" * * const { BadRequest, NotFound } = Data.taggedEnum< - * | { readonly _tag: "BadRequest"; readonly status: 400; readonly message: string } - * | { readonly _tag: "NotFound"; readonly status: 404; readonly message: string } + * | { + * readonly _tag: "BadRequest" + * readonly status: 400 + * readonly message: string + * } + * | { + * readonly _tag: "NotFound" + * readonly status: 404 + * readonly message: string + * } * >() * * const notFound = NotFound({ status: 404, message: "Not Found" }) @@ -622,12 +640,11 @@ function taggedMatch< * * @example * ```ts - * import { Effect, Exit } from "effect" - * import { Data } from "effect" + * import { Data, Effect } from "effect" * * class NetworkError extends Data.Error<{ code: number; message: string }> {} * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * yield* new NetworkError({ code: 500, message: "Server error" }) * }) * @@ -651,8 +668,7 @@ export const Error: new = {}>( * * @example * ```ts - * import { Effect, pipe } from "effect" - * import { Data } from "effect" + * import { Data, Effect, pipe } from "effect" * * class NetworkError extends Data.TaggedError("NetworkError")<{ * code: number @@ -664,14 +680,15 @@ export const Error: new = {}>( * message: string * }> {} * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * yield* new NetworkError({ code: 500, message: "Server error" }) * }) * * const result = pipe( * program, - * Effect.catchTag("NetworkError", (error) => - * Effect.succeed(`Network error: ${error.message}`) + * Effect.catchTag( + * "NetworkError", + * (error) => Effect.succeed(`Network error: ${error.message}`) * ) * ) * ``` diff --git a/packages/effect/src/DateTime.ts b/packages/effect/src/DateTime.ts index d8c8b52938..4088ec561d 100644 --- a/packages/effect/src/DateTime.ts +++ b/packages/effect/src/DateTime.ts @@ -400,8 +400,7 @@ export const Equivalence: equivalence.Equivalence = Internal.Equivalen * * @example * ```ts - * import { DateTime } from "effect" - * import { Array } from "effect" + * import { Array, DateTime } from "effect" * * const dates = [ * DateTime.makeUnsafe("2024-03-01"), diff --git a/packages/effect/src/Deferred.ts b/packages/effect/src/Deferred.ts index 291e13d7b6..e18d4d7f07 100644 --- a/packages/effect/src/Deferred.ts +++ b/packages/effect/src/Deferred.ts @@ -17,17 +17,15 @@ * * @example * ```ts - * import { Effect } from "effect" - * import { Deferred } from "effect" - * import { Fiber } from "effect" + * import { Deferred, Effect, Fiber } from "effect" * * // Basic usage: coordinate between fibers - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const deferred = yield* Deferred.make() * * // Fiber 1: waits for the value * const waiter = yield* Effect.forkChild( - * Effect.gen(function* () { + * Effect.gen(function*() { * const value = yield* Deferred.await(deferred) * console.log("Received:", value) * return value @@ -36,7 +34,7 @@ * * // Fiber 2: sets the value after a delay * const setter = yield* Effect.forkChild( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Effect.sleep("1 second") * yield* Deferred.succeed(deferred, "Hello from setter!") * }) @@ -48,15 +46,15 @@ * }) * * // Producer-consumer pattern - * const producerConsumer = Effect.gen(function* () { - * const buffer = yield* Deferred.make() + * const producerConsumer = Effect.gen(function*() { + * const buffer = yield* Deferred.make, never>() * - * const producer = Effect.gen(function* () { + * const producer = Effect.gen(function*() { * const data = [1, 2, 3, 4, 5] * yield* Deferred.succeed(buffer, data) * }) * - * const consumer = Effect.gen(function* () { + * const consumer = Effect.gen(function*() { * const data = yield* Deferred.await(buffer) * return data.reduce((sum, n) => sum + n, 0) * }) @@ -91,18 +89,16 @@ const TypeId = "~effect/Deferred" * * @example * ```ts - * import { Effect } from "effect" - * import { Deferred } from "effect" - * import { Fiber } from "effect" + * import { Deferred, Effect, Fiber } from "effect" * * // Create and use a Deferred for inter-fiber communication - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * // Create a Deferred that will hold a string value * const deferred: Deferred.Deferred = yield* Deferred.make() * * // Fork a fiber that will set the deferred value * const producer = yield* Effect.forkChild( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Effect.sleep("100 millis") * yield* Deferred.succeed(deferred, "Hello, World!") * }) @@ -110,7 +106,7 @@ const TypeId = "~effect/Deferred" * * // Fork a fiber that will await the deferred value * const consumer = yield* Effect.forkChild( - * Effect.gen(function* () { + * Effect.gen(function*() { * const value = yield* Deferred.await(deferred) * console.log("Received:", value) * return value @@ -185,8 +181,7 @@ export const makeUnsafe = (): Deferred => { * * @example * ```ts - * import { Effect } from "effect" - * import { Deferred } from "effect" + * import { Deferred, Effect } from "effect" * * const program = Effect.gen(function*() { * const deferred = yield* Deferred.make() @@ -219,8 +214,7 @@ export { * * @example * ```ts - * import { Effect } from "effect" - * import { Deferred } from "effect" + * import { Deferred, Effect } from "effect" * * const program = Effect.gen(function*() { * const deferred = yield* Deferred.make() @@ -246,8 +240,7 @@ export { * * @example * ```ts - * import { Effect } from "effect" - * import { Deferred } from "effect" + * import { Deferred, Effect } from "effect" * * const program = Effect.gen(function*() { * const deferred = yield* Deferred.make() @@ -277,8 +270,7 @@ export const complete: { * * @example * ```ts - * import { Effect } from "effect" - * import { Deferred } from "effect" + * import { Deferred, Effect } from "effect" * * const program = Effect.gen(function*() { * const deferred = yield* Deferred.make() @@ -308,8 +300,7 @@ export const completeWith: { * * @example * ```ts - * import { Effect, Exit } from "effect" - * import { Deferred } from "effect" + * import { Deferred, Effect, Exit } from "effect" * * const program = Effect.gen(function*() { * const deferred = yield* Deferred.make() @@ -334,8 +325,7 @@ export const done: { * * @example * ```ts - * import { Effect } from "effect" - * import { Deferred } from "effect" + * import { Deferred, Effect } from "effect" * * const program = Effect.gen(function*() { * const deferred = yield* Deferred.make() @@ -358,8 +348,7 @@ export const fail: { * * @example * ```ts - * import { Effect } from "effect" - * import { Deferred } from "effect" + * import { Deferred, Effect } from "effect" * * const program = Effect.gen(function*() { * const deferred = yield* Deferred.make() @@ -386,12 +375,14 @@ export const failSync: { * * @example * ```ts - * import { Effect, Cause } from "effect" - * import { Deferred } from "effect" + * import { Cause, Deferred, Effect } from "effect" * * const program = Effect.gen(function*() { * const deferred = yield* Deferred.make() - * const success = yield* Deferred.failCause(deferred, Cause.fail("Operation failed")) + * const success = yield* Deferred.failCause( + * deferred, + * Cause.fail("Operation failed") + * ) * console.log(success) // true * }) * ``` @@ -413,12 +404,14 @@ export const failCause: { * * @example * ```ts - * import { Effect, Cause } from "effect" - * import { Deferred } from "effect" + * import { Cause, Deferred, Effect } from "effect" * * const program = Effect.gen(function*() { * const deferred = yield* Deferred.make() - * const success = yield* Deferred.failCauseSync(deferred, () => Cause.fail("Lazy error")) + * const success = yield* Deferred.failCauseSync( + * deferred, + * () => Cause.fail("Lazy error") + * ) * console.log(success) // true * }) * ``` @@ -441,12 +434,14 @@ export const failCauseSync: { * * @example * ```ts - * import { Effect } from "effect" - * import { Deferred } from "effect" + * import { Deferred, Effect } from "effect" * * const program = Effect.gen(function*() { * const deferred = yield* Deferred.make() - * const success = yield* Deferred.die(deferred, new Error("Something went wrong")) + * const success = yield* Deferred.die( + * deferred, + * new Error("Something went wrong") + * ) * console.log(success) // true * }) * ``` @@ -465,12 +460,14 @@ export const die: { * * @example * ```ts - * import { Effect } from "effect" - * import { Deferred } from "effect" + * import { Deferred, Effect } from "effect" * * const program = Effect.gen(function*() { * const deferred = yield* Deferred.make() - * const success = yield* Deferred.dieSync(deferred, () => new Error("Lazy error")) + * const success = yield* Deferred.dieSync( + * deferred, + * () => new Error("Lazy error") + * ) * console.log(success) // true * }) * ``` @@ -494,8 +491,7 @@ export const dieSync: { * * @example * ```ts - * import { Effect } from "effect" - * import { Deferred } from "effect" + * import { Deferred, Effect } from "effect" * * const program = Effect.gen(function*() { * const deferred = yield* Deferred.make() @@ -516,8 +512,7 @@ export const interrupt = (self: Deferred): Effect => * * @example * ```ts - * import { Effect } from "effect" - * import { Deferred } from "effect" + * import { Deferred, Effect } from "effect" * * const program = Effect.gen(function*() { * const deferred = yield* Deferred.make() @@ -544,8 +539,7 @@ export const interruptWith: { * * @example * ```ts - * import { Effect } from "effect" - * import { Deferred } from "effect" + * import { Deferred, Effect } from "effect" * * const program = Effect.gen(function*() { * const deferred = yield* Deferred.make() @@ -578,8 +572,7 @@ export const isDoneUnsafe = (self: Deferred): boolean => self.effect * * @example * ```ts - * import { Effect } from "effect" - * import { Deferred } from "effect" + * import { Deferred, Effect } from "effect" * * const program = Effect.gen(function*() { * const deferred = yield* Deferred.make() @@ -604,8 +597,7 @@ export function poll(self: Deferred): Effect | undefine * * @example * ```ts - * import { Effect } from "effect" - * import { Deferred } from "effect" + * import { Deferred, Effect } from "effect" * * const program = Effect.gen(function*() { * const deferred = yield* Deferred.make() @@ -629,8 +621,7 @@ export const succeed: { * * @example * ```ts - * import { Effect } from "effect" - * import { Deferred } from "effect" + * import { Deferred, Effect } from "effect" * * const program = Effect.gen(function*() { * const deferred = yield* Deferred.make() @@ -659,8 +650,7 @@ export const sync: { * * @example * ```ts - * import { Effect } from "effect" - * import { Deferred } from "effect" + * import { Deferred, Effect } from "effect" * * const deferred = Deferred.makeUnsafe() * const success = Deferred.doneUnsafe(deferred, Effect.succeed(42)) @@ -694,8 +684,7 @@ export const doneUnsafe = (self: Deferred, effect: Effect): bo * * @example * ```ts - * import { Effect } from "effect" - * import { Deferred } from "effect" + * import { Deferred, Effect } from "effect" * * // Define an effect that succeeds * const successEffect = Effect.succeed(42) diff --git a/packages/effect/src/Effect.ts b/packages/effect/src/Effect.ts index 3d8b5b173c..1ad2973cab 100644 --- a/packages/effect/src/Effect.ts +++ b/packages/effect/src/Effect.ts @@ -22,14 +22,13 @@ * * @example * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" + * import { Console, Effect } from "effect" * * // Creating a simple effect * const hello = Effect.succeed("Hello, World!") * * // Composing effects - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const message = yield* hello * yield* Console.log(message) * return message.length @@ -50,7 +49,7 @@ * : Effect.succeed(a / b) * * // Error handling - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const result = yield* divide(10, 2) * console.log("Result:", result) // Result: 5 * return result @@ -149,7 +148,7 @@ const TypeId = core.EffectTypeId * const risky = Effect.fail(new Error("Something went wrong")) * * // Effects can be composed using generator functions - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const value = yield* success * console.log(value) // 42 * return value * 2 @@ -180,8 +179,8 @@ export interface Effect extends Pipeable, Y * 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 program = Effect.gen(function*() { + * const a = yield* effect1 // yields the Effect which implements Yieldable * const b = yield* effect2 * return a + b * }) @@ -218,7 +217,7 @@ export abstract class YieldableClass implements Yieldab * @since 2.0.0 * @example * ```ts - * import { Effect } from "effect" + * import type { Effect } from "effect" * * // EffectUnify is used internally for type unification * // It enables automatic unification of Effect types in unions @@ -237,7 +236,7 @@ export interface EffectUnify { * @since 2.0.0 * @example * ```ts - * import { Effect } from "effect" + * import type { Effect } from "effect" * * // EffectUnifyIgnore is used internally to control type unification * // It prevents certain types from being unified with Effect types @@ -252,7 +251,7 @@ export interface EffectUnifyIgnore { * @since 2.0.0 * @example * ```ts - * import { Effect } from "effect" + * import type { Effect } from "effect" * * // EffectTypeLambda is used for higher-kinded type operations * // It defines the type structure for Effect in higher-kinded contexts @@ -278,7 +277,7 @@ export interface Variance { * @category models * @example * ```ts - * import { Effect } from "effect" + * import type { Effect } from "effect" * * // Extract the success type from an Effect * declare const myEffect: Effect.Effect @@ -293,7 +292,7 @@ export type Success = T extends Effect ? _A * @category models * @example * ```ts - * import { Effect } from "effect" + * import type { Effect } from "effect" * * // Extract the error type from an Effect * declare const myEffect: Effect.Effect @@ -308,7 +307,7 @@ export type Error = T extends Effect ? _E * @category models * @example * ```ts - * import { Effect } from "effect" + * import type { Effect } from "effect" * * // Extract the context/services type from an Effect * declare const myEffect: Effect.Effect @@ -334,10 +333,10 @@ export declare namespace Yieldable { * @category models * @example * ```ts - * import { Effect } from "effect" + * import type { Effect } from "effect" * * // Extract the success type from a Yieldable - * type SuccessType = Effect.Yieldable.Success> // string + * type SuccessType = Effect.Yieldable.Success> // string * ``` */ export type Success = T extends Yieldable ? _A @@ -368,7 +367,7 @@ export const isEffect = (u: unknown): u is Effect => typeof u === * import { Effect } from "effect" * * // Effects are iterable and work with generator functions - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const effect: Effect.Effect = Effect.succeed(42) * * // The effect's iterator is used internally by yield* @@ -440,7 +439,7 @@ export declare namespace All { * @category models * @example * ```ts - * import { Effect } from "effect" + * import type { Effect } from "effect" * * // ReturnIterable computes the return type for Effect.all with iterables * type EffectArray = Array> @@ -459,10 +458,13 @@ export declare namespace All { * @category models * @example * ```ts - * import { Effect } from "effect" + * import type { Effect } from "effect" * * // ReturnTuple computes the return type for Effect.all with tuples - * type EffectTuple = [Effect.Effect, Effect.Effect] + * type EffectTuple = [ + * Effect.Effect, + * Effect.Effect + * ] * type Result = Effect.All.ReturnTuple * // Result: Effect<[string, number], Error, never> * ``` @@ -495,10 +497,13 @@ export declare namespace All { * @category models * @example * ```ts - * import { Effect } from "effect" + * import type { Effect } from "effect" * * // ReturnObject computes the return type for Effect.all with objects - * type EffectRecord = { a: Effect.Effect, b: Effect.Effect } + * type EffectRecord = { + * a: Effect.Effect + * b: Effect.Effect + * } * type Result = Effect.All.ReturnObject * // Result: Effect<{ a: string, b: number }, Error, never> * ``` @@ -527,12 +532,12 @@ export declare namespace All { * @category models * @example * ```ts - * import { Effect } from "effect" + * import type { Effect } from "effect" * * // 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 WithDiscard = Effect.All.IsDiscard // true * type WithoutDiscard = Effect.All.IsDiscard // false * ``` */ @@ -546,7 +551,7 @@ export declare namespace All { * @category models * @example * ```ts - * import { Effect } from "effect" + * import type { Effect } from "effect" * * // Return determines the result type based on input and options * type EffectArray = Array> @@ -616,8 +621,7 @@ export declare namespace All { * * @example Combining Effects in Tuples * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" + * import { Console, Effect } from "effect" * * const tupleOfEffects = [ * Effect.succeed(42).pipe(Effect.tap(Console.log)), @@ -637,8 +641,7 @@ export declare namespace All { * * @example Combining Effects in Iterables * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" + * import { Console, Effect } from "effect" * * const iterableOfEffects: Iterable> = [1, 2, 3].map( * (n) => Effect.succeed(n).pipe(Effect.tap(Console.log)) @@ -658,8 +661,7 @@ export declare namespace All { * * @example Combining Effects in Structs * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" + * import { Console, Effect } from "effect" * * const structOfEffects = { * a: Effect.succeed(42).pipe(Effect.tap(Console.log)), @@ -679,8 +681,7 @@ export declare namespace All { * * @example Combining Effects in Records * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" + * import { Console, Effect } from "effect" * * const recordOfEffects: Record> = { * key1: Effect.succeed(1).pipe(Effect.tap(Console.log)), @@ -700,8 +701,7 @@ export declare namespace All { * * @example Short-Circuiting Behavior * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" + * import { Console, Effect } from "effect" * * const program = Effect.all([ * Effect.succeed("Task1").pipe(Effect.tap(Console.log)), @@ -768,8 +768,10 @@ export const all: < * import { Effect } from "effect" * import { Console } from "effect" * - * const result = Effect.forEach([1, 2, 3, 4, 5], (n, index) => - * Console.log(`Currently at index ${index}`).pipe(Effect.as(n * 2)) + * const result = Effect.forEach( + * [1, 2, 3, 4, 5], + * (n, index) => + * Console.log(`Currently at index ${index}`).pipe(Effect.as(n * 2)) * ) * * Effect.runPromise(result).then(console.log) @@ -1289,7 +1291,7 @@ export const never: Effect = internal.never * * const fetchDiscountRate = Effect.promise(() => Promise.resolve(5)) * - * export const program = Effect.gen(function* () { + * export const program = Effect.gen(function*() { * const transactionAmount = yield* fetchTransactionAmount * const discountRate = yield* fetchDiscountRate * const discountedAmount = yield* applyDiscount( @@ -1512,7 +1514,7 @@ export { * }) * * // Success case - * Effect.runPromise(parseJSON('{"name": "Alice"}')).then(console.log) + * Effect.runPromise(parseJSON("{\"name\": \"Alice\"}")).then(console.log) * // Output: { name: "Alice" } * * // Failure case @@ -1547,7 +1549,7 @@ export { * ```ts * import { Effect } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * console.log("Before yield") * yield* Effect.yieldNow * console.log("After yield") @@ -1568,7 +1570,7 @@ export const yieldNow: Effect = internal.yieldNow * ```ts * import { Effect } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * console.log("High priority task") * yield* Effect.yieldNowWith(10) // Higher priority * console.log("Continued after yield") @@ -1613,8 +1615,7 @@ export const withFiber: ( * * @example * ```ts - * import { Effect } from "effect" - * import { Result } from "effect" + * import { Effect, Result } from "effect" * * const success = Result.succeed(42) * const failure = Result.fail("Something went wrong") @@ -1637,8 +1638,7 @@ export const fromResult: (result: Result.Result) => Effect = i * * @example * ```ts - * import { Effect } from "effect" - * import { Option } from "effect" + * import { Effect, Option } from "effect" * * const some = Option.some(42) * const none = Option.none() @@ -1676,7 +1676,7 @@ export const fromNullishOr: (value: A) => Effect, Cause.NoSuch * import * as Option from "effect/Option" * * // Option is yieldable in Effect - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const value = yield* Effect.fromYieldable(Option.some(42)) * return value * 2 * }) @@ -1728,7 +1728,7 @@ export const fromYieldable: ( * * @example * ```ts - * import { pipe, Effect } from "effect" + * import { Effect, pipe } from "effect" * * // Function to apply a discount safely to a transaction amount * const applyDiscount = ( @@ -1810,7 +1810,7 @@ export const flatten: (self: Effect, E2, R2>) = * * @example Applying a Discount Based on Fetched Amount * ```ts - * import { pipe, Effect } from "effect" + * import { Effect, pipe } from "effect" * * // Function to apply a discount safely to a transaction amount * const applyDiscount = ( @@ -1994,7 +1994,6 @@ export const tap: { * @example * ```ts * import { Effect } from "effect" - * import { Result } from "effect" * * const success = Effect.succeed(42) * const failure = Effect.fail("Something went wrong") @@ -2055,7 +2054,7 @@ export const option: (self: Effect) => Effect, never * * @example * ```ts - * import { Effect, Exit } from "effect" + * import { Effect } from "effect" * * const success = Effect.succeed(42) * const failure = Effect.fail("Something went wrong") @@ -2104,7 +2103,7 @@ export const exit: ( * * @example Adding a Service Charge * ```ts - * import { pipe, Effect } from "effect" + * import { Effect, pipe } from "effect" * * const addServiceCharge = (amount: number) => amount + 1 * @@ -2140,7 +2139,7 @@ export const map: { * @example * ```ts * // Title: Replacing a Value - * import { pipe, Effect } from "effect" + * import { Effect, pipe } from "effect" * * // Replaces the value 5 with the constant "new value" * const program = pipe(Effect.succeed(5), Effect.as("new value")) @@ -2165,7 +2164,6 @@ export const as: { * @example * ```ts * import { Effect } from "effect" - * import * as Option from "effect/Option" * * const program = Effect.asSome(Effect.succeed(42)) * @@ -2434,8 +2432,10 @@ export { * * declare const task: Effect.Effect * - * const program = Effect.catchTag(task, "NetworkError", (error) => - * Effect.succeed(`Recovered from network error: ${error.message}`) + * const program = Effect.catchTag( + * task, + * "NetworkError", + * (error) => Effect.succeed(`Recovered from network error: ${error.message}`) * ) * ``` * @@ -2472,8 +2472,7 @@ export const catchTag: { * * @example * ```ts - * import { Effect } from "effect" - * import { Data } from "effect" + * import { Data, Effect } from "effect" * * // Define tagged error types * class ValidationError extends Data.TaggedError("ValidationError")<{ @@ -2489,7 +2488,8 @@ export const catchTag: { * * // Handle multiple error types at once * const handled = Effect.catchTags(program, { - * ValidationError: (error) => Effect.succeed(`Validation failed: ${error.message}`), + * ValidationError: (error) => + * Effect.succeed(`Validation failed: ${error.message}`), * NetworkError: (error) => Effect.succeed(`Network error: ${error.statusCode}`) * }) * ``` @@ -2566,8 +2566,7 @@ export const catchTags: { * * @example * ```ts - * import { Effect, Cause } from "effect" - * import { Console } from "effect" + * import { Cause, Console, Effect } from "effect" * * // An effect that might fail in different ways * const program = Effect.die("Something went wrong") @@ -2621,8 +2620,7 @@ export const catchCause: { * * @example * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" + * import { Console, Effect } from "effect" * * // An effect that might throw an unexpected error (defect) * const program = Effect.sync(() => { @@ -2669,7 +2667,8 @@ export const catchDefect: { * const program = Effect.fail(42) * * // Recover only from specific error values - * const recovered = Effect.catchFilter(program, + * const recovered = Effect.catchFilter( + * program, * (error) => error === 42, * (error) => Effect.succeed(`Recovered from error: ${error}`) * ) @@ -2699,8 +2698,7 @@ export const catchFilter: { * * @example * ```ts - * import { Effect, Cause } from "effect" - * import { Console } from "effect" + * import { Cause, Console, Effect } from "effect" * * const httpRequest = Effect.fail("Network Error") * @@ -2708,10 +2706,11 @@ export const catchFilter: { * const program = Effect.catchCauseFilter( * httpRequest, * (cause) => Cause.hasFail(cause), - * (failure, cause) => Effect.gen(function* () { - * yield* Console.log(`Caught network error: ${Cause.squash(cause)}`) - * return "Fallback response" - * }) + * (failure, cause) => + * Effect.gen(function*() { + * yield* Console.log(`Caught network error: ${Cause.squash(cause)}`) + * return "Fallback response" + * }) * ) * * Effect.runPromise(program).then(console.log) @@ -2864,15 +2863,15 @@ export const orDie: (self: Effect) => Effect = in * * @example * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" + * import { Console, Effect } from "effect" * * // Simulate a task that fails with an error * const task: Effect.Effect = Effect.fail("NetworkError") * * // Use tapError to log the error message when the task fails - * const tapping = Effect.tapError(task, (error) => - * Console.log(`expected error: ${error}`) + * const tapping = Effect.tapError( + * task, + * (error) => Console.log(`expected error: ${error}`) * ) * * Effect.runFork(tapping) @@ -2904,13 +2903,13 @@ export const tapError: { * * @example * ```ts - * import { Effect, Cause } from "effect" - * import { Console } from "effect" + * import { Cause, Console, Effect } from "effect" * * const task = Effect.fail("Something went wrong") * - * const program = Effect.tapCause(task, (cause) => - * Console.log(`Logging cause: ${Cause.squash(cause)}`) + * const program = Effect.tapCause( + * task, + * (cause) => Console.log(`Logging cause: ${Cause.squash(cause)}`) * ) * * Effect.runPromiseExit(program).then(console.log) @@ -2940,8 +2939,7 @@ export const tapCause: { * * @example * ```ts - * import { Effect, Cause } from "effect" - * import { Console } from "effect" + * import { Cause, Console, Effect } from "effect" * * const task = Effect.fail("Network timeout") * @@ -2949,8 +2947,7 @@ export const tapCause: { * const program = Effect.tapCauseFilter( * task, * (cause) => Cause.hasFail(cause), - * (_, cause) => - * Console.log(`Logging failure cause: ${Cause.squash(cause)}`) + * (_, cause) => Console.log(`Logging failure cause: ${Cause.squash(cause)}`) * ) * * Effect.runPromiseExit(program).then(console.log) @@ -2991,15 +2988,15 @@ export const tapCauseFilter: { * * @example * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" + * import { Console, Effect } from "effect" * * // Simulate a task that fails with a recoverable error * const task1: Effect.Effect = Effect.fail("NetworkError") * * // tapDefect won't log anything because NetworkError is not a defect - * const tapping1 = Effect.tapDefect(task1, (cause) => - * Console.log(`defect: ${cause}`) + * const tapping1 = Effect.tapDefect( + * task1, + * (cause) => Console.log(`defect: ${cause}`) * ) * * Effect.runFork(tapping1) @@ -3011,8 +3008,9 @@ export const tapCauseFilter: { * ) * * // Log the defect using tapDefect - * const tapping2 = Effect.tapDefect(task2, (cause) => - * Console.log(`defect: ${cause}`) + * const tapping2 = Effect.tapDefect( + * task2, + * (cause) => Console.log(`defect: ${cause}`) * ) * * Effect.runFork(tapping2) @@ -3062,7 +3060,7 @@ export const eventually: (self: Effect) => Effect * @category Error handling * @example * ```ts - * import { Effect } from "effect" + * import type { Effect } from "effect" * * // Retry namespace contains types for retry operations * declare const effect: Effect.Effect @@ -3076,7 +3074,7 @@ export declare namespace Retry { * @category Error handling * @example * ```ts - * import { Effect } from "effect" + * import type { Effect } from "effect" * * // Return type for retry operations with specific options * declare const options: Effect.Retry.Options @@ -3118,8 +3116,8 @@ export declare namespace Retry { * @category Error handling * @example * ```ts - * import { Effect } from "effect" * import { Schedule } from "effect" + * import type { Effect } from "effect" * * // Options for configuring retry behavior * const retryOptions: Effect.Retry.Options = { @@ -3160,8 +3158,7 @@ export declare namespace Retry { * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" + * import { Effect, Schedule } from "effect" * * let attempt = 0 * const task = Effect.callback((resume) => { @@ -3218,12 +3215,10 @@ export const retry: { * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * let attempt = 0 - * const networkRequest = Effect.gen(function* () { + * const networkRequest = Effect.gen(function*() { * attempt++ * yield* Console.log(`Network attempt ${attempt}`) * if (attempt < 3) { @@ -3236,10 +3231,11 @@ export const retry: { * const program = Effect.retryOrElse( * networkRequest, * Schedule.recurs(2), - * (error, retryCount) => Effect.gen(function* () { - * yield* Console.log(`All ${retryCount} retries failed, using cache`) - * return "Cached data" - * }) + * (error, retryCount) => + * Effect.gen(function*() { + * yield* Console.log(`All ${retryCount} retries failed, using cache`) + * return "Cached data" + * }) * ) * * Effect.runPromise(program).then(console.log) @@ -3280,12 +3276,12 @@ export const retryOrElse: { * * @example * ```ts - * import { Effect, Cause } from "effect" + * import { Cause, Effect } from "effect" * * const task = Effect.fail("Something went wrong") * * // Sandbox exposes the full cause as the error type - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const result = yield* Effect.flip(Effect.sandbox(task)) * return `Caught cause: ${Cause.squash(result)}` * }) @@ -3429,7 +3425,7 @@ export const orElseSucceed: { * ```ts * import { Effect } from "effect" * - * const task = Effect.gen(function* () { + * const task = Effect.gen(function*() { * console.log("Start processing...") * yield* Effect.sleep("2 seconds") // Simulates a delay in processing * console.log("Processing complete.") @@ -3490,7 +3486,7 @@ export const timeout: { * ```ts * import { Effect } from "effect" * - * const task = Effect.gen(function* () { + * const task = Effect.gen(function*() { * console.log("Start processing...") * yield* Effect.sleep("2 seconds") // Simulates a delay in processing * console.log("Processing complete.") @@ -3534,10 +3530,9 @@ export const timeoutOption: { * * @example * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" + * import { Console, Effect } from "effect" * - * const slowQuery = Effect.gen(function* () { + * const slowQuery = Effect.gen(function*() { * yield* Console.log("Starting database query...") * yield* Effect.sleep("5 seconds") * return "Database result" @@ -3546,10 +3541,11 @@ export const timeoutOption: { * // Use cached data as fallback when timeout is reached * const program = Effect.timeoutOrElse(slowQuery, { * duration: "2 seconds", - * onTimeout: () => Effect.gen(function* () { - * yield* Console.log("Query timed out, using cached data") - * return "Cached result" - * }) + * onTimeout: () => + * Effect.gen(function*() { + * yield* Console.log("Query timed out, using cached data") + * return "Cached result" + * }) * }) * * Effect.runPromise(program).then(console.log) @@ -3582,8 +3578,7 @@ export const timeoutOrElse: { * * @example * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" + * import { Console, Effect } from "effect" * * const program = Effect.delay( * Console.log("Delayed message"), @@ -3613,10 +3608,9 @@ export const delay: { * * @example * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" + * import { Console, Effect } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * yield* Console.log("Start") * yield* Effect.sleep("2 seconds") * yield* Console.log("End") @@ -3681,8 +3675,7 @@ export const timed: (self: Effect) => Effect<[duration: Durati * * @example * ```ts - * import { Effect } from "effect" - * import { Duration } from "effect" + * import { Duration, Effect } from "effect" * * // Multiple effects with different delays * const effect1 = Effect.delay(Effect.succeed("Fast"), Duration.millis(100)) @@ -3720,8 +3713,7 @@ export const raceAll: >( * * @example * ```ts - * import { Effect } from "effect" - * import { Duration } from "effect" + * import { Duration, Effect } from "effect" * * // Multiple effects with different delays and potential failures * const effect1 = Effect.delay(Effect.succeed("First"), Duration.millis(200)) @@ -3795,8 +3787,7 @@ export const raceFirst: { * * @example * ```ts - * import { Effect } from "effect" - * import { Filter } from "effect" + * import { Effect, Filter } from "effect" * * const isEven = (n: number) => Effect.succeed(n % 2 === 0 ? n : Filter.fail(n)) * @@ -3827,8 +3818,7 @@ export const filter: ( * * @example * ```ts - * import { Effect } from "effect" - * import { Filter } from "effect" + * import { Effect, Filter } from "effect" * * // An effect that produces a number * const program = Effect.succeed(5) @@ -3869,8 +3859,7 @@ export const filterOrElse: { * * @example * ```ts - * import { Effect } from "effect" - * import { Filter } from "effect" + * import { Effect, Filter } from "effect" * * // An effect that produces a number * const program = Effect.succeed(5) @@ -3929,9 +3918,7 @@ export const filterOrFail: { * * @example * ```ts - * import { Effect } from "effect" - * import * as Option from "effect/Option" - * import { Console } from "effect" + * import { Console, Effect } from "effect" * * const shouldLog = true * @@ -4051,7 +4038,7 @@ export const match: { * ```ts * import { Effect } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const result = yield* Effect.matchEager(Effect.succeed(42), { * onFailure: (error) => `Failed: ${error}`, * onSuccess: (value) => `Success: ${value}` @@ -4096,7 +4083,7 @@ export const matchEager: { * * @example * ```ts - * import { Effect, Cause } from "effect" + * import { Cause, Effect } from "effect" * * const task = Effect.fail("Something went wrong") * @@ -4206,15 +4193,14 @@ export const matchCauseEffectEager: { * * @example * ```ts - * import { Effect, Cause } from "effect" + * import { Cause, Console, Effect } from "effect" * import * as Filter from "effect/Filter" - * import { Console } from "effect" * * const task = Effect.fail(new Error("Task failed")) * * const program = Effect.matchCauseEffect(task, { * onFailure: (cause) => - * Effect.gen(function* () { + * Effect.gen(function*() { * if (Cause.hasFail(cause)) { * const error = Cause.filterError(cause) * if (Filter.isPass(error)) { @@ -4227,7 +4213,7 @@ export const matchCauseEffectEager: { * } * }), * onSuccess: (value) => - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log(`Success: ${value}`) * return `processed ${value}` * }) @@ -4399,8 +4385,7 @@ export const isSuccess: (self: Effect) => Effect void @@ -4409,7 +4394,7 @@ export const isSuccess: (self: Effect) => Effect string * }>("Database") * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const allServices = yield* Effect.services() * * // Check if specific services are available @@ -4440,8 +4425,7 @@ export const services: () => Effect, never, R> = int * * @example * ```ts - * import { Console, Effect, ServiceMap } from "effect" - * import { Option } from "effect" + * import { Console, Effect, Option, ServiceMap } from "effect" * * const Logger = ServiceMap.Service<{ * log: (msg: string) => void @@ -4455,13 +4439,13 @@ export const services: () => Effect, never, R> = int * const hasCache = Option.isSome(cacheOption) * * if (hasCache) { - * return Effect.gen(function* () { + * return Effect.gen(function*() { * const cache = yield* Effect.service(Cache) * yield* Console.log("Using cached data") * return cache.get("user:123") || "default" * }) * } else { - * return Effect.gen(function* () { + * return Effect.gen(function*() { * yield* Console.log("No cache available, using fallback") * return "fallback data" * }) @@ -4497,7 +4481,7 @@ export const servicesWith: ( * query: (sql: string) => Effect.succeed(`Result for: ${sql}`) * }) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const db = yield* Database * return yield* db.query("SELECT * FROM users") * }) @@ -4573,7 +4557,7 @@ export const provide: { * .pipe(ServiceMap.add(Database, { query: () => "result" })) * * // An effect that requires both services - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const logger = yield* Effect.service(Logger) * const db = yield* Effect.service(Database) * logger.log("Querying database") @@ -4609,7 +4593,7 @@ export const provideServices: { * * const Database = ServiceMap.Service("Database") * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const db = yield* Effect.service(Database) * return yield* db.query("SELECT * FROM users") * }) @@ -4632,8 +4616,7 @@ export const service: (service: ServiceMap.Service) => Effect(service: ServiceMap.Service) => Effect("Logger") * * // Use serviceOption to optionally access the logger - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const maybeLogger = yield* Effect.serviceOption(Logger) * * if (Option.isSome(maybeLogger)) { @@ -4717,7 +4700,7 @@ export const updateServices: { * // Define a counter service * const Counter = ServiceMap.Service<{ count: number }>("Counter") * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const updatedCounter = yield* Effect.service(Counter) * yield* Console.log(`Updated count: ${updatedCounter.count}`) * return updatedCounter.count @@ -4765,10 +4748,11 @@ export const updateService: { * * // Define a service for configuration * const Config = ServiceMap.Service<{ - * apiUrl: string; timeout: number + * apiUrl: string + * timeout: number * }>("Config") * - * const fetchData = Effect.gen(function* () { + * const fetchData = Effect.gen(function*() { * const config = yield* Effect.service(Config) * yield* Console.log(`Fetching from: ${config.apiUrl}`) * yield* Console.log(`Timeout: ${config.timeout}ms`) @@ -4830,7 +4814,7 @@ export const provideService: { * const Database = ServiceMap.Service("Database") * * // Effect that creates a database connection - * const createConnection = Effect.gen(function* () { + * const createConnection = Effect.gen(function*() { * yield* Console.log("Establishing database connection...") * yield* Effect.sleep("100 millis") // Simulate connection time * yield* Console.log("Database connected!") @@ -4839,13 +4823,17 @@ export const provideService: { * } * }) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const db = yield* Effect.service(Database) * return yield* db.query("SELECT * FROM users") * }) * * // Provide the service through an effect - * const withDatabase = Effect.provideServiceEffect(program, Database, createConnection) + * const withDatabase = Effect.provideServiceEffect( + * program, + * Database, + * createConnection + * ) * * Effect.runPromise(withDatabase).then(console.log) * // Output: @@ -4880,15 +4868,16 @@ export const provideServiceEffect: { * ```ts * import { Console, Effect } from "effect" * - * const task = (id: number) => Effect.gen(function* () { - * yield* Console.log(`Task ${id} starting`) - * yield* Effect.sleep("100 millis") - * yield* Console.log(`Task ${id} completed`) - * return id - * }) + * const task = (id: number) => + * Effect.gen(function*() { + * yield* Console.log(`Task ${id} starting`) + * yield* Effect.sleep("100 millis") + * yield* Console.log(`Task ${id} completed`) + * return id + * }) * * // Run tasks with limited concurrency (max 2 at a time) - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const tasks = [1, 2, 3, 4, 5].map(task) * return yield* Effect.all(tasks, { concurrency: 2 }) * }).pipe( @@ -4922,9 +4911,9 @@ export const withConcurrency: { * * @example * ```ts - * import { Console, Effect, Scope } from "effect" + * import { Console, Effect } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const currentScope = yield* Effect.scope * yield* Console.log("Got scope for resource management") * @@ -4957,8 +4946,7 @@ export const scope: Effect = internal.scope * * @example * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" + * import { Console, Effect } from "effect" * * const resource = Effect.acquireRelease( * Console.log("Acquiring resource").pipe(Effect.as("resource")), @@ -4966,7 +4954,7 @@ export const scope: Effect = internal.scope * ) * * const program = Effect.scoped( - * Effect.gen(function* () { + * Effect.gen(function*() { * const res = yield* resource * yield* Console.log(`Using ${res}`) * return res @@ -4991,12 +4979,10 @@ export const scoped: ( * * @example * ```ts - * import { Effect } from "effect" - * import { Scope } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Scope } from "effect" * * const program = Effect.scopedWith((scope) => - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log("Inside scoped context") * * // Manually add a finalizer to the scope @@ -5045,8 +5031,7 @@ export const scopedWith: ( * * @example * ```ts - * import { Effect, Exit } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Exit } from "effect" * * // Simulate a resource that needs cleanup * interface FileHandle { @@ -5055,21 +5040,25 @@ export const scopedWith: ( * } * * // Acquire a file handle - * const acquire = Effect.gen(function* () { + * const acquire = Effect.gen(function*() { * yield* Console.log("Opening file") * return { path: "/tmp/file.txt", content: "file content" } * }) * * // Release the file handle * const release = (handle: FileHandle, exit: Exit.Exit) => - * Console.log(`Closing file ${handle.path} with exit: ${Exit.isSuccess(exit) ? "success" : "failure"}`) + * Console.log( + * `Closing file ${handle.path} with exit: ${ + * Exit.isSuccess(exit) ? "success" : "failure" + * }` + * ) * * // Create a scoped resource * const resource = Effect.acquireRelease(acquire, release) * * // Use the resource within a scope * const program = Effect.scoped( - * Effect.gen(function* () { + * Effect.gen(function*() { * const handle = yield* resource * yield* Console.log(`Using file: ${handle.path}`) * return handle.content @@ -5110,8 +5099,7 @@ export const acquireRelease: ( * * @example * ```ts - * import { Effect, Exit } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Exit } from "effect" * * interface Database { * readonly connection: string @@ -5120,7 +5108,7 @@ export const acquireRelease: ( * * const program = Effect.acquireUseRelease( * // Acquire - connect to database - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log("Connecting to database...") * return { * connection: "db://localhost:5432", @@ -5128,20 +5116,22 @@ export const acquireRelease: ( * } * }), * // Use - perform database operations - * (db) => Effect.gen(function* () { - * yield* Console.log(`Connected to ${db.connection}`) - * const result = yield* db.query("SELECT * FROM users") - * yield* Console.log(`Query result: ${result}`) - * return result - * }), + * (db) => + * Effect.gen(function*() { + * yield* Console.log(`Connected to ${db.connection}`) + * const result = yield* db.query("SELECT * FROM users") + * yield* Console.log(`Query result: ${result}`) + * return result + * }), * // Release - close database connection - * (db, exit) => Effect.gen(function* () { - * if (Exit.isSuccess(exit)) { - * yield* Console.log(`Closing connection to ${db.connection} (success)`) - * } else { - * yield* Console.log(`Closing connection to ${db.connection} (failure)`) - * } - * }) + * (db, exit) => + * Effect.gen(function*() { + * if (Exit.isSuccess(exit)) { + * yield* Console.log(`Closing connection to ${db.connection} (success)`) + * } else { + * yield* Console.log(`Closing connection to ${db.connection} (failure)`) + * } + * }) * ) * * Effect.runPromise(program) @@ -5172,11 +5162,10 @@ export const acquireUseRelease: ( * * @example * ```ts - * import { Effect, Exit } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Exit } from "effect" * * const program = Effect.scoped( - * Effect.gen(function* () { + * Effect.gen(function*() { * // Add a finalizer that runs when the scope closes * yield* Effect.addFinalizer((exit) => * Console.log( @@ -5220,10 +5209,9 @@ export const addFinalizer: ( * * @example * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" + * import { Console, Effect } from "effect" * - * const task = Effect.gen(function* () { + * const task = Effect.gen(function*() { * yield* Console.log("Task started") * yield* Effect.sleep("1 second") * yield* Console.log("Task completed") @@ -5263,13 +5251,13 @@ export const ensuring: { * * @example * ```ts - * import { Effect, Cause } from "effect" - * import { Console } from "effect" + * import { Cause, Console, Effect } from "effect" * * const task = Effect.fail(new Error("Something went wrong")) * - * const program = Effect.onError(task, (cause) => - * Console.log(`Cleanup on error: ${Cause.squash(cause)}`) + * const program = Effect.onError( + * task, + * (cause) => Console.log(`Cleanup on error: ${Cause.squash(cause)}`) * ) * * Effect.runPromise(program).catch(console.error) @@ -5316,8 +5304,7 @@ export const onErrorFilter: { * * @example * ```ts - * import { Effect, Exit } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Exit } from "effect" * * const task = Effect.succeed(42) * @@ -5326,8 +5313,7 @@ export const onErrorFilter: { * Exit.isSuccess(exit) * ? `Task succeeded with: ${exit.value}` * : `Task failed: ${Exit.isFailure(exit) ? exit.cause : "interrupted"}` - * ) - * ) + * )) * * Effect.runPromise(program).then(console.log) * // Output: @@ -5407,8 +5393,7 @@ export const onExitFilter: { * * @example * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" + * import { Console, Effect } from "effect" * * let i = 1 * const expensiveTask = Effect.promise(() => { @@ -5420,7 +5405,7 @@ export const onExitFilter: { * }) * }) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * console.log("non-cached version:") * yield* expensiveTask.pipe(Effect.andThen(Console.log)) * yield* expensiveTask.pipe(Effect.andThen(Console.log)) @@ -5482,8 +5467,7 @@ export const cached: (self: Effect) => Effect> * * @example * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" + * import { Console, Effect } from "effect" * * let i = 1 * const expensiveTask = Effect.promise(() => { @@ -5495,7 +5479,7 @@ export const cached: (self: Effect) => Effect> * }) * }) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const cached = yield* Effect.cachedWithTTL(expensiveTask, "150 millis") * yield* cached.pipe(Effect.andThen(Console.log)) * yield* cached.pipe(Effect.andThen(Console.log)) @@ -5554,8 +5538,7 @@ export const cachedWithTTL: { * * @example * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" + * import { Console, Effect } from "effect" * * let i = 1 * const expensiveTask = Effect.promise(() => { @@ -5567,7 +5550,7 @@ export const cachedWithTTL: { * }) * }) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const [cached, invalidate] = yield* Effect.cachedInvalidateWithTTL( * expensiveTask, * "1 hour" @@ -5606,7 +5589,7 @@ export const cachedInvalidateWithTTL: { * ```ts * import { Effect } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * yield* Effect.interrupt * yield* Effect.succeed("This won't execute") * }) @@ -5648,13 +5631,12 @@ export const interruptible: ( * * @example * ```ts - * import { Effect } from "effect" - * import { Fiber } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Fiber } from "effect" * * const task = Effect.forever(Effect.succeed("working...")) * - * const program = Effect.onInterrupt(task, + * const program = Effect.onInterrupt( + * task, * Console.log("Task was interrupted, cleaning up...") * ) * @@ -5682,11 +5664,9 @@ export const onInterrupt: { * * @example * ```ts - * import { Effect } from "effect" - * import { Fiber } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Fiber } from "effect" * - * const criticalTask = Effect.gen(function* () { + * const criticalTask = Effect.gen(function*() { * yield* Console.log("Starting critical section...") * yield* Effect.sleep("2 seconds") * yield* Console.log("Critical section completed") @@ -5712,17 +5692,16 @@ export const uninterruptible: ( * * @example * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" + * import { Console, Effect } from "effect" * * const program = Effect.uninterruptibleMask((restore) => - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log("Uninterruptible phase...") * yield* Effect.sleep("1 second") * * // Restore interruptibility for this part * yield* restore( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log("Interruptible phase...") * yield* Effect.sleep("2 seconds") * }) @@ -5749,17 +5728,16 @@ export const uninterruptibleMask: ( * * @example * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" + * import { Console, Effect } from "effect" * * const program = Effect.interruptibleMask((restore) => - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log("Interruptible phase...") * yield* Effect.sleep("1 second") * * // Make this part uninterruptible * yield* restore( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log("Uninterruptible phase...") * yield* Effect.sleep("2 seconds") * }) @@ -5791,7 +5769,7 @@ export const interruptibleMask: ( * import { Effect } from "effect" * * // Create and use a semaphore for controlling concurrent access - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const semaphore = yield* Effect.makeSemaphore(2) * * return yield* semaphore.withPermits(1)( @@ -5875,7 +5853,7 @@ export interface Semaphore { * * const task = (id: number) => * semaphore.withPermits(1)( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Effect.log(`Task ${id} started`) * yield* Effect.sleep("1 second") * yield* Effect.log(`Task ${id} completed`) @@ -5884,7 +5862,11 @@ export interface Semaphore { * * // Only 3 tasks can run concurrently * const program = Effect.all([ - * task(1), task(2), task(3), task(4), task(5) + * task(1), + * task(2), + * task(3), + * task(4), + * task(5) * ], { concurrency: "unbounded" }) * ``` * @@ -5900,12 +5882,12 @@ export const makeSemaphoreUnsafe: (permits: number) => Semaphore = internal.make * ```ts * import { Effect } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const semaphore = yield* Effect.makeSemaphore(2) * * const task = (id: number) => * semaphore.withPermits(1)( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Effect.log(`Task ${id} acquired permit`) * yield* Effect.sleep("1 second") * yield* Effect.log(`Task ${id} releasing permit`) @@ -5934,7 +5916,7 @@ export const makeSemaphore: (permits: number) => Effect = internal.ma * import { Effect } from "effect" * * // Create and use a latch for coordination between fibers - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const latch = yield* Effect.makeLatch() * * // Wait for the latch to be opened @@ -5970,13 +5952,13 @@ export interface Latch { * * const latch = Effect.makeLatchUnsafe(false) * - * const waiter = Effect.gen(function* () { + * const waiter = Effect.gen(function*() { * yield* Effect.log("Waiting for latch to open...") * yield* latch.await * yield* Effect.log("Latch opened! Continuing...") * }) * - * const opener = Effect.gen(function* () { + * const opener = Effect.gen(function*() { * yield* Effect.sleep("2 seconds") * yield* Effect.log("Opening latch...") * yield* latch.open @@ -5997,16 +5979,16 @@ export const makeLatchUnsafe: (open?: boolean | undefined) => Latch = internal.m * ```ts * import { Effect } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const latch = yield* Effect.makeLatch(false) * - * const waiter = Effect.gen(function* () { + * const waiter = Effect.gen(function*() { * yield* Effect.log("Waiting for latch to open...") * yield* latch.await * yield* Effect.log("Latch opened! Continuing...") * }) * - * const opener = Effect.gen(function* () { + * const opener = Effect.gen(function*() { * yield* Effect.sleep("2 seconds") * yield* Effect.log("Opening latch...") * yield* latch.open @@ -6030,7 +6012,7 @@ export const makeLatch: (open?: boolean | undefined) => Effect = internal * @category repetition / recursion * @example * ```ts - * import { Effect } from "effect" + * import type { Effect } from "effect" * * // Repeat namespace contains types for repeating operations * declare const effect: Effect.Effect @@ -6044,7 +6026,7 @@ export declare namespace Repeat { * @category repetition / recursion * @example * ```ts - * import { Effect } from "effect" + * import type { Effect } from "effect" * * // Return type for repeat operations with specific options * declare const options: Effect.Repeat.Options @@ -6086,8 +6068,8 @@ export declare namespace Repeat { * @category repetition / recursion * @example * ```ts - * import { Effect } from "effect" * import { Schedule } from "effect" + * import type { Effect } from "effect" * * // Options for configuring repeat behavior * const repeatOptions: Effect.Repeat.Options = { @@ -6110,11 +6092,9 @@ export declare namespace Repeat { * * @example * ```ts - * import { Effect } from "effect" - * import { Fiber } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Fiber } from "effect" * - * const task = Effect.gen(function* () { + * const task = Effect.gen(function*() { * yield* Console.log("Task running...") * yield* Effect.sleep("1 second") * }) @@ -6123,7 +6103,7 @@ export declare namespace Repeat { * const program = Effect.forever(task) * * // Run for 5 seconds then interrupt - * const timedProgram = Effect.gen(function* () { + * const timedProgram = Effect.gen(function*() { * const fiber = yield* Effect.forkChild(program) * yield* Effect.sleep("5 seconds") * yield* Fiber.interrupt(fiber) @@ -6234,13 +6214,11 @@ export const repeat: { * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" + * import { Console, Effect, Schedule } from "effect" * import * as Option from "effect/Option" - * import { Console } from "effect" * * let attempt = 0 - * const task = Effect.gen(function* () { + * const task = Effect.gen(function*() { * attempt++ * if (attempt <= 2) { * yield* Console.log(`Attempt ${attempt} failed`) @@ -6255,7 +6233,9 @@ export const repeat: { * Schedule.recurs(3), * (error, attempts) => * Console.log( - * `Final failure: ${error}, after ${Option.getOrElse(attempts, () => 0)} attempts` + * `Final failure: ${error}, after ${ + * Option.getOrElse(attempts, () => 0) + * } attempts` * ).pipe(Effect.map(() => 0)) * ) * ``` @@ -6353,11 +6333,9 @@ export const replicateEffect: { * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * - * const task = Effect.gen(function* () { + * const task = Effect.gen(function*() { * yield* Console.log("Task executing...") * return Math.random() * }) @@ -6412,12 +6390,10 @@ export const schedule: { * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * const task = (input: number) => - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log(`Processing: ${input}`) * return input + 1 * }) @@ -6459,7 +6435,7 @@ export const scheduleFrom: { * ```ts * import { Effect } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const currentTracer = yield* Effect.tracer * yield* Effect.log(`Using tracer: ${currentTracer}`) * return "operation completed" @@ -6478,7 +6454,7 @@ export const tracer: Effect = internal.tracer * ```ts * import { Effect } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * yield* Effect.log("Using tracer") * return "completed" * }) @@ -6523,7 +6499,7 @@ export const withTracerEnabled: { * ```ts * import { Effect } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * yield* Effect.log("Doing some work...") * return "result" * }) @@ -6568,7 +6544,7 @@ export const annotateSpans: { * ```ts * import { Effect } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * yield* Effect.annotateCurrentSpan("userId", "123") * yield* Effect.annotateCurrentSpan({ * operation: "user-lookup", @@ -6596,7 +6572,7 @@ export const annotateCurrentSpan: { * ```ts * import { Effect } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const span = yield* Effect.currentSpan * yield* Effect.log(`Current span: ${span}`) * return "done" @@ -6617,13 +6593,13 @@ export const currentSpan: Effect = internal.curr * ```ts * import { Effect } from "effect" * - * const childOperation = Effect.gen(function* () { + * const childOperation = Effect.gen(function*() { * const parentSpan = yield* Effect.currentParentSpan * yield* Effect.log(`Parent span: ${parentSpan}`) * return "child completed" * }) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * yield* Effect.withSpan(childOperation, "child-span") * return "parent completed" * }) @@ -6643,7 +6619,7 @@ export const currentParentSpan: Effect = inte * ```ts * import { Effect } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * // Add some annotations to the current span * yield* Effect.annotateCurrentSpan("userId", "123") * yield* Effect.annotateCurrentSpan("operation", "data-processing") @@ -6675,7 +6651,7 @@ export const spanAnnotations: Effect>> = intern * ```ts * import { Effect } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * // Get the current span links * const links = yield* Effect.spanLinks * console.log(`Current span has ${links.length} links`) @@ -6708,7 +6684,7 @@ export const spanLinks: Effect> = internal.spanLinks * ) * * // Link the child span to the parent span - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const parentSpan = yield* Effect.currentSpan * const result = yield* childEffect.pipe( * Effect.linkSpans(parentSpan, { relationship: "follows" }) @@ -6722,7 +6698,7 @@ export const spanLinks: Effect> = internal.spanLinks * import { Effect } from "effect" * * // Link multiple spans - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const span1 = yield* Effect.currentSpan * const span2 = yield* Effect.currentSpan * @@ -6757,7 +6733,7 @@ export const linkSpans: { * ```ts * import { Effect } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const span = yield* Effect.makeSpan("my-operation") * yield* Effect.log("Operation in progress") * return "completed" @@ -6781,7 +6757,7 @@ export const makeSpan: (name: string, options?: SpanOptionsNoTrace) => Effect - * Effect.gen(function* () { - * yield* Effect.log("Processing user data") - * return "success" - * }) + * const program = Effect.useSpan( + * "user-operation", + * (span) => + * Effect.gen(function*() { + * yield* Effect.log("Processing user data") + * return "success" + * }) * ) * ``` * @@ -6832,7 +6810,7 @@ export const useSpan: { * ```ts * import { Effect } from "effect" * - * const task = Effect.gen(function* () { + * const task = Effect.gen(function*() { * yield* Effect.log("Executing task") * return "result" * }) @@ -6871,7 +6849,7 @@ export const withSpan: { * import { Effect } from "effect" * * const program = Effect.scoped( - * Effect.gen(function* () { + * Effect.gen(function*() { * const task = Effect.log("Working...") * yield* Effect.withSpanScoped(task, "scoped-task") * return "completed" @@ -6903,7 +6881,7 @@ export const withSpanScoped: { * ```ts * import { Effect } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const span = yield* Effect.makeSpan("parent-span") * const childTask = Effect.log("Child operation") * yield* Effect.withParentSpan(childTask, span) @@ -6985,16 +6963,15 @@ export const requestUnsafe: ( * * @example * ```ts - * import { Effect } from "effect" - * import { Fiber } from "effect" + * import { Effect, Fiber } from "effect" * - * const longRunningTask = Effect.gen(function* () { + * const longRunningTask = Effect.gen(function*() { * yield* Effect.sleep("2 seconds") * yield* Effect.log("Task completed") * return "result" * }) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const fiber = yield* Effect.forkChild(longRunningTask) * yield* Effect.log("Task forked, continuing...") * const result = yield* Fiber.join(fiber) @@ -7026,16 +7003,14 @@ export const forkChild: < * @example * ```ts * import { Effect } from "effect" - * import { Scope } from "effect" - * import { Fiber } from "effect" * - * const task = Effect.gen(function* () { + * const task = Effect.gen(function*() { * yield* Effect.sleep("10 seconds") * return "completed" * }) * * const program = Effect.scoped( - * Effect.gen(function* () { + * Effect.gen(function*() { * const scope = yield* Effect.scope * const fiber = yield* Effect.forkIn(task, scope) * yield* Effect.sleep("1 second") @@ -7072,16 +7047,15 @@ export const forkIn: { * @example * ```ts * import { Effect } from "effect" - * import { Fiber } from "effect" * - * const backgroundTask = Effect.gen(function* () { + * const backgroundTask = Effect.gen(function*() { * yield* Effect.sleep("5 seconds") * yield* Effect.log("Background task completed") * return "result" * }) * * const program = Effect.scoped( - * Effect.gen(function* () { + * Effect.gen(function*() { * const fiber = yield* Effect.forkScoped(backgroundTask) * yield* Effect.log("Task forked in scope") * yield* Effect.sleep("1 second") @@ -7116,16 +7090,15 @@ export const forkScoped: < * @example * ```ts * import { Effect } from "effect" - * import { Fiber } from "effect" * - * const daemonTask = Effect.gen(function* () { + * const daemonTask = Effect.gen(function*() { * while (true) { * yield* Effect.sleep("1 second") * yield* Effect.log("Daemon running...") * } * }) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const fiber = yield* Effect.forkDetach(daemonTask) * yield* Effect.log("Daemon started") * yield* Effect.sleep("3 seconds") @@ -7179,7 +7152,7 @@ export const fiberId: Effect = internal.fiberId * ```ts * import { Effect } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * yield* Effect.sleep("2 seconds") * return "completed" * }) @@ -7263,7 +7236,7 @@ export const runFork: (effect: Effect, options?: RunOptions | * log: (message) => console.log(message) * }) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const logger = yield* Logger * logger.log("Hello from service!") * return "done" @@ -7355,7 +7328,7 @@ export const runPromise: ( * apiUrl: "https://api.example.com" * }) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const config = yield* Config * return `Connecting to ${config.apiUrl}` * }) @@ -7439,7 +7412,7 @@ export const runPromiseExit: ( * query: (sql) => `Result for: ${sql}` * }) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const db = yield* Database * return db.query("SELECT * FROM users") * }) @@ -7535,7 +7508,7 @@ export const runSync: (effect: Effect) => A = internal.runSync * add: (a, b) => a + b * }) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const math = yield* MathService * return math.add(2, 3) * }) @@ -7634,7 +7607,7 @@ export const runSyncExit: (effect: Effect) => Exit.Exit = inte * log: (msg: string) => void * }>("Logger") * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const logger = yield* Effect.service(Logger) * logger.log("Computing result...") * return 42 @@ -7673,7 +7646,7 @@ export const runSyncExitWith: ( * @category Function * @example * ```ts - * import { Effect } from "effect" + * import type { Effect } from "effect" * * // fn namespace contains utilities for function-based effects * // This namespace provides utilities for creating function effects @@ -10025,8 +9998,7 @@ export const fn: fn.Gen & fn.NonGen = internal.fn * * @example * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" + * import { Console, Effect } from "effect" * * const program = Effect.clockWith((clock) => * clock.currentTimeMillis.pipe( @@ -10065,7 +10037,7 @@ export const logWithLevel: (level?: LogLevel) => (...message: ReadonlyArray * ```ts * import { Effect } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * yield* Effect.log("Starting computation") * const result = 2 + 2 * yield* Effect.log("Result:", result) @@ -10093,7 +10065,7 @@ export const log: (...message: ReadonlyArray) => Effect = internal.lo * ```ts * import { Effect } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * try { * // Simulate a critical system failure * throw new Error("System memory exhausted") @@ -10122,7 +10094,7 @@ export const logFatal: (...message: ReadonlyArray) => Effect = intern * ```ts * import { Effect } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * yield* Effect.logWarning("API rate limit approaching") * yield* Effect.logWarning("Retries remaining:", 2, "Operation:", "fetchData") * @@ -10152,9 +10124,14 @@ export const logWarning: (...message: ReadonlyArray) => Effect = inte * ```ts * import { Effect } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * yield* Effect.logError("Database connection failed") - * yield* Effect.logError("Error code:", 500, "Message:", "Internal server error") + * yield* Effect.logError( + * "Error code:", + * 500, + * "Message:", + * "Internal server error" + * ) * * // Can be used with error objects * const error = new Error("Something went wrong") @@ -10180,7 +10157,7 @@ export const logError: (...message: ReadonlyArray) => Effect = intern * ```ts * import { Effect } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * yield* Effect.logInfo("Application starting up") * yield* Effect.logInfo("Config loaded:", "production", "Port:", 3000) * @@ -10208,7 +10185,7 @@ export const logInfo: (...message: ReadonlyArray) => Effect = interna * ```ts * import { Effect } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * yield* Effect.logDebug("Debug mode enabled") * * const userInput = { name: "Alice", age: 30 } @@ -10237,7 +10214,7 @@ export const logDebug: (...message: ReadonlyArray) => Effect = intern * ```ts * import { Effect } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * yield* Effect.logTrace("Entering function processData") * * // Trace detailed execution flow @@ -10267,15 +10244,14 @@ export const logTrace: (...message: ReadonlyArray) => Effect = intern * * @example * ```ts - * import { Effect } from "effect" - * import { Logger } from "effect" + * import { Effect, Logger } from "effect" * * // Create a custom logger that logs to the console * const customLogger = Logger.make(({ message }) => * Effect.sync(() => console.log(`[CUSTOM]: ${message}`)) * ) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * yield* Effect.log("This will go to both default and custom logger") * return "completed" * }) @@ -10312,7 +10288,7 @@ export const withLogger = dual< * ```ts * import { Effect } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * yield* Effect.log("Starting operation") * yield* Effect.log("Processing data") * yield* Effect.log("Operation completed") @@ -10379,14 +10355,14 @@ export const annotateLogs = dual< * ```ts * import { Effect } from "effect" * - * const databaseOperation = Effect.gen(function* () { + * const databaseOperation = Effect.gen(function*() { * yield* Effect.log("Connecting to database") * yield* Effect.log("Executing query") * yield* Effect.log("Processing results") * return "data" * }) * - * const httpRequest = Effect.gen(function* () { + * const httpRequest = Effect.gen(function*() { * yield* Effect.log("Making HTTP request") * const data = yield* Effect.withLogSpan(databaseOperation, "db-operation") * yield* Effect.log("Sending response") @@ -10427,8 +10403,7 @@ export const withLogSpan = dual< * * @example * ```ts - * import { Effect } from "effect" - * import { Metric } from "effect" + * import { Effect, Metric } from "effect" * * const counter = Metric.counter("effect_executions", { * description: "Counts effect executions" @@ -10447,8 +10422,7 @@ export const withLogSpan = dual< * * @example * ```ts - * import { Effect, Exit } from "effect" - * import { Metric } from "effect" + * import { Effect, Exit, Metric } from "effect" * * // Track different exit types with custom mapping * const exitTracker = Metric.frequency("exit_types", { @@ -10508,8 +10482,7 @@ export const track: { * * @example * ```ts - * import { Effect } from "effect" - * import { Metric } from "effect" + * import { Effect, Metric } from "effect" * * const successCounter = Metric.counter("successes").pipe( * Metric.withConstantInput(1) @@ -10527,8 +10500,7 @@ export const track: { * * @example * ```ts - * import { Effect } from "effect" - * import { Metric } from "effect" + * import { Effect, Metric } from "effect" * * // Track successful request sizes * const requestSizeGauge = Metric.gauge("request_size_bytes") @@ -10585,8 +10557,7 @@ export const trackSuccesses: { * * @example * ```ts - * import { Effect } from "effect" - * import { Metric } from "effect" + * import { Effect, Metric } from "effect" * * const errorCounter = Metric.counter("errors").pipe( * Metric.withConstantInput(1) @@ -10604,8 +10575,7 @@ export const trackSuccesses: { * * @example * ```ts - * import { Effect } from "effect" - * import { Metric } from "effect" + * import { Effect, Metric } from "effect" * * // Track error types using frequency metric * const errorTypeFrequency = Metric.frequency("error_types") @@ -10662,8 +10632,7 @@ export const trackErrors: { * * @example * ```ts - * import { Effect } from "effect" - * import { Metric } from "effect" + * import { Effect, Metric } from "effect" * * const defectCounter = Metric.counter("defects").pipe( * Metric.withConstantInput(1) @@ -10681,8 +10650,7 @@ export const trackErrors: { * * @example * ```ts - * import { Effect } from "effect" - * import { Metric } from "effect" + * import { Effect, Metric } from "effect" * * // Track defect types using frequency metric * const defectTypeFrequency = Metric.frequency("defect_types") @@ -10739,9 +10707,7 @@ export const trackDefects: { * * @example * ```ts - * import { Effect } from "effect" - * import { Metric } from "effect" - * import { Duration } from "effect" + * import { Effect, Metric } from "effect" * * const executionTimer = Metric.timer("execution_time") * @@ -10757,9 +10723,7 @@ export const trackDefects: { * * @example * ```ts - * import { Effect } from "effect" - * import { Metric } from "effect" - * import { Duration } from "effect" + * import { Duration, Effect, Metric } from "effect" * * // Track execution time in milliseconds using custom mapping * const durationGauge = Metric.gauge("execution_millis") @@ -10830,7 +10794,7 @@ export const trackDuration: { * import { Effect } from "effect" * * // Transaction class for software transactional memory operations - * const txEffect = Effect.gen(function* () { + * const txEffect = Effect.gen(function*() { * const tx = yield* Effect.Transaction * // Use transaction for coordinated state changes * return "Transaction complete" @@ -10874,12 +10838,12 @@ export class Transaction extends ServiceMap.Service< * import { Effect } from "effect" * import { TxRef } from "effect/stm" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const ref1 = yield* TxRef.make(0) * const ref2 = yield* TxRef.make(0) * * // All operations within atomic block succeed or fail together - * yield* Effect.atomic(Effect.gen(function* () { + * yield* Effect.atomic(Effect.gen(function*() { * yield* TxRef.set(ref1, 10) * yield* TxRef.set(ref2, 20) * const sum = (yield* TxRef.get(ref1)) + (yield* TxRef.get(ref2)) @@ -10907,7 +10871,7 @@ export const atomic = ( * import { TxRef } from "effect/stm" * * const program = Effect.atomicWith((txState) => - * Effect.gen(function* () { + * Effect.gen(function*() { * const ref = yield* TxRef.make(0) * * // Access transaction state for debugging @@ -10966,22 +10930,22 @@ export const atomicWith = ( * import { Effect } from "effect" * import { TxRef } from "effect/stm" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const ref1 = yield* TxRef.make(0) * const ref2 = yield* TxRef.make(100) * * // Nested atomic transaction - ref1 will be part of outer transaction - * yield* Effect.atomic(Effect.gen(function* () { + * yield* Effect.atomic(Effect.gen(function*() { * yield* TxRef.set(ref1, 10) * * // This atomic operation composes with the parent - * yield* Effect.atomic(Effect.gen(function* () { + * yield* Effect.atomic(Effect.gen(function*() { * yield* TxRef.set(ref1, 20) // Part of same transaction * })) * })) * * // Isolated transaction - ref2 will be in its own transaction - * yield* Effect.transaction(Effect.gen(function* () { + * yield* Effect.transaction(Effect.gen(function*() { * yield* TxRef.set(ref2, 200) * })) * @@ -11010,7 +10974,7 @@ export const transaction = ( * import { TxRef } from "effect/stm" * * const program = Effect.transactionWith((txState) => - * Effect.gen(function* () { + * Effect.gen(function*() { * const ref = yield* TxRef.make(0) * * // This transaction is isolated - it has its own journal @@ -11023,7 +10987,7 @@ export const transaction = ( * * // Even when nested in another atomic block, this transaction is isolated * const nestedProgram = Effect.atomic( - * Effect.gen(function* () { + * Effect.gen(function*() { * const result = yield* program // Runs in its own isolated transaction * return result * }) @@ -11173,7 +11137,10 @@ export const retryTransaction: Effect = flatMap( * import { Effect } from "effect" * * // Effectify namespace contains utilities for converting callback-based APIs - * declare function readFile(path: string, cb: (err: Error | null, data?: string) => void): void + * 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 * ``` @@ -11192,10 +11159,13 @@ export declare namespace Effectify { * @category Effectify * @example * ```ts - * import { Effect } from "effect" + * import type { Effect } from "effect" * * // Effectify type converts callback-based function types to Effect-based types - * type CallbackFn = (x: number, cb: (err: Error | null, result?: string) => void) => void + * type CallbackFn = ( + * x: number, + * cb: (err: Error | null, result?: string) => void + * ) => void * type EffectFn = Effect.Effectify.Effectify * // Result: (x: number) => Effect * ``` @@ -11347,10 +11317,13 @@ export declare namespace Effectify { * @since 4.0.0 * @example * ```ts - * import { Effect } from "effect" + * import type { Effect } from "effect" * * // EffectifyError extracts error types from callback-based function types - * type CallbackFn = (x: number, cb: (err: Error | null, result?: string) => void) => void + * type CallbackFn = ( + * x: number, + * cb: (err: Error | null, result?: string) => void + * ) => void * type ErrorType = Effect.Effectify.EffectifyError * // Result: Error | null * ``` @@ -11605,11 +11578,11 @@ export const satisfiesServicesType = () => (effect: Effec * * // For resolved effects, the mapping is applied immediately * const resolved = Effect.succeed(5) - * const mapped = Effect.mapEager(resolved, n => n * 2) // Applied eagerly + * const mapped = Effect.mapEager(resolved, (n) => n * 2) // Applied eagerly * * // For pending effects, behaves like regular map * const pending = Effect.delay(Effect.succeed(5), "100 millis") - * const mappedPending = Effect.mapEager(pending, n => n * 2) // Uses regular map + * const mappedPending = Effect.mapEager(pending, (n) => n * 2) // Uses regular map * ``` * * @since 4.0.0 @@ -11646,7 +11619,10 @@ export const mapEager: { * * // For pending effects, behaves like regular mapError * const pending = Effect.delay(Effect.fail("error"), "100 millis") - * const mappedPending = Effect.mapErrorEager(pending, (err: string) => `mapped: ${err}`) // Uses regular mapError + * const mappedPending = Effect.mapErrorEager( + * pending, + * (err: string) => `mapped: ${err}` + * ) // Uses regular mapError * ``` * * @since 4.0.0 @@ -11726,11 +11702,14 @@ export const mapBothEager: { * * // For resolved effects, the flatMap is applied immediately * const resolved = Effect.succeed(5) - * const flatMapped = Effect.flatMapEager(resolved, n => Effect.succeed(n * 2)) // Applied eagerly + * const flatMapped = Effect.flatMapEager(resolved, (n) => Effect.succeed(n * 2)) // Applied eagerly * * // For pending effects, behaves like regular flatMap * const pending = Effect.delay(Effect.succeed(5), "100 millis") - * const flatMappedPending = Effect.flatMapEager(pending, n => Effect.succeed(n * 2)) // Uses regular flatMap + * const flatMappedPending = Effect.flatMapEager( + * pending, + * (n) => Effect.succeed(n * 2) + * ) // Uses regular flatMap * ``` * * @since 4.0.0 @@ -11763,20 +11742,23 @@ export const flatMapEager: { * * // For resolved failure effects, the catch function is applied immediately * const failed = Effect.fail("original error") - * const recovered = Effect.catchEager(failed, (err: string) => - * Effect.succeed(`recovered from: ${err}`) + * const recovered = Effect.catchEager( + * failed, + * (err: string) => Effect.succeed(`recovered from: ${err}`) * ) // Applied eagerly * * // For success effects, returns success as-is * const success = Effect.succeed(42) - * const unchanged = Effect.catchEager(success, (err: string) => - * Effect.succeed(`recovered from: ${err}`) + * const unchanged = Effect.catchEager( + * success, + * (err: string) => Effect.succeed(`recovered from: ${err}`) * ) // Returns success as-is * * // For pending effects, behaves like regular catch * const pending = Effect.delay(Effect.fail("error"), "100 millis") - * const recoveredPending = Effect.catchEager(pending, (err: string) => - * Effect.succeed(`recovered from: ${err}`) + * const recoveredPending = Effect.catchEager( + * pending, + * (err: string) => Effect.succeed(`recovered from: ${err}`) * ) // Uses regular catch * ``` * diff --git a/packages/effect/src/Equal.ts b/packages/effect/src/Equal.ts index 0b2693ea2c..65617c82ca 100644 --- a/packages/effect/src/Equal.ts +++ b/packages/effect/src/Equal.ts @@ -30,8 +30,8 @@ export const symbol = "~effect/interfaces/Equal" * * [Equal.symbol](that: Equal.Equal): boolean { * return that instanceof Coordinate && - * this.x === that.x && - * this.y === that.y + * this.x === that.x && + * this.y === that.y * } * * [Hash.symbol](): number { @@ -345,8 +345,7 @@ export const isEqual = (u: unknown): u is Equal => hasProperty(u, symbol) * * @example * ```ts - * import { Equal } from "effect" - * import { Array } from "effect" + * import { Array, Equal } from "effect" * * const eq = Equal.equivalence() * const result = Array.dedupeWith([1, 2, 2, 3, 1], eq) diff --git a/packages/effect/src/Equivalence.ts b/packages/effect/src/Equivalence.ts index 118202f525..d89ac477b2 100644 --- a/packages/effect/src/Equivalence.ts +++ b/packages/effect/src/Equivalence.ts @@ -10,8 +10,7 @@ * * @example * ```ts - * import { Equivalence } from "effect" - * import { Array } from "effect" + * import { Array, Equivalence } from "effect" * * // Case-insensitive string equivalence * const caseInsensitive = Equivalence.make((a, b) => @@ -49,7 +48,7 @@ import type { TypeLambda } from "./types/HKT.ts" * * @example * ```ts - * import { Equivalence } from "effect" + * import type { Equivalence } from "effect" * * // Simple number equivalence * const numberEq: Equivalence.Equivalence = (a, b) => a === b @@ -82,11 +81,17 @@ export type Equivalence = (self: A, that: A) => boolean * * @example * ```ts - * import { Equivalence } from "effect" + * import type { Equivalence } from "effect" * import type { Kind } from "effect/types/HKT" * * // Used internally for type-level computations - * type NumberEquivalence = Kind + * type NumberEquivalence = Kind< + * Equivalence.EquivalenceTypeLambda, + * never, + * never, + * never, + * number + * > * // Equivalent to: Equivalence.Equivalence * ``` * @@ -120,9 +125,7 @@ export interface EquivalenceTypeLambda extends TypeLambda { * console.log(caseInsensitive(str, str)) // true (fast path) * * // Numeric tolerance equivalence - * const tolerance = Equivalence.make((a, b) => - * Math.abs(a - b) < 0.0001 - * ) + * 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.00001)) // true @@ -225,9 +228,18 @@ export const combine: { * z: number * } * - * const xEq = Equivalence.mapInput(Equivalence.strict(), (p: Point3D) => p.x) - * const yEq = Equivalence.mapInput(Equivalence.strict(), (p: Point3D) => p.y) - * const zEq = Equivalence.mapInput(Equivalence.strict(), (p: Point3D) => p.z) + * const xEq = Equivalence.mapInput( + * Equivalence.strict(), + * (p: Point3D) => p.x + * ) + * const yEq = Equivalence.mapInput( + * Equivalence.strict(), + * (p: Point3D) => p.y + * ) + * const zEq = Equivalence.mapInput( + * Equivalence.strict(), + * (p: Point3D) => p.z + * ) * * const point3DEq = Equivalence.combineAll([xEq, yEq, zEq]) * @@ -345,11 +357,13 @@ export const mapInput: { * * const customTupleEq = Equivalence.tuple([ * caseInsensitive, - * caseInsensitive, // Case-insensitive string comparison + * caseInsensitive, // Case-insensitive string comparison * caseInsensitive * ]) * - * console.log(customTupleEq(["Hello", "World", "Test"], ["HELLO", "WORLD", "TEST"])) // true + * console.log( + * customTupleEq(["Hello", "World", "Test"], ["HELLO", "WORLD", "TEST"]) + * ) // true * ``` * * @category combinators @@ -439,9 +453,9 @@ export function array(item: Equivalence): Equivalence> { * ) * * const personEq = Equivalence.struct({ - * name: caseInsensitive, // Case-insensitive name comparison - * age: Equivalence.strict(), // Exact age comparison - * email: caseInsensitive // Case-insensitive email comparison + * name: caseInsensitive, // Case-insensitive name comparison + * age: Equivalence.strict(), // Exact age comparison + * email: caseInsensitive // Case-insensitive email comparison * }) * * const person1 = { name: "Alice", age: 30, email: "alice@example.com" } diff --git a/packages/effect/src/ExecutionPlan.ts b/packages/effect/src/ExecutionPlan.ts index 5a21aee4e1..a5bd6b2265 100644 --- a/packages/effect/src/ExecutionPlan.ts +++ b/packages/effect/src/ExecutionPlan.ts @@ -34,9 +34,9 @@ export const isExecutionPlan = (u: unknown): u is ExecutionPlan => Predicat * A `ExecutionPlan` can be used with `Effect.withExecutionPlan` or `Stream.withExecutionPlan`, allowing you to provide different resources for each step of execution until the effect succeeds or the plan is exhausted. * * ```ts - * import type { LanguageModel } from "effect/unstable/ai" * import type { Layer } from "effect" * import { Effect, ExecutionPlan, Schedule } from "effect" + * import type { LanguageModel } from "effect/unstable/ai" * * declare const layerBad: Layer.Layer * declare const layerGood: Layer.Layer @@ -124,9 +124,9 @@ 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. * * ```ts - * import type { LanguageModel } from "effect/unstable/ai" * import type { Layer } from "effect" * import { Effect, ExecutionPlan, Schedule } from "effect" + * import type { LanguageModel } from "effect/unstable/ai" * * declare const layerBad: Layer.Layer * declare const layerGood: Layer.Layer diff --git a/packages/effect/src/Exit.ts b/packages/effect/src/Exit.ts index 57bf3ae3be..eab09dfde8 100644 --- a/packages/effect/src/Exit.ts +++ b/packages/effect/src/Exit.ts @@ -144,7 +144,7 @@ export const succeed: (a: A) => Exit = core.exitSucceed * * @example * ```ts - * import { Exit, Cause } from "effect" + * import { Cause, Exit } from "effect" * * const cause = Cause.fail("Something went wrong") * const exit = Exit.failCause(cause) @@ -408,10 +408,10 @@ export const match: { * const success = Exit.succeed(42) * const failure = Exit.fail("error") * - * const doubled = Exit.map(success, x => x * 2) + * const doubled = Exit.map(success, (x) => x * 2) * console.log(doubled) // Exit.succeed(84) * - * const stillFailure = Exit.map(failure, x => x * 2) + * const stillFailure = Exit.map(failure, (x) => x * 2) * console.log(stillFailure) // Exit.fail("error") * ``` * diff --git a/packages/effect/src/Fiber.ts b/packages/effect/src/Fiber.ts index 17008cebe3..8012e19987 100644 --- a/packages/effect/src/Fiber.ts +++ b/packages/effect/src/Fiber.ts @@ -18,15 +18,13 @@ * * @example * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" - * import { Fiber } from "effect" + * import { Console, Effect, Fiber } from "effect" * * // Basic fiber operations - * const basicExample = Effect.gen(function* () { + * const basicExample = Effect.gen(function*() { * // Fork an effect to run concurrently * const fiber = yield* Effect.forkChild( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Effect.sleep("2 seconds") * yield* Console.log("Background task completed") * return "background result" @@ -43,7 +41,7 @@ * }) * * // Joining multiple fibers - * const joinExample = Effect.gen(function* () { + * const joinExample = Effect.gen(function*() { * const task1 = Effect.delay(Effect.succeed("task1"), "1 second") * const task2 = Effect.delay(Effect.succeed("task2"), "2 seconds") * @@ -58,9 +56,9 @@ * }) * * // Parallel execution with structured concurrency - * const parallelExample = Effect.gen(function* () { - * const tasks = [1, 2, 3, 4, 5].map(n => - * Effect.gen(function* () { + * 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 * }) @@ -97,10 +95,9 @@ const TypeId = `~effect/Fiber/${version}` * * @example * ```ts - * import { Effect } from "effect" - * import { Fiber } from "effect" + * import { Effect, Fiber } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * // Fork an effect to run in a new fiber * const fiber = yield* Effect.forkChild(Effect.succeed(42)) * @@ -141,10 +138,9 @@ export interface Fiber extends Pipeable { * * @example * ```ts - * import { Effect } from "effect" - * import { Fiber } from "effect" + * import { Effect, Fiber } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * // Create a fiber * const fiber = yield* Effect.forkChild(Effect.succeed(42)) * @@ -170,7 +166,7 @@ export declare namespace Fiber { * * @example * ```ts - * import { Fiber } from "effect" + * import type { Fiber } from "effect" * * // Variance allows safe subtyping * declare const fiber: Fiber.Fiber @@ -193,10 +189,9 @@ export { * * @example * ```ts - * import { Effect } from "effect" - * import { Fiber } from "effect" + * import { Effect, Fiber } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const fiber = yield* Effect.forkChild(Effect.succeed(42)) * const exit = yield* Fiber.await(fiber) * console.log(exit) // Exit.succeed(42) @@ -214,10 +209,9 @@ export { * * @example * ```ts - * import { Effect } from "effect" - * import { Fiber } from "effect" + * import { Effect, Fiber } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const fiber1 = yield* Effect.forkChild(Effect.succeed(1)) * const fiber2 = yield* Effect.forkChild(Effect.succeed(2)) * const exits = yield* Fiber.awaitAll([fiber1, fiber2]) @@ -245,10 +239,9 @@ export const awaitAll: >( * * @example * ```ts - * import { Effect } from "effect" - * import { Fiber } from "effect" + * import { Effect, Fiber } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const fiber = yield* Effect.forkChild(Effect.succeed(42)) * const result = yield* Fiber.join(fiber) * console.log(result) // 42 @@ -277,11 +270,12 @@ export const joinAll: >( * * @example * ```ts - * import { Effect } from "effect" - * import { Fiber } from "effect" + * import { Effect, Fiber } from "effect" * - * const program = Effect.gen(function* () { - * const fiber = yield* Effect.forkChild(Effect.delay("1 second")(Effect.succeed(42))) + * const program = Effect.gen(function*() { + * const fiber = yield* Effect.forkChild( + * Effect.delay("1 second")(Effect.succeed(42)) + * ) * yield* Fiber.interrupt(fiber) * console.log("Fiber interrupted") * }) @@ -298,10 +292,9 @@ export const interrupt: (self: Fiber) => Effect = effect.fiber * * @example * ```ts - * import { Effect } from "effect" - * import { Fiber } from "effect" + * import { Effect, Fiber } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const targetFiber = yield* Effect.forkChild( * Effect.delay("5 seconds")(Effect.succeed("task completed")) * ) @@ -326,14 +319,12 @@ export const interruptAs: { * * @example * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" - * import { Fiber } from "effect" + * import { Console, Effect, Fiber } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * // Create multiple long-running fibers * const fiber1 = yield* Effect.forkChild( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Effect.sleep("5 seconds") * yield* Console.log("Task 1 completed") * return "result1" @@ -341,7 +332,7 @@ export const interruptAs: { * ) * * const fiber2 = yield* Effect.forkChild( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Effect.sleep("3 seconds") * yield* Console.log("Task 2 completed") * return "result2" @@ -349,7 +340,7 @@ export const interruptAs: { * ) * * const fiber3 = yield* Effect.forkChild( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Effect.sleep("4 seconds") * yield* Console.log("Task 3 completed") * return "result3" @@ -378,17 +369,15 @@ export const interruptAll: >>( * * @example * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" - * import { Fiber } from "effect" + * import { Console, Effect, Fiber } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * // Create a controlling fiber * const controllerFiber = yield* Effect.forkChild(Effect.succeed("controller")) * * // Create multiple worker fibers * const worker1 = yield* Effect.forkChild( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Effect.sleep("5 seconds") * yield* Console.log("Worker 1 completed") * return "worker1" @@ -396,7 +385,7 @@ export const interruptAll: >>( * ) * * const worker2 = yield* Effect.forkChild( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Effect.sleep("3 seconds") * yield* Console.log("Worker 2 completed") * return "worker2" @@ -425,10 +414,9 @@ export const interruptAllAs: { * * @example * ```ts - * import { Effect } from "effect" - * import { Fiber } from "effect" + * import { Effect, Fiber } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * // Create a fiber * const fiber = yield* Effect.forkChild(Effect.succeed(42)) * @@ -460,10 +448,9 @@ export const isFiber = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Fiber } from "effect" + * import { Effect, Fiber } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const current = Fiber.getCurrent() * if (current) { * console.log(`Current fiber ID: ${current.id}`) diff --git a/packages/effect/src/FiberHandle.ts b/packages/effect/src/FiberHandle.ts index d075ae1824..f6ef08008a 100644 --- a/packages/effect/src/FiberHandle.ts +++ b/packages/effect/src/FiberHandle.ts @@ -542,7 +542,7 @@ const runImpl = ( * readonly _: unique symbol * } * const Users = ServiceMap.Service> + * getAll: Effect.Effect> * }>("Users") * * Effect.gen(function*() { @@ -550,10 +550,10 @@ 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.asEffect(), (_) => _.getAll)) * * // this will interrupt the previous fiber - * run(Effect.andThen(Users.asEffect(), _ => _.getAll)) + * run(Effect.andThen(Users.asEffect(), (_) => _.getAll)) * }).pipe( * Effect.scoped // The fiber will be interrupted when the scope is closed * ) @@ -679,13 +679,13 @@ export const runtimePromise = (self: FiberHandle): () => * ```ts * import { Effect, FiberHandle } from "effect" * - * Effect.gen(function* () { + * Effect.gen(function*() { * const handle = yield* FiberHandle.make() * yield* FiberHandle.set(handle, Effect.runFork(Effect.fail("error"))) * * // parent fiber will fail with "error" * yield* FiberHandle.join(handle) - * }); + * }) * ``` * * @since 2.0.0 diff --git a/packages/effect/src/FiberMap.ts b/packages/effect/src/FiberMap.ts index e2fffc25e8..e6457ab00c 100644 --- a/packages/effect/src/FiberMap.ts +++ b/packages/effect/src/FiberMap.ts @@ -27,10 +27,10 @@ const TypeId = "~effect/FiberMap" * * @example * ```ts - * import { Effect, Fiber, FiberMap } from "effect" + * import { Effect, FiberMap } from "effect" * * // Create a FiberMap with string keys - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const map = yield* FiberMap.make() * * // Add some fibers to the map @@ -62,9 +62,9 @@ export interface FiberMap /** * @example * ```ts - * import { Effect, Fiber, FiberMap } from "effect" + * import { Effect, FiberMap } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const map = yield* FiberMap.make() * * console.log(FiberMap.isFiberMap(map)) // true @@ -114,7 +114,7 @@ const makeUnsafe = ( * * @example * ```ts - * import { Effect, Fiber, FiberMap } from "effect" + * import { Effect, FiberMap } from "effect" * * Effect.gen(function*() { * const map = yield* FiberMap.make() @@ -158,7 +158,7 @@ export const make = (): Effect.Effect() * * // Run effects and get back fibers @@ -200,9 +200,9 @@ export const makeRuntime = (): Effect.Effect< * * @example * ```ts - * import { Effect, Fiber, FiberMap } from "effect" + * import { Effect, FiberMap } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const run = yield* FiberMap.makeRuntimePromise() * * // Run effects and get back promises @@ -252,7 +252,7 @@ const isInternalInterruption = Filter.toPredicate(Filter.compose( * ```ts * import { Effect, Fiber, FiberMap } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const map = yield* FiberMap.make() * * // Create a fiber and add it to the map @@ -342,7 +342,7 @@ export const setUnsafe: { * ```ts * import { Effect, Fiber, FiberMap } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const map = yield* FiberMap.make() * * // Create a fiber and add it to the map using Effect @@ -393,7 +393,7 @@ export const set: { * ```ts * import { Effect, Fiber, FiberMap } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const map = yield* FiberMap.make() * * // Add a fiber to the map @@ -431,7 +431,7 @@ export const getUnsafe: { * ```ts * import { Effect, Fiber, FiberMap } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const map = yield* FiberMap.make() * * // Add a fiber to the map @@ -464,9 +464,9 @@ export const get: { * * @example * ```ts - * import { Effect, Fiber, FiberMap } from "effect" + * import { Effect, FiberMap } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const map = yield* FiberMap.make() * * // Add a fiber to the map @@ -496,9 +496,9 @@ export const hasUnsafe: { * * @example * ```ts - * import { Effect, Fiber, FiberMap } from "effect" + * import { Effect, FiberMap } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const map = yield* FiberMap.make() * * // Add a fiber to the map @@ -529,9 +529,9 @@ export const has: { * * @example * ```ts - * import { Effect, Fiber, FiberMap } from "effect" + * import { Effect, FiberMap } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const map = yield* FiberMap.make() * * // Add some fibers to the map @@ -578,9 +578,9 @@ export const remove: { * * @example * ```ts - * import { Effect, Fiber, FiberMap } from "effect" + * import { Effect, FiberMap } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const map = yield* FiberMap.make() * * // Add some fibers to the map @@ -626,7 +626,7 @@ const constInterruptedFiber = (function() { * ```ts * import { Effect, Fiber, FiberMap } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const map = yield* FiberMap.make() * * // Run effects and add the fibers to the map @@ -708,7 +708,7 @@ const runImpl = ( * readonly _: unique symbol * } * const Users = ServiceMap.Service> + * getAll: Effect.Effect> * }>("Users") * * Effect.gen(function*() { @@ -716,8 +716,8 @@ 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.asEffect(), (_) => _.getAll)) + * run("effect-b", Effect.andThen(Users.asEffect(), (_) => _.getAll)) * }).pipe( * Effect.scoped // The fibers will be interrupted when the scope is closed * ) @@ -774,9 +774,9 @@ export const runtime: ( * * @example * ```ts - * import { Effect, Fiber, FiberMap } from "effect" + * import { Effect, FiberMap } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const map = yield* FiberMap.make() * const runPromise = yield* FiberMap.runtimePromise(map)() * @@ -836,9 +836,9 @@ export const runtimePromise = (self: FiberMap): () * * @example * ```ts - * import { Effect, Fiber, FiberMap } from "effect" + * import { Effect, FiberMap } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const map = yield* FiberMap.make() * * console.log(yield* FiberMap.size(map)) // 0 @@ -863,15 +863,15 @@ export const size = (self: FiberMap): Effect.Effect => * * @example * ```ts - * import { Effect, Fiber, FiberMap } from "effect" + * import { Effect, FiberMap } from "effect" * - * Effect.gen(function* () { + * Effect.gen(function*() { * const map = yield* FiberMap.make() * yield* FiberMap.set(map, "a", Effect.runFork(Effect.fail("error"))) * * // parent fiber will fail with "error" * yield* FiberMap.join(map) - * }); + * }) * ``` * * @since 2.0.0 @@ -886,9 +886,9 @@ export const join = (self: FiberMap): Effect.Effect = * * @example * ```ts - * import { Effect, Fiber, FiberMap } from "effect" + * import { Effect, FiberMap } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const map = yield* FiberMap.make() * * // Add some fibers that will complete after a delay diff --git a/packages/effect/src/FiberSet.ts b/packages/effect/src/FiberSet.ts index 4afdf6ac83..024a583bad 100644 --- a/packages/effect/src/FiberSet.ts +++ b/packages/effect/src/FiberSet.ts @@ -462,7 +462,7 @@ const runImpl = ( * readonly _: unique symbol * } * const Users = ServiceMap.Service> + * getAll: Effect.Effect> * }>("Users") * * Effect.gen(function*() { @@ -470,7 +470,7 @@ 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.asEffect(), (_) => _.getAll)) * }).pipe( * Effect.scoped // The fibers will be interrupted when the scope is closed * ) @@ -574,8 +574,7 @@ export const runtimePromise = (self: FiberSet): () => Eff * * @example * ```ts - * import { Effect } from "effect" - * import { FiberSet } from "effect" + * import { Effect, FiberSet } from "effect" * * const program = Effect.gen(function*() { * const set = yield* FiberSet.make() @@ -604,13 +603,13 @@ export const size = (self: FiberSet): Effect.Effect => * ```ts * import { Effect, FiberSet } from "effect" * - * Effect.gen(function* () { + * Effect.gen(function*() { * const set = yield* FiberSet.make() * yield* FiberSet.add(set, Effect.runFork(Effect.fail("error"))) * * // parent fiber will fail with "error" * yield* FiberSet.join(set) - * }); + * }) * ``` * * @since 2.0.0 diff --git a/packages/effect/src/platform/FileSystem.ts b/packages/effect/src/FileSystem.ts similarity index 89% rename from packages/effect/src/platform/FileSystem.ts rename to packages/effect/src/FileSystem.ts index 805e143d93..d82f9237bc 100644 --- a/packages/effect/src/platform/FileSystem.ts +++ b/packages/effect/src/FileSystem.ts @@ -9,11 +9,9 @@ * * @example * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" - * import { FileSystem } from "effect/platform" + * import { Console, Effect, FileSystem } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const fs = yield* FileSystem.FileSystem * * // Create a directory @@ -37,19 +35,19 @@ * * @since 4.0.0 */ -import * as Arr from "../Array.ts" -import * as Brand from "../Brand.ts" -import * as Effect from "../Effect.ts" -import { pipe } from "../Function.ts" -import * as Layer from "../Layer.ts" -import * as Pull from "../Pull.ts" -import type { Scope } from "../Scope.ts" -import * as ServiceMap from "../ServiceMap.ts" -import * as Sink from "../Sink.ts" -import * as Stream from "../Stream.ts" -import * as UndefinedOr from "../UndefinedOr.ts" +import * as Arr from "./Array.ts" +import * as Brand from "./Brand.ts" +import * as Effect from "./Effect.ts" +import { pipe } from "./Function.ts" +import * as Layer from "./Layer.ts" import type { PlatformError } from "./PlatformError.ts" import { BadArgument, SystemError } from "./PlatformError.ts" +import * as Pull from "./Pull.ts" +import type { Scope } from "./Scope.ts" +import * as ServiceMap from "./ServiceMap.ts" +import * as Sink from "./Sink.ts" +import * as Stream from "./Stream.ts" +import * as UndefinedOr from "./UndefinedOr.ts" const TypeId = "~effect/platform/FileSystem" @@ -62,17 +60,15 @@ const TypeId = "~effect/platform/FileSystem" * * @example * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" - * import { FileSystem } from "effect/platform" + * import { Console, Effect, FileSystem } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const fs = yield* FileSystem.FileSystem * * // Basic file operations * const exists = yield* fs.exists("./config.json") * if (!exists) { - * yield* fs.writeFileString("./config.json", '{"env": "development"}') + * yield* fs.writeFileString("./config.json", "{\"env\": \"development\"}") * } * * // Directory operations @@ -379,8 +375,7 @@ export interface FileSystem { * * @example * ```ts - * import { Effect } from "effect" - * import { FileSystem } from "effect/platform" + * import { Effect, FileSystem } from "effect" * * // Create sizes using the Size constructor * const smallFile = FileSystem.Size(1024) // 1 KB @@ -388,7 +383,7 @@ export interface FileSystem { * * // Use with file operations * const truncateToSize = (path: string, size: FileSystem.Size) => - * Effect.gen(function* () { + * Effect.gen(function*() { * const fs = yield* FileSystem.FileSystem * return fs.truncate(path, size) * }) @@ -408,14 +403,13 @@ export type Size = Brand.Branded * * @example * ```ts - * import { Effect } from "effect" - * import { FileSystem } from "effect/platform" + * import { Effect, FileSystem } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const fs = yield* FileSystem.FileSystem * * // All of these are valid SizeInput values - * yield* fs.truncate("file1.txt", 1024) // number + * yield* fs.truncate("file1.txt", 1024) // number * yield* fs.truncate("file2.txt", BigInt(2048)) // bigint * yield* fs.truncate("file3.txt", FileSystem.Size(4096)) // Size * }) @@ -435,8 +429,7 @@ export type SizeInput = bigint | number | Size * * @example * ```ts - * import { Effect } from "effect" - * import { FileSystem } from "effect/platform" + * import { Effect, FileSystem } from "effect" * * // From number * const size1 = FileSystem.Size(1024) @@ -450,7 +443,7 @@ export type SizeInput = bigint | number | Size * * // Use in file operations * const readChunk = (path: string, chunkSize: number) => - * Effect.gen(function* () { + * Effect.gen(function*() { * const fs = yield* FileSystem.FileSystem * return fs.stream(path, { * chunkSize: FileSystem.Size(chunkSize) @@ -471,10 +464,9 @@ export const Size = (bytes: SizeInput): Size => typeof bytes === "bigint" ? byte * * @example * ```ts - * import { Effect } from "effect" - * import { FileSystem } from "effect/platform" + * import { Effect, FileSystem } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const fs = yield* FileSystem.FileSystem * * // Create a 64 KiB buffer size for streaming @@ -502,10 +494,9 @@ export const KiB = (n: number): Size => Size(n * 1024) * * @example * ```ts - * import { Effect } from "effect" - * import { FileSystem } from "effect/platform" + * import { Effect, FileSystem } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const fs = yield* FileSystem.FileSystem * * // Set a 10 MiB chunk size for large file operations @@ -537,11 +528,9 @@ export const MiB = (n: number): Size => Size(n * 1024 * 1024) * * @example * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" - * import { FileSystem } from "effect/platform" + * import { Console, Effect, FileSystem } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const fs = yield* FileSystem.FileSystem * * // Check available space before creating large files @@ -569,11 +558,9 @@ export const GiB = (n: number): Size => Size(n * 1024 * 1024 * 1024) * * @example * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" - * import { FileSystem } from "effect/platform" + * import { Console, Effect, FileSystem } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const fs = yield* FileSystem.FileSystem * * // Check if we're dealing with very large files @@ -608,11 +595,9 @@ const bigintPiB = bigint1024 * bigint1024 * bigint1024 * bigint1024 * bigint1024 * * @example * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" - * import { FileSystem } from "effect/platform" + * import { Console, Effect, FileSystem } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const fs = yield* FileSystem.FileSystem * * // For extremely large data processing scenarios @@ -624,7 +609,7 @@ const bigintPiB = bigint1024 * bigint1024 * bigint1024 * bigint1024 * bigint1024 * // Such large files would require specialized streaming * const stream = fs.stream("massive-dataset.bin", { * chunkSize: FileSystem.GiB(1), // 1 GiB chunks - * offset: FileSystem.TiB(100) // Start from 100 TiB offset + * offset: FileSystem.TiB(100) // Start from 100 TiB offset * }) * }) * ``` @@ -653,10 +638,9 @@ export const PiB = (n: number): Size => Size(BigInt(n) * bigintPiB) * * @example * ```ts - * import { Effect } from "effect" - * import { FileSystem } from "effect/platform" + * import { Effect, FileSystem } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const fs = yield* FileSystem.FileSystem * * // Open for reading only @@ -696,11 +680,10 @@ export type OpenFlag = * * @example * ```ts - * import { Effect } from "effect" - * import { FileSystem } from "effect/platform" + * import { Effect, FileSystem } from "effect" * * // Access the FileSystem service - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const fs = yield* FileSystem.FileSystem * * const exists = yield* fs.exists("./data.txt") @@ -711,10 +694,17 @@ export type OpenFlag = * }) * * // Provide a custom FileSystem implementation - * declare const platformImpl: Omit + * declare const platformImpl: Omit< + * FileSystem.FileSystem, + * "exists" | "readFileString" | "stream" | "sink" | "writeFileString" + * > * const customFs = FileSystem.make(platformImpl) * - * const withCustomFs = Effect.provideService(program, FileSystem.FileSystem, customFs) + * const withCustomFs = Effect.provideService( + * program, + * FileSystem.FileSystem, + * customFs + * ) * ``` * * @since 4.0.0 @@ -828,34 +818,39 @@ const notFound = (method: string, path: string) => * * @example * ```ts - * import { Effect } from "effect" - * import { FileSystem, PlatformError } from "effect/platform" + * import { Effect, FileSystem, PlatformError } from "effect" * * // Create a test filesystem that only allows reading specific files * const testFs = FileSystem.makeNoop({ * readFileString: (path) => { * if (path === "test-config.json") { - * return Effect.succeed('{"test": true}') + * return Effect.succeed("{\"test\": true}") * } - * return Effect.fail(new PlatformError.SystemError({ - * module: "FileSystem", - * method: "readFileString", - * reason: "NotFound", - * description: "File not found", - * pathOrDescriptor: path - * })) + * return Effect.fail( + * new PlatformError.SystemError({ + * module: "FileSystem", + * method: "readFileString", + * reason: "NotFound", + * description: "File not found", + * pathOrDescriptor: path + * }) + * ) * }, * exists: (path) => Effect.succeed(path === "test-config.json") * }) * * // Use in tests - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const content = yield* testFs.readFileString("test-config.json") * // Will succeed with mocked content * }) * * // Test with the no-op filesystem - * const testProgram = Effect.provideService(program, FileSystem.FileSystem, testFs) + * const testProgram = Effect.provideService( + * program, + * FileSystem.FileSystem, + * testFs + * ) * ``` * * @since 4.0.0 @@ -962,9 +957,7 @@ export const makeNoop = (fileSystem: Partial): FileSystem => * * @example * ```ts - * import { Effect } from "effect" - * import { Layer } from "effect" - * import { FileSystem } from "effect/platform" + * import { Effect, FileSystem } from "effect" * * // Create a test layer with specific behaviors * const testLayer = FileSystem.layerNoop({ @@ -972,7 +965,7 @@ export const makeNoop = (fileSystem: Partial): FileSystem => * exists: () => Effect.succeed(true) * }) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const fs = yield* FileSystem.FileSystem * const content = yield* fs.readFileString("any-file.txt") * return content @@ -1014,16 +1007,14 @@ export const isFile = (u: unknown): u is File => typeof u === "object" && u !== * * @example * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" - * import { FileSystem } from "effect/platform" + * import { Console, Effect, FileSystem } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const fs = yield* FileSystem.FileSystem * * // Open a file and work with the handle * yield* Effect.scoped( - * Effect.gen(function* () { + * Effect.gen(function*() { * const file = yield* fs.open("./data.txt", { flag: "r+" }) * * // Get file information @@ -1105,11 +1096,9 @@ export declare namespace File { * * @example * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" - * import { FileSystem } from "effect/platform" + * import { Console, Effect, FileSystem } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const fs = yield* FileSystem.FileSystem * * const info: FileSystem.File.Info = yield* fs.stat("./data.txt") @@ -1237,9 +1226,7 @@ export declare namespace WatchEvent { * * @example * ```ts - * import { Effect } from "effect" - * import { Stream } from "effect" - * import { FileSystem } from "effect/platform" + * import { Effect, FileSystem, Stream } from "effect" * * // Custom watch backend implementation * const customWatchBackend = { @@ -1250,7 +1237,7 @@ export declare namespace WatchEvent { * } * * // Provide custom watch backend - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const fs = yield* FileSystem.FileSystem * * // File watching will use the custom backend diff --git a/packages/effect/src/Filter.ts b/packages/effect/src/Filter.ts index 16dac607f7..71616de33c 100644 --- a/packages/effect/src/Filter.ts +++ b/packages/effect/src/Filter.ts @@ -20,11 +20,10 @@ import type { EqualsWith, ExcludeTag, ExtractTag, Tags } from "./types/Types.ts" * import { Filter } from "effect" * * // A filter that only passes positive numbers - * const positiveFilter: Filter.Filter = (n) => - * n > 0 ? n : Filter.fail(n) + * const positiveFilter: Filter.Filter = (n) => n > 0 ? n : Filter.fail(n) * - * console.log(positiveFilter(5)) // 5 - * console.log(positiveFilter(-3)) // fail + * console.log(positiveFilter(5)) // 5 + * console.log(positiveFilter(-3)) // fail * ``` * * @since 4.0.0 @@ -42,15 +41,20 @@ export interface Filter { * * @example * ```ts - * import { Effect } from "effect" - * import { Filter } from "effect" + * import { Effect, Filter } from "effect" * * // An effectful filter that validates user data * type User = { id: string; isActive: boolean } * type ValidationError = { message: string } * - * const validateUser: Filter.FilterEffect = (id) => - * Effect.gen(function* () { + * const validateUser: Filter.FilterEffect< + * string, + * User, + * User, + * ValidationError, + * never + * > = (id) => + * Effect.gen(function*() { * // Simple validation logic * const user: User = { id, isActive: id.length > 0 } * return user.isActive ? user : Filter.fail(user) @@ -121,17 +125,15 @@ export type WithoutFail = Exclude> * import { Filter } from "effect" * * // Create a filter for positive numbers - * const positiveFilter = Filter.make((n: number) => - * n > 0 ? n : Filter.fail(n) - * ) + * const positiveFilter = Filter.make((n: number) => n > 0 ? n : Filter.fail(n)) * * // Create a filter that transforms strings to uppercase * const uppercaseFilter = Filter.make((s: string) => * s.length > 0 ? s.toUpperCase() : Filter.fail(s) * ) * - * console.log(positiveFilter(5)) // 5 - * console.log(positiveFilter(-1)) // `fail` + * console.log(positiveFilter(5)) // 5 + * console.log(positiveFilter(-1)) // `fail` * console.log(uppercaseFilter("hi")) // "HI" * ``` * @@ -151,19 +153,18 @@ export const make = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Filter } from "effect" + * import { Effect, Filter } from "effect" * * // Create an effectful filter that validates async * const asyncValidate = Filter.makeEffect((id: string) => - * Effect.gen(function* () { + * Effect.gen(function*() { * const isValid = yield* Effect.succeed(id.length > 0) // Simple validation * return isValid ? id : Filter.fail(id) * }) * ) * * // Use in Effect context - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const result = yield* asyncValidate("user123") * console.log(result) // "user123" or fail * }) @@ -230,12 +231,14 @@ export { * const nonEmptyStrings = Filter.fromPredicate((s: string) => s.length > 0) * * // Type refinement - * const isString = Filter.fromPredicate((x: unknown): x is string => typeof x === "string") + * const isString = Filter.fromPredicate((x: unknown): x is string => + * typeof x === "string" + * ) * - * console.log(positiveNumbers(5)) // 5 - * console.log(positiveNumbers(-1)) // fail - * console.log(isString("hello")) // "hello" (typed as string) - * console.log(isString(42)) // fail + * console.log(positiveNumbers(5)) // 5 + * console.log(positiveNumbers(-1)) // fail + * console.log(isString("hello")) // "hello" (typed as string) + * console.log(isString(42)) // fail * ``` * * @since 4.0.0 @@ -292,14 +295,14 @@ export const toPredicate = ( * ```ts * import { Filter } from "effect" * - * console.log(Filter.string("hello")) // "hello" - * console.log(Filter.string(42)) // fail - * console.log(Filter.string(true)) // fail - * console.log(Filter.string(null)) // fail + * console.log(Filter.string("hello")) // "hello" + * console.log(Filter.string(42)) // fail + * console.log(Filter.string(true)) // fail + * console.log(Filter.string(null)) // fail * * // Use with arrays of mixed types * const mixed = ["a", 1, "b", true, "c"] - * const strings = mixed.map(Filter.string).filter(x => Filter.isPass(x)) + * const strings = mixed.map(Filter.string).filter((x) => Filter.isPass(x)) * console.log(strings) // ["a", "b", "c"] * ``` * @@ -350,11 +353,11 @@ export const instanceOf = * ```ts * import { Filter } from "effect" * - * console.log(Filter.number(42)) // 42 - * console.log(Filter.number(3.14)) // 3.14 - * console.log(Filter.number("42")) // fail - * console.log(Filter.number(true)) // fail - * console.log(Filter.number(NaN)) // fail + * console.log(Filter.number(42)) // 42 + * console.log(Filter.number(3.14)) // 3.14 + * console.log(Filter.number("42")) // fail + * console.log(Filter.number(true)) // fail + * console.log(Filter.number(NaN)) // fail * * // Extract numbers from mixed array * const mixed = [1, "2", 3, true, 4.5] @@ -362,14 +365,19 @@ export const instanceOf = * console.log(numbers) // [1, 3, 4.5] * * // Use with array filtering - * const data: unknown[] = [10, "hello", 20, null, 30.5, "world"] - * const numbersOnly = data.filter(item => Filter.isPass(Filter.number(item))) as number[] + * const data: Array = [10, "hello", 20, null, 30.5, "world"] + * const numbersOnly = data.filter((item) => + * Filter.isPass(Filter.number(item)) + * ) as Array * console.log(numbersOnly) // [10, 20, 30.5] * * // Combine with other filters - * const positiveNumbers = Filter.compose(Filter.number, Filter.fromPredicate((n: number) => n > 0)) - * console.log(positiveNumbers(5)) // 5 - * console.log(positiveNumbers(-1)) // fail + * const positiveNumbers = Filter.compose( + * Filter.number, + * Filter.fromPredicate((n: number) => n > 0) + * ) + * console.log(positiveNumbers(5)) // 5 + * console.log(positiveNumbers(-1)) // fail * console.log(positiveNumbers("5")) // fail * ``` * @@ -524,8 +532,8 @@ export const zipWith: { * // Combine into tuple * const positiveAndEven = Filter.zip(positiveNumbers, evenNumbers) * - * console.log(positiveAndEven(4)) // [4, 4] (both filters pass) - * console.log(positiveAndEven(3)) // fail (not even) + * console.log(positiveAndEven(4)) // [4, 4] (both filters pass) + * console.log(positiveAndEven(3)) // fail (not even) * console.log(positiveAndEven(-2)) // fail (not positive) * * // Different types @@ -571,8 +579,8 @@ export const zip: { * // Validate both conditions but return the original number * const positiveEven = Filter.andLeft(positiveNumbers, evenNumbers) * - * console.log(positiveEven(4)) // 4 (both conditions met, returns left result) - * console.log(positiveEven(3)) // fail (not even) + * console.log(positiveEven(4)) // 4 (both conditions met, returns left result) + * console.log(positiveEven(3)) // fail (not even) * console.log(positiveEven(-2)) // fail (not positive) * * // Useful for validation pipelines @@ -617,12 +625,14 @@ export const andLeft: { * // Validate positive but return doubled value * const positiveDoubled = Filter.andRight(positiveNumbers, doubleNumbers) * - * console.log(positiveDoubled(5)) // 10 (positive, returns doubled) + * console.log(positiveDoubled(5)) // 10 (positive, returns doubled) * console.log(positiveDoubled(-3)) // fail (not positive) * * // Sequential transformations * const nonEmpty = Filter.fromPredicate((s: string) => s.length > 0) - * const uppercase = Filter.make((s: string) => s.length > 0 ? s.toUpperCase() : Filter.fail(s)) + * const uppercase = Filter.make((s: string) => + * s.length > 0 ? s.toUpperCase() : Filter.fail(s) + * ) * const transform = Filter.andRight(nonEmpty, uppercase) * console.log(transform("hello")) // "HELLO" * ``` @@ -667,9 +677,9 @@ export const andRight: { * // Compose: unknown -> string -> uppercase string * const stringToUpper = Filter.compose(stringFilter, nonEmptyUpper) * - * console.log(stringToUpper("hello")) // "HELLO" - * console.log(stringToUpper("")) // fail (empty string) - * console.log(stringToUpper(123)) // fail (not a string) + * console.log(stringToUpper("hello")) // "HELLO" + * console.log(stringToUpper("")) // fail (empty string) + * console.log(stringToUpper(123)) // fail (not a string) * * // Multi-stage number processing * const positiveFilter = Filter.fromPredicate((n: number) => n > 0) diff --git a/packages/effect/src/Function.ts b/packages/effect/src/Function.ts index 48648bfbbb..bb8674398a 100644 --- a/packages/effect/src/Function.ts +++ b/packages/effect/src/Function.ts @@ -9,8 +9,8 @@ import type { TypeLambda } from "./types/HKT.ts" * * @example * ```ts - * import type { Kind } from "effect/types/HKT" * import type { FunctionTypeLambda } from "effect/Function" + * import type { Kind } from "effect/types/HKT" * * // Create a function type using the type lambda * type StringToNumber = Kind @@ -29,8 +29,8 @@ export interface FunctionTypeLambda extends TypeLambda { * * @example * ```ts - * import * as assert from "node:assert" * import * as Predicate from "effect/Predicate" + * import * as assert from "node:assert" * * assert.deepStrictEqual(Predicate.isFunction(Predicate.isFunction), true) * assert.deepStrictEqual(Predicate.isFunction("function"), false) @@ -181,9 +181,9 @@ export const dual: { * * @example * ```ts - * import * as assert from "node:assert" - * import { pipe, apply } from "effect/Function" + * import { apply, pipe } from "effect/Function" * import { length } from "effect/String" + * import * as assert from "node:assert" * * assert.deepStrictEqual(pipe(length, apply("hello")), 5) * ``` @@ -198,8 +198,7 @@ export const apply = (a: A) => (self: (a: A) => B): B => self(a) * * @example * ```ts - * import * as assert from "node:assert" - * import { LazyArg, constant } from "effect/Function" + * import { constant, type LazyArg } from "effect/Function" * * const constNull: LazyArg = constant(null) * ``` @@ -214,8 +213,8 @@ export type LazyArg = () => A * * @example * ```ts + * import type { FunctionN } from "effect/Function" * import * as assert from "node:assert" - * import { FunctionN } from "effect/Function" * * const sum: FunctionN<[number, number], number> = (a, b) => a + b * assert.deepStrictEqual(sum(2, 3), 5) @@ -231,8 +230,8 @@ export type FunctionN, B> = (...args: A) => B * * @example * ```ts - * import * as assert from "node:assert" * import { identity } from "effect/Function" + * import * as assert from "node:assert" * * assert.deepStrictEqual(identity(5), 5) * ``` @@ -248,14 +247,14 @@ export const identity = (a: A): A => a * * @example * ```ts - * import * as assert from "node:assert" * import { satisfies } from "effect/Function" + * import * as assert from "node:assert" * * const test1 = satisfies()(5 as const) - * //^? const test: 5 - * // @ts-expect-error + * // ^? const test: 5 + * // @ts-expect-error * const test2 = satisfies()(5) - * //^? Argument of type 'number' is not assignable to parameter of type 'string' + * // ^? Argument of type 'number' is not assignable to parameter of type 'string' * * assert.deepStrictEqual(satisfies()(5), 5) * ``` @@ -270,8 +269,8 @@ export const satisfies = () => (b: B) => b * * @example * ```ts - * import * as assert from "node:assert" * import { coerceUnsafe, identity } from "effect/Function" + * import * as assert from "node:assert" * * assert.deepStrictEqual(coerceUnsafe, identity) * ``` @@ -289,8 +288,8 @@ export const coerceUnsafe: (a: A) => B = identity as any * * @example * ```ts - * import * as assert from "node:assert" * import { constant } from "effect/Function" + * import * as assert from "node:assert" * * const constNull = constant(null) * @@ -308,8 +307,8 @@ export const constant = (value: A): LazyArg => () => value * * @example * ```ts - * import * as assert from "node:assert" * import { constTrue } from "effect/Function" + * import * as assert from "node:assert" * * assert.deepStrictEqual(constTrue(), true) * ``` @@ -324,8 +323,8 @@ export const constTrue: LazyArg = constant(true) * * @example * ```ts - * import * as assert from "node:assert" * import { constFalse } from "effect/Function" + * import * as assert from "node:assert" * * assert.deepStrictEqual(constFalse(), false) * ``` @@ -340,8 +339,8 @@ export const constFalse: LazyArg = constant(false) * * @example * ```ts - * import * as assert from "node:assert" * import { constNull } from "effect/Function" + * import * as assert from "node:assert" * * assert.deepStrictEqual(constNull(), null) * ``` @@ -356,8 +355,8 @@ export const constNull: LazyArg = constant(null) * * @example * ```ts - * import * as assert from "node:assert" * import { constUndefined } from "effect/Function" + * import * as assert from "node:assert" * * assert.deepStrictEqual(constUndefined(), undefined) * ``` @@ -372,8 +371,8 @@ export const constUndefined: LazyArg = constant(undefined) * * @example * ```ts - * import * as assert from "node:assert" * import { constVoid } from "effect/Function" + * import * as assert from "node:assert" * * assert.deepStrictEqual(constVoid(), undefined) * ``` @@ -388,12 +387,12 @@ export const constVoid: LazyArg = constUndefined * * @example * ```ts - * import * as assert from "node:assert" * import { flip } from "effect/Function" + * import * as assert from "node:assert" * * const f = (a: number) => (b: string) => a - b.length * - * assert.deepStrictEqual(flip(f)('aaa')(2), -1) + * assert.deepStrictEqual(flip(f)("aaa")(2), -1) * ``` * * @category combinators @@ -411,13 +410,13 @@ export const flip = , B extends Array, C>( * * @example * ```ts - * import * as assert from "node:assert" * import { compose } from "effect/Function" + * import * as assert from "node:assert" * - * const increment = (n: number) => n + 1; - * const square = (n: number) => n * n; + * const increment = (n: number) => n + 1 + * const square = (n: number) => n * n * - * assert.strictEqual(compose(increment, square)(2), 9); + * assert.strictEqual(compose(increment, square)(2), 9) * ``` * * @category combinators @@ -455,8 +454,8 @@ export const absurd = (_: never): A => { * * @example * ```ts - * import * as assert from "node:assert" * import { tupled } from "effect/Function" + * import * as assert from "node:assert" * * const sumTupled = tupled((x: number, y: number): number => x + y) * @@ -473,8 +472,8 @@ export const tupled = , B>(f: (...a: A) => B): * * @example * ```ts - * import * as assert from "node:assert" * import { untupled } from "effect/Function" + * import * as assert from "node:assert" * * const getFirst = untupled((tuple: [A, B]): A => tuple[0]) * @@ -530,8 +529,7 @@ export const untupled = , B>(f: (a: A) => B): ( * becomes: * * ```ts skip-type-checking - * import { pipe } from "effect" - * import { Array } from "effect" + * import { Array, pipe } from "effect" * * pipe(as, Array.map(f), Array.filter(g)) * ``` @@ -560,9 +558,9 @@ export const untupled = , B>(f: (a: A) => B): ( * // Simple transformation pipeline * const result = pipe( * 5, - * x => x * 2, // 10 - * x => x + 1, // 11 - * x => x.toString() // "11" + * (x) => x * 2, // 10 + * (x) => x + 1, // 11 + * (x) => x.toString() // "11" * ) * * console.log(result) // "11" @@ -1030,15 +1028,15 @@ export function pipe(a: unknown, ...args: Array): unknown { * * @example * ```ts - * import * as assert from "node:assert" * import { flow } from "effect/Function" + * import * as assert from "node:assert" * * const len = (s: string): number => s.length * const double = (n: number): number => n * 2 * * const f = flow(len, double) * - * assert.strictEqual(f('aaa'), 6) + * assert.strictEqual(f("aaa"), 6) * ``` * * @category combinators @@ -1233,8 +1231,8 @@ export const hole: () => T = coerceUnsafe(absurd) * * @example * ```ts + * import { SK } from "effect/Function" * import * as assert from "node:assert" - * import { SK } from "effect/Function"; * * assert.deepStrictEqual(SK(0, "hello"), "hello") * ``` diff --git a/packages/effect/src/Graph.ts b/packages/effect/src/Graph.ts index 6256040515..fcd818fad8 100644 --- a/packages/effect/src/Graph.ts +++ b/packages/effect/src/Graph.ts @@ -881,9 +881,9 @@ export const mapEdges = ( * const a = Graph.addNode(mutable, "A") * const b = Graph.addNode(mutable, "B") * const c = Graph.addNode(mutable, "C") - * Graph.addEdge(mutable, a, b, 1) // A -> B - * Graph.addEdge(mutable, b, c, 2) // B -> C - * Graph.reverse(mutable) // Now B -> A, C -> B + * Graph.addEdge(mutable, a, b, 1) // A -> B + * Graph.addEdge(mutable, b, c, 2) // B -> C + * Graph.reverse(mutable) // Now B -> A, C -> B * }) * * const edge0 = Graph.getEdge(graph, 0) @@ -943,8 +943,10 @@ export const reverse = ( * Graph.addEdge(mutable, b, c, 2) * * // Keep only "active" nodes and transform to uppercase - * Graph.filterMapNodes(mutable, (data) => - * data === "active" ? Option.some(data.toUpperCase()) : Option.none() + * Graph.filterMapNodes( + * mutable, + * (data) => + * data === "active" ? Option.some(data.toUpperCase()) : Option.none() * ) * }) * @@ -996,8 +998,9 @@ export const filterMapNodes = ( * Graph.addEdge(mutable, c, a, 25) * * // Keep only edges with weight >= 10 and double their weight - * Graph.filterMapEdges(mutable, (data) => - * data >= 10 ? Option.some(data * 2) : Option.none() + * Graph.filterMapEdges( + * mutable, + * (data) => data >= 10 ? Option.some(data * 2) : Option.none() * ) * }) * @@ -1646,7 +1649,7 @@ export const neighborsDirected: { * * @example * ```ts - * import * as Graph from "effect/Graph" + * import type * as Graph from "effect/Graph" * * // Basic options with custom labels * const basicOptions: Graph.GraphVizOptions = { @@ -1776,7 +1779,7 @@ export const toGraphViz: { * * @example * ```ts - * import * as Graph from "effect/Graph" + * import type * as Graph from "effect/Graph" * * // Shape selector function for different node types * const shapeSelector = (nodeData: string): Graph.MermaidNodeShape => { @@ -1816,7 +1819,7 @@ export type MermaidNodeShape = * * @example * ```ts - * import * as Graph from "effect/Graph" + * import type * as Graph from "effect/Graph" * * // Horizontal workflow diagram * const horizontalOptions: Graph.MermaidOptions = { @@ -1856,7 +1859,7 @@ export type MermaidDirection = * * @example * ```ts - * import * as Graph from "effect/Graph" + * import type * as Graph from "effect/Graph" * * // Force flowchart format (even for undirected graphs) * const flowchartOptions: Graph.MermaidOptions = { @@ -1893,7 +1896,7 @@ export type MermaidDiagramType = * * @example * ```ts - * import * as Graph from "effect/Graph" + * import type * as Graph from "effect/Graph" * * // Basic options with custom labels * const basicOptions: Graph.MermaidOptions = { @@ -2026,7 +2029,7 @@ const formatMermaidNode = ( * import * as Graph from "effect/Graph" * * // Undirected graph with custom labels and direction - * const socialGraph = Graph.undirected<{name: string}, string>((mutable) => { + * const socialGraph = Graph.undirected<{ name: string }, string>((mutable) => { * const alice = Graph.addNode(mutable, { name: "Alice" }) * const bob = Graph.addNode(mutable, { name: "Bob" }) * const charlie = Graph.addNode(mutable, { name: "Charlie" }) @@ -2053,25 +2056,38 @@ const formatMermaidNode = ( * import * as Graph from "effect/Graph" * * // Advanced styling with node shapes for flowchart - * const workflow = Graph.directed<{type: string, name: string}, string>((mutable) => { - * const start = Graph.addNode(mutable, { type: "start", name: "Begin" }) - * const process = Graph.addNode(mutable, { type: "process", name: "Process Data" }) - * const decision = Graph.addNode(mutable, { type: "decision", name: "Valid?" }) - * const end = Graph.addNode(mutable, { type: "end", name: "Complete" }) - * Graph.addEdge(mutable, start, process, "") - * Graph.addEdge(mutable, process, decision, "") - * Graph.addEdge(mutable, decision, end, "yes") - * }) + * const workflow = Graph.directed<{ type: string; name: string }, string>( + * (mutable) => { + * const start = Graph.addNode(mutable, { type: "start", name: "Begin" }) + * const process = Graph.addNode(mutable, { + * type: "process", + * name: "Process Data" + * }) + * const decision = Graph.addNode(mutable, { + * type: "decision", + * name: "Valid?" + * }) + * const end = Graph.addNode(mutable, { type: "end", name: "Complete" }) + * Graph.addEdge(mutable, start, process, "") + * Graph.addEdge(mutable, process, decision, "") + * Graph.addEdge(mutable, decision, end, "yes") + * } + * ) * * const mermaid = Graph.toMermaid(workflow, { * nodeLabel: (node) => node.name, * nodeShape: (node) => { * switch (node.type) { - * case "start": return "stadium" - * case "process": return "rectangle" - * case "decision": return "diamond" - * case "end": return "stadium" - * default: return "rectangle" + * case "start": + * return "stadium" + * case "process": + * return "rectangle" + * case "decision": + * return "diamond" + * case "end": + * return "stadium" + * default: + * return "rectangle" * } * } * }) @@ -2098,10 +2114,26 @@ const formatMermaidNode = ( * } * * const dependencyGraph = Graph.directed((mutable) => { - * const app = Graph.addNode(mutable, { name: "MyApp", version: "1.0.0", type: "library" }) - * const react = Graph.addNode(mutable, { name: "React", version: "18.0.0", type: "framework" }) - * const lodash = Graph.addNode(mutable, { name: "Lodash", version: "4.17.0", type: "library" }) - * const webpack = Graph.addNode(mutable, { name: "Webpack", version: "5.0.0", type: "tool" }) + * const app = Graph.addNode(mutable, { + * name: "MyApp", + * version: "1.0.0", + * type: "library" + * }) + * const react = Graph.addNode(mutable, { + * name: "React", + * version: "18.0.0", + * type: "framework" + * }) + * const lodash = Graph.addNode(mutable, { + * name: "Lodash", + * version: "4.17.0", + * type: "library" + * }) + * const webpack = Graph.addNode(mutable, { + * name: "Webpack", + * version: "5.0.0", + * type: "tool" + * }) * * Graph.addEdge(mutable, app, react, "depends on") * Graph.addEdge(mutable, app, lodash, "depends on") @@ -2111,8 +2143,12 @@ const formatMermaidNode = ( * const dependencyDiagram = Graph.toMermaid(dependencyGraph, { * nodeLabel: (dep) => `${dep.name}\\nv${dep.version}`, * edgeLabel: (edge) => edge, - * nodeShape: (dep) => dep.type === "framework" ? "hexagon" : - * dep.type === "tool" ? "diamond" : "rectangle", + * nodeShape: (dep) => + * dep.type === "framework" ? + * "hexagon" : + * dep.type === "tool" + * ? "diamond" + * : "rectangle", * direction: "TB" * }) * @@ -2207,10 +2243,14 @@ export const toMermaid: { * }) * * // Follow outgoing edges (normal direction) - * const outgoingNodes = Array.from(Graph.indices(Graph.dfs(graph, { start: [0], direction: "outgoing" }))) + * const outgoingNodes = Array.from( + * Graph.indices(Graph.dfs(graph, { start: [0], direction: "outgoing" })) + * ) * * // Follow incoming edges (reverse direction) - * const incomingNodes = Array.from(Graph.indices(Graph.dfs(graph, { start: [1], direction: "incoming" }))) + * const incomingNodes = Array.from( + * Graph.indices(Graph.dfs(graph, { start: [1], direction: "incoming" })) + * ) * ``` * * @since 4.0.0 @@ -2656,7 +2696,6 @@ export interface DijkstraConfig { * @example * ```ts * import { Graph } from "effect" - * import * as Option from "effect/Option" * * const graph = Graph.directed((mutable) => { * const a = Graph.addNode(mutable, "A") @@ -3000,23 +3039,25 @@ export interface AstarConfig { * ```ts * import { Graph } from "effect" * - * const graph = Graph.directed<{x: number, y: number}, number>((mutable) => { - * const a = Graph.addNode(mutable, {x: 0, y: 0}) - * const b = Graph.addNode(mutable, {x: 1, y: 0}) - * const c = Graph.addNode(mutable, {x: 2, y: 0}) + * const graph = Graph.directed<{ x: number; y: number }, number>((mutable) => { + * const a = Graph.addNode(mutable, { x: 0, y: 0 }) + * const b = Graph.addNode(mutable, { x: 1, y: 0 }) + * const c = Graph.addNode(mutable, { x: 2, y: 0 }) * Graph.addEdge(mutable, a, b, 1) * Graph.addEdge(mutable, b, c, 1) * }) * * // Manhattan distance heuristic - * const heuristic = (nodeData: {x: number, y: number}, targetData: {x: number, y: number}) => - * Math.abs(nodeData.x - targetData.x) + Math.abs(nodeData.y - targetData.y) + * const heuristic = ( + * nodeData: { x: number; y: number }, + * targetData: { x: number; y: number } + * ) => Math.abs(nodeData.x - targetData.x) + Math.abs(nodeData.y - targetData.y) * * const result = Graph.astar(graph, { * source: 0, * target: 2, * cost: (edgeData) => edgeData, - * heuristic: heuristic + * heuristic * }) * * if (result !== undefined) { @@ -3213,7 +3254,7 @@ export interface BellmanFordConfig { * const a = Graph.addNode(mutable, "A") * const b = Graph.addNode(mutable, "B") * const c = Graph.addNode(mutable, "C") - * Graph.addEdge(mutable, a, b, -1) // Negative weight allowed + * Graph.addEdge(mutable, a, b, -1) // Negative weight allowed * Graph.addEdge(mutable, b, c, 3) * Graph.addEdge(mutable, a, c, 5) * }) @@ -3432,7 +3473,9 @@ export class Walker implements Iterable<[T, N]> { * console.log(values) // ["A", "B"] * * // Map to custom objects - * const custom = Array.from(dfs.visit((index, data) => ({ id: index, name: data }))) + * const custom = Array.from( + * dfs.visit((index, data) => ({ id: index, name: data })) + * ) * console.log(custom) // [{ id: 0, name: "A" }, { id: 1, name: "B" }] * ``` * @@ -3466,7 +3509,9 @@ export class Walker implements Iterable<[T, N]> { * console.log(values) // ["A", "B"] * * // Map to custom objects - * const custom = Array.from(dfs.visit((index, data) => ({ id: index, name: data }))) + * const custom = Array.from( + * dfs.visit((index, data) => ({ id: index, name: data })) + * ) * console.log(custom) // [{ id: 0, name: "A" }, { id: 1, name: "B" }] * ``` * @@ -4121,9 +4166,9 @@ export interface ExternalsConfig { * import { Graph } from "effect" * * const graph = Graph.directed((mutable) => { - * const source = Graph.addNode(mutable, "source") // 0 - no incoming - * const middle = Graph.addNode(mutable, "middle") // 1 - has both - * const sink = Graph.addNode(mutable, "sink") // 2 - no outgoing + * const source = Graph.addNode(mutable, "source") // 0 - no incoming + * const middle = Graph.addNode(mutable, "middle") // 1 - has both + * const sink = Graph.addNode(mutable, "sink") // 2 - no outgoing * const isolated = Graph.addNode(mutable, "isolated") // 3 - no edges * * Graph.addEdge(mutable, source, middle, 1) @@ -4131,11 +4176,15 @@ export interface ExternalsConfig { * }) * * // Nodes with no outgoing edges (sinks + isolated) - * const sinks = Array.from(Graph.indices(Graph.externals(graph, { direction: "outgoing" }))) + * const sinks = Array.from( + * Graph.indices(Graph.externals(graph, { direction: "outgoing" })) + * ) * console.log(sinks) // [2, 3] * * // Nodes with no incoming edges (sources + isolated) - * const sources = Array.from(Graph.indices(Graph.externals(graph, { direction: "incoming" }))) + * const sources = Array.from( + * Graph.indices(Graph.externals(graph, { direction: "incoming" })) + * ) * console.log(sources) // [0, 3] * ``` * diff --git a/packages/effect/src/Hash.ts b/packages/effect/src/Hash.ts index 7fc7a80054..811e8d6060 100644 --- a/packages/effect/src/Hash.ts +++ b/packages/effect/src/Hash.ts @@ -176,17 +176,17 @@ export const random: (self: A) => number = (self) => { * * @example * ```ts - * import { Hash } from "effect" + * import { Hash } from "effect" // combined hash value + * + * // Can also be used with pipe + * import { pipe } from "effect" * * const hash1 = Hash.hash("hello") * const hash2 = Hash.hash("world") * * // Combine two hash values * const combined = Hash.combine(hash2)(hash1) - * console.log(combined) // combined hash value - * - * // Can also be used with pipe - * import { pipe } from "effect" + * console.log(combined) * const result = pipe(hash1, Hash.combine(hash2)) * ``` * diff --git a/packages/effect/src/HashMap.ts b/packages/effect/src/HashMap.ts index 59af22a4d8..96405a5e18 100644 --- a/packages/effect/src/HashMap.ts +++ b/packages/effect/src/HashMap.ts @@ -19,7 +19,6 @@ const TypeId = internal.HashMapTypeId * @example * ```ts * import * as HashMap from "effect/HashMap" - * import * as Option from "effect/Option" * * // Create a HashMap * const map = HashMap.make(["a", 1], ["b", 2], ["c", 3]) @@ -50,7 +49,6 @@ export interface HashMap extends Iterable<[Key, Value]>, Equ * @example * ```ts * import * as HashMap from "effect/HashMap" - * import * as Option from "effect/Option" * * // Create a concrete HashMap for type extraction * const inventory = HashMap.make( @@ -59,8 +57,8 @@ export interface HashMap extends Iterable<[Key, Value]>, Equ * ) * * // Extract types for reuse - * type ProductId = HashMap.HashMap.Key // string - * type Product = HashMap.HashMap.Value // { quantity: number, price: number } + * type ProductId = HashMap.HashMap.Key // string + * type Product = HashMap.HashMap.Value // { quantity: number, price: number } * type InventoryEntry = HashMap.HashMap.Entry // [string, Product] * * // Use extracted types in functions @@ -295,7 +293,6 @@ export const isEmpty: (self: HashMap) => boolean = internal.isEmpty * @example * ```ts * import * as HashMap from "effect/HashMap" - * import * as Option from "effect/Option" * * const map = HashMap.make(["a", 1], ["b", 2]) * @@ -320,9 +317,8 @@ export const get: { * * @example * ```ts + * import { Hash } from "effect" * import * as HashMap from "effect/HashMap" -import { Hash } from "effect" - * import * as Option from "effect/Option" * * // Useful when implementing custom equality for complex keys * const userMap = HashMap.make( @@ -422,8 +418,8 @@ export const has: { * * @example * ```ts + * import { Hash } from "effect" * import * as HashMap from "effect/HashMap" -import { Hash } from "effect" * * // Create a map with case-sensitive keys * const userMap = HashMap.make( @@ -455,9 +451,9 @@ export const hasHash: { * ```ts * import * as HashMap from "effect/HashMap" * - * const hm = HashMap.make([1, 'a']) - * HashMap.hasBy(hm, (value, key) => value === 'a' && key === 1) // -> true - * HashMap.hasBy(hm, (value) => value === 'b') // -> false + * 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 @@ -550,7 +546,7 @@ export const values: (self: HashMap) => IterableIterator = intern * console.log(totalSalary) // 260000 * * // Filter by department - * const engineers = allEmployees.filter(emp => emp.department === "engineering") + * const engineers = allEmployees.filter((emp) => emp.department === "engineering") * console.log(engineers.length) // 2 * ``` * @@ -612,7 +608,7 @@ export const entries: (self: HashMap) => IterableIterator<[K, V]> = * * // Sort by score (descending) * const leaderboard = scoreEntries - * .sort(([,a], [,b]) => b - a) + * .sort(([, a], [, b]) => b - a) * .map(([player, score], rank) => `${rank + 1}. ${player}: ${score}`) * * console.log(leaderboard) @@ -770,8 +766,8 @@ export const modifyAt: { * * @example * ```ts + * import { Hash } from "effect" * import * as HashMap from "effect/HashMap" -import { Hash } from "effect" * import * as Option from "effect/Option" * * // Useful when working with precomputed hashes for performance @@ -786,13 +782,23 @@ import { Hash } from "effect" * Option.isSome(current) ? Option.some(current.value + 1) : Option.some(1) * * // Use cached hash for efficient updates in loops - * const updated = HashMap.modifyHash(counters, metricKey, cachedHash, incrementCounter) + * const updated = HashMap.modifyHash( + * counters, + * metricKey, + * cachedHash, + * incrementCounter + * ) * console.log(HashMap.get(updated, "downloads")) // Option.some(101) * * // Add new metric with precomputed hash * const newMetric = "clicks" * const clicksHash = Hash.string(newMetric) - * const withClicks = HashMap.modifyHash(updated, newMetric, clicksHash, incrementCounter) + * const withClicks = HashMap.modifyHash( + * updated, + * newMetric, + * clicksHash, + * incrementCounter + * ) * console.log(HashMap.get(withClicks, "clicks")) // Option.some(1) * ``` * @@ -952,8 +958,9 @@ export const map: { * import * as HashMap from "effect/HashMap" * * const map1 = HashMap.make(["a", 1], ["b", 2]) - * const map2 = HashMap.flatMap(map1, (value, key) => - * HashMap.make([key + "1", value], [key + "2", value * 2]) + * const map2 = HashMap.flatMap( + * map1, + * (value, key) => HashMap.make([key + "1", value], [key + "2", value * 2]) * ) * * console.log(HashMap.size(map2)) // 4 @@ -1074,8 +1081,9 @@ export const compact: (self: HashMap>) => HashMap = int * import * as Option from "effect/Option" * * const map1 = HashMap.make(["a", 1], ["b", 2], ["c", 3], ["d", 4]) - * const map2 = HashMap.filterMap(map1, (value) => - * value % 2 === 0 ? Option.some(value * 2) : Option.none() + * const map2 = HashMap.filterMap( + * map1, + * (value) => value % 2 === 0 ? Option.some(value * 2) : Option.none() * ) * * console.log(HashMap.size(map2)) // 2 diff --git a/packages/effect/src/HashSet.ts b/packages/effect/src/HashSet.ts index 3115a211c0..70b1b4cdf4 100644 --- a/packages/effect/src/HashSet.ts +++ b/packages/effect/src/HashSet.ts @@ -212,15 +212,15 @@ export const add: { * * @example * ```ts - * import * as HashSet from "effect/HashSet" + * import * as HashSet from "effect/HashSet" // false + * + * // 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")) // false - * - * // Works with any type that implements Equal - * import { Equal, Hash } from "effect" + * console.log(HashSet.has(set, "grape")) * * class Person implements Equal.Equal { * constructor(readonly name: string) {} @@ -434,14 +434,14 @@ export const isSubset: { * import * as HashSet from "effect/HashSet" * * const numbers = HashSet.make(1, 2, 3) - * const doubled = HashSet.map(numbers, n => n * 2) + * const doubled = HashSet.map(numbers, (n) => n * 2) * * console.log(Array.from(doubled).sort()) // [2, 4, 6] * console.log(HashSet.size(doubled)) // 3 * * // Mapping can reduce size if function produces duplicates * const strings = HashSet.make("apple", "banana", "cherry") - * const lengths = HashSet.map(strings, s => s.length) + * const lengths = HashSet.map(strings, (s) => s.length) * console.log(Array.from(lengths).sort()) // [5, 6] (apple=5, banana=6, cherry=6) * ``` * @@ -464,7 +464,7 @@ export const map: { * import * as HashSet from "effect/HashSet" * * const numbers = HashSet.make(1, 2, 3, 4, 5, 6) - * const evens = HashSet.filter(numbers, n => n % 2 === 0) + * const evens = HashSet.filter(numbers, (n) => n % 2 === 0) * * console.log(Array.from(evens).sort()) // [2, 4, 6] * console.log(HashSet.size(evens)) // 3 @@ -498,11 +498,11 @@ export const filter: { * * const numbers = HashSet.make(1, 2, 3, 4, 5) * - * console.log(HashSet.some(numbers, n => n > 3)) // true - * console.log(HashSet.some(numbers, n => n > 10)) // false + * console.log(HashSet.some(numbers, (n) => n > 3)) // true + * console.log(HashSet.some(numbers, (n) => n > 10)) // false * * const empty = HashSet.empty() - * console.log(HashSet.some(empty, n => n > 0)) // false + * console.log(HashSet.some(empty, (n) => n > 0)) // false * ``` * * @since 2.0.0 @@ -525,11 +525,11 @@ export const some: { * * const numbers = HashSet.make(2, 4, 6, 8) * - * console.log(HashSet.every(numbers, n => n % 2 === 0)) // true - * console.log(HashSet.every(numbers, n => n > 5)) // false + * console.log(HashSet.every(numbers, (n) => n % 2 === 0)) // true + * console.log(HashSet.every(numbers, (n) => n > 5)) // false * * const empty = HashSet.empty() - * console.log(HashSet.every(empty, n => n > 0)) // true (vacuously true) + * console.log(HashSet.every(empty, (n) => n > 0)) // true (vacuously true) * ``` * * @since 2.0.0 diff --git a/packages/effect/src/Iterable.ts b/packages/effect/src/Iterable.ts index 6123631c57..59dd0b0ca9 100644 --- a/packages/effect/src/Iterable.ts +++ b/packages/effect/src/Iterable.ts @@ -16,8 +16,8 @@ * * // Create iterables * const numbers = Iterable.range(1, 5) - * const doubled = Iterable.map(numbers, x => x * 2) - * const filtered = Iterable.filter(doubled, x => x > 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] * @@ -57,15 +57,15 @@ import type { NoInfer } from "./types/Types.ts" * import { Iterable } from "effect" * * // Generate first 5 even numbers - * const evens = Iterable.makeBy(n => n * 2, { length: 5 }) + * const evens = Iterable.makeBy((n) => n * 2, { length: 5 }) * console.log(Array.from(evens)) // [0, 2, 4, 6, 8] * * // Generate squares - * const squares = Iterable.makeBy(n => n * n, { length: 4 }) + * const squares = Iterable.makeBy((n) => n * n, { length: 4 }) * console.log(Array.from(squares)) // [0, 1, 4, 9] * * // Infinite sequence (be careful when consuming!) - * const naturals = Iterable.makeBy(n => n) + * const naturals = Iterable.makeBy((n) => n) * const first10 = Iterable.take(naturals, 10) * console.log(Array.from(first10)) // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] * ``` @@ -99,8 +99,8 @@ export const makeBy = (f: (i: number) => A, options?: { * * @example * ```ts - * import * as assert from "node:assert" * import { range } from "effect/Iterable" + * import * as assert from "node:assert" * * assert.deepStrictEqual(Array.from(range(1, 3)), [1, 2, 3]) * ``` @@ -124,8 +124,8 @@ export const range = (start: number, end?: number): Iterable => { * * @example * ```ts - * import * as assert from "node:assert" * import { replicate } from "effect/Iterable" + * import * as assert from "node:assert" * * assert.deepStrictEqual(Array.from(replicate("a", 3)), ["a", "a", "a"]) * ``` @@ -158,11 +158,14 @@ export const forever = (self: Iterable): Iterable => repeat(self, Infin * * @example * ```ts - * import * as assert from "node:assert" * import { fromRecord } from "effect/Iterable" + * import * as assert from "node:assert" * * const x = { a: 1, b: 2, c: 3 } - * assert.deepStrictEqual(Array.from(fromRecord(x)), [["a", 1], ["b", 2], ["c", 3]]) + * assert.deepStrictEqual(Array.from(fromRecord(x)), [["a", 1], ["b", 2], [ + * "c", + * 3 + * ]]) * ``` * * @category conversions @@ -208,8 +211,8 @@ export const prepend: { * * @example * ```ts - * import * as assert from "node:assert" * import { Iterable } from "effect" + * import * as assert from "node:assert" * * assert.deepStrictEqual( * Array.from(Iterable.prependAll([1, 2], ["a", "b"])), @@ -365,11 +368,11 @@ export const scan: { * * @example * ```ts - * import * as assert from "node:assert" * import { isEmpty } from "effect/Iterable" + * import * as assert from "node:assert" * - * assert.deepStrictEqual(isEmpty([]), true); - * assert.deepStrictEqual(isEmpty([1, 2, 3]), false); + * assert.deepStrictEqual(isEmpty([]), true) + * assert.deepStrictEqual(isEmpty([1, 2, 3]), false) * ``` * * @category guards @@ -429,11 +432,13 @@ export const size = (self: Iterable): number => { * console.log(Iterable.head(empty)) // Option.none() * * // Safe way to get first element - * const firstEven = Iterable.head(Iterable.filter([1, 3, 4, 5], x => x % 2 === 0)) + * const firstEven = Iterable.head( + * Iterable.filter([1, 3, 4, 5], (x) => x % 2 === 0) + * ) * console.log(firstEven) // Option.some(4) * * // Use with Option methods - * const doubled = Option.map(Iterable.head([5, 10, 15]), x => x * 2) + * const doubled = Option.map(Iterable.head([5, 10, 15]), (x) => x * 2) * console.log(doubled) // Option.some(10) * ``` * @@ -539,7 +544,7 @@ export const take: { * import { Iterable } from "effect" * * const numbers = [2, 4, 6, 8, 3, 10, 12] - * const evenPrefix = Iterable.takeWhile(numbers, x => x % 2 === 0) + * const evenPrefix = Iterable.takeWhile(numbers, (x) => x % 2 === 0) * console.log(Array.from(evenPrefix)) // [2, 4, 6, 8] * * // With index @@ -549,12 +554,15 @@ export const take: { * * // Stops at first non-matching element * const mixed = [1, 3, 5, 4, 7, 9] - * const oddPrefix = Iterable.takeWhile(mixed, x => x % 2 === 1) + * const oddPrefix = Iterable.takeWhile(mixed, (x) => x % 2 === 1) * console.log(Array.from(oddPrefix)) // [1, 3, 5] * * // Type refinement - * const values: (string | number)[] = ["a", "b", "c", 1, "d"] - * const stringPrefix = Iterable.takeWhile(values, (x): x is string => typeof x === "string") + * const values: Array = ["a", "b", "c", 1, "d"] + * const stringPrefix = Iterable.takeWhile( + * values, + * (x): x is string => typeof x === "string" + * ) * console.log(Array.from(stringPrefix)) // ["a", "b", "c"] (typed as string[]) * ``` * @@ -643,10 +651,10 @@ export const drop: { * import * as Option from "effect/Option" * * const numbers = [1, 3, 4, 6, 8] - * const firstEven = Iterable.findFirst(numbers, x => x % 2 === 0) + * const firstEven = Iterable.findFirst(numbers, (x) => x % 2 === 0) * console.log(firstEven) // Option.some(4) * - * const firstGreaterThan10 = Iterable.findFirst(numbers, x => x > 10) + * const firstGreaterThan10 = Iterable.findFirst(numbers, (x) => x > 10) * console.log(firstGreaterThan10) // Option.none() * * // With index @@ -655,12 +663,15 @@ export const drop: { * console.log(atEvenIndex) // Option.some("a") * * // Type refinement - * const mixed: (string | number)[] = [1, "hello", 2, "world"] - * const firstString = Iterable.findFirst(mixed, (x): x is string => typeof x === "string") + * const mixed: Array = [1, "hello", 2, "world"] + * const firstString = Iterable.findFirst( + * mixed, + * (x): x is string => typeof x === "string" + * ) * console.log(firstString) // Option.some("hello") * * // Transform during search - * const findSquareRoot = Iterable.findFirst([1, 4, 9, 16], x => { + * const findSquareRoot = Iterable.findFirst([1, 4, 9, 16], (x) => { * const sqrt = Math.sqrt(x) * return Number.isInteger(sqrt) ? Option.some(sqrt) : Option.none() * }) @@ -704,13 +715,12 @@ export const findFirst: { * @example * ```ts * import { Iterable } from "effect" - * import * as Option from "effect/Option" * * const numbers = [1, 3, 4, 6, 8, 2] - * const lastEven = Iterable.findLast(numbers, x => x % 2 === 0) + * const lastEven = Iterable.findLast(numbers, (x) => x % 2 === 0) * console.log(lastEven) // Option.some(2) * - * const lastGreaterThan10 = Iterable.findLast(numbers, x => x > 10) + * const lastGreaterThan10 = Iterable.findLast(numbers, (x) => x > 10) * console.log(lastGreaterThan10) // Option.none() * * // With index @@ -719,8 +729,11 @@ export const findFirst: { * console.log(lastAtEvenIndex) // Option.some("e") (index 4) * * // Type refinement - * const mixed: (string | number)[] = [1, "hello", 2, "world", 3] - * const lastString = Iterable.findLast(mixed, (x): x is string => typeof x === "string") + * const mixed: Array = [1, "hello", 2, "world", 3] + * const lastString = Iterable.findLast( + * mixed, + * (x): x is string => typeof x === "string" + * ) * console.log(lastString) // Option.some("world") * ``` * @@ -815,13 +828,21 @@ export const zip: { * // Combine strings * const firstNames = ["John", "Jane", "Bob"] * const lastNames = ["Doe", "Smith", "Johnson"] - * const fullNames = Iterable.zipWith(firstNames, lastNames, (first, last) => `${first} ${last}`) + * const fullNames = Iterable.zipWith( + * firstNames, + * lastNames, + * (first, last) => `${first} ${last}` + * ) * console.log(Array.from(fullNames)) // ["John Doe", "Jane Smith", "Bob Johnson"] * * // Different lengths - stops at shorter * const short = [1, 2] * const long = ["a", "b", "c", "d"] - * const combined = Iterable.zipWith(short, long, (num, letter) => `${num}${letter}`) + * const combined = Iterable.zipWith( + * short, + * long, + * (num, letter) => `${num}${letter}` + * ) * console.log(Array.from(combined)) // ["1a", "2b"] * * // Complex transformations @@ -934,7 +955,8 @@ export const intersperse: { * console.log(hasUser1) // true (same id) * * // Case-insensitive string comparison - * const caseInsensitive = (a: string, b: string) => a.toLowerCase() === b.toLowerCase() + * const caseInsensitive = (a: string, b: string) => + * a.toLowerCase() === b.toLowerCase() * const containsCaseInsensitive = Iterable.containsWith(caseInsensitive) * * const words = ["Hello", "World"] @@ -1012,26 +1034,27 @@ export const contains: { * * const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9] * const chunks = Iterable.chunksOf(numbers, 3) - * console.log(Array.from(chunks).map(chunk => Array.from(chunk))) + * console.log(Array.from(chunks).map((chunk) => Array.from(chunk))) * // [[1, 2, 3], [4, 5, 6], [7, 8, 9]] * * // Last chunk can be shorter * const uneven = [1, 2, 3, 4, 5, 6, 7] * const chunks2 = Iterable.chunksOf(uneven, 3) - * console.log(Array.from(chunks2).map(chunk => Array.from(chunk))) + * console.log(Array.from(chunks2).map((chunk) => Array.from(chunk))) * // [[1, 2, 3], [4, 5, 6], [7]] * * // Chunk size larger than iterable * const small = [1, 2] * const chunks3 = Iterable.chunksOf(small, 5) - * console.log(Array.from(chunks3).map(chunk => Array.from(chunk))) + * console.log(Array.from(chunks3).map((chunk) => Array.from(chunk))) * // [[1, 2]] * * // Process data in batches * const data = Iterable.range(1, 100) * const batches = Iterable.chunksOf(data, 10) - * const batchSums = Iterable.map(batches, batch => - * Iterable.reduce(batch, 0, (sum, n) => sum + n) + * const batchSums = Iterable.map( + * batches, + * (batch) => Iterable.reduce(batch, 0, (sum, n) => sum + n) * ) * console.log(Array.from(Iterable.take(batchSums, 3))) // [55, 155, 255] * ``` @@ -1085,7 +1108,8 @@ export const chunksOf: { * * // Case-insensitive grouping of strings * const words = ["Apple", "APPLE", "banana", "Banana", "cherry"] - * const caseInsensitive = (a: string, b: string) => a.toLowerCase() === b.toLowerCase() + * const caseInsensitive = (a: string, b: string) => + * a.toLowerCase() === b.toLowerCase() * const groupedWords = Iterable.groupWith(words, caseInsensitive) * console.log(Array.from(groupedWords)) * // [["Apple", "APPLE"], ["banana", "Banana"], ["cherry"]] @@ -1193,13 +1217,13 @@ export const group: (self: Iterable) => Iterable> = group * * // Group by string length * const words = ["a", "bb", "ccc", "dd", "eee", "f"] - * const byLength = Iterable.groupBy(words, word => word.length.toString()) + * const byLength = Iterable.groupBy(words, (word) => word.length.toString()) * console.log(byLength) * // { "1": ["a", "f"], "2": ["bb", "dd"], "3": ["ccc", "eee"] } * * // Group by first letter * const names = ["Alice", "Bob", "Charlie", "David", "Anna", "Betty"] - * const byFirstLetter = Iterable.groupBy(names, name => name[0]) + * const byFirstLetter = Iterable.groupBy(names, (name) => name[0]) * console.log(byFirstLetter) * // { "A": ["Alice", "Anna"], "B": ["Bob", "Betty"], "C": ["Charlie"], "D": ["David"] } * @@ -1210,7 +1234,7 @@ export const group: (self: Iterable) => Iterable> = group * { name: "banana", category: "fruit" }, * { name: "broccoli", category: "vegetable" } * ] - * const byCategory = Iterable.groupBy(items, item => item.category) + * const byCategory = Iterable.groupBy(items, (item) => item.category) * console.log(byCategory) * // { * // "fruit": [{ name: "apple", category: "fruit" }, { name: "banana", category: "fruit" }], @@ -1219,7 +1243,7 @@ export const group: (self: Iterable) => Iterable> = group * * // Group numbers by even/odd * const numbers = [1, 2, 3, 4, 5, 6] - * const evenOdd = Iterable.groupBy(numbers, n => n % 2 === 0 ? "even" : "odd") + * const evenOdd = Iterable.groupBy(numbers, (n) => n % 2 === 0 ? "even" : "odd") * console.log(evenOdd) * // { "odd": [1, 3, 5], "even": [2, 4, 6] } * ``` @@ -1312,8 +1336,9 @@ export const empty = (): Iterable => constEmpty * * // Can be used with flatMap for conditional inclusion * const numbers = [1, 2, 3, 4, 5] - * const evensOnly = Iterable.flatMap(numbers, n => - * n % 2 === 0 ? Iterable.of(n) : Iterable.empty() + * const evensOnly = Iterable.flatMap( + * numbers, + * (n) => n % 2 === 0 ? Iterable.of(n) : Iterable.empty() * ) * console.log(Array.from(evensOnly)) // [2, 4] * ``` @@ -1340,7 +1365,7 @@ export const of = (a: A): Iterable => [a] * * // Transform numbers to their squares * const numbers = [1, 2, 3, 4, 5] - * const squares = Iterable.map(numbers, x => x * x) + * const squares = Iterable.map(numbers, (x) => x * x) * console.log(Array.from(squares)) // [1, 4, 9, 16, 25] * * // Use index in transformation @@ -1349,8 +1374,8 @@ export const of = (a: A): Iterable => [a] * * // Chain transformations * const result = Iterable.map( - * Iterable.map([1, 2, 3], x => x * 2), - * x => x + 1 + * Iterable.map([1, 2, 3], (x) => x * 2), + * (x) => x + 1 * ) * console.log(Array.from(result)) // [3, 5, 7] * ``` @@ -1388,25 +1413,27 @@ export const map: { * * // Expand each number to a range * const numbers = [1, 2, 3] - * const expanded = Iterable.flatMap(numbers, n => Iterable.range(1, n)) + * const expanded = Iterable.flatMap(numbers, (n) => Iterable.range(1, n)) * console.log(Array.from(expanded)) // [1, 1, 2, 1, 2, 3] * * // Split strings into characters * const words = ["hi", "bye"] - * const chars = Iterable.flatMap(words, word => word) + * const chars = Iterable.flatMap(words, (word) => word) * console.log(Array.from(chars)) // ["h", "i", "b", "y", "e"] * * // Conditional expansion with empty iterables * const values = [1, 2, 3, 4, 5] - * const evenMultiples = Iterable.flatMap(values, n => - * n % 2 === 0 ? [n, n * 2, n * 3] : [] + * const evenMultiples = Iterable.flatMap( + * values, + * (n) => n % 2 === 0 ? [n, n * 2, n * 3] : [] * ) * console.log(Array.from(evenMultiples)) // [2, 4, 6, 4, 8, 12] * * // Use index in transformation * const letters = ["a", "b", "c"] - * const indexed = Iterable.flatMap(letters, (letter, i) => - * Iterable.replicate(letter, i + 1) + * const indexed = Iterable.flatMap( + * letters, + * (letter, i) => Iterable.replicate(letter, i + 1) * ) * console.log(Array.from(indexed)) // ["a", "b", "b", "c", "c", "c"] * ``` @@ -1437,14 +1464,14 @@ export const flatMap: { * console.log(Array.from(flat)) // [1, 2, 3, 4, 5, 6] * * // Flatten different iterable types - * const mixed: Iterable[] = ["ab", "cd"] + * const mixed: Array> = ["ab", "cd"] * const flatMixed = Iterable.flatten(mixed) * console.log(Array.from(flatMixed)) // ["a", "b", "c", "d"] * * // Flatten deeply nested (only one level) * const deepNested = [[[1, 2]], [[3, 4]]] * const oneLevelFlat = Iterable.flatten(deepNested) - * console.log(Array.from(oneLevelFlat).map(arr => Array.from(arr))) + * console.log(Array.from(oneLevelFlat).map((arr) => Array.from(arr))) * // [[1, 2], [3, 4]] (still contains arrays) * * // Empty iterables are handled correctly @@ -1492,7 +1519,7 @@ export const flatten = (self: Iterable>): Iterable => ({ * * // Parse strings to numbers, keeping only valid ones * const strings = ["1", "2", "invalid", "4", "not-a-number"] - * const numbers = Iterable.filterMap(strings, s => { + * const numbers = Iterable.filterMap(strings, (s) => { * const num = parseInt(s) * return isNaN(num) ? Option.none() : Option.some(num) * }) @@ -1505,15 +1532,18 @@ export const flatten = (self: Iterable>): Iterable => ({ * { name: "Charlie", age: 30, email: "charlie@example.com" }, * { name: "David", age: 16, email: undefined } * ] - * const adultEmails = Iterable.filterMap(users, user => - * user.age >= 18 && user.email ? Option.some(user.email) : Option.none() + * const adultEmails = Iterable.filterMap( + * users, + * (user) => + * user.age >= 18 && user.email ? Option.some(user.email) : Option.none() * ) * console.log(Array.from(adultEmails)) // ["alice@example.com", "charlie@example.com"] * * // Use index in transformation * const items = ["a", "b", "c", "d", "e"] - * const evenIndexItems = Iterable.filterMap(items, (item, i) => - * i % 2 === 0 ? Option.some(`${i}: ${item}`) : Option.none() + * const evenIndexItems = Iterable.filterMap( + * items, + * (item, i) => i % 2 === 0 ? Option.some(`${i}: ${item}`) : Option.none() * ) * console.log(Array.from(evenIndexItems)) // ["0: a", "2: c", "4: e"] * ``` @@ -1557,7 +1587,7 @@ export const filterMap: { * * // Parse numbers until we hit an invalid one * const strings = ["1", "2", "3", "invalid", "4", "5"] - * const numbers = Iterable.filterMapWhile(strings, s => { + * const numbers = Iterable.filterMapWhile(strings, (s) => { * const num = parseInt(s) * return isNaN(num) ? Option.none() : Option.some(num) * }) @@ -1565,15 +1595,17 @@ export const filterMap: { * * // Take elements while they meet a condition and transform them * const values = [2, 4, 6, 7, 8, 10] - * const doubledEvens = Iterable.filterMapWhile(values, n => - * n % 2 === 0 ? Option.some(n * 2) : Option.none() + * const doubledEvens = Iterable.filterMapWhile( + * values, + * (n) => n % 2 === 0 ? Option.some(n * 2) : Option.none() * ) * console.log(Array.from(doubledEvens)) // [4, 8, 12] (stops at 7) * * // Process with index until condition fails * const letters = ["a", "b", "c", "d", "e"] - * const indexedUntilC = Iterable.filterMapWhile(letters, (letter, i) => - * letter !== "c" ? Option.some(`${i}: ${letter}`) : Option.none() + * const indexedUntilC = Iterable.filterMapWhile( + * letters, + * (letter, i) => letter !== "c" ? Option.some(`${i}: ${letter}`) : Option.none() * ) * console.log(Array.from(indexedUntilC)) // ["0: a", "1: b"] (stops at "c") * ``` @@ -1609,12 +1641,14 @@ export const filterMapWhile: { * * @example * ```ts - * import * as assert from "node:assert" * import { Iterable } from "effect" * import * as Option from "effect/Option" + * import * as assert from "node:assert" * * assert.deepStrictEqual( - * Array.from(Iterable.getSomes([Option.some(1), Option.none(), Option.some(2)])), + * Array.from( + * Iterable.getSomes([Option.some(1), Option.none(), Option.some(2)]) + * ), * [1, 2] * ) * ``` @@ -1629,12 +1663,18 @@ export const getSomes: (self: Iterable>) => Iterable = filterMap * * @example * ```ts - * import * as assert from "node:assert" * import { Iterable } from "effect" * import * as Result from "effect/Result" + * import * as assert from "node:assert" * * assert.deepStrictEqual( - * Array.from(Iterable.getFailures([Result.succeed(1), Result.fail("err"), Result.succeed(2)])), + * Array.from( + * Iterable.getFailures([ + * Result.succeed(1), + * Result.fail("err"), + * Result.succeed(2) + * ]) + * ), * ["err"] * ) * ``` @@ -1649,12 +1689,18 @@ export const getFailures = (self: Iterable>): Iterable => * * @example * ```ts - * import * as assert from "node:assert" * import { Iterable } from "effect" * import * as Result from "effect/Result" + * import * as assert from "node:assert" * * assert.deepStrictEqual( - * Array.from(Iterable.getSuccesses([Result.succeed(1), Result.fail("err"), Result.succeed(2)])), + * Array.from( + * Iterable.getSuccesses([ + * Result.succeed(1), + * Result.fail("err"), + * Result.succeed(2) + * ]) + * ), * [1, 2] * ) * ``` @@ -1680,7 +1726,7 @@ export const getSuccesses = (self: Iterable>): Iterable => * * // Filter even numbers * const numbers = [1, 2, 3, 4, 5, 6] - * const evens = Iterable.filter(numbers, x => x % 2 === 0) + * const evens = Iterable.filter(numbers, (x) => x % 2 === 0) * console.log(Array.from(evens)) // [2, 4, 6] * * // Filter with index @@ -1689,14 +1735,17 @@ export const getSuccesses = (self: Iterable>): Iterable => * console.log(Array.from(oddPositions)) // ["b", "d"] * * // Type refinement - * const mixed: (string | number)[] = ["hello", 42, "world", 100] - * const onlyStrings = Iterable.filter(mixed, (x): x is string => typeof x === "string") + * const mixed: Array = ["hello", 42, "world", 100] + * const onlyStrings = Iterable.filter( + * mixed, + * (x): x is string => typeof x === "string" + * ) * console.log(Array.from(onlyStrings)) // ["hello", "world"] (typed as string[]) * * // Combine with map * const processed = Iterable.map( - * Iterable.filter([1, 2, 3, 4, 5], x => x > 2), - * x => x * 10 + * Iterable.filter([1, 2, 3, 4, 5], (x) => x > 2), + * (x) => x * 10 * ) * console.log(Array.from(processed)) // [30, 40, 50] * ``` @@ -1743,7 +1792,7 @@ export const filter: { * * // Extract valid elements from nullable function results * const data = ["1", "2", "invalid", "4"] - * const parsed = Iterable.flatMapNullishOr(data, s => { + * const parsed = Iterable.flatMapNullishOr(data, (s) => { * const num = parseInt(s) * return isNaN(num) ? null : num * 2 * }) @@ -1756,7 +1805,7 @@ export const filter: { * { nested: { value: 20 } }, * {} * ] - * const values = Iterable.flatMapNullishOr(objects, obj => obj.nested?.value) + * const values = Iterable.flatMapNullishOr(objects, (obj) => obj.nested?.value) * console.log(Array.from(values)) // [10, 20] * * // Working with Map.get (returns undefined for missing keys) @@ -1766,7 +1815,7 @@ export const filter: { * ["c", 3] * ]) * const keys = ["a", "x", "b", "y", "c"] - * const foundValues = Iterable.flatMapNullishOr(keys, key => map.get(key)) + * const foundValues = Iterable.flatMapNullishOr(keys, (key) => map.get(key)) * console.log(Array.from(foundValues)) // [1, 2, 3] * ``` * @@ -1793,11 +1842,11 @@ export const flatMapNullishOr: { * import { Iterable } from "effect" * * const numbers = [1, 3, 5, 7, 8] - * const hasEven = Iterable.some(numbers, x => x % 2 === 0) + * const hasEven = Iterable.some(numbers, (x) => x % 2 === 0) * console.log(hasEven) // true (because of 8) * * const allOdd = [1, 3, 5, 7] - * const hasEvenInAllOdd = Iterable.some(allOdd, x => x % 2 === 0) + * const hasEvenInAllOdd = Iterable.some(allOdd, (x) => x % 2 === 0) * console.log(hasEvenInAllOdd) // false * * // With index @@ -1806,16 +1855,19 @@ export const flatMapNullishOr: { * console.log(hasElementAtIndex2) // true * * // Early termination - stops at first match - * const infiniteOdds = Iterable.filter(Iterable.range(1), x => x % 2 === 1) + * const infiniteOdds = Iterable.filter(Iterable.range(1), (x) => x % 2 === 1) * const hasEvenInInfiniteOdds = Iterable.some( * Iterable.take(infiniteOdds, 1000), - * x => x % 2 === 0 + * (x) => x % 2 === 0 * ) * console.log(hasEvenInInfiniteOdds) // false (quickly, doesn't check all 1000) * * // Type guard usage - * const mixed: (string | number)[] = [1, 2, "hello"] - * const hasString = Iterable.some(mixed, (x): x is string => typeof x === "string") + * const mixed: Array = [1, 2, "hello"] + * const hasString = Iterable.some( + * mixed, + * (x): x is string => typeof x === "string" + * ) * console.log(hasString) // true * ``` * @@ -1851,26 +1903,20 @@ export const some: { * import { Iterable } from "effect" * * // Generate Fibonacci sequence - * const fibonacci = Iterable.unfold([0, 1], ([a, b]) => - * [a, [b, a + b]] - * ) + * const fibonacci = Iterable.unfold([0, 1], ([a, b]) => [a, [b, a + b]]) * const first10Fib = Iterable.take(fibonacci, 10) * console.log(Array.from(first10Fib)) // [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] * * // Generate powers of 2 up to a limit - * const powersOf2 = Iterable.unfold(1, n => - * n <= 1000 ? [n, n * 2] : undefined - * ) + * const powersOf2 = Iterable.unfold(1, (n) => n <= 1000 ? [n, n * 2] : undefined) * console.log(Array.from(powersOf2)) // [1, 2, 4, 8, 16, 32, 64, 128, 256, 512] * * // Generate countdown - * const countdown = Iterable.unfold(5, n => - * n > 0 ? [n, n - 1] : undefined - * ) + * const countdown = Iterable.unfold(5, (n) => n > 0 ? [n, n - 1] : undefined) * console.log(Array.from(countdown)) // [5, 4, 3, 2, 1] * * // Generate collatz sequence - * const collatz = Iterable.unfold(7, n => { + * const collatz = Iterable.unfold(7, (n) => { * if (n === 1) return undefined * const next = n % 2 === 0 ? n / 2 : n * 3 + 1 * return [n, next] @@ -1907,7 +1953,7 @@ export const unfold = (b: B, f: (b: B) => readonly [A, B] | undefined): It * * // Print each element * const numbers = [1, 2, 3, 4, 5] - * Iterable.forEach(numbers, n => console.log(n)) + * Iterable.forEach(numbers, (n) => console.log(n)) * // Prints: 1, 2, 3, 4, 5 * * // Use index in the callback @@ -1918,15 +1964,15 @@ export const unfold = (b: B, f: (b: B) => readonly [A, B] | undefined): It * // Prints: "0: a", "1: b", "2: c" * * // Side effects with any iterable - * const results: number[] = [] - * Iterable.forEach(Iterable.range(1, 5), n => { + * const results: Array = [] + * Iterable.forEach(Iterable.range(1, 5), (n) => { * results.push(n * n) * }) * console.log(results) // [1, 4, 9, 16, 25] * * // Process in chunks * const data = Iterable.chunksOf([1, 2, 3, 4, 5, 6], 2) - * Iterable.forEach(data, chunk => { + * Iterable.forEach(data, (chunk) => { * console.log(`Processing chunk: ${Array.from(chunk)}`) * }) * // Prints: "Processing chunk: 1,2", "Processing chunk: 3,4", "Processing chunk: 5,6" @@ -1967,18 +2013,26 @@ export const forEach: { * * // Build an object from key-value pairs * const pairs = [["a", 1], ["b", 2], ["c", 3]] as const - * const obj = Iterable.reduce(pairs, {} as Record, (acc, [key, value]) => { - * acc[key] = value - * return acc - * }) + * const obj = Iterable.reduce( + * pairs, + * {} as Record, + * (acc, [key, value]) => { + * acc[key] = value + * return acc + * } + * ) * console.log(obj) // { a: 1, b: 2, c: 3 } * * // Use index in the reducer * const letters = ["a", "b", "c"] - * const indexed = Iterable.reduce(letters, [] as string[], (acc, letter, i) => { - * acc.push(`${i}: ${letter}`) - * return acc - * }) + * const indexed = Iterable.reduce( + * letters, + * [] as Array, + * (acc, letter, i) => { + * acc.push(`${i}: ${letter}`) + * return acc + * } + * ) * console.log(indexed) // ["0: a", "1: b", "2: c"] * ``` * @@ -2014,7 +2068,8 @@ export const reduce: { * * // Case-insensitive deduplication * const words = ["Hello", "HELLO", "world", "World", "test"] - * const caseInsensitive = (a: string, b: string) => a.toLowerCase() === b.toLowerCase() + * const caseInsensitive = (a: string, b: string) => + * a.toLowerCase() === b.toLowerCase() * const dedupedWords = Iterable.dedupeAdjacentWith(words, caseInsensitive) * console.log(Array.from(dedupedWords)) // ["Hello", "world", "test"] * @@ -2028,7 +2083,7 @@ export const reduce: { * ] * const byId = (a: typeof users[0], b: typeof users[0]) => a.id === b.id * const dedupedUsers = Iterable.dedupeAdjacentWith(users, byId) - * console.log(Array.from(dedupedUsers).map(u => u.id)) // [1, 2, 3] + * console.log(Array.from(dedupedUsers).map((u) => u.id)) // [1, 2, 3] * * // Approximate numeric equality * const floats = [1.0, 1.01, 1.02, 2.0, 2.01, 3.0] @@ -2095,7 +2150,7 @@ export const dedupeAdjacentWith: { * { type: "A" } * ] * const dedupedObjects = Iterable.dedupeAdjacent(objects) - * console.log(Array.from(dedupedObjects).map(o => o.type)) // ["A", "B", "A"] + * console.log(Array.from(dedupedObjects).map((o) => o.type)) // ["A", "B", "A"] * * // Clean up streaming data * const sensorData = [100, 100, 100, 101, 101, 102, 102, 102, 100] @@ -2124,7 +2179,11 @@ export const dedupeAdjacent: (self: Iterable) => Iterable = dedupeAdjac * // Generate all combinations of options * const sizes = ["S", "M", "L"] * const colors = ["red", "blue"] - * const products = Iterable.cartesianWith(sizes, colors, (size, color) => ({ size, color })) + * const products = Iterable.cartesianWith( + * sizes, + * colors, + * (size, color) => ({ size, color }) + * ) * console.log(Array.from(products)) * // [ * // { size: "S", color: "red" }, { size: "S", color: "blue" }, @@ -2141,8 +2200,10 @@ export const dedupeAdjacent: (self: Iterable) => Iterable = dedupeAdjac * // Create test data combinations * const userTypes = ["admin", "user"] * const features = ["read", "write", "delete"] - * const testCases = Iterable.cartesianWith(userTypes, features, (user, feature) => - * `${user}_can_${feature}` + * const testCases = Iterable.cartesianWith( + * userTypes, + * features, + * (user, feature) => `${user}_can_${feature}` * ) * console.log(Array.from(testCases)) * // ["admin_can_read", "admin_can_write", "admin_can_delete", "user_can_read", "user_can_write", "user_can_delete"] @@ -2216,7 +2277,7 @@ export const cartesian: { * ```ts * import { Iterable } from "effect" * - * const result = Iterable.countBy([1, 2, 3, 4, 5], n => n % 2 === 0) + * const result = Iterable.countBy([1, 2, 3, 4, 5], (n) => n % 2 === 0) * console.log(result) // 2 * ``` * diff --git a/packages/effect/src/Layer.ts b/packages/effect/src/Layer.ts index 01ad8183dd..0b4177d2ef 100644 --- a/packages/effect/src/Layer.ts +++ b/packages/effect/src/Layer.ts @@ -120,11 +120,13 @@ const MemoMapTypeId = "~effect/Layer/MemoMap" * }>()("Database") {} * * // Create a custom MemoMap for manual layer building - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const memoMap = yield* Layer.makeMemoMap * const scope = yield* Effect.scope * - * const dbLayer = Layer.succeed(Database)({ query: (sql: string) => Effect.succeed("result") }) + * const dbLayer = Layer.succeed(Database)({ + * query: (sql: string) => Effect.succeed("result") + * }) * const services = yield* Layer.buildWithMemoMap(dbLayer, memoMap, scope) * * return ServiceMap.get(services, Database) @@ -205,9 +207,11 @@ const fromBuildUnsafe = ( * }>()("Database") {} * * const databaseLayer = Layer.fromBuild(() => - * Effect.sync(() => ServiceMap.make(Database, { - * query: (sql: string) => Effect.succeed("result") - * })) + * Effect.sync(() => + * ServiceMap.make(Database, { + * query: (sql: string) => Effect.succeed("result") + * }) + * ) * ) * ``` * @@ -244,9 +248,11 @@ export const fromBuild = ( * }>()("Database") {} * * const databaseLayer = Layer.fromBuildMemo(() => - * Effect.sync(() => ServiceMap.make(Database, { - * query: (sql: string) => Effect.succeed("result") - * })) + * Effect.sync(() => + * ServiceMap.make(Database, { + * query: (sql: string) => Effect.succeed("result") + * }) + * ) * ) * ``` * @@ -325,7 +331,7 @@ class MemoMapImpl implements MemoMap { * }>()("Database") {} * * // Create a memo map for manual layer building - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const memoMap = Layer.makeMemoMapUnsafe() * const scope = yield* Effect.scope * @@ -355,7 +361,7 @@ export const makeMemoMapUnsafe = (): MemoMap => new MemoMapImpl() * }>()("Database") {} * * // Create a memo map safely within an Effect - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const memoMap = yield* Layer.makeMemoMap * const scope = yield* Effect.scope * @@ -381,9 +387,7 @@ export const makeMemoMap: Effect = internalEffect.sync(makeMemoMapUnsaf * * @example * ```ts - * import { Effect } from "effect" - * import { Layer } from "effect" - * import { ServiceMap } from "effect" + * import { Layer, ServiceMap } from "effect" * * const getMemoMap = ServiceMap.get(Layer.CurrentMemoMap) * ``` @@ -412,7 +416,7 @@ export const CurrentMemoMap = ServiceMap.Reference("effect/Layer/Curren * }>()("Logger") {} * * // Build layers with explicit memoization control - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const memoMap = yield* Layer.makeMemoMap * const scope = yield* Effect.scope * @@ -426,7 +430,11 @@ export const CurrentMemoMap = ServiceMap.Reference("effect/Layer/Curren * const loggerLayer = Layer.succeed(Logger)({ * log: (msg: string) => Effect.sync(() => console.log(msg)) * }) - * const loggerServices = yield* Layer.buildWithMemoMap(loggerLayer, memoMap, scope) + * const loggerServices = yield* Layer.buildWithMemoMap( + * loggerLayer, + * memoMap, + * scope + * ) * * return { * database: ServiceMap.get(dbServices, Database), @@ -471,7 +479,7 @@ export const buildWithMemoMap: { * }>()("Database") {} * * // Build a layer to get its services - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const dbLayer = Layer.succeed(Database)({ * query: (sql: string) => Effect.succeed("result") * }) @@ -510,12 +518,15 @@ export const build = ( * }>()("Database") {} * * // Build a layer with explicit scope control - * const program = Effect.gen(function* () { + * 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, Effect.sync(() => console.log("Database closed"))) + * yield* Scope.addFinalizer( + * scope, + * Effect.sync(() => console.log("Database closed")) + * ) * return { query: (sql: string) => Effect.succeed(`Result: ${sql}`) } * })) * @@ -564,7 +575,7 @@ export const buildWithScope: { * }) * * // Use the layers in a program - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const database = yield* Database * const logger = yield* Logger * @@ -610,8 +621,14 @@ export const succeed: { * readonly log: (msg: string) => Effect.Effect * }>()("Logger") {} * - * const services = ServiceMap.make(Database, { query: (sql: string) => Effect.succeed("result") }) - * .pipe(ServiceMap.add(Logger, { log: (msg: string) => Effect.sync(() => console.log(msg)) })) + * const services = ServiceMap.make(Database, { + * query: (sql: string) => Effect.succeed("result") + * }) + * .pipe( + * ServiceMap.add(Logger, { + * log: (msg: string) => Effect.sync(() => console.log(msg)) + * }) + * ) * * const layer = Layer.succeedServices(services) * ``` @@ -765,11 +782,12 @@ const effectImpl = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Layer } from "effect" - * import { ServiceMap } from "effect" + * import { Effect, Layer, ServiceMap } from "effect" * - * class Database extends ServiceMap.Service Effect.Effect }>()("Database") {} + * class Database extends ServiceMap.Service< + * Database, + * { readonly query: (sql: string) => Effect.Effect } + * >()("Database") {} * * const layer = Layer.effectServices( * Effect.succeed(ServiceMap.make(Database, { @@ -793,8 +811,7 @@ export const effectServices = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Layer } from "effect" + * import { Effect, Layer } from "effect" * * const initLayer = Layer.effectDiscard( * Effect.sync(() => { @@ -996,7 +1013,8 @@ const provideWith = ( * * class UserService extends ServiceMap.Service Effect.Effect<{ - * id: string; name: string + * id: string + * name: string * }> * }>()("UserService") {} * @@ -1014,18 +1032,19 @@ const provideWith = ( * }) * * // 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 * * return { - * getUser: (id: string) => Effect.gen(function* () { - * yield* logger.log(`Looking up user ${id}`) - * const result = yield* database.query( - * `SELECT * FROM users WHERE id = ${id}` - * ) - * return { id, name: result } - * }) + * getUser: (id: string) => + * Effect.gen(function*() { + * yield* logger.log(`Looking up user ${id}`) + * const result = yield* database.query( + * `SELECT * FROM users WHERE id = ${id}` + * ) + * return { id, name: result } + * }) * } * })) * @@ -1035,7 +1054,7 @@ const provideWith = ( * ) * * // Now UserService layer has no dependencies - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const userService = yield* UserService * return yield* userService.getUser("123") * }).pipe( @@ -1097,7 +1116,7 @@ export const provide: { * * class UserService extends ServiceMap.Service Effect.Effect<{ - * id: string; + * id: string * name: string * }> * }>()("UserService") {} @@ -1112,18 +1131,19 @@ export const provide: { * }) * * // 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 * * return { - * getUser: (id: string) => Effect.gen(function* () { - * yield* logger.log(`Looking up user ${id}`) - * const result = yield* database.query( - * `SELECT * FROM users WHERE id = ${id}` - * ) - * return { id, name: result } - * }) + * getUser: (id: string) => + * Effect.gen(function*() { + * yield* logger.log(`Looking up user ${id}`) + * const result = yield* database.query( + * `SELECT * FROM users WHERE id = ${id}` + * ) + * return { id, name: result } + * }) * } * })) * @@ -1133,7 +1153,7 @@ export const provide: { * ) * * // Now the resulting layer provides UserService, Database, AND Logger - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const userService = yield* UserService * const logger = yield* Logger // Still available! * const database = yield* Database // Still available! @@ -1195,7 +1215,8 @@ export const provideMerge: { * import { Effect, Layer, ServiceMap } from "effect" * * class Config extends ServiceMap.Service()("Config") {} * * class Database extends ServiceMap.Service Effect.succeed( - * `Querying ${config.dbUrl}: ${sql}` - * ) + * query: (sql: string) => + * Effect.succeed( + * `Querying ${config.dbUrl}: ${sql}` + * ) * }) * * // Create logger layer based on config * const loggerLayer = Layer.succeed(Logger)({ - * log: (msg: string) => config.logLevel === "debug" - * ? Effect.sync(() => console.log(`[DEBUG] ${msg}`)) - * : Effect.sync(() => console.log(msg)) + * log: (msg: string) => + * config.logLevel === "debug" + * ? Effect.sync(() => console.log(`[DEBUG] ${msg}`)) + * : Effect.sync(() => console.log(msg)) * }) * * // Return combined layer @@ -1237,7 +1260,7 @@ export const provideMerge: { * ) * * // Use the dynamic services - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const database = yield* Database * const logger = yield* Logger * @@ -1278,8 +1301,7 @@ export const flatMap: { * * @example * ```ts - * import { Effect, Layer, ServiceMap } from "effect" - * import { Data } from "effect" + * import { Data, Effect, Layer, ServiceMap } from "effect" * * class DatabaseError extends Data.TaggedError("DatabaseError")<{ * message: string @@ -1290,7 +1312,7 @@ export const flatMap: { * }>()("Database") {} * * // Layer that can fail during construction - * const flakyDatabaseLayer = Layer.effect(Database)(Effect.gen(function* () { + * const flakyDatabaseLayer = Layer.effect(Database)(Effect.gen(function*() { * // Simulate a database connection that might fail * const shouldFail = Math.random() > 0.5 * if (shouldFail) { @@ -1304,7 +1326,7 @@ export const flatMap: { * const reliableDatabaseLayer = flakyDatabaseLayer.pipe(Layer.orDie) * * // Now the layer type is Layer - no error in type - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const database = yield* Database * return yield* database.query("SELECT * FROM users") * }).pipe( @@ -1355,8 +1377,7 @@ export { * * @example * ```ts - * import { Cause, Effect, Layer, ServiceMap } from "effect" - * import { Data } from "effect" + * import { Data, Effect, Layer, ServiceMap } from "effect" * * class DatabaseError extends Data.TaggedError("DatabaseError")<{ * message: string @@ -1375,7 +1396,7 @@ export { * }>()("Logger") {} * * // Primary database layer that might fail - * const primaryDatabaseLayer = Layer.effect(Database)(Effect.gen(function* () { + * const primaryDatabaseLayer = Layer.effect(Database)(Effect.gen(function*() { * yield* Effect.fail(new DatabaseError({ message: "Primary DB unreachable" })) * return { query: (sql: string) => Effect.succeed(`Primary: ${sql}`) } * })) @@ -1389,13 +1410,14 @@ export { * query: (sql: string) => Effect.succeed(`Memory: ${sql}`) * }), * Layer.succeed(Logger)({ - * log: (msg: string) => Effect.sync(() => console.log(`[FALLBACK] ${msg}`)) + * log: (msg: string) => + * Effect.sync(() => console.log(`[FALLBACK] ${msg}`)) * }) * ) * }) * ) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const database = yield* Database * return yield* database.query("SELECT * FROM users") * }).pipe( @@ -1470,23 +1492,24 @@ export const updateService: { * import { Effect, Layer, Ref, ServiceMap } from "effect" * * class Counter extends ServiceMap.Service Effect.Effect * }>()("Counter") {} * * // Layer that creates a counter with shared state - * const counterLayer = Layer.effect(Counter)(Effect.gen(function* () { + * const counterLayer = Layer.effect(Counter)(Effect.gen(function*() { * const ref = yield* Ref.make(0) * return { * count: 0, - * increment: () => Ref.update(ref, n => n + 1).pipe( - * Effect.flatMap(() => Ref.get(ref)) - * ) + * increment: () => + * Ref.update(ref, (n) => n + 1).pipe( + * Effect.flatMap(() => Ref.get(ref)) + * ) * } * })) * * // By default, layers are shared - same instance used everywhere - * const sharedProgram = Effect.gen(function* () { + * const sharedProgram = Effect.gen(function*() { * const counter1 = yield* Counter * const counter2 = yield* Counter * @@ -1497,7 +1520,7 @@ export const updateService: { * ) * * // Fresh layer creates a new instance each time - * const freshProgram = Effect.gen(function* () { + * const freshProgram = Effect.gen(function*() { * const counter1 = yield* Counter * const counter2 = yield* Counter * @@ -1532,18 +1555,20 @@ 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 { - * start: () => Effect.gen(function* () { - * yield* Console.log("Server listening on port 3000") - * return "Server started" - * }), - * stop: () => Effect.gen(function* () { - * yield* Console.log("Server stopped gracefully") - * return "Server stopped" - * }) + * start: () => + * Effect.gen(function*() { + * yield* Console.log("Server listening on port 3000") + * return "Server started" + * }), + * stop: () => + * Effect.gen(function*() { + * yield* Console.log("Server stopped gracefully") + * return "Server stopped" + * }) * } * })) * @@ -1607,20 +1632,25 @@ export type PartialEffectful = Types.Simplify< * * class UserService extends ServiceMap.Service Effect.Effect<{ id: string; name: string }, Error> + * readonly getUser: ( + * id: string + * ) => Effect.Effect<{ id: string; name: string }, Error> * readonly deleteUser: (id: string) => Effect.Effect - * readonly updateUser: (id: string, data: object) => Effect.Effect<{ id: string; name: string }, Error> + * readonly updateUser: ( + * id: string, + * data: object + * ) => Effect.Effect<{ id: string; name: string }, Error> * }>()("UserService") {} * * // Create a partial mock - only implement what you need for testing * const testUserLayer = Layer.mock(UserService)({ * config: { apiUrl: "https://test-api.com" }, // Required - non-Effect property - * getUser: (id: string) => Effect.succeed({ id, name: "Test User" }), // Mock implementation + * getUser: (id: string) => Effect.succeed({ id, name: "Test User" }) // Mock implementation * // deleteUser and updateUser are omitted - will throw UnimplementedError if called * }) * * // Use in tests - * const testProgram = Effect.gen(function* () { + * const testProgram = Effect.gen(function*() { * const userService = yield* UserService * * // This works - we provided an implementation @@ -1716,7 +1746,7 @@ export const satisfiesSuccessType = * declare const TypeErrorLayer: Layer.Layer * declare const StringLayer: Layer.Layer * - * // Define a constraint that the error type must be an Error + * // Define a constraint that the error type must be an Error * const satisfiesError = Layer.satisfiesErrorType() * * // This works - Layer extends Layer diff --git a/packages/effect/src/LayerMap.ts b/packages/effect/src/LayerMap.ts index 8beaec8a31..d272b9bc9d 100644 --- a/packages/effect/src/LayerMap.ts +++ b/packages/effect/src/LayerMap.ts @@ -17,10 +17,7 @@ const TypeId = "~effect/LayerMap" * @category Models * @example * ```ts - * import { Effect } from "effect" - * import { Layer } from "effect" - * import { ServiceMap } from "effect" - * import { LayerMap } from "effect" + * import { Effect, Layer, LayerMap, ServiceMap } from "effect" * * // Define a service key * const DatabaseService = ServiceMap.Service<{ @@ -35,7 +32,7 @@ const TypeId = "~effect/LayerMap" * ) * * // Use the LayerMap - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const layerMap = yield* createDatabaseLayerMap * * // Get a layer for a specific environment @@ -82,9 +79,7 @@ export interface LayerMap { * * @example * ```ts - * import { Effect } from "effect" - * import { Layer, ServiceMap } from "effect" - * import { LayerMap, Scope } from "effect" + * import { Effect, Layer, LayerMap, ServiceMap } from "effect" * * // Define a service key * const DatabaseService = ServiceMap.Service<{ @@ -92,11 +87,12 @@ export interface LayerMap { * }>("Database") * * // Create a LayerMap that provides different database configurations - * const program = Effect.gen(function* () { - * const layerMap = yield* LayerMap.make((env: string) => - * Layer.succeed(DatabaseService)({ - * query: (sql) => Effect.succeed(`${env}: ${sql}`) - * }), + * const program = Effect.gen(function*() { + * const layerMap = yield* LayerMap.make( + * (env: string) => + * Layer.succeed(DatabaseService)({ + * query: (sql) => Effect.succeed(`${env}: ${sql}`) + * }), * { idleTimeToLive: "5 seconds" } * ) * @@ -105,7 +101,7 @@ export interface LayerMap { * * // Use the layer to provide the service * const result = yield* Effect.provide( - * Effect.gen(function* () { + * Effect.gen(function*() { * const db = yield* DatabaseService * return yield* db.query("SELECT * FROM users") * }), @@ -161,9 +157,7 @@ export const make: < * @category Constructors * @example * ```ts - * import { Effect } from "effect" - * import { LayerMap } from "effect" - * import { Layer, ServiceMap } from "effect" + * import { Effect, Layer, LayerMap, ServiceMap } from "effect" * * // Define service keys * const DevDatabase = ServiceMap.Service<{ @@ -185,7 +179,7 @@ export const make: < * } as const * * // Create a LayerMap from the record - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const layerMap = yield* LayerMap.fromRecord(layers, { * idleTimeToLive: "10 seconds" * }) @@ -275,11 +269,7 @@ export interface TagClass< * * @example * ```ts - * import { Effect } from "effect" - * import { Layer } from "effect" - * import { ServiceMap } from "effect" - * import { Console } from "effect" - * import { LayerMap } from "effect" + * import { Console, Effect, Layer, LayerMap, ServiceMap } from "effect" * * // Define a service key * const Greeter = ServiceMap.Service<{ @@ -299,7 +289,7 @@ export interface TagClass< * }) {} * * // Usage - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * // Access and use the Greeter service * const greeter = yield* Greeter * yield* Console.log(yield* greeter.greet) diff --git a/packages/effect/src/Logger.ts b/packages/effect/src/Logger.ts index e46170fedf..9399cb1da5 100644 --- a/packages/effect/src/Logger.ts +++ b/packages/effect/src/Logger.ts @@ -74,8 +74,7 @@ * ## Batched Logging * * ```ts - * import { Effect, Logger } from "effect" - * import { Duration } from "effect" + * import { Duration, Effect, Logger } from "effect" * * const batchedLogger = Logger.batched(Logger.formatJson, { * window: Duration.seconds(5), @@ -104,6 +103,7 @@ import type * as Cause from "./Cause.ts" import type * as Duration from "./Duration.ts" import type * as Effect from "./Effect.ts" import type * as Fiber from "./Fiber.ts" +import * as FileSystem from "./FileSystem.ts" import * as Formatter from "./Formatter.ts" import { dual } from "./Function.ts" import { isEffect, withFiber } from "./internal/core.ts" @@ -111,8 +111,7 @@ import * as effect from "./internal/effect.ts" import * as Layer from "./Layer.ts" import type * as LogLevel from "./LogLevel.ts" import type { Pipeable } from "./Pipeable.ts" -import * as FileSystem from "./platform/FileSystem.ts" -import type { PlatformError } from "./platform/PlatformError.ts" +import type { PlatformError } from "./PlatformError.ts" import * as Predicate from "./Predicate.ts" import { CurrentLogAnnotations, CurrentLogSpans } from "./References.ts" import type * as Scope from "./Scope.ts" @@ -819,8 +818,7 @@ export const formatJson = map(formatStructured, Formatter.formatJson) * * @example * ```ts - * import { Effect, Logger } from "effect" - * import { Duration } from "effect" + * import { Duration, Effect, Logger } from "effect" * * // Create a batched logger that flushes every 5 seconds * const batchedLogger = Logger.batched(Logger.formatJson, { @@ -1217,8 +1215,7 @@ export const layer = < * @example * ```ts * import { NodeFileSystem } from "@effect/platform-node" - * import { Effect, Logger } from "effect" - * import { Duration } from "effect" + * import { Duration, Effect, Logger } from "effect" * * // Basic file logging * const basicFileLogger = Effect.gen(function*() { diff --git a/packages/effect/src/ManagedRuntime.ts b/packages/effect/src/ManagedRuntime.ts index 305c8f1d3c..89d85f6dcf 100644 --- a/packages/effect/src/ManagedRuntime.ts +++ b/packages/effect/src/ManagedRuntime.ts @@ -135,18 +135,14 @@ export interface ManagedRuntime { * @category runtime class * @example * ```ts - * import { Effect } from "effect" - * import { Layer } from "effect" - * import { Console } from "effect" - * import { ServiceMap } from "effect" - * import { ManagedRuntime } from "effect" + * import { Console, Effect, Layer, ManagedRuntime, ServiceMap } from "effect" * - * class Notifications extends ServiceMap.Service< Notifications, { + * class Notifications extends ServiceMap.Service Effect.Effect * }>()("Notifications") { * static layer = Layer.succeed(this)({ * notify: (message) => Console.log(message) - * }) + * }) * } * * async function main() { diff --git a/packages/effect/src/Metric.ts b/packages/effect/src/Metric.ts index 023524e68c..8606a774db 100644 --- a/packages/effect/src/Metric.ts +++ b/packages/effect/src/Metric.ts @@ -172,8 +172,7 @@ import type { Contravariant, Covariant } from "./types/Types.ts" * * @example * ```ts - * import { Effect, Metric } from "effect" - * import { Data } from "effect" + * import { Data, Effect, Metric } from "effect" * * class MetricExample extends Data.TaggedError("MetricExample")<{ * readonly operation: string @@ -249,8 +248,7 @@ export interface Metric extends Pipeable { * * @example * ```ts - * import { Effect, Metric } from "effect" - * import { Data } from "effect" + * import { Data, Effect, Metric } from "effect" * * class CounterInterfaceError extends Data.TaggedError("CounterInterfaceError")<{ * readonly operation: string @@ -312,8 +310,7 @@ export interface Counter extends Metric { * * @example * ```ts - * import { Effect, Metric } from "effect" - * import { Data } from "effect" + * import { Data, Effect, Metric } from "effect" * * class FrequencyInterfaceError * extends Data.TaggedError("FrequencyInterfaceError")<{ @@ -460,8 +456,7 @@ export interface Frequency extends Metric {} * * @example * ```ts - * import { Effect, Metric } from "effect" - * import { Data } from "effect" + * import { Data, Effect, Metric } from "effect" * * class FrequencyStateError extends Data.TaggedError("FrequencyStateError")<{ * readonly operation: string @@ -550,8 +545,7 @@ export interface FrequencyState { * * @example * ```ts - * import { Effect, Metric } from "effect" - * import { Data } from "effect" + * import { Data, Effect, Metric } from "effect" * * class GaugeInterfaceError extends Data.TaggedError("GaugeInterfaceError")<{ * readonly operation: string @@ -606,8 +600,7 @@ export interface Gauge extends Metric { * * @example * ```ts - * import { Effect, Metric } from "effect" - * import { Data } from "effect" + * import { Data, Effect, Metric } from "effect" * * class HistogramInterfaceError * extends Data.TaggedError("HistogramInterfaceError")<{ @@ -764,8 +756,7 @@ export interface Histogram extends Metric {} * * @example * ```ts - * import { Effect, Metric } from "effect" - * import { Data } from "effect" + * import { Data, Effect, Metric } from "effect" * * class HistogramStateError extends Data.TaggedError("HistogramStateError")<{ * readonly operation: string @@ -861,8 +852,7 @@ export interface HistogramState { * * @example * ```ts - * import { Effect, Metric } from "effect" - * import { Data } from "effect" + * import { Data, Effect, Metric } from "effect" * * class SummaryInterfaceError extends Data.TaggedError("SummaryInterfaceError")<{ * readonly operation: string @@ -955,8 +945,7 @@ export interface Summary extends Metric {} * * @example * ```ts - * import { Effect, Metric } from "effect" - * import { Data } from "effect" + * import { Data, Effect, Metric } from "effect" * * class SummaryStateError extends Data.TaggedError("SummaryStateError")<{ * readonly operation: string @@ -1044,8 +1033,7 @@ export interface SummaryState { * * @example * ```ts - * import { Effect, Metric } from "effect" - * import { Data } from "effect" + * import { Data, Effect, Metric } from "effect" * * class MetricsError extends Data.TaggedError("MetricsError")<{ * readonly operation: string @@ -1090,8 +1078,7 @@ export declare namespace Metric { * * @example * ```ts - * import { Effect, Metric } from "effect" - * import { Data } from "effect" + * import { Data, Effect, Metric } from "effect" * * class MetricTypeError extends Data.TaggedError("MetricTypeError")<{ * readonly operation: string @@ -1171,8 +1158,7 @@ export declare namespace Metric { * * @example * ```ts - * import { Effect, Metric } from "effect" - * import { Data } from "effect" + * import { Data, Effect, Metric } from "effect" * * class AttributesError extends Data.TaggedError("AttributesError")<{ * readonly operation: string @@ -1247,8 +1233,7 @@ export declare namespace Metric { * * @example * ```ts - * import { Effect, Metric } from "effect" - * import { Data } from "effect" + * import { Data, Effect, Metric } from "effect" * * class AttributeSetError extends Data.TaggedError("AttributeSetError")<{ * readonly operation: string @@ -1434,8 +1419,7 @@ export declare namespace Metric { * * @example * ```ts - * import { Effect, Metric } from "effect" - * import { Data } from "effect" + * import { Data, Effect, Metric } from "effect" * * class HooksError extends Data.TaggedError("HooksError")<{ * readonly operation: string @@ -1483,8 +1467,7 @@ export declare namespace Metric { * * @example * ```ts - * import { Effect, Metric } from "effect" - * import { Data } from "effect" + * import { Data, Effect, Metric } from "effect" * * class MetadataError extends Data.TaggedError("MetadataError")<{ * readonly operation: string @@ -1551,8 +1534,7 @@ export declare namespace Metric { * * @example * ```ts - * import { Effect, Metric } from "effect" - * import { Data } from "effect" + * import { Data, Effect, Metric } from "effect" * * class SnapshotProtoError extends Data.TaggedError("SnapshotProtoError")<{ * readonly operation: string @@ -1624,8 +1606,7 @@ export declare namespace Metric { * * @example * ```ts - * import { Effect, Metric } from "effect" - * import { Data } from "effect" + * import { Data, Effect, Metric } from "effect" * * class SnapshotError extends Data.TaggedError("SnapshotError")<{ * readonly operation: string @@ -1701,8 +1682,7 @@ export declare namespace Metric { * * @example * ```ts - * import { Effect, Metric } from "effect" - * import { Data } from "effect" + * import { Data, Effect, Metric } from "effect" * * class AttributesKeyError extends Data.TaggedError("AttributesKeyError")<{ * readonly operation: string @@ -1752,8 +1732,7 @@ export const CurrentMetricAttributesKey = "effect/Metric/CurrentMetricAttributes * * @example * ```ts - * import { Effect, Metric } from "effect" - * import { Data } from "effect" + * import { Data, Effect, Metric } from "effect" * * class AttributesError extends Data.TaggedError("AttributesError")<{ * readonly operation: string @@ -2206,8 +2185,7 @@ export const isMetric = (u: unknown): u is Metric => * * @example * ```ts - * import { Effect, Metric } from "effect" - * import { Data } from "effect" + * import { Data, Effect, Metric } from "effect" * * class CounterError extends Data.TaggedError("CounterError")<{ * readonly operation: string @@ -2286,8 +2264,7 @@ export const counter: { * * @example * ```ts - * import { Effect, Metric } from "effect" - * import { Data } from "effect" + * import { Data, Effect, Metric } from "effect" * * class GaugeError extends Data.TaggedError("GaugeError")<{ * readonly operation: string @@ -2364,8 +2341,7 @@ export const gauge: { * * @example * ```ts - * import { Effect, Metric } from "effect" - * import { Data } from "effect" + * import { Data, Effect, Metric } from "effect" * * class FrequencyError extends Data.TaggedError("FrequencyError")<{ * readonly operation: string @@ -2444,8 +2420,7 @@ export const frequency = (name: string, options?: { * * @example * ```ts - * import { Effect, Metric } from "effect" - * import { Data } from "effect" + * import { Data, Effect, Metric } from "effect" * * class HistogramError extends Data.TaggedError("HistogramError")<{ * readonly operation: string @@ -2524,9 +2499,7 @@ export const histogram = (name: string, options: { * * @example * ```ts - * import { Effect, Metric } from "effect" - * import { Data } from "effect" - * import { Duration } from "effect" + * import { Data, Duration, Effect, Metric } from "effect" * * class SummaryError extends Data.TaggedError("SummaryError")<{ * readonly operation: string @@ -2650,9 +2623,7 @@ export const summaryWithTimestamp = (name: string, options: { * * @example * ```ts - * import { Effect, Metric } from "effect" - * import { Data } from "effect" - * import { Duration } from "effect" + * import { Data, Duration, Effect, Metric } from "effect" * * class TimerError extends Data.TaggedError("TimerError")<{ * readonly operation: string @@ -2861,8 +2832,7 @@ export const update: { * * @example * ```ts - * import { Effect, Metric } from "effect" - * import { Data } from "effect" + * import { Data, Effect, Metric } from "effect" * * class MetricError extends Data.TaggedError("MetricError")<{ * readonly operation: string @@ -2927,8 +2897,7 @@ export const mapInput: { * * @example * ```ts - * import { Effect, Metric } from "effect" - * import { Data } from "effect" + * import { Data, Effect, Metric } from "effect" * * class MetricError extends Data.TaggedError("MetricError")<{ * readonly operation: string @@ -3046,8 +3015,7 @@ export const withAttributes: { * * @example * ```ts - * import { Console, Effect, Metric } from "effect" - * import { Data } from "effect" + * import { Console, Data, Effect, Metric } from "effect" * * class SnapshotError extends Data.TaggedError("SnapshotError")<{ * readonly operation: string @@ -3102,8 +3070,7 @@ export const snapshot: Effect> = InternalEffect.m * * @example * ```ts - * import { Console, Effect, Metric } from "effect" - * import { Data } from "effect" + * import { Console, Data, Effect, Metric } from "effect" * * class DumpError extends Data.TaggedError("DumpError")<{ * readonly operation: string @@ -3192,8 +3159,7 @@ export const dump: Effect = InternalEffect.flatMap(InternalEffect.servic * * @example * ```ts - * import { Effect, Metric } from "effect" - * import { Data } from "effect" + * import { Data, Effect, Metric } from "effect" * * class UnsafeSnapshotError extends Data.TaggedError("UnsafeSnapshotError")<{ * readonly operation: string @@ -3322,8 +3288,7 @@ const attributesToString = (attributes: Metric.AttributeSet): string => { * * @example * ```ts - * import { Effect, Metric } from "effect" - * import { Data } from "effect" + * import { Data, Effect, Metric } from "effect" * * class BoundaryError extends Data.TaggedError("BoundaryError")<{ * readonly operation: string @@ -3390,8 +3355,7 @@ export const boundariesFromIterable = (iterable: Iterable): ReadonlyArra * * @example * ```ts - * import { Effect, Metric } from "effect" - * import { Data } from "effect" + * import { Data, Effect, Metric } from "effect" * * class BoundaryError extends Data.TaggedError("BoundaryError")<{ * readonly operation: string @@ -3442,8 +3406,7 @@ export const linearBoundaries = (options: { * * @example * ```ts - * import { Effect, Metric } from "effect" - * import { Data } from "effect" + * import { Data, Effect, Metric } from "effect" * * class BoundaryError extends Data.TaggedError("BoundaryError")<{ * readonly operation: string @@ -3515,8 +3478,7 @@ const fiberFailures = counter("child_fiber_failures", { * * @example * ```ts - * import { Effect, Layer, Metric } from "effect" - * import { Data } from "effect" + * import { Data, Effect, Layer, Metric } from "effect" * * class MetricsError extends Data.TaggedError("MetricsError")<{ * readonly operation: string @@ -3556,8 +3518,7 @@ export const FiberRuntimeMetricsKey: "effect/observability/Metric/FiberRuntimeMe * @example * ```ts * import type { ServiceMap } from "effect" - * import { Effect, Layer, Metric } from "effect" - * import { Data } from "effect" + * import { Data, Effect, Layer, Metric } from "effect" * import type { Exit } from "effect/Exit" * * class MetricsError extends Data.TaggedError("MetricsError")<{ @@ -3600,8 +3561,7 @@ export interface FiberRuntimeMetricsService { * * @example * ```ts - * import { Effect, Metric } from "effect" - * import { Data } from "effect" + * import { Data, Effect, Metric } from "effect" * * class MetricsError extends Data.TaggedError("MetricsError")<{ * readonly operation: string @@ -3651,8 +3611,7 @@ export const FiberRuntimeMetrics = ServiceMap.Reference(self: Effect) => Effect = MutableHashMap.empty() + * const map: MutableHashMap.MutableHashMap = MutableHashMap + * .empty() * * // Add some data * MutableHashMap.set(map, "count", 42) @@ -164,7 +165,7 @@ export const make: >( * console.log(MutableHashMap.size(map)) // 3 * * // Works with any iterable - * const fromMap = MutableHashMap.fromIterable(new Map([['x', 10], ['y', 20]])) + * const fromMap = MutableHashMap.fromIterable(new Map([["x", 10], ["y", 20]])) * console.log(MutableHashMap.get(fromMap, "x")) // Some(10) * ``` * @@ -185,7 +186,6 @@ export const fromIterable = (entries: Iterable): MutableH * @example * ```ts * import * as MutableHashMap from "effect/MutableHashMap" - * import * as Option from "effect/Option" * * const map = MutableHashMap.make(["key1", 42], ["key2", 100]) * @@ -273,7 +273,7 @@ export const keys = (self: MutableHashMap): Iterable => self.back * console.log(total) // 6 * * // Filter values - * const largeValues = allValues.filter(value => value > 1) + * const largeValues = allValues.filter((value) => value > 1) * console.log(largeValues) // [2, 3] * ``` * @@ -479,14 +479,18 @@ export const modify: { * const map = MutableHashMap.make(["count", 5]) * * // Update existing key - * MutableHashMap.modifyAt(map, "count", (option) => - * Option.map(option, (n) => n * 2) + * MutableHashMap.modifyAt( + * map, + * "count", + * (option) => Option.map(option, (n) => n * 2) * ) * console.log(MutableHashMap.get(map, "count")) // Some(10) * * // Add new key - * MutableHashMap.modifyAt(map, "new", (option) => - * Option.isNone(option) ? Option.some(42) : option + * MutableHashMap.modifyAt( + * map, + * "new", + * (option) => Option.isNone(option) ? Option.some(42) : option * ) * console.log(MutableHashMap.get(map, "new")) // Some(42) * @@ -495,8 +499,10 @@ export const modify: { * console.log(MutableHashMap.has(map, "count")) // false * * // Conditional update - * MutableHashMap.modifyAt(map, "new", (option) => - * Option.filter(option, (n) => n > 50) // Remove if <= 50 + * MutableHashMap.modifyAt( + * map, + * "new", + * (option) => Option.filter(option, (n) => n > 50) // Remove if <= 50 * ) * console.log(MutableHashMap.has(map, "new")) // false (42 <= 50) * ``` diff --git a/packages/effect/src/MutableHashSet.ts b/packages/effect/src/MutableHashSet.ts index b35fe4616e..89ce0e9b94 100644 --- a/packages/effect/src/MutableHashSet.ts +++ b/packages/effect/src/MutableHashSet.ts @@ -39,7 +39,10 @@ const TypeId = "~effect/collections/MutableHashSet" * import { MutableHashSet } from "effect" * * // Create a mutable hash set - * const set: MutableHashSet.MutableHashSet = MutableHashSet.make("apple", "banana") + * const set: MutableHashSet.MutableHashSet = MutableHashSet.make( + * "apple", + * "banana" + * ) * * // Add elements * MutableHashSet.add(set, "cherry") diff --git a/packages/effect/src/MutableList.ts b/packages/effect/src/MutableList.ts index 93cfb7834c..d62bf8e395 100644 --- a/packages/effect/src/MutableList.ts +++ b/packages/effect/src/MutableList.ts @@ -95,7 +95,7 @@ export interface MutableList { * const createProcessor = (): { * queue: MutableList.MutableList * add: (item: T) => void - * process: () => T[] + * process: () => Array * } => { * const queue = MutableList.make() * return { @@ -123,7 +123,9 @@ export declare namespace MutableList { * MutableList.append(list, 2) * * // Access bucket information (for debugging or advanced usage) - * const inspectBucket = (bucket: MutableList.MutableList.Bucket | undefined) => { + * const inspectBucket = ( + * bucket: MutableList.MutableList.Bucket | undefined + * ) => { * if (bucket) { * console.log("Bucket array:", bucket.array) * console.log("Bucket offset:", bucket.offset) @@ -196,7 +198,9 @@ export const Empty: unique symbol = Symbol.for("effect/MutableList/Empty") * const list = MutableList.make() * * // Type-safe handling of empty results - * const takeAndDouble = (queue: MutableList.MutableList): number | null => { + * const takeAndDouble = ( + * queue: MutableList.MutableList + * ): number | null => { * const item: number | MutableList.Empty = MutableList.take(queue) * * if (item === MutableList.Empty) { @@ -213,7 +217,9 @@ export const Empty: unique symbol = Symbol.for("effect/MutableList/Empty") * console.log(takeAndDouble(list)) // 10 * * // Type guard function - * const isEmpty = (result: number | MutableList.Empty): result is MutableList.Empty => { + * const isEmpty = ( + * result: number | MutableList.Empty + * ): result is MutableList.Empty => { * return result === MutableList.Empty * } * @@ -451,7 +457,10 @@ export const prependAllUnsafe = (self: MutableList, messages: ReadonlyArra * * // Useful for bulk loading * const bulkList = MutableList.make() - * const count = MutableList.appendAll(bulkList, Array.from({ length: 1000 }, (_, i) => i)) + * const count = MutableList.appendAll( + * bulkList, + * Array.from({ length: 1000 }, (_, i) => i) + * ) * console.log(count) // 1000 * ``` * @@ -676,7 +685,10 @@ export const takeNVoid = (self: MutableList, n: number): void => { * console.log("Queue is now empty:", queue.length === 0) * * // Drain pattern for processing - * function drainAndProcess(list: MutableList.MutableList, processor: (items: T[]) => void) { + * function drainAndProcess( + * list: MutableList.MutableList, + * processor: (items: Array) => void + * ) { * if (list.length > 0) { * const items = MutableList.takeAll(list) * processor(items) @@ -721,7 +733,10 @@ export const takeAll = (self: MutableList): Array => takeN(self, self.l * } * * // Consumer pattern - * function processNext(queue: MutableList.MutableList, processor: (item: T) => void): boolean { + * function processNext( + * queue: MutableList.MutableList, + * processor: (item: T) => void + * ): boolean { * const item = MutableList.take(queue) * if (item !== MutableList.Empty) { * processor(item) @@ -803,7 +818,7 @@ export const toArray = (self: MutableList): Array => toArrayN(self, sel * console.log(MutableList.takeAll(indexed)) // ["a", "c", "e"] * * // Real-world example: filtering a log queue - * const logs = MutableList.make<{ level: string, message: string }>() + * const logs = MutableList.make<{ level: string; message: string }>() * MutableList.appendAll(logs, [ * { level: "INFO", message: "App started" }, * { level: "ERROR", message: "Connection failed" }, @@ -862,7 +877,7 @@ export const filter = (self: MutableList, f: (value: A, i: number) => bool * console.log(list.length) // 2 * * // Real-world example: removing completed tasks - * const tasks = MutableList.make<{ id: number, status: string }>() + * const tasks = MutableList.make<{ id: number; status: string }>() * MutableList.appendAll(tasks, [ * { id: 1, status: "pending" }, * { id: 2, status: "completed" }, diff --git a/packages/effect/src/MutableRef.ts b/packages/effect/src/MutableRef.ts index e51247232b..655338026b 100644 --- a/packages/effect/src/MutableRef.ts +++ b/packages/effect/src/MutableRef.ts @@ -357,7 +357,7 @@ export const getAndIncrement = (self: MutableRef): number => getAndUpdat * console.log(previousValue) // "new" * * // Useful for atomic swaps in algorithms - * const buffer = MutableRef.make(["a", "b", "c"]) + * const buffer = MutableRef.make>(["a", "b", "c"]) * const oldBuffer = MutableRef.getAndSet(buffer, []) * console.log(oldBuffer) // ["a", "b", "c"] * console.log(MutableRef.get(buffer)) // [] @@ -410,7 +410,7 @@ export const getAndSet: { * console.log(result) // Previous value before increment * * // Useful for implementing atomic operations - * const list = MutableRef.make([1, 2, 3]) + * const list = MutableRef.make>([1, 2, 3]) * const oldList = MutableRef.getAndUpdate(list, (arr) => [...arr, 4]) * console.log(oldList) // [1, 2, 3] * console.log(MutableRef.get(list)) // [1, 2, 3, 4] @@ -525,10 +525,10 @@ export const incrementAndGet = (self: MutableRef): number => updateAndGe * console.log(MutableRef.get(ref)) // "new value" * * // Useful for state management - * const state = MutableRef.make<'idle' | 'loading' | 'success' | 'error'>('idle') - * MutableRef.set(state, 'loading') + * const state = MutableRef.make<"idle" | "loading" | "success" | "error">("idle") + * MutableRef.set(state, "loading") * // ... perform async operation - * MutableRef.set(state, 'success') + * MutableRef.set(state, "success") * ``` * * @since 2.0.0 @@ -625,7 +625,7 @@ export const setAndGet: { * console.log(MutableRef.get(counter)) // 24 * * // Array operations - * const list = MutableRef.make([1, 2, 3]) + * const list = MutableRef.make>([1, 2, 3]) * MutableRef.update(list, (arr) => [...arr, 4]) * console.log(MutableRef.get(list)) // [1, 2, 3, 4] * ``` @@ -677,8 +677,8 @@ export const update: { * console.log(`New score: ${newScore}`) // "New score: 150" * * // Array transformations - * const list = MutableRef.make([1, 2, 3]) - * const newList = MutableRef.updateAndGet(list, (arr) => arr.map(x => x * 2)) + * const list = MutableRef.make>([1, 2, 3]) + * const newList = MutableRef.updateAndGet(list, (arr) => arr.map((x) => x * 2)) * console.log(newList) // [2, 4, 6] * console.log(MutableRef.get(list)) // [2, 4, 6] * ``` @@ -720,7 +720,7 @@ export const updateAndGet: { * const darkMode = MutableRef.make(false) * const toggleDarkMode = () => { * MutableRef.toggle(darkMode) - * console.log(`Dark mode: ${MutableRef.get(darkMode) ? 'ON' : 'OFF'}`) + * console.log(`Dark mode: ${MutableRef.get(darkMode) ? "ON" : "OFF"}`) * } * * toggleDarkMode() // "Dark mode: ON" diff --git a/packages/effect/src/NonEmptyIterable.ts b/packages/effect/src/NonEmptyIterable.ts index 131893e3b2..1ddedc2682 100644 --- a/packages/effect/src/NonEmptyIterable.ts +++ b/packages/effect/src/NonEmptyIterable.ts @@ -33,7 +33,13 @@ * } * * // Using Array.make to create non-empty arrays - * const numbers = Array.make(1, 2, 3, 4, 5) as unknown as NonEmptyIterable.NonEmptyIterable + * 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 @@ -53,16 +59,19 @@ * ## Working with Different Iterable Types * * ```ts - * import { pipe } from "effect" - * import * as NonEmptyIterable from "effect/NonEmptyIterable" * import { Array } from "effect" - * import * as Chunk from "effect/Chunk" * * // Creating non-empty arrays - * const nonEmptyArray = Array.make(1, 2, 3) as unknown as NonEmptyIterable.NonEmptyIterable + * 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 + * const nonEmptyString = "hello" as unknown as NonEmptyIterable.NonEmptyIterable< + * string + * > * const [firstChar] = NonEmptyIterable.unprepend(nonEmptyString) * console.log(firstChar) // "h" * @@ -86,17 +95,18 @@ * } * } * - * const [firstFib, restFib] = NonEmptyIterable.unprepend(fibonacci() as unknown as NonEmptyIterable.NonEmptyIterable) + * const [firstFib, restFib] = NonEmptyIterable.unprepend( + * fibonacci() as unknown as NonEmptyIterable.NonEmptyIterable + * ) * console.log(firstFib) // 1 * ``` * * ## Integration with Effect Arrays * * ```ts - * import { pipe } from "effect" - * import * as NonEmptyIterable from "effect/NonEmptyIterable" - * import { Array } from "effect" - * import * as Chunk from "effect/Chunk" + * 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 @@ -104,8 +114,8 @@ * const processData = pipe( * nonEmptyData, * Array.fromIterable, - * Array.map(x => x * 2), - * Array.filter(x => x > 5), + * Array.map((x) => x * 2), + * Array.filter((x) => x > 5) * // Result is a regular array since filtering might make it empty * ) * @@ -113,7 +123,7 @@ * const doubledData = pipe( * nonEmptyData, * Array.fromIterable, - * Array.map(x => x * 2) + * Array.map((x) => x * 2) * // This would still be non-empty if the source was non-empty * ) * ``` @@ -128,7 +138,7 @@ * * @example * ```ts - * import * as NonEmptyIterable from "effect/NonEmptyIterable" + * import type * as NonEmptyIterable from "effect/NonEmptyIterable" * * // The symbol is used internally for type branding * declare const data: NonEmptyIterable @@ -161,9 +171,9 @@ export declare const nonEmpty: unique symbol * * @example * ```ts - * import * as NonEmptyIterable from "effect/NonEmptyIterable" * import { Array } from "effect" * import * as Chunk from "effect/Chunk" + * import * as NonEmptyIterable from "effect/NonEmptyIterable" * * // Function that requires non-empty data * function getFirst(data: NonEmptyIterable.NonEmptyIterable): A { @@ -173,13 +183,20 @@ export declare const nonEmpty: unique symbol * } * * // Works with any non-empty iterable - * const numbers = Array.make(1, 2, 3) as unknown as NonEmptyIterable.NonEmptyIterable + * const numbers = Array.make( + * 1, + * 2, + * 3 + * ) as unknown as NonEmptyIterable.NonEmptyIterable * const firstNumber = getFirst(numbers) // 1 * * const chars = "hello" as unknown as NonEmptyIterable.NonEmptyIterable * const firstChar = getFirst(chars) // "h" * - * const entries = new Map([["a", 1], ["b", 2]]) as unknown as NonEmptyIterable.NonEmptyIterable<[string, number]> + * const entries = new Map([["a", 1], [ + * "b", + * 2 + * ]]) as unknown as NonEmptyIterable.NonEmptyIterable<[string, number]> * const firstEntry = getFirst(entries) // ["a", 1] * * // Custom generator @@ -188,7 +205,11 @@ export declare const nonEmpty: unique symbol * yield 2 * yield 1 * } - * const firstCount = getFirst(Chunk.fromIterable(countdown()) as unknown as NonEmptyIterable.NonEmptyIterable) // 3 + * const firstCount = getFirst( + * Chunk.fromIterable( + * countdown() + * ) as unknown as NonEmptyIterable.NonEmptyIterable + * ) // 3 * ``` * * @category model @@ -210,17 +231,25 @@ export interface NonEmptyIterable extends Iterable { * * @example * ```ts - * import * as NonEmptyIterable from "effect/NonEmptyIterable" * import { Array } from "effect" * import * as Chunk from "effect/Chunk" + * import * as NonEmptyIterable from "effect/NonEmptyIterable" * * // Helper to make iterator iterable for Array.from * const iteratorToIterable = (iterator: Iterator): Iterable => ({ - * [Symbol.iterator]() { return iterator } + * [Symbol.iterator]() { + * return iterator + * } * }) * * // With NonEmptyArray from Array.make (cast to NonEmptyIterable) - * const numbers = Array.make(1, 2, 3, 4, 5) as unknown as NonEmptyIterable.NonEmptyIterable + * const numbers = Array.make( + * 1, + * 2, + * 3, + * 4, + * 5 + * ) as unknown as NonEmptyIterable.NonEmptyIterable * const [first, rest] = NonEmptyIterable.unprepend(numbers) * console.log(first) // 1 * console.log(globalThis.Array.from(iteratorToIterable(rest))) // [2, 3, 4, 5] @@ -232,13 +261,20 @@ export interface NonEmptyIterable extends Iterable { * console.log(globalThis.Array.from(iteratorToIterable(restChars)).join("")) // "ello" * * // With Sets (assert when known to be non-empty) - * const uniqueNumbers = new Set([10, 20, 30]) as unknown as NonEmptyIterable.NonEmptyIterable + * const uniqueNumbers = new Set([ + * 10, + * 20, + * 30 + * ]) as unknown as NonEmptyIterable.NonEmptyIterable * const [firstUnique, restUnique] = NonEmptyIterable.unprepend(uniqueNumbers) * console.log(firstUnique) // 10 (or any element, Set order is not guaranteed) * console.log(globalThis.Array.from(iteratorToIterable(restUnique))) // [20, 30] (in some order) * * // With Maps (assert when known to be non-empty) - * const keyValuePairs = new Map([["a", 1], ["b", 2], ["c", 3]]) as unknown as NonEmptyIterable.NonEmptyIterable<[string, number]> + * const keyValuePairs = new Map([["a", 1], ["b", 2], [ + * "c", + * 3 + * ]]) as unknown as NonEmptyIterable.NonEmptyIterable<[string, number]> * const [firstPair, restPairs] = NonEmptyIterable.unprepend(keyValuePairs) * console.log(firstPair) // ["a", 1] * console.log(globalThis.Array.from(iteratorToIterable(restPairs))) // [["b", 2], ["c", 3]] @@ -255,7 +291,9 @@ export interface NonEmptyIterable extends Iterable { * } * } * - * const generator = Chunk.fromIterable(fibonacci()) as unknown as NonEmptyIterable.NonEmptyIterable + * const generator = Chunk.fromIterable( + * fibonacci() + * ) as unknown as NonEmptyIterable.NonEmptyIterable * const [firstFib, restFib] = NonEmptyIterable.unprepend(generator) * console.log(firstFib) // 1 * console.log(globalThis.Array.from(iteratorToIterable(restFib))) // [1, 2, 3, 5, 8, 13, 21, 34, 55, 89] @@ -270,7 +308,11 @@ export interface NonEmptyIterable extends Iterable { * let result = f(initial, first) * * // Convert iterator to iterable for iteration - * const iterable = { [Symbol.iterator]() { return rest } } + * const iterable = { + * [Symbol.iterator]() { + * return rest + * } + * } * for (const item of iterable) { * result = f(result, item) * } @@ -278,7 +320,12 @@ export interface NonEmptyIterable extends Iterable { * return result * } * - * const data = Array.make(1, 2, 3, 4) as unknown as NonEmptyIterable.NonEmptyIterable + * const data = Array.make( + * 1, + * 2, + * 3, + * 4 + * ) as unknown as NonEmptyIterable.NonEmptyIterable * const sum = reduceNonEmpty(data, (acc, x) => acc + x, 0) // 10 * ``` * diff --git a/packages/effect/src/Option.ts b/packages/effect/src/Option.ts index 470004bfc0..8620724d74 100644 --- a/packages/effect/src/Option.ts +++ b/packages/effect/src/Option.ts @@ -100,12 +100,14 @@ export interface Some extends Pipeable, Inspectable, Yieldable, /** * @example * ```ts - * import { Option } from "effect" - * import * as Unify from "effect/types/Unify" + * import type { Option } from "effect" + * import type * as Unify from "effect/types/Unify" * * // Internal unification interface used by the Effect library * // for type-level operations with Option types - * type ExampleUnify = Option.OptionUnify<{ [Unify.typeSymbol]?: Option.Option }> + * type ExampleUnify = Option.OptionUnify< + * { [Unify.typeSymbol]?: Option.Option } + * > * ``` * * @category Models @@ -118,7 +120,7 @@ export interface OptionUnify { /** * @example * ```ts - * import { Option } from "effect" + * import type { Option } from "effect" * * // Namespace containing utility types for Option * type StringOption = Option.Option @@ -134,7 +136,7 @@ export declare namespace Option { * * @example * ```ts - * import { Option } from "effect" + * import type { Option } from "effect" * * // Declare an Option holding a string * declare const myOption: Option.Option @@ -155,7 +157,7 @@ export declare namespace Option { /** * @example * ```ts - * import { Option } from "effect" + * import type { Option } from "effect" * * // Internal interface for type unification behavior * // Used by the Effect library's type system @@ -170,7 +172,7 @@ export interface OptionUnifyIgnore {} /** * @example * ```ts - * import { Option } from "effect" + * import type { Option } from "effect" * * // Type lambda interface for higher-kinded types with Option * // Used internally by the Effect library's type system @@ -463,8 +465,7 @@ export const fromIterable = (collection: Iterable): Option => { * * @example * ```ts - * import { Result } from "effect" - * import { Option } from "effect" + * import { Option, Result } from "effect" * * console.log(Option.getSuccess(Result.succeed("ok"))) * // Output: { _id: 'Option', _tag: 'Some', value: 'ok' } @@ -498,8 +499,7 @@ export const getSuccess: (self: Result) => Option = result.getSuc * * @example * ```ts - * import { Result } from "effect" - * import { Option } from "effect" + * import { Option, Result } from "effect" * * console.log(Option.getFailure(Result.succeed("ok"))) * // Output: { _id: 'Option', _tag: 'None' } @@ -659,7 +659,6 @@ export const orElseSome: { * * @example * ```ts - * import { Result } from "effect" * import { Option } from "effect" * * const primary = Option.some("primary") @@ -921,14 +920,16 @@ export const liftThrowable = , B>( * * @example * ```ts - * import * as assert from "node:assert" * import { Option } from "effect" + * import * as assert from "node:assert" * * assert.deepStrictEqual( - * Option.getOrThrowWith(Option.some(1), () => new Error('Unexpected None')), + * Option.getOrThrowWith(Option.some(1), () => new Error("Unexpected None")), * 1 * ) - * assert.throws(() => Option.getOrThrowWith(Option.none(), () => new Error('Unexpected None'))) + * assert.throws(() => + * Option.getOrThrowWith(Option.none(), () => new Error("Unexpected None")) + * ) * ``` * * @see {@link getOrThrow} for a version that throws a default error. @@ -959,8 +960,8 @@ export const getOrThrowWith: { * * @example * ```ts - * import * as assert from "node:assert" * import { Option } from "effect" + * import * as assert from "node:assert" * * assert.deepStrictEqual(Option.getOrThrow(Option.some(1)), 1) * assert.throws(() => Option.getOrThrow(Option.none())) @@ -1262,12 +1263,18 @@ export const andThen: { * } * } * - * const employee1: Employee = { company: { address: { street: { name: "high street" } } } } + * const employee1: Employee = { + * company: { address: { street: { name: "high street" } } } + * } * * // Extracting a deeply nested property * console.log( * Option.some(employee1) - * .pipe(Option.flatMapNullishOr((employee) => employee.company?.address?.street?.name)) + * .pipe( + * Option.flatMapNullishOr((employee) => + * employee.company?.address?.street?.name + * ) + * ) * ) * // Output: { _id: 'Option', _tag: 'Some', value: 'high street' } * @@ -1276,7 +1283,11 @@ export const andThen: { * // Property does not exist * console.log( * Option.some(employee2) - * .pipe(Option.flatMapNullishOr((employee) => employee.company?.address?.street?.name)) + * .pipe( + * Option.flatMapNullishOr((employee) => + * employee.company?.address?.street?.name + * ) + * ) * ) * // Output: { _id: 'Option', _tag: 'None' } * ``` @@ -1418,9 +1429,11 @@ export const zipLeft: { * ```ts * import { Option } from "effect" * - * const parse = (s: string): Option.Option => isNaN(Number(s)) ? Option.none() : Option.some(Number(s)) + * const parse = (s: string): Option.Option => + * isNaN(Number(s)) ? Option.none() : Option.some(Number(s)) * - * const double = (n: number): Option.Option => n > 0 ? Option.some(n * 2) : Option.none() + * const double = (n: number): Option.Option => + * n > 0 ? Option.some(n * 2) : Option.none() * * const parseAndDouble = Option.composeK(parse, double) * @@ -1460,7 +1473,8 @@ export const composeK: { * ```ts * import { Option } from "effect" * - * const getInteger = (n: number) => Number.isInteger(n) ? Option.some(n) : Option.none() + * const getInteger = (n: number) => + * Number.isInteger(n) ? Option.some(n) : Option.none() * * console.log(Option.tap(Option.none(), getInteger)) * // Output: { _id: 'Option', _tag: 'None' } @@ -1730,8 +1744,7 @@ export const ap: { * * @example * ```ts - * import { pipe } from "effect" - * import { Option } from "effect" + * import { Option, pipe } from "effect" * * const iterable = [Option.some(1), Option.none(), Option.some(2), Option.none()] * @@ -1808,8 +1821,7 @@ export const toArray = (self: Option): Array => isNone(self) ? [] : [se * * @example * ```ts - * import { Result } from "effect" - * import { Option } from "effect" + * import { Option, Result } from "effect" * * const parseNumber = (s: string): Result.Result => { * const n = Number(s) @@ -1853,7 +1865,10 @@ export const partitionMap: { * * // Transform and filter numbers * const transformEven = (n: Option.Option): Option.Option => - * Option.filterMap(n, (n) => (n % 2 === 0 ? Option.some(`Even: ${n}`) : Option.none())) + * Option.filterMap( + * n, + * (n) => (n % 2 === 0 ? Option.some(`Even: ${n}`) : Option.none()) + * ) * * console.log(transformEven(Option.none())) * // Output: { _id: 'Option', _tag: 'None' } @@ -1934,7 +1949,7 @@ export const filter: { * * @example * ```ts - * import { Option, Equivalence } from "effect" + * import { Equivalence, Option } from "effect" * * const isEquivalent = Option.getEquivalence(Equivalence.strict()) * @@ -2103,7 +2118,7 @@ export const liftPredicate: { // Note: I intentionally avoid using the NoInfer p * * @example * ```ts - * import { Option, Equivalence } from "effect" + * import { Equivalence, Option } from "effect" * * const contains = Option.containsWith(Equivalence.strict()) * @@ -2226,8 +2241,7 @@ export const exists: { * @example * ```ts * import * as assert from "node:assert" - * import { pipe } from "effect" - * import { Option } from "effect" + * import { Option, pipe } from "effect" * * const result = pipe( * Option.Do, @@ -2278,8 +2292,7 @@ export { * @example * ```ts * import * as assert from "node:assert" - * import { pipe } from "effect" - * import { Option } from "effect" + * import { Option, pipe } from "effect" * * const result = pipe( * Option.Do, @@ -2315,8 +2328,7 @@ export { * @example * ```ts * import * as assert from "node:assert" - * import { pipe } from "effect" - * import { Option } from "effect" + * import { Option, pipe } from "effect" * * const result = pipe( * Option.Do, @@ -2361,8 +2373,7 @@ export const bind: { * @example * ```ts * import * as assert from "node:assert" - * import { pipe } from "effect" - * import { Option } from "effect" + * import { Option, pipe } from "effect" * * const result = pipe( * Option.Do, @@ -2396,7 +2407,7 @@ export const Do: Option<{}> = some({}) * const maybeName: Option.Option = Option.some("John") * const maybeAge: Option.Option = Option.some(25) * - * const person = Option.gen(function* () { + * const person = Option.gen(function*() { * const name = (yield* maybeName).toUpperCase() * const age = yield* maybeAge * return { name, age } diff --git a/packages/effect/src/Order.ts b/packages/effect/src/Order.ts index 9fd82a05f7..87921e1199 100644 --- a/packages/effect/src/Order.ts +++ b/packages/effect/src/Order.ts @@ -30,10 +30,10 @@ import type { TypeLambda } from "./types/HKT.ts" * * @example * ```ts - * import { Order } from "effect" + * import type { Order } from "effect" * * // Custom order for objects by age - * const byAge: Order.Order<{ name: string, age: number }> = (self, that) => { + * const byAge: Order.Order<{ name: string; age: number }> = (self, that) => { * if (self.age < that.age) return -1 * if (self.age > that.age) return 1 * return 0 @@ -57,7 +57,7 @@ export interface Order { * * @example * ```ts - * import { Order } from "effect" + * import type { Order } from "effect" * * // OrderTypeLambda is used internally for type-level operations * type MyOrderType = Order.OrderTypeLambda @@ -75,17 +75,23 @@ export interface OrderTypeLambda extends TypeLambda { * * @example * ```ts - * import * as assert from "node:assert" * import { Order } from "effect" + * import * as assert from "node:assert" * - * const byAge = Order.make<{ name: string, age: number }>((self, that) => { + * const byAge = Order.make<{ name: string; age: number }>((self, that) => { * if (self.age < that.age) return -1 * if (self.age > that.age) return 1 * return 0 * }) * - * assert.deepStrictEqual(byAge({ name: "Alice", age: 30 }, { name: "Bob", age: 25 }), 1) - * assert.deepStrictEqual(byAge({ name: "Alice", age: 25 }, { name: "Bob", age: 30 }), -1) + * assert.deepStrictEqual( + * byAge({ name: "Alice", age: 30 }, { name: "Bob", age: 25 }), + * 1 + * ) + * assert.deepStrictEqual( + * byAge({ name: "Alice", age: 25 }, { name: "Bob", age: 30 }), + * -1 + * ) * ``` * * @category constructors @@ -101,8 +107,8 @@ export const make = ( * * @example * ```ts - * import * as assert from "node:assert" * import { Order } from "effect" + * import * as assert from "node:assert" * * assert.deepStrictEqual(Order.string("apple", "banana"), -1) * assert.deepStrictEqual(Order.string("banana", "apple"), 1) @@ -119,8 +125,8 @@ export const string: Order = make((self, that) => self < that ? -1 : 1) * * @example * ```ts - * import * as assert from "node:assert" * import { Order } from "effect" + * import * as assert from "node:assert" * * assert.deepStrictEqual(Order.number(1, 2), -1) * assert.deepStrictEqual(Order.number(2, 1), 1) @@ -137,8 +143,8 @@ export const number: Order = make((self, that) => self < that ? -1 : 1) * * @example * ```ts - * import * as assert from "node:assert" * import { Order } from "effect" + * import * as assert from "node:assert" * * assert.deepStrictEqual(Order.boolean(false, true), -1) * assert.deepStrictEqual(Order.boolean(true, false), 1) @@ -155,8 +161,8 @@ export const boolean: Order = make((self, that) => self < that ? -1 : 1 * * @example * ```ts - * import * as assert from "node:assert" * import { Order } from "effect" + * import * as assert from "node:assert" * * assert.deepStrictEqual(Order.bigint(1n, 2n), -1) * assert.deepStrictEqual(Order.bigint(2n, 1n), 1) @@ -173,8 +179,8 @@ export const bigint: Order = make((self, that) => self < that ? -1 : 1) * * @example * ```ts - * import * as assert from "node:assert" * import { Order } from "effect" + * import * as assert from "node:assert" * * const reverseNumber = Order.reverse(Order.number) * @@ -194,11 +200,17 @@ export const reverse = (O: Order): Order => make((self, that) => O(that * * @example * ```ts - * import * as assert from "node:assert" * import { Order } from "effect" + * import * as assert from "node:assert" * - * const byAge = Order.mapInput(Order.number, (person: { name: string, age: number }) => person.age) - * const byName = Order.mapInput(Order.string, (person: { name: string, age: number }) => person.name) + * const byAge = Order.mapInput( + * Order.number, + * (person: { name: string; age: number }) => person.age + * ) + * const byName = Order.mapInput( + * Order.string, + * (person: { name: string; age: number }) => person.name + * ) * const byAgeAndName = Order.combine(byAge, byName) * * const person1 = { name: "Alice", age: 30 } @@ -229,8 +241,8 @@ export const combine: { * * @example * ```ts - * import * as assert from "node:assert" * import { Order } from "effect" + * import * as assert from "node:assert" * * const emptyOrder = Order.empty() * @@ -250,11 +262,17 @@ export const empty = (): Order => make(() => 0) * * @example * ```ts - * import * as assert from "node:assert" * import { Order } from "effect" + * import * as assert from "node:assert" * - * const byAge = Order.mapInput(Order.number, (person: { name: string, age: number }) => person.age) - * const byName = Order.mapInput(Order.string, (person: { name: string, age: number }) => person.name) + * const byAge = Order.mapInput( + * Order.number, + * (person: { name: string; age: number }) => person.age + * ) + * const byName = Order.mapInput( + * Order.string, + * (person: { name: string; age: number }) => person.name + * ) * * const combinedOrder = Order.combineAll([byAge, byName]) * @@ -285,8 +303,8 @@ export const combineAll = (collection: Iterable>): Order => * * @example * ```ts - * import * as assert from "node:assert" * import { Order } from "effect" + * import * as assert from "node:assert" * * const byLength = Order.mapInput(Order.number, (s: string) => s.length) * @@ -311,8 +329,8 @@ export const mapInput: { * * @example * ```ts - * import * as assert from "node:assert" * import { Order } from "effect" + * import * as assert from "node:assert" * * const date1 = new Date("2023-01-01") * const date2 = new Date("2023-01-02") @@ -333,8 +351,8 @@ export const Date: Order = mapInput(number, (date) => date.getTime()) * * @example * ```ts - * import * as assert from "node:assert" * import { Order } from "effect" + * import * as assert from "node:assert" * * const tupleOrder = Order.product(Order.number, Order.string) * @@ -361,8 +379,8 @@ export const product: { * * @example * ```ts - * import * as assert from "node:assert" * import { Order } from "effect" + * import * as assert from "node:assert" * * const arrayOrder = Order.all([Order.number, Order.number]) * @@ -398,8 +416,8 @@ export const all = (collection: Iterable>): Order> * * @example * ```ts - * import * as assert from "node:assert" * import { Order } from "effect" + * import * as assert from "node:assert" * * const tupleOrder = Order.productMany(Order.number, [Order.number, Order.number]) * @@ -436,8 +454,8 @@ export const productMany: { * * @example * ```ts - * import * as assert from "node:assert" * import { Order } from "effect" + * import * as assert from "node:assert" * * const tupleOrder = Order.tuple([Order.number, Order.number]) * @@ -461,8 +479,8 @@ export const tuple = >>( * * @example * ```ts - * import * as assert from "node:assert" * import { Order } from "effect" + * import * as assert from "node:assert" * * const arrayOrder = Order.array(Order.number) * @@ -495,8 +513,8 @@ export const array = (O: Order): Order> => * * @example * ```ts - * import * as assert from "node:assert" * import { Order } from "effect" + * import * as assert from "node:assert" * * const personOrder = Order.struct({ * name: Order.string, @@ -535,8 +553,8 @@ export const struct = }>( * * @example * ```ts - * import * as assert from "node:assert" * import { Order } from "effect" + * import * as assert from "node:assert" * * const lessThanNumber = Order.lessThan(Order.number) * @@ -558,8 +576,8 @@ export const lessThan = (O: Order): { * * @example * ```ts - * import * as assert from "node:assert" * import { Order } from "effect" + * import * as assert from "node:assert" * * const greaterThanNumber = Order.greaterThan(Order.number) * @@ -581,8 +599,8 @@ export const greaterThan = (O: Order): { * * @example * ```ts - * import * as assert from "node:assert" * import { Order } from "effect" + * import * as assert from "node:assert" * * const lessThanOrEqualToNumber = Order.lessThanOrEqualTo(Order.number) * @@ -604,8 +622,8 @@ export const lessThanOrEqualTo = (O: Order): { * * @example * ```ts - * import * as assert from "node:assert" * import { Order } from "effect" + * import * as assert from "node:assert" * * const greaterThanOrEqualToNumber = Order.greaterThanOrEqualTo(Order.number) * @@ -627,8 +645,8 @@ export const greaterThanOrEqualTo = (O: Order): { * * @example * ```ts - * import * as assert from "node:assert" * import { Order } from "effect" + * import * as assert from "node:assert" * * const minNumber = Order.min(Order.number) * @@ -650,8 +668,8 @@ export const min = (O: Order): { * * @example * ```ts - * import * as assert from "node:assert" * import { Order } from "effect" + * import * as assert from "node:assert" * * const maxNumber = Order.max(Order.number) * @@ -673,9 +691,9 @@ export const max = (O: Order): { * * @example * ```ts - * import * as assert from "node:assert" * import { Order } from "effect" * import * as N from "effect/Number" + * import * as assert from "node:assert" * * const clamp = Order.clamp(N.Order)({ minimum: 1, maximum: 5 }) * @@ -710,8 +728,8 @@ export const clamp = (O: Order): { * * @example * ```ts - * import * as assert from "node:assert" * import { Order } from "effect" + * import * as assert from "node:assert" * * const betweenNumber = Order.between(Order.number) * diff --git a/packages/effect/src/Ordering.ts b/packages/effect/src/Ordering.ts index 556d5f41a5..17d3ed8da6 100644 --- a/packages/effect/src/Ordering.ts +++ b/packages/effect/src/Ordering.ts @@ -38,7 +38,7 @@ import * as Reducer_ from "./Reducer.ts" * * @example * ```ts - * import { Ordering } from "effect" + * import type { Ordering } from "effect" * * // Custom comparison function * const compareNumbers = (a: number, b: number): Ordering.Ordering => { @@ -49,7 +49,7 @@ import * as Reducer_ from "./Reducer.ts" * * console.log(compareNumbers(5, 10)) // -1 (5 < 10) * console.log(compareNumbers(10, 5)) // 1 (10 > 5) - * console.log(compareNumbers(5, 5)) // 0 (5 == 5) + * console.log(compareNumbers(5, 5)) // 0 (5 == 5) * * // Using with string comparison * const compareStrings = (a: string, b: string): Ordering.Ordering => { @@ -71,9 +71,9 @@ export type Ordering = -1 | 0 | 1 * import { Ordering } from "effect" * * // Basic reversal - * console.log(Ordering.reverse(1)) // -1 (greater becomes less) + * console.log(Ordering.reverse(1)) // -1 (greater becomes less) * console.log(Ordering.reverse(-1)) // 1 (less becomes greater) - * console.log(Ordering.reverse(0)) // 0 (equal stays equal) + * console.log(Ordering.reverse(0)) // 0 (equal stays equal) * * // Creating descending sort from ascending comparison * const compareNumbers = (a: number, b: number): Ordering.Ordering => @@ -83,7 +83,7 @@ export type Ordering = -1 | 0 | 1 * Ordering.reverse(compareNumbers(a, b)) * * const numbers = [3, 1, 4, 1, 5] - * numbers.sort(compareNumbers) // [1, 1, 3, 4, 5] (ascending) + * numbers.sort(compareNumbers) // [1, 1, 3, 4, 5] (ascending) * numbers.sort(compareDescending) // [5, 4, 3, 1, 1] (descending) * * // Useful for toggling sort direction @@ -103,14 +103,14 @@ export const reverse = (o: Ordering): Ordering => (o === -1 ? 1 : o === 1 ? -1 : * * @example * ```ts - * import * as assert from "node:assert" * import { Ordering } from "effect" * import { constant } from "effect/Function" + * import * as assert from "node:assert" * * const toMessage = Ordering.match({ - * onLessThan: constant('less than'), - * onEqual: constant('equal'), - * onGreaterThan: constant('greater than') + * onLessThan: constant("less than"), + * onEqual: constant("equal"), + * onGreaterThan: constant("greater than") * }) * * assert.deepStrictEqual(toMessage(-1), "less than") diff --git a/packages/effect/src/platform/Path.ts b/packages/effect/src/Path.ts similarity index 96% rename from packages/effect/src/platform/Path.ts rename to packages/effect/src/Path.ts index e01db08549..329675a956 100644 --- a/packages/effect/src/platform/Path.ts +++ b/packages/effect/src/Path.ts @@ -1,11 +1,11 @@ /** * @since 4.0.0 */ -import * as Effect from "../Effect.ts" -import { identity } from "../Function.ts" -import * as Layer from "../Layer.ts" -import * as ServiceMap from "../ServiceMap.ts" +import * as Effect from "./Effect.ts" +import { identity } from "./Function.ts" +import * as Layer from "./Layer.ts" import { BadArgument } from "./PlatformError.ts" +import * as ServiceMap from "./ServiceMap.ts" /** * @since 4.0.0 @@ -17,10 +17,9 @@ export const TypeId = "~effect/platform/Path" * @category model * @example * ```ts - * import { Effect } from "effect" - * import { Path } from "effect/platform" + * import { Effect, Path } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const path = yield* Path.Path * * // Use various path operations @@ -71,11 +70,10 @@ export interface Path { * @category namespace * @example * ```ts - * import { Effect } from "effect" - * import { Path } from "effect/platform" + * import { Effect, Path } from "effect" * * // Access types and utilities in the Path namespace - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const path = yield* Path.Path * * // Parse a path and get a Path.Parsed object @@ -100,10 +98,9 @@ export declare namespace Path { * @category model * @example * ```ts - * import { Effect } from "effect" - * import { Path } from "effect/platform" + * import { Effect, Path } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const path = yield* Path.Path * * // Parse a path into its components @@ -141,9 +138,7 @@ export declare namespace Path { * @category tag * @example * ```ts - * import { Effect } from "effect" - * import { Layer } from "effect" - * import { Path } from "effect/platform" + * import { Effect, Layer, Path } from "effect" * * // Create a custom path implementation * const customPath: Path.Path = { @@ -151,7 +146,9 @@ export declare namespace Path { * sep: "/", * basename: (path: string, suffix?: string) => { * const base = path.split("/").pop() || "" - * return suffix && base.endsWith(suffix) ? base.slice(0, -suffix.length) : base + * return suffix && base.endsWith(suffix) + * ? base.slice(0, -suffix.length) + * : base * }, * dirname: (path: string) => path.split("/").slice(0, -1).join("/") || "/", * extname: (path: string) => { @@ -184,7 +181,7 @@ export declare namespace Path { * // Provide the path service * const customPathLayer = Layer.succeed(Path.Path)(customPath) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const path = yield* Path.Path * const joined = path.join("home", "user", "file.txt") * console.log(joined) // "home/user/file.txt" diff --git a/packages/effect/src/platform/PlatformError.ts b/packages/effect/src/PlatformError.ts similarity index 97% rename from packages/effect/src/platform/PlatformError.ts rename to packages/effect/src/PlatformError.ts index b863fd479f..d8df669e71 100644 --- a/packages/effect/src/platform/PlatformError.ts +++ b/packages/effect/src/PlatformError.ts @@ -1,7 +1,7 @@ /** * @since 4.0.0 */ -import * as Data from "../Data.ts" +import * as Data from "./Data.ts" const TypeId = "~effect/platform/PlatformError" diff --git a/packages/effect/src/Pool.ts b/packages/effect/src/Pool.ts index bf3c8b4234..c1987743c1 100644 --- a/packages/effect/src/Pool.ts +++ b/packages/effect/src/Pool.ts @@ -142,16 +142,16 @@ export const make = (options: { * By default, the `timeToLiveStrategy` is set to "usage". * * ```ts skip-type-checking - * import { createConnection } from "mysql2"; * import { Duration, Effect, Pool } from "effect" + * import { createConnection } from "mysql2" * * const acquireDBConnection = Effect.acquireRelease( - * Effect.sync(() => createConnection('mysql://...')), - * (connection) => Effect.sync(() => connection.end(() => {})), + * Effect.sync(() => createConnection("mysql://...")), + * (connection) => Effect.sync(() => connection.end(() => {})) * ) * * const connectionPool = Effect.flatMap( - * Pool.makeWithTTL({ + * Pool.makeWithTTL({ * acquire: acquireDBConnection, * min: 10, * max: 20, diff --git a/packages/effect/src/Predicate.ts b/packages/effect/src/Predicate.ts index dd080a2b3a..827188030c 100644 --- a/packages/effect/src/Predicate.ts +++ b/packages/effect/src/Predicate.ts @@ -11,7 +11,7 @@ import type { TupleOf, TupleOfAtLeast } from "./types/Types.ts" * * @example * ```ts - * import { Predicate } from "effect" + * import type { Predicate } from "effect" * * const isPositive: Predicate.Predicate = (n) => n > 0 * const isEven: Predicate.Predicate = (n) => n % 2 === 0 @@ -35,7 +35,7 @@ export interface Predicate { * * @example * ```ts - * import { Predicate } from "effect" + * import type { Predicate } from "effect" * * // Type lambda allows Predicate to work with higher-kinded type operations * // This is used internally by the Effect ecosystem for generic abstractions @@ -60,13 +60,15 @@ export interface PredicateTypeLambda extends TypeLambda { * * @example * ```ts - * import { Predicate } from "effect" + * import type { Predicate } from "effect" * * // A refinement that narrows string to non-empty string - * const isNonEmpty: Predicate.Refinement = (s): s is string => s.length > 0 + * const isNonEmpty: Predicate.Refinement = (s): s is string => + * s.length > 0 * * // A refinement that narrows unknown to string - * const isString: Predicate.Refinement = (u): u is string => typeof u === "string" + * const isString: Predicate.Refinement = (u): u is string => + * typeof u === "string" * * const value: unknown = "hello" * if (isString(value)) { @@ -88,7 +90,7 @@ export interface Refinement { * * @example * ```ts - * import { Predicate } from "effect" + * import type { Predicate } from "effect" * * // Extract the input type from a predicate * type StringPredicate = Predicate.Predicate @@ -107,7 +109,7 @@ export declare namespace Predicate { * * @example * ```ts - * import { Predicate } from "effect" + * import type { Predicate } from "effect" * * type StringPredicate = Predicate.Predicate * type InputType = Predicate.Predicate.In // string @@ -126,14 +128,14 @@ export declare namespace Predicate { * * @example * ```ts - * import { Predicate } from "effect" + * import type { Predicate } from "effect" * * // A utility type for generic predicate operations * type AnyPredicate = Predicate.Predicate.Any * * // Function that negates any predicate - simplified version for demonstration - * const negatePredicate = (predicate: Predicate.Predicate) => - * (input: A) => !predicate(input) + * const negatePredicate = (predicate: Predicate.Predicate) => (input: A) => + * !predicate(input) * * const isPositive = (n: number) => n > 0 * const isNegative = negatePredicate(isPositive) @@ -152,7 +154,7 @@ export declare namespace Predicate { * * @example * ```ts - * import { Predicate } from "effect" + * import type { Predicate } from "effect" * * // Extract types from a refinement * type StringFromUnknown = Predicate.Refinement @@ -172,7 +174,7 @@ export declare namespace Refinement { * * @example * ```ts - * import { Predicate } from "effect" + * import type { Predicate } from "effect" * * type StringFromUnknown = Predicate.Refinement * type InputType = Predicate.Refinement.In // unknown @@ -190,7 +192,7 @@ export declare namespace Refinement { * * @example * ```ts - * import { Predicate } from "effect" + * import type { Predicate } from "effect" * * type StringFromUnknown = Predicate.Refinement * type OutputType = Predicate.Refinement.Out // string @@ -209,15 +211,16 @@ export declare namespace Refinement { * * @example * ```ts - * import { Predicate } from "effect" + * import type { Predicate } from "effect" * * // Function that composes any refinement with a predicate * const composeRefinement = ( * refinement: R - * ) => >( + * ) => + * >( * predicate: Predicate.Predicate * ): Predicate.Refinement, A> => - * (input): input is A => refinement(input) && predicate(input as A) + * (input): input is A => refinement(input) && predicate(input as A) * * const isString = (u: unknown): u is string => typeof u === "string" * const isLong = (s: string) => s.length > 5 @@ -235,9 +238,9 @@ export declare namespace Refinement { * * @example * ```ts - * import * as assert from "node:assert" * import { Predicate } from "effect" * import * as N from "effect/Number" + * import * as assert from "node:assert" * * const minLength3 = Predicate.mapInput(N.greaterThan(2), (s: string) => s.length) * @@ -262,16 +265,16 @@ export const mapInput: { * * @example * ```ts - * import * as assert from "node:assert" * import { isTupleOf } from "effect/Predicate" + * import * as assert from "node:assert" * - * assert.deepStrictEqual(isTupleOf([1, 2, 3], 3), true); - * assert.deepStrictEqual(isTupleOf([1, 2, 3], 2), false); - * assert.deepStrictEqual(isTupleOf([1, 2, 3], 4), false); + * assert.deepStrictEqual(isTupleOf([1, 2, 3], 3), true) + * assert.deepStrictEqual(isTupleOf([1, 2, 3], 2), false) + * assert.deepStrictEqual(isTupleOf([1, 2, 3], 4), false) * - * const arr: number[] = [1, 2, 3]; + * const arr: Array = [1, 2, 3] * if (isTupleOf(arr, 3)) { - * console.log(arr); + * console.log(arr) * // ^? [number, number, number] * } * ``` @@ -291,16 +294,16 @@ export const isTupleOf: { * * @example * ```ts - * import * as assert from "node:assert" * import { isTupleOfAtLeast } from "effect/Predicate" + * import * as assert from "node:assert" * - * assert.deepStrictEqual(isTupleOfAtLeast([1, 2, 3], 3), true); - * assert.deepStrictEqual(isTupleOfAtLeast([1, 2, 3], 2), true); - * assert.deepStrictEqual(isTupleOfAtLeast([1, 2, 3], 4), false); + * assert.deepStrictEqual(isTupleOfAtLeast([1, 2, 3], 3), true) + * assert.deepStrictEqual(isTupleOfAtLeast([1, 2, 3], 2), true) + * assert.deepStrictEqual(isTupleOfAtLeast([1, 2, 3], 4), false) * - * const arr: number[] = [1, 2, 3, 4]; + * const arr: Array = [1, 2, 3, 4] * if (isTupleOfAtLeast(arr, 3)) { - * console.log(arr); + * console.log(arr) * // ^? [number, number, number, ...number[]] * } * ``` @@ -318,8 +321,8 @@ export const isTupleOfAtLeast: { * * @example * ```ts - * import * as assert from "node:assert" * import { isTruthy } from "effect/Predicate" + * import * as assert from "node:assert" * * assert.deepStrictEqual(isTruthy(1), true) * assert.deepStrictEqual(isTruthy(0), false) @@ -336,8 +339,8 @@ export const isTruthy = (input: unknown) => !!input * * @example * ```ts - * import * as assert from "node:assert" * import { isSet } from "effect/Predicate" + * import * as assert from "node:assert" * * assert.deepStrictEqual(isSet(new Set([1, 2])), true) * assert.deepStrictEqual(isSet(new Set()), true) @@ -356,8 +359,8 @@ export const isSet = (input: unknown): input is Set => input instanceof * * @example * ```ts - * import * as assert from "node:assert" * import { isMap } from "effect/Predicate" + * import * as assert from "node:assert" * * assert.deepStrictEqual(isMap(new Map()), true) * assert.deepStrictEqual(isMap({}), false) @@ -375,8 +378,8 @@ export const isMap = (input: unknown): input is Map => input i * * @example * ```ts - * import * as assert from "node:assert" * import { isString } from "effect/Predicate" + * import * as assert from "node:assert" * * assert.deepStrictEqual(isString("a"), true) * @@ -393,8 +396,8 @@ export const isString = (input: unknown): input is string => typeof input === "s * * @example * ```ts - * import * as assert from "node:assert" * import { isNumber } from "effect/Predicate" + * import * as assert from "node:assert" * * assert.deepStrictEqual(isNumber(2), true) * @@ -411,8 +414,8 @@ export const isNumber = (input: unknown): input is number => typeof input === "n * * @example * ```ts - * import * as assert from "node:assert" * import { isBoolean } from "effect/Predicate" + * import * as assert from "node:assert" * * assert.deepStrictEqual(isBoolean(true), true) * @@ -429,8 +432,8 @@ export const isBoolean = (input: unknown): input is boolean => typeof input === * * @example * ```ts - * import * as assert from "node:assert" * import { isBigInt } from "effect/Predicate" + * import * as assert from "node:assert" * * assert.deepStrictEqual(isBigInt(1n), true) * @@ -447,8 +450,8 @@ export const isBigInt = (input: unknown): input is bigint => typeof input === "b * * @example * ```ts - * import * as assert from "node:assert" * import { isSymbol } from "effect/Predicate" + * import * as assert from "node:assert" * * assert.deepStrictEqual(isSymbol(Symbol.for("a")), true) * @@ -471,8 +474,8 @@ export const isPropertyKey = (u: unknown): u is PropertyKey => isString(u) || is * * @example * ```ts - * import * as assert from "node:assert" * import { isFunction } from "effect/Predicate" + * import * as assert from "node:assert" * * assert.deepStrictEqual(isFunction(isFunction), true) * @@ -489,8 +492,8 @@ export const isFunction: (input: unknown) => input is Function = isFunction_ * * @example * ```ts - * import * as assert from "node:assert" * import { isUndefined } from "effect/Predicate" + * import * as assert from "node:assert" * * assert.deepStrictEqual(isUndefined(undefined), true) * @@ -508,8 +511,8 @@ export const isUndefined = (input: unknown): input is undefined => input === und * * @example * ```ts - * import * as assert from "node:assert" * import { isNotUndefined } from "effect/Predicate" + * import * as assert from "node:assert" * * assert.deepStrictEqual(isNotUndefined(null), true) * assert.deepStrictEqual(isNotUndefined("undefined"), true) @@ -527,8 +530,8 @@ export const isNotUndefined = (input: A): input is Exclude => i * * @example * ```ts - * import * as assert from "node:assert" * import { isNull } from "effect/Predicate" + * import * as assert from "node:assert" * * assert.deepStrictEqual(isNull(null), true) * @@ -546,8 +549,8 @@ export const isNull = (input: unknown): input is null => input === null * * @example * ```ts - * import * as assert from "node:assert" * import { isNotNull } from "effect/Predicate" + * import * as assert from "node:assert" * * assert.deepStrictEqual(isNotNull(undefined), true) * assert.deepStrictEqual(isNotNull("null"), true) @@ -565,8 +568,8 @@ export const isNotNull = (input: A): input is Exclude => input !== n * * @example * ```ts - * import * as assert from "node:assert" * import { isNullish } from "effect/Predicate" + * import * as assert from "node:assert" * * assert.deepStrictEqual(isNullish(null), true) * assert.deepStrictEqual(isNullish(undefined), true) @@ -586,8 +589,8 @@ export const isNullish = (input: unknown): input is null | undefined => input == * * @example * ```ts - * import * as assert from "node:assert" * import { isNotNullish } from "effect/Predicate" + * import * as assert from "node:assert" * * assert.deepStrictEqual(isNotNullish(0), true) * assert.deepStrictEqual(isNotNullish(""), true) @@ -607,8 +610,8 @@ export const isNotNullish = (input: A): input is NonNullable => input != n * * @example * ```ts - * import * as assert from "node:assert" * import { isNever } from "effect/Predicate" + * import * as assert from "node:assert" * * assert.deepStrictEqual(isNever(null), false) * assert.deepStrictEqual(isNever(undefined), false) @@ -626,8 +629,8 @@ export const isNever: (input: unknown) => input is never = (_: unknown): _ is ne * * @example * ```ts - * import * as assert from "node:assert" * import { isUnknown } from "effect/Predicate" + * import * as assert from "node:assert" * * assert.deepStrictEqual(isUnknown(null), true) * assert.deepStrictEqual(isUnknown(undefined), true) @@ -657,8 +660,8 @@ export const isObjectOrArray = (input: unknown): input is { [x: PropertyKey]: un * * @example * ```ts - * import * as assert from "node:assert" * import { isObject } from "effect/Predicate" + * import * as assert from "node:assert" * * assert.deepStrictEqual(isObject({}), true) * assert.deepStrictEqual(isObject({ a: 1 }), true) @@ -681,8 +684,8 @@ export const isObject = (input: unknown): input is { [x: PropertyKey]: unknown } * * @example * ```ts - * import * as assert from "node:assert" * import { isReadonlyObject } from "effect/Predicate" + * import * as assert from "node:assert" * * assert.deepStrictEqual(isReadonlyObject({ a: 1 }), true) * @@ -701,8 +704,8 @@ export const isReadonlyObject: (input: unknown) => input is { readonly [x: Prope * * @example * ```ts - * import * as assert from "node:assert" * import { isObjectKeyword } from "effect/Predicate" + * import * as assert from "node:assert" * * assert.deepStrictEqual(isObjectKeyword({}), true) * assert.deepStrictEqual(isObjectKeyword([]), true) @@ -724,8 +727,8 @@ export const isObjectKeyword = (input: unknown): input is object => * * @example * ```ts - * import * as assert from "node:assert" * import { Predicate } from "effect" + * import * as assert from "node:assert" * * const hasName = Predicate.hasProperty("name") * const hasAge = Predicate.hasProperty("age") @@ -735,8 +738,14 @@ export const isObjectKeyword = (input: unknown): input is object => * assert.deepStrictEqual(hasName(null), false) * * // Curried usage - * assert.deepStrictEqual(Predicate.hasProperty({ name: "Bob", age: 25 }, "name"), true) - * assert.deepStrictEqual(Predicate.hasProperty({ name: "Bob", age: 25 }, "email"), false) + * assert.deepStrictEqual( + * Predicate.hasProperty({ name: "Bob", age: 25 }, "name"), + * true + * ) + * assert.deepStrictEqual( + * Predicate.hasProperty({ name: "Bob", age: 25 }, "email"), + * false + * ) * * // Type guard usage * const data: unknown = { name: "Charlie", age: 35 } @@ -763,8 +772,8 @@ export const hasProperty: { * * @example * ```ts - * import * as assert from "node:assert" * import { isTagged } from "effect/Predicate" + * import * as assert from "node:assert" * * assert.deepStrictEqual(isTagged(1, "a"), false) * assert.deepStrictEqual(isTagged(null, "a"), false) @@ -790,8 +799,8 @@ export const isTagged: { * * @example * ```ts - * import * as assert from "node:assert" * import { isError } from "effect/Predicate" + * import * as assert from "node:assert" * * assert.deepStrictEqual(isError(new Error()), true) * @@ -809,8 +818,8 @@ export const isError = (input: unknown): input is Error => input instanceof Erro * * @example * ```ts - * import * as assert from "node:assert" * import { isUint8Array } from "effect/Predicate" + * import * as assert from "node:assert" * * assert.deepStrictEqual(isUint8Array(new Uint8Array()), true) * @@ -828,8 +837,8 @@ export const isUint8Array = (input: unknown): input is Uint8Array => input insta * * @example * ```ts - * import * as assert from "node:assert" * import { isDate } from "effect/Predicate" + * import * as assert from "node:assert" * * assert.deepStrictEqual(isDate(new Date()), true) * @@ -847,8 +856,8 @@ export const isDate = (input: unknown): input is Date => input instanceof Date * * @example * ```ts - * import * as assert from "node:assert" * import { isIterable } from "effect/Predicate" + * import * as assert from "node:assert" * * assert.deepStrictEqual(isIterable([]), true) * assert.deepStrictEqual(isIterable(new Set()), true) @@ -869,8 +878,8 @@ export function isIterable(input: unknown): input is Iterable { * * @example * ```ts - * import * as assert from "node:assert" * import { isPromise } from "effect/Predicate" + * import * as assert from "node:assert" * * assert.deepStrictEqual(isPromise({}), false) * assert.deepStrictEqual(isPromise(Promise.resolve("hello")), true) @@ -889,8 +898,8 @@ export const isPromise = ( * * @example * ```ts - * import * as assert from "node:assert" * import { isPromiseLike } from "effect/Predicate" + * import * as assert from "node:assert" * * assert.deepStrictEqual(isPromiseLike(Promise.resolve("hello")), true) * assert.deepStrictEqual(isPromiseLike({ then: () => {} }), true) @@ -911,8 +920,8 @@ export const isPromiseLike = ( * * @example * ```ts - * import * as assert from "node:assert" * import { Predicate } from "effect" + * import * as assert from "node:assert" * * assert.deepStrictEqual(Predicate.isRegExp(/a/), true) * assert.deepStrictEqual(Predicate.isRegExp("a"), false) @@ -929,8 +938,8 @@ export const isRegExp = (input: unknown): input is RegExp => input instanceof Re * * @example * ```ts - * import * as assert from "node:assert" * import { Predicate } from "effect" + * import * as assert from "node:assert" * * const isPositive = (n: number): n is number => n > 0 * const isInteger = (n: number): n is number => Number.isInteger(n) @@ -960,8 +969,8 @@ export const compose: { * * @example * ```ts - * import * as assert from "node:assert" * import { Predicate } from "effect" + * import * as assert from "node:assert" * * const isPositive = (n: number) => n > 0 * const isLongString = (s: string) => s.length > 3 @@ -984,8 +993,8 @@ export const product = * * @example * ```ts - * import * as assert from "node:assert" * import { Predicate } from "effect" + * import * as assert from "node:assert" * * const isPositive = (n: number) => n > 0 * const isEven = (n: number) => n % 2 === 0 @@ -1023,8 +1032,8 @@ export const all = ( * * @example * ```ts - * import * as assert from "node:assert" * import { Predicate } from "effect" + * import * as assert from "node:assert" * * const isPositive = (n: number) => n > 0 * const isEven = (n: number) => n % 2 === 0 @@ -1052,8 +1061,8 @@ export const productMany = ( * * @example * ```ts - * import * as assert from "node:assert" * import { Predicate } from "effect" + * import * as assert from "node:assert" * * const isPositive = (n: number) => n > 0 * const isString = (s: unknown): s is string => typeof s === "string" @@ -1082,8 +1091,8 @@ export const tuple: { * * @example * ```ts - * import * as assert from "node:assert" * import { Predicate } from "effect" + * import * as assert from "node:assert" * * const isPositive = (n: number) => n > 0 * const isString = (s: unknown): s is string => typeof s === "string" @@ -1123,9 +1132,9 @@ export const struct: { * * @example * ```ts - * import * as assert from "node:assert" * import { Predicate } from "effect" * import * as N from "effect/Number" + * import * as assert from "node:assert" * * const isPositive = Predicate.not(N.lessThan(0)) * @@ -1144,9 +1153,9 @@ export const not = (self: Predicate): Predicate => (a) => !self(a) * * @example * ```ts - * import * as assert from "node:assert" * import { Predicate } from "effect" * import * as N from "effect/Number" + * import * as assert from "node:assert" * * const nonZero = Predicate.or(N.lessThan(0), N.greaterThan(0)) * @@ -1170,8 +1179,8 @@ export const or: { * * @example * ```ts - * import * as assert from "node:assert" * import { Predicate } from "effect" + * import * as assert from "node:assert" * * const minLength = (n: number) => (s: string) => s.length >= n * const maxLength = (n: number) => (s: string) => s.length <= n @@ -1198,8 +1207,8 @@ export const and: { * * @example * ```ts - * import * as assert from "node:assert" * import { Predicate } from "effect" + * import * as assert from "node:assert" * * const isEven = (n: number) => n % 2 === 0 * const isPositive = (n: number) => n > 0 @@ -1224,8 +1233,8 @@ export const xor: { * * @example * ```ts - * import * as assert from "node:assert" * import { Predicate } from "effect" + * import * as assert from "node:assert" * * const isEven = (n: number) => n % 2 === 0 * const isDivisibleBy2 = (n: number) => n % 2 === 0 @@ -1266,8 +1275,8 @@ export const eqv: { * * @example * ```ts - * import * as assert from "node:assert" * import { Predicate } from "effect" + * import * as assert from "node:assert" * * type Triple = { * readonly a: number @@ -1303,8 +1312,8 @@ export const implies: { * * @example * ```ts - * import * as assert from "node:assert" * import { Predicate } from "effect" + * import * as assert from "node:assert" * * const isEven = (n: number) => n % 2 === 0 * const isPositive = (n: number) => n > 0 @@ -1332,8 +1341,8 @@ export const nor: { * * @example * ```ts - * import * as assert from "node:assert" * import { Predicate } from "effect" + * import * as assert from "node:assert" * * const isEven = (n: number) => n % 2 === 0 * const isPositive = (n: number) => n > 0 @@ -1361,8 +1370,8 @@ export const nand: { * * @example * ```ts - * import * as assert from "node:assert" * import { Predicate } from "effect" + * import * as assert from "node:assert" * * const isPositive = (n: number) => n > 0 * const isEven = (n: number) => n % 2 === 0 @@ -1391,8 +1400,8 @@ export const every = (collection: Iterable>): Predicate => (a * * @example * ```ts - * import * as assert from "node:assert" * import { Predicate } from "effect" + * import * as assert from "node:assert" * * const isPositive = (n: number) => n > 0 * const isEven = (n: number) => n % 2 === 0 diff --git a/packages/effect/src/PubSub.ts b/packages/effect/src/PubSub.ts index c51a554e92..84967c81f4 100644 --- a/packages/effect/src/PubSub.ts +++ b/packages/effect/src/PubSub.ts @@ -7,9 +7,7 @@ * * @example * ```ts - * import { Effect } from "effect" - * import { Scope } from "effect" - * import { PubSub } from "effect" + * import { Effect, PubSub } from "effect" * * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(10) @@ -53,7 +51,7 @@ const TypeId = "~effect/PubSub" * @example * ```ts * import { Effect } from "effect" -import * as PubSub from "effect/PubSub" + * import * as PubSub from "effect/PubSub" * * const program = Effect.gen(function*() { * // Create a bounded PubSub with capacity 10 @@ -212,14 +210,16 @@ const SubscriptionTypeId = "~effect/PubSub/Subscription" * @example * ```ts * import { Effect } from "effect" -import * as PubSub from "effect/PubSub" + * import * as PubSub from "effect/PubSub" * * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(10) * * // Subscribe within a scope for automatic cleanup * yield* Effect.scoped(Effect.gen(function*() { - * const subscription: PubSub.Subscription = yield* PubSub.subscribe(pubsub) + * const subscription: PubSub.Subscription = yield* PubSub.subscribe( + * pubsub + * ) * * // Take individual messages * const message = yield* PubSub.take(subscription) @@ -254,7 +254,7 @@ export interface Subscription extends Pipeable { * @example * ```ts * import { Effect } from "effect" -import * as PubSub from "effect/PubSub" + * import * as PubSub from "effect/PubSub" * * const program = Effect.gen(function*() { * // Create custom PubSub with specific atomic implementation and strategy @@ -302,7 +302,7 @@ export const make = ( * @example * ```ts * import { Effect } from "effect" -import * as PubSub from "effect/PubSub" + * import * as PubSub from "effect/PubSub" * * const program = Effect.gen(function*() { * // Create bounded PubSub with capacity 100 @@ -339,7 +339,7 @@ export const bounded = ( * @example * ```ts * import { Effect } from "effect" -import * as PubSub from "effect/PubSub" + * import * as PubSub from "effect/PubSub" * * const program = Effect.gen(function*() { * // Create dropping PubSub that drops new messages when full @@ -383,7 +383,7 @@ export const dropping = ( * @example * ```ts * import { Effect } from "effect" -import * as PubSub from "effect/PubSub" + * import * as PubSub from "effect/PubSub" * * const program = Effect.gen(function*() { * // Create sliding PubSub that evicts old messages when full @@ -429,7 +429,7 @@ export const sliding = ( * @example * ```ts * import { Effect } from "effect" -import * as PubSub from "effect/PubSub" + * import * as PubSub from "effect/PubSub" * * const program = Effect.gen(function*() { * // Create unbounded PubSub @@ -504,7 +504,7 @@ export const makeAtomicUnbounded = (options?: { * @example * ```ts * import { Effect } from "effect" -import * as PubSub from "effect/PubSub" + * import * as PubSub from "effect/PubSub" * * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(100) @@ -560,7 +560,6 @@ export const size = (self: PubSub): Effect.Effect => Effect.sync(( * @example * ```ts * import { PubSub } from "effect" - * import { Option } from "effect" * * // Unsafe synchronous size check * declare const pubsub: PubSub.PubSub @@ -586,7 +585,7 @@ export const sizeUnsafe = (self: PubSub): number => { * @example * ```ts * import { Effect } from "effect" -import * as PubSub from "effect/PubSub" + * import * as PubSub from "effect/PubSub" * * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(2) @@ -616,7 +615,7 @@ export const isFull = (self: PubSub): Effect.Effect => * @example * ```ts * import { Effect } from "effect" -import * as PubSub from "effect/PubSub" + * import * as PubSub from "effect/PubSub" * * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(10) @@ -644,9 +643,7 @@ export const isEmpty = (self: PubSub): Effect.Effect => Effect.ma * * @example * ```ts - * import { Effect } from "effect" - * import { Fiber } from "effect" - * import { PubSub } from "effect" + * import { Effect, Fiber, PubSub } from "effect" * * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(1) @@ -687,7 +684,7 @@ export const shutdown = (self: PubSub): Effect.Effect => * @example * ```ts * import { Effect } from "effect" -import * as PubSub from "effect/PubSub" + * import * as PubSub from "effect/PubSub" * * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(10) @@ -739,9 +736,7 @@ export const isShutdownUnsafe = (self: PubSub): boolean => self.shutdownFl * * @example * ```ts - * import { Effect } from "effect" - * import { Fiber } from "effect" - * import { PubSub } from "effect" + * import { Effect, Fiber, PubSub } from "effect" * * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(10) @@ -777,7 +772,7 @@ export const awaitShutdown = (self: PubSub): Effect.Effect => self.s * @example * ```ts * import { Effect } from "effect" -import * as PubSub from "effect/PubSub" + * import * as PubSub from "effect/PubSub" * * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(10) @@ -848,9 +843,8 @@ export const publish: { * * // Useful for scenarios where you don't want to suspend * const messages = ["msg1", "msg2", "msg3"] - * const publishedCount = messages.filter(msg => - * PubSub.publishUnsafe(pubsub, msg) - * ).length + * const publishedCount = + * messages.filter((msg) => PubSub.publishUnsafe(pubsub, msg)).length * console.log(`Published ${publishedCount} out of ${messages.length} messages`) * ``` * @@ -876,7 +870,7 @@ export const publishUnsafe: { * @example * ```ts * import { Effect } from "effect" -import * as PubSub from "effect/PubSub" + * import * as PubSub from "effect/PubSub" * * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(10) @@ -934,9 +928,7 @@ export const publishAll: { * * @example * ```ts - * import { Effect } from "effect" - * import { Scope } from "effect" - * import { PubSub } from "effect" + * import { Effect, PubSub } from "effect" * * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(10) @@ -1008,9 +1000,7 @@ const unsubscribe = (self: Subscription): Effect.Effect => * * @example * ```ts - * import { Effect } from "effect" - * import { Fiber } from "effect" - * import { PubSub } from "effect" + * import { Effect, Fiber, PubSub } from "effect" * * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(10) @@ -1062,8 +1052,7 @@ export const take = (self: Subscription): Effect.Effect => * * @example * ```ts - * import { Effect } from "effect" - * import { PubSub } from "effect" + * import { Effect, PubSub } from "effect" * * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(10) @@ -1189,9 +1178,7 @@ export const takeUpTo: { * * @example * ```ts - * import { Effect } from "effect" - * import { Fiber } from "effect" - * import { PubSub } from "effect" + * import { Effect, Fiber, PubSub } from "effect" * * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(10) @@ -1266,7 +1253,7 @@ const takeRemainderLoop = ( * @example * ```ts * import { Effect } from "effect" -import * as PubSub from "effect/PubSub" + * import * as PubSub from "effect/PubSub" * * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(10) @@ -1306,7 +1293,6 @@ export const remaining = (self: Subscription): Effect.Effect => * @example * ```ts * import { PubSub } from "effect" - * import * as Option from "effect/Option" * * declare const subscription: PubSub.Subscription * @@ -2318,7 +2304,7 @@ export class BackPressureStrategy implements PubSub.Strategy { * @example * ```ts * import { Effect } from "effect" -import * as PubSub from "effect/PubSub" + * import * as PubSub from "effect/PubSub" * * const program = Effect.gen(function*() { * // Create PubSub with dropping strategy @@ -2394,7 +2380,7 @@ export class DroppingStrategy implements PubSub.Strategy { * @example * ```ts * import { Effect } from "effect" -import * as PubSub from "effect/PubSub" + * import * as PubSub from "effect/PubSub" * * const program = Effect.gen(function*() { * // Create PubSub with sliding strategy diff --git a/packages/effect/src/Pull.ts b/packages/effect/src/Pull.ts index e0f775528a..da0f6bc84c 100644 --- a/packages/effect/src/Pull.ts +++ b/packages/effect/src/Pull.ts @@ -16,8 +16,7 @@ import { hasProperty } from "./Predicate.ts" * * @example * ```ts - * import { Pull } from "effect" - * import { Effect } from "effect" + * import { Effect, Pull } from "effect" * * // A Pull that emits a single value * const pullValue: Pull.Pull = Effect.succeed(42) @@ -39,8 +38,7 @@ export interface Pull exte * * @example * ```ts - * import { Pull } from "effect" - * import { Effect } from "effect" + * import type { Pull } from "effect" * * type MyPull = Pull.Pull * type SuccessType = Pull.Success // number @@ -56,8 +54,7 @@ export type Success

= P extends Effect ? _A : n * * @example * ```ts - * import { Pull } from "effect" - * import { Effect } from "effect" + * import type { Pull } from "effect" * * type MyPull = Pull.Pull * type ErrorType = Pull.Error // string @@ -74,8 +71,7 @@ export type Error

= P extends Effect ? _E exten * * @example * ```ts - * import { Pull } from "effect" - * import { Effect } from "effect" + * import type { Pull } from "effect" * * type MyPull = Pull.Pull * type LeftoverType = Pull.Leftover // number @@ -92,8 +88,7 @@ export type Leftover

= P extends Effect ? _E ex * * @example * ```ts - * import { Pull } from "effect" - * import { Effect } from "effect" + * import type { Pull } from "effect" * import { ServiceMap } from "effect" * * interface MyService { @@ -115,7 +110,7 @@ export type ServiceMap

= P extends Effect ? _R * * @example * ```ts - * import { Pull } from "effect" + * import type { Pull } from "effect" * * type ErrorUnion = string | Pull.Halt | Error * type WithoutHalt = Pull.ExcludeHalt // string | Error @@ -161,7 +156,7 @@ export class Halt { * * @example * ```ts - * import { Pull } from "effect" + * import type { Pull } from "effect" * * // Extract leftover type from halt * type MyHalt = Pull.Halt @@ -181,7 +176,7 @@ export declare namespace Halt { * * @example * ```ts - * import { Pull } from "effect" + * import type { Pull } from "effect" * * type MyHalt = Pull.Halt * type Leftover = Pull.Halt.Extract // string @@ -197,7 +192,7 @@ export declare namespace Halt { * * @example * ```ts - * import { Pull } from "effect" + * import type { Pull } from "effect" * * type ErrorUnion = string | Pull.Halt * type OnlyHalt = Pull.Halt.Only // Pull.Halt @@ -214,12 +209,12 @@ export declare namespace Halt { * * @example * ```ts - * import { Pull } from "effect" - * import { Effect } from "effect" + * import { Effect, Pull } from "effect" * * const pullWithHalt = Pull.halt("stream ended") - * const recovered = Pull.catchHalt(pullWithHalt, (leftover) => - * Effect.succeed(`Recovered from: ${leftover}`) + * const recovered = Pull.catchHalt( + * pullWithHalt, + * (leftover) => Effect.succeed(`Recovered from: ${leftover}`) * ) * ``` * @@ -264,8 +259,7 @@ export const isHalt = (u: unknown): u is Halt => hasProperty(u, HaltTyp * * @example * ```ts - * import { Pull } from "effect" - * import { Cause } from "effect" + * import { Cause, Pull } from "effect" * * const halt = new Pull.Halt("completed") * const causeWithHalt = Cause.fail(halt) @@ -285,8 +279,7 @@ export const isHaltCause = (cause: Cause.Cause): boolean => cause.failures * * @example * ```ts - * import { Pull } from "effect" - * import { Cause } from "effect" + * import { Cause, Pull } from "effect" * * const halt = new Pull.Halt("completed") * const haltCause = Cause.fail(halt) @@ -332,8 +325,7 @@ export const filterNoHalt: ( * * @example * ```ts - * import { Pull } from "effect" - * import { Cause } from "effect" + * import { Cause, Pull } from "effect" * * const halt = new Pull.Halt("stream completed") * const causeWithHalt = Cause.fail(halt) @@ -358,7 +350,6 @@ export const filterHaltLeftover: ( * @example * ```ts * import { Pull } from "effect" - * import { Effect } from "effect" * * // Create a halt with a string leftover * const haltWithMessage = Pull.halt("operation completed") @@ -378,7 +369,6 @@ export const halt = (leftover: L): Effect> => internalEffect.f * @example * ```ts * import { Pull } from "effect" - * import { Effect } from "effect" * * // Use the pre-defined halt with void * const completePull = Pull.haltVoid @@ -397,8 +387,7 @@ export const haltVoid: Effect> = internalEffect.fail(new Halt( * * @example * ```ts - * import { Cause, Exit } from "effect" - * import { Pull } from "effect" + * import { Cause, Pull } from "effect" * * const halt = new Pull.Halt("completed") * const causeWithHalt = Cause.fail(halt) @@ -420,8 +409,7 @@ export const haltExitFromCause = (cause: Cause.Cause): Exit.Exit(10) * const notQueue = { value: 42 } * - * console.log(Queue.isQueue(queue)) // true + * console.log(Queue.isQueue(queue)) // true * console.log(Queue.isQueue(notQueue)) // false * }) * ``` @@ -84,8 +82,7 @@ export const isQueue = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Queue } from "effect" + * import { Effect, Queue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* Queue.bounded(10) @@ -139,8 +136,7 @@ export declare namespace Dequeue { * * @example * ```ts - * import { Effect } from "effect" - * import { Queue } from "effect" + * import { Effect, Queue } from "effect" * * const program = Effect.gen(function*() { * // Create a bounded queue @@ -254,8 +250,7 @@ const QueueProto = { * @example * ```ts * import * as assert from "node:assert" - * import { Effect } from "effect" - * import { Queue } from "effect" + * import { Effect, Queue } from "effect" * * Effect.gen(function*() { * const queue = yield* Queue.make() @@ -312,8 +307,7 @@ export const make = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Queue } from "effect" + * import { Effect, Queue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* Queue.bounded(5) @@ -344,8 +338,7 @@ export const bounded = (capacity: number): Effect> => * * @example * ```ts - * import { Effect } from "effect" - * import { Queue } from "effect" + * import { Effect, Queue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* Queue.sliding(3) @@ -380,8 +373,7 @@ export const sliding = (capacity: number): Effect> => * * @example * ```ts - * import { Effect } from "effect" - * import { Queue } from "effect" + * import { Effect, Queue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* Queue.dropping(2) @@ -415,8 +407,7 @@ export const dropping = (capacity: number): Effect> => * * @example * ```ts - * import { Effect } from "effect" - * import { Queue } from "effect" + * import { Effect, Queue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* Queue.unbounded() @@ -450,8 +441,7 @@ export const unbounded = (): Effect> => make() * * @example * ```ts - * import { Effect } from "effect" - * import { Queue } from "effect" + * import { Effect, Queue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* Queue.bounded(3) @@ -504,8 +494,7 @@ export const offer = (self: Queue, message: Types.NoInfer): Effec * * @example * ```ts - * import { Effect } from "effect" - * import { Queue } from "effect" + * import { Effect, Queue } from "effect" * * // Create a queue effect and extract the queue for unsafe operations * const program = Effect.gen(function*() { @@ -555,8 +544,7 @@ export const offerUnsafe = (self: Queue, message: Types.NoInfer): * * @example * ```ts - * import { Effect } from "effect" - * import { Queue } from "effect" + * import { Effect, Queue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* Queue.bounded(3) @@ -600,8 +588,7 @@ export const offerAll = (self: Queue, messages: Iterable): Effect * * @example * ```ts - * import { Effect } from "effect" - * import { Queue } from "effect" + * import { Effect, Queue } from "effect" * * // Create a bounded queue and use unsafe API * const program = Effect.gen(function*() { @@ -660,8 +647,7 @@ export const offerAllUnsafe = (self: Queue, messages: Iterable): * * @example * ```ts - * import { Effect } from "effect" - * import { Queue } from "effect" + * import { Effect, Queue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* Queue.bounded(10) @@ -690,8 +676,7 @@ export const fail = (self: Queue, error: E) => done(self, core.exitF * * @example * ```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) @@ -719,8 +704,7 @@ export const failCause = (self: Queue, cause: Cause) => done(self * * @example * ```ts - * import { Effect } from "effect" - * import { Queue } from "effect" + * import { Effect, Queue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* Queue.bounded(10) @@ -756,8 +740,7 @@ export const end = (self: Queue): Effect => done(sel * * @example * ```ts - * import { Effect } from "effect" - * import { Queue } from "effect" + * import { Effect, Queue } from "effect" * * // Create a queue and use unsafe operations * const program = Effect.gen(function*() { @@ -787,8 +770,7 @@ export const endUnsafe = (self: Queue) => doneUnsafe(self, in * * @example * ```ts - * import { Effect, Exit } from "effect" - * import { Queue } from "effect" + * import { Effect, Exit, Queue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* Queue.bounded(10) @@ -824,8 +806,7 @@ export const done = (self: Queue, exit: Exit(self: Queue, exit: Exit(2) @@ -921,8 +901,7 @@ export const shutdown = (self: Queue): Effect => * * @example * ```ts - * import { Effect } from "effect" - * import { Queue } from "effect" + * import { Effect, Queue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* Queue.bounded(10) @@ -992,8 +971,7 @@ export const filterDone: (u: A) => Done | Filter.fail> = Fil * * @example * ```ts - * import { Effect } from "effect" - * import { Queue } from "effect" + * import { Effect, Queue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* Queue.bounded(5) @@ -1058,8 +1036,7 @@ export const collect = (self: Dequeue): Effect, Excl * * @example * ```ts - * import { Effect } from "effect" - * import { Queue } from "effect" + * import { Effect, Queue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* Queue.bounded(10) @@ -1098,8 +1075,7 @@ export const takeN = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Queue } from "effect" + * import { Effect, Queue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* Queue.bounded(10) @@ -1141,8 +1117,7 @@ export const takeBetween = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Queue } from "effect" + * import { Effect, Queue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* Queue.bounded(3) @@ -1188,8 +1163,7 @@ export const take = (self: Dequeue): Effect => * * @example * ```ts - * import { Effect, Exit } from "effect" - * import { Queue } from "effect" + * import { Effect, Queue } from "effect" * * // Create a queue and use unsafe operations * const program = Effect.gen(function*() { @@ -1267,9 +1241,7 @@ export { * * @example * ```ts - * import { Effect } from "effect" - * import { Queue } from "effect" - * import * as Option from "effect/Option" + * import { Effect, Queue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* Queue.bounded(10) @@ -1313,9 +1285,7 @@ export const isFull = (self: Dequeue): Effect => internalEf * * @example * ```ts - * import { Effect } from "effect" - * import { Queue } from "effect" - * import * as Option from "effect/Option" + * import { Effect, Queue } from "effect" * * // Create a queue and use unsafe operations * const program = Effect.gen(function*() { @@ -1359,8 +1329,7 @@ export const isFullUnsafe = (self: Dequeue): boolean => sizeUnsafe(s * * @example * ```ts - * import { Effect } from "effect" - * import { Queue } from "effect" + * import { Effect, Queue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* Queue.bounded(10) @@ -1394,8 +1363,7 @@ export const asDequeue: (self: Queue) => Dequeue = identity * * @example * ```ts - * import { Effect } from "effect" - * import { Queue } from "effect" + * import { Effect, Queue } from "effect" * * const program = Effect.gen(function*() { * const queue = yield* Queue.bounded(10) @@ -1451,10 +1419,9 @@ export const into: { * * @example * ```ts - * import { Effect } from "effect" - * import { Queue } from "effect" + * import { Effect, Queue } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const queue = yield* Queue.bounded(10) * const pull = Queue.toPull(queue) * @@ -1473,10 +1440,9 @@ export const toPull: (self: Dequeue) => Pull.Pull(10) * const pull = Queue.toPullArray(queue) * diff --git a/packages/effect/src/Random.ts b/packages/effect/src/Random.ts index 3f86fc76c3..224161474a 100644 --- a/packages/effect/src/Random.ts +++ b/packages/effect/src/Random.ts @@ -7,7 +7,7 @@ * ```ts * import { Effect, Random } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const randomFloat = yield* Random.next * console.log("Random float:", randomFloat) * @@ -33,7 +33,7 @@ import * as ServiceMap from "./ServiceMap.ts" * ```ts * import { Effect, Random } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const float = yield* Random.next * const integer = yield* Random.nextInt * const inRange = yield* Random.nextIntBetween(1, 100) @@ -74,7 +74,7 @@ const randomWith = (f: (random: typeof Random["Service"]) => A): Effect.Effec * ```ts * import { Effect, Random } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const randomDouble = yield* Random.next * console.log("Random double:", randomDouble) * }) @@ -93,7 +93,7 @@ export const next: Effect.Effect = randomWith((r) => r.nextDoubleUnsafe( * ```ts * import { Effect, Random } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const randomInt = yield* Random.nextInt * console.log("Random integer:", randomInt) * }) @@ -111,7 +111,7 @@ export const nextInt: Effect.Effect = randomWith((r) => r.nextIntUnsafe( * ```ts * import { Effect, Random } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const randomDouble = yield* Random.nextBetween(0, 1) * console.log("Random double: ", randomDouble) * }) @@ -133,7 +133,7 @@ export const nextBetween = (min: number, max: number): Effect.Effect => * ```ts * import { Effect, Random } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const diceRoll1 = yield* Random.nextIntBetween(1, 6) * const diceRoll2 = yield* Random.nextIntBetween(1, 6, { * halfOpen: true @@ -163,7 +163,7 @@ export const nextIntBetween = (min: number, max: number, options?: { * ```ts * import { Effect, Random } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const uuid = yield* Random.nextUUIDv4 * console.log("UUID:", uuid) * }) @@ -208,7 +208,7 @@ export const nextUUIDv4: Effect.Effect = randomWith((r) => { * ```ts * import { Effect, Random } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const value1 = yield* Random.next * const value2 = yield* Random.next * console.log(value1, value2) diff --git a/packages/effect/src/RcMap.ts b/packages/effect/src/RcMap.ts index 5340f55448..cf8a681b2a 100644 --- a/packages/effect/src/RcMap.ts +++ b/packages/effect/src/RcMap.ts @@ -26,8 +26,7 @@ const TypeId = "~effect/RcMap" * @category models * @example * ```ts - * import { Effect } from "effect" - * import { RcMap } from "effect" + * import { Effect, RcMap } from "effect" * * Effect.gen(function*() { * // Create an RcMap that manages database connections @@ -69,7 +68,7 @@ export interface RcMap extends Pipeable { * @category Models * @example * ```ts - * import { RcMap } from "effect" + * import type { RcMap } from "effect" * * // State is a union type that can be either: * declare const openState: RcMap.State.Open @@ -95,7 +94,7 @@ export type State = State.Open | State.Closed * @category Models * @example * ```ts - * import { RcMap } from "effect" + * import type { RcMap } from "effect" * * // The State namespace contains types for RcMap internal state: * // - Open: Contains the active resource map @@ -116,8 +115,8 @@ export declare namespace State { * @category Models * @example * ```ts + * import type { RcMap } from "effect" * import * as MutableHashMap from "effect/MutableHashMap" - * import { RcMap } from "effect" * * // State.Open contains the active resource map * declare const openState: RcMap.State.Open @@ -143,7 +142,7 @@ export declare namespace State { * @category Models * @example * ```ts - * import { RcMap } from "effect" + * import type { RcMap } from "effect" * * // State.Closed indicates the RcMap is shut down * declare const closedState: RcMap.State.Closed @@ -167,11 +166,7 @@ export declare namespace State { * @category Models * @example * ```ts - * import { Effect } from "effect" - * import { Deferred } from "effect" - * import { Fiber } from "effect" - * import { RcMap } from "effect" - * import { Scope } from "effect" + * import type { RcMap } from "effect" * * // Entry contains all metadata for a resource in the map * declare const entry: RcMap.State.Entry @@ -237,8 +232,7 @@ const makeUnsafe = (options: { * @category models * @example * ```ts - * import { Effect } from "effect" - * import { RcMap } from "effect" + * import { Effect, RcMap } from "effect" * * Effect.gen(function*() { * const map = yield* RcMap.make({ @@ -315,8 +309,7 @@ export const make: { * @category combinators * @example * ```ts - * import { Effect } from "effect" - * import { RcMap } from "effect" + * import { Effect, RcMap } from "effect" * * Effect.gen(function*() { * const map = yield* RcMap.make({ @@ -431,8 +424,7 @@ const release = (self: RcMap, key: K, entry: State.Entry * @category combinators * @example * ```ts - * import { Effect } from "effect" - * import { RcMap } from "effect" + * import { Effect, RcMap } from "effect" * * Effect.gen(function*() { * const map = yield* RcMap.make({ @@ -464,8 +456,7 @@ export const keys = (self: RcMap): Effect.Effect> * @category combinators * @example * ```ts - * import { Effect } from "effect" - * import { RcMap } from "effect" + * import { Effect, RcMap } from "effect" * * Effect.gen(function*() { * const map = yield* RcMap.make({ @@ -530,8 +521,7 @@ export const has: { * @category combinators * @example * ```ts - * import { Effect } from "effect" - * import { RcMap } from "effect" + * import { Effect, RcMap } from "effect" * * Effect.gen(function*() { * const map = yield* RcMap.make({ diff --git a/packages/effect/src/RcRef.ts b/packages/effect/src/RcRef.ts index b782371a5a..5b153bd2e5 100644 --- a/packages/effect/src/RcRef.ts +++ b/packages/effect/src/RcRef.ts @@ -20,8 +20,7 @@ const TypeId = "~effect/RcRef" * @category models * @example * ```ts - * import { Effect } from "effect" - * import { RcRef } from "effect" + * import { Effect, RcRef } from "effect" * * // Create an RcRef for a database connection * const createConnectionRef = (connectionString: string) => @@ -33,7 +32,7 @@ const TypeId = "~effect/RcRef" * }) * * // Use the RcRef in multiple operations - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const connectionRef = yield* createConnectionRef("postgres://localhost") * * // Multiple gets will share the same connection @@ -94,8 +93,7 @@ export declare namespace RcRef { * @category constructors * @example * ```ts - * import { Effect } from "effect" - * import { RcRef } from "effect" + * import { Effect, RcRef } from "effect" * * Effect.gen(function*() { * const ref = yield* RcRef.make({ @@ -136,10 +134,9 @@ export const make: ( * @category combinators * @example * ```ts - * import { Effect } from "effect" - * import { RcRef } from "effect" + * import { Effect, RcRef } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * // Create an RcRef with a resource * const ref = yield* RcRef.make({ * acquire: Effect.acquireRelease( diff --git a/packages/effect/src/Record.ts b/packages/effect/src/Record.ts index ecd0422d0a..8d339fbfc7 100644 --- a/packages/effect/src/Record.ts +++ b/packages/effect/src/Record.ts @@ -21,7 +21,7 @@ import type { NoInfer } from "./types/Types.ts" * * @example * ```ts - * import { Record } from "effect" + * import type { Record } from "effect" * * // Creating a readonly record type * type UserRecord = Record.ReadonlyRecord<"name" | "age", string | number> @@ -45,7 +45,7 @@ export type ReadonlyRecord = { * * @example * ```ts - * import { Record } from "effect" + * import type { Record } from "effect" * * // Using NonLiteralKey to convert literal keys to generic types * type GenericKey = Record.ReadonlyRecord.NonLiteralKey<"foo" | "bar"> // string @@ -69,7 +69,7 @@ export declare namespace ReadonlyRecord { * * @example * ```ts - * import { Record } from "effect" + * import type { Record } from "effect" * * // For literal string keys, this becomes 'string' * type Example1 = Record.ReadonlyRecord.NonLiteralKey<"foo" | "bar"> // string @@ -90,7 +90,7 @@ export declare namespace ReadonlyRecord { * * @example * ```ts - * import { Record } from "effect" + * import type { Record } from "effect" * * // Intersection of literal keys * type Example1 = Record.ReadonlyRecord.IntersectKeys<"a" | "b", "b" | "c"> // "b" @@ -113,8 +113,7 @@ export declare namespace ReadonlyRecord { * * @example * ```ts - * import { Record } from "effect" - * import type { TypeLambda } from "effect/types/HKT" + * import type { Record } from "effect" * * // The type lambda allows records to be used as higher-kinded types * type RecordTypeLambda = Record.ReadonlyRecordTypeLambda<"key1" | "key2"> @@ -159,11 +158,11 @@ export const empty = (): Record< * * @example * ```ts - * import * as assert from "node:assert" * import { Record } from "effect" + * import * as assert from "node:assert" * - * assert.deepStrictEqual(Record.isRecordEmpty({}), true); - * assert.deepStrictEqual(Record.isRecordEmpty({ a: 3 }), false); + * assert.deepStrictEqual(Record.isRecordEmpty({}), true) + * assert.deepStrictEqual(Record.isRecordEmpty({ a: 3 }), false) * ``` * * @category guards @@ -177,11 +176,11 @@ export const isRecordEmpty = (self: Record): self is * * @example * ```ts - * import * as assert from "node:assert" * import { Record } from "effect" + * import * as assert from "node:assert" * - * assert.deepStrictEqual(Record.isReadonlyRecordEmpty({}), true); - * assert.deepStrictEqual(Record.isReadonlyRecordEmpty({ a: 3 }), false); + * assert.deepStrictEqual(Record.isReadonlyRecordEmpty({}), true) + * assert.deepStrictEqual(Record.isReadonlyRecordEmpty({ a: 3 }), false) * ``` * * @category guards @@ -197,14 +196,14 @@ export const isReadonlyRecordEmpty: ( * * @example * ```ts - * import * as assert from "node:assert" * import { Record } from "effect" + * import * as assert from "node:assert" * * const input = [1, 2, 3, 4] * * assert.deepStrictEqual( - * Record.fromIterableWith(input, a => [String(a), a * 2]), - * { '1': 2, '2': 4, '3': 6, '4': 8 } + * Record.fromIterableWith(input, (a) => [String(a), a * 2]), + * { "1": 2, "2": 4, "3": 6, "4": 8 } * ) * ``` * @@ -239,8 +238,8 @@ export const fromIterableWith: { * * @example * ```ts - * import * as assert from "node:assert" * import { Record } from "effect" + * import * as assert from "node:assert" * * const users = [ * { id: "2", name: "name2" }, @@ -248,7 +247,7 @@ export const fromIterableWith: { * ] * * assert.deepStrictEqual( - * Record.fromIterableBy(users, user => user.id), + * Record.fromIterableBy(users, (user) => user.id), * { * "2": { id: "2", name: "name2" }, * "1": { id: "1", name: "name1" } @@ -272,8 +271,8 @@ export const fromIterableBy = ( * * @example * ```ts - * import * as assert from "node:assert" * import { Record } from "effect" + * import * as assert from "node:assert" * * const input: Array<[string, number]> = [["a", 1], ["b", 2]] * @@ -292,11 +291,14 @@ export const fromEntries: ( * * @example * ```ts - * import * as assert from "node:assert" * import { Record } from "effect" + * import * as assert from "node:assert" * * const x = { a: 1, b: 2, c: 3 } - * assert.deepStrictEqual(Record.collect(x, (key, n) => [key, n]), [["a", 1], ["b", 2], ["c", 3]]) + * assert.deepStrictEqual(Record.collect(x, (key, n) => [key, n]), [["a", 1], [ + * "b", + * 2 + * ], ["c", 3]]) * ``` * * @category conversions @@ -321,8 +323,8 @@ export const collect: { * * @example * ```ts - * import * as assert from "node:assert" * import { Record } from "effect" + * import * as assert from "node:assert" * * const x = { a: 1, b: 2, c: 3 } * assert.deepStrictEqual(Record.toEntries(x), [["a", 1], ["b", 2], ["c", 3]]) @@ -341,10 +343,10 @@ export const toEntries: (self: ReadonlyRecord) => Arr * * @example * ```ts - * import * as assert from "node:assert" * import { Record } from "effect" + * import * as assert from "node:assert" * - * assert.deepStrictEqual(Record.size({ a: "a", b: 1, c: true }), 3); + * assert.deepStrictEqual(Record.size({ a: "a", b: 1, c: true }), 3) * ``` * * @category getters @@ -357,11 +359,11 @@ export const size = (self: ReadonlyRecord): number => * * @example * ```ts - * import * as assert from "node:assert" * import { Record } from "effect" + * import * as assert from "node:assert" * - * assert.deepStrictEqual(Record.has({ a: 1, b: 2 }, "a"), true); - * assert.deepStrictEqual(Record.has(Record.empty(), "c"), false); + * assert.deepStrictEqual(Record.has({ a: 1, b: 2 }, "a"), true) + * assert.deepStrictEqual(Record.has(Record.empty(), "c"), false) * ``` * * @category guards @@ -389,8 +391,7 @@ export const has: { * @example * ```ts * import * as assert from "node:assert" - * import { Record as R } from "effect" - * import { Option } from "effect" + * import { Option, Record as R } from "effect" * * const person: Record = { name: "John Doe", age: 35 } * @@ -458,8 +459,8 @@ export const modify: { * ```ts * import { Record } from "effect" * - * Record.replace({ a: 1, b: 2, c: 3 }, 'a', 10) // { a: 10, b: 2, c: 3 } - * Record.replace(Record.empty(), 'a', 10) // undefined + * Record.replace({ a: 1, b: 2, c: 3 }, "a", 10) // { a: 10, b: 2, c: 3 } + * Record.replace(Record.empty(), "a", 10) // undefined * ``` * * @category utils @@ -490,8 +491,8 @@ export const replace: { * * @example * ```ts - * import * as assert from "node:assert" * import { Record } from "effect" + * import * as assert from "node:assert" * * assert.deepStrictEqual(Record.remove({ a: 1, b: 2 }, "a"), { b: 2 }) * ``` @@ -550,8 +551,8 @@ export const pop: { * * @example * ```ts - * import * as assert from "node:assert" * import { Record } from "effect" + * import * as assert from "node:assert" * * const f = (n: number) => `-${n}` * @@ -584,10 +585,13 @@ export const map: { * * @example * ```ts - * import * as assert from "node:assert" * import { Record } from "effect" + * import * as assert from "node:assert" * - * assert.deepStrictEqual(Record.mapKeys({ a: 3, b: 5 }, (key) => key.toUpperCase()), { A: 3, B: 5 }) + * assert.deepStrictEqual( + * Record.mapKeys({ a: 3, b: 5 }, (key) => key.toUpperCase()), + * { A: 3, B: 5 } + * ) * ``` * * @category mapping @@ -621,10 +625,13 @@ export const mapKeys: { * * @example * ```ts - * import * as assert from "node:assert" * import { Record } from "effect" + * import * as assert from "node:assert" * - * assert.deepStrictEqual(Record.mapEntries({ a: 3, b: 5 }, (a, key) => [key.toUpperCase(), a + 1]), { A: 4, B: 6 }) + * assert.deepStrictEqual( + * Record.mapEntries({ a: 3, b: 5 }, (a, key) => [key.toUpperCase(), a + 1]), + * { A: 4, B: 6 } + * ) * ``` * * @category mapping @@ -660,8 +667,7 @@ export const mapEntries: { * @example * ```ts * import * as assert from "node:assert" - * import { Record } from "effect" - * import { Option } from "effect" + * import { Option, Record } from "effect" * * const x = { a: 1, b: 2, c: 3 } * const f = (a: number, key: string) => a > 2 ? Option.some(a * 2) : Option.none() @@ -701,8 +707,8 @@ export const filterMap: { * * @example * ```ts - * import * as assert from "node:assert" * import { Record } from "effect" + * import * as assert from "node:assert" * * const x = { a: 1, b: 2, c: 3, d: 4 } * assert.deepStrictEqual(Record.filter(x, (n) => n > 2), { c: 3, d: 4 }) @@ -748,8 +754,7 @@ export const filter: { * @example * ```ts * import * as assert from "node:assert" - * import { Record } from "effect" - * import { Option } from "effect" + * import { Option, Record } from "effect" * * assert.deepStrictEqual( * Record.getSomes({ a: Option.some(1), b: Option.none(), c: Option.some(2) }), @@ -771,12 +776,15 @@ export const getSomes: ( * * @example * ```ts + * import { Record, Result } from "effect" * import * as assert from "node:assert" - * import { Record } from "effect" - * import { Result } from "effect" * * assert.deepStrictEqual( - * Record.getFailures({ a: Result.succeed(1), b: Result.fail("err"), c: Result.succeed(2) }), + * Record.getFailures({ + * a: Result.succeed(1), + * b: Result.fail("err"), + * c: Result.succeed(2) + * }), * { b: "err" } * ) * ``` @@ -803,12 +811,15 @@ export const getFailures = ( * * @example * ```ts + * import { Record, Result } from "effect" * import * as assert from "node:assert" - * import { Record } from "effect" - * import { Result } from "effect" * * assert.deepStrictEqual( - * Record.getSuccesses({ a: Result.succeed(1), b: Result.fail("err"), c: Result.succeed(2) }), + * Record.getSuccesses({ + * a: Result.succeed(1), + * b: Result.fail("err"), + * c: Result.succeed(2) + * }), * { a: 1, c: 2 } * ) * ``` @@ -836,12 +847,11 @@ export const getSuccesses = ( * @example * ```ts * import * as assert from "node:assert" - * import { Record } from "effect" - * import { Result } from "effect" + * import { Record, Result } from "effect" * * const x = { a: 1, b: 2, c: 3 } * const f = (n: number) => (n % 2 === 0 ? Result.succeed(n) : Result.fail(n)) - * assert.deepStrictEqual(Record.partitionMap(x, f), [{ a: 1, c: 3 }, { b: 2}]) + * assert.deepStrictEqual(Record.partitionMap(x, f), [{ a: 1, c: 3 }, { b: 2 }]) * ``` * * @category filtering @@ -884,8 +894,7 @@ export const partitionMap: { * @example * ```ts * import * as assert from "node:assert" - * import { Record } from "effect" - * import { Result } from "effect" + * import { Record, Result } from "effect" * * assert.deepStrictEqual( * Record.separate({ a: Result.fail("e"), b: Result.succeed(1) }), @@ -905,8 +914,8 @@ export const separate: ( * * @example * ```ts - * import * as assert from "node:assert" * import { Record } from "effect" + * import * as assert from "node:assert" * * assert.deepStrictEqual( * Record.partition({ a: 1, b: 3 }, (n) => n > 2), @@ -964,8 +973,8 @@ export const partition: { * * @example * ```ts - * import * as assert from "node:assert" * import { Record } from "effect" + * import * as assert from "node:assert" * * assert.deepStrictEqual(Record.keys({ a: 1, b: 2, c: 3 }), ["a", "b", "c"]) * ``` @@ -981,8 +990,8 @@ export const keys = (self: ReadonlyRecord): * * @example * ```ts - * import * as assert from "node:assert" * import { Record } from "effect" + * import * as assert from "node:assert" * * assert.deepStrictEqual(Record.values({ a: 1, b: 2, c: 3 }), [1, 2, 3]) * ``` @@ -997,11 +1006,11 @@ export const values = (self: ReadonlyRecord): Array()) * - * 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) + * 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 + * ) * ``` * * @category predicates @@ -1066,11 +1080,17 @@ export const isSubrecordBy = (equivalence: Equivalence): { * * @example * ```ts - * import * as assert from "node:assert" * import { Record } from "effect" + * import * as assert from "node:assert" * - * 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) + * 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 + * ) * ``` * * @category predicates @@ -1086,8 +1106,8 @@ export const isSubrecord: { * * @example * ```ts - * import * as assert from "node:assert" * import { Record } from "effect" + * import * as assert from "node:assert" * * assert.deepStrictEqual( * Record.reduce({ a: 1, b: 2, c: 3 }, 0, (acc, value, key) => acc + value), @@ -1124,8 +1144,8 @@ export const reduce: { * * @example * ```ts - * import * as assert from "node:assert" * import { Record } from "effect" + * import * as assert from "node:assert" * * assert.deepStrictEqual(Record.every({ a: 1, b: 2 }, (n) => n > 0), true) * assert.deepStrictEqual(Record.every({ a: 1, b: -1 }, (n) => n > 0), false) @@ -1164,8 +1184,8 @@ export const every: { * * @example * ```ts - * import * as assert from "node:assert" * import { Record } from "effect" + * import * as assert from "node:assert" * * assert.deepStrictEqual(Record.some({ a: 1, b: 2 }, (n) => n > 1), true) * assert.deepStrictEqual(Record.some({ a: 1, b: 2 }, (n) => n > 2), false) @@ -1195,8 +1215,8 @@ export const some: { * * @example * ```ts - * import * as assert from "node:assert" * import { Record } from "effect" + * import * as assert from "node:assert" * * assert.deepStrictEqual( * Record.union({ a: 1, b: 2 }, { b: 3, c: 4 }, (a, b) => a + b), @@ -1253,8 +1273,8 @@ export const union: { * * @example * ```ts - * import * as assert from "node:assert" * import { Record } from "effect" + * import * as assert from "node:assert" * * assert.deepStrictEqual( * Record.intersection({ a: 1, b: 2 }, { b: 3, c: 4 }, (a, b) => a + b), @@ -1301,8 +1321,8 @@ export const intersection: { * * @example * ```ts - * import * as assert from "node:assert" * import { Record } from "effect" + * import * as assert from "node:assert" * * assert.deepStrictEqual( * Record.difference({ a: 1, b: 2 }, { b: 3, c: 4 }), @@ -1352,8 +1372,7 @@ export const difference: { * @example * ```ts * import * as assert from "node:assert" - * import { Record } from "effect" - * import { Equal } from "effect" + * import { Equal, Record } from "effect" * * const recordEquivalence = Record.getEquivalence(Equal.equivalence()) * @@ -1376,8 +1395,8 @@ export const getEquivalence = ( * * @example * ```ts - * import * as assert from "node:assert" * import { Record } from "effect" + * import * as assert from "node:assert" * * assert.deepStrictEqual(Record.singleton("a", 1), { a: 1 }) * ``` @@ -1425,10 +1444,13 @@ export function getReducerIntersection( * * @example * ```ts - * import { Record, Option } from "effect" + * import { Record } from "effect" * * const record = { a: 1, b: 2, c: 3 } - * const result = Record.findFirst(record, (value, key) => value > 1 && key !== "b") + * const result = Record.findFirst( + * record, + * (value, key) => value > 1 && key !== "b" + * ) * console.log(result) // Option.Some(["c", 3]) * ``` * diff --git a/packages/effect/src/Redactable.ts b/packages/effect/src/Redactable.ts index cb41a2edf8..e6a03f3923 100644 --- a/packages/effect/src/Redactable.ts +++ b/packages/effect/src/Redactable.ts @@ -22,8 +22,8 @@ export const symbolRedactable: unique symbol = Symbol.for("~effect/Inspectable/r * * @example * ```ts + * import type { ServiceMap } from "effect" * import { Redactable } from "effect" - * import { ServiceMap } from "effect" * * class SensitiveData implements Redactable.Redactable { * constructor(private secret: string) {} diff --git a/packages/effect/src/Redacted.ts b/packages/effect/src/Redacted.ts index 6780525445..1ead2fac2d 100644 --- a/packages/effect/src/Redacted.ts +++ b/packages/effect/src/Redacted.ts @@ -97,7 +97,7 @@ export declare namespace Redacted { * const secret = Redacted.make("my-secret") * const plainString = "not-secret" * - * console.log(Redacted.isRedacted(secret)) // true + * console.log(Redacted.isRedacted(secret)) // true * console.log(Redacted.isRedacted(plainString)) // false * ``` * @@ -160,8 +160,8 @@ const Proto = { * * @example * ```ts - * import * as assert from "node:assert" * import { Redacted } from "effect" + * import * as assert from "node:assert" * * const API_KEY = Redacted.make("1234567890") * @@ -186,8 +186,8 @@ export const value = (self: Redacted): T => { * * @example * ```ts - * import * as assert from "node:assert" * import { Redacted } from "effect" + * import * as assert from "node:assert" * * const API_KEY = Redacted.make("1234567890") * @@ -195,7 +195,10 @@ export const value = (self: Redacted): T => { * * Redacted.wipeUnsafe(API_KEY) * - * assert.throws(() => Redacted.value(API_KEY), new Error("Unable to get redacted value")) + * assert.throws( + * () => Redacted.value(API_KEY), + * new Error("Unable to get redacted value") + * ) * ``` * * @since 3.3.0 @@ -211,8 +214,7 @@ export const wipeUnsafe = (self: Redacted): boolean => redactedRegistry.de * @example * ```ts * import * as assert from "node:assert" - * import { Equivalence } from "effect" - * import { Redacted } from "effect" + * import { Equivalence, Redacted } from "effect" * * const API_KEY1 = Redacted.make("1234567890") * const API_KEY2 = Redacted.make("1-34567890") diff --git a/packages/effect/src/Ref.ts b/packages/effect/src/Ref.ts index 3a6ff27faf..b8f8baccf1 100644 --- a/packages/effect/src/Ref.ts +++ b/packages/effect/src/Ref.ts @@ -7,16 +7,15 @@ * * @example * ```ts - * import { Effect } from "effect" - * import { Ref } from "effect" + * 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) + * yield* Ref.update(counter, (n) => n + 1) + * yield* Ref.update(counter, (n) => n * 2) * * const value = yield* Ref.get(counter) * console.log(value) // 2 @@ -47,8 +46,7 @@ const TypeId = "~effect/Ref" * * @example * ```ts - * import { Effect } from "effect" - * import { Ref } from "effect" + * import { Effect, Ref } from "effect" * * const program = Effect.gen(function*() { * // Create a ref with initial value @@ -59,7 +57,7 @@ const TypeId = "~effect/Ref" * console.log(value) // 0 * * // Update the value atomically - * yield* Ref.update(counter, n => n + 1) + * yield* Ref.update(counter, (n) => n + 1) * * // Read the updated value * const newValue = yield* Ref.get(counter) @@ -86,8 +84,7 @@ export declare namespace Ref { * * @example * ```ts - * import { Effect } from "effect" - * import { Ref } from "effect" + * import { Effect, Ref } from "effect" * * // This interface defines the invariant nature of Ref's type parameter * // A Ref is both a producer and consumer of A @@ -95,8 +92,8 @@ export declare namespace Ref { * const ref = yield* Ref.make(42) * * // Ref is invariant - it can both produce and consume numbers - * const value = yield* Ref.get(ref) // produces number - * yield* Ref.set(ref, value + 1) // consumes number + * const value = yield* Ref.get(ref) // produces number + * yield* Ref.set(ref, value + 1) // consumes number * }) * ``` * @@ -161,8 +158,7 @@ export const makeUnsafe = (value: A): Ref => { * * @example * ```ts - * import { Effect } from "effect" - * import { Ref } from "effect" + * import { Effect, Ref } from "effect" * * const program = Effect.gen(function*() { * const ref = yield* Ref.make(42) @@ -181,8 +177,7 @@ export const make = (value: A): Effect.Effect> => Effect.sync(() => ma * * @example * ```ts - * import { Effect } from "effect" - * import { Ref } from "effect" + * import { Effect, Ref } from "effect" * * const program = Effect.gen(function*() { * const ref = yield* Ref.make(42) @@ -201,8 +196,7 @@ export const get = (self: Ref) => Effect.sync(() => self.ref.current) * * @example * ```ts - * import { Effect } from "effect" - * import { Ref } from "effect" + * import { Effect, Ref } from "effect" * * const program = Effect.gen(function*() { * const ref = yield* Ref.make(0) @@ -235,8 +229,7 @@ export const set = dual< * * @example * ```ts - * import { Effect } from "effect" - * import { Ref } from "effect" + * import { Effect, Ref } from "effect" * * const program = Effect.gen(function*() { * const ref = yield* Ref.make("initial") @@ -270,14 +263,13 @@ export const getAndSet = dual< * * @example * ```ts - * import { Effect } from "effect" - * import { Ref } from "effect" + * import { Effect, Ref } from "effect" * * const program = Effect.gen(function*() { * const counter = yield* Ref.make(10) * * // Get current value and update it atomically - * const previous = yield* Ref.getAndUpdate(counter, n => n * 2) + * const previous = yield* Ref.getAndUpdate(counter, (n) => n * 2) * console.log(previous) // 10 * * const current = yield* Ref.get(counter) @@ -307,16 +299,16 @@ export const getAndUpdate = dual< * * @example * ```ts - * import { Effect } from "effect" - * import { Ref } from "effect" + * import { Effect, Ref } from "effect" * import * as Option from "effect/Option" * * const program = Effect.gen(function*() { * const counter = yield* Ref.make(5) * * // Only update if value is greater than 3 - * const previous1 = yield* Ref.getAndUpdateSome(counter, n => - * n > 3 ? Option.some(n * 2) : Option.none() + * const previous1 = yield* Ref.getAndUpdateSome( + * counter, + * (n) => n > 3 ? Option.some(n * 2) : Option.none() * ) * console.log(previous1) // 5 * @@ -324,8 +316,9 @@ export const getAndUpdate = dual< * console.log(current1) // 10 * * // Try to update again (won't update since 10 > 3 is true but let's say condition is n < 3) - * const previous2 = yield* Ref.getAndUpdateSome(counter, n => - * n < 3 ? Option.some(n * 2) : Option.none() + * const previous2 = yield* Ref.getAndUpdateSome( + * counter, + * (n) => n < 3 ? Option.some(n * 2) : Option.none() * ) * console.log(previous2) // 10 * @@ -357,8 +350,7 @@ export const getAndUpdateSome = dual< * * @example * ```ts - * import { Effect } from "effect" - * import { Ref } from "effect" + * import { Effect, Ref } from "effect" * * const program = Effect.gen(function*() { * const ref = yield* Ref.make(10) @@ -397,16 +389,15 @@ export const setAndGet = dual< * * @example * ```ts - * import { Effect } from "effect" - * import { Ref } from "effect" + * import { Effect, Ref } from "effect" * * const program = Effect.gen(function*() { * const counter = yield* Ref.make(10) * * // Modify the ref and return some computation result - * const result = yield* Ref.modify(counter, n => [ + * const result = yield* Ref.modify(counter, (n) => [ * `Previous value was ${n}`, // Return value - * n * 2 // New ref value + * n * 2 // New ref value * ]) * * console.log(result) // "Previous value was 10" @@ -419,8 +410,8 @@ export const setAndGet = dual< * const program2 = Effect.gen(function*() { * const state = yield* Ref.make({ count: 0, total: 0 }) * - * const incremented = yield* Ref.modify(state, s => [ - * s.count, // Return previous count + * const incremented = yield* Ref.modify(state, (s) => [ + * s.count, // Return previous count * { count: s.count + 1, total: s.total + s.count + 1 } // New state * ]) * @@ -450,8 +441,7 @@ export const modify = dual< * * @example * ```ts - * import { Effect } from "effect" - * import { Ref } from "effect" + * import { Effect, Ref } from "effect" * import * as Option from "effect/Option" * * const program = Effect.gen(function*() { @@ -460,9 +450,10 @@ export const modify = dual< * // Only modify if value is greater than 3 * const result1 = yield* Ref.modifySome( * counter, - * n => n > 3 - * ? [`incremented ${n}`, Option.some(n + 10)] - * : ["no change", Option.none()] + * (n) => + * n > 3 + * ? [`incremented ${n}`, Option.some(n + 10)] + * : ["no change", Option.none()] * ) * * console.log(result1) // "incremented 5" @@ -473,9 +464,10 @@ export const modify = dual< * // Try to modify with a condition that fails * const result2 = yield* Ref.modifySome( * counter, - * n => n < 10 - * ? [`decremented ${n}`, Option.some(n - 5)] - * : ["no change", Option.none()] + * (n) => + * n < 10 + * ? [`decremented ${n}`, Option.some(n - 5)] + * : ["no change", Option.none()] * ) * * console.log(result2) // "no change" @@ -510,14 +502,13 @@ export const modifySome: { * * @example * ```ts - * import { Effect } from "effect" - * import { Ref } from "effect" + * import { Effect, Ref } from "effect" * * const program = Effect.gen(function*() { * const counter = yield* Ref.make(5) * * // Update the value - * yield* Ref.update(counter, n => n * 2) + * yield* Ref.update(counter, (n) => n * 2) * * const value = yield* Ref.get(counter) * console.log(value) // 10 @@ -548,14 +539,13 @@ export const update = dual< * * @example * ```ts - * import { Effect } from "effect" - * import { Ref } from "effect" + * import { Effect, Ref } from "effect" * * const program = Effect.gen(function*() { * const counter = yield* Ref.make(5) * * // Update and get the new value in one operation - * const newValue = yield* Ref.updateAndGet(counter, n => n * 3) + * const newValue = yield* Ref.updateAndGet(counter, (n) => n * 3) * console.log(newValue) // 15 * * // Verify the ref contains the new value @@ -580,16 +570,16 @@ export const updateAndGet = dual< * * @example * ```ts - * import { Effect } from "effect" - * import { Ref } from "effect" + * import { Effect, Ref } from "effect" * import * as Option from "effect/Option" * * const program = Effect.gen(function*() { * const counter = yield* Ref.make(5) * * // Only update if value is even - * yield* Ref.updateSome(counter, n => - * n % 2 === 0 ? Option.some(n * 2) : Option.none() + * yield* Ref.updateSome( + * counter, + * (n) => n % 2 === 0 ? Option.some(n * 2) : Option.none() * ) * * let current = yield* Ref.get(counter) @@ -597,8 +587,9 @@ export const updateAndGet = dual< * * // Set to even number and try again * yield* Ref.set(counter, 6) - * yield* Ref.updateSome(counter, n => - * n % 2 === 0 ? Option.some(n * 2) : Option.none() + * yield* Ref.updateSome( + * counter, + * (n) => n % 2 === 0 ? Option.some(n * 2) : Option.none() * ) * * current = yield* Ref.get(counter) @@ -629,22 +620,23 @@ export const updateSome = dual< * * @example * ```ts - * import { Effect } from "effect" - * import { Ref } from "effect" + * import { Effect, Ref } from "effect" * import * as Option from "effect/Option" * * const program = Effect.gen(function*() { * const counter = yield* Ref.make(10) * * // Only update if value is greater than 5 - * const result1 = yield* Ref.updateSomeAndGet(counter, n => - * n > 5 ? Option.some(n / 2) : Option.none() + * const result1 = yield* Ref.updateSomeAndGet( + * counter, + * (n) => n > 5 ? Option.some(n / 2) : Option.none() * ) * console.log(result1) // 5 (updated and returned) * * // Try to update again with same condition - * const result2 = yield* Ref.updateSomeAndGet(counter, n => - * n > 5 ? Option.some(n / 2) : Option.none() + * const result2 = yield* Ref.updateSomeAndGet( + * counter, + * (n) => n > 5 ? Option.some(n / 2) : Option.none() * ) * console.log(result2) // 5 (unchanged because 5 is not > 5) * }) diff --git a/packages/effect/src/References.ts b/packages/effect/src/References.ts index ed8c01592e..3d86113274 100644 --- a/packages/effect/src/References.ts +++ b/packages/effect/src/References.ts @@ -41,17 +41,16 @@ export { * * @example * ```ts - * import { Effect } from "effect" - * import { References } from "effect" + * import { Effect, References } from "effect" * - * const limitConcurrency = Effect.gen(function* () { + * const limitConcurrency = Effect.gen(function*() { * // Get current setting * const current = yield* References.CurrentConcurrency * console.log(current) // "unbounded" (default) * * // Run with limited concurrency * yield* Effect.provideService( - * Effect.gen(function* () { + * Effect.gen(function*() { * const limited = yield* References.CurrentConcurrency * console.log(limited) // 10 * }), @@ -61,7 +60,7 @@ export { * * // Run with unlimited concurrency * yield* Effect.provideService( - * Effect.gen(function* () { + * Effect.gen(function*() { * const unlimited = yield* References.CurrentConcurrency * console.log(unlimited) // "unbounded" * }), @@ -85,18 +84,16 @@ export { * * @example * ```ts - * import { Effect } from "effect" - * import { References } from "effect" - * import { Scheduler } from "effect" + * import { Effect, References, Scheduler } from "effect" * - * const customScheduling = Effect.gen(function* () { + * const customScheduling = Effect.gen(function*() { * // Get current scheduler (default is MixedScheduler) * const current = yield* References.Scheduler * console.log(current) // MixedScheduler instance * * // Use a custom scheduler * yield* Effect.provideService( - * Effect.gen(function* () { + * Effect.gen(function*() { * const scheduler = yield* References.Scheduler * console.log(scheduler) // Custom scheduler instance * @@ -139,17 +136,16 @@ export const CurrentStackFrame = ServiceMap.Reference("e * * @example * ```ts - * import { Effect } from "effect" - * import { References } from "effect" + * import { Effect, References } from "effect" * - * const tracingControl = Effect.gen(function* () { + * const tracingControl = Effect.gen(function*() { * // Check if tracing is enabled (default is true) * const current = yield* References.TracerEnabled * console.log(current) // true * * // Disable tracing globally * yield* Effect.provideService( - * Effect.gen(function* () { + * Effect.gen(function*() { * const isEnabled = yield* References.TracerEnabled * console.log(isEnabled) // false * @@ -162,7 +158,7 @@ export const CurrentStackFrame = ServiceMap.Reference("e * * // Re-enable tracing * yield* Effect.provideService( - * Effect.gen(function* () { + * Effect.gen(function*() { * const isEnabled = yield* References.TracerEnabled * console.log(isEnabled) // true * @@ -188,23 +184,22 @@ export const TracerEnabled = ServiceMap.Reference("effect/References/Tr * * @example * ```ts - * import { Effect } from "effect" - * import { References } from "effect" + * import { Effect, References } from "effect" * - * const spanAnnotationExample = Effect.gen(function* () { + * const spanAnnotationExample = Effect.gen(function*() { * // Get current annotations (empty by default) * const current = yield* References.TracerSpanAnnotations * console.log(current) // {} * * // Set global span annotations * yield* Effect.provideService( - * Effect.gen(function* () { + * Effect.gen(function*() { * // Get current annotations * const annotations = yield* References.TracerSpanAnnotations * console.log(annotations) // { service: "user-service", version: "1.2.3", environment: "production" } * * // All spans created will include these annotations - * yield* Effect.gen(function* () { + * yield* Effect.gen(function*() { * // Add more specific annotations for this span * yield* Effect.annotateCurrentSpan("userId", "123") * yield* Effect.log("Processing user") @@ -220,7 +215,7 @@ export const TracerEnabled = ServiceMap.Reference("effect/References/Tr * * // Clear annotations * yield* Effect.provideService( - * Effect.gen(function* () { + * Effect.gen(function*() { * const annotations = yield* References.TracerSpanAnnotations * console.log(annotations) // {} * }), @@ -244,11 +239,9 @@ export const TracerSpanAnnotations = ServiceMap.Reference>("ef * * @example * ```ts - * import { Effect } from "effect" - * import { References } from "effect" - * import { Console } from "effect" + * import { Console, Effect, References } from "effect" * - * const logAnnotationExample = Effect.gen(function* () { + * const logAnnotationExample = Effect.gen(function*() { * // Get current annotations (empty by default) * const current = yield* References.CurrentLogAnnotations * console.log(current) // {} * * // Run with custom log annotations * yield* Effect.provideService( - * Effect.gen(function* () { + * Effect.gen(function*() { * const annotations = yield* References.CurrentLogAnnotations * console.log(annotations) // { requestId: "req-123", userId: "user-456", version: "1.0.0" } * @@ -339,7 +330,7 @@ export const TracerSpanLinks = ServiceMap.Reference>("ef * * // Run with extended annotations * yield* Effect.provideService( - * Effect.gen(function* () { + * Effect.gen(function*() { * const extended = yield* References.CurrentLogAnnotations * console.log(extended) // { requestId: "req-123", userId: "user-456", version: "1.0.0", operation: "data-sync", timestamp: 1234567890 } * @@ -370,18 +361,16 @@ export const CurrentLogAnnotations = ServiceMap.Reference = Ser * * @example * ```ts - * import { Effect } from "effect" - * import { References } from "effect" - * import { Console } from "effect" + * import { Console, Effect, References } from "effect" * - * const logSpanExample = Effect.gen(function* () { + * const logSpanExample = Effect.gen(function*() { * // Get current spans (empty by default) * const current = yield* References.CurrentLogSpans * console.log(current.length) // 0 @@ -442,7 +429,7 @@ export const UnhandledLogLevel: ServiceMap.Reference = Ser * // Add a log span manually * const startTime = Date.now() * yield* Effect.provideService( - * Effect.gen(function* () { + * Effect.gen(function*() { * // Simulate some work * yield* Effect.sleep("100 millis") * yield* Console.log("Database operation in progress") @@ -456,7 +443,7 @@ export const UnhandledLogLevel: ServiceMap.Reference = Ser * * // Add another span * yield* Effect.provideService( - * Effect.gen(function* () { + * Effect.gen(function*() { * const spans = yield* References.CurrentLogSpans * console.log("Active spans:", spans.map(([label]) => label)) // ["database-connection", "data-processing"] * @@ -471,7 +458,7 @@ export const UnhandledLogLevel: ServiceMap.Reference = Ser * * // Clear spans when operations complete * yield* Effect.provideService( - * Effect.gen(function* () { + * Effect.gen(function*() { * const spans = yield* References.CurrentLogSpans * console.log("Active spans:", spans.length) // 0 * }), @@ -494,24 +481,22 @@ export const CurrentLogSpans = ServiceMap.Reference< * * @example * ```ts - * import { Effect } from "effect" - * import { References } from "effect" - * import { Console } from "effect" + * import { Console, Effect, References } from "effect" * - * const configureMinimumLogging = Effect.gen(function* () { + * const configureMinimumLogging = Effect.gen(function*() { * // Get current minimum level (default is "Info") * const current = yield* References.MinimumLogLevel * console.log(current) // "Info" * * // Set minimum level to Warn - Debug and Info will be filtered * yield* Effect.provideService( - * Effect.gen(function* () { + * Effect.gen(function*() { * const minLevel = yield* References.MinimumLogLevel * console.log(minLevel) // "Warn" * * // These won't be processed at all * yield* Console.debug("Debug message") // Filtered out - * yield* Console.info("Info message") // Filtered out + * yield* Console.info("Info message") // Filtered out * * // These will be processed * yield* Console.warn("Warning message") // Shown @@ -523,7 +508,7 @@ export const CurrentLogSpans = ServiceMap.Reference< * * // Reset to default Info level * yield* Effect.provideService( - * Effect.gen(function* () { + * Effect.gen(function*() { * const minLevel = yield* References.MinimumLogLevel * console.log(minLevel) // "Info" * diff --git a/packages/effect/src/Result.ts b/packages/effect/src/Result.ts index 4064d36a13..b04e9b799b 100644 --- a/packages/effect/src/Result.ts +++ b/packages/effect/src/Result.ts @@ -148,7 +148,7 @@ export interface ResultUnifyIgnore {} * * @example * ```ts - * import { Result } from "effect" + * import type { Result } from "effect" * * // This interface allows Result to work with higher-kinded type utilities * declare const resultTypeLambda: Result.ResultTypeLambda @@ -260,8 +260,8 @@ export { * * @example * ```ts - * import * as assert from "node:assert" * import { Result } from "effect" + * import * as assert from "node:assert" * * const result = Result.void * assert.deepStrictEqual(result, Result.succeed(undefined)) @@ -280,11 +280,17 @@ export { * * @example * ```ts - * import * as assert from "node:assert" * import { Result } from "effect" + * import * as assert from "node:assert" * - * assert.deepStrictEqual(Result.fromNullishOr(1, () => 'fallback'), Result.succeed(1)) - * assert.deepStrictEqual(Result.fromNullishOr(null, () => 'fallback'), Result.fail('fallback')) + * assert.deepStrictEqual( + * Result.fromNullishOr(1, () => "fallback"), + * Result.succeed(1) + * ) + * assert.deepStrictEqual( + * Result.fromNullishOr(null, () => "fallback"), + * Result.fail("fallback") + * ) * ``` * * @category Constructors @@ -302,12 +308,17 @@ export const fromNullishOr: { /** * @example * ```ts + * import { Option, Result } from "effect" * import * as assert from "node:assert" - * import { Result } from "effect" - * import { Option } from "effect" * - * assert.deepStrictEqual(Result.fromOption(Option.some(1), () => 'error'), Result.succeed(1)) - * assert.deepStrictEqual(Result.fromOption(Option.none(), () => 'error'), Result.fail('error')) + * assert.deepStrictEqual( + * Result.fromOption(Option.some(1), () => "error"), + * Result.succeed(1) + * ) + * assert.deepStrictEqual( + * Result.fromOption(Option.none(), () => "error"), + * Result.fail("error") + * ) * ``` * * @category Constructors @@ -354,10 +365,10 @@ export { * * @example * ```ts - * import * as assert from "node:assert" * import { Result } from "effect" + * import * as assert from "node:assert" * - * const success = Result.try(() => JSON.parse('{"name": "John"}')) + * const success = Result.try(() => JSON.parse("{\"name\": \"John\"}")) * assert.deepStrictEqual(success, Result.succeed({ name: "John" })) * * const failure = Result.try(() => JSON.parse("invalid json")) @@ -375,8 +386,8 @@ export { * * @example * ```ts - * import * as assert from "node:assert" * import { Result } from "effect" + * import * as assert from "node:assert" * * assert.deepStrictEqual(Result.isResult(Result.succeed(1)), true) * assert.deepStrictEqual(Result.isResult(Result.fail("a")), true) @@ -393,8 +404,8 @@ export const isResult: (input: unknown) => input is Result = r * * @example * ```ts - * import * as assert from "node:assert" * import { Result } from "effect" + * import * as assert from "node:assert" * * assert.deepStrictEqual(Result.isFailure(Result.succeed(1)), false) * assert.deepStrictEqual(Result.isFailure(Result.fail("a")), true) @@ -410,8 +421,8 @@ export const isFailure: (self: Result) => self is Failure = re * * @example * ```ts - * import * as assert from "node:assert" * import { Result } from "effect" + * import * as assert from "node:assert" * * assert.deepStrictEqual(Result.isSuccess(Result.succeed(1)), true) * assert.deepStrictEqual(Result.isSuccess(Result.fail("a")), false) @@ -427,12 +438,14 @@ export const isSuccess: (self: Result) => self is Success = re * * @example * ```ts + * import { Option, Result } from "effect" * import * as assert from "node:assert" - * import { Result } from "effect" - * import { Option } from "effect" * - * assert.deepStrictEqual(Result.getSuccess(Result.succeed('ok')), Option.some('ok')) - * assert.deepStrictEqual(Result.getSuccess(Result.fail('err')), Option.none()) + * assert.deepStrictEqual( + * Result.getSuccess(Result.succeed("ok")), + * Option.some("ok") + * ) + * assert.deepStrictEqual(Result.getSuccess(Result.fail("err")), Option.none()) * ``` * * @category Getters @@ -445,12 +458,14 @@ export const getSuccess: (self: Result) => Option = result.getSuc * * @example * ```ts + * import { Option, Result } from "effect" * import * as assert from "node:assert" - * import { Result } from "effect" - * import { Option } from "effect" * - * assert.deepStrictEqual(Result.getFailure(Result.succeed('ok')), Option.none()) - * assert.deepStrictEqual(Result.getFailure(Result.fail('err')), Option.some('err')) + * assert.deepStrictEqual(Result.getFailure(Result.succeed("ok")), Option.none()) + * assert.deepStrictEqual( + * Result.getFailure(Result.fail("err")), + * Option.some("err") + * ) * ``` * * @category Getters @@ -464,8 +479,7 @@ export const getFailure: (self: Result) => Option = result.getFai * **Example** * * ```ts - * import { Result } from "effect" - * import { Equivalence } from "effect" + * import { Equivalence, Result } from "effect" * * const stringEquivalence = Equivalence.strict() * const numberEquivalence = Equivalence.strict() @@ -502,8 +516,7 @@ export const getEquivalence = ( * @example * ```ts * import * as assert from "node:assert" - * import { pipe } from "effect" - * import { Result } from "effect" + * import { pipe, Result } from "effect" * * const success = pipe( * Result.succeed(1), @@ -550,8 +563,7 @@ export const mapBoth: { * @example * ```ts * import * as assert from "node:assert" - * import { pipe } from "effect" - * import { Result } from "effect" + * import { pipe, Result } from "effect" * * const success = pipe( * Result.succeed(1), @@ -584,8 +596,7 @@ export const mapError: { * @example * ```ts * import * as assert from "node:assert" - * import { pipe } from "effect" - * import { Result } from "effect" + * import { pipe, Result } from "effect" * * const success = pipe( * Result.succeed(1), @@ -620,17 +631,23 @@ export const map: { * @example * ```ts * import * as assert from "node:assert" - * import { pipe } from "effect" - * import { Result } from "effect" + * import { pipe, Result } from "effect" * - * const onFailure = (strings: ReadonlyArray): string => `strings: ${strings.join(', ')}` + * const onFailure = (strings: ReadonlyArray): string => + * `strings: ${strings.join(", ")}` * * const onSuccess = (value: number): string => `Ok: ${value}` * - * assert.deepStrictEqual(pipe(Result.succeed(1), Result.match({ onFailure, onSuccess })), 'Ok: 1') * assert.deepStrictEqual( - * pipe(Result.fail(['string 1', 'string 2']), Result.match({ onFailure, onSuccess })), - * 'strings: string 1, string 2' + * pipe(Result.succeed(1), Result.match({ onFailure, onSuccess })), + * "Ok: 1" + * ) + * assert.deepStrictEqual( + * pipe( + * Result.fail(["string 1", "string 2"]), + * Result.match({ onFailure, onSuccess }) + * ), + * "strings: string 1, string 2" * ) * ``` * @@ -660,23 +677,22 @@ export const match: { * * @example * ```ts + * import { pipe, Result } from "effect" * import * as assert from "node:assert" - * import { pipe } from "effect" - * import { Result } from "effect" * * const isPositive = (n: number): boolean => n > 0 * * assert.deepStrictEqual( * pipe( * 1, - * Result.liftPredicate(isPositive, n => `${n} is not positive`) + * Result.liftPredicate(isPositive, (n) => `${n} is not positive`) * ), * Result.succeed(1) * ) * assert.deepStrictEqual( * pipe( * 0, - * Result.liftPredicate(isPositive, n => `${n} is not positive`) + * Result.liftPredicate(isPositive, (n) => `${n} is not positive`) * ), * Result.fail("0 is not positive") * ) @@ -713,23 +729,22 @@ export const liftPredicate: { * * @example * ```ts + * import { pipe, Result } from "effect" * import * as assert from "node:assert" - * import { pipe } from "effect" - * import { Result } from "effect" * * const isPositive = (n: number): boolean => n > 0 * * assert.deepStrictEqual( * pipe( * Result.succeed(1), - * Result.filterOrFail(isPositive, n => `${n} is not positive`) + * Result.filterOrFail(isPositive, (n) => `${n} is not positive`) * ), * Result.succeed(1) * ) * assert.deepStrictEqual( * pipe( * Result.succeed(0), - * Result.filterOrFail(isPositive, n => `${n} is not positive`) + * Result.filterOrFail(isPositive, (n) => `${n} is not positive`) * ), * Result.fail("0 is not positive") * ) @@ -764,8 +779,8 @@ export const filterOrFail: { * * @example * ```ts - * import * as assert from "node:assert" * import { Result } from "effect" + * import * as assert from "node:assert" * * const success = Result.succeed(42) * assert.deepStrictEqual(Result.merge(success), 42) @@ -784,11 +799,17 @@ export const merge: (self: Result) => E | A = match({ onFailure: ide * * @example * ```ts - * import * as assert from "node:assert" * import { Result } from "effect" + * import * as assert from "node:assert" * - * assert.deepStrictEqual(Result.getOrElse(Result.succeed(1), (error) => error + "!"), 1) - * assert.deepStrictEqual(Result.getOrElse(Result.fail("not a number"), (error) => error + "!"), "not a number!") + * assert.deepStrictEqual( + * Result.getOrElse(Result.succeed(1), (error) => error + "!"), + * 1 + * ) + * assert.deepStrictEqual( + * Result.getOrElse(Result.fail("not a number"), (error) => error + "!"), + * "not a number!" + * ) * ``` * * @category Getters @@ -808,8 +829,8 @@ export const getOrElse: { * * @example * ```ts - * import * as assert from "node:assert" * import { Result } from "effect" + * import * as assert from "node:assert" * * assert.deepStrictEqual(Result.getOrNull(Result.succeed(1)), 1) * assert.deepStrictEqual(Result.getOrNull(Result.fail("a")), null) @@ -825,8 +846,8 @@ export const getOrNull: (self: Result) => A | null = getOrElse(const * * @example * ```ts - * import * as assert from "node:assert" * import { Result } from "effect" + * import * as assert from "node:assert" * * assert.deepStrictEqual(Result.getOrUndefined(Result.succeed(1)), 1) * assert.deepStrictEqual(Result.getOrUndefined(Result.fail("a")), undefined) @@ -846,10 +867,13 @@ export const getOrUndefined: (self: Result) => A | undefined = getOr * ```ts * import { Result } from "effect" * - * Result.getOrThrowWith(Result.succeed(1), () => new Error('Unexpected Err')) + * Result.getOrThrowWith(Result.succeed(1), () => new Error("Unexpected Err")) * // => 1 * - * Result.getOrThrowWith(Result.fail("error"), (err) => new Error(`Unexpected Err: ${err}`)) + * Result.getOrThrowWith( + * Result.fail("error"), + * (err) => new Error(`Unexpected Err: ${err}`) + * ) * // => throws new Error('Unexpected Err: error') * ``` * @@ -874,8 +898,8 @@ export const getOrThrowWith: { * * @example * ```ts - * import * as assert from "node:assert" * import { Result } from "effect" + * import * as assert from "node:assert" * * assert.deepStrictEqual(Result.getOrThrow(Result.succeed(1)), 1) * assert.throws(() => Result.getOrThrow(Result.fail("error"))) @@ -894,8 +918,7 @@ export const getOrThrow: (self: Result) => A = getOrThrowWith(identi * @example * ```ts * import * as assert from "node:assert" - * import { pipe } from "effect" - * import { Result } from "effect" + * import { pipe, Result } from "effect" * * const success = pipe( * Result.succeed(1), @@ -927,14 +950,15 @@ export const orElse: { * * @example * ```ts + * import { pipe, Result } from "effect" * import * as assert from "node:assert" - * import { pipe } from "effect" - * import { Result } from "effect" * * const parseAndDouble = (s: string) => * pipe( * Result.try(() => parseInt(s)), - * Result.flatMap(n => n > 0 ? Result.succeed(n * 2) : Result.fail("not positive")) + * Result.flatMap((n) => + * n > 0 ? Result.succeed(n * 2) : Result.fail("not positive") + * ) * ) * * assert.deepStrictEqual(parseAndDouble("5"), Result.succeed(10)) @@ -958,19 +982,18 @@ export const flatMap: { * * @example * ```ts + * import { pipe, Result } from "effect" * import * as assert from "node:assert" - * import { pipe } from "effect" - * import { Result } from "effect" * * const success = pipe( * Result.succeed(1), - * Result.andThen(n => Result.succeed(n + 1)) + * Result.andThen((n) => Result.succeed(n + 1)) * ) * assert.deepStrictEqual(success, Result.succeed(2)) * * const failure = pipe( * Result.fail("error"), - * Result.andThen(n => Result.succeed(n + 1)) + * Result.andThen((n) => Result.succeed(n + 1)) * ) * assert.deepStrictEqual(failure, Result.fail("error")) * ``` @@ -1008,12 +1031,21 @@ export const andThen: { * * @example * ```ts - * import * as assert from "node:assert" * import { Result } from "effect" + * import * as assert from "node:assert" * - * assert.deepStrictEqual(Result.all([Result.succeed(1), Result.succeed(2)]), Result.succeed([1, 2])) - * assert.deepStrictEqual(Result.all({ right: Result.succeed(1), b: Result.succeed("hello") }), Result.succeed({ right: 1, b: "hello" })) - * assert.deepStrictEqual(Result.all({ right: Result.succeed(1), b: Result.fail("error") }), Result.fail("error")) + * assert.deepStrictEqual( + * Result.all([Result.succeed(1), Result.succeed(2)]), + * Result.succeed([1, 2]) + * ) + * assert.deepStrictEqual( + * Result.all({ right: Result.succeed(1), b: Result.succeed("hello") }), + * Result.succeed({ right: 1, b: "hello" }) + * ) + * assert.deepStrictEqual( + * Result.all({ right: Result.succeed(1), b: Result.fail("error") }), + * Result.fail("error") + * ) * ``` * * @category Sequencing @@ -1061,8 +1093,8 @@ export const all: > | Record(self: Result): Result => * * @example * ```ts - * import * as assert from "node:assert" * import { Result } from "effect" + * import * as assert from "node:assert" * - * const program = Result.gen(function* () { + * const program = Result.gen(function*() { * const a = yield* Result.succeed(1) * const b = yield* Result.succeed(2) * return a + b @@ -1134,8 +1166,7 @@ export const gen: Gen.Gen = (...args) => { * @example * ```ts * import * as assert from "node:assert" - * import { pipe } from "effect" - * import { Result } from "effect" + * import { pipe, Result } from "effect" * * const result = pipe( * Result.Do, @@ -1168,8 +1199,7 @@ export const Do: Result<{}> = succeed({}) * @example * ```ts * import * as assert from "node:assert" - * import { pipe } from "effect" - * import { Result } from "effect" + * import { pipe, Result } from "effect" * * const result = pipe( * Result.Do, @@ -1212,8 +1242,7 @@ export const bind: { * @example * ```ts * import * as assert from "node:assert" - * import { pipe } from "effect" - * import { Result } from "effect" + * import { pipe, Result } from "effect" * * const result = pipe( * Result.Do, @@ -1262,8 +1291,7 @@ export { * @example * ```ts * import * as assert from "node:assert" - * import { pipe } from "effect" - * import { Result } from "effect" + * import { pipe, Result } from "effect" * * const result = pipe( * Result.Do, @@ -1272,7 +1300,6 @@ export { * Result.let("sum", ({ x, y }) => x + y) * ) * assert.deepStrictEqual(result, Result.succeed({ x: 2, y: 3, sum: 5 })) - * * ``` * @category Do Notation * @since 4.0.0 @@ -1292,9 +1319,7 @@ export { * * @example * ```ts - * import { Effect } from "effect" - * import { Result } from "effect" - * import { Option } from "effect" + * import { Option, Result } from "effect" * * // ┌─── Option> * // ▼ @@ -1319,8 +1344,7 @@ export const transposeOption = ( * * @example * ```ts - * import { Result } from "effect" - * import { Option } from "effect" + * import { Option, Result } from "effect" * * const parseNumber = (s: string) => * isNaN(Number(s)) ? Result.fail("Invalid number") : Result.succeed(Number(s)) @@ -1357,8 +1381,7 @@ export const transposeMapOption = dual< * @example * ```ts * import * as assert from "node:assert" - * import { Result } from "effect" - * import { Option } from "effect" + * import { Option, Result } from "effect" * * const result = Result.succeedNone * assert.deepStrictEqual(result, Result.succeed(Option.none())) @@ -1375,8 +1398,7 @@ export const succeedNone = succeed(option_.none) * @example * ```ts * import * as assert from "node:assert" - * import { Result } from "effect" - * import { Option } from "effect" + * import { Option, Result } from "effect" * * const result = Result.succeedSome(42) * assert.deepStrictEqual(result, Result.succeed(Option.some(42))) @@ -1392,14 +1414,15 @@ export const succeedSome = (a: A): Result, E> => succeed * * @example * ```ts + * import { pipe, Result } from "effect" * import * as assert from "node:assert" - * import { pipe } from "effect" - * import { Result } from "effect" * * let sideEffect = 0 * const success = pipe( * Result.succeed(42), - * Result.tap(n => { sideEffect = n }) + * Result.tap((n) => { + * sideEffect = n + * }) * ) * * assert.deepStrictEqual(success, Result.succeed(42)) diff --git a/packages/effect/src/Runtime.ts b/packages/effect/src/Runtime.ts index 132746a1bb..0bcaa6c562 100644 --- a/packages/effect/src/Runtime.ts +++ b/packages/effect/src/Runtime.ts @@ -7,14 +7,12 @@ * * @example * ```ts - * import { Effect } from "effect" - * import { Runtime } from "effect" - * import { Fiber } from "effect" + * 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))) + * 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)) @@ -45,8 +43,7 @@ import type * as Fiber from "./Fiber.ts" * * @example * ```ts - * import { Effect, Exit } from "effect" - * import { Runtime } from "effect" + * import { Effect, Exit, Runtime } from "effect" * * // Custom teardown that logs completion status * const customTeardown: Runtime.Teardown = (exit, onExit) => { @@ -89,8 +86,7 @@ export interface Teardown { * * @example * ```ts - * import { Effect, Exit, Cause } from "effect" - * import { Runtime } from "effect" + * import { Effect, Exit, Runtime } from "effect" * * // The default teardown behavior * const program1 = Effect.succeed(42) @@ -135,9 +131,7 @@ export const defaultTeardown: Teardown = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Runtime } from "effect" - * import { Fiber } from "effect" + * import { Effect, Fiber, Runtime } from "effect" * * // Create a simple runner for a hypothetical platform * const runMain = Runtime.makeRunMain(({ fiber, teardown }) => { @@ -160,7 +154,7 @@ export const defaultTeardown: Teardown = ( * }) * * // Use the runner - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * yield* Effect.log("Starting program") * yield* Effect.sleep(1000) * yield* Effect.log("Program completed") diff --git a/packages/effect/src/Schedule.ts b/packages/effect/src/Schedule.ts index fc0ae40c03..92953681d3 100644 --- a/packages/effect/src/Schedule.ts +++ b/packages/effect/src/Schedule.ts @@ -8,9 +8,7 @@ * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Duration } from "effect" + * import { Effect, Schedule } from "effect" * * // Retry with exponential backoff * const retryPolicy = Schedule.exponential("100 millis", 2.0) @@ -53,9 +51,7 @@ const TypeId = "~effect/Schedule" * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * // Basic retry schedule - retry up to 3 times with exponential backoff * const retrySchedule = Schedule.exponential("100 millis").pipe( @@ -63,13 +59,13 @@ const TypeId = "~effect/Schedule" * ) * * // Basic repeat schedule - repeat every 30 seconds forever - * const repeatSchedule: Schedule.Schedule = - * Schedule.spaced("30 seconds") + * const repeatSchedule: Schedule.Schedule = Schedule + * .spaced("30 seconds") * * // Advanced schedule with custom logic * const smartRetry = Schedule.exponential("1 second") * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * // Using retry schedule * const result1 = yield* Effect.retry( * Effect.fail("temporary error"), @@ -95,10 +91,7 @@ export interface Schedule { * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Duration } from "effect" - * import { Console } from "effect" + * import { Console, Duration, Effect, Schedule } from "effect" * * // Custom schedule that logs metadata including output * const loggingSchedule = Schedule.unfold(0, (n) => n + 1).pipe( @@ -154,7 +144,7 @@ export interface InputMetadata { * }) * ) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * yield* Effect.repeat( * Effect.succeed("task completed"), * loggingSchedule.pipe(Schedule.take(3)) @@ -197,9 +187,7 @@ export const CurrentMetadata = ServiceMap.Reference("effect/Schedule/C * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Duration } from "effect" + * import { Duration, Effect, Schedule } from "effect" * * // Usage of the Schedule namespace for creating schedules * @@ -208,11 +196,11 @@ export const CurrentMetadata = ServiceMap.Reference("effect/Schedule/C * Schedule.addDelay((n) => Duration.millis(n * 100)) * ) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * let attempt = 0 * * yield* Effect.retry( - * Effect.gen(function* () { + * Effect.gen(function*() { * attempt++ * if (attempt < 3) { * yield* Effect.fail(`Attempt ${attempt} failed`) @@ -233,9 +221,7 @@ export declare namespace Schedule { * * @example * ```ts - * import { Effect } from "effect" * import { Schedule } from "effect" - * import { Duration } from "effect" * * // Understanding Schedule variance: * // - Output: covariant (can be a subtype) @@ -244,18 +230,17 @@ export declare namespace Schedule { * // - Env: covariant (can be a subtype) * * // Schedule that produces strings, accepts any input - * const stringSchedule = - * Schedule.spaced("1 second").pipe(Schedule.map(() => "tick")) + * const stringSchedule = Schedule.spaced("1 second").pipe( + * Schedule.map(() => "tick") + * ) * * // Schedule that only accepts Error inputs - * const errorSchedule = - * Schedule.exponential("100 millis").pipe( - * Schedule.take(5) - * ) + * const errorSchedule = Schedule.exponential("100 millis").pipe( + * Schedule.take(5) + * ) * * // Schedule requiring a service environment - * const serviceSchedule = - * Schedule.spaced("5 seconds") + * const serviceSchedule = Schedule.spaced("5 seconds") * ``` * * @since 2.0.0 @@ -276,11 +261,17 @@ export declare namespace Schedule { * // This internal interface is used for type variance annotations * * // Example showing variance relationships: - * interface Animal { name: string } - * interface Dog extends Animal { breed: string } + * 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(() => "output")) + * const stringSchedule = Schedule.spaced("1 second").pipe( + * Schedule.map(() => "output") + * ) * * // Input is contravariant - more general types can be accepted * const numberSchedule = Schedule.exponential("100 millis") @@ -336,7 +327,6 @@ export const isSchedule = (u: unknown): u is Schedule { * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" + * import { Effect, Schedule } from "effect" * * // fromStepWithMetadata is an advanced function for creating schedules * // that need access to execution metadata like timing and recurrence count @@ -423,13 +412,12 @@ export const fromStepWithMetadata = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" + * import { Effect, Schedule } from "effect" * * // Extract step function from an existing schedule * const schedule = Schedule.exponential("100 millis").pipe(Schedule.take(3)) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const stepFn = yield* Schedule.toStep(schedule) * * // Use the step function directly for custom logic @@ -496,13 +484,12 @@ export const toStepWithMetadata = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" + * import { Effect, Schedule } from "effect" * * // Convert schedule to step function with automatic sleeping * const schedule = Schedule.spaced("1 second").pipe(Schedule.take(3)) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const stepWithSleep = yield* Schedule.toStepWithSleep(schedule) * * // Each call will automatically sleep for the scheduled delay @@ -539,9 +526,7 @@ export const toStepWithSleep = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * // Add random jitter to schedule delays * const jitteredSchedule = Schedule.addDelay( @@ -553,14 +538,16 @@ export const toStepWithSleep = ( * } * ) * - * const jitterProgram = Effect.gen(function* () { + * const jitterProgram = Effect.gen(function*() { * yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log(`Task executed at ${new Date().toISOString()}`) * return "jittered task" * }), * jitteredSchedule.pipe( - * Schedule.tapOutput((delay) => Console.log(`Base delay with jitter applied`)) + * Schedule.tapOutput((delay) => + * Console.log(`Base delay with jitter applied`) + * ) * ) * ) * }) @@ -575,14 +562,16 @@ export const toStepWithSleep = ( * } * ) * - * const adaptiveProgram = Effect.gen(function* () { + * const adaptiveProgram = Effect.gen(function*() { * yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log("Adaptive delay task") * return "adaptive" * }), * adaptiveSchedule.pipe( - * Schedule.tapOutput((count) => Console.log(`Execution ${count + 1} with adaptive delay`)) + * Schedule.tapOutput((count) => + * Console.log(`Execution ${count + 1} with adaptive delay`) + * ) * ) * ) * }) @@ -598,9 +587,9 @@ export const toStepWithSleep = ( * } * ) * - * const dynamicProgram = Effect.gen(function* () { + * const dynamicProgram = Effect.gen(function*() { * yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log("Dynamic delay task") * return "dynamic" * }), @@ -621,9 +610,9 @@ export const toStepWithSleep = ( * } * ) * - * const resultProgram = Effect.gen(function* () { + * const resultProgram = Effect.gen(function*() { * yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log("Result-based delay task") * return Math.random() * }), @@ -642,11 +631,11 @@ export const toStepWithSleep = ( * } * ) * - * const retryProgram = Effect.gen(function* () { + * const retryProgram = Effect.gen(function*() { * let attempt = 0 * * const result = yield* Effect.retry( - * Effect.gen(function* () { + * Effect.gen(function*() { * attempt++ * if (attempt < 5) { * yield* Effect.fail(new Error(`Attempt ${attempt} failed`)) @@ -692,9 +681,7 @@ export const addDelay: { * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * // First retry 3 times quickly, then switch to slower retries * const quickRetries = Schedule.exponential("100 millis").pipe( @@ -706,10 +693,10 @@ export const addDelay: { * * const combinedRetries = Schedule.andThen(quickRetries, slowRetries) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * let attempt = 0 * yield* Effect.retry( - * Effect.gen(function* () { + * Effect.gen(function*() { * attempt++ * yield* Console.log(`Attempt ${attempt}`) * if (attempt < 6) { @@ -752,10 +739,7 @@ export const andThen: { * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Result } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Result, Schedule } from "effect" * * // Track which phase of the schedule we're in * const phaseTracker = Schedule.andThenResult( @@ -763,9 +747,9 @@ export const andThen: { * Schedule.spaced("500 millis").pipe(Schedule.take(2)) * ) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log("Task executed") * return "task-result" * }), @@ -835,9 +819,7 @@ export const andThenResult: { * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * // Both schedules must want to continue for the combined schedule to continue * const timeLimit = Schedule.spaced("1 second").pipe(Schedule.take(5)) // max 5 times @@ -847,9 +829,9 @@ export const andThenResult: { * const bothSchedule = Schedule.both(timeLimit, attemptLimit) * // Outputs: [time_result, attempt_count] tuple * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const results = yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log(`Task executed at ${new Date().toISOString()}`) * return "task completed" * }), @@ -870,11 +852,11 @@ export const andThenResult: { * // Will use the slower (maximum) delay and stop when first schedule exhausts * const conservativeSchedule = Schedule.both(fastSchedule, slowSchedule) * - * const retryProgram = Effect.gen(function* () { + * const retryProgram = Effect.gen(function*() { * let attempt = 0 * * const result = yield* Effect.retry( - * Effect.gen(function* () { + * Effect.gen(function*() { * attempt++ * yield* Console.log(`Retry attempt ${attempt}`) * @@ -920,9 +902,7 @@ export const both: { * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * // Combine two schedules, keeping left output * const leftSchedule = Schedule.exponential("100 millis").pipe( @@ -932,9 +912,9 @@ export const both: { * * const combined = Schedule.bothLeft(leftSchedule, rightSchedule) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log("Task executed") * return "task-done" * }), @@ -968,9 +948,7 @@ export const bothLeft: { * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * // Combine two schedules, keeping right output * const leftSchedule = Schedule.exponential("100 millis").pipe( @@ -982,9 +960,9 @@ export const bothLeft: { * * const combined = Schedule.bothRight(leftSchedule, rightSchedule) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log("Task executed") * return "task-done" * }), @@ -1019,9 +997,7 @@ export const bothRight: { * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * // Combine two schedules with custom output combination * const leftSchedule = Schedule.exponential("100 millis").pipe( @@ -1037,9 +1013,9 @@ export const bothRight: { * (left, right) => `${left}-${right}` * ) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log("Task executed") * return "task-result" * }), @@ -1098,9 +1074,7 @@ export const bothWith: { * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * // Compose a quick retry phase followed by slower retry phase * const fastRetries = Schedule.exponential("100 millis").pipe( @@ -1115,11 +1089,11 @@ export const bothWith: { * const composedRetry = Schedule.compose(fastRetries, slowRetries) * // Outputs: [number_from_fast_phase, number_from_slow_phase] * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * let attempt = 0 * * const result = yield* Effect.retry( - * Effect.gen(function* () { + * Effect.gen(function*() { * attempt++ * yield* Console.log(`Attempt ${attempt}`) * @@ -1176,19 +1150,17 @@ export const compose: { * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * // Collect all inputs passed to the schedule * const inputCollector = Schedule.collectInputs( * Schedule.spaced("100 millis") * ) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * let counter = 0 * yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * counter++ * yield* Console.log(`Iteration ${counter}`) * return `result-${counter}` @@ -1211,18 +1183,16 @@ export const collectInputs = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * // Collect all outputs from the schedule * const outputCollector = Schedule.collectOutputs( * Schedule.recurs(4) * ) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log("Task executed") * return "task-result" * }), @@ -1244,9 +1214,7 @@ export const collectOutputs = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * // Collect outputs while under time limit * const collectForTime = Schedule.collectWhile( @@ -1254,9 +1222,9 @@ export const collectOutputs = ( * (metadata) => metadata.elapsed < 3000 // Stop after 3 seconds * ) * - * const timeBasedProgram = Effect.gen(function* () { + * const timeBasedProgram = Effect.gen(function*() { * const results = yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * const value = Math.floor(Math.random() * 100) * yield* Console.log(`Generated value: ${value}`) * return value @@ -1264,7 +1232,9 @@ export const collectOutputs = ( * collectForTime * ) * - * yield* Console.log(`Collected ${results.length} values: [${results.join(", ")}]`) + * yield* Console.log( + * `Collected ${results.length} values: [${results.join(", ")}]` + * ) * }) * * // Collect outputs while condition is met @@ -1276,11 +1246,11 @@ export const collectOutputs = ( * } * ) * - * const conditionalProgram = Effect.gen(function* () { + * const conditionalProgram = Effect.gen(function*() { * let attempt = 0 * * const delays = yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * attempt++ * yield* Console.log(`Retry attempt ${attempt}`) * return `${Date.now()}` @@ -1295,16 +1265,18 @@ export const collectOutputs = ( * const collectWithCheck = Schedule.collectWhile( * Schedule.fixed("1 second"), * (metadata) => - * Effect.gen(function* () { + * Effect.gen(function*() { * const shouldContinue = metadata.attempt < 5 - * yield* Console.log(`Check ${metadata.attempt}: continue = ${shouldContinue}`) + * yield* Console.log( + * `Check ${metadata.attempt}: continue = ${shouldContinue}` + * ) * return shouldContinue * }) * ) * - * const effectfulProgram = Effect.gen(function* () { + * const effectfulProgram = Effect.gen(function*() { * const timestamps = yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * const now = new Date().toISOString() * yield* Console.log(`Task at ${now}`) * return now @@ -1324,9 +1296,9 @@ export const collectOutputs = ( * } * ) * - * const samplingProgram = Effect.gen(function* () { + * const samplingProgram = Effect.gen(function*() { * const samples = yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * const sample = Math.random() * 100 * yield* Console.log(`Sample: ${sample.toFixed(1)}`) * return sample @@ -1335,7 +1307,9 @@ export const collectOutputs = ( * ) * * const average = samples.reduce((sum, s) => sum + s, 0) / samples.length - * yield* Console.log(`Collected ${samples.length} samples, average: ${average.toFixed(1)}`) + * yield* Console.log( + * `Collected ${samples.length} samples, average: ${average.toFixed(1)}` + * ) * }) * ``` * @@ -1373,16 +1347,14 @@ export const collectWhile: { * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * // Run every minute * const everyMinute = Schedule.cron("* * * * *") * - * const minutelyProgram = Effect.gen(function* () { + * const minutelyProgram = Effect.gen(function*() { * yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log(`Minutely task at ${new Date().toISOString()}`) * return "minute" * }), @@ -1398,9 +1370,9 @@ export const collectWhile: { * // Run every day at 2:30 AM * const dailyBackup = Schedule.cron("30 2 * * *") * - * const backupProgram = Effect.gen(function* () { + * const backupProgram = Effect.gen(function*() { * yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log("Running daily backup...") * // Simulate backup process * yield* Effect.sleep("2 seconds") @@ -1416,9 +1388,9 @@ export const collectWhile: { * // Run every Monday at 9:00 AM with timezone * const weeklyReport = Schedule.cron("0 9 * * 1", "America/New_York") * - * const reportProgram = Effect.gen(function* () { + * const reportProgram = Effect.gen(function*() { * yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log("Generating weekly report...") * const report = { * week: Math.floor(Date.now() / (7 * 24 * 60 * 60 * 1000)), @@ -1434,9 +1406,9 @@ export const collectWhile: { * // Run every 15 minutes during business hours (9 AM - 5 PM) * const businessHoursCheck = Schedule.cron("0,15,30,45 9-17 * * 1-5") * - * const businessProgram = Effect.gen(function* () { + * const businessProgram = Effect.gen(function*() { * yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log("Business hours health check...") * const status = Math.random() > 0.1 ? "healthy" : "degraded" * yield* Console.log(`System status: ${status}`) @@ -1451,9 +1423,9 @@ export const collectWhile: { * // Run on specific days of the month * const monthlyInvoice = Schedule.cron("0 10 1,15 * *") // 1st and 15th at 10 AM * - * const invoiceProgram = Effect.gen(function* () { + * const invoiceProgram = Effect.gen(function*() { * yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log("Processing monthly invoices...") * const invoiceCount = Math.floor(Math.random() * 100) + 50 * yield* Console.log(`Processed ${invoiceCount} invoices`) @@ -1470,9 +1442,9 @@ export const collectWhile: { * ) * ) * - * const robustProgram = Effect.gen(function* () { + * const robustProgram = Effect.gen(function*() { * yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log("Complex scheduled task...") * // Simulate occasional failures * if (Math.random() < 0.3) { @@ -1482,7 +1454,9 @@ export const collectWhile: { * }), * complexCron.pipe(Schedule.take(3)) * ).pipe( - * Effect.catch((error: unknown) => Console.log(`Cron task error: ${String(error)}`)) + * Effect.catch((error: unknown) => + * Console.log(`Cron task error: ${String(error)}`) + * ) * ) * }) * ``` @@ -1508,18 +1482,16 @@ export const cron: { * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * // Extract delays from an exponential backoff schedule * const exponentialDelays = Schedule.delays( * Schedule.exponential("100 millis").pipe(Schedule.take(5)) * ) * - * const delayProgram = Effect.gen(function* () { + * const delayProgram = Effect.gen(function*() { * yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log("Task executed") * return "task result" * }), @@ -1536,13 +1508,11 @@ export const cron: { * Schedule.fibonacci("200 millis").pipe(Schedule.take(8)) * ) * - * const fibDelayProgram = Effect.gen(function* () { + * const fibDelayProgram = Effect.gen(function*() { * yield* Effect.repeat( * Console.log("Fibonacci task"), * fibonacciDelays.pipe( - * Schedule.tapOutput((delay) => - * Console.log(`Fibonacci delay: ${delay}`) - * ) + * Schedule.tapOutput((delay) => Console.log(`Fibonacci delay: ${delay}`)) * ) * ) * }) @@ -1552,7 +1522,7 @@ export const cron: { * Schedule.spaced("1 second").pipe(Schedule.take(3)) * ).pipe( * Schedule.tapOutput((delay) => - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log(`Recorded delay: ${delay}`) * // In real applications, might send to metrics system * }) @@ -1566,16 +1536,14 @@ export const cron: { * * const adaptiveDelays = Schedule.delays(adaptiveSchedule) * - * const adaptiveProgram = Effect.gen(function* () { + * const adaptiveProgram = Effect.gen(function*() { * yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log("Adaptive task execution") * return Date.now() * }), * adaptiveDelays.pipe( - * Schedule.tapOutput((delay) => - * Console.log(`Adaptive delay: ${delay}`) - * ) + * Schedule.tapOutput((delay) => Console.log(`Adaptive delay: ${delay}`)) * ) * ) * }) @@ -1610,18 +1578,16 @@ export const delays = (self: Schedule): Schedule(self: Schedule): Schedule(self: Schedule): Schedule `${primary}+${fallback}` * ) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log("Task executed") * return "task-result" * }), @@ -1982,10 +1942,7 @@ export const eitherWith: { * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Duration } from "effect" - * import { Console } from "effect" + * import { Console, Duration, Effect, Schedule } from "effect" * * const program = Effect.gen(function*() { * yield* Effect.repeat( @@ -2015,9 +1972,7 @@ export const elapsed: Schedule = fromStepWithMetadata( * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * // Basic exponential backoff with default factor of 2 * const basicExponential = Schedule.exponential("100 millis") @@ -2032,11 +1987,11 @@ export const elapsed: Schedule = fromStepWithMetadata( * Schedule.compose(Schedule.recurs(5)) * ) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * let attempt = 0 * * const result = yield* Effect.retry( - * Effect.gen(function* () { + * Effect.gen(function*() { * attempt++ * if (attempt < 4) { * yield* Console.log(`Attempt ${attempt} failed, retrying...`) @@ -2074,20 +2029,18 @@ export const exponential = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * // 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 - * const retryWithFib = Effect.gen(function* () { + * const retryWithFib = Effect.gen(function*() { * let attempt = 0 * * const result = yield* Effect.retry( - * Effect.gen(function* () { + * Effect.gen(function*() { * attempt++ * yield* Console.log(`Attempt ${attempt}`) * @@ -2099,9 +2052,7 @@ export const exponential = ( * }), * Schedule.fibonacci("50 millis").pipe( * Schedule.compose(Schedule.recurs(6)), // Maximum 6 retries - * Schedule.tapOutput((delay) => - * Console.log(`Next retry in ${delay}`) - * ) + * Schedule.tapOutput((delay) => Console.log(`Next retry in ${delay}`)) * ) * ) * @@ -2109,7 +2060,7 @@ export const exponential = ( * }) * * // Heartbeat with fibonacci intervals (starts fast, gets slower) - * const adaptiveHeartbeat = Effect.gen(function* () { + * const adaptiveHeartbeat = Effect.gen(function*() { * yield* Console.log(`Heartbeat at ${new Date().toISOString()}`) * return "pulse" * }).pipe( @@ -2121,7 +2072,7 @@ export const exponential = ( * ) * * // Fibonacci vs exponential comparison - * const compareSchedules = Effect.gen(function* () { + * const compareSchedules = Effect.gen(function*() { * yield* Console.log("=== Fibonacci Delays ===") * // 100ms, 100ms, 200ms, 300ms, 500ms, 800ms * @@ -2164,15 +2115,13 @@ export const fibonacci = (one: Duration.DurationInput): Schedule => { * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * // Transform schedule output from number to string * const countSchedule = Schedule.recurs(5).pipe( @@ -2255,13 +2202,15 @@ export const fixed = (interval: Duration.DurationInput): Schedule => { * })) * ) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const results = yield* Effect.repeat( * Effect.succeed("task completed"), * structuredSchedule.pipe( * Schedule.take(8), * Schedule.tapOutput((info) => - * Console.log(`${info.phase} phase - iteration ${info.iteration} at ${info.timestamp}`) + * Console.log( + * `${info.phase} phase - iteration ${info.iteration} at ${info.timestamp}` + * ) * ) * ) * ) @@ -2272,7 +2221,7 @@ export const fixed = (interval: Duration.DurationInput): Schedule => { * // Map with effectful transformation * const effectfulMap = Schedule.fixed("2 seconds").pipe( * Schedule.map((count) => - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log(`Processing count: ${count}`) * return count * 10 * }) @@ -2324,10 +2273,7 @@ export const map: { * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Duration } from "effect" - * import { Console } from "effect" + * import { Console, Duration, Effect, Schedule } from "effect" * * // Modify delays based on output - increase delay on high iteration counts * const adaptiveDelay = Schedule.recurs(10).pipe( @@ -2337,10 +2283,10 @@ export const map: { * }) * ) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * let counter = 0 * yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * counter++ * yield* Console.log(`Attempt ${counter}`) * return counter @@ -2392,19 +2338,17 @@ export const modifyDelay: { * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * // Create a schedule that outputs the inputs instead of original outputs * const inputSchedule = Schedule.passthrough( * Schedule.exponential("100 millis").pipe(Schedule.take(3)) * ) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * let counter = 0 * yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * counter++ * yield* Console.log(`Task ${counter} executed`) * return `result-${counter}` @@ -2433,19 +2377,17 @@ export const passthrough = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * // Basic recurs - retry at most 3 times * const maxThreeAttempts = Schedule.recurs(3) * * // Retry a failing operation at most 5 times - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * let attempt = 0 * * const result = yield* Effect.retry( - * Effect.gen(function* () { + * Effect.gen(function*() { * attempt++ * yield* Console.log(`Attempt ${attempt}`) * @@ -2467,7 +2409,7 @@ export const passthrough = ( * ) * * // Repeat an effect exactly 10 times - * const exactlyTenTimes = Effect.gen(function* () { + * const exactlyTenTimes = Effect.gen(function*() { * yield* Console.log("Executing task...") * return Math.random() * }).pipe( @@ -2492,9 +2434,7 @@ export const recurs = (times: number): Schedule => while_(forever, ({ at * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * // Sum up execution counts from a counter schedule * const sumSchedule = Schedule.reduce( @@ -2503,9 +2443,9 @@ export const recurs = (times: number): Schedule => while_(forever, ({ at * (sum, count) => sum + count // Add each count to the sum * ) * - * const sumProgram = Effect.gen(function* () { + * const sumProgram = Effect.gen(function*() { * const finalSum = yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log("Task executed") * return "task" * }), @@ -2520,20 +2460,22 @@ export const recurs = (times: number): Schedule => while_(forever, ({ at * // Build a history of execution times * const historySchedule = Schedule.reduce( * Schedule.spaced("1 second").pipe(Schedule.take(4)), - * () => [] as number[], // Initial empty array + * () => [] as Array, // Initial empty array * (history, executionNumber) => [...history, Date.now()] * ) * - * const historyProgram = Effect.gen(function* () { + * const historyProgram = Effect.gen(function*() { * const timeline = yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log("Recording timestamp...") * return "recorded" * }), * historySchedule * ) * - * yield* Console.log(`Execution timeline: ${timeline.length} timestamps recorded`) + * yield* Console.log( + * `Execution timeline: ${timeline.length} timestamps recorded` + * ) * }) * * // Accumulate metrics with effectful combination @@ -2551,9 +2493,9 @@ export const recurs = (times: number): Schedule => while_(forever, ({ at * } * ) * - * const metricsProgram = Effect.gen(function* () { + * const metricsProgram = Effect.gen(function*() { * const finalMetrics = yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log("Processing...") * return "processed" * }), @@ -2562,7 +2504,9 @@ export const recurs = (times: number): Schedule => while_(forever, ({ at * * const average = finalMetrics.total / finalMetrics.count * yield* Console.log(`Final metrics: ${finalMetrics.count} executions`) - * yield* Console.log(`Average delay: ${average.toFixed(1)}ms, Max delay: ${finalMetrics.max}ms`) + * yield* Console.log( + * `Average delay: ${average.toFixed(1)}ms, Max delay: ${finalMetrics.max}ms` + * ) * }) * * // Build configuration state over time @@ -2576,15 +2520,17 @@ export const recurs = (times: number): Schedule => while_(forever, ({ at * }) * ) * - * const configProgram = Effect.gen(function* () { + * const configProgram = Effect.gen(function*() { * const finalConfig = yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log("Updating configuration...") * return "updated" * }), * configBuilder.pipe( * Schedule.tapOutput((config) => - * Console.log(`Config: retries=${config.retries}, timeout=${config.timeout}ms`) + * Console.log( + * `Config: retries=${config.retries}, timeout=${config.timeout}ms` + * ) * ) * ) * ) @@ -2642,22 +2588,20 @@ export const reduce: { * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * // Basic spaced schedule - runs every 2 seconds * const everyTwoSeconds = Schedule.spaced("2 seconds") * * // Heartbeat that runs indefinitely with fixed spacing - * const heartbeat = Effect.gen(function* () { + * const heartbeat = Effect.gen(function*() { * yield* Console.log(`Heartbeat at ${new Date().toISOString()}`) * }).pipe( * Effect.repeat(everyTwoSeconds) * ) * * // Limited repeat - run only 5 times with 1-second spacing - * const limitedTask = Effect.gen(function* () { + * const limitedTask = Effect.gen(function*() { * yield* Console.log("Executing scheduled task...") * yield* Effect.sleep("500 millis") // simulate work * return "Task completed" @@ -2672,7 +2616,7 @@ export const reduce: { * Schedule.compose(Schedule.recurs(5)) // at most 5 times * ) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * yield* Console.log("Starting spaced execution...") * * yield* Effect.repeat( @@ -2699,9 +2643,7 @@ export const spaced = (duration: Duration.DurationInput): Schedule => { * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * // Log retry errors for debugging * const errorLoggingSchedule = Schedule.exponential("100 millis").pipe( @@ -2711,11 +2653,11 @@ export const spaced = (duration: Duration.DurationInput): Schedule => { * ) * ) * - * const retryProgram = Effect.gen(function* () { + * const retryProgram = Effect.gen(function*() { * let attempt = 0 * * const result = yield* Effect.retry( - * Effect.gen(function* () { + * Effect.gen(function*() { * attempt++ * if (attempt < 4) { * yield* Effect.fail(new Error(`Network timeout on attempt ${attempt}`)) @@ -2732,7 +2674,7 @@ export const spaced = (duration: Duration.DurationInput): Schedule => { * const inputMonitoringSchedule = Schedule.spaced("1 second").pipe( * Schedule.take(5), * Schedule.tapInput((input: unknown) => - * Effect.gen(function* () { + * 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 @@ -2744,8 +2686,8 @@ export const spaced = (duration: Duration.DurationInput): Schedule => { * const validatingSchedule = Schedule.fixed("500 millis").pipe( * Schedule.take(4), * Schedule.tapInput((input: any) => - * Effect.gen(function* () { - * if (typeof input === 'object' && input !== null) { + * Effect.gen(function*() { + * if (typeof input === "object" && input !== null) { * yield* Console.log(`Valid object input: ${JSON.stringify(input)}`) * } else { * yield* Console.log(`Warning: Non-object input received: ${input}`) @@ -2754,9 +2696,9 @@ export const spaced = (duration: Duration.DurationInput): Schedule => { * ) * ) * - * const validationProgram = Effect.gen(function* () { + * const validationProgram = Effect.gen(function*() { * yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log("Task with validation") * return { data: Math.random(), timestamp: Date.now() } * }), @@ -2768,7 +2710,7 @@ export const spaced = (duration: Duration.DurationInput): Schedule => { * const alertingSchedule = Schedule.exponential("200 millis").pipe( * Schedule.take(6), * Schedule.tapInput((error: Error) => - * Effect.gen(function* () { + * Effect.gen(function*() { * if (String(error).includes("critical")) { * yield* Console.log(`🚨 CRITICAL ERROR: ${String(error)}`) * // In real applications, might trigger alerts or notifications @@ -2779,26 +2721,32 @@ export const spaced = (duration: Duration.DurationInput): Schedule => { * ) * ) * - * const alertProgram = Effect.gen(function* () { + * const alertProgram = Effect.gen(function*() { * let attempt = 0 * * yield* Effect.retry( - * Effect.gen(function* () { + * Effect.gen(function*() { * attempt++ * const isCritical = attempt === 3 - * const errorType = isCritical ? "critical database failure" : "temporary network issue" + * const errorType = isCritical + * ? "critical database failure" + * : "temporary network issue" * yield* Effect.fail(new Error(errorType)) * }), * alertingSchedule * ).pipe( - * Effect.catch((error: unknown) => Console.log(`All retries exhausted: ${String(error)}`)) + * Effect.catch((error: unknown) => + * Console.log(`All retries exhausted: ${String(error)}`) + * ) * ) * }) * * // Chain multiple input taps for different purposes * const comprehensiveSchedule = Schedule.fibonacci("100 millis").pipe( * Schedule.take(5), - * Schedule.tapInput((error: Error) => Console.log(`Error occurred: ${error.name}`)), + * Schedule.tapInput((error: Error) => + * Console.log(`Error occurred: ${error.name}`) + * ), * Schedule.tapInput((error: Error) => * String(error).length > 20 * ? Console.log("📝 Long error message detected") @@ -2836,23 +2784,19 @@ export const tapInput: { * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * // Log schedule outputs for debugging/monitoring * const monitoredSchedule = Schedule.exponential("100 millis").pipe( * Schedule.take(5), - * Schedule.tapOutput((delay) => - * Console.log(`Next delay will be: ${delay}`) - * ) + * Schedule.tapOutput((delay) => Console.log(`Next delay will be: ${delay}`)) * ) * - * const retryProgram = Effect.gen(function* () { + * const retryProgram = Effect.gen(function*() { * let attempt = 0 * * const result = yield* Effect.retry( - * Effect.gen(function* () { + * Effect.gen(function*() { * attempt++ * if (attempt < 4) { * yield* Effect.fail(new Error(`Attempt ${attempt} failed`)) @@ -2869,7 +2813,7 @@ export const tapInput: { * const metricsSchedule = Schedule.spaced("1 second").pipe( * Schedule.take(10), * Schedule.tapOutput((executionCount) => - * Effect.gen(function* () { + * Effect.gen(function*() { * // Simulate metrics collection * yield* Console.log(`Recording metric: execution_count=${executionCount}`) * // In real code, this might send to monitoring system @@ -2881,7 +2825,7 @@ export const tapInput: { * const alertingSchedule = Schedule.fibonacci("200 millis").pipe( * Schedule.take(8), * Schedule.tapOutput((delay) => - * Effect.gen(function* () { + * Effect.gen(function*() { * const delayMs = delay.toString() * if (delayMs.includes("1000")) { // Alert on delays >= 1 second * yield* Console.log(`🚨 High delay detected: ${delay}`) @@ -2890,9 +2834,9 @@ export const tapInput: { * ) * ) * - * const healthCheckProgram = Effect.gen(function* () { + * const healthCheckProgram = Effect.gen(function*() { * yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log("Performing health check...") * // Simulate health check * return Math.random() > 0.7 ? "healthy" : "degraded" @@ -2942,18 +2886,16 @@ export const tapOutput: { * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * // Limit an infinite schedule to run only 5 times * const limitedHeartbeat = Schedule.spaced("1 second").pipe( * Schedule.take(5) // Will stop after 5 executions * ) * - * const heartbeatProgram = Effect.gen(function* () { + * const heartbeatProgram = Effect.gen(function*() { * yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log(`Heartbeat at ${new Date().toISOString()}`) * return "pulse" * }), @@ -2968,11 +2910,11 @@ export const tapOutput: { * Schedule.take(3) // At most 3 retry attempts * ) * - * const retryProgram = Effect.gen(function* () { + * const retryProgram = Effect.gen(function*() { * let attempt = 0 * * const result = yield* Effect.retry( - * Effect.gen(function* () { + * Effect.gen(function*() { * attempt++ * yield* Console.log(`Attempt ${attempt}`) * @@ -2987,7 +2929,9 @@ export const tapOutput: { * * yield* Console.log(`Result: ${result}`) * }).pipe( - * Effect.catch((error: unknown) => Console.log(`Failed after limited retries: ${String(error)}`)) + * Effect.catch((error: unknown) => + * Console.log(`Failed after limited retries: ${String(error)}`) + * ) * ) * * // Combine take with other schedule operations @@ -2996,9 +2940,9 @@ export const tapOutput: { * Schedule.map((count) => `Sample #${count + 1}`) * ) * - * const samplingProgram = Effect.gen(function* () { + * const samplingProgram = Effect.gen(function*() { * yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * const value = Math.random() * yield* Console.log(`Sampled value: ${value.toFixed(3)}`) * return value @@ -3032,17 +2976,15 @@ export const take: { * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * // Counter schedule that increments by 1 each time * const counterSchedule = Schedule.unfold(0, (n) => n + 1) * // Outputs: 0, 1, 2, 3, 4, 5, ... * - * const countingProgram = Effect.gen(function* () { + * const countingProgram = Effect.gen(function*() { * yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log("Task executed") * return "done" * }), @@ -3057,7 +2999,7 @@ export const take: { * const fibonacciSchedule = Schedule.unfold([0, 1], ([a, b]) => [b, a + b]) * // Outputs: [0,1], [1,1], [1,2], [2,3], [3,5], [5,8], ... * - * const fibProgram = Effect.gen(function* () { + * const fibProgram = Effect.gen(function*() { * yield* Effect.repeat( * Console.log("Fibonacci step"), * fibonacciSchedule.pipe( @@ -3068,37 +3010,45 @@ export const take: { * }) * * // Effectful unfold - exponential backoff with state - * const exponentialState = Schedule.unfold(100, (delayMs) => - * Effect.gen(function* () { - * yield* Console.log(`Current delay: ${delayMs}ms`) - * return Math.min(delayMs * 2, 5000) // Cap at 5 seconds - * }) + * const exponentialState = Schedule.unfold( + * 100, + * (delayMs) => + * Effect.gen(function*() { + * yield* Console.log(`Current delay: ${delayMs}ms`) + * return Math.min(delayMs * 2, 5000) // Cap at 5 seconds + * }) * ) * * // Random jitter schedule - * const jitteredSchedule = Schedule.unfold(1000, (baseDelay) => - * 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 jitteredSchedule = Schedule.unfold( + * 1000, + * (baseDelay) => + * 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 + * }) * ) * * // State machine schedule * type State = "init" | "warming" | "active" | "cooling" * const stateMachineSchedule = Schedule.unfold("init" as State, (state) => { * switch (state) { - * case "init": return "warming" - * case "warming": return "active" - * case "active": return "cooling" - * case "cooling": return "active" + * case "init": + * return "warming" + * case "warming": + * return "active" + * case "active": + * return "cooling" + * case "cooling": + * return "active" * } * }) * - * const stateMachineProgram = Effect.gen(function* () { + * const stateMachineProgram = Effect.gen(function*() { * yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log("State machine step") * return "step" * }), @@ -3193,16 +3143,14 @@ export { * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * // Execute tasks at regular intervals aligned to window boundaries * const windowSchedule = Schedule.windowed("5 seconds") * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * const now = new Date().toISOString() * yield* Console.log(`Window task executed at: ${now}`) * return "window-task" @@ -3233,16 +3181,14 @@ export const windowed = (interval: Duration.DurationInput): Schedule => * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Schedule } from "effect" * * // A schedule that runs forever with no delay * const infiniteSchedule = Schedule.forever * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * yield* Effect.repeat( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Console.log("Running forever...") * return "continuous-task" * }), @@ -3292,7 +3238,6 @@ export const satisfiesInputType = () => * @example * ```ts * import { Schedule } from "effect" - * import { Duration } from "effect" * * // satisfiesOutputType is a type-level function for compile-time constraints * // It ensures that a schedule's output type matches the specified type @@ -3317,8 +3262,7 @@ export const satisfiesOutputType = () => * * @example * ```ts - * import { Schedule } from "effect" - * import { Data } from "effect" + * import { Data, Schedule } from "effect" * * // Create a custom error using Data.TaggedError * class CustomError extends Data.TaggedError("CustomError")<{ diff --git a/packages/effect/src/Scheduler.ts b/packages/effect/src/Scheduler.ts index 0b17250dd2..be00116078 100644 --- a/packages/effect/src/Scheduler.ts +++ b/packages/effect/src/Scheduler.ts @@ -16,7 +16,6 @@ import * as ServiceMap from "./ServiceMap.ts" * * @example * ```ts - * import { Effect } from "effect" * import type { Fiber } from "effect" * import type { Scheduler } from "effect/Scheduler" * @@ -205,14 +204,14 @@ export class MixedScheduler implements Scheduler { * import { MaxOpsBeforeYield } from "effect/Scheduler" * * // Configure a fiber to yield more frequently - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * // Get current max ops setting (default is 2048) * const currentMax = yield* MaxOpsBeforeYield * yield* Effect.log(`Default max ops before yield: ${currentMax}`) * * // Run with reduced max ops for more frequent yielding * return yield* Effect.provideService( - * Effect.gen(function* () { + * Effect.gen(function*() { * const maxOps = yield* MaxOpsBeforeYield * yield* Effect.log(`Max ops before yield: ${maxOps}`) * @@ -231,19 +230,21 @@ export class MixedScheduler implements Scheduler { * }) * * // Configure for high-performance scenarios - * const highPerformanceProgram = Effect.gen(function* () { + * const highPerformanceProgram = Effect.gen(function*() { * // Run with increased max ops for better performance (less yielding) * return yield* Effect.provideService( - * Effect.gen(function* () { + * Effect.gen(function*() { * const maxOps = yield* MaxOpsBeforeYield * yield* Effect.log(`High-performance max ops: ${maxOps}`) * * // Run multiple concurrent tasks - * const tasks = Array.from({ length: 100 }, (_, i) => - * Effect.gen(function* () { - * yield* Effect.sleep(`${i * 10} millis`) - * return `Task ${i} completed` - * }) + * const tasks = Array.from( + * { length: 100 }, + * (_, i) => + * Effect.gen(function*() { + * yield* Effect.sleep(`${i * 10} millis`) + * return `Task ${i} completed` + * }) * ) * * return yield* Effect.all(tasks, { concurrency: "unbounded" }) @@ -254,21 +255,21 @@ export class MixedScheduler implements Scheduler { * }) * * // Configure for fair scheduling - * const fairSchedulingProgram = Effect.gen(function* () { + * const fairSchedulingProgram = Effect.gen(function*() { * // Run with lower max ops for more frequent yielding * return yield* Effect.provideService( - * Effect.gen(function* () { + * Effect.gen(function*() { * const maxOps = yield* MaxOpsBeforeYield * yield* Effect.log(`Fair scheduling max ops: ${maxOps}`) * - * const longRunningTask = Effect.gen(function* () { + * const longRunningTask = Effect.gen(function*() { * for (let i = 0; i < 1000; i++) { * yield* Effect.sync(() => Math.random()) * } * return "Long task completed" * }) * - * const quickTask = Effect.gen(function* () { + * const quickTask = Effect.gen(function*() { * yield* Effect.sleep("10 millis") * return "Quick task completed" * }) diff --git a/packages/effect/src/Scope.ts b/packages/effect/src/Scope.ts index f3c9d85661..3be5061a33 100644 --- a/packages/effect/src/Scope.ts +++ b/packages/effect/src/Scope.ts @@ -29,11 +29,9 @@ const CloseableTypeId = effect.ScopeCloseableTypeId * * @example * ```ts - * import { Effect, Exit } from "effect" - * import { Console } from "effect" - * import { Scope } from "effect" + * import { Effect, Exit, Scope } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const scope = yield* Scope.make("sequential") * * // Scope has a strategy and state @@ -60,11 +58,9 @@ export interface Scope { * * @example * ```ts - * import { Effect, Exit } from "effect" - * import { Console } from "effect" - * import { Scope } from "effect" + * import { Console, Effect, Exit, Scope } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const scope = yield* Scope.make() * * // Add a finalizer @@ -88,11 +84,10 @@ export interface Closeable extends Scope { * * @example * ```ts - * import { Effect, Exit } from "effect" - * import { Scope } from "effect" + * import { Effect, Exit, Scope } from "effect" * * // Example of checking scope states - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const scope = yield* Scope.make() * * // When open, the scope accepts finalizers @@ -119,7 +114,6 @@ export namespace State { * * @example * ```ts - * import { Effect, Exit } from "effect" * import { Scope } from "effect" * * const scope = Scope.makeUnsafe() @@ -143,7 +137,6 @@ export namespace State { * * @example * ```ts - * import { Effect, Exit } from "effect" * import { Scope } from "effect" * * const scope = Scope.makeUnsafe() @@ -168,10 +161,9 @@ export namespace State { * * @example * ```ts - * import { Effect, Exit } from "effect" - * import { Scope } from "effect" + * import { Effect, Exit, Scope } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const scope = yield* Scope.make() * * // Close the scope @@ -199,10 +191,9 @@ export namespace State { * * @example * ```ts - * import { Effect } from "effect" - * import { Scope } from "effect" + * import { Effect, Scope } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * // Access the scope from the context * const scope = yield* Scope.Scope * @@ -224,11 +215,9 @@ export const Scope: ServiceMap.Service = effect.scopeTag * * @example * ```ts - * import { Effect, Exit } from "effect" - * import { Console } from "effect" - * import { Scope } from "effect" + * import { Console, Effect, Exit, Scope } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * // Create a scope with sequential cleanup * const scope = yield* Scope.make("sequential") * @@ -254,15 +243,13 @@ export const make: (finalizerStrategy?: "sequential" | "parallel") => Effect Clos * * @example * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" - * import { Scope } from "effect" + * import { Console, Effect, Scope } from "effect" * * // An effect that requires a Scope - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const scope = yield* Scope.Scope * yield* Scope.addFinalizer(scope, Console.log("Cleanup")) * yield* Console.log("Working...") * }) * * // Provide a scope to the program - * const withScope = Effect.gen(function* () { + * const withScope = Effect.gen(function*() { * const scope = yield* Scope.make() * yield* Scope.provide(scope)(program) * }) @@ -311,16 +296,20 @@ export const provide: { * * @example * ```ts - * import { Effect, Exit } from "effect" - * import { Console } from "effect" - * import { Scope } from "effect" + * import { Console, Effect, Exit, Scope } from "effect" * - * const withResource = Effect.gen(function* () { + * const withResource = Effect.gen(function*() { * const scope = yield* Scope.make() * * // Add a finalizer for cleanup - * yield* Scope.addFinalizerExit(scope, (exit) => - * Console.log(`Cleaning up resource. Exit: ${Exit.isSuccess(exit) ? "Success" : "Failure"}`) + * yield* Scope.addFinalizerExit( + * scope, + * (exit) => + * Console.log( + * `Cleaning up resource. Exit: ${ + * Exit.isSuccess(exit) ? "Success" : "Failure" + * }` + * ) * ) * * // Use the resource @@ -344,11 +333,9 @@ export const addFinalizerExit: (scope: Scope, finalizer: (exit: Exit) * * @example * ```ts - * import { Effect, Exit } from "effect" - * import { Console } from "effect" - * import { Scope } from "effect" + * import { Console, Effect, Exit, Scope } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const scope = yield* Scope.make() * * // Add simple finalizers @@ -375,11 +362,9 @@ export const addFinalizer: (scope: Scope, finalizer: Effect) => Effect< * * @example * ```ts - * import { Effect, Exit } from "effect" - * import { Console } from "effect" - * import { Scope } from "effect" + * import { Console, Effect, Exit, Scope } from "effect" * - * const nestedScopes = Effect.gen(function* () { + * const nestedScopes = Effect.gen(function*() { * const parentScope = yield* Scope.make("sequential") * * // Add finalizer to parent @@ -411,11 +396,9 @@ export const fork: ( * * @example * ```ts - * import { Effect, Exit } from "effect" - * import { Console } from "effect" - * import { Scope } from "effect" + * import { Console, Effect, Exit, Scope } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const parentScope = Scope.makeUnsafe("sequential") * const childScope = Scope.forkUnsafe(parentScope, "parallel") * @@ -441,11 +424,9 @@ export const forkUnsafe: (scope: Scope, finalizerStrategy?: "sequential" | "para * * @example * ```ts - * import { Effect, Exit } from "effect" - * import { Console } from "effect" - * import { Scope } from "effect" + * import { Console, Effect, Exit, Scope } from "effect" * - * const resourceManagement = Effect.gen(function* () { + * const resourceManagement = Effect.gen(function*() { * const scope = yield* Scope.make("sequential") * * // Add multiple finalizers diff --git a/packages/effect/src/ServiceMap.ts b/packages/effect/src/ServiceMap.ts index ad09e085f3..b38d5a24ab 100644 --- a/packages/effect/src/ServiceMap.ts +++ b/packages/effect/src/ServiceMap.ts @@ -30,7 +30,9 @@ const ServiceTypeId = "~effect/ServiceMap/Service" as const * import { ServiceMap } from "effect" * * // Define an identifier for a database service - * const Database = ServiceMap.Service<{ query: (sql: string) => string }>("Database") + * const Database = ServiceMap.Service<{ query: (sql: string) => string }>( + * "Database" + * ) * * // The key can be used to store and retrieve services * const services = ServiceMap.make(Database, { query: (sql) => `Result: ${sql}` }) @@ -215,7 +217,9 @@ const ReferenceTypeId = "~effect/ServiceMap/Reference" as const * * // Define a reference with a default value * const LoggerRef: ServiceMap.Reference<{ log: (msg: string) => void }> = - * ServiceMap.Reference("Logger", { defaultValue: () => ({ log: (msg: string) => console.log(msg) }) }) + * ServiceMap.Reference("Logger", { + * defaultValue: () => ({ log: (msg: string) => console.log(msg) }) + * }) * * // The reference can be used without explicit provision * const serviceMap = ServiceMap.empty() @@ -254,7 +258,7 @@ export declare namespace Service { /** * @example * ```ts - * import { ServiceMap } from "effect" + * import type { ServiceMap } from "effect" * * // Variance interface is used internally for type inference * type MyVariance = ServiceMap.Service.Variance<"MyId", { value: number }> @@ -292,7 +296,9 @@ export declare namespace Service { * ```ts * import { ServiceMap } from "effect" * - * const Database = ServiceMap.Service<{ query: (sql: string) => string }>("Database") + * const Database = ServiceMap.Service<{ query: (sql: string) => string }>( + * "Database" + * ) * * // Extract the service shape from the service * type DatabaseService = ServiceMap.Service.Shape @@ -309,7 +315,9 @@ export declare namespace Service { * ```ts * import { ServiceMap } from "effect" * - * const Database = ServiceMap.Service<{ query: (sql: string) => string }>("Database") + * const Database = ServiceMap.Service<{ query: (sql: string) => string }>( + * "Database" + * ) * * // Extract the identifier type from a key * type DatabaseId = ServiceMap.Service.Identifier @@ -331,9 +339,13 @@ const TypeId = "~effect/ServiceMap" as const * * // Create a service map with multiple services * const Logger = ServiceMap.Service<{ log: (msg: string) => void }>("Logger") - * const Database = ServiceMap.Service<{ query: (sql: string) => string }>("Database") + * const Database = ServiceMap.Service<{ query: (sql: string) => string }>( + * "Database" + * ) * - * const services = ServiceMap.make(Logger, { log: (msg: string) => console.log(msg) }) + * const services = ServiceMap.make(Logger, { + * log: (msg: string) => console.log(msg) + * }) * .pipe(ServiceMap.add(Database, { query: (sql) => `Result: ${sql}` })) * ``` * @@ -405,8 +417,8 @@ const Proto: Omit, "mapUnsafe"> = { * * @example * ```ts - * import * as assert from "node:assert" * import { ServiceMap } from "effect" + * import * as assert from "node:assert" * * assert.strictEqual(ServiceMap.isServiceMap(ServiceMap.empty()), true) * ``` @@ -421,8 +433,8 @@ export const isServiceMap = (u: unknown): u is ServiceMap => hasProperty( * * @example * ```ts - * import * as assert from "node:assert" * import { ServiceMap } from "effect" + * import * as assert from "node:assert" * * assert.strictEqual(ServiceMap.isService(ServiceMap.Service("Service")), true) * ``` @@ -437,10 +449,12 @@ export const isService = (u: unknown): u is Service => hasProperty(u, * * @example * ```ts - * import * as assert from "node:assert" * import { ServiceMap } from "effect" + * import * as assert from "node:assert" * - * const LoggerRef = ServiceMap.Reference("Logger", { defaultValue: () => ({ log: (msg: string) => console.log(msg) }) }) + * const LoggerRef = ServiceMap.Reference("Logger", { + * defaultValue: () => ({ log: (msg: string) => console.log(msg) }) + * }) * * assert.strictEqual(ServiceMap.isReference(LoggerRef), true) * assert.strictEqual(ServiceMap.isReference(ServiceMap.Service("Key")), false) @@ -456,8 +470,8 @@ export const isReference = (u: unknown): u is Reference => hasProperty(u, R * * @example * ```ts - * import * as assert from "node:assert" * import { ServiceMap } from "effect" + * import * as assert from "node:assert" * * assert.strictEqual(ServiceMap.isServiceMap(ServiceMap.empty()), true) * ``` @@ -473,8 +487,8 @@ const emptyServiceMap = makeUnsafe(new Map()) * * @example * ```ts - * import * as assert from "node:assert" * import { ServiceMap } from "effect" + * import * as assert from "node:assert" * * const Port = ServiceMap.Service<{ PORT: number }>("Port") * @@ -497,8 +511,7 @@ export const make = ( * @example * ```ts * import * as assert from "node:assert" - * import { pipe } from "effect" - * import { ServiceMap } from "effect" + * import { pipe, ServiceMap } from "effect" * * const Port = ServiceMap.Service<{ PORT: number }>("Port") * const Timeout = ServiceMap.Service<{ TIMEOUT: number }>("Timeout") @@ -571,16 +584,24 @@ export const addOrOmit: { * * @example * ```ts - * import * as assert from "node:assert" * import { ServiceMap } from "effect" + * import * as assert from "node:assert" * * const Logger = ServiceMap.Service<{ log: (msg: string) => void }>("Logger") - * const Database = ServiceMap.Service<{ query: (sql: string) => string }>("Database") + * const Database = ServiceMap.Service<{ query: (sql: string) => string }>( + * "Database" + * ) * - * const services = ServiceMap.make(Logger, { log: (msg: string) => console.log(msg) }) + * const services = ServiceMap.make(Logger, { + * log: (msg: string) => console.log(msg) + * }) * * const logger = ServiceMap.getOrElse(services, Logger, () => ({ log: () => {} })) - * const database = ServiceMap.getOrElse(services, Database, () => ({ query: () => "fallback" })) + * const database = ServiceMap.getOrElse( + * services, + * Database, + * () => ({ query: () => "fallback" }) + * ) * * assert.deepStrictEqual(logger, { log: (msg: string) => console.log(msg) }) * assert.deepStrictEqual(database, { query: () => "fallback" }) @@ -624,8 +645,8 @@ export const getOrUndefined: { * * @example * ```ts - * import * as assert from "node:assert" * import { ServiceMap } from "effect" + * import * as assert from "node:assert" * * const Port = ServiceMap.Service<{ PORT: number }>("Port") * const Timeout = ServiceMap.Service<{ TIMEOUT: number }>("Timeout") @@ -662,8 +683,7 @@ export const getUnsafe: { * @example * ```ts * import * as assert from "node:assert" - * import { pipe } from "effect" - * import { ServiceMap } from "effect" + * import { pipe, ServiceMap } from "effect" * * const Port = ServiceMap.Service<{ PORT: number }>("Port") * const Timeout = ServiceMap.Service<{ TIMEOUT: number }>("Timeout") @@ -687,8 +707,8 @@ export const get: { /** * @example * ```ts - * import * as assert from "node:assert" * import { ServiceMap } from "effect" + * import * as assert from "node:assert" * * const LoggerRef = ServiceMap.Reference("Logger", { * defaultValue: () => ({ log: (msg: string) => console.log(msg) }) @@ -750,16 +770,18 @@ const serviceNotFoundError = (service: Service) => { * * @example * ```ts + * import { Option, ServiceMap } from "effect" * import * as assert from "node:assert" - * import { ServiceMap } from "effect" - * import { Option } from "effect" * * const Port = ServiceMap.Service<{ PORT: number }>("Port") * const Timeout = ServiceMap.Service<{ TIMEOUT: number }>("Timeout") * * const Services = ServiceMap.make(Port, { PORT: 8080 }) * - * assert.deepStrictEqual(ServiceMap.getOption(Services, Port), Option.some({ PORT: 8080 })) + * assert.deepStrictEqual( + * ServiceMap.getOption(Services, Port), + * Option.some({ PORT: 8080 }) + * ) * assert.deepStrictEqual(ServiceMap.getOption(Services, Timeout), Option.none()) * ``` * @@ -784,8 +806,8 @@ export const getOption: { * * @example * ```ts - * import * as assert from "node:assert" * import { ServiceMap } from "effect" + * import * as assert from "node:assert" * * const Port = ServiceMap.Service<{ PORT: number }>("Port") * const Timeout = ServiceMap.Service<{ TIMEOUT: number }>("Timeout") @@ -818,8 +840,8 @@ export const merge: { * * @example * ```ts - * import * as assert from "node:assert" * import { ServiceMap } from "effect" + * import * as assert from "node:assert" * * const Port = ServiceMap.Service<{ PORT: number }>("Port") * const Timeout = ServiceMap.Service<{ TIMEOUT: number }>("Timeout") @@ -829,7 +851,11 @@ export const merge: { * const secondServiceMap = ServiceMap.make(Timeout, { TIMEOUT: 5000 }) * const thirdServiceMap = ServiceMap.make(Host, { HOST: "localhost" }) * - * const Services = ServiceMap.mergeAll(firstServiceMap, secondServiceMap, thirdServiceMap) + * const Services = ServiceMap.mergeAll( + * firstServiceMap, + * secondServiceMap, + * thirdServiceMap + * ) * * assert.deepStrictEqual(ServiceMap.get(Services, Port), { PORT: 8080 }) * assert.deepStrictEqual(ServiceMap.get(Services, Timeout), { TIMEOUT: 5000 }) @@ -859,9 +885,7 @@ export const mergeAll = >( * @example * ```ts * import * as assert from "node:assert" - * import { pipe } from "effect" - * import { ServiceMap } from "effect" - * import { Option } from "effect" + * import { Option, pipe, ServiceMap } from "effect" * * const Port = ServiceMap.Service<{ PORT: number }>("Port") * const Timeout = ServiceMap.Service<{ TIMEOUT: number }>("Timeout") @@ -873,7 +897,10 @@ export const mergeAll = >( * * const Services = pipe(someServiceMap, ServiceMap.pick(Port)) * - * assert.deepStrictEqual(ServiceMap.getOption(Services, Port), Option.some({ PORT: 8080 })) + * assert.deepStrictEqual( + * ServiceMap.getOption(Services, Port), + * Option.some({ PORT: 8080 }) + * ) * assert.deepStrictEqual(ServiceMap.getOption(Services, Timeout), Option.none()) * ``` * @@ -898,9 +925,7 @@ export const pick = >>( * @example * ```ts * import * as assert from "node:assert" - * import { pipe } from "effect" - * import { ServiceMap } from "effect" - * import { Option } from "effect" + * import { Option, pipe, ServiceMap } from "effect" * * const Port = ServiceMap.Service<{ PORT: number }>("Port") * const Timeout = ServiceMap.Service<{ TIMEOUT: number }>("Timeout") @@ -912,7 +937,10 @@ export const pick = >>( * * const Services = pipe(someServiceMap, ServiceMap.omit(Timeout)) * - * assert.deepStrictEqual(ServiceMap.getOption(Services, Port), Option.some({ PORT: 8080 })) + * assert.deepStrictEqual( + * ServiceMap.getOption(Services, Port), + * Option.some({ PORT: 8080 }) + * ) * assert.deepStrictEqual(ServiceMap.getOption(Services, Timeout), Option.none()) * ``` * @@ -942,7 +970,6 @@ export const omit = >>( * * @example * ```ts - * import * as assert from "node:assert" * import { ServiceMap } from "effect" * * // Create a reference with a default value @@ -955,7 +982,9 @@ export const omit = >>( * const logger = ServiceMap.get(services, LoggerRef) * * // You can also override the default value - * const customServices = ServiceMap.make(LoggerRef, { log: (msg) => `Custom: ${msg}` }) + * const customServices = ServiceMap.make(LoggerRef, { + * log: (msg: string) => `Custom: ${msg}` + * }) * const customLogger = ServiceMap.get(customServices, LoggerRef) * ``` * diff --git a/packages/effect/src/Sink.ts b/packages/effect/src/Sink.ts index aff806203a..536a387048 100644 --- a/packages/effect/src/Sink.ts +++ b/packages/effect/src/Sink.ts @@ -30,9 +30,9 @@ const TypeId = "~effect/Sink" * * @example * ```ts + * import { Effect } from "effect" * import * as Sink from "effect/Sink" * import * as Stream from "effect/Stream" - * import { Effect } from "effect" * * // Create a simple sink that always succeeds with a value * const sink: Sink.Sink = Sink.succeed(42) @@ -76,8 +76,8 @@ const endVoid = Pull.halt([void 0] as End) * * @example * ```ts - * import type * as Sink from "effect/Sink" * import type { Effect } from "effect" + * import type * as Sink from "effect/Sink" * import type * as Unify from "effect/types/Unify" * * // SinkUnify helps unify Sink and Effect types @@ -208,7 +208,7 @@ const SinkProto = { * const sink = Sink.never * const notStream = { data: [1, 2, 3] } * - * console.log(Sink.isSink(sink)) // true + * console.log(Sink.isSink(sink)) // true * console.log(Sink.isSink(notStream)) // false * ``` * @@ -258,7 +258,6 @@ export const fromTransform = ( * @example * ```ts * import { Sink } from "effect" - * import { Channel } from "effect" * * // Create a sink and extract its channel * const sink = Sink.succeed(42) @@ -277,9 +276,7 @@ export const toChannel = ( * * @example * ```ts - * import { Sink } from "effect" - * import { Stream } from "effect" - * import { Effect } from "effect" + * import { Effect, Sink, Stream } from "effect" * * // Create a sink that always yields the same value * const sink = Sink.succeed(42) @@ -320,9 +317,7 @@ export const suspend = (evaluate: LazyArg>) * * @example * ```ts - * import { Sink } from "effect" - * import { Stream } from "effect" - * import { Effect } from "effect" + * import { Effect, Sink, Stream } from "effect" * * // Create a sink that always fails * const sink = Sink.fail(new Error("Sink failed")) @@ -345,9 +340,7 @@ export const fail = (e: E): Sink => fromChannel(Cha * * @example * ```ts - * import { Sink } from "effect" - * import { Stream } from "effect" - * import { Effect } from "effect" + * import { Effect, Sink, Stream } from "effect" * * // Create a sink that fails with a lazy error * const sink = Sink.failSync(() => new Error("Lazy error")) @@ -371,9 +364,7 @@ export const failSync = (evaluate: LazyArg): Sink(cause: Cause.Cause): Sink Cause.fail(new Error("Lazy cause"))) @@ -425,9 +414,7 @@ export const failCauseSync = (evaluate: LazyArg>): Sink( * * @example * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" - * import { Sink, Stream } from "effect" + * import { Console, Effect, Sink, Stream } from "effect" * * // Create a sink that logs each item * const sink = Sink.forEach((item: number) => Console.log(`Processing: ${item}`)) @@ -1076,13 +1061,13 @@ export const forEach = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" - * import { Sink, Stream } from "effect" + * import { Console, Effect, Sink, Stream } from "effect" * * // Create a sink that processes chunks - * const sink = Sink.forEachArray((chunk: readonly number[]) => - * Console.log(`Processing chunk of ${chunk.length} items: [${chunk.join(", ")}]`) + * const sink = Sink.forEachArray((chunk: ReadonlyArray) => + * Console.log( + * `Processing chunk of ${chunk.length} items: [${chunk.join(", ")}]` + * ) * ) * * // Use it with a stream @@ -1114,12 +1099,12 @@ export const forEachArray = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" - * import { Sink, Stream } from "effect" + * import { Console, Effect, Sink, Stream } from "effect" * * // Create a sink from an effect that produces a sink - * const sinkEffect = Effect.succeed(Sink.forEach((item: number) => Console.log(`Item: ${item}`))) + * const sinkEffect = Effect.succeed( + * Sink.forEach((item: number) => Console.log(`Item: ${item}`)) + * ) * const sink = Sink.unwrap(sinkEffect) * * // Use it with a stream diff --git a/packages/effect/src/Stream.ts b/packages/effect/src/Stream.ts index a36d69e361..6eef3dbc93 100644 --- a/packages/effect/src/Stream.ts +++ b/packages/effect/src/Stream.ts @@ -62,15 +62,14 @@ const TypeId = "~effect/Stream" * * @example * ```ts - * import { Stream } from "effect" - * import { Effect } from "effect" + * import { Effect, Stream } from "effect" * * // Create a stream that emits numbers 1, 2, 3 * const stream: Stream.Stream = Stream.make(1, 2, 3) * * // Transform the stream and run it * const program = stream.pipe( - * Stream.map(n => n * 2), + * Stream.map((n) => n * 2), * Stream.runCollect * ) * @@ -93,8 +92,7 @@ export interface Stream extends Variance @@ -136,8 +134,8 @@ export interface StreamUnifyIgnore extends Effect.EffectUnifyIgnore { * * @example * ```ts - * import type { Kind } from "effect/types/HKT" * import type { StreamTypeLambda } from "effect/Stream" + * import type { Kind } from "effect/types/HKT" * * // Create a Stream type using the type lambda * type NumberStream = Kind @@ -178,7 +176,7 @@ export interface VarianceStruct { * * @example * ```ts - * import { Stream } from "effect" + * import type { Stream } from "effect" * * type NumberStream = Stream.Stream * type SuccessType = Stream.Success @@ -195,7 +193,7 @@ export type Success> = [T] extends [Stream * type ErrorType = Stream.Error @@ -212,9 +210,11 @@ export type Error> = [T] extends [Stream unknown } + * interface Database { + * query: (sql: string) => unknown + * } * type NumberStream = Stream.Stream * type Services = Stream.Services * // Services is { db: Database } @@ -242,7 +242,7 @@ const streamVariance = { * const stream = Stream.make(1, 2, 3) * const notStream = { data: [1, 2, 3] } * - * console.log(Stream.isStream(stream)) // true + * console.log(Stream.isStream(stream)) // true * console.log(Stream.isStream(notStream)) // false * ``` * @@ -288,8 +288,7 @@ export type HaltStrategy = Channel.HaltStrategy * * @example * ```ts - * import { Stream } from "effect" - * import { Channel } from "effect" + * import { Channel, Stream } from "effect" * * const myChannel = Channel.succeed([1, 2, 3] as const) * const stream = Stream.fromChannel(myChannel) @@ -389,8 +388,7 @@ export const tick = (interval: Duration.DurationInput): Stream => * * @example * ```ts - * import { Stream } from "effect" - * import { Effect } from "effect" + * import { Effect, Stream } from "effect" * * const pullEffect = Effect.succeed(Effect.succeed([1, 2, 3] as const)) * const stream = Stream.fromPull(pullEffect) @@ -408,8 +406,7 @@ export const fromPull = ( * * @example * ```ts - * import { Stream } from "effect" - * import { Effect } from "effect" + * import { Effect, Stream } from "effect" * * const originalStream = Stream.make(1, 2, 3) * @@ -498,9 +495,7 @@ export const toChannel = ( * * @example * ```ts - * import { Stream } from "effect" - * import { Effect } from "effect" - * import { Queue } from "effect" + * import { Effect, Queue, Stream } from "effect" * * const stream = Stream.callback((queue) => { * // Emit values to the stream @@ -530,8 +525,7 @@ export const callback = ( * * @example * ```ts - * import { Stream } from "effect" - * import { Effect } from "effect" + * import { Effect, Stream } from "effect" * * const emptyStream = Stream.empty * @@ -552,7 +546,6 @@ export const empty: Stream = fromChannel(Channel.empty) * @example * ```ts * import { Stream } from "effect" - * import { Effect } from "effect" * * // A Stream with a single number * const stream = Stream.succeed(3) @@ -571,8 +564,7 @@ export const succeed = (value: A): Stream => fromChannel(Channel.succeed(A * * @example * ```ts - * import { Stream } from "effect" - * import { Effect } from "effect" + * import { Effect, Stream } from "effect" * * const stream = Stream.make(1, 2, 3) * @@ -592,8 +584,7 @@ export const make = >(...values: As): Stream * * @example * ```ts - * import { Stream } from "effect" - * import { Effect } from "effect" + * import { Effect, Stream } from "effect" * * const stream = Stream.sync(() => Math.random()) * @@ -613,8 +604,7 @@ export const sync = (evaluate: LazyArg): Stream => fromChannel(Channel. * * @example * ```ts - * import { Stream } from "effect" - * import { Effect } from "effect" + * import { Effect, Stream } from "effect" * * const lazyStream = Stream.suspend(() => { * console.log("Creating stream...") @@ -636,8 +626,7 @@ export const suspend = (stream: LazyArg>): Stream(error: E): Stream => fromChannel(Channel.fail( * * @example * ```ts - * import { Stream } from "effect" - * import { Effect } from "effect" + * import { Effect, Stream } from "effect" * * const stream = Stream.failSync(() => new Error("Something went wrong")) * @@ -684,9 +672,7 @@ export const failSync = (evaluate: LazyArg): Stream => fromChann * * @example * ```ts - * import { Effect } from "effect" - * import { Stream } from "effect" - * import { Cause } from "effect" + * import { Cause, Effect, Stream } from "effect" * * const cause = Cause.fail("Database connection failed") * const stream = Stream.failCause(cause) @@ -711,9 +697,7 @@ export const die = (defect: unknown): Stream => fromChannel(Channel.die(d * * @example * ```ts - * import { Effect } from "effect" - * import { Stream } from "effect" - * import { Cause } from "effect" + * import { Cause, Effect, Stream } from "effect" * * const stream = Stream.failCauseSync(() => * Cause.fail("Connection timeout after retries") @@ -738,8 +722,7 @@ export const failCauseSync = (evaluate: LazyArg>): Stream(iterator: IterableIterator, maxChunkSi * @example * ```ts * import { Stream } from "effect" - * import { Effect } from "effect" * * const numbers = [1, 2, 3] * @@ -811,8 +793,7 @@ export const fromIterableEffectRepeat = ( * * @example * ```ts - * import { Stream } from "effect" - * import { Effect } from "effect" + * import { Effect, Stream } from "effect" * * const numbers = [1, 2, 3, 4, 5] * const stream = Stream.fromArray(numbers) @@ -857,11 +838,9 @@ export const fromArrays = >>( * * @example * ```ts - * import { Stream } from "effect" - * import { Effect } from "effect" - * import { Queue } from "effect" + * import { Effect, Queue, Stream } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const queue = yield* Queue.unbounded() * yield* Queue.offer(queue, 1) * yield* Queue.offer(queue, 2) @@ -884,11 +863,9 @@ export const fromQueue = (queue: Queue.Dequeue): Stream() * * // Publish some values @@ -919,7 +896,6 @@ export const fromPubSubTake = (pubsub: PubSub.PubSub>): St * @example * ```ts * import { Stream } from "effect" - * import { Effect } from "effect" * * const readableStream = new ReadableStream({ * start(controller) { @@ -993,11 +969,9 @@ export const fromSchedule = (schedule: Schedule.Schedule() * const subscription = yield* PubSub.subscribe(pubsub) * @@ -1058,7 +1032,6 @@ export interface EventListener { * @example * ```ts * import { Stream } from "effect" - * import { Effect } from "effect" * * // In a browser environment * const clickStream = Stream.fromEventListener(document, "click") @@ -1097,12 +1070,13 @@ export const fromEventListener = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Stream } from "effect" + * import { Effect, Stream } from "effect" * * const stream = Stream.unfold(1, (n) => Effect.succeed([n, n + 1])) * - * Effect.runPromise(Stream.runCollect(stream.pipe(Stream.take(5)))).then(console.log) + * Effect.runPromise(Stream.runCollect(stream.pipe(Stream.take(5)))).then( + * console.log + * ) * // [ 1, 2, 3, 4, 5 ] * ``` * @@ -1127,16 +1101,16 @@ export const unfold = ( * * @example * ```ts - * import { Stream } from "effect" - * import { Effect } from "effect" + * import { Effect, Stream } from "effect" * import * as Option from "effect/Option" * * const stream = Stream.paginate(0, (n: number) => - * Effect.succeed([ - * [n], - * n < 3 ? Option.some(n + 1) : Option.none() - * ] as const) - * ) + * Effect.succeed( + * [ + * [n], + * n < 3 ? Option.some(n + 1) : Option.none() + * ] as const + * )) * * Effect.runPromise(Stream.runCollect(stream)).then(console.log) * ``` @@ -1176,13 +1150,14 @@ export const paginate = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Stream } from "effect" + * import { Effect, Stream } from "effect" * * // An infinite Stream of numbers starting from 1 and incrementing * const stream = Stream.iterate(1, (n) => n + 1) * - * Effect.runPromise(Stream.runCollect(stream.pipe(Stream.take(10)))).then(console.log) + * Effect.runPromise(Stream.runCollect(stream.pipe(Stream.take(10)))).then( + * console.log + * ) * // [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ] * ``` * @@ -1202,7 +1177,6 @@ export const iterate = (value: A, next: (value: A) => A): Stream => * @example * ```ts * import { Stream } from "effect" - * import { Effect } from "effect" * * const stream = Stream.range(1, 5) * @@ -1240,7 +1214,6 @@ export const range = ( * @example * ```ts * import { Stream } from "effect" - * import { Effect } from "effect" * * // A stream that never emits values or completes * const neverStream = Stream.never @@ -1260,8 +1233,7 @@ export const never: Stream = fromChannel(Channel.never) * * @example * ```ts - * import { Stream } from "effect" - * import { Effect } from "effect" + * import { Effect, Stream } from "effect" * * const effectThatCreatesStream = Effect.succeed( * Stream.make(1, 2, 3) @@ -1293,7 +1265,6 @@ export const scoped = ( * @example * ```ts * import { Stream } from "effect" - * import { Effect } from "effect" * * const stream = Stream.fromArray([1, 2, 3]).pipe(Stream.map((n) => n + 1)) * @@ -1362,15 +1333,13 @@ export const mapArray: { * * @example * ```ts - * import { Effect } from "effect" - * import { Stream } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Stream } from "effect" * * const stream = Stream.make(1, 2, 3) * * const mappedStream = stream.pipe( - * Stream.mapEffect(n => - * Effect.gen(function* () { + * Stream.mapEffect((n) => + * Effect.gen(function*() { * yield* Console.log(`Processing: ${n}`) * return n * 2 * }) @@ -1481,9 +1450,7 @@ export const result = (self: Stream): Stream Console.log(`before mapping: ${n}`)), @@ -1653,13 +1620,12 @@ export const tapSink: { * * @example * ```ts - * import { Stream } from "effect" - * import { Effect } from "effect" + * import { Effect, Stream } from "effect" * * const stream = Stream.make(1, 2, 3) * * const flatMapped = stream.pipe( - * Stream.flatMap(n => Stream.make(n, n * 2)) + * Stream.flatMap((n) => Stream.make(n, n * 2)) * ) * * const program = flatMapped.pipe(Stream.runCollect) @@ -1705,8 +1671,7 @@ export const flatMap: { * * @example * ```ts - * import { Stream } from "effect" - * import { Effect } from "effect" + * import { Effect, Stream } from "effect" * * const streamOfStreams = Stream.make( * Stream.make(1, 2), @@ -1782,12 +1747,13 @@ export const drainFork: { * * @example * ```ts - * import { Effect, Schedule } from "effect" - * import { Stream } from "effect" + * import { Effect, Schedule, Stream } from "effect" * * const stream = Stream.repeat(Stream.succeed(1), Schedule.forever) * - * Effect.runPromise(Stream.runCollect(stream.pipe(Stream.take(5)))).then(console.log) + * Effect.runPromise(Stream.runCollect(stream.pipe(Stream.take(5)))).then( + * console.log + * ) * // { _id: 'Chunk', values: [ 1, 1, 1, 1, 1 ] } * ``` * @@ -1942,8 +1908,7 @@ export const flattenTake = (self: Stream, E2, R>): * * @example * ```ts - * import { Stream } from "effect" - * import { Effect } from "effect" + * import { Effect, Stream } from "effect" * * const stream1 = Stream.make(1, 2, 3) * const stream2 = Stream.make(4, 5, 6) @@ -2162,8 +2127,7 @@ export const crossWith: { * * @example * ```ts - * import { Effect } from "effect" - * import { Stream } from "effect" + * import { Effect, Stream } from "effect" * * const stream1 = Stream.make(1, 2, 3, 4, 5, 6) * const stream2 = Stream.make("a", "b", "c") @@ -2303,8 +2267,7 @@ export const zipWithArray: { * * @example * ```ts - * import { Effect } from "effect" - * import { Stream } from "effect" + * import { Effect, Stream } from "effect" * * const stream1 = Stream.make(1, 2, 3) * const stream2 = Stream.make("a", "b", "c") @@ -2337,8 +2300,7 @@ export const zip: { * * @example * ```ts - * import { Effect } from "effect" - * import { Stream } from "effect" + * import { Effect, Stream } from "effect" * * const stream1 = Stream.make(1, 2, 3, 4) * const stream2 = Stream.make("a", "b") @@ -2379,8 +2341,7 @@ export const zipLeft: { * * @example * ```ts - * import { Effect } from "effect" - * import { Stream } from "effect" + * import { Effect, Stream } from "effect" * * const stream1 = Stream.make(1, 2) * const stream2 = Stream.make("a", "b", "c", "d") @@ -2421,10 +2382,13 @@ export const zipRight: { * * @example * ```ts - * import { Effect } from "effect" - * import { Stream } from "effect" + * import { Effect, Stream } from "effect" * - * const stream1 = Stream.make([1, "a"] as const, [2, "b"] as const, [3, "c"] as const) + * const stream1 = Stream.make( + * [1, "a"] as const, + * [2, "b"] as const, + * [3, "c"] as const + * ) * const stream2 = Stream.make("x", "y", "z") * * const zipped = Stream.zipFlatten(stream1, stream2) @@ -2457,8 +2421,7 @@ export const zipFlatten: { * * @example * ```ts - * import { Effect } from "effect" - * import { Stream } from "effect" + * import { Effect, Stream } from "effect" * * const stream = Stream.make("a", "b", "c", "d") * @@ -2478,8 +2441,7 @@ export const zipWithIndex = (self: Stream): Stream<[A, number] * * @example * ```ts - * import { Effect } from "effect" - * import { Stream } from "effect" + * import { Effect, Stream } from "effect" * * const stream = Stream.zipWithNext(Stream.make(1, 2, 3, 4)) * @@ -2521,8 +2483,7 @@ export const zipWithNext = (self: Stream): Stream<[A, Option.O * * @example * ```ts - * import { Effect } from "effect" - * import { Stream } from "effect" + * import { Effect, Stream } from "effect" * * const stream = Stream.zipWithPrevious(Stream.make(1, 2, 3, 4)) * @@ -2554,8 +2515,7 @@ export const zipWithPrevious = (self: Stream): Stream<[Option. * * @example * ```ts - * import { Effect } from "effect" - * import { Stream } from "effect" + * import { Effect, Stream } from "effect" * * const stream = Stream.zipWithPreviousAndNext(Stream.make(1, 2, 3, 4)) * @@ -2672,8 +2632,7 @@ export const zipLatestAll = >>( * * @example * ```ts - * import { Effect } from "effect" - * import { Stream } from "effect" + * import { Effect, Stream } from "effect" * * const s1 = Stream.make(1, 2, 3) * const s2 = Stream.make("a", "b", "c", "d") @@ -2686,8 +2645,7 @@ export const zipLatestAll = >>( * * @example * ```ts - * import { Effect } from "effect" - * import { Stream } from "effect" + * import { Effect, Stream } from "effect" * * // Combining sensor readings with timestamps * const temperatures = Stream.make(20.5, 21.0, 20.8, 22.1) @@ -2731,8 +2689,7 @@ export const zipLatest: { * * @example * ```ts - * import { Effect } from "effect" - * import { Stream } from "effect" + * import { Effect, Stream } from "effect" * * const numbers = Stream.make(1, 2, 3) * const multipliers = Stream.make(10, 20, 30) @@ -2749,8 +2706,7 @@ export const zipLatest: { * * @example * ```ts - * import { Effect } from "effect" - * import { Stream } from "effect" + * import { Effect, Stream } from "effect" * * // Combining first and last names * const firstNames = Stream.make("Alice", "Bob", "Charlie") @@ -3154,9 +3110,7 @@ export const bufferArray: { * * @example * ```ts - * import { Effect } from "effect" - * import { Stream } from "effect" - * import { Cause } from "effect" + * import { Effect, Stream } from "effect" * * const failingStream = Stream.make(1, 2).pipe( * Stream.concat(Stream.fail("Oops!")), @@ -3405,9 +3359,7 @@ export const mapError: { * * @example * ```ts - * import { Effect } from "effect" - * import { Stream } from "effect" - * import { Cause } from "effect" + * import { Cause, Stream } from "effect" * * const failingStream = Stream.fail("NetworkError") * @@ -3485,7 +3437,6 @@ export const orElseSucceed: { * @example * ```ts * import { Stream } from "effect" - * import { Effect } from "effect" * * const failingStream = Stream.fail("This will become a defect") * const stream = Stream.orDie(failingStream) @@ -3650,8 +3601,7 @@ export const withExecutionPlan: { * * @example * ```ts - * import { Stream } from "effect" - * import { Effect } from "effect" + * import { Effect, Stream } from "effect" * * const stream = Stream.make(1, 2, 3, 4, 5) * @@ -3679,8 +3629,7 @@ export const take: { * * @example * ```ts - * import { Effect } from "effect" - * import { Stream } from "effect" + * import { Effect, Stream } from "effect" * * const stream = Stream.takeRight(Stream.make(1, 2, 3, 4, 5, 6), 3) * @@ -3716,21 +3665,20 @@ export const takeRight: { * * @example * ```ts - * import { Stream } from "effect" - * import { Effect } from "effect" + * import { Effect, Stream } from "effect" * * const stream = Stream.make(1, 2, 3, 4, 5, 6) * * // Take until we find a number greater than 3 * const taken = stream.pipe( - * Stream.takeUntil(n => n > 3) + * Stream.takeUntil((n) => n > 3) * ) * * Effect.runPromise(Stream.runCollect(taken)).then(console.log) * * // Exclude the element that satisfies the predicate * const takenExclusive = stream.pipe( - * Stream.takeUntil(n => n > 3, { excludeLast: true }) + * Stream.takeUntil((n) => n > 3, { excludeLast: true }) * ) * * Effect.runPromise(Stream.runCollect(takenExclusive)).then(console.log) @@ -3777,13 +3725,10 @@ export const takeUntil: { * * @example * ```ts - * import { Stream } from "effect" - * import { Effect } from "effect" + * import { Effect, Stream } from "effect" * * const stream = Stream.make(1, 2, 3, 4, 5) - * const result = Stream.takeUntilEffect(stream, (n) => - * Effect.succeed(n === 3) - * ) + * const result = Stream.takeUntilEffect(stream, (n) => Effect.succeed(n === 3)) * * Effect.runPromise(Stream.runCollect(result)).then(console.log) * ``` @@ -3836,8 +3781,7 @@ export const takeUntilEffect: { * * @example * ```ts - * import { Stream } from "effect" - * import { Effect } from "effect" + * import { Effect, Stream } from "effect" * * const stream = Stream.make(1, 2, 3, 4, 5, 6) * const result = Stream.takeWhile(stream, (n) => n < 4) @@ -3865,13 +3809,10 @@ export const takeWhile: { * * @example * ```ts - * import { Stream } from "effect" - * import { Effect } from "effect" + * import { Effect, Stream } from "effect" * * const stream = Stream.make(1, 2, 3, 4, 5) - * const result = Stream.takeWhileEffect(stream, (n) => - * Effect.succeed(n < 4) - * ) + * const result = Stream.takeWhileEffect(stream, (n) => Effect.succeed(n < 4)) * * Effect.runPromise(Stream.runCollect(result)).then(console.log) * ``` @@ -3902,8 +3843,7 @@ export const takeWhileEffect: { * * @example * ```ts - * import { Stream } from "effect" - * import { Effect } from "effect" + * import { Effect, Stream } from "effect" * * const stream = Stream.make(1, 2, 3, 4, 5) * const result = Stream.drop(stream, 2) @@ -4076,8 +4016,7 @@ export const dropRight: { * * @example * ```ts - * import { Stream } from "effect" - * import { Effect } from "effect" + * import { Effect, Stream } from "effect" * * const stream = Stream.make(1, 2, 3, 4, 5) * const chunked = Stream.chunks(stream) @@ -4219,9 +4158,7 @@ export const slidingSize: { * Splits elements based on a filter function. * * ```ts - * import { pipe } from "effect" - * import { Filter } from "effect" - * import { Stream } from "effect" + * import { Filter, pipe, Stream } from "effect" * * pipe( * Stream.range(1, 10), @@ -4719,8 +4656,7 @@ export const debounce: { * * @example * ```ts - * import { Effect, Schedule } from "effect" - * import { Stream } from "effect" + * import { Effect, Schedule, Stream } from "effect" * * // Using the "shape" strategy to delay elements * const stream = Stream.fromSchedule(Schedule.spaced("50 millis")).pipe( @@ -4877,8 +4813,7 @@ const throttleShapeEffect = ( * * @example * ```ts - * import { Effect, Schedule } from "effect" - * import { Stream } from "effect" + * import { Effect, Schedule, Stream } from "effect" * * // Rate limiting a stream to 1 element per 100ms using array length as cost * const stream = Stream.fromSchedule(Schedule.spaced("50 millis")).pipe( @@ -5441,9 +5376,8 @@ export const share: { * * @example * ```ts - * import { Effect } from "effect" - * import { Stream, Channel } from "effect" - * import { Console } from "effect" + * import type { Channel } from "effect" + * import { Console, Effect, Stream } from "effect" * * // Create a channel that processes chunks - this is a conceptual example * // In practice, this function is primarily used with specialized channels @@ -5451,10 +5385,10 @@ export const share: { * // encoding/decoding, or platform-specific transformations. * * declare const transformChannel: Channel.Channel< - * readonly [string, ...string[]], + * readonly [string, ...Array], * never, * unknown, - * readonly [number, ...number[]], + * readonly [number, ...Array], * never, * unknown, * never @@ -5463,19 +5397,17 @@ export const share: { * const program = Stream.make(1, 2, 3).pipe( * Stream.pipeThroughChannel(transformChannel), * Stream.runCollect, - * Effect.flatMap(result => Console.log(result)) + * Effect.flatMap((result) => Console.log(result)) * ) * ``` * * @example * ```ts - * import { Effect } from "effect" - * import { Stream, Channel } from "effect" - * import { Console } from "effect" + * import { Channel, Console, Effect, Stream } from "effect" * * // Practical example: combining two channels with pipeTo * declare const sourceChannel: Channel.Channel< - * readonly [number, ...number[]], + * readonly [number, ...Array], * never, * void, * unknown, @@ -5484,10 +5416,10 @@ export const share: { * never * > * declare const transformChannel: Channel.Channel< - * readonly [string, ...string[]], + * readonly [string, ...Array], * never, * unknown, - * readonly [number, ...number[]], + * readonly [number, ...Array], * never, * void, * never @@ -5498,7 +5430,7 @@ export const share: { * const program = Stream.empty.pipe( * Stream.pipeThroughChannel(combinedChannel), * Stream.runCollect, - * Effect.flatMap(result => Console.log(result)) + * Effect.flatMap((result) => Console.log(result)) * ) * ``` * @@ -5528,16 +5460,15 @@ export const pipeThroughChannel: { * * @example * ```ts - * import { Effect } from "effect" - * import { Stream, Channel } from "effect" - * import { Console } from "effect" + * import type { Channel } from "effect" + * import { Console, Effect, Stream } from "effect" * * // Channel that might fail during processing * declare const transformChannel: Channel.Channel< - * readonly [string, ...string[]], + * readonly [string, ...Array], * "ChannelError", * unknown, - * readonly [number, ...number[]], + * readonly [number, ...Array], * never, * unknown, * never @@ -5546,26 +5477,27 @@ export const pipeThroughChannel: { * const program = Stream.make(1, 2, 3).pipe( * Stream.pipeThroughChannelOrFail(transformChannel), * Stream.runCollect, - * Effect.flatMap(result => Console.log(result)) + * Effect.flatMap((result) => Console.log(result)) * ) * ``` * * @example * ```ts - * import { Effect } from "effect" - * import { Stream, Channel } from "effect" - * import { Console } from "effect" + * import type { Channel } from "effect" + * import { Console, Effect, Stream } from "effect" * * // Demonstrate error preservation: both stream and channel can fail * const failingStream = Stream.make(1, 2, 3).pipe( - * Stream.flatMap(n => n === 2 ? Stream.fail("StreamError" as const) : Stream.succeed(n)) + * Stream.flatMap((n) => + * n === 2 ? Stream.fail("StreamError" as const) : Stream.succeed(n) + * ) * ) * * declare const numericTransformChannel: Channel.Channel< - * readonly [string, ...string[]], + * readonly [string, ...Array], * "ChannelError", * unknown, - * readonly [number, ...number[]], + * readonly [number, ...Array], * "StreamError", * unknown, * never @@ -5739,8 +5671,7 @@ export const changesWithEffect: { * * @example * ```ts - * import { Stream } from "effect" - * import { Effect } from "effect" + * import { Effect, Stream } from "effect" * * const encoder = new TextEncoder() * const stream = Stream.make( @@ -5772,8 +5703,7 @@ export const decodeText: { * * @example * ```ts - * import { Stream } from "effect" - * import { Effect } from "effect" + * import { Effect, Stream } from "effect" * * const stream = Stream.make("Hello", " ", "World") * const encoded = Stream.encodeText(stream) @@ -5805,8 +5735,7 @@ export const splitLines = (self: Stream): Stream @@ -6429,8 +6353,7 @@ export const bindTo: { * * @example * ```ts - * import { Effect } from "effect" - * import { Stream, Sink } from "effect" + * import { Effect, Sink, Stream } from "effect" * * const stream = Stream.make(1, 2, 3, 4, 5) * const collectSink = Sink.succeed(42) @@ -6466,8 +6389,7 @@ export const run: { * * @example * ```ts - * import { Stream } from "effect" - * import { Effect } from "effect" + * import { Effect, Stream } from "effect" * * const stream = Stream.make(1, 2, 3, 4, 5) * @@ -6497,8 +6419,7 @@ export const runCollect = (self: Stream): Effect.Effect(self: Stream): Effect.Effect - * Console.log(`Processing: ${n}`) + * const program = Stream.runForEach( + * stream, + * (n) => Console.log(`Processing: ${n}`) * ) * * Effect.runPromise(program) @@ -6689,13 +6609,12 @@ export const runForEachWhile: { * * @example * ```ts - * import { Effect } from "effect" - * import { Stream } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Stream } from "effect" * * const stream = Stream.make(1, 2, 3, 4, 5) - * const result = Stream.runForEachArray(stream, (chunk) => - * Console.log(`Processing chunk: ${chunk.join(", ")}`) + * const result = Stream.runForEachArray( + * stream, + * (chunk) => Console.log(`Processing chunk: ${chunk.join(", ")}`) * ) * * Effect.runPromise(result) @@ -6723,9 +6642,7 @@ export const runForEachArray: { * * @example * ```ts - * import { Effect } from "effect" - * import { Stream } from "effect" - * import { Console } from "effect" + * import { Console, Effect, Stream } from "effect" * * const stream = Stream.make(1, 2, 3).pipe( * Stream.mapEffect((n) => Console.log(`Processing: ${n}`)) @@ -6750,13 +6667,11 @@ export const runDrain = (self: Stream): Effect.Effect( * * @example * ```ts - * import { Stream } from "effect" - * import { Effect } from "effect" + * import { Effect, Stream } from "effect" * * const stream = Stream.make("Hello", " ", "World", "!") * const result = Stream.mkString(stream) @@ -6806,8 +6720,7 @@ export const mkString = (self: Stream): Effect.Effect + * Effect.runPromise(readableStreamEffect).then((rs) => * console.log(rs instanceof ReadableStream) // true * ) * ``` diff --git a/packages/effect/src/Struct.ts b/packages/effect/src/Struct.ts index b720970cf0..3ae0604ac0 100644 --- a/packages/effect/src/Struct.ts +++ b/packages/effect/src/Struct.ts @@ -68,8 +68,7 @@ export type Assign = keyof T & keyof U extends never ? T & U : Omit(self: S): Array<(keyof S) & string> => * * @example * ```ts - * import { pipe } from "effect" - * import { Struct } from "effect" + * import { pipe, Struct } from "effect" * * console.log(pipe({ a: "a", b: 1, c: true }, Struct.pick(["a", "b"]))) * // { a: "a", b: 1 } @@ -138,8 +136,7 @@ export const pick: { * * @example * ```ts - * import { pipe } from "effect" - * import { Struct } from "effect" + * import { pipe, Struct } from "effect" * * console.log(pipe({ a: "a", b: 1, c: true }, Struct.omit(["c"]))) * // { a: "a", b: 1 } @@ -165,8 +162,7 @@ export const omit: { * * @example * ```ts - * import { pipe } from "effect" - * import { Struct } from "effect" + * import { pipe, Struct } from "effect" * * console.log(pipe({ a: "a", b: 1 }, Struct.assign({ b: 2, c: 3 }))) * // { a: "a", b: 2, c: 3 } @@ -198,12 +194,11 @@ type Evolved = Simplify< * * @example * ```ts - * import { pipe } from "effect" - * import { Struct } from "effect" + * import { pipe, Struct } from "effect" * * console.log( * pipe( - * { a: 'a', b: 1, c: 3 }, + * { a: "a", b: 1, c: 3 }, * Struct.evolve({ * a: (a) => a.length, * b: (b) => b * 2 @@ -237,8 +232,7 @@ type KeyEvolved = Simplify< * * @example * ```ts - * import { pipe } from "effect" - * import { Struct } from "effect" + * import { pipe, Struct } from "effect" * * const result = pipe( * { a: 1, b: 2 }, @@ -281,8 +275,7 @@ type EntryEvolved = { * * @example * ```ts - * import { pipe } from "effect" - * import { Struct } from "effect" + * import { pipe, Struct } from "effect" * * const result = pipe( * { a: 1, b: 2 }, @@ -313,8 +306,7 @@ export const evolveEntries: { * * @example * ```ts - * import { pipe } from "effect" - * import { Struct } from "effect" + * import { pipe, Struct } from "effect" * * const result = pipe( * { a: 1, b: 2, c: 3 }, @@ -347,17 +339,21 @@ export const renameKeys: { * * @example * ```ts - * import { Struct, Equivalence } from "effect" + * import { Equivalence, Struct } from "effect" * * const PersonEquivalence = Struct.getEquivalence({ * name: Equivalence.strict(), * age: Equivalence.strict() * }) * - * console.log(PersonEquivalence({ name: "John", age: 25 }, { name: "John", age: 25 })) + * console.log( + * PersonEquivalence({ name: "John", age: 25 }, { name: "John", age: 25 }) + * ) * // true * - * console.log(PersonEquivalence({ name: "John", age: 25 }, { name: "John", age: 40 })) + * console.log( + * PersonEquivalence({ name: "John", age: 25 }, { name: "John", age: 40 }) + * ) * // false * ``` * @@ -374,8 +370,8 @@ export const getEquivalence = Equivalence.struct * @example * ```ts * import { Struct } from "effect" - * import * as S from "effect/String" * import * as N from "effect/Number" + * import * as S from "effect/String" * * const PersonOrder = Struct.getOrder({ * name: S.Order, @@ -399,7 +395,7 @@ export const getOrder = order.struct * * @example * ```ts - * import { Struct } from "effect" + * import type { Struct } from "effect" * * // Lambda is used internally for type-level operations * type MyLambda = Struct.Lambda @@ -457,10 +453,8 @@ export const lambda = any>( * * @example * ```ts - * import { Struct } from "effect" - * * // Used with lambda functions for type-level operations - * const struct = { a: 1, b: 2, c: 3 } + * const original = { a: 1, b: 2, c: 3 } * // Map transforms all values using the provided lambda * ``` * @@ -487,10 +481,8 @@ export const map: { * * @example * ```ts - * import { Struct } from "effect" - * * // Used with lambda functions for selective transformation - * const struct = { a: 1, b: 2, c: 3 } + * const data = { a: 1, b: 2, c: 3 } * const keys = ["a", "c"] * // Transforms only the specified keys * ``` @@ -526,10 +518,8 @@ export const mapPick: { * * @example * ```ts - * import { Struct } from "effect" - * * // Used with lambda functions for selective omission - * const struct = { a: 1, b: 2, c: 3 } + * const source = { a: 1, b: 2, c: 3 } * const keysToOmit = ["b"] * // Transforms all keys except the omitted ones * ``` @@ -600,8 +590,7 @@ function buildStruct< * **Example** * * ```ts - * import { Struct } from "effect" - * import { Number, String } from "effect" + * import { Number, String, Struct } from "effect" * * const C = Struct.getCombiner<{ readonly n: number; readonly s: string }>({ * n: Number.ReducerSum, @@ -646,8 +635,7 @@ export function getCombiner( * **Example** * * ```ts - * import { Struct } from "effect" - * import { Number, String } from "effect" + * import { Number, String, Struct } from "effect" * * const R = Struct.getReducer<{ readonly n: number; readonly s: string }>({ * n: Number.ReducerSum, diff --git a/packages/effect/src/SubscriptionRef.ts b/packages/effect/src/SubscriptionRef.ts index 84428e2004..99e2ca8a4e 100644 --- a/packages/effect/src/SubscriptionRef.ts +++ b/packages/effect/src/SubscriptionRef.ts @@ -77,16 +77,16 @@ export const make: (value: A) => Effect.Effect> = Effect.f * * @example * ```ts - * import { Effect } from "effect" - * import { Stream, SubscriptionRef } from "effect" + * import { Effect, Stream, SubscriptionRef } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const ref = yield* SubscriptionRef.make(0) * * const stream = SubscriptionRef.changes(ref) * - * const fiber = yield* Stream.runForEach(stream, (value) => - * Effect.sync(() => console.log("Value:", value)) + * const fiber = yield* Stream.runForEach( + * stream, + * (value) => Effect.sync(() => console.log("Value:", value)) * ).pipe(Effect.forkScoped) * * yield* SubscriptionRef.set(ref, 1) @@ -117,10 +117,9 @@ export const changes = (self: SubscriptionRef): Stream.Stream => * * @example * ```ts - * import { Effect } from "effect" - * import { SubscriptionRef } from "effect" + * import { Effect, SubscriptionRef } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const ref = yield* SubscriptionRef.make(42) * * const value = SubscriptionRef.getUnsafe(ref) @@ -138,10 +137,9 @@ export const getUnsafe = (self: SubscriptionRef): A => self.backing.ref.cu * * @example * ```ts - * import { Effect } from "effect" - * import { SubscriptionRef } from "effect" + * import { Effect, SubscriptionRef } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const ref = yield* SubscriptionRef.make(42) * * const value = yield* SubscriptionRef.get(ref) @@ -160,10 +158,9 @@ export const get = (self: SubscriptionRef): Effect.Effect => Effect.syn * * @example * ```ts - * import { Effect } from "effect" - * import { SubscriptionRef } from "effect" + * import { Effect, SubscriptionRef } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const ref = yield* SubscriptionRef.make(10) * * const oldValue = yield* SubscriptionRef.getAndSet(ref, 20) @@ -192,10 +189,9 @@ export const getAndSet: { * * @example * ```ts - * import { Effect } from "effect" - * import { SubscriptionRef } from "effect" + * import { Effect, SubscriptionRef } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const ref = yield* SubscriptionRef.make(10) * * const oldValue = yield* SubscriptionRef.getAndUpdate(ref, (n) => n * 2) @@ -226,14 +222,14 @@ export const getAndUpdate: { * * @example * ```ts - * import { Effect } from "effect" - * import { SubscriptionRef } from "effect" + * import { Effect, SubscriptionRef } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const ref = yield* SubscriptionRef.make(10) * - * const oldValue = yield* SubscriptionRef.getAndUpdateEffect(ref, (n) => - * Effect.succeed(n + 5) + * const oldValue = yield* SubscriptionRef.getAndUpdateEffect( + * ref, + * (n) => Effect.succeed(n + 5) * ) * console.log("Old value:", oldValue) * @@ -267,15 +263,14 @@ export const getAndUpdateEffect: { * * @example * ```ts - * import { Effect } from "effect" - * import { Option } from "effect" - * import { SubscriptionRef } from "effect" + * import { Effect, Option, SubscriptionRef } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const ref = yield* SubscriptionRef.make(10) * - * const oldValue = yield* SubscriptionRef.getAndUpdateSome(ref, (n) => - * n > 5 ? Option.some(n * 2) : Option.none() + * const oldValue = yield* SubscriptionRef.getAndUpdateSome( + * ref, + * (n) => n > 5 ? Option.some(n * 2) : Option.none() * ) * console.log("Old value:", oldValue) * @@ -311,11 +306,9 @@ export const getAndUpdateSome: { * * @example * ```ts - * import { Effect } from "effect" - * import { Option } from "effect" - * import { SubscriptionRef } from "effect" + * import { Effect, Option, SubscriptionRef } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const ref = yield* SubscriptionRef.make(10) * * const oldValue = yield* SubscriptionRef.getAndUpdateSomeEffect( @@ -361,10 +354,9 @@ export const getAndUpdateSomeEffect: { * * @example * ```ts - * import { Effect } from "effect" - * import { SubscriptionRef } from "effect" + * import { Effect, SubscriptionRef } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const ref = yield* SubscriptionRef.make(10) * * const result = yield* SubscriptionRef.modify(ref, (n) => [ @@ -401,14 +393,14 @@ export const modify: { * * @example * ```ts - * import { Effect } from "effect" - * import { SubscriptionRef } from "effect" + * import { Effect, SubscriptionRef } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const ref = yield* SubscriptionRef.make(10) * - * const result = yield* SubscriptionRef.modifyEffect(ref, (n) => - * Effect.succeed([`Doubled from ${n}`, n * 2] as const) + * const result = yield* SubscriptionRef.modifyEffect( + * ref, + * (n) => Effect.succeed([`Doubled from ${n}`, n * 2] as const) * ) * console.log(result) * @@ -447,15 +439,15 @@ export const modifyEffect: { * * @example * ```ts - * import { Effect } from "effect" - * import { Option } from "effect" - * import { SubscriptionRef } from "effect" + * import { Effect, Option, SubscriptionRef } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const ref = yield* SubscriptionRef.make(10) * - * const result = yield* SubscriptionRef.modifySome(ref, (n) => - * n > 5 ? ["Updated", Option.some(n * 2)] : ["Not updated", Option.none()] + * const result = yield* SubscriptionRef.modifySome( + * ref, + * (n) => + * n > 5 ? ["Updated", Option.some(n * 2)] : ["Not updated", Option.none()] * ) * console.log(result) * @@ -495,19 +487,19 @@ export const modifySome: { * * @example * ```ts - * import { Effect } from "effect" - * import { Option } from "effect" - * import { SubscriptionRef } from "effect" + * import { Effect, Option, SubscriptionRef } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const ref = yield* SubscriptionRef.make(10) * - * const result = yield* SubscriptionRef.modifySomeEffect(ref, (n) => - * Effect.succeed( - * n > 5 - * ? (["Updated", Option.some(n + 5)] as const) - * : (["Not updated", Option.none()] as const) - * ) + * const result = yield* SubscriptionRef.modifySomeEffect( + * ref, + * (n) => + * Effect.succeed( + * n > 5 + * ? (["Updated", Option.some(n + 5)] as const) + * : (["Not updated", Option.none()] as const) + * ) * ) * console.log(result) * @@ -548,10 +540,9 @@ export const modifySomeEffect: { * * @example * ```ts - * import { Effect } from "effect" - * import { SubscriptionRef } from "effect" + * import { Effect, SubscriptionRef } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const ref = yield* SubscriptionRef.make(0) * * yield* SubscriptionRef.set(ref, 42) @@ -579,10 +570,9 @@ export const set: { * * @example * ```ts - * import { Effect } from "effect" - * import { SubscriptionRef } from "effect" + * import { Effect, SubscriptionRef } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const ref = yield* SubscriptionRef.make(0) * * const newValue = yield* SubscriptionRef.setAndGet(ref, 42) @@ -608,10 +598,9 @@ export const setAndGet: { * * @example * ```ts - * import { Effect } from "effect" - * import { SubscriptionRef } from "effect" + * import { Effect, SubscriptionRef } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const ref = yield* SubscriptionRef.make(10) * * yield* SubscriptionRef.update(ref, (n) => n * 2) @@ -640,15 +629,12 @@ export const update: { * * @example * ```ts - * import { Effect } from "effect" - * import { SubscriptionRef } from "effect" + * import { Effect, SubscriptionRef } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const ref = yield* SubscriptionRef.make(10) * - * yield* SubscriptionRef.updateEffect(ref, (n) => - * Effect.succeed(n + 5) - * ) + * yield* SubscriptionRef.updateEffect(ref, (n) => Effect.succeed(n + 5)) * * const value = yield* SubscriptionRef.get(ref) * console.log(value) @@ -679,10 +665,9 @@ export const updateEffect: { * * @example * ```ts - * import { Effect } from "effect" - * import { SubscriptionRef } from "effect" + * import { Effect, SubscriptionRef } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const ref = yield* SubscriptionRef.make(10) * * const newValue = yield* SubscriptionRef.updateAndGet(ref, (n) => n * 2) @@ -710,14 +695,14 @@ export const updateAndGet: { * * @example * ```ts - * import { Effect } from "effect" - * import { SubscriptionRef } from "effect" + * import { Effect, SubscriptionRef } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const ref = yield* SubscriptionRef.make(10) * - * const newValue = yield* SubscriptionRef.updateAndGetEffect(ref, (n) => - * Effect.succeed(n + 5) + * const newValue = yield* SubscriptionRef.updateAndGetEffect( + * ref, + * (n) => Effect.succeed(n + 5) * ) * console.log("New value:", newValue) * }) @@ -748,15 +733,14 @@ export const updateAndGetEffect: { * * @example * ```ts - * import { Effect } from "effect" - * import { Option } from "effect" - * import { SubscriptionRef } from "effect" + * import { Effect, Option, SubscriptionRef } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const ref = yield* SubscriptionRef.make(10) * - * yield* SubscriptionRef.updateSome(ref, (n) => - * n > 5 ? Option.some(n * 2) : Option.none() + * yield* SubscriptionRef.updateSome( + * ref, + * (n) => n > 5 ? Option.some(n * 2) : Option.none() * ) * * const value = yield* SubscriptionRef.get(ref) @@ -790,15 +774,14 @@ export const updateSome: { * * @example * ```ts - * import { Effect } from "effect" - * import { Option } from "effect" - * import { SubscriptionRef } from "effect" + * import { Effect, Option, SubscriptionRef } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const ref = yield* SubscriptionRef.make(10) * - * yield* SubscriptionRef.updateSomeEffect(ref, (n) => - * Effect.succeed(n > 5 ? Option.some(n + 3) : Option.none()) + * yield* SubscriptionRef.updateSomeEffect( + * ref, + * (n) => Effect.succeed(n > 5 ? Option.some(n + 3) : Option.none()) * ) * * const value = yield* SubscriptionRef.get(ref) @@ -839,15 +822,14 @@ export const updateSomeEffect: { * * @example * ```ts - * import { Effect } from "effect" - * import { Option } from "effect" - * import { SubscriptionRef } from "effect" + * import { Effect, Option, SubscriptionRef } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const ref = yield* SubscriptionRef.make(10) * - * const newValue = yield* SubscriptionRef.updateSomeAndGet(ref, (n) => - * n > 5 ? Option.some(n * 2) : Option.none() + * const newValue = yield* SubscriptionRef.updateSomeAndGet( + * ref, + * (n) => n > 5 ? Option.some(n * 2) : Option.none() * ) * console.log("New value:", newValue) * }) @@ -880,11 +862,9 @@ export const updateSomeAndGet: { * * @example * ```ts - * import { Effect } from "effect" - * import { Option } from "effect" - * import { SubscriptionRef } from "effect" + * import { Effect, Option, SubscriptionRef } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const ref = yield* SubscriptionRef.make(10) * * const newValue = yield* SubscriptionRef.updateSomeAndGetEffect( diff --git a/packages/effect/src/platform/Terminal.ts b/packages/effect/src/Terminal.ts similarity index 90% rename from packages/effect/src/platform/Terminal.ts rename to packages/effect/src/Terminal.ts index b68c8260cc..e02aa4a990 100644 --- a/packages/effect/src/platform/Terminal.ts +++ b/packages/effect/src/Terminal.ts @@ -1,13 +1,13 @@ /** * @since 4.0.0 */ -import type * as Effect from "../Effect.ts" -import * as Predicate from "../Predicate.ts" -import type * as Queue from "../Queue.ts" -import * as Schema from "../schema/Schema.ts" -import type * as Scope from "../Scope.ts" -import * as ServiceMap from "../ServiceMap.ts" +import type * as Effect from "./Effect.ts" import type { PlatformError } from "./PlatformError.ts" +import * as Predicate from "./Predicate.ts" +import type * as Queue from "./Queue.ts" +import * as Schema from "./schema/Schema.ts" +import type * as Scope from "./Scope.ts" +import * as ServiceMap from "./ServiceMap.ts" const TypeId = "~effect/platform/Terminal" diff --git a/packages/effect/src/Tracer.ts b/packages/effect/src/Tracer.ts index d06d1202a9..d67a11d2fa 100644 --- a/packages/effect/src/Tracer.ts +++ b/packages/effect/src/Tracer.ts @@ -11,12 +11,18 @@ import * as ServiceMap from "./ServiceMap.ts" * @category models * @example * ```ts - * import { Tracer } from "effect" - * import { ServiceMap } from "effect" + * import { ServiceMap, Tracer } from "effect" * * // Create a custom tracer implementation * const customTracer: Tracer.Tracer = { - * span: (name: string, parent: Tracer.AnySpan | undefined, context: ServiceMap.ServiceMap, links: ReadonlyArray, startTime: bigint, kind: Tracer.SpanKind) => { + * span: ( + * name: string, + * parent: Tracer.AnySpan | undefined, + * context: ServiceMap.ServiceMap, + * links: ReadonlyArray, + * startTime: bigint, + * kind: Tracer.SpanKind + * ) => { * console.log(`Creating span: ${name}`) * return new Tracer.NativeSpan(name, parent, context, links, startTime, kind) * }, @@ -49,8 +55,8 @@ export interface Tracer { * @category models * @example * ```ts + * import type { Tracer } from "effect" * import { Exit } from "effect" - * import { Tracer } from "effect" * * // Started span status * const startedStatus: Tracer.SpanStatus = { @@ -82,8 +88,7 @@ export type SpanStatus = { * @category models * @example * ```ts - * import { Effect } from "effect" - * import { Tracer } from "effect" + * import { Effect, Tracer } from "effect" * * // Function that accepts any span type * const logSpan = (span: Tracer.AnySpan) => { @@ -118,11 +123,10 @@ export const ParentSpanKey = "effect/Tracer/ParentSpan" * @category tags * @example * ```ts - * import { Effect } from "effect" - * import { Tracer } from "effect" + * import { Effect, Tracer } from "effect" * * // Access the parent span from the context - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const parentSpan = yield* Effect.service(Tracer.ParentSpan) * console.log(`Parent span: ${parentSpan.spanId}`) * }) @@ -135,8 +139,7 @@ export class ParentSpan extends ServiceMap.Service()(Parent * @category models * @example * ```ts - * import { Tracer } from "effect" - * import { ServiceMap } from "effect" + * import { ServiceMap, Tracer } from "effect" * * // Create an external span from another tracing system * const externalSpan: Tracer.ExternalSpan = { @@ -163,8 +166,8 @@ export interface ExternalSpan { * @category models * @example * ```ts + * import type { Tracer } from "effect" * import { Effect } from "effect" - * import { Tracer } from "effect" * * // Create an effect with span options * const options: Tracer.SpanOptions = { @@ -207,8 +210,8 @@ export interface TraceOptions { * @category models * @example * ```ts + * import type { Tracer } from "effect" * import { Effect } from "effect" - * import { Tracer } from "effect" * * // Different span kinds for different operations * const serverSpan = Effect.withSpan("handle-request", { @@ -264,8 +267,7 @@ export interface Span { * @category models * @example * ```ts - * import { Effect } from "effect" - * import { Tracer } from "effect" + * import { Effect, Tracer } from "effect" * * // Create a span link to connect spans * const externalSpan = Tracer.externalSpan({ @@ -294,8 +296,6 @@ export interface SpanLink { * @example * ```ts * import { Tracer } from "effect" - * import { ServiceMap } from "effect" - * import { Option } from "effect" * * // Create a custom tracer with logging * const loggingTracer = Tracer.make({ @@ -317,8 +317,7 @@ export const make = (options: Tracer): Tracer => options * @category constructors * @example * ```ts - * import { Effect } from "effect" - * import { Tracer } from "effect" + * import { Effect, Tracer } from "effect" * * // Create an external span from another tracing system * const span = Tracer.externalSpan({ @@ -353,11 +352,10 @@ export const externalSpan = ( * @category references * @example * ```ts - * import { Effect } from "effect" - * import { Tracer } from "effect" + * import { Effect, Tracer } from "effect" * * // Disable span propagation for a specific effect - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * yield* Effect.log("This will not propagate parent span") * }).pipe( * Effect.provideService(Tracer.DisablePropagation, true) @@ -380,17 +378,16 @@ export const TracerKey = "effect/Tracer" * @category references * @example * ```ts - * import { Effect } from "effect" - * import { Tracer } from "effect" + * import { Effect, Tracer } from "effect" * * // Access the current tracer from the context - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const tracer = yield* Effect.service(Tracer.Tracer) * console.log("Using current tracer") * }) * * // Or use the built-in tracer effect - * const tracerEffect = Effect.gen(function* () { + * const tracerEffect = Effect.gen(function*() { * const tracer = yield* Effect.tracer * console.log("Current tracer obtained") * }) @@ -416,9 +413,7 @@ export const Tracer: ServiceMap.Reference = ServiceMap.Reference * @category native tracer * @example * ```ts - * import { Tracer } from "effect" - * import { ServiceMap } from "effect" - * import { Option } from "effect" + * import { ServiceMap, Tracer } from "effect" * * // Create a native span directly * const span = new Tracer.NativeSpan( diff --git a/packages/effect/src/Trie.ts b/packages/effect/src/Trie.ts index 0b43266fb7..8c7f3704a4 100644 --- a/packages/effect/src/Trie.ts +++ b/packages/effect/src/Trie.ts @@ -27,7 +27,6 @@ const TypeId = TR.TrieTypeId /** * @example * ```ts - * import * as Option from "effect/Option" * import * as Trie from "effect/Trie" * * // Create a trie with string-to-number mappings @@ -73,9 +72,8 @@ export interface Trie extends Iterable<[string, Value]>, Equal, Pi * * @example * ```ts - * import * as assert from "node:assert" * import * as Trie from "effect/Trie" - * import * as Equal from "effect/Equal" + * import * as assert from "node:assert" * * const trie = Trie.empty() * @@ -93,16 +91,28 @@ export const empty: () => Trie = TR.empty * * @example * ```ts - * import * as assert from "node:assert" - * import * as Trie from "effect/Trie" * import * as Equal from "effect/Equal" + * import * as Trie from "effect/Trie" + * import * as assert from "node:assert" * - * const iterable: Array = [["call", 0], ["me", 1], ["mind", 2], ["mid", 3]] + * const iterable: Array = [["call", 0], ["me", 1], [ + * "mind", + * 2 + * ], ["mid", 3]] * const trie = Trie.fromIterable(iterable) * * // The entries in the `Trie` are extracted in alphabetical order, regardless of the insertion order - * assert.deepStrictEqual(Array.from(trie), [["call", 0], ["me", 1], ["mid", 3], ["mind", 2]]) - * assert.equal(Equal.equals(Trie.make(["call", 0], ["me", 1], ["mind", 2], ["mid", 3]), trie), true) + * assert.deepStrictEqual(Array.from(trie), [["call", 0], ["me", 1], ["mid", 3], [ + * "mind", + * 2 + * ]]) + * assert.equal( + * Equal.equals( + * Trie.make(["call", 0], ["me", 1], ["mind", 2], ["mid", 3]), + * trie + * ), + * true + * ) * ``` * * @since 2.0.0 @@ -115,14 +125,17 @@ export const fromIterable: (entries: Iterable) => Trie< * * @example * ```ts - * import * as assert from "node:assert" - * import * as Trie from "effect/Trie" * import * as Equal from "effect/Equal" + * import * as Trie from "effect/Trie" + * import * as assert from "node:assert" * * const trie = Trie.make(["ca", 0], ["me", 1]) * * assert.deepStrictEqual(Array.from(trie), [["ca", 0], ["me", 1]]) - * assert.equal(Equal.equals(Trie.fromIterable([["ca", 0], ["me", 1]]), trie), true) + * assert.equal( + * Equal.equals(Trie.fromIterable([["ca", 0], ["me", 1]]), trie), + * true + * ) * ``` * * @since 2.0.0 @@ -137,8 +150,8 @@ export const make: >( * * @example * ```ts - * import * as assert from "node:assert" * import * as Trie from "effect/Trie" + * import * as assert from "node:assert" * * const trie1 = Trie.empty().pipe( * Trie.insert("call", 0) @@ -150,7 +163,10 @@ export const make: >( * assert.deepStrictEqual(Array.from(trie1), [["call", 0]]) * assert.deepStrictEqual(Array.from(trie2), [["call", 0], ["me", 1]]) * assert.deepStrictEqual(Array.from(trie3), [["call", 0], ["me", 1], ["mind", 2]]) - * assert.deepStrictEqual(Array.from(trie4), [["call", 0], ["me", 1], ["mid", 3], ["mind", 2]]) + * assert.deepStrictEqual(Array.from(trie4), [["call", 0], ["me", 1], ["mid", 3], [ + * "mind", + * 2 + * ]]) * ``` * * @since 2.0.0 @@ -168,8 +184,8 @@ export const insert: { * * @example * ```ts - * import * as assert from "node:assert" * import * as Trie from "effect/Trie" + * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( * Trie.insert("cab", 0), @@ -193,8 +209,8 @@ export const keys: (self: Trie) => IterableIterator = TR.keys * * @example * ```ts - * import * as assert from "node:assert" * import * as Trie from "effect/Trie" + * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( * Trie.insert("call", 0), @@ -218,8 +234,8 @@ export const values: (self: Trie) => IterableIterator = TR.values * * @example * ```ts - * import * as assert from "node:assert" * import * as Trie from "effect/Trie" + * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( * Trie.insert("call", 0), @@ -242,8 +258,8 @@ export const entries: (self: Trie) => IterableIterator<[string, V]> = TR.e * * @example * ```ts - * import * as assert from "node:assert" * import * as Trie from "effect/Trie" + * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( * Trie.insert("call", 0), @@ -265,8 +281,8 @@ export const toEntries = (self: Trie): Array<[string, V]> => Array.from(en * * @example * ```ts - * import * as assert from "node:assert" * import * as Trie from "effect/Trie" + * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( * Trie.insert("she", 0), @@ -293,8 +309,8 @@ export const keysWithPrefix: { * * @example * ```ts - * import * as assert from "node:assert" * import * as Trie from "effect/Trie" + * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( * Trie.insert("she", 0), @@ -323,8 +339,8 @@ export const valuesWithPrefix: { * * @example * ```ts - * import * as assert from "node:assert" * import * as Trie from "effect/Trie" + * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( * Trie.insert("she", 0), @@ -351,8 +367,8 @@ export const entriesWithPrefix: { * * @example * ```ts - * import * as assert from "node:assert" * import * as Trie from "effect/Trie" + * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( * Trie.insert("shells", 0), @@ -379,8 +395,8 @@ export const toEntriesWithPrefix: { * * @example * ```ts - * import * as assert from "node:assert" * import * as Trie from "effect/Trie" + * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( * Trie.insert("shells", 0), @@ -407,8 +423,8 @@ export const longestPrefixOf: { * * @example * ```ts - * import * as assert from "node:assert" * import * as Trie from "effect/Trie" + * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( * Trie.insert("a", 0), @@ -428,9 +444,9 @@ export const size: (self: Trie) => number = TR.size * * @example * ```ts - * import * as assert from "node:assert" * import * as Option from "effect/Option" * import * as Trie from "effect/Trie" + * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( * Trie.insert("call", 0), @@ -462,8 +478,8 @@ export const get: { * * @example * ```ts - * import * as assert from "node:assert" * import * as Trie from "effect/Trie" + * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( * Trie.insert("call", 0), @@ -495,8 +511,8 @@ export const has: { * * @example * ```ts - * import * as assert from "node:assert" * import * as Trie from "effect/Trie" + * import * as assert from "node:assert" * * const trie = Trie.empty() * const trie1 = trie.pipe(Trie.insert("ma", 0)) @@ -518,8 +534,8 @@ export const isEmpty: (self: Trie) => boolean = TR.isEmpty * * @example * ```ts - * import * as assert from "node:assert" * import * as Trie from "effect/Trie" + * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( * Trie.insert("call", 0), @@ -542,9 +558,9 @@ export const getUnsafe: { * * @example * ```ts - * import * as assert from "node:assert" * import * as Option from "effect/Option" * import * as Trie from "effect/Trie" + * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( * Trie.insert("call", 0), @@ -574,8 +590,8 @@ export const remove: { * * @example * ```ts - * import * as assert from "node:assert" * import * as Trie from "effect/Trie" + * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( * Trie.insert("shells", 0), @@ -616,9 +632,9 @@ export const reduce: { * * @example * ```ts - * import * as assert from "node:assert" - * import * as Trie from "effect/Trie" * import * as Equal from "effect/Equal" + * import * as Trie from "effect/Trie" + * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( * Trie.insert("shells", 0), @@ -655,9 +671,9 @@ export const map: { * * @example * ```ts - * import * as assert from "node:assert" - * import * as Trie from "effect/Trie" * import * as Equal from "effect/Equal" + * import * as Trie from "effect/Trie" + * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( * Trie.insert("shells", 0), @@ -675,7 +691,10 @@ export const map: { * ) * * assert.equal(Equal.equals(Trie.filter(trie, (v) => v > 1), trieMapV), true) - * assert.equal(Equal.equals(Trie.filter(trie, (_, k) => k.length > 3), trieMapK), true) + * assert.equal( + * Equal.equals(Trie.filter(trie, (_, k) => k.length > 3), trieMapK), + * true + * ) * ``` * * @since 2.0.0 @@ -694,10 +713,10 @@ export const filter: { * * @example * ```ts - * import * as assert from "node:assert" - * import * as Trie from "effect/Trie" * import * as Equal from "effect/Equal" * import * as Option from "effect/Option" + * import * as Trie from "effect/Trie" + * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( * Trie.insert("shells", 0), @@ -714,9 +733,21 @@ export const filter: { * Trie.insert("sells", 1) * ) * - * assert.equal(Equal.equals(Trie.filterMap(trie, (v) => v > 1 ? Option.some(v) : Option.none()), trieMapV), true) * assert.equal( - * Equal.equals(Trie.filterMap(trie, (v, k) => k.length > 3 ? Option.some(v) : Option.none()), trieMapK), + * Equal.equals( + * Trie.filterMap(trie, (v) => v > 1 ? Option.some(v) : Option.none()), + * trieMapV + * ), + * true + * ) + * assert.equal( + * Equal.equals( + * Trie.filterMap( + * trie, + * (v, k) => k.length > 3 ? Option.some(v) : Option.none() + * ), + * trieMapK + * ), * true * ) * ``` @@ -734,10 +765,10 @@ export const filterMap: { * * @example * ```ts - * import * as assert from "node:assert" - * import * as Trie from "effect/Trie" * import * as Equal from "effect/Equal" * import * as Option from "effect/Option" + * import * as Trie from "effect/Trie" + * import * as assert from "node:assert" * * const trie = Trie.empty>().pipe( * Trie.insert("shells", Option.some(0)), @@ -763,8 +794,8 @@ export const compact: (self: Trie>) => Trie = TR.compact * * @example * ```ts - * import * as assert from "node:assert" * import * as Trie from "effect/Trie" + * import * as assert from "node:assert" * * let value = 0 * @@ -793,10 +824,10 @@ export const forEach: { * * @example * ```ts - * import * as assert from "node:assert" - * import * as Trie from "effect/Trie" * import * as Equal from "effect/Equal" * import * as Option from "effect/Option" + * import * as Trie from "effect/Trie" + * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( * Trie.insert("shells", 0), @@ -804,7 +835,10 @@ export const forEach: { * Trie.insert("she", 2) * ) * - * assert.deepStrictEqual(trie.pipe(Trie.modify("she", (v) => v + 10), Trie.get("she")), Option.some(12)) + * assert.deepStrictEqual( + * trie.pipe(Trie.modify("she", (v) => v + 10), Trie.get("she")), + * Option.some(12) + * ) * * assert.equal(Equal.equals(trie.pipe(Trie.modify("me", (v) => v)), trie), true) * ``` @@ -822,9 +856,9 @@ export const modify: { * * @example * ```ts - * import * as assert from "node:assert" - * import * as Trie from "effect/Trie" * import * as Equal from "effect/Equal" + * import * as Trie from "effect/Trie" + * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( * Trie.insert("shells", 0), @@ -833,7 +867,10 @@ export const modify: { * ) * * assert.equal( - * Equal.equals(trie.pipe(Trie.removeMany(["she", "sells"])), Trie.empty().pipe(Trie.insert("shells", 0))), + * Equal.equals( + * trie.pipe(Trie.removeMany(["she", "sells"])), + * Trie.empty().pipe(Trie.insert("shells", 0)) + * ), * true * ) * ``` @@ -851,9 +888,9 @@ export const removeMany: { * * @example * ```ts - * import * as assert from "node:assert" - * import * as Trie from "effect/Trie" * import * as Equal from "effect/Equal" + * import * as Trie from "effect/Trie" + * import * as assert from "node:assert" * * const trie = Trie.empty().pipe( * Trie.insert("shells", 0), diff --git a/packages/effect/src/Tuple.ts b/packages/effect/src/Tuple.ts index 91f488c053..4e37b610dc 100644 --- a/packages/effect/src/Tuple.ts +++ b/packages/effect/src/Tuple.ts @@ -15,10 +15,10 @@ import type { Apply, Lambda } from "./Struct.ts" * * @example * ```ts - * import * as assert from "node:assert" * import { make } from "effect/Tuple" + * import * as assert from "node:assert" * - * assert.deepStrictEqual(make(1, 'hello', true), [1, 'hello', true]) + * assert.deepStrictEqual(make(1, "hello", true), [1, "hello", true]) * ``` * * @category Constructors @@ -35,7 +35,7 @@ type Indices> = Exclude["length"], T * ```ts * import { Tuple } from "effect" * - * console.log(Tuple.get([1, true, 'hello'], 2)) + * console.log(Tuple.get([1, true, "hello"], 2)) * // 'hello' * ``` * @@ -190,10 +190,8 @@ type Evolved = { [I in keyof T]: I extends keyof E ? (E[I] extends (...a: * * @example * ```ts - * import { Tuple } from "effect" - * * // Transform specific elements by index - * const original = ["hello", 42, true] + * const evolveOriginal = ["hello", 42, true] * const transformers = { * 0: (s: string) => s.toUpperCase(), * 1: (n: number) => n * 2 @@ -219,10 +217,8 @@ export const evolve: { * * @example * ```ts - * import { Tuple } from "effect" - * * // Example demonstrates index remapping concept - * const original = ["a", "b", "c"] + * const renameOriginal = ["a", "b", "c"] * const mapping = { 0: "2", 1: "0" } * // Result would remap indices according to the mapping * ``` @@ -253,10 +249,8 @@ export const renameIndices: { * * @example * ```ts - * import { Tuple } from "effect" - * * // Used with lambda functions for transforming all elements - * const tuple = [1, 2, 3] as const + * const mapTuple = [1, 2, 3] as const * // Map applies transformation to each element * ``` * @@ -285,10 +279,8 @@ export const map: { * * @example * ```ts - * import { Tuple } from "effect" - * * // Transform only elements at specified indices - * const tuple = [1, 2, 3] as const + * const pickTuple = [1, 2, 3] as const * const indices = [0, 2] * // Transforms elements at index 0 and 2 only * ``` @@ -325,10 +317,8 @@ export const mapPick: { * * @example * ```ts - * import { Tuple } from "effect" - * * // Transform all elements except those at specified indices - * const tuple = [1, 2, 3] as const + * const omitTuple = [1, 2, 3] as const * const indicesToOmit = [1] * // Transforms all elements except index 1 * ``` @@ -365,10 +355,13 @@ export const mapOmit: { * * @example * ```ts - * import { Tuple, Equivalence } from "effect" + * import { Equivalence, Tuple } from "effect" * * // Creates an equivalence for tuples with string and number elements - * const equivalence = Tuple.getEquivalence([Equivalence.strict(), Equivalence.strict()]) + * const equivalence = Tuple.getEquivalence([ + * Equivalence.strict(), + * Equivalence.strict() + * ]) * ``` * * @category Equivalence @@ -382,8 +375,8 @@ export const getEquivalence = Equivalence.tuple * @example * ```ts * import { Tuple } from "effect" - * import * as S from "effect/String" * import * as N from "effect/Number" + * import * as S from "effect/String" * * // Creates an order for tuples with string and number elements * const tupleOrder = Tuple.getOrder([S.Order, N.Order]) @@ -402,19 +395,18 @@ export { * * @example * ```ts - * import * as assert from "node:assert" * import { isTupleOf } from "effect/Tuple" + * import * as assert from "node:assert" * - * assert.deepStrictEqual(isTupleOf([1, 2, 3], 3), true); - * assert.deepStrictEqual(isTupleOf([1, 2, 3], 2), false); - * assert.deepStrictEqual(isTupleOf([1, 2, 3], 4), false); + * assert.deepStrictEqual(isTupleOf([1, 2, 3], 3), true) + * assert.deepStrictEqual(isTupleOf([1, 2, 3], 2), false) + * assert.deepStrictEqual(isTupleOf([1, 2, 3], 4), false) * - * const arr: number[] = [1, 2, 3]; + * const arr: Array = [1, 2, 3] * if (isTupleOf(arr, 3)) { - * console.log(arr); + * console.log(arr) * // ^? [number, number, number] * } - * * ``` * @category Guards * @since 3.3.0 @@ -427,19 +419,18 @@ export { * * @example * ```ts - * import * as assert from "node:assert" * import { isTupleOfAtLeast } from "effect/Tuple" + * import * as assert from "node:assert" * - * assert.deepStrictEqual(isTupleOfAtLeast([1, 2, 3], 3), true); - * assert.deepStrictEqual(isTupleOfAtLeast([1, 2, 3], 2), true); - * assert.deepStrictEqual(isTupleOfAtLeast([1, 2, 3], 4), false); + * assert.deepStrictEqual(isTupleOfAtLeast([1, 2, 3], 3), true) + * assert.deepStrictEqual(isTupleOfAtLeast([1, 2, 3], 2), true) + * assert.deepStrictEqual(isTupleOfAtLeast([1, 2, 3], 4), false) * - * const arr: number[] = [1, 2, 3, 4]; + * const arr: Array = [1, 2, 3, 4] * if (isTupleOfAtLeast(arr, 3)) { - * console.log(arr); + * console.log(arr) * // ^? [number, number, number, ...number[]] * } - * * ``` * @category Guards * @since 3.3.0 @@ -460,10 +451,12 @@ export { * **Example** * * ```ts - * import { Tuple } from "effect" - * import { Number, String } from "effect" + * import { Number, String, Tuple } from "effect" * - * const C = Tuple.getCombiner([Number.ReducerSum, String.ReducerConcat]) + * const C = Tuple.getCombiner([ + * Number.ReducerSum, + * String.ReducerConcat + * ]) * ``` * * @since 4.0.0 @@ -496,10 +489,12 @@ export function getCombiner>( * **Example** * * ```ts - * import { Tuple } from "effect" - * import { Number, String } from "effect" + * import { Number, String, Tuple } from "effect" * - * const R = Tuple.getReducer([Number.ReducerSum, String.ReducerConcat]) + * const R = Tuple.getReducer([ + * Number.ReducerSum, + * String.ReducerConcat + * ]) * ``` * * @since 4.0.0 diff --git a/packages/effect/src/Utils.ts b/packages/effect/src/Utils.ts index dfdfe70109..24f3203870 100644 --- a/packages/effect/src/Utils.ts +++ b/packages/effect/src/Utils.ts @@ -106,11 +106,16 @@ export const makeGenKind = ( /** * @example * ```ts - * import { Utils } from "effect" - * import * as Option from "effect/Option" + * import type { Utils } from "effect" + * import type * as Option from "effect/Option" * * // Variance defines the type parameter relationships - * declare const variance: Utils.Variance + * declare const variance: Utils.Variance< + * Option.OptionTypeLambda, + * never, + * never, + * never + * > * ``` * * @category models @@ -127,8 +132,7 @@ export interface Variance { /** * @example * ```ts - * import { Utils } from "effect" - * import { Option } from "effect" + * import type { Option, Utils } from "effect" * * // Gen enables generator-based syntax for any TypeLambda * declare const gen: Utils.Gen @@ -167,7 +171,7 @@ export type Gen = < /** * @example * ```ts - * import { Utils } from "effect" + * import type { Utils } from "effect" * * const value1: Utils.OptionalNumber = 42 * const value2: Utils.OptionalNumber = null diff --git a/packages/effect/src/encoding/Base64.ts b/packages/effect/src/encoding/Base64.ts index 151fe6b05f..ab4cd493b3 100644 --- a/packages/effect/src/encoding/Base64.ts +++ b/packages/effect/src/encoding/Base64.ts @@ -67,8 +67,8 @@ const encodeUint8Array = (bytes: Uint8Array) => { * * @example * ```ts - * import { Base64 } from "effect/encoding" * import { Result } from "effect" + * import { Base64 } from "effect/encoding" * * const result = Base64.decode("SGVsbG8=") * if (Result.isSuccess(result)) { @@ -137,8 +137,8 @@ export const decode = (str: string): Result.Result => * * @example * ```ts - * import { Base64 } from "effect/encoding" * import { Result } from "effect" + * import { Base64 } from "effect/encoding" * * const result = Base64.decodeString("aGVsbG8=") * if (Result.isSuccess(result)) { diff --git a/packages/effect/src/encoding/Base64Url.ts b/packages/effect/src/encoding/Base64Url.ts index d9edacd040..f11e021a01 100644 --- a/packages/effect/src/encoding/Base64Url.ts +++ b/packages/effect/src/encoding/Base64Url.ts @@ -33,8 +33,8 @@ const encodeUint8Array = (data: Uint8Array) => * * @example * ```ts - * import { Base64Url } from "effect/encoding" * import { Result } from "effect" + * import { Base64Url } from "effect/encoding" * * const result = Base64Url.decode("SGVsbG8_") * if (Result.isSuccess(result)) { @@ -82,8 +82,8 @@ export const decode = (str: string): Result.Result => * * @example * ```ts - * import { Base64Url } from "effect/encoding" * import { Result } from "effect" + * import { Base64Url } from "effect/encoding" * * const result = Base64Url.decodeString("aGVsbG8_") * if (Result.isSuccess(result)) { diff --git a/packages/effect/src/encoding/Hex.ts b/packages/effect/src/encoding/Hex.ts index 592e18eab9..ab8069a345 100644 --- a/packages/effect/src/encoding/Hex.ts +++ b/packages/effect/src/encoding/Hex.ts @@ -39,8 +39,8 @@ const encodeUint8Array = (bytes: Uint8Array) => { * * @example * ```ts - * import { Hex } from "effect/encoding" * import { Result } from "effect" + * import { Hex } from "effect/encoding" * * const result = Hex.decode("48656c6c6f") * if (Result.isSuccess(result)) { @@ -91,8 +91,8 @@ export const decode = (str: string): Result.Result => * * @example * ```ts - * import { Hex } from "effect/encoding" * import { Result } from "effect" + * import { Hex } from "effect/encoding" * * const result = Hex.decodeString("68656c6c6f") * if (Result.isSuccess(result)) { diff --git a/packages/effect/src/index.ts b/packages/effect/src/index.ts index 21b26bd4bb..8813d68415 100644 --- a/packages/effect/src/index.ts +++ b/packages/effect/src/index.ts @@ -161,7 +161,6 @@ export * as Cause from "./Cause.ts" * @example * ```ts * import { Channel } from "effect" - * import { Effect } from "effect" * * // Simple channel that outputs numbers * const numberChannel = Channel.succeed(42) @@ -175,7 +174,6 @@ export * as Cause from "./Cause.ts" * @example * ```ts * import { Channel } from "effect" - * import { Effect } from "effect" * * // Channel from an array of values * const arrayChannel = Channel.fromArray([1, 2, 3, 4, 5]) @@ -252,12 +250,11 @@ export * as ChannelSchema from "./ChannelSchema.ts" * * @example * ```ts - * import { Chunk } from "effect" -import { Effect } from "effect" + * import { Chunk, Effect } from "effect" * * // Working with Effects * const processChunk = (chunk: Chunk.Chunk) => - * Effect.gen(function* () { + * Effect.gen(function*() { * const mapped = Chunk.map(chunk, (n) => n * 2) * const filtered = Chunk.filter(mapped, (n) => n > 5) * return Chunk.toReadonlyArray(filtered) @@ -461,17 +458,15 @@ export * as DateTime from "./DateTime.ts" * * @example * ```ts - * import { Effect } from "effect" - * import { Deferred } from "effect" - * import { Fiber } from "effect" + * import { Deferred, Effect, Fiber } from "effect" * * // Basic usage: coordinate between fibers - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const deferred = yield* Deferred.make() * * // Fiber 1: waits for the value * const waiter = yield* Effect.forkChild( - * Effect.gen(function* () { + * Effect.gen(function*() { * const value = yield* Deferred.await(deferred) * console.log("Received:", value) * return value @@ -480,7 +475,7 @@ export * as DateTime from "./DateTime.ts" * * // Fiber 2: sets the value after a delay * const setter = yield* Effect.forkChild( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Effect.sleep("1 second") * yield* Deferred.succeed(deferred, "Hello from setter!") * }) @@ -492,15 +487,15 @@ export * as DateTime from "./DateTime.ts" * }) * * // Producer-consumer pattern - * const producerConsumer = Effect.gen(function* () { - * const buffer = yield* Deferred.make() + * const producerConsumer = Effect.gen(function*() { + * const buffer = yield* Deferred.make, never>() * - * const producer = Effect.gen(function* () { + * const producer = Effect.gen(function*() { * const data = [1, 2, 3, 4, 5] * yield* Deferred.succeed(buffer, data) * }) * - * const consumer = Effect.gen(function* () { + * const consumer = Effect.gen(function*() { * const data = yield* Deferred.await(buffer) * return data.reduce((sum, n) => sum + n, 0) * }) @@ -560,14 +555,13 @@ export * as Duration from "./Duration.ts" * * @example * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" + * import { Console, Effect } from "effect" * * // Creating a simple effect * const hello = Effect.succeed("Hello, World!") * * // Composing effects - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const message = yield* hello * yield* Console.log(message) * return message.length @@ -588,7 +582,7 @@ export * as Duration from "./Duration.ts" * : Effect.succeed(a / b) * * // Error handling - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const result = yield* divide(10, 2) * console.log("Result:", result) // Result: 5 * return result @@ -628,8 +622,7 @@ export * as Equal from "./Equal.ts" * * @example * ```ts - * import { Equivalence } from "effect" - * import { Array } from "effect" + * import { Array, Equivalence } from "effect" * * // Case-insensitive string equivalence * const caseInsensitive = Equivalence.make((a, b) => @@ -695,15 +688,13 @@ export * as Exit from "./Exit.ts" * * @example * ```ts - * import { Effect } from "effect" - * import { Console } from "effect" - * import { Fiber } from "effect" + * import { Console, Effect, Fiber } from "effect" * * // Basic fiber operations - * const basicExample = Effect.gen(function* () { + * const basicExample = Effect.gen(function*() { * // Fork an effect to run concurrently * const fiber = yield* Effect.forkChild( - * Effect.gen(function* () { + * Effect.gen(function*() { * yield* Effect.sleep("2 seconds") * yield* Console.log("Background task completed") * return "background result" @@ -720,7 +711,7 @@ export * as Exit from "./Exit.ts" * }) * * // Joining multiple fibers - * const joinExample = Effect.gen(function* () { + * const joinExample = Effect.gen(function*() { * const task1 = Effect.delay(Effect.succeed("task1"), "1 second") * const task2 = Effect.delay(Effect.succeed("task2"), "2 seconds") * @@ -735,9 +726,9 @@ export * as Exit from "./Exit.ts" * }) * * // Parallel execution with structured concurrency - * const parallelExample = Effect.gen(function* () { - * const tasks = [1, 2, 3, 4, 5].map(n => - * Effect.gen(function* () { + * 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 * }) @@ -768,6 +759,45 @@ 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" + /** * @since 4.0.0 */ @@ -873,8 +903,8 @@ export * as Inspectable from "./Inspectable.ts" * * // Create iterables * const numbers = Iterable.range(1, 5) - * const doubled = Iterable.map(numbers, x => x * 2) - * const filtered = Iterable.filter(doubled, x => x > 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] * @@ -990,8 +1020,7 @@ export * as LayerMap from "./LayerMap.ts" * ## Batched Logging * * ```ts - * import { Effect, Logger } from "effect" - * import { Duration } from "effect" + * import { Duration, Effect, Logger } from "effect" * * const batchedLogger = Logger.batched(Logger.formatJson, { * window: Duration.seconds(5), @@ -1457,7 +1486,13 @@ export * as MutableRef from "./MutableRef.ts" * } * * // Using Array.make to create non-empty arrays - * const numbers = Array.make(1, 2, 3, 4, 5) as unknown as NonEmptyIterable.NonEmptyIterable + * 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 @@ -1477,16 +1512,19 @@ export * as MutableRef from "./MutableRef.ts" * ## Working with Different Iterable Types * * ```ts - * import { pipe } from "effect" - * import * as NonEmptyIterable from "effect/NonEmptyIterable" * import { Array } from "effect" - * import * as Chunk from "effect/Chunk" * * // Creating non-empty arrays - * const nonEmptyArray = Array.make(1, 2, 3) as unknown as NonEmptyIterable.NonEmptyIterable + * 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 + * const nonEmptyString = "hello" as unknown as NonEmptyIterable.NonEmptyIterable< + * string + * > * const [firstChar] = NonEmptyIterable.unprepend(nonEmptyString) * console.log(firstChar) // "h" * @@ -1510,17 +1548,18 @@ export * as MutableRef from "./MutableRef.ts" * } * } * - * const [firstFib, restFib] = NonEmptyIterable.unprepend(fibonacci() as unknown as NonEmptyIterable.NonEmptyIterable) + * const [firstFib, restFib] = NonEmptyIterable.unprepend( + * fibonacci() as unknown as NonEmptyIterable.NonEmptyIterable + * ) * console.log(firstFib) // 1 * ``` * * ## Integration with Effect Arrays * * ```ts - * import { pipe } from "effect" - * import * as NonEmptyIterable from "effect/NonEmptyIterable" - * import { Array } from "effect" - * import * as Chunk from "effect/Chunk" + * 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 @@ -1528,8 +1567,8 @@ export * as MutableRef from "./MutableRef.ts" * const processData = pipe( * nonEmptyData, * Array.fromIterable, - * Array.map(x => x * 2), - * Array.filter(x => x > 5), + * Array.map((x) => x * 2), + * Array.filter((x) => x > 5) * // Result is a regular array since filtering might make it empty * ) * @@ -1537,7 +1576,7 @@ export * as MutableRef from "./MutableRef.ts" * const doubledData = pipe( * nonEmptyData, * Array.fromIterable, - * Array.map(x => x * 2) + * Array.map((x) => x * 2) * // This would still be non-empty if the source was non-empty * ) * ``` @@ -1647,11 +1686,21 @@ export * as Order from "./Order.ts" */ export * as Ordering from "./Ordering.ts" +/** + * @since 4.0.0 + */ +export * as Path from "./Path.ts" + /** * @since 2.0.0 */ export * as Pipeable from "./Pipeable.ts" +/** + * @since 4.0.0 + */ +export * as PlatformError from "./PlatformError.ts" + /** * @since 2.0.0 */ @@ -1684,9 +1733,7 @@ export * as PrimaryKey from "./PrimaryKey.ts" * * @example * ```ts - * import { Effect } from "effect" - * import { Scope } from "effect" - * import { PubSub } from "effect" + * import { Effect, PubSub } from "effect" * * const program = Effect.gen(function*() { * const pubsub = yield* PubSub.bounded(10) @@ -1723,8 +1770,7 @@ export * as Pull from "./Pull.ts" * * @example * ```ts - * import { Effect } from "effect" - * import { Queue } from "effect" + * import { Effect, Queue } from "effect" * * // Creating a bounded queue with capacity 10 * const program = Effect.gen(function*() { @@ -1760,7 +1806,7 @@ export * as Queue from "./Queue.ts" * ```ts * import { Effect, Random } from "effect" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const randomFloat = yield* Random.next * console.log("Random float:", randomFloat) * @@ -1822,16 +1868,15 @@ export * as Reducer from "./Reducer.ts" * * @example * ```ts - * import { Effect } from "effect" - * import { Ref } from "effect" + * 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) + * yield* Ref.update(counter, (n) => n + 1) + * yield* Ref.update(counter, (n) => n * 2) * * const value = yield* Ref.get(counter) * console.log(value) // 2 @@ -1903,14 +1948,12 @@ export * as Result from "./Result.ts" * * @example * ```ts - * import { Effect } from "effect" - * import { Runtime } from "effect" - * import { Fiber } from "effect" + * 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))) + * 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)) @@ -1936,9 +1979,7 @@ export * as Runtime from "./Runtime.ts" * * @example * ```ts - * import { Effect } from "effect" - * import { Schedule } from "effect" - * import { Duration } from "effect" + * import { Effect, Schedule } from "effect" * * // Retry with exponential backoff * const retryPolicy = Schedule.exponential("100 millis", 2.0) @@ -2053,6 +2094,11 @@ export * as SynchronizedRef from "./SynchronizedRef.ts" */ export * as Take from "./Take.ts" +/** + * @since 4.0.0 + */ +export * as Terminal from "./Terminal.ts" + /** * @since 2.0.0 */ diff --git a/packages/effect/src/platform/index.ts b/packages/effect/src/platform/index.ts deleted file mode 100644 index 1946144586..0000000000 --- a/packages/effect/src/platform/index.ts +++ /dev/null @@ -1,59 +0,0 @@ -/** - * @since 4.0.0 - */ - -/** - * 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 { Effect } from "effect" - * import { Console } from "effect" - * import { FileSystem } from "effect/platform" - * - * 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" - -/** - * @since 4.0.0 - */ -export * as Path from "./Path.ts" - -/** - * @since 4.0.0 - */ -export * as PlatformError from "./PlatformError.ts" - -/** - * @since 4.0.0 - */ -export * as Terminal from "./Terminal.ts" diff --git a/packages/effect/src/platform/index.ts.tpl b/packages/effect/src/platform/index.ts.tpl deleted file mode 100644 index c2aac82f76..0000000000 --- a/packages/effect/src/platform/index.ts.tpl +++ /dev/null @@ -1,3 +0,0 @@ -/** - * @since 4.0.0 - */ diff --git a/packages/effect/src/schema/Annotations.ts b/packages/effect/src/schema/Annotations.ts index 0ba32e3783..6837b32231 100644 --- a/packages/effect/src/schema/Annotations.ts +++ b/packages/effect/src/schema/Annotations.ts @@ -26,7 +26,9 @@ import type * as Schema from "./Schema.ts" * // Extend the Annotations interface with a custom `version` annotation * declare module "effect/schema/Annotations" { * interface Annotations { - * readonly version?: readonly [major: number, minor: number, patch: number] | undefined + * readonly version?: + * | readonly [major: number, minor: number, patch: number] + * | undefined * } * } * diff --git a/packages/effect/src/schema/Schema.ts b/packages/effect/src/schema/Schema.ts index 1f6dc26f8b..07899e4596 100644 --- a/packages/effect/src/schema/Schema.ts +++ b/packages/effect/src/schema/Schema.ts @@ -654,7 +654,9 @@ export const is = Parser.is * ```ts * import { Schema } from "effect/schema" * - * const assertString: (u: unknown) => asserts u is string = Schema.asserts(Schema.String) + * const assertString: (u: unknown) => asserts u is string = Schema.asserts( + * Schema.String + * ) * * // This will pass silently (no return value) * try { @@ -1480,6 +1482,7 @@ export interface UniqueSymbol * * ```ts * import { Schema } from "effect/schema" + * * const a = Symbol.for("a") * const schema = Schema.UniqueSymbol(a) * ``` @@ -1669,8 +1672,8 @@ interface fieldsAssign extends Lambda { * **Example** (Adding fields to a union of structs) * * ```ts - * import { Schema } from "effect/schema" * import { Tuple } from "effect" + * import { Schema } from "effect/schema" * * // Add a new field to all members of a union of structs * const schema = Schema.Union([ @@ -2842,14 +2845,14 @@ export interface compose extends decodeTo Number(s)), - * encode: Getter.transform(n => String(n)) + * decode: Getter.transform((s) => Number(s)), + * encode: Getter.transform((n) => String(n)) * } * ) * ) @@ -2912,12 +2915,12 @@ export function decodeTo s.trim()), - * encode: Getter.transform(s => s.trim()) + * decode: Getter.transform((s) => s.trim()), + * encode: Getter.transform((s) => s.trim()) * }) * ) * diff --git a/packages/effect/src/stm/TxChunk.ts b/packages/effect/src/stm/TxChunk.ts index 257434f71a..e5c35fbbb2 100644 --- a/packages/effect/src/stm/TxChunk.ts +++ b/packages/effect/src/stm/TxChunk.ts @@ -32,8 +32,7 @@ const TypeId = "~effect/transactions/TxChunk" * * @example * ```ts - * import { Effect } from "effect" - * import { Chunk } from "effect" + * import { Chunk, Effect } from "effect" * import { TxChunk } from "effect/stm" * * const program = Effect.gen(function*() { @@ -98,8 +97,7 @@ const TxChunkProto = { * @category Constructors * @example * ```ts - * import { Effect } from "effect" - * import { Chunk } from "effect" + * import { Chunk, Effect } from "effect" * import { TxChunk } from "effect/stm" * * const program = Effect.gen(function*() { @@ -158,8 +156,7 @@ export const empty = (): Effect.Effect> => * @category Constructors * @example * ```ts - * import { Effect } from "effect" - * import { Chunk } from "effect" + * import { Chunk, Effect } from "effect" * import { TxChunk } from "effect/stm" * * const program = Effect.gen(function*() { @@ -222,8 +219,7 @@ export const makeUnsafe = (ref: TxRef.TxRef>): TxChunk => { * @category Combinators * @example * ```ts - * import { Effect } from "effect" - * import { Chunk } from "effect" + * import { Chunk, Effect } from "effect" * import { TxChunk } from "effect/stm" * * const program = Effect.gen(function*() { @@ -266,8 +262,7 @@ export const modify: { * * @example * ```ts - * import { Effect } from "effect" - * import { Chunk } from "effect" + * import { Chunk, Effect } from "effect" * import { TxChunk } from "effect/stm" * * const program = Effect.gen(function*() { @@ -299,8 +294,7 @@ export const update: { * * @example * ```ts - * import { Effect } from "effect" - * import { Chunk } from "effect" + * import { Chunk, Effect } from "effect" * import { TxChunk } from "effect/stm" * * const program = Effect.gen(function*() { @@ -329,8 +323,7 @@ export const get = (self: TxChunk): Effect.Effect> => TxRef * * @example * ```ts - * import { Effect } from "effect" - * import { Chunk } from "effect" + * import { Chunk, Effect } from "effect" * import { TxChunk } from "effect/stm" * * const program = Effect.gen(function*() { @@ -361,8 +354,7 @@ export const set: { * * @example * ```ts - * import { Effect } from "effect" - * import { Chunk } from "effect" + * import { Chunk, Effect } from "effect" * import { TxChunk } from "effect/stm" * * const program = Effect.gen(function*() { @@ -395,8 +387,7 @@ export const append: { * * @example * ```ts - * import { Effect } from "effect" - * import { Chunk } from "effect" + * import { Chunk, Effect } from "effect" * import { TxChunk } from "effect/stm" * * const program = Effect.gen(function*() { @@ -511,8 +502,7 @@ export const isNonEmpty = (self: TxChunk): Effect.Effect => * * @example * ```ts - * import { Effect } from "effect" - * import { Chunk } from "effect" + * import { Chunk, Effect } from "effect" * import { TxChunk } from "effect/stm" * * const program = Effect.gen(function*() { @@ -542,8 +532,7 @@ export const take: { * * @example * ```ts - * import { Effect } from "effect" - * import { Chunk } from "effect" + * import { Chunk, Effect } from "effect" * import { TxChunk } from "effect/stm" * * const program = Effect.gen(function*() { @@ -573,8 +562,7 @@ export const drop: { * * @example * ```ts - * import { Effect } from "effect" - * import { Chunk } from "effect" + * import { Chunk, Effect } from "effect" * import { TxChunk } from "effect/stm" * * const program = Effect.gen(function*() { @@ -609,8 +597,7 @@ export const slice: { * * @example * ```ts - * import { Effect } from "effect" - * import { Chunk } from "effect" + * import { Chunk, Effect } from "effect" * import { TxChunk } from "effect/stm" * * const program = Effect.gen(function*() { @@ -644,8 +631,7 @@ export const map: { * * @example * ```ts - * import { Effect } from "effect" - * import { Chunk } from "effect" + * import { Chunk, Effect } from "effect" * import { TxChunk } from "effect/stm" * * const program = Effect.gen(function*() { @@ -682,8 +668,7 @@ export const filter: { * * @example * ```ts - * import { Effect } from "effect" - * import { Chunk } from "effect" + * import { Chunk, Effect } from "effect" * import { TxChunk } from "effect/stm" * * const program = Effect.gen(function*() { @@ -719,8 +704,7 @@ export const appendAll: { * * @example * ```ts - * import { Effect } from "effect" - * import { Chunk } from "effect" + * import { Chunk, Effect } from "effect" * import { TxChunk } from "effect/stm" * * const program = Effect.gen(function*() { @@ -758,8 +742,7 @@ export const prependAll: { * @category Combinators * @example * ```ts - * import { Effect } from "effect" - * import { Chunk } from "effect" + * import { Chunk, Effect } from "effect" * import { TxChunk } from "effect/stm" * * const program = Effect.gen(function*() { diff --git a/packages/effect/src/stm/TxHashMap.ts b/packages/effect/src/stm/TxHashMap.ts index e6dd2196da..40f2f3198a 100644 --- a/packages/effect/src/stm/TxHashMap.ts +++ b/packages/effect/src/stm/TxHashMap.ts @@ -41,8 +41,7 @@ const TxHashMapProto = { * * @example * ```ts - * import { Effect } from "effect" - * import { Option } from "effect" + * import { Effect, Option } from "effect" * import { TxHashMap } from "effect/stm" * * const program = Effect.gen(function*() { @@ -335,8 +334,7 @@ export const fromIterable = (entries: Iterable): Effect.E * * @example * ```ts - * import { Effect } from "effect" - * import { Option } from "effect" + * import { Effect, Option } from "effect" * import { TxHashMap } from "effect/stm" * * const program = Effect.gen(function*() { @@ -731,8 +729,7 @@ export const modify: { * * @example * ```ts - * import { Effect } from "effect" - * import { Option } from "effect" + * import { Effect, Option } from "effect" * import { TxHashMap } from "effect/stm" * * const program = Effect.gen(function*() { @@ -793,8 +790,7 @@ export const modifyAt: { * * @example * ```ts - * import { Effect } from "effect" - * import { Option } from "effect" + * import { Effect, Option } from "effect" * import { TxHashMap } from "effect/stm" * * const program = Effect.gen(function*() { @@ -907,8 +903,7 @@ export const entries = (self: TxHashMap): Effect.Effect(self: TxHashMap): Effect.Effect(value: unknown): value is TxHashMap => { * * @example * ```ts - * import { Effect } from "effect" - * import { Hash } from "effect" + * import { Effect, Hash } from "effect" * import { TxHashMap } from "effect/stm" * * const program = Effect.gen(function*() { @@ -1208,8 +1201,7 @@ export const getHash: { * * @example * ```ts - * import { Effect } from "effect" - * import { Hash } from "effect" + * import { Effect, Hash } from "effect" * import { TxHashMap } from "effect/stm" * * const program = Effect.gen(function*() { @@ -1463,8 +1455,7 @@ export const reduce: { * * @example * ```ts - * import { Effect } from "effect" - * import { Option } from "effect" + * import { Effect, Option } from "effect" * import { TxHashMap } from "effect/stm" * * const program = Effect.gen(function*() { @@ -1876,8 +1867,7 @@ export const flatMap: { * * @example * ```ts - * import { Effect } from "effect" - * import { Option } from "effect" + * import { Effect, Option } from "effect" * import { TxHashMap } from "effect/stm" * * const program = Effect.gen(function*() { diff --git a/packages/effect/src/stm/TxHashSet.ts b/packages/effect/src/stm/TxHashSet.ts index 976813a889..7f5b26b4b2 100644 --- a/packages/effect/src/stm/TxHashSet.ts +++ b/packages/effect/src/stm/TxHashSet.ts @@ -381,8 +381,7 @@ export const remove: { * * @example * ```ts - * import { Effect } from "effect" - * import { Equal, Hash } from "effect" + * import { Effect, Equal, Hash } from "effect" * import { TxHashSet } from "effect/stm" * * const program = Effect.gen(function*() { diff --git a/packages/effect/src/stm/TxQueue.ts b/packages/effect/src/stm/TxQueue.ts index c538ff4002..236c60717f 100644 --- a/packages/effect/src/stm/TxQueue.ts +++ b/packages/effect/src/stm/TxQueue.ts @@ -621,8 +621,7 @@ export const offer: { * * @example * ```ts - * import { Effect } from "effect" - * import { Chunk } from "effect" + * import { Chunk, Effect } from "effect" * import { TxQueue } from "effect/stm" * * const program = Effect.gen(function*() { @@ -726,8 +725,7 @@ export const take = (self: TxDequeue): Effect.Effect => * * @example * ```ts - * import { Effect } from "effect" - * import { Option } from "effect" + * import { Effect, Option } from "effect" * import { TxQueue } from "effect/stm" * * const program = Effect.gen(function*() { diff --git a/packages/effect/src/testing/FastCheck.ts b/packages/effect/src/testing/FastCheck.ts index dbde2f7772..b01e75a8ea 100644 --- a/packages/effect/src/testing/FastCheck.ts +++ b/packages/effect/src/testing/FastCheck.ts @@ -48,8 +48,8 @@ * (a, b) => { * const result = a + b * return result.length === a.length + b.length && - * result.startsWith(a) && - * result.endsWith(b) + * result.startsWith(a) && + * result.endsWith(b) * } * ) * @@ -72,9 +72,9 @@ * personArbitrary, * (person) => { * return person.name.length > 0 && - * person.age >= 0 && - * person.age <= 120 && - * person.email.includes("@") + * person.age >= 0 && + * person.age <= 120 && + * person.email.includes("@") * } * ) * diff --git a/packages/effect/src/testing/TestClock.ts b/packages/effect/src/testing/TestClock.ts index 0036c25b05..b9df741182 100644 --- a/packages/effect/src/testing/TestClock.ts +++ b/packages/effect/src/testing/TestClock.ts @@ -23,12 +23,9 @@ import * as Order from "../Order.ts" * For example, here is how we can test `Effect.timeout` using `TestClock`: * * ```ts - * import * as assert from "node:assert" - * import { Duration } from "effect" - * import { Effect, pipe } from "effect" - * import { Option } from "effect" - * import { Fiber } from "effect" + * import { Effect, Fiber, Option, pipe } from "effect" * import { TestClock } from "effect/testing" + * import * as assert from "node:assert" * * Effect.gen(function*() { * const fiber = yield* pipe( @@ -348,7 +345,6 @@ export const make = Effect.fnUntraced(function*( * @example * ```ts * import { Effect } from "effect" - * import { Layer } from "effect" * import { TestClock } from "effect/testing" * * // Create a TestClock layer @@ -386,9 +382,7 @@ export const layer: (options?: TestClock.Options) => Layer.Layer = La * ) * * // Adjust time using the TestClock instance - * yield* TestClock.testClockWith((testClock) => - * testClock.adjust("2 hours") - * ) + * yield* TestClock.testClockWith((testClock) => testClock.adjust("2 hours")) * * console.log(currentTime) // Initial time * }) @@ -440,8 +434,7 @@ export const adjust = (duration: Duration.DurationInput): Effect.Effect => * * @example * ```ts - * import { Duration } from "effect" - * import { Effect } from "effect" + * import { Duration, Effect } from "effect" * import { TestClock } from "effect/testing" * * const program = Effect.gen(function*() { @@ -474,8 +467,7 @@ export const setTime = (timestamp: number): Effect.Effect => * * @example * ```ts - * import { Effect } from "effect" - * import { Clock } from "effect" + * import { Clock, Effect } from "effect" * import { TestClock } from "effect/testing" * * const program = Effect.gen(function*() { diff --git a/packages/effect/src/testing/TestConsole.ts b/packages/effect/src/testing/TestConsole.ts index cc728c3c59..307e6b788c 100644 --- a/packages/effect/src/testing/TestConsole.ts +++ b/packages/effect/src/testing/TestConsole.ts @@ -17,9 +17,8 @@ import * as Option from "../Option.ts" * * @example * ```ts - * import { TestConsole } from "effect/testing" - * import { Effect } from "effect" - * import { Console } from "effect" + * import { Console, Effect } from "effect" + * import * as TestConsole from "effect/testing/TestConsole" * * const program = Effect.gen(function*() { * yield* Console.log("Hello, World!") @@ -28,7 +27,7 @@ import * as Option from "../Option.ts" * const logs = yield* TestConsole.logLines * const errors = yield* TestConsole.errorLines * - * console.log(logs) // [["Hello, World!"]] + * console.log(logs) // [["Hello, World!"]] * console.log(errors) // [["An error occurred"]] * }).pipe(Effect.provide(TestConsole.layer)) * ``` @@ -55,8 +54,6 @@ export interface TestConsole extends Console.Console { * * @example * ```ts - * import { TestConsole } from "effect/testing" - * * // 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 @@ -72,8 +69,6 @@ export declare namespace TestConsole { * * @example * ```ts - * import { Console } from "effect" - * * // Method represents console method names like: * // "log", "error", "warn", "debug", "info", etc. * // All methods from the Console interface are supported @@ -90,8 +85,6 @@ export declare namespace TestConsole { * * @example * ```ts - * import { TestConsole } from "effect/testing" - * * // 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 @@ -113,9 +106,8 @@ export declare namespace TestConsole { * * @example * ```ts - * import { TestConsole } from "effect/testing" - * import { Effect } from "effect" - * import { Console } from "effect" + * import { Console, Effect } from "effect" + * import * as TestConsole from "effect/testing/TestConsole" * * const program = Effect.gen(function*() { * yield* Console.log("Debug message") @@ -186,8 +178,8 @@ export const make = Effect.gen(function*() { * * @example * ```ts - * import { TestConsole } from "effect/testing" * import { Effect } from "effect" + * import * as TestConsole from "effect/testing/TestConsole" * * const program = TestConsole.testConsoleWith((testConsole) => * Effect.gen(function*() { @@ -197,7 +189,7 @@ export const make = Effect.gen(function*() { * const logs = yield* testConsole.logLines * const errors = yield* testConsole.errorLines * - * console.log("Logs:", logs) // [["Test message"]] + * console.log("Logs:", logs) // [["Test message"]] * console.log("Errors:", errors) // [["Test error"]] * }) * ).pipe(Effect.provide(TestConsole.layer)) @@ -216,9 +208,8 @@ export const testConsoleWith = (f: (console: TestConsole) => Effect.Eff * * @example * ```ts - * import { TestConsole } from "effect/testing" - * import { Effect } from "effect" - * import { Console } from "effect" + * import { Console, Effect } from "effect" + * import * as TestConsole from "effect/testing/TestConsole" * * const program = Effect.gen(function*() { * yield* Console.log("This will be captured") @@ -243,9 +234,8 @@ export const layer: Layer.Layer = Layer.effect(Console.Console)(mak * * @example * ```ts - * import { TestConsole } from "effect/testing" - * import { Effect } from "effect" - * import { Console } from "effect" + * import { Console, Effect } from "effect" + * import * as TestConsole from "effect/testing/TestConsole" * * const program = Effect.gen(function*() { * yield* Console.log("First message") @@ -276,9 +266,8 @@ export const logLines: Effect.Effect, never, never> = tes * * @example * ```ts - * import { TestConsole } from "effect/testing" - * import { Effect } from "effect" - * import { Console } from "effect" + * import { Console, Effect } from "effect" + * import * as TestConsole from "effect/testing/TestConsole" * * const program = Effect.gen(function*() { * yield* Console.error("Error message") diff --git a/packages/effect/src/types/HKT.ts b/packages/effect/src/types/HKT.ts index d431c3ff4f..c3a8cc10e3 100644 --- a/packages/effect/src/types/HKT.ts +++ b/packages/effect/src/types/HKT.ts @@ -12,7 +12,7 @@ * * @example * ```ts - * import { HKT } from "effect/types" + * import type { HKT } from "effect/types" * * // Define a TypeLambda for Array * interface ArrayTypeLambda extends HKT.TypeLambda { @@ -25,7 +25,10 @@ * * // Define a TypeClass that works with any HKT * interface Functor extends HKT.TypeClass { - * map(fa: HKT.Kind, f: (a: A) => B): HKT.Kind + * map( + * fa: HKT.Kind, + * f: (a: A) => B + * ): HKT.Kind * } * ``` * @@ -42,7 +45,7 @@ import type * as Types from "../types/Types.ts" * * @example * ```ts - * import { HKT } from "effect/types" + * import type { HKT } from "effect/types" * * interface MyTypeClass extends HKT.TypeClass { * // TypeClass methods here @@ -66,7 +69,7 @@ export declare const URI: unique symbol * * @example * ```ts - * import { HKT } from "effect/types" + * import type { HKT } from "effect/types" * * // Define a Functor type class * interface Functor extends HKT.TypeClass { @@ -107,8 +110,8 @@ export interface TypeClass { * * @example * ```ts - * import { Effect } from "effect" - * import { HKT } from "effect/types" + * import type { Effect } from "effect" + * import type { HKT } from "effect/types" * * // TypeLambda for Array * interface ArrayTypeLambda extends HKT.TypeLambda { @@ -149,9 +152,8 @@ export interface TypeLambda { * * @example * ```ts - * import { Effect } from "effect" - * import { Option } from "effect" - * import { HKT } from "effect/types" + * import type { Effect, Option } from "effect" + * import type { HKT } from "effect/types" * * // Define TypeLambdas * interface OptionTypeLambda extends HKT.TypeLambda { @@ -166,11 +168,23 @@ export interface TypeLambda { * type OptionString = HKT.Kind * // Result: Option.Option * - * type EffectStringNumberBoolean = HKT.Kind + * type EffectStringNumberBoolean = HKT.Kind< + * EffectTypeLambda, + * never, + * number, + * boolean, + * string + * > * // Result: Effect.Effect * * // TypeLambdas enable generic programming over type constructors - * type StringType = HKT.Kind + * type StringType = HKT.Kind< + * F, + * never, + * never, + * never, + * string + * > * ``` * * @since 2.0.0 diff --git a/packages/effect/src/types/Types.ts b/packages/effect/src/types/Types.ts index 7d84d1dab7..5bdacd845e 100644 --- a/packages/effect/src/types/Types.ts +++ b/packages/effect/src/types/Types.ts @@ -18,14 +18,14 @@ type TupleOf_> = `${N}` extends `- * * @example * ```ts - * import { TupleOf } from "effect/types/Types" + * import type { TupleOf } from "effect/types/Types" * * // A tuple with exactly 3 numbers - * const example1: TupleOf<3, number> = [1, 2, 3]; // valid + * const example1: TupleOf<3, number> = [1, 2, 3] // valid * // @ts-expect-error - * const example2: TupleOf<3, number> = [1, 2]; // invalid + * const example2: TupleOf<3, number> = [1, 2] // invalid * // @ts-expect-error - * const example3: TupleOf<3, number> = [1, 2, 3, 4]; // invalid + * const example3: TupleOf<3, number> = [1, 2, 3, 4] // invalid * ``` * * @category tuples @@ -44,13 +44,13 @@ export type TupleOf = N extends N ? number extends N ? Arra * * @example * ```ts - * import { TupleOfAtLeast } from "effect/types/Types" + * import type { TupleOfAtLeast } from "effect/types/Types" * * // A tuple with at least 3 numbers - * const example1: TupleOfAtLeast<3, number> = [1, 2, 3]; // valid - * const example2: TupleOfAtLeast<3, number> = [1, 2, 3, 4, 5]; // valid + * const example1: TupleOfAtLeast<3, number> = [1, 2, 3] // valid + * const example2: TupleOfAtLeast<3, number> = [1, 2, 3, 4, 5] // valid * // @ts-expect-error - * const example3: TupleOfAtLeast<3, number> = [1, 2]; // invalid + * const example3: TupleOfAtLeast<3, number> = [1, 2] // invalid * ``` * * @category tuples @@ -64,7 +64,7 @@ export type TupleOfAtLeast = [...TupleOf, ...Array * ```ts * import type { Types } from "effect/types" * - * type Res = Types.Tags // "a" | "b" + * type Res = Types.Tags // "a" | "b" * ``` * * @category types @@ -93,7 +93,10 @@ export type ExcludeTag = Exclude * ```ts * import type { Types } from "effect/types" * - * type Res = Types.ExtractTag<{ _tag: "a", a: number } | { _tag: "b", b: number }, "b"> // { _tag: "b", b: number } + * type Res = Types.ExtractTag< + * { _tag: "a"; a: number } | { _tag: "b"; b: number }, + * "b" + * > // { _tag: "b", b: number } * ``` * * @category types @@ -194,7 +197,8 @@ export type Has = (Key extends infer K ? K extends keyof * @example * ```ts * import type { Types } from "effect/types" - * type MergeLeft = Types.MergeLeft<{ a: number, b: number; }, { a: string }> // { a: number; b: number; } + * + * type MergeLeft = Types.MergeLeft<{ a: number; b: number }, { a: string }> // { a: number; b: number; } * ``` * * @since 2.0.0 @@ -208,7 +212,8 @@ export type MergeLeft = MergeRight * @example * ```ts * import type { Types } from "effect/types" - * type MergeRight = Types.MergeRight<{ a: number, b: number; }, { a: string }> // { a: string; b: number; } + * + * type MergeRight = Types.MergeRight<{ a: number; b: number }, { a: string }> // { a: string; b: number; } * ``` * * @since 2.0.0 @@ -228,7 +233,10 @@ export type MergeRight = Simplify< * ```ts * import type { Types } from "effect/types" * - * type Result = Types.MergeRecord<{ a: number, b: number }, { a: string, c: boolean }> // { a: number; b: number; c: boolean } + * type Result = Types.MergeRecord< + * { a: number; b: number }, + * { a: string; c: boolean } + * > // { a: number; b: number; c: boolean } * ``` * * @since 2.0.0 @@ -284,8 +292,8 @@ export type Mutable = { * import type { Types } from "effect/types" * * type DeepMutableStruct = Types.DeepMutable<{ - * readonly a: string; - * readonly b: readonly string[] + * readonly a: string + * readonly b: ReadonlyArray * }> * // { a: string; b: string[] } * ``` diff --git a/packages/effect/src/types/Unify.ts b/packages/effect/src/types/Unify.ts index 101447be9f..0b58e50bb1 100644 --- a/packages/effect/src/types/Unify.ts +++ b/packages/effect/src/types/Unify.ts @@ -12,7 +12,7 @@ import { identity } from "../Function.ts" * * @example * ```ts - * import { Unify } from "effect/types" + * import type { Unify } from "effect/types" * * // The unifySymbol is used internally in Effect types * // to enable automatic type unification @@ -35,7 +35,7 @@ export declare const unifySymbol: unique symbol * * @example * ```ts - * import { Unify } from "effect/types" + * import type { Unify } from "effect/types" * * // The unifySymbol type is used in type declarations * // to enable unification behavior @@ -57,7 +57,7 @@ export type unifySymbol = typeof unifySymbol * * @example * ```ts - * import { Unify } from "effect/types" + * import type { Unify } from "effect/types" * * // The typeSymbol is used internally in Effect types * // to store type information for unification @@ -80,7 +80,7 @@ export declare const typeSymbol: unique symbol * * @example * ```ts - * import { Unify } from "effect/types" + * import type { Unify } from "effect/types" * * // The typeSymbol type is used in type declarations * // to store type information for unification @@ -103,7 +103,7 @@ export type typeSymbol = typeof typeSymbol * * @example * ```ts - * import { Unify } from "effect/types" + * import type { Unify } from "effect/types" * * // The ignoreSymbol is used internally in Effect types * // to mark types that should be ignored during unification @@ -126,7 +126,7 @@ export declare const ignoreSymbol: unique symbol * * @example * ```ts - * import { Unify } from "effect/types" + * import type { Unify } from "effect/types" * * // The ignoreSymbol type is used in type declarations * // to mark types that should be ignored during unification @@ -171,7 +171,7 @@ type FilterOut = A extends any ? typeSymbol extends keyof A ? never : A : nev * * @example * ```ts - * import * as Unify from "effect/types/Unify" + * import type * as Unify from "effect/types/Unify" * * // Example of types that can be unified * type UnifiableA = { diff --git a/packages/effect/src/types/index.ts b/packages/effect/src/types/index.ts index 9598a15f1b..9c078ff4db 100644 --- a/packages/effect/src/types/index.ts +++ b/packages/effect/src/types/index.ts @@ -16,7 +16,7 @@ * * @example * ```ts - * import { HKT } from "effect/types" + * import type { HKT } from "effect/types" * * // Define a TypeLambda for Array * interface ArrayTypeLambda extends HKT.TypeLambda { @@ -29,7 +29,10 @@ * * // Define a TypeClass that works with any HKT * interface Functor extends HKT.TypeClass { - * map(fa: HKT.Kind, f: (a: A) => B): HKT.Kind + * map( + * fa: HKT.Kind, + * f: (a: A) => B + * ): HKT.Kind * } * ``` * diff --git a/packages/effect/src/unstable/ai/AiError.ts b/packages/effect/src/unstable/ai/AiError.ts index 10b47de1e6..ac94f589ea 100644 --- a/packages/effect/src/unstable/ai/AiError.ts +++ b/packages/effect/src/unstable/ai/AiError.ts @@ -17,24 +17,27 @@ * @example * ```ts * import { Effect, Match } from "effect" - * import { AiError } from "effect/unstable/ai" + * import type { AiError } from "effect/unstable/ai" * * const handleAiError = Match.type().pipe( - * Match.tag("HttpRequestError", (err) => - * Effect.logError(`Request failed: ${err.message}`) + * Match.tag( + * "HttpRequestError", + * (err) => Effect.logError(`Request failed: ${err.message}`) * ), - * Match.tag("HttpResponseError", (err) => - * Effect.logError(`Response error (${err.response.status}): ${err.message}`) + * Match.tag( + * "HttpResponseError", + * (err) => + * Effect.logError(`Response error (${err.response.status}): ${err.message}`) * ), - * Match.tag("MalformedInput", (err) => - * Effect.logError(`Invalid input: ${err.message}`) + * Match.tag( + * "MalformedInput", + * (err) => Effect.logError(`Invalid input: ${err.message}`) * ), - * Match.tag("MalformedOutput", (err) => - * Effect.logError(`Invalid output: ${err.message}`) + * Match.tag( + * "MalformedOutput", + * (err) => Effect.logError(`Invalid output: ${err.message}`) * ), - * Match.orElse((err) => - * Effect.logError(`Unknown error: ${err.message}`) - * ) + * Match.orElse((err) => Effect.logError(`Unknown error: ${err.message}`)) * ) * ``` * @@ -43,7 +46,7 @@ * import { Effect } from "effect" * import { AiError } from "effect/unstable/ai" * - * const aiOperation = Effect.gen(function* () { + * const aiOperation = Effect.gen(function*() { * // Some AI operation that might fail * return yield* new AiError.HttpRequestError({ * module: "OpenAI", @@ -95,7 +98,7 @@ const TypeId = "~effect/unstable/ai/AiError" as const * }) * * console.log(AiError.isAiError(someError)) // false - * console.log(AiError.isAiError(aiError)) // true + * console.log(AiError.isAiError(aiError)) // true * ``` * * @since 4.0.0 @@ -115,7 +118,7 @@ export const isAiError = (u: unknown): u is AiError => Predicate.hasProperty(u, * * @example * ```ts - * import { AiError } from "effect/unstable/ai" + * import type { AiError } from "effect/unstable/ai" * * const requestDetails: typeof AiError.HttpRequestDetails.Type = { * method: "POST", @@ -149,7 +152,7 @@ export const HttpRequestDetails = Schema.Struct({ * import { Effect } from "effect" * import { AiError } from "effect/unstable/ai" * - * const handleNetworkError = Effect.gen(function* () { + * const handleNetworkError = Effect.gen(function*() { * const error = new AiError.HttpRequestError({ * module: "OpenAI", * method: "createCompletion", @@ -194,7 +197,7 @@ export class HttpRequestError extends Schema.ErrorClass( * @example * ```ts * import { AiError } from "effect/unstable/ai" - * import { HttpClientError } from "effect/unstable/http" + * import type { HttpClientError } from "effect/unstable/http" * * declare const platformError: HttpClientError.RequestError * @@ -274,7 +277,7 @@ export class HttpRequestError extends Schema.ErrorClass( * * @example * ```ts - * import { AiError } from "effect/unstable/ai" + * import type { AiError } from "effect/unstable/ai" * * const responseDetails: typeof AiError.HttpResponseDetails.Type = { * status: 429, @@ -353,7 +356,7 @@ export class HttpResponseError extends Schema.ErrorClass( * @example * ```ts * import { AiError } from "effect/unstable/ai" - * import { Headers, HttpClientError } from "effect/unstable/http" + * import type { HttpClientError } from "effect/unstable/http" * * declare const platformError: HttpClientError.ResponseError * @@ -520,7 +523,7 @@ export class MalformedInput extends Schema.ErrorClass( * * const parseResponse = (data: unknown) => * Schema.decodeUnknownEffect(ResponseSchema)(data).pipe( - * Effect.mapError(schemaError => + * Effect.mapError((schemaError) => * new AiError.MalformedOutput({ * module: "OpenAI", * method: "completion", @@ -619,12 +622,14 @@ export class MalformedOutput extends Schema.ErrorClass( * // Some operation that might throw * throw new Error("Unexpected network issue") * } catch (cause) { - * return Effect.fail(new AiError.UnknownError({ - * module: "ChatService", - * method: "sendMessage", - * description: "An unexpected error occurred during message processing", - * cause - * })) + * return Effect.fail( + * new AiError.UnknownError({ + * module: "ChatService", + * method: "sendMessage", + * description: "An unexpected error occurred during message processing", + * cause + * }) + * ) * } * } * @@ -677,25 +682,24 @@ export class UnknownError extends Schema.ErrorClass( * * @example * ```ts - * import { Effect, Match } from "effect" - * import { AiError } from "effect/unstable/ai" + * import { Match } from "effect" + * import type { AiError } from "effect/unstable/ai" * * const handleAnyAiError = Match.type().pipe( - * Match.tag("HttpRequestError", (err) => - * `Network error: ${err.reason}` + * Match.tag("HttpRequestError", (err) => `Network error: ${err.reason}`), + * Match.tag( + * "HttpResponseError", + * (err) => `Server error: HTTP ${err.response.status}` * ), - * Match.tag("HttpResponseError", (err) => - * `Server error: HTTP ${err.response.status}` + * Match.tag( + * "MalformedInput", + * (err) => `Invalid input: ${err.description || "Data validation failed"}` * ), - * Match.tag("MalformedInput", (err) => - * `Invalid input: ${err.description || "Data validation failed"}` + * Match.tag( + * "MalformedOutput", + * (err) => `Invalid response: ${err.description || "Response parsing failed"}` * ), - * Match.tag("MalformedOutput", (err) => - * `Invalid response: ${err.description || "Response parsing failed"}` - * ), - * Match.orElse((err) => - * `Unknown error: ${err.message}` - * ) + * Match.orElse((err) => `Unknown error: ${err.message}`) * ) * ``` * @@ -719,21 +723,23 @@ export type AiError = * @example * ```ts * import { Effect } from "effect" - * import { AiError } from "effect/unstable/ai" * import { Schema } from "effect/schema" + * import { AiError } from "effect/unstable/ai" * * const parseAiError = (data: unknown) => * Schema.decodeUnknownEffect(AiError.AiError)(data).pipe( - * Effect.map(error => { + * Effect.map((error) => { * console.log(`Parsed AI error: ${error._tag}`) * return error * }), * Effect.catch(() => - * Effect.succeed(new AiError.UnknownError({ - * module: "Parser", - * method: "parseAiError", - * description: "Failed to parse error data" - * })) + * Effect.succeed( + * new AiError.UnknownError({ + * module: "Parser", + * method: "parseAiError", + * description: "Failed to parse error data" + * }) + * ) * ) * ) * ``` diff --git a/packages/effect/src/unstable/ai/Chat.ts b/packages/effect/src/unstable/ai/Chat.ts index 868753a446..51a23ef534 100644 --- a/packages/effect/src/unstable/ai/Chat.ts +++ b/packages/effect/src/unstable/ai/Chat.ts @@ -9,11 +9,11 @@ * * @example * ```ts - * import { Effect, Layer } from "effect" - * import { Chat, LanguageModel } from "effect/unstable/ai" + * import { Effect } from "effect" + * import { Chat } from "effect/unstable/ai" * * // Create a new chat session - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const chat = yield* Chat.empty * * // Send a message and get response @@ -29,19 +29,16 @@ * * @example * ```ts - * import { Effect } from "effect" - * import { Stream } from "effect" - * import { Chat, LanguageModel } from "effect/unstable/ai" + * import { Effect, Stream } from "effect" + * import { Chat } from "effect/unstable/ai" * * // Streaming chat with tool support - * const streamingChat = Effect.gen(function* () { + * 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)) - * )) + * }).pipe(Stream.runForEach((part) => Effect.sync(() => console.log(part)))) * }) * ``` * @@ -79,7 +76,7 @@ import type * as Tool from "./Tool.ts" * import { Effect } from "effect" * import { Chat } from "effect/unstable/ai" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const chat = yield* Chat.empty * const response = yield* chat.generateText({ * prompt: "Explain quantum computing in simple terms" @@ -113,7 +110,7 @@ export interface Service { * import { Effect, Ref } from "effect" * import { Chat } from "effect/unstable/ai" * - * const inspectHistory = Effect.gen(function* () { + * const inspectHistory = Effect.gen(function*() { * const chat = yield* Chat.empty * const currentHistory = yield* Ref.get(chat.history) * console.log("Current conversation:", currentHistory) @@ -134,7 +131,7 @@ export interface Service { * import { Effect } from "effect" * import { Chat } from "effect/unstable/ai" * - * const saveChat = Effect.gen(function* () { + * const saveChat = Effect.gen(function*() { * const chat = yield* Chat.empty * yield* chat.generateText({ prompt: "Hello!" }) * @@ -158,16 +155,14 @@ export interface Service { * import { Effect } from "effect" * import { Chat } from "effect/unstable/ai" * - * const backupChat = Effect.gen(function* () { + * const backupChat = Effect.gen(function*() { * const chat = yield* Chat.empty * * yield* chat.generateText({ prompt: "Explain photosynthesis" }) * * const jsonBackup = yield* chat.exportJson * - * yield* Effect.sync(() => - * localStorage.setItem("chat-backup", jsonBackup) - * ) + * yield* Effect.sync(() => localStorage.setItem("chat-backup", jsonBackup)) * * return jsonBackup * }) @@ -187,7 +182,7 @@ export interface Service { * import { Effect } from "effect" * import { Chat } from "effect/unstable/ai" * - * const chatWithAI = Effect.gen(function* () { + * const chatWithAI = Effect.gen(function*() { * const chat = yield* Chat.empty * * const response1 = yield* chat.generateText({ @@ -195,7 +190,7 @@ export interface Service { * }) * * const response2 = yield* chat.generateText({ - * prompt: "What's the population of that city?", + * prompt: "What's the population of that city?" * }) * * return [response1.content, response2.content] @@ -219,11 +214,10 @@ export interface Service { * * @example * ```ts - * import { Console, Effect } from "effect" - * import { Stream } from "effect" + * import { Effect, Stream } from "effect" * import { Chat } from "effect/unstable/ai" * - * const streamingChat = Effect.gen(function* () { + * const streamingChat = Effect.gen(function*() { * const chat = yield* Chat.empty * * const stream = yield* chat.streamText({ @@ -233,8 +227,7 @@ export interface Service { * yield* Stream.runForEach(stream, (part) => * part.type === "text-delta" * ? Effect.sync(() => process.stdout.write(part.delta)) - * : Effect.void - * ) + * : Effect.void) * }) * ``` */ @@ -266,7 +259,7 @@ export interface Service { * phone: Schema.optional(Schema.String) * }) * - * const extractContact = Effect.gen(function* () { + * const extractContact = Effect.gen(function*() { * const chat = yield* Chat.empty * * const contact = yield* chat.generateObject({ @@ -313,7 +306,7 @@ const encodeHistoryJson = Schema.encodeUnknownEffect(Schema.fromJsonString(Promp * import { Effect } from "effect" * import { Chat } from "effect/unstable/ai" * - * const freshChat = Effect.gen(function* () { + * const freshChat = Effect.gen(function*() { * const chat = yield* Chat.empty * * const response = yield* chat.generateText({ @@ -444,9 +437,9 @@ export const empty: Effect.Effect = Effect.gen(function*() { * @example * ```ts * import { Effect } from "effect" - * import { Chat, Prompt } from "effect/unstable/ai" + * import { Chat } from "effect/unstable/ai" * - * const chatWithSystemPrompt = Effect.gen(function* () { + * const chatWithSystemPrompt = Effect.gen(function*() { * const chat = yield* Chat.fromPrompt([{ * role: "system", * content: "You are a helpful assistant specialized in mathematics." @@ -463,14 +456,23 @@ export const empty: Effect.Effect = Effect.gen(function*() { * @example * ```ts * import { Effect } from "effect" - * import { Chat, Prompt } from "effect/unstable/ai" + * import { Chat } from "effect/unstable/ai" * * // Initialize with conversation history - * const existingChat = Effect.gen(function* () { + * const existingChat = Effect.gen(function*() { * const chat = yield* Chat.fromPrompt([ - * { role: "user", content: [{ type: "text", text: "What's the weather like?" }] }, - * { role: "assistant", content: [{ type: "text", text: "I don't have access to weather data." }] }, - * { role: "user", content: [{ type: "text", text: "Can you help me with coding?" }] } + * { + * role: "user", + * content: [{ type: "text", text: "What's the weather like?" }] + * }, + * { + * role: "assistant", + * content: [{ type: "text", text: "I don't have access to weather data." }] + * }, + * { + * role: "user", + * content: [{ type: "text", text: "Can you help me with coding?" }] + * } * ]) * * const response = yield* chat.generateText({ @@ -506,7 +508,7 @@ export const fromPrompt = Effect.fnUntraced( * * declare const loadFromDatabase: (sessionId: string) => Effect.Effect * - * const restoreChat = Effect.gen(function* () { + * const restoreChat = Effect.gen(function*() { * // Assume we have previously exported data * const savedData = yield* loadFromDatabase("chat-session-123") * @@ -545,7 +547,7 @@ export const fromExport = (data: unknown): Effect.Effect< * import { Effect } from "effect" * import { Chat } from "effect/unstable/ai" * - * const restoreFromJson = Effect.gen(function* () { + * const restoreFromJson = Effect.gen(function*() { * // Load JSON from localStorage or file system * const jsonData = localStorage.getItem("my-chat-backup") * if (!jsonData) return yield* Chat.empty diff --git a/packages/effect/src/unstable/ai/IdGenerator.ts b/packages/effect/src/unstable/ai/IdGenerator.ts index f96d76bfad..b14f662974 100644 --- a/packages/effect/src/unstable/ai/IdGenerator.ts +++ b/packages/effect/src/unstable/ai/IdGenerator.ts @@ -7,11 +7,11 @@ * * @example * ```ts - * import { Effect, Layer } from "effect" + * import { Effect } from "effect" * import { IdGenerator } from "effect/unstable/ai" * * // Using the default ID generator - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const idGen = yield* IdGenerator.IdGenerator * const toolCallId = yield* idGen.generateId() * console.log(toolCallId) // "id_A7xK9mP2qR5tY8uV" @@ -24,7 +24,7 @@ * * @example * ```ts - * import { Effect, Layer } from "effect" + * import { Effect } from "effect" * import { IdGenerator } from "effect/unstable/ai" * * // Creating a custom ID generator for AI tool calls @@ -35,7 +35,7 @@ * size: 12 * }) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const idGen = yield* IdGenerator.IdGenerator * const id = yield* idGen.generateId() * console.log(id) // "tool_call-A7XK9MP2QR5T" @@ -64,7 +64,7 @@ import * as ServiceMap from "../../ServiceMap.ts" * import { Effect } from "effect" * import { IdGenerator } from "effect/unstable/ai" * - * const useIdGenerator = Effect.gen(function* () { + * const useIdGenerator = Effect.gen(function*() { * const idGenerator = yield* IdGenerator.IdGenerator * const newId = yield* idGenerator.generateId() * return newId @@ -88,14 +88,14 @@ export class IdGenerator extends ServiceMap.Service()( * @example * ```ts * import { Effect } from "effect" - * import { IdGenerator } from "effect/unstable/ai" + * import type { IdGenerator } from "effect/unstable/ai" * * // Custom implementation * const customService: IdGenerator.Service = { * generateId: () => Effect.succeed(`custom_${Date.now()}`) * } * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const id = yield* customService.generateId() * console.log(id) // "custom_1234567890" * return id @@ -114,7 +114,7 @@ export interface Service { * * @example * ```ts - * import { IdGenerator } from "effect/unstable/ai" + * import type { IdGenerator } from "effect/unstable/ai" * * // Configuration for tool call IDs * const toolCallOptions: IdGenerator.MakeOptions = { @@ -183,10 +183,10 @@ const makeGenerator = ({ * * @example * ```ts - * import { Effect, Layer } from "effect" + * import { Effect } from "effect" * import { IdGenerator } from "effect/unstable/ai" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const id = yield* IdGenerator.defaultIdGenerator.generateId() * console.log(id) // "id_A7xK9mP2qR5tY8uV" * return id @@ -219,7 +219,7 @@ export const defaultIdGenerator: Service = { * import { Effect } from "effect" * import { IdGenerator } from "effect/unstable/ai" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * // Create a generator for AI assistant message IDs * const messageIdGen = yield* IdGenerator.make({ * alphabet: "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ", @@ -247,12 +247,14 @@ export const defaultIdGenerator: Service = { * size: 8 * }) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const generator = yield* invalidConfig * return generator - * }).pipe(Effect.catch(error => - * Effect.succeed(`Configuration error: ${error.message}`) - * )) + * }).pipe( + * Effect.catch((error) => + * Effect.succeed(`Configuration error: ${error.message}`) + * ) + * ) * ``` * * @since 4.0.0 @@ -286,7 +288,7 @@ export const make = Effect.fnUntraced(function*({ * * @example * ```ts - * import { Effect, Layer } from "effect" + * import { Effect } from "effect" * import { IdGenerator } from "effect/unstable/ai" * * // Create a layer for generating AI tool call IDs @@ -297,7 +299,7 @@ export const make = Effect.fnUntraced(function*({ * size: 12 * }) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const idGen = yield* IdGenerator.IdGenerator * const toolCallId = yield* idGen.generateId() * console.log(toolCallId) // "tool_call_A7XK9MP2QR5T" diff --git a/packages/effect/src/unstable/ai/LanguageModel.ts b/packages/effect/src/unstable/ai/LanguageModel.ts index 67b8f1ac4c..a3928735cc 100644 --- a/packages/effect/src/unstable/ai/LanguageModel.ts +++ b/packages/effect/src/unstable/ai/LanguageModel.ts @@ -14,7 +14,7 @@ * import { LanguageModel } from "effect/unstable/ai" * * // Basic text generation - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const response = yield* LanguageModel.generateText({ * prompt: "Explain quantum computing" * }) @@ -37,7 +37,7 @@ * email: Schema.String * }) * - * const extractContact = Effect.gen(function* () { + * const extractContact = Effect.gen(function*() { * const response = yield* LanguageModel.generateObject({ * prompt: "Extract contact: John Doe, john@example.com", * schema: ContactSchema @@ -84,7 +84,7 @@ import * as Toolkit from "./Toolkit.ts" * import { Effect } from "effect" * import { LanguageModel } from "effect/unstable/ai" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const model = yield* LanguageModel.LanguageModel * const response = yield* model.generateText({ * prompt: "What is machine learning?" @@ -268,7 +268,7 @@ export type ToolChoice = "auto" | "none" | "required" | { * import { Effect } from "effect" * import { LanguageModel } from "effect/unstable/ai" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const response = yield* LanguageModel.generateText({ * prompt: "Explain photosynthesis" * }) @@ -378,7 +378,7 @@ export class GenerateTextResponse> { * email: Schema.String * }) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const response = yield* LanguageModel.generateObject({ * prompt: "Create user: John Doe, john@example.com", * schema: UserSchema @@ -905,7 +905,7 @@ export const make: (params: ConstructorParams) => Effect.Effect = Effec * import { Effect } from "effect" * import { LanguageModel } from "effect/unstable/ai" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const response = yield* LanguageModel.generateText({ * prompt: "Write a haiku about programming", * toolChoice: "none" @@ -945,9 +945,10 @@ export const generateText = < * location: Schema.String * }) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const response = yield* LanguageModel.generateObject({ - * prompt: "Extract event info: Tech Conference on March 15th in San Francisco", + * prompt: + * "Extract event info: Tech Conference on March 15th in San Francisco", * schema: EventSchema, * objectName: "event" * }) @@ -981,8 +982,7 @@ export const generateObject = < * * @example * ```ts - * import { Console, Effect } from "effect" - * import { Stream } from "effect" + * import { Console, Effect, Stream } from "effect" * import { LanguageModel } from "effect/unstable/ai" * * const program = LanguageModel.streamText({ diff --git a/packages/effect/src/unstable/ai/McpServer.ts b/packages/effect/src/unstable/ai/McpServer.ts index 9396f02aa9..5afb48bdaf 100644 --- a/packages/effect/src/unstable/ai/McpServer.ts +++ b/packages/effect/src/unstable/ai/McpServer.ts @@ -448,10 +448,10 @@ export const layer = (options: { * * @example * ```ts + * import { NodeRuntime, NodeSink, NodeStream } from "@effect/platform-node" * import { Effect, Layer, Logger } from "effect" * import { Schema } from "effect/schema" * import { McpSchema, McpServer } from "effect/unstable/ai" - * import { NodeRuntime, NodeSink, NodeStream } from "@effect/platform-node" * * const idParam = McpSchema.param("id", Schema.Number) * @@ -477,7 +477,8 @@ export const layer = (options: { * completion: { * flightNumber: () => Effect.succeed(["FL123", "FL456", "FL789"]) * }, - * content: ({ flightNumber }) => Effect.succeed(`Get the booking details for flight number: ${flightNumber}`) + * content: ({ flightNumber }) => + * Effect.succeed(`Get the booking details for flight number: ${flightNumber}`) * }) * * // Merge all the resources and prompts into a single server layer diff --git a/packages/effect/src/unstable/ai/Model.ts b/packages/effect/src/unstable/ai/Model.ts index aa77e29b6d..a8cbe521fb 100644 --- a/packages/effect/src/unstable/ai/Model.ts +++ b/packages/effect/src/unstable/ai/Model.ts @@ -8,14 +8,15 @@ * * @example * ```ts - * import { Effect, Layer } from "effect" - * import { Model, LanguageModel } from "effect/unstable/ai" + * 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", myAnthropicLayer) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const response = yield* LanguageModel.generateText({ * prompt: "Hello, world!" * }) @@ -105,13 +106,14 @@ const Proto = { * * @example * ```ts - * import { Effect, Layer } from "effect" - * import { Model, LanguageModel } from "effect/unstable/ai" + * import type { Layer } from "effect" + * import { Effect } from "effect" + * import { LanguageModel, Model } from "effect/unstable/ai" * * declare const bedrockLayer: Layer.Layer * * // Model automatically provides ProviderName service - * const checkProviderAndGenerate = Effect.gen(function* () { + * const checkProviderAndGenerate = Effect.gen(function*() { * const provider = yield* Model.ProviderName * * console.log(`Generating with: ${provider}`) diff --git a/packages/effect/src/unstable/ai/Prompt.ts b/packages/effect/src/unstable/ai/Prompt.ts index ac6f4924e5..032677a9f0 100644 --- a/packages/effect/src/unstable/ai/Prompt.ts +++ b/packages/effect/src/unstable/ai/Prompt.ts @@ -253,7 +253,7 @@ export type PartConstructorParams

= Omit): TextPart => m * 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...", + * text: + * "Let me think step by step: First I need to understand the user's question..." * }) * ``` * @@ -513,7 +514,7 @@ export const filePart = (params: PartConstructorParams): FilePart => m * id: "call_123", * name: "get_weather", * params: { city: "San Francisco", units: "celsius" }, - * providerExecuted: false, + * providerExecuted: false * }) * ``` * @@ -871,7 +872,7 @@ export const ContentFromString: Schema.decodeTo< * * const systemMessage: Prompt.SystemMessage = Prompt.makeMessage("system", { * content: "You are a helpful assistant specialized in mathematics. " + - * "Always show your work step by step." + * "Always show your work step by step." * }) * ``` * @@ -1101,31 +1102,35 @@ export const userMessage = (params: MessageConstructorParams): User * ```ts * import { Prompt } from "effect/unstable/ai" * - * const assistantMessage: Prompt.AssistantMessage = Prompt.makeMessage("assistant", { - * content: [ - * Prompt.makePart("text", { - * text: "The user is asking about the weather. I should use the weather tool." - * }), - * Prompt.makePart("tool-call", { - * id: "call_123", - * name: "get_weather", - * params: { city: "San Francisco" }, - * providerExecuted: false - * }), - * Prompt.makePart("tool-result", { - * id: "call_123", - * name: "get_weather", - * isFailure: false, - * result: { - * temperature: 72, - * condition: "sunny" - * } - * }), - * Prompt.makePart("text", { - * text: "The weather in San Francisco is currently 72°F and sunny." - * }) - * ] - * }) + * const assistantMessage: Prompt.AssistantMessage = Prompt.makeMessage( + * "assistant", + * { + * content: [ + * Prompt.makePart("text", { + * text: + * "The user is asking about the weather. I should use the weather tool." + * }), + * Prompt.makePart("tool-call", { + * id: "call_123", + * name: "get_weather", + * params: { city: "San Francisco" }, + * providerExecuted: false + * }), + * Prompt.makePart("tool-result", { + * id: "call_123", + * name: "get_weather", + * isFailure: false, + * result: { + * temperature: 72, + * condition: "sunny" + * } + * }), + * Prompt.makePart("text", { + * text: "The weather in San Francisco is currently 72°F and sunny." + * }) + * ] + * } + * ) * ``` * * @since 4.0.0 @@ -1535,7 +1540,7 @@ export const Prompt: Schema.Codec = Schema.Struct({ * * @example * ```ts - * import { Prompt } from "effect/unstable/ai" + * import type { Prompt } from "effect/unstable/ai" * * // String input - creates a user message * const stringInput: Prompt.RawInput = "Hello, world!" diff --git a/packages/effect/src/unstable/ai/Response.ts b/packages/effect/src/unstable/ai/Response.ts index f56881eefe..34dc51c79f 100644 --- a/packages/effect/src/unstable/ai/Response.ts +++ b/packages/effect/src/unstable/ai/Response.ts @@ -587,7 +587,7 @@ export type ConstructorParams = * import { Response } from "effect/unstable/ai" * * const textPart: Response.TextPart = Response.makePart("text", { - * text: "The answer to your question is 42.", + * text: "The answer to your question is 42." * }) * ``` * @@ -846,7 +846,8 @@ export const TextEndPart: Schema.Struct<{ * import { Response } from "effect/unstable/ai" * * const reasoningPart: Response.ReasoningPart = Response.makePart("reasoning", { - * text: "Let me think step by step: First I need to analyze the user's question...", + * text: + * "Let me think step by step: First I need to analyze the user's question..." * }) * ``` * @@ -1358,7 +1359,7 @@ export const ToolParamsEndPart: Schema.Struct<{ * id: "call_123", * name: "get_weather", * params: { city: "San Francisco", units: "celsius" }, - * providerExecuted: false, + * providerExecuted: false * }) * ``` * @@ -1781,7 +1782,7 @@ export const toolResultPart = + * type PrefixedAttrs = Telemetry.AttributesWithPrefix< + * RequestAttrs, + * "gen_ai.request" + * > * // Results in: { * // "gen_ai.request.model_name": string * // "gen_ai.request.max_tokens": number @@ -270,11 +273,11 @@ export type AttributesWithPrefix, Prefix * * @example * ```ts - * import { Telemetry } from "effect/unstable/ai" + * import type { Telemetry } from "effect/unstable/ai" * - * type Formatted1 = Telemetry.FormatAttributeName<"modelName"> // "model_name" - * type Formatted2 = Telemetry.FormatAttributeName<"maxTokens"> // "max_tokens" - * type Formatted3 = Telemetry.FormatAttributeName<"temperature"> // "temperature" + * type Formatted1 = Telemetry.FormatAttributeName<"modelName"> // "model_name" + * type Formatted2 = Telemetry.FormatAttributeName<"maxTokens"> // "max_tokens" + * type Formatted3 = Telemetry.FormatAttributeName<"temperature"> // "temperature" * ``` * * @since 4.0.0 @@ -294,7 +297,8 @@ export type FormatAttributeName = T extends * * @example * ```ts - * import { String, Tracer } from "effect" + * import type { Tracer } from "effect" + * import { String } from "effect" * import { Telemetry } from "effect/unstable/ai" * * const addCustomAttributes = Telemetry.addSpanAttributes( @@ -356,7 +360,7 @@ const addSpanUsageAttributes = addSpanAttributes("gen_ai.usage", String.camelToS * * @example * ```ts - * import { Telemetry } from "effect/unstable/ai" + * import type { Telemetry } from "effect/unstable/ai" * * const telemetryOptions: Telemetry.GenAITelemetryAttributeOptions = { * system: "openai", @@ -419,7 +423,7 @@ export type GenAITelemetryAttributeOptions = BaseAttributes & { * import { Effect } from "effect" * import { Telemetry } from "effect/unstable/ai" * - * const directUsage = Effect.gen(function* () { + * const directUsage = Effect.gen(function*() { * const span = yield* Effect.currentSpan * * Telemetry.addGenAIAnnotations(span, { @@ -453,13 +457,14 @@ export const addGenAIAnnotations: { * * @example * ```ts - * import { Telemetry } from "effect/unstable/ai" + * import type { Telemetry } from "effect/unstable/ai" * - * const customTransformer: Telemetry.SpanTransformer = ({ span, response }) => { + * const customTransformer: Telemetry.SpanTransformer = ({ response, span }) => { * // Add custom attributes based on the response - * const textParts = response.filter(part => part.type === "text") - * const totalTextLength = textParts.reduce((sum, part) => - * sum + (part.type === "text" ? part.text.length : 0), 0 + * const textParts = response.filter((part) => part.type === "text") + * const totalTextLength = textParts.reduce( + * (sum, part) => sum + (part.type === "text" ? part.text.length : 0), + * 0 * ) * span.attribute("total_text_length", totalTextLength) * } diff --git a/packages/effect/src/unstable/ai/Tokenizer.ts b/packages/effect/src/unstable/ai/Tokenizer.ts index 6a02079ccc..7e39326810 100644 --- a/packages/effect/src/unstable/ai/Tokenizer.ts +++ b/packages/effect/src/unstable/ai/Tokenizer.ts @@ -8,10 +8,10 @@ * * @example * ```ts - * import { Tokenizer, Prompt } from "effect/unstable/ai" * import { Effect } from "effect" + * import { Tokenizer } from "effect/unstable/ai" * - * const tokenizeText = Effect.gen(function* () { + * const tokenizeText = Effect.gen(function*() { * const tokenizer = yield* Tokenizer.Tokenizer * const tokens = yield* tokenizer.tokenize("Hello, world!") * console.log(`Token count: ${tokens.length}`) @@ -21,11 +21,11 @@ * * @example * ```ts - * import { Tokenizer, Prompt } from "effect/unstable/ai" * import { Effect } from "effect" + * import { Tokenizer } from "effect/unstable/ai" * * // Truncate a prompt to fit within token limits - * const truncatePrompt = Effect.gen(function* () { + * 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) @@ -49,10 +49,10 @@ import * as Prompt from "./Prompt.ts" * * @example * ```ts - * import { Tokenizer } from "effect/unstable/ai" * import { Effect } from "effect" + * import { Tokenizer } from "effect/unstable/ai" * - * const useTokenizer = Effect.gen(function* () { + * const useTokenizer = Effect.gen(function*() { * const tokenizer = yield* Tokenizer.Tokenizer * const tokens = yield* tokenizer.tokenize("Hello, world!") * return tokens.length @@ -76,11 +76,12 @@ export class Tokenizer extends ServiceMap.Service()( * @example * ```ts * import { Effect } from "effect" - * import { Tokenizer, Prompt } from "effect/unstable/ai" + * import type { Tokenizer } from "effect/unstable/ai" + * import { Prompt } from "effect/unstable/ai" * * const customTokenizer: Tokenizer.Service = { * tokenize: (input) => - * Effect.succeed(input.toString().split(' ').map((_, i) => i)), + * Effect.succeed(input.toString().split(" ").map((_, i) => i)), * truncate: (input, maxTokens) => * Effect.succeed(Prompt.make(input.toString().slice(0, maxTokens * 5))) * } @@ -124,19 +125,19 @@ export interface Service { * @example * ```ts * import { Effect } from "effect" - * import { Tokenizer, Prompt } from "effect/unstable/ai" + * import { Tokenizer } from "effect/unstable/ai" * * // Simple word-based tokenizer * const wordTokenizer = Tokenizer.make({ * tokenize: (prompt) => * Effect.succeed( * prompt.content - * .flatMap(msg => + * .flatMap((msg) => * typeof msg.content === "string" - * ? msg.content.split(' ') - * : msg.content.flatMap(part => - * part.type === "text" ? part.text.split(' ') : [] - * ) + * ? msg.content.split(" ") + * : msg.content.flatMap((part) => + * part.type === "text" ? part.text.split(" ") : [] + * ) * ) * .map((_, index) => index) * ) diff --git a/packages/effect/src/unstable/ai/Tool.ts b/packages/effect/src/unstable/ai/Tool.ts index d184f2ec42..c354f45956 100644 --- a/packages/effect/src/unstable/ai/Tool.ts +++ b/packages/effect/src/unstable/ai/Tool.ts @@ -353,8 +353,8 @@ export interface ProviderDefined< * }) * }) * - * console.log(Tool.isUserDefined(UserDefinedTool)) // true - * console.log(Tool.isUserDefined(ProviderDefinedTool)) // false + * console.log(Tool.isUserDefined(UserDefinedTool)) // true + * console.log(Tool.isUserDefined(ProviderDefinedTool)) // false * ``` * * @since 4.0.0 @@ -397,8 +397,8 @@ export const isUserDefined = (u: unknown): u is Tool => * }) * }) * - * console.log(Tool.isUserDefined(UserDefinedTool)) // false - * console.log(Tool.isUserDefined(ProviderDefinedTool)) // true + * console.log(Tool.isUserDefined(UserDefinedTool)) // false + * console.log(Tool.isUserDefined(ProviderDefinedTool)) // true * ``` * * @since 4.0.0 diff --git a/packages/effect/src/unstable/ai/Toolkit.ts b/packages/effect/src/unstable/ai/Toolkit.ts index c142190a5c..82b27fcca8 100644 --- a/packages/effect/src/unstable/ai/Toolkit.ts +++ b/packages/effect/src/unstable/ai/Toolkit.ts @@ -7,7 +7,7 @@ * ```ts * import { Effect } from "effect" * import { Schema } from "effect/schema" - * import { Toolkit, Tool } from "effect/unstable/ai" + * import { Tool, Toolkit } from "effect/unstable/ai" * * // Create individual tools * const GetCurrentTime = Tool.make("GetCurrentTime", { @@ -29,10 +29,11 @@ * * const MyToolkitLayer = MyToolkit.toLayer({ * GetCurrentTime: () => Effect.succeed(Date.now()), - * GetWeather: ({ location }) => Effect.succeed({ - * temperature: 72, - * condition: "sunny" - * }) + * GetWeather: ({ location }) => + * Effect.succeed({ + * temperature: 72, + * condition: "sunny" + * }) * }) * ``` * @@ -61,7 +62,7 @@ const TypeId = "~effect/ai/Toolkit" as const * ```ts * import { Effect } from "effect" * import { Schema } from "effect/schema" - * import { Toolkit, Tool } from "effect/unstable/ai" + * import { Tool, Toolkit } from "effect/unstable/ai" * * // Create individual tools * const GetCurrentTime = Tool.make("GetCurrentTime", { @@ -83,10 +84,11 @@ const TypeId = "~effect/ai/Toolkit" as const * * const MyToolkitLayer = MyToolkit.toLayer({ * GetCurrentTime: () => Effect.succeed(Date.now()), - * GetWeather: ({ location }) => Effect.succeed({ - * temperature: 72, - * condition: "sunny" - * }) + * GetWeather: ({ location }) => + * Effect.succeed({ + * temperature: 72, + * condition: "sunny" + * }) * }) * ``` * @@ -397,7 +399,7 @@ export const empty: Toolkit<{}> = makeProto({}) * @example * ```ts * import { Schema } from "effect/schema" - * import { Toolkit, Tool } from "effect/unstable/ai" + * import { Tool, Toolkit } from "effect/unstable/ai" * * const GetCurrentTime = Tool.make("GetCurrentTime", { * description: "Get the current timestamp", @@ -464,7 +466,7 @@ export type MergedTools> = SimplifyRecord< * * @example * ```ts - * import { Toolkit, Tool } from "effect/unstable/ai" + * import { Tool, Toolkit } from "effect/unstable/ai" * * const mathToolkit = Toolkit.make( * Tool.make("add"), @@ -482,7 +484,7 @@ export type MergedTools> = SimplifyRecord< * * @example * ```ts - * import { Toolkit, Tool } from "effect/unstable/ai" + * import { Tool, Toolkit } from "effect/unstable/ai" * * // Incremental toolkit building * const baseToolkit = Toolkit.make(Tool.make("base_tool")) diff --git a/packages/effect/src/unstable/ai/index.ts b/packages/effect/src/unstable/ai/index.ts index 0c6ecd1152..711dd8972c 100644 --- a/packages/effect/src/unstable/ai/index.ts +++ b/packages/effect/src/unstable/ai/index.ts @@ -21,24 +21,27 @@ * @example * ```ts * import { Effect, Match } from "effect" - * import { AiError } from "effect/unstable/ai" + * import type { AiError } from "effect/unstable/ai" * * const handleAiError = Match.type().pipe( - * Match.tag("HttpRequestError", (err) => - * Effect.logError(`Request failed: ${err.message}`) + * Match.tag( + * "HttpRequestError", + * (err) => Effect.logError(`Request failed: ${err.message}`) * ), - * Match.tag("HttpResponseError", (err) => - * Effect.logError(`Response error (${err.response.status}): ${err.message}`) + * Match.tag( + * "HttpResponseError", + * (err) => + * Effect.logError(`Response error (${err.response.status}): ${err.message}`) * ), - * Match.tag("MalformedInput", (err) => - * Effect.logError(`Invalid input: ${err.message}`) + * Match.tag( + * "MalformedInput", + * (err) => Effect.logError(`Invalid input: ${err.message}`) * ), - * Match.tag("MalformedOutput", (err) => - * Effect.logError(`Invalid output: ${err.message}`) + * Match.tag( + * "MalformedOutput", + * (err) => Effect.logError(`Invalid output: ${err.message}`) * ), - * Match.orElse((err) => - * Effect.logError(`Unknown error: ${err.message}`) - * ) + * Match.orElse((err) => Effect.logError(`Unknown error: ${err.message}`)) * ) * ``` * @@ -47,7 +50,7 @@ * import { Effect } from "effect" * import { AiError } from "effect/unstable/ai" * - * const aiOperation = Effect.gen(function* () { + * const aiOperation = Effect.gen(function*() { * // Some AI operation that might fail * return yield* new AiError.HttpRequestError({ * module: "OpenAI", @@ -86,11 +89,11 @@ export * as AiError from "./AiError.ts" * * @example * ```ts - * import { Effect, Layer } from "effect" - * import { Chat, LanguageModel } from "effect/unstable/ai" + * import { Effect } from "effect" + * import { Chat } from "effect/unstable/ai" * * // Create a new chat session - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const chat = yield* Chat.empty * * // Send a message and get response @@ -106,19 +109,16 @@ export * as AiError from "./AiError.ts" * * @example * ```ts - * import { Effect } from "effect" - * import { Stream } from "effect" - * import { Chat, LanguageModel } from "effect/unstable/ai" + * import { Effect, Stream } from "effect" + * import { Chat } from "effect/unstable/ai" * * // Streaming chat with tool support - * const streamingChat = Effect.gen(function* () { + * 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)) - * )) + * }).pipe(Stream.runForEach((part) => Effect.sync(() => console.log(part)))) * }) * ``` * @@ -135,11 +135,11 @@ export * as Chat from "./Chat.ts" * * @example * ```ts - * import { Effect, Layer } from "effect" + * import { Effect } from "effect" * import { IdGenerator } from "effect/unstable/ai" * * // Using the default ID generator - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const idGen = yield* IdGenerator.IdGenerator * const toolCallId = yield* idGen.generateId() * console.log(toolCallId) // "id_A7xK9mP2qR5tY8uV" @@ -152,7 +152,7 @@ export * as Chat from "./Chat.ts" * * @example * ```ts - * import { Effect, Layer } from "effect" + * import { Effect } from "effect" * import { IdGenerator } from "effect/unstable/ai" * * // Creating a custom ID generator for AI tool calls @@ -163,7 +163,7 @@ export * as Chat from "./Chat.ts" * size: 12 * }) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const idGen = yield* IdGenerator.IdGenerator * const id = yield* idGen.generateId() * console.log(id) // "tool_call-A7XK9MP2QR5T" @@ -191,7 +191,7 @@ export * as IdGenerator from "./IdGenerator.ts" * import { LanguageModel } from "effect/unstable/ai" * * // Basic text generation - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const response = yield* LanguageModel.generateText({ * prompt: "Explain quantum computing" * }) @@ -214,7 +214,7 @@ export * as IdGenerator from "./IdGenerator.ts" * email: Schema.String * }) * - * const extractContact = Effect.gen(function* () { + * const extractContact = Effect.gen(function*() { * const response = yield* LanguageModel.generateObject({ * prompt: "Extract contact: John Doe, john@example.com", * schema: ContactSchema @@ -248,14 +248,15 @@ export * as McpServer from "./McpServer.ts" * * @example * ```ts - * import { Effect, Layer } from "effect" - * import { Model, LanguageModel } from "effect/unstable/ai" + * 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", myAnthropicLayer) * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const response = yield* LanguageModel.generateText({ * prompt: "Hello, world!" * }) @@ -366,7 +367,7 @@ export * as Response from "./Response.ts" * import { Telemetry } from "effect/unstable/ai" * * // Add telemetry attributes to a span - * const addTelemetry = Effect.gen(function* () { + * const addTelemetry = Effect.gen(function*() { * const span = yield* Effect.currentSpan * * Telemetry.addGenAIAnnotations(span, { @@ -399,10 +400,10 @@ export * as Telemetry from "./Telemetry.ts" * * @example * ```ts - * import { Tokenizer, Prompt } from "effect/unstable/ai" * import { Effect } from "effect" + * import { Tokenizer } from "effect/unstable/ai" * - * const tokenizeText = Effect.gen(function* () { + * const tokenizeText = Effect.gen(function*() { * const tokenizer = yield* Tokenizer.Tokenizer * const tokens = yield* tokenizer.tokenize("Hello, world!") * console.log(`Token count: ${tokens.length}`) @@ -412,11 +413,11 @@ export * as Telemetry from "./Telemetry.ts" * * @example * ```ts - * import { Tokenizer, Prompt } from "effect/unstable/ai" * import { Effect } from "effect" + * import { Tokenizer } from "effect/unstable/ai" * * // Truncate a prompt to fit within token limits - * const truncatePrompt = Effect.gen(function* () { + * 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) @@ -467,7 +468,7 @@ export * as Tool from "./Tool.ts" * ```ts * import { Effect } from "effect" * import { Schema } from "effect/schema" - * import { Toolkit, Tool } from "effect/unstable/ai" + * import { Tool, Toolkit } from "effect/unstable/ai" * * // Create individual tools * const GetCurrentTime = Tool.make("GetCurrentTime", { @@ -489,10 +490,11 @@ export * as Tool from "./Tool.ts" * * const MyToolkitLayer = MyToolkit.toLayer({ * GetCurrentTime: () => Effect.succeed(Date.now()), - * GetWeather: ({ location }) => Effect.succeed({ - * temperature: 72, - * condition: "sunny" - * }) + * GetWeather: ({ location }) => + * Effect.succeed({ + * temperature: 72, + * condition: "sunny" + * }) * }) * ``` * diff --git a/packages/effect/src/unstable/cli/Argument.ts b/packages/effect/src/unstable/cli/Argument.ts index 02e7a9ac56..35ff7407d6 100644 --- a/packages/effect/src/unstable/cli/Argument.ts +++ b/packages/effect/src/unstable/cli/Argument.ts @@ -2,10 +2,10 @@ * @since 4.0.0 */ import type * as Effect from "../../Effect.ts" +import type * as FileSystem from "../../FileSystem.ts" import { dual, type LazyArg } from "../../Function.ts" import type * as Option from "../../Option.ts" -import type * as FileSystem from "../../platform/FileSystem.ts" -import type * as Path from "../../platform/Path.ts" +import type * as Path from "../../Path.ts" import type * as Redacted from "../../Redacted.ts" import type * as Result from "../../Result.ts" import type * as Schema from "../../schema/Schema.ts" @@ -219,8 +219,8 @@ export const fileParse = ( * * @example * ```ts - * import { Argument } from "effect/unstable/cli" * import { Schema } from "effect/schema" + * import { Argument } from "effect/unstable/cli" * * const ConfigSchema = Schema.Struct({ * port: Schema.Number, @@ -325,10 +325,14 @@ export const withDefault: { * const anyFiles = Argument.string("files").pipe(Argument.variadic) * * // Accept at least 1 file - * const atLeastOneFile = Argument.string("files").pipe(Argument.variadic({ min: 1 })) + * const atLeastOneFile = Argument.string("files").pipe( + * Argument.variadic({ min: 1 }) + * ) * * // Accept between 1 and 5 files - * const limitedFiles = Argument.string("files").pipe(Argument.variadic({ min: 1, max: 5 })) + * const limitedFiles = Argument.string("files").pipe( + * Argument.variadic({ min: 1, max: 5 }) + * ) * ``` * * @since 4.0.0 @@ -350,7 +354,7 @@ export const variadic: { * import { Argument } from "effect/unstable/cli" * * const port = Argument.integer("port").pipe( - * Argument.map(p => ({ port: p, url: `http://localhost:${p}` })) + * Argument.map((p) => ({ port: p, url: `http://localhost:${p}` })) * ) * ``` * @@ -367,16 +371,18 @@ export const map: { * * @example * ```ts - * import { Argument, CliError } from "effect/unstable/cli" * import { Effect } from "effect" + * import { Argument, CliError } from "effect/unstable/cli" * * const files = Argument.string("files").pipe( - * Argument.mapEffect(file => + * Argument.mapEffect((file) => * file.endsWith(".txt") * ? Effect.succeed(file) - * : Effect.fail(new CliError.UserError({ + * : Effect.fail( + * new CliError.UserError({ * cause: new Error("Only .txt files allowed") - * })) + * }) + * ) * ) * ) * ``` @@ -406,8 +412,9 @@ export const mapEffect: { * * const json = Argument.string("data").pipe( * Argument.mapTryCatch( - * str => JSON.parse(str), - * error => `Invalid JSON: ${error instanceof Error ? error.message : String(error)}` + * (str) => JSON.parse(str), + * (error) => + * `Invalid JSON: ${error instanceof Error ? error.message : String(error)}` * ) * ) * ``` @@ -486,8 +493,8 @@ export const between: { * * @example * ```ts - * import { Argument } from "effect/unstable/cli" * import { Schema } from "effect/schema" + * import { Argument } from "effect/unstable/cli" * * const input = Argument.string("input").pipe( * Argument.withSchema(Schema.NonEmptyString) @@ -561,8 +568,8 @@ export const withMetavar: { * * const positiveInt = Argument.integer("count").pipe( * Argument.filter( - * n => n > 0, - * n => `Expected positive integer, got ${n}` + * (n) => n > 0, + * (n) => `Expected positive integer, got ${n}` * ) * ) * ``` diff --git a/packages/effect/src/unstable/cli/CliError.ts b/packages/effect/src/unstable/cli/CliError.ts index 955603591e..9783ae00dc 100644 --- a/packages/effect/src/unstable/cli/CliError.ts +++ b/packages/effect/src/unstable/cli/CliError.ts @@ -15,8 +15,8 @@ const TypeId = "~effect/cli/CliError" * * @example * ```ts - * import { CliError } from "effect/unstable/cli" * import { Effect } from "effect" + * import { CliError } from "effect/unstable/cli" * * const handleError = (error: unknown) => { * if (CliError.isCliError(error)) { @@ -27,7 +27,7 @@ const TypeId = "~effect/cli/CliError" * } * * // Example usage in error handling - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const result = yield* Effect.try({ * try: () => ({ success: true }), * catch: (error) => error @@ -46,8 +46,7 @@ export const isCliError = (u: unknown): u is CliError => Predicate.hasProperty(u * * @example * ```ts - * import { CliError } from "effect/unstable/cli" - * import { Effect } from "effect" + * import type { CliError } from "effect/unstable/cli" * * const handleCliError = (error: CliError.CliError): void => { * switch (error._tag) { @@ -88,8 +87,8 @@ export type CliError = * * @example * ```ts - * import { CliError } from "effect/unstable/cli" * import { Effect } from "effect" + * import { CliError } from "effect/unstable/cli" * * // Creating an unrecognized option error * const unrecognizedError = new CliError.UnrecognizedOption({ @@ -106,7 +105,7 @@ export type CliError = * // --force" * * // In CLI parsing context - * const parseCommand = Effect.gen(function* () { + * const parseCommand = Effect.gen(function*() { * // If parsing encounters unknown flag * return yield* Effect.fail(unrecognizedError) * }) @@ -186,8 +185,8 @@ export class DuplicateOption extends Schema.ErrorClass(`${TypeId}/DuplicateOptio * * @example * ```ts - * import { CliError } from "effect/unstable/cli" * import { Effect } from "effect" + * import { CliError } from "effect/unstable/cli" * * const missingOptionError = new CliError.MissingOption({ * option: "api-key" @@ -197,13 +196,14 @@ export class DuplicateOption extends Schema.ErrorClass(`${TypeId}/DuplicateOptio * // "Missing required flag: --api-key" * * // In validation context - * const validateRequiredOptions = (options: Record) => Effect.gen(function* () { - * const apiKey = options["api-key"] - * if (!apiKey) { - * return yield* Effect.fail(missingOptionError) - * } - * return apiKey - * }) + * const validateRequiredOptions = (options: Record) => + * Effect.gen(function*() { + * const apiKey = options["api-key"] + * if (!apiKey) { + * return yield* Effect.fail(missingOptionError) + * } + * return apiKey + * }) * ``` * * @since 4.0.0 @@ -231,8 +231,8 @@ export class MissingOption extends Schema.ErrorClass(`${TypeId}/MissingOption`)( * * @example * ```ts - * import { CliError } from "effect/unstable/cli" * import { Effect } from "effect" + * import { CliError } from "effect/unstable/cli" * * const missingArgError = new CliError.MissingArgument({ * argument: "target" @@ -242,12 +242,13 @@ export class MissingOption extends Schema.ErrorClass(`${TypeId}/MissingOption`)( * // "Missing required argument: target" * * // In argument parsing - * const parseArguments = (args: string[]) => Effect.gen(function* () { - * if (args.length === 0) { - * return yield* Effect.fail(missingArgError) - * } - * return args[0] - * }) + * const parseArguments = (args: Array) => + * Effect.gen(function*() { + * if (args.length === 0) { + * return yield* Effect.fail(missingArgError) + * } + * return args[0] + * }) * ``` * * @since 4.0.0 @@ -275,8 +276,8 @@ export class MissingArgument extends Schema.ErrorClass(`${TypeId}/MissingArgumen * * @example * ```ts - * import { CliError } from "effect/unstable/cli" * import { Effect } from "effect" + * import { CliError } from "effect/unstable/cli" * * const invalidValueError = new CliError.InvalidValue({ * option: "port", @@ -288,13 +289,14 @@ export class MissingArgument extends Schema.ErrorClass(`${TypeId}/MissingArgumen * // "Invalid value for flag --port: "abc123". Expected: integer between 1 and 65535" * * // In value validation - * const validatePortValue = (value: string) => Effect.gen(function* () { - * const port = Number(value) - * if (isNaN(port) || port < 1 || port > 65535) { - * return yield* Effect.fail(invalidValueError) - * } - * return port - * }) + * const validatePortValue = (value: string) => + * Effect.gen(function*() { + * const port = Number(value) + * if (isNaN(port) || port < 1 || port > 65535) { + * return yield* Effect.fail(invalidValueError) + * } + * return port + * }) * ``` * * @since 4.0.0 @@ -324,8 +326,8 @@ export class InvalidValue extends Schema.ErrorClass(`${TypeId}/InvalidValue`)({ * * @example * ```ts - * import { CliError } from "effect/unstable/cli" * import { Effect } from "effect" + * import { CliError } from "effect/unstable/cli" * * const unknownSubcommandError = new CliError.UnknownSubcommand({ * subcommand: "deplyo", // typo @@ -341,13 +343,14 @@ export class InvalidValue extends Schema.ErrorClass(`${TypeId}/InvalidValue`)({ * // destroy" * * // In subcommand parsing - * const parseSubcommand = (subcommand: string) => Effect.gen(function* () { - * const validCommands = ["deploy", "destroy", "status"] - * if (!validCommands.includes(subcommand)) { - * return yield* Effect.fail(unknownSubcommandError) - * } - * return subcommand - * }) + * const parseSubcommand = (subcommand: string) => + * Effect.gen(function*() { + * const validCommands = ["deploy", "destroy", "status"] + * if (!validCommands.includes(subcommand)) { + * return yield* Effect.fail(unknownSubcommandError) + * } + * return subcommand + * }) * ``` * * @since 4.0.0 @@ -383,8 +386,8 @@ export class UnknownSubcommand extends Schema.ErrorClass(`${TypeId}/UnknownSubco * * @example * ```ts - * import { CliError } from "effect/unstable/cli" * import { Effect } from "effect" + * import { CliError } from "effect/unstable/cli" * * const showHelpIndicator = new CliError.ShowHelp({ * commandPath: ["myapp", "deploy", "production"] @@ -394,12 +397,13 @@ export class UnknownSubcommand extends Schema.ErrorClass(`${TypeId}/UnknownSubco * // "Help requested" * * // In help flag handling - * const handleHelpFlag = (hasHelpFlag: boolean) => Effect.gen(function* () { - * if (hasHelpFlag) { - * return yield* Effect.fail(showHelpIndicator) - * } - * return "continuing with command" - * }) + * const handleHelpFlag = (hasHelpFlag: boolean) => + * Effect.gen(function*() { + * if (hasHelpFlag) { + * return yield* Effect.fail(showHelpIndicator) + * } + * return "continuing with command" + * }) * * // In error handling * const handleCliErrors = (error: CliError.CliError): void => { @@ -436,8 +440,8 @@ export class ShowHelp extends Schema.ErrorClass(`${TypeId}/ShowHelp`)({ * * @example * ```ts - * import { CliError } from "effect/unstable/cli" * import { Effect } from "effect" + * import { CliError } from "effect/unstable/cli" * * // Wrapping user errors * const userError = new CliError.UserError({ @@ -445,7 +449,7 @@ export class ShowHelp extends Schema.ErrorClass(`${TypeId}/ShowHelp`)({ * }) * * // In command handler - * const deployCommand = Effect.gen(function* () { + * const deployCommand = Effect.gen(function*() { * const result = yield* Effect.try({ * try: () => ({ deployed: true }), * catch: (error) => new CliError.UserError({ cause: error }) diff --git a/packages/effect/src/unstable/cli/CliOutput.ts b/packages/effect/src/unstable/cli/CliOutput.ts index 3445c61e5c..c7f3cda87f 100644 --- a/packages/effect/src/unstable/cli/CliOutput.ts +++ b/packages/effect/src/unstable/cli/CliOutput.ts @@ -44,7 +44,8 @@ export interface Formatter { * * @example * ```ts - * import { CliOutput, HelpDoc } from "effect/unstable/cli" + * import type { HelpDoc } from "effect/unstable/cli" + * import { CliOutput } from "effect/unstable/cli" * * const helpDoc: HelpDoc = { * usage: "myapp [options] ", @@ -84,8 +85,8 @@ export interface Formatter { * * @example * ```ts - * import { CliOutput, CliError } from "effect/unstable/cli" * import * as Data from "effect/Data" + * import { CliOutput } from "effect/unstable/cli" * * class InvalidOption extends Data.TaggedError("InvalidOption")<{ * readonly message: string @@ -106,8 +107,8 @@ export interface Formatter { * * @example * ```ts - * import { CliOutput, CliError } from "effect/unstable/cli" * import * as Data from "effect/Data" + * import { CliOutput } from "effect/unstable/cli" * * class ValidationError extends Data.TaggedError("ValidationError")<{ * readonly message: string @@ -158,12 +159,15 @@ export interface Formatter { * * @example * ```ts - * import { CliOutput, CliError } from "effect/unstable/cli" + * import { CliError, CliOutput } from "effect/unstable/cli" * * const formatter = CliOutput.defaultFormatter({ colors: false }) * * const errors = [ - * new CliError.UnrecognizedOption({ option: "--foo", suggestions: ["--force"] }), + * new CliError.UnrecognizedOption({ + * option: "--foo", + * suggestions: ["--force"] + * }), * new CliError.UnrecognizedOption({ option: "--bar", suggestions: [] }), * new CliError.MissingOption({ option: "--required" }) * ] @@ -183,11 +187,11 @@ export interface Formatter { * * @example * ```ts - * import { CliOutput } from "effect/unstable/cli" * import * as Effect from "effect/Effect" + * import { CliOutput } from "effect/unstable/cli" * * // Access the formatter service - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const formatter = yield* CliOutput.Formatter * * // Format version information @@ -214,16 +218,16 @@ export const Formatter: ServiceMap.Reference = ServiceMap.Reference( * * @example * ```ts - * import { CliOutput } from "effect/unstable/cli" - * import * as Effect from "effect/Effect" * import * as Console from "effect/Console" + * import * as Effect from "effect/Effect" + * import { CliOutput } from "effect/unstable/cli" * * // Create a custom formatter without colors * const noColorFormatter = CliOutput.defaultFormatter({ colors: false }) * const NoColorLayer = CliOutput.layer(noColorFormatter) * * // Create a program that uses the custom formatter - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const formatter = yield* CliOutput.Formatter * const versionText = formatter.formatVersion("my-cli", "1.0.0") * yield* Console.log(`Using custom formatter: ${versionText}`) @@ -235,7 +239,8 @@ export const Formatter: ServiceMap.Reference = ServiceMap.Reference( * const jsonFormatter: CliOutput.Formatter = { * formatHelpDoc: (doc) => JSON.stringify(doc, null, 2), * formatCliError: (error) => JSON.stringify({ error: error.message }), - * formatError: (error) => JSON.stringify({ type: "error", message: error.message }), + * formatError: (error) => + * JSON.stringify({ type: "error", message: error.message }), * formatVersion: (name, version) => JSON.stringify({ name, version }), * formatErrors: (errors) => JSON.stringify(errors.map((error) => error.message)) * } diff --git a/packages/effect/src/unstable/cli/Command.ts b/packages/effect/src/unstable/cli/Command.ts index 86b6d249d2..a7f11ab3e9 100644 --- a/packages/effect/src/unstable/cli/Command.ts +++ b/packages/effect/src/unstable/cli/Command.ts @@ -3,15 +3,15 @@ */ import * as Console from "../../Console.ts" import * as Effect from "../../Effect.ts" +import type * as FileSystem from "../../FileSystem.ts" import { dual } from "../../Function.ts" import type * as Layer from "../../Layer.ts" +import type * as Path from "../../Path.ts" import type { Pipeable } from "../../Pipeable.ts" -import type * as FileSystem from "../../platform/FileSystem.ts" -import type * as Path from "../../platform/Path.ts" -import type * as Terminal from "../../platform/Terminal.ts" import * as Predicate from "../../Predicate.ts" import * as References from "../../References.ts" import type * as ServiceMap from "../../ServiceMap.ts" +import type * as Terminal from "../../Terminal.ts" import type { Simplify } from "../../types/Types.ts" import * as CliError from "./CliError.ts" import * as CliOutput from "./CliOutput.ts" @@ -46,7 +46,9 @@ import * as Prompt from "./Prompt.ts" * import { Argument, Command, Flag } from "effect/unstable/cli" * * // Simple command with no configuration - * const version: Command.Command<"version", {}, never, never> = Command.make("version") + * const version: Command.Command<"version", {}, never, never> = Command.make( + * "version" + * ) * * // Command with flags and arguments * const deploy: Command.Command< @@ -114,8 +116,8 @@ export declare namespace Command { * * @example * ```ts - * import type * as CliCommand from "effect/unstable/cli/Command" * import { Argument, Flag } from "effect/unstable/cli" + * import type * as CliCommand from "effect/unstable/cli/Command" * * // Simple flat configuration * const simpleConfig: CliCommand.Command.Config = { @@ -162,8 +164,8 @@ export declare namespace Command { * * @example * ```ts + * import { Flag } from "effect/unstable/cli" * import type * as CliCommand from "effect/unstable/cli/Command" - * import { Argument, Flag } from "effect/unstable/cli" * * const config = { * name: Flag.string("name"), @@ -243,8 +245,8 @@ export type Error = C extends Command< * * @example * ```ts + * import { Console, Effect } from "effect" * import { Command, Flag } from "effect/unstable/cli" - * import { Effect, Console } from "effect" * * const parent = Command.make("app", { * verbose: Flag.boolean("verbose"), @@ -260,8 +262,7 @@ export type Error = C extends Command< * yield* Console.log(`Verbose: ${parentConfig.verbose}`) * yield* Console.log(`Config: ${parentConfig.config}`) * yield* Console.log(`Target: ${config.target}`) - * }) - * ) + * })) * * const app = parent.pipe(Command.withSubcommands([child])) * // Usage: app --verbose --config prod.json deploy --target staging @@ -304,8 +305,8 @@ export interface ParsedTokens { * * @example * ```ts - * import { Command, Flag, Argument } from "effect/unstable/cli" - * import { Effect, Console } from "effect" + * import { Console, Effect } from "effect" + * import { Argument, Command, Flag } from "effect/unstable/cli" * * // Simple command with no configuration * const version = Command.make("version") @@ -318,7 +319,9 @@ export interface ParsedTokens { * * // Command with nested configuration * const deploy = Command.make("deploy", { - * environment: Flag.string("env").pipe(Flag.withDescription("Target environment")), + * environment: Flag.string("env").pipe( + * Flag.withDescription("Target environment") + * ), * server: { * host: Flag.string("host").pipe(Flag.withDefault("localhost")), * port: Flag.integer("port").pipe(Flag.withDefault(3000)) @@ -340,8 +343,7 @@ export interface ParsedTokens { * } * * yield* Console.log("Deployment completed successfully") - * }) - * ) + * })) * ``` * * @since 4.0.0 @@ -382,8 +384,8 @@ export const make: { * * @example * ```ts + * import { Console } from "effect" * import { Command, Prompt } from "effect/unstable/cli" - * import { Effect, Console } from "effect" * * const setup = Command.prompt( * "setup", @@ -420,8 +422,8 @@ export const prompt = ( * * @example * ```ts + * import { Console } from "effect" * import { Command, Flag } from "effect/unstable/cli" - * import { Effect, Console } from "effect" * * // Command without initial handler * const greet = Command.make("greet", { @@ -430,7 +432,7 @@ export const prompt = ( * * // Add handler later * const greetWithHandler = greet.pipe( - * Command.withHandler((config) => + * Command.withHandler((config: { readonly name: string }) => * Console.log(`Hello, ${config.name}!`) * ) * ) @@ -463,8 +465,8 @@ export const withHandler: { * * @example * ```ts + * import { Console, Effect } from "effect" * import { Command, Flag } from "effect/unstable/cli" - * import { Effect, Console } from "effect" * * // Parent command with global flags * const git = Command.make("git", { @@ -476,13 +478,12 @@ export const withHandler: { * repository: Flag.string("repo") * }, (config) => * Effect.gen(function*() { - * const parent = yield* git // Access parent's parsed config + * const parent = yield* git // Access parent's parsed config * if (parent.verbose) { * yield* Console.log("Verbose mode enabled") * } * yield* Console.log(`Cloning ${config.repository}`) - * }) - * ) + * })) * * const app = git.pipe(Command.withSubcommands([clone])) * // Usage: git --verbose clone --repo github.com/foo/bar @@ -596,18 +597,17 @@ type ExtractSubcommandContext * Effect.gen(function*() { * yield* Console.log(`Deploying to ${config.environment}`) - * }) - * ).pipe( - * Command.withDescription("Deploy the application to a specified environment") - * ) + * })).pipe( + * Command.withDescription("Deploy the application to a specified environment") + * ) * ``` * * @since 4.0.0 @@ -645,9 +645,8 @@ const mapHandler = ( * * @example * ```ts + * import { Effect, FileSystem, PlatformError } from "effect" * import { Command, Flag } from "effect/unstable/cli" - * import { Effect, Layer } from "effect" - * import { FileSystem, PlatformError } from "effect/platform" * * const deploy = Command.make("deploy", { * env: Flag.string("env") @@ -655,21 +654,22 @@ const mapHandler = ( * Effect.gen(function*() { * const fs = yield* FileSystem.FileSystem * // Use fs... - * }) - * ).pipe( - * // Provide FileSystem based on the --env flag - * Command.provide((config) => - * config.env === "local" - * ? FileSystem.layerNoop({}) - * : FileSystem.layerNoop({ + * })).pipe( + * // Provide FileSystem based on the --env flag + * Command.provide((config) => + * config.env === "local" + * ? FileSystem.layerNoop({}) + * : FileSystem.layerNoop({ * access: () => - * Effect.fail(new PlatformError.BadArgument({ - * module: "FileSystem", - * method: "access" - * })) + * Effect.fail( + * new PlatformError.BadArgument({ + * module: "FileSystem", + * method: "access" + * }) + * ) * }) + * ) * ) - * ) * ``` * * @since 4.0.0 @@ -797,16 +797,15 @@ const showHelp = ( * * @example * ```ts + * import { Console, Effect } from "effect" * import { Command, Flag } from "effect/unstable/cli" - * import { Effect, Console } from "effect" * * const greetCommand = Command.make("greet", { * name: Flag.string("name") * }, (config) => * Effect.gen(function*() { * yield* Console.log(`Hello, ${config.name}!`) - * }) - * ) + * })) * * // Automatically gets args from process.argv * const program = Command.run(greetCommand, { @@ -844,8 +843,8 @@ export const run: { * * @example * ```ts - * import { Command, Flag, Argument } from "effect/unstable/cli" - * import { Effect, Console } from "effect" + * import { Console, Effect } from "effect" + * import { Command, Flag } from "effect/unstable/cli" * * const greet = Command.make("greet", { * name: Flag.string("name"), @@ -855,8 +854,7 @@ export const run: { * for (let i = 0; i < config.count; i++) { * yield* Console.log(`Hello, ${config.name}!`) * } - * }) - * ) + * })) * * // Test with specific arguments * const testProgram = Effect.gen(function*() { diff --git a/packages/effect/src/unstable/cli/Flag.ts b/packages/effect/src/unstable/cli/Flag.ts index 89f604caa3..31ca209358 100644 --- a/packages/effect/src/unstable/cli/Flag.ts +++ b/packages/effect/src/unstable/cli/Flag.ts @@ -2,10 +2,10 @@ * @since 4.0.0 */ import type * as Effect from "../../Effect.ts" +import type * as FileSystem from "../../FileSystem.ts" import { dual, type LazyArg } from "../../Function.ts" import type * as Option from "../../Option.ts" -import type * as FileSystem from "../../platform/FileSystem.ts" -import type * as Path from "../../platform/Path.ts" +import type * as Path from "../../Path.ts" import type * as Redacted from "../../Redacted.ts" import type * as Result from "../../Result.ts" import type * as Schema from "../../schema/Schema.ts" @@ -230,8 +230,7 @@ export const directory = (name: string, options?: { * * @example * ```ts - * import { Effect } from "effect" - * import { Redacted } from "effect" + * import { Effect, Redacted } from "effect" * import { Flag } from "effect/unstable/cli" * * const passwordFlag = Flag.redacted("password") @@ -299,8 +298,8 @@ export const fileParse = ( * * @example * ```ts - * import { Flag } from "effect/unstable/cli" * import { Schema } from "effect/schema" + * import { Flag } from "effect/unstable/cli" * * const ConfigSchema = Schema.Struct({ * port: Schema.Number, @@ -450,8 +449,7 @@ export const withMetavar: { * * @example * ```ts - * import { Effect } from "effect" - * import { Option } from "effect" + * import { Effect, Option } from "effect" * import { Flag } from "effect/unstable/cli" * * const optionalPort = Flag.optional(Flag.integer("port")) @@ -509,12 +507,12 @@ export const withDefault: { * * // Convert string to uppercase * const nameFlag = Flag.string("name").pipe( - * Flag.map(name => name.toUpperCase()) + * Flag.map((name) => name.toUpperCase()) * ) * * // Convert port to URL * const urlFlag = Flag.integer("port").pipe( - * Flag.map(port => `http://localhost:${port}`) + * Flag.map((port) => `http://localhost:${port}`) * ) * ``` * @@ -531,8 +529,7 @@ export const map: { * * @example * ```ts - * import { Effect } from "effect" - * import { FileSystem } from "effect/platform" + * import { Effect, FileSystem } from "effect" * import { Flag } from "effect/unstable/cli" * * // Read file size from path flag @@ -571,16 +568,16 @@ export const mapEffect: { * // Parse JSON string with error handling * const jsonFlag = Flag.string("config").pipe( * Flag.mapTryCatch( - * json => JSON.parse(json), - * error => `Invalid JSON: ${error}` + * (json) => JSON.parse(json), + * (error) => `Invalid JSON: ${error}` * ) * ) * * // Parse URL with error handling * const urlFlag = Flag.string("url").pipe( * Flag.mapTryCatch( - * url => new URL(url), - * error => `Invalid URL: ${error}` + * (url) => new URL(url), + * (error) => `Invalid URL: ${error}` * ) * ) * ``` @@ -719,15 +716,15 @@ export const filterMap: { * // Ensure port is in valid range * const portFlag = Flag.integer("port").pipe( * Flag.filter( - * port => port >= 1 && port <= 65535, - * port => `Port ${port} is out of range (1-65535)` + * (port) => port >= 1 && port <= 65535, + * (port) => `Port ${port} is out of range (1-65535)` * ) * ) * * // Ensure non-empty string * const nameFlag = Flag.string("name").pipe( * Flag.filter( - * name => name.trim().length > 0, + * (name) => name.trim().length > 0, * () => "Name cannot be empty" * ) * ) @@ -778,8 +775,7 @@ export const orElse: { * * @example * ```ts - * import { Effect } from "effect" - * import { Result } from "effect" + * import { Effect, Result } from "effect" * import { Flag } from "effect/unstable/cli" * * // Try file path, fallback to URL diff --git a/packages/effect/src/unstable/cli/HelpDoc.ts b/packages/effect/src/unstable/cli/HelpDoc.ts index ffe8c6e49b..e7e0209957 100644 --- a/packages/effect/src/unstable/cli/HelpDoc.ts +++ b/packages/effect/src/unstable/cli/HelpDoc.ts @@ -9,7 +9,7 @@ * * @example * ```ts - * import * as HelpDoc from "effect/unstable/cli/HelpDoc" + * import type * as HelpDoc from "effect/unstable/cli/HelpDoc" * * const deployCommandHelp: HelpDoc.HelpDoc = { * description: "Deploy your application to the cloud", @@ -78,7 +78,7 @@ export interface HelpDoc { * * @example * ```ts - * import { HelpDoc } from "effect/unstable/cli" + * import type { HelpDoc } from "effect/unstable/cli" * * const verboseFlag: HelpDoc.FlagDoc = { * name: "verbose", @@ -132,7 +132,7 @@ export interface FlagDoc { * * @example * ```ts - * import { HelpDoc } from "effect/unstable/cli" + * import type { HelpDoc } from "effect/unstable/cli" * * const deploySubcommand: HelpDoc.SubcommandDoc = { * name: "deploy", @@ -173,7 +173,7 @@ export interface SubcommandDoc { * * @example * ```ts - * import { HelpDoc } from "effect/unstable/cli" + * import type { HelpDoc } from "effect/unstable/cli" * * const sourceArg: HelpDoc.ArgDoc = { * name: "source", diff --git a/packages/effect/src/unstable/cli/Param.ts b/packages/effect/src/unstable/cli/Param.ts index 967a717ef2..d0757e81c2 100644 --- a/packages/effect/src/unstable/cli/Param.ts +++ b/packages/effect/src/unstable/cli/Param.ts @@ -11,12 +11,12 @@ * @since 4.0.0 */ import * as Effect from "../../Effect.ts" +import type * as FileSystem from "../../FileSystem.ts" import type { LazyArg } from "../../Function.ts" import { dual, identity } from "../../Function.ts" import * as Option from "../../Option.ts" +import type * as Path from "../../Path.ts" import { type Pipeable, pipeArguments } from "../../Pipeable.ts" -import type * as FileSystem from "../../platform/FileSystem.ts" -import type * as Path from "../../platform/Path.ts" import * as Predicate from "../../Predicate.ts" import type * as Redacted from "../../Redacted.ts" import * as Result from "../../Result.ts" @@ -230,7 +230,7 @@ export const isParam = (u: unknown): u is Param => Predicate.has * const nameParam = Param.string(Param.flagKind, "name") * const optionalParam = Param.optional(nameParam) * - * console.log(Param.isSingle(nameParam)) // true + * console.log(Param.isSingle(nameParam)) // true * console.log(Param.isSingle(optionalParam)) // false * ``` * @@ -693,7 +693,9 @@ export const fileText = (kind: Kind, name: string): Para * const config = Param.fileParse(Param.flagKind, "config") * * // Will use the JSON parser - * const jsonConfig = Param.fileParse(Param.flagKind, "json-config", { format: "json" }) + * const jsonConfig = Param.fileParse(Param.flagKind, "json-config", { + * format: "json" + * }) * ``` * * @since 4.0.0 @@ -846,7 +848,7 @@ const FLAG_DASH_REGEXP = /^-+/ * // Also works on composed params: * const count = Param.integer(Param.flagKind, "count").pipe( * Param.optional, - * Param.withAlias("-c") // finds the underlying Single and adds alias + * Param.withAlias("-c") // finds the underlying Single and adds alias * ) * ``` * @@ -906,7 +908,7 @@ export const withDescription: { * // @internal - this module is not exported publicly * * const port = Param.integer(Param.flagKind, "port").pipe( - * Param.map(n => ({ port: n, url: `http://localhost:${n}` })) + * Param.map((n) => ({ port: n, url: `http://localhost:${n}` })) * ) * ``` * @@ -939,18 +941,20 @@ export const map: { * import * as Param from "effect/unstable/cli/Param" * * // @internal - this module is not exported publicly - * import { CliError } from "effect/unstable/cli" * import { Effect } from "effect" + * import { CliError } from "effect/unstable/cli" * * const validatedEmail = Param.string(Param.flagKind, "email").pipe( - * Param.mapEffect(email => + * Param.mapEffect((email) => * email.includes("@") * ? Effect.succeed(email) - * : Effect.fail(new CliError.InvalidValue({ - * option: "email", - * value: email, - * expected: "valid email format" - * })) + * : Effect.fail( + * new CliError.InvalidValue({ + * option: "email", + * value: email, + * expected: "valid email format" + * }) + * ) * ) * ) * ``` @@ -996,8 +1000,9 @@ export const mapEffect: { * * const parsedJson = Param.string(Param.flagKind, "config").pipe( * Param.mapTryCatch( - * str => JSON.parse(str), - * error => `Invalid JSON: ${error instanceof Error ? error.message : String(error)}` + * (str) => JSON.parse(str), + * (error) => + * `Invalid JSON: ${error instanceof Error ? error.message : String(error)}` * ) * ) * ``` @@ -1164,13 +1169,13 @@ export type VariadicParamOptions = { * // Variadic with minimum count * const inputs = Param.variadic( * Param.string(Param.flagKind, "input"), - * { min: 1 } // at least 1 required + * { min: 1 } // at least 1 required * ) * * // 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 5 times * }) * ``` * @@ -1380,8 +1385,8 @@ export const filterMap: { * * const evenNumber = Param.integer(Param.flagKind, "num").pipe( * Param.filter( - * n => n % 2 === 0, - * n => `Expected even number, got ${n}` + * (n) => n % 2 === 0, + * (n) => `Expected even number, got ${n}` * ) * ) * ``` @@ -1419,7 +1424,10 @@ export const filter: { * * const port = Param.integer(Param.flagKind, "port").pipe( * Param.withMetavar("PORT"), - * Param.filter(p => p >= 1 && p <= 65535, () => "Port must be between 1 and 65535") + * Param.filter( + * (p) => p >= 1 && p <= 65535, + * () => "Port must be between 1 and 65535" + * ) * ) * ``` * diff --git a/packages/effect/src/unstable/cli/Primitive.ts b/packages/effect/src/unstable/cli/Primitive.ts index 2ff6861ed4..9658a282ff 100644 --- a/packages/effect/src/unstable/cli/Primitive.ts +++ b/packages/effect/src/unstable/cli/Primitive.ts @@ -16,10 +16,10 @@ import * as Toml from "toml" import * as Yaml from "yaml" import * as Config from "../../Config.ts" import * as Effect from "../../Effect.ts" +import * as FileSystem from "../../FileSystem.ts" import { format } from "../../Formatter.ts" import { identity } from "../../Function.ts" -import * as FileSystem from "../../platform/FileSystem.ts" -import * as Path from "../../platform/Path.ts" +import * as Path from "../../Path.ts" import * as Redacted from "../../Redacted.ts" import type { Formatter } from "../../schema/Issue.ts" import * as Schema from "../../schema/Schema.ts" @@ -33,11 +33,11 @@ const TypeId = "~effect/cli/Primitive" * * @example * ```ts - * import { Primitive } from "effect/unstable/cli" * import { Effect } from "effect" + * import { Primitive } from "effect/unstable/cli" * * // Using built-in primitives - * const parseString = Effect.gen(function* () { + * const parseString = Effect.gen(function*() { * const stringResult = yield* Primitive.string.parse("hello") * const numberResult = yield* Primitive.integer.parse("42") * const boolResult = yield* Primitive.boolean.parse("true") @@ -46,7 +46,7 @@ const TypeId = "~effect/cli/Primitive" * }) * * // All primitives provide parsing functionality - * const parseDate = Effect.gen(function* () { + * const parseDate = Effect.gen(function*() { * const dateResult = yield* Primitive.date.parse("2023-12-25") * const pathResult = yield* Primitive.path("file", true).parse("./package.json") * return { dateResult, pathResult } @@ -120,10 +120,10 @@ const makeSchemaPrimitive = ( * * @example * ```ts - * import { Primitive } from "effect/unstable/cli" * import { Effect } from "effect" + * import { Primitive } from "effect/unstable/cli" * - * const parseBoolean = Effect.gen(function* () { + * const parseBoolean = Effect.gen(function*() { * const result1 = yield* Primitive.boolean.parse("true") * console.log(result1) // true * @@ -151,10 +151,10 @@ export const boolean: Primitive = makeSchemaPrimitive( * * @example * ```ts - * import { Primitive } from "effect/unstable/cli" * import { Effect } from "effect" + * import { Primitive } from "effect/unstable/cli" * - * const parseFloat = Effect.gen(function* () { + * const parseFloat = Effect.gen(function*() { * const result1 = yield* Primitive.float.parse("3.14") * console.log(result1) // 3.14 * @@ -179,10 +179,10 @@ export const float: Primitive = makeSchemaPrimitive( * * @example * ```ts - * import { Primitive } from "effect/unstable/cli" * import { Effect } from "effect" + * import { Primitive } from "effect/unstable/cli" * - * const parseInteger = Effect.gen(function* () { + * const parseInteger = Effect.gen(function*() { * const result1 = yield* Primitive.integer.parse("42") * console.log(result1) // 42 * @@ -207,10 +207,10 @@ export const integer: Primitive = makeSchemaPrimitive( * * @example * ```ts - * import { Primitive } from "effect/unstable/cli" * import { Effect } from "effect" + * import { Primitive } from "effect/unstable/cli" * - * const parseDate = Effect.gen(function* () { + * const parseDate = Effect.gen(function*() { * const result1 = yield* Primitive.date.parse("2023-12-25") * console.log(result1) // Date object for December 25, 2023 * @@ -235,10 +235,10 @@ export const date: Primitive = makeSchemaPrimitive( * * @example * ```ts - * import { Primitive } from "effect/unstable/cli" * import { Effect } from "effect" + * import { Primitive } from "effect/unstable/cli" * - * const parseString = Effect.gen(function* () { + * const parseString = Effect.gen(function*() { * const result1 = yield* Primitive.string.parse("hello world") * console.log(result1) // "hello world" * @@ -260,8 +260,8 @@ export const string: Primitive = makePrimitive("String", (value) => Effe * * @example * ```ts - * import { Primitive } from "effect/unstable/cli" * import { Effect } from "effect" + * import { Primitive } from "effect/unstable/cli" * * type LogLevel = "debug" | "info" | "warn" | "error" * @@ -272,7 +272,7 @@ export const string: Primitive = makePrimitive("String", (value) => Effe * ["error", "error"] * ]) * - * const parseLogLevel = Effect.gen(function* () { + * const parseLogLevel = Effect.gen(function*() { * const result1 = yield* logLevelPrimitive.parse("info") * console.log(result1) // "info" * @@ -303,7 +303,6 @@ export const choice = ( * @example * ```ts * import { Primitive } from "effect/unstable/cli" - * import { Effect } from "effect" * * // Only accept files * const filePath = Primitive.path("file", true) @@ -325,10 +324,10 @@ export type PathType = "file" | "directory" | "either" * * @example * ```ts - * import { Primitive } from "effect/unstable/cli" * import { Effect } from "effect" + * import { Primitive } from "effect/unstable/cli" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * // Parse a file path that must exist * const filePrimitive = Primitive.path("file", true) * const filePath = yield* filePrimitive.parse("./package.json") @@ -397,8 +396,7 @@ export const path = ( * * @example * ```ts - * import { Effect } from "effect" - * import { Redacted } from "effect" + * import { Effect, Redacted } from "effect" * import { Primitive } from "effect/unstable/cli" * * const parseRedacted = Effect.gen(function*() { @@ -421,10 +419,10 @@ export const redacted: Primitive> = makePrimitive( * * @example * ```ts - * import { Primitive } from "effect/unstable/cli" * import { Effect } from "effect" + * import { Primitive } from "effect/unstable/cli" * - * const readConfigFile = Effect.gen(function* () { + * const readConfigFile = Effect.gen(function*() { * const content = yield* Primitive.fileText.parse("./config.json") * console.log(content) // File contents as string * @@ -501,12 +499,12 @@ const fileParsers: Record unknown> = { * * @example * ```ts - * import { Primitive } from "effect/unstable/cli" * import { Effect } from "effect" + * import { Primitive } from "effect/unstable/cli" * * const tomlFilePrimitive = Primitive.fileParse({ format: "toml" }) * - * const loadConfig = Effect.gen(function* () { + * const loadConfig = Effect.gen(function*() { * const config = yield* tomlFilePrimitive.parse("./config.toml") * console.log(config) // { name: "my-app", version: "1.0.0", port: 3000 } * return config @@ -552,9 +550,9 @@ export type FileSchemaOptions = Struct.Simplify< * * @example * ```ts - * import { Primitive } from "effect/unstable/cli" * import { Effect } from "effect" * import { Schema } from "effect/schema" + * import { Primitive } from "effect/unstable/cli" * * const ConfigSchema = Schema.Struct({ * name: Schema.String, @@ -598,10 +596,10 @@ export const fileSchema = ( * * @example * ```ts - * import { Primitive } from "effect/unstable/cli" * import { Effect } from "effect" + * import { Primitive } from "effect/unstable/cli" * - * const parseKeyValue = Effect.gen(function* () { + * const parseKeyValue = Effect.gen(function*() { * const result1 = yield* Primitive.keyValuePair.parse("name=john") * console.log(result1) // { name: "john" } * @@ -642,10 +640,10 @@ export const keyValuePair: Primitive> = makePrimitive( * * @example * ```ts - * import { Primitive } from "effect/unstable/cli" * import { Effect } from "effect" + * import { Primitive } from "effect/unstable/cli" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * // This will always fail - useful for boolean flags * const result = yield* Primitive.none.parse("any-value") * }) diff --git a/packages/effect/src/unstable/cli/Prompt.ts b/packages/effect/src/unstable/cli/Prompt.ts index 9da8def2c0..7df10fa2fc 100644 --- a/packages/effect/src/unstable/cli/Prompt.ts +++ b/packages/effect/src/unstable/cli/Prompt.ts @@ -5,18 +5,18 @@ import * as Arr from "../../Array.ts" import type { NoSuchElementError } from "../../Cause.ts" import * as Data from "../../Data.ts" import * as Effect from "../../Effect.ts" +import * as FileSystem from "../../FileSystem.ts" import * as Filter from "../../Filter.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 FileSystem from "../../platform/FileSystem.ts" -import * as Path from "../../platform/Path.ts" -import * as Terminal from "../../platform/Terminal.ts" import * as Predicate from "../../Predicate.ts" import * as Queue from "../../Queue.ts" import * as Redacted from "../../Redacted.ts" +import * as Terminal from "../../Terminal.ts" import type { Covariant } from "../../types/Types.ts" import * as Ansi from "./internal/ansi.ts" import type * as Primitive from "./Primitive.ts" @@ -545,8 +545,8 @@ export declare namespace All { * **Example** * * ```ts - * import { Prompt } from "effect/unstable/cli" * import { Effect } from "effect" + * import { Prompt } from "effect/unstable/cli" * * const username = Prompt.text({ * message: "Enter your username: " diff --git a/packages/effect/src/unstable/cli/internal/parser.ts b/packages/effect/src/unstable/cli/internal/parser.ts index 1fa4bf3ca9..1562404a39 100644 --- a/packages/effect/src/unstable/cli/internal/parser.ts +++ b/packages/effect/src/unstable/cli/internal/parser.ts @@ -25,10 +25,10 @@ * - Errors accumulate rather than throwing exceptions */ import * as Effect from "../../../Effect.ts" +import type { FileSystem } from "../../../FileSystem.ts" import type { LogLevel } from "../../../LogLevel.ts" import * as Option from "../../../Option.ts" -import type { FileSystem } from "../../../platform/FileSystem.ts" -import type { Path } from "../../../platform/Path.ts" +import type { Path } from "../../../Path.ts" import * as CliError from "../CliError.ts" import type { Command, ParsedTokens } from "../Command.ts" import * as Param from "../Param.ts" diff --git a/packages/effect/src/unstable/cluster/EntityProxy.ts b/packages/effect/src/unstable/cluster/EntityProxy.ts index 96b98cff52..955131e120 100644 --- a/packages/effect/src/unstable/cluster/EntityProxy.ts +++ b/packages/effect/src/unstable/cluster/EntityProxy.ts @@ -20,10 +20,15 @@ const clientErrors = [ * Derives an `RpcGroup` from an `Entity`. * * ```ts - * import { ClusterSchema, Entity, EntityProxy, EntityProxyServer } from "effect/unstable/cluster" - * import { Rpc, RpcServer } from "effect/unstable/rpc" - * import { Schema } from "effect/schema" * import { Layer } from "effect" + * import { Schema } from "effect/schema" + * import { + * ClusterSchema, + * Entity, + * EntityProxy, + * EntityProxyServer + * } from "effect/unstable/cluster" + * import { Rpc, RpcServer } from "effect/unstable/rpc" * * export const Counter = Entity.make("Counter", [ * Rpc.make("Increment", { @@ -128,11 +133,16 @@ const entityIdPath = Schema.Struct({ * Derives an `HttpApiGroup` from an `Entity`. * * ```ts - * import { ClusterSchema, Entity, EntityProxy, EntityProxyServer } from "effect/unstable/cluster" + * import { Layer } from "effect" + * import { Schema } from "effect/schema" + * import { + * ClusterSchema, + * Entity, + * EntityProxy, + * EntityProxyServer + * } from "effect/unstable/cluster" * import { HttpApi, HttpApiBuilder } from "effect/unstable/httpapi" * import { Rpc } from "effect/unstable/rpc" - * import { Schema } from "effect/schema" - * import { Layer } from "effect" * * export const Counter = Entity.make("Counter", [ * Rpc.make("Increment", { diff --git a/packages/effect/src/unstable/cluster/K8sHttpClient.ts b/packages/effect/src/unstable/cluster/K8sHttpClient.ts index 34777d69f4..8ab48cdd64 100644 --- a/packages/effect/src/unstable/cluster/K8sHttpClient.ts +++ b/packages/effect/src/unstable/cluster/K8sHttpClient.ts @@ -3,11 +3,11 @@ */ import type * as v1 from "kubernetes-types/core/v1.d.ts" import * as Effect from "../../Effect.ts" +import * as FileSystem from "../../FileSystem.ts" import * as Filter from "../../Filter.ts" import { identity } from "../../Function.ts" import * as Layer from "../../Layer.ts" import * as Option from "../../Option.ts" -import * as FileSystem from "../../platform/FileSystem.ts" import * as Schedule from "../../Schedule.ts" import * as Schema from "../../schema/Schema.ts" import * as ServiceMap from "../../ServiceMap.ts" diff --git a/packages/effect/src/unstable/http/Etag.ts b/packages/effect/src/unstable/http/Etag.ts index edcd2bf4bd..3f26c88817 100644 --- a/packages/effect/src/unstable/http/Etag.ts +++ b/packages/effect/src/unstable/http/Etag.ts @@ -2,8 +2,8 @@ * @since 4.0.0 */ import * as Effect from "../../Effect.ts" +import type * as FileSystem from "../../FileSystem.ts" import * as Layer from "../../Layer.ts" -import type * as FileSystem from "../../platform/FileSystem.ts" import * as ServiceMap from "../../ServiceMap.ts" import type * as Body from "./HttpBody.ts" diff --git a/packages/effect/src/unstable/http/HttpBody.ts b/packages/effect/src/unstable/http/HttpBody.ts index d886d66514..fd0cfb4c02 100644 --- a/packages/effect/src/unstable/http/HttpBody.ts +++ b/packages/effect/src/unstable/http/HttpBody.ts @@ -3,10 +3,10 @@ */ import * as Data from "../../Data.ts" import * as Effect from "../../Effect.ts" +import * as FileSystem from "../../FileSystem.ts" import { format } from "../../Formatter.ts" import * as Inspectable from "../../Inspectable.ts" -import * as FileSystem from "../../platform/FileSystem.ts" -import type * as PlatformError from "../../platform/PlatformError.ts" +import type * as PlatformError from "../../PlatformError.ts" import * as Predicate from "../../Predicate.ts" import type { ParseOptions } from "../../schema/AST.ts" import type { Issue } from "../../schema/Issue.ts" diff --git a/packages/effect/src/unstable/http/HttpClientRequest.ts b/packages/effect/src/unstable/http/HttpClientRequest.ts index a302973e6f..b13786907f 100644 --- a/packages/effect/src/unstable/http/HttpClientRequest.ts +++ b/packages/effect/src/unstable/http/HttpClientRequest.ts @@ -2,11 +2,11 @@ * @since 4.0.0 */ import * as Effect from "../../Effect.ts" +import type * as FileSystem from "../../FileSystem.ts" import { dual } from "../../Function.ts" import * as Inspectable from "../../Inspectable.ts" import { type Pipeable, pipeArguments } from "../../Pipeable.ts" -import type * as FileSystem from "../../platform/FileSystem.ts" -import type * as PlatformError from "../../platform/PlatformError.ts" +import type * as PlatformError from "../../PlatformError.ts" import { hasProperty } from "../../Predicate.ts" import { redact } from "../../Redactable.ts" import * as Redacted from "../../Redacted.ts" diff --git a/packages/effect/src/unstable/http/HttpIncomingMessage.ts b/packages/effect/src/unstable/http/HttpIncomingMessage.ts index 506a9812a1..108c2d2e3e 100644 --- a/packages/effect/src/unstable/http/HttpIncomingMessage.ts +++ b/packages/effect/src/unstable/http/HttpIncomingMessage.ts @@ -2,8 +2,8 @@ * @since 4.0.0 */ import * as Effect from "../../Effect.ts" +import type * as FileSystem from "../../FileSystem.ts" import type * as Inspectable from "../../Inspectable.ts" -import type * as FileSystem from "../../platform/FileSystem.ts" import { hasProperty } from "../../Predicate.ts" import { redact } from "../../Redactable.ts" import type { ParseOptions } from "../../schema/AST.ts" diff --git a/packages/effect/src/unstable/http/HttpPlatform.ts b/packages/effect/src/unstable/http/HttpPlatform.ts index f826172de0..7ae2a38343 100644 --- a/packages/effect/src/unstable/http/HttpPlatform.ts +++ b/packages/effect/src/unstable/http/HttpPlatform.ts @@ -2,10 +2,10 @@ * @since 4.0.0 */ import * as Effect from "../../Effect.ts" +import * as FileSystem from "../../FileSystem.ts" import { identity } from "../../Function.ts" import * as Layer from "../../Layer.ts" -import * as FileSystem from "../../platform/FileSystem.ts" -import type { PlatformError } from "../../platform/PlatformError.ts" +import type { PlatformError } from "../../PlatformError.ts" import * as ServiceMap from "../../ServiceMap.ts" import * as Stream from "../../Stream.ts" import * as Etag from "./Etag.ts" diff --git a/packages/effect/src/unstable/http/HttpRouter.ts b/packages/effect/src/unstable/http/HttpRouter.ts index a1ca8dfff0..40bda643cb 100644 --- a/packages/effect/src/unstable/http/HttpRouter.ts +++ b/packages/effect/src/unstable/http/HttpRouter.ts @@ -365,9 +365,9 @@ export const schemaPathParams = ( * import * as HttpRouter from "effect/unstable/http/HttpRouter" * import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse" * - * const Route = HttpRouter.add("GET", "/hello", Effect.succeed(HttpServerResponse.text("Hello, World!"))) + * const Route = HttpRouter.add( + * "GET", + * "/hello", + * Effect.succeed(HttpServerResponse.text("Hello, World!")) + * ) * ``` * * @since 4.0.0 @@ -420,7 +424,11 @@ export const add = ( * import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse" * * const Routes = HttpRouter.addAll([ - * HttpRouter.route("GET", "/hello", Effect.succeed(HttpServerResponse.text("Hello, World!"))) + * HttpRouter.route( + * "GET", + * "/hello", + * Effect.succeed(HttpServerResponse.text("Hello, World!")) + * ) * ]) * ``` * @@ -713,12 +721,12 @@ export interface Middleware< * the `global` option as `true`. * * ```ts - * import * as HttpRouter from "effect/unstable/http/HttpRouter" - * import * as HttpMiddleware from "effect/unstable/http/HttpMiddleware" - * import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse" - * import * as ServiceMap from "effect/ServiceMap" * import { Effect } from "effect" * import * as Layer from "effect/Layer" + * import * as ServiceMap from "effect/ServiceMap" + * import * as HttpMiddleware from "effect/unstable/http/HttpMiddleware" + * import * as HttpRouter from "effect/unstable/http/HttpRouter" + * import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse" * * // Here we are defining a CORS middleware * const CorsMiddleware = HttpRouter.middleware(HttpMiddleware.cors()).layer @@ -750,7 +758,9 @@ export interface Middleware< * Effect.gen(function*() { * // Requests can now access the current session * const session = yield* CurrentSession - * return HttpServerResponse.text(`Hello, World! Your token is ${session.token}`) + * return HttpServerResponse.text( + * `Hello, World! Your token is ${session.token}` + * ) * }) * ) * }).pipe( @@ -1002,11 +1012,15 @@ export const cors = ( * * ```ts * import { Effect } from "effect" + * import * as Layer from "effect/Layer" * import * as HttpRouter from "effect/unstable/http/HttpRouter" * import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse" - * import * as Layer from "effect/Layer" * - * const Route = HttpRouter.add("GET", "/hello", Effect.succeed(HttpServerResponse.text("Hello, World!"))).pipe( + * const Route = HttpRouter.add( + * "GET", + * "/hello", + * Effect.succeed(HttpServerResponse.text("Hello, World!")) + * ).pipe( * // disable the logger for this route * Layer.provide(HttpRouter.disableLogger) * ) diff --git a/packages/effect/src/unstable/http/HttpServer.ts b/packages/effect/src/unstable/http/HttpServer.ts index cfef7bdfe6..d465900303 100644 --- a/packages/effect/src/unstable/http/HttpServer.ts +++ b/packages/effect/src/unstable/http/HttpServer.ts @@ -2,10 +2,10 @@ * @since 4.0.0 */ import * as Effect from "../../Effect.ts" +import * as FileSystem from "../../FileSystem.ts" import { dual } from "../../Function.ts" import * as Layer from "../../Layer.ts" -import * as FileSystem from "../../platform/FileSystem.ts" -import * as Path from "../../platform/Path.ts" +import * as Path from "../../Path.ts" import type * as Scope from "../../Scope.ts" import * as ServiceMap from "../../ServiceMap.ts" import * as Etag from "./Etag.ts" diff --git a/packages/effect/src/unstable/http/HttpServerRequest.ts b/packages/effect/src/unstable/http/HttpServerRequest.ts index 40ef79f2e3..daab26e494 100644 --- a/packages/effect/src/unstable/http/HttpServerRequest.ts +++ b/packages/effect/src/unstable/http/HttpServerRequest.ts @@ -4,9 +4,9 @@ import type * as Arr from "../../Array.ts" import * as Channel from "../../Channel.ts" import * as Effect from "../../Effect.ts" +import type * as FileSystem from "../../FileSystem.ts" import * as Inspectable from "../../Inspectable.ts" -import type * as FileSystem from "../../platform/FileSystem.ts" -import type * as Path from "../../platform/Path.ts" +import type * as Path from "../../Path.ts" import type { ReadonlyRecord } from "../../Record.ts" import * as Result from "../../Result.ts" import type { ParseOptions } from "../../schema/AST.ts" diff --git a/packages/effect/src/unstable/http/HttpServerResponse.ts b/packages/effect/src/unstable/http/HttpServerResponse.ts index 9e246c8798..e0a9873a3f 100644 --- a/packages/effect/src/unstable/http/HttpServerResponse.ts +++ b/packages/effect/src/unstable/http/HttpServerResponse.ts @@ -2,12 +2,12 @@ * @since 4.0.0 */ import * as Effect from "../../Effect.ts" +import type * as FileSystem from "../../FileSystem.ts" import { dual } from "../../Function.ts" import type * as Inspectable from "../../Inspectable.ts" import { PipeInspectableProto } from "../../internal/core.ts" import type { Pipeable } from "../../Pipeable.ts" -import type * as FileSystem from "../../platform/FileSystem.ts" -import type { PlatformError } from "../../platform/PlatformError.ts" +import type { PlatformError } from "../../PlatformError.ts" import { hasProperty } from "../../Predicate.ts" import { redact } from "../../Redactable.ts" import type { ParseOptions } from "../../schema/AST.ts" diff --git a/packages/effect/src/unstable/http/Multipart.ts b/packages/effect/src/unstable/http/Multipart.ts index 6201392ade..9dcefca42b 100644 --- a/packages/effect/src/unstable/http/Multipart.ts +++ b/packages/effect/src/unstable/http/Multipart.ts @@ -5,11 +5,11 @@ import * as Arr from "../../Array.ts" import * as Channel from "../../Channel.ts" import * as Effect from "../../Effect.ts" import * as Exit from "../../Exit.ts" +import * as FileSystem from "../../FileSystem.ts" import { constant, dual } from "../../Function.ts" import * as Inspectable from "../../Inspectable.ts" import * as Option from "../../Option.ts" -import * as FileSystem from "../../platform/FileSystem.ts" -import * as Path from "../../platform/Path.ts" +import * as Path from "../../Path.ts" import * as Predicate from "../../Predicate.ts" import * as Pull from "../../Pull.ts" import type { ParseOptions } from "../../schema/AST.ts" diff --git a/packages/effect/src/unstable/http/UrlParams.ts b/packages/effect/src/unstable/http/UrlParams.ts index 075874edb7..dd405195d9 100644 --- a/packages/effect/src/unstable/http/UrlParams.ts +++ b/packages/effect/src/unstable/http/UrlParams.ts @@ -361,10 +361,15 @@ const baseUrl = (): string | undefined => { * **Example** * * ```ts - * import * as assert from "node:assert" * import { UrlParams } from "effect/unstable/http" + * import * as assert from "node:assert" * - * const urlParams = UrlParams.fromInput({ a: 1, b: true, c: "string", e: [1, 2, 3] }) + * const urlParams = UrlParams.fromInput({ + * a: 1, + * b: true, + * c: "string", + * e: [1, 2, 3] + * }) * const result = UrlParams.toRecord(urlParams) * * assert.deepStrictEqual( diff --git a/packages/effect/src/unstable/httpapi/HttpApiBuilder.ts b/packages/effect/src/unstable/httpapi/HttpApiBuilder.ts index 40dcf6d903..5452d34b6b 100644 --- a/packages/effect/src/unstable/httpapi/HttpApiBuilder.ts +++ b/packages/effect/src/unstable/httpapi/HttpApiBuilder.ts @@ -5,13 +5,13 @@ import * as Cause from "../../Cause.ts" import * as Effect from "../../Effect.ts" import * as Base64 from "../../encoding/Base64.ts" import * as Fiber from "../../Fiber.ts" +import type { FileSystem } from "../../FileSystem.ts" import * as Filter from "../../Filter.ts" import { identity } from "../../Function.ts" import * as Layer from "../../Layer.ts" import * as Option from "../../Option.ts" +import type { Path } from "../../Path.ts" import { type Pipeable, pipeArguments } from "../../Pipeable.ts" -import type { FileSystem } from "../../platform/FileSystem.ts" -import type { Path } from "../../platform/Path.ts" import type { ReadonlyRecord } from "../../Record.ts" import * as Redacted from "../../Redacted.ts" import * as Result from "../../Result.ts" diff --git a/packages/effect/src/unstable/httpapi/HttpApiSchema.ts b/packages/effect/src/unstable/httpapi/HttpApiSchema.ts index f047dc248c..b8e600e12a 100644 --- a/packages/effect/src/unstable/httpapi/HttpApiSchema.ts +++ b/packages/effect/src/unstable/httpapi/HttpApiSchema.ts @@ -2,9 +2,9 @@ * @since 4.0.0 */ import type { YieldableError } from "../../Cause.ts" +import type * as FileSystem from "../../FileSystem.ts" import { constant, constVoid, dual, type LazyArg } from "../../Function.ts" import * as Iterable from "../../Iterable.ts" -import type * as FileSystem from "../../platform/FileSystem.ts" import * as Annotations from "../../schema/Annotations.ts" import * as AST from "../../schema/AST.ts" import * as Schema from "../../schema/Schema.ts" diff --git a/packages/effect/src/unstable/observability/OtlpMetrics.ts b/packages/effect/src/unstable/observability/OtlpMetrics.ts index ffe0d0a79d..5c67bb3e48 100644 --- a/packages/effect/src/unstable/observability/OtlpMetrics.ts +++ b/packages/effect/src/unstable/observability/OtlpMetrics.ts @@ -26,9 +26,7 @@ import * as OtlpResource from "./OtlpResource.ts" * * @example * ```ts - * import { Effect, Layer, Metric } from "effect" * import * as OtlpMetrics from "effect/unstable/observability/OtlpMetrics" - * import * as HttpClient from "effect/unstable/http/HttpClient" * * // Use delta temporality for backends that prefer it (e.g., Datadog, Dynatrace) * const metricsLayer = OtlpMetrics.layer({ diff --git a/packages/effect/src/unstable/observability/PrometheusMetrics.ts b/packages/effect/src/unstable/observability/PrometheusMetrics.ts index 2a96feb7ed..81d9471179 100644 --- a/packages/effect/src/unstable/observability/PrometheusMetrics.ts +++ b/packages/effect/src/unstable/observability/PrometheusMetrics.ts @@ -39,7 +39,7 @@ import * as HttpServerResponse from "../http/HttpServerResponse.ts" * * @example * ```ts - * import * as PrometheusMetrics from "effect/unstable/observability/PrometheusMetrics" + * import type * as PrometheusMetrics from "effect/unstable/observability/PrometheusMetrics" * * // Convert camelCase to snake_case * const mapper: PrometheusMetrics.MetricNameMapper = (name) => @@ -168,9 +168,6 @@ export const formatUnsafe = ( * * @example * ```ts - * import { Effect, Layer } from "effect" - * import * as HttpRouter from "effect/unstable/http/HttpRouter" - * import * as HttpServer from "effect/unstable/http/HttpServer" * import * as PrometheusMetrics from "effect/unstable/observability/PrometheusMetrics" * * // Create a layer that adds /metrics endpoint to the router diff --git a/packages/effect/src/unstable/persistence/KeyValueStore.ts b/packages/effect/src/unstable/persistence/KeyValueStore.ts index 04327011b7..6bd13cdaef 100644 --- a/packages/effect/src/unstable/persistence/KeyValueStore.ts +++ b/packages/effect/src/unstable/persistence/KeyValueStore.ts @@ -4,12 +4,12 @@ import * as Data from "../../Data.ts" import * as Effect from "../../Effect.ts" import * as Base64 from "../../encoding/Base64.ts" +import * as FileSystem from "../../FileSystem.ts" import { dual, identity, type LazyArg } from "../../Function.ts" import * as Layer from "../../Layer.ts" import * as Option from "../../Option.ts" -import * as FileSystem from "../../platform/FileSystem.ts" -import * as Path from "../../platform/Path.ts" -import type { PlatformError } from "../../platform/PlatformError.ts" +import * as Path from "../../Path.ts" +import type { PlatformError } from "../../PlatformError.ts" import * as Predicate from "../../Predicate.ts" import * as Result from "../../Result.ts" import * as Schema from "../../schema/Schema.ts" diff --git a/packages/effect/src/unstable/persistence/RateLimiter.ts b/packages/effect/src/unstable/persistence/RateLimiter.ts index 0d815ecf02..ecb726d0b1 100644 --- a/packages/effect/src/unstable/persistence/RateLimiter.ts +++ b/packages/effect/src/unstable/persistence/RateLimiter.ts @@ -189,8 +189,8 @@ export const layer: Layer.Layer< * Access a function that applies rate limiting to an effect. * * ```ts - * import { RateLimiter } from "effect/unstable/persistence" * import { Effect } from "effect" + * import { RateLimiter } from "effect/unstable/persistence" * * Effect.gen(function*() { * // Access the `withLimiter` function from the RateLimiter module @@ -236,8 +236,8 @@ export const makeWithRateLimiter: Effect.Effect< * Access a function that sleeps when the rate limit is exceeded. * * ```ts - * import { RateLimiter } from "effect/unstable/persistence" * import { Effect } from "effect" + * import { RateLimiter } from "effect/unstable/persistence" * * Effect.gen(function*() { * // Access the `sleep` function from the RateLimiter module diff --git a/packages/effect/src/unstable/process/ChildProcess.ts b/packages/effect/src/unstable/process/ChildProcess.ts index 71377f2cc3..ed4addcf54 100644 --- a/packages/effect/src/unstable/process/ChildProcess.ts +++ b/packages/effect/src/unstable/process/ChildProcess.ts @@ -6,16 +6,15 @@ * * @example * ```ts - * import { Effect } from "effect" - * import { Stream } from "effect" - * import { ChildProcess } from "effect/unstable/process" * import { NodeServices } from "@effect/platform-node" + * import { Effect, Stream } from "effect" + * import { ChildProcess } from "effect/unstable/process" * * // Build a command * const command = ChildProcess.make`echo "hello world"` * * // Spawn and collect output - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * // You can `yield*` a command, which calls `ChildProcess.spawn` * const handle = yield* command * const chunks = yield* Stream.runCollect(handle.stdout) @@ -32,7 +31,7 @@ * ) * * // Spawn the pipeline - * const pipelineProgram = Effect.gen(function* () { + * const pipelineProgram = Effect.gen(function*() { * const handle = yield* pipeline * const chunks = yield* Stream.runCollect(handle.stdout) * return chunks @@ -46,7 +45,7 @@ import * as Effect from "../../Effect.ts" import { dual } from "../../Function.ts" import { PipeInspectableProto, YieldableProto } from "../../internal/core.ts" import type { Pipeable } from "../../Pipeable.ts" -import type * as PlatformError from "../../platform/PlatformError.ts" +import type * as PlatformError from "../../PlatformError.ts" import * as Predicate from "../../Predicate.ts" import type * as Scope from "../../Scope.ts" import type * as Sink from "../../Sink.ts" @@ -740,12 +739,11 @@ export const pipeTo: { * * @example * ```ts - * import { Console, Effect } from "effect" - * import { Stream } from "effect" - * import { ChildProcess } from "effect/unstable/process" * import { NodeServices } from "@effect/platform-node" + * import { Console, Effect, Stream } from "effect" + * import { ChildProcess } from "effect/unstable/process" * - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * const cmd = ChildProcess.make`long-running-process` * const handle = yield* ChildProcess.spawn(cmd) * diff --git a/packages/effect/src/unstable/process/ChildProcessSpawner.ts b/packages/effect/src/unstable/process/ChildProcessSpawner.ts index 2f220ec627..c12425e720 100644 --- a/packages/effect/src/unstable/process/ChildProcessSpawner.ts +++ b/packages/effect/src/unstable/process/ChildProcessSpawner.ts @@ -9,7 +9,7 @@ import * as Brand from "../../Brand.ts" import type * as Effect from "../../Effect.ts" import * as Inspectable from "../../Inspectable.ts" -import type * as PlatformError from "../../platform/PlatformError.ts" +import type * as PlatformError from "../../PlatformError.ts" import type * as Scope from "../../Scope.ts" import * as ServiceMap from "../../ServiceMap.ts" import type * as Sink from "../../Sink.ts" diff --git a/packages/effect/src/unstable/process/index.ts b/packages/effect/src/unstable/process/index.ts index f118f79c7b..ee02b25c6a 100644 --- a/packages/effect/src/unstable/process/index.ts +++ b/packages/effect/src/unstable/process/index.ts @@ -10,16 +10,15 @@ * * @example * ```ts - * import { Effect } from "effect" - * import { Stream } from "effect" - * import { ChildProcess } from "effect/unstable/process" * import { NodeServices } from "@effect/platform-node" + * import { Effect, Stream } from "effect" + * import { ChildProcess } from "effect/unstable/process" * * // Build a command * const command = ChildProcess.make`echo "hello world"` * * // Spawn and collect output - * const program = Effect.gen(function* () { + * const program = Effect.gen(function*() { * // You can `yield*` a command, which calls `ChildProcess.spawn` * const handle = yield* command * const chunks = yield* Stream.runCollect(handle.stdout) @@ -36,7 +35,7 @@ * ) * * // Spawn the pipeline - * const pipelineProgram = Effect.gen(function* () { + * const pipelineProgram = Effect.gen(function*() { * const handle = yield* pipeline * const chunks = yield* Stream.runCollect(handle.stdout) * return chunks diff --git a/packages/effect/src/unstable/sql/Migrator.ts b/packages/effect/src/unstable/sql/Migrator.ts index 9b3c56f680..031c3c51ec 100644 --- a/packages/effect/src/unstable/sql/Migrator.ts +++ b/packages/effect/src/unstable/sql/Migrator.ts @@ -4,11 +4,11 @@ import * as Arr from "../../Array.ts" import * as Data from "../../Data.ts" import * as Effect from "../../Effect.ts" +import { FileSystem } from "../../FileSystem.ts" import * as Filter from "../../Filter.ts" import { pipe } from "../../Function.ts" import * as Option from "../../Option.ts" import * as Order from "../../Order.ts" -import { FileSystem } from "../../platform/FileSystem.ts" import * as Client from "./SqlClient.ts" import type { SqlError } from "./SqlError.ts" diff --git a/packages/effect/src/unstable/workflow/WorkflowProxy.ts b/packages/effect/src/unstable/workflow/WorkflowProxy.ts index 3876804514..2a408fc523 100644 --- a/packages/effect/src/unstable/workflow/WorkflowProxy.ts +++ b/packages/effect/src/unstable/workflow/WorkflowProxy.ts @@ -13,10 +13,14 @@ import type * as Workflow from "./Workflow.ts" * Derives an `RpcGroup` from a list of workflows. * * ```ts - * import { RpcServer } from "effect/unstable/rpc" - * import { Workflow, WorkflowProxy, WorkflowProxyServer } from "effect/unstable/workflow" - * import { Schema } from "effect/schema" * import { Layer } from "effect" + * import { Schema } from "effect/schema" + * import { RpcServer } from "effect/unstable/rpc" + * import { + * Workflow, + * WorkflowProxy, + * WorkflowProxyServer + * } from "effect/unstable/workflow" * * const EmailWorkflow = Workflow.make({ * name: "EmailWorkflow", @@ -90,10 +94,14 @@ export type ConvertRpcs = * Derives an `HttpApiGroup` from a list of workflows. * * ```ts - * import { HttpApi, HttpApiBuilder } from "effect/unstable/httpapi" - * import { Workflow, WorkflowProxy, WorkflowProxyServer } from "effect/unstable/workflow" - * import { Schema } from "effect/schema" * import { Layer } from "effect" + * import { Schema } from "effect/schema" + * import { HttpApi, HttpApiBuilder } from "effect/unstable/httpapi" + * import { + * Workflow, + * WorkflowProxy, + * WorkflowProxyServer + * } from "effect/unstable/workflow" * * const EmailWorkflow = Workflow.make({ * name: "EmailWorkflow", @@ -115,7 +123,9 @@ export type ConvertRpcs = * // Use WorkflowProxyServer.layerHttpApi to create a layer that implements the * // workflows HttpApiGroup * const ApiLayer = HttpApiBuilder.layer(MyApi).pipe( - * Layer.provide(WorkflowProxyServer.layerHttpApi(MyApi, "workflows", myWorkflows)) + * Layer.provide( + * WorkflowProxyServer.layerHttpApi(MyApi, "workflows", myWorkflows) + * ) * ) * ``` * diff --git a/packages/effect/test/config/ConfigProvider.test.ts b/packages/effect/test/config/ConfigProvider.test.ts index 85325b0588..f681f20aca 100644 --- a/packages/effect/test/config/ConfigProvider.test.ts +++ b/packages/effect/test/config/ConfigProvider.test.ts @@ -1,8 +1,6 @@ import { describe, it } from "@effect/vitest" import { deepStrictEqual } from "@effect/vitest/utils" -import { ConfigProvider, Effect, Layer, Result } from "effect" -import { FileSystem, Path } from "effect/platform" -import { SystemError } from "effect/platform/PlatformError" +import { ConfigProvider, Effect, FileSystem, Layer, Path, PlatformError, Result } from "effect" async function assertSuccess( provider: ConfigProvider.ConfigProvider, @@ -522,7 +520,7 @@ A=1`) return Effect.succeed(files[path]) } return Effect.fail( - new SystemError({ + new PlatformError.SystemError({ module: "FileSystem", reason: "NotFound", method: "readFileString" @@ -532,7 +530,7 @@ A=1`) readDirectory(_path) { // For the test, we only have files, no directories return Effect.fail( - new SystemError({ + new PlatformError.SystemError({ module: "FileSystem", reason: "NotFound", method: "readDirectory" diff --git a/packages/effect/test/unstable/cli/Arguments.test.ts b/packages/effect/test/unstable/cli/Arguments.test.ts index 59da5a89ef..52a2891f69 100644 --- a/packages/effect/test/unstable/cli/Arguments.test.ts +++ b/packages/effect/test/unstable/cli/Arguments.test.ts @@ -1,6 +1,5 @@ import { assert, describe, expect, it } from "@effect/vitest" -import { Effect, Layer, Option, Ref, Result } from "effect" -import { FileSystem, Path, PlatformError } from "effect/platform" +import { Effect, FileSystem, Layer, Option, Path, PlatformError, Ref, Result } from "effect" import { TestConsole } from "effect/testing" import { Argument, CliOutput, Command, Flag } from "effect/unstable/cli" import * as MockTerminal from "./services/MockTerminal.ts" diff --git a/packages/effect/test/unstable/cli/Command.test.ts b/packages/effect/test/unstable/cli/Command.test.ts index d172962ac0..7a6fc74fd7 100644 --- a/packages/effect/test/unstable/cli/Command.test.ts +++ b/packages/effect/test/unstable/cli/Command.test.ts @@ -1,6 +1,5 @@ import { assert, describe, expect, it } from "@effect/vitest" -import { Effect, Layer, Option } from "effect" -import { FileSystem, Path } from "effect/platform" +import { Effect, FileSystem, Layer, Option, Path } from "effect" import { TestConsole } from "effect/testing" import { Argument, CliOutput, Command, Flag } from "effect/unstable/cli" import * as Cli from "./fixtures/ComprehensiveCli.ts" diff --git a/packages/effect/test/unstable/cli/Errors.test.ts b/packages/effect/test/unstable/cli/Errors.test.ts index bf93f7d13b..500339f644 100644 --- a/packages/effect/test/unstable/cli/Errors.test.ts +++ b/packages/effect/test/unstable/cli/Errors.test.ts @@ -1,6 +1,5 @@ import { assert, describe, it } from "@effect/vitest" -import { Effect, Layer } from "effect" -import { FileSystem, Path } from "effect/platform" +import { Effect, FileSystem, Layer, Path } from "effect" import { CliError, CliOutput, Command, Flag } from "effect/unstable/cli" import { toImpl } from "effect/unstable/cli/internal/command" import * as Lexer from "effect/unstable/cli/internal/lexer" diff --git a/packages/effect/test/unstable/cli/Help.test.ts b/packages/effect/test/unstable/cli/Help.test.ts index aacede0db8..22cd17f2ce 100644 --- a/packages/effect/test/unstable/cli/Help.test.ts +++ b/packages/effect/test/unstable/cli/Help.test.ts @@ -1,6 +1,5 @@ import { describe, expect, it } from "@effect/vitest" -import { Effect, Layer } from "effect" -import { FileSystem, Path } from "effect/platform" +import { Effect, FileSystem, Layer, Path } from "effect" import { TestConsole } from "effect/testing" import { CliOutput } from "effect/unstable/cli" import * as Cli from "./fixtures/ComprehensiveCli.ts" diff --git a/packages/effect/test/unstable/cli/LogLevel.test.ts b/packages/effect/test/unstable/cli/LogLevel.test.ts index 4d3df16128..6c67250f68 100644 --- a/packages/effect/test/unstable/cli/LogLevel.test.ts +++ b/packages/effect/test/unstable/cli/LogLevel.test.ts @@ -1,6 +1,5 @@ import { assert, describe, it } from "@effect/vitest" -import { Effect, Layer, Logger } from "effect" -import { FileSystem, Path } from "effect/platform" +import { Effect, FileSystem, Layer, Logger, Path } from "effect" import { CliOutput, Command, Flag } from "effect/unstable/cli" import * as MockTerminal from "./services/MockTerminal.ts" diff --git a/packages/effect/test/unstable/cli/Primitive.test.ts b/packages/effect/test/unstable/cli/Primitive.test.ts index 30f7e6d39a..5c28ecbe99 100644 --- a/packages/effect/test/unstable/cli/Primitive.test.ts +++ b/packages/effect/test/unstable/cli/Primitive.test.ts @@ -1,6 +1,5 @@ import { assert, describe, it } from "@effect/vitest" -import { Effect, Layer, Redacted } from "effect" -import { FileSystem, Path, PlatformError } from "effect/platform" +import { Effect, FileSystem, Layer, Path, PlatformError, Redacted } from "effect" import { Primitive } from "effect/unstable/cli" const FileSystemLayer = FileSystem.layerNoop({}) diff --git a/packages/effect/test/unstable/cli/services/MockTerminal.ts b/packages/effect/test/unstable/cli/services/MockTerminal.ts index a7b83e0fb3..a393fd823a 100644 --- a/packages/effect/test/unstable/cli/services/MockTerminal.ts +++ b/packages/effect/test/unstable/cli/services/MockTerminal.ts @@ -2,10 +2,10 @@ import * as Array from "effect/Array" import * as Console from "effect/Console" import * as Effect from "effect/Effect" import * as Layer from "effect/Layer" -import * as Terminal from "effect/platform/Terminal" import * as Queue from "effect/Queue" import type * as Scope from "effect/Scope" import * as ServiceMap from "effect/ServiceMap" +import * as Terminal from "effect/Terminal" // ============================================================================= // Models diff --git a/packages/effect/test/unstable/process/ChildProcess.test.ts b/packages/effect/test/unstable/process/ChildProcess.test.ts index 6f9e3d185f..6bdd014db7 100644 --- a/packages/effect/test/unstable/process/ChildProcess.test.ts +++ b/packages/effect/test/unstable/process/ChildProcess.test.ts @@ -1,7 +1,7 @@ import { assert, describe, it } from "@effect/vitest" import * as Effect from "effect/Effect" import * as Layer from "effect/Layer" -import type * as PlatformError from "effect/platform/PlatformError" +import type * as PlatformError from "effect/PlatformError" import * as Sink from "effect/Sink" import * as Stream from "effect/Stream" import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process" diff --git a/packages/platform-bun/src/BunClusterSocket.ts b/packages/platform-bun/src/BunClusterSocket.ts index e6d21df95d..8254b0fb80 100644 --- a/packages/platform-bun/src/BunClusterSocket.ts +++ b/packages/platform-bun/src/BunClusterSocket.ts @@ -4,8 +4,8 @@ import { layerClientProtocol, layerSocketServer } from "@effect/platform-node-shared/NodeClusterSocket" import type * as Config from "effect/Config" import * as Effect from "effect/Effect" +import * as FileSystem from "effect/FileSystem" import * as Layer from "effect/Layer" -import * as FileSystem from "effect/platform/FileSystem" import * as K8sHttpClient from "effect/unstable/cluster/K8sHttpClient" import * as MessageStorage from "effect/unstable/cluster/MessageStorage" import * as RunnerHealth from "effect/unstable/cluster/RunnerHealth" diff --git a/packages/platform-bun/src/BunFileSystem.ts b/packages/platform-bun/src/BunFileSystem.ts index 344ff8d4d3..c505ee1acb 100644 --- a/packages/platform-bun/src/BunFileSystem.ts +++ b/packages/platform-bun/src/BunFileSystem.ts @@ -2,8 +2,8 @@ * @since 1.0.0 */ import * as NodeFileSystem from "@effect/platform-node-shared/NodeFileSystem" +import type { FileSystem } from "effect/FileSystem" import type * as Layer from "effect/Layer" -import type { FileSystem } from "effect/platform/FileSystem" /** * @since 1.0.0 diff --git a/packages/platform-bun/src/BunHttpPlatform.ts b/packages/platform-bun/src/BunHttpPlatform.ts index c30d529e38..3a35fe23d7 100644 --- a/packages/platform-bun/src/BunHttpPlatform.ts +++ b/packages/platform-bun/src/BunHttpPlatform.ts @@ -2,8 +2,8 @@ * @since 1.0.0 */ import type { Effect } from "effect" +import type { FileSystem } from "effect/FileSystem" import * as Layer from "effect/Layer" -import type { FileSystem } from "effect/platform/FileSystem" import * as Etag from "effect/unstable/http/Etag" import * as Platform from "effect/unstable/http/HttpPlatform" import * as Response from "effect/unstable/http/HttpServerResponse" diff --git a/packages/platform-bun/src/BunHttpServer.ts b/packages/platform-bun/src/BunHttpServer.ts index 0cf7089b94..3b9fdb92e3 100644 --- a/packages/platform-bun/src/BunHttpServer.ts +++ b/packages/platform-bun/src/BunHttpServer.ts @@ -9,10 +9,10 @@ import * as Effect from "effect/Effect" import * as Exit from "effect/Exit" import * as Fiber from "effect/Fiber" import * as FiberSet from "effect/FiberSet" +import type * as FileSystem from "effect/FileSystem" import * as Inspectable from "effect/Inspectable" import * as Layer from "effect/Layer" -import type * as FileSystem from "effect/platform/FileSystem" -import type * as Path from "effect/platform/Path" +import type * as Path from "effect/Path" import type * as Record from "effect/Record" import type * as Scope from "effect/Scope" import * as ServiceMap from "effect/ServiceMap" diff --git a/packages/platform-bun/src/BunMultipart.ts b/packages/platform-bun/src/BunMultipart.ts index e13e9e5ea9..13b4f281ec 100644 --- a/packages/platform-bun/src/BunMultipart.ts +++ b/packages/platform-bun/src/BunMultipart.ts @@ -2,8 +2,8 @@ * @since 1.0.0 */ import type * as Effect from "effect/Effect" -import type { FileSystem } from "effect/platform/FileSystem" -import type { Path } from "effect/platform/Path" +import type { FileSystem } from "effect/FileSystem" +import type { Path } from "effect/Path" import type * as Scope from "effect/Scope" import * as Stream from "effect/Stream" import * as Multipart from "effect/unstable/http/Multipart" diff --git a/packages/platform-bun/src/BunPath.ts b/packages/platform-bun/src/BunPath.ts index 76bc53b0b0..2166a93679 100644 --- a/packages/platform-bun/src/BunPath.ts +++ b/packages/platform-bun/src/BunPath.ts @@ -3,7 +3,7 @@ */ import * as NodePath from "@effect/platform-node-shared/NodePath" import type * as Layer from "effect/Layer" -import type { Path } from "effect/platform/Path" +import type { Path } from "effect/Path" /** * @since 1.0.0 diff --git a/packages/platform-bun/src/BunServices.ts b/packages/platform-bun/src/BunServices.ts index a234e26f3a..dfc1976262 100644 --- a/packages/platform-bun/src/BunServices.ts +++ b/packages/platform-bun/src/BunServices.ts @@ -1,10 +1,10 @@ /** * @since 1.0.0 */ +import type { FileSystem } from "effect/FileSystem" import * as Layer from "effect/Layer" -import type { FileSystem } from "effect/platform/FileSystem" -import type { Path } from "effect/platform/Path" -import type { Terminal } from "effect/platform/Terminal" +import type { Path } from "effect/Path" +import type { Terminal } from "effect/Terminal" import * as BunFileSystem from "./BunFileSystem.ts" import * as BunPath from "./BunPath.ts" import * as BunTerminal from "./BunTerminal.ts" diff --git a/packages/platform-bun/src/BunTerminal.ts b/packages/platform-bun/src/BunTerminal.ts index 151850cd2f..ba79b65a87 100644 --- a/packages/platform-bun/src/BunTerminal.ts +++ b/packages/platform-bun/src/BunTerminal.ts @@ -4,8 +4,8 @@ import * as NodeTerminal from "@effect/platform-node-shared/NodeTerminal" import type { Effect } from "effect/Effect" import type { Layer } from "effect/Layer" -import type { Terminal, UserInput } from "effect/platform/Terminal" import type { Scope } from "effect/Scope" +import type { Terminal, UserInput } from "effect/Terminal" /** * @since 1.0.0 diff --git a/packages/platform-node-shared/src/NodeChildProcessSpawner.ts b/packages/platform-node-shared/src/NodeChildProcessSpawner.ts index 85924c32d6..bb75ecc808 100644 --- a/packages/platform-node-shared/src/NodeChildProcessSpawner.ts +++ b/packages/platform-node-shared/src/NodeChildProcessSpawner.ts @@ -7,11 +7,11 @@ import type * as Arr from "effect/Array" import * as Deferred from "effect/Deferred" import * as Effect from "effect/Effect" import * as Exit from "effect/Exit" +import * as FileSystem from "effect/FileSystem" import { identity } from "effect/Function" import * as Layer from "effect/Layer" -import * as FileSystem from "effect/platform/FileSystem" -import * as Path from "effect/platform/Path" -import type * as PlatformError from "effect/platform/PlatformError" +import * as Path from "effect/Path" +import type * as PlatformError from "effect/PlatformError" import * as Predicate from "effect/Predicate" import type * as Scope from "effect/Scope" import * as Sink from "effect/Sink" diff --git a/packages/platform-node-shared/src/NodeFileSystem.ts b/packages/platform-node-shared/src/NodeFileSystem.ts index e7c8f251aa..80312554cb 100644 --- a/packages/platform-node-shared/src/NodeFileSystem.ts +++ b/packages/platform-node-shared/src/NodeFileSystem.ts @@ -4,11 +4,11 @@ import * as Effect from "effect/Effect" import { effectify } from "effect/Effect" import * as Exit from "effect/Exit" +import * as FileSystem from "effect/FileSystem" import { pipe } from "effect/Function" import * as Layer from "effect/Layer" import * as Option from "effect/Option" -import * as FileSystem from "effect/platform/FileSystem" -import * as Error from "effect/platform/PlatformError" +import * as Error from "effect/PlatformError" import * as Queue from "effect/Queue" import * as Stream from "effect/Stream" import * as Crypto from "node:crypto" diff --git a/packages/platform-node-shared/src/NodePath.ts b/packages/platform-node-shared/src/NodePath.ts index e3f1bf58e8..daa308024b 100644 --- a/packages/platform-node-shared/src/NodePath.ts +++ b/packages/platform-node-shared/src/NodePath.ts @@ -3,8 +3,8 @@ */ import * as Effect from "effect/Effect" import * as Layer from "effect/Layer" -import { Path, TypeId } from "effect/platform/Path" -import { BadArgument } from "effect/platform/PlatformError" +import { Path, TypeId } from "effect/Path" +import { BadArgument } from "effect/PlatformError" import * as NodePath from "node:path" import * as NodeUrl from "node:url" diff --git a/packages/platform-node-shared/src/NodeSink.ts b/packages/platform-node-shared/src/NodeSink.ts index 1af05651ee..e19b257e3b 100644 --- a/packages/platform-node-shared/src/NodeSink.ts +++ b/packages/platform-node-shared/src/NodeSink.ts @@ -5,8 +5,8 @@ import type { NonEmptyReadonlyArray } from "effect/Array" import * as Channel from "effect/Channel" import * as Effect from "effect/Effect" import { identity, type LazyArg } from "effect/Function" -import type { PlatformError } from "effect/platform/PlatformError" -import { SystemError } from "effect/platform/PlatformError" +import type { PlatformError } from "effect/PlatformError" +import { SystemError } from "effect/PlatformError" import * as Pull from "effect/Pull" import * as Sink from "effect/Sink" import type { Writable } from "node:stream" diff --git a/packages/platform-node-shared/src/NodeStream.ts b/packages/platform-node-shared/src/NodeStream.ts index 3a1d751624..afe3dc771f 100644 --- a/packages/platform-node-shared/src/NodeStream.ts +++ b/packages/platform-node-shared/src/NodeStream.ts @@ -7,9 +7,9 @@ import * as Channel from "effect/Channel" import * as Effect from "effect/Effect" import * as Exit from "effect/Exit" import * as Fiber from "effect/Fiber" +import type { SizeInput } from "effect/FileSystem" import { dual, type LazyArg } from "effect/Function" import * as MutableRef from "effect/MutableRef" -import type { SizeInput } from "effect/platform/FileSystem" import * as Pull from "effect/Pull" import * as Scope from "effect/Scope" import * as ServiceMap from "effect/ServiceMap" diff --git a/packages/platform-node-shared/src/NodeTerminal.ts b/packages/platform-node-shared/src/NodeTerminal.ts index 57e6945246..2a61069e00 100644 --- a/packages/platform-node-shared/src/NodeTerminal.ts +++ b/packages/platform-node-shared/src/NodeTerminal.ts @@ -4,12 +4,12 @@ import * as Effect from "effect/Effect" import * as Exit from "effect/Exit" import * as Layer from "effect/Layer" -import * as PlatformError from "effect/platform/PlatformError" -import * as Terminal from "effect/platform/Terminal" +import * as PlatformError from "effect/PlatformError" import * as Predicate from "effect/Predicate" import * as Queue from "effect/Queue" import * as RcRef from "effect/RcRef" import type * as Scope from "effect/Scope" +import * as Terminal from "effect/Terminal" import * as readline from "node:readline" /** diff --git a/packages/platform-node-shared/src/internal/utils.ts b/packages/platform-node-shared/src/internal/utils.ts index 4f3413192d..e4b5f6d659 100644 --- a/packages/platform-node-shared/src/internal/utils.ts +++ b/packages/platform-node-shared/src/internal/utils.ts @@ -1,5 +1,5 @@ -import type { PlatformError, SystemErrorReason } from "effect/platform/PlatformError" -import { SystemError } from "effect/platform/PlatformError" +import type { PlatformError, SystemErrorReason } from "effect/PlatformError" +import { SystemError } from "effect/PlatformError" import type { PathLike } from "node:fs" /** @internal */ diff --git a/packages/platform-node-shared/test/NodeChildProcessSpawner.test.ts b/packages/platform-node-shared/test/NodeChildProcessSpawner.test.ts index d7e610795f..c244b4af06 100644 --- a/packages/platform-node-shared/test/NodeChildProcessSpawner.test.ts +++ b/packages/platform-node-shared/test/NodeChildProcessSpawner.test.ts @@ -4,8 +4,8 @@ import * as NodePath from "@effect/platform-node-shared/NodePath" import { assert, describe, it } from "@effect/vitest" import * as Effect from "effect/Effect" import * as Layer from "effect/Layer" -import * as Path from "effect/platform/Path" -import * as PlatformError from "effect/platform/PlatformError" +import * as Path from "effect/Path" +import * as PlatformError from "effect/PlatformError" import * as Stream from "effect/Stream" import * as TestClock from "effect/testing/TestClock" import { ChildProcess, ChildProcessSpawner } from "effect/unstable/process" diff --git a/packages/platform-node-shared/test/NodeFileSystem.test.ts b/packages/platform-node-shared/test/NodeFileSystem.test.ts index 83932732d5..4ad7a17745 100644 --- a/packages/platform-node-shared/test/NodeFileSystem.test.ts +++ b/packages/platform-node-shared/test/NodeFileSystem.test.ts @@ -2,7 +2,7 @@ import * as NodeFileSystem from "@effect/platform-node-shared/NodeFileSystem" import { assert, describe, expect, it } from "@effect/vitest" import { Array, Option } from "effect" import * as Effect from "effect/Effect" -import * as Fs from "effect/platform/FileSystem" +import * as Fs from "effect/FileSystem" import * as Stream from "effect/Stream" const runPromise = (self: Effect.Effect) => diff --git a/packages/platform-node/src/NodeClusterSocket.ts b/packages/platform-node/src/NodeClusterSocket.ts index 3b1393eb7b..09350a6db9 100644 --- a/packages/platform-node/src/NodeClusterSocket.ts +++ b/packages/platform-node/src/NodeClusterSocket.ts @@ -4,8 +4,8 @@ import { layerClientProtocol, layerSocketServer } from "@effect/platform-node-shared/NodeClusterSocket" import type { ConfigError } from "effect/Config" import * as Effect from "effect/Effect" +import * as FileSystem from "effect/FileSystem" import * as Layer from "effect/Layer" -import * as FileSystem from "effect/platform/FileSystem" import * as K8sHttpClient from "effect/unstable/cluster/K8sHttpClient" import * as MessageStorage from "effect/unstable/cluster/MessageStorage" import * as RunnerHealth from "effect/unstable/cluster/RunnerHealth" diff --git a/packages/platform-node/src/NodeFileSystem.ts b/packages/platform-node/src/NodeFileSystem.ts index 7af111d694..2f34de9b67 100644 --- a/packages/platform-node/src/NodeFileSystem.ts +++ b/packages/platform-node/src/NodeFileSystem.ts @@ -2,8 +2,8 @@ * @since 1.0.0 */ import * as NodeFileSystem from "@effect/platform-node-shared/NodeFileSystem" +import type { FileSystem } from "effect/FileSystem" import type * as Layer from "effect/Layer" -import type { FileSystem } from "effect/platform/FileSystem" /** * @since 1.0.0 diff --git a/packages/platform-node/src/NodeHttpServer.ts b/packages/platform-node/src/NodeHttpServer.ts index 589ac1ccda..3a9dfe13fd 100644 --- a/packages/platform-node/src/NodeHttpServer.ts +++ b/packages/platform-node/src/NodeHttpServer.ts @@ -5,10 +5,10 @@ import * as Cause from "effect/Cause" import * as Config from "effect/Config" import * as Effect from "effect/Effect" import * as Fiber from "effect/Fiber" +import type * as FileSystem from "effect/FileSystem" import type { LazyArg } from "effect/Function" import * as Layer from "effect/Layer" -import type * as FileSystem from "effect/platform/FileSystem" -import type * as Path from "effect/platform/Path" +import type * as Path from "effect/Path" import type * as Record from "effect/Record" import * as Scope from "effect/Scope" import * as ServiceMap from "effect/ServiceMap" diff --git a/packages/platform-node/src/NodeMultipart.ts b/packages/platform-node/src/NodeMultipart.ts index e2905328fe..a521a4c0b0 100644 --- a/packages/platform-node/src/NodeMultipart.ts +++ b/packages/platform-node/src/NodeMultipart.ts @@ -2,9 +2,9 @@ * @since 1.0.0 */ import * as Effect from "effect/Effect" +import type * as FileSystem from "effect/FileSystem" import * as Inspectable from "effect/Inspectable" -import type * as FileSystem from "effect/platform/FileSystem" -import type * as Path from "effect/platform/Path" +import type * as Path from "effect/Path" import type * as Scope from "effect/Scope" import * as Stream from "effect/Stream" import * as Multipart from "effect/unstable/http/Multipart" diff --git a/packages/platform-node/src/NodePath.ts b/packages/platform-node/src/NodePath.ts index 76bc53b0b0..2166a93679 100644 --- a/packages/platform-node/src/NodePath.ts +++ b/packages/platform-node/src/NodePath.ts @@ -3,7 +3,7 @@ */ import * as NodePath from "@effect/platform-node-shared/NodePath" import type * as Layer from "effect/Layer" -import type { Path } from "effect/platform/Path" +import type { Path } from "effect/Path" /** * @since 1.0.0 diff --git a/packages/platform-node/src/NodeServices.ts b/packages/platform-node/src/NodeServices.ts index d91967d16f..26e2d99069 100644 --- a/packages/platform-node/src/NodeServices.ts +++ b/packages/platform-node/src/NodeServices.ts @@ -1,10 +1,10 @@ /** * @since 1.0.0 */ +import type { FileSystem } from "effect/FileSystem" import * as Layer from "effect/Layer" -import type { FileSystem } from "effect/platform/FileSystem" -import type { Path } from "effect/platform/Path" -import type { Terminal } from "effect/platform/Terminal" +import type { Path } from "effect/Path" +import type { Terminal } from "effect/Terminal" import type { ChildProcessSpawner } from "effect/unstable/process/ChildProcessSpawner" import * as NodeChildProcessSpawner from "./NodeChildProcessSpawner.ts" import * as NodeFileSystem from "./NodeFileSystem.ts" diff --git a/packages/platform-node/src/NodeTerminal.ts b/packages/platform-node/src/NodeTerminal.ts index 151850cd2f..ba79b65a87 100644 --- a/packages/platform-node/src/NodeTerminal.ts +++ b/packages/platform-node/src/NodeTerminal.ts @@ -4,8 +4,8 @@ import * as NodeTerminal from "@effect/platform-node-shared/NodeTerminal" import type { Effect } from "effect/Effect" import type { Layer } from "effect/Layer" -import type { Terminal, UserInput } from "effect/platform/Terminal" import type { Scope } from "effect/Scope" +import type { Terminal, UserInput } from "effect/Terminal" /** * @since 1.0.0 diff --git a/packages/platform-node/test/HttpApi.test.ts b/packages/platform-node/test/HttpApi.test.ts index 3133c1d750..7018840172 100644 --- a/packages/platform-node/test/HttpApi.test.ts +++ b/packages/platform-node/test/HttpApi.test.ts @@ -1,7 +1,6 @@ import { NodeHttpServer } from "@effect/platform-node" import { assert, describe, it } from "@effect/vitest" -import { Array, DateTime, Effect, Filter, Layer, Redacted, Ref, ServiceMap, Stream, Struct } from "effect" -import { FileSystem } from "effect/platform" +import { Array, DateTime, Effect, FileSystem, Filter, Layer, Redacted, Ref, ServiceMap, Stream, Struct } from "effect" import { Getter, Schema, Transformation } from "effect/schema" import { Cookies, diff --git a/packages/platform-node/test/cluster/SqlMessageStorage.test.ts b/packages/platform-node/test/cluster/SqlMessageStorage.test.ts index 33b3bf6dbe..11487bf850 100644 --- a/packages/platform-node/test/cluster/SqlMessageStorage.test.ts +++ b/packages/platform-node/test/cluster/SqlMessageStorage.test.ts @@ -1,8 +1,7 @@ import { NodeFileSystem } from "@effect/platform-node" import { SqliteClient } from "@effect/sql-sqlite-node" import { assert, describe, expect, it } from "@effect/vitest" -import { Effect, Fiber, Layer } from "effect" -import { FileSystem } from "effect/platform" +import { Effect, Fiber, FileSystem, Layer } from "effect" import { TestClock } from "effect/testing" import { Message, MessageStorage, ShardingConfig, Snowflake, SqlMessageStorage } from "effect/unstable/cluster" import { SqlClient } from "effect/unstable/sql" diff --git a/packages/platform-node/test/cluster/SqlRunnerStorage.test.ts b/packages/platform-node/test/cluster/SqlRunnerStorage.test.ts index 55c2a66444..913899875e 100644 --- a/packages/platform-node/test/cluster/SqlRunnerStorage.test.ts +++ b/packages/platform-node/test/cluster/SqlRunnerStorage.test.ts @@ -1,8 +1,7 @@ import { NodeFileSystem } from "@effect/platform-node" import { SqliteClient } from "@effect/sql-sqlite-node" import { describe, expect, it } from "@effect/vitest" -import { Effect, Layer } from "effect" -import { FileSystem } from "effect/platform" +import { Effect, FileSystem, Layer } from "effect" import { Runner, RunnerAddress, diff --git a/packages/sql/sqlite-node/test/Client.test.ts b/packages/sql/sqlite-node/test/Client.test.ts index c6a79f800e..1611382ead 100644 --- a/packages/sql/sqlite-node/test/Client.test.ts +++ b/packages/sql/sqlite-node/test/Client.test.ts @@ -1,8 +1,7 @@ import { NodeFileSystem } from "@effect/platform-node" import { SqliteClient } from "@effect/sql-sqlite-node" import { assert, describe, it } from "@effect/vitest" -import { Effect } from "effect" -import { FileSystem } from "effect/platform" +import { Effect, FileSystem } from "effect" import { Reactivity } from "effect/unstable/reactivity" const makeClient = Effect.gen(function*() { diff --git a/packages/sql/sqlite-node/test/Persistence.test.ts b/packages/sql/sqlite-node/test/Persistence.test.ts index c0e6ac324c..e7a3b016eb 100644 --- a/packages/sql/sqlite-node/test/Persistence.test.ts +++ b/packages/sql/sqlite-node/test/Persistence.test.ts @@ -1,8 +1,7 @@ import { NodeFileSystem } from "@effect/platform-node" import { SqliteClient } from "@effect/sql-sqlite-node" import { expect, it } from "@effect/vitest" -import { Duration, Effect, Layer } from "effect" -import { FileSystem } from "effect/platform" +import { Duration, Effect, FileSystem, Layer } from "effect" import { TestClock } from "effect/testing" import { Persistence } from "effect/unstable/persistence" import { Reactivity } from "effect/unstable/reactivity" diff --git a/packages/sql/sqlite-node/test/Resolver.test.ts b/packages/sql/sqlite-node/test/Resolver.test.ts index cdd69a19b4..19dcf651c6 100644 --- a/packages/sql/sqlite-node/test/Resolver.test.ts +++ b/packages/sql/sqlite-node/test/Resolver.test.ts @@ -1,8 +1,7 @@ import { NodeFileSystem } from "@effect/platform-node" import { SqliteClient } from "@effect/sql-sqlite-node" import { assert, describe, it } from "@effect/vitest" -import { Cause, Effect, Iterable } from "effect" -import { FileSystem } from "effect/platform" +import { Cause, Effect, FileSystem, Iterable } from "effect" import { Schema } from "effect/schema" import { Reactivity } from "effect/unstable/reactivity" import { SqlError, SqlResolver } from "effect/unstable/sql" diff --git a/packages/vitest/src/index.ts b/packages/vitest/src/index.ts index 94000758f0..39eeeeadd2 100644 --- a/packages/vitest/src/index.ts +++ b/packages/vitest/src/index.ts @@ -170,8 +170,7 @@ export const live: Vitest.Tester = internal.live * * ```ts * import { expect, layer } from "@effect/vitest" - * import { Effect, Layer } from "effect" - * import { ServiceMap } from "effect" + * import { Effect, Layer, ServiceMap } from "effect" * * class Foo extends ServiceMap.Service("Foo")() { * static Live = Layer.succeed(Foo, "foo") @@ -186,21 +185,19 @@ export const live: Vitest.Tester = internal.live * * layer(Foo.Live)("layer", (it) => { * it.effect("adds context", () => - * Effect.gen(function* () { + * Effect.gen(function*() { * const foo = yield* Foo * expect(foo).toEqual("foo") - * }) - * ) + * })) * * it.layer(Bar.Live)("nested", (it) => { * it.effect("adds context", () => - * Effect.gen(function* () { + * Effect.gen(function*() { * const foo = yield* Foo * const bar = yield* Bar * expect(foo).toEqual("foo") * expect(bar).toEqual("bar") - * }) - * ) + * })) * }) * }) * ``` diff --git a/scripts/eslint-examples.ts b/scripts/eslint-examples.ts index fb9418b909..6c8fe04438 100644 --- a/scripts/eslint-examples.ts +++ b/scripts/eslint-examples.ts @@ -1,6 +1,6 @@ import { NodeRuntime, NodeServices } from "@effect/platform-node" import { Array, Cause, Effect, Filter, Stream } from "effect" -import { FileSystem, Path } from "effect/platform" +import { FileSystem, Path } from "effect" import * as ChildProcess from "node:child_process" const exec = (command: string, options?: ChildProcess.ExecOptions) =>