From c9ce64ff90d2a7c2a158668a4d575fd5305ac3fc Mon Sep 17 00:00:00 2001 From: Tim Date: Sun, 4 May 2025 21:56:04 +1200 Subject: [PATCH] add HttpClient (#94) --- packages/effect/src/Cause.ts | 6 +- packages/effect/src/Channel.ts | 6 +- packages/effect/src/Effect.ts | 439 ++++++- packages/effect/src/Effectify.ts | 271 ---- packages/effect/src/LayerMap.ts | 4 +- packages/effect/src/Match.ts | 1103 +++++++++++++--- packages/effect/src/Stream.ts | 173 ++- packages/effect/src/Types.ts | 8 + packages/effect/src/index.ts | 32 +- packages/effect/src/internal/effect.ts | 158 ++- packages/effect/src/internal/matcher.ts | 124 +- packages/effect/src/unstable/Cookies.ts | 757 +++++++++++ .../effect/src/unstable/FetchHttpClient.ts | 68 + packages/effect/src/unstable/Headers.ts | 268 ++++ packages/effect/src/unstable/HttpBody.ts | 339 +++++ packages/effect/src/unstable/HttpClient.ts | 1136 +++++++++++++++++ .../effect/src/unstable/HttpClientError.ts | 97 ++ .../effect/src/unstable/HttpClientRequest.ts | 674 ++++++++++ .../effect/src/unstable/HttpClientResponse.ts | 330 +++++ .../src/unstable/HttpIncomingMessage.ts | 127 ++ packages/effect/src/unstable/HttpMethod.ts | 66 + .../effect/src/unstable/HttpTraceContext.ts | 109 ++ packages/effect/src/unstable/UrlParams.ts | 328 +++++ packages/platform-bun/src/index.ts | 10 + .../src/NodeFileSystem.ts | 2 +- packages/platform-node/src/index.ts | 10 + scratchpad/http-client.ts | 16 + 27 files changed, 6087 insertions(+), 574 deletions(-) delete mode 100644 packages/effect/src/Effectify.ts create mode 100644 packages/effect/src/unstable/Cookies.ts create mode 100644 packages/effect/src/unstable/FetchHttpClient.ts create mode 100644 packages/effect/src/unstable/Headers.ts create mode 100644 packages/effect/src/unstable/HttpBody.ts create mode 100644 packages/effect/src/unstable/HttpClientError.ts create mode 100644 packages/effect/src/unstable/HttpClientRequest.ts create mode 100644 packages/effect/src/unstable/HttpClientResponse.ts create mode 100644 packages/effect/src/unstable/HttpIncomingMessage.ts create mode 100644 packages/effect/src/unstable/HttpMethod.ts create mode 100644 packages/effect/src/unstable/HttpTraceContext.ts create mode 100644 packages/effect/src/unstable/UrlParams.ts create mode 100644 scratchpad/http-client.ts diff --git a/packages/effect/src/Cause.ts b/packages/effect/src/Cause.ts index f27567cd16..1bd66e42a1 100644 --- a/packages/effect/src/Cause.ts +++ b/packages/effect/src/Cause.ts @@ -145,19 +145,19 @@ export const squash: (self: Cause) => unknown = effect.causeSquash * @since 2.0.0 * @category utils */ -export const causeHasFail: (self: Cause) => boolean = effect.causeHasFail +export const hasFail: (self: Cause) => boolean = effect.causeHasFail /** * @since 2.0.0 * @category utils */ -export const causeHasDie: (self: Cause) => boolean = effect.causeHasDie +export const hasDie: (self: Cause) => boolean = effect.causeHasDie /** * @since 2.0.0 * @category utils */ -export const causeHasInterrupt: (self: Cause) => boolean = effect.causeHasInterrupt +export const hasInterrupt: (self: Cause) => boolean = effect.causeHasInterrupt /** * @since 2.0.0 diff --git a/packages/effect/src/Channel.ts b/packages/effect/src/Channel.ts index d4ec3622b6..15bb5f8fc3 100644 --- a/packages/effect/src/Channel.ts +++ b/packages/effect/src/Channel.ts @@ -1701,10 +1701,10 @@ export const embedInput: { * guaranteed to be executed so long as the channel begins execution (and * regardless of whether or not it completes). * - * @since 2.0.0 + * @since 4.0.0 * @category utils */ -export const ensuringWith: { +export const onExit: { ( finalizer: (e: Exit.Exit) => Effect.Effect ): ( @@ -1745,7 +1745,7 @@ export const ensuring: { } = dual(2, ( self: Channel, finalizer: Effect.Effect -): Channel => ensuringWith(self, (_) => finalizer)) +): Channel => onExit(self, (_) => finalizer)) const runWith = < OutElem, diff --git a/packages/effect/src/Effect.ts b/packages/effect/src/Effect.ts index 3a3e45fb8d..ff22a8147f 100644 --- a/packages/effect/src/Effect.ts +++ b/packages/effect/src/Effect.ts @@ -31,7 +31,7 @@ import type { Scheduler } from "./Scheduler.js" import type { Scope } from "./Scope.js" import type { AnySpan, ParentSpan, Span, SpanLink, SpanOptions, Tracer } from "./Tracer.js" import type { TxRef } from "./TxRef.js" -import type { Concurrency, Covariant, NoInfer, NotFunction } from "./Types.js" +import type { Concurrency, Covariant, EqualsWith, NoInfer, NotFunction } from "./Types.js" import type * as Unify from "./Unify.js" import type { YieldWrap } from "./Utils.js" import { SingleShotGen } from "./Utils.js" @@ -1846,6 +1846,73 @@ export const catchTag: { ): Effect, R | R1> } = internal.catchTag +/** + * Handles multiple errors in a single block of code using their `_tag` field. + * + * **When to Use** + * + * `catchTags` is a convenient way to handle multiple error types at + * once. Instead of using {@link catchTag} multiple times, you can pass an + * object where each key is an error type's `_tag`, and the value is the handler + * for that specific error. This allows you to catch and recover from multiple + * error types in a single call. + * + * The error type must have a readonly `_tag` field to use `catchTag`. This + * field is used to identify and match errors. + * + * @since 2.0.0 + * @category Error handling + */ +export const catchTags: { + < + E, + Cases extends + & { [K in Extract["_tag"]]+?: ((error: Extract) => Effect) } + & (unknown extends E ? {} : { [K in Exclude["_tag"]>]: never }) + >( + cases: Cases + ): ( + self: Effect + ) => Effect< + | A + | { + [K in keyof Cases]: Cases[K] extends (...args: Array) => Effect ? A : never + }[keyof Cases], + | Exclude + | { + [K in keyof Cases]: Cases[K] extends (...args: Array) => Effect ? E : never + }[keyof Cases], + | R + | { + [K in keyof Cases]: Cases[K] extends (...args: Array) => Effect ? R : never + }[keyof Cases] + > + < + R, + E, + A, + Cases extends + & { [K in Extract["_tag"]]+?: ((error: Extract) => Effect) } + & (unknown extends E ? {} : { [K in Exclude["_tag"]>]: never }) + >( + self: Effect, + cases: Cases + ): Effect< + | A + | { + [K in keyof Cases]: Cases[K] extends (...args: Array) => Effect ? A : never + }[keyof Cases], + | Exclude + | { + [K in keyof Cases]: Cases[K] extends (...args: Array) => Effect ? E : never + }[keyof Cases], + | R + | { + [K in keyof Cases]: Cases[K] extends (...args: Array) => Effect ? R : never + }[keyof Cases] + > +} = internal.catchTags + /** * Handles both recoverable and unrecoverable errors by providing a recovery * effect. @@ -2228,7 +2295,7 @@ export declare namespace Retry { while?: ((error: E) => boolean | Effect) | undefined until?: ((error: E) => boolean | Effect) | undefined times?: number | undefined - schedule?: Schedule | undefined + schedule?: Schedule | undefined } } @@ -2673,6 +2740,100 @@ export const filter: ( } ) => Effect, E, R> = internal.filter +/** + * Filters an effect, providing an alternative effect if the predicate fails. + * + * **Details** + * + * This function applies a predicate to the result of an effect. If the + * predicate evaluates to `false`, it executes the `orElse` effect instead. The + * `orElse` effect can produce an alternative value or perform additional + * computations. + * + * @since 2.0.0 + * @category Filtering + */ +export const filterOrElse: { + ( + predicate: Predicate.Predicate> | Predicate.Refinement, B>, + orElse: (a: EqualsWith, Exclude, B>>) => Effect + ): (self: Effect) => Effect + ( + self: Effect, + predicate: Predicate.Predicate | Predicate.Refinement, + orElse: (a: EqualsWith>) => Effect + ): Effect +} = internal.filterOrElse + +/** + * Filters an effect, failing with a custom error if the predicate fails. + * + * **Details** + * + * This function applies a predicate to the result of an effect. If the + * predicate evaluates to `false`, the effect fails with a custom error + * generated by the `orFailWith` function. + * + * **When to Use** + * + * This is useful for enforcing constraints and treating violations as + * recoverable errors. + * + * **Providing a Guard** + * + * In addition to the filtering capabilities discussed earlier, you have the + * option to further refine and narrow down the type of the success channel by + * providing a [user-defined type + * guard](https://www.typescriptlang.org/docs/handbook/2/narrowing.html#using-type-predicates). + * Let's explore this concept through an example: + * + * **Example** + * + * ```ts + * import { Effect, pipe } from "effect" + * + * // Define a user interface + * interface User { + * readonly name: string + * } + * + * // Simulate an asynchronous authentication function + * declare const auth: () => Promise + * + * const program = pipe( + * Effect.promise(() => auth()), + * // Use filterOrFail with a custom type guard to ensure user is not null + * Effect.filterOrFail( + * (user): user is User => user !== null, // Type guard + * () => new Error("Unauthorized") + * ), + * // 'user' now has the type `User` (not `User | null`) + * Effect.andThen((user) => user.name) + * ) + * ``` + * + * @since 2.0.0 + * @category Filtering + */ +export const filterOrFail: { + ( + predicate: Predicate.Predicate> | Predicate.Refinement, B>, + orFailWith: (a: EqualsWith, Exclude, B>>) => E2 + ): (self: Effect) => Effect + ( + self: Effect, + predicate: Predicate.Predicate | Predicate.Refinement, + orFailWith: (a: EqualsWith>) => E2 + ): Effect + ( + predicate: Predicate.Predicate> | Predicate.Refinement, B> + ): (self: Effect) => Effect + ( + self: Effect, + predicate: Predicate.Predicate | Predicate.Refinement + ): Effect +} = internal.filterOrFail + // ----------------------------------------------------------------------------- // Conditional Operators // ----------------------------------------------------------------------------- @@ -5637,3 +5798,277 @@ export const retryTransaction: Effect = flatMap( return interrupt } ) +/** + * @since 4.0.0 + * @category Effectify + */ +export declare namespace Effectify { + interface Callback { + (err: E, a?: A): void + } + + type ArgsWithCallback, E, A> = [...args: Args, cb: Callback] + + type WithoutNull = unknown extends A ? void : Exclude + + /** + * @since 4.0.0 + * @category Effectify + */ + export type Effectify = T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + (...args: ArgsWithCallback): infer _R3 + (...args: ArgsWithCallback): infer _R4 + (...args: ArgsWithCallback): infer _R5 + (...args: ArgsWithCallback): infer _R6 + (...args: ArgsWithCallback): infer _R7 + (...args: ArgsWithCallback): infer _R8 + (...args: ArgsWithCallback): infer _R9 + (...args: ArgsWithCallback): infer _R10 + } ? { + (...args: Args1): Effect, E> + (...args: Args2): Effect, E> + (...args: Args3): Effect, E> + (...args: Args4): Effect, E> + (...args: Args5): Effect, E> + (...args: Args6): Effect, E> + (...args: Args7): Effect, E> + (...args: Args8): Effect, E> + (...args: Args9): Effect, E> + (...args: Args10): Effect, E> + } + : T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + (...args: ArgsWithCallback): infer _R3 + (...args: ArgsWithCallback): infer _R4 + (...args: ArgsWithCallback): infer _R5 + (...args: ArgsWithCallback): infer _R6 + (...args: ArgsWithCallback): infer _R7 + (...args: ArgsWithCallback): infer _R8 + (...args: ArgsWithCallback): infer _R9 + } ? { + (...args: Args1): Effect, E> + (...args: Args2): Effect, E> + (...args: Args3): Effect, E> + (...args: Args4): Effect, E> + (...args: Args5): Effect, E> + (...args: Args6): Effect, E> + (...args: Args7): Effect, E> + (...args: Args8): Effect, E> + (...args: Args9): Effect, E> + } + : T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + (...args: ArgsWithCallback): infer _R3 + (...args: ArgsWithCallback): infer _R4 + (...args: ArgsWithCallback): infer _R5 + (...args: ArgsWithCallback): infer _R6 + (...args: ArgsWithCallback): infer _R7 + (...args: ArgsWithCallback): infer _R8 + } ? { + (...args: Args1): Effect, E> + (...args: Args2): Effect, E> + (...args: Args3): Effect, E> + (...args: Args4): Effect, E> + (...args: Args5): Effect, E> + (...args: Args6): Effect, E> + (...args: Args7): Effect, E> + (...args: Args8): Effect, E> + } + : T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + (...args: ArgsWithCallback): infer _R3 + (...args: ArgsWithCallback): infer _R4 + (...args: ArgsWithCallback): infer _R5 + (...args: ArgsWithCallback): infer _R6 + (...args: ArgsWithCallback): infer _R7 + } ? { + (...args: Args1): Effect, E> + (...args: Args2): Effect, E> + (...args: Args3): Effect, E> + (...args: Args4): Effect, E> + (...args: Args5): Effect, E> + (...args: Args6): Effect, E> + (...args: Args7): Effect, E> + } + : T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + (...args: ArgsWithCallback): infer _R3 + (...args: ArgsWithCallback): infer _R4 + (...args: ArgsWithCallback): infer _R5 + (...args: ArgsWithCallback): infer _R6 + } ? { + (...args: Args1): Effect, E> + (...args: Args2): Effect, E> + (...args: Args3): Effect, E> + (...args: Args4): Effect, E> + (...args: Args5): Effect, E> + (...args: Args6): Effect, E> + } + : T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + (...args: ArgsWithCallback): infer _R3 + (...args: ArgsWithCallback): infer _R4 + (...args: ArgsWithCallback): infer _R5 + } ? { + (...args: Args1): Effect, E> + (...args: Args2): Effect, E> + (...args: Args3): Effect, E> + (...args: Args4): Effect, E> + (...args: Args5): Effect, E> + } + : T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + (...args: ArgsWithCallback): infer _R3 + (...args: ArgsWithCallback): infer _R4 + } ? { + (...args: Args1): Effect, E> + (...args: Args2): Effect, E> + (...args: Args3): Effect, E> + (...args: Args4): Effect, E> + } + : T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + (...args: ArgsWithCallback): infer _R3 + } ? { + (...args: Args1): Effect, E> + (...args: Args2): Effect, E> + (...args: Args3): Effect, E> + } + : T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + } ? { + (...args: Args1): Effect, E> + (...args: Args2): Effect, E> + } + : T extends { + (...args: ArgsWithCallback): infer _R1 + } ? { + (...args: Args1): Effect, E> + } + : never + + /** + * @category util + * @since 4.0.0 + */ + export type EffectifyError = T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + (...args: ArgsWithCallback): infer _R3 + (...args: ArgsWithCallback): infer _R4 + (...args: ArgsWithCallback): infer _R5 + (...args: ArgsWithCallback): infer _R6 + (...args: ArgsWithCallback): infer _R7 + (...args: ArgsWithCallback): infer _R8 + (...args: ArgsWithCallback): infer _R9 + (...args: ArgsWithCallback): infer _R10 + } ? NonNullable + : T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + (...args: ArgsWithCallback): infer _R3 + (...args: ArgsWithCallback): infer _R4 + (...args: ArgsWithCallback): infer _R5 + (...args: ArgsWithCallback): infer _R6 + (...args: ArgsWithCallback): infer _R7 + (...args: ArgsWithCallback): infer _R8 + (...args: ArgsWithCallback): infer _R9 + } ? NonNullable + : T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + (...args: ArgsWithCallback): infer _R3 + (...args: ArgsWithCallback): infer _R4 + (...args: ArgsWithCallback): infer _R5 + (...args: ArgsWithCallback): infer _R6 + (...args: ArgsWithCallback): infer _R7 + (...args: ArgsWithCallback): infer _R8 + } ? NonNullable + : T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + (...args: ArgsWithCallback): infer _R3 + (...args: ArgsWithCallback): infer _R4 + (...args: ArgsWithCallback): infer _R5 + (...args: ArgsWithCallback): infer _R6 + (...args: ArgsWithCallback): infer _R7 + } ? NonNullable + : T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + (...args: ArgsWithCallback): infer _R3 + (...args: ArgsWithCallback): infer _R4 + (...args: ArgsWithCallback): infer _R5 + (...args: ArgsWithCallback): infer _R6 + } ? NonNullable + : T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + (...args: ArgsWithCallback): infer _R3 + (...args: ArgsWithCallback): infer _R4 + (...args: ArgsWithCallback): infer _R5 + } ? NonNullable + : T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + (...args: ArgsWithCallback): infer _R3 + (...args: ArgsWithCallback): infer _R4 + } ? NonNullable + : T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + (...args: ArgsWithCallback): infer _R3 + } ? NonNullable + : T extends { + (...args: ArgsWithCallback): infer _R1 + (...args: ArgsWithCallback): infer _R2 + } ? NonNullable + : T extends { + (...args: ArgsWithCallback): infer _R1 + } ? NonNullable + : never +} + +/** + * Converts a callback-based function to a function that returns an `Effect`. + * + * @since 4.0.0 + * @category Effectify + */ +export const effectify: { + ) => any>(fn: F): Effectify.Effectify> + ) => any, E>( + fn: F, + onError: (error: Effectify.EffectifyError, args: Parameters) => E + ): Effectify.Effectify + ) => any, E, E2>( + fn: F, + onError: (error: Effectify.EffectifyError, args: Parameters) => E, + onSyncError: (error: unknown, args: Parameters) => E2 + ): Effectify.Effectify +} = + ((fn: Function, onError?: (e: any, args: any) => any, onSyncError?: (e: any, args: any) => any) => + (...args: Array) => + callback((resume) => { + try { + fn(...args, (err: Error | null, result: A) => { + if (err) { + resume(fail(onError ? onError(err, args) : err)) + } else { + resume(succeed(result)) + } + }) + } catch (err) { + resume(onSyncError ? fail(onSyncError(err, args)) : die(err)) + } + })) as any diff --git a/packages/effect/src/Effectify.ts b/packages/effect/src/Effectify.ts deleted file mode 100644 index 7b0e2c3094..0000000000 --- a/packages/effect/src/Effectify.ts +++ /dev/null @@ -1,271 +0,0 @@ -/** - * @since 1.0.0 - */ -import * as Effect from "./Effect.js" - -interface Callback { - (err: E, a?: A): void -} - -type ArgsWithCallback, E, A> = [...args: Args, cb: Callback] - -type WithoutNull = unknown extends A ? void : Exclude - -/** - * Converts a callback-based function to a function that returns an `Effect`. - * - * @since 1.0.0 - */ -export type Effectify = T extends { - (...args: ArgsWithCallback): infer _R1 - (...args: ArgsWithCallback): infer _R2 - (...args: ArgsWithCallback): infer _R3 - (...args: ArgsWithCallback): infer _R4 - (...args: ArgsWithCallback): infer _R5 - (...args: ArgsWithCallback): infer _R6 - (...args: ArgsWithCallback): infer _R7 - (...args: ArgsWithCallback): infer _R8 - (...args: ArgsWithCallback): infer _R9 - (...args: ArgsWithCallback): infer _R10 -} ? { - (...args: Args1): Effect.Effect, E> - (...args: Args2): Effect.Effect, E> - (...args: Args3): Effect.Effect, E> - (...args: Args4): Effect.Effect, E> - (...args: Args5): Effect.Effect, E> - (...args: Args6): Effect.Effect, E> - (...args: Args7): Effect.Effect, E> - (...args: Args8): Effect.Effect, E> - (...args: Args9): Effect.Effect, E> - (...args: Args10): Effect.Effect, E> - } - : T extends { - (...args: ArgsWithCallback): infer _R1 - (...args: ArgsWithCallback): infer _R2 - (...args: ArgsWithCallback): infer _R3 - (...args: ArgsWithCallback): infer _R4 - (...args: ArgsWithCallback): infer _R5 - (...args: ArgsWithCallback): infer _R6 - (...args: ArgsWithCallback): infer _R7 - (...args: ArgsWithCallback): infer _R8 - (...args: ArgsWithCallback): infer _R9 - } ? { - (...args: Args1): Effect.Effect, E> - (...args: Args2): Effect.Effect, E> - (...args: Args3): Effect.Effect, E> - (...args: Args4): Effect.Effect, E> - (...args: Args5): Effect.Effect, E> - (...args: Args6): Effect.Effect, E> - (...args: Args7): Effect.Effect, E> - (...args: Args8): Effect.Effect, E> - (...args: Args9): Effect.Effect, E> - } - : T extends { - (...args: ArgsWithCallback): infer _R1 - (...args: ArgsWithCallback): infer _R2 - (...args: ArgsWithCallback): infer _R3 - (...args: ArgsWithCallback): infer _R4 - (...args: ArgsWithCallback): infer _R5 - (...args: ArgsWithCallback): infer _R6 - (...args: ArgsWithCallback): infer _R7 - (...args: ArgsWithCallback): infer _R8 - } ? { - (...args: Args1): Effect.Effect, E> - (...args: Args2): Effect.Effect, E> - (...args: Args3): Effect.Effect, E> - (...args: Args4): Effect.Effect, E> - (...args: Args5): Effect.Effect, E> - (...args: Args6): Effect.Effect, E> - (...args: Args7): Effect.Effect, E> - (...args: Args8): Effect.Effect, E> - } - : T extends { - (...args: ArgsWithCallback): infer _R1 - (...args: ArgsWithCallback): infer _R2 - (...args: ArgsWithCallback): infer _R3 - (...args: ArgsWithCallback): infer _R4 - (...args: ArgsWithCallback): infer _R5 - (...args: ArgsWithCallback): infer _R6 - (...args: ArgsWithCallback): infer _R7 - } ? { - (...args: Args1): Effect.Effect, E> - (...args: Args2): Effect.Effect, E> - (...args: Args3): Effect.Effect, E> - (...args: Args4): Effect.Effect, E> - (...args: Args5): Effect.Effect, E> - (...args: Args6): Effect.Effect, E> - (...args: Args7): Effect.Effect, E> - } - : T extends { - (...args: ArgsWithCallback): infer _R1 - (...args: ArgsWithCallback): infer _R2 - (...args: ArgsWithCallback): infer _R3 - (...args: ArgsWithCallback): infer _R4 - (...args: ArgsWithCallback): infer _R5 - (...args: ArgsWithCallback): infer _R6 - } ? { - (...args: Args1): Effect.Effect, E> - (...args: Args2): Effect.Effect, E> - (...args: Args3): Effect.Effect, E> - (...args: Args4): Effect.Effect, E> - (...args: Args5): Effect.Effect, E> - (...args: Args6): Effect.Effect, E> - } - : T extends { - (...args: ArgsWithCallback): infer _R1 - (...args: ArgsWithCallback): infer _R2 - (...args: ArgsWithCallback): infer _R3 - (...args: ArgsWithCallback): infer _R4 - (...args: ArgsWithCallback): infer _R5 - } ? { - (...args: Args1): Effect.Effect, E> - (...args: Args2): Effect.Effect, E> - (...args: Args3): Effect.Effect, E> - (...args: Args4): Effect.Effect, E> - (...args: Args5): Effect.Effect, E> - } - : T extends { - (...args: ArgsWithCallback): infer _R1 - (...args: ArgsWithCallback): infer _R2 - (...args: ArgsWithCallback): infer _R3 - (...args: ArgsWithCallback): infer _R4 - } ? { - (...args: Args1): Effect.Effect, E> - (...args: Args2): Effect.Effect, E> - (...args: Args3): Effect.Effect, E> - (...args: Args4): Effect.Effect, E> - } - : T extends { - (...args: ArgsWithCallback): infer _R1 - (...args: ArgsWithCallback): infer _R2 - (...args: ArgsWithCallback): infer _R3 - } ? { - (...args: Args1): Effect.Effect, E> - (...args: Args2): Effect.Effect, E> - (...args: Args3): Effect.Effect, E> - } - : T extends { - (...args: ArgsWithCallback): infer _R1 - (...args: ArgsWithCallback): infer _R2 - } ? { - (...args: Args1): Effect.Effect, E> - (...args: Args2): Effect.Effect, E> - } - : T extends { - (...args: ArgsWithCallback): infer _R1 - } ? { - (...args: Args1): Effect.Effect, E> - } - : never - -/** - * @category util - * @since 1.0.0 - */ -export type EffectifyError = T extends { - (...args: ArgsWithCallback): infer _R1 - (...args: ArgsWithCallback): infer _R2 - (...args: ArgsWithCallback): infer _R3 - (...args: ArgsWithCallback): infer _R4 - (...args: ArgsWithCallback): infer _R5 - (...args: ArgsWithCallback): infer _R6 - (...args: ArgsWithCallback): infer _R7 - (...args: ArgsWithCallback): infer _R8 - (...args: ArgsWithCallback): infer _R9 - (...args: ArgsWithCallback): infer _R10 -} ? NonNullable - : T extends { - (...args: ArgsWithCallback): infer _R1 - (...args: ArgsWithCallback): infer _R2 - (...args: ArgsWithCallback): infer _R3 - (...args: ArgsWithCallback): infer _R4 - (...args: ArgsWithCallback): infer _R5 - (...args: ArgsWithCallback): infer _R6 - (...args: ArgsWithCallback): infer _R7 - (...args: ArgsWithCallback): infer _R8 - (...args: ArgsWithCallback): infer _R9 - } ? NonNullable - : T extends { - (...args: ArgsWithCallback): infer _R1 - (...args: ArgsWithCallback): infer _R2 - (...args: ArgsWithCallback): infer _R3 - (...args: ArgsWithCallback): infer _R4 - (...args: ArgsWithCallback): infer _R5 - (...args: ArgsWithCallback): infer _R6 - (...args: ArgsWithCallback): infer _R7 - (...args: ArgsWithCallback): infer _R8 - } ? NonNullable - : T extends { - (...args: ArgsWithCallback): infer _R1 - (...args: ArgsWithCallback): infer _R2 - (...args: ArgsWithCallback): infer _R3 - (...args: ArgsWithCallback): infer _R4 - (...args: ArgsWithCallback): infer _R5 - (...args: ArgsWithCallback): infer _R6 - (...args: ArgsWithCallback): infer _R7 - } ? NonNullable - : T extends { - (...args: ArgsWithCallback): infer _R1 - (...args: ArgsWithCallback): infer _R2 - (...args: ArgsWithCallback): infer _R3 - (...args: ArgsWithCallback): infer _R4 - (...args: ArgsWithCallback): infer _R5 - (...args: ArgsWithCallback): infer _R6 - } ? NonNullable - : T extends { - (...args: ArgsWithCallback): infer _R1 - (...args: ArgsWithCallback): infer _R2 - (...args: ArgsWithCallback): infer _R3 - (...args: ArgsWithCallback): infer _R4 - (...args: ArgsWithCallback): infer _R5 - } ? NonNullable - : T extends { - (...args: ArgsWithCallback): infer _R1 - (...args: ArgsWithCallback): infer _R2 - (...args: ArgsWithCallback): infer _R3 - (...args: ArgsWithCallback): infer _R4 - } ? NonNullable - : T extends { - (...args: ArgsWithCallback): infer _R1 - (...args: ArgsWithCallback): infer _R2 - (...args: ArgsWithCallback): infer _R3 - } ? NonNullable - : T extends { - (...args: ArgsWithCallback): infer _R1 - (...args: ArgsWithCallback): infer _R2 - } ? NonNullable - : T extends { - (...args: ArgsWithCallback): infer _R1 - } ? NonNullable - : never - -/** - * @since 1.0.0 - */ -export const effectify: { - ) => any>(fn: F): Effectify> - ) => any, E>( - fn: F, - onError: (error: EffectifyError, args: Parameters) => E - ): Effectify - ) => any, E, E2>( - fn: F, - onError: (error: EffectifyError, args: Parameters) => E, - onSyncError: (error: unknown, args: Parameters) => E2 - ): Effectify -} = - ((fn: Function, onError?: (e: any, args: any) => any, onSyncError?: (e: any, args: any) => any) => - (...args: Array) => - Effect.callback((resume) => { - try { - fn(...args, (err: Error | null, result: A) => { - if (err) { - resume(Effect.fail(onError ? onError(err, args) : err)) - } else { - resume(Effect.succeed(result)) - } - }) - } catch (err) { - resume(onSyncError ? Effect.fail(onSyncError(err, args)) : Effect.die(err)) - } - })) as any diff --git a/packages/effect/src/LayerMap.ts b/packages/effect/src/LayerMap.ts index 22ac9f2bed..b02af76d97 100644 --- a/packages/effect/src/LayerMap.ts +++ b/packages/effect/src/LayerMap.ts @@ -64,7 +64,7 @@ export interface LayerMap { * ```ts * import { Completions } from "@effect/ai" * import { OpenAiClient, OpenAiCompletions } from "@effect/ai-openai" - * import { FetchHttpClient } from "@effect/platform" + * import * as FetchHttpClient from "effect/unstable/FetchHttpClient" * import { NodeRuntime } from "@effect/platform-node" * import { Config, Effect, Layer, LayerMap } from "effect" * @@ -252,7 +252,7 @@ export interface TagClass< * ```ts * import { Completions } from "@effect/ai" * import { OpenAiClient, OpenAiCompletions } from "@effect/ai-openai" - * import { FetchHttpClient } from "@effect/platform" + * import * as FetchHttpClient from "effect/unstable/FetchHttpClient" * import { NodeRuntime } from "@effect/platform-node" * import { Config, Effect, Layer, LayerMap } from "effect" * diff --git a/packages/effect/src/Match.ts b/packages/effect/src/Match.ts index eada6a41b9..b24e08e5df 100644 --- a/packages/effect/src/Match.ts +++ b/packages/effect/src/Match.ts @@ -1,5 +1,30 @@ /** - * @since 1.0.0 + * The `effect/match` module provides a type-safe pattern matching system for + * TypeScript. Inspired by functional programming, it simplifies conditional + * logic by replacing verbose if/else or switch statements with a structured and + * expressive API. + * + * This module supports matching against types, values, and discriminated unions + * while enforcing exhaustiveness checking to ensure all cases are handled. + * + * Although pattern matching is not yet a native JavaScript feature, + * `effect/match` offers a reliable implementation that is available today. + * + * **How Pattern Matching Works** + * + * Pattern matching follows a structured process: + * + * - **Creating a matcher**: Define a `Matcher` that operates on either a + * specific `Match.type` or `Match.value`. + * + * - **Defining patterns**: Use combinators such as `Match.when`, `Match.not`, + * and `Match.tag` to specify matching conditions. + * + * - **Completing the match**: Apply a finalizer such as `Match.exhaustive`, + * `Match.orElse`, or `Match.option` to determine how unmatched cases should + * be handled. + * + * @since 4.0.0 */ import type * as Either from "./Either.js" import * as internal from "./internal/matcher.js" @@ -10,28 +35,62 @@ import type * as T from "./Types.js" import type { Unify } from "./Unify.js" /** - * @category type ids - * @since 1.0.0 + * @category Symbols + * @since 4.0.0 */ export const MatcherTypeId: unique symbol = internal.TypeId /** - * @category type ids - * @since 1.0.0 + * @category Symbols + * @since 4.0.0 */ export type MatcherTypeId = typeof MatcherTypeId /** - * @category model - * @since 1.0.0 + * Pattern matching follows a structured process: + * + * - **Creating a matcher**: Define a `Matcher` that operates on either a + * specific `Match.type` or `Match.value`. + * + * - **Defining patterns**: Use combinators such as `Match.when`, `Match.not`, + * and `Match.tag` to specify matching conditions. + * + * - **Completing the match**: Apply a finalizer such as `Match.exhaustive`, + * `Match.orElse`, or `Match.option` to determine how unmatched cases should + * be handled. + * + * @example + * ```ts + * import { Match } from "effect" + * + * // Simulated dynamic input that can be a string or a number + * const input: string | number = "some input" + * + * // ┌─── string + * // ▼ + * const result = Match.value(input).pipe( + * // Match if the value is a number + * Match.when(Match.number, (n) => `number: ${n}`), + * // Match if the value is a string + * Match.when(Match.string, (s) => `string: ${s}`), + * // Ensure all possible cases are covered + * Match.exhaustive + * ) + * + * console.log(result) + * // Output: "string: some input" + * ``` + * + * @category Model + * @since 4.0.0 */ export type Matcher = | TypeMatcher | ValueMatcher /** - * @category model - * @since 1.0.0 + * @category Model + * @since 4.0.0 */ export interface TypeMatcher extends Pipeable { readonly _tag: "TypeMatcher" @@ -47,8 +106,8 @@ export interface TypeMatcher extends Pipeable @@ -66,14 +125,14 @@ export interface ValueMatcher string + * // ▼ + * const match = Match.type().pipe( + * // Match when the value is a number + * Match.when(Match.number, (n) => `number: ${n}`), + * // Match when the value is a string + * Match.when(Match.string, (s) => `string: ${s}`), + * // Ensure all possible cases are handled + * Match.exhaustive + * ) + * + * console.log(match(0)) + * // Output: "number: 0" + * + * console.log(match("hello")) + * // Output: "string: hello" + * ``` + * + * @see {@link value} for creating a matcher from a specific value. + * + * @category Creating a matcher + * @since 4.0.0 */ export const type: () => Matcher, I, never, never> = internal.type /** - * @category constructors - * @since 1.0.0 + * Creates a matcher from a specific value. + * + * **Details** + * + * This function allows you to define a `Matcher` directly from a given value, + * rather than from a type. This is useful when working with known values, + * enabling structured pattern matching on objects, primitives, or any data + * structure. + * + * Once the matcher is created, you can use pattern-matching functions like + * {@link when} to define how different cases should be handled. + * + * **Example** (Matching an Object by Property) + * + * ```ts + * import { Match } from "effect" + * + * const input = { name: "John", age: 30 } + * + * // Create a matcher for the specific object + * const result = Match.value(input).pipe( + * // Match when the 'name' property is "John" + * Match.when( + * { name: "John" }, + * (user) => `${user.name} is ${user.age} years old` + * ), + * // Provide a fallback if no match is found + * Match.orElse(() => "Oh, not John") + * ) + * + * console.log(result) + * // Output: "John is 30 years old" + * ``` + * + * @see {@link type} for creating a matcher from a specific type. + * + * @category Creating a matcher + * @since 4.0.0 */ export const value: ( i: I ) => Matcher, I, never, I> = internal.value /** - * @category constructors - * @since 1.0.0 + * @category Creating a matcher + * @since 4.0.0 */ -export const valueTags: < - const I, - P extends - & { - readonly [Tag in Types.Tags<"_tag", I> & string]: ( - _: Extract - ) => any - } - & Readonly>, never>> ->(fields: P) => (input: I) => Unify> = internal.valueTags +export const valueTags: { + < + const I, + P extends + & { readonly [Tag in Types.Tags<"_tag", I> & string]: (_: Extract) => any } + & { readonly [Tag in Exclude>]: never } + >(fields: P): (input: I) => Unify> + < + const I, + P extends + & { readonly [Tag in Types.Tags<"_tag", I> & string]: (_: Extract) => any } + & { readonly [Tag in Exclude>]: never } + >(input: I, fields: P): Unify> +} = internal.valueTags /** - * @category constructors - * @since 1.0.0 + * @category Creating a matcher + * @since 4.0.0 */ -export const typeTags: () => < - P extends - & { - readonly [Tag in Types.Tags<"_tag", I> & string]: ( - _: Extract - ) => any - } - & Readonly>, never>> ->(fields: P) => (input: I) => Unify> = internal.typeTags +export const typeTags: { + (): < + P extends + & { + readonly [Tag in Types.Tags<"_tag", I> & string]: ( + _: Extract + ) => Ret + } + & { readonly [Tag in Exclude>]: never } + >(fields: P) => (input: I) => Ret + (): < + P extends + & { + readonly [Tag in Types.Tags<"_tag", I> & string]: ( + _: Extract + ) => any + } + & { readonly [Tag in Exclude>]: never } + >(fields: P) => (input: I) => Unify> +} = internal.typeTags /** - * @category combinators - * @since 1.0.0 + * Ensures that all branches of a matcher return a specific type. + * + * **Details** + * + * This function enforces a consistent return type across all pattern-matching + * branches. By specifying a return type, TypeScript will check that every + * matching condition produces a value of the expected type. + * + * **Important:** This function must be the first step in the matcher pipeline. + * If used later, TypeScript will not enforce type consistency correctly. + * + * **Example** (Validating Return Type Consistency) + * + * ```ts + * import { Match } from "effect" + * + * const match = Match.type<{ a: number } | { b: string }>().pipe( + * // Ensure all branches return a string + * Match.withReturnType(), + * // ❌ Type error: 'number' is not assignable to type 'string' + * // @ts-expect-error + * Match.when({ a: Match.number }, (_) => _.a), + * // ✅ Correct: returns a string + * Match.when({ b: Match.string }, (_) => _.b), + * Match.exhaustive + * ) + * ``` + * + * @since 4.0.0 */ export const withReturnType: () => ( self: Matcher @@ -144,8 +317,51 @@ export const withReturnType: () => ( : "withReturnType constraint does not extend Result type" = internal.withReturnType /** - * @category combinators - * @since 1.0.0 + * Defines a condition for matching values. + * + * **Details** + * + * This function enables pattern matching by checking whether a given value + * satisfies a condition. It supports both direct value comparisons and + * predicate functions. If the condition is met, the associated function is + * executed. + * + * This function is useful when defining matchers that need to check for + * specific values or apply logical conditions to determine a match. It works + * well with structured objects and primitive types. + * + * **Example** (Matching with Values and Predicates) + * + * ```ts + * import { Match } from "effect" + * + * // Create a matcher for objects with an "age" property + * const match = Match.type<{ age: number }>().pipe( + * // Match when age is greater than 18 + * Match.when({ age: (age) => age > 18 }, (user) => `Age: ${user.age}`), + * // Match when age is exactly 18 + * Match.when({ age: 18 }, () => "You can vote"), + * // Fallback case for all other ages + * Match.orElse((user) => `${user.age} is too young`) + * ) + * + * console.log(match({ age: 20 })) + * // Output: "Age: 20" + * + * console.log(match({ age: 18 })) + * // Output: "You can vote" + * + * console.log(match({ age: 4 })) + * // Output: "4 is too young" + * ``` + * + * @see {@link whenOr} Use this when multiple patterns should match in a single + * condition. + * @see {@link whenAnd} Use this when a value must match all provided patterns. + * @see {@link orElse} Provides a fallback when no patterns match. + * + * @category Defining patterns + * @since 4.0.0 */ export const when: < R, @@ -167,8 +383,46 @@ export const when: < > = internal.when /** - * @category combinators - * @since 1.0.0 + * Matches one of multiple patterns in a single condition. + * + * **Details** + * + * This function allows defining a condition where a value matches any of the + * provided patterns. If a match is found, the associated function is executed. + * It simplifies cases where multiple patterns share the same handling logic. + * + * Unlike {@link when}, which requires separate conditions for each pattern, + * this function enables combining them into a single statement, making the + * matcher more concise. + * + * @example + * ```ts + * import { Match } from "effect" + * + * type ErrorType = + * | { readonly _tag: "NetworkError"; readonly message: string } + * | { readonly _tag: "TimeoutError"; readonly duration: number } + * | { readonly _tag: "ValidationError"; readonly field: string } + * + * const handleError = Match.type().pipe( + * Match.whenOr( + * { _tag: "NetworkError" }, + * { _tag: "TimeoutError" }, + * () => "Retry the request" + * ), + * Match.when({ _tag: "ValidationError" }, (_) => `Invalid field: ${_.field}`), + * Match.exhaustive + * ) + * + * console.log(handleError({ _tag: "NetworkError", message: "No connection" })) + * // Output: "Retry the request" + * + * console.log(handleError({ _tag: "ValidationError", field: "email" })) + * // Output: "Invalid field: email" + * ``` + * + * @category Defining patterns + * @since 4.0.0 */ export const whenOr: < R, @@ -189,8 +443,43 @@ export const whenOr: < > = internal.whenOr /** - * @category combinators - * @since 1.0.0 + * Matches a value that satisfies all provided patterns. + * + * **Details** + * + * This function allows defining a condition where a value must match all the + * given patterns simultaneously. If the value satisfies every pattern, the + * associated function is executed. + * + * Unlike {@link when}, which matches a single pattern at a time, this function + * ensures that multiple conditions are met before executing the callback. It is + * useful when checking for values that need to fulfill multiple criteria at + * once. + * + * @example + * ```ts + * import { Match } from "effect" + * + * type User = { readonly age: number; readonly role: "admin" | "user" } + * + * const checkUser = Match.type().pipe( + * Match.whenAnd( + * { age: (n) => n >= 18 }, + * { role: "admin" }, + * () => "Admin access granted" + * ), + * Match.orElse(() => "Access denied") + * ) + * + * console.log(checkUser({ age: 20, role: "admin" })) + * // Output: "Admin access granted" + * + * console.log(checkUser({ age: 20, role: "user" })) + * // Output: "Access denied" + * ``` + * + * @category Defining patterns + * @since 4.0.0 */ export const whenAnd: < R, @@ -210,47 +499,126 @@ export const whenAnd: < > = internal.whenAnd /** - * @category combinators - * @since 1.0.0 + * Matches values based on a specified discriminant field. + * + * **Details** + * + * This function is used to define pattern matching on objects that follow a + * **discriminated union** structure, where a specific field (e.g., `type`, + * `kind`, `_tag`) determines the variant of the object. It allows matching + * multiple values of the discriminant and provides a function to handle the + * matched cases. + * + * @example + * ```ts + * import { Match, pipe } from "effect" + * + * const match = pipe( + * Match.type<{ type: "A"; a: string } | { type: "B"; b: number } | { type: "C"; c: boolean }>(), + * Match.discriminator("type")("A", "B", (_) => `A or B: ${_.type}`), + * Match.discriminator("type")("C", (_) => `C(${_.c})`), + * Match.exhaustive + * ) + * ``` + * + * @category Defining patterns + * @since 4.0.0 */ export const discriminator: ( field: D -) => & string, Ret, B extends Ret>( - ...pattern: [first: P, ...values: Array

, f: (_: Extract>) => B] +) => & string, Ret, Fn extends (_: Extract>) => Ret>( + ...pattern: [first: P, ...values: Array

, f: Fn] ) => ( self: Matcher ) => Matcher< I, Types.AddWithout>>, Types.ApplyFilters>>>, - B | A, + A | ReturnType, Pr, Ret > = internal.discriminator /** - * @category combinators - * @since 1.0.0 + * Matches values where a specified field starts with a given prefix. + * + * **Details** + * + * This function is useful for working with discriminated unions where the + * discriminant field follows a hierarchical or namespaced structure. It allows + * you to match values based on whether the specified field starts with a given + * prefix, making it easier to handle grouped cases. + * + * Instead of checking for exact matches, this function lets you match values + * that share a common prefix. For example, if your discriminant field contains + * hierarchical names like `"A"`, `"A.A"`, and `"B"`, you can match all values + * starting with `"A"` using a single rule. + * + * @example + * ```ts + * import { Match, pipe } from "effect" + * + * const match = pipe( + * Match.type<{ type: "A" } | { type: "B" } | { type: "A.A" } | {}>(), + * Match.discriminatorStartsWith("type")("A", (_) => 1 as const), + * Match.discriminatorStartsWith("type")("B", (_) => 2 as const), + * Match.orElse((_) => 3 as const) + * ) + * + * console.log(match({ type: "A" })) // 1 + * console.log(match({ type: "B" })) // 2 + * console.log(match({ type: "A.A" })) // 1 + * ``` + * + * @category Defining patterns + * @since 4.0.0 */ export const discriminatorStartsWith: ( field: D -) => ( +) => >) => Ret>( pattern: P, - f: (_: Extract>) => B + f: Fn ) => ( self: Matcher ) => Matcher< I, Types.AddWithout>>, Types.ApplyFilters>>>, - B | A, + A | ReturnType, Pr, Ret -> = internal.discriminatorStartsWith as any +> = internal.discriminatorStartsWith /** - * @category combinators - * @since 1.0.0 + * Matches values based on a field that serves as a discriminator, mapping each + * possible value to a corresponding handler. + * + * **Details** + * + * This function simplifies working with discriminated unions by letting you + * define a set of handlers for each possible value of a given field. Instead of + * chaining multiple calls to {@link discriminator}, this function allows + * defining all possible cases at once using an object where the keys are the + * possible values of the field, and the values are the corresponding handler + * functions. + * + * @example + * ```ts + * import { Match, pipe } from "effect" + * + * const match = pipe( + * Match.type<{ type: "A"; a: string } | { type: "B"; b: number } | { type: "C"; c: boolean }>(), + * Match.discriminators("type")({ + * A: (a) => a.a, + * B: (b) => b.b, + * C: (c) => c.c + * }), + * Match.exhaustive + * ) + * ``` + * + * @category Defining patterns + * @since 4.0.0 */ export const discriminators: ( field: D @@ -259,7 +627,7 @@ export const discriminators: ( Ret, P extends & { readonly [Tag in Types.Tags & string]?: ((_: Extract>) => Ret) | undefined } - & Readonly>, never>> + & { readonly [Tag in Exclude>]: never } >( fields: P ) => ( @@ -274,8 +642,36 @@ export const discriminators: ( > = internal.discriminators /** - * @category combinators - * @since 1.0.0 + * Matches values based on a discriminator field and **ensures all cases are + * handled**. + * + * **Details*+ + * + * This function is similar to {@link discriminators}, but **requires that all + * possible cases** are explicitly handled. It is useful when working with + * discriminated unions, where a specific field (e.g., `"type"`) determines the + * shape of an object. Each possible value of the field must have a + * corresponding handler, ensuring **exhaustiveness checking** at compile time. + * + * This function **does not require** `Match.exhaustive` at the end of the + * pipeline because it enforces exhaustiveness by design. + * + * @example + * ```ts + * import { Match, pipe } from "effect" + * + * const match = pipe( + * Match.type<{ type: "A"; a: string } | { type: "B"; b: number } | { type: "C"; c: boolean }>(), + * Match.discriminatorsExhaustive("type")({ + * A: (a) => a.a, + * B: (b) => b.b, + * C: (c) => c.c + * }) + * ) + * ``` + * + * @category Defining patterns + * @since 4.0.0 */ export const discriminatorsExhaustive: ( field: D @@ -284,7 +680,7 @@ export const discriminatorsExhaustive: ( Ret, P extends & { readonly [Tag in Types.Tags & string]: (_: Extract>) => Ret } - & Readonly>, never>> + & { readonly [Tag in Exclude>]: never } >( fields: P ) => ( @@ -293,50 +689,149 @@ export const discriminatorsExhaustive: ( internal.discriminatorsExhaustive /** - * @category combinators - * @since 1.0.0 + * The `Match.tag` function allows pattern matching based on the `_tag` field in + * a [Discriminated Union](https://www.typescriptlang.org/docs/handbook/typescript-in-5-minutes-func.html#discriminated-unions). + * You can specify multiple tags to match within a single pattern. + * + * **Note** + * + * The `Match.tag` function relies on the convention within the Effect ecosystem + * of naming the tag field as `"_tag"`. Ensure that your discriminated unions + * follow this naming convention for proper functionality. + * + * **Example** (Matching a Discriminated Union by Tag) + * + * ```ts + * import { Match } from "effect" + * + * type Event = + * | { readonly _tag: "fetch" } + * | { readonly _tag: "success"; readonly data: string } + * | { readonly _tag: "error"; readonly error: Error } + * | { readonly _tag: "cancel" } + * + * // Create a Matcher for Either + * const match = Match.type().pipe( + * // Match either "fetch" or "success" + * Match.tag("fetch", "success", () => `Ok!`), + * // Match "error" and extract the error message + * Match.tag("error", (event) => `Error: ${event.error.message}`), + * // Match "cancel" + * Match.tag("cancel", () => "Cancelled"), + * Match.exhaustive + * ) + * + * console.log(match({ _tag: "success", data: "Hello" })) + * // Output: "Ok!" + * + * console.log(match({ _tag: "error", error: new Error("Oops!") })) + * // Output: "Error: Oops!" + * ``` + * + * @category Defining patterns + * @since 4.0.0 */ -export const tag: & string, Ret, B extends Ret>( - ...pattern: [first: P, ...values: Array

, f: (_: Extract, Record<"_tag", P>>) => B] +export const tag: < + R, + P extends Types.Tags<"_tag", R> & string, + Ret, + Fn extends (_: Extract>) => Ret +>( + ...pattern: [first: P, ...values: Array

- : P extends SafeRefinement ? SP + [0] extends [1 & R] ? ResolvePred

: + P extends SafeRefinement ? SP : P extends Predicate.Refinement // try to narrow refinement ? [Extract] extends [infer X] ? [X] extends [never] @@ -576,21 +1285,24 @@ export declare namespace Types { : X : never : P extends PredicateA ? PP - : ExtractMatch> + : ExtractMatch /** - * @since 1.0.0 + * @since 4.0.0 */ - export type NotMatch = Exclude>> + export type NotMatch = Exclude>> - /** - * @since 1.0.0 - */ - export type PForMatch

= [SafeRefinementP>] extends [infer X] ? X + type PForNotMatch

= [ToInvertedRefinement

] extends [infer X] ? X : never /** - * @since 1.0.0 + * @since 4.0.0 + */ + export type PForMatch

= [ResolvePred

] extends [infer X] ? X + : never + + /** + * @since 4.0.0 */ export type PForExclude

= [SafeRefinementR>] extends [infer X] ? X : never @@ -598,22 +1310,16 @@ export declare namespace Types { // utilities type PredicateA = Predicate.Predicate | Predicate.Refinement - type SafeRefinementP = A extends never ? never - : A extends SafeRefinement ? S - : A extends Function ? A - : A extends Record ? { [K in keyof A]: SafeRefinementP } - : A - type SafeRefinementR = A extends never ? never : A extends SafeRefinement ? R : A extends Function ? A : A extends Record ? { [K in keyof A]: SafeRefinementR } : A - type ResolvePred = A extends never ? never - : A extends Predicate.Refinement ? P + type ResolvePred = A extends never ? never + : A extends SafeRefinement ? _A + : A extends Predicate.Refinement ? P : A extends Predicate.Predicate ? P - : A extends SafeRefinement ? A : A extends Record ? { [K in keyof A]: ResolvePred } : A @@ -624,6 +1330,13 @@ export declare namespace Types { : A extends Record ? { [K in keyof A]: ToSafeRefinement } : NonLiteralsTo + type ToInvertedRefinement = A extends never ? never + : A extends Predicate.Refinement ? SafeRefinement

+ : A extends Predicate.Predicate ? SafeRefinement + : A extends SafeRefinement ? SafeRefinement<_R> + : A extends Record ? { [K in keyof A]: ToInvertedRefinement } + : NonLiteralsTo + type NonLiteralsTo = [A] extends [string | number | boolean | bigint] ? [string] extends [A] ? T : [number] extends [A] ? T : [boolean] extends [A] ? T @@ -632,7 +1345,7 @@ export declare namespace Types { : A /** - * @since 1.0.0 + * @since 4.0.0 */ export type PatternBase = A extends ReadonlyArray ? ReadonlyArray | PatternPrimitive : A extends Record ? Partial< @@ -641,12 +1354,12 @@ export declare namespace Types { : never /** - * @since 1.0.0 + * @since 4.0.0 */ export type PatternPrimitive = PredicateA | A | SafeRefinement /** - * @since 1.0.0 + * @since 4.0.0 */ export interface Without { readonly _tag: "Without" @@ -654,7 +1367,7 @@ export declare namespace Types { } /** - * @since 1.0.0 + * @since 4.0.0 */ export interface Only { readonly _tag: "Only" @@ -662,14 +1375,14 @@ export declare namespace Types { } /** - * @since 1.0.0 + * @since 4.0.0 */ export type AddWithout = [A] extends [Without] ? Without : [A] extends [Only] ? Only> : never /** - * @since 1.0.0 + * @since 4.0.0 */ export type AddOnly = [A] extends [Without] ? [X] extends [WX] ? never : Only @@ -678,26 +1391,26 @@ export declare namespace Types { : never /** - * @since 1.0.0 + * @since 4.0.0 */ export type ApplyFilters = A extends Only ? X : A extends Without ? Exclude : never /** - * @since 1.0.0 + * @since 4.0.0 */ export type Tags = P extends Record ? X : never /** - * @since 1.0.0 + * @since 4.0.0 */ export type ArrayToIntersection> = T.UnionToIntersection< A[number] > /** - * @since 1.0.0 + * @since 4.0.0 */ export type ExtractMatch = [ExtractAndNarrow] extends [infer EI] ? EI : never @@ -724,33 +1437,37 @@ export declare namespace Types { type Simplify = { [K in keyof A]: A[K] } & {} - type ExtractAndNarrow = - // unknown is a wildcard pattern - unknown extends P ? Input - : Input extends infer I ? Exclude< - I extends ReadonlyArray ? P extends ReadonlyArray ? { - readonly [K in keyof I]: K extends keyof P ? ExtractAndNarrow - : I[K] - } extends infer R ? Fail extends R[keyof R] ? never - : R + type ExtractAndNarrow = P extends Predicate.Refinement ? + _Out extends Input ? Extract<_Out, Input> + : Extract : + P extends SafeRefinement ? [0] extends [1 & _R] ? Input + : _In extends Input ? Extract<_In, Input> + : Extract + : P extends Predicate.Predicate ? Extract + : Input extends infer I ? Exclude< + I extends ReadonlyArray ? P extends ReadonlyArray ? { + readonly [K in keyof I]: K extends keyof P ? ExtractAndNarrow + : I[K] + } extends infer R ? Fail extends R[keyof R] ? never + : R + : never + : never + : IsPlainObject extends true ? string extends keyof I ? I extends P ? I + : never + : symbol extends keyof I ? I extends P ? I + : never + : Simplify< + & { [RK in Extract]-?: ExtractAndNarrow } + & Omit + > extends infer R ? keyof P extends NonFailKeys ? R : never : never - : IsPlainObject extends true ? string extends keyof I ? I extends P ? I - : never - : symbol extends keyof I ? I extends P ? I - : never - : Simplify< - & { [RK in Extract]-?: ExtractAndNarrow } - & Omit - > extends infer R ? keyof P extends NonFailKeys ? R - : never - : never - : MaybeReplace extends infer R ? [I] extends [R] ? I - : R - : never, - Fail - > : - never + : MaybeReplace extends infer R ? [I] extends [R] ? I + : R + : never, + Fail + > : + never type NonFailKeys = keyof A & {} extends infer K ? K extends keyof A ? A[K] extends Fail ? never : K : never : diff --git a/packages/effect/src/Stream.ts b/packages/effect/src/Stream.ts index e85114c888..378ea1399c 100644 --- a/packages/effect/src/Stream.ts +++ b/packages/effect/src/Stream.ts @@ -2,9 +2,12 @@ * @since 2.0.0 */ import * as Arr from "./Array.js" -import type * as Cause from "./Cause.js" +import * as Cause from "./Cause.js" import * as Channel from "./Channel.js" +import * as Context from "./Context.js" import * as Effect from "./Effect.js" +import type * as Exit from "./Exit.js" +import * as Fiber from "./Fiber.js" import type { LazyArg } from "./Function.js" import { dual, identity } from "./Function.js" import type { TypeLambda } from "./HKT.js" @@ -14,7 +17,7 @@ import { hasProperty } from "./Predicate.js" import type * as PubSub from "./PubSub.js" import * as Pull from "./Pull.js" import * as Queue from "./Queue.js" -import type * as Scope from "./Scope.js" +import * as Scope from "./Scope.js" import type * as Sink from "./Sink.js" import type { Covariant } from "./Types.js" import type * as Unify from "./Unify.js" @@ -373,6 +376,35 @@ export const fromQueue = (queue: Queue.Dequeue): Stream => fro export const fromPubSub = (pubsub: PubSub.PubSub, chunkSize?: number): Stream => fromChannel(Channel.fromPubSubArray(pubsub, chunkSize)) +/** + * @since 2.0.0 + * @category constructors + */ +export const fromReadableStream = ( + options: { + readonly evaluate: LazyArg> + readonly onError: (error: unknown) => E + readonly releaseLockOnEnd?: boolean | undefined + } +): Stream => + fromChannel(Channel.fromTransform(Effect.fnUntraced(function*(_, scope) { + const reader = options.evaluate().getReader() + yield* Scope.addFinalizer( + scope, + () => + options.releaseLockOnEnd + ? Effect.sync(() => reader.releaseLock()) + : Effect.promise(() => reader.cancel()) + ) + return Effect.flatMap( + Effect.tryPromise({ + try: () => reader.read(), + catch: (reason) => options.onError(reason) + }), + ({ done, value }) => done ? Pull.haltVoid : Effect.succeed(Arr.of(value)) + ) + }))) + /** * @since 4.0.0 * @category constructors @@ -1019,6 +1051,22 @@ export const encodeText = (self: Stream): Stream encoder.encode(chunk)) }) +/** + * Executes the provided finalizer after this stream's finalizers run. + * + * @since 4.0.0 + * @category utils + */ +export const onExit = dual< + ( + finalizer: (exit: Exit.Exit) => Effect.Effect + ) => (self: Stream) => Stream, + ( + self: Stream, + finalizer: (exit: Exit.Exit) => Effect.Effect + ) => Stream +>(2, (self, finalizer) => fromChannel(Channel.onExit(self.channel, finalizer))) + /** * Runs the sink on the stream to produce either the sink's result or an error. * @@ -1143,3 +1191,124 @@ export const mkString = (self: Stream): Effect.Effect "", (acc, chunk) => acc + chunk.join("") ) + +/** + * Converts the stream to a `ReadableStream`. + * + * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream. + * + * @since 2.0.0 + * @category destructors + */ +export const toReadableStreamContext = dual< + ( + context: Context.Context, + options?: { readonly strategy?: QueuingStrategy | undefined } + ) => (self: Stream) => ReadableStream, + ( + self: Stream, + context: Context.Context, + options?: { readonly strategy?: QueuingStrategy | undefined } + ) => ReadableStream +>( + (args) => isStream(args[0]), + ( + self: Stream, + context: Context.Context, + options?: { readonly strategy?: QueuingStrategy | undefined } + ): ReadableStream => { + let currentResolve: (() => void) | undefined = undefined + let fiber: Fiber.Fiber | undefined = undefined + const latch = Effect.unsafeMakeLatch(false) + + return new ReadableStream({ + start(controller) { + fiber = Effect.runFork(Effect.provideContext( + runForEachChunk(self, (chunk) => + latch.whenOpen(Effect.sync(() => { + latch.unsafeClose() + for (let i = 0; i < chunk.length; i++) { + controller.enqueue(chunk[i]) + } + currentResolve!() + currentResolve = undefined + }))), + context + )) + fiber.addObserver((exit) => { + if (exit._tag === "Failure") { + controller.error(Cause.squash(exit.cause)) + } else { + controller.close() + } + }) + }, + pull() { + return new Promise((resolve) => { + currentResolve = resolve + Effect.runSync(latch.open) + }) + }, + cancel() { + if (!fiber) return + return Effect.runPromise(Effect.asVoid(Fiber.interrupt(fiber))) + } + }, options?.strategy) + } +) + +/** + * Converts the stream to a `ReadableStream`. + * + * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream. + * + * @since 2.0.0 + * @category destructors + */ +export const toReadableStream: { + ( + options?: { readonly strategy?: QueuingStrategy | undefined } + ): ( + self: Stream + ) => ReadableStream + ( + self: Stream, + options?: { readonly strategy?: QueuingStrategy | undefined } + ): ReadableStream +} = dual( + (args) => isStream(args[0]), + ( + self: Stream, + options?: { readonly strategy?: QueuingStrategy | undefined } + ): ReadableStream => toReadableStreamContext(self, Context.empty(), options) +) + +/** + * Converts the stream to a `Effect`. + * + * See https://developer.mozilla.org/en-US/docs/Web/API/ReadableStream. + * + * @since 2.0.0 + * @category destructors + */ +export const toReadableStreamEffect: { + ( + options?: { readonly strategy?: QueuingStrategy | undefined } + ): ( + self: Stream + ) => Effect.Effect, never, R> + ( + self: Stream, + options?: { readonly strategy?: QueuingStrategy | undefined } + ): Effect.Effect, never, R> +} = dual( + (args) => isStream(args[0]), + ( + self: Stream, + options?: { readonly strategy?: QueuingStrategy | undefined } + ): Effect.Effect, never, R> => + Effect.map( + Effect.context(), + (context) => toReadableStreamContext(self, context, options) + ) +) diff --git a/packages/effect/src/Types.ts b/packages/effect/src/Types.ts index 78706b2587..91a99c7292 100644 --- a/packages/effect/src/Types.ts +++ b/packages/effect/src/Types.ts @@ -144,6 +144,14 @@ export type Equals = (() => T extends X ? 1 : 2) extends < >() => T extends Y ? 1 : 2 ? true : false +/** + * Determines if two types are equal, allowing to specify the return types. + * + * @since 3.15.0 + * @category models + */ +export type EqualsWith = (() => T extends A ? 1 : 2) extends (() => T extends B ? 1 : 2) ? Y : N + /** * Determines if a record contains any of the given keys. * diff --git a/packages/effect/src/index.ts b/packages/effect/src/index.ts index d684a1d264..5ac1592481 100644 --- a/packages/effect/src/index.ts +++ b/packages/effect/src/index.ts @@ -157,11 +157,6 @@ export * as Duration from "./Duration.js" */ export * as Effect from "./Effect.js" -/** - * @since 1.0.0 - */ -export * as Effectify from "./Effectify.js" - /** * @since 2.0.0 */ @@ -277,7 +272,32 @@ export * as LogLevel from "./LogLevel.js" export * as Logger from "./Logger.js" /** - * @since 1.0.0 + * The `effect/match` module provides a type-safe pattern matching system for + * TypeScript. Inspired by functional programming, it simplifies conditional + * logic by replacing verbose if/else or switch statements with a structured and + * expressive API. + * + * This module supports matching against types, values, and discriminated unions + * while enforcing exhaustiveness checking to ensure all cases are handled. + * + * Although pattern matching is not yet a native JavaScript feature, + * `effect/match` offers a reliable implementation that is available today. + * + * **How Pattern Matching Works** + * + * Pattern matching follows a structured process: + * + * - **Creating a matcher**: Define a `Matcher` that operates on either a + * specific `Match.type` or `Match.value`. + * + * - **Defining patterns**: Use combinators such as `Match.when`, `Match.not`, + * and `Match.tag` to specify matching conditions. + * + * - **Completing the match**: Apply a finalizer such as `Match.exhaustive`, + * `Match.orElse`, or `Match.option` to determine how unmatched cases should + * be handled. + * + * @since 4.0.0 */ export * as Match from "./Match.js" diff --git a/packages/effect/src/internal/effect.ts b/packages/effect/src/internal/effect.ts index e4bb463b3d..58a755bfa9 100644 --- a/packages/effect/src/internal/effect.ts +++ b/packages/effect/src/internal/effect.ts @@ -20,7 +20,7 @@ import * as Option from "../Option.js" import * as Order from "../Order.js" import { pipeArguments } from "../Pipeable.js" import type { Predicate, Refinement } from "../Predicate.js" -import { hasProperty, isIterable, isTagged } from "../Predicate.js" +import { hasProperty, isIterable, isString, isTagged } from "../Predicate.js" import { CurrentConcurrency, CurrentLogAnnotations, @@ -36,7 +36,7 @@ import * as Result from "../Result.js" import * as Scheduler from "../Scheduler.js" import type * as Scope from "../Scope.js" import * as Tracer from "../Tracer.js" -import type { Concurrency, NoInfer, NotFunction, Simplify } from "../Types.js" +import type { Concurrency, EqualsWith, NoInfer, NotFunction, Simplify } from "../Types.js" import type { YieldWrap } from "../Utils.js" import { yieldWrapGet } from "../Utils.js" import * as InternalContext from "./context.js" @@ -1493,24 +1493,15 @@ export const zipWith: { /** @internal */ export const filterOrFailCause: { - ( - refinement: Refinement, - orFailWith: (a: NoInfer) => Cause.Cause + ( + predicate: Predicate> | Refinement, B>, + orFailWith: (a: EqualsWith, Exclude, B>>) => Cause.Cause ): (self: Effect.Effect) => Effect.Effect - ( - predicate: Predicate>, - orFailWith: (a: NoInfer) => Cause.Cause - ): (self: Effect.Effect) => Effect.Effect - ( + ( self: Effect.Effect, - refinement: Refinement, - orFailWith: (a: A) => Cause.Cause - ): Effect.Effect - ( - self: Effect.Effect, - predicate: Predicate, - orFailWith: (a: A) => Cause.Cause - ): Effect.Effect + predicate: Predicate | Refinement, + orFailWith: (a: EqualsWith>) => Cause.Cause + ): Effect.Effect } = dual( (args) => isEffect(args[0]), ( @@ -1520,34 +1511,35 @@ export const filterOrFailCause: { ): Effect.Effect => flatMap(self, (a) => refinement(a) ? succeed(a) : failCause(orFailWith(a))) ) -/** @internal */ +/* @internal */ export const filterOrFail: { - ( - refinement: Refinement, - orFailWith: (a: NoInfer) => E2 + ( + predicate: Predicate> | Refinement, B>, + orFailWith: (a: EqualsWith, Exclude, B>>) => E2 ): (self: Effect.Effect) => Effect.Effect - ( - predicate: Predicate>, - orFailWith: (a: NoInfer) => E2 - ): (self: Effect.Effect) => Effect.Effect - ( + ( self: Effect.Effect, - refinement: Refinement, - orFailWith: (a: A) => E2 - ): Effect.Effect - ( + predicate: Predicate | Refinement, + orFailWith: (a: EqualsWith>) => E2 + ): Effect.Effect + ( + predicate: Predicate> | Refinement, B> + ): (self: Effect.Effect) => Effect.Effect + ( self: Effect.Effect, - predicate: Predicate, - orFailWith: (a: A) => E2 - ): Effect.Effect -} = dual( - (args) => isEffect(args[0]), - ( - self: Effect.Effect, - refinement: Refinement, - orFailWith: (a: A) => E2 - ): Effect.Effect => flatMap(self, (a) => (refinement(a) ? succeed(a) : fail(orFailWith(a)))) -) + predicate: Predicate | Refinement + ): Effect.Effect +} = dual((args) => isEffect(args[0]), ( + self: Effect.Effect, + predicate: Predicate, + orFailWith?: (a: A) => E2 +): Effect.Effect => + filterOrElse( + self, + predicate, + (a): Effect.Effect => + fail(orFailWith === undefined ? new NoSuchElementError() : orFailWith(a)) + )) /** @internal */ export const when: { @@ -1941,6 +1933,67 @@ export const catchTag: { ) as any ) +/** @internal */ +export const catchTags: { + < + E, + Cases extends (E extends { _tag: string } ? { + [K in E["_tag"]]+?: (error: Extract) => Effect.Effect + } : + {}) + >( + cases: Cases + ): (self: Effect.Effect) => Effect.Effect< + | A + | { + [K in keyof Cases]: Cases[K] extends ((...args: Array) => Effect.Effect) ? A : never + }[keyof Cases], + | Exclude + | { + [K in keyof Cases]: Cases[K] extends ((...args: Array) => Effect.Effect) ? E : never + }[keyof Cases], + | R + | { + [K in keyof Cases]: Cases[K] extends ((...args: Array) => Effect.Effect) ? R : never + }[keyof Cases] + > + < + R, + E, + A, + Cases extends (E extends { _tag: string } ? { + [K in E["_tag"]]+?: (error: Extract) => Effect.Effect + } : + {}) + >( + self: Effect.Effect, + cases: Cases + ): Effect.Effect< + | A + | { + [K in keyof Cases]: Cases[K] extends ((...args: Array) => Effect.Effect) ? A : never + }[keyof Cases], + | Exclude + | { + [K in keyof Cases]: Cases[K] extends ((...args: Array) => Effect.Effect) ? E : never + }[keyof Cases], + | R + | { + [K in keyof Cases]: Cases[K] extends ((...args: Array) => Effect.Effect) ? R : never + }[keyof Cases] + > +} = dual(2, (self, cases) => { + let keys: Array + return catchIf( + self, + (e): e is { readonly _tag: string } => { + keys ??= Object.keys(cases) + return hasProperty(e, "_tag") && isString(e["_tag"]) && keys.includes(e["_tag"]) + }, + (e) => cases[e["_tag"]](e) + ) +}) + /** @internal */ export const mapErrorCause: { ( @@ -2912,6 +2965,27 @@ export const filter = ( options ) +/* @internal */ +export const filterOrElse: { + ( + predicate: Predicate> | Refinement, B>, + orElse: (a: EqualsWith, Exclude, B>>) => Effect.Effect + ): (self: Effect.Effect) => Effect.Effect + ( + self: Effect.Effect, + predicate: Predicate | Refinement, + orElse: (a: EqualsWith>) => Effect.Effect + ): Effect.Effect +} = dual(3, ( + self: Effect.Effect, + predicate: Predicate, + orElse: (a: A) => Effect.Effect +): Effect.Effect => + flatMap( + self, + (a) => predicate(a) ? succeed(a) : orElse(a) + )) + /** @internal */ export const filterMap = ( iterable: Iterable, diff --git a/packages/effect/src/internal/matcher.ts b/packages/effect/src/internal/matcher.ts index 44d09bb7bb..4938e6b877 100644 --- a/packages/effect/src/internal/matcher.ts +++ b/packages/effect/src/internal/matcher.ts @@ -1,5 +1,5 @@ import * as Either from "../Either.js" -import { identity } from "../Function.js" +import { dual, identity } from "../Function.js" import type { Case, Matcher, @@ -18,7 +18,7 @@ import type { Unify } from "../Unify.js" /** @internal */ export const TypeId: MatcherTypeId = Symbol.for( - "@effect/matcher/Matcher" + "effect/Match/Matcher" ) as MatcherTypeId const TypeMatcherProto: Omit, "cases"> = { @@ -209,19 +209,31 @@ export const value = ( ): Matcher, I, never, I> => makeValueMatcher(i, Either.left(i)) /** @internal */ -export const valueTags = < - const I, - P extends { - readonly [Tag in Types.Tags<"_tag", I> & string]: ( - _: Extract - ) => any +export const valueTags: { + < + const I, + P extends + & { readonly [Tag in Types.Tags<"_tag", I> & string]: (_: Extract) => any } + & { readonly [Tag in Exclude>]: never } + >(fields: P): (input: I) => Unify> + < + const I, + P extends + & { readonly [Tag in Types.Tags<"_tag", I> & string]: (_: Extract) => any } + & { readonly [Tag in Exclude>]: never } + >(input: I, fields: P): Unify> +} = dual( + 2, + < + const I, + P extends + & { readonly [Tag in Types.Tags<"_tag", I> & string]: (_: Extract) => any } + & { readonly [Tag in Exclude>]: never } + >(input: I, fields: P): Unify> => { + const match: any = tagsExhaustive(fields as any)(makeTypeMatcher([])) + return match(input) } ->( - fields: P -) => { - const match: any = tagsExhaustive(fields as any)(makeTypeMatcher([])) - return (input: I): Unify> => match(input) -} +) /** @internal */ export const typeTags = () => @@ -321,38 +333,47 @@ export const whenAnd = < } /** @internal */ -export const discriminator = - (field: D) => - & string, Ret, B extends Ret>( - ...pattern: [ - first: P, - ...values: Array

, - f: (_: Extract>) => B - ] - ) => { - const f = pattern[pattern.length - 1] - const values: Array

= pattern.slice(0, -1) as any - const pred = values.length === 1 - ? (_: any) => _[field] === values[0] - : (_: any) => values.includes(_[field]) +export const discriminator = (field: D) => +< + R, + P extends Types.Tags & string, + Ret, + Fn extends (_: Extract>) => Ret +>( + ...pattern: [ + first: P, + ...values: Array

, + f: Fn + ] +) => { + const f = pattern[pattern.length - 1] + const values: Array

= pattern.slice(0, -1) as any + const pred = values.length === 1 + ? (_: any) => _[field] === values[0] + : (_: any) => values.includes(_[field]) - return ( - self: Matcher - ): Matcher< - I, - Types.AddWithout>>, - Types.ApplyFilters>>>, - A | B, - Pr, - Ret - > => (self as any).add(makeWhen(pred, f as any)) as any - } + return ( + self: Matcher + ): Matcher< + I, + Types.AddWithout>>, + Types.ApplyFilters>>>, + A | ReturnType, + Pr, + Ret + > => (self as any).add(makeWhen(pred, f as any)) as any +} /** @internal */ export const discriminatorStartsWith = (field: D) => -( +< + R, + P extends string, + Ret, + Fn extends (_: Extract>) => Ret +>( pattern: P, - f: (_: Extract>) => B + f: Fn ) => { const pred = (_: any) => typeof _[field] === "string" && _[field].startsWith(pattern) @@ -365,7 +386,7 @@ export const discriminatorStartsWith = (field: D) => I, Types.AddWithout>> >, - A | B, + A | ReturnType, Pr, Ret > => (self as any).add(makeWhen(pred, f as any)) as any @@ -382,12 +403,12 @@ export const discriminators = (field: D) => | ((_: Extract>) => Ret) | undefined } - & Readonly>, never>> + & { readonly [Tag in Exclude>]: never } >( fields: P ) => { const predicate = makeWhen( - (_: any) => _[field] in fields, + (arg: any) => arg != null && arg[field] in fields, (data: any) => (fields as any)[data[field]](data) ) @@ -415,7 +436,7 @@ export const discriminatorsExhaustive: ( _: Extract> ) => Ret } - & Readonly>, never>> + & { readonly [Tag in Exclude>]: never } >( fields: P ) => ( @@ -427,11 +448,16 @@ export const discriminatorsExhaustive: ( } /** @internal */ -export const tag: & string, Ret, B extends Ret>( +export const tag: < + R, + P extends Types.Tags<"_tag", R> & string, + Ret, + Fn extends (_: Extract>) => Ret +>( ...pattern: [ first: P, ...values: Array

, - f: (_: Extract>) => B + f: Fn ] ) => ( self: Matcher @@ -439,7 +465,7 @@ export const tag: & string, Ret, B extends R I, Types.AddWithout>>, Types.ApplyFilters>>>, - B | A, + ReturnType | A, Pr, Ret > = discriminator("_tag") @@ -483,7 +509,7 @@ export const is: < Literals extends ReadonlyArray >( ...literals: Literals -) => Predicate.Refinement = (...literals): any => { +) => SafeRefinement = (...literals): any => { const len = literals.length return (u: unknown) => { for (let i = 0; i < len; i++) { diff --git a/packages/effect/src/unstable/Cookies.ts b/packages/effect/src/unstable/Cookies.ts new file mode 100644 index 0000000000..c03556deb3 --- /dev/null +++ b/packages/effect/src/unstable/Cookies.ts @@ -0,0 +1,757 @@ +/** + * @since 4.0.0 + */ +import * as Data from "../Data.js" +import * as Duration from "../Duration.js" +import { dual, identity } from "../Function.js" +import * as Inspectable from "../Inspectable.js" +import * as Option from "../Option.js" +import { type Pipeable, pipeArguments } from "../Pipeable.js" +import * as Predicate from "../Predicate.js" +import * as Record from "../Record.js" +import * as Result from "../Result.js" +import type * as Types from "../Types.js" + +/** + * @since 4.0.0 + * @category type ids + */ +export const TypeId: unique symbol = Symbol.for("effect/Cookies") + +/** + * @since 4.0.0 + * @category type ids + */ +export type TypeId = typeof TypeId + +/** + * @since 4.0.0 + * @category refinements + */ +export const isCookies = (u: unknown): u is Cookies => Predicate.hasProperty(u, TypeId) + +/** + * @since 4.0.0 + * @category models + */ +export interface Cookies extends Pipeable, Inspectable.Inspectable { + readonly [TypeId]: TypeId + readonly cookies: Record.ReadonlyRecord +} + +/** + * @since 4.0.0 + * @category type ids + */ +export const CookieTypeId: unique symbol = Symbol.for("effect/Cookies/Cookie") + +/** + * @since 4.0.0 + * @category type ids + */ +export type CookieTypeId = typeof CookieTypeId + +/** + * @since 4.0.0 + * @category cookie + */ +export interface Cookie extends Inspectable.Inspectable { + readonly [CookieTypeId]: CookieTypeId + readonly name: string + readonly value: string + readonly valueEncoded: string + readonly options?: { + readonly domain?: string | undefined + readonly expires?: Date | undefined + readonly maxAge?: Duration.DurationInput | undefined + readonly path?: string | undefined + readonly priority?: "low" | "medium" | "high" | undefined + readonly httpOnly?: boolean | undefined + readonly secure?: boolean | undefined + readonly partitioned?: boolean | undefined + readonly sameSite?: "lax" | "strict" | "none" | undefined + } | undefined +} + +/** + * @since 4.0.0 + * @category type ids + */ +export const ErrorTypeId: unique symbol = Symbol.for("effect/Cookies/CookieError") + +/** + * @since 4.0.0 + * @category type ids + */ +export type ErrorTypeId = typeof ErrorTypeId + +/** + * @since 4.0.0 + * @category errors + */ +export class CookiesError extends Data.TaggedError("CookieError")<{ + readonly reason: "InvalidName" | "InvalidValue" | "InvalidDomain" | "InvalidPath" | "InfinityMaxAge" + readonly cause?: unknown +}> { + /** + * @since 4.0.0 + */ + readonly [ErrorTypeId]: ErrorTypeId = ErrorTypeId + + /** + * @since 4.0.0 + */ + get message() { + return this.reason + } +} + +const Proto: Omit = { + [TypeId]: TypeId, + ...Inspectable.BaseProto, + toJSON(this: Cookies) { + return { + _id: "effect/Cookies", + cookies: Record.map(this.cookies, (cookie) => cookie.toJSON()) + } + }, + pipe() { + return pipeArguments(this, arguments) + } +} + +/** + * Create a Cookies object from an Iterable + * + * @since 4.0.0 + * @category constructors + */ +export const fromReadonlyRecord = (cookies: Record.ReadonlyRecord): Cookies => { + const self = Object.create(Proto) + self.cookies = cookies + return self +} + +/** + * Create a Cookies object from an Iterable + * + * @since 4.0.0 + * @category constructors + */ +export const fromIterable = (cookies: Iterable): Cookies => { + const record: Record = {} + for (const cookie of cookies) { + record[cookie.name] = cookie + } + return fromReadonlyRecord(record) +} + +/** + * Create a Cookies object from a set of Set-Cookie headers + * + * @since 4.0.0 + * @category constructors + */ +export const fromSetCookie = (headers: Iterable | string): Cookies => { + const arrayHeaders = typeof headers === "string" ? [headers] : headers + const cookies: Array = [] + for (const header of arrayHeaders) { + const cookie = parseSetCookie(header.trim()) + if (Option.isSome(cookie)) { + cookies.push(cookie.value) + } + } + + return fromIterable(cookies) +} + +function parseSetCookie(header: string): Option.Option { + const parts = header.split(";").map((_) => _.trim()).filter((_) => _ !== "") + if (parts.length === 0) { + return Option.none() + } + + const firstEqual = parts[0].indexOf("=") + if (firstEqual === -1) { + return Option.none() + } + const name = parts[0].slice(0, firstEqual) + if (!fieldContentRegExp.test(name)) { + return Option.none() + } + + const valueEncoded = parts[0].slice(firstEqual + 1) + const value = tryDecodeURIComponent(valueEncoded) + + if (parts.length === 1) { + return Option.some(Object.assign(Object.create(CookieProto), { + name, + value, + valueEncoded + })) + } + + const options: Types.Mutable = {} + + for (let i = 1; i < parts.length; i++) { + const part = parts[i] + const equalIndex = part.indexOf("=") + const key = equalIndex === -1 ? part : part.slice(0, equalIndex).trim() + const value = equalIndex === -1 ? undefined : part.slice(equalIndex + 1).trim() + + switch (key.toLowerCase()) { + case "domain": { + if (value === undefined) { + break + } + const domain = value.trim().replace(/^\./, "") + if (domain) { + options.domain = domain + } + break + } + case "expires": { + if (value === undefined) { + break + } + const date = new Date(value) + if (!isNaN(date.getTime())) { + options.expires = date + } + break + } + case "max-age": { + if (value === undefined) { + break + } + const maxAge = parseInt(value, 10) + if (!isNaN(maxAge)) { + options.maxAge = Duration.seconds(maxAge) + } + break + } + case "path": { + if (value === undefined) { + break + } + if (value[0] === "/") { + options.path = value + } + break + } + case "priority": { + if (value === undefined) { + break + } + switch (value.toLowerCase()) { + case "low": + options.priority = "low" + break + case "medium": + options.priority = "medium" + break + case "high": + options.priority = "high" + break + } + break + } + case "httponly": { + options.httpOnly = true + break + } + case "secure": { + options.secure = true + break + } + case "partitioned": { + options.partitioned = true + break + } + case "samesite": { + if (value === undefined) { + break + } + switch (value.toLowerCase()) { + case "lax": + options.sameSite = "lax" + break + case "strict": + options.sameSite = "strict" + break + case "none": + options.sameSite = "none" + break + } + break + } + } + } + + return Option.some(Object.assign(Object.create(CookieProto), { + name, + value, + valueEncoded, + options: Object.keys(options).length > 0 ? options : undefined + })) +} + +/** + * An empty Cookies object + * + * @since 4.0.0 + * @category constructors + */ +export const empty: Cookies = fromIterable([]) + +/** + * @since 4.0.0 + * @category refinements + */ +export const isEmpty = (self: Cookies): boolean => Record.isEmptyRecord(self.cookies) + +// eslint-disable-next-line no-control-regex +const fieldContentRegExp = /^[\u0009\u0020-\u007e\u0080-\u00ff]+$/ + +const CookieProto = { + [CookieTypeId]: CookieTypeId, + ...Inspectable.BaseProto, + toJSON(this: Cookie) { + return { + _id: "effect/Cookies/Cookie", + name: this.name, + value: this.value, + options: this.options + } + } +} + +/** + * Create a new cookie + * + * @since 4.0.0 + * @category constructors + */ +export function makeCookie( + name: string, + value: string, + options?: Cookie["options"] | undefined +): Result.Result { + if (!fieldContentRegExp.test(name)) { + return Result.err(new CookiesError({ reason: "InvalidName" })) + } + const encodedValue = encodeURIComponent(value) + if (encodedValue && !fieldContentRegExp.test(encodedValue)) { + return Result.err(new CookiesError({ reason: "InvalidValue" })) + } + + if (options !== undefined) { + if (options.domain !== undefined && !fieldContentRegExp.test(options.domain)) { + return Result.err(new CookiesError({ reason: "InvalidDomain" })) + } + + if (options.path !== undefined && !fieldContentRegExp.test(options.path)) { + return Result.err(new CookiesError({ reason: "InvalidPath" })) + } + + if (options.maxAge !== undefined && !Duration.isFinite(Duration.decode(options.maxAge))) { + return Result.err(new CookiesError({ reason: "InfinityMaxAge" })) + } + } + + return Result.ok(Object.assign(Object.create(CookieProto), { + name, + value, + valueEncoded: encodedValue, + options + })) +} + +/** + * Create a new cookie, throwing an error if invalid + * + * @since 4.0.0 + * @category constructors + */ +export const unsafeMakeCookie = ( + name: string, + value: string, + options?: Cookie["options"] | undefined +): Cookie => Result.getOrThrowWith(makeCookie(name, value, options), identity) + +/** + * Add a cookie to a Cookies object + * + * @since 4.0.0 + * @category combinators + */ +export const setCookie: { + (cookie: Cookie): (self: Cookies) => Cookies + ( + self: Cookies, + cookie: Cookie + ): Cookies +} = dual( + 2, + (self: Cookies, cookie: Cookie) => + fromReadonlyRecord(Record.set( + self.cookies, + cookie.name, + cookie + )) +) + +/** + * Add multiple cookies to a Cookies object + * + * @since 4.0.0 + * @category combinators + */ +export const setAllCookie: { + (cookies: Iterable): (self: Cookies) => Cookies + ( + self: Cookies, + cookies: Iterable + ): Cookies +} = dual(2, (self: Cookies, cookies: Iterable) => { + const record = { ...self.cookies } + for (const cookie of cookies) { + record[cookie.name] = cookie + } + return fromReadonlyRecord(record) +}) + +/** + * Combine two Cookies objects, removing duplicates from the first + * + * @since 4.0.0 + * @category combinators + */ +export const merge: { + (that: Cookies): (self: Cookies) => Cookies + ( + self: Cookies, + that: Cookies + ): Cookies +} = dual(2, (self: Cookies, that: Cookies) => + fromReadonlyRecord({ + ...self.cookies, + ...that.cookies + })) + +/** + * Remove a cookie by name + * + * @since 4.0.0 + * @category combinators + */ +export const remove: { + (name: string): (self: Cookies) => Cookies + ( + self: Cookies, + name: string + ): Cookies +} = dual(2, (self: Cookies, name: string) => fromReadonlyRecord(Record.remove(self.cookies, name))) + +/** + * Get a cookie from a Cookies object + * + * @since 4.0.0 + * @category combinators + */ +export const get: { + (name: string): (self: Cookies) => Option.Option + (self: Cookies, name: string): Option.Option +} = dual( + (args) => isCookies(args[0]), + (self: Cookies, name: string): Option.Option => Record.get(self.cookies, name) +) + +/** + * Get a cookie from a Cookies object + * + * @since 4.0.0 + * @category combinators + */ +export const getValue: { + (name: string): (self: Cookies) => Option.Option + (self: Cookies, name: string): Option.Option +} = dual( + (args) => isCookies(args[0]), + (self: Cookies, name: string): Option.Option => + Option.map(Record.get(self.cookies, name), (cookie) => cookie.value) +) + +/** + * Add a cookie to a Cookies object + * + * @since 4.0.0 + * @category combinators + */ +export const set: { + ( + name: string, + value: string, + options?: Cookie["options"] + ): (self: Cookies) => Result.Result + ( + self: Cookies, + name: string, + value: string, + options?: Cookie["options"] + ): Result.Result +} = dual( + (args) => isCookies(args[0]), + (self: Cookies, name: string, value: string, options?: Cookie["options"]) => + Result.map( + makeCookie(name, value, options), + (cookie) => fromReadonlyRecord(Record.set(self.cookies, name, cookie)) + ) +) + +/** + * Add a cookie to a Cookies object + * + * @since 4.0.0 + * @category combinators + */ +export const unsafeSet: { + ( + name: string, + value: string, + options?: Cookie["options"] + ): (self: Cookies) => Cookies + ( + self: Cookies, + name: string, + value: string, + options?: Cookie["options"] + ): Cookies +} = dual( + (args) => isCookies(args[0]), + (self: Cookies, name: string, value: string, options?: Cookie["options"]) => + fromReadonlyRecord(Record.set( + self.cookies, + name, + unsafeMakeCookie(name, value, options) + )) +) + +/** + * Add multiple cookies to a Cookies object + * + * @since 4.0.0 + * @category combinators + */ +export const setAll: { + ( + cookies: Iterable + ): (self: Cookies) => Result.Result + ( + self: Cookies, + cookies: Iterable + ): Result.Result +} = dual( + 2, + ( + self: Cookies, + cookies: Iterable + ): Result.Result => { + const record: Record = { ...self.cookies } + for (const [name, value, options] of cookies) { + const result = makeCookie(name, value, options) + if (Result.isErr(result)) { + return result as Result.Err + } + record[name] = result.ok + } + return Result.ok(fromReadonlyRecord(record)) + } +) + +/** + * Add multiple cookies to a Cookies object, throwing an error if invalid + * + * @since 4.0.0 + * @category combinators + */ +export const unsafeSetAll: { + ( + cookies: Iterable + ): (self: Cookies) => Cookies + ( + self: Cookies, + cookies: Iterable + ): Cookies +} = dual( + 2, + ( + self: Cookies, + cookies: Iterable + ): Cookies => Result.getOrThrowWith(setAll(self, cookies), identity) +) + +/** + * Serialize a cookie into a string + * + * Adapted from https://github.com/fastify/fastify-cookie under MIT License + * + * @since 4.0.0 + * @category encoding + */ +export function serializeCookie(self: Cookie): string { + let str = self.name + "=" + self.valueEncoded + + if (self.options === undefined) { + return str + } + const options = self.options + + if (options.maxAge !== undefined) { + const maxAge = Duration.toSeconds(options.maxAge) + str += "; Max-Age=" + Math.trunc(maxAge) + } + + if (options.domain !== undefined) { + str += "; Domain=" + options.domain + } + + if (options.path !== undefined) { + str += "; Path=" + options.path + } + + if (options.priority !== undefined) { + switch (options.priority) { + case "low": + str += "; Priority=Low" + break + case "medium": + str += "; Priority=Medium" + break + case "high": + str += "; Priority=High" + break + } + } + + if (options.expires !== undefined) { + str += "; Expires=" + options.expires.toUTCString() + } + + if (options.httpOnly) { + str += "; HttpOnly" + } + + if (options.secure) { + str += "; Secure" + } + + // Draft implementation to support Chrome from 2024-Q1 forward. + // See https://datatracker.ietf.org/doc/html/draft-cutler-httpbis-partitioned-cookies#section-2.1 + if (options.partitioned) { + str += "; Partitioned" + } + + if (options.sameSite !== undefined) { + switch (options.sameSite) { + case "lax": + str += "; SameSite=Lax" + break + case "strict": + str += "; SameSite=Strict" + break + case "none": + str += "; SameSite=None" + break + } + } + + return str +} + +/** + * Serialize a Cookies object into a Cookie header + * + * @since 4.0.0 + * @category encoding + */ +export const toCookieHeader = (self: Cookies): string => + Object.values(self.cookies).map((cookie) => `${cookie.name}=${cookie.valueEncoded}`).join("; ") + +/** + * To record + * + * @since 4.0.0 + * @category encoding + */ +export const toRecord = (self: Cookies): Record => { + const record: Record = {} + const cookies = Object.values(self.cookies) + for (let index = 0; index < cookies.length; index++) { + const cookie = cookies[index] + record[cookie.name] = cookie.value + } + return record +} + +/** + * Serialize a Cookies object into Headers object containing one or more Set-Cookie headers + * + * @since 4.0.0 + * @category encoding + */ +export const toSetCookieHeaders = (self: Cookies): Array => Object.values(self.cookies).map(serializeCookie) + +/** + * Parse a cookie header into a record of key-value pairs + * + * Adapted from https://github.com/fastify/fastify-cookie under MIT License + * + * @since 4.0.0 + * @category decoding + */ +export function parseHeader(header: string): Record { + const result: Record = {} + + const strLen = header.length + let pos = 0 + let terminatorPos = 0 + + while (true) { + if (terminatorPos === strLen) break + terminatorPos = header.indexOf(";", pos) + if (terminatorPos === -1) terminatorPos = strLen // This is the last pair + + let eqIdx = header.indexOf("=", pos) + if (eqIdx === -1) break // No key-value pairs left + if (eqIdx > terminatorPos) { + // Malformed key-value pair + pos = terminatorPos + 1 + continue + } + + const key = header.substring(pos, eqIdx++).trim() + if (result[key] === undefined) { + const val = header.charCodeAt(eqIdx) === 0x22 + ? header.substring(eqIdx + 1, terminatorPos - 1).trim() + : header.substring(eqIdx, terminatorPos).trim() + + result[key] = !(val.indexOf("%") === -1) + ? tryDecodeURIComponent(val) + : val + } + + pos = terminatorPos + 1 + } + + return result +} + +const tryDecodeURIComponent = (str: string): string => { + try { + return decodeURIComponent(str) + // eslint-disable-next-line @typescript-eslint/no-unused-vars + } catch (_) { + return str + } +} diff --git a/packages/effect/src/unstable/FetchHttpClient.ts b/packages/effect/src/unstable/FetchHttpClient.ts new file mode 100644 index 0000000000..cd2a3691f5 --- /dev/null +++ b/packages/effect/src/unstable/FetchHttpClient.ts @@ -0,0 +1,68 @@ +/** + * @since 1.0.0 + */ +import * as Context from "effect/Context" +import type * as Layer from "effect/Layer" +import * as Effect from "../Effect.js" +import * as Stream from "../Stream.js" +import * as Headers from "./Headers.js" +import * as HttpClient from "./HttpClient.js" +import { RequestError } from "./HttpClientError.js" +import * as HttpClientResponse from "./HttpClientResponse.js" + +/** + * @since 1.0.0 + * @category tags + */ +export class Fetch extends Context.Tag()("effect/FetchHttpClient/Fetch") {} + +/** + * @since 1.0.0 + * @category tags + */ +export class RequestInit + extends Context.Tag()("effect/FetchHttpClient/RequestInit") +{} + +const fetch: HttpClient.HttpClient = HttpClient.make((request, url, signal, fiber) => { + const fetch: typeof globalThis.fetch = fiber.context.unsafeMap.get(Fetch.key) ?? globalThis.fetch + const options: globalThis.RequestInit = fiber.context.unsafeMap.get(RequestInit.key) ?? {} + const headers = options.headers ? Headers.merge(Headers.fromInput(options.headers), request.headers) : request.headers + const send = (body: BodyInit | undefined) => + Effect.map( + Effect.tryPromise({ + try: () => + fetch(url, { + ...options, + method: request.method, + headers, + body, + duplex: request.body._tag === "Stream" ? "half" : undefined, + signal + } as any), + catch: (cause) => + new RequestError({ + request, + reason: "Transport", + cause + }) + }), + (response) => HttpClientResponse.fromWeb(request, response) + ) + switch (request.body._tag) { + case "Raw": + case "Uint8Array": + return send(request.body.body as any) + case "FormData": + return send(request.body.formData) + case "Stream": + return Effect.flatMap(Stream.toReadableStreamEffect(request.body.stream), send) + } + return send(undefined) +}) + +/** + * @since 1.0.0 + * @category layers + */ +export const layer: Layer.Layer = HttpClient.layerMergedContext(Effect.succeed(fetch)) diff --git a/packages/effect/src/unstable/Headers.ts b/packages/effect/src/unstable/Headers.ts new file mode 100644 index 0000000000..f50dd3dc54 --- /dev/null +++ b/packages/effect/src/unstable/Headers.ts @@ -0,0 +1,268 @@ +/** + * @since 4.0.0 + */ +import * as Context from "../Context.js" +import { dual } from "../Function.js" +import { type Redactable, symbolRedactable } from "../Inspectable.js" +import type * as Option from "../Option.js" +import * as Predicate from "../Predicate.js" +import * as Record from "../Record.js" +import * as Redacted from "../Redacted.js" +import * as Schema from "../Schema.js" +import * as String from "../String.js" +import type { Mutable } from "../Types.js" + +/** + * @since 4.0.0 + * @category type ids + */ +export const TypeId: unique symbol = Symbol.for("effect/Headers") + +/** + * @since 4.0.0 + * @category type ids + */ +export type TypeId = typeof TypeId + +/** + * @since 4.0.0 + * @category refinements + */ +export const isHeaders = (u: unknown): u is Headers => Predicate.hasProperty(u, TypeId) + +/** + * @since 4.0.0 + * @category models + */ +export interface Headers extends Redactable { + readonly [TypeId]: TypeId + readonly [key: string]: string +} + +const Proto = Object.assign(Object.create(null), { + [TypeId]: TypeId, + [symbolRedactable]( + this: Headers, + context: Context.Context + ): Record> { + return redact(this, Context.get(context, CurrentRedactedNames)) + } +}) + +const make = (input: Record.ReadonlyRecord): Mutable => + Object.assign(Object.create(Proto), input) as Headers + +/** + * @since 4.0.0 + * @category schemas + */ +export const schemaFromSelf: Schema.Schema = Schema.declare(isHeaders, { + identifier: "Headers", + equivalence: () => Record.getEquivalence(String.Equivalence) +}) + +// /** +// * @since 4.0.0 +// * @category schemas +// */ +// export const schema: Schema.Schema> = Schema +// .transform( +// Schema.Record({ key: Schema.String, value: Schema.String }), +// schemaFromSelf, +// { strict: true, decode: (record) => fromInput(record), encode: identity } +// ) + +/** + * @since 4.0.0 + * @category models + */ +export type Input = + | Record.ReadonlyRecord | undefined> + | Iterable + +/** + * @since 4.0.0 + * @category constructors + */ +export const empty: Headers = Object.create(Proto) + +/** + * @since 4.0.0 + * @category constructors + */ +export const fromInput: (input?: Input) => Headers = (input) => { + if (input === undefined) { + return empty + } else if (Symbol.iterator in input) { + const out: Record = Object.create(Proto) + for (const [k, v] of input) { + out[k.toLowerCase()] = v + } + return out as Headers + } + const out: Record = Object.create(Proto) + for (const [k, v] of Object.entries(input)) { + if (Array.isArray(v)) { + out[k.toLowerCase()] = v.join(", ") + } else if (v !== undefined) { + out[k.toLowerCase()] = v as string + } + } + return out as Headers +} + +/** + * @since 4.0.0 + * @category constructors + */ +export const unsafeFromRecord = (input: Record.ReadonlyRecord): Headers => + Object.setPrototypeOf(input, Proto) as Headers + +/** + * @since 4.0.0 + * @category combinators + */ +export const has: { + (key: string): (self: Headers) => boolean + (self: Headers, key: string): boolean +} = dual< + (key: string) => (self: Headers) => boolean, + (self: Headers, key: string) => boolean +>(2, (self, key) => key.toLowerCase() in self) + +/** + * @since 4.0.0 + * @category combinators + */ +export const get: { + (key: string): (self: Headers) => Option.Option + (self: Headers, key: string): Option.Option +} = dual< + (key: string) => (self: Headers) => Option.Option, + (self: Headers, key: string) => Option.Option +>(2, (self, key) => Record.get(self as Record, key.toLowerCase())) + +/** + * @since 4.0.0 + * @category combinators + */ +export const set: { + (key: string, value: string): (self: Headers) => Headers + (self: Headers, key: string, value: string): Headers +} = dual< + (key: string, value: string) => (self: Headers) => Headers, + (self: Headers, key: string, value: string) => Headers +>(3, (self, key, value) => { + const out = make(self) + out[key.toLowerCase()] = value + return out +}) + +/** + * @since 4.0.0 + * @category combinators + */ +export const setAll: { + (headers: Input): (self: Headers) => Headers + (self: Headers, headers: Input): Headers +} = dual< + (headers: Input) => (self: Headers) => Headers, + (self: Headers, headers: Input) => Headers +>(2, (self, headers) => + make({ + ...self, + ...fromInput(headers) + })) + +/** + * @since 4.0.0 + * @category combinators + */ +export const merge: { + (headers: Headers): (self: Headers) => Headers + (self: Headers, headers: Headers): Headers +} = dual< + (headers: Headers) => (self: Headers) => Headers, + (self: Headers, headers: Headers) => Headers +>(2, (self, headers) => { + const out = make(self) + Object.assign(out, headers) + return out +}) + +/** + * @since 4.0.0 + * @category combinators + */ +export const remove: { + (key: string): (self: Headers) => Headers + (self: Headers, key: string): Headers +} = dual< + (key: string) => (self: Headers) => Headers, + (self: Headers, key: string) => Headers +>(2, (self, key) => { + const out = make(self) + // eslint-disable-next-line @typescript-eslint/no-dynamic-delete + delete out[key.toLowerCase()] + return out +}) + +/** + * @since 4.0.0 + * @category combinators + */ +export const redact: { + ( + key: string | RegExp | ReadonlyArray + ): (self: Headers) => Record + ( + self: Headers, + key: string | RegExp | ReadonlyArray + ): Record +} = dual( + 2, + ( + self: Headers, + key: string | RegExp | ReadonlyArray + ): Record => { + const out: Record = { ...self } + const modify = (key: string | RegExp) => { + if (typeof key === "string") { + const k = key.toLowerCase() + if (k in self) { + out[k] = Redacted.make(self[k]) + } + } else { + for (const name in self) { + if (key.test(name)) { + out[name] = Redacted.make(self[name]) + } + } + } + } + if (Array.isArray(key)) { + for (let i = 0; i < key.length; i++) { + modify(key[i]) + } + } else { + modify(key as string | RegExp) + } + return out + } +) + +/** + * @since 4.0.0 + * @category fiber refs + */ +export class CurrentRedactedNames extends Context.Reference< + "effect/Headers/CurrentRedactedNames", + ReadonlyArray +>("effect/Headers/CurrentRedactedNames", { + defaultValue: () => [ + "authorization", + "cookie", + "set-cookie", + "x-api-key" + ] +}) {} diff --git a/packages/effect/src/unstable/HttpBody.ts b/packages/effect/src/unstable/HttpBody.ts new file mode 100644 index 0000000000..990fd6c20c --- /dev/null +++ b/packages/effect/src/unstable/HttpBody.ts @@ -0,0 +1,339 @@ +/** + * @since 4.0.0 + */ +import * as Data from "../Data.js" +import * as Effect from "../Effect.js" +import * as FileSystem from "../FileSystem.js" +import * as Inspectable from "../Inspectable.js" +import type * as PlatformError from "../PlatformError.js" +import * as Predicate from "../Predicate.js" +import type { Issue } from "../SchemaIssue.js" +import type * as Stream_ from "../Stream.js" +import * as UrlParams from "./UrlParams.js" + +/** + * @since 4.0.0 + * @category type ids + */ +export const TypeId: unique symbol = Symbol.for("effect/HttpBody") + +/** + * @since 4.0.0 + * @category type ids + */ +export type TypeId = typeof TypeId + +/** + * @since 4.0.0 + * @category refinements + */ +export const isHttpBody = (u: unknown): u is HttpBody => Predicate.hasProperty(u, TypeId) + +/** + * @since 4.0.0 + * @category models + */ +export type HttpBody = Empty | Raw | Uint8Array | FormData | Stream + +/** + * @since 4.0.0 + */ +export declare namespace HttpBody { + /** + * @since 4.0.0 + * @category models + */ + export interface Proto extends Inspectable.Inspectable { + readonly [TypeId]: TypeId + readonly _tag: string + readonly contentType?: string | undefined + readonly contentLength?: number | undefined + } + + /** + * @since 4.0.0 + * @category models + */ + export interface FileLike { + readonly name: string + readonly lastModified: number + readonly size: number + readonly stream: () => unknown + readonly type: string + } +} + +/** + * @since 4.0.0 + * @category type ids + */ +export const ErrorTypeId: unique symbol = Symbol.for("effect/HttpBody/HttpBodyError") + +/** + * @since 4.0.0 + * @category type ids + */ +export type ErrorTypeId = typeof ErrorTypeId + +/** + * @since 4.0.0 + * @category errors + */ +export class HttpBodyError extends Data.TaggedError("HttpBodyError")<{ + readonly reason: ErrorReason + readonly cause?: unknown +}> { + /** + * @since 4.0.0 + */ + readonly [ErrorTypeId]: ErrorTypeId = ErrorTypeId +} + +/** + * @since 4.0.0 + * @category errors + */ +export type ErrorReason = { + readonly _tag: "JsonError" +} | { + readonly _tag: "SchemaError" + readonly issue: Issue +} + +abstract class Proto implements HttpBody.Proto { + readonly [TypeId]: TypeId + abstract readonly _tag: string + constructor() { + this[TypeId] = TypeId + } + abstract toJSON(): unknown + [Inspectable.NodeInspectSymbol](): unknown { + return this.toJSON() + } + toString(): string { + return Inspectable.format(this) + } +} + +/** + * @since 4.0.0 + * @category models + */ +export class Empty extends Proto { + readonly _tag = "Empty" + toJSON(): unknown { + return { + _id: "effect/HttpBody", + _tag: "Empty" + } + } +} + +/** + * @since 4.0.0 + * @category constructors + */ +export const empty: Empty = new Empty() + +/** + * @since 4.0.0 + * @category models + */ +export class Raw extends Proto { + readonly _tag = "Raw" + constructor( + readonly body: unknown, + readonly contentType: string | undefined, + readonly contentLength: number | undefined + ) { + super() + } + toJSON(): unknown { + return { + _id: "effect/HttpBody", + _tag: "Raw", + body: this.body, + contentType: this.contentType, + contentLength: this.contentLength + } + } +} + +/** + * @since 4.0.0 + * @category constructors + */ +export const raw = ( + body: unknown, + options?: { + readonly contentType?: string | undefined + readonly contentLength?: number | undefined + } | undefined +): Raw => new Raw(body, options?.contentType, options?.contentLength) + +/** + * @since 4.0.0 + * @category models + */ +export class Uint8Array extends Proto { + readonly _tag = "Uint8Array" + constructor( + readonly body: globalThis.Uint8Array, + readonly contentType: string, + readonly contentLength: number + ) { + super() + } + toJSON(): unknown { + const toString = this.contentType.startsWith("text/") || this.contentType.endsWith("json") + return { + _id: "effect/HttpBody", + _tag: "Uint8Array", + body: toString ? new TextDecoder().decode(this.body) : `Uint8Array(${this.body.length})`, + contentType: this.contentType, + contentLength: this.contentLength + } + } +} + +/** + * @since 4.0.0 + * @category constructors + */ +export const uint8Array = (body: globalThis.Uint8Array, contentType?: string): Uint8Array => + new Uint8Array(body, contentType ?? "application/octet-stream", body.length) + +const encoder = new TextEncoder() + +/** + * @since 4.0.0 + * @category constructors + */ +export const text = (body: string, contentType?: string): Uint8Array => + uint8Array(encoder.encode(body), contentType ?? "text/plain") + +/** + * @since 4.0.0 + * @category constructors + */ +export const unsafeJson = (body: unknown): Uint8Array => text(JSON.stringify(body), "application/json") + +/** + * @since 4.0.0 + * @category constructors + */ +export const json = (body: unknown): Effect.Effect => + Effect.try({ + try: () => text(JSON.stringify(body), "application/json"), + catch: (cause) => new HttpBodyError({ reason: { _tag: "JsonError" }, cause }) + }) + +// /** +// * @since 4.0.0 +// * @category constructors +// */ +// export const jsonSchema: ( +// schema: Schema.Schema +// ) => (body: A) => Effect.Effect = internal.jsonSchema + +/** + * @since 4.0.0 + * @category constructors + */ +export const urlParams = (urlParams: UrlParams.UrlParams): Uint8Array => + text(UrlParams.toString(urlParams), "application/x-www-form-urlencoded") + +/** + * @since 4.0.0 + * @category models + */ +export class FormData extends Proto { + readonly _tag = "FormData" + constructor(readonly formData: globalThis.FormData) { + super() + } + toJSON(): unknown { + return { + _id: "effect/HttpBody", + _tag: "FormData", + formData: this.formData + } + } +} + +/** + * @since 4.0.0 + * @category constructors + */ +export const formData = (body: globalThis.FormData): FormData => new FormData(body) + +/** + * @since 4.0.0 + * @category models + */ +export class Stream extends Proto { + readonly _tag = "Stream" + constructor( + readonly stream: Stream_.Stream, + readonly contentType: string, + readonly contentLength: number | undefined + ) { + super() + } + toJSON(): unknown { + return { + _id: "effect/HttpBody", + _tag: "Stream", + contentType: this.contentType, + contentLength: this.contentLength + } + } +} + +/** + * @since 4.0.0 + * @category constructors + */ +export const stream = ( + body: Stream_.Stream, + contentType?: string, + contentLength?: number +): Stream => new Stream(body, contentType ?? "application/octet-stream", contentLength) + +/** + * @since 4.0.0 + * @category constructors + */ +export const file = ( + path: string, + options?: FileSystem.StreamOptions & { readonly contentType?: string } +): Effect.Effect => + Effect.flatMap( + FileSystem.FileSystem.asEffect(), + (fs) => + Effect.map(fs.stat(path), (info) => + stream( + fs.stream(path, options), + options?.contentType, + Number(info.size) + )) + ) + +/** + * @since 4.0.0 + * @category constructors + */ +export const fileFromInfo = ( + path: string, + info: FileSystem.File.Info, + options?: FileSystem.StreamOptions & { readonly contentType?: string } +): Effect.Effect => + Effect.map( + FileSystem.FileSystem.asEffect(), + (fs) => + stream( + fs.stream(path, options), + options?.contentType, + Number(info.size) + ) + ) diff --git a/packages/effect/src/unstable/HttpClient.ts b/packages/effect/src/unstable/HttpClient.ts index e69de29bb2..12eec22cd8 100644 --- a/packages/effect/src/unstable/HttpClient.ts +++ b/packages/effect/src/unstable/HttpClient.ts @@ -0,0 +1,1136 @@ +/** + * @since 4.0.0 + */ +import * as Cause from "../Cause.js" +import * as Context from "../Context.js" +import * as Effect from "../Effect.js" +import * as Exit from "../Exit.js" +import type { Fiber } from "../Fiber.js" +import { constFalse, constTrue, dual } from "../Function.js" +import * as Inspectable from "../Inspectable.js" +import * as Layer from "../Layer.js" +import { type Pipeable, pipeArguments } from "../Pipeable.js" +import * as Predicate from "../Predicate.js" +import * as Ref from "../Ref.js" +import * as Schedule from "../Schedule.js" +import * as Stream from "../Stream.js" +import * as Tracer from "../Tracer.js" +import type { NoExcessProperties, NoInfer } from "../Types.js" +import * as Cookies from "./Cookies.js" +import * as Headers from "./Headers.js" +import * as Error from "./HttpClientError.js" +import * as HttpClientRequest from "./HttpClientRequest.js" +import * as HttpClientResponse from "./HttpClientResponse.js" +import * as HttpIncomingMessage from "./HttpIncomingMessage.js" +import * as TraceContext from "./HttpTraceContext.js" +import * as UrlParams from "./UrlParams.js" + +/** + * @since 4.0.0 + * @category type ids + */ +export const TypeId: unique symbol = Symbol.for("effect/HttpClient") + +/** + * @since 4.0.0 + * @category type ids + */ +export type TypeId = typeof TypeId + +/** + * @since 4.0.0 + * @category Guards + */ +export const isHttpClient = (u: unknown): u is HttpClient => Predicate.hasProperty(u, TypeId) + +/** + * @since 4.0.0 + * @category models + */ +export interface HttpClient extends HttpClient.With {} + +/** + * @since 4.0.0 + */ +export declare namespace HttpClient { + /** + * @since 4.0.0 + * @category models + */ + export interface With extends Pipeable, Inspectable.Inspectable { + readonly [TypeId]: TypeId + readonly preprocess: Preprocess + readonly postprocess: Postprocess + readonly execute: ( + request: HttpClientRequest.HttpClientRequest + ) => Effect.Effect + + readonly get: ( + url: string | URL, + options?: HttpClientRequest.Options.NoBody + ) => Effect.Effect + readonly head: ( + url: string | URL, + options?: HttpClientRequest.Options.NoBody + ) => Effect.Effect + readonly post: ( + url: string | URL, + options?: HttpClientRequest.Options.NoUrl + ) => Effect.Effect + readonly patch: ( + url: string | URL, + options?: HttpClientRequest.Options.NoUrl + ) => Effect.Effect + readonly put: ( + url: string | URL, + options?: HttpClientRequest.Options.NoUrl + ) => Effect.Effect + readonly del: ( + url: string | URL, + options?: HttpClientRequest.Options.NoUrl + ) => Effect.Effect + readonly options: ( + url: string | URL, + options?: HttpClientRequest.Options.NoUrl + ) => Effect.Effect + } + + /** + * @since 4.0.0 + * @category models + */ + export type Preprocess = ( + request: HttpClientRequest.HttpClientRequest + ) => Effect.Effect + + /** + * @since 4.0.0 + * @category models + */ + export type Postprocess = ( + request: Effect.Effect + ) => Effect.Effect +} + +/** + * @since 4.0.0 + * @category tags + */ +export const HttpClient: Context.Tag = Context.GenericTag( + "effect/HttpClient" +) + +/** + * @since 4.0.0 + * @category accessors + */ +export const execute = ( + request: HttpClientRequest.HttpClientRequest +): Effect.Effect => + Effect.flatMap( + HttpClient.asEffect(), + (client) => client.execute(request) + ) + +/** + * @since 4.0.0 + * @category accessors + */ +export const get = ( + url: string | URL, + options?: HttpClientRequest.Options.NoBody | undefined +): Effect.Effect< + HttpClientResponse.HttpClientResponse, + Error.HttpClientError, + HttpClient +> => + Effect.flatMap( + HttpClient.asEffect(), + (client) => client.get(url, options) + ) + +/** + * @since 4.0.0 + * @category accessors + */ +export const head = ( + url: string | URL, + options?: HttpClientRequest.Options.NoBody | undefined +): Effect.Effect< + HttpClientResponse.HttpClientResponse, + Error.HttpClientError, + HttpClient +> => + Effect.flatMap( + HttpClient.asEffect(), + (client) => client.head(url, options) + ) + +/** + * @since 4.0.0 + * @category accessors + */ +export const post = ( + url: string | URL, + options?: HttpClientRequest.Options.NoUrl | undefined +): Effect.Effect< + HttpClientResponse.HttpClientResponse, + Error.HttpClientError, + HttpClient +> => + Effect.flatMap( + HttpClient.asEffect(), + (client) => client.post(url, options) + ) + +/** + * @since 4.0.0 + * @category accessors + */ +export const patch = ( + url: string | URL, + options?: HttpClientRequest.Options.NoUrl | undefined +): Effect.Effect< + HttpClientResponse.HttpClientResponse, + Error.HttpClientError, + HttpClient +> => + Effect.flatMap( + HttpClient.asEffect(), + (client) => client.patch(url, options) + ) + +/** + * @since 4.0.0 + * @category accessors + */ +export const put = ( + url: string | URL, + options?: HttpClientRequest.Options.NoUrl | undefined +): Effect.Effect< + HttpClientResponse.HttpClientResponse, + Error.HttpClientError, + HttpClient +> => + Effect.flatMap( + HttpClient.asEffect(), + (client) => client.put(url, options) + ) + +/** + * @since 4.0.0 + * @category accessors + */ +export const del = ( + url: string | URL, + options?: HttpClientRequest.Options.NoUrl | undefined +): Effect.Effect< + HttpClientResponse.HttpClientResponse, + Error.HttpClientError, + HttpClient +> => + Effect.flatMap( + HttpClient.asEffect(), + (client) => client.del(url, options) + ) + +/** + * @since 4.0.0 + * @category accessors + */ +export const options = ( + url: string | URL, + options?: HttpClientRequest.Options.NoUrl | undefined +): Effect.Effect< + HttpClientResponse.HttpClientResponse, + Error.HttpClientError, + HttpClient +> => + Effect.flatMap( + HttpClient.asEffect(), + (client) => client.options(url, options) + ) + +/** + * @since 4.0.0 + * @category mapping & sequencing + */ +export const transform: { + ( + f: ( + effect: Effect.Effect, + request: HttpClientRequest.HttpClientRequest + ) => Effect.Effect + ): (self: HttpClient.With) => HttpClient.With + ( + self: HttpClient.With, + f: ( + effect: Effect.Effect, + request: HttpClientRequest.HttpClientRequest + ) => Effect.Effect + ): HttpClient.With +} = dual(2, ( + self: HttpClient.With, + f: ( + effect: Effect.Effect, + request: HttpClientRequest.HttpClientRequest + ) => Effect.Effect +): HttpClient.With => + makeWith( + Effect.flatMap((request) => f(self.postprocess(Effect.succeed(request)), request)), + self.preprocess + )) + +/** + * @since 4.0.0 + * @category mapping & sequencing + */ +export const transformResponse: { + ( + f: ( + effect: Effect.Effect + ) => Effect.Effect + ): (self: HttpClient.With) => HttpClient.With + ( + self: HttpClient.With, + f: ( + effect: Effect.Effect + ) => Effect.Effect + ): HttpClient.With +} = dual(2, ( + self: HttpClient.With, + f: ( + effect: Effect.Effect + ) => Effect.Effect +): HttpClient.With => makeWith((request) => f(self.postprocess(request)), self.preprocess)) + +/** + * @since 4.0.0 + * @category error handling + */ +export const catchAll: { + ( + f: (e: E) => Effect.Effect + ): (self: HttpClient.With) => HttpClient.With + ( + self: HttpClient.With, + f: (e: E) => Effect.Effect + ): HttpClient.With +} = dual( + 2, + ( + self: HttpClient.With, + f: (e: E) => Effect.Effect + ): HttpClient.With => transformResponse(self, Effect.catch(f)) +) + +/** + * @since 4.0.0 + * @category error handling + */ +export const catchTag: { + ( + tag: K, + f: (e: Extract) => Effect.Effect + ): (self: HttpClient.With) => HttpClient.With, R1 | R> + ( + self: HttpClient.With, + tag: K, + f: (e: Extract) => Effect.Effect + ): HttpClient.With, R1 | R> +} = dual( + 3, + < + R, + E, + K extends E extends { _tag: string } ? E["_tag"] : never, + R1, + E1 + >( + self: HttpClient.With, + tag: K, + f: (e: Extract) => Effect.Effect + ): HttpClient.With, R1 | R> => transformResponse(self, Effect.catchTag(tag, f)) +) + +/** + * @since 4.0.0 + * @category error handling + */ +export const catchTags: { + < + E, + Cases extends + & { + [K in Extract["_tag"]]+?: ( + error: Extract + ) => Effect.Effect + } + & (unknown extends E ? {} : { [K in Exclude["_tag"]>]: never }) + >( + cases: Cases + ): ( + self: HttpClient.With + ) => HttpClient.With< + | Exclude + | { + [K in keyof Cases]: Cases[K] extends (...args: Array) => Effect.Effect ? E : never + }[keyof Cases], + | R + | { + [K in keyof Cases]: Cases[K] extends (...args: Array) => Effect.Effect ? R : never + }[keyof Cases] + > + < + E extends { _tag: string }, + R, + Cases extends + & { + [K in Extract["_tag"]]+?: ( + error: Extract + ) => Effect.Effect + } + & (unknown extends E ? {} : { [K in Exclude["_tag"]>]: never }) + >( + self: HttpClient.With, + cases: Cases + ): HttpClient.With< + | Exclude + | { + [K in keyof Cases]: Cases[K] extends (...args: Array) => Effect.Effect ? E : never + }[keyof Cases], + | R + | { + [K in keyof Cases]: Cases[K] extends (...args: Array) => Effect.Effect ? R : never + }[keyof Cases] + > +} = dual( + 2, + < + E extends { _tag: string }, + R, + Cases extends + & { + [K in Extract["_tag"]]+?: ( + error: Extract + ) => Effect.Effect + } + & (unknown extends E ? {} + : { + [ + K in Exclude< + keyof Cases, + Extract["_tag"] + > + ]: never + }) + >( + self: HttpClient.With, + cases: Cases + ): HttpClient.With< + | Exclude + | { + [K in keyof Cases]: Cases[K] extends ( + ...args: Array + ) => Effect.Effect ? E + : never + }[keyof Cases], + | R + | { + [K in keyof Cases]: Cases[K] extends ( + ...args: Array + ) => Effect.Effect ? R + : never + }[keyof Cases] + > => transformResponse(self, Effect.catchTags(cases) as any) +) + +/** + * Filters the result of a response, or runs an alternative effect if the predicate fails. + * + * @since 4.0.0 + * @category filters + */ +export const filterOrElse: { + ( + predicate: Predicate.Predicate, + orElse: ( + response: HttpClientResponse.HttpClientResponse + ) => Effect.Effect + ): (self: HttpClient.With) => HttpClient.With + ( + self: HttpClient.With, + predicate: Predicate.Predicate, + orElse: ( + response: HttpClientResponse.HttpClientResponse + ) => Effect.Effect + ): HttpClient.With +} = dual(3, (self, f, orElse) => transformResponse(self, Effect.filterOrElse(f, orElse))) + +/** + * Filters the result of a response, or throws an error if the predicate fails. + * + * @since 4.0.0 + * @category filters + */ +export const filterOrFail: { + ( + predicate: Predicate.Predicate, + orFailWith: (response: HttpClientResponse.HttpClientResponse) => E2 + ): (self: HttpClient.With) => HttpClient.With + ( + self: HttpClient.With, + predicate: Predicate.Predicate, + orFailWith: (response: HttpClientResponse.HttpClientResponse) => E2 + ): HttpClient.With +} = dual(3, (self, f, orFailWith) => transformResponse(self, Effect.filterOrFail(f, orFailWith))) + +/** + * Filters responses by HTTP status code. + * + * @since 4.0.0 + * @category filters + */ +export const filterStatus: { + (f: (status: number) => boolean): (self: HttpClient.With) => HttpClient.With + (self: HttpClient.With, f: (status: number) => boolean): HttpClient.With +} = dual( + 2, + (self: HttpClient.With, f: (status: number) => boolean): HttpClient.With => + transformResponse(self, Effect.flatMap(HttpClientResponse.filterStatus(f))) +) + +/** + * Filters responses that return a 2xx status code. + * + * @since 4.0.0 + * @category filters + */ +export const filterStatusOk: (self: HttpClient.With) => HttpClient.With = + transformResponse(Effect.flatMap(HttpClientResponse.filterStatusOk)) + +/** + * @since 4.0.0 + * @category constructors + */ +export const makeWith = ( + postprocess: ( + request: Effect.Effect + ) => Effect.Effect, + preprocess: HttpClient.Preprocess +): HttpClient.With => { + const self = Object.create(Proto) + self.preprocess = preprocess + self.postprocess = postprocess + self.execute = function(request: HttpClientRequest.HttpClientRequest) { + return postprocess(preprocess(request)) + } + return self +} + +const Proto = { + [TypeId]: TypeId, + pipe() { + return pipeArguments(this, arguments) + }, + ...Inspectable.BaseProto, + toJSON() { + return { + _id: "effect/HttpClient" + } + }, + get(this: HttpClient, url: string | URL, options?: HttpClientRequest.Options.NoBody) { + return this.execute(HttpClientRequest.get(url, options)) + }, + head(this: HttpClient, url: string | URL, options?: HttpClientRequest.Options.NoBody) { + return this.execute(HttpClientRequest.head(url, options)) + }, + post(this: HttpClient, url: string | URL, options: HttpClientRequest.Options.NoUrl) { + return this.execute(HttpClientRequest.post(url, options)) + }, + put(this: HttpClient, url: string | URL, options: HttpClientRequest.Options.NoUrl) { + return this.execute(HttpClientRequest.put(url, options)) + }, + patch(this: HttpClient, url: string | URL, options: HttpClientRequest.Options.NoUrl) { + return this.execute(HttpClientRequest.patch(url, options)) + }, + del(this: HttpClient, url: string | URL, options?: HttpClientRequest.Options.NoUrl) { + return this.execute(HttpClientRequest.del(url, options)) + }, + options(this: HttpClient, url: string | URL, options?: HttpClientRequest.Options.NoBody) { + return this.execute(HttpClientRequest.options(url, options)) + } +} + +/** + * @since 4.0.0 + * @category constructors + */ +export const make = ( + f: ( + request: HttpClientRequest.HttpClientRequest, + url: URL, + signal: AbortSignal, + fiber: Fiber + ) => Effect.Effect +): HttpClient => + makeWith((effect) => + Effect.flatMap(effect, (request) => + Effect.withFiber((fiber) => { + const controller = new AbortController() + const urlResult = UrlParams.makeUrl(request.url, request.urlParams, request.hash) + if (urlResult._tag === "Left") { + return Effect.fail(new Error.RequestError({ request, reason: "InvalidUrl", cause: urlResult.left })) + } + const url = urlResult.right + const tracerDisabled = fiber.getRef(Tracer.DisablePropagation) || + fiber.getRef(TracerDisabledWhen)(request) + if (tracerDisabled) { + return Effect.uninterruptibleMask((restore) => + Effect.matchCauseEffect(restore(f(request, url, controller.signal, fiber as any)), { + onSuccess(response) { + responseRegistry.register(response, controller) + return Effect.succeed(new InterruptibleResponse(response, controller)) + }, + onFailure(cause) { + if (Cause.hasInterrupt(cause)) { + controller.abort() + } + return Effect.failCause(cause) + } + }) + ) + } + return Effect.useSpan( + `http.client ${request.method}`, + { kind: "client", captureStackTrace: false }, + (span) => { + span.attribute("http.request.method", request.method) + span.attribute("server.address", url.origin) + if (url.port !== "") { + span.attribute("server.port", +url.port) + } + span.attribute("url.full", url.toString()) + span.attribute("url.path", url.pathname) + span.attribute("url.scheme", url.protocol.slice(0, -1)) + const query = url.search.slice(1) + if (query !== "") { + span.attribute("url.query", query) + } + const redactedHeaderNames = fiber.getRef(Headers.CurrentRedactedNames) + const redactedHeaders = Headers.redact(request.headers, redactedHeaderNames) + for (const name in redactedHeaders) { + span.attribute(`http.request.header.${name}`, String(redactedHeaders[name])) + } + request = fiber.getRef(TracerPropagationEnabled) + ? HttpClientRequest.setHeaders(request, TraceContext.toHeaders(span)) + : request + return Effect.uninterruptibleMask((restore) => + restore(f(request, url, controller.signal, fiber as any)).pipe( + Effect.withParentSpan(span), + Effect.matchCauseEffect({ + onSuccess: (response) => { + span.attribute("http.response.status_code", response.status) + const redactedHeaders = Headers.redact(response.headers, redactedHeaderNames) + for (const name in redactedHeaders) { + span.attribute(`http.response.header.${name}`, String(redactedHeaders[name])) + } + + responseRegistry.register(response, controller) + return Effect.succeed(new InterruptibleResponse(response, controller)) + }, + onFailure(cause) { + if (Cause.hasInterrupt(cause)) { + controller.abort() + } + return Effect.failCause(cause) + } + }) + ) + ) + } + ) + })), Effect.succeed as HttpClient.Preprocess) + +/** + * Appends a transformation of the request object before sending it. + * + * @since 4.0.0 + * @category mapping & sequencing + */ +export const mapRequest: { + ( + f: (a: HttpClientRequest.HttpClientRequest) => HttpClientRequest.HttpClientRequest + ): (self: HttpClient.With) => HttpClient.With + ( + self: HttpClient.With, + f: (a: HttpClientRequest.HttpClientRequest) => HttpClientRequest.HttpClientRequest + ): HttpClient.With +} = dual( + 2, + ( + self: HttpClient.With, + f: (a: HttpClientRequest.HttpClientRequest) => HttpClientRequest.HttpClientRequest + ): HttpClient.With => makeWith(self.postprocess, (request) => Effect.map(self.preprocess(request), f)) +) + +/** + * Appends an effectful transformation of the request object before sending it. + * + * @since 4.0.0 + * @category mapping & sequencing + */ +export const mapRequestEffect: { + ( + f: (a: HttpClientRequest.HttpClientRequest) => Effect.Effect + ): (self: HttpClient.With) => HttpClient.With + ( + self: HttpClient.With, + f: (a: HttpClientRequest.HttpClientRequest) => Effect.Effect + ): HttpClient.With +} = dual( + 2, + ( + self: HttpClient.With, + f: (a: HttpClientRequest.HttpClientRequest) => Effect.Effect + ): HttpClient.With => + makeWith(self.postprocess as any, (request) => Effect.flatMap(self.preprocess(request), f)) +) + +/** + * Prepends a transformation of the request object before sending it. + * + * @since 4.0.0 + * @category mapping & sequencing + */ +export const mapRequestInput: { + ( + f: (a: HttpClientRequest.HttpClientRequest) => HttpClientRequest.HttpClientRequest + ): (self: HttpClient.With) => HttpClient.With + ( + self: HttpClient.With, + f: (a: HttpClientRequest.HttpClientRequest) => HttpClientRequest.HttpClientRequest + ): HttpClient.With +} = dual( + 2, + ( + self: HttpClient.With, + f: (a: HttpClientRequest.HttpClientRequest) => HttpClientRequest.HttpClientRequest + ): HttpClient.With => makeWith(self.postprocess, (request) => self.preprocess(f(request))) +) + +/** + * Prepends an effectful transformation of the request object before sending it. + * + * @since 4.0.0 + * @category mapping & sequencing + */ +export const mapRequestInputEffect: { + ( + f: (a: HttpClientRequest.HttpClientRequest) => Effect.Effect + ): (self: HttpClient.With) => HttpClient.With + ( + self: HttpClient.With, + f: (a: HttpClientRequest.HttpClientRequest) => Effect.Effect + ): HttpClient.With +} = dual( + 2, + ( + self: HttpClient.With, + f: (a: HttpClientRequest.HttpClientRequest) => Effect.Effect + ): HttpClient.With => + makeWith(self.postprocess as any, (request) => Effect.flatMap(f(request), self.preprocess)) +) + +/** + * @since 4.0.0 + * @category error handling + */ +export declare namespace Retry { + /** + * @since 4.0.0 + * @category error handling + */ + export type Return, O>> = HttpClient.With< + | (O extends { schedule: Schedule.Schedule } ? E | _E + : O extends { until: Predicate.Refinement } ? E2 + : E) + | (O extends { while: (...args: Array) => Effect.Effect } ? E : never) + | (O extends { until: (...args: Array) => Effect.Effect } ? E : never), + | R + | (O extends { schedule: Schedule.Schedule } ? R : never) + | (O extends { while: (...args: Array) => Effect.Effect } ? R : never) + | (O extends { until: (...args: Array) => Effect.Effect } ? R : never) + > extends infer Z ? Z : never +} + +/** + * Retries the request based on a provided schedule or policy. + * + * @since 4.0.0 + * @category error handling + */ +export const retry: { + , O>>( + options: O + ): (self: HttpClient.With) => Retry.Return + ( + policy: Schedule.Schedule, ES, R1> + ): (self: HttpClient.With) => HttpClient.With + , O>>( + self: HttpClient.With, + options: O + ): Retry.Return + ( + self: HttpClient.With, + policy: Schedule.Schedule + ): HttpClient.With +} = dual( + 2, + ( + self: HttpClient.With, + policy: Schedule.Schedule + ): HttpClient.With => transformResponse(self, Effect.retry(policy)) +) + +/** + * Retries common transient errors, such as rate limiting, timeouts or network issues. + * + * Specifying a `while` predicate allows you to consider other errors as + * transient. + * + * @since 4.0.0 + * @category error handling + */ +export const retryTransient: { + ( + options: { + readonly while?: Predicate.Predicate> + readonly schedule?: Schedule.Schedule, ES, R1> + readonly times?: number + } | Schedule.Schedule, ES, R1> + ): (self: HttpClient.With) => HttpClient.With + ( + self: HttpClient.With, + options: { + readonly while?: Predicate.Predicate> + readonly schedule?: Schedule.Schedule, ES, R1> + readonly times?: number + } | Schedule.Schedule, ES, R1> + ): HttpClient.With +} = dual( + 2, + ( + self: HttpClient.With, + options: { + readonly while?: Predicate.Predicate> + readonly schedule?: Schedule.Schedule, ES, R1> + readonly times?: number + } | Schedule.Schedule, ES, R1> + ): HttpClient.With => + transformResponse( + self, + Effect.retry({ + while: Schedule.TypeId in options || options.while === undefined + ? isTransientError + : Predicate.or(isTransientError, options.while), + schedule: Schedule.TypeId in options ? options : options.schedule, + times: Schedule.TypeId in options ? undefined : options.times + }) + ) as any +) + +/** + * Performs an additional effect after a successful request. + * + * @since 4.0.0 + * @category mapping & sequencing + */ +export const tap: { + <_, E2, R2>( + f: (response: HttpClientResponse.HttpClientResponse) => Effect.Effect<_, E2, R2> + ): (self: HttpClient.With) => HttpClient.With + ( + self: HttpClient.With, + f: (response: HttpClientResponse.HttpClientResponse) => Effect.Effect<_, E2, R2> + ): HttpClient.With +} = dual( + 2, + ( + self: HttpClient.With, + f: (response: HttpClientResponse.HttpClientResponse) => Effect.Effect<_, E2, R2> + ): HttpClient.With => transformResponse(self, Effect.tap(f)) +) + +/** + * Performs an additional effect after an unsuccessful request. + * + * @since 4.0.0 + * @category mapping & sequencing + */ +export const tapError: { + <_, E, E2, R2>( + f: (e: NoInfer) => Effect.Effect<_, E2, R2> + ): (self: HttpClient.With) => HttpClient.With + ( + self: HttpClient.With, + f: (e: NoInfer) => Effect.Effect<_, E2, R2> + ): HttpClient.With +} = dual( + 2, + ( + self: HttpClient.With, + f: (e: NoInfer) => Effect.Effect<_, E2, R2> + ): HttpClient.With => transformResponse(self, Effect.tapError(f)) +) + +/** + * Performs an additional effect on the request before sending it. + * + * @since 4.0.0 + * @category mapping & sequencing + */ +export const tapRequest: { + <_, E2, R2>( + f: (a: HttpClientRequest.HttpClientRequest) => Effect.Effect<_, E2, R2> + ): (self: HttpClient.With) => HttpClient.With + ( + self: HttpClient.With, + f: (a: HttpClientRequest.HttpClientRequest) => Effect.Effect<_, E2, R2> + ): HttpClient.With +} = dual( + 2, + ( + self: HttpClient.With, + f: (a: HttpClientRequest.HttpClientRequest) => Effect.Effect<_, E2, R2> + ): HttpClient.With => + makeWith(self.postprocess as any, (request) => Effect.tap(self.preprocess(request), f)) +) + +/** + * Associates a `Ref` of cookies with the client for handling cookies across requests. + * + * @since 4.0.0 + * @category cookies + */ +export const withCookiesRef: { + (ref: Ref.Ref): (self: HttpClient.With) => HttpClient.With + (self: HttpClient.With, ref: Ref.Ref): HttpClient.With +} = dual( + 2, + ( + self: HttpClient.With, + ref: Ref.Ref + ): HttpClient.With => + makeWith( + (request: Effect.Effect) => + Effect.tap( + self.postprocess(request), + (response) => Ref.update(ref, (cookies) => Cookies.merge(cookies, response.cookies)) + ), + (request) => + Effect.flatMap(self.preprocess(request), (request) => + Effect.map( + Ref.get(ref), + (cookies) => + Cookies.isEmpty(cookies) + ? request + : HttpClientRequest.setHeader(request, "cookie", Cookies.toCookieHeader(cookies)) + )) + ) +) + +/** + * Follows HTTP redirects up to a specified number of times. + * + * @since 4.0.0 + * @category redirects + */ +export const followRedirects: { + (maxRedirects?: number | undefined): (self: HttpClient.With) => HttpClient.With + (self: HttpClient.With, maxRedirects?: number | undefined): HttpClient.With +} = dual((args) => isHttpClient(args[0]), ( + self: HttpClient.With, + maxRedirects?: number | undefined +): HttpClient.With => + makeWith( + (request) => { + const loop = ( + request: HttpClientRequest.HttpClientRequest, + redirects: number + ): Effect.Effect => + Effect.flatMap( + self.postprocess(Effect.succeed(request)), + (response) => + response.status >= 300 && response.status < 400 && response.headers.location && + redirects < (maxRedirects ?? 10) + ? loop( + HttpClientRequest.setUrl( + request, + new URL(response.headers.location, response.request.url) + ), + redirects + 1 + ) + : Effect.succeed(response) + ) + return Effect.flatMap(request, (request) => loop(request, 0)) + }, + self.preprocess + )) + +/** + * @since 4.0.0 + * @category fiber refs + */ +export class TracerDisabledWhen extends Context.Reference< + "effect/HttpClient/TracerDisabledWhen", + Predicate.Predicate +>("effect/HttpClient/TracerDisabledWhen", { + defaultValue: () => constFalse +}) {} + +/** + * @since 4.0.0 + * @category fiber refs + */ +export class TracerPropagationEnabled extends Context.Reference("effect/HttpClient/TracerPropagationEnabled", { + defaultValue: () => constTrue +}) {} + +/** + * @since 4.0.0 + */ +export const layerMergedContext = ( + effect: Effect.Effect +): Layer.Layer => + Layer.effect( + HttpClient, + Effect.flatMap(Effect.context(), (context) => + Effect.map(effect, (client) => + transformResponse( + client, + Effect.updateContext((input: Context.Context) => Context.merge(context, input)) + ))) + ) + +// ----------------------------------------------------------------------------- +// internal +// ----------------------------------------------------------------------------- + +const responseRegistry = (() => { + if ("FinalizationRegistry" in globalThis && globalThis.FinalizationRegistry) { + const registry = new FinalizationRegistry((controller: AbortController) => { + controller.abort() + }) + return { + register(response: HttpClientResponse.HttpClientResponse, controller: AbortController) { + registry.register(response, controller, response) + }, + unregister(response: HttpClientResponse.HttpClientResponse) { + registry.unregister(response) + } + } + } + + const timers = new Map() + return { + register(response: HttpClientResponse.HttpClientResponse, controller: AbortController) { + timers.set(response, setTimeout(() => controller.abort(), 5000)) + }, + unregister(response: HttpClientResponse.HttpClientResponse) { + const timer = timers.get(response) + if (timer === undefined) return + clearTimeout(timer) + timers.delete(response) + } + } +})() + +class InterruptibleResponse implements HttpClientResponse.HttpClientResponse { + constructor( + readonly original: HttpClientResponse.HttpClientResponse, + readonly controller: AbortController + ) {} + + readonly [HttpClientResponse.TypeId]: HttpClientResponse.TypeId = HttpClientResponse.TypeId + readonly [HttpIncomingMessage.TypeId]: HttpIncomingMessage.TypeId = HttpIncomingMessage.TypeId + + private applyInterrupt(effect: Effect.Effect) { + return Effect.suspend(() => { + responseRegistry.unregister(this.original) + return Effect.onInterrupt( + effect, + Effect.sync(() => { + this.controller.abort() + }) + ) + }) + } + + get request() { + return this.original.request + } + + get status() { + return this.original.status + } + + get headers() { + return this.original.headers + } + + get cookies() { + return this.original.cookies + } + + get remoteAddress() { + return this.original.remoteAddress + } + + get formData() { + return this.applyInterrupt(this.original.formData) + } + + get text() { + return this.applyInterrupt(this.original.text) + } + + get json() { + return this.applyInterrupt(this.original.json) + } + + get urlParamsBody() { + return this.applyInterrupt(this.original.urlParamsBody) + } + + get arrayBuffer() { + return this.applyInterrupt(this.original.arrayBuffer) + } + + get stream() { + return Stream.suspend(() => { + responseRegistry.unregister(this.original) + return Stream.onExit(this.original.stream, (exit) => { + if (Exit.hasInterrupt(exit)) { + this.controller.abort() + } + return Effect.void + }) + }) + } + + toJSON() { + return this.original.toJSON() + } + + [Inspectable.NodeInspectSymbol]() { + return this.original[Inspectable.NodeInspectSymbol]() + } +} + +const isTransientError = (error: unknown) => Cause.isTimeoutError(error) || isTransientHttpError(error) + +const isTransientHttpError = (error: unknown) => + Error.isHttpClientError(error) && + ((error._tag === "RequestError" && error.reason === "Transport") || + (error._tag === "ResponseError" && error.response.status >= 429)) diff --git a/packages/effect/src/unstable/HttpClientError.ts b/packages/effect/src/unstable/HttpClientError.ts new file mode 100644 index 0000000000..d0df60a96f --- /dev/null +++ b/packages/effect/src/unstable/HttpClientError.ts @@ -0,0 +1,97 @@ +/** + * @since 4.0.0 + */ +import * as Data from "../Data.js" +import { hasProperty } from "../Predicate.js" +import type * as HttpClientRequest from "./HttpClientRequest.js" +import type * as ClientResponse from "./HttpClientResponse.js" + +/** + * @since 4.0.0 + * @category type id + */ +export const TypeId: unique symbol = Symbol.for("effect/HttpClientError") + +/** + * @since 4.0.0 + * @category type id + */ +export type TypeId = typeof TypeId + +/** + * @since 4.0.0 + * @category guards + */ +export const isHttpClientError = (u: unknown): u is HttpClientError => hasProperty(u, TypeId) + +/** + * @since 4.0.0 + * @category error + */ +export type HttpClientError = RequestError | ResponseError + +/** + * @since 4.0.0 + * @category error + */ +export class RequestError extends Data.TaggedError("RequestError")<{ + readonly request: HttpClientRequest.HttpClientRequest + readonly reason: "Transport" | "Encode" | "InvalidUrl" + readonly cause?: unknown + readonly description?: string +}> { + /** + * @since 4.0.0 + */ + readonly [TypeId] = TypeId + + /** + * @since 4.0.0 + */ + get methodAndUrl() { + return `${this.request.method} ${this.request.url}` + } + + /** + * @since 4.0.0 + */ + get message() { + return this.description ? + `${this.reason}: ${this.description} (${this.methodAndUrl})` : + `${this.reason} error (${this.methodAndUrl})` + } +} + +/** + * @since 4.0.0 + * @category error + */ +export class ResponseError extends Data.TaggedError("ResponseError")<{ + readonly request: HttpClientRequest.HttpClientRequest + readonly response: ClientResponse.HttpClientResponse + readonly reason: "StatusCode" | "Decode" | "EmptyBody" + readonly cause?: unknown + readonly description?: string +}> { + /** + * @since 4.0.0 + */ + readonly [TypeId] = TypeId + + /** + * @since 4.0.0 + */ + get methodAndUrl() { + return `${this.request.method} ${this.request.url}` + } + + /** + * @since 4.0.0 + */ + get message() { + const info = `${this.response.status} ${this.methodAndUrl}` + return this.description ? + `${this.reason}: ${this.description} (${info})` : + `${this.reason} error (${info})` + } +} diff --git a/packages/effect/src/unstable/HttpClientRequest.ts b/packages/effect/src/unstable/HttpClientRequest.ts new file mode 100644 index 0000000000..787fca4114 --- /dev/null +++ b/packages/effect/src/unstable/HttpClientRequest.ts @@ -0,0 +1,674 @@ +/** + * @since 4.0.0 + */ +import * as Effect from "../Effect.js" +import type * as FileSystem from "../FileSystem.js" +import { dual } from "../Function.js" +import * as Inspectable from "../Inspectable.js" +import * as Option from "../Option.js" +import { type Pipeable, pipeArguments } from "../Pipeable.js" +import type * as PlatformError from "../PlatformError.js" +import { hasProperty } from "../Predicate.js" +import * as Redacted from "../Redacted.js" +import type * as Stream from "../Stream.js" +import * as Headers from "./Headers.js" +import * as HttpBody from "./HttpBody.js" +import type { HttpMethod } from "./HttpMethod.js" +import * as UrlParams from "./UrlParams.js" + +/** + * @since 4.0.0 + * @category type ids + */ +export const TypeId: unique symbol = Symbol.for("effect/HttpClientRequest") + +/** + * @since 4.0.0 + * @category type ids + */ +export type TypeId = typeof TypeId + +/** + * @since 4.0.0 + * @category Guards + */ +export const isHttpClientRequest = (u: unknown): u is HttpClientRequest => hasProperty(u, TypeId) + +/** + * @since 4.0.0 + * @category models + */ +export interface HttpClientRequest extends Inspectable.Inspectable, Pipeable { + readonly [TypeId]: TypeId + readonly method: HttpMethod + readonly url: string + readonly urlParams: UrlParams.UrlParams + readonly hash: Option.Option + readonly headers: Headers.Headers + readonly body: HttpBody.HttpBody +} + +/** + * @since 4.0.0 + * @category models + */ +export interface Options { + readonly method?: HttpMethod | undefined + readonly url?: string | URL | undefined + readonly urlParams?: UrlParams.Input | undefined + readonly hash?: string | undefined + readonly headers?: Headers.Input | undefined + readonly body?: HttpBody.HttpBody | undefined + readonly accept?: string | undefined + readonly acceptJson?: boolean | undefined +} + +/** + * @since 4.0.0 + */ +export declare namespace Options { + /** + * @since 4.0.0 + * @category models + */ + export interface NoBody extends Omit {} + + /** + * @since 4.0.0 + * @category models + */ + export interface NoUrl extends Omit {} +} + +const Proto = { + [TypeId]: TypeId, + ...Inspectable.BaseProto, + toJSON(this: HttpClientRequest): unknown { + return { + _id: "effect/HttpClientRequest", + method: this.method, + url: this.url, + urlParams: this.urlParams, + hash: this.hash, + headers: Inspectable.redact(this.headers), + body: this.body.toJSON() + } + }, + pipe() { + return pipeArguments(this, arguments) + } +} + +function makeProto( + method: HttpMethod, + url: string, + urlParams: UrlParams.UrlParams, + hash: Option.Option, + headers: Headers.Headers, + body: HttpBody.HttpBody +): HttpClientRequest { + const self = Object.create(Proto) + self.method = method + self.url = url + self.urlParams = urlParams + self.hash = hash + self.headers = headers + self.body = body + return self +} + +/** + * @since 4.0.0 + * @category constructors + */ +export const empty: HttpClientRequest = makeProto( + "GET", + "", + UrlParams.empty, + Option.none(), + Headers.empty, + HttpBody.empty +) + +/** + * @since 4.0.0 + * @category constructors + */ +export const make = ( + method: M +) => +( + url: string | URL, + options?: (M extends "GET" | "HEAD" ? Options.NoBody : Options.NoUrl) | undefined +): HttpClientRequest => + modify(empty, { + method, + url, + ...(options ?? undefined) + }) + +/** + * @since 4.0.0 + * @category constructors + */ +export const get: (url: string | URL, options?: Options.NoBody) => HttpClientRequest = make("GET") + +/** + * @since 4.0.0 + * @category constructors + */ +export const post: (url: string | URL, options?: Options.NoUrl) => HttpClientRequest = make("POST") + +/** + * @since 4.0.0 + * @category constructors + */ +export const patch: (url: string | URL, options?: Options.NoUrl) => HttpClientRequest = make("PATCH") + +/** + * @since 4.0.0 + * @category constructors + */ +export const put: (url: string | URL, options?: Options.NoUrl) => HttpClientRequest = make("PUT") + +/** + * @since 4.0.0 + * @category constructors + */ +export const del: (url: string | URL, options?: Options.NoUrl) => HttpClientRequest = make("DELETE") + +/** + * @since 4.0.0 + * @category constructors + */ +export const head: (url: string | URL, options?: Options.NoBody) => HttpClientRequest = make("HEAD") + +/** + * @since 4.0.0 + * @category constructors + */ +export const options: (url: string | URL, options?: Options.NoUrl) => HttpClientRequest = make("OPTIONS") + +/** + * @since 4.0.0 + * @category combinators + */ +export const modify: { + (options: Options): (self: HttpClientRequest) => HttpClientRequest + (self: HttpClientRequest, options: Options): HttpClientRequest +} = dual(2, (self: HttpClientRequest, options: Options): HttpClientRequest => { + let result = self + + if (options.method) { + result = setMethod(result, options.method) + } + if (options.url) { + result = setUrl(result, options.url) + } + if (options.headers) { + result = setHeaders(result, options.headers) + } + if (options.urlParams) { + result = setUrlParams(result, options.urlParams) + } + if (options.hash) { + result = setHash(result, options.hash) + } + if (options.body) { + result = setBody(result, options.body) + } + if (options.accept) { + result = accept(result, options.accept) + } + if (options.acceptJson) { + result = acceptJson(result) + } + + return result +}) + +/** + * @since 4.0.0 + * @category combinators + */ +export const setMethod: { + (method: HttpMethod): (self: HttpClientRequest) => HttpClientRequest + (self: HttpClientRequest, method: HttpMethod): HttpClientRequest +} = dual( + 2, + (self: HttpClientRequest, method: HttpMethod): HttpClientRequest => + makeProto(method, self.url, self.urlParams, self.hash, self.headers, self.body) +) + +/** + * @since 4.0.0 + * @category combinators + */ +export const setHeader: { + (key: string, value: string): (self: HttpClientRequest) => HttpClientRequest + (self: HttpClientRequest, key: string, value: string): HttpClientRequest +} = dual(3, (self: HttpClientRequest, key: string, value: string): HttpClientRequest => + makeProto( + self.method, + self.url, + self.urlParams, + self.hash, + Headers.set(self.headers, key, value), + self.body + )) + +/** + * @since 4.0.0 + * @category combinators + */ +export const setHeaders: { + (input: Headers.Input): (self: HttpClientRequest) => HttpClientRequest + (self: HttpClientRequest, input: Headers.Input): HttpClientRequest +} = dual(2, (self: HttpClientRequest, input: Headers.Input): HttpClientRequest => + makeProto( + self.method, + self.url, + self.urlParams, + self.hash, + Headers.setAll(self.headers, input), + self.body + )) + +/** + * @since 4.0.0 + * @category combinators + */ +export const basicAuth: { + ( + username: string | Redacted.Redacted, + password: string | Redacted.Redacted + ): (self: HttpClientRequest) => HttpClientRequest + ( + self: HttpClientRequest, + username: string | Redacted.Redacted, + password: string | Redacted.Redacted + ): HttpClientRequest +} = dual( + 3, + ( + self: HttpClientRequest, + username: string | Redacted.Redacted, + password: string | Redacted.Redacted + ): HttpClientRequest => + setHeader(self, "Authorization", `Basic ${btoa(`${stringOrRedacted(username)}:${stringOrRedacted(password)}`)}`) +) + +/** + * @since 4.0.0 + * @category combinators + */ +export const bearerToken: { + (token: string | Redacted.Redacted): (self: HttpClientRequest) => HttpClientRequest + (self: HttpClientRequest, token: string | Redacted.Redacted): HttpClientRequest +} = dual( + 2, + (self: HttpClientRequest, token: string | Redacted.Redacted): HttpClientRequest => + setHeader(self, "Authorization", `Bearer ${stringOrRedacted(token)}`) +) + +/** + * @since 4.0.0 + * @category combinators + */ +export const accept: { + (mediaType: string): (self: HttpClientRequest) => HttpClientRequest + (self: HttpClientRequest, mediaType: string): HttpClientRequest +} = dual(2, (self: HttpClientRequest, mediaType: string): HttpClientRequest => setHeader(self, "Accept", mediaType)) + +/** + * @since 4.0.0 + * @category combinators + */ +export const acceptJson: (self: HttpClientRequest) => HttpClientRequest = accept("application/json") + +/** + * @since 4.0.0 + * @category combinators + */ +export const setUrl: { + (url: string | URL): (self: HttpClientRequest) => HttpClientRequest + (self: HttpClientRequest, url: string | URL): HttpClientRequest +} = dual(2, (self: HttpClientRequest, url: string | URL): HttpClientRequest => { + if (typeof url === "string") { + return makeProto( + self.method, + url, + self.urlParams, + self.hash, + self.headers, + self.body + ) + } + const clone = new URL(url.toString()) + const urlParams = UrlParams.fromInput(clone.searchParams) + const hash = clone.hash ? Option.some(clone.hash.slice(1)) : Option.none() + clone.search = "" + clone.hash = "" + return makeProto( + self.method, + clone.toString(), + urlParams, + hash, + self.headers, + self.body + ) +}) + +/** + * @since 4.0.0 + * @category combinators + */ +export const prependUrl: { + (path: string): (self: HttpClientRequest) => HttpClientRequest + (self: HttpClientRequest, path: string): HttpClientRequest +} = dual(2, (self: HttpClientRequest, path: string): HttpClientRequest => + makeProto( + self.method, + path.endsWith("/") && self.url.startsWith("/") ? + path + self.url.slice(1) : + path + self.url, + self.urlParams, + self.hash, + self.headers, + self.body + )) + +/** + * @since 4.0.0 + * @category combinators + */ +export const appendUrl: { + (path: string): (self: HttpClientRequest) => HttpClientRequest + (self: HttpClientRequest, path: string): HttpClientRequest +} = dual(2, (self: HttpClientRequest, path: string): HttpClientRequest => + makeProto( + self.method, + self.url.endsWith("/") && path.startsWith("/") ? + self.url + path.slice(1) : + self.url + path, + self.urlParams, + self.hash, + self.headers, + self.body + )) + +/** + * @since 4.0.0 + * @category combinators + */ +export const updateUrl: { + (f: (url: string) => string): (self: HttpClientRequest) => HttpClientRequest + (self: HttpClientRequest, f: (url: string) => string): HttpClientRequest +} = dual(2, (self: HttpClientRequest, f: (url: string) => string): HttpClientRequest => + makeProto( + self.method, + f(self.url), + self.urlParams, + self.hash, + self.headers, + self.body + )) + +/** + * @since 4.0.0 + * @category combinators + */ +export const setUrlParam: { + (key: string, value: string): (self: HttpClientRequest) => HttpClientRequest + (self: HttpClientRequest, key: string, value: string): HttpClientRequest +} = dual(3, (self: HttpClientRequest, key: string, value: string): HttpClientRequest => + makeProto( + self.method, + self.url, + UrlParams.set(self.urlParams, key, value), + self.hash, + self.headers, + self.body + )) + +/** + * @since 4.0.0 + * @category combinators + */ +export const setUrlParams: { + (input: UrlParams.Input): (self: HttpClientRequest) => HttpClientRequest + (self: HttpClientRequest, input: UrlParams.Input): HttpClientRequest +} = dual(2, (self: HttpClientRequest, input: UrlParams.Input): HttpClientRequest => + makeProto( + self.method, + self.url, + UrlParams.setAll(self.urlParams, input), + self.hash, + self.headers, + self.body + )) + +/** + * @since 4.0.0 + * @category combinators + */ +export const appendUrlParam: { + (key: string, value: string): (self: HttpClientRequest) => HttpClientRequest + (self: HttpClientRequest, key: string, value: string): HttpClientRequest +} = dual(3, (self: HttpClientRequest, key: string, value: string): HttpClientRequest => + makeProto( + self.method, + self.url, + UrlParams.append(self.urlParams, key, value), + self.hash, + self.headers, + self.body + )) + +/** + * @since 4.0.0 + * @category combinators + */ +export const appendUrlParams: { + (input: UrlParams.Input): (self: HttpClientRequest) => HttpClientRequest + (self: HttpClientRequest, input: UrlParams.Input): HttpClientRequest +} = dual(2, (self: HttpClientRequest, input: UrlParams.Input): HttpClientRequest => + makeProto( + self.method, + self.url, + UrlParams.appendAll(self.urlParams, input), + self.hash, + self.headers, + self.body + )) + +/** + * @since 4.0.0 + * @category combinators + */ +export const setHash: { + (hash: string): (self: HttpClientRequest) => HttpClientRequest + (self: HttpClientRequest, hash: string): HttpClientRequest +} = dual(2, (self: HttpClientRequest, hash: string): HttpClientRequest => + makeProto( + self.method, + self.url, + self.urlParams, + Option.some(hash), + self.headers, + self.body + )) + +/** + * @since 4.0.0 + * @category combinators + */ +export const removeHash = (self: HttpClientRequest): HttpClientRequest => + makeProto( + self.method, + self.url, + self.urlParams, + Option.none(), + self.headers, + self.body + ) + +/** + * @since 4.0.0 + * @category combinators + */ +export const setBody: { + (body: HttpBody.HttpBody): (self: HttpClientRequest) => HttpClientRequest + (self: HttpClientRequest, body: HttpBody.HttpBody): HttpClientRequest +} = dual(2, (self: HttpClientRequest, body: HttpBody.HttpBody): HttpClientRequest => + makeProto( + self.method, + self.url, + self.urlParams, + self.hash, + self.headers, + body + )) + +/** + * @since 4.0.0 + * @category combinators + */ +export const bodyUint8Array: { + (body: Uint8Array, contentType?: string): (self: HttpClientRequest) => HttpClientRequest + (self: HttpClientRequest, body: Uint8Array, contentType?: string): HttpClientRequest +} = dual( + (args) => isHttpClientRequest(args[0]), + (self: HttpClientRequest, body: Uint8Array, contentType?: string): HttpClientRequest => + setBody(self, HttpBody.uint8Array(body, contentType)) +) + +/** + * @since 4.0.0 + * @category combinators + */ +export const bodyText: { + (body: string, contentType?: string): (self: HttpClientRequest) => HttpClientRequest + (self: HttpClientRequest, body: string, contentType?: string): HttpClientRequest +} = dual( + (args) => isHttpClientRequest(args[0]), + (self: HttpClientRequest, body: string, contentType?: string): HttpClientRequest => + setBody(self, HttpBody.text(body, contentType)) +) + +/** + * @since 4.0.0 + * @category combinators + */ +export const bodyJson: { + (body: unknown): (self: HttpClientRequest) => Effect.Effect + (self: HttpClientRequest, body: unknown): Effect.Effect +} = dual( + 2, + (self: HttpClientRequest, body: unknown): Effect.Effect => + Effect.map(HttpBody.json(body), (body) => setBody(self, body)) +) + +/** + * @since 4.0.0 + * @category combinators + */ +export const bodyUnsafeJson: { + (body: unknown): (self: HttpClientRequest) => HttpClientRequest + (self: HttpClientRequest, body: unknown): HttpClientRequest +} = dual(2, (self: HttpClientRequest, body: unknown): HttpClientRequest => setBody(self, HttpBody.unsafeJson(body))) + +// /** +// * @since 4.0.0 +// * @category combinators +// */ +// export const schemaBodyJson: ( +// schema: Schema.Schema, +// options?: ParseOptions | undefined +// ) => { +// (body: A): (self: HttpClientRequest) => Effect.Effect +// (self: HttpClientRequest, body: A): Effect.Effect +// } = internal.schemaBodyJson + +/** + * @since 4.0.0 + * @category combinators + */ +export const bodyUrlParams: { + (input: UrlParams.Input): (self: HttpClientRequest) => HttpClientRequest + (self: HttpClientRequest, input: UrlParams.Input): HttpClientRequest +} = dual( + 2, + (self: HttpClientRequest, input: UrlParams.Input): HttpClientRequest => + setBody(self, HttpBody.urlParams(UrlParams.fromInput(input))) +) + +/** + * @since 4.0.0 + * @category combinators + */ +export const bodyFormData: { + (body: FormData): (self: HttpClientRequest) => HttpClientRequest + (self: HttpClientRequest, body: FormData): HttpClientRequest +} = dual(2, (self: HttpClientRequest, body: FormData): HttpClientRequest => setBody(self, HttpBody.formData(body))) + +/** + * @since 4.0.0 + * @category combinators + */ +export const bodyStream: { + ( + body: Stream.Stream, + options?: { readonly contentType?: string | undefined; readonly contentLength?: number | undefined } | undefined + ): (self: HttpClientRequest) => HttpClientRequest + ( + self: HttpClientRequest, + body: Stream.Stream, + options?: { readonly contentType?: string | undefined; readonly contentLength?: number | undefined } | undefined + ): HttpClientRequest +} = dual( + (args) => isHttpClientRequest(args[0]), + ( + self: HttpClientRequest, + body: Stream.Stream, + options?: { readonly contentType?: string | undefined; readonly contentLength?: number | undefined } | undefined + ): HttpClientRequest => + setBody( + self, + HttpBody.stream(body, options?.contentType, options?.contentLength) + ) +) + +/** + * @since 4.0.0 + * @category combinators + */ +export const bodyFile: { + ( + path: string, + options?: FileSystem.StreamOptions & { readonly contentType?: string } + ): (self: HttpClientRequest) => Effect.Effect + ( + self: HttpClientRequest, + path: string, + options?: FileSystem.StreamOptions & { readonly contentType?: string } + ): Effect.Effect +} = dual( + (args) => isHttpClientRequest(args[0]), + ( + self: HttpClientRequest, + path: string, + options?: FileSystem.StreamOptions & { readonly contentType?: string } + ): Effect.Effect => + Effect.map( + HttpBody.file(path, options), + (body) => setBody(self, body) + ) +) + +// ---------------------------------------------------------------------------- +// internal +// ---------------------------------------------------------------------------- + +const stringOrRedacted = (value: string | Redacted.Redacted): string => + typeof value === "string" ? value : Redacted.value(value) diff --git a/packages/effect/src/unstable/HttpClientResponse.ts b/packages/effect/src/unstable/HttpClientResponse.ts new file mode 100644 index 0000000000..8ca61c4107 --- /dev/null +++ b/packages/effect/src/unstable/HttpClientResponse.ts @@ -0,0 +1,330 @@ +/** + * @since 4.0.0 + */ +import * as Effect from "../Effect.js" +import { dual } from "../Function.js" +import * as Inspectable from "../Inspectable.js" +import * as Option from "../Option.js" +import * as Stream from "../Stream.js" +import type { Unify } from "../Unify.js" +import * as Cookies from "./Cookies.js" +import * as Headers from "./Headers.js" +import * as Error from "./HttpClientError.js" +import type * as HttpClientRequest from "./HttpClientRequest.js" +import * as HttpIncomingMessage from "./HttpIncomingMessage.js" +import * as UrlParams from "./UrlParams.js" + +// export { +// /** +// * @since 4.0.0 +// * @category schema +// */ +// schemaBodyJson, +// /** +// * @since 4.0.0 +// * @category schema +// */ +// schemaBodyUrlParams, +// /** +// * @since 4.0.0 +// * @category schema +// */ +// schemaHeaders +// } from "./HttpIncomingMessage.js" + +/** + * @since 4.0.0 + * @category type ids + */ +export const TypeId: unique symbol = Symbol.for("effect/HttpClientResponse") + +/** + * @since 4.0.0 + * @category type ids + */ +export type TypeId = typeof TypeId + +/** + * @since 4.0.0 + * @category models + */ +export interface HttpClientResponse extends HttpIncomingMessage.HttpIncomingMessage { + readonly [TypeId]: TypeId + readonly request: HttpClientRequest.HttpClientRequest + readonly status: number + readonly cookies: Cookies.Cookies + readonly formData: Effect.Effect +} + +/** + * @since 4.0.0 + * @category constructors + */ +export const fromWeb = (request: HttpClientRequest.HttpClientRequest, source: Response): HttpClientResponse => + new WebHttpClientResponse(request, source) + +// /** +// * @since 4.0.0 +// * @category schema +// */ +// export const schemaJson: < +// R, +// I extends { +// readonly status?: number | undefined +// readonly headers?: Readonly> | undefined +// readonly body?: unknown +// }, +// A +// >( +// schema: Schema.Schema, +// options?: ParseOptions | undefined +// ) => (self: HttpClientResponse) => Effect.Effect = +// internal.schemaJson +// +// /** +// * @since 4.0.0 +// * @category schema +// */ +// export const schemaNoBody: < +// R, +// I extends { +// readonly status?: number | undefined +// readonly headers?: Readonly> | undefined +// }, +// A +// >( +// schema: Schema.Schema, +// options?: ParseOptions | undefined +// ) => (self: HttpClientResponse) => Effect.Effect = internal.schemaNoBody + +/** + * @since 4.0.0 + * @category accessors + */ +export const stream = ( + effect: Effect.Effect +): Stream.Stream => Stream.unwrap(Effect.map(effect, (self) => self.stream)) + +/** + * @since 4.0.0 + * @category pattern matching + */ +export const matchStatus: { + < + const Cases extends { + readonly [status: number]: (_: HttpClientResponse) => any + readonly "2xx"?: (_: HttpClientResponse) => any + readonly "3xx"?: (_: HttpClientResponse) => any + readonly "4xx"?: (_: HttpClientResponse) => any + readonly "5xx"?: (_: HttpClientResponse) => any + readonly orElse: (_: HttpClientResponse) => any + } + >(cases: Cases): (self: HttpClientResponse) => Cases[keyof Cases] extends (_: any) => infer R ? Unify : never + < + const Cases extends { + readonly [status: number]: (_: HttpClientResponse) => any + readonly "2xx"?: (_: HttpClientResponse) => any + readonly "3xx"?: (_: HttpClientResponse) => any + readonly "4xx"?: (_: HttpClientResponse) => any + readonly "5xx"?: (_: HttpClientResponse) => any + readonly orElse: (_: HttpClientResponse) => any + } + >(self: HttpClientResponse, cases: Cases): Cases[keyof Cases] extends (_: any) => infer R ? Unify : never +} = dual(2, < + const Cases extends { + readonly [status: number]: (_: HttpClientResponse) => any + readonly "2xx"?: (_: HttpClientResponse) => any + readonly "3xx"?: (_: HttpClientResponse) => any + readonly "4xx"?: (_: HttpClientResponse) => any + readonly "5xx"?: (_: HttpClientResponse) => any + readonly orElse: (_: HttpClientResponse) => any + } +>(self: HttpClientResponse, cases: Cases) => { + const status = self.status + if (cases[status]) { + return cases[status](self) + } else if (status >= 200 && status < 300 && cases["2xx"]) { + return cases["2xx"](self) + } else if (status >= 300 && status < 400 && cases["3xx"]) { + return cases["3xx"](self) + } else if (status >= 400 && status < 500 && cases["4xx"]) { + return cases["4xx"](self) + } else if (status >= 500 && status < 600 && cases["5xx"]) { + return cases["5xx"](self) + } + return cases.orElse(self) +}) + +/** + * @since 4.0.0 + * @category filters + */ +export const filterStatus: { + (f: (status: number) => boolean): (self: HttpClientResponse) => Effect.Effect + (self: HttpClientResponse, f: (status: number) => boolean): Effect.Effect +} = dual( + 2, + (self: HttpClientResponse, f: (status: number) => boolean) => + Effect.suspend(() => + f(self.status) ? Effect.succeed(self) : Effect.fail( + new Error.ResponseError({ + response: self, + request: self.request, + reason: "StatusCode", + description: "invalid status code" + }) + ) + ) +) + +/** + * @since 4.0.0 + * @category filters + */ +export const filterStatusOk = (self: HttpClientResponse): Effect.Effect => + self.status >= 200 && self.status < 300 ? Effect.succeed(self) : Effect.fail( + new Error.ResponseError({ + response: self, + request: self.request, + reason: "StatusCode", + description: "non 2xx status code" + }) + ) + +// ----------------------------------------------------------------------------- +// internal +// ----------------------------------------------------------------------------- + +class WebHttpClientResponse extends Inspectable.Class implements HttpClientResponse { + readonly [HttpIncomingMessage.TypeId]: HttpIncomingMessage.TypeId + readonly [TypeId]: TypeId + + constructor( + readonly request: HttpClientRequest.HttpClientRequest, + private readonly source: globalThis.Response + ) { + super() + this[HttpIncomingMessage.TypeId] = HttpIncomingMessage.TypeId + this[TypeId] = TypeId + } + + toJSON(): unknown { + return HttpIncomingMessage.inspect(this, { + _id: "effect/HttpClientResponse", + request: this.request.toJSON(), + status: this.status + }) + } + + get status(): number { + return this.source.status + } + + get headers(): Headers.Headers { + return Headers.fromInput(this.source.headers) + } + + cachedCookies?: Cookies.Cookies + get cookies(): Cookies.Cookies { + if (this.cachedCookies) { + return this.cachedCookies + } + return this.cachedCookies = Cookies.fromSetCookie(this.source.headers.getSetCookie()) + } + + get remoteAddress(): Option.Option { + return Option.none() + } + + get stream(): Stream.Stream { + return this.source.body + ? Stream.fromReadableStream({ + evaluate: () => this.source.body!, + onError: (cause) => + new Error.ResponseError({ + request: this.request, + response: this, + reason: "Decode", + cause + }) + }) + : Stream.fail( + new Error.ResponseError({ + request: this.request, + response: this, + reason: "EmptyBody", + description: "can not create stream from empty body" + }) + ) + } + + get json(): Effect.Effect { + return Effect.flatMap(this.text, (text) => + Effect.try({ + try: () => text === "" ? null : JSON.parse(text) as unknown, + catch: (cause) => + new Error.ResponseError({ + request: this.request, + response: this, + reason: "Decode", + cause + }) + })) + } + + private textBody?: Effect.Effect + get text(): Effect.Effect { + return this.textBody ??= Effect.tryPromise({ + try: () => this.source.text(), + catch: (cause) => + new Error.ResponseError({ + request: this.request, + response: this, + reason: "Decode", + cause + }) + }).pipe(Effect.cached, Effect.runSync) + } + + get urlParamsBody(): Effect.Effect { + return Effect.flatMap(this.text, (_) => + Effect.try({ + try: () => UrlParams.fromInput(new URLSearchParams(_)), + catch: (cause) => + new Error.ResponseError({ + request: this.request, + response: this, + reason: "Decode", + cause + }) + })) + } + + private formDataBody?: Effect.Effect + get formData(): Effect.Effect { + return this.formDataBody ??= Effect.tryPromise({ + try: () => this.source.formData(), + catch: (cause) => + new Error.ResponseError({ + request: this.request, + response: this, + reason: "Decode", + cause + }) + }).pipe(Effect.cached, Effect.runSync) + } + + private arrayBufferBody?: Effect.Effect + get arrayBuffer(): Effect.Effect { + return this.arrayBufferBody ??= Effect.tryPromise({ + try: () => this.source.arrayBuffer(), + catch: (cause) => + new Error.ResponseError({ + request: this.request, + response: this, + reason: "Decode", + cause + }) + }).pipe(Effect.cached, Effect.runSync) + } +} diff --git a/packages/effect/src/unstable/HttpIncomingMessage.ts b/packages/effect/src/unstable/HttpIncomingMessage.ts new file mode 100644 index 0000000000..a30253efa7 --- /dev/null +++ b/packages/effect/src/unstable/HttpIncomingMessage.ts @@ -0,0 +1,127 @@ +/** + * @since 4.0.0 + */ +import * as Context from "../Context.js" +import * as Effect from "../Effect.js" +import * as FileSystem from "../FileSystem.js" +import { dual } from "../Function.js" +import * as Inspectable from "../Inspectable.js" +import * as Option from "../Option.js" +import type * as Stream from "../Stream.js" +import type * as Headers from "./Headers.js" +import type * as UrlParams from "./UrlParams.js" + +/** + * @since 4.0.0 + * @category type ids + */ +export const TypeId: unique symbol = Symbol.for("effect/HttpIncomingMessage") + +/** + * @since 4.0.0 + * @category type ids + */ +export type TypeId = typeof TypeId + +/** + * @since 4.0.0 + * @category models + */ +export interface HttpIncomingMessage extends Inspectable.Inspectable { + readonly [TypeId]: TypeId + readonly headers: Headers.Headers + readonly remoteAddress: Option.Option + readonly json: Effect.Effect + readonly text: Effect.Effect + readonly urlParamsBody: Effect.Effect + readonly arrayBuffer: Effect.Effect + readonly stream: Stream.Stream +} + +// /** +// * @since 4.0.0 +// * @category schema +// */ +// export const schemaBodyJson = (schema: Schema.Schema, options?: ParseOptions | undefined) => { +// const parse = Schema.decodeUnknown(schema, options) +// return (self: HttpIncomingMessage): Effect.Effect => +// Effect.flatMap(self.json, parse) +// } + +// /** +// * @since 4.0.0 +// * @category schema +// */ +// export const schemaBodyUrlParams = < +// A, +// I extends Readonly | undefined>>, +// R +// >( +// schema: Schema.Schema, +// options?: ParseOptions | undefined +// ) => { +// const decode = UrlParams.schemaStruct(schema, options) +// return (self: HttpIncomingMessage): Effect.Effect => +// Effect.flatMap(self.urlParamsBody, decode) +// } + +// /** +// * @since 4.0.0 +// * @category schema +// */ +// export const schemaHeaders = >, R>( +// schema: Schema.Schema, +// options?: ParseOptions | undefined +// ) => { +// const parse = Schema.decodeUnknown(schema, options) +// return (self: HttpIncomingMessage): Effect.Effect => parse(self.headers) +// } + +/** + * @since 4.0.0 + * @category References + */ +export class MaxBodySize extends Context.Reference("effect/HttpIncomingMessage/MaxBodySize", { + defaultValue: () => Option.none() +}) {} + +/** + * @since 4.0.0 + * @category fiber refs + */ +export const withMaxBodySize = dual< + (size: Option.Option) => (effect: Effect.Effect) => Effect.Effect, + (effect: Effect.Effect, size: Option.Option) => Effect.Effect +>(2, (effect, size) => Effect.provideService(effect, MaxBodySize, Option.map(size, FileSystem.Size))) + +/** + * @since 4.0.0 + */ +export const inspect = (self: HttpIncomingMessage, that: object): object => { + const contentType = self.headers["content-type"] ?? "" + let body: unknown + if (contentType.includes("application/json")) { + try { + body = Effect.runSync(self.json) + // eslint-disable-next-line @typescript-eslint/no-unused-vars + } catch (_) { + // + } + } else if (contentType.includes("text/") || contentType.includes("urlencoded")) { + try { + body = Effect.runSync(self.text) + // eslint-disable-next-line @typescript-eslint/no-unused-vars + } catch (_) { + // + } + } + const obj: any = { + ...that, + headers: Inspectable.redact(self.headers), + remoteAddress: self.remoteAddress.toJSON() + } + if (body !== undefined) { + obj.body = body + } + return obj +} diff --git a/packages/effect/src/unstable/HttpMethod.ts b/packages/effect/src/unstable/HttpMethod.ts new file mode 100644 index 0000000000..9c29d32382 --- /dev/null +++ b/packages/effect/src/unstable/HttpMethod.ts @@ -0,0 +1,66 @@ +/** + * @since 4.0.0 + * @category models + */ + +/** + * @since 4.0.0 + * @category models + */ +export type HttpMethod = + | "GET" + | "POST" + | "PUT" + | "DELETE" + | "PATCH" + | "HEAD" + | "OPTIONS" + +/** + * @since 4.0.0 + * @category models + */ +export declare namespace HttpMethod { + /** + * @since 4.0.0 + * @category models + */ + export type NoBody = "GET" | "HEAD" | "OPTIONS" + + /** + * @since 4.0.0 + * @category models + */ + export type WithBody = Exclude +} + +/** + * @since 4.0.0 + */ +export const hasBody = (method: HttpMethod): boolean => method !== "GET" && method !== "HEAD" && method !== "OPTIONS" + +/** + * @since 4.0.0 + */ +export const all: ReadonlySet = new Set(["GET", "POST", "PUT", "DELETE", "PATCH", "HEAD", "OPTIONS"]) + +/** + * Tests if a value is a `HttpMethod`. + * + * **Example** + * + * ```ts + * import * as HttpMethod from "effect/unstable/HttpMethod" + * + * console.log(HttpMethod.isHttpMethod("GET")) + * // true + * console.log(HttpMethod.isHttpMethod("get")) + * // false + * console.log(HttpMethod.isHttpMethod(1)) + * // false + * ``` + * + * @since 4.0.0 + * @category refinements + */ +export const isHttpMethod = (u: unknown): u is HttpMethod => all.has(u as HttpMethod) diff --git a/packages/effect/src/unstable/HttpTraceContext.ts b/packages/effect/src/unstable/HttpTraceContext.ts new file mode 100644 index 0000000000..182ae7ccbb --- /dev/null +++ b/packages/effect/src/unstable/HttpTraceContext.ts @@ -0,0 +1,109 @@ +/** + * @since 4.0.0 + */ +import * as Option from "../Option.js" +import * as Tracer from "../Tracer.js" +import * as Headers from "./Headers.js" + +/** + * @since 4.0.0 + * @category models + */ +export interface FromHeaders { + (headers: Headers.Headers): Option.Option +} + +/** + * @since 4.0.0 + * @category encoding + */ +export const toHeaders = (span: Tracer.Span): Headers.Headers => + Headers.unsafeFromRecord({ + b3: `${span.traceId}-${span.spanId}-${span.sampled ? "1" : "0"}${ + span.parent._tag === "Some" ? `-${span.parent.value.spanId}` : "" + }`, + traceparent: `00-${span.traceId}-${span.spanId}-${span.sampled ? "01" : "00"}` + }) + +/** + * @since 4.0.0 + * @category decoding + */ +export const fromHeaders = (headers: Headers.Headers): Option.Option => { + let span = w3c(headers) + if (span._tag === "Some") { + return span + } + span = b3(headers) + if (span._tag === "Some") { + return span + } + return xb3(headers) +} + +/** + * @since 4.0.0 + * @category decoding + */ +export const b3: FromHeaders = (headers) => { + if (!("b3" in headers)) { + return Option.none() + } + const parts = headers["b3"].split("-") + if (parts.length < 2) { + return Option.none() + } + return Option.some(Tracer.externalSpan({ + traceId: parts[0], + spanId: parts[1], + sampled: parts[2] ? parts[2] === "1" : true + })) +} + +/** + * @since 4.0.0 + * @category decoding + */ +export const xb3: FromHeaders = (headers) => { + if (!(headers["x-b3-traceid"]) || !(headers["x-b3-spanid"])) { + return Option.none() + } + return Option.some(Tracer.externalSpan({ + traceId: headers["x-b3-traceid"], + spanId: headers["x-b3-spanid"], + sampled: headers["x-b3-sampled"] ? headers["x-b3-sampled"] === "1" : true + })) +} + +const w3cTraceId = /^[0-9a-f]{32}$/i +const w3cSpanId = /^[0-9a-f]{16}$/i + +/** + * @since 4.0.0 + * @category decoding + */ +export const w3c: FromHeaders = (headers) => { + if (!(headers["traceparent"])) { + return Option.none() + } + const parts = headers["traceparent"].split("-") + if (parts.length !== 4) { + return Option.none() + } + const [version, traceId, spanId, flags] = parts + switch (version) { + case "00": { + if (w3cTraceId.test(traceId) === false || w3cSpanId.test(spanId) === false) { + return Option.none() + } + return Option.some(Tracer.externalSpan({ + traceId, + spanId, + sampled: (parseInt(flags, 16) & 1) === 1 + })) + } + default: { + return Option.none() + } + } +} diff --git a/packages/effect/src/unstable/UrlParams.ts b/packages/effect/src/unstable/UrlParams.ts new file mode 100644 index 0000000000..a50f5ae7b8 --- /dev/null +++ b/packages/effect/src/unstable/UrlParams.ts @@ -0,0 +1,328 @@ +/** + * @since 4.0.0 + */ +import * as Arr from "../Array.js" +import * as Either from "../Either.js" +import { dual } from "../Function.js" +import * as Option from "../Option.js" + +/** + * @since 4.0.0 + * @category models + */ +export interface UrlParams extends ReadonlyArray {} + +/** + * @since 4.0.0 + * @category models + */ +export type Input = + | CoercibleRecord + | Iterable + | URLSearchParams + +/** + * @since 4.0.0 + * @category models + */ +export type Coercible = string | number | bigint | boolean | null | undefined + +/** + * @since 4.0.0 + * @category models + */ +export interface CoercibleRecord { + readonly [key: string]: Coercible | ReadonlyArray | CoercibleRecord +} + +/** + * @since 4.0.0 + * @category constructors + */ +export const fromInput = (input: Input): UrlParams => { + const parsed = fromInputNested(input) + const out: Array<[string, string]> = [] + for (let i = 0; i < parsed.length; i++) { + if (Array.isArray(parsed[i][0])) { + const [keys, value] = parsed[i] as [Array, string] + out.push([`${keys[0]}[${keys.slice(1).join("][")}]`, value]) + } else { + out.push(parsed[i] as [string, string]) + } + } + return out +} + +const fromInputNested = (input: Input): Array<[string | Array, any]> => { + const entries = Symbol.iterator in input ? Arr.fromIterable(input) : Object.entries(input) + const out: Array<[string | Array, string]> = [] + for (const [key, value] of entries) { + if (Array.isArray(value)) { + for (let i = 0; i < value.length; i++) { + if (value[i] !== undefined) { + out.push([key, String(value[i])]) + } + } + } else if (typeof value === "object") { + const nested = fromInputNested(value as CoercibleRecord) + for (const [k, v] of nested) { + out.push([[key, ...(typeof k === "string" ? [k] : k)], v]) + } + } else if (value !== undefined) { + out.push([key, String(value)]) + } + } + return out +} + +// /** +// * @since 4.0.0 +// * @category schemas +// */ +// export const schema: Schema.Schema> = Schema.Array( +// Schema.Tuple(Schema.String, Schema.String) +// ).annotations({ identifier: "UrlParams" }) + +/** + * @since 4.0.0 + * @category constructors + */ +export const empty: UrlParams = [] + +/** + * @since 4.0.0 + * @category combinators + */ +export const getAll: { + (key: string): (self: UrlParams) => ReadonlyArray + (self: UrlParams, key: string): ReadonlyArray +} = dual( + 2, + (self: UrlParams, key: string): ReadonlyArray => + Arr.reduce(self, [] as Array, (acc, [k, value]) => { + if (k === key) { + acc.push(value) + } + return acc + }) +) + +/** + * @since 4.0.0 + * @category combinators + */ +export const getFirst: { + (key: string): (self: UrlParams) => Option.Option + (self: UrlParams, key: string): Option.Option +} = dual(2, (self: UrlParams, key: string): Option.Option => + Option.map( + Arr.findFirst(self, ([k]) => k === key), + ([, value]) => value + )) + +/** + * @since 4.0.0 + * @category combinators + */ +export const getLast: { + (key: string): (self: UrlParams) => Option.Option + (self: UrlParams, key: string): Option.Option +} = dual(2, (self: UrlParams, key: string): Option.Option => + Option.map( + Arr.findLast(self, ([k]) => k === key), + ([, value]) => value + )) + +/** + * @since 4.0.0 + * @category combinators + */ +export const set: { + (key: string, value: Coercible): (self: UrlParams) => UrlParams + (self: UrlParams, key: string, value: Coercible): UrlParams +} = dual(3, (self: UrlParams, key: string, value: Coercible): UrlParams => + Arr.append( + Arr.filter(self, ([k]) => k !== key), + [key, String(value)] + )) + +/** + * @since 4.0.0 + * @category combinators + */ +export const setAll: { + (input: Input): (self: UrlParams) => UrlParams + (self: UrlParams, input: Input): UrlParams +} = dual(2, (self: UrlParams, input: Input): UrlParams => { + const toSet = fromInput(input) + const keys = toSet.map(([k]) => k) + return Arr.appendAll( + Arr.filter(self, ([k]) => keys.includes(k)), + toSet + ) +}) + +/** + * @since 4.0.0 + * @category combinators + */ +export const append: { + (key: string, value: Coercible): (self: UrlParams) => UrlParams + (self: UrlParams, key: string, value: Coercible): UrlParams +} = dual(3, (self: UrlParams, key: string, value: Coercible): UrlParams => + Arr.append( + self, + [key, String(value)] + )) + +/** + * @since 4.0.0 + * @category combinators + */ +export const appendAll: { + (input: Input): (self: UrlParams) => UrlParams + (self: UrlParams, input: Input): UrlParams +} = dual(2, (self: UrlParams, input: Input): UrlParams => Arr.appendAll(self, fromInput(input))) + +/** + * @since 4.0.0 + * @category combinators + */ +export const remove: { + (key: string): (self: UrlParams) => UrlParams + (self: UrlParams, key: string): UrlParams +} = dual(2, (self: UrlParams, key: string): UrlParams => Arr.filter(self, ([k]) => k !== key)) + +/** + * @since 4.0.0 + * @category conversions + */ +export const makeUrl = (url: string, params: UrlParams, hash: Option.Option): Either.Either => { + try { + const urlInstance = new URL(url, baseUrl()) + for (let i = 0; i < params.length; i++) { + const [key, value] = params[i] + if (value !== undefined) { + urlInstance.searchParams.append(key, value) + } + } + if (hash._tag === "Some") { + urlInstance.hash = hash.value + } + return Either.right(urlInstance) + } catch (e) { + return Either.left(e as Error) + } +} + +/** + * @since 4.0.0 + * @category conversions + */ +export const toString = (self: UrlParams): string => new URLSearchParams(self as any).toString() + +const baseUrl = (): string | undefined => { + if ( + "location" in globalThis && + globalThis.location !== undefined && + globalThis.location.origin !== undefined && + globalThis.location.pathname !== undefined + ) { + return location.origin + location.pathname + } + return undefined +} + +/** + * Builds a `Record` containing all the key-value pairs in the given `UrlParams` + * as `string` (if only one value for a key) or a `NonEmptyArray` + * (when more than one value for a key) + * + * **Example** + * + * ```ts + * import * as assert from "node:assert" + * import * as UrlParams from "effect/unstable/UrlParams" + * + * const urlParams = UrlParams.fromInput({ a: 1, b: true, c: "string", e: [1, 2, 3] }) + * const result = UrlParams.toRecord(urlParams) + * + * assert.deepStrictEqual( + * result, + * { "a": "1", "b": "true", "c": "string", "e": ["1", "2", "3"] } + * ) + * ``` + * + * @since 4.0.0 + * @category conversions + */ +export const toRecord = (self: UrlParams): Record> => { + const out: Record> = {} + for (const [k, value] of self) { + const curr = out[k] + if (curr === undefined) { + out[k] = value + } else if (typeof curr === "string") { + out[k] = [curr, value] + } else { + curr.push(value) + } + } + return out +} + +// /** +// * @since 4.0.0 +// * @category schema +// */ +// export const schemaJson = (schema: Schema.Schema, options?: ParseOptions | undefined): { +// ( +// field: string +// ): (self: UrlParams) => Effect.Effect +// ( +// self: UrlParams, +// field: string +// ): Effect.Effect +// } => { +// const parse = Schema.decodeUnknown(Schema.parseJson(schema), options) +// return dual< +// (field: string) => (self: UrlParams) => Effect.Effect, +// (self: UrlParams, field: string) => Effect.Effect +// >(2, (self, field) => parse(Option.getOrElse(getLast(self, field), () => ""))) +// } + +// /** +// * Extract schema from all key-value pairs in the given `UrlParams`. +// * +// * **Example** +// * +// * ```ts +// * import * as assert from "node:assert" +// * import { Effect, Schema } from "effect" +// * import * as UrlParams from "effect/unstable/UrlParams" +// * +// * Effect.gen(function* () { +// * const urlParams = UrlParams.fromInput({ "a": [10, "string"], "b": false }) +// * const result = yield* UrlParams.schemaStruct(Schema.Struct({ +// * a: Schema.Tuple(Schema.NumberFromString, Schema.String), +// * b: Schema.BooleanFromString +// * }))(urlParams) +// * +// * assert.deepStrictEqual(result, { +// * a: [10, "string"], +// * b: false +// * }) +// * }) +// * ``` +// * +// * @since 4.0.0 +// * @category schema +// */ +// export const schemaStruct = | undefined>, R>( +// schema: Schema.Schema, +// options?: ParseOptions | undefined +// ) => +// (self: UrlParams): Effect.Effect => { +// const parse = Schema.decodeUnknown(schema, options) +// return parse(toRecord(self)) +// } diff --git a/packages/platform-bun/src/index.ts b/packages/platform-bun/src/index.ts index 11dc145941..d8b16bb118 100644 --- a/packages/platform-bun/src/index.ts +++ b/packages/platform-bun/src/index.ts @@ -12,3 +12,13 @@ export * as BunPath from "./BunPath.js" * @since 1.0.0 */ export * as BunRuntime from "./BunRuntime.js" + +/** + * @since 1.0.0 + */ +export * as BunSink from "./BunSink.js" + +/** + * @since 1.0.0 + */ +export * as BunStream from "./BunStream.js" diff --git a/packages/platform-node-shared/src/NodeFileSystem.ts b/packages/platform-node-shared/src/NodeFileSystem.ts index 3d7c3c21bc..bbf256fe1d 100644 --- a/packages/platform-node-shared/src/NodeFileSystem.ts +++ b/packages/platform-node-shared/src/NodeFileSystem.ts @@ -3,7 +3,7 @@ */ import type * as Context from "effect/Context" import * as Effect from "effect/Effect" -import { effectify } from "effect/Effectify" +import { effectify } from "effect/Effect" import * as Exit from "effect/Exit" import * as FileSystem from "effect/FileSystem" import { pipe } from "effect/Function" diff --git a/packages/platform-node/src/index.ts b/packages/platform-node/src/index.ts index 46d26916c4..f7b3c07dc9 100644 --- a/packages/platform-node/src/index.ts +++ b/packages/platform-node/src/index.ts @@ -12,3 +12,13 @@ export * as NodePath from "./NodePath.js" * @since 1.0.0 */ export * as NodeRuntime from "./NodeRuntime.js" + +/** + * @since 1.0.0 + */ +export * as NodeSink from "./NodeSink.js" + +/** + * @since 1.0.0 + */ +export * as NodeStream from "./NodeStream.js" diff --git a/scratchpad/http-client.ts b/scratchpad/http-client.ts new file mode 100644 index 0000000000..1bf5bf485b --- /dev/null +++ b/scratchpad/http-client.ts @@ -0,0 +1,16 @@ +import { NodeRuntime } from "@effect/platform-node" +import { Effect } from "effect" +import * as FetchHttpClient from "effect/unstable/FetchHttpClient" +import * as HttpClient from "effect/unstable/HttpClient" + +Effect.gen(function*() { + const client = yield* HttpClient.HttpClient + + const res = yield* client.get("https://jsonplaceholder.typicode.com/posts/1") + const json = yield* res.json + + yield* Effect.log(json) +}).pipe( + Effect.provide(FetchHttpClient.layer), + NodeRuntime.runMain +)

, f: Fn] ) => ( self: Matcher ) => Matcher< I, Types.AddWithout>>, Types.ApplyFilters>>>, - B | A, + ReturnType | A, Pr, Ret > = internal.tag /** - * @category combinators - * @since 1.0.0 + * Matches values where the `_tag` field starts with a given prefix. + * + * **Details** + * + * This function allows you to match on values in a **discriminated union** + * based on whether the `_tag` field starts with a specified prefix. It is + * useful for handling hierarchical or namespaced tags, where multiple related + * cases share a common prefix. + * + * @example + ```ts + * import { Match, pipe } from "effect" + * + * const match = pipe( + * Match.type<{ _tag: "A" } | { _tag: "B" } | { _tag: "A.A" } | {}>(), + * Match.tagStartsWith("A", (_) => 1 as const), + * Match.tagStartsWith("B", (_) => 2 as const), + * Match.orElse((_) => 3 as const) + * ) + * + * console.log(match({ _tag: "A" })) // 1 + * console.log(match({ _tag: "B" })) // 2 + * console.log(match({ _tag: "A.A" })) // 1 + * ``` + * + * @category Defining patterns + * @since 4.0.0 */ -export const tagStartsWith: ( +export const tagStartsWith: < + R, + P extends string, + Ret, + Fn extends (_: Extract>) => Ret +>( pattern: P, - f: (_: Extract, Record<"_tag", `${P}${string}`>>) => B + f: Fn ) => ( self: Matcher ) => Matcher< I, Types.AddWithout>>, Types.ApplyFilters>>>, - B | A, + ReturnType | A, Pr, Ret -> = internal.tagStartsWith as any +> = internal.tagStartsWith /** - * @category combinators - * @since 1.0.0 + * Matches values based on their `_tag` field, mapping each tag to a + * corresponding handler. + * + * **Details** + * + * This function provides a way to handle discriminated unions by mapping `_tag` + * values to specific functions. Each handler receives the matched value and + * returns a transformed result. If all possible tags are handled, you can + * enforce exhaustiveness using `Match.exhaustive` to ensure no case is missed. + * + * @example + * ```ts + * import { Match, pipe } from "effect" + * + * const match = pipe( + * Match.type<{ _tag: "A"; a: string } | { _tag: "B"; b: number } | { _tag: "C"; c: boolean }>(), + * Match.tags({ + * A: (a) => a.a, + * B: (b) => b.b, + * C: (c) => c.c + * }), + * Match.exhaustive + * ) + * ``` + * + * @category Defining patterns + * @since 4.0.0 */ export const tags: < R, Ret, P extends & { readonly [Tag in Types.Tags<"_tag", R> & string]?: ((_: Extract>) => Ret) | undefined } - & Readonly>, never>> + & { readonly [Tag in Exclude>]: never } >( fields: P ) => ( @@ -351,15 +846,40 @@ export const tags: < > = internal.tags /** - * @category combinators - * @since 1.0.0 + * Matches values based on their `_tag` field and requires handling of all + * possible cases. + * + * **Details** + * + * This function is designed for **discriminated unions** where every possible + * `_tag` value must have a corresponding handler. Unlike {@link tags}, this + * function ensures **exhaustiveness**, meaning all cases must be explicitly + * handled. If a `_tag` value is missing from the mapping, TypeScript will + * report an error. + * + * @example + * ```ts + * import { Match, pipe } from "effect" + * + * const match = pipe( + * Match.type<{ _tag: "A"; a: string } | { _tag: "B"; b: number } | { _tag: "C"; c: boolean }>(), + * Match.tagsExhaustive({ + * A: (a) => a.a, + * B: (b) => b.b, + * C: (c) => c.c + * }) + * ) + * ``` + * + * @category Defining patterns + * @since 4.0.0 */ export const tagsExhaustive: < R, Ret, P extends & { readonly [Tag in Types.Tags<"_tag", R> & string]: (_: Extract>) => Ret } - & Readonly>, never>> + & { readonly [Tag in Exclude>]: never } >( fields: P ) => ( @@ -368,14 +888,44 @@ export const tagsExhaustive: < internal.tagsExhaustive /** - * @category combinators - * @since 1.0.0 + * Excludes a specific value from matching while allowing all others. + * + * **Details** + * + * This function is useful when you need to **handle all values except one or + * more specific cases**. Instead of listing all possible matches manually, this + * function simplifies the logic by allowing you to specify values to exclude. + * Any excluded value will bypass the provided function and continue matching + * through other cases. + * + * **Example** (Ignoring a Specific Value) + * + * ```ts + * import { Match } from "effect" + * + * // Create a matcher for string or number values + * const match = Match.type().pipe( + * // Match any value except "hi", returning "ok" + * Match.not("hi", () => "ok"), + * // Fallback case for when the value is "hi" + * Match.orElse(() => "fallback") + * ) + * + * console.log(match("hello")) + * // Output: "ok" + * + * console.log(match("hi")) + * // Output: "fallback" + * ``` + * + * @category Defining patterns + * @since 4.0.0 */ export const not: < R, const P extends Types.PatternPrimitive | Types.PatternBase, Ret, - Fn extends (_: Exclude>>) => Ret + Fn extends (_: Types.NotMatch) => Ret >( pattern: P, f: Fn @@ -391,54 +941,70 @@ export const not: < > = internal.not /** - * @category predicates - * @since 1.0.0 + * Matches non-empty strings. + * + * @category Predicates + * @since 4.0.0 */ export const nonEmptyString: SafeRefinement = internal.nonEmptyString /** - * @category predicates - * @since 1.0.0 + * Matches a specific set of literal values (e.g., `Match.is("a", 42, true)`). + * + * @category Predicates + * @since 4.0.0 */ export const is: < Literals extends ReadonlyArray ->(...literals: Literals) => Predicate.Refinement = internal.is +>(...literals: Literals) => SafeRefinement = internal.is /** - * @category predicates - * @since 1.0.0 + * Matches values of type `string`. + * + * @category Predicates + * @since 4.0.0 */ export const string: Predicate.Refinement = Predicate.isString /** - * @category predicates - * @since 1.0.0 + * Matches values of type `number`. + * + * @category Predicates + * @since 4.0.0 */ export const number: Predicate.Refinement = Predicate.isNumber /** - * @category predicates - * @since 1.0.0 + * Matches any value without restrictions. + * + * @category Predicates + * @since 4.0.0 */ export const any: SafeRefinement = internal.any /** - * @category predicates - * @since 1.0.0 + * Matches any defined (non-null and non-undefined) value. + * + * @category Predicates + * @since 4.0.0 */ export const defined: (u: A) => u is A & {} = internal.defined /** - * @category predicates - * @since 1.0.0 + * Matches values of type `boolean`. + * + * @category Predicates + * @since 4.0.0 */ export const boolean: Predicate.Refinement = Predicate.isBoolean const _undefined: Predicate.Refinement = Predicate.isUndefined export { /** - * @category predicates - * @since 1.0.0 + * Matches the value `undefined`. + * + * @category Predicates + * @since 4.0.0 */ _undefined as undefined } @@ -446,55 +1012,96 @@ export { const _null: Predicate.Refinement = Predicate.isNull export { /** - * @category predicates - * @since 1.0.0 + * Matches the value `null`. + * + * @category Predicates + * @since 4.0.0 */ _null as null } /** - * @category predicates - * @since 1.0.0 + * Matches values of type `bigint`. + * + * @category Predicates + * @since 4.0.0 */ export const bigint: Predicate.Refinement = Predicate.isBigInt /** - * @category predicates - * @since 1.0.0 + * Matches values of type `symbol`. + * + * @category Predicates + * @since 4.0.0 */ export const symbol: Predicate.Refinement = Predicate.isSymbol /** - * @category predicates - * @since 1.0.0 + * Matches values that are instances of `Date`. + * + * @category Predicates + * @since 4.0.0 */ export const date: Predicate.Refinement = Predicate.isDate /** - * @category predicates - * @since 1.0.0 + * Matches objects where keys are `string` or `symbol` and values are `unknown`. + * + * @category Predicates + * @since 4.0.0 */ -export const record: Predicate.Refinement> = Predicate.isRecord +export const record: Predicate.Refinement = Predicate.isRecord /** - * @category predicates - * @since 1.0.0 + * Matches instances of a given class. + * + * @category Predicates + * @since 4.0.0 */ export const instanceOf: any>( constructor: A ) => SafeRefinement, never> = internal.instanceOf /** - * @category predicates - * @since 1.0.0 + * @category Predicates + * @since 4.0.0 */ export const instanceOfUnsafe: any>( constructor: A ) => SafeRefinement, InstanceType> = internal.instanceOf /** - * @category conversions - * @since 1.0.0 + * Provides a fallback value when no patterns match. + * + * **Details** + * + * This function ensures that a matcher always returns a valid result, even if + * no defined patterns match. It acts as a default case, similar to the + * `default` clause in a `switch` statement or the final `else` in an `if-else` + * chain. + * + * **Example** (Providing a Default Value When No Patterns Match) + * + * ```ts + * import { Match } from "effect" + * + * // Create a matcher for string or number values + * const match = Match.type().pipe( + * // Match when the value is "a" + * Match.when("a", () => "ok"), + * // Fallback when no patterns match + * Match.orElse(() => "fallback") + * ) + * + * console.log(match("a")) + * // Output: "ok" + * + * console.log(match("b")) + * // Output: "fallback" + * ``` + * + * @category Completion + * @since 4.0.0 */ export const orElse: Ret>( f: F @@ -502,53 +1109,155 @@ export const orElse: Ret>( self: Matcher ) => [Pr] extends [never] ? (input: I) => Unify | A> : Unify | A> = internal.orElse +// TODO(4.0): Rename to "orThrow"? Like Either.getOrThrow /** - * @category conversions - * @since 1.0.0 + * Throws an error if no pattern matches. + * + * **Details** + * + * This function finalizes a matcher by ensuring that if no patterns match, an + * error is thrown. It is useful when all cases should be covered, and any + * unexpected input should trigger an error instead of returning a default + * value. + * + * When used, this function removes the need for an explicit fallback case and + * ensures that an unmatched value is never silently ignored. + * + * @category Completion + * @since 4.0.0 */ export const orElseAbsurd: ( self: Matcher ) => [Pr] extends [never] ? (input: I) => Unify : Unify = internal.orElseAbsurd /** - * @category conversions - * @since 1.0.0 + * Wraps the match result in an `Either`, distinguishing matched and unmatched + * cases. + * + * **Details** + * + * This function ensures that the result of a matcher is always wrapped in an + * `Either`, allowing clear differentiation between successful matches + * (`Right(value)`) and cases where no pattern matched (`Left(unmatched + * value)`). + * + * This approach is particularly useful when handling optional values or when an + * unmatched case should be explicitly handled rather than returning a default + * value or throwing an error. + * + * **Example** (Extracting a User Role with `Match.either`) + * + * ```ts + * import { Match } from "effect" + * + * type User = { readonly role: "admin" | "editor" | "viewer" } + * + * // Create a matcher to extract user roles + * const getRole = Match.type().pipe( + * Match.when({ role: "admin" }, () => "Has full access"), + * Match.when({ role: "editor" }, () => "Can edit content"), + * Match.either // Wrap the result in an Either + * ) + * + * console.log(getRole({ role: "admin" })) + * // Output: { _id: 'Either', _tag: 'Right', right: 'Has full access' } + * + * console.log(getRole({ role: "viewer" })) + * // Output: { _id: 'Either', _tag: 'Left', left: { role: 'viewer' } } + * ``` + * + * @category Completion + * @since 4.0.0 */ export const either: ( self: Matcher ) => [Pr] extends [never] ? (input: I) => Either.Either, R> : Either.Either, R> = internal.either /** - * @category conversions - * @since 1.0.0 + * Wraps the match result in an `Option`, representing an optional match. + * + * **Details** + * + * This function ensures that the result of a matcher is wrapped in an `Option`, + * making it easy to handle cases where no pattern matches. If a match is found, + * it returns `Some(value)`, otherwise, it returns `None`. + * + * This is useful in cases where a missing match is expected and should be + * handled explicitly rather than throwing an error or returning a default + * value. + * + * **Example** (Extracting a User Role with `Match.option`) + * + * ```ts + * import { Match } from "effect" + * + * type User = { readonly role: "admin" | "editor" | "viewer" } + * + * // Create a matcher to extract user roles + * const getRole = Match.type().pipe( + * Match.when({ role: "admin" }, () => "Has full access"), + * Match.when({ role: "editor" }, () => "Can edit content"), + * Match.option // Wrap the result in an Option + * ) + * + * console.log(getRole({ role: "admin" })) + * // Output: { _id: 'Option', _tag: 'Some', value: 'Has full access' } + * + * console.log(getRole({ role: "viewer" })) + * // Output: { _id: 'Option', _tag: 'None' } + * ``` + * + * @category Completion + * @since 4.0.0 */ export const option: ( self: Matcher ) => [Pr] extends [never] ? (input: I) => Option.Option> : Option.Option> = internal.option /** - * @category conversions - * @since 1.0.0 + * The `Match.exhaustive` method finalizes the pattern matching process by + * ensuring that all possible cases are accounted for. If any case is missing, + * TypeScript will produce a type error. This is particularly useful when + * working with unions, as it helps prevent unintended gaps in pattern matching. + * + * **Example** (Ensuring All Cases Are Covered) + * + * ```ts + * import { Match } from "effect" + * + * // Create a matcher for string or number values + * const match = Match.type().pipe( + * // Match when the value is a number + * Match.when(Match.number, (n) => `number: ${n}`), + * // Mark the match as exhaustive, ensuring all cases are handled + * // TypeScript will throw an error if any case is missing + * // @ts-expect-error Type 'string' is not assignable to type 'never' + * Match.exhaustive + * ) + * ``` + * + * @category Completion + * @since 4.0.0 */ export const exhaustive: ( self: Matcher ) => [Pr] extends [never] ? (u: I) => Unify : Unify = internal.exhaustive /** - * @since 1.0.0 - * @category type ids + * @since 4.0.0 + * @category Symbols */ export const SafeRefinementId = Symbol.for("effect/SafeRefinement") /** - * @since 1.0.0 - * @category type ids + * @since 4.0.0 + * @category Symbols */ export type SafeRefinementId = typeof SafeRefinementId /** - * @category model - * @since 1.0.0 + * @category Model + * @since 4.0.0 */ export interface SafeRefinement { readonly [SafeRefinementId]: (a: A) => R @@ -558,16 +1267,16 @@ const Fail = Symbol.for("effect/Fail") type Fail = typeof Fail /** - * @since 1.0.0 + * @since 4.0.0 */ export declare namespace Types { /** - * @since 1.0.0 + * @since 4.0.0 */ export type WhenMatch = // check for any - [0] extends [1 & R] ? PForMatch