diff --git a/.opencode/node_modules/effect/src/unstable/cluster/internal/entityManager.ts b/.opencode/node_modules/effect/src/unstable/cluster/internal/entityManager.ts index 66f3ba1b84f73f8e8eb14fa21b8caac6343ec921..fac03bdfa92970efb34e5811c9a0da712964b4b2 100644 --- a/.opencode/node_modules/effect/src/unstable/cluster/internal/entityManager.ts +++ b/.opencode/node_modules/effect/src/unstable/cluster/internal/entityManager.ts @@ -15,7 +15,7 @@ import * as Option from "../../../Option.ts" import { CurrentLogAnnotations } from "../../../References.ts" import * as Schedule from "../../../Schedule.ts" import * as Schema from "../../../Schema.ts" -import * as Issue from "../../../SchemaIssue.ts" +import * as SchemaIssue from "../../../SchemaIssue.ts" import * as Scope from "../../../Scope.ts" import type * as Rpc from "../../rpc/Rpc.ts" import { RequestId } from "../../rpc/RpcMessage.ts" @@ -145,7 +145,8 @@ export const make = Effect.fnUntraced(function*< ) const activeRequests: EntityState["activeRequests"] = new Map() - let defectRequestIds: Array = [] + let defectRequestIds = new Set() + let isRestartingDueToDefect = false // the server is stored in a ref, so if there is a defect, we can // swap the server without losing the active requests @@ -186,6 +187,14 @@ export const make = Effect.fnUntraced(function*< request.sentReply = true + if ( + isShuttingDown && + Exit.hasInterrupts(response.exit) && + defectRequestIds.has(response.requestId) + ) { + return Effect.void + } + // For durable messages, ignore interrupts during shutdown. // They will be retried when the entity is restarted. // Also, if the request is uninterruptible, we ignore the @@ -281,9 +290,11 @@ export const make = Effect.fnUntraced(function*< }) ) - if (defectRequestIds.length > 0) { + if (defectRequestIds.size > 0) { for (const id of defectRequestIds) { - const { lastSentChunk, message } = activeRequests.get(id)! + const request = activeRequests.get(id) + if (!request) continue + const { lastSentChunk, message } = request yield* server.write(0, { ...message.envelope, id: RequestId(message.envelope.requestId), @@ -294,7 +305,7 @@ export const make = Effect.fnUntraced(function*< } as any) as any }) } - defectRequestIds = [] + defectRequestIds.clear() } return server.write @@ -305,11 +316,18 @@ export const make = Effect.fnUntraced(function*< if (!activeServers.has(address.entityId)) { return endLatch.open } + if (isRestartingDueToDefect) { + return Effect.void + } + defectRequestIds = new Set(activeRequests.keys()) + isRestartingDueToDefect = true const effect = writeRef.rebuildUnsafe() - defectRequestIds = Array.from(activeRequests.keys()) return Effect.logError("Defect in entity, restarting", cause).pipe( Effect.andThen(Effect.ignore(retryDriver(void 0))), Effect.flatMap(() => activeServers.has(address.entityId) ? effect : endLatch.open), + Effect.ensuring(Effect.sync(() => { + isRestartingDueToDefect = false + })), Effect.annotateLogs({ module: "EntityManager", address, @@ -636,7 +654,7 @@ const makeMessageDecode = ( if (!rpc) { return Effect.fail( new Schema.SchemaError( - new Issue.InvalidValue(Option.some(message), { + new SchemaIssue.InvalidValue(Option.some(message), { message: `Unknown tag ${message.envelope.tag} for entity type ${entity.type}` }) ) diff --git a/.opencode/node_modules/effect/src/unstable/cluster/internal/hash.ts b/.opencode/node_modules/effect/src/unstable/cluster/internal/hash.ts index cd3045931eacc3895c0606d7ce884fde407a3ed6..cddf7bd2e33c99216302673398f9e13e0a68d7f5 100644 --- a/.opencode/node_modules/effect/src/unstable/cluster/internal/hash.ts +++ b/.opencode/node_modules/effect/src/unstable/cluster/internal/hash.ts @@ -1,3 +1,15 @@ +/** + * Internal hashing helpers used by cluster routing to map entity identifiers to + * shard numbers. The hash is intentionally small and deterministic for + * JavaScript strings so every node that sees the same entity id and sharding + * configuration derives the same destination shard. + * + * **Gotchas** + * + * - Changing this implementation changes entity-to-shard assignment. + * - Strings are hashed as UTF-16 code units; normalize ids before routing if + * callers may produce equivalent text in different Unicode forms. + */ /** @internal */ export const hashOptimize = (n: number): number => (n & 0xbfffffff) | ((n >>> 1) & 0x40000000) diff --git a/.opencode/node_modules/effect/src/unstable/devtools/DevTools.ts b/.opencode/node_modules/effect/src/unstable/devtools/DevTools.ts index a0479edfd5af60315a0410feeac18c763a20d1c2..3074afdb214520bcdfd3dabf5fd87ca9497463cd 100644 --- a/.opencode/node_modules/effect/src/unstable/devtools/DevTools.ts +++ b/.opencode/node_modules/effect/src/unstable/devtools/DevTools.ts @@ -1,4 +1,12 @@ /** + * High-level layers for connecting an Effect runtime to the unstable devtools + * tracer. + * + * `DevTools` is the application-facing entry point for installing a tracer that + * mirrors the current tracer and streams spans, span events, span completions, + * and metric snapshots to an external devtools process. Lower-level socket + * protocol details live in `DevToolsClient`. + * * @since 4.0.0 */ import * as Layer from "../../Layer.ts" @@ -6,14 +14,19 @@ import * as Socket from "../socket/Socket.ts" import * as DevToolsClient from "./DevToolsClient.ts" /** - * @since 4.0.0 + * Layer that installs the devtools tracer using an existing `Socket`. + * * @category layers + * @since 4.0.0 */ export const layerSocket: Layer.Layer = DevToolsClient.layerTracer /** - * @since 4.0.0 + * Layer that installs the devtools tracer over a WebSocket connection to the + * specified URL, defaulting to `ws://localhost:34437`. + * * @category layers + * @since 4.0.0 */ export const layerWebSocket = ( url = "ws://localhost:34437" @@ -23,8 +36,31 @@ export const layerWebSocket = ( ) /** - * @since 4.0.0 + * Layer that installs the devtools tracer over a WebSocket connection using the + * global WebSocket constructor, defaulting to `ws://localhost:34437`. + * + * **When to use** + * + * Use to stream Effect tracing and metrics telemetry to a devtools process when + * the runtime environment already provides a global `WebSocket` constructor. + * + * **Details** + * + * This is a convenience wrapper around `layerWebSocket(url)` that provides + * `Socket.layerWebSocketConstructorGlobal`, so the resulting layer has no + * remaining requirements. + * + * **Gotchas** + * + * This layer only installs the client-side tracer; it does not start a devtools + * server, so the configured WebSocket endpoint must already be reachable. It + * relies on `globalThis.WebSocket` being available in the runtime. + * + * @see {@link layerWebSocket} for installing the devtools tracer with an explicit `WebSocketConstructor` requirement + * @see {@link layerSocket} for installing the devtools tracer over an existing `Socket` transport + * * @category layers + * @since 4.0.0 */ export const layer = (url = "ws://localhost:34437"): Layer.Layer => layerWebSocket(url).pipe( diff --git a/.opencode/node_modules/effect/src/unstable/devtools/DevToolsClient.ts b/.opencode/node_modules/effect/src/unstable/devtools/DevToolsClient.ts index 350244c49357a69fa0d1a64c6a61f5e81186b1ef..ff7d7f3dede4258d00dc98ccb93c3da28d870a59 100644 --- a/.opencode/node_modules/effect/src/unstable/devtools/DevToolsClient.ts +++ b/.opencode/node_modules/effect/src/unstable/devtools/DevToolsClient.ts @@ -1,4 +1,11 @@ /** + * Low-level devtools client and tracer wiring over the current `Socket`. + * + * `DevToolsClient` speaks the devtools NDJSON protocol used by the unstable + * devtools integration. It sends span starts, span events, span completions, + * ping messages, and metric snapshots through a socket, then exposes tracer + * layers that forward telemetry while preserving the current tracer's behavior. + * * @since 4.0.0 */ import * as Cause from "../../Cause.ts" @@ -21,8 +28,11 @@ const RequestSchema = Schema.toCodecJson(DevToolsSchema.Request) const ResponseSchema = Schema.toCodecJson(DevToolsSchema.Response) /** + * Service for sending span and span-event telemetry to the Effect devtools + * connection. + * + * @category services * @since 4.0.0 - * @category tags */ export class DevToolsClient extends Context.Service< DevToolsClient, @@ -103,8 +113,30 @@ const toMetricsSnapshot = ( }) /** - * @since 4.0.0 + * Creates a devtools client over the current `Socket`, speaking the devtools + * NDJSON protocol, sending periodic pings, and responding to metrics snapshot + * requests. + * + * **When to use** + * + * Use when you already have a `Socket` and need the low-level `DevToolsClient` + * service to exchange devtools telemetry directly. + * + * **Details** + * + * The effect requires `Scope` because it starts background fibers for the socket + * stream and heartbeat. + * + * **Gotchas** + * + * `make` creates only the client service; tracing is installed separately. + * + * @see {@link layer} for providing the client as a layer + * @see {@link makeTracer} for creating a tracer after a `DevToolsClient` is available + * @see {@link layerTracer} for creating the client from the current `Socket` and installing the tracer as a layer + * * @category constructors + * @since 4.0.0 */ export const make: Effect.Effect< DevToolsClient["Service"], @@ -118,8 +150,30 @@ export const make: Effect.Effect< ) /** - * @since 4.0.0 + * Layer that provides `DevToolsClient` using the current `Socket`. + * + * **When to use** + * + * Use to provide the low-level `DevToolsClient` service over an existing + * `Socket` for custom devtools integrations that send telemetry through the + * client directly. + * + * **Details** + * + * It delegates to `make`, so it speaks the devtools NDJSON protocol over the + * provided `Socket`, sends periodic pings, responds to metrics snapshot + * requests, and finalizes its background fibers when the layer scope closes. + * + * **Gotchas** + * + * This layer only provides the client. It does not install the devtools tracer + * by itself. + * + * @see {@link make} for constructing the client as a scoped effect instead of a layer + * @see {@link layerTracer} for a higher-level layer that creates the client and installs the devtools tracer + * * @category layers + * @since 4.0.0 */ export const layer: Layer.Layer = Layer.effect(DevToolsClient, make) @@ -157,8 +211,11 @@ const makeTracerEffect = Effect.gen(function*() { }) /** - * @since 4.0.0 + * Creates a tracer that delegates to the current tracer while sending span + * starts, span events, and span ends to `DevToolsClient`. + * * @category constructors + * @since 4.0.0 */ export const makeTracer: Effect.Effect = makeTracerEffect.pipe( Effect.annotateLogs({ @@ -168,8 +225,11 @@ export const makeTracer: Effect.Effect = m ) /** - * @since 4.0.0 + * Layer that creates a `DevToolsClient` from the current `Socket` and installs + * the devtools tracer. + * * @category layers + * @since 4.0.0 */ export const layerTracer: Layer.Layer = Layer.effect(Tracer.Tracer, makeTracer).pipe( Layer.provide(layer) diff --git a/.opencode/node_modules/effect/src/unstable/devtools/DevToolsSchema.ts b/.opencode/node_modules/effect/src/unstable/devtools/DevToolsSchema.ts index 1bcafde607793e54ac2b25e9425cbfcedf7da2a0..d5d66597e2a9a9a061fcadbd847ee6881f5cc157 100644 --- a/.opencode/node_modules/effect/src/unstable/devtools/DevToolsSchema.ts +++ b/.opencode/node_modules/effect/src/unstable/devtools/DevToolsSchema.ts @@ -1,4 +1,12 @@ /** + * Defines the experimental wire schema used by the Effect devtools protocol. + * + * The module contains the serialized message shapes exchanged between devtools + * clients and servers: span snapshots, span events, metric snapshots, + * heartbeats, and request/response unions. Use these schemas at protocol + * boundaries to encode, decode, or validate custom transports that need to + * interoperate with the built-in unstable devtools client and server. + * * @since 4.0.0 */ import * as Exit from "../../Exit.ts" @@ -8,8 +16,11 @@ import * as Schema from "../../Schema.ts" import * as SchemaTransformation from "../../SchemaTransformation.ts" /** - * @since 4.0.0 + * Schema for a span status representing a span that has started but not yet + * ended. + * * @category schemas + * @since 4.0.0 */ export const SpanStatusStarted = Schema.Struct({ _tag: Schema.tag("Started"), @@ -17,20 +28,26 @@ export const SpanStatusStarted = Schema.Struct({ }) /** - * @since 4.0.0 + * Type of a span status representing a span that has started but not yet ended. + * * @category schemas + * @since 4.0.0 */ export type SpanStatusStarted = Schema.Schema.Type /** - * @since 4.0.0 + * Schema for a span status representing an ended span, including start time, + * end time, and encoded exit status. Encoding drops success values with + * `Exit.asVoid`. + * * @category schemas + * @since 4.0.0 */ export const SpanStatusEnded = Schema.Struct({ _tag: Schema.tag("Ended"), startTime: Schema.BigInt, endTime: Schema.BigInt, - exit: Schema.Exit(Schema.Void, Schema.DefectWithStack, Schema.DefectWithStack).pipe( + exit: Schema.Exit(Schema.Void, Schema.Defect({ includeStack: true }), Schema.Defect({ includeStack: true })).pipe( Schema.decodeTo( Schema.Exit(Schema.Unknown, Schema.Unknown, Schema.Unknown), SchemaTransformation.transform({ @@ -42,26 +59,36 @@ export const SpanStatusEnded = Schema.Struct({ }) /** - * @since 4.0.0 + * Type of a span status representing an ended span with start time, end time, + * and exit status. + * * @category schemas + * @since 4.0.0 */ export type SpanStatusEnded = Schema.Schema.Type /** - * @since 4.0.0 + * Schema for devtools span status, either started or ended. + * * @category schemas + * @since 4.0.0 */ export const SpanStatus = Schema.Union([SpanStatusStarted, SpanStatusEnded]) /** - * @since 4.0.0 + * Type of a devtools span status, either started or ended. + * * @category schemas + * @since 4.0.0 */ export type SpanStatus = Schema.Schema.Type /** - * @since 4.0.0 + * Serialized parent span context for a span created outside the current + * devtools span tree. + * * @category schemas + * @since 4.0.0 */ export interface ExternalSpan { readonly _tag: "ExternalSpan" @@ -71,8 +98,11 @@ export interface ExternalSpan { } /** - * @since 4.0.0 + * Schema for an external parent span context containing span id, trace id, and + * sampling flag. + * * @category schemas + * @since 4.0.0 */ export const ExternalSpan: Schema.Codec = Schema.Struct({ _tag: Schema.tag("ExternalSpan"), @@ -82,8 +112,11 @@ export const ExternalSpan: Schema.Codec = Schema.Struct({ }) /** - * @since 4.0.0 + * Telemetry payload for an Effect span sent to devtools, including identity, + * attributes, status, sampling flag, and optional parent span. + * * @category schemas + * @since 4.0.0 */ export interface Span { readonly _tag: "Span" @@ -97,8 +130,10 @@ export interface Span { } /** - * @since 4.0.0 + * Schema for an Effect span telemetry payload sent to devtools. + * * @category schemas + * @since 4.0.0 */ export const Span: Schema.Codec = Schema.Struct({ _tag: Schema.tag("Span"), @@ -112,8 +147,11 @@ export const Span: Schema.Codec = Schema.Struct({ }) /** - * @since 4.0.0 + * Schema for a named event emitted by a span, including trace id, span id, + * start time, and optional attributes. + * * @category schemas + * @since 4.0.0 */ export const SpanEvent = Schema.Struct({ _tag: Schema.tag("SpanEvent"), @@ -125,68 +163,90 @@ export const SpanEvent = Schema.Struct({ }) /** - * @since 4.0.0 + * Type of a named event emitted by a span and sent to devtools. + * * @category schemas + * @since 4.0.0 */ export type SpanEvent = Schema.Schema.Type /** - * @since 4.0.0 + * Type of a span parent, represented either by a devtools `Span` payload or an + * `ExternalSpan` context. + * * @category schemas + * @since 4.0.0 */ export type ParentSpan = Span | ExternalSpan /** - * @since 4.0.0 + * Schema for a span parent, either a full devtools `Span` payload or an + * `ExternalSpan` context. + * * @category schemas + * @since 4.0.0 */ export const ParentSpan = Schema.Union([Span, ExternalSpan]) /** - * @since 4.0.0 + * Schema for the devtools heartbeat request sent by the client. + * * @category schemas + * @since 4.0.0 */ export const Ping = Schema.Struct({ _tag: Schema.tag("Ping") }) /** - * @since 4.0.0 + * Type of the devtools heartbeat request sent by the client. + * * @category schemas + * @since 4.0.0 */ export type Ping = Schema.Schema.Type /** - * @since 4.0.0 + * Schema for the devtools heartbeat response. + * * @category schemas + * @since 4.0.0 */ export const Pong = Schema.Struct({ _tag: Schema.tag("Pong") }) /** - * @since 4.0.0 + * Type of the devtools heartbeat response. + * * @category schemas + * @since 4.0.0 */ export type Pong = Schema.Schema.Type /** - * @since 4.0.0 + * Schema for a devtools request asking the client to send a metrics snapshot. + * * @category schemas + * @since 4.0.0 */ export const MetricsRequest = Schema.Struct({ _tag: Schema.tag("MetricsRequest") }) /** - * @since 4.0.0 + * Type of a devtools request asking the client to send a metrics snapshot. + * * @category schemas + * @since 4.0.0 */ export type MetricsRequest = Schema.Schema.Type /** - * @since 4.0.0 + * Schema for a metric label key/value pair in a devtools metrics snapshot. + * * @category schemas + * @since 4.0.0 */ export const MetricLabel = Schema.Struct({ key: Schema.String, @@ -194,8 +254,10 @@ export const MetricLabel = Schema.Struct({ }) /** - * @since 4.0.0 + * Type of a metric label key/value pair in a devtools metrics snapshot. + * * @category schemas + * @since 4.0.0 */ export type MetricLabel = Schema.Schema.Type @@ -209,8 +271,11 @@ const metric = (type: Type, state }) /** - * @since 4.0.0 + * Schema for a counter metric snapshot, including the count and whether updates + * are incremental. + * * @category schemas + * @since 4.0.0 */ export const Counter = metric( "Counter", @@ -221,14 +286,27 @@ export const Counter = metric( ) /** - * @since 4.0.0 + * Type of a devtools counter metric snapshot. + * + * **Details** + * + * The state contains the current count and whether the counter reports + * incremental updates. + * * @category schemas + * @since 4.0.0 */ export type Counter = Schema.Schema.Type /** - * @since 4.0.0 + * Schema for a devtools frequency metric snapshot. + * + * **Details** + * + * The metric state records occurrence counts by string key. + * * @category schemas + * @since 4.0.0 */ export const Frequency = metric( "Frequency", @@ -238,14 +316,26 @@ export const Frequency = metric( ) /** - * @since 4.0.0 + * Type of a devtools frequency metric snapshot. + * + * **Details** + * + * The state maps observed string values to occurrence counts. + * * @category schemas + * @since 4.0.0 */ export type Frequency = Schema.Schema.Type /** - * @since 4.0.0 + * Schema for a devtools gauge metric snapshot. + * + * **Details** + * + * The metric state contains the current numeric or bigint value. + * * @category schemas + * @since 4.0.0 */ export const Gauge = metric( "Gauge", @@ -255,14 +345,27 @@ export const Gauge = metric( ) /** - * @since 4.0.0 + * Type of a devtools gauge metric snapshot. + * + * **Details** + * + * The state contains the current numeric or bigint value. + * * @category schemas + * @since 4.0.0 */ export type Gauge = Schema.Schema.Type /** - * @since 4.0.0 + * Schema for a devtools histogram metric snapshot. + * + * **Details** + * + * The metric state includes bucket counts plus the total count, minimum, + * maximum, and sum. + * * @category schemas + * @since 4.0.0 */ export const Histogram = metric( "Histogram", @@ -276,14 +379,28 @@ export const Histogram = metric( ) /** - * @since 4.0.0 + * Type of a devtools histogram metric snapshot. + * + * **Details** + * + * The state includes bucket counts plus the total count, minimum, maximum, and + * sum. + * * @category schemas + * @since 4.0.0 */ export type Histogram = Schema.Schema.Type /** - * @since 4.0.0 + * Schema for a devtools summary metric snapshot. + * + * **Details** + * + * The metric state contains quantile values plus the total count, minimum, + * maximum, and sum. + * * @category schemas + * @since 4.0.0 */ export const Summary = metric( "Summary", @@ -297,26 +414,49 @@ export const Summary = metric( ) /** - * @since 4.0.0 + * Type of a devtools summary metric snapshot. + * + * **Details** + * + * The state contains quantile values plus the total count, minimum, maximum, + * and sum. + * * @category schemas + * @since 4.0.0 */ export type Summary = Schema.Schema.Type /** - * @since 4.0.0 + * Schema for any devtools metric snapshot. + * + * **Details** + * + * Accepted metric kinds are counters, frequencies, gauges, histograms, and + * summaries. + * * @category schemas + * @since 4.0.0 */ export const Metric = Schema.Union([Counter, Frequency, Gauge, Histogram, Summary]) /** - * @since 4.0.0 + * Type of any devtools metric snapshot. + * + * **Details** + * + * The union covers counters, frequencies, gauges, histograms, and summaries. + * * @category schemas + * @since 4.0.0 */ export type Metric = Schema.Schema.Type /** - * @since 4.0.0 + * Schema for a devtools protocol message containing the current metric + * snapshots. + * * @category schemas + * @since 4.0.0 */ export const MetricsSnapshot = Schema.Struct({ _tag: Schema.tag("MetricsSnapshot"), @@ -324,55 +464,95 @@ export const MetricsSnapshot = Schema.Struct({ }) /** - * @since 4.0.0 + * Type of a devtools protocol message containing the current metric snapshots. + * * @category schemas + * @since 4.0.0 */ export type MetricsSnapshot = Schema.Schema.Type /** - * @since 4.0.0 + * Schema for devtools protocol requests accepted by the server. + * + * **Details** + * + * Requests include heartbeat pings, spans, span events, and metric snapshots. + * * @category schemas + * @since 4.0.0 */ export const Request = Schema.Union([Ping, Span, SpanEvent, MetricsSnapshot]) /** - * @since 4.0.0 + * Type of devtools protocol requests accepted by the server. + * + * **Details** + * + * Requests include heartbeat pings, spans, span events, and metric snapshots. + * * @category schemas + * @since 4.0.0 */ export type Request = Schema.Schema.Type /** + * Namespace containing helper types for devtools protocol requests. + * * @since 4.0.0 - * @category schemas */ export declare namespace Request { /** + * Devtools request messages excluding heartbeat pings. + * + * **Details** + * + * `DevToolsServer` handles `Ping` internally and exposes only these requests + * to client handlers. + * * @since 4.0.0 - * @category schemas */ export type WithoutPing = Exclude } /** - * @since 4.0.0 + * Schema for devtools protocol responses sent by the server. + * + * **Details** + * + * Responses include heartbeat pongs and requests for metric snapshots. + * * @category schemas + * @since 4.0.0 */ export const Response = Schema.Union([Pong, MetricsRequest]) /** - * @since 4.0.0 + * Type of devtools protocol responses sent by the server. + * + * **Details** + * + * Responses include heartbeat pongs and requests for metric snapshots. + * * @category schemas + * @since 4.0.0 */ export type Response = Schema.Schema.Type /** + * Namespace containing helper types for devtools protocol responses. + * * @since 4.0.0 - * @category schemas */ export declare namespace Response { /** + * Devtools response messages excluding heartbeat pongs. + * + * **Details** + * + * `DevToolsServer` sends `Pong` internally and accepts only these responses + * from client handlers. + * * @since 4.0.0 - * @category schemas */ export type WithoutPong = Exclude } diff --git a/.opencode/node_modules/effect/src/unstable/devtools/DevToolsServer.ts b/.opencode/node_modules/effect/src/unstable/devtools/DevToolsServer.ts index 8cb2797c85f2c539cbacbb69e09d279f403b6ce3..327dda33eb29ea1f56f38e2f3f816b04cee1629f 100644 --- a/.opencode/node_modules/effect/src/unstable/devtools/DevToolsServer.ts +++ b/.opencode/node_modules/effect/src/unstable/devtools/DevToolsServer.ts @@ -1,4 +1,12 @@ /** + * Runs the server side of the unstable Effect devtools socket protocol. + * + * Use this module when an integration needs to accept devtools clients over a + * `SocketServer`, decode newline-delimited JSON messages, and handle each + * connection with application-specific logic. It does not interpret spans or + * metrics itself; it gives handlers a typed surface for the telemetry described + * by `DevToolsSchema`. + * * @since 4.0.0 */ import * as Effect from "../../Effect.ts" @@ -14,8 +22,15 @@ const RequestSchema = Schema.toCodecJson(DevToolsSchema.Request) const ResponseSchema = Schema.toCodecJson(DevToolsSchema.Response) /** - * @since 4.0.0 + * Handle for a connected devtools client. + * + * **Details** + * + * It exposes a queue of non-ping requests received from the socket and a + * `send` function for non-pong responses. + * * @category models + * @since 4.0.0 */ export interface Client { readonly queue: Queue.Dequeue @@ -23,8 +38,16 @@ export interface Client { } /** - * @since 4.0.0 + * Runs the devtools socket server. + * + * **Details** + * + * Each connection is decoded as NDJSON devtools protocol messages, `Ping` + * requests are answered with `Pong`, and all other requests are delivered + * through the `Client` passed to the handler. + * * @category constructors + * @since 4.0.0 */ export const run: <_, E, R>( handle: (client: Client) => Effect.Effect<_, E, R> diff --git a/.opencode/node_modules/effect/src/unstable/encoding/Msgpack.ts b/.opencode/node_modules/effect/src/unstable/encoding/Msgpack.ts index 757feb0dc835fc607a111940348ad2a30c5d7534..d266ba81faedfb598b2156ad3408dcee53e23a37 100644 --- a/.opencode/node_modules/effect/src/unstable/encoding/Msgpack.ts +++ b/.opencode/node_modules/effect/src/unstable/encoding/Msgpack.ts @@ -1,4 +1,12 @@ /** + * Encodes and decodes MessagePack frames in Effect channels. + * + * MessagePack is a compact binary serialization format for protocols and + * storage layers that expect bytes instead of JSON text, such as RPC + * transports, socket streams, caches, or database columns. This module includes + * raw channel helpers for values whose shape is already agreed on, and + * schema-based helpers for validating and transforming values at the boundary. + * * @since 4.0.0 */ import { Packr, Unpackr } from "msgpackr" @@ -13,25 +21,36 @@ import * as Option from "../../Option.ts" import * as Predicate from "../../Predicate.ts" import type * as Pull from "../../Pull.ts" import * as Schema from "../../Schema.ts" -import * as Issue from "../../SchemaIssue.ts" -import * as Transformation from "../../SchemaTransformation.ts" +import * as SchemaIssue from "../../SchemaIssue.ts" +import * as SchemaTransformation from "../../SchemaTransformation.ts" const MsgPackErrorTypeId = "~effect/encoding/MsgPack/MsgPackError" /** - * @since 4.0.0 + * Error raised when MessagePack encoding or decoding fails. + * + * **Details** + * + * The `kind` field identifies whether the failure happened while packing or + * unpacking, and `cause` preserves the original error. + * * @category errors + * @since 4.0.0 */ export class MsgPackError extends Data.TaggedError("MsgPackError")<{ readonly kind: "Pack" | "Unpack" readonly cause: unknown }> { /** + * Marks this value as a MessagePack encoding or decoding error for runtime guards. + * * @since 4.0.0 */ readonly [MsgPackErrorTypeId] = MsgPackErrorTypeId /** + * Uses the failed MessagePack operation as the public message. + * * @since 4.0.0 */ override get message() { @@ -40,8 +59,15 @@ export class MsgPackError extends Data.TaggedError("MsgPackError")<{ } /** - * @since 4.0.0 + * Creates a channel that encodes non-empty chunks of values as MessagePack byte + * arrays. + * + * **Details** + * + * The channel fails with `MsgPackError` when any value cannot be packed. + * * @category constructors + * @since 4.0.0 */ export const encode = (): Channel.Channel< Arr.NonEmptyReadonlyArray>, @@ -65,8 +91,15 @@ export const encode = (): Channel.Channel< ) /** - * @since 4.0.0 + * Creates a MessagePack encoder channel for values of a schema. + * + * **Details** + * + * Values are first encoded with the schema and then packed as MessagePack bytes, + * so the channel can fail with either schema errors or `MsgPackError`. + * * @category constructors + * @since 4.0.0 */ export const encodeSchema = ( schema: S @@ -82,8 +115,15 @@ export const encodeSchema = ( > => Channel.pipeTo(ChannelSchema.encode(schema)(), encode()) /** - * @since 4.0.0 + * Creates a channel that decodes MessagePack byte chunks into values. + * + * **Details** + * + * Incomplete frames are buffered across chunks, and invalid MessagePack data + * fails with `MsgPackError`. + * * @category constructors + * @since 4.0.0 */ export const decode = (): Channel.Channel< Arr.NonEmptyReadonlyArray, @@ -131,8 +171,15 @@ export const decode = (): Channel.Channel< ) /** - * @since 4.0.0 + * Creates a MessagePack decoder channel for values of a schema. + * + * **Details** + * + * The channel unpacks bytes into unknown values and then decodes each value with + * the schema. + * * @category constructors + * @since 4.0.0 */ export const decodeSchema = ( schema: S @@ -148,8 +195,15 @@ export const decodeSchema = ( > => Channel.pipeTo(decode(), ChannelSchema.decodeUnknown(schema)()) /** - * @since 4.0.0 + * Wraps a bidirectional byte channel with MessagePack encoding and decoding. + * + * **Details** + * + * Outgoing values are packed as MessagePack bytes before reaching the wrapped + * channel, and incoming bytes are unpacked into values. + * * @category combinators + * @since 4.0.0 */ export const duplex = ( self: Channel.Channel< @@ -176,13 +230,31 @@ export const duplex = ( ) /** - * @since 4.0.0 + * Wraps a bidirectional byte channel with schema-aware MessagePack encoding and + * decoding. + * + * **Details** + * + * Values sent to the wrapped channel are encoded with `inputSchema` and packed + * as MessagePack bytes; bytes received from it are unpacked and decoded with + * `outputSchema`. + * * @category combinators + * @since 4.0.0 */ export const duplexSchema: { /** - * @since 4.0.0 + * Wraps a bidirectional byte channel with schema-aware MessagePack encoding and + * decoding. + * + * **Details** + * + * Values sent to the wrapped channel are encoded with `inputSchema` and packed + * as MessagePack bytes; bytes received from it are unpacked and decoded with + * `outputSchema`. + * * @category combinators + * @since 4.0.0 */ ( options: { @@ -209,8 +281,17 @@ export const duplexSchema: { R | In["EncodingServices"] | Out["DecodingServices"] > /** - * @since 4.0.0 + * Wraps a bidirectional byte channel with schema-aware MessagePack encoding and + * decoding. + * + * **Details** + * + * Values sent to the wrapped channel are encoded with `inputSchema` and packed + * as MessagePack bytes; bytes received from it are unpacked and decoded with + * `outputSchema`. + * * @category combinators + * @since 4.0.0 */ ( self: Channel.Channel< @@ -260,25 +341,39 @@ export const duplexSchema: { > => ChannelSchema.duplexUnknown(duplex(self), options)) /** - * @since 4.0.0 + * Schema type for values encoded as MessagePack bytes. + * + * **Details** + * + * It decodes a `Uint8Array` MessagePack payload to the target schema type and + * encodes the target type back to bytes. + * * @category schemas + * @since 4.0.0 */ export interface schema extends Schema.decodeTo>> {} /** - * @since 4.0.0 + * Schema for decoding MessagePack bytes into values and encoding values back to + * MessagePack bytes. + * + * **Details** + * + * MessagePack codec failures are converted to `InvalidValue` schema issues. + * * @category schemas + * @since 4.0.0 */ -export const transformation: Transformation.Transformation< +export const transformation: SchemaTransformation.Transformation< unknown, Uint8Array -> = Transformation.transformOrFail({ +> = SchemaTransformation.transformOrFail({ decode(e, _options) { try { return Effect.succeed(Msgpackr.decode(e)) } catch (cause) { return Effect.fail( - new Issue.InvalidValue(Option.some(e), { + new SchemaIssue.InvalidValue(Option.some(e), { message: Predicate.hasProperty(cause, "message") ? String(cause.message) : String(cause) }) ) @@ -289,7 +384,7 @@ export const transformation: Transformation.Transformation< return Effect.succeed(Msgpackr.encode(t) as Uint8Array) } catch (cause) { return Effect.fail( - new Issue.InvalidValue(Option.some(t), { + new SchemaIssue.InvalidValue(Option.some(t), { message: Predicate.hasProperty(cause, "message") ? String(cause.message) : String(cause) }) ) @@ -298,8 +393,15 @@ export const transformation: Transformation.Transformation< }) /** - * @since 4.0.0 + * Builds a schema that stores values as MessagePack bytes. + * + * **Details** + * + * The resulting schema decodes `Uint8Array` payloads with MessagePack and the + * provided schema, and encodes values back to MessagePack bytes. + * * @category schemas + * @since 4.0.0 */ export const schema = (schema: S): schema => (Schema.Uint8Array as Schema.instanceOf>).pipe( diff --git a/.opencode/node_modules/effect/src/unstable/encoding/Ndjson.ts b/.opencode/node_modules/effect/src/unstable/encoding/Ndjson.ts index e9f05bff6c32b0c455ed32fe2decbd6930c669da..c87a3dc833fc5b1addcc9c520a05513beb10b9cd 100644 --- a/.opencode/node_modules/effect/src/unstable/encoding/Ndjson.ts +++ b/.opencode/node_modules/effect/src/unstable/encoding/Ndjson.ts @@ -1,4 +1,10 @@ /** + * Encodes and decodes newline-delimited JSON streams in Effect channels. + * + * NDJSON stores one complete JSON value on each line. This module has helpers + * for byte streams, string streams, and schema-checked records, so streaming + * code can read or write one JSON record at a time. + * * @since 4.0.0 */ import * as Arr from "../../Array.ts" @@ -14,19 +20,30 @@ const NdjsonErrorTypeId = "~effect/encoding/Ndjson/NdjsonError" const encoder = new TextEncoder() /** - * @since 4.0.0 + * Error raised when NDJSON encoding or decoding fails. + * + * **Details** + * + * The `kind` field identifies whether the failure happened while packing or + * unpacking, and `cause` preserves the original error. + * * @category errors + * @since 4.0.0 */ export class NdjsonError extends Data.TaggedError("NdjsonError")<{ readonly kind: "Pack" | "Unpack" readonly cause: unknown }> { /** + * Marks this value as an NDJSON encoding or decoding error for runtime guards. + * * @since 4.0.0 */ readonly [NdjsonErrorTypeId] = NdjsonErrorTypeId /** + * Uses the failed NDJSON operation as the public message. + * * @since 4.0.0 */ override get message() { @@ -35,8 +52,15 @@ export class NdjsonError extends Data.TaggedError("NdjsonError")<{ } /** - * @since 4.0.0 + * Creates a channel that encodes chunks of values as NDJSON strings. + * + * **Details** + * + * Each input item is `JSON.stringify`-encoded, separated by newlines, and the + * output chunk ends with a trailing newline. + * * @category constructors + * @since 4.0.0 */ export const encodeString = (): Channel.Channel< Arr.NonEmptyReadonlyArray, @@ -57,8 +81,10 @@ export const encodeString = (): Channel.Channel< ) /** - * @since 4.0.0 + * Creates a channel that encodes chunks of values as UTF-8 NDJSON bytes. + * * @category constructors + * @since 4.0.0 */ export const encode = (): Channel.Channel< Arr.NonEmptyReadonlyArray, @@ -70,8 +96,15 @@ export const encode = (): Channel.Channel< > => Channel.map(encodeString(), Arr.map((_) => encoder.encode(_))) /** - * @since 4.0.0 + * Creates an NDJSON byte encoder channel for values of a schema. + * + * **Details** + * + * Values are first encoded with the schema and then written as UTF-8 + * newline-delimited JSON. + * * @category constructors + * @since 4.0.0 */ export const encodeSchema = ( schema: S @@ -87,8 +120,15 @@ export const encodeSchema = ( > => Channel.pipeTo(ChannelSchema.encode(schema)(), encode()) /** - * @since 4.0.0 + * Creates an NDJSON string encoder channel for values of a schema. + * + * **Details** + * + * Values are first encoded with the schema and then written as newline-delimited + * JSON strings. + * * @category constructors + * @since 4.0.0 */ export const encodeSchemaString = ( schema: S @@ -104,8 +144,24 @@ export const encodeSchemaString = ( > => Channel.pipeTo(ChannelSchema.encode(schema)(), encodeString()) /** - * @since 4.0.0 + * Creates a channel that parses NDJSON string chunks into values. + * + * **When to use** + * + * Use when NDJSON input arrives as string chunks and each complete line should + * be parsed into a JSON value. + * + * **Details** + * + * Lines may span input chunks. + * + * **Gotchas** + * + * Set `ignoreEmptyLines` to skip blank lines before calling `JSON.parse`; + * otherwise blank lines are parsed and fail as invalid JSON. + * * @category constructors + * @since 4.0.0 */ export const decodeString = (options?: { readonly ignoreEmptyLines?: boolean | undefined @@ -132,8 +188,15 @@ export const decodeString = (options?: { } /** - * @since 4.0.0 + * Creates a channel that decodes UTF-8 byte chunks and parses them as NDJSON. + * + * **Details** + * + * Lines may span input chunks, and `ignoreEmptyLines` controls whether blank + * lines are skipped before JSON parsing. + * * @category constructors + * @since 4.0.0 */ export const decode = (options?: { readonly ignoreEmptyLines?: boolean | undefined @@ -149,8 +212,15 @@ export const decode = (options?: { } /** - * @since 4.0.0 + * Creates an NDJSON byte decoder channel for values of a schema. + * + * **Details** + * + * The channel decodes UTF-8 bytes, parses each NDJSON line, and then decodes + * each parsed value with the schema. + * * @category constructors + * @since 4.0.0 */ export const decodeSchema = ( schema: S @@ -168,8 +238,15 @@ export const decodeSchema = ( > => Channel.pipeTo(decode(options), ChannelSchema.decodeUnknown(schema)()) /** - * @since 4.0.0 + * Creates an NDJSON string decoder channel for values of a schema. + * + * **Details** + * + * The channel parses each line as JSON and then decodes each parsed value with + * the schema. + * * @category constructors + * @since 4.0.0 */ export const decodeSchemaString = ( schema: S @@ -187,13 +264,27 @@ export const decodeSchemaString = ( > => Channel.pipeTo(decodeString(options), ChannelSchema.decodeUnknown(schema)()) /** - * @since 4.0.0 + * Wraps a bidirectional byte channel with NDJSON encoding and decoding. + * + * **Details** + * + * Outgoing values are written as UTF-8 NDJSON bytes, and incoming bytes are + * parsed as NDJSON values. + * * @category combinators + * @since 4.0.0 */ export const duplex: { /** - * @since 4.0.0 + * Wraps a bidirectional byte channel with NDJSON encoding and decoding. + * + * **Details** + * + * Outgoing values are written as UTF-8 NDJSON bytes, and incoming bytes are + * parsed as NDJSON values. + * * @category combinators + * @since 4.0.0 */ ( options?: { @@ -219,8 +310,15 @@ export const duplex: { R > /** - * @since 4.0.0 + * Wraps a bidirectional byte channel with NDJSON encoding and decoding. + * + * **Details** + * + * Outgoing values are written as UTF-8 NDJSON bytes, and incoming bytes are + * parsed as NDJSON values. + * * @category combinators + * @since 4.0.0 */ ( self: Channel.Channel< @@ -272,13 +370,27 @@ export const duplex: { )) /** - * @since 4.0.0 + * Wraps a bidirectional string channel with NDJSON encoding and decoding. + * + * **Details** + * + * Outgoing values are written as NDJSON strings, and incoming strings are parsed + * as NDJSON values. + * * @category combinators + * @since 4.0.0 */ export const duplexString: { /** - * @since 4.0.0 + * Wraps a bidirectional string channel with NDJSON encoding and decoding. + * + * **Details** + * + * Outgoing values are written as NDJSON strings, and incoming strings are parsed + * as NDJSON values. + * * @category combinators + * @since 4.0.0 */ ( options?: { @@ -304,8 +416,15 @@ export const duplexString: { R > /** - * @since 4.0.0 + * Wraps a bidirectional string channel with NDJSON encoding and decoding. + * + * **Details** + * + * Outgoing values are written as NDJSON strings, and incoming strings are parsed + * as NDJSON values. + * * @category combinators + * @since 4.0.0 */ ( self: Channel.Channel< @@ -357,13 +476,29 @@ export const duplexString: { )) /** - * @since 4.0.0 + * Wraps a bidirectional byte channel with schema-aware NDJSON encoding and + * decoding. + * + * **Details** + * + * Values sent to the wrapped channel are encoded with `inputSchema`; bytes + * received from it are parsed as NDJSON and decoded with `outputSchema`. + * * @category combinators + * @since 4.0.0 */ export const duplexSchema: { /** - * @since 4.0.0 + * Wraps a bidirectional byte channel with schema-aware NDJSON encoding and + * decoding. + * + * **Details** + * + * Values sent to the wrapped channel are encoded with `inputSchema`; bytes + * received from it are parsed as NDJSON and decoded with `outputSchema`. + * * @category combinators + * @since 4.0.0 */ ( options: { @@ -391,8 +526,16 @@ export const duplexSchema: { R | In["EncodingServices"] | Out["DecodingServices"] > /** - * @since 4.0.0 + * Wraps a bidirectional byte channel with schema-aware NDJSON encoding and + * decoding. + * + * **Details** + * + * Values sent to the wrapped channel are encoded with `inputSchema`; bytes + * received from it are parsed as NDJSON and decoded with `outputSchema`. + * * @category combinators + * @since 4.0.0 */ ( self: Channel.Channel< @@ -444,13 +587,29 @@ export const duplexSchema: { > => ChannelSchema.duplexUnknown(duplex(self, options), options)) /** - * @since 4.0.0 + * Wraps a bidirectional string channel with schema-aware NDJSON encoding and + * decoding. + * + * **Details** + * + * Values sent to the wrapped channel are encoded with `inputSchema`; strings + * received from it are parsed as NDJSON and decoded with `outputSchema`. + * * @category combinators + * @since 4.0.0 */ export const duplexSchemaString: { /** - * @since 4.0.0 + * Wraps a bidirectional string channel with schema-aware NDJSON encoding and + * decoding. + * + * **Details** + * + * Values sent to the wrapped channel are encoded with `inputSchema`; strings + * received from it are parsed as NDJSON and decoded with `outputSchema`. + * * @category combinators + * @since 4.0.0 */ ( options: { @@ -478,8 +637,16 @@ export const duplexSchemaString: { R | In["EncodingServices"] | Out["DecodingServices"] > /** - * @since 4.0.0 + * Wraps a bidirectional string channel with schema-aware NDJSON encoding and + * decoding. + * + * **Details** + * + * Values sent to the wrapped channel are encoded with `inputSchema`; strings + * received from it are parsed as NDJSON and decoded with `outputSchema`. + * * @category combinators + * @since 4.0.0 */ ( self: Channel.Channel< diff --git a/.opencode/node_modules/effect/src/unstable/encoding/Sse.ts b/.opencode/node_modules/effect/src/unstable/encoding/Sse.ts index b6356d7d0244167b870f36b65bd4466f50be45c5..cc7f5dd5e5d752a82513f3a029daa34bd56028a2 100644 --- a/.opencode/node_modules/effect/src/unstable/encoding/Sse.ts +++ b/.opencode/node_modules/effect/src/unstable/encoding/Sse.ts @@ -1,4 +1,11 @@ /** + * Parses and renders Server-Sent Events text streams. + * + * Server-Sent Events, or SSE, are the text format used by `EventSource` for + * one-way server-to-client updates. This module includes parsers, encoders, + * channel helpers, and schema-based helpers for the `id`, `event`, and `data` + * fields of each event. + * * @since 4.0.0 */ import type { NonEmptyReadonlyArray } from "../../Array.ts" @@ -13,11 +20,18 @@ import { hasProperty } from "../../Predicate.ts" import * as Pull from "../../Pull.ts" import * as Result from "../../Result.ts" import * as Schema from "../../Schema.ts" -import * as Transformation from "../../SchemaTransformation.ts" +import * as SchemaTransformation from "../../SchemaTransformation.ts" /** + * Creates a channel that parses Server-Sent Events text chunks into `Event` values. + * + * **Details** + * + * SSE `retry` directives are emitted as `Retry` failures so callers can + * reconnect with the requested delay. + * + * @category decoding * @since 4.0.0 - * @category Decoding */ export const decode = (): Channel.Channel< NonEmptyReadonlyArray, @@ -60,28 +74,49 @@ export const decode = (): Channel.Channel< ) /** + * A constraint for schemas that can decode SSE events. + * + * @category decoding + * @since 4.0.0 + */ +export interface EventCodec extends + Schema.Codec< + any, + { + readonly id?: string | undefined + readonly event?: string | undefined + readonly data: string + }, + any, + any + > +{} + +/** + * Creates an SSE decoder channel that decodes each parsed event with a schema. + * + * **Details** + * + * The schema receives the untagged event shape containing `id`, `event`, and + * string `data`. + * + * @category decoding * @since 4.0.0 - * @category Decoding */ export const decodeSchema = < - Type extends { - readonly id?: string | undefined - readonly event: string - readonly data: string - }, - DecodingServices, + S extends EventCodec, IE, Done >( - schema: Schema.Decoder + schema: S ): Channel.Channel< - NonEmptyReadonlyArray, + NonEmptyReadonlyArray, IE | Retry | Schema.SchemaError, Done, NonEmptyReadonlyArray, IE, Done, - DecodingServices + S["DecodingServices"] > => Channel.pipeTo( decode(), @@ -91,8 +126,15 @@ export const decodeSchema = < ) /** + * Creates an SSE decoder channel that JSON-decodes each event `data` field with a schema. + * + * **Details** + * + * The output preserves the SSE `event` name and optional `id` while replacing + * `data` with the decoded value. + * + * @category decoding * @since 4.0.0 - * @category Decoding */ export const decodeDataSchema = ( schema: Schema.Decoder @@ -115,17 +157,23 @@ export const decodeDataSchema = ( }) return Channel.pipeTo( decode(), - ChannelSchema.decode(eventSchema)() + Channel.map( + ChannelSchema.decode(eventSchema)(), + Arr.map((event) => ({ ...event, id: event.id })) + ) ) } /** - * Create a SSE parser. + * Creates a stateful Server-Sent Events parser. + * + * **Details** * - * Adapted from https://github.com/rexxars/eventsource-parser under MIT license. + * Call `feed` with text chunks to parse `Event` and `Retry` values through the + * callback, and call `reset` to clear any buffered event state. * + * @category decoding * @since 4.0.0 - * @category Decoding */ export function makeParser(onParse: (event: AnyEvent) => void): Parser { // Processing state @@ -286,8 +334,14 @@ function hasBom(buffer: string) { } /** + * Stateful Server-Sent Events parser returned by `makeParser`. + * + * **Details** + * + * `feed` accepts additional text chunks and `reset` clears buffered parser state. + * + * @category decoding * @since 4.0.0 - * @category Decoding */ export interface Parser { feed(chunk: string): void @@ -295,8 +349,15 @@ export interface Parser { } /** + * Creates a channel that encodes `Event` values as Server-Sent Events text. + * + * **Details** + * + * If the upstream channel fails with `Retry`, the retry directive is written and + * the encoder completes. + * + * @category encoding * @since 4.0.0 - * @category Encoding */ export const encode = (): Channel.Channel< NonEmptyReadonlyArray, @@ -322,14 +383,18 @@ export const encode = (): Channel.Channel< ) /** + * Creates an SSE encoder channel for values accepted by a schema. + * + * **Details** + * + * Values are schema-encoded to the untagged SSE event shape, transformed to + * `Event`, and then written as Server-Sent Events text. + * + * @category encoding * @since 4.0.0 - * @category Encoding */ export const encodeSchema = < - S extends Schema.Encoder< - { readonly id?: string | undefined; readonly event: string; readonly data: string }, - unknown - >, + S extends EventCodec, IE, Done >(schema: S): Channel.Channel< @@ -348,16 +413,21 @@ export const encodeSchema = < ) /** + * Encoder capable of rendering an `Event` or `Retry` value as Server-Sent + * Events text. + * + * @category encoding * @since 4.0.0 - * @category Encoding */ export interface Encoder { write(event: AnyEvent): string } /** + * Tagged model for a Server-Sent Events message containing the event name, optional event ID, and string data payload. + * + * @category models * @since 4.0.0 - * @category Models */ export interface Event { readonly _tag: "Event" @@ -367,22 +437,26 @@ export interface Event { } /** + * Schema for the untagged Server-Sent Events payload shape containing an optional `id`, `event`, and string `data` fields. + * + * @category models * @since 4.0.0 - * @category Models */ export const EventEncoded: Schema.Struct<{ - readonly id: Schema.UndefinedOr + readonly id: Schema.optional readonly event: Schema.String readonly data: Schema.String }> = Schema.Struct({ - id: Schema.UndefinedOr(Schema.String), + id: Schema.optional(Schema.String), event: Schema.String, data: Schema.String }) /** + * Schema for the tagged Server-Sent Events message model that adds `_tag: "Event"` to the event name, optional event ID, and string data payload. + * + * @category models * @since 4.0.0 - * @category Models */ export const Event: Schema.Struct<{ readonly _tag: Schema.tag<"Event"> @@ -397,12 +471,15 @@ export const Event: Schema.Struct<{ }) /** + * Schema for transforming untagged SSE event payloads into tagged `Event` + * models. + * + * @category models * @since 4.0.0 - * @category Models */ -export const transformEvent = Transformation.transform<{ +export const transformEvent = SchemaTransformation.transform<{ readonly id?: string | undefined - readonly event: string + readonly event?: string | undefined readonly data: string }, { readonly _tag: "Event" @@ -414,42 +491,57 @@ export const transformEvent = Transformation.transform<{ encode: (event) => ({ _tag: "Event", id: event.id, - event: event.event, + event: event.event ?? "message", data: event.data }) }) /** + * Untagged Server-Sent Events payload shape containing the event name, optional event ID, and string data payload. + * + * @category models * @since 4.0.0 - * @category Models */ export interface EventEncoded { readonly event: string - readonly id: string | undefined + readonly id?: string | undefined readonly data: string } const RetryTypeId = "~effect/encoding/Sse/Retry" as const /** + * Represents a Server-Sent Events retry directive. + * + * **Details** + * + * Decoders surface this value as a failure to request reconnection after + * `duration`; encoders serialize an upstream `Retry` failure as a `retry:` line. + * + * @category models * @since 4.0.0 - * @category Models */ export class Retry extends Data.TaggedClass("Retry")<{ readonly duration: Duration.Duration readonly lastEventId: string | undefined }> { /** + * Marks this value as an SSE retry directive for runtime guards. + * * @since 4.0.0 */ readonly [RetryTypeId]: typeof RetryTypeId = RetryTypeId /** + * Returns `true` when the value is an SSE retry directive. + * * @since 4.0.0 */ static is(u: unknown): u is Retry { return hasProperty(u, RetryTypeId) } /** + * Separates SSE retry directives from regular event values. + * * @since 4.0.0 */ static filter(u: A): Result.Result> { @@ -458,14 +550,24 @@ export class Retry extends Data.TaggedClass("Retry")<{ } /** + * Union of SSE values that can be rendered by an `Encoder`: regular events and + * retry directives. + * + * @category models * @since 4.0.0 - * @category Models */ export type AnyEvent = Event | Retry /** + * Default Server-Sent Events encoder. + * + * **Details** + * + * It renders `Event` values as `id`, `event`, and `data` lines and renders + * `Retry` values as `retry:` directives. + * + * @category encoding * @since 4.0.0 - * @category Encoding */ export const encoder: Encoder = { write(event: AnyEvent): string { diff --git a/.opencode/node_modules/effect/src/unstable/eventlog/Event.ts b/.opencode/node_modules/effect/src/unstable/eventlog/Event.ts index 58e6fcedb9712c6e1ae627030486b9f259ee908c..f40709ea88f2587b68ddbee49aa59d0fc55f80ab 100644 --- a/.opencode/node_modules/effect/src/unstable/eventlog/Event.ts +++ b/.opencode/node_modules/effect/src/unstable/eventlog/Event.ts @@ -1,4 +1,13 @@ /** + * Typed event definitions for the unstable event-log system. + * + * An `Event` is the durable contract shared by writers, handlers, journals, and + * replicas. It gives an event a stable tag, derives the aggregate or entity + * primary key from the decoded payload, and records the schemas used for the + * payload, handler result, and handler errors. The payload schema is also used + * to derive the MessagePack encoding for journal entries and remote + * replication. + * * @since 4.0.0 */ import { pipeArguments } from "../../Pipeable.ts" @@ -7,28 +16,39 @@ import * as Schema from "../../Schema.ts" import * as Msgpack from "../encoding/Msgpack.ts" /** + * Unique type identifier used to mark event log event definitions. + * + * @category type IDs * @since 4.0.0 - * @category type ids */ export type TypeId = "~effect/eventlog/Event" /** + * Runtime type identifier used to mark event log event definitions. + * + * @category type IDs * @since 4.0.0 - * @category type ids */ export const TypeId: TypeId = "~effect/eventlog/Event" /** - * @since 4.0.0 + * Returns `true` when a value is an event log event definition. + * * @category guards + * @since 4.0.0 */ export const isEvent = (u: unknown): u is Event => Predicate.hasProperty(u, TypeId) /** - * Represents an event in an EventLog. + * Definition of an event type that can be written to an `EventLog`. + * + * **Details** + * + * An event definition contains its tag, primary-key function, payload schema, + * MessagePack payload schema, success schema, and error schema. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface Event< out Tag extends string, @@ -46,8 +66,15 @@ export interface Event< } /** - * @since 4.0.0 + * Marker service associated with the handler for an event tag. + * + * **Details** + * + * `ToService` derives this service from an `Event` so handler layers can expose + * which events they implement. + * * @category models + * @since 4.0.0 */ export interface EventHandler { readonly _: unique symbol @@ -55,8 +82,15 @@ export interface EventHandler { } /** - * @since 4.0.0 + * Type-erased event log event definition. + * + * **Details** + * + * It preserves the runtime tag, primary-key function, payload schema, success + * schema, and error schema without retaining the original type parameters. + * * @category models + * @since 4.0.0 */ export interface Any { readonly [TypeId]: TypeId @@ -69,14 +103,19 @@ export interface Any { } /** - * @since 4.0.0 + * Type-erased event definition with its runtime properties available + * structurally. + * * @category models + * @since 4.0.0 */ export interface AnyWithProps extends Any {} /** - * @since 4.0.0 + * Derives the handler service marker for an event definition. + * * @category models + * @since 4.0.0 */ export type ToService = A extends Event< infer _Tag, @@ -87,8 +126,10 @@ export type ToService = A extends Event< never /** - * @since 4.0.0 + * Extracts the tag string from an event definition. + * * @category models + * @since 4.0.0 */ export type Tag = A extends Event< infer _Tag, @@ -99,8 +140,10 @@ export type Tag = A extends Event< never /** - * @since 4.0.0 + * Extracts the error schema from an event definition. + * * @category models + * @since 4.0.0 */ export type ErrorSchema = A extends Event< infer _Tag, @@ -111,14 +154,19 @@ export type ErrorSchema = A extends Event< : never /** - * @since 4.0.0 + * Decoded error value type for an event definition. + * * @category models + * @since 4.0.0 */ export type Error = Schema.Schema.Type> /** - * @since 4.0.0 + * Returns an event definition type whose error schema also includes the provided + * error schema. + * * @category models + * @since 4.0.0 */ export type AddError = A extends Event< infer _Tag, @@ -129,8 +177,10 @@ export type AddError = A extends Event< : never /** - * @since 4.0.0 + * Extracts the payload schema from an event definition. + * * @category models + * @since 4.0.0 */ export type PayloadSchema = A extends Event< infer _Tag, @@ -141,8 +191,10 @@ export type PayloadSchema = A extends Event< : never /** - * @since 4.0.0 + * Extracts the payload schema for the event in a union with the specified tag. + * * @category models + * @since 4.0.0 */ export type PayloadSchemaWithTag = A extends Event< Tag, @@ -153,14 +205,23 @@ export type PayloadSchemaWithTag = A extends : never /** - * @since 4.0.0 + * Decoded payload value type for an event definition. + * * @category models + * @since 4.0.0 */ export type Payload = Schema.Schema.Type> /** - * @since 4.0.0 + * Tagged payload value for an event definition. + * + * **Details** + * + * The result contains `_tag` set to the event tag and `payload` set to the + * decoded payload value. + * * @category models + * @since 4.0.0 */ export type TaggedPayload = A extends Event< infer _Tag, @@ -174,8 +235,10 @@ export type TaggedPayload = A extends Event< : never /** - * @since 4.0.0 + * Extracts the success schema from an event definition. + * * @category models + * @since 4.0.0 */ export type SuccessSchema = A extends Event< infer _Tag, @@ -186,14 +249,23 @@ export type SuccessSchema = A extends Event< : never /** - * @since 4.0.0 + * Decoded success value type for an event definition. + * * @category models + * @since 4.0.0 */ export type Success = Schema.Schema.Type> /** - * @since 4.0.0 + * Schema services required by a client for an event definition. + * + * **Details** + * + * This includes payload encoding services plus success and error decoding + * services. + * * @category models + * @since 4.0.0 */ export type ServicesClient = A extends Event< infer _Tag, @@ -207,8 +279,15 @@ export type ServicesClient = A extends Event< : never /** - * @since 4.0.0 + * Schema services required by a server for an event definition. + * + * **Details** + * + * This includes payload decoding services plus success and error encoding + * services. + * * @category models + * @since 4.0.0 */ export type ServicesServer = A extends Event< infer _Tag, @@ -222,8 +301,11 @@ export type ServicesServer = A extends Event< : never /** - * @since 4.0.0 + * All schema services required to encode and decode the payload, success, and + * error schemas for an event definition. + * * @category models + * @since 4.0.0 */ export type Services = A extends Event< infer _Tag, @@ -240,38 +322,51 @@ export type Services = A extends Event< : never /** - * @since 4.0.0 + * Extracts the event definition with the specified tag from an event union. + * * @category models + * @since 4.0.0 */ export type WithTag = Extract /** - * @since 4.0.0 + * Removes event definitions with the specified tag from an event union. + * * @category models + * @since 4.0.0 */ export type ExcludeTag = Exclude /** - * @since 4.0.0 + * Decoded payload value type for the event in a union with the specified tag. + * * @category models + * @since 4.0.0 */ export type PayloadWithTag = Payload> /** - * @since 4.0.0 + * Decoded success value type for the event in a union with the specified tag. + * * @category models + * @since 4.0.0 */ export type SuccessWithTag = Success> /** - * @since 4.0.0 + * Decoded error value type for the event in a union with the specified tag. + * * @category models + * @since 4.0.0 */ export type ErrorWithTag = Error> /** - * @since 4.0.0 + * Client-side schema services required for the event in a union with the specified + * tag. + * * @category models + * @since 4.0.0 */ export type ServicesClientWithTag = ServicesClient> @@ -283,8 +378,16 @@ const Proto = { } /** - * @since 4.0.0 + * Creates an event log event definition. + * + * **Details** + * + * If omitted, the payload and success schemas default to `Schema.Void`, the error + * schema defaults to `Schema.Never`, and the MessagePack payload schema is derived + * from the payload schema. + * * @category constructors + * @since 4.0.0 */ export function make< Tag extends string, @@ -319,8 +422,15 @@ export function make(options: { } /** - * @since 4.0.0 + * Adds another error schema to an event definition. + * + * **Details** + * + * The returned event keeps the same tag, primary key, payload, and success schema + * while replacing the error schema with a union of the existing and new errors. + * * @category constructors + * @since 4.0.0 */ export function addError( event: A, diff --git a/.opencode/node_modules/effect/src/unstable/eventlog/EventGroup.ts b/.opencode/node_modules/effect/src/unstable/eventlog/EventGroup.ts index c35f0662199ba7f82c2720ac3269fe0451ff6e9c..d814c006c0ba89481c98df4cf1c4472cdd35817e 100644 --- a/.opencode/node_modules/effect/src/unstable/eventlog/EventGroup.ts +++ b/.opencode/node_modules/effect/src/unstable/eventlog/EventGroup.ts @@ -1,4 +1,12 @@ /** + * Defines groups of typed events for the unstable event-log system. + * + * An `EventGroup` collects event definitions that belong together. Start with + * `empty`, add events with their payload, success, and error schemas, then use + * the group to build clients with `EventLog.schema` and server handlers with + * `EventLog.group`. The group only describes events; it does not write or run + * them. + * * @since 4.0.0 */ import { type Pipeable, pipeArguments } from "../../Pipeable.ts" @@ -8,31 +16,40 @@ import type * as Schema from "../../Schema.ts" import * as Event from "./Event.ts" /** + * Unique type identifier used to mark event log event groups. + * + * @category type IDs * @since 4.0.0 - * @category type ids */ export type TypeId = "~effect/eventlog/EventGroup" /** + * Runtime type identifier used to mark event log event groups. + * + * @category type IDs * @since 4.0.0 - * @category type ids */ export const TypeId: TypeId = "~effect/eventlog/EventGroup" /** - * @since 4.0.0 + * Returns `true` when a value is an event log event group. + * * @category guards + * @since 4.0.0 */ export const isEventGroup = (u: unknown): u is Any => Predicate.hasProperty(u, TypeId) /** - * An `EventGroup` is a collection of `Event`s. You can use an `EventGroup` to - * represent a portion of your domain. + * Typed collection of event definitions that represents a portion of an event log + * domain. * - * The events can be implemented later using the `EventLogBuilder.group` api. + * **When to use** + * + * Use when build groups from `empty.add(...)`, then provide implementations for the events + * with `EventLog.group`. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface EventGroup< out Events extends Event.Any = Event.Any @@ -63,42 +80,54 @@ export interface EventGroup< } /** - * @since 4.0.0 + * Type-erased marker for an event log event group. + * * @category models + * @since 4.0.0 */ export interface Any { readonly [TypeId]: TypeId } /** - * @since 4.0.0 + * Type-erased event group with its events record available structurally. + * * @category models + * @since 4.0.0 */ export type AnyWithProps = EventGroup /** - * @since 4.0.0 + * Derives the handler service markers required for all events in an event group. + * * @category models + * @since 4.0.0 */ export type ToService = A extends EventGroup ? Event.ToService<_Events> : never /** - * @since 4.0.0 + * Extracts the union of event definitions contained in an event group. + * * @category models + * @since 4.0.0 */ export type Events = Group extends EventGroup ? _Events : never /** - * @since 4.0.0 + * Client-side schema services required by all events in an event group. + * * @category models + * @since 4.0.0 */ export type ServicesClient = Event.ServicesClient> /** - * @since 4.0.0 + * Server-side schema services required by all events in an event group. + * * @category models + * @since 4.0.0 */ export type ServicesServer = Event.ServicesServer> @@ -151,12 +180,14 @@ const makeProto = < } /** - * An `EventGroup` is a collection of `Event`s. You can use an `EventGroup` to - * represent a portion of your domain. + * Creates an empty event group used as the starting point for defining a group. * - * The events can be implemented later using the `EventLog.group` api. + * **When to use** + * + * Use when you need the starting `EventGroup` value before adding event + * definitions with `.add(...)`. * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const empty: EventGroup = makeProto({ events: Record.empty() }) diff --git a/.opencode/node_modules/effect/src/unstable/eventlog/EventJournal.ts b/.opencode/node_modules/effect/src/unstable/eventlog/EventJournal.ts index 9315059c06d2ed9b22eff2bae0ebee37b2dd72b0..f89b50df5bebddc2161e9204aa1e5af7d4029b26 100644 --- a/.opencode/node_modules/effect/src/unstable/eventlog/EventJournal.ts +++ b/.opencode/node_modules/effect/src/unstable/eventlog/EventJournal.ts @@ -1,4 +1,14 @@ /** + * Stores event-log entries and replication state. + * + * `EventJournal` records committed entries, exposes them for replay, publishes + * local changes, and tracks the remote metadata needed to exchange entries with + * other journals. Higher-level event-log schemas and handlers use this service + * to rebuild projections, sync offline clients, import remote changes, and + * coordinate writes per store. This module also defines journal errors, entry + * and remote identifiers, schemas, and in-memory or IndexedDB-backed journal + * layers. + * * @since 4.0.0 */ import * as Uuid from "uuid" @@ -17,8 +27,15 @@ import * as Msgpack from "../encoding/Msgpack.ts" import type { StoreId } from "./EventLogMessage.ts" /** - * @since 4.0.0 + * Context service for storing and replaying event journal entries. + * + * **Details** + * + * The service writes local entries, imports entries from remote journals, exposes + * a stream of local changes, and provides per-store locking. + * * @category context + * @since 4.0.0 */ export class EventJournal extends Context.Service { /** + * Marks this value as an event journal error for runtime guards. + * * @since 4.0.0 */ readonly [TypeId] = TypeId } /** + * Brand identifier used for `RemoteId` values. + * + * @category type IDs * @since 4.0.0 - * @category remote */ export type RemoteIdTypeId = "effect/eventlog/EventJournal/RemoteId" /** + * Runtime brand identifier used for `RemoteId` values. + * + * @category type IDs * @since 4.0.0 - * @category remote */ export const RemoteIdTypeId: RemoteIdTypeId = "effect/eventlog/EventJournal/RemoteId" /** - * @since 4.0.0 + * Branded byte identifier for a remote event journal source. + * * @category remote + * @since 4.0.0 */ export type RemoteId = Uint8Array & Brand /** - * @since 4.0.0 + * Schema for branded remote event journal identifiers. + * * @category remote + * @since 4.0.0 */ export const RemoteId = Schema.Uint8Array.pipe(Schema.brand(RemoteIdTypeId)) /** - * @since 4.0.0 + * Generates a new random `RemoteId`. + * + * **When to use** + * + * Use when generating a fresh event-log remote id internally and the UUID bytes + * are trusted to satisfy the brand. + * + * **Gotchas** + * + * This is unsafe because the generated UUID bytes are cast to the brand without + * schema validation. + * * @category remote + * @since 4.0.0 */ export const makeRemoteIdUnsafe = (): RemoteId => Uuid.v4({}, new globalThis.Uint8Array(16)) as RemoteId /** + * Runtime brand identifier used for `EntryId` values. + * + * @category type IDs * @since 4.0.0 - * @category entry */ export const EntryIdTypeId: EntryIdTypeId = "effect/eventlog/EventJournal/EntryId" /** + * Brand identifier used for `EntryId` values. + * + * @category type IDs * @since 4.0.0 - * @category entry */ export type EntryIdTypeId = "effect/eventlog/EventJournal/EntryId" /** - * @since 4.0.0 + * Branded byte identifier for an event journal entry. + * * @category entry + * @since 4.0.0 */ export type EntryId = Uint8Array & Brand /** - * @since 4.0.0 + * Schema for branded event journal entry identifiers. + * * @category entry + * @since 4.0.0 */ export const EntryId = (Schema.Uint8Array as Schema.instanceOf>).pipe( Schema.brand(EntryIdTypeId) ) /** - * @since 4.0.0 + * Provides an Ordering instance for entry identifiers based on their raw UUID bytes. + * * @category entry + * @since 4.0.0 */ export const EntryIdOrder = Order.make((a, b) => { for (let i = 0; i < 16; i++) { @@ -173,15 +230,30 @@ export const EntryIdOrder = Order.make((a, b) => { }) /** - * @since 4.0.0 + * Generates a UUID v7 `EntryId`, optionally using the supplied millisecond + * timestamp. + * + * **When to use** + * + * Use when generating an event-log entry id internally and the UUID v7 bytes + * are trusted to satisfy the brand. + * + * **Gotchas** + * + * This is unsafe because the generated UUID bytes are cast to the brand without + * schema validation. + * * @category entry + * @since 4.0.0 */ export const makeEntryIdUnsafe = (options: { msecs?: number } = {}): EntryId => Uuid.v7(options, new globalThis.Uint8Array(16)) as EntryId /** - * @since 4.0.0 + * Extracts the millisecond timestamp encoded in a UUID v7 `EntryId`. + * * @category entry + * @since 4.0.0 */ export const entryIdMillis = (entryId: EntryId): number => { const bytes = new Uint8Array(8) @@ -190,8 +262,15 @@ export const entryIdMillis = (entryId: EntryId): number => { } /** - * @since 4.0.0 + * Schema for a committed event journal entry. + * + * **Details** + * + * An entry records its ID, event tag, primary key, and MessagePack-encoded + * payload, with helpers for array MessagePack encoding and creation timestamps. + * * @category entry + * @since 4.0.0 */ export class Entry extends Schema.Class("effect/eventlog/EventJournal/Entry")({ id: EntryId, @@ -200,26 +279,36 @@ export class Entry extends Schema.Class("effect/eventlog/EventJournal/Ent payload: Schema.Uint8Array }) { /** + * MessagePack schema for arrays of committed event journal entries. + * * @since 4.0.0 */ static arrayMsgpack = Schema.Array(Msgpack.schema(Entry)) /** + * Encodes arrays of committed entries with the MessagePack entry schema. + * * @since 4.0.0 */ static encodeArray = Schema.encodeUnknownEffect(Entry.arrayMsgpack) /** + * Decodes arrays of committed entries with the MessagePack entry schema. + * * @since 4.0.0 */ static decodeArray = Schema.decodeUnknownEffect(Entry.arrayMsgpack) /** + * Ordering for committed entries by their event journal entry id. + * * @since 4.0.0 */ static Order = Order.make((a, b) => EntryIdOrder(a.id, b.id)) /** + * String representation of the entry id. + * * @since 4.0.0 */ get idString(): string { @@ -227,6 +316,8 @@ export class Entry extends Schema.Class("effect/eventlog/EventJournal/Ent } /** + * Creation timestamp encoded in the UUID v7 entry id, in epoch milliseconds. + * * @since 4.0.0 */ get createdAtMillis(): number { @@ -234,6 +325,8 @@ export class Entry extends Schema.Class("effect/eventlog/EventJournal/Ent } /** + * Creation timestamp encoded in the UUID v7 entry id, as a UTC date-time. + * * @since 4.0.0 */ get createdAt(): DateTime.Utc { @@ -242,8 +335,14 @@ export class Entry extends Schema.Class("effect/eventlog/EventJournal/Ent } /** - * @since 4.0.0 + * Schema for an event journal entry received from a remote source. + * + * **Details** + * + * It pairs the remote sequence number with the journal entry payload. + * * @category entry + * @since 4.0.0 */ export class RemoteEntry extends Schema.Class("effect/eventlog/EventJournal/RemoteEntry")({ remoteSequence: Schema.Number, @@ -251,8 +350,15 @@ export class RemoteEntry extends Schema.Class("effect/eventlog/Even }) {} /** - * @since 4.0.0 + * Creates an in-memory `EventJournal` service. + * + * **Gotchas** + * + * Entries, remote tracking state, and locks live only in the current process and + * are lost when the service is discarded. + * * @category memory + * @since 4.0.0 */ export const makeMemory: Effect.Effect = Effect.gen(function*() { const journal: Array = [] @@ -384,14 +490,29 @@ export const makeMemory: Effect.Effect = Effect.gen(fun }) /** - * @since 4.0.0 + * Layer that provides an in-memory `EventJournal`. + * + * **Gotchas** + * + * All journal data is stored in process memory and is not persisted across layer + * lifetimes. + * * @category memory + * @since 4.0.0 */ export const layerMemory: Layer.Layer = Layer.effect(EventJournal, makeMemory) /** - * @since 4.0.0 + * Creates an `EventJournal` backed by IndexedDB. + * + * **Details** + * + * The journal stores entries and remote replication metadata in the configured + * browser database, publishes local changes, and requires `Scope` so the database + * connection can be closed when the scope ends. + * * @category indexed db + * @since 4.0.0 */ export const makeIndexedDb = (options?: { readonly database?: string @@ -648,8 +769,11 @@ const EntryIdbArray = Schema.Array(Entry) const decodeEntryIdbArray = Schema.decodeUnknownEffect(EntryIdbArray) /** - * @since 4.0.0 + * Provides `EventJournal` using the IndexedDB-backed implementation created by + * `makeIndexedDb`. + * * @category indexed db + * @since 4.0.0 */ export const layerIndexedDb = (options?: { readonly database?: string diff --git a/.opencode/node_modules/effect/src/unstable/eventlog/EventLog.ts b/.opencode/node_modules/effect/src/unstable/eventlog/EventLog.ts index 9be17694f50941735f8ea81d12381f739e9de617..db7b1779f8f45d207139eb508f2f68eca6353eb0 100644 --- a/.opencode/node_modules/effect/src/unstable/eventlog/EventLog.ts +++ b/.opencode/node_modules/effect/src/unstable/eventlog/EventLog.ts @@ -1,4 +1,12 @@ /** + * Runtime for writing typed events to an event journal. + * + * `EventLog` combines event groups, handlers, a journal, local identity, + * optional remote replicas, and reactivity hooks. Writers send typed payloads + * through a client; the matching handler runs first, and the journal entry is + * committed only after the handler succeeds. This module also contains the + * layers and helpers needed to assemble that runtime. + * * @since 4.0.0 */ import * as Context from "../../Context.ts" @@ -28,8 +36,16 @@ import { StoreId } from "./EventLogMessage.ts" import type { EventLogRemote } from "./EventLogRemote.ts" /** + * Service for writing typed event-log events through registered handlers. + * + * **Details** + * + * `write` encodes the event payload, runs the matching handler, commits the entry + * only when the handler succeeds, and exposes access to the underlying journal + * entries and destroy operation. + * + * @category services * @since 4.0.0 - * @category tags */ export class EventLog extends Context.Service>>(options: { @@ -45,8 +61,11 @@ export class EventLog extends Context.Service()("effect/eventlog/EventLog") {} /** + * Service that collects event handlers, compaction handlers, remote replicas, + * and reactivity invalidation keys. + * + * @category services * @since 4.0.0 - * @category Registry */ export class Registry extends Context.Service()("effect/unstable/eventlog/EventLog/Registry") {} /** + * Provides an in-memory `Registry` for event handlers, compactors, remote + * replicas, and reactivity keys. + * + * @category layers * @since 4.0.0 - * @category Registry */ export const layerRegistry = Layer.effect( Registry, @@ -145,8 +167,16 @@ export const layerRegistry = Layer.effect( ) /** + * Context service for an event-log identity containing a public key and redacted + * private key material. + * + * **Details** + * + * The identity is used by remote replication for authentication and by the + * encryption service to derive signing and encryption keys. + * + * @category services * @since 4.0.0 - * @category models */ export class Identity extends Context.Service()("effect/eventlog/EventLog/Identity") {} /** + * Type-level identifier used to brand `EventLogSchema` values. + * + * @category type IDs * @since 4.0.0 - * @category schema */ export type SchemaTypeId = "~effect/eventlog/EventLog/Schema" /** + * Runtime property key used to identify `EventLogSchema` values. + * + * @category type IDs * @since 4.0.0 - * @category schema */ export const SchemaTypeId: SchemaTypeId = "~effect/eventlog/EventLog/Schema" /** + * Returns `true` when a value carries the `EventLogSchema` marker. + * + * @category schemas * @since 4.0.0 - * @category schema */ export const isEventLogSchema = (u: unknown): u is EventLogSchema => Predicate.hasProperty(u, SchemaTypeId) /** + * Schema describing the event groups that can be written through an `EventLog`. + * + * @category schemas * @since 4.0.0 - * @category schema */ export interface EventLogSchema { readonly [SchemaTypeId]: SchemaTypeId @@ -182,8 +220,10 @@ export interface EventLogSchema { } /** + * Creates an `EventLogSchema` from one or more event groups. + * + * @category schemas * @since 4.0.0 - * @category schema */ export const schema = >( ...groups: Groups @@ -196,22 +236,32 @@ export const schema = >( } /** + * Type-level identifier used to brand `Handlers` values. + * + * @category type IDs * @since 4.0.0 - * @category handlers */ export type HandlersTypeId = "~effect/eventlog/EventLog/Handlers" /** + * Runtime property key used to identify `Handlers` values. + * + * @category type IDs * @since 4.0.0 - * @category handlers */ export const HandlersTypeId: HandlersTypeId = "~effect/eventlog/EventLog/Handlers" /** - * Represents a handled `EventGroup`. + * Builder for the handlers associated with an `EventGroup`. + * + * **Details** + * + * The `Events` type parameter tracks the event tags that still need handlers, and + * each call to `handle` records a handler while accumulating any required + * services. * - * @since 4.0.0 * @category handlers + * @since 4.0.0 */ export interface Handlers< R, @@ -245,21 +295,29 @@ export interface Handlers< } /** + * Namespace containing helper types for `Handlers` values and handler-producing + * layers. + * * @since 4.0.0 - * @category handlers */ export declare namespace Handlers { /** - * @since 4.0.0 + * Type that matches any `Handlers` value regardless of its services or remaining + * events. + * * @category handlers + * @since 4.0.0 */ export interface Any { readonly [HandlersTypeId]: unknown } /** - * @since 4.0.0 + * Runtime representation of one registered event handler, including its event + * metadata, captured context, and handler function. + * * @category handlers + * @since 4.0.0 */ export type Item = { readonly event: Event.AnyWithProps @@ -276,8 +334,15 @@ export declare namespace Handlers { } /** - * @since 4.0.0 + * Validates that a handler builder returned all required handlers. + * + * **Details** + * + * If any event tag remains unhandled, the type evaluates to an explanatory + * compile-time error string. + * * @category handlers + * @since 4.0.0 */ export type ValidateReturn = A extends ( | Handlers< @@ -297,8 +362,10 @@ export declare namespace Handlers { `Must return the implemented handlers` /** - * @since 4.0.0 + * Extracts the error type from an effect that produces `Handlers`. + * * @category handlers + * @since 4.0.0 */ export type Error = A extends Effect.Effect< Handlers< @@ -311,8 +378,11 @@ export declare namespace Handlers { never /** - * @since 4.0.0 + * Computes the services required by a `Handlers` value or by an effect that + * produces one, including event schema services. + * * @category handlers + * @since 4.0.0 */ export type Services = A extends Handlers< infer _R, @@ -330,8 +400,15 @@ export declare namespace Handlers { } /** - * @since 4.0.0 + * Context reference for the store id used by event-log writes and remote + * replication. + * + * **Details** + * + * Defaults to the branded store id `"default"`. + * * @category models + * @since 4.0.0 */ export class CurrentStoreId extends Context.Reference("effect/eventlog/EventLog/CurrentStoreId", { defaultValue: constant(StoreId.make("default")) @@ -345,8 +422,11 @@ const RedactedUint8Array = Schema.Uint8ArrayFromBase64.pipe( ) /** + * Schema for an event-log identity with a string public key and redacted + * base64-encoded private key bytes. + * + * @category schemas * @since 4.0.0 - * @category schema */ export const IdentitySchema = Schema.Struct({ publicKey: Schema.String, @@ -363,8 +443,14 @@ const IdentityStringSchema = Schema.StringFromBase64Url.pipe( ) /** - * @since 4.0.0 + * Decodes a base64url identity string produced by `encodeIdentityString`. + * + * **Gotchas** + * + * Invalid input throws a schema decoding error. + * * @category constructors + * @since 4.0.0 */ export const decodeIdentityString = (value: string): Identity["Service"] => { const decoded = Schema.decodeUnknownSync(IdentityStringSchema)(value) @@ -375,8 +461,11 @@ export const decodeIdentityString = (value: string): Identity["Service"] => { } /** - * @since 4.0.0 + * Encodes an event-log identity as a base64url string containing the public key + * and private key bytes. + * * @category constructors + * @since 4.0.0 */ export const encodeIdentityString = (identity: Identity["Service"]): string => Schema.encodeSync(IdentityStringSchema)({ @@ -385,8 +474,11 @@ export const encodeIdentityString = (identity: Identity["Service"]): string => }) /** - * @since 4.0.0 + * Generates a new event-log identity using the configured + * `EventLogEncryption` service. + * * @category constructors + * @since 4.0.0 */ export const makeIdentity: Effect.Effect = EventLogEncryption.EventLogEncryption.use((_) => _.generateIdentity) @@ -425,8 +517,15 @@ const makeHandlers = (options: { }): Handlers => Object.assign(Object.create(handlersProto), options) /** - * @since 4.0.0 + * Creates a layer that registers handlers for every event in an event group. + * + * **Details** + * + * The callback receives a `Handlers` builder; its return type is checked so every + * event in the group is handled. + * * @category handlers + * @since 4.0.0 */ export const group = ( group: EventGroup.EventGroup, @@ -455,8 +554,15 @@ export const group = ( ) as any /** - * @since 4.0.0 + * Registers a compaction handler for an event group. + * + * **Details** + * + * During remote replay, matching entries are decoded, grouped by primary key, and + * passed to the compaction effect, which may write replacement entries. + * * @category compaction + * @since 4.0.0 */ export const groupCompaction = ( group: EventGroup.EventGroup, @@ -546,8 +652,15 @@ export const groupCompaction = ( ) /** - * @since 4.0.0 + * Registers reactivity keys to invalidate when events from a group are written or + * replayed. + * + * **Details** + * + * Pass a single key list for all events or a mapping from event tag to key list. + * * @category reactivity + * @since 4.0.0 */ export const groupReactivity = ( group: EventGroup.EventGroup, @@ -571,8 +684,16 @@ export const groupReactivity = ( ) /** - * @since 4.0.0 + * Builds the effect used to replay entries received from a remote event log. + * + * **Details** + * + * The returned handler decodes the entry and conflicts with the registered event + * schema, runs the matching handler with the supplied identity and store id, logs + * failures, and invalidates configured reactivity keys. + * * @category handlers + * @since 4.0.0 */ export const makeReplayFromRemote = (options: { readonly handlers: ReadonlyMap> @@ -816,8 +937,11 @@ const make = Effect.gen(function*() { }) /** - * @since 4.0.0 + * Provides `EventLog` and `Registry` using the configured `EventJournal` and + * `Identity`. + * * @category layers + * @since 4.0.0 */ export const layerEventLog: Layer.Layer = Layer.effect( EventLog, @@ -828,8 +952,33 @@ export const layerEventLog: Layer.Layer"`. + * + * @see {@link schema} for creating the schema argument from event groups + * @see {@link group} for building the handler layer consumed by this layer + * @see {@link layerEventLog} for installing the runtime and registry without combining a handler layer + * * @category layers + * @since 4.0.0 */ export const layer = ( _schema: EventLogSchema, @@ -844,8 +993,16 @@ export const layer = ( ) /** - * @since 4.0.0 + * Creates a typed client function for writing events defined by an + * `EventLogSchema`. + * + * **Details** + * + * The returned function delegates to the `EventLog` service and preserves each + * event's success and error types. + * * @category client + * @since 4.0.0 */ export const makeClient = ( schema: EventLogSchema diff --git a/.opencode/node_modules/effect/src/unstable/eventlog/EventLogEncryption.ts b/.opencode/node_modules/effect/src/unstable/eventlog/EventLogEncryption.ts index 6d615cdcf4e751f78cbc8451342c05f9174ed9e0..052628a72804a0c337a947574922a5392202e585 100644 --- a/.opencode/node_modules/effect/src/unstable/eventlog/EventLogEncryption.ts +++ b/.opencode/node_modules/effect/src/unstable/eventlog/EventLogEncryption.ts @@ -1,4 +1,11 @@ /** + * Cryptographic service for encrypted event-log replication. + * + * `EventLogEncryption` turns local journal entries into encrypted remote + * payloads and decrypts encrypted changes received from a server. It also + * hashes byte data and creates event-log identities, so remote replication can + * use storage or transport that should not see plaintext event data. + * * @since 4.0.0 */ import * as Context from "../../Context.ts" @@ -12,8 +19,11 @@ import type { Identity } from "./EventLog.ts" import { makeGetIdentityRootSecretMaterial } from "./internal/identityRootSecretDerivation.ts" /** - * @since 4.0.0 + * Schema for an encrypted journal entry paired with the id of the original + * entry. + * * @category models + * @since 4.0.0 */ export const EncryptedEntry = Schema.Struct({ entryId: EntryId, @@ -21,14 +31,19 @@ export const EncryptedEntry = Schema.Struct({ }) /** - * @since 4.0.0 + * Type of an encrypted remote entry, including its remote sequence number, + * initialization vector, entry id, and encrypted entry bytes. + * * @category models + * @since 4.0.0 */ export interface EncryptedRemoteEntry extends Schema.Schema.Type {} /** - * @since 4.0.0 + * Schema for encrypted entries exchanged with a remote event-log server. + * * @category models + * @since 4.0.0 */ export const EncryptedRemoteEntry = Schema.Struct({ sequence: Schema.Number, @@ -46,8 +61,16 @@ const toArrayBuffer = (data: Uint8Array): ArrayBuffer => { const toBufferSource = (data: Uint8Array): ArrayBufferView => new Uint8Array(toArrayBuffer(data)) /** - * @since 4.0.0 + * Service that provides identity generation, entry + * encryption and decryption, and SHA-256 hashing for event-log replication. + * + * **When to use** + * + * Use to provide cryptographic operations required by encrypted event-log + * replication. + * * @category services + * @since 4.0.0 */ export class EventLogEncryption extends Context.Service()("effect/eventlog/EventLogEncryption") {} /** - * @since 4.0.0 + * Creates an `EventLogEncryption` service backed by the Web Crypto `SubtleCrypto` + * APIs from the supplied `Crypto` implementation. + * * @category encryption + * @since 4.0.0 */ export const makeEncryptionSubtle = (crypto: Crypto): Effect.Effect => Effect.sync(() => { @@ -132,8 +158,10 @@ export const makeEncryptionSubtle = (crypto: Crypto): Effect.Effect = Layer.effect( EventLogEncryption, diff --git a/.opencode/node_modules/effect/src/unstable/eventlog/EventLogMessage.ts b/.opencode/node_modules/effect/src/unstable/eventlog/EventLogMessage.ts index d0777d14118f5be92a4f3c9629da6a1417148472..0f5cb629c297c0779bf09070b2e879c6679ed89f 100644 --- a/.opencode/node_modules/effect/src/unstable/eventlog/EventLogMessage.ts +++ b/.opencode/node_modules/effect/src/unstable/eventlog/EventLogMessage.ts @@ -1,4 +1,11 @@ /** + * Defines protocol messages for event-log remote clients and servers. + * + * This module is the shared boundary between `EventLogRemote` clients and + * event-log servers. It defines store ids, protocol errors, the + * hello/authenticate session handshake, remote calls for writes and changes, + * and message formats for encrypted or plaintext journal entries. + * * @since 4.0.0 */ import type { NonEmptyArray, NonEmptyReadonlyArray } from "../../Array.ts" @@ -14,32 +21,47 @@ import type { Identity } from "./EventLog.ts" import { EncryptedEntry, EncryptedRemoteEntry } from "./EventLogEncryption.ts" /** + * Type-level identifier used to brand event-log store ids. + * + * @category type IDs * @since 4.0.0 - * @category StoreId */ export type StoreIdTypeId = "effect/eventlog/EventLog/StoreId" /** + * Runtime brand identifier for event-log store ids. + * + * @category type IDs * @since 4.0.0 - * @category StoreId */ export const StoreIdTypeId: StoreIdTypeId = "effect/eventlog/EventLog/StoreId" /** - * @since 4.0.0 + * Branded string identifying a logical event-log store. + * * @category StoreId + * @since 4.0.0 */ export type StoreId = string & Brand /** - * @since 4.0.0 + * Schema for branded event-log store ids. + * * @category StoreId + * @since 4.0.0 */ export const StoreId = Schema.String.pipe(Schema.brand(StoreIdTypeId)) /** + * Error returned by event-log remote RPCs. + * + * **Details** + * + * It records the request tag, optional identity and store information, a protocol + * error code, and a human-readable message. + * + * @category protocols * @since 4.0.0 - * @category protocol */ export class EventLogProtocolError extends Schema.TaggedErrorClass( "effect/eventlog/EventLogRemote/ProtocolError" @@ -52,8 +74,11 @@ export class EventLogProtocolError extends Schema.TaggedErrorClass("effect/eventlog/EventLogRemote/HelloResponse")({ remoteId: RemoteId, @@ -71,16 +103,22 @@ export class HelloResponse extends Schema.Class("effect/eventlog/ }) {} /** + * RPC used to start an event-log remote session and receive a `HelloResponse`. + * + * @category protocols * @since 4.0.0 - * @category protocol */ export class HelloRpc extends Rpc.make("EventLog.Hello", { success: HelloResponse }) {} /** + * Schema for an authentication request containing the client public key, + * Ed25519 signing public key, signature over the session challenge payload, and + * algorithm name. + * + * @category protocols * @since 4.0.0 - * @category protocol */ export class Authenticate extends Schema.Class("effect/eventlog/EventLogRemote/Authenticate")({ publicKey: Schema.String, @@ -90,8 +128,10 @@ export class Authenticate extends Schema.Class("effect/eventlog/Ev }) {} /** + * RPC used to authenticate a remote event-log session after `HelloRpc`. + * + * @category protocols * @since 4.0.0 - * @category protocol */ export class AuthenticateRpc extends Rpc.make("EventLog.Authenticate", { payload: Authenticate, @@ -99,8 +139,10 @@ export class AuthenticateRpc extends Rpc.make("EventLog.Authenticate", { }) {} /** + * Represents an entire encoded event-log payload in one transport frame. + * + * @category protocols * @since 4.0.0 - * @category protocol */ export class SingleMessage extends Schema.TaggedClass("effect/eventlog/EventLogRemote/SingleMessage")("Single", { @@ -109,8 +151,15 @@ export class SingleMessage {} /** + * Represents one part of a large encoded event-log payload. + * + * **When to use** + * + * Use to divide data into chunks and `join` to reassemble all chunks with + * the same id once every part has arrived. + * + * @category protocols * @since 4.0.0 - * @category protocol */ export class ChunkedMessage extends Schema.TaggedClass("effect/eventlog/EventLogRemote/ChunkedMessage")("Chunked", { @@ -130,6 +179,8 @@ export class ChunkedMessage } /** + * Splits binary event-log message data into numbered chunks. + * * @since 4.0.0 */ static split(id: number, data: Uint8Array): NonEmptyReadonlyArray { @@ -148,6 +199,8 @@ export class ChunkedMessage } /** + * Reassembles all chunks for a message id into the original binary payload. + * * @since 4.0.0 */ static join( @@ -186,8 +239,10 @@ export class ChunkedMessage } /** + * RPC used to send one chunk of a large encoded write payload. + * + * @category protocols * @since 4.0.0 - * @category protocol */ export class WriteChunkedRpc extends Rpc.make("EventLog.WriteChunked", { payload: ChunkedMessage, @@ -195,8 +250,15 @@ export class WriteChunkedRpc extends Rpc.make("EventLog.WriteChunked", { }).middleware(EventLogAuthentication) {} /** + * Schema for encrypted event-log write payloads sent to a remote store. + * + * **Details** + * + * It includes the client public key, target store id, AES-GCM initialization + * vector, and encrypted entries. + * + * @category protocols * @since 4.0.0 - * @category protocol */ export class WriteEntries extends Schema.Class("effect/eventlog/EventLogRemote/WriteEntries")({ publicKey: Schema.String, @@ -213,8 +275,10 @@ export class WriteEntries extends Schema.Class("effect/eventlog/Ev } /** + * Schema for plaintext event-log write payloads sent to a remote store. + * + * @category protocols * @since 4.0.0 - * @category protocol */ export class WriteEntriesUnencrypted extends Schema.Class("effect/eventlog/EventLogRemote/WriteEntriesUnencrypted")({ @@ -232,8 +296,10 @@ export class WriteEntriesUnencrypted } /** + * RPC used to send an encoded write payload that fits in one message. + * + * @category protocols * @since 4.0.0 - * @category protocol */ export class WriteSingleRpc extends Rpc.make("EventLog.WriteSingle", { payload: { @@ -243,8 +309,16 @@ export class WriteSingleRpc extends Rpc.make("EventLog.WriteSingle", { }).middleware(EventLogAuthentication) {} /** + * RPC used to stream remote event-log changes for a public key and store id + * starting at a sequence number. + * + * **Details** + * + * Responses are encoded as either `SingleMessage` values or `ChunkedMessage` + * parts. + * + * @category protocols * @since 4.0.0 - * @category protocol */ export class ChangesRpc extends Rpc.make("EventLog.Changes", { payload: { @@ -265,8 +339,11 @@ export class ChangesRpc extends Rpc.make("EventLog.Changes", { } /** + * RPC group containing the event-log remote handshake, authentication, write, and + * changes endpoints. + * + * @category protocols * @since 4.0.0 - * @category protocol */ export class EventLogRemoteRpcs extends RpcGroup.make( HelloRpc, diff --git a/.opencode/node_modules/effect/src/unstable/eventlog/EventLogRemote.ts b/.opencode/node_modules/effect/src/unstable/eventlog/EventLogRemote.ts index b6646357d5ccd9b581d4a2fe2177b431cdb8f437..c45a835a800acf911cb33072dca692836a27f95d 100644 --- a/.opencode/node_modules/effect/src/unstable/eventlog/EventLogRemote.ts +++ b/.opencode/node_modules/effect/src/unstable/eventlog/EventLogRemote.ts @@ -1,4 +1,13 @@ /** + * Connects a local event log to a remote replica. + * + * `EventLogRemote` writes local entries to another journal, receives remote + * change streams from a sequence number, and can wait until the current + * event-log identity has completed remote authentication. The encrypted + * constructor is the default for browser, edge, or service replicas crossing an + * untrusted network. The unencrypted constructor is intended for trusted + * transports or tests. + * * @since 4.0.0 */ import * as Cache from "../../Cache.ts" @@ -32,8 +41,20 @@ import { encodeSessionAuthPayload, signSessionAuthPayloadBytes } from "./EventLo import { makeGetIdentityRootSecretMaterial } from "./internal/identityRootSecretDerivation.ts" /** + * Service that represents a remote event-log replica. + * + * **When to use** + * + * Use to access or provide a remote event-log replica that can write local + * entries and stream remote changes. + * + * **Details** + * + * It can write local entries to the remote, stream remote changes from a sequence + * number, and run effects only after the supplied identity has authenticated. + * + * @category services * @since 4.0.0 - * @category models */ export class EventLogRemote extends Context.Service()("effect/eventlog/EventLogRemote") {} /** - * @since 4.0.0 + * Error raised by `EventLogRemote` operations, recording the failed method and + * underlying cause. + * * @category errors + * @since 4.0.0 */ export class EventLogRemoteError extends Data.TaggedError("EventLogRemoteError")<{ readonly method: string @@ -88,8 +112,15 @@ const makeAuthenticate = Effect.fnUntraced(function*(options: { }) /** + * Service that provides a typed RPC client for the `EventLogRemoteRpcs` protocol. + * + * **When to use** + * + * Use to provide the RPC client used by remote event-log replicas to + * authenticate, write entries, and subscribe to changes. + * + * @category RPC client * @since 4.0.0 - * @category RpcClient */ export class EventLogRemoteClient extends Context.Service< EventLogRemoteClient, @@ -106,8 +137,17 @@ export class EventLogRemoteClient extends Context.Service< } /** - * @since 4.0.0 + * Creates an `EventLogRemote` from custom write encoding and change decoding + * functions. + * + * **Details** + * + * The remote performs the hello/authentication handshake, retries after forbidden + * responses by re-authenticating, chunks large writes, and registers itself with + * the `Registry` for the current scope. + * * @category constructors + * @since 4.0.0 */ export const makeWith = Effect.fnUntraced(function*({ encodeWrite, decodeChanges }: { readonly encodeWrite: (options: { @@ -251,8 +291,11 @@ class IdentityService extends Context.Service()( ) {} /** - * @since 4.0.0 + * Creates an `EventLogRemote` that encrypts outgoing entries and decrypts + * incoming changes with `EventLogEncryption`. + * * @category constructors + * @since 4.0.0 */ export const makeEncrypted = Effect.gen(function*(): Effect.fn.Return< EventLogRemote["Service"], @@ -284,8 +327,10 @@ export const makeEncrypted = Effect.gen(function*(): Effect.fn.Return< }) /** - * @since 4.0.0 + * Creates an `EventLogRemote` that sends and receives plaintext entry payloads. + * * @category constructors + * @since 4.0.0 */ export const makeUnencrypted: Effect.Effect< EventLogRemote["Service"], @@ -302,8 +347,11 @@ export const makeUnencrypted: Effect.Effect< }) /** + * Provides an encrypted `EventLogRemote` using the remote RPC client and the + * default Web Crypto encryption layer. + * + * @category layers * @since 4.0.0 - * @category Layers */ export const layerEncrypted: Layer.Layer< EventLogRemote, @@ -315,8 +363,10 @@ export const layerEncrypted: Layer.Layer< ) /** + * Provides an unencrypted `EventLogRemote` using the remote RPC client. + * + * @category layers * @since 4.0.0 - * @category Layers */ export const layerUnencrypted: Layer.Layer< EventLogRemote, diff --git a/.opencode/node_modules/effect/src/unstable/eventlog/EventLogServer.ts b/.opencode/node_modules/effect/src/unstable/eventlog/EventLogServer.ts index b7a46bad08733d4e80a080604dd42e0497fccd4a..b41a6731c123141a938cef87e2f8adc33ce8b58d 100644 --- a/.opencode/node_modules/effect/src/unstable/eventlog/EventLogServer.ts +++ b/.opencode/node_modules/effect/src/unstable/eventlog/EventLogServer.ts @@ -1,4 +1,11 @@ /** + * Builds server-side handlers for the event-log remote protocol. + * + * Transport modules use these handlers to expose an event journal to remote + * replicas. The handlers run the hello/authenticate challenge flow, attach the + * authenticated `EventLog.Identity` to later requests, accept single or chunked + * writes, and stream changes back as single or chunked messages. + * * @since 4.0.0 */ import type { NonEmptyReadonlyArray } from "../../Array.ts" @@ -29,8 +36,15 @@ import { import * as EventLogSessionAuth from "./EventLogSessionAuth.ts" /** + * Provides RPC authentication middleware that reads the authenticated + * `EventLog.Identity` from client annotations. + * + * **Details** + * + * Requests without an identity fail with a forbidden `EventLogProtocolError`. + * + * @category layers * @since 4.0.0 - * @category Layers */ export const layerAuthMiddleware: Layer.Layer< EventLogAuthentication @@ -48,8 +62,16 @@ export const layerAuthMiddleware: Layer.Layer< }) /** + * Creates the shared RPC handlers for the event-log remote protocol. + * + * **Details** + * + * The layer manages hello challenges, verifies session authentication, reassembles + * chunked writes, delegates write and change handling to the supplied callbacks, + * and frames large change payloads into chunks. + * + * @category layers * @since 4.0.0 - * @category Layers */ export const layerRpcHandlers = (options: { readonly remoteId: RemoteId @@ -184,8 +206,16 @@ export const layerRpcHandlers = (options: { ) /** + * Annotation that stores partial `ChunkedMessage` data while chunked writes are + * being reassembled. + * + * **When to use** + * + * Use to keep per-client chunk assembly state while handling chunked event-log + * writes. + * + * @category chunked message state * @since 4.0.0 - * @category ChunkedMessage state */ export class ChunkedMessageState extends Context.Reference< Map = RpcServer.layer(EventLogRemoteRpcs).pipe( Layer.provide(layerRpcHandlers) ) /** - * @since 4.0.0 + * Schema for encrypted entries persisted by the encrypted event-log server. + * * @category storage + * @since 4.0.0 */ export class PersistedEntry extends Schema.Class( "effect/eventlog/EventLogServerEncrypted/PersistedEntry" @@ -89,6 +127,8 @@ export class PersistedEntry extends Schema.Class( encryptedEntry: Transferable.Uint8Array }) { /** + * String representation of the encrypted entry id. + * * @since 4.0.0 */ get entryIdString(): string { @@ -97,8 +137,21 @@ export class PersistedEntry extends Schema.Class( } /** - * @since 4.0.0 + * Defines the backing store service used by the encrypted event-log server. + * + * **When to use** + * + * Use to provide durable encrypted event-log persistence for an encrypted + * event-log server layer. + * + * **Details** + * + * It provides the server remote id, stores session authentication bindings, + * persists encrypted entries, and streams encrypted changes for a public key and + * store id. + * * @category storage + * @since 4.0.0 */ export class Storage extends Context.Service @@ -119,8 +172,15 @@ export class Storage extends Context.Service()("effect/eventlog/EventLogServer/Storage") {} /** - * @since 4.0.0 + * Creates an in-memory encrypted server `Storage`. + * + * **Details** + * + * Data, session authentication bindings, and streams are process-local and are + * released with the surrounding scope. + * * @category storage + * @since 4.0.0 */ export const makeStorageMemory: Effect.Effect = Effect.gen(function*() { const knownIds = new Map>() @@ -193,8 +253,10 @@ export const makeStorageMemory: Effect.Effect = Layer.effect(Storage)(makeStorageMemory) diff --git a/.opencode/node_modules/effect/src/unstable/eventlog/EventLogServerUnencrypted.ts b/.opencode/node_modules/effect/src/unstable/eventlog/EventLogServerUnencrypted.ts index babab7ffd68095bb776a075268725d79aea5112c..0f9278a9c8753cc169e542058ac6ecae23b16811 100644 --- a/.opencode/node_modules/effect/src/unstable/eventlog/EventLogServerUnencrypted.ts +++ b/.opencode/node_modules/effect/src/unstable/eventlog/EventLogServerUnencrypted.ts @@ -1,4 +1,14 @@ /** + * Plaintext server implementation for the event-log remote protocol. + * + * This module accepts unencrypted event batches from remote clients, runs the + * registered event handlers, stores journal entries, and streams backlog plus + * live changes through the shared `EventLogServer` RPC protocol. It is intended + * for trusted deployments, local development, and tests where event data does + * not need a server-side encryption layer. The module also provides the + * services and layers needed to authorize requests, map stores, persist entries, + * and install the plaintext server. + * * @since 4.0.0 */ import * as Arr from "../../Array.ts" @@ -33,8 +43,16 @@ import { import * as EventLogServer from "./EventLogServer.ts" /** + * Service that writes plaintext event-log entries directly to + * unencrypted storage through registered event handlers. + * + * **When to use** + * + * Use to access or provide the server service that handles plaintext + * event-log writes. + * + * @category services * @since 4.0.0 - * @category EventLogServerUnencrypted */ export class EventLogServerUnencrypted extends Context.Service( @@ -53,8 +71,11 @@ export class EventLogServerUnencrypted extends Context.Service()("effect/eventlog/EventLogServerUnencrypted") {} /** - * @since 4.0.0 + * Creates a typed server-side write function for events in the supplied + * `EventLogSchema`. + * * @category EventLogServerUnencrypted + * @since 4.0.0 */ export const makeWrite = ( schema: EventLog.EventLogSchema @@ -75,8 +96,16 @@ export const makeWrite = ( > => EventLogServerUnencrypted.useSync((_) => _.makeWrite(schema)) /** + * Provides RPC handlers for the unencrypted event-log server. + * + * **Details** + * + * Incoming plaintext entries are authorized, mapped to a server store, checked + * for conflicts, run through registered handlers, and persisted; change streams + * include compacted backlog entries when compactors are registered. + * + * @category layers * @since 4.0.0 - * @category Layers */ export const layerRpcHandlers: Layer.Layer< Rpc.ToHandler> | EventLogAuthentication, @@ -198,8 +227,10 @@ export const layerRpcHandlers: Layer.Layer< })) /** - * @since 4.0.0 + * Error raised by unencrypted server storage and store mapping operations. + * * @category errors + * @since 4.0.0 */ export class EventLogServerStoreError extends Data.TaggedError("EventLogServerStoreError")<{ readonly reason: "NotFound" | "PersistenceFailure" @@ -209,8 +240,11 @@ export class EventLogServerStoreError extends Data.TaggedError("EventLogServerSt }> {} /** - * @since 4.0.0 + * Error raised when unencrypted server authorization rejects an identity or store + * operation. + * * @category errors + * @since 4.0.0 */ export class EventLogServerAuthError extends Data.TaggedError("EventLogServerAuthError")<{ readonly reason: "Unauthorized" | "Forbidden" @@ -220,8 +254,16 @@ export class EventLogServerAuthError extends Data.TaggedError("EventLogServerAut }> {} /** + * Service that validates unencrypted event-log server + * write access, read access, and identities. + * + * **When to use** + * + * Use to provide authorization checks for plaintext event-log writes, reads, + * and identity authentication. + * + * @category services * @since 4.0.0 - * @category context */ export class EventLogServerAuthorization extends Context.Service()("effect/eventlog/EventLogServerUnencrypted/EventLogServerAuthorization") {} /** + * Service that resolves client-requested store ids to server store ids and checks + * whether a store exists. + * + * **When to use** + * + * Use to map client-visible store identifiers to server storage identifiers + * before authorizing or serving unencrypted event-log requests. + * + * @category services * @since 4.0.0 - * @category context */ export class StoreMapping extends Context.Service @@ -405,8 +471,21 @@ const toCompactedRemoteEntries = (options: { } /** - * @since 4.0.0 + * Runs the registered compactors over a backlog of remote entries. + * + * **When to use** + * + * Use to reduce stored remote entries before replaying them to an unencrypted + * event-log client. + * + * **Details** + * + * Contiguous entries handled by the same compactor may be replaced with compacted + * entries when the replacement count can be mapped back to increasing remote + * sequence numbers; otherwise the original entries are kept. + * * @category compaction + * @since 4.0.0 */ export const compactBacklog = Effect.fnUntraced(function*(options: { readonly remoteEntries: ReadonlyArray @@ -469,8 +548,16 @@ export const compactBacklog = Effect.fnUntraced(function*(options: { }) /** - * @since 4.0.0 + * Creates an in-memory unencrypted server `Storage`. + * + * **Details** + * + * The implementation keeps per-store journals and session authentication bindings + * in memory, publishes live changes, and serializes transactions with a + * semaphore. + * * @category storage + * @since 4.0.0 */ export const makeStorageMemory: Effect.Effect = Effect.gen(function*() { const knownIds = new Map>() @@ -574,14 +661,39 @@ export const makeStorageMemory: Effect.Effect = Layer.effect(Storage)(makeStorageMemory) /** - * @since 4.0.0 + * Creates the `EventLogServerUnencrypted` service from the configured storage and + * registered event handlers. + * + * **When to use** + * + * Use when you need the unencrypted event-log server service from provided + * `Storage` and an event-log `Registry`. + * + * **Details** + * + * The constructed service exposes `makeWrite`, which builds a typed server-side + * write function from an `EventLogSchema`. Each write encodes the payload with + * the event schema, runs the registered handler, and persists the generated + * entry inside `Storage.withTransaction`. + * + * **Gotchas** + * + * The write function dies if the requested event tag is not present in the + * schema passed to `makeWrite`; it does not report that case as a typed failure. + * + * @see {@link makeWrite} for the accessor that retrieves the typed server-side write function from the service environment + * @see {@link layerServer} for the layer form that provides this service together with an event-log `Registry` + * * @category constructors + * @since 4.0.0 */ export const make = Effect.gen(function*() { const storage = yield* Storage @@ -640,8 +752,16 @@ export const make = Effect.gen(function*() { }) /** - * @since 4.0.0 + * Provides `EventLogServerUnencrypted` and an event-log `Registry` using the + * configured unencrypted server `Storage`. + * + * **When to use** + * + * Use to provide the unencrypted event-log server service together with the + * registry needed by event handlers. + * * @category layers + * @since 4.0.0 */ export const layerServer: Layer.Layer< EventLogServerUnencrypted | EventLog.Registry, @@ -652,8 +772,34 @@ export const layerServer: Layer.Layer< ) /** - * @since 4.0.0 + * Builds a full unencrypted event-log RPC server for the supplied schema and + * event-group handler layer. + * + * **When to use** + * + * Use when you need the full unencrypted event-log RPC server layer with + * storage, authorization, RPC protocol, and event-group handler dependencies + * supplied externally. + * + * **Details** + * + * The layer installs `EventLogRemoteRpcs`, wires `layerRpcHandlers`, registers + * the supplied event-group handler layer, and provides `layerServer`, leaving + * only the required infrastructure services in the environment. + * + * **Gotchas** + * + * Entries are persisted and streamed in plaintext. Protect the backing + * `Storage` with the surrounding infrastructure, and use durable storage that + * preserves session authentication bindings when the server must survive + * restarts. + * + * @see {@link layerNoRpcServer} for installing the same unencrypted handlers when an `RpcServer.Protocol` is provided elsewhere + * @see {@link layerRpcHandlers} for wiring the unencrypted RPC handlers directly + * @see {@link layerServer} for constructing the server service and event-log registry without RPC handlers + * * @category layers + * @since 4.0.0 */ export const layer = ( _schema: EventLog.EventLogSchema, @@ -674,8 +820,11 @@ export const layer = ( ) /** - * @since 4.0.0 + * Builds the unencrypted event-log server handlers without installing an + * `RpcServer.Protocol` implementation. + * * @category layers + * @since 4.0.0 */ export const layerNoRpcServer = ( _schema: EventLog.EventLogSchema, diff --git a/.opencode/node_modules/effect/src/unstable/eventlog/EventLogSessionAuth.ts b/.opencode/node_modules/effect/src/unstable/eventlog/EventLogSessionAuth.ts index 20c07a3d00872e37ff3f1cc6ce1256dd756f2eae..e749955443deb7aa8f7460b5c23d647886e4c8ca 100644 --- a/.opencode/node_modules/effect/src/unstable/eventlog/EventLogSessionAuth.ts +++ b/.opencode/node_modules/effect/src/unstable/eventlog/EventLogSessionAuth.ts @@ -1,4 +1,11 @@ /** + * Signs and verifies event-log session authentication payloads. + * + * Remote peers use this challenge-response flow to prove that they control a + * session signing key before sending session traffic. The signed payload + * includes the remote id, a short-lived challenge, the event-log public key, and + * the signing public key in a stable byte format. + * * @since 4.0.0 */ import * as Data from "../../Data.ts" @@ -10,38 +17,79 @@ const textDecoder = new TextDecoder("utf-8", { fatal: true }) const constLengthPrefixBytes = 4 /** - * @since 4.0.0 + * Defines the domain-separation string embedded in canonical session + * authentication payloads. + * + * **When to use** + * + * Use when you need the domain-separation string used to build canonical + * event-log session authentication payloads. + * * @category constants + * @since 4.0.0 */ export const AuthPayloadContext = "eventlog-auth-v1" /** - * @since 4.0.0 + * Defines the required byte length for raw Ed25519 public keys used in session + * authentication. + * + * **When to use** + * + * Use when implementing session-auth serialization or validation that must + * reject public keys with a non-canonical raw byte length. + * * @category constants + * @since 4.0.0 */ export const Ed25519PublicKeyLength = 32 /** - * @since 4.0.0 + * Defines the required byte length for Ed25519 signatures used in session authentication. + * + * **When to use** + * + * Use when implementing session-auth verification that must reject signatures + * with a non-canonical byte length before cryptographic checking. + * * @category constants + * @since 4.0.0 */ export const Ed25519SignatureLength = 64 /** - * @since 4.0.0 + * Defines the number of random bytes generated for a session authentication + * challenge. + * + * **When to use** + * + * Use when you need the challenge size for event-log session authentication. + * * @category constants + * @since 4.0.0 */ export const SessionAuthChallengeLength = 32 /** - * @since 4.0.0 + * Defines the time-to-live, in milliseconds, for a pending session + * authentication challenge. + * + * **When to use** + * + * Use when you need the timeout for pending event-log session authentication + * challenges. + * * @category constants + * @since 4.0.0 */ export const SessionAuthChallengeTimeToLiveMillis = 30_000 /** + * Payload fields that are canonicalized and signed during session + * authentication. + * + * @category models * @since 4.0.0 - * @category model */ export interface SessionAuthPayload { readonly remoteId: string | Uint8Array @@ -51,8 +99,11 @@ export interface SessionAuthPayload { } /** - * @since 4.0.0 + * Error raised while encoding, decoding, signing, verifying, or generating + * session authentication challenges. + * * @category errors + * @since 4.0.0 */ export class EventLogSessionAuthError extends Data.TaggedError("EventLogSessionAuthError")<{ readonly reason: @@ -206,7 +257,11 @@ const encodeRemoteIdField = (remoteId: string | Uint8Array): Uint8Array => : textEncoder.encode(bytesToHex(remoteId)) /** - * Canonical payload format uses ordered big-endian length-prefixed fields: + * Encodes a session authentication payload into the canonical byte format. + * + * **Details** + * + * The canonical payload format uses ordered big-endian length-prefixed fields: * * 1. context (fixed: eventlog-auth-v1) * 2. remoteId @@ -214,8 +269,8 @@ const encodeRemoteIdField = (remoteId: string | Uint8Array): Uint8Array => * 4. publicKey * 5. signingPublicKey bytes * - * @since 4.0.0 * @category encoding + * @since 4.0.0 */ export const encodeSessionAuthPayload = Effect.fnUntraced(function*(payload: SessionAuthPayload) { yield* assertSigningPublicKeyLength(payload.signingPublicKey) @@ -245,8 +300,15 @@ export const encodeSessionAuthPayload = Effect.fnUntraced(function*(payload: Ses }) /** - * @since 4.0.0 + * Decodes a canonical session authentication payload. + * + * **Details** + * + * The decoder validates the context field, UTF-8 fields, signing public key + * length, and rejects truncated or trailing bytes. + * * @category encoding + * @since 4.0.0 */ export const decodeSessionAuthPayload = Effect.fnUntraced( function*(payload: Uint8Array): Effect.fn.Return { @@ -283,8 +345,14 @@ export const decodeSessionAuthPayload = Effect.fnUntraced( ) /** - * @since 4.0.0 + * Creates a canonical session authentication signature with an Ed25519 private key. + * + * **Details** + * + * The private key must be PKCS#8-encoded bytes importable by `SubtleCrypto`. + * * @category signing + * @since 4.0.0 */ export const signSessionAuthPayloadBytes = Effect.fnUntraced(function*(options: { readonly payload: Uint8Array @@ -323,8 +391,16 @@ export const signSessionAuthPayloadBytes = Effect.fnUntraced(function*(options: }) /** - * @since 4.0.0 + * Verifies an Ed25519 signature for canonical session authentication payload + * bytes. + * + * **Details** + * + * The payload, signing public key, and signature lengths are validated before + * calling `SubtleCrypto.verify`. + * * @category verification + * @since 4.0.0 */ export const verifySessionAuthPayloadBytes = Effect.fnUntraced(function*(options: { readonly payload: Uint8Array @@ -358,8 +434,11 @@ export const verifySessionAuthPayloadBytes = Effect.fnUntraced(function*(options }) /** - * @since 4.0.0 + * Encodes a session authentication payload in canonical form and signs it with an + * Ed25519 private key. + * * @category signing + * @since 4.0.0 */ export const signSessionAuthPayload = ( options: SessionAuthPayload & { @@ -376,8 +455,11 @@ export const signSessionAuthPayload = ( ) /** - * @since 4.0.0 + * Encodes a session authentication payload in canonical form and verifies its + * Ed25519 signature. + * * @category verification + * @since 4.0.0 */ export const verifySessionAuthPayload = ( options: SessionAuthPayload & { @@ -395,8 +477,10 @@ export const verifySessionAuthPayload = ( ) /** - * @since 4.0.0 + * Generates a random session authentication challenge using `globalThis.crypto`. + * * @category challenge + * @since 4.0.0 */ export const makeSessionAuthChallenge: Effect.Effect< Uint8Array, @@ -409,8 +493,11 @@ export const makeSessionAuthChallenge: Effect.Effect< }) /** - * @since 4.0.0 + * Verifies an authentication request by requiring the `Ed25519` algorithm and + * checking the signature over the canonical session authentication payload. + * * @category verification + * @since 4.0.0 */ export const verifySessionAuthenticateRequest = Effect.fnUntraced(function*(options: { readonly remoteId: string | Uint8Array diff --git a/.opencode/node_modules/effect/src/unstable/eventlog/SqlEventJournal.ts b/.opencode/node_modules/effect/src/unstable/eventlog/SqlEventJournal.ts index ecd1b3f51574d09ec4bf7613d0c75f0d42d5fd41..d60357457ae388485b73540f6831567197c50b96 100644 --- a/.opencode/node_modules/effect/src/unstable/eventlog/SqlEventJournal.ts +++ b/.opencode/node_modules/effect/src/unstable/eventlog/SqlEventJournal.ts @@ -1,4 +1,11 @@ /** + * SQL-backed persistence for the unstable event-log journal. + * + * This module implements `EventJournal` on top of a `SqlClient`. It stores event + * entries as encoded bytes and stores per-remote sequence metadata in separate + * tables, giving event-log programs a durable journal that can be replayed after + * restart and synchronized with remote journals. + * * @since 4.0.0 */ import * as Uuid from "uuid" @@ -14,8 +21,15 @@ import * as EventJournal from "./EventJournal.ts" type WriteFromRemoteOptions = Parameters[0] /** - * @since 4.0.0 + * Creates an `EventJournal` backed by a SQL database. + * + * **Details** + * + * The constructor creates the entry and remote metadata tables when needed, + * persists local and remote entries, and uses the configured `SqlClient`. + * * @category constructors + * @since 4.0.0 */ export const make = (options?: { readonly entryTable?: string @@ -267,8 +281,32 @@ export const make = (options?: { }) /** - * @since 4.0.0 + * Provides `EventJournal` using the SQL-backed implementation created by + * `make`. + * + * **When to use** + * + * Use when composing a Layer graph that should provide a persistent SQL-backed + * `EventJournal` from an existing `SqlClient` service. + * + * **Details** + * + * The layer delegates to `make(options)`, so the same optional `entryTable` and + * `remotesTable` settings are used and construction requires `SqlClient` and + * may fail with `SqlError`. + * + * **Gotchas** + * + * Layer construction performs the same minimal `CREATE TABLE IF NOT EXISTS` + * setup as `make`; manage indexes and schema migrations outside this layer when + * your SQL schema needs more than the built-in tables. + * + * @see {@link make} for constructing the SQL-backed service directly + * @see {@link EventJournal.layerMemory} for an in-memory `EventJournal` layer + * @see {@link EventJournal.layerIndexedDb} for an IndexedDB-backed `EventJournal` layer + * * @category layers + * @since 4.0.0 */ export const layer = (options?: { readonly entryTable?: string diff --git a/.opencode/node_modules/effect/src/unstable/eventlog/SqlEventLogServerEncrypted.ts b/.opencode/node_modules/effect/src/unstable/eventlog/SqlEventLogServerEncrypted.ts index 1f586cd75209e4d93f767c492e30745c6e5d75a0..892391aa790c8ff9de5450748eafc824121974a3 100644 --- a/.opencode/node_modules/effect/src/unstable/eventlog/SqlEventLogServerEncrypted.ts +++ b/.opencode/node_modules/effect/src/unstable/eventlog/SqlEventLogServerEncrypted.ts @@ -1,4 +1,13 @@ /** + * Stores encrypted event-log server state in SQL. + * + * This module provides the durable `Storage` implementation used by + * `EventLogServerEncrypted` when entries should be stored without exposing + * plaintext event data to the database. It persists the server remote id, + * session authentication bindings, and encrypted entry tables, assigns stable + * sequence numbers, and streams changes. Clients remain responsible for + * encrypting writes and decrypting reads. + * * @since 4.0.0 */ import * as Effect from "../../Effect.ts" @@ -15,8 +24,16 @@ import * as EventLogEncryption from "./EventLogEncryption.ts" import * as EventLogServerEncrypted from "./EventLogServerEncrypted.ts" /** - * @since 4.0.0 + * Creates encrypted event-log server `Storage` backed by SQL. + * + * **Details** + * + * It persists the server remote id, session authentication bindings, and encrypted + * entries in dialect-specific tables, creating per-identity/store entry tables as + * needed. + * * @category constructors + * @since 4.0.0 */ export const makeStorage = (options?: { readonly entryTablePrefix?: string @@ -287,8 +304,10 @@ const decodeSessionAuthBindings = ( ): Effect.Effect, Schema.SchemaError> => decodeSessionAuthBindingRows(rows) /** - * @since 4.0.0 + * Provides encrypted server `Storage` using the SQL-backed implementation. + * * @category layers + * @since 4.0.0 */ export const layerStorage = (options?: { readonly entryTablePrefix?: string @@ -301,8 +320,11 @@ export const layerStorage = (options?: { > => Layer.effect(EventLogServerEncrypted.Storage)(makeStorage(options)) /** - * @since 4.0.0 + * Provides SQL-backed encrypted server `Storage` and supplies the default Web + * Crypto `EventLogEncryption` layer. + * * @category layers + * @since 4.0.0 */ export const layerStorageSubtle = (options?: { readonly entryTablePrefix?: string diff --git a/.opencode/node_modules/effect/src/unstable/eventlog/SqlEventLogServerUnencrypted.ts b/.opencode/node_modules/effect/src/unstable/eventlog/SqlEventLogServerUnencrypted.ts index 3f6e563bd69e7428f10d26845c106c20c48c0cc7..ba38af32b85d2b47207570803ea25c6264148222 100644 --- a/.opencode/node_modules/effect/src/unstable/eventlog/SqlEventLogServerUnencrypted.ts +++ b/.opencode/node_modules/effect/src/unstable/eventlog/SqlEventLogServerUnencrypted.ts @@ -1,4 +1,12 @@ /** + * SQL-backed storage for unencrypted event-log servers. + * + * This module provides the durable `Storage` implementation used by + * `EventLogServerUnencrypted` when remote entries should be stored in a SQL + * database and streamed back to clients by store sequence. It creates + * dialect-specific tables for the server remote id, per-store sequence state, + * plaintext entries, and session authentication bindings. + * * @since 4.0.0 */ import * as Arr from "../../Array.ts" @@ -15,8 +23,16 @@ import { Entry, EntryId, makeRemoteIdUnsafe, RemoteEntry, type RemoteId } from " import * as EventLogServerUnencrypted from "./EventLogServerUnencrypted.ts" /** - * @since 4.0.0 + * Creates unencrypted event-log server `Storage` backed by SQL. + * + * **Details** + * + * The implementation creates tables for the server remote id, store sequences, + * entries, and session authentication bindings, then persists and streams + * plaintext remote entries. + * * @category constructors + * @since 4.0.0 */ export const makeStorage = (options?: { readonly entryTablePrefix?: string @@ -424,8 +440,10 @@ export const makeStorage = (options?: { }).pipe(withTracerDisabled) /** - * @since 4.0.0 + * Provides unencrypted server `Storage` using the SQL-backed implementation. + * * @category layers + * @since 4.0.0 */ export const layerStorage = (options?: { readonly entryTablePrefix?: string diff --git a/.opencode/node_modules/effect/src/unstable/http/Cookies.ts b/.opencode/node_modules/effect/src/unstable/http/Cookies.ts index f4e9c34f8d29a6ae399dca8da6e7502607df16f2..90647addebfff52d59788385ff02eda7a9d61625 100644 --- a/.opencode/node_modules/effect/src/unstable/http/Cookies.ts +++ b/.opencode/node_modules/effect/src/unstable/http/Cookies.ts @@ -1,4 +1,12 @@ /** + * Models HTTP cookies and cookie collections for requests and responses. + * + * A `Cookie` stores a name, value, encoded value, and standard cookie + * attributes. A `Cookies` value is an immutable collection keyed by cookie + * name. This module parses request `Cookie` headers, builds response + * `Set-Cookie` headers, and provides helpers for adding, removing, merging, and + * expiring cookies. + * * @since 4.0.0 */ import * as Data from "../../Data.ts" @@ -11,20 +19,24 @@ import * as Predicate from "../../Predicate.ts" import * as Record from "../../Record.ts" import * as Result from "../../Result.ts" import * as Schema from "../../Schema.ts" -import * as Transformation from "../../SchemaTransformation.ts" +import * as SchemaTransformation from "../../SchemaTransformation.ts" import type * as Types from "../../Types.ts" const TypeId = "~effect/http/Cookies" /** - * @since 4.0.0 + * Returns `true` when a value is a `Cookies` collection. + * * @category refinements + * @since 4.0.0 */ export const isCookies = (u: unknown): u is Cookies => Predicate.hasProperty(u, TypeId) /** - * @since 4.0.0 + * Immutable collection of HTTP cookies keyed by cookie name. + * * @category models + * @since 4.0.0 */ export interface Cookies extends Pipeable, Inspectable.Inspectable { readonly [TypeId]: typeof TypeId @@ -32,14 +44,23 @@ export interface Cookies extends Pipeable, Inspectable.Inspectable { } /** + * Schema interface for validating and encoding `Cookies` collections. + * + * @category schemas * @since 4.0.0 - * @category Schemas */ export interface CookiesSchema extends Schema.declare> {} /** + * Schema for `Cookies` collections. + * + * **Details** + * + * JSON encoding uses `Set-Cookie` header strings, while isomorphic encoding uses + * a readonly record of cookie values. + * + * @category schemas * @since 4.0.0 - * @category Schemas */ export const CookiesSchema: CookiesSchema = Schema.declare( isCookies, @@ -57,7 +78,7 @@ export const CookiesSchema: CookiesSchema = Schema.declare( toCodecJson: () => Schema.link()( Schema.Array(Schema.String), - Transformation.transform({ + SchemaTransformation.transform({ decode: (input) => fromSetCookie(input), encode: (cookies) => toSetCookieHeaders(cookies) }) @@ -65,7 +86,7 @@ export const CookiesSchema: CookiesSchema = Schema.declare( toCodecIso: () => Schema.link()( Schema.Record(Schema.String, CookieSchema), - Transformation.transform({ + SchemaTransformation.transform({ decode: (input) => fromReadonlyRecord(input), encode: (cookies) => cookies.cookies }) @@ -76,8 +97,11 @@ export const CookiesSchema: CookiesSchema = Schema.declare( const CookieTypeId = "~effect/http/Cookies/Cookie" /** + * HTTP cookie value with its decoded value, encoded value, and optional cookie + * attributes such as domain, path, expiration, security, and same-site settings. + * + * @category cookies * @since 4.0.0 - * @category cookie */ export interface Cookie extends Inspectable.Inspectable { readonly [CookieTypeId]: typeof CookieTypeId @@ -98,20 +122,26 @@ export interface Cookie extends Inspectable.Inspectable { } /** + * Returns `true` when a value is a `Cookie`. + * + * @category guards * @since 4.0.0 - * @category Guards */ export const isCookie = (u: unknown): u is Cookie => Predicate.hasProperty(u, CookieTypeId) /** + * Schema interface for validating `Cookie` values. + * + * @category schemas * @since 4.0.0 - * @category Schemas */ export interface CookieSchema extends Schema.declare {} /** + * Schema for `Cookie` values. + * + * @category schemas * @since 4.0.0 - * @category Schemas */ export const CookieSchema: CookieSchema = Schema.declare( isCookie, @@ -131,8 +161,11 @@ export const CookieSchema: CookieSchema = Schema.declare( const CookieErrorTypeId = "~effect/http/Cookies/CookieError" /** - * @since 4.0.0 + * Error reason describing why cookie construction failed, such as invalid name, + * value, domain, path, or infinite max-age. + * * @category errors + * @since 4.0.0 */ export class CookiesErrorReason extends Data.Error<{ readonly _tag: @@ -145,13 +178,21 @@ export class CookiesErrorReason extends Data.Error<{ }> {} /** - * @since 4.0.0 + * Error returned when a cookie name, value, domain, path, or max-age option is invalid. + * + * **Details** + * + * Inspect `reason` to determine the specific validation failure. + * * @category errors + * @since 4.0.0 */ export class CookiesError extends Data.TaggedError("CookieError")<{ readonly reason: CookiesErrorReason }> { /** + * Creates a cookie error from a reason tag and optional cause. + * * @since 4.0.0 */ static fromReason(reason: CookiesError["reason"]["_tag"], cause?: unknown): CookiesError { @@ -159,11 +200,15 @@ export class CookiesError extends Data.TaggedError("CookieError")<{ } /** + * Marks this value as a cookie validation error for runtime guards. + * * @since 4.0.0 */ readonly [CookieErrorTypeId] = CookieErrorTypeId /** + * Uses the concrete cookie error reason as the public message. + * * @since 4.0.0 */ override get message() { @@ -186,10 +231,10 @@ const Proto: Omit = { } /** - * Create a Cookies object from an Iterable + * Creates a `Cookies` collection from an existing readonly record of cookies keyed by cookie name. * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fromReadonlyRecord = (cookies: Record.ReadonlyRecord): Cookies => { const self = Object.create(Proto) @@ -200,8 +245,8 @@ export const fromReadonlyRecord = (cookies: Record.ReadonlyRecord): Cookies => { const record: Record = {} @@ -214,8 +259,8 @@ export const fromIterable = (cookies: Iterable): Cookies => { /** * Create a Cookies object from a set of Set-Cookie headers * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const fromSetCookie = (headers: Iterable | string): Cookies => { const arrayHeaders = typeof headers === "string" ? [headers] : headers @@ -364,14 +409,16 @@ function parseSetCookie(header: string): Cookie | undefined { /** * An empty Cookies object * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const empty: Cookies = fromIterable([]) /** - * @since 4.0.0 + * Returns `true` when the `Cookies` collection contains no cookies. + * * @category refinements + * @since 4.0.0 */ export const isEmpty = (self: Cookies): boolean => Record.isEmptyRecord(self.cookies) @@ -392,10 +439,14 @@ const CookieProto = { } /** - * Create a new cookie + * Creates a cookie, validating the name, encoded value, domain, path, and finite `maxAge`. + * + * **Details** + * + * Returns a `CookiesError` in the `Result` failure channel when validation fails. * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export function makeCookie( name: string, @@ -435,8 +486,8 @@ export function makeCookie( /** * Create a new cookie, throwing an error if invalid * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const makeCookieUnsafe = ( name: string, @@ -445,24 +496,24 @@ export const makeCookieUnsafe = ( ): Cookie => Result.getOrThrow(makeCookie(name, value, options)) /** - * Add a cookie to a Cookies object + * Adds a cookie to a Cookies object * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const setCookie: { /** - * Add a cookie to a Cookies object + * Adds a cookie to a Cookies object * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (cookie: Cookie): (self: Cookies) => Cookies /** - * Add a cookie to a Cookies object + * Adds a cookie to a Cookies object * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Cookies, cookie: Cookie): Cookies } = dual( @@ -476,24 +527,24 @@ export const setCookie: { ) /** - * Add multiple cookies to a Cookies object + * Adds multiple cookies to a Cookies object * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const setAllCookie: { /** - * Add multiple cookies to a Cookies object + * Adds multiple cookies to a Cookies object * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (cookies: Iterable): (self: Cookies) => Cookies /** - * Add multiple cookies to a Cookies object + * Adds multiple cookies to a Cookies object * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Cookies, cookies: Iterable): Cookies } = dual(2, (self: Cookies, cookies: Iterable) => { @@ -505,24 +556,24 @@ export const setAllCookie: { }) /** - * Combine two Cookies objects, removing duplicates from the first + * Combines two Cookies objects, removing duplicates from the first * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const merge: { /** - * Combine two Cookies objects, removing duplicates from the first + * Combines two Cookies objects, removing duplicates from the first * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (that: Cookies): (self: Cookies) => Cookies /** - * Combine two Cookies objects, removing duplicates from the first + * Combines two Cookies objects, removing duplicates from the first * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Cookies, that: Cookies): Cookies } = dual(2, (self: Cookies, that: Cookies) => @@ -532,47 +583,47 @@ export const merge: { })) /** - * Remove a cookie by name + * Removes a cookie by name * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const remove: { /** - * Remove a cookie by name + * Removes a cookie by name * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (name: string): (self: Cookies) => Cookies /** - * Remove a cookie by name + * Removes a cookie by name * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Cookies, name: string): Cookies } = dual(2, (self: Cookies, name: string) => fromReadonlyRecord(Record.remove(self.cookies, name))) /** - * Get a cookie from a Cookies object + * Gets a cookie from a Cookies object safely. * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const get: { /** - * Get a cookie from a Cookies object + * Gets a cookie from a Cookies object safely. * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (name: string): (self: Cookies) => Option.Option /** - * Get a cookie from a Cookies object + * Gets a cookie from a Cookies object safely. * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Cookies, name: string): Option.Option } = dual( @@ -581,24 +632,36 @@ export const get: { ) /** - * Get a cookie from a Cookies object + * Gets the decoded value of a cookie by name safely. + * + * **Details** + * + * Returns `Option.none()` when the cookie is not present. * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const getValue: { /** - * Get a cookie from a Cookies object + * Gets the decoded value of a cookie by name safely. + * + * **Details** + * + * Returns `Option.none()` when the cookie is not present. * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (name: string): (self: Cookies) => Option.Option /** - * Get a cookie from a Cookies object + * Gets the decoded value of a cookie by name safely. + * + * **Details** + * + * Returns `Option.none()` when the cookie is not present. * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Cookies, name: string): Option.Option } = dual( @@ -607,24 +670,36 @@ export const getValue: { ) /** - * Add a cookie to a Cookies object + * Creates and adds a cookie safely by name and value. + * + * **Details** + * + * The cookie fields are validated first; invalid input returns a `CookiesError` in the `Result` failure channel. * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const set: { /** - * Add a cookie to a Cookies object + * Creates and adds a cookie safely by name and value. + * + * **Details** + * + * The cookie fields are validated first; invalid input returns a `CookiesError` in the `Result` failure channel. * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (name: string, value: string, options?: Cookie["options"]): (self: Cookies) => Result.Result /** - * Add a cookie to a Cookies object + * Creates and adds a cookie safely by name and value. + * + * **Details** + * + * The cookie fields are validated first; invalid input returns a `CookiesError` in the `Result` failure channel. * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Cookies, name: string, value: string, options?: Cookie["options"]): Result.Result } = dual( @@ -637,24 +712,24 @@ export const set: { ) /** - * Add a cookie to a Cookies object + * Creates and adds a cookie by name and value, throwing if the cookie fields are invalid. * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const setUnsafe: { /** - * Add a cookie to a Cookies object + * Creates and adds a cookie by name and value, throwing if the cookie fields are invalid. * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (name: string, value: string, options?: Cookie["options"]): (self: Cookies) => Cookies /** - * Add a cookie to a Cookies object + * Creates and adds a cookie by name and value, throwing if the cookie fields are invalid. * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ (self: Cookies, name: string, value: string, options?: Cookie["options"]): Cookies } = dual( @@ -668,27 +743,39 @@ export const setUnsafe: { ) /** - * Add an expired cookie to a Cookies object + * Adds an expired cookie safely with an empty value, `Max-Age=0`, and an epoch `Expires` value. + * + * **Details** + * + * Returns a `CookiesError` in the `Result` failure channel when the name or options are invalid. * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const expireCookie: { /** - * Add an expired cookie to a Cookies object + * Adds an expired cookie safely with an empty value, `Max-Age=0`, and an epoch `Expires` value. + * + * **Details** + * + * Returns a `CookiesError` in the `Result` failure channel when the name or options are invalid. * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ ( name: string, options?: Omit, "expires" | "maxAge"> ): (self: Cookies) => Result.Result /** - * Add an expired cookie to a Cookies object + * Adds an expired cookie safely with an empty value, `Max-Age=0`, and an epoch `Expires` value. + * + * **Details** + * + * Returns a `CookiesError` in the `Result` failure channel when the name or options are invalid. * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ ( self: Cookies, @@ -710,27 +797,27 @@ export const expireCookie: { ) /** - * Add an expired cookie to a Cookies object, throwing an error if invalid + * Adds an expired cookie to a Cookies object, throwing an error if invalid * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const expireCookieUnsafe: { /** - * Add an expired cookie to a Cookies object, throwing an error if invalid + * Adds an expired cookie to a Cookies object, throwing an error if invalid * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ ( name: string, options?: Omit, "expires" | "maxAge"> ): (self: Cookies) => Cookies /** - * Add an expired cookie to a Cookies object, throwing an error if invalid + * Adds an expired cookie to a Cookies object, throwing an error if invalid * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ ( self: Cookies, @@ -752,26 +839,38 @@ export const expireCookieUnsafe: { ) /** - * Add multiple cookies to a Cookies object + * Creates and adds multiple cookies safely from name/value/options tuples. + * + * **Details** + * + * If any tuple is invalid, returns the first `CookiesError` and leaves the original collection unchanged. * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const setAll: { /** - * Add multiple cookies to a Cookies object + * Creates and adds multiple cookies safely from name/value/options tuples. + * + * **Details** + * + * If any tuple is invalid, returns the first `CookiesError` and leaves the original collection unchanged. * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ ( cookies: Iterable ): (self: Cookies) => Result.Result /** - * Add multiple cookies to a Cookies object + * Creates and adds multiple cookies safely from name/value/options tuples. + * + * **Details** + * + * If any tuple is invalid, returns the first `CookiesError` and leaves the original collection unchanged. * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ ( self: Cookies, @@ -796,26 +895,26 @@ export const setAll: { ) /** - * Add multiple cookies to a Cookies object, throwing an error if invalid + * Adds multiple cookies to a Cookies object, throwing an error if invalid * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ export const setAllUnsafe: { /** - * Add multiple cookies to a Cookies object, throwing an error if invalid + * Adds multiple cookies to a Cookies object, throwing an error if invalid * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ ( cookies: Iterable ): (self: Cookies) => Cookies /** - * Add multiple cookies to a Cookies object, throwing an error if invalid + * Adds multiple cookies to a Cookies object, throwing an error if invalid * - * @since 4.0.0 * @category combinators + * @since 4.0.0 */ ( self: Cookies, @@ -830,12 +929,14 @@ export const setAllUnsafe: { ) /** - * Serialize a cookie into a string + * Serializes a cookie into a string. + * + * **Details** * * Adapted from https://github.com/fastify/fastify-cookie under MIT License * - * @since 4.0.0 * @category encoding + * @since 4.0.0 */ export function serializeCookie(self: Cookie): string { let str = self.name + "=" + self.valueEncoded @@ -908,17 +1009,19 @@ export function serializeCookie(self: Cookie): string { } /** - * Serialize a Cookies object into a Cookie header + * Serializes a `Cookies` object into a Cookie header. * - * @since 4.0.0 * @category encoding + * @since 4.0.0 */ export const toCookieHeader = (self: Cookies): string => Object.values(self.cookies).map((cookie) => `${cookie.name}=${cookie.valueEncoded}`).join("; ") /** - * @since 4.0.0 + * Converts a `Cookies` collection to a record of decoded cookie values keyed by cookie name. + * * @category encoding + * @since 4.0.0 */ export const toRecord = (self: Cookies): Record => { const record: Record = {} @@ -931,13 +1034,16 @@ export const toRecord = (self: Cookies): Record => { } /** + * Schema for transforming `Cookies` into records of decoded string values keyed + * by cookie name. + * + * @category schemas * @since 4.0.0 - * @category Schemas */ export const schemaRecord = CookiesSchema.pipe( Schema.decodeTo( Schema.Record(Schema.String, Schema.String), - Transformation.transform({ + SchemaTransformation.transform({ decode: toRecord, encode: (self) => fromIterable(Object.entries(self).map(([name, value]) => makeCookieUnsafe(name, value))) }) @@ -945,20 +1051,22 @@ export const schemaRecord = CookiesSchema.pipe( ) /** - * Serialize a Cookies object into Headers object containing one or more Set-Cookie headers + * Serializes a `Cookies` collection into an array of `Set-Cookie` header values. * - * @since 4.0.0 * @category encoding + * @since 4.0.0 */ export const toSetCookieHeaders = (self: Cookies): Array => Object.values(self.cookies).map(serializeCookie) /** - * Parse a cookie header into a record of key-value pairs + * Parses a cookie header into a record of key-value pairs + * + * **Details** * * Adapted from https://github.com/fastify/fastify-cookie under MIT License * - * @since 4.0.0 * @category decoding + * @since 4.0.0 */ export function parseHeader(header: string): Record { const result: Record = {} diff --git a/.opencode/node_modules/effect/src/unstable/http/Etag.ts b/.opencode/node_modules/effect/src/unstable/http/Etag.ts index 433d7c049b23df1f73b63f24bb78601e08a69e89..0a8545b6007c4ae0bda0fd78ef550876609236f9 100644 --- a/.opencode/node_modules/effect/src/unstable/http/Etag.ts +++ b/.opencode/node_modules/effect/src/unstable/http/Etag.ts @@ -1,4 +1,11 @@ /** + * HTTP entity tag values and metadata-based generator layers. + * + * ETags are validators for a specific representation of a resource. Servers put + * them in `ETag` response headers so clients and intermediaries can revalidate + * cached content with `If-None-Match`, or protect writes with preconditions such + * as `If-Match`. + * * @since 4.0.0 */ import * as Context from "../../Context.ts" @@ -9,14 +16,22 @@ import * as Option from "../../Option.ts" import type * as Body from "./HttpBody.ts" /** - * @since 4.0.0 + * Represents an HTTP entity tag, either weak or strong. + * * @category models + * @since 4.0.0 */ export type Etag = Weak | Strong /** - * @since 4.0.0 + * Weak HTTP entity tag. + * + * **Details** + * + * The `value` is the raw tag value without the surrounding quotes or `W/` prefix. + * * @category models + * @since 4.0.0 */ export interface Weak { readonly _tag: "Weak" @@ -24,8 +39,14 @@ export interface Weak { } /** - * @since 4.0.0 + * Strong HTTP entity tag. + * + * **Details** + * + * The `value` is the raw tag value without the surrounding quotes. + * * @category models + * @since 4.0.0 */ export interface Strong { readonly _tag: "Strong" @@ -33,8 +54,10 @@ export interface Strong { } /** + * Formats an `Etag` as an HTTP header value, including quotes and the `W/` prefix for weak tags. + * + * @category converting * @since 4.0.0 - * @category convertions */ export const toString = (self: Etag): string => { switch (self._tag) { @@ -46,8 +69,10 @@ export const toString = (self: Etag): string => { } /** - * @since 4.0.0 + * Service for generating ETags from filesystem file information or Web `File`-like metadata. + * * @category models + * @since 4.0.0 */ export class Generator extends Context.Service Effect.Effect @@ -67,8 +92,25 @@ const fromFileWeb = (file: Body.HttpBody.FileLike) => { } /** + * Layer that provides a `Generator` which produces strong ETags from file size + * and modification time metadata. + * + * **When to use** + * + * Use when you need the `Generator` service to produce strong ETags and file + * size plus modification time reliably change for every byte-level change. + * + * **Gotchas** + * + * This layer marks metadata-derived tags as strong. If the underlying storage + * can update file contents without changing the recorded size or modification + * time, those tags can stop representing byte-for-byte identity. + * + * @see {@link layerWeak} for weak metadata-derived ETags when byte-for-byte identity is not required + * @see {@link Generator} for the service provided by this layer + * + * @category layers * @since 4.0.0 - * @category Layers */ export const layer: Layer.Layer = Layer.succeed( Generator @@ -82,8 +124,10 @@ export const layer: Layer.Layer = Layer.succeed( }) /** + * Layer that provides a `Generator` which produces weak ETags from file size and modification time metadata. + * + * @category layers * @since 4.0.0 - * @category Layers */ export const layerWeak: Layer.Layer = Layer.succeed( Generator diff --git a/.opencode/node_modules/effect/src/unstable/http/FetchHttpClient.ts b/.opencode/node_modules/effect/src/unstable/http/FetchHttpClient.ts index 7f66330ab6eaef42bd3369ef518f2bf48bf9572a..0e3379970fb785c6beafd021a1aea646394f15a6 100644 --- a/.opencode/node_modules/effect/src/unstable/http/FetchHttpClient.ts +++ b/.opencode/node_modules/effect/src/unstable/http/FetchHttpClient.ts @@ -1,4 +1,11 @@ /** + * Fetch-based implementation of the Effect HTTP client service. + * + * This module provides an `HttpClient` layer that executes requests through a + * Web Fetch API implementation. It is the transport to use in browsers, edge + * runtimes, and Node.js environments where `globalThis.fetch` is available, or + * anywhere a compatible fetch function can be supplied. + * * @since 4.0.0 */ import * as Context from "../../Context.ts" @@ -11,16 +18,33 @@ import * as HttpClientError from "./HttpClientError.ts" import * as HttpClientResponse from "./HttpClientResponse.ts" /** + * Context reference for the `fetch` implementation used by the fetch-based HTTP client. + * + * **Details** + * + * Defaults to `globalThis.fetch`. + * + * @category services * @since 4.0.0 - * @category tags */ export const Fetch = Context.Reference("effect/http/FetchHttpClient/Fetch", { defaultValue: () => globalThis.fetch }) /** + * Service that contains default fetch options for the fetch-based HTTP client. + * + * **When to use** + * + * Use to provide default credentials, cache, redirect, integrity, or other + * fetch options for outgoing HTTP requests. + * + * **Details** + * + * Request-specific method, headers, body, and abort signal are supplied by the client when a request is executed. + * + * @category services * @since 4.0.0 - * @category tags */ export class RequestInit extends Context.Service()( "effect/http/FetchHttpClient/RequestInit" @@ -29,7 +53,10 @@ export class RequestInit extends Context.Service { const fetch = fiber.getRef(Fetch) const options: globalThis.RequestInit = fiber.context.mapUnsafe.get(RequestInit.key) ?? {} - const headers = options.headers ? Headers.merge(Headers.fromInput(options.headers), request.headers) : request.headers + let headers = options.headers ? Headers.merge(Headers.fromInput(options.headers), request.headers) : request.headers + if (headers["content-length"]) { + headers = Headers.remove(headers, "content-length") + } const send = (body: BodyInit | undefined) => Effect.map( Effect.tryPromise({ @@ -65,7 +92,32 @@ const fetch: HttpClient.HttpClient = HttpClient.make((request, url, signal, fibe }) /** - * @since 4.0.0 + * Layer that provides an `HttpClient` implementation backed by the configured + * `Fetch` function. + * + * **When to use** + * + * Use when an Effect program should execute `HttpClient` requests through the + * platform `fetch` implementation, especially in browser, edge, or Node.js + * runtimes with `globalThis.fetch`. + * + * **Details** + * + * The layer uses the current `Fetch` reference and optional `RequestInit` + * service for each request. Request-specific method, headers, body, and abort + * signal are supplied by the client and override matching `RequestInit` fields. + * + * **Gotchas** + * + * Fetch behavior comes from the runtime's implementation, so CORS, cookies, + * redirects, abort handling, and streaming support can vary by platform. Stream + * request bodies are sent as Web streams with `duplex: "half"`, and any + * `content-length` header is removed before calling `fetch`. + * + * @see {@link Fetch} for supplying the fetch implementation used by this layer + * @see {@link RequestInit} for default `RequestInit` options applied before request-specific fields + * * @category layers + * @since 4.0.0 */ export const layer: Layer.Layer = HttpClient.layerMergedContext(Effect.succeed(fetch)) diff --git a/.opencode/node_modules/effect/src/unstable/http/FindMyWay.ts b/.opencode/node_modules/effect/src/unstable/http/FindMyWay.ts index 7f1a8d746f04043cb3275a2c57f9aa13f7c94bdf..7507cb4fc81ac033991aa52ca4dcc3f7e65c76de 100644 --- a/.opencode/node_modules/effect/src/unstable/http/FindMyWay.ts +++ b/.opencode/node_modules/effect/src/unstable/http/FindMyWay.ts @@ -1,9 +1,15 @@ /** + * Re-exports the `find-my-way-ts` router package used by the unstable HTTP + * routing modules. + * + * This module keeps the router types and helpers available from the Effect HTTP + * namespace without wrapping or changing them. + * * @since 4.0.0 */ /** - * @since 4.0.0 * @category re-exports + * @since 4.0.0 */ export * from "find-my-way-ts" diff --git a/.opencode/node_modules/effect/src/unstable/http/Headers.ts b/.opencode/node_modules/effect/src/unstable/http/Headers.ts index 93618bd2fdd256340bc328e7188f1c5ac753e1d3..e5291b8a8ffa74ea16b8f45a98ae0016cfe5706c 100644 --- a/.opencode/node_modules/effect/src/unstable/http/Headers.ts +++ b/.opencode/node_modules/effect/src/unstable/http/Headers.ts @@ -1,4 +1,11 @@ /** + * Models HTTP headers for the unstable HTTP client and server modules. + * + * `Headers` values are immutable maps keyed by lowercase header name. This + * module converts common header inputs into that shape, provides helpers for + * reading and updating header values, and redacts configured sensitive headers + * when values are inspected. + * * @since 4.0.0 */ import * as Context from "../../Context.ts" @@ -13,41 +20,52 @@ import * as Record from "../../Record.ts" import * as Redactable from "../../Redactable.ts" import * as Redacted from "../../Redacted.ts" import * as Schema from "../../Schema.ts" -import * as Transformation from "../../SchemaTransformation.ts" +import * as SchemaTransformation from "../../SchemaTransformation.ts" import type { Mutable } from "../../Types.ts" /** - * This is a symbol to allow direct access of keys without conflicts. + * Runtime type identifier for `Headers` values. * + * @category type IDs * @since 4.0.0 - * @category type ids */ export const TypeId: unique symbol = Symbol.for("~effect/http/Headers") /** + * Type of the unique symbol used to brand `Headers` values. + * + * @category type IDs * @since 4.0.0 - * @category type ids */ export type TypeId = typeof TypeId /** - * @since 4.0.0 + * Returns `true` if the provided value is a `Headers` value. + * * @category refinements + * @since 4.0.0 */ export const isHeaders = (u: unknown): u is Headers => Predicate.hasProperty(u, TypeId) /** - * @since 4.0.0 + * Represents an immutable HTTP header collection keyed by lowercase header name. + * + * **Details** + * + * `Headers` values also support redaction through the `Redactable` protocol. + * * @category models + * @since 4.0.0 */ export interface Headers extends Redactable.Redactable { readonly [TypeId]: TypeId readonly [key: string]: string } -const Proto = Object.create(null) - -Object.defineProperties(Proto, { +// the properties are folded into the initializer (rather than a separate +// `Object.defineProperties(Proto, ...)` statement) so the whole definition +// is pure-annotated by the build and tree-shakable. +const Proto = Object.defineProperties(Object.create(null), { [TypeId]: { value: TypeId }, @@ -83,20 +101,31 @@ const make = (input: Record.ReadonlyRecord): Mutable => Object.assign(Object.create(Proto), input) as Headers /** + * Provides an `Equivalence` instance that compares `Headers` by header names + * and string values. + * + * @category instances * @since 4.0.0 - * @category Equivalence */ export const Equivalence: Equ.Equivalence = Record.makeEquivalence(Equ.strictEqual()) /** - * @since 4.0.0 + * Schema interface for `Headers` values encoded as records of string header values. + * * @category schemas + * @since 4.0.0 */ export interface HeadersSchema extends Schema.declare {} /** - * @since 4.0.0 + * Schema for `Headers` values encoded as records of string header values. + * + * **Details** + * + * Decoding normalizes header names through `fromInput`; encoding returns a plain record. + * * @category schemas + * @since 4.0.0 */ export const HeadersSchema: HeadersSchema = Schema.declare( isHeaders, @@ -115,7 +144,7 @@ export const HeadersSchema: HeadersSchema = Schema.declare( toCodec: () => Schema.link()( Schema.Record(Schema.String, Schema.String), - Transformation.transform({ + SchemaTransformation.transform({ decode: (input) => fromInput(input), encode: (headers) => ({ ...headers }) }) @@ -124,22 +153,36 @@ export const HeadersSchema: HeadersSchema = Schema.declare( ) /** - * @since 4.0.0 + * Input accepted when constructing headers. + * + * **Details** + * + * Records may contain string values, string arrays, or `undefined`; arrays are joined with `", "`, and `undefined` values are omitted. + * * @category models + * @since 4.0.0 */ export type Input = | Record.ReadonlyRecord | undefined> | Iterable /** - * @since 4.0.0 + * An empty `Headers` collection. + * * @category constructors + * @since 4.0.0 */ export const empty: Headers = Object.create(Proto) /** - * @since 4.0.0 + * Creates `Headers` from a record or iterable of header entries. + * + * **Details** + * + * Header names are normalized to lowercase. Array values in record input are joined with `", "`, and `undefined` values are omitted. + * * @category constructors + * @since 4.0.0 */ export const fromInput: (input?: Input) => Headers = (input) => { if (input === undefined) { @@ -163,92 +206,188 @@ export const fromInput: (input?: Input) => Headers = (input) => { } /** - * @since 4.0.0 + * Treats an existing record as `Headers` unsafely. + * + * **Gotchas** + * + * This mutates the record's prototype and does not normalize header names; callers must provide the expected lowercase keys. + * * @category constructors + * @since 4.0.0 */ export const fromRecordUnsafe = (input: Record.ReadonlyRecord): Headers => Object.setPrototypeOf(input, Proto) as Headers /** - * @since 4.0.0 + * Returns `true` when a header with the given name is present. + * + * **Details** + * + * The lookup lowercases the provided header name. + * * @category combinators + * @since 4.0.0 */ export const has: { /** - * @since 4.0.0 + * Returns `true` when a header with the given name is present. + * + * **Details** + * + * The lookup lowercases the provided header name. + * * @category combinators + * @since 4.0.0 */ (key: string): (self: Headers) => boolean /** - * @since 4.0.0 + * Returns `true` when a header with the given name is present. + * + * **Details** + * + * The lookup lowercases the provided header name. + * * @category combinators + * @since 4.0.0 */ (self: Headers, key: string): boolean } = dual< /** - * @since 4.0.0 + * Returns `true` when a header with the given name is present. + * + * **Details** + * + * The lookup lowercases the provided header name. + * * @category combinators + * @since 4.0.0 */ (key: string) => (self: Headers) => boolean, /** - * @since 4.0.0 + * Returns `true` when a header with the given name is present. + * + * **Details** + * + * The lookup lowercases the provided header name. + * * @category combinators + * @since 4.0.0 */ (self: Headers, key: string) => boolean >(2, (self, key) => key.toLowerCase() in self) /** - * @since 4.0.0 + * Gets a header value by name safely. + * + * **Details** + * + * The lookup lowercases the provided header name and returns `Option.none()` when absent. + * * @category combinators + * @since 4.0.0 */ export const get: { /** - * @since 4.0.0 + * Gets a header value by name safely. + * + * **Details** + * + * The lookup lowercases the provided header name and returns `Option.none()` when absent. + * * @category combinators + * @since 4.0.0 */ (key: string): (self: Headers) => Option.Option /** - * @since 4.0.0 + * Gets a header value by name safely. + * + * **Details** + * + * The lookup lowercases the provided header name and returns `Option.none()` when absent. + * * @category combinators + * @since 4.0.0 */ (self: Headers, key: string): Option.Option } = dual< /** - * @since 4.0.0 + * Gets a header value by name safely. + * + * **Details** + * + * The lookup lowercases the provided header name and returns `Option.none()` when absent. + * * @category combinators + * @since 4.0.0 */ (key: string) => (self: Headers) => Option.Option, /** - * @since 4.0.0 + * Gets a header value by name safely. + * + * **Details** + * + * The lookup lowercases the provided header name and returns `Option.none()` when absent. + * * @category combinators + * @since 4.0.0 */ (self: Headers, key: string) => Option.Option >(2, (self, key) => Option.fromUndefinedOr(self[key.toLowerCase()])) /** - * @since 4.0.0 + * Returns a new `Headers` collection with the given header set. + * + * **Details** + * + * The header name is normalized to lowercase. + * * @category combinators + * @since 4.0.0 */ export const set: { /** - * @since 4.0.0 + * Returns a new `Headers` collection with the given header set. + * + * **Details** + * + * The header name is normalized to lowercase. + * * @category combinators + * @since 4.0.0 */ (key: string, value: string): (self: Headers) => Headers /** - * @since 4.0.0 + * Returns a new `Headers` collection with the given header set. + * + * **Details** + * + * The header name is normalized to lowercase. + * * @category combinators + * @since 4.0.0 */ (self: Headers, key: string, value: string): Headers } = dual< /** - * @since 4.0.0 + * Returns a new `Headers` collection with the given header set. + * + * **Details** + * + * The header name is normalized to lowercase. + * * @category combinators + * @since 4.0.0 */ (key: string, value: string) => (self: Headers) => Headers, /** - * @since 4.0.0 + * Returns a new `Headers` collection with the given header set. + * + * **Details** + * + * The header name is normalized to lowercase. + * * @category combinators + * @since 4.0.0 */ (self: Headers, key: string, value: string) => Headers >(3, (self, key, value) => { @@ -258,29 +397,59 @@ export const set: { }) /** - * @since 4.0.0 + * Returns a new `Headers` collection with all provided headers set. + * + * **Details** + * + * Input headers are normalized with `fromInput` and override existing headers with the same lowercase name. + * * @category combinators + * @since 4.0.0 */ export const setAll: { /** - * @since 4.0.0 + * Returns a new `Headers` collection with all provided headers set. + * + * **Details** + * + * Input headers are normalized with `fromInput` and override existing headers with the same lowercase name. + * * @category combinators + * @since 4.0.0 */ (headers: Input): (self: Headers) => Headers /** - * @since 4.0.0 + * Returns a new `Headers` collection with all provided headers set. + * + * **Details** + * + * Input headers are normalized with `fromInput` and override existing headers with the same lowercase name. + * * @category combinators + * @since 4.0.0 */ (self: Headers, headers: Input): Headers } = dual< /** - * @since 4.0.0 + * Returns a new `Headers` collection with all provided headers set. + * + * **Details** + * + * Input headers are normalized with `fromInput` and override existing headers with the same lowercase name. + * * @category combinators + * @since 4.0.0 */ (headers: Input) => (self: Headers) => Headers, /** - * @since 4.0.0 + * Returns a new `Headers` collection with all provided headers set. + * + * **Details** + * + * Input headers are normalized with `fromInput` and override existing headers with the same lowercase name. + * * @category combinators + * @since 4.0.0 */ (self: Headers, headers: Input) => Headers >(2, (self, headers) => @@ -290,29 +459,59 @@ export const setAll: { })) /** - * @since 4.0.0 + * Returns a new `Headers` collection containing headers from both collections. + * + * **Details** + * + * Headers from the second collection override headers from the first collection with the same name. + * * @category combinators + * @since 4.0.0 */ export const merge: { /** - * @since 4.0.0 + * Returns a new `Headers` collection containing headers from both collections. + * + * **Details** + * + * Headers from the second collection override headers from the first collection with the same name. + * * @category combinators + * @since 4.0.0 */ (headers: Headers): (self: Headers) => Headers /** - * @since 4.0.0 + * Returns a new `Headers` collection containing headers from both collections. + * + * **Details** + * + * Headers from the second collection override headers from the first collection with the same name. + * * @category combinators + * @since 4.0.0 */ (self: Headers, headers: Headers): Headers } = dual< /** - * @since 4.0.0 + * Returns a new `Headers` collection containing headers from both collections. + * + * **Details** + * + * Headers from the second collection override headers from the first collection with the same name. + * * @category combinators + * @since 4.0.0 */ (headers: Headers) => (self: Headers) => Headers, /** - * @since 4.0.0 + * Returns a new `Headers` collection containing headers from both collections. + * + * **Details** + * + * Headers from the second collection override headers from the first collection with the same name. + * * @category combinators + * @since 4.0.0 */ (self: Headers, headers: Headers) => Headers >(2, (self, headers) => { @@ -322,29 +521,59 @@ export const merge: { }) /** - * @since 4.0.0 + * Returns a new `Headers` collection with the named header removed. + * + * **Details** + * + * The provided header name is normalized to lowercase before removal. + * * @category combinators + * @since 4.0.0 */ export const remove: { /** - * @since 4.0.0 + * Returns a new `Headers` collection with the named header removed. + * + * **Details** + * + * The provided header name is normalized to lowercase before removal. + * * @category combinators + * @since 4.0.0 */ (key: string): (self: Headers) => Headers /** - * @since 4.0.0 + * Returns a new `Headers` collection with the named header removed. + * + * **Details** + * + * The provided header name is normalized to lowercase before removal. + * * @category combinators + * @since 4.0.0 */ (self: Headers, key: string): Headers } = dual< /** - * @since 4.0.0 + * Returns a new `Headers` collection with the named header removed. + * + * **Details** + * + * The provided header name is normalized to lowercase before removal. + * * @category combinators + * @since 4.0.0 */ (key: string) => (self: Headers) => Headers, /** - * @since 4.0.0 + * Returns a new `Headers` collection with the named header removed. + * + * **Details** + * + * The provided header name is normalized to lowercase before removal. + * * @category combinators + * @since 4.0.0 */ (self: Headers, key: string) => Headers >(2, (self, key) => { @@ -354,29 +583,59 @@ export const remove: { }) /** - * @since 4.0.0 + * Returns a new `Headers` collection with each named header removed. + * + * **Details** + * + * Each provided header name is normalized to lowercase before removal. + * * @category combinators + * @since 4.0.0 */ export const removeMany: { /** - * @since 4.0.0 + * Returns a new `Headers` collection with each named header removed. + * + * **Details** + * + * Each provided header name is normalized to lowercase before removal. + * * @category combinators + * @since 4.0.0 */ (keys: Iterable): (self: Headers) => Headers /** - * @since 4.0.0 + * Returns a new `Headers` collection with each named header removed. + * + * **Details** + * + * Each provided header name is normalized to lowercase before removal. + * * @category combinators + * @since 4.0.0 */ (self: Headers, keys: Iterable): Headers } = dual< /** - * @since 4.0.0 + * Returns a new `Headers` collection with each named header removed. + * + * **Details** + * + * Each provided header name is normalized to lowercase before removal. + * * @category combinators + * @since 4.0.0 */ (keys: Iterable) => (self: Headers) => Headers, /** - * @since 4.0.0 + * Returns a new `Headers` collection with each named header removed. + * + * **Details** + * + * Each provided header name is normalized to lowercase before removal. + * * @category combinators + * @since 4.0.0 */ (self: Headers, keys: Iterable) => Headers >(2, (self, keys) => { @@ -388,18 +647,36 @@ export const removeMany: { }) /** - * @since 4.0.0 + * Returns a plain record with selected header values wrapped in `Redacted`. + * + * **Details** + * + * String keys are normalized to lowercase before matching; regular expressions are tested against the stored header names. + * * @category combinators + * @since 4.0.0 */ export const redact: { /** - * @since 4.0.0 + * Returns a plain record with selected header values wrapped in `Redacted`. + * + * **Details** + * + * String keys are normalized to lowercase before matching; regular expressions are tested against the stored header names. + * * @category combinators + * @since 4.0.0 */ (key: string | RegExp | ReadonlyArray): (self: Headers) => Record /** - * @since 4.0.0 + * Returns a plain record with selected header values wrapped in `Redacted`. + * + * **Details** + * + * String keys are normalized to lowercase before matching; regular expressions are tested against the stored header names. + * * @category combinators + * @since 4.0.0 */ (self: Headers, key: string | RegExp | ReadonlyArray): Record } = dual( @@ -435,8 +712,14 @@ export const redact: { ) /** - * @since 4.0.0 + * Context reference listing header names or patterns that should be redacted when `Headers` are inspected or rendered. + * + * **Details** + * + * Defaults include `authorization`, `cookie`, `set-cookie`, and `x-api-key`. + * * @category fiber refs + * @since 4.0.0 */ export const CurrentRedactedNames = Context.Reference< ReadonlyArray diff --git a/.opencode/node_modules/effect/src/unstable/http/HttpBody.ts b/.opencode/node_modules/effect/src/unstable/http/HttpBody.ts index e919a3f52505c1d5c067edf9d298718f38041feb..49ff779cbbf04b201d8425424de61c4198c17d9c 100644 --- a/.opencode/node_modules/effect/src/unstable/http/HttpBody.ts +++ b/.opencode/node_modules/effect/src/unstable/http/HttpBody.ts @@ -1,4 +1,14 @@ /** + * Describes HTTP request and response bodies before they reach a platform + * adapter. + * + * `HttpBody` is the shared body representation used by the HTTP modules. Each + * variant stores the payload together with metadata that can be known before + * sending it, such as `contentType` and `contentLength`. This module includes + * body constructors for common payload shapes, support for schema-encoded JSON + * bodies, streaming and file-backed bodies, and the error type used when body + * construction fails. + * * @since 4.0.0 */ import * as Data from "../../Data.ts" @@ -11,31 +21,47 @@ import * as Predicate from "../../Predicate.ts" import * as Schema from "../../Schema.ts" import type { ParseOptions } from "../../SchemaAST.ts" import type { Issue } from "../../SchemaIssue.ts" -import * as Parser from "../../SchemaParser.ts" +import * as SchemaParser from "../../SchemaParser.ts" import type * as Stream_ from "../../Stream.ts" import * as UrlParams from "./UrlParams.ts" const TypeId = "~effect/http/HttpBody" /** - * @since 4.0.0 + * Returns `true` if the provided value is an `HttpBody`. + * * @category refinements + * @since 4.0.0 */ export const isHttpBody = (u: unknown): u is HttpBody => Predicate.hasProperty(u, TypeId) /** - * @since 4.0.0 + * Represents an HTTP request body. + * + * **Details** + * + * Supported variants include empty bodies, raw bodies, byte arrays, `FormData`, and streams of bytes. + * * @category models + * @since 4.0.0 */ export type HttpBody = Empty | Raw | Uint8Array | FormData | Stream /** + * Namespace containing type-level members associated with `HttpBody`. + * * @since 4.0.0 */ export declare namespace HttpBody { /** - * @since 4.0.0 + * Common protocol implemented by all HTTP body variants. + * + * **Details** + * + * It carries the variant tag plus optional `contentType` and `contentLength` metadata. + * * @category models + * @since 4.0.0 */ export interface Proto extends Inspectable.Inspectable { readonly [TypeId]: typeof TypeId @@ -45,8 +71,10 @@ export declare namespace HttpBody { } /** - * @since 4.0.0 + * Minimal Web `File`-like shape used by HTTP helpers that need file metadata. + * * @category models + * @since 4.0.0 */ export interface FileLike { readonly name: string @@ -60,22 +88,32 @@ export declare namespace HttpBody { const HttpBodyErrorTypeId = "~effect/http/HttpBody/HttpBodyError" /** - * @since 4.0.0 + * Error produced while constructing an HTTP body from JSON or schema-encoded input. + * * @category errors + * @since 4.0.0 */ export class HttpBodyError extends Data.TaggedError("HttpBodyError")<{ readonly reason: ErrorReason readonly cause?: unknown }> { /** + * Marks this value as an HTTP body error for runtime guards. + * * @since 4.0.0 */ readonly [HttpBodyErrorTypeId] = HttpBodyErrorTypeId } /** - * @since 4.0.0 + * Reason for an `HttpBodyError`. + * + * **Details** + * + * `JsonError` represents a `JSON.stringify` failure; `SchemaError` represents a schema encoding issue. + * * @category errors + * @since 4.0.0 */ export type ErrorReason = { readonly _tag: "JsonError" @@ -100,8 +138,10 @@ abstract class Proto implements HttpBody.Proto { } /** - * @since 4.0.0 + * HTTP body variant representing the absence of request content. + * * @category models + * @since 4.0.0 */ export class Empty extends Proto { readonly _tag = "Empty" @@ -114,14 +154,22 @@ export class Empty extends Proto { } /** + * Provides the singleton empty HTTP body. + * + * **When to use** + * + * Use when you need an HTTP body value that represents no body content. + * + * @category constants * @since 4.0.0 - * @category constructors */ export const empty: Empty = new Empty() /** - * @since 4.0.0 + * HTTP body variant containing an arbitrary runtime body value with optional content metadata. + * * @category models + * @since 4.0.0 */ export class Raw extends Proto { readonly _tag = "Raw" @@ -151,8 +199,10 @@ export class Raw extends Proto { } /** - * @since 4.0.0 + * Creates a raw HTTP body from an arbitrary value and optional `contentType` and `contentLength` metadata. + * * @category constructors + * @since 4.0.0 */ export const raw = ( body: unknown, @@ -163,8 +213,14 @@ export const raw = ( ): Raw => new Raw(body, options?.contentType, options?.contentLength) /** - * @since 4.0.0 + * HTTP body variant backed by a `Uint8Array`. + * + * **Details** + * + * It stores the bytes, content type, and byte length. + * * @category models + * @since 4.0.0 */ export class Uint8Array extends Proto { readonly _tag = "Uint8Array" @@ -195,8 +251,14 @@ export class Uint8Array extends Proto { } /** - * @since 4.0.0 + * Creates a byte-array HTTP body. + * + * **Details** + * + * The content type defaults to `application/octet-stream`, and the content length is the byte array length. + * * @category constructors + * @since 4.0.0 */ export const uint8Array = (body: globalThis.Uint8Array, contentType?: string): Uint8Array => new Uint8Array(body, contentType ?? "application/octet-stream", body.length) @@ -204,22 +266,40 @@ export const uint8Array = (body: globalThis.Uint8Array, contentType?: string): U const encoder = new TextEncoder() /** - * @since 4.0.0 + * Creates a UTF-8 encoded text HTTP body. + * + * **Details** + * + * The content type defaults to `text/plain`. + * * @category constructors + * @since 4.0.0 */ export const text = (body: string, contentType?: string): Uint8Array => uint8Array(encoder.encode(body), contentType ?? "text/plain") /** - * @since 4.0.0 + * Creates a JSON HTTP body using `JSON.stringify`, throwing if serialization fails. + * + * **Details** + * + * The content type defaults to `application/json`. + * * @category constructors + * @since 4.0.0 */ export const jsonUnsafe = (body: unknown, contentType?: string): Uint8Array => text(JSON.stringify(body), contentType ?? "application/json") /** - * @since 4.0.0 + * Creates a JSON HTTP body in an `Effect`. + * + * **Details** + * + * `JSON.stringify` failures are captured as `HttpBodyError` values, and the content type defaults to `application/json`. + * * @category constructors + * @since 4.0.0 */ export const json = (body: unknown, contentType?: string): Effect.Effect => Effect.try({ @@ -228,14 +308,20 @@ export const json = (body: unknown, contentType?: string): Effect.Effect( schema: S, options?: ParseOptions | undefined ) => { - const encode = Parser.encodeUnknownEffect(Schema.toCodecJson(schema)) + const encode = SchemaParser.encodeUnknownEffect(Schema.toCodecJson(schema)) return (body: S["Type"], contentType?: string): Effect.Effect => encode(body, options).pipe( Effect.mapError((issue) => new HttpBodyError({ reason: { _tag: "SchemaError", issue }, cause: issue })), @@ -244,15 +330,23 @@ export const jsonSchema = ( } /** - * @since 4.0.0 + * Creates an `application/x-www-form-urlencoded` HTTP body from `UrlParams`. + * * @category constructors + * @since 4.0.0 */ export const urlParams = (urlParams: UrlParams.UrlParams, contentType?: string): Uint8Array => text(UrlParams.toString(urlParams), contentType ?? "application/x-www-form-urlencoded") /** - * @since 4.0.0 + * HTTP body variant backed by Web `FormData`. + * + * **Details** + * + * The content type and content length are left unset so the runtime can supply multipart boundaries. + * * @category models + * @since 4.0.0 */ export class FormData extends Proto { readonly _tag = "FormData" @@ -276,20 +370,34 @@ export class FormData extends Proto { } /** - * @since 4.0.0 + * Wraps a Web `FormData` value as an HTTP body. + * * @category constructors + * @since 4.0.0 */ export const formData = (body: globalThis.FormData): FormData => new FormData(body) /** - * @since 4.0.0 + * Record input accepted by `formDataRecord`. + * + * **Details** + * + * Each field may be a single coercible value or an array of coercible values. + * * @category models + * @since 4.0.0 */ export type FormDataInput = Record> /** - * @since 4.0.0 + * Value that can be appended by `formDataRecord`. + * + * **Details** + * + * `File` and `Blob` values are appended directly, primitive values are converted to strings, and `null` or `undefined` values are skipped. + * * @category models + * @since 4.0.0 */ export type FormDataCoercible = string | number | boolean | globalThis.File | globalThis.Blob | null | undefined @@ -305,8 +413,14 @@ const appendFormDataValue = (formData: globalThis.FormData, key: string, value: } /** - * @since 4.0.0 + * Creates a `FormData` HTTP body from a record. + * + * **Details** + * + * Array fields append each item under the same key; primitive values are stringified, `File` and `Blob` values are appended directly, and nullish values are skipped. + * * @category constructors + * @since 4.0.0 */ export const formDataRecord = (entries: FormDataInput): FormData => { const data = new globalThis.FormData() @@ -323,8 +437,10 @@ export const formDataRecord = (entries: FormDataInput): FormData => { } /** - * @since 4.0.0 + * HTTP body variant backed by a stream of `Uint8Array` chunks. + * * @category models + * @since 4.0.0 */ export class Stream extends Proto { readonly _tag = "Stream" @@ -353,8 +469,14 @@ export class Stream extends Proto { } /** - * @since 4.0.0 + * Creates a streaming HTTP body from a stream of byte chunks. + * + * **Details** + * + * The content type defaults to `application/octet-stream`; content length is optional. + * * @category constructors + * @since 4.0.0 */ export const stream = ( body: Stream_.Stream, @@ -363,8 +485,14 @@ export const stream = ( ): Stream => new Stream(body, contentType ?? "application/octet-stream", contentLength) /** - * @since 4.0.0 + * Creates a streaming HTTP body for a file path. + * + * **Details** + * + * The effect requires `FileSystem`, stats the file to set the content length, and can fail with `PlatformError`. + * * @category constructors + * @since 4.0.0 */ export const file = ( path: string, @@ -376,7 +504,7 @@ export const file = ( } ): Effect.Effect => Effect.flatMap( - FileSystem.FileSystem.asEffect(), + FileSystem.FileSystem, (fs) => Effect.map(fs.stat(path), (info) => stream( @@ -387,8 +515,14 @@ export const file = ( ) /** - * @since 4.0.0 + * Creates a streaming HTTP body for a file path using already-known file information. + * + * **Details** + * + * The effect requires `FileSystem`, uses the provided file size as the content length, and can fail with `PlatformError`. + * * @category constructors + * @since 4.0.0 */ export const fileFromInfo = ( path: string, @@ -401,7 +535,7 @@ export const fileFromInfo = ( } ): Effect.Effect => Effect.map( - FileSystem.FileSystem.asEffect(), + FileSystem.FileSystem, (fs) => stream( fs.stream(path, options), diff --git a/.opencode/node_modules/effect/src/unstable/http/HttpClient.ts b/.opencode/node_modules/effect/src/unstable/http/HttpClient.ts index 07e9c8e92a16e827f75da9a5018a7c4ad608d655..a7b34dcb3866bb7bf934435daae0ede6ef68a3d8 100644 --- a/.opencode/node_modules/effect/src/unstable/http/HttpClient.ts +++ b/.opencode/node_modules/effect/src/unstable/http/HttpClient.ts @@ -1,4 +1,14 @@ /** + * Provides the service used to run outgoing HTTP requests. + * + * `HttpClient` executes immutable `HttpClientRequest` values and returns + * `HttpClientResponse` values. Keeping HTTP behind this service lets programs, + * tests, and generated API clients use the same request model without depending + * on one concrete platform transport. This module includes request accessors, + * constructors and layers, request and response transformations, status + * filtering, retries, rate limiting, cookies, redirect handling, scoped request + * abortion, and tracing support. + * * @since 4.0.0 */ import type { NonEmptyReadonlyArray } from "../../Array.ts" @@ -35,24 +45,36 @@ import * as UrlParams from "./UrlParams.ts" const TypeId = "~effect/http/HttpClient" /** + * Returns `true` if the provided value is an `HttpClient`. + * + * @category guards * @since 4.0.0 - * @category Guards */ export const isHttpClient = (u: unknown): u is HttpClient => Predicate.hasProperty(u, TypeId) /** - * @since 4.0.0 + * HTTP client whose requests produce `HttpClientResponse` values and can fail with `HttpClientError`. + * * @category models + * @since 4.0.0 */ export interface HttpClient extends HttpClient.With {} /** + * Namespace containing type-level members associated with `HttpClient`. + * * @since 4.0.0 */ export declare namespace HttpClient { /** - * @since 4.0.0 + * Parameterized HTTP client that may fail with `E` and require environment `R`. + * + * **Details** + * + * It exposes preprocessing, postprocessing, direct request execution, and method-specific helpers. + * * @category models + * @since 4.0.0 */ export interface With extends Pipeable, Inspectable.Inspectable { readonly [TypeId]: typeof TypeId @@ -93,16 +115,20 @@ export declare namespace HttpClient { } /** - * @since 4.0.0 + * Effectful transformation applied to a request before the client executes it. + * * @category models + * @since 4.0.0 */ export type Preprocess = ( request: HttpClientRequest.HttpClientRequest ) => Effect.Effect /** - * @since 4.0.0 + * Function that turns a preprocessed request effect into the response effect executed by the client. + * * @category models + * @since 4.0.0 */ export type Postprocess = ( request: Effect.Effect @@ -110,8 +136,15 @@ export declare namespace HttpClient { } /** + * Service tag for the default outgoing HTTP client service. + * + * **When to use** + * + * Use to provide the default outgoing HTTP client service used by request + * accessors such as `execute`, `get`, and `post`. + * + * @category services * @since 4.0.0 - * @category tags */ export const HttpClient: Context.Service = Context.Service( "effect/HttpClient" @@ -119,21 +152,25 @@ export const HttpClient: Context.Service = Context.Servi const accessor = (method: keyof HttpClient) => (...args: Array): Effect.Effect => Effect.flatMap( - HttpClient.asEffect(), + HttpClient, (client) => (client as any)[method](...args) ) /** - * @since 4.0.0 + * Executes a prebuilt `HttpClientRequest` using the `HttpClient` service from the environment. + * * @category accessors + * @since 4.0.0 */ export const execute: ( request: HttpClientRequest.HttpClientRequest ) => Effect.Effect = accessor("execute") /** - * @since 4.0.0 + * Executes a `GET` request using the `HttpClient` service from the environment. + * * @category accessors + * @since 4.0.0 */ export const get: (url: string | URL, options?: HttpClientRequest.Options.NoUrl | undefined) => Effect.Effect< HttpClientResponse.HttpClientResponse, @@ -142,8 +179,10 @@ export const get: (url: string | URL, options?: HttpClientRequest.Options.NoUrl > = accessor("get") /** - * @since 4.0.0 + * Executes a `HEAD` request using the `HttpClient` service from the environment. + * * @category accessors + * @since 4.0.0 */ export const head: (url: string | URL, options?: HttpClientRequest.Options.NoUrl | undefined) => Effect.Effect< HttpClientResponse.HttpClientResponse, @@ -152,8 +191,10 @@ export const head: (url: string | URL, options?: HttpClientRequest.Options.NoUrl > = accessor("head") /** - * @since 4.0.0 + * Executes a `POST` request using the `HttpClient` service from the environment. + * * @category accessors + * @since 4.0.0 */ export const post: (url: string | URL, options?: HttpClientRequest.Options.NoUrl | undefined) => Effect.Effect< HttpClientResponse.HttpClientResponse, @@ -162,8 +203,10 @@ export const post: (url: string | URL, options?: HttpClientRequest.Options.NoUrl > = accessor("post") /** - * @since 4.0.0 + * Executes a `PATCH` request using the `HttpClient` service from the environment. + * * @category accessors + * @since 4.0.0 */ export const patch: (url: string | URL, options?: HttpClientRequest.Options.NoUrl | undefined) => Effect.Effect< HttpClientResponse.HttpClientResponse, @@ -172,8 +215,10 @@ export const patch: (url: string | URL, options?: HttpClientRequest.Options.NoUr > = accessor("patch") /** - * @since 4.0.0 + * Executes a `PUT` request using the `HttpClient` service from the environment. + * * @category accessors + * @since 4.0.0 */ export const put: (url: string | URL, options?: HttpClientRequest.Options.NoUrl | undefined) => Effect.Effect< HttpClientResponse.HttpClientResponse, @@ -182,8 +227,10 @@ export const put: (url: string | URL, options?: HttpClientRequest.Options.NoUrl > = accessor("put") /** - * @since 4.0.0 + * Executes a `DELETE` request using the `HttpClient` service from the environment. + * * @category accessors + * @since 4.0.0 */ export const del: (url: string | URL, options?: HttpClientRequest.Options.NoUrl | undefined) => Effect.Effect< HttpClientResponse.HttpClientResponse, @@ -192,8 +239,10 @@ export const del: (url: string | URL, options?: HttpClientRequest.Options.NoUrl > = accessor("del") /** - * @since 4.0.0 + * Executes an `OPTIONS` request using the `HttpClient` service from the environment. + * * @category accessors + * @since 4.0.0 */ export const options: (url: string | URL, options?: HttpClientRequest.Options.NoUrl | undefined) => Effect.Effect< HttpClientResponse.HttpClientResponse, @@ -202,13 +251,25 @@ export const options: (url: string | URL, options?: HttpClientRequest.Options.No > = accessor("options") /** - * @since 4.0.0 + * Transforms a client by wrapping the response effect for each request. + * + * **Details** + * + * The transformation receives both the response effect and the original request, allowing it to change success, error, and environment behavior. + * * @category mapping & sequencing + * @since 4.0.0 */ export const transform: { /** - * @since 4.0.0 + * Transforms a client by wrapping the response effect for each request. + * + * **Details** + * + * The transformation receives both the response effect and the original request, allowing it to change success, error, and environment behavior. + * * @category mapping & sequencing + * @since 4.0.0 */ ( f: ( @@ -217,8 +278,14 @@ export const transform: { ) => Effect.Effect ): (self: HttpClient.With) => HttpClient.With /** - * @since 4.0.0 + * Transforms a client by wrapping the response effect for each request. + * + * **Details** + * + * The transformation receives both the response effect and the original request, allowing it to change success, error, and environment behavior. + * * @category mapping & sequencing + * @since 4.0.0 */ ( self: HttpClient.With, @@ -240,13 +307,17 @@ export const transform: { )) /** - * @since 4.0.0 + * Transforms a client by applying an effectful transformation to each response effect. + * * @category mapping & sequencing + * @since 4.0.0 */ export const transformResponse: { /** - * @since 4.0.0 + * Transforms a client by applying an effectful transformation to each response effect. + * * @category mapping & sequencing + * @since 4.0.0 */ ( f: ( @@ -254,8 +325,10 @@ export const transformResponse: { ) => Effect.Effect ): (self: HttpClient.With) => HttpClient.With /** - * @since 4.0.0 + * Transforms a client by applying an effectful transformation to each response effect. + * * @category mapping & sequencing + * @since 4.0.0 */ ( self: HttpClient.With, @@ -288,20 +361,26 @@ const catch_: { export { /** - * @since 4.0.0 + * Handles all client failures with an effectful recovery function and returns a transformed client. + * * @category error handling + * @since 4.0.0 */ catch_ as catch } /** - * @since 4.0.0 + * Handles client failures with one or more matching `_tag` values and returns a transformed client. + * * @category error handling + * @since 4.0.0 */ export const catchTag: { /** - * @since 4.0.0 + * Handles client failures with one or more matching `_tag` values and returns a transformed client. + * * @category error handling + * @since 4.0.0 */ | NonEmptyReadonlyArray>, E, E1, R1>( tag: K, @@ -312,8 +391,10 @@ export const catchTag: { self: HttpClient.With ) => HttpClient.With ? K[number] : K>, R1 | R> /** - * @since 4.0.0 + * Handles client failures with one or more matching `_tag` values and returns a transformed client. + * * @category error handling + * @since 4.0.0 */ | NonEmptyReadonlyArray>, R1, E1>( self: HttpClient.With, @@ -331,17 +412,71 @@ export const catchTag: { e: ExtractTag ? K[number] : K> ) => Effect.Effect ): HttpClient.With ? K[number] : K>, R1 | R> => - transformResponse(self, Effect.catchTag(tag, f)) + transformResponse( + self, + (effect) => + Effect.catchTag( + effect, + tag, + f + ) + ) ) /** - * @since 4.0.0 + * Handles client failures by matching their `_tag` values against a case map. + * * @category error handling + * @since 4.0.0 */ export const catchTags: { /** - * @since 4.0.0 + * Handles client failures by matching their `_tag` values against a case map. + * * @category error handling + * @since 4.0.0 */ < E, @@ -365,8 +500,10 @@ export const catchTags: { }[keyof Cases] > /** - * @since 4.0.0 + * Handles client failures by matching their `_tag` values against a case map. + * * @category error handling + * @since 4.0.0 */ < E extends { _tag: string }, @@ -432,15 +569,15 @@ export const catchTags: { /** * Filters the result of a response, or runs an alternative effect if the predicate fails. * - * @since 4.0.0 * @category filters + * @since 4.0.0 */ export const filterOrElse: { /** * Filters the result of a response, or runs an alternative effect if the predicate fails. * - * @since 4.0.0 * @category filters + * @since 4.0.0 */ ( refinement: Predicate.Refinement, B>, @@ -456,8 +593,8 @@ export const filterOrElse: { /** * Filters the result of a response, or runs an alternative effect if the predicate fails. * - * @since 4.0.0 * @category filters + * @since 4.0.0 */ ( predicate: Predicate.Predicate>, @@ -468,8 +605,8 @@ export const filterOrElse: { /** * Filters the result of a response, or runs an alternative effect if the predicate fails. * - * @since 4.0.0 * @category filters + * @since 4.0.0 */ ( self: HttpClient.With, @@ -486,8 +623,8 @@ export const filterOrElse: { /** * Filters the result of a response, or runs an alternative effect if the predicate fails. * - * @since 4.0.0 * @category filters + * @since 4.0.0 */ ( self: HttpClient.With, @@ -499,37 +636,37 @@ export const filterOrElse: { } = 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. + * Filters successful responses, or fails with the error produced by `orFailWith` when the predicate does not match. * - * @since 4.0.0 * @category filters + * @since 4.0.0 */ export const filterOrFail: { /** - * Filters the result of a response, or throws an error if the predicate fails. + * Filters successful responses, or fails with the error produced by `orFailWith` when the predicate does not match. * - * @since 4.0.0 * @category filters + * @since 4.0.0 */ ( refinement: Predicate.Refinement, B>, orFailWith: (response: NoInfer) => E2 ): (self: HttpClient.With) => HttpClient.With /** - * Filters the result of a response, or throws an error if the predicate fails. + * Filters successful responses, or fails with the error produced by `orFailWith` when the predicate does not match. * - * @since 4.0.0 * @category filters + * @since 4.0.0 */ ( predicate: Predicate.Predicate>, orFailWith: (response: NoInfer) => E2 ): (self: HttpClient.With) => HttpClient.With /** - * Filters the result of a response, or throws an error if the predicate fails. + * Filters successful responses, or fails with the error produced by `orFailWith` when the predicate does not match. * - * @since 4.0.0 * @category filters + * @since 4.0.0 */ ( self: HttpClient.With, @@ -537,10 +674,10 @@ export const filterOrFail: { orFailWith: (response: NoInfer) => E2 ): HttpClient.With /** - * Filters the result of a response, or throws an error if the predicate fails. + * Filters successful responses, or fails with the error produced by `orFailWith` when the predicate does not match. * - * @since 4.0.0 * @category filters + * @since 4.0.0 */ ( self: HttpClient.With, @@ -552,22 +689,22 @@ export const filterOrFail: { /** * Filters responses by HTTP status code. * - * @since 4.0.0 * @category filters + * @since 4.0.0 */ export const filterStatus: { /** * Filters responses by HTTP status code. * - * @since 4.0.0 * @category filters + * @since 4.0.0 */ (f: (status: number) => boolean): (self: HttpClient.With) => HttpClient.With /** * Filters responses by HTTP status code. * - * @since 4.0.0 * @category filters + * @since 4.0.0 */ (self: HttpClient.With, f: (status: number) => boolean): HttpClient.With } = dual( @@ -579,15 +716,21 @@ export const filterStatus: { /** * Filters responses that return a 2xx status code. * - * @since 4.0.0 * @category filters + * @since 4.0.0 */ export const filterStatusOk: (self: HttpClient.With) => HttpClient.With = transformResponse(Effect.flatMap(HttpClientResponse.filterStatusOk)) /** - * @since 4.0.0 + * Constructs an `HttpClient.With` from a preprocessing function and a postprocessing function. + * + * **Details** + * + * `execute` applies preprocessing to the request and then passes the resulting request effect to postprocessing. + * * @category constructors + * @since 4.0.0 */ export const makeWith = ( postprocess: ( @@ -625,8 +768,14 @@ const Proto = { } /** - * @since 4.0.0 + * Constructs an `HttpClient` from a low-level request runner. + * + * **Details** + * + * The runner receives the request, resolved URL, abort signal, and current fiber. The client wrapper handles URL construction failures, tracing and propagation, header redaction, and aborting non-scoped requests on interruption. + * * @category constructors + * @since 4.0.0 */ export const make = ( f: ( @@ -728,15 +877,15 @@ export const make = ( /** * Appends a transformation of the request object before sending it. * - * @since 4.0.0 * @category mapping & sequencing + * @since 4.0.0 */ export const mapRequest: { /** * Appends a transformation of the request object before sending it. * - * @since 4.0.0 * @category mapping & sequencing + * @since 4.0.0 */ ( f: (a: HttpClientRequest.HttpClientRequest) => HttpClientRequest.HttpClientRequest @@ -744,8 +893,8 @@ export const mapRequest: { /** * Appends a transformation of the request object before sending it. * - * @since 4.0.0 * @category mapping & sequencing + * @since 4.0.0 */ ( self: HttpClient.With, @@ -762,15 +911,15 @@ export const mapRequest: { /** * Appends an effectful transformation of the request object before sending it. * - * @since 4.0.0 * @category mapping & sequencing + * @since 4.0.0 */ export const mapRequestEffect: { /** * Appends an effectful transformation of the request object before sending it. * - * @since 4.0.0 * @category mapping & sequencing + * @since 4.0.0 */ ( f: (a: HttpClientRequest.HttpClientRequest) => Effect.Effect @@ -778,8 +927,8 @@ export const mapRequestEffect: { /** * Appends an effectful transformation of the request object before sending it. * - * @since 4.0.0 * @category mapping & sequencing + * @since 4.0.0 */ ( self: HttpClient.With, @@ -797,15 +946,15 @@ export const mapRequestEffect: { /** * Prepends a transformation of the request object before sending it. * - * @since 4.0.0 * @category mapping & sequencing + * @since 4.0.0 */ export const mapRequestInput: { /** * Prepends a transformation of the request object before sending it. * - * @since 4.0.0 * @category mapping & sequencing + * @since 4.0.0 */ ( f: (a: HttpClientRequest.HttpClientRequest) => HttpClientRequest.HttpClientRequest @@ -813,8 +962,8 @@ export const mapRequestInput: { /** * Prepends a transformation of the request object before sending it. * - * @since 4.0.0 * @category mapping & sequencing + * @since 4.0.0 */ ( self: HttpClient.With, @@ -831,15 +980,15 @@ export const mapRequestInput: { /** * Prepends an effectful transformation of the request object before sending it. * - * @since 4.0.0 * @category mapping & sequencing + * @since 4.0.0 */ export const mapRequestInputEffect: { /** * Prepends an effectful transformation of the request object before sending it. * - * @since 4.0.0 * @category mapping & sequencing + * @since 4.0.0 */ ( f: (a: HttpClientRequest.HttpClientRequest) => Effect.Effect @@ -847,8 +996,8 @@ export const mapRequestInputEffect: { /** * Prepends an effectful transformation of the request object before sending it. * - * @since 4.0.0 * @category mapping & sequencing + * @since 4.0.0 */ ( self: HttpClient.With, @@ -864,13 +1013,20 @@ export const mapRequestInputEffect: { ) /** + * Namespace containing type-level helpers for retrying HTTP clients. + * * @since 4.0.0 - * @category error handling */ export declare namespace Retry { /** - * @since 4.0.0 + * Computes the client type returned by `retry` for a given set of retry options. + * + * **Details** + * + * The result includes errors and requirements introduced by schedules and effectful retry predicates. + * * @category error handling + * @since 4.0.0 */ export type Return, O>> = HttpClient.With< | (O extends { schedule: Schedule.Schedule } ? E | _E @@ -889,36 +1045,36 @@ export declare namespace Retry { /** * Retries the request based on a provided schedule or policy. * - * @since 4.0.0 * @category error handling + * @since 4.0.0 */ export const retry: { /** * Retries the request based on a provided schedule or policy. * - * @since 4.0.0 * @category error handling + * @since 4.0.0 */ , O>>(options: O): (self: HttpClient.With) => Retry.Return /** * Retries the request based on a provided schedule or policy. * - * @since 4.0.0 * @category error handling + * @since 4.0.0 */ (policy: Schedule.Schedule, ES, R1>): (self: HttpClient.With) => HttpClient.With /** * Retries the request based on a provided schedule or policy. * - * @since 4.0.0 * @category error handling + * @since 4.0.0 */ , O>>(self: HttpClient.With, options: O): Retry.Return /** * Retries the request based on a provided schedule or policy. * - * @since 4.0.0 * @category error handling + * @since 4.0.0 */ (self: HttpClient.With, policy: Schedule.Schedule): HttpClient.With } = dual( @@ -932,25 +1088,33 @@ export const retry: { /** * Retries common transient errors, such as rate limiting, timeouts or network issues. * - * Use `retryOn` to focus on retrying errors, transient responses, or both. + * **When to use** + * + * Use to focus on retrying errors, transient responses, or both. + * + * **Details** * * Specifying a `while` predicate allows you to consider other errors as * transient, and is ignored in "response-only" mode. * - * @since 4.0.0 * @category error handling + * @since 4.0.0 */ export const retryTransient: { /** * Retries common transient errors, such as rate limiting, timeouts or network issues. * - * Use `retryOn` to focus on retrying errors, transient responses, or both. + * **When to use** + * + * Use to focus on retrying errors, transient responses, or both. + * + * **Details** * * Specifying a `while` predicate allows you to consider other errors as * transient, and is ignored in "response-only" mode. * - * @since 4.0.0 * @category error handling + * @since 4.0.0 */ < E, @@ -975,13 +1139,17 @@ export const retryTransient: { /** * Retries common transient errors, such as rate limiting, timeouts or network issues. * - * Use `retryOn` to focus on retrying errors, transient responses, or both. + * **When to use** + * + * Use to focus on retrying errors, transient responses, or both. + * + * **Details** * * Specifying a `while` predicate allows you to consider other errors as * transient, and is ignored in "response-only" mode. * - * @since 4.0.0 * @category error handling + * @since 4.0.0 */ < E, @@ -1008,13 +1176,17 @@ export const retryTransient: { /** * Retries common transient errors, such as rate limiting, timeouts or network issues. * - * Use `retryOn` to focus on retrying errors, transient responses, or both. + * **When to use** + * + * Use to focus on retrying errors, transient responses, or both. + * + * **Details** * * Specifying a `while` predicate allows you to consider other errors as * transient, and is ignored in "response-only" mode. * - * @since 4.0.0 * @category error handling + * @since 4.0.0 */ ( options: Schedule.Schedule, ES, R1> @@ -1022,13 +1194,17 @@ export const retryTransient: { /** * Retries common transient errors, such as rate limiting, timeouts or network issues. * - * Use `retryOn` to focus on retrying errors, transient responses, or both. + * **When to use** + * + * Use to focus on retrying errors, transient responses, or both. + * + * **Details** * * Specifying a `while` predicate allows you to consider other errors as * transient, and is ignored in "response-only" mode. * - * @since 4.0.0 * @category error handling + * @since 4.0.0 */ ( self: HttpClient.With, @@ -1077,13 +1253,20 @@ export const retryTransient: { ) /** + * Namespace containing configuration types for `withRateLimiter`. + * * @since 4.0.0 - * @category rate limiting */ export declare namespace WithRateLimiter { /** - * @since 4.0.0 + * Options used to configure `withRateLimiter`. + * + * **Details** + * + * They define the backing limiter, initial limit window, keying strategy, algorithm, token cost, and whether response headers update future limits. + * * @category rate limiting + * @since 4.0.0 */ export interface Options { /** @@ -1122,23 +1305,27 @@ export declare namespace WithRateLimiter { /** * Applies request rate limiting using the `RateLimiter` service. * + * **Details** + * * It can update limits by inspecting common rate limit response headers and * automatically retries HTTP `429` responses (or `HttpClientError` values * wrapping a `429` response) by forcing the retry back through the limiter. * - * @since 4.0.0 * @category rate limiting + * @since 4.0.0 */ export const withRateLimiter: { /** * Applies request rate limiting using the `RateLimiter` service. * + * **Details** + * * It can update limits by inspecting common rate limit response headers and * automatically retries HTTP `429` responses (or `HttpClientError` values * wrapping a `429` response) by forcing the retry back through the limiter. * - * @since 4.0.0 * @category rate limiting + * @since 4.0.0 */ (options: WithRateLimiter.Options): ( self: HttpClient.With @@ -1146,12 +1333,14 @@ export const withRateLimiter: { /** * Applies request rate limiting using the `RateLimiter` service. * + * **Details** + * * It can update limits by inspecting common rate limit response headers and * automatically retries HTTP `429` responses (or `HttpClientError` values * wrapping a `429` response) by forcing the retry back through the limiter. * - * @since 4.0.0 * @category rate limiting + * @since 4.0.0 */ (self: HttpClient.With, options: WithRateLimiter.Options): HttpClient.With } = dual(2, ( @@ -1374,15 +1563,15 @@ const getHeader = (headers: Headers.Headers, ...keys: Array): string | u /** * Performs an additional effect after a successful request. * - * @since 4.0.0 * @category mapping & sequencing + * @since 4.0.0 */ export const tap: { /** * Performs an additional effect after a successful request. * - * @since 4.0.0 * @category mapping & sequencing + * @since 4.0.0 */ <_, E2, R2>( f: (response: HttpClientResponse.HttpClientResponse) => Effect.Effect<_, E2, R2> @@ -1390,8 +1579,8 @@ export const tap: { /** * Performs an additional effect after a successful request. * - * @since 4.0.0 * @category mapping & sequencing + * @since 4.0.0 */ ( self: HttpClient.With, @@ -1408,22 +1597,22 @@ export const tap: { /** * Performs an additional effect after an unsuccessful request. * - * @since 4.0.0 * @category mapping & sequencing + * @since 4.0.0 */ export const tapError: { /** * Performs an additional effect after an unsuccessful request. * - * @since 4.0.0 * @category mapping & sequencing + * @since 4.0.0 */ <_, E, E2, R2>(f: (e: NoInfer) => Effect.Effect<_, E2, R2>): (self: HttpClient.With) => HttpClient.With /** * Performs an additional effect after an unsuccessful request. * - * @since 4.0.0 * @category mapping & sequencing + * @since 4.0.0 */ ( self: HttpClient.With, @@ -1440,22 +1629,22 @@ export const tapError: { /** * Performs an additional effect on the request before sending it. * - * @since 4.0.0 * @category mapping & sequencing + * @since 4.0.0 */ export const tapRequest: { /** * Performs an additional effect on the request before sending it. * - * @since 4.0.0 * @category mapping & sequencing + * @since 4.0.0 */ <_, E2, R2>(f: (a: HttpClientRequest.HttpClientRequest) => Effect.Effect<_, E2, R2>): (self: HttpClient.With) => HttpClient.With /** * Performs an additional effect on the request before sending it. * - * @since 4.0.0 * @category mapping & sequencing + * @since 4.0.0 */ ( self: HttpClient.With, @@ -1471,24 +1660,39 @@ export const tapRequest: { ) /** - * Associates a `Ref` of cookies with the client for handling cookies across requests. + * Adds a `Ref` of cookies to the client for handling cookies across requests. + * + * **When to use** + * + * Use to add shared cookie storage to a client so response cookies are retained + * and sent by later requests. * - * @since 4.0.0 * @category cookies + * @since 4.0.0 */ export const withCookiesRef: { /** - * Associates a `Ref` of cookies with the client for handling cookies across requests. + * Adds a `Ref` of cookies to the client for handling cookies across requests. + * + * **When to use** + * + * Use to add shared cookie storage to a client so response cookies are retained + * and sent by later requests. * - * @since 4.0.0 * @category cookies + * @since 4.0.0 */ (ref: Ref.Ref): (self: HttpClient.With) => HttpClient.With /** - * Associates a `Ref` of cookies with the client for handling cookies across requests. + * Adds a `Ref` of cookies to the client for handling cookies across requests. + * + * **When to use** + * + * Use to add shared cookie storage to a client so response cookies are retained + * and sent by later requests. * - * @since 4.0.0 * @category cookies + * @since 4.0.0 */ (self: HttpClient.With, ref: Ref.Ref): HttpClient.With } = dual( @@ -1516,10 +1720,10 @@ export const withCookiesRef: { ) /** - * Ties the lifetime of the `HttpClientRequest` to a `Scope`. + * Attaches the lifetime of the `HttpClientRequest` to a `Scope`. * + * @category resource management * @since 4.0.0 - * @category Scope */ export const withScope = ( self: HttpClient.With @@ -1537,24 +1741,24 @@ export const withScope = ( ) /** - * Follows HTTP redirects up to a specified number of times. + * Enables following HTTP redirects up to a specified number of times. * - * @since 4.0.0 * @category redirects + * @since 4.0.0 */ export const followRedirects: { /** - * Follows HTTP redirects up to a specified number of times. + * Enables following HTTP redirects up to a specified number of times. * - * @since 4.0.0 * @category redirects + * @since 4.0.0 */ (maxRedirects?: number | undefined): (self: HttpClient.With) => HttpClient.With /** - * Follows HTTP redirects up to a specified number of times. + * Enables following HTTP redirects up to a specified number of times. * - * @since 4.0.0 * @category redirects + * @since 4.0.0 */ (self: HttpClient.With, maxRedirects?: number | undefined): HttpClient.With } = dual((args) => isHttpClient(args[0]), ( @@ -1587,8 +1791,10 @@ export const followRedirects: { )) /** + * Context reference for a predicate that disables client-side tracing for matching outgoing requests. + * + * @category references * @since 4.0.0 - * @category References */ export const TracerDisabledWhen = Context.Reference< Predicate.Predicate @@ -1597,16 +1803,20 @@ export const TracerDisabledWhen = Context.Reference< }) /** + * Context reference that controls whether outgoing client spans are propagated to request headers. + * + * @category references * @since 4.0.0 - * @category References */ export const TracerPropagationEnabled = Context.Reference("effect/HttpClient/TracerPropagationEnabled", { defaultValue: constTrue }) /** + * Context reference for generating the span name used for outgoing client request spans. + * + * @category references * @since 4.0.0 - * @category References */ export const SpanNameGenerator = Context.Reference< (request: HttpClientRequest.HttpClientRequest) => string @@ -1615,6 +1825,9 @@ export const SpanNameGenerator = Context.Reference< }) /** + * Creates an `HttpClient` layer and merges the layer construction context into client response effects. + * + * @category layers * @since 4.0.0 */ export const layerMergedContext = ( diff --git a/.opencode/node_modules/effect/src/unstable/http/HttpClientError.ts b/.opencode/node_modules/effect/src/unstable/http/HttpClientError.ts index f801915718f41577a05dba637df741e8ad4cc1d8..e4909af4f21d2231c04e714dd7217632ba5815e4 100644 --- a/.opencode/node_modules/effect/src/unstable/http/HttpClientError.ts +++ b/.opencode/node_modules/effect/src/unstable/http/HttpClientError.ts @@ -1,4 +1,12 @@ /** + * Typed failure model for Effect HTTP client operations. + * + * HTTP clients wrap request construction, transport, status-code validation, and + * response decoding failures in `HttpClientError`. The wrapper keeps the failed + * request and the specific failure reason together, so callers can handle client + * failures uniformly while still matching on the reason `_tag` for retry + * policy, logging, metrics, and user-facing messages. + * * @since 4.0.0 */ import * as Data from "../../Data.ts" @@ -10,14 +18,18 @@ import type * as ClientResponse from "./HttpClientResponse.ts" const TypeId = "~effect/http/HttpClientError" /** - * @since 4.0.0 + * Returns `true` when a value is an `HttpClientError`. + * * @category guards + * @since 4.0.0 */ export const isHttpClientError = (u: unknown): u is HttpClientError => hasProperty(u, TypeId) /** + * Error wrapper for HTTP client failures, exposing the failed request and the optional response through its `reason`. + * + * @category errors * @since 4.0.0 - * @category error */ export class HttpClientError extends Data.TaggedError("HttpClientError")<{ readonly reason: HttpClientErrorReason @@ -36,11 +48,15 @@ export class HttpClientError extends Data.TaggedError("HttpClientError")<{ } /** + * Marks this value as an HTTP client error for runtime guards. + * * @since 4.0.0 */ readonly [TypeId] = TypeId /** + * HTTP request associated with the client failure. + * * @since 4.0.0 */ get request(): HttpClientRequest.HttpClientRequest { @@ -48,6 +64,8 @@ export class HttpClientError extends Data.TaggedError("HttpClientError")<{ } /** + * HTTP response associated with the client failure, when one was received. + * * @since 4.0.0 */ get response(): ClientResponse.HttpClientResponse | undefined { @@ -65,8 +83,10 @@ const formatMessage = (reason: string, description: string | undefined, info: st description ? `${reason}: ${description} (${info})` : `${reason} error (${info})` /** + * Error describing transport-level failures that occur while sending an HTTP request. + * + * @category errors * @since 4.0.0 - * @category error */ export class TransportError extends Data.TaggedError("TransportError")<{ readonly request: HttpClientRequest.HttpClientRequest @@ -74,6 +94,8 @@ export class TransportError extends Data.TaggedError("TransportError")<{ readonly description?: string }> { /** + * Formats the request method and URL for transport error messages. + * * @since 4.0.0 */ get methodAndUrl() { @@ -81,6 +103,8 @@ export class TransportError extends Data.TaggedError("TransportError")<{ } /** + * Builds the transport error message from the optional description and request details. + * * @since 4.0.0 */ override get message() { @@ -89,8 +113,10 @@ export class TransportError extends Data.TaggedError("TransportError")<{ } /** + * Error describing failures while encoding an HTTP request body. + * + * @category errors * @since 4.0.0 - * @category error */ export class EncodeError extends Data.TaggedError("EncodeError")<{ readonly request: HttpClientRequest.HttpClientRequest @@ -98,6 +124,8 @@ export class EncodeError extends Data.TaggedError("EncodeError")<{ readonly description?: string }> { /** + * Formats the request method and URL for request encoding error messages. + * * @since 4.0.0 */ get methodAndUrl() { @@ -105,6 +133,8 @@ export class EncodeError extends Data.TaggedError("EncodeError")<{ } /** + * Builds the request encoding error message from the optional description and request details. + * * @since 4.0.0 */ override get message() { @@ -113,8 +143,10 @@ export class EncodeError extends Data.TaggedError("EncodeError")<{ } /** + * Error describing failures while constructing a URL from an HTTP client request. + * + * @category errors * @since 4.0.0 - * @category error */ export class InvalidUrlError extends Data.TaggedError("InvalidUrlError")<{ readonly request: HttpClientRequest.HttpClientRequest @@ -122,6 +154,8 @@ export class InvalidUrlError extends Data.TaggedError("InvalidUrlError")<{ readonly description?: string }> { /** + * Formats the request method and URL for invalid URL error messages. + * * @since 4.0.0 */ get methodAndUrl() { @@ -129,6 +163,8 @@ export class InvalidUrlError extends Data.TaggedError("InvalidUrlError")<{ } /** + * Builds the invalid URL error message from the optional description and request details. + * * @since 4.0.0 */ override get message() { @@ -137,8 +173,10 @@ export class InvalidUrlError extends Data.TaggedError("InvalidUrlError")<{ } /** + * Response error for HTTP responses rejected because of their status code. + * + * @category errors * @since 4.0.0 - * @category error */ export class StatusCodeError extends Data.TaggedError("StatusCodeError")<{ readonly request: HttpClientRequest.HttpClientRequest @@ -147,6 +185,8 @@ export class StatusCodeError extends Data.TaggedError("StatusCodeError")<{ readonly description?: string | undefined }> { /** + * Formats the request method and URL for status code error messages. + * * @since 4.0.0 */ get methodAndUrl() { @@ -154,6 +194,8 @@ export class StatusCodeError extends Data.TaggedError("StatusCodeError")<{ } /** + * Builds the status code error message from the response status, optional description, and request details. + * * @since 4.0.0 */ override get message() { @@ -163,8 +205,10 @@ export class StatusCodeError extends Data.TaggedError("StatusCodeError")<{ } /** + * Response error for failures while decoding an HTTP response body. + * + * @category errors * @since 4.0.0 - * @category error */ export class DecodeError extends Data.TaggedError("DecodeError")<{ readonly request: HttpClientRequest.HttpClientRequest @@ -173,6 +217,8 @@ export class DecodeError extends Data.TaggedError("DecodeError")<{ readonly description?: string | undefined }> { /** + * Formats the request method and URL for response decoding error messages. + * * @since 4.0.0 */ get methodAndUrl() { @@ -180,6 +226,8 @@ export class DecodeError extends Data.TaggedError("DecodeError")<{ } /** + * Builds the response decoding error message from the response status, optional description, and request details. + * * @since 4.0.0 */ override get message() { @@ -189,8 +237,10 @@ export class DecodeError extends Data.TaggedError("DecodeError")<{ } /** + * Response error for operations that expected a response body but received an empty body. + * + * @category errors * @since 4.0.0 - * @category error */ export class EmptyBodyError extends Data.TaggedError("EmptyBodyError")<{ readonly request: HttpClientRequest.HttpClientRequest @@ -199,6 +249,8 @@ export class EmptyBodyError extends Data.TaggedError("EmptyBodyError")<{ readonly description?: string | undefined }> { /** + * Formats the request method and URL for empty response body error messages. + * * @since 4.0.0 */ get methodAndUrl() { @@ -206,6 +258,8 @@ export class EmptyBodyError extends Data.TaggedError("EmptyBodyError")<{ } /** + * Builds the empty body error message from the response status, optional description, and request details. + * * @since 4.0.0 */ override get message() { @@ -215,26 +269,35 @@ export class EmptyBodyError extends Data.TaggedError("EmptyBodyError")<{ } /** + * Union of HTTP client errors that occur before a response is available. + * + * @category errors * @since 4.0.0 - * @category error */ export type RequestError = TransportError | EncodeError | InvalidUrlError /** + * Union of HTTP client errors that include an HTTP response. + * + * @category errors * @since 4.0.0 - * @category error */ export type ResponseError = StatusCodeError | DecodeError | EmptyBodyError /** + * Union of all specific failure reasons carried by `HttpClientError`. + * + * @category errors * @since 4.0.0 - * @category error */ export type HttpClientErrorReason = RequestError | ResponseError /** + * Schema for serializable HTTP client errors, preserving the specific error kind + * and cause. + * + * @category schemas * @since 4.0.0 - * @category Schema */ export class HttpClientErrorSchema extends Schema.ErrorClass(TypeId)({ _tag: Schema.tag("HttpError"), @@ -248,9 +311,11 @@ export class HttpClientErrorSchema extends Schema.ErrorClass ), - cause: Schema.optional(Schema.Defect) + cause: Schema.optional(Schema.Defect()) }) { /** + * Builds the serializable schema representation for an HTTP client error. + * * @since 4.0.0 */ static fromHttpClientError(error: HttpClientError): HttpClientErrorSchema { diff --git a/.opencode/node_modules/effect/src/unstable/http/HttpClientRequest.ts b/.opencode/node_modules/effect/src/unstable/http/HttpClientRequest.ts index 13b92ef8c73d9cb783921798beecc22528e72c42..5602f51bfd4fd521c30aeded3feb8c5efe4c1f0b 100644 --- a/.opencode/node_modules/effect/src/unstable/http/HttpClientRequest.ts +++ b/.opencode/node_modules/effect/src/unstable/http/HttpClientRequest.ts @@ -1,4 +1,12 @@ /** + * Describes immutable outgoing HTTP client requests. + * + * `HttpClientRequest` is the request model shared by Effect HTTP clients and + * platform adapters. A request stores its method, URL, query parameters, hash, + * headers, and body as structured data. This module includes constructors, + * helpers for updating requests, body encoders for common payloads, and + * conversions to and from Web `Request` values. + * * @since 4.0.0 */ import * as Context from "../../Context.ts" @@ -25,14 +33,18 @@ import * as UrlParams from "./UrlParams.ts" const TypeId = "~effect/http/HttpClientRequest" /** + * Returns `true` when a value is an `HttpClientRequest`. + * + * @category guards * @since 4.0.0 - * @category Guards */ export const isHttpClientRequest = (u: unknown): u is HttpClientRequest => hasProperty(u, TypeId) /** - * @since 4.0.0 + * Immutable model of an outgoing HTTP client request, including its method, URL components, headers, and body. + * * @category models + * @since 4.0.0 */ export interface HttpClientRequest extends Inspectable.Inspectable, Pipeable { readonly [TypeId]: typeof TypeId @@ -45,8 +57,10 @@ export interface HttpClientRequest extends Inspectable.Inspectable, Pipeable { } /** + * Options for constructing or modifying an `HttpClientRequest`. + * + * @category options * @since 4.0.0 - * @category models */ export interface Options { readonly method?: HttpMethod | undefined @@ -60,12 +74,16 @@ export interface Options { } /** + * Namespace containing option types associated with `HttpClientRequest` construction. + * * @since 4.0.0 */ export declare namespace Options { /** + * Request options that omit the method and URL for helpers that already receive those values separately. + * + * @category options * @since 4.0.0 - * @category models */ export interface NoUrl extends Omit {} } @@ -90,8 +108,10 @@ const Proto = { } /** - * @since 4.0.0 + * Constructs an `HttpClientRequest` from fully normalized request components. + * * @category constructors + * @since 4.0.0 */ export function makeWith( method: HttpMethod, @@ -112,8 +132,10 @@ export function makeWith( } /** - * @since 4.0.0 + * An empty `GET` request with no URL, query parameters, hash, headers, or body. + * * @category constructors + * @since 4.0.0 */ export const empty: HttpClientRequest = makeWith( "GET", @@ -125,8 +147,10 @@ export const empty: HttpClientRequest = makeWith( ) /** - * @since 4.0.0 + * Creates a request constructor for the specified HTTP method. + * * @category constructors + * @since 4.0.0 */ export const make = ( method: M @@ -142,26 +166,34 @@ export const make = ( }) /** - * @since 4.0.0 + * Creates a `GET` request for the specified URL. + * * @category constructors + * @since 4.0.0 */ export const get: (url: string | URL, options?: Options.NoUrl) => HttpClientRequest = make("GET") /** - * @since 4.0.0 + * Creates a `POST` request for the specified URL. + * * @category constructors + * @since 4.0.0 */ export const post: (url: string | URL, options?: Options.NoUrl) => HttpClientRequest = make("POST") /** - * @since 4.0.0 + * Creates a `PATCH` request for the specified URL. + * * @category constructors + * @since 4.0.0 */ export const patch: (url: string | URL, options?: Options.NoUrl) => HttpClientRequest = make("PATCH") /** - * @since 4.0.0 + * Creates a `PUT` request for the specified URL. + * * @category constructors + * @since 4.0.0 */ export const put: (url: string | URL, options?: Options.NoUrl) => HttpClientRequest = make("PUT") @@ -169,43 +201,57 @@ const del: (url: string | URL, options?: Options.NoUrl) => HttpClientRequest = m export { /** - * @since 4.0.0 + * Creates a `DELETE` request for the specified URL. + * * @category constructors + * @since 4.0.0 */ del as delete } /** - * @since 4.0.0 + * Creates a `HEAD` request for the specified URL. + * * @category constructors + * @since 4.0.0 */ export const head: (url: string | URL, options?: Options.NoUrl) => HttpClientRequest = make("HEAD") /** - * @since 4.0.0 + * Creates an `OPTIONS` request for the specified URL. + * * @category constructors + * @since 4.0.0 */ export const options: (url: string | URL, options?: Options.NoUrl) => HttpClientRequest = make("OPTIONS") /** - * @since 4.0.0 + * Creates a `TRACE` request for the specified URL. + * * @category constructors + * @since 4.0.0 */ export const trace: (url: string | URL, options?: Options.NoUrl) => HttpClientRequest = make("TRACE") /** - * @since 4.0.0 + * Applies request options to an `HttpClientRequest`, returning a new request. + * * @category combinators + * @since 4.0.0 */ export const modify: { /** - * @since 4.0.0 + * Applies request options to an `HttpClientRequest`, returning a new request. + * * @category combinators + * @since 4.0.0 */ (options: Options): (self: HttpClientRequest) => HttpClientRequest /** - * @since 4.0.0 + * Applies request options to an `HttpClientRequest`, returning a new request. + * * @category combinators + * @since 4.0.0 */ (self: HttpClientRequest, options: Options): HttpClientRequest } = dual(2, (self: HttpClientRequest, options: Options): HttpClientRequest => { @@ -240,18 +286,24 @@ export const modify: { }) /** - * @since 4.0.0 + * Sets the HTTP method on a request, returning a new request. + * * @category combinators + * @since 4.0.0 */ export const setMethod: { /** - * @since 4.0.0 + * Sets the HTTP method on a request, returning a new request. + * * @category combinators + * @since 4.0.0 */ (method: HttpMethod): (self: HttpClientRequest) => HttpClientRequest /** - * @since 4.0.0 + * Sets the HTTP method on a request, returning a new request. + * * @category combinators + * @since 4.0.0 */ (self: HttpClientRequest, method: HttpMethod): HttpClientRequest } = dual( @@ -261,18 +313,24 @@ export const setMethod: { ) /** - * @since 4.0.0 + * Sets a single request header, replacing any existing value for that header. + * * @category combinators + * @since 4.0.0 */ export const setHeader: { /** - * @since 4.0.0 + * Sets a single request header, replacing any existing value for that header. + * * @category combinators + * @since 4.0.0 */ (key: string, value: string): (self: HttpClientRequest) => HttpClientRequest /** - * @since 4.0.0 + * Sets a single request header, replacing any existing value for that header. + * * @category combinators + * @since 4.0.0 */ (self: HttpClientRequest, key: string, value: string): HttpClientRequest } = dual(3, (self: HttpClientRequest, key: string, value: string): HttpClientRequest => @@ -286,18 +344,24 @@ export const setHeader: { )) /** - * @since 4.0.0 + * Sets multiple request headers from an input collection, replacing existing values with matching names. + * * @category combinators + * @since 4.0.0 */ export const setHeaders: { /** - * @since 4.0.0 + * Sets multiple request headers from an input collection, replacing existing values with matching names. + * * @category combinators + * @since 4.0.0 */ (input: Headers.Input): (self: HttpClientRequest) => HttpClientRequest /** - * @since 4.0.0 + * Sets multiple request headers from an input collection, replacing existing values with matching names. + * * @category combinators + * @since 4.0.0 */ (self: HttpClientRequest, input: Headers.Input): HttpClientRequest } = dual(2, (self: HttpClientRequest, input: Headers.Input): HttpClientRequest => @@ -311,18 +375,24 @@ export const setHeaders: { )) /** - * @since 4.0.0 + * Sets the `Authorization` header using HTTP Basic authentication credentials. + * * @category combinators + * @since 4.0.0 */ export const basicAuth: { /** - * @since 4.0.0 + * Sets the `Authorization` header using HTTP Basic authentication credentials. + * * @category combinators + * @since 4.0.0 */ (username: string | Redacted.Redacted, password: string | Redacted.Redacted): (self: HttpClientRequest) => HttpClientRequest /** - * @since 4.0.0 + * Sets the `Authorization` header using HTTP Basic authentication credentials. + * * @category combinators + * @since 4.0.0 */ ( self: HttpClientRequest, @@ -340,18 +410,24 @@ export const basicAuth: { ) /** - * @since 4.0.0 + * Sets the `Authorization` header using a bearer token. + * * @category combinators + * @since 4.0.0 */ export const bearerToken: { /** - * @since 4.0.0 + * Sets the `Authorization` header using a bearer token. + * * @category combinators + * @since 4.0.0 */ (token: string | Redacted.Redacted): (self: HttpClientRequest) => HttpClientRequest /** - * @since 4.0.0 + * Sets the `Authorization` header using a bearer token. + * * @category combinators + * @since 4.0.0 */ (self: HttpClientRequest, token: string | Redacted.Redacted): HttpClientRequest } = dual( @@ -361,41 +437,55 @@ export const bearerToken: { ) /** - * @since 4.0.0 + * Sets the `Accept` header to the specified media type. + * * @category combinators + * @since 4.0.0 */ export const accept: { /** - * @since 4.0.0 + * Sets the `Accept` header to the specified media type. + * * @category combinators + * @since 4.0.0 */ (mediaType: string): (self: HttpClientRequest) => HttpClientRequest /** - * @since 4.0.0 + * Sets the `Accept` header to the specified media type. + * * @category combinators + * @since 4.0.0 */ (self: HttpClientRequest, mediaType: string): HttpClientRequest } = dual(2, (self: HttpClientRequest, mediaType: string): HttpClientRequest => setHeader(self, "Accept", mediaType)) /** - * @since 4.0.0 + * Sets the `Accept` header to `application/json`. + * * @category combinators + * @since 4.0.0 */ export const acceptJson: (self: HttpClientRequest) => HttpClientRequest = accept("application/json") /** - * @since 4.0.0 + * Sets the request URL. When given a `URL`, its search parameters and hash are extracted into the request's structured fields. + * * @category combinators + * @since 4.0.0 */ export const setUrl: { /** - * @since 4.0.0 + * Sets the request URL. When given a `URL`, its search parameters and hash are extracted into the request's structured fields. + * * @category combinators + * @since 4.0.0 */ (url: string | URL): (self: HttpClientRequest) => HttpClientRequest /** - * @since 4.0.0 + * Sets the request URL. When given a `URL`, its search parameters and hash are extracted into the request's structured fields. + * * @category combinators + * @since 4.0.0 */ (self: HttpClientRequest, url: string | URL): HttpClientRequest } = dual(2, (self: HttpClientRequest, url: string | URL): HttpClientRequest => { @@ -425,18 +515,24 @@ export const setUrl: { }) /** - * @since 4.0.0 + * Prepends a URL segment to the request URL, inserting or trimming one slash as needed. + * * @category combinators + * @since 4.0.0 */ export const prependUrl: { /** - * @since 4.0.0 + * Prepends a URL segment to the request URL, inserting or trimming one slash as needed. + * * @category combinators + * @since 4.0.0 */ (path: string): (self: HttpClientRequest) => HttpClientRequest /** - * @since 4.0.0 + * Prepends a URL segment to the request URL, inserting or trimming one slash as needed. + * * @category combinators + * @since 4.0.0 */ (self: HttpClientRequest, path: string): HttpClientRequest } = dual(2, (self: HttpClientRequest, path: string): HttpClientRequest => { @@ -452,18 +548,24 @@ export const prependUrl: { }) /** - * @since 4.0.0 + * Appends a URL segment to the request URL, inserting or trimming one slash as needed. + * * @category combinators + * @since 4.0.0 */ export const appendUrl: { /** - * @since 4.0.0 + * Appends a URL segment to the request URL, inserting or trimming one slash as needed. + * * @category combinators + * @since 4.0.0 */ (path: string): (self: HttpClientRequest) => HttpClientRequest /** - * @since 4.0.0 + * Appends a URL segment to the request URL, inserting or trimming one slash as needed. + * * @category combinators + * @since 4.0.0 */ (self: HttpClientRequest, path: string): HttpClientRequest } = dual(2, (self: HttpClientRequest, path: string): HttpClientRequest => { @@ -491,18 +593,24 @@ const joinSegments = (first: string, second: string): string => { } /** - * @since 4.0.0 + * Updates the request URL by applying a function to the current URL string. + * * @category combinators + * @since 4.0.0 */ export const updateUrl: { /** - * @since 4.0.0 + * Updates the request URL by applying a function to the current URL string. + * * @category combinators + * @since 4.0.0 */ (f: (url: string) => string): (self: HttpClientRequest) => HttpClientRequest /** - * @since 4.0.0 + * Updates the request URL by applying a function to the current URL string. + * * @category combinators + * @since 4.0.0 */ (self: HttpClientRequest, f: (url: string) => string): HttpClientRequest } = dual(2, (self: HttpClientRequest, f: (url: string) => string): HttpClientRequest => @@ -516,18 +624,24 @@ export const updateUrl: { )) /** - * @since 4.0.0 + * Sets one query parameter, replacing existing values for that parameter name. + * * @category combinators + * @since 4.0.0 */ export const setUrlParam: { /** - * @since 4.0.0 + * Sets one query parameter, replacing existing values for that parameter name. + * * @category combinators + * @since 4.0.0 */ (key: string, value: string): (self: HttpClientRequest) => HttpClientRequest /** - * @since 4.0.0 + * Sets one query parameter, replacing existing values for that parameter name. + * * @category combinators + * @since 4.0.0 */ (self: HttpClientRequest, key: string, value: string): HttpClientRequest } = dual(3, (self: HttpClientRequest, key: string, value: string): HttpClientRequest => @@ -541,18 +655,24 @@ export const setUrlParam: { )) /** - * @since 4.0.0 + * Sets query parameters from an input collection, replacing existing values for matching names. + * * @category combinators + * @since 4.0.0 */ export const setUrlParams: { /** - * @since 4.0.0 + * Sets query parameters from an input collection, replacing existing values for matching names. + * * @category combinators + * @since 4.0.0 */ (input: UrlParams.Input): (self: HttpClientRequest) => HttpClientRequest /** - * @since 4.0.0 + * Sets query parameters from an input collection, replacing existing values for matching names. + * * @category combinators + * @since 4.0.0 */ (self: HttpClientRequest, input: UrlParams.Input): HttpClientRequest } = dual(2, (self: HttpClientRequest, input: UrlParams.Input): HttpClientRequest => @@ -566,18 +686,24 @@ export const setUrlParams: { )) /** - * @since 4.0.0 + * Appends one query parameter value without removing existing values for the same name. + * * @category combinators + * @since 4.0.0 */ export const appendUrlParam: { /** - * @since 4.0.0 + * Appends one query parameter value without removing existing values for the same name. + * * @category combinators + * @since 4.0.0 */ (key: string, value: string): (self: HttpClientRequest) => HttpClientRequest /** - * @since 4.0.0 + * Appends one query parameter value without removing existing values for the same name. + * * @category combinators + * @since 4.0.0 */ (self: HttpClientRequest, key: string, value: string): HttpClientRequest } = dual(3, (self: HttpClientRequest, key: string, value: string): HttpClientRequest => @@ -591,18 +717,24 @@ export const appendUrlParam: { )) /** - * @since 4.0.0 + * Appends query parameters from an input collection without removing existing values for matching names. + * * @category combinators + * @since 4.0.0 */ export const appendUrlParams: { /** - * @since 4.0.0 + * Appends query parameters from an input collection without removing existing values for matching names. + * * @category combinators + * @since 4.0.0 */ (input: UrlParams.Input): (self: HttpClientRequest) => HttpClientRequest /** - * @since 4.0.0 + * Appends query parameters from an input collection without removing existing values for matching names. + * * @category combinators + * @since 4.0.0 */ (self: HttpClientRequest, input: UrlParams.Input): HttpClientRequest } = dual(2, (self: HttpClientRequest, input: UrlParams.Input): HttpClientRequest => @@ -616,18 +748,24 @@ export const appendUrlParams: { )) /** - * @since 4.0.0 + * Sets the URL fragment on a request without the leading `#`. + * * @category combinators + * @since 4.0.0 */ export const setHash: { /** - * @since 4.0.0 + * Sets the URL fragment on a request without the leading `#`. + * * @category combinators + * @since 4.0.0 */ (hash: string): (self: HttpClientRequest) => HttpClientRequest /** - * @since 4.0.0 + * Sets the URL fragment on a request without the leading `#`. + * * @category combinators + * @since 4.0.0 */ (self: HttpClientRequest, hash: string): HttpClientRequest } = dual(2, (self: HttpClientRequest, hash: string): HttpClientRequest => @@ -641,8 +779,10 @@ export const setHash: { )) /** - * @since 4.0.0 + * Removes the URL fragment from a request. + * * @category combinators + * @since 4.0.0 */ export const removeHash = (self: HttpClientRequest): HttpClientRequest => makeWith( @@ -655,18 +795,24 @@ export const removeHash = (self: HttpClientRequest): HttpClientRequest => ) /** - * @since 4.0.0 + * Sets the request body and updates `Content-Type` and `Content-Length` headers from the body metadata when available. + * * @category combinators + * @since 4.0.0 */ export const setBody: { /** - * @since 4.0.0 + * Sets the request body and updates `Content-Type` and `Content-Length` headers from the body metadata when available. + * * @category combinators + * @since 4.0.0 */ (body: HttpBody.HttpBody): (self: HttpClientRequest) => HttpClientRequest /** - * @since 4.0.0 + * Sets the request body and updates `Content-Type` and `Content-Length` headers from the body metadata when available. + * * @category combinators + * @since 4.0.0 */ (self: HttpClientRequest, body: HttpBody.HttpBody): HttpClientRequest } = dual(2, (self: HttpClientRequest, body: HttpBody.HttpBody): HttpClientRequest => { @@ -692,18 +838,24 @@ export const setBody: { }) /** - * @since 4.0.0 + * Sets a `Uint8Array` request body with an optional content type. + * * @category combinators + * @since 4.0.0 */ export const bodyUint8Array: { /** - * @since 4.0.0 + * Sets a `Uint8Array` request body with an optional content type. + * * @category combinators + * @since 4.0.0 */ (body: Uint8Array, contentType?: string): (self: HttpClientRequest) => HttpClientRequest /** - * @since 4.0.0 + * Sets a `Uint8Array` request body with an optional content type. + * * @category combinators + * @since 4.0.0 */ (self: HttpClientRequest, body: Uint8Array, contentType?: string): HttpClientRequest } = dual( @@ -713,18 +865,24 @@ export const bodyUint8Array: { ) /** - * @since 4.0.0 + * Sets a text request body with an optional content type. + * * @category combinators + * @since 4.0.0 */ export const bodyText: { /** - * @since 4.0.0 + * Sets a text request body with an optional content type. + * * @category combinators + * @since 4.0.0 */ (body: string, contentType?: string): (self: HttpClientRequest) => HttpClientRequest /** - * @since 4.0.0 + * Sets a text request body with an optional content type. + * * @category combinators + * @since 4.0.0 */ (self: HttpClientRequest, body: string, contentType?: string): HttpClientRequest } = dual( @@ -734,18 +892,24 @@ export const bodyText: { ) /** - * @since 4.0.0 + * Encodes a value as a JSON request body and sets it on the request, failing with `HttpBodyError` if encoding fails. + * * @category combinators + * @since 4.0.0 */ export const bodyJson: { /** - * @since 4.0.0 + * Encodes a value as a JSON request body and sets it on the request, failing with `HttpBodyError` if encoding fails. + * * @category combinators + * @since 4.0.0 */ (body: unknown): (self: HttpClientRequest) => Effect.Effect /** - * @since 4.0.0 + * Encodes a value as a JSON request body and sets it on the request, failing with `HttpBodyError` if encoding fails. + * * @category combinators + * @since 4.0.0 */ (self: HttpClientRequest, body: unknown): Effect.Effect } = dual( @@ -755,25 +919,60 @@ export const bodyJson: { ) /** - * @since 4.0.0 + * Sets a JSON request body using unsafe JSON encoding. + * + * **When to use** + * + * Use when the request body is known to be JSON-serializable and a synchronous + * `HttpClientRequest` result is needed. + * + * **Gotchas** + * + * JSON encoding may throw instead of failing in the Effect error channel. + * * @category combinators + * @since 4.0.0 */ export const bodyJsonUnsafe: { /** - * @since 4.0.0 + * Sets a JSON request body using unsafe JSON encoding. + * + * **When to use** + * + * Use when the request body is known to be JSON-serializable and a synchronous + * `HttpClientRequest` result is needed. + * + * **Gotchas** + * + * JSON encoding may throw instead of failing in the Effect error channel. + * * @category combinators + * @since 4.0.0 */ (body: unknown): (self: HttpClientRequest) => HttpClientRequest /** - * @since 4.0.0 + * Sets a JSON request body using unsafe JSON encoding. + * + * **When to use** + * + * Use when the request body is known to be JSON-serializable and a synchronous + * `HttpClientRequest` result is needed. + * + * **Gotchas** + * + * JSON encoding may throw instead of failing in the Effect error channel. + * * @category combinators + * @since 4.0.0 */ (self: HttpClientRequest, body: unknown): HttpClientRequest } = dual(2, (self: HttpClientRequest, body: unknown): HttpClientRequest => setBody(self, HttpBody.jsonUnsafe(body))) /** - * @since 4.0.0 + * Creates a schema-based JSON body encoder that sets the encoded value on a request. + * * @category combinators + * @since 4.0.0 */ export const schemaBodyJson = ( schema: S, @@ -801,18 +1000,24 @@ export const schemaBodyJson = ( } /** - * @since 4.0.0 + * Sets an `application/x-www-form-urlencoded` request body from URL parameter input. + * * @category combinators + * @since 4.0.0 */ export const bodyUrlParams: { /** - * @since 4.0.0 + * Sets an `application/x-www-form-urlencoded` request body from URL parameter input. + * * @category combinators + * @since 4.0.0 */ (input: UrlParams.Input): (self: HttpClientRequest) => HttpClientRequest /** - * @since 4.0.0 + * Sets an `application/x-www-form-urlencoded` request body from URL parameter input. + * * @category combinators + * @since 4.0.0 */ (self: HttpClientRequest, input: UrlParams.Input): HttpClientRequest } = dual( @@ -822,35 +1027,47 @@ export const bodyUrlParams: { ) /** - * @since 4.0.0 + * Sets a `FormData` request body. + * * @category combinators + * @since 4.0.0 */ export const bodyFormData: { /** - * @since 4.0.0 + * Sets a `FormData` request body. + * * @category combinators + * @since 4.0.0 */ (body: FormData): (self: HttpClientRequest) => HttpClientRequest /** - * @since 4.0.0 + * Sets a `FormData` request body. + * * @category combinators + * @since 4.0.0 */ (self: HttpClientRequest, body: FormData): HttpClientRequest } = dual(2, (self: HttpClientRequest, body: FormData): HttpClientRequest => setBody(self, HttpBody.formData(body))) /** - * @since 4.0.0 + * Creates a `FormData` request body from record-style entries and sets it on the request. + * * @category combinators + * @since 4.0.0 */ export const bodyFormDataRecord: { /** - * @since 4.0.0 + * Creates a `FormData` request body from record-style entries and sets it on the request. + * * @category combinators + * @since 4.0.0 */ (entries: HttpBody.FormDataInput): (self: HttpClientRequest) => HttpClientRequest /** - * @since 4.0.0 + * Creates a `FormData` request body from record-style entries and sets it on the request. + * * @category combinators + * @since 4.0.0 */ (self: HttpClientRequest, entries: HttpBody.FormDataInput): HttpClientRequest } = dual( @@ -860,21 +1077,27 @@ export const bodyFormDataRecord: { ) /** - * @since 4.0.0 + * Sets a streaming `Uint8Array` request body with optional content type and content length metadata. + * * @category combinators + * @since 4.0.0 */ export const bodyStream: { /** - * @since 4.0.0 + * Sets a streaming `Uint8Array` request body with optional content type and content length metadata. + * * @category combinators + * @since 4.0.0 */ ( body: Stream.Stream, options?: { readonly contentType?: string | undefined; readonly contentLength?: number | undefined } | undefined ): (self: HttpClientRequest) => HttpClientRequest /** - * @since 4.0.0 + * Sets a streaming `Uint8Array` request body with optional content type and content length metadata. + * * @category combinators + * @since 4.0.0 */ ( self: HttpClientRequest, @@ -895,13 +1118,17 @@ export const bodyStream: { ) /** - * @since 4.0.0 + * Creates a file-backed request body from a filesystem path and sets it on the request. + * * @category combinators + * @since 4.0.0 */ export const bodyFile: { /** - * @since 4.0.0 + * Creates a file-backed request body from a filesystem path and sets it on the request. + * * @category combinators + * @since 4.0.0 */ ( path: string, @@ -913,8 +1140,10 @@ export const bodyFile: { } ): (self: HttpClientRequest) => Effect.Effect /** - * @since 4.0.0 + * Creates a file-backed request body from a filesystem path and sets it on the request. + * * @category combinators + * @since 4.0.0 */ ( self: HttpClientRequest, @@ -945,8 +1174,10 @@ export const bodyFile: { ) /** - * @since 4.0.0 + * Builds a `URL` from the request URL, query parameters, and hash, returning `Option.none()` if the URL is invalid. + * * @category combinators + * @since 4.0.0 */ export function toUrl(self: HttpClientRequest): Option.Option { const r = UrlParams.makeUrl(self.url, self.urlParams, Option.getOrUndefined(self.hash)) @@ -957,8 +1188,10 @@ export function toUrl(self: HttpClientRequest): Option.Option { } /** + * Converts a Web `Request` into an `HttpClientRequest`, preserving method, URL, headers, and supported request bodies. + * + * @category converting * @since 4.0.0 - * @category conversions */ export const fromWeb = (request: globalThis.Request): HttpClientRequest => { const method = request.method.toUpperCase() as HttpMethod @@ -989,8 +1222,10 @@ const parseContentLength = (contentLength: string | null): number | undefined => } /** + * Converts an `HttpClientRequest` safely to a Web `Request` as a `Result`, failing when the request URL is invalid. + * + * @category converting * @since 4.0.0 - * @category conversions */ export const toWebResult = (self: HttpClientRequest, options?: { readonly signal?: AbortSignal | undefined @@ -1044,15 +1279,17 @@ const isReadableStream = (u: unknown): u is ReadableStream => typeof ReadableStream !== "undefined" && u instanceof ReadableStream /** + * Converts an `HttpClientRequest` to a Web `Request`, failing with `UrlParamsError` when the request URL is invalid. + * + * @category converting * @since 4.0.0 - * @category conversions */ export const toWeb = (self: HttpClientRequest, options?: { readonly signal?: AbortSignal | undefined }): Effect.Effect => Effect.contextWith((context) => - toWebResult(self, { + Effect.fromResult(toWebResult(self, { context: context, signal: options?.signal - }).asEffect() + })) ) diff --git a/.opencode/node_modules/effect/src/unstable/http/HttpClientResponse.ts b/.opencode/node_modules/effect/src/unstable/http/HttpClientResponse.ts index cad5999401694f95567588836e05e29edcf3e1fd..b5ec195e1d1a937e8afdb4719213aed7e7a3c73b 100644 --- a/.opencode/node_modules/effect/src/unstable/http/HttpClientResponse.ts +++ b/.opencode/node_modules/effect/src/unstable/http/HttpClientResponse.ts @@ -1,4 +1,12 @@ /** + * Represents responses returned by the Effect HTTP client. + * + * An `HttpClientResponse` keeps the original request together with the response + * status, headers, cookies, and body accessors from the shared incoming-message + * model. This module includes constructors, schema-based decoders, helpers for + * streaming response bodies, and utilities for matching or filtering by HTTP + * status. + * * @since 4.0.0 */ import * as Effect from "../../Effect.ts" @@ -19,31 +27,41 @@ import * as UrlParams from "./UrlParams.ts" export { /** + * Creates a decoder that reads a response JSON body and decodes it with the supplied schema. + * + * @category schemas * @since 4.0.0 - * @category schema */ schemaBodyJson, /** + * Creates a decoder that reads response URL-encoded body parameters and decodes them with the supplied schema. + * + * @category schemas * @since 4.0.0 - * @category schema */ schemaBodyUrlParams, /** + * Creates a decoder that validates and decodes response headers with the supplied schema. + * + * @category schemas * @since 4.0.0 - * @category schema */ schemaHeaders } from "./HttpIncomingMessage.ts" /** + * Type identifier for `HttpClientResponse` values. + * + * @category type IDs * @since 4.0.0 - * @category Type IDs */ export const TypeId = "~effect/http/HttpClientResponse" /** - * @since 4.0.0 + * Model of an HTTP client response, including the original request, status, cookies, headers, and body accessors. + * * @category models + * @since 4.0.0 */ export interface HttpClientResponse extends HttpIncomingMessage.HttpIncomingMessage, Pipeable { readonly [TypeId]: typeof TypeId @@ -54,15 +72,19 @@ export interface HttpClientResponse extends HttpIncomingMessage.HttpIncomingMess } /** - * @since 4.0.0 + * Wraps a Web `Response` and its original `HttpClientRequest` as an `HttpClientResponse`. + * * @category constructors + * @since 4.0.0 */ export const fromWeb = (request: HttpClientRequest.HttpClientRequest, source: Response): HttpClientResponse => new WebHttpClientResponse(request, source) /** + * Creates a decoder for a response's status, headers, and JSON body using the supplied schema. + * + * @category schemas * @since 4.0.0 - * @category schema */ export const schemaJson = < A, @@ -90,8 +112,10 @@ export const schemaJson = < } /** + * Creates a decoder for a response's status and headers without reading a response body. + * + * @category schemas * @since 4.0.0 - * @category schema */ export const schemaNoBody = < A, @@ -114,21 +138,27 @@ export const schemaNoBody = < } /** - * @since 4.0.0 + * Converts an effect producing an `HttpClientResponse` into a stream of response body bytes. + * * @category accessors + * @since 4.0.0 */ export const stream = ( effect: Effect.Effect ): Stream.Stream => Stream.unwrap(Effect.map(effect, (self) => self.stream)) /** - * @since 4.0.0 + * Pattern matches on a response status, checking exact status handlers before status-class handlers and `orElse`. + * * @category pattern matching + * @since 4.0.0 */ export const matchStatus: { /** - * @since 4.0.0 + * Pattern matches on a response status, checking exact status handlers before status-class handlers and `orElse`. + * * @category pattern matching + * @since 4.0.0 */ < const Cases extends { @@ -141,8 +171,10 @@ export const matchStatus: { } >(cases: Cases): (self: HttpClientResponse) => Cases[keyof Cases] extends (_: any) => infer R ? Unify : never /** - * @since 4.0.0 + * Pattern matches on a response status, checking exact status handlers before status-class handlers and `orElse`. + * * @category pattern matching + * @since 4.0.0 */ < const Cases extends { @@ -180,18 +212,24 @@ export const matchStatus: { }) /** - * @since 4.0.0 + * Succeeds with the response when its status satisfies the predicate, otherwise fails with `HttpClientError`. + * * @category filters + * @since 4.0.0 */ export const filterStatus: { /** - * @since 4.0.0 + * Succeeds with the response when its status satisfies the predicate, otherwise fails with `HttpClientError`. + * * @category filters + * @since 4.0.0 */ (f: (status: number) => boolean): (self: HttpClientResponse) => Effect.Effect /** - * @since 4.0.0 + * Succeeds with the response when its status satisfies the predicate, otherwise fails with `HttpClientError`. + * * @category filters + * @since 4.0.0 */ (self: HttpClientResponse, f: (status: number) => boolean): Effect.Effect } = dual( @@ -211,8 +249,10 @@ export const filterStatus: { ) /** - * @since 4.0.0 + * Succeeds with the response only when its status is in the 2xx range, otherwise fails with `HttpClientError`. + * * @category filters + * @since 4.0.0 */ export const filterStatusOk = (self: HttpClientResponse): Effect.Effect => self.status >= 200 && self.status < 300 ? Effect.succeed(self) : Effect.fail( diff --git a/.opencode/node_modules/effect/src/unstable/http/HttpEffect.ts b/.opencode/node_modules/effect/src/unstable/http/HttpEffect.ts index 1e6e85b98ba44e729b963adb5d0972846cd09307..021b7f533456a2e631d6de24d0386675087677be 100644 --- a/.opencode/node_modules/effect/src/unstable/http/HttpEffect.ts +++ b/.opencode/node_modules/effect/src/unstable/http/HttpEffect.ts @@ -1,4 +1,11 @@ /** + * Runs Effect HTTP server handlers at platform boundaries. + * + * This module turns effects that produce `HttpServerResponse` values into Web + * `Request` handlers and other server adapters. It also applies middleware, + * converts failures into responses, runs hooks before a response is sent, and + * manages request scopes for streamed responses. + * * @since 4.0.0 */ import type * as Cause from "../../Cause.ts" @@ -21,8 +28,10 @@ import * as Response from "./HttpServerResponse.ts" import { appendPreResponseHandlerUnsafe, requestPreResponseHandlers } from "./internal/preResponseHandler.ts" /** - * @since 4.0.0 + * Runs an HTTP server effect, sends the produced response with the supplied handler, and converts failures into HTTP responses. + * * @category combinators + * @since 4.0.0 */ export const toHandled = ( self: Effect.Effect, @@ -107,19 +116,25 @@ export const toHandled = ( const handledSymbol = Symbol.for("effect/http/HttpEffect/handled") /** - * If you want to finalize the http request scope elsewhere, you can use this - * function to eject from the default scope closure. + * Disables automatic closing for an HTTP request scope. + * + * **Gotchas** * + * Use only when another owner will close the scope; otherwise resources attached + * to the request scope can leak. + * + * @category resource management * @since 4.0.0 - * @category Scope */ export const scopeDisableClose = (scope: Scope.Scope): void => { ;(scope as any)[scopeEjected] = true } /** + * Returns a streaming server response that closes the request scope when the body stream exits. + * + * @category resource management * @since 4.0.0 - * @category Scope */ export const scopeTransferToStream = ( response: HttpServerResponse @@ -155,8 +170,10 @@ const scoped = (effect: Effect.Effect) => }) /** - * @since 4.0.0 + * Function run with the current request and response just before the response is sent, allowing the response to be replaced or failing with `HttpServerError`. + * * @category Pre-response handlers + * @since 4.0.0 */ export type PreResponseHandler = ( request: HttpServerRequest, @@ -164,8 +181,10 @@ export type PreResponseHandler = ( ) => Effect.Effect /** - * @since 4.0.0 + * Registers an additional pre-response handler for the current HTTP server request. + * * @category fiber refs + * @since 4.0.0 */ export const appendPreResponseHandler = (handler: PreResponseHandler): Effect.Effect => HttpServerRequest.use((request) => { @@ -175,36 +194,48 @@ export const appendPreResponseHandler = (handler: PreResponseHandler): Effect.Ef export { /** - * @since 4.0.0 + * Registers a pre-response handler for the supplied HTTP server request. + * * @category fiber refs + * @since 4.0.0 */ appendPreResponseHandlerUnsafe } /** - * @since 4.0.0 + * Runs an effect after registering a pre-response handler for the current HTTP server request. + * * @category fiber refs + * @since 4.0.0 */ export const withPreResponseHandler: { /** - * @since 4.0.0 + * Runs an effect after registering a pre-response handler for the current HTTP server request. + * * @category fiber refs + * @since 4.0.0 */ (handler: PreResponseHandler): (self: Effect.Effect) => Effect.Effect /** - * @since 4.0.0 + * Runs an effect after registering a pre-response handler for the current HTTP server request. + * * @category fiber refs + * @since 4.0.0 */ (self: Effect.Effect, handler: PreResponseHandler): Effect.Effect } = dual< /** - * @since 4.0.0 + * Runs an effect after registering a pre-response handler for the current HTTP server request. + * * @category fiber refs + * @since 4.0.0 */ (handler: PreResponseHandler) => (self: Effect.Effect) => Effect.Effect, /** - * @since 4.0.0 + * Runs an effect after registering a pre-response handler for the current HTTP server request. + * * @category fiber refs + * @since 4.0.0 */ (self: Effect.Effect, handler: PreResponseHandler) => Effect.Effect >(2, (self, handler) => @@ -214,8 +245,10 @@ export const withPreResponseHandler: { })) /** + * Converts an HTTP server effect into a Web `Request` handler using the supplied base context and optional middleware. + * + * @category converting * @since 4.0.0 - * @category conversions */ export const toWebHandlerWith = >( context: Context.Context @@ -254,8 +287,10 @@ export const toWebHandlerWith = ( self: Effect.Effect, @@ -264,8 +299,10 @@ export const toWebHandler: ( toWebHandlerWith(Context.empty()) /** + * Builds a Web `Request` handler from a layer and handler factory, returning the handler with a `dispose` function for the layer scope. + * + * @category converting * @since 4.0.0 - * @category conversions */ export const toWebHandlerLayerWith = < E, @@ -324,8 +361,10 @@ export const toWebHandlerLayerWith = < } /** + * Builds a Web `Request` handler for an HTTP server effect using a layer to provide its services, returning the handler with a `dispose` function. + * + * @category converting * @since 4.0.0 - * @category conversions */ export const toWebHandlerLayer = >( self: Effect.Effect, @@ -349,8 +388,10 @@ export const toWebHandlerLayer = Promise diff --git a/.opencode/node_modules/effect/src/unstable/http/HttpIncomingMessage.ts b/.opencode/node_modules/effect/src/unstable/http/HttpIncomingMessage.ts index 1501a0c24ffd8b45c692742402f0c7524685ad1a..141802988ca8ac2bcfcffcb4d38c9b01e4e81d1c 100644 --- a/.opencode/node_modules/effect/src/unstable/http/HttpIncomingMessage.ts +++ b/.opencode/node_modules/effect/src/unstable/http/HttpIncomingMessage.ts @@ -1,4 +1,12 @@ /** + * Common model for incoming HTTP messages. + * + * `HttpIncomingMessage` is used by server requests and client responses to + * expose headers, an optional remote address, and body accessors. This module + * provides decoders for JSON bodies, URL-encoded bodies, and headers, plus the + * shared body-size setting and inspection helper used by request and response + * implementations. + * * @since 4.0.0 */ import * as Context from "../../Context.ts" @@ -15,20 +23,26 @@ import type * as Headers from "./Headers.ts" import * as UrlParams from "./UrlParams.ts" /** + * Type identifier for `HttpIncomingMessage` values. + * + * @category type IDs * @since 4.0.0 - * @category Type IDs */ export const TypeId = "~effect/http/HttpIncomingMessage" /** + * Returns `true` when a value is an `HttpIncomingMessage`. + * + * @category guards * @since 4.0.0 - * @category Guards */ export const isHttpIncomingMessage = (u: unknown): u is HttpIncomingMessage => hasProperty(u, TypeId) /** - * @since 4.0.0 + * Common model for incoming HTTP messages, with headers, remote address, and effectful body accessors. + * * @category models + * @since 4.0.0 */ export interface HttpIncomingMessage extends Inspectable.Inspectable { readonly [TypeId]: typeof TypeId @@ -42,8 +56,10 @@ export interface HttpIncomingMessage extends Inspectable.Inspectabl } /** + * Creates a decoder that reads an incoming message's JSON body and decodes it with the supplied schema. + * + * @category schemas * @since 4.0.0 - * @category schema */ export const schemaBodyJson = (schema: S, options?: ParseOptions | undefined) => { const decode = Schema.decodeEffect(Schema.toCodecJson(schema)) @@ -54,8 +70,10 @@ export const schemaBodyJson = (schema: S, options?: ParseO } /** + * Creates a decoder that reads an incoming message's URL-encoded body parameters and decodes them with the supplied schema. + * + * @category schemas * @since 4.0.0 - * @category schema */ export const schemaBodyUrlParams = < A, @@ -75,8 +93,10 @@ export const schemaBodyUrlParams = < } /** + * Creates a decoder that validates and decodes an incoming message's headers with the supplied schema. + * + * @category schemas * @since 4.0.0 - * @category schema */ export const schemaHeaders = >, RD, RE>( schema: Schema.Codec, @@ -87,8 +107,10 @@ export const schemaHeaders = ( "effect/http/HttpIncomingMessage/MaxBodySize", @@ -96,6 +118,9 @@ export const MaxBodySize = Context.Reference( ) /** + * Builds an inspectable object for an incoming message, redacting headers and including a synchronously readable JSON or text body when available. + * + * @category converting * @since 4.0.0 */ export const inspect = (self: HttpIncomingMessage, that: object): object => { diff --git a/.opencode/node_modules/effect/src/unstable/http/HttpMethod.ts b/.opencode/node_modules/effect/src/unstable/http/HttpMethod.ts index 0dc7f7eccd2e4ba916e44ff09ff497cc4128abf4..b491a52717e9f9ce613470a2db6a3e42a33d1000 100644 --- a/.opencode/node_modules/effect/src/unstable/http/HttpMethod.ts +++ b/.opencode/node_modules/effect/src/unstable/http/HttpMethod.ts @@ -1,10 +1,19 @@ /** + * Defines supported HTTP method names for the unstable HTTP modules. + * + * Values are uppercase string literals such as `"GET"` and `"POST"`, matching + * the method tokens used by HTTP requests and routes. This module also includes + * helpers for checking whether a method can carry a request body and whether an + * unknown value is one of the supported methods. + * * @since 4.0.0 */ /** - * @since 4.0.0 + * Union of supported uppercase HTTP method literals. + * * @category models + * @since 4.0.0 */ export type HttpMethod = | "GET" @@ -17,30 +26,46 @@ export type HttpMethod = | "TRACE" /** + * Namespace containing subtype helpers associated with `HttpMethod`. + * * @since 4.0.0 - * @category models */ export declare namespace HttpMethod { /** - * @since 4.0.0 + * HTTP methods that this module treats as not carrying a request body. + * * @category models + * @since 4.0.0 */ export type NoBody = "GET" | "HEAD" | "OPTIONS" | "TRACE" /** - * @since 4.0.0 + * HTTP methods that this module treats as capable of carrying a request body. + * * @category models + * @since 4.0.0 */ export type WithBody = Exclude } /** + * Returns `true` when a method can carry a request body and narrows it to `HttpMethod.WithBody`. + * + * @category predicates * @since 4.0.0 */ export const hasBody = (method: HttpMethod): method is HttpMethod.WithBody => method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" /** + * Provides a readonly set containing every supported `HttpMethod` literal. + * + * **When to use** + * + * Use when you need to iterate over or test membership against every supported + * HTTP method literal. + * + * @category constants * @since 4.0.0 */ export const all: ReadonlySet = new Set([ @@ -55,6 +80,15 @@ export const all: ReadonlySet = new Set([ ]) /** + * Provides tuples mapping each supported HTTP method to its short + * request-constructor name. + * + * **When to use** + * + * Use when you need the mapping from supported HTTP method literals to their + * short request-constructor names. + * + * @category constants * @since 4.0.0 */ export const allShort = [ @@ -69,9 +103,9 @@ export const allShort = [ ] as const /** - * Tests if a value is a `HttpMethod`. + * Checks whether a value is a `HttpMethod`. * - * **Example** + * **Example** (Checking HTTP method values) * * ```ts * import { HttpMethod } from "effect/unstable/http" @@ -84,7 +118,7 @@ export const allShort = [ * // false * ``` * - * @since 4.0.0 * @category refinements + * @since 4.0.0 */ export const isHttpMethod = (u: unknown): u is HttpMethod => all.has(u as HttpMethod) diff --git a/.opencode/node_modules/effect/src/unstable/http/HttpMiddleware.ts b/.opencode/node_modules/effect/src/unstable/http/HttpMiddleware.ts index 3c663b857c4bd07f5ae1abab86d66dde49d77c0f..0d723ccf45491ebca4d2e662bd8479e6f0d2727c 100644 --- a/.opencode/node_modules/effect/src/unstable/http/HttpMiddleware.ts +++ b/.opencode/node_modules/effect/src/unstable/http/HttpMiddleware.ts @@ -1,4 +1,13 @@ /** + * Wraps HTTP server apps with request and response behavior. + * + * A middleware is a function from one HTTP server app effect to another. The app + * runs with the current `HttpServerRequest` in its context, so middleware can + * inspect or rewrite the request, provide request-scoped services, attach hooks + * before the response is sent, or observe the app exit. This module includes + * middleware for response logging, server tracing, forwarded proxy headers, + * parsed search parameters, and CORS response headers. + * * @since 4.0.0 */ import { Clock } from "../../Clock.ts" @@ -22,18 +31,25 @@ import * as TraceContext from "./HttpTraceContext.ts" import { appendPreResponseHandlerUnsafe } from "./internal/preResponseHandler.ts" /** - * @since 4.0.0 + * Middleware that transforms an HTTP server app effect into another HTTP server app effect. + * * @category models + * @since 4.0.0 */ export interface HttpMiddleware { (self: Effect.Effect): Effect.Effect } /** + * Namespace containing types associated with `HttpMiddleware`. + * * @since 4.0.0 */ export declare namespace HttpMiddleware { /** + * Callable type representing middleware already specialized to a particular transformed app type. + * + * @category models * @since 4.0.0 */ export interface Applied, E, R> { @@ -42,8 +58,10 @@ export declare namespace HttpMiddleware { } /** - * @since 4.0.0 + * Defines an `HttpMiddleware` while preserving its precise type. + * * @category constructors + * @since 4.0.0 */ export const make = (middleware: M): M => middleware @@ -63,8 +81,10 @@ const stripSearchAndHash = (url: string): string => { } /** - * @since 4.0.0 + * Runs an effect with HTTP response logging disabled for the current server request. + * * @category Logger + * @since 4.0.0 */ export const withLoggerDisabled = (self: Effect.Effect): Effect.Effect => Effect.withFiber((fiber) => { @@ -74,8 +94,10 @@ export const withLoggerDisabled = (self: Effect.Effect): Effec }) /** - * @since 4.0.0 + * Context reference for a predicate that disables server-side tracing for matching requests. + * * @category Tracer + * @since 4.0.0 */ export const TracerDisabledWhen = Context.Reference>( "effect/http/HttpMiddleware/TracerDisabledWhen", @@ -83,16 +105,20 @@ export const TracerDisabledWhen = Context.Reference ) /** - * @since 4.0.0 + * Creates a layer that disables server-side tracing for requests whose URL exactly matches one of the supplied URLs. + * * @category Tracer + * @since 4.0.0 */ export const layerTracerDisabledForUrls = ( urls: ReadonlyArray ): Layer.Layer => Layer.succeed(TracerDisabledWhen)((req) => urls.includes(req.url)) /** - * @since 4.0.0 + * Context reference for generating server span names from HTTP server requests. + * * @category Tracer + * @since 4.0.0 */ export const SpanNameGenerator = Context.Reference<(request: HttpServerRequest) => string>( "@effect/platform/HttpMiddleware/SpanNameGenerator", @@ -100,14 +126,15 @@ export const SpanNameGenerator = Context.Reference<(request: HttpServerRequest) ) /** - * @since 4.0.0 + * Middleware that logs sent HTTP responses with request method, request URL, and response status annotations. + * * @category Logger + * @since 4.0.0 */ export const logger: ( httpApp: Effect.Effect -) => Effect.Effect = make((httpApp) => { - let counter = 0 - return Effect.withFiber((fiber) => { +) => Effect.Effect = make((httpApp) => + Effect.withFiber((fiber) => { const request = Context.getUnsafe(fiber.context, HttpServerRequest) const path = stripSearchAndHash(request.url) return Effect.withLogSpan( @@ -134,14 +161,16 @@ export const logger: ( exit ) }), - `http.span.${++counter}` + "http.span" ) }) -}) +) /** - * @since 4.0.0 + * Middleware that creates a server trace span for each request and records request and response HTTP attributes. + * * @category Tracer + * @since 4.0.0 */ export const tracer: ( httpApp: Effect.Effect @@ -203,8 +232,10 @@ export const tracer: ( ) /** - * @since 4.0.0 + * Middleware that trusts `X-Forwarded-Host` and `X-Forwarded-For`, updating the request host header and remote address. + * * @category Proxying + * @since 4.0.0 */ export const xForwardedHeaders = make((httpApp) => Effect.updateService(httpApp, HttpServerRequest, (request) => @@ -221,8 +252,10 @@ export const xForwardedHeaders = make((httpApp) => ) /** + * Middleware that parses the current request URL's search parameters and provides them as `ParsedSearchParams`. + * + * @category search params * @since 4.0.0 - * @category Search params */ export const searchParamsParser = ( httpApp: Effect.Effect @@ -239,8 +272,10 @@ export const searchParamsParser = ( }) /** - * @since 4.0.0 + * Middleware that handles CORS preflight requests and adds configured CORS headers to HTTP responses. + * * @category CORS + * @since 4.0.0 */ export const cors = (options?: { readonly allowedOrigins?: ReadonlyArray | Predicate | undefined diff --git a/.opencode/node_modules/effect/src/unstable/http/HttpPlatform.ts b/.opencode/node_modules/effect/src/unstable/http/HttpPlatform.ts index 4f865f1523a97f4b42a08530fa68ae28f463ec67..d4c8b2d7aefc13ec9ad32ac66eb650b830b39c91 100644 --- a/.opencode/node_modules/effect/src/unstable/http/HttpPlatform.ts +++ b/.opencode/node_modules/effect/src/unstable/http/HttpPlatform.ts @@ -1,4 +1,12 @@ /** + * Platform-specific support for serving files as HTTP server responses. + * + * `HttpPlatform` is the boundary between the portable HTTP response model and + * the runtime that knows how to stream bytes from the host platform. Server + * code uses this service when it needs to return local files, static assets, + * downloads, byte ranges, or Web `File`-like values without constructing the + * response body by hand. + * * @since 4.0.0 */ import * as Context from "../../Context.ts" @@ -15,8 +23,10 @@ import type * as Body from "./HttpBody.ts" import * as Response from "./HttpServerResponse.ts" /** + * Service for platform-specific HTTP response helpers, including file-backed server responses. + * + * @category services * @since 4.0.0 - * @category tags */ export class HttpPlatform extends Context.Service()("effect/http/HttpPlatform") {} /** - * @since 4.0.0 + * Creates an `HttpPlatform` service from platform-specific file response constructors, using `FileSystem` and `Etag.Generator`. + * * @category constructors + * @since 4.0.0 */ export const make: (impl: { readonly fileResponse: ( @@ -117,11 +129,19 @@ export const make: (impl: { }) /** - * @since 4.0.0 + * Provides the default `HttpPlatform` implementation for serving file paths and + * `File`-like values as streamed HTTP responses. + * + * **Details** + * + * The layer uses the `FileSystem` and weak ETag services to add file metadata + * headers such as `etag` and `last-modified`. + * * @category layers + * @since 4.0.0 */ export const layer = Layer.effect(HttpPlatform)( - Effect.flatMap(FileSystem.FileSystem.asEffect(), (fs) => + Effect.flatMap(FileSystem.FileSystem, (fs) => make({ fileResponse(path, status, statusText, headers, start, end, contentLength) { return Response.stream( diff --git a/.opencode/node_modules/effect/src/unstable/http/HttpRouter.ts b/.opencode/node_modules/effect/src/unstable/http/HttpRouter.ts index b8e02fb91ab80ba02e5bfd6c063883fe21401ab5..a15caaf61fd9692d5de7b7ccf710d88e1039ae8e 100644 --- a/.opencode/node_modules/effect/src/unstable/http/HttpRouter.ts +++ b/.opencode/node_modules/effect/src/unstable/http/HttpRouter.ts @@ -1,4 +1,12 @@ /** + * Builds server-side routers for Effect HTTP applications. + * + * `HttpRouter` collects routes and middleware while an application layer is + * being built. Once the router is complete, it handles each + * `HttpServerRequest` by finding a matching route and producing an + * `HttpServerResponse`. The module also includes helpers for route definitions, + * prefixes, parameters, request decoding, CORS, and running the router. + * * @since 4.0.0 */ import * as Arr from "../../Array.ts" @@ -25,8 +33,16 @@ import * as HttpServerResponse from "./HttpServerResponse.ts" const TypeId = "~effect/http/HttpRouter" /** - * @since 4.0.0 + * Defines the service interface for registering HTTP routes and middleware. + * + * **Details** + * + * An `HttpRouter` can add routes, apply path prefixes, install global middleware, + * and expose the registered routes as an Effect that handles the current server + * request. + * * @category HttpRouter + * @since 4.0.0 */ export interface HttpRouter { readonly [TypeId]: typeof TypeId @@ -77,16 +93,27 @@ export interface HttpRouter { } /** - * @since 4.0.0 + * Service tag for the HTTP router used while constructing an HTTP application. + * Route and middleware layers require this service to register themselves with + * the router. + * * @category HttpRouter + * @since 4.0.0 */ export const HttpRouter: Context.Service = Context.Service( "effect/http/HttpRouter" ) /** - * @since 4.0.0 + * Constructs an empty `HttpRouter` service. + * + * **Details** + * + * The returned router accepts route and middleware registrations and later routes + * the current `HttpServerRequest` to the matching `HttpServerResponse`. + * * @category HttpRouter + * @since 4.0.0 */ export const make = Effect.gen(function*() { const router = FindMyWay.make>(yield* RouterConfig) @@ -148,7 +175,7 @@ export const make = Effect.gen(function*() { Effect.succeed(handler) : Effect.isEffect(handler) ? handler - : Effect.flatMap(HttpServerRequest.HttpServerRequest.asEffect(), handler), + : Effect.flatMap(HttpServerRequest.HttpServerRequest, handler), uninterruptible: options?.uninterruptible ?? false, prefix }) @@ -215,8 +242,15 @@ function sliceRequestUrl(request: HttpServerRequest.HttpServerRequest, prefix: s } /** + * Context reference for low-level router configuration. + * + * **Details** + * + * The value is passed to the route matcher when an `HttpRouter` is created and + * defaults to an empty configuration. + * + * @category configuration * @since 4.0.0 - * @category Configuration */ export const RouterConfig = Context.Reference>( "effect/http/HttpRouter/RouterConfig", @@ -224,8 +258,20 @@ export const RouterConfig = Context.Reference>( ) /** + * Service for the matched HTTP route in the current request. + * + * **When to use** + * + * Use to read captured path parameters and route metadata while handling a + * request matched by the router. + * + * **Details** + * + * It provides the route definition and the path parameters captured by the route + * matcher. + * + * @category services * @since 4.0.0 - * @category RouteContext */ export class RouteContext extends Context.Service> @@ -233,18 +279,28 @@ export class RouteContext extends Context.Service()("effect/http/HttpRouter/RouteContext") {} /** + * Effect that returns the path parameters captured for the current matched route. + * + * @category getters * @since 4.0.0 - * @category RouteContext */ export const params: Effect.Effect< ReadonlyRecord, never, RouteContext -> = Effect.map(RouteContext.asEffect(), (_) => _.params) +> = Effect.map(RouteContext, (_) => _.params) /** + * Decodes a schema from the current request and its JSON body. + * + * **Details** + * + * The input passed to the schema includes the request method, URL, headers, + * cookies, path parameters, search parameters, and parsed JSON body. The effect + * fails if the body cannot be parsed or the schema decode fails. + * + * @category schemas * @since 4.0.0 - * @category Schema */ export const schemaJson = < A, @@ -292,8 +348,15 @@ export const schemaJson = < } /** + * Decodes a schema from the current request without reading the request body. + * + * **Details** + * + * The input passed to the schema includes the request method, URL, headers, + * cookies, path parameters, and search parameters. + * + * @category schemas * @since 4.0.0 - * @category Schema */ export const schemaNoBody = < A, @@ -338,8 +401,14 @@ export const schemaNoBody = < } /** + * Decodes a schema from the current route path parameters and search parameters. + * + * **Details** + * + * When the same key appears in both sources, the path parameter value is used. + * + * @category schemas * @since 4.0.0 - * @category Schema */ export const schemaParams = | undefined>>, RD, RE>( schema: Schema.Codec, @@ -354,8 +423,11 @@ export const schemaParams = >, RD, RE>( schema: Schema.Codec, @@ -366,12 +438,19 @@ export const schemaPathParams = ( f: (router: HttpRouter) => Effect.Effect -): Layer.Layer> => - Layer.effectDiscard(Effect.flatMap(HttpRouter.asEffect(), f)) +): Layer.Layer> => Layer.effectDiscard(Effect.flatMap(HttpRouter, f)) /** * Create a layer that adds a single route to the HTTP router. * + * **Example** (Adding a GET route) + * * ```ts * import { Effect } from "effect" - * import * as HttpRouter from "effect/unstable/http/HttpRouter" - * import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse" + * import { HttpRouter, HttpServerResponse } from "effect/unstable/http" * * const Route = HttpRouter.add( * "GET", @@ -403,8 +482,8 @@ export const use = ( * ) * ``` * - * @since 4.0.0 * @category HttpRouter + * @since 4.0.0 */ export const add = ( method: "*" | "GET" | "POST" | "PUT" | "PATCH" | "DELETE" | "OPTIONS", @@ -422,10 +501,11 @@ export const add = ( /** * Create a layer that adds multiple routes to the HTTP router. * + * **Example** (Adding multiple routes) + * * ```ts * import { Effect } from "effect" - * import * as HttpRouter from "effect/unstable/http/HttpRouter" - * import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse" + * import { HttpRouter, HttpServerResponse } from "effect/unstable/http" * * const Routes = HttpRouter.addAll([ * HttpRouter.route( @@ -436,8 +516,8 @@ export const add = ( * ]) * ``` * - * @since 4.0.0 * @category HttpRouter + * @since 4.0.0 */ export const addAll = >, EX = never, RX = never>( routes: Routes | Effect.Effect, @@ -462,14 +542,25 @@ export const addAll = >, EX = never })) /** - * @since 4.0.0 + * Layer that provides a newly constructed `HttpRouter`. + * * @category HttpRouter + * @since 4.0.0 */ export const layer: Layer.Layer = Layer.effect(HttpRouter)(make) /** - * @since 4.0.0 + * Builds an application layer with a router and returns the router as an HTTP + * handler effect. + * + * **Details** + * + * The returned effect handles the current `HttpServerRequest` in the current + * `Scope`; route request markers are converted into the ordinary requirements of + * the returned handler. + * * @category HttpRouter + * @since 4.0.0 */ export const toHttpEffect = ( appLayer: Layer.Layer @@ -492,8 +583,15 @@ export const toHttpEffect = ( const RouteTypeId = "~effect/http/HttpRouter/Route" /** - * @since 4.0.0 + * Description of a registered HTTP route. + * + * **Details** + * + * A route pairs an HTTP method and path pattern with a response handler, plus + * metadata used for prefix handling and interruptibility. + * * @category Route + * @since 4.0.0 */ export interface Route { readonly [RouteTypeId]: typeof RouteTypeId @@ -505,19 +603,25 @@ export interface Route { } /** + * Helper types for extracting the error and context types carried by `Route` + * values. + * * @since 4.0.0 - * @category Route */ export declare namespace Route { /** - * @since 4.0.0 + * Extracts the error type produced by a `Route` handler. + * * @category Route + * @since 4.0.0 */ export type Error> = R extends Route ? E : never /** - * @since 4.0.0 + * Extracts the context requirements of a `Route` handler. + * * @category Route + * @since 4.0.0 */ export type Context> = T extends Route ? R : never } @@ -528,17 +632,24 @@ const makeRoute = (options: { readonly handler: Effect.Effect readonly uninterruptible?: boolean | undefined readonly prefix?: Option.Option | string | undefined -}): Route> => - (({ - ...options, - uninterruptible: options.uninterruptible ?? false, - prefix: typeof options.prefix === "string" ? Option.some(options.prefix) : options.prefix ?? Option.none(), - [RouteTypeId]: RouteTypeId - }) as Route>) +}): Route> => (({ + ...options, + uninterruptible: options.uninterruptible ?? false, + prefix: typeof options.prefix === "string" ? Option.some(options.prefix) : options.prefix ?? Option.none(), + [RouteTypeId]: RouteTypeId +}) as Route>) /** - * @since 4.0.0 + * Constructs a `Route` from an HTTP method, path, and handler. + * + * **Details** + * + * The handler may be a static response, an effect that produces a response, or a + * function from the current request to a response effect. Set `uninterruptible` to + * prevent the route handler from being made interruptible while it runs. + * * @category Route + * @since 4.0.0 */ export const route = ( method: "*" | HttpMethod.HttpMethod, @@ -559,13 +670,16 @@ export const route = ( Effect.succeed(handler) : Effect.isEffect(handler) ? handler - : Effect.flatMap(HttpServerRequest.HttpServerRequest.asEffect(), handler), + : Effect.flatMap(HttpServerRequest.HttpServerRequest, handler), uninterruptible: options?.uninterruptible ?? false }) /** - * @since 4.0.0 + * Path pattern accepted by the router. Routes must use an absolute path + * beginning with `/` or the wildcard `*`. + * * @category PathInput + * @since 4.0.0 */ export type PathInput = `/${string}` | "*" @@ -574,18 +688,39 @@ const removeTrailingSlash = ( ): PathInput => (path.endsWith("/") ? path.slice(0, -1) : path) as any /** - * @since 4.0.0 + * Adds a path prefix to a route path. + * + * **Details** + * + * Trailing slashes are removed from the prefix; `/` becomes the prefix itself and + * `*` becomes a wildcard route under the prefix. + * * @category PathInput + * @since 4.0.0 */ export const prefixPath: { /** - * @since 4.0.0 + * Adds a path prefix to a route path. + * + * **Details** + * + * Trailing slashes are removed from the prefix; `/` becomes the prefix itself and + * `*` becomes a wildcard route under the prefix. + * * @category PathInput + * @since 4.0.0 */ (prefix: string): (self: string) => string /** - * @since 4.0.0 + * Adds a path prefix to a route path. + * + * **Details** + * + * Trailing slashes are removed from the prefix; `/` becomes the prefix itself and + * `*` becomes a wildcard route under the prefix. + * * @category PathInput + * @since 4.0.0 */ (self: string, prefix: string): string } = dual(2, (self: string, prefix: string) => { @@ -596,18 +731,42 @@ export const prefixPath: { }) /** - * @since 4.0.0 + * Returns a copy of a route with its path prefixed. + * + * **Details** + * + * The prefix is also tracked on the route so that, when the route handles a + * request, the matched prefix can be removed from the request URL seen by the + * handler. + * * @category Route + * @since 4.0.0 */ export const prefixRoute: { /** - * @since 4.0.0 + * Returns a copy of a route with its path prefixed. + * + * **Details** + * + * The prefix is also tracked on the route so that, when the route handles a + * request, the matched prefix can be removed from the request URL seen by the + * handler. + * * @category Route + * @since 4.0.0 */ (prefix: string): (self: Route) => Route /** - * @since 4.0.0 + * Returns a copy of a route with its path prefixed. + * + * **Details** + * + * The prefix is also tracked on the route so that, when the route handles a + * request, the matched prefix can be removed from the request URL seen by the + * handler. + * * @category Route + * @since 4.0.0 */ (self: Route, prefix: string): Route } = dual(2, (self: Route, prefix: string): Route => @@ -624,8 +783,8 @@ export const prefixRoute: { * Represents a request-level dependency, that needs to be provided by * middleware. * - * @since 4.0.0 * @category Request types + * @since 4.0.0 */ export interface Request { readonly _: unique symbol @@ -634,25 +793,35 @@ export interface Request { } /** + * Helper types for request-level dependency markers used by router layers and + * middleware. + * * @since 4.0.0 - * @category Request types */ export declare namespace Request { /** - * @since 4.0.0 + * Wraps a type in a request-level marker of the supplied kind. + * * @category Request types + * @since 4.0.0 */ export type From = R extends infer T ? Request : never /** - * @since 4.0.0 + * Extracts the payload types from request-level markers that have the supplied + * kind. + * * @category Request types + * @since 4.0.0 */ export type Only = A extends Request ? T : never /** - * @since 4.0.0 + * Removes request-level markers from a union, leaving only ordinary requirement + * or error types. + * * @category Request types + * @since 4.0.0 */ export type Without = A extends Request ? never : A } @@ -661,8 +830,8 @@ export declare namespace Request { * Services provided by the HTTP router, which are available in the * request context. * - * @since 4.0.0 * @category Request types + * @since 4.0.0 */ export type Provided = | HttpServerRequest.HttpServerRequest @@ -673,8 +842,8 @@ export type Provided = /** * Services provided to global middleware. * - * @since 4.0.0 * @category Request types + * @since 4.0.0 */ export type GlobalProvided = | HttpServerRequest.HttpServerRequest @@ -683,8 +852,16 @@ export type GlobalProvided = const MiddlewareTypeId = "~effect/http/HttpRouter/Middleware" /** + * Composable descriptor for route-scoped HTTP router middleware. + * + * **Details** + * + * Its `layer` can be provided to route layers, and `combine` composes middleware + * while tracking provided services, handled errors, and remaining requirements at + * the type level. + * + * @category middleware * @since 4.0.0 - * @category Middleware */ export interface Middleware< Config extends { @@ -729,18 +906,18 @@ export interface Middleware< /** * Create a middleware layer that can be used to modify requests and responses. * + * **Details** + * * By default, the middleware only affects the routes that it is provided to. * * If you want to create a middleware that applies globally to all routes, pass * the `global` option as `true`. * + * **Example** (Applying route and global middleware) + * * ```ts - * import { Effect } from "effect" - * import * as Layer from "effect/Layer" - * import * as Context from "effect/Context" - * import * as HttpMiddleware from "effect/unstable/http/HttpMiddleware" - * import * as HttpRouter from "effect/unstable/http/HttpRouter" - * import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse" + * import { Context, Effect, Layer } from "effect" + * import { HttpMiddleware, HttpRouter, HttpServerResponse } from "effect/unstable/http" * * // Here we are defining a CORS middleware * const CorsMiddleware = HttpRouter.middleware(HttpMiddleware.cors()).layer @@ -784,8 +961,8 @@ export interface Middleware< * ) * ``` * + * @category middleware * @since 4.0.0 - * @category Middleware */ export const middleware: & middleware.Make @@ -908,13 +1085,22 @@ const getMiddleware = (context: Context.Context): Array => } /** + * Types used by the `middleware` constructor. + * * @since 4.0.0 - * @category Middleware */ export declare namespace middleware { /** + * Overloaded constructor type for router middleware. + * + * **Details** + * + * It builds either a route-scoped `Middleware` or, when `global` is `true`, a + * layer that installs middleware for all routes. The type tracks provided + * services, handled errors, middleware failures, and remaining requirements. + * + * @category middleware * @since 4.0.0 - * @category Middleware */ export type Make = { ( @@ -995,8 +1181,11 @@ export declare namespace middleware { } /** + * Function that transforms an HTTP response effect into another HTTP response + * effect. + * + * @category middleware * @since 4.0.0 - * @category Middleware */ export type Fn = ( effect: Effect.Effect @@ -1004,10 +1193,10 @@ export declare namespace middleware { } /** - * A middleware that applies CORS headers to the HTTP response. + * Middleware that applies CORS headers to the HTTP response. * + * @category middleware * @since 4.0.0 - * @category Middleware */ export const cors = ( options?: { @@ -1021,13 +1210,13 @@ export const cors = ( ): Layer.Layer => middleware(HttpMiddleware.cors(options), { global: true }) /** - * A middleware that disables the logger for some routes. + * Middleware that disables the logger for some routes. + * + * **Example** (Disabling route logging) * * ```ts - * import { Effect } from "effect" - * import * as Layer from "effect/Layer" - * import * as HttpRouter from "effect/unstable/http/HttpRouter" - * import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse" + * import { Effect, Layer } from "effect" + * import { HttpRouter, HttpServerResponse } from "effect/unstable/http" * * const Route = HttpRouter.add( * "GET", @@ -1039,16 +1228,16 @@ export const cors = ( * ) * ``` * + * @category middleware * @since 4.0.0 - * @category Middleware */ export const disableLogger: Layer.Layer = middleware(HttpMiddleware.withLoggerDisabled).layer /** * Provides request-level dependencies to some routes. * + * @category middleware * @since 4.0.0 - * @category Middleware */ export const provideRequest = (layer: Layer.Layer) => @@ -1070,10 +1259,10 @@ export const provideRequest = ) /** - * Serves the provided application layer as an HTTP server. + * Runs the provided application layer as an HTTP server. * + * @category server * @since 4.0.0 - * @category Server */ export const serve = | Request.Only<"GlobalRequires", R>>( appLayer: Layer.Layer, @@ -1084,13 +1273,12 @@ export const serve = | Request.On /** * Middleware to apply to the HTTP server. * - * NOTE: This middleware is applied to the entire HTTP server chain, - * including the sending of the response. This means that modifications - * to the response **WILL NOT** be reflected in the final response sent to the - * client. + * **Gotchas** * - * Use HttpRouter.middleware to create middleware that can modify the - * response. + * This middleware is applied to the entire HTTP server chain, including the + * sending of the response. Changes to the response are not reflected in the + * final response sent to the client. Use `HttpRouter.middleware` when + * middleware must modify the response. */ readonly middleware?: ( effect: Effect.Effect< @@ -1128,8 +1316,17 @@ export const serve = | Request.On } /** + * Builds a Fetch-compatible request handler from an HTTP router application + * layer. + * + * **Details** + * + * The result contains a `handler` function that converts Web `Request` values to + * Web `Response` values and a `dispose` function for releasing the layer + * resources. + * + * @category server * @since 4.0.0 - * @category Server */ export const toWebHandler = < A, @@ -1151,13 +1348,12 @@ export const toWebHandler = < /** * Middleware to apply to the HTTP server. * - * NOTE: This middleware is applied to the entire HTTP server chain, - * including the sending of the response. This means that modifications - * to the response **WILL NOT** be reflected in the final response sent to the - * client. + * **Gotchas** * - * Use HttpRouter.middleware to create middleware that can modify the - * response. + * This middleware is applied to the entire HTTP server chain, including the + * sending of the response. Changes to the response are not reflected in the + * final response sent to the client. Use `HttpRouter.middleware` when + * middleware must modify the response. */ readonly middleware?: ( effect: Effect.Effect< diff --git a/.opencode/node_modules/effect/src/unstable/http/HttpServer.ts b/.opencode/node_modules/effect/src/unstable/http/HttpServer.ts index 9468b5073ad18ab1a12ebdb5e9d3c8a8906e74f4..b17c37c93d1595cf91f5bac4dd559c501e9d5be4 100644 --- a/.opencode/node_modules/effect/src/unstable/http/HttpServer.ts +++ b/.opencode/node_modules/effect/src/unstable/http/HttpServer.ts @@ -1,4 +1,12 @@ /** + * Service for serving Effect HTTP responses on a concrete HTTP server. + * + * Platform adapters provide `HttpServer`, and routers or applications consume + * it to run an `HttpServerResponse` effect for each incoming request. The + * service exposes the listening address, while this module also includes helpers + * for address formatting, server logging, and clients that target the current + * server in tests. + * * @since 4.0.0 */ import * as Context from "../../Context.ts" @@ -17,8 +25,15 @@ import type { HttpServerRequest } from "./HttpServerRequest.ts" import type { HttpServerResponse } from "./HttpServerResponse.ts" /** - * @since 4.0.0 + * Service tag for an HTTP server runtime. + * + * **Details** + * + * The service can serve an HTTP response effect and exposes the address where the + * server is listening. + * * @category models + * @since 4.0.0 */ export class HttpServer extends Context.Service()("effect/http/HttpServer") {} /** - * @since 4.0.0 + * Address where an HTTP server is listening. + * + * **Details** + * + * The address is either a TCP host and port or a Unix domain socket path. + * * @category address + * @since 4.0.0 */ export type Address = UnixAddress | TcpAddress /** - * @since 4.0.0 + * TCP address for an HTTP server, identified by hostname and port. + * * @category address + * @since 4.0.0 */ export interface TcpAddress { readonly _tag: "TcpAddress" @@ -57,8 +80,10 @@ export interface TcpAddress { } /** - * @since 4.0.0 + * Unix domain socket address for an HTTP server. + * * @category address + * @since 4.0.0 */ export interface UnixAddress { readonly _tag: "UnixAddress" @@ -66,8 +91,11 @@ export interface UnixAddress { } /** - * @since 4.0.0 + * Constructs an `HttpServer` service from a serving implementation and listening + * address. + * * @category constructors + * @since 4.0.0 */ export const make = ( options: { @@ -80,20 +108,47 @@ export const make = ( ): HttpServer["Service"] => options /** - * @since 4.0.0 + * Creates a layer that starts serving an HTTP response effect with the current + * `HttpServer`. + * + * **Details** + * + * The request service is supplied by the server for each request; the returned + * layer still requires the server, a scope, and any non-request dependencies of + * the response effect or middleware. + * * @category accessors + * @since 4.0.0 */ export const serve: { /** - * @since 4.0.0 + * Creates a layer that starts serving an HTTP response effect with the current + * `HttpServer`. + * + * **Details** + * + * The request service is supplied by the server for each request; the returned + * layer still requires the server, a scope, and any non-request dependencies of + * the response effect or middleware. + * * @category accessors + * @since 4.0.0 */ (): ( effect: Effect.Effect ) => Layer.Layer> /** - * @since 4.0.0 + * Creates a layer that starts serving an HTTP response effect with the current + * `HttpServer`. + * + * **Details** + * + * The request service is supplied by the server for each request; the returned + * layer still requires the server, a scope, and any non-request dependencies of + * the response effect or middleware. + * * @category accessors + * @since 4.0.0 */ >(middleware: Middleware.HttpMiddleware.Applied): ( effect: Effect.Effect @@ -103,13 +158,31 @@ export const serve: { HttpServer | Exclude, HttpServerRequest | Scope.Scope> > /** - * @since 4.0.0 + * Creates a layer that starts serving an HTTP response effect with the current + * `HttpServer`. + * + * **Details** + * + * The request service is supplied by the server for each request; the returned + * layer still requires the server, a scope, and any non-request dependencies of + * the response effect or middleware. + * * @category accessors + * @since 4.0.0 */ (effect: Effect.Effect): Layer.Layer> /** - * @since 4.0.0 + * Creates a layer that starts serving an HTTP response effect with the current + * `HttpServer`. + * + * **Details** + * + * The request service is supplied by the server for each request; the returned + * layer still requires the server, a scope, and any non-request dependencies of + * the response effect or middleware. + * * @category accessors + * @since 4.0.0 */ >( effect: Effect.Effect, @@ -132,20 +205,47 @@ export const serve: { ) as any) /** - * @since 4.0.0 + * Effect that starts serving an HTTP response effect with the current + * `HttpServer`. + * + * **Details** + * + * The request service is supplied by the server for each request; the effect + * requires a scope and any non-request dependencies of the response effect or + * middleware. + * * @category accessors + * @since 4.0.0 */ export const serveEffect: { /** - * @since 4.0.0 + * Effect that starts serving an HTTP response effect with the current + * `HttpServer`. + * + * **Details** + * + * The request service is supplied by the server for each request; the effect + * requires a scope and any non-request dependencies of the response effect or + * middleware. + * * @category accessors + * @since 4.0.0 */ (): ( effect: Effect.Effect ) => Effect.Effect> /** - * @since 4.0.0 + * Effect that starts serving an HTTP response effect with the current + * `HttpServer`. + * + * **Details** + * + * The request service is supplied by the server for each request; the effect + * requires a scope and any non-request dependencies of the response effect or + * middleware. + * * @category accessors + * @since 4.0.0 */ >(middleware: Middleware.HttpMiddleware.Applied): ( effect: Effect.Effect @@ -155,13 +255,31 @@ export const serveEffect: { Scope.Scope | HttpServer | Exclude, HttpServerRequest> > /** - * @since 4.0.0 + * Effect that starts serving an HTTP response effect with the current + * `HttpServer`. + * + * **Details** + * + * The request service is supplied by the server for each request; the effect + * requires a scope and any non-request dependencies of the response effect or + * middleware. + * * @category accessors + * @since 4.0.0 */ (effect: Effect.Effect): Effect.Effect> /** - * @since 4.0.0 + * Effect that starts serving an HTTP response effect with the current + * `HttpServer`. + * + * **Details** + * + * The request service is supplied by the server for each request; the effect + * requires a scope and any non-request dependencies of the response effect or + * middleware. + * * @category accessors + * @since 4.0.0 */ >( effect: Effect.Effect, @@ -181,8 +299,15 @@ export const serveEffect: { > => HttpServer.use((server) => server.serve(effect, middleware!)) as any) /** - * @since 4.0.0 + * Formats a server address as a display string. + * + * **Details** + * + * TCP addresses are formatted as `http://host:port`; Unix socket addresses are + * formatted as `unix://path`. + * * @category address + * @since 4.0.0 */ export const formatAddress = (address: Address): string => { switch (address._tag) { @@ -194,28 +319,35 @@ export const formatAddress = (address: Address): string => { } /** - * @since 4.0.0 + * Reads the current server address, formats it with `formatAddress`, and passes + * the formatted address to the supplied effectful function. + * * @category address + * @since 4.0.0 */ export const addressFormattedWith = ( f: (address: string) => Effect.Effect ): Effect.Effect => Effect.flatMap( - HttpServer.asEffect(), + HttpServer, (server) => f(formatAddress(server.address)) ) /** - * @since 4.0.0 + * Logs the formatted address of the current HTTP server. + * * @category address + * @since 4.0.0 */ export const logAddress: Effect.Effect = addressFormattedWith((_) => Effect.log(`Listening on ${_}`) ) /** - * @since 4.0.0 + * Adds address logging to a layer that provides an `HttpServer`. + * * @category address + * @since 4.0.0 */ export const withLogAddress = ( layer: Layer.Layer @@ -225,8 +357,19 @@ export const withLogAddress = ( ) /** + * Builds an `HttpClient` that sends requests to the current test HTTP server. + * + * **Details** + * + * For TCP servers, requests are prefixed with the server URL and `0.0.0.0` is + * rewritten to `127.0.0.1`. + * + * **Gotchas** + * + * Unix socket addresses are not supported. + * + * @category testing * @since 4.0.0 - * @category Testing */ export const makeTestClient: Effect.Effect< HttpClient.HttpClient, @@ -245,8 +388,10 @@ export const makeTestClient: Effect.Effect< }) /** + * Layer that provides the test `HttpClient` created by `makeTestClient`. + * + * @category testing * @since 4.0.0 - * @category Testing */ export const layerTestClient: Layer.Layer< HttpClient.HttpClient, @@ -255,8 +400,16 @@ export const layerTestClient: Layer.Layer< > = Layer.effect(HttpClient.HttpClient)(makeTestClient) /** + * Layer that provides the platform services commonly needed by HTTP + * server tests. + * + * **Details** + * + * It includes `HttpPlatform`, `Path`, a weak ETag generator, and a no-op + * `FileSystem`. + * + * @category testing * @since 4.0.0 - * @category Testing */ export const layerServices: Layer.Layer< | Path.Path diff --git a/.opencode/node_modules/effect/src/unstable/http/HttpServerError.ts b/.opencode/node_modules/effect/src/unstable/http/HttpServerError.ts index e40d701792de8eff0c09c9c23dda7900ab2b597b..7fb6aeffa88b6b485a731e5e546fdb29ad7b304e 100644 --- a/.opencode/node_modules/effect/src/unstable/http/HttpServerError.ts +++ b/.opencode/node_modules/effect/src/unstable/http/HttpServerError.ts @@ -1,4 +1,13 @@ /** + * Describes failures raised while handling HTTP server requests. + * + * `HttpServerError` covers failures that happen while accepting a request, + * matching a route, running a handler, or building and sending a response. + * Request-scoped failures keep the request that caused them, and response + * failures keep the response being produced. This module also includes helpers + * for turning failed causes or exits into HTTP responses and an annotation for + * interrupts caused by client aborts. + * * @since 4.0.0 */ import * as Cause from "../../Cause.ts" @@ -17,8 +26,16 @@ import * as Response from "./HttpServerResponse.ts" const TypeId = "~effect/http/HttpServerError" /** + * Tagged error for failures that occur while handling an HTTP server request. + * + * **Details** + * + * It wraps a `HttpServerErrorReason`, exposes the associated request and optional + * response, and can be converted to an HTTP response through the `Respondable` + * protocol. + * + * @category errors * @since 4.0.0 - * @category error */ export class HttpServerError extends Data.TaggedError("HttpServerError")<{ readonly reason: HttpServerErrorReason @@ -62,8 +79,14 @@ export class HttpServerError extends Data.TaggedError("HttpServerError")<{ } /** + * Error describing a failure to parse or read an incoming request. + * + * **Details** + * + * When converted to a response it produces an empty `400` response. + * + * @category errors * @since 4.0.0 - * @category error */ export class RequestParseError extends Data.TaggedError("RequestParseError")<{ readonly request: Request.HttpServerRequest @@ -71,6 +94,8 @@ export class RequestParseError extends Data.TaggedError("RequestParseError")<{ readonly cause?: unknown }> implements Respondable.Respondable { /** + * Converts the request error into a `400 Bad Request` response. + * * @since 4.0.0 */ [Respondable.symbol]() { @@ -87,8 +112,15 @@ export class RequestParseError extends Data.TaggedError("RequestParseError")<{ } /** + * Error indicating that no route matched the incoming request. + * + * **Details** + * + * When converted to a response it produces an empty `404` response, and it is + * ignored by the error reporter. + * + * @category errors * @since 4.0.0 - * @category error */ export class RouteNotFound extends Data.TaggedError("RouteNotFound")<{ readonly request: Request.HttpServerRequest @@ -111,8 +143,14 @@ export class RouteNotFound extends Data.TaggedError("RouteNotFound")<{ } /** + * Error describing an unexpected server-side failure while handling a request. + * + * **Details** + * + * When converted to a response it produces an empty `500` response. + * + * @category errors * @since 4.0.0 - * @category error */ export class InternalError extends Data.TaggedError("InternalError")<{ readonly request: Request.HttpServerRequest @@ -120,6 +158,8 @@ export class InternalError extends Data.TaggedError("InternalError")<{ readonly cause?: unknown }> implements Respondable.Respondable { /** + * Converts the server error into a `500 Internal Server Error` response. + * * @since 4.0.0 */ [Respondable.symbol]() { @@ -136,14 +176,23 @@ export class InternalError extends Data.TaggedError("InternalError")<{ } /** - * @since 4.0.0 + * Returns `true` when the supplied value is an `HttpServerError`. + * * @category predicates + * @since 4.0.0 */ export const isHttpServerError = (u: unknown): u is HttpServerError => hasProperty(u, TypeId) /** + * Error describing a failure related to an HTTP response. + * + * **Details** + * + * It carries the request and response involved in the failure. When converted to + * a response it produces an empty `500` response. + * + * @category errors * @since 4.0.0 - * @category error */ export class ResponseError extends Data.TaggedError("ResponseError")<{ readonly request: Request.HttpServerRequest @@ -166,28 +215,42 @@ export class ResponseError extends Data.TaggedError("ResponseError")<{ } /** + * Union of errors that are tied directly to an incoming server request. + * + * @category errors * @since 4.0.0 - * @category error */ export type RequestError = RequestParseError | RouteNotFound | InternalError /** + * Reason carried by an `HttpServerError`, either a request-level error or a response-level error. + * + * @category errors * @since 4.0.0 - * @category error */ export type HttpServerErrorReason = RequestError | ResponseError /** + * Error wrapping a low-level failure from the HTTP server implementation. + * + * @category errors * @since 4.0.0 - * @category error */ export class ServeError extends Data.TaggedError("ServeError")<{ readonly cause: unknown }> {} /** + * Context annotation used to mark an interrupt as caused by the client aborting + * the request. + * + * **Details** + * + * `causeResponse` uses this annotation to map a pure client abort to a `499` + * response instead of a server abort response. + * + * @category annotations * @since 4.0.0 - * @category Annotations */ export class ClientAbort extends Context.Service()("effect/http/HttpServerError/ClientAbort") { static annotation = this.context(true).pipe( @@ -205,6 +268,16 @@ const formatRequestMessage = (reason: string, description: string | undefined, i } /** + * Converts a failed handler cause into the HTTP response that should be sent and + * the cause that should be reported. + * + * **Details** + * + * Respondable failures and defects can choose their own response, defects that + * are already `HttpServerResponse` values are used directly, and pure interrupts + * produce either `499` for client aborts or `503` for server aborts. + * + * @category error handling * @since 4.0.0 */ export const causeResponse = ( @@ -253,6 +326,15 @@ export const causeResponse = ( } /** + * Derives an HTTP response from a failed handler cause synchronously. + * + * **Details** + * + * If the cause contains a defect that is already an `HttpServerResponse`, that + * response is used and removed from the remaining cause. Otherwise the response + * defaults to `500`. + * + * @category error handling * @since 4.0.0 */ export const causeResponseStripped = ( @@ -278,6 +360,10 @@ const clientAbortError = Effect.succeed(Response.empty({ status: 499 })) const serverAbortError = Effect.succeed(Response.empty({ status: 503 })) /** + * Extracts the response from a successful handler exit, or derives a response + * from the failure cause. + * + * @category error handling * @since 4.0.0 */ export const exitResponse = (exit: Exit.Exit): Response.HttpServerResponse => { diff --git a/.opencode/node_modules/effect/src/unstable/http/HttpServerRequest.ts b/.opencode/node_modules/effect/src/unstable/http/HttpServerRequest.ts index 668d64514334d126549b8b6cb16b21aaab7b4166..83e6c3e6f9d0f12ce2eb4ccec969459f9f99c7a4 100644 --- a/.opencode/node_modules/effect/src/unstable/http/HttpServerRequest.ts +++ b/.opencode/node_modules/effect/src/unstable/http/HttpServerRequest.ts @@ -1,4 +1,13 @@ /** + * Provides server-side access to the current incoming HTTP request. + * + * `HttpServerRequest` is the context service used by handlers, middleware, + * schema decoders, multipart parsers, WebSocket upgrades, and adapters. A + * request stores its method, URL, original URL, headers, cookies, remote + * address, body stream, and platform source object. This module also includes + * request conversions and schema decoders for cookies, headers, search + * parameters, JSON, forms, URL-encoded bodies, and multipart bodies. + * * @since 4.0.0 */ import type * as Arr from "../../Array.ts" @@ -28,21 +37,38 @@ import * as UrlParams from "./UrlParams.ts" export { /** - * @since 4.0.0 + * Provides the `MaxBodySize` fiber reference for configuring request body limits. + * + * **When to use** + * + * Use to configure the maximum body size accepted while reading server + * request bodies. + * * @category fiber refs + * @since 4.0.0 */ MaxBodySize } from "./HttpIncomingMessage.ts" /** + * Runtime type identifier for `HttpServerRequest` values. + * + * @category type IDs * @since 4.0.0 - * @category Type IDs */ export const TypeId = "~effect/http/HttpServerRequest" /** - * @since 4.0.0 + * Server-side representation of an incoming HTTP request. + * + * **Details** + * + * It extends `HttpIncomingMessage` with request metadata, parsed cookies, + * multipart accessors, WebSocket upgrade support, and a `modify` method for + * creating adjusted request views. + * * @category models + * @since 4.0.0 */ export interface HttpServerRequest extends HttpIncomingMessage.HttpIncomingMessage { readonly [TypeId]: typeof TypeId @@ -71,16 +97,35 @@ export interface HttpServerRequest extends HttpIncomingMessage.HttpIncomingMessa } /** - * @since 4.0.0 + * Service tag for the active server-side HTTP request. + * + * **When to use** + * + * Use to access the request currently being handled by HTTP server routes and + * middleware. + * * @category context + * @since 4.0.0 */ export const HttpServerRequest: Context.Service = Context.Service( "effect/http/HttpServerRequest" ) /** - * @since 4.0.0 + * Service that contains decoded URL query parameters for the current request. + * + * **When to use** + * + * Use to access query parameters that have already been parsed for the current + * server request. + * + * **Details** + * + * Each key maps to a string value, or to an array when the parameter appears more + * than once. + * * @category search params + * @since 4.0.0 */ export class ParsedSearchParams extends Context.Service< ParsedSearchParams, @@ -88,8 +133,14 @@ export class ParsedSearchParams extends Context.Service< >()("effect/http/ParsedSearchParams") {} /** - * @since 4.0.0 + * Converts a `URL` object's search parameters into a record. + * + * **Details** + * + * Repeated parameters are represented as arrays in insertion order. + * * @category search params + * @since 4.0.0 */ export const searchParamsFromURL = (url: URL): ReadonlyRecord> => { const out: Record> = {} @@ -109,8 +160,15 @@ export const searchParamsFromURL = (url: URL): ReadonlyRecord(): Channel.Channel< Arr.NonEmptyReadonlyArray, @@ -121,39 +179,45 @@ export const upgradeChannel = (): Channel.Channel< unknown, HttpServerRequest > => - HttpServerRequest.asEffect().pipe( + HttpServerRequest.pipe( Effect.flatMap((_) => _.upgrade), Effect.map(Socket.toChannelWith()), Channel.unwrap ) /** + * Decodes a schema from the cookies of the current request. + * + * @category schemas * @since 4.0.0 - * @category schema */ export const schemaCookies = >, RD, RE>( schema: Schema.Codec, options?: ParseOptions | undefined ): Effect.Effect => { const parse = Schema.decodeUnknownEffect(schema) - return Effect.flatMap(HttpServerRequest.asEffect(), (req) => parse(req.cookies, options)) + return Effect.flatMap(HttpServerRequest, (req) => parse(req.cookies, options)) } /** + * Decodes a schema from the headers of the current request. + * + * @category schemas * @since 4.0.0 - * @category schema */ export const schemaHeaders = >, RD, RE>( schema: Schema.Codec, options?: ParseOptions | undefined ): Effect.Effect => { const parse = Schema.decodeUnknownEffect(schema) - return Effect.flatMap(HttpServerRequest.asEffect(), (req) => parse(req.headers, options)) + return Effect.flatMap(HttpServerRequest, (req) => parse(req.headers, options)) } /** + * Decodes a schema from the parsed search parameters of the current request. + * + * @category schemas * @since 4.0.0 - * @category schema */ export const schemaSearchParams = < A, @@ -165,18 +229,25 @@ export const schemaSearchParams = < options?: ParseOptions | undefined ): Effect.Effect => { const parse = Schema.decodeUnknownEffect(schema) - return Effect.flatMap(ParsedSearchParams.asEffect(), (params) => parse(params, options)) + return Effect.flatMap(ParsedSearchParams, (params) => parse(params, options)) } /** + * Reads the current request body as JSON and decodes it with the supplied schema. + * + * **Details** + * + * The effect can fail if the body cannot be read or parsed, or if schema decoding + * fails. + * + * @category schemas * @since 4.0.0 - * @category schema */ export const schemaBodyJson = ( schema: Schema.Codec, options?: ParseOptions | undefined ): Effect.Effect => { const parse = HttpIncomingMessage.schemaBodyJson(schema, options) - return Effect.flatMap(HttpServerRequest.asEffect(), parse) + return Effect.flatMap(HttpServerRequest, parse) } const isMultipart = (request: HttpServerRequest) => @@ -184,8 +255,15 @@ const isMultipart = (request: HttpServerRequest) => getFormDataBody(request) !== undefined /** + * Decodes the current request body as form data. + * + * **Details** + * + * Multipart requests are persisted and decoded as multipart data; other form + * requests are decoded from URL-encoded body parameters. + * + * @category schemas * @since 4.0.0 - * @category schema */ export const schemaBodyForm = , RD, RE>( schema: Schema.Codec, @@ -193,7 +271,7 @@ export const schemaBodyForm = , RD, RE ) => { const parseMultipart = Multipart.schemaPersisted(schema) const parseUrlParams = HttpIncomingMessage.schemaBodyUrlParams(schema as Schema.Codec, options) - return Effect.flatMap(HttpServerRequest.asEffect(), (request): Effect.Effect< + return Effect.flatMap(HttpServerRequest, (request): Effect.Effect< A, Multipart.MultipartError | Schema.SchemaError | HttpServerError, RD | HttpServerRequest | Scope.Scope | FileSystem.FileSystem | Path.Path @@ -206,8 +284,11 @@ export const schemaBodyForm = , RD, RE } /** + * Reads the current request body as URL-encoded parameters and decodes them with + * the supplied schema. + * + * @category schemas * @since 4.0.0 - * @category schema */ export const schemaBodyUrlParams = < A, @@ -219,12 +300,20 @@ export const schemaBodyUrlParams = < options?: ParseOptions | undefined ): Effect.Effect => { const parse = HttpIncomingMessage.schemaBodyUrlParams(schema, options) - return Effect.flatMap(HttpServerRequest.asEffect(), parse) + return Effect.flatMap(HttpServerRequest, parse) } /** + * Persists the current multipart request body and decodes it with the supplied + * schema. + * + * **Details** + * + * The effect requires the services needed to persist multipart files, including a + * scope, file system, and path service. + * + * @category schemas * @since 4.0.0 - * @category schema */ export const schemaBodyMultipart = , RD, RE>( schema: Schema.Codec, @@ -235,15 +324,23 @@ export const schemaBodyMultipart = , R HttpServerRequest | Scope.Scope | FileSystem.FileSystem | Path.Path | RD > => { const parse = Multipart.schemaPersisted(schema) - return HttpServerRequest.asEffect().pipe( + return HttpServerRequest.pipe( Effect.flatMap((_) => _.multipart), Effect.flatMap((_) => parse(_, options)) ) } /** + * Creates a decoder for a JSON value stored in a form field. + * + * **Details** + * + * For multipart requests, the named multipart field is decoded as JSON. For + * URL-encoded requests, the named parameter is decoded as JSON and then decoded + * with the supplied schema. + * + * @category schemas * @since 4.0.0 - * @category schema */ export const schemaBodyFormJson = ( schema: Schema.Codec, @@ -256,7 +353,7 @@ export const schemaBodyFormJson = ( Schema.decodeEffect ) return Effect.flatMap( - HttpServerRequest.asEffect(), + HttpServerRequest, (request): Effect.Effect< A, Schema.SchemaError | HttpServerError, @@ -281,8 +378,15 @@ export const schemaBodyFormJson = ( } /** + * Creates an `HttpServerRequest` view of an `HttpClientRequest`. + * + * **Details** + * + * If the client request can be converted to an absolute URL, that URL is used as + * the original URL. + * + * @category converting * @since 4.0.0 - * @category conversions */ export const fromClientRequest = (request: HttpClientRequest.HttpClientRequest): HttpServerRequest => { const url = Option.match(HttpClientRequest.toUrl(request), { @@ -293,15 +397,29 @@ export const fromClientRequest = (request: HttpClientRequest.HttpClientRequest): } /** + * Wraps a Web `Request` as an `HttpServerRequest`. + * + * **Details** + * + * The request's current URL is stored without the scheme and host, while the + * original Web URL remains available as `originalUrl`. + * + * @category converting * @since 4.0.0 - * @category conversions */ export const fromWeb = (request: globalThis.Request): HttpServerRequest => new ServerRequestImpl(request, removeHost(request.url)) /** + * Converts an `HttpServerRequest` into an `HttpClientRequest`. + * + * **Details** + * + * The converted request preserves the method, headers, body stream, and a URL + * derived from the request when possible. + * + * @category converting * @since 4.0.0 - * @category conversions */ export const toClientRequest = (request: HttpServerRequest): HttpClientRequest.HttpClientRequest => HttpClientRequest.setUrl( @@ -878,8 +996,16 @@ const isFormData = (u: unknown): u is FormData => typeof FormData !== "undefined const textDecoder = new TextDecoder() /** + * Attempts to construct an absolute `URL` for a server request safely. + * + * **Details** + * + * The host comes from the `host` header, defaulting to `localhost`, and the + * protocol is `https` only when `x-forwarded-proto` is `https`; invalid URLs + * return `Option.none`. + * + * @category converting * @since 4.0.0 - * @category conversions */ export const toURL = (self: HttpServerRequest): Option.Option => { const host = self.headers.host ?? "localhost" @@ -892,8 +1018,16 @@ export const toURL = (self: HttpServerRequest): Option.Option => { } /** + * Converts an `HttpServerRequest` safely to a Web `Request` as a `Result`. + * + * **Details** + * + * If the source is already a Web `Request`, it is returned unchanged. Otherwise + * an absolute URL is derived from the request; invalid URLs fail with a + * `RequestParseError`. + * + * @category converting * @since 4.0.0 - * @category conversions */ export const toWebResult = (self: HttpServerRequest, options?: { readonly signal?: AbortSignal | undefined @@ -926,15 +1060,22 @@ export const toWebResult = (self: HttpServerRequest, options?: { } /** + * Converts an `HttpServerRequest` to a Web `Request` in `Effect`. + * + * **Details** + * + * The current context is used when streaming the request body into the Web + * request. + * + * @category converting * @since 4.0.0 - * @category conversions */ export const toWeb = (self: HttpServerRequest, options?: { readonly signal?: AbortSignal | undefined }): Effect.Effect => Effect.contextWith((context) => - toWebResult(self, { + Effect.fromResult(toWebResult(self, { context, signal: options?.signal - }).asEffect() + })) ) diff --git a/.opencode/node_modules/effect/src/unstable/http/HttpServerRespondable.ts b/.opencode/node_modules/effect/src/unstable/http/HttpServerRespondable.ts index 109fcc8ecd8c68dabc43acb56ee63a6dfff6cf45..3a377d075d072758a4ec313db1081078cd6ba2b3 100644 --- a/.opencode/node_modules/effect/src/unstable/http/HttpServerRespondable.ts +++ b/.opencode/node_modules/effect/src/unstable/http/HttpServerRespondable.ts @@ -1,4 +1,11 @@ /** + * Converts supported values into HTTP server responses. + * + * Server-side errors and helper values can implement `Respondable` when they + * know which status, headers, cookies, or body should be sent to the client. + * This module detects those values and converts them to `HttpServerResponse` + * values, with fallback handling for schema errors and missing values. + * * @since 4.0.0 */ import * as Cause from "../../Cause.ts" @@ -9,22 +16,34 @@ import type { HttpServerResponse } from "./HttpServerResponse.ts" import * as Response from "./HttpServerResponse.ts" /** + * Protocol key used by values that can render themselves as + * `HttpServerResponse` values. + * + * @category type IDs * @since 4.0.0 - * @category Type IDs */ export const symbol = "~effect/http/HttpServerRespondable" /** - * @since 4.0.0 + * Protocol for values that can be converted into an `HttpServerResponse`. + * + * **Details** + * + * Implement the protocol method to describe the response that should be sent for + * the value. + * * @category models + * @since 4.0.0 */ export interface Respondable { [symbol](): Effect.Effect } /** - * @since 4.0.0 + * Returns `true` when the supplied value implements the `Respondable` protocol. + * * @category guards + * @since 4.0.0 */ export const isRespondable = (u: unknown): u is Respondable => hasProperty(u, symbol) @@ -32,8 +51,15 @@ const badRequest = Response.empty({ status: 400 }) const notFound = Response.empty({ status: 404 }) /** - * @since 4.0.0 + * Converts a `Respondable` value into an `HttpServerResponse`. + * + * **Details** + * + * If the value is already an HTTP server response it is returned directly; errors + * from the response conversion are converted to defects. + * * @category accessors + * @since 4.0.0 */ export const toResponse = (self: Respondable): Effect.Effect => { if (Response.isHttpServerResponse(self)) { @@ -43,8 +69,16 @@ export const toResponse = (self: Respondable): Effect.Effect } /** - * @since 4.0.0 + * Attempts to convert an unknown value into an `HttpServerResponse`, falling back + * to the supplied response when no conversion is available. + * + * **Details** + * + * `HttpServerResponse` and `Respondable` values are used directly, schema errors + * become `400` responses, and no-such-element errors become `404` responses. + * * @category accessors + * @since 4.0.0 */ export const toResponseOrElse = (u: unknown, orElse: HttpServerResponse): Effect.Effect => { if (Response.isHttpServerResponse(u)) { @@ -61,8 +95,15 @@ export const toResponseOrElse = (u: unknown, orElse: HttpServerResponse): Effect } /** - * @since 4.0.0 + * Attempts to convert an unknown defect into an `HttpServerResponse`, falling + * back to the supplied response when no conversion is available. + * + * **Details** + * + * Only `HttpServerResponse` and `Respondable` values receive special handling. + * * @category accessors + * @since 4.0.0 */ export const toResponseOrElseDefect = (u: unknown, orElse: HttpServerResponse): Effect.Effect => { if (Response.isHttpServerResponse(u)) { diff --git a/.opencode/node_modules/effect/src/unstable/http/HttpServerResponse.ts b/.opencode/node_modules/effect/src/unstable/http/HttpServerResponse.ts index 1df3ed70d576b4ff48c1e671f24e7bc3a2daf12f..3d00f72292abe14dd8056492f90392f9208011b2 100644 --- a/.opencode/node_modules/effect/src/unstable/http/HttpServerResponse.ts +++ b/.opencode/node_modules/effect/src/unstable/http/HttpServerResponse.ts @@ -1,4 +1,13 @@ /** + * Describes immutable responses returned by Effect HTTP handlers. + * + * An `HttpServerResponse` stores the status, optional status text, headers, + * cookies, and body that the server runtime later turns into a platform + * response such as a Web `Response`. This module includes constructors for + * common response bodies, helpers for updating response data, file response + * support through `HttpPlatform`, and conversions to or from Web and Effect + * HTTP client responses. + * * @since 4.0.0 */ import * as Context from "../../Context.ts" @@ -31,8 +40,15 @@ import * as UrlParams from "./UrlParams.ts" const TypeId = "~effect/http/HttpServerResponse" /** - * @since 4.0.0 + * Server-side HTTP response model. + * + * **Details** + * + * A response contains a status, optional status text, headers, cookies, and an + * HTTP body that can later be converted to platform-specific response types. + * * @category models + * @since 4.0.0 */ export interface HttpServerResponse extends Inspectable.Inspectable, Pipeable, ErrorReporter.Reportable { readonly [TypeId]: typeof TypeId @@ -44,8 +60,10 @@ export interface HttpServerResponse extends Inspectable.Inspectable, Pipeable, E } /** + * Common options accepted by HTTP server response constructors. + * + * @category options * @since 4.0.0 - * @category models */ export interface Options { readonly status?: number | undefined @@ -57,30 +75,48 @@ export interface Options { } /** + * Option variants used by response constructors with different body metadata + * rules. + * * @since 4.0.0 */ export declare namespace Options { /** + * Response options for constructors whose body determines its own content type + * and content length. + * + * @category options * @since 4.0.0 - * @category models */ export interface WithContent extends Omit {} /** + * Response options for constructors that allow overriding the content type while + * deriving the content length from the body. + * + * @category options * @since 4.0.0 - * @category models */ export interface WithContentType extends Omit {} } /** + * Returns `true` when the supplied value is an `HttpServerResponse`. + * + * @category guards * @since 4.0.0 */ export const isHttpServerResponse = (u: unknown): u is HttpServerResponse => hasProperty(u, TypeId) /** - * @since 4.0.0 + * Creates an empty HTTP response. + * + * **Details** + * + * The default status is `204`. + * * @category constructors + * @since 4.0.0 */ export const empty = ( options?: Options.WithContent | undefined @@ -93,8 +129,15 @@ export const empty = ( }) /** - * @since 4.0.0 + * Creates a redirect response with a `Location` header. + * + * **Details** + * + * The default status is `302`; custom headers are merged with the generated + * `Location` header. + * * @category constructors + * @since 4.0.0 */ export const redirect = ( location: string | URL, @@ -112,8 +155,10 @@ export const redirect = ( } /** - * @since 4.0.0 + * Creates an HTTP response whose body is a `Uint8Array`. + * * @category constructors + * @since 4.0.0 */ export const uint8Array = ( body: Uint8Array, @@ -143,8 +188,10 @@ const getContentType = ( } /** - * @since 4.0.0 + * Creates an HTTP response whose body is a string. + * * @category constructors + * @since 4.0.0 */ export const text = ( body: string, @@ -163,13 +210,29 @@ export const text = ( } /** - * @since 4.0.0 + * Creates an HTML response with the `text/html` content type. + * + * **Details** + * + * Passing a string returns a response directly. Using it as a template tag returns + * an effect so interpolated values can be rendered with their required services + * and errors. + * * @category constructors + * @since 4.0.0 */ export const html: { /** - * @since 4.0.0 + * Creates an HTML response with the `text/html` content type. + * + * **Details** + * + * Passing a string returns a response directly. Using it as a template tag returns + * an effect so interpolated values can be rendered with their required services + * and errors. + * * @category constructors + * @since 4.0.0 */ >(strings: TemplateStringsArray, ...args: A): Effect.Effect< HttpServerResponse, @@ -177,8 +240,16 @@ export const html: { Template.Interpolated.Context > /** - * @since 4.0.0 + * Creates an HTML response with the `text/html` content type. + * + * **Details** + * + * Passing a string returns a response directly. Using it as a template tag returns + * an effect so interpolated values can be rendered with their required services + * and errors. + * * @category constructors + * @since 4.0.0 */ (html: string): HttpServerResponse } = ( @@ -193,8 +264,15 @@ export const html: { } /** - * @since 4.0.0 + * Creates a streaming HTML response from a template. + * + * **Details** + * + * The template is encoded as a byte stream and can use streaming interpolated + * values from the current context. + * * @category constructors + * @since 4.0.0 */ export const htmlStream = < A extends ReadonlyArray @@ -219,8 +297,15 @@ export const htmlStream = < ) /** - * @since 4.0.0 + * Creates a JSON HTTP response. + * + * **Details** + * + * The body is serialized with `JSON.stringify`; serialization errors are captured + * as `HttpBodyError` failures. + * * @category constructors + * @since 4.0.0 */ export const json = ( body: unknown, @@ -238,8 +323,16 @@ export const json = ( } /** - * @since 4.0.0 + * Creates a JSON response constructor backed by a schema encoder. + * + * **Details** + * + * The returned function encodes the value with the supplied schema before + * serializing it as JSON, and can fail with `HttpBodyError` if schema encoding or + * JSON serialization fails. + * * @category constructors + * @since 4.0.0 */ export const schemaJson = ( schema: Schema.Codec, @@ -263,8 +356,20 @@ export const schemaJson = ( } /** - * @since 4.0.0 + * Creates a JSON HTTP response synchronously. + * + * **When to use** + * + * Use when the response body is known to be JSON-serializable and you need a + * synchronous `HttpServerResponse`. + * + * **Gotchas** + * + * Unlike `json`, serialization errors from `JSON.stringify` are not captured in + * `Effect`. + * * @category constructors + * @since 4.0.0 */ export const jsonUnsafe = ( body: unknown, @@ -281,8 +386,11 @@ export const jsonUnsafe = ( } /** - * @since 4.0.0 + * Creates a response from URL parameters using the + * `application/x-www-form-urlencoded` content type by default. + * * @category constructors + * @since 4.0.0 */ export const urlParams = ( body: UrlParams.Input, @@ -302,8 +410,16 @@ export const urlParams = ( } /** - * @since 4.0.0 + * Creates a response with a raw body value. + * + * **When to use** + * + * Use when you want to pass through a body value already understood by the + * underlying runtime, such as a Web `Response`, `Blob`, or `ReadableStream`, + * for later platform conversion. + * * @category constructors + * @since 4.0.0 */ export const raw = ( body: unknown, @@ -321,8 +437,10 @@ export const raw = ( }) /** - * @since 4.0.0 + * Creates a response whose body is a Web `FormData` value. + * * @category constructors + * @since 4.0.0 */ export const formData = ( body: FormData, @@ -337,8 +455,15 @@ export const formData = ( }) /** - * @since 4.0.0 + * Creates a streaming response from a stream of byte chunks. + * + * **Details** + * + * Optional response metadata can supply the status, headers, content type, and + * content length. + * * @category constructors + * @since 4.0.0 */ export const stream = ( body: Stream.Stream, @@ -366,8 +491,15 @@ const HttpPlatformKey = Context.Service< >("effect/http/HttpPlatform" satisfies typeof HttpPlatform.key) /** - * @since 4.0.0 + * Creates a streamed file response for a file system path. + * + * **Details** + * + * The effect requires `HttpPlatform`, can fail with a platform error, and supports + * options for status, headers, offset, and byte range. + * * @category constructors + * @since 4.0.0 */ export const file = ( path: string, @@ -379,11 +511,18 @@ export const file = ( }) | undefined ): Effect.Effect => - Effect.flatMap(HttpPlatformKey.asEffect(), (platform) => platform.fileResponse(path, options)) + Effect.flatMap(HttpPlatformKey, (platform) => platform.fileResponse(path, options)) /** - * @since 4.0.0 + * Creates a streamed file response for a Web `File`-like value. + * + * **Details** + * + * The effect requires `HttpPlatform` and supports options for status, headers, + * offset, and byte range. + * * @category constructors + * @since 4.0.0 */ export const fileWeb = ( file: Body.HttpBody.FileLike, @@ -395,21 +534,27 @@ export const fileWeb = ( }) | undefined ): Effect.Effect => - Effect.flatMap(HttpPlatformKey.asEffect(), (platform) => platform.fileWebResponse(file, options)) + Effect.flatMap(HttpPlatformKey, (platform) => platform.fileWebResponse(file, options)) /** - * @since 4.0.0 + * Returns a response with the specified header set to the supplied value. + * * @category combinators + * @since 4.0.0 */ export const setHeader: { /** - * @since 4.0.0 + * Returns a response with the specified header set to the supplied value. + * * @category combinators + * @since 4.0.0 */ (key: string, value: string): (self: HttpServerResponse) => HttpServerResponse /** - * @since 4.0.0 + * Returns a response with the specified header set to the supplied value. + * * @category combinators + * @since 4.0.0 */ (self: HttpServerResponse, key: string, value: string): HttpServerResponse } = dual( @@ -422,18 +567,24 @@ export const setHeader: { ) /** - * @since 4.0.0 + * Returns a response with all supplied headers set on the existing header map. + * * @category combinators + * @since 4.0.0 */ export const setHeaders: { /** - * @since 4.0.0 + * Returns a response with all supplied headers set on the existing header map. + * * @category combinators + * @since 4.0.0 */ (input: Headers.Input): (self: HttpServerResponse) => HttpServerResponse /** - * @since 4.0.0 + * Returns a response with all supplied headers set on the existing header map. + * * @category combinators + * @since 4.0.0 */ (self: HttpServerResponse, input: Headers.Input): HttpServerResponse } = dual( @@ -446,18 +597,24 @@ export const setHeaders: { ) /** - * @since 4.0.0 + * Returns a response with the cookie of the specified name removed. + * * @category combinators + * @since 4.0.0 */ export const removeCookie: { /** - * @since 4.0.0 + * Returns a response with the cookie of the specified name removed. + * * @category combinators + * @since 4.0.0 */ (name: string): (self: HttpServerResponse) => HttpServerResponse /** - * @since 4.0.0 + * Returns a response with the cookie of the specified name removed. + * * @category combinators + * @since 4.0.0 */ (self: HttpServerResponse, name: string): HttpServerResponse } = dual( @@ -470,18 +627,24 @@ export const removeCookie: { ) /** - * @since 4.0.0 + * Returns a response with its cookie collection replaced by the supplied cookies. + * * @category combinators + * @since 4.0.0 */ export const replaceCookies: { /** - * @since 4.0.0 + * Returns a response with its cookie collection replaced by the supplied cookies. + * * @category combinators + * @since 4.0.0 */ (cookies: Cookies.Cookies): (self: HttpServerResponse) => HttpServerResponse /** - * @since 4.0.0 + * Returns a response with its cookie collection replaced by the supplied cookies. + * * @category combinators + * @since 4.0.0 */ (self: HttpServerResponse, cookies: Cookies.Cookies): HttpServerResponse } = dual( @@ -490,20 +653,41 @@ export const replaceCookies: { ) /** - * @since 4.0.0 + * Sets a cookie on the response. + * + * **Details** + * + * The effect fails with `CookiesError` if the cookie name, value, or options are + * invalid. + * * @category combinators + * @since 4.0.0 */ export const setCookie: { /** - * @since 4.0.0 + * Sets a cookie on the response. + * + * **Details** + * + * The effect fails with `CookiesError` if the cookie name, value, or options are + * invalid. + * * @category combinators + * @since 4.0.0 */ (name: string, value: string, options?: Cookies.Cookie["options"]): ( self: HttpServerResponse ) => Effect.Effect /** - * @since 4.0.0 + * Sets a cookie on the response. + * + * **Details** + * + * The effect fails with `CookiesError` if the cookie name, value, or options are + * invalid. + * * @category combinators + * @since 4.0.0 */ ( self: HttpServerResponse, @@ -520,7 +704,7 @@ export const setCookie: { options?: Cookies.Cookie["options"] ): Effect.Effect => Effect.map( - Cookies.set(self.cookies, name, value, options).asEffect(), + Effect.fromResult(Cookies.set(self.cookies, name, value, options)), (cookies) => makeResponse({ ...self, @@ -530,13 +714,27 @@ export const setCookie: { ) /** - * @since 4.0.0 + * Sets an expired cookie on an `HttpServerResponse`. + * + * **Details** + * + * Returns an effect because cookie encoding can fail. The original response is not + * mutated; the effect succeeds with a response containing the updated cookie set. + * * @category combinators + * @since 4.0.0 */ export const expireCookie: { /** - * @since 4.0.0 + * Sets an expired cookie on an `HttpServerResponse`. + * + * **Details** + * + * Returns an effect because cookie encoding can fail. The original response is not + * mutated; the effect succeeds with a response containing the updated cookie set. + * * @category combinators + * @since 4.0.0 */ ( name: string, @@ -545,8 +743,15 @@ export const expireCookie: { self: HttpServerResponse ) => Effect.Effect /** - * @since 4.0.0 + * Sets an expired cookie on an `HttpServerResponse`. + * + * **Details** + * + * Returns an effect because cookie encoding can fail. The original response is not + * mutated; the effect succeeds with a response containing the updated cookie set. + * * @category combinators + * @since 4.0.0 */ ( self: HttpServerResponse, @@ -561,7 +766,7 @@ export const expireCookie: { options?: Omit, "expires" | "maxAge"> ): Effect.Effect => Effect.map( - Cookies.expireCookie(self.cookies, name, options).asEffect(), + Effect.fromResult(Cookies.expireCookie(self.cookies, name, options)), (cookies) => makeResponse({ ...self, @@ -571,18 +776,42 @@ export const expireCookie: { ) /** - * @since 4.0.0 + * Sets a cookie on an `HttpServerResponse`, throwing if the cookie cannot be + * encoded. + * + * **When to use** + * + * Use when you need to set one trusted cookie and want encoding failures to + * throw instead of being represented as `CookiesError` failures. + * * @category combinators + * @since 4.0.0 */ export const setCookieUnsafe: { /** - * @since 4.0.0 + * Sets a cookie on an `HttpServerResponse`, throwing if the cookie cannot be + * encoded. + * + * **When to use** + * + * Use when you need to set one trusted cookie and want encoding failures to + * throw instead of being represented as `CookiesError` failures. + * * @category combinators + * @since 4.0.0 */ (name: string, value: string, options?: Cookies.Cookie["options"]): (self: HttpServerResponse) => HttpServerResponse /** - * @since 4.0.0 + * Sets a cookie on an `HttpServerResponse`, throwing if the cookie cannot be + * encoded. + * + * **When to use** + * + * Use when you need to set one trusted cookie and want encoding failures to + * throw instead of being represented as `CookiesError` failures. + * * @category combinators + * @since 4.0.0 */ ( self: HttpServerResponse, @@ -605,21 +834,45 @@ export const setCookieUnsafe: { ) /** - * @since 4.0.0 + * Sets an expired cookie on an `HttpServerResponse`, throwing if the expiration cookie + * cannot be encoded. + * + * **When to use** + * + * Use when you need to expire one trusted cookie and want encoding failures to + * throw instead of being represented as `CookiesError` failures. + * * @category combinators + * @since 4.0.0 */ export const expireCookieUnsafe: { /** - * @since 4.0.0 + * Sets an expired cookie on an `HttpServerResponse`, throwing if the expiration cookie + * cannot be encoded. + * + * **When to use** + * + * Use when you need to expire one trusted cookie and want encoding failures to + * throw instead of being represented as `CookiesError` failures. + * * @category combinators + * @since 4.0.0 */ ( name: string, options?: Omit, "expires" | "maxAge"> ): (self: HttpServerResponse) => HttpServerResponse /** - * @since 4.0.0 + * Sets an expired cookie on an `HttpServerResponse`, throwing if the expiration cookie + * cannot be encoded. + * + * **When to use** + * + * Use when you need to expire one trusted cookie and want encoding failures to + * throw instead of being represented as `CookiesError` failures. + * * @category combinators + * @since 4.0.0 */ ( self: HttpServerResponse, @@ -640,18 +893,42 @@ export const expireCookieUnsafe: { ) /** - * @since 4.0.0 + * Updates the cookies attached to an `HttpServerResponse` using the supplied + * function. + * + * **Details** + * + * The original response is not mutated; a new response is returned with the + * callback result as its cookie collection. + * * @category combinators + * @since 4.0.0 */ export const updateCookies: { /** - * @since 4.0.0 + * Updates the cookies attached to an `HttpServerResponse` using the supplied + * function. + * + * **Details** + * + * The original response is not mutated; a new response is returned with the + * callback result as its cookie collection. + * * @category combinators + * @since 4.0.0 */ (f: (cookies: Cookies.Cookies) => Cookies.Cookies): (self: HttpServerResponse) => HttpServerResponse /** - * @since 4.0.0 + * Updates the cookies attached to an `HttpServerResponse` using the supplied + * function. + * + * **Details** + * + * The original response is not mutated; a new response is returned with the + * callback result as its cookie collection. + * * @category combinators + * @since 4.0.0 */ (self: HttpServerResponse, f: (cookies: Cookies.Cookies) => Cookies.Cookies): HttpServerResponse } = dual( @@ -667,18 +944,42 @@ export const updateCookies: { ) /** - * @since 4.0.0 + * Merges additional cookies into the cookies attached to an + * `HttpServerResponse`. + * + * **Details** + * + * The original response is not mutated; a new response is returned with the merged + * cookie collection. + * * @category combinators + * @since 4.0.0 */ export const mergeCookies: { /** - * @since 4.0.0 + * Merges additional cookies into the cookies attached to an + * `HttpServerResponse`. + * + * **Details** + * + * The original response is not mutated; a new response is returned with the merged + * cookie collection. + * * @category combinators + * @since 4.0.0 */ (cookies: Cookies.Cookies): (self: HttpServerResponse) => HttpServerResponse /** - * @since 4.0.0 + * Merges additional cookies into the cookies attached to an + * `HttpServerResponse`. + * + * **Details** + * + * The original response is not mutated; a new response is returned with the merged + * cookie collection. + * * @category combinators + * @since 4.0.0 */ (self: HttpServerResponse, cookies: Cookies.Cookies): HttpServerResponse } = dual( @@ -688,13 +989,27 @@ export const mergeCookies: { ) /** - * @since 4.0.0 + * Sets multiple cookies on an `HttpServerResponse`. + * + * **Details** + * + * Each input entry contains a cookie name, value, and optional cookie options. The + * returned effect fails with `CookiesError` if any cookie cannot be encoded. + * * @category combinators + * @since 4.0.0 */ export const setCookies: { /** - * @since 4.0.0 + * Sets multiple cookies on an `HttpServerResponse`. + * + * **Details** + * + * Each input entry contains a cookie name, value, and optional cookie options. The + * returned effect fails with `CookiesError` if any cookie cannot be encoded. + * * @category combinators + * @since 4.0.0 */ ( cookies: Iterable< @@ -708,8 +1023,15 @@ export const setCookies: { self: HttpServerResponse ) => Effect.Effect /** - * @since 4.0.0 + * Sets multiple cookies on an `HttpServerResponse`. + * + * **Details** + * + * Each input entry contains a cookie name, value, and optional cookie options. The + * returned effect fails with `CookiesError` if any cookie cannot be encoded. + * * @category combinators + * @since 4.0.0 */ ( self: HttpServerResponse, @@ -733,7 +1055,7 @@ export const setCookies: { ] > ): Effect.Effect => - Effect.map(Cookies.setAll(self.cookies, cookies).asEffect(), (cookies) => + Effect.map(Effect.fromResult(Cookies.setAll(self.cookies, cookies)), (cookies) => makeResponse({ ...self, cookies @@ -741,13 +1063,29 @@ export const setCookies: { ) /** - * @since 4.0.0 + * Sets multiple cookies on an `HttpServerResponse`, throwing if any cookie cannot + * be encoded. + * + * **When to use** + * + * Use when you need to set multiple trusted cookies and want encoding failures + * to throw instead of being represented as `CookiesError` failures. + * * @category combinators + * @since 4.0.0 */ export const setCookiesUnsafe: { /** - * @since 4.0.0 + * Sets multiple cookies on an `HttpServerResponse`, throwing if any cookie cannot + * be encoded. + * + * **When to use** + * + * Use when you need to set multiple trusted cookies and want encoding failures + * to throw instead of being represented as `CookiesError` failures. + * * @category combinators + * @since 4.0.0 */ ( cookies: Iterable< @@ -759,8 +1097,16 @@ export const setCookiesUnsafe: { > ): (self: HttpServerResponse) => HttpServerResponse /** - * @since 4.0.0 + * Sets multiple cookies on an `HttpServerResponse`, throwing if any cookie cannot + * be encoded. + * + * **When to use** + * + * Use when you need to set multiple trusted cookies and want encoding failures + * to throw instead of being represented as `CookiesError` failures. + * * @category combinators + * @since 4.0.0 */ ( self: HttpServerResponse, @@ -791,18 +1137,39 @@ export const setCookiesUnsafe: { ) /** - * @since 4.0.0 + * Replaces the body of an `HttpServerResponse`. + * + * **Details** + * + * When the body carries a content type or content length, the returned response + * includes the corresponding headers. + * * @category combinators + * @since 4.0.0 */ export const setBody: { /** - * @since 4.0.0 + * Replaces the body of an `HttpServerResponse`. + * + * **Details** + * + * When the body carries a content type or content length, the returned response + * includes the corresponding headers. + * * @category combinators + * @since 4.0.0 */ (body: Body.HttpBody): (self: HttpServerResponse) => HttpServerResponse /** - * @since 4.0.0 + * Replaces the body of an `HttpServerResponse`. + * + * **Details** + * + * When the body carries a content type or content length, the returned response + * includes the corresponding headers. + * * @category combinators + * @since 4.0.0 */ (self: HttpServerResponse, body: Body.HttpBody): HttpServerResponse } = dual( @@ -811,18 +1178,36 @@ export const setBody: { ) /** - * @since 4.0.0 + * Sets the HTTP status code of an `HttpServerResponse`. + * + * **Details** + * + * When `statusText` is omitted, the existing status text is preserved. + * * @category combinators + * @since 4.0.0 */ export const setStatus: { /** - * @since 4.0.0 + * Sets the HTTP status code of an `HttpServerResponse`. + * + * **Details** + * + * When `statusText` is omitted, the existing status text is preserved. + * * @category combinators + * @since 4.0.0 */ (status: number, statusText?: string | undefined): (self: HttpServerResponse) => HttpServerResponse /** - * @since 4.0.0 + * Sets the HTTP status code of an `HttpServerResponse`. + * + * **Details** + * + * When `statusText` is omitted, the existing status text is preserved. + * * @category combinators + * @since 4.0.0 */ (self: HttpServerResponse, status: number, statusText?: string | undefined): HttpServerResponse } = dual( @@ -840,8 +1225,16 @@ export const setStatus: { ) /** + * Converts an `HttpServerResponse` to a Web `Response`. + * + * **Details** + * + * Cookies are appended as `Set-Cookie` headers. Stream bodies are converted using + * the supplied context, and `withoutBody` can be used for responses such as HEAD + * responses. + * + * @category converting * @since 4.0.0 - * @category conversions */ export const toWeb = ( response: HttpServerResponse, @@ -911,8 +1304,15 @@ export const toWeb = ( } /** + * Wraps an `HttpServerResponse` as an `HttpClientResponse`. + * + * **Details** + * + * An optional request can be supplied for client-response metadata and decode + * errors. + * + * @category converting * @since 4.0.0 - * @category conversions */ export const toClientResponse = ( response: HttpServerResponse, @@ -1125,8 +1525,15 @@ class ServerHttpClientResponse extends Inspectable.Class implements HttpClientRe const textDecoder = new TextDecoder() /** + * Converts an `HttpClientResponse` to an `HttpServerResponse`. + * + * **Details** + * + * The response body is streamed from the client response. `Set-Cookie` headers are + * removed from the header map and represented in the response cookie collection. + * + * @category converting * @since 4.0.0 - * @category conversions */ export const fromClientResponse = ( response: HttpClientResponse.HttpClientResponse @@ -1211,8 +1618,15 @@ const makeResponse = (options: { } /** + * Converts a Web `Response` to an `HttpServerResponse`. + * + * **Details** + * + * `Set-Cookie` headers are parsed into the response cookie collection and removed + * from the header map. A present Web body is exposed as a stream body. + * + * @category converting * @since 4.0.0 - * @category conversions */ export const fromWeb = (response: Response): HttpServerResponse => { const headers = new globalThis.Headers(response.headers) diff --git a/.opencode/node_modules/effect/src/unstable/http/HttpStaticServer.ts b/.opencode/node_modules/effect/src/unstable/http/HttpStaticServer.ts index 33cef989016b4ff234e702a42f854a9585ff77c8..a36d39c75aa4cba4490c9d3641efe020162849ab 100644 --- a/.opencode/node_modules/effect/src/unstable/http/HttpStaticServer.ts +++ b/.opencode/node_modules/effect/src/unstable/http/HttpStaticServer.ts @@ -1,4 +1,12 @@ /** + * Serves static files for Effect HTTP applications. + * + * `HttpStaticServer` turns request paths into file responses under a configured + * root directory. It can be used as an application value or mounted onto an + * `HttpRouter`, and it handles index files, optional single-page application + * fallback, MIME type headers, cache-control headers, byte ranges, and + * conditional `304 Not Modified` responses. + * * @since 4.0.0 */ import * as Effect from "../../Effect.ts" @@ -16,10 +24,11 @@ import * as HttpServerResponse from "./HttpServerResponse.ts" /** * Creates an `HttpApp` that serves files from a directory. * - * @example + * **Example** (Serving files from a directory) + * * ```ts * import { Effect } from "effect" - * import * as HttpStaticServer from "effect/unstable/http/HttpStaticServer" + * import { HttpStaticServer } from "effect/unstable/http" * * const program = Effect.gen(function*() { * const app = yield* HttpStaticServer.make({ root: "./public" }) @@ -27,8 +36,8 @@ import * as HttpServerResponse from "./HttpServerResponse.ts" * }) * ``` * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const make: (options: { readonly root: string @@ -168,12 +177,11 @@ export const make: (options: { /** * Creates a layer that mounts static files on an `HttpRouter`. * - * @example + * **Example** (Mounting static files on a router) + * * ```ts * import { Layer } from "effect" - * import * as HttpRouter from "effect/unstable/http/HttpRouter" - * import * as HttpServerResponse from "effect/unstable/http/HttpServerResponse" - * import * as HttpStaticServer from "effect/unstable/http/HttpStaticServer" + * import { HttpRouter, HttpServerResponse, HttpStaticServer } from "effect/unstable/http" * * const ApiLayer = HttpRouter.add("GET", "/health", HttpServerResponse.text("ok")) * @@ -185,8 +193,8 @@ export const make: (options: { * const AppLayer = Layer.mergeAll(ApiLayer, StaticFilesLayer) * ``` * - * @since 4.0.0 * @category layers + * @since 4.0.0 */ export const layer = (options: { readonly root: string diff --git a/.opencode/node_modules/effect/src/unstable/http/HttpTraceContext.ts b/.opencode/node_modules/effect/src/unstable/http/HttpTraceContext.ts index d19fda1dd3dc8ec0371dd8c07c343679d4784031..82e1c3f5a3457b85363bb071cbf0a184617badce 100644 --- a/.opencode/node_modules/effect/src/unstable/http/HttpTraceContext.ts +++ b/.opencode/node_modules/effect/src/unstable/http/HttpTraceContext.ts @@ -1,4 +1,11 @@ /** + * HTTP propagation helpers for Effect tracing context. + * + * This module converts Effect `Tracer.Span` values into outbound trace headers + * and decodes inbound propagation headers into `Tracer.ExternalSpan` parents. + * HTTP clients use it to continue the current span across outgoing requests, and + * server middleware uses it to parent request spans from upstream services. + * * @since 4.0.0 */ import * as Option from "../../Option.ts" @@ -6,16 +13,30 @@ import * as Tracer from "../../Tracer.ts" import * as Headers from "./Headers.ts" /** - * @since 4.0.0 + * Function type for decoding tracing headers into an external span. + * + * **Details** + * + * Returns `Option.none` when the headers do not contain a supported or valid trace + * context. + * * @category models + * @since 4.0.0 */ export interface FromHeaders { (headers: Headers.Headers): Option.Option } /** - * @since 4.0.0 + * Encodes a span into HTTP trace propagation headers. + * + * **Details** + * + * The generated headers include both compact B3 (`b3`) and W3C `traceparent` + * formats. + * * @category encoding + * @since 4.0.0 */ export const toHeaders = (span: Tracer.Span): Headers.Headers => Headers.fromRecordUnsafe({ @@ -29,8 +50,15 @@ export const toHeaders = (span: Tracer.Span): Headers.Headers => }) /** - * @since 4.0.0 + * Decodes an external span safely from HTTP trace propagation headers. + * + * **Details** + * + * W3C `traceparent` is tried first, followed by compact B3 (`b3`) and then + * multi-header B3 (`x-b3-*`). + * * @category decoding + * @since 4.0.0 */ export const fromHeaders = (headers: Headers.Headers): Option.Option => { let span = w3c(headers) @@ -45,8 +73,15 @@ export const fromHeaders = (headers: Headers.Headers): Option.Option { if (!("b3" in headers)) { @@ -64,8 +99,15 @@ export const b3: FromHeaders = (headers) => { } /** - * @since 4.0.0 + * Decodes an external span safely from multi-header B3 propagation headers. + * + * **Details** + * + * The decoder reads `x-b3-traceid`, `x-b3-spanid`, and optional `x-b3-sampled` + * headers. + * * @category decoding + * @since 4.0.0 */ export const xb3: FromHeaders = (headers) => { if (!(headers["x-b3-traceid"]) || !(headers["x-b3-spanid"])) { @@ -82,8 +124,14 @@ const w3cTraceId = /^[0-9a-f]{32}$/i const w3cSpanId = /^[0-9a-f]{16}$/i /** - * @since 4.0.0 + * Decodes an external span safely from the W3C `traceparent` header. + * + * **Details** + * + * Only version `00` headers with valid trace and span identifiers are accepted. + * * @category decoding + * @since 4.0.0 */ export const w3c: FromHeaders = (headers) => { if (!(headers["traceparent"])) { diff --git a/.opencode/node_modules/effect/src/unstable/http/Multipart.ts b/.opencode/node_modules/effect/src/unstable/http/Multipart.ts index 2ffb22f5ba0b77a57c5575255169e1e36cf00afc..5d87fe6663974f04b6383be4bce4ac27d4b78f6e 100644 --- a/.opencode/node_modules/effect/src/unstable/http/Multipart.ts +++ b/.opencode/node_modules/effect/src/unstable/http/Multipart.ts @@ -1,4 +1,13 @@ /** + * Parses and persists HTTP `multipart/form-data` request bodies. + * + * `Multipart` turns incoming byte streams into typed form parts. Text parts + * become decoded fields, while upload parts stay as streamed files until they + * are collected or written to scoped temporary files. The persisted + * representation can then be decoded with schemas for handlers that receive + * fields and uploaded files together. This module also includes multipart error + * types, schema helpers for persisted files, and parser limit settings. + * * @since 4.0.0 */ import * as Arr from "../../Array.ts" @@ -17,7 +26,7 @@ import * as Predicate from "../../Predicate.ts" import * as Pull from "../../Pull.ts" import * as Schema from "../../Schema.ts" import type { ParseOptions } from "../../SchemaAST.ts" -import * as Transformation from "../../SchemaTransformation.ts" +import * as SchemaTransformation from "../../SchemaTransformation.ts" import type * as Scope from "../../Scope.ts" import * as Stream from "../../Stream.ts" import * as UndefinedOr from "../../UndefinedOr.ts" @@ -25,23 +34,41 @@ import * as IncomingMessage from "./HttpIncomingMessage.ts" import * as MP from "./Multipasta.ts" /** + * Type identifier used to brand multipart part values. + * + * @category type IDs * @since 4.0.0 */ export const TypeId = "~effect/http/Multipart" /** - * @since 4.0.0 + * A parsed multipart part. + * + * **Details** + * + * A part is either a text `Field` or a streamed `File`. + * * @category models + * @since 4.0.0 */ export type Part = Field | File /** + * Namespace containing shared multipart part model types. + * * @since 4.0.0 */ export declare namespace Part { /** - * @since 4.0.0 + * Common protocol implemented by multipart part values. + * + * **Details** + * + * It provides the multipart type identifier, tag, and inspectable behavior shared + * by fields, files, and persisted files. + * * @category models + * @since 4.0.0 */ export interface Proto extends Inspectable.Inspectable { readonly [TypeId]: typeof TypeId @@ -50,8 +77,15 @@ export declare namespace Part { } /** - * @since 4.0.0 + * Multipart form field containing a decoded text value. + * + * **Details** + * + * The `key` is the field name, `contentType` is the part media type, and `value` + * is the decoded field content. + * * @category models + * @since 4.0.0 */ export interface Field extends Part.Proto { readonly _tag: "Field" @@ -61,20 +95,31 @@ export interface Field extends Part.Proto { } /** + * Returns `true` when a value is a multipart `Part`. + * + * @category guards * @since 4.0.0 - * @category Guards */ export const isPart = (u: unknown): u is Part => Predicate.hasProperty(u, TypeId) /** + * Returns `true` when a value is a multipart text `Field`. + * + * @category guards * @since 4.0.0 - * @category Guards */ export const isField = (u: unknown): u is Field => isPart(u) && u._tag === "Field" /** - * @since 4.0.0 + * Multipart file part. + * + * **Gotchas** + * + * The file content is exposed as a byte stream. `contentEffect` collects the full + * file into memory and should be used only when the file size is acceptable. + * * @category models + * @since 4.0.0 */ export interface File extends Part.Proto { readonly _tag: "File" @@ -86,14 +131,23 @@ export interface File extends Part.Proto { } /** + * Returns `true` when a value is a multipart `File`. + * + * @category guards * @since 4.0.0 - * @category Guards */ export const isFile = (u: unknown): u is File => isPart(u) && u._tag === "File" /** - * @since 4.0.0 + * Multipart file part that has been written to the filesystem. + * + * **Details** + * + * The `path` points to the persisted file while the scope used to persist the + * multipart data remains open. + * * @category models + * @since 4.0.0 */ export interface PersistedFile extends Part.Proto { readonly _tag: "PersistedFile" @@ -104,15 +158,24 @@ export interface PersistedFile extends Part.Proto { } /** + * Returns `true` when a value is a persisted multipart file. + * + * @category guards * @since 4.0.0 - * @category Guards */ export const isPersistedFile = (u: unknown): u is PersistedFile => Predicate.hasProperty(u, TypeId) && Predicate.isTagged(u, "PersistedFile") /** - * @since 4.0.0 + * Record representation of persisted multipart data. + * + * **Details** + * + * Field names map to text values, arrays of text values, or arrays of + * `PersistedFile` values. + * * @category models + * @since 4.0.0 */ export interface Persisted { readonly [key: string]: ReadonlyArray | ReadonlyArray | string @@ -121,8 +184,15 @@ export interface Persisted { const MultipartErrorTypeId = "~effect/http/Multipart/MultipartError" /** + * Error reason carried by a `MultipartError`. + * + * **Details** + * + * It identifies parser and limit failures such as oversized files or fields, too + * many parts, total body size limits, parse errors, and internal errors. + * + * @category errors * @since 4.0.0 - * @category Errors */ export class MultipartErrorReason extends Data.Error<{ readonly _tag: "FileTooLarge" | "FieldTooLarge" | "BodyTooLarge" | "TooManyParts" | "InternalError" | "Parse" @@ -130,13 +200,21 @@ export class MultipartErrorReason extends Data.Error<{ }> {} /** + * Error raised while parsing, streaming, or persisting multipart form data. + * + * **Details** + * + * The `reason` field contains the concrete `MultipartErrorReason`. + * + * @category errors * @since 4.0.0 - * @category Errors */ export class MultipartError extends Data.TaggedError("MultipartError")<{ readonly reason: MultipartErrorReason }> { /** + * Creates a multipart error from a reason tag and optional cause. + * * @since 4.0.0 */ static fromReason(reason: MultipartErrorReason["_tag"], cause?: unknown): MultipartError { @@ -144,11 +222,15 @@ export class MultipartError extends Data.TaggedError("MultipartError")<{ } /** + * Marks this value as a multipart error for runtime guards. + * * @since 4.0.0 */ readonly [MultipartErrorTypeId] = MultipartErrorTypeId /** + * Uses the concrete multipart error reason as the public message. + * * @since 4.0.0 */ override get message(): string { @@ -157,14 +239,23 @@ export class MultipartError extends Data.TaggedError("MultipartError")<{ } /** + * Schema type for persisted multipart files. + * + * @category schemas * @since 4.0.0 - * @category Schemas */ export interface PersistedFileSchema extends Schema.declare {} /** + * Schema for persisted multipart files. + * + * **Details** + * + * The encoded form contains the field key, original file name, content type, and + * filesystem path. + * + * @category schemas * @since 4.0.0 - * @category Schemas */ export const PersistedFileSchema: PersistedFileSchema = Schema.declare( isPersistedFile, @@ -186,7 +277,7 @@ export const PersistedFileSchema: PersistedFileSchema = Schema.declare( contentType: Schema.String.annotate({ contentEncoding: "binary" }), path: Schema.String }), - Transformation.transform({ + SchemaTransformation.transform({ decode: ({ contentType, key, name, path }) => new PersistedFileImpl(key, name, contentType, path), encode: (file) => ({ key: file.key, @@ -200,14 +291,23 @@ export const PersistedFileSchema: PersistedFileSchema = Schema.declare( ) /** + * Schema for an array of persisted multipart files. + * + * @category schemas * @since 4.0.0 - * @category Schemas */ export const FilesSchema: Schema.$Array = Schema.Array(PersistedFileSchema) /** + * Schema for exactly one persisted multipart file. + * + * **Details** + * + * The encoded form is a one-element file array, while the decoded value is the + * single `PersistedFile`. + * + * @category schemas * @since 4.0.0 - * @category Schemas */ export const SingleFileSchema: Schema.decodeTo> = FilesSchema .check( @@ -215,7 +315,7 @@ export const SingleFileSchema: Schema.decodeTo file, encode: (file) => [file] }) @@ -223,8 +323,15 @@ export const SingleFileSchema: Schema.decodeTo, RD, RE>( schema: Schema.Codec @@ -232,8 +339,15 @@ export const schemaPersisted = , RD, RE>( Schema.decodeUnknownEffect(schema) /** + * Creates a decoder for a JSON-encoded field in persisted multipart data. + * + * **Details** + * + * The selected field is parsed from a JSON string and decoded with the supplied + * schema. + * + * @category schemas * @since 4.0.0 - * @category Schemas */ export const schemaJson = (schema: Schema.Codec, options?: ParseOptions | undefined): { ( @@ -253,8 +367,16 @@ export const schemaJson = (schema: Schema.Codec, opt } /** + * Builds the low-level multipart parser configuration from request headers and + * the current fiber context. + * + * **Details** + * + * Parser limits are read from the multipart references, including maximum parts, + * field size, file size, total body size, and field MIME type overrides. + * + * @category configuration * @since 4.0.0 - * @category Config */ export const makeConfig = ( headers: Record @@ -275,8 +397,16 @@ export const makeConfig = ( }) /** - * @since 4.0.0 + * Creates a channel that parses multipart byte chunks into multipart parts. + * + * **Details** + * + * The channel consumes non-empty batches of `Uint8Array` chunks and emits + * non-empty batches of parsed `Part` values, failing with `MultipartError` for + * parser and limit failures. + * * @category Parsers + * @since 4.0.0 */ export const makeChannel = (headers: Record): Channel.Channel< Arr.NonEmptyReadonlyArray, @@ -455,7 +585,7 @@ class FileImpl extends PartBase implements File { const defaultWriteFile = (path: string, file: File) => Effect.flatMap( - FileSystem.FileSystem.asEffect(), + FileSystem.FileSystem, (fs) => Effect.mapError( Stream.run(file.content, fs.sink(path)), @@ -464,6 +594,14 @@ const defaultWriteFile = (path: string, file: File) => ) /** + * Runs a channel of byte chunks and collects all output into a single + * `Uint8Array`. + * + * **Gotchas** + * + * This materializes the full content in memory. + * + * @category converting * @since 4.0.0 */ export const collectUint8Array = ( @@ -482,8 +620,19 @@ export const collectUint8Array = ( }) /** + * Persists a stream of multipart parts into a record. + * + * **Details** + * + * Text fields are collected as strings, and file parts are written to files in a + * scoped temporary directory. + * + * **Gotchas** + * + * Persisted file paths remain valid for the lifetime of the scope. + * + * @category converting * @since 4.0.0 - * @category Conversions */ export const toPersisted = ( stream: Stream.Stream, @@ -560,8 +709,15 @@ class PersistedFileImpl extends PartBase implements PersistedFile { } /** + * Creates a context containing multipart parser limit settings. + * + * **Details** + * + * The context can provide maximum part count, field size, file size, total body + * size, and MIME types that should be parsed as fields. + * + * @category references * @since 4.0.0 - * @category References */ export const limitsServices = (options: { readonly maxParts?: number | undefined @@ -590,13 +746,21 @@ export const limitsServices = (options: { } /** + * Namespace containing multipart parser limit option types. + * * @since 4.0.0 - * @category fiber refs */ export declare namespace withLimits { /** - * @since 4.0.0 + * Options for overriding multipart parser limits. + * + * **Details** + * + * These settings control maximum part count, field size, file size, total body + * size, and MIME types that should be treated as fields instead of files. + * * @category fiber refs + * @since 4.0.0 */ export type Options = { readonly maxParts?: number | undefined @@ -608,24 +772,42 @@ export declare namespace withLimits { } /** + * Context reference for the maximum number of multipart parts allowed. + * + * **Details** + * + * The default is `undefined`, meaning no explicit part-count limit. + * + * @category references * @since 4.0.0 - * @category References */ export const MaxParts = Context.Reference("effect/http/Multipart/MaxParts", { defaultValue: () => undefined }) /** + * Context reference for the maximum size of a multipart field value. + * + * **Details** + * + * The default limit is 10 MiB. + * + * @category references * @since 4.0.0 - * @category References */ export const MaxFieldSize = Context.Reference("effect/http/Multipart/MaxFieldSize", { defaultValue: constant(FileSystem.Size(10 * 1024 * 1024)) }) /** + * Context reference for the maximum size of a multipart file part. + * + * **Details** + * + * The default is `undefined`, meaning no explicit per-file limit. + * + * @category references * @since 4.0.0 - * @category References */ export const MaxFileSize = Context.Reference( "effect/http/Multipart/MaxFileSize", @@ -633,8 +815,15 @@ export const MaxFileSize = Context.Reference( ) /** + * Context reference for MIME type fragments that should be parsed as multipart + * fields instead of files. + * + * **Details** + * + * The default treats `application/json` parts as fields. + * + * @category references * @since 4.0.0 - * @category References */ export const FieldMimeTypes = Context.Reference>("effect/http/Multipart/FieldMimeTypes", { defaultValue: constant(["application/json"]) diff --git a/.opencode/node_modules/effect/src/unstable/http/Multipasta.ts b/.opencode/node_modules/effect/src/unstable/http/Multipasta.ts index 312773ad11a3cb37f8b81f6a07c22abf4aacff3a..53d5ff8b2589e3f11ad8daab780fedf007e58d10 100644 --- a/.opencode/node_modules/effect/src/unstable/http/Multipasta.ts +++ b/.opencode/node_modules/effect/src/unstable/http/Multipasta.ts @@ -1,9 +1,15 @@ /** + * Re-exports the `multipasta` multipart parser used by the unstable HTTP + * modules. + * + * This module keeps the parser types and helpers available from the Effect HTTP + * namespace without wrapping or changing them. + * * @since 4.0.0 */ /** - * @since 4.0.0 * @category re-exports + * @since 4.0.0 */ export * from "multipasta" diff --git a/.opencode/node_modules/effect/src/unstable/http/Multipasta/HeadersParser.ts b/.opencode/node_modules/effect/src/unstable/http/Multipasta/HeadersParser.ts index 69d6983d6dec723d68e9211b941c2212d156d7f8..094cae5f5a6fe6cd42126290455c86dcad24a29c 100644 --- a/.opencode/node_modules/effect/src/unstable/http/Multipasta/HeadersParser.ts +++ b/.opencode/node_modules/effect/src/unstable/http/Multipasta/HeadersParser.ts @@ -1,9 +1,14 @@ /** + * Re-exports the `multipasta` header parser used by multipart HTTP parsing. + * + * This module keeps the parser available from the Effect HTTP namespace without + * wrapping or changing it. + * * @since 4.0.0 */ /** - * @since 4.0.0 * @category re-exports + * @since 4.0.0 */ export * from "multipasta/HeadersParser" diff --git a/.opencode/node_modules/effect/src/unstable/http/Multipasta/Node.ts b/.opencode/node_modules/effect/src/unstable/http/Multipasta/Node.ts index 63805b42e606cce82a9046f63253c03517f050ae..effc1f465b71641fa985479e77f678ba493b44fa 100644 --- a/.opencode/node_modules/effect/src/unstable/http/Multipasta/Node.ts +++ b/.opencode/node_modules/effect/src/unstable/http/Multipasta/Node.ts @@ -1,9 +1,14 @@ /** + * Re-exports the Node.js multipart helpers from `multipasta`. + * + * This module keeps the Node-specific parser helpers available from the Effect + * HTTP namespace without wrapping or changing them. + * * @since 4.0.0 */ /** - * @since 4.0.0 * @category re-exports + * @since 4.0.0 */ export * from "multipasta/node" diff --git a/.opencode/node_modules/effect/src/unstable/http/Multipasta/Search.ts b/.opencode/node_modules/effect/src/unstable/http/Multipasta/Search.ts index 9ca59b98b8f2ec40aec7da0862d0ae5fbca13e40..4a1c3013a4b4e8db1fb20761f38c0fdab41516b7 100644 --- a/.opencode/node_modules/effect/src/unstable/http/Multipasta/Search.ts +++ b/.opencode/node_modules/effect/src/unstable/http/Multipasta/Search.ts @@ -1,9 +1,14 @@ /** + * Re-exports the multipart search helpers from `multipasta`. + * + * This module keeps the search helpers available from the Effect HTTP namespace + * without wrapping or changing them. + * * @since 4.0.0 */ /** - * @since 4.0.0 * @category re-exports + * @since 4.0.0 */ export * from "multipasta/Search" diff --git a/.opencode/node_modules/effect/src/unstable/http/Multipasta/Web.ts b/.opencode/node_modules/effect/src/unstable/http/Multipasta/Web.ts index 0c31c1b5cd08944fc9e880f1ae16e2ee1d238d41..30e60a5afb07630b1683949ff2d641bfe6b1374c 100644 --- a/.opencode/node_modules/effect/src/unstable/http/Multipasta/Web.ts +++ b/.opencode/node_modules/effect/src/unstable/http/Multipasta/Web.ts @@ -1,9 +1,14 @@ /** + * Re-exports the Web multipart helpers from `multipasta`. + * + * This module keeps the Web-specific parser helpers available from the Effect + * HTTP namespace without wrapping or changing them. + * * @since 4.0.0 */ /** - * @since 4.0.0 * @category re-exports + * @since 4.0.0 */ export * from "multipasta/web" diff --git a/.opencode/node_modules/effect/src/unstable/http/Template.ts b/.opencode/node_modules/effect/src/unstable/http/Template.ts index a589a10b940d144917170484785443bdafdabab1..38d3f95e9a98be9ae68316bce3123ce97e448089 100644 --- a/.opencode/node_modules/effect/src/unstable/http/Template.ts +++ b/.opencode/node_modules/effect/src/unstable/http/Template.ts @@ -1,4 +1,11 @@ /** + * Builds HTTP response text from template literals. + * + * Template interpolations can be plain values, optional values, effects, or + * streams. The resulting effect or stream keeps the errors and service + * requirements from any effectful interpolations, which lets response helpers + * assemble dynamic text without losing type information. + * * @since 4.0.0 */ import * as Effect from "../../Effect.ts" @@ -7,18 +14,34 @@ import * as Option from "../../Option.ts" import * as Stream from "../../Stream.ts" /** + * Primitive value that can be interpolated into an HTTP template. + * * @category models * @since 4.0.0 */ export type PrimitiveValue = string | number | bigint | boolean | null | undefined /** + * Primitive template interpolation value. + * + * **Details** + * + * Arrays are rendered by converting each element to a string and concatenating the + * results. + * * @category models * @since 4.0.0 */ export type Primitive = PrimitiveValue | ReadonlyArray /** + * Value accepted by the string template constructor. + * + * **Details** + * + * Interpolations can be primitive values, optional primitive values, or effects + * that produce primitive values. + * * @category models * @since 4.0.0 */ @@ -28,17 +51,31 @@ export type Interpolated = | Effect.Effect /** + * Value accepted by the streaming template constructor. + * + * **Details** + * + * In addition to normal interpolations, stream interpolations can emit primitive + * values over time. + * * @category models * @since 4.0.0 */ export type InterpolatedWithStream = Interpolated | Stream.Stream /** - * @category models + * Namespace containing type-level helpers for template interpolations. + * * @since 4.0.0 */ export declare namespace Interpolated { /** + * Extracts the required context from an effect or stream interpolation. + * + * **Details** + * + * Plain values and `Option` interpolations contribute no context. + * * @category models * @since 4.0.0 */ @@ -49,6 +86,12 @@ export declare namespace Interpolated { : never /** + * Extracts the error type from an effect or stream interpolation. + * + * **Details** + * + * Plain values and `Option` interpolations contribute no error type. + * * @category models * @since 4.0.0 */ @@ -60,6 +103,13 @@ export declare namespace Interpolated { } /** + * Creates an effectful string from a template literal. + * + * **Details** + * + * Primitive and `Option` interpolations are rendered immediately. Effect + * interpolations are evaluated and rendered before the final string is produced. + * * @category constructors * @since 4.0.0 */ @@ -113,6 +163,14 @@ export function make>( } /** + * Creates a stream of strings from a template literal. + * + * **Details** + * + * Static text is emitted with interpolated values. Effect interpolations are + * evaluated as stream chunks, and stream interpolations are flattened into the + * output. + * * @category constructors * @since 4.0.0 */ diff --git a/.opencode/node_modules/effect/src/unstable/http/Url.ts b/.opencode/node_modules/effect/src/unstable/http/Url.ts index 2ee35be967b1dc4e43029aa1d2f7727cfd04be02..373ec82b4d60038e85a50b8640bd0207214bddba 100644 --- a/.opencode/node_modules/effect/src/unstable/http/Url.ts +++ b/.opencode/node_modules/effect/src/unstable/http/Url.ts @@ -1,4 +1,11 @@ /** + * Parses and edits platform `URL` values. + * + * The HTTP modules use the standard `URL` object as their URL representation. + * This module adds safe parsing and helpers that return updated copies when + * changing credentials, host, path, protocol, query, or hash parts. Query + * strings can also be read or updated through `UrlParams`. + * * @since 4.0.0 */ import * as Cause from "../../Cause.ts" @@ -8,7 +15,7 @@ import * as Result from "../../Result.ts" import * as UrlParams from "./UrlParams.ts" /** - * Parses a URL string into a `URL` object, returning an `Result` type for safe + * Parses a URL string safely into a `URL` object, returning a `Result` type for * error handling. * * **Details** @@ -24,11 +31,11 @@ import * as UrlParams from "./UrlParams.ts" * `base`. This is especially useful when dealing with URLs that might not be * fully qualified. * - * **Example** + * **Example** (Parsing absolute and relative URLs) * * ```ts - * import { Url } from "effect/unstable/http" * import { Result } from "effect" + * import { Url } from "effect/unstable/http" * * // Parse an absolute URL * // @@ -54,12 +61,12 @@ import * as UrlParams from "./UrlParams.ts" * // Output: Parsed relative URL: https://example.com/relative-path * ``` * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const fromString: { /** - * Parses a URL string into a `URL` object, returning an `Result` type for safe + * Parses a URL string safely into a `URL` object, returning a `Result` type for * error handling. * * **Details** @@ -75,11 +82,11 @@ export const fromString: { * `base`. This is especially useful when dealing with URLs that might not be * fully qualified. * - * **Example** + * **Example** (Parsing absolute and relative URLs) * * ```ts - * import { Url } from "effect/unstable/http" * import { Result } from "effect" + * import { Url } from "effect/unstable/http" * * // Parse an absolute URL * // @@ -105,8 +112,8 @@ export const fromString: { * // Output: Parsed relative URL: https://example.com/relative-path * ``` * + * @category constructors * @since 4.0.0 - * @category Constructors */ (url: string, base?: string | URL | undefined): Result.Result } = (url, base) => @@ -117,10 +124,9 @@ export const fromString: { }) /** - * This function clones the original `URL` object and applies a callback to the - * clone, allowing multiple updates at once. + * Updates a cloned `URL` with a callback, allowing multiple changes at once. * - * **Example** + * **Example** (Mutating URL credentials) * * ```ts * import { Url } from "effect/unstable/http" @@ -136,15 +142,14 @@ export const fromString: { * // Output: Mutated: https://user:pass@example.com/ * ``` * + * @category modifiers * @since 4.0.0 - * @category Modifiers */ export const mutate: { /** - * This function clones the original `URL` object and applies a callback to the - * clone, allowing multiple updates at once. + * Updates a cloned `URL` with a callback, allowing multiple changes at once. * - * **Example** + * **Example** (Mutating URL credentials) * * ```ts * import { Url } from "effect/unstable/http" @@ -160,15 +165,14 @@ export const mutate: { * // Output: Mutated: https://user:pass@example.com/ * ``` * + * @category modifiers * @since 4.0.0 - * @category Modifiers */ (f: (url: URL) => void): (self: URL) => URL /** - * This function clones the original `URL` object and applies a callback to the - * clone, allowing multiple updates at once. + * Updates a cloned `URL` with a callback, allowing multiple changes at once. * - * **Example** + * **Example** (Mutating URL credentials) * * ```ts * import { Url } from "effect/unstable/http" @@ -184,8 +188,8 @@ export const mutate: { * // Output: Mutated: https://user:pass@example.com/ * ``` * + * @category modifiers * @since 4.0.0 - * @category Modifiers */ (self: URL, f: (url: URL) => void): URL } = dual(2, (self: URL, f: (url: URL) => void) => { @@ -207,22 +211,22 @@ const immutableURLSetter =

(property: P): { /** * Updates the hash fragment of the URL. * + * @category setters * @since 4.0.0 - * @category Setters */ export const setHash: { /** * Updates the hash fragment of the URL. * + * @category setters * @since 4.0.0 - * @category Setters */ (hash: string): (url: URL) => URL /** * Updates the hash fragment of the URL. * + * @category setters * @since 4.0.0 - * @category Setters */ (url: URL, hash: string): URL } = immutableURLSetter("hash") @@ -230,22 +234,22 @@ export const setHash: { /** * Updates the host (domain and port) of the URL. * + * @category setters * @since 4.0.0 - * @category Setters */ export const setHost: { /** * Updates the host (domain and port) of the URL. * + * @category setters * @since 4.0.0 - * @category Setters */ (host: string): (url: URL) => URL /** * Updates the host (domain and port) of the URL. * + * @category setters * @since 4.0.0 - * @category Setters */ (url: URL, host: string): URL } = immutableURLSetter("host") @@ -253,22 +257,22 @@ export const setHost: { /** * Updates the domain of the URL without modifying the port. * + * @category setters * @since 4.0.0 - * @category Setters */ export const setHostname: { /** * Updates the domain of the URL without modifying the port. * + * @category setters * @since 4.0.0 - * @category Setters */ (hostname: string): (url: URL) => URL /** * Updates the domain of the URL without modifying the port. * + * @category setters * @since 4.0.0 - * @category Setters */ (url: URL, hostname: string): URL } = immutableURLSetter("hostname") @@ -276,22 +280,22 @@ export const setHostname: { /** * Replaces the entire URL string. * + * @category setters * @since 4.0.0 - * @category Setters */ export const setHref: { /** * Replaces the entire URL string. * + * @category setters * @since 4.0.0 - * @category Setters */ (href: string): (url: URL) => URL /** * Replaces the entire URL string. * + * @category setters * @since 4.0.0 - * @category Setters */ (url: URL, href: string): URL } = immutableURLSetter("href") @@ -299,22 +303,22 @@ export const setHref: { /** * Updates the password used for authentication. * + * @category setters * @since 4.0.0 - * @category Setters */ export const setPassword: { /** * Updates the password used for authentication. * + * @category setters * @since 4.0.0 - * @category Setters */ (password: string | Redacted.Redacted): (url: URL) => URL /** * Updates the password used for authentication. * + * @category setters * @since 4.0.0 - * @category Setters */ (url: URL, password: string | Redacted.Redacted): URL } = dual(2, (url: URL, password: string | Redacted.Redacted) => @@ -327,22 +331,22 @@ export const setPassword: { /** * Updates the path of the URL. * + * @category setters * @since 4.0.0 - * @category Setters */ export const setPathname: { /** * Updates the path of the URL. * + * @category setters * @since 4.0.0 - * @category Setters */ (pathname: string): (url: URL) => URL /** * Updates the path of the URL. * + * @category setters * @since 4.0.0 - * @category Setters */ (url: URL, pathname: string): URL } = immutableURLSetter("pathname") @@ -350,22 +354,22 @@ export const setPathname: { /** * Updates the port of the URL. * + * @category setters * @since 4.0.0 - * @category Setters */ export const setPort: { /** * Updates the port of the URL. * + * @category setters * @since 4.0.0 - * @category Setters */ (port: string | number): (url: URL) => URL /** * Updates the port of the URL. * + * @category setters * @since 4.0.0 - * @category Setters */ (url: URL, port: string | number): URL } = immutableURLSetter("port") @@ -373,22 +377,22 @@ export const setPort: { /** * Updates the protocol (e.g., `http`, `https`). * + * @category setters * @since 4.0.0 - * @category Setters */ export const setProtocol: { /** * Updates the protocol (e.g., `http`, `https`). * + * @category setters * @since 4.0.0 - * @category Setters */ (protocol: string): (url: URL) => URL /** * Updates the protocol (e.g., `http`, `https`). * + * @category setters * @since 4.0.0 - * @category Setters */ (url: URL, protocol: string): URL } = immutableURLSetter("protocol") @@ -396,22 +400,22 @@ export const setProtocol: { /** * Updates the query string of the URL. * + * @category setters * @since 4.0.0 - * @category Setters */ export const setSearch: { /** * Updates the query string of the URL. * + * @category setters * @since 4.0.0 - * @category Setters */ (search: string): (url: URL) => URL /** * Updates the query string of the URL. * + * @category setters * @since 4.0.0 - * @category Setters */ (url: URL, search: string): URL } = immutableURLSetter("search") @@ -419,22 +423,22 @@ export const setSearch: { /** * Updates the username used for authentication. * + * @category setters * @since 4.0.0 - * @category Setters */ export const setUsername: { /** * Updates the username used for authentication. * + * @category setters * @since 4.0.0 - * @category Setters */ (username: string): (url: URL) => URL /** * Updates the username used for authentication. * + * @category setters * @since 4.0.0 - * @category Setters */ (url: URL, username: string): URL } = immutableURLSetter("username") @@ -448,7 +452,7 @@ export const setUsername: { * object using the provided `UrlParams`. It creates a new `URL` object with the * updated parameters, leaving the original object unchanged. * - * **Example** + * **Example** (Replacing query parameters) * * ```ts * import { Url, UrlParams } from "effect/unstable/http" @@ -465,8 +469,8 @@ export const setUsername: { * // Output: https://example.com/?key=value * ``` * + * @category setters * @since 4.0.0 - * @category Setters */ export const setUrlParams: { /** @@ -478,7 +482,7 @@ export const setUrlParams: { * object using the provided `UrlParams`. It creates a new `URL` object with the * updated parameters, leaving the original object unchanged. * - * **Example** + * **Example** (Replacing query parameters) * * ```ts * import { Url, UrlParams } from "effect/unstable/http" @@ -495,8 +499,8 @@ export const setUrlParams: { * // Output: https://example.com/?key=value * ``` * + * @category setters * @since 4.0.0 - * @category Setters */ (urlParams: UrlParams.UrlParams): (url: URL) => URL /** @@ -508,7 +512,7 @@ export const setUrlParams: { * object using the provided `UrlParams`. It creates a new `URL` object with the * updated parameters, leaving the original object unchanged. * - * **Example** + * **Example** (Replacing query parameters) * * ```ts * import { Url, UrlParams } from "effect/unstable/http" @@ -525,8 +529,8 @@ export const setUrlParams: { * // Output: https://example.com/?key=value * ``` * + * @category setters * @since 4.0.0 - * @category Setters */ (url: URL, urlParams: UrlParams.UrlParams): URL } = dual(2, (url: URL, searchParams: UrlParams.UrlParams) => @@ -543,7 +547,7 @@ export const setUrlParams: { * them as `UrlParams`. The resulting structure can be easily manipulated or * inspected. * - * **Example** + * **Example** (Reading query parameters) * * ```ts * import { Url } from "effect/unstable/http" @@ -557,13 +561,13 @@ export const setUrlParams: { * // Output: [ [ 'foo', 'bar' ] ] * ``` * + * @category getters * @since 4.0.0 - * @category Getters */ export const urlParams = (url: URL): UrlParams.UrlParams => UrlParams.fromInput(url.searchParams) /** - * Reads, modifies, and updates the query parameters of a URL. + * Reads the query parameters of a URL, modifies them, and updates the URL. * * **Details** * @@ -572,7 +576,7 @@ export const urlParams = (url: URL): UrlParams.UrlParams => UrlParams.fromInput( * writing the updated parameters back to the URL. It returns a new `URL` object * with the modified parameters, ensuring immutability. * - * **Example** + * **Example** (Modifying query parameters) * * ```ts * import { Url, UrlParams } from "effect/unstable/http" @@ -585,12 +589,12 @@ export const urlParams = (url: URL): UrlParams.UrlParams => UrlParams.fromInput( * // Output: https://example.com/?foo=bar&key=value * ``` * + * @category modifiers * @since 4.0.0 - * @category Modifiers */ export const modifyUrlParams: { /** - * Reads, modifies, and updates the query parameters of a URL. + * Reads the query parameters of a URL, modifies them, and updates the URL. * * **Details** * @@ -599,7 +603,7 @@ export const modifyUrlParams: { * writing the updated parameters back to the URL. It returns a new `URL` object * with the modified parameters, ensuring immutability. * - * **Example** + * **Example** (Modifying query parameters) * * ```ts * import { Url, UrlParams } from "effect/unstable/http" @@ -612,12 +616,12 @@ export const modifyUrlParams: { * // Output: https://example.com/?foo=bar&key=value * ``` * + * @category modifiers * @since 4.0.0 - * @category Modifiers */ (f: (urlParams: UrlParams.UrlParams) => UrlParams.UrlParams): (url: URL) => URL /** - * Reads, modifies, and updates the query parameters of a URL. + * Reads the query parameters of a URL, modifies them, and updates the URL. * * **Details** * @@ -626,7 +630,7 @@ export const modifyUrlParams: { * writing the updated parameters back to the URL. It returns a new `URL` object * with the modified parameters, ensuring immutability. * - * **Example** + * **Example** (Modifying query parameters) * * ```ts * import { Url, UrlParams } from "effect/unstable/http" @@ -639,8 +643,8 @@ export const modifyUrlParams: { * // Output: https://example.com/?foo=bar&key=value * ``` * + * @category modifiers * @since 4.0.0 - * @category Modifiers */ (url: URL, f: (urlParams: UrlParams.UrlParams) => UrlParams.UrlParams): URL } = dual(2, (url: URL, f: (urlParams: UrlParams.UrlParams) => UrlParams.UrlParams) => diff --git a/.opencode/node_modules/effect/src/unstable/http/UrlParams.ts b/.opencode/node_modules/effect/src/unstable/http/UrlParams.ts index 2921dc4e8c2e465ce9117a779524def9168abb11..a831b9f018394bd66a00feaa6189ebd04535a7db 100644 --- a/.opencode/node_modules/effect/src/unstable/http/UrlParams.ts +++ b/.opencode/node_modules/effect/src/unstable/http/UrlParams.ts @@ -1,4 +1,11 @@ /** + * Models URL query parameters as ordered string pairs. + * + * `UrlParams` is used for HTTP client query strings, URL-encoded form bodies, + * and server-side decoding. Values can be built from records, iterables, or + * native `URLSearchParams`, then updated, serialized, converted to a `URL`, or + * decoded with schemas. + * * @since 4.0.0 */ import * as Arr from "../../Array.ts" @@ -16,15 +23,22 @@ import { hasProperty } from "../../Predicate.ts" import type { ReadonlyRecord } from "../../Record.ts" import * as Result from "../../Result.ts" import * as Schema from "../../Schema.ts" -import * as Issue from "../../SchemaIssue.ts" -import * as Transformation from "../../SchemaTransformation.ts" +import * as SchemaIssue from "../../SchemaIssue.ts" +import * as SchemaTransformation from "../../SchemaTransformation.ts" import * as Tuple from "../../Tuple.ts" const TypeId = "~effect/http/UrlParams" /** - * @since 4.0.0 + * Immutable collection of URL query parameters. + * + * **Details** + * + * Parameters are stored as ordered string key-value pairs and can contain multiple + * values for the same key. + * * @category models + * @since 4.0.0 */ export interface UrlParams extends Pipeable, Inspectable, Iterable { readonly [TypeId]: typeof TypeId @@ -32,14 +46,23 @@ export interface UrlParams extends Pipeable, Inspectable, Iterable hasProperty(u, TypeId) /** - * @since 4.0.0 + * Input accepted when constructing `UrlParams`. + * + * **Details** + * + * Values can be provided as a coercible record, an iterable of key-value pairs, or + * a native `URLSearchParams` value. + * * @category models + * @since 4.0.0 */ export type Input = | CoercibleRecordInput @@ -51,14 +74,20 @@ type CoercibleRecordInput = CoercibleRecord & { } /** - * @since 4.0.0 + * Primitive value that can be converted into a URL parameter string. + * + * **Gotchas** + * + * `undefined` values are skipped when constructing from input. + * * @category models + * @since 4.0.0 */ export type Coercible = string | number | bigint | boolean | null | undefined /** - * @since 4.0.0 * @category models + * @since 4.0.0 */ type CoercibleRecordField = A extends Coercible ? A : A extends ReadonlyArray ? ReadonlyArray @@ -66,8 +95,15 @@ type CoercibleRecordField = A extends Coercible ? A : never /** - * @since 4.0.0 + * Record input whose fields can be coerced into URL parameter values. + * + * **Details** + * + * Nested records are rendered using bracket notation, and arrays produce repeated + * parameters. + * * @category models + * @since 4.0.0 */ export type CoercibleRecord = { readonly [K in keyof A]: CoercibleRecordField @@ -94,8 +130,14 @@ const Proto = { } /** - * @since 4.0.0 + * Creates `UrlParams` from ordered string key-value pairs. + * + * **Details** + * + * The input pairs are used as-is and are not coerced or normalized. + * * @category constructors + * @since 4.0.0 */ export const make = (params: ReadonlyArray): UrlParams => { const self = Object.create(Proto) @@ -104,8 +146,15 @@ export const make = (params: ReadonlyArray): UrlParam } /** - * @since 4.0.0 + * Creates `UrlParams` from a supported input shape. + * + * **Details** + * + * Primitive values are converted to strings, arrays produce repeated parameters, + * nested records use bracket notation, and `undefined` values are omitted. + * * @category constructors + * @since 4.0.0 */ export const fromInput = (input: Input): UrlParams => { const parsed = fromInputNested(input) @@ -146,8 +195,15 @@ const fromInputNested = (input: Input): Array<[string | Array, any]> => } /** + * Provides an order-sensitive `Equivalence` instance for `UrlParams`. + * + * **Details** + * + * Two values are equivalent when they contain the same key-value pairs in the same + * order. + * + * @category instances * @since 4.0.0 - * @category Equivalence */ export const Equivalence: Equ.Equivalence = Equ.make((a, b) => arrayEquivalence(a.params, b.params) @@ -158,14 +214,22 @@ const arrayEquivalence = Arr.makeEquivalence( ) /** - * @since 4.0.0 + * Schema type for `UrlParams`. + * * @category schemas + * @since 4.0.0 */ export interface UrlParamsSchema extends Schema.declare> {} /** - * @since 4.0.0 + * Schema for `UrlParams`. + * + * **Details** + * + * The encoded representation is an array of string key-value tuples. + * * @category schemas + * @since 4.0.0 */ export const UrlParamsSchema: UrlParamsSchema = Schema.declare( isUrlParams, @@ -184,7 +248,7 @@ export const UrlParamsSchema: UrlParamsSchema = Schema.declare( toCodec: () => Schema.link()( Schema.Array(Schema.Tuple([Schema.String, Schema.String])), - Transformation.transform({ + SchemaTransformation.transform({ decode: make, encode: (self) => self.params }) @@ -193,24 +257,44 @@ export const UrlParamsSchema: UrlParamsSchema = Schema.declare( ) /** - * @since 4.0.0 + * An empty `UrlParams` value. + * * @category constructors + * @since 4.0.0 */ export const empty: UrlParams = make([]) /** - * @since 4.0.0 + * Returns all values for a query parameter key in insertion order. + * + * **Details** + * + * Returns an empty array when the key is absent. + * * @category combinators + * @since 4.0.0 */ export const getAll: { /** - * @since 4.0.0 + * Returns all values for a query parameter key in insertion order. + * + * **Details** + * + * Returns an empty array when the key is absent. + * * @category combinators + * @since 4.0.0 */ (key: string): (self: UrlParams) => ReadonlyArray /** - * @since 4.0.0 + * Returns all values for a query parameter key in insertion order. + * + * **Details** + * + * Returns an empty array when the key is absent. + * * @category combinators + * @since 4.0.0 */ (self: UrlParams, key: string): ReadonlyArray } = dual( @@ -225,18 +309,51 @@ export const getAll: { ) /** - * @since 4.0.0 + * Returns the first value for a query parameter key safely. + * + * **When to use** + * + * Use when duplicate query parameters are ordered and the first occurrence has + * precedence. + * + * **Details** + * + * Returns `Option.none` when the key is absent. + * * @category combinators + * @since 4.0.0 */ export const getFirst: { /** - * @since 4.0.0 + * Returns the first value for a query parameter key safely. + * + * **When to use** + * + * Use when duplicate query parameters are ordered and the first occurrence has + * precedence. + * + * **Details** + * + * Returns `Option.none` when the key is absent. + * * @category combinators + * @since 4.0.0 */ (key: string): (self: UrlParams) => Option.Option /** - * @since 4.0.0 + * Returns the first value for a query parameter key safely. + * + * **When to use** + * + * Use when duplicate query parameters are ordered and the first occurrence has + * precedence. + * + * **Details** + * + * Returns `Option.none` when the key is absent. + * * @category combinators + * @since 4.0.0 */ (self: UrlParams, key: string): Option.Option } = dual( @@ -248,18 +365,51 @@ export const getFirst: { ) /** - * @since 4.0.0 + * Returns the last value for a query parameter key safely. + * + * **When to use** + * + * Use when duplicate query parameters are ordered and the last occurrence has + * precedence. + * + * **Details** + * + * Returns `Option.none` when the key is absent. + * * @category combinators + * @since 4.0.0 */ export const getLast: { /** - * @since 4.0.0 + * Returns the last value for a query parameter key safely. + * + * **When to use** + * + * Use when duplicate query parameters are ordered and the last occurrence has + * precedence. + * + * **Details** + * + * Returns `Option.none` when the key is absent. + * * @category combinators + * @since 4.0.0 */ (key: string): (self: UrlParams) => Option.Option /** - * @since 4.0.0 + * Returns the last value for a query parameter key safely. + * + * **When to use** + * + * Use when duplicate query parameters are ordered and the last occurrence has + * precedence. + * + * **Details** + * + * Returns `Option.none` when the key is absent. + * * @category combinators + * @since 4.0.0 */ (self: UrlParams, key: string): Option.Option } = dual(2, (self: UrlParams, key: string): Option.Option => @@ -268,18 +418,39 @@ export const getLast: { )) /** - * @since 4.0.0 + * Sets a query parameter to a single value. + * + * **Details** + * + * Existing values for the same key are removed, and the new value is appended to + * the end. + * * @category combinators + * @since 4.0.0 */ export const set: { /** - * @since 4.0.0 + * Sets a query parameter to a single value. + * + * **Details** + * + * Existing values for the same key are removed, and the new value is appended to + * the end. + * * @category combinators + * @since 4.0.0 */ (key: string, value: Coercible): (self: UrlParams) => UrlParams /** - * @since 4.0.0 + * Sets a query parameter to a single value. + * + * **Details** + * + * Existing values for the same key are removed, and the new value is appended to + * the end. + * * @category combinators + * @since 4.0.0 */ (self: UrlParams, key: string, value: Coercible): UrlParams } = dual(3, (self: UrlParams, key: string, value: Coercible): UrlParams => @@ -291,18 +462,36 @@ export const set: { )) /** - * @since 4.0.0 + * Transforms the underlying ordered key-value pairs of `UrlParams`. + * + * **Details** + * + * The result is wrapped in a new `UrlParams` value. + * * @category combinators + * @since 4.0.0 */ export const transform: { /** - * @since 4.0.0 + * Transforms the underlying ordered key-value pairs of `UrlParams`. + * + * **Details** + * + * The result is wrapped in a new `UrlParams` value. + * * @category combinators + * @since 4.0.0 */ (f: (params: UrlParams["params"]) => UrlParams["params"]): (self: UrlParams) => UrlParams /** - * @since 4.0.0 + * Transforms the underlying ordered key-value pairs of `UrlParams`. + * + * **Details** + * + * The result is wrapped in a new `UrlParams` value. + * * @category combinators + * @since 4.0.0 */ (self: UrlParams, f: (params: UrlParams["params"]) => UrlParams["params"]): UrlParams } = dual( @@ -311,18 +500,39 @@ export const transform: { ) /** - * @since 4.0.0 + * Sets multiple query parameters from input. + * + * **Details** + * + * Keys present in the input replace existing values for those keys, while + * unmentioned existing parameters are preserved. + * * @category combinators + * @since 4.0.0 */ export const setAll: { /** - * @since 4.0.0 + * Sets multiple query parameters from input. + * + * **Details** + * + * Keys present in the input replace existing values for those keys, while + * unmentioned existing parameters are preserved. + * * @category combinators + * @since 4.0.0 */ (input: Input): (self: UrlParams) => UrlParams /** - * @since 4.0.0 + * Sets multiple query parameters from input. + * + * **Details** + * + * Keys present in the input replace existing values for those keys, while + * unmentioned existing parameters are preserved. + * * @category combinators + * @since 4.0.0 */ (self: UrlParams, input: Input): UrlParams } = dual(2, (self: UrlParams, input: Input): UrlParams => { @@ -340,18 +550,24 @@ export const setAll: { }) /** - * @since 4.0.0 + * Appends a query parameter value without removing existing values for the key. + * * @category combinators + * @since 4.0.0 */ export const append: { /** - * @since 4.0.0 + * Appends a query parameter value without removing existing values for the key. + * * @category combinators + * @since 4.0.0 */ (key: string, value: Coercible): (self: UrlParams) => UrlParams /** - * @since 4.0.0 + * Appends a query parameter value without removing existing values for the key. + * * @category combinators + * @since 4.0.0 */ (self: UrlParams, key: string, value: Coercible): UrlParams } = dual(3, (self: UrlParams, key: string, value: Coercible): UrlParams => @@ -361,50 +577,83 @@ export const append: { ))) /** - * @since 4.0.0 + * Appends all query parameters produced from the supplied input. + * + * **Details** + * + * Existing parameters are preserved. + * * @category combinators + * @since 4.0.0 */ export const appendAll: { /** - * @since 4.0.0 + * Appends all query parameters produced from the supplied input. + * + * **Details** + * + * Existing parameters are preserved. + * * @category combinators + * @since 4.0.0 */ (input: Input): (self: UrlParams) => UrlParams /** - * @since 4.0.0 + * Appends all query parameters produced from the supplied input. + * + * **Details** + * + * Existing parameters are preserved. + * * @category combinators + * @since 4.0.0 */ (self: UrlParams, input: Input): UrlParams } = dual(2, (self: UrlParams, input: Input): UrlParams => transform(self, Arr.appendAll(fromInput(input).params))) /** - * @since 4.0.0 + * Removes all query parameter values for the specified key. + * * @category combinators + * @since 4.0.0 */ export const remove: { /** - * @since 4.0.0 + * Removes all query parameter values for the specified key. + * * @category combinators + * @since 4.0.0 */ (key: string): (self: UrlParams) => UrlParams /** - * @since 4.0.0 + * Removes all query parameter values for the specified key. + * * @category combinators + * @since 4.0.0 */ (self: UrlParams, key: string): UrlParams } = dual(2, (self: UrlParams, key: string): UrlParams => transform(self, Arr.filter(([k]) => k !== key))) /** + * Error returned when constructing a `URL` from `UrlParams` fails. + * + * @category errors * @since 4.0.0 - * @category Errors */ export class UrlParamsError extends Data.TaggedError("UrlParamsError")<{ cause: unknown }> {} /** + * Creates a `URL` safely by appending `UrlParams` and an optional hash to a URL string. + * + * **Details** + * + * Returns a `Result` that fails with `UrlParamsError` if the URL cannot be + * constructed. + * + * @category converting * @since 4.0.0 - * @category conversions */ export const makeUrl = ( url: string, @@ -429,8 +678,10 @@ export const makeUrl = ( } /** + * Serializes `UrlParams` to a URL query string without a leading question mark. + * + * @category converting * @since 4.0.0 - * @category conversions */ export const toString = (self: UrlParams): string => new URLSearchParams(self.params as any).toString() @@ -451,7 +702,7 @@ const baseUrl = (): string | undefined => { * as `string` (if only one value for a key) or a `NonEmptyArray` * (when more than one value for a key) * - * **Example** + * **Example** (Converting parameters to a record) * * ```ts * import { UrlParams } from "effect/unstable/http" @@ -471,8 +722,8 @@ const baseUrl = (): string | undefined => { * ) * ``` * + * @category converting * @since 4.0.0 - * @category conversions */ export const toRecord = (self: UrlParams): Record> => { const out: Record> = {} @@ -490,22 +741,33 @@ export const toRecord = (self: UrlParams): Record ReadonlyRecord> = toRecord as any /** + * Schema type for decoding one URL parameter field as JSON. + * + * @category schemas * @since 4.0.0 - * @category Schemas */ export interface schemaJsonField extends Schema.decodeTo {} /** - * Extract a JSON value from the first occurrence of the given `field` in the + * Extracts a JSON value from the first occurrence of the given `field` in the * `UrlParams`. * + * **Example** (Decoding JSON parameter fields) + * * ```ts * import { Schema } from "effect" * import { UrlParams } from "effect/unstable/http" @@ -525,17 +787,17 @@ export interface schemaJsonField extends Schema.decodeTo UrlParamsSchema.pipe( Schema.decodeTo( Schema.UnknownFromJsonString, - Transformation.transformOrFail({ + SchemaTransformation.transformOrFail({ decode: (params) => Option.match(getFirst(params, field), { - onNone: () => Effect.fail(new Issue.Pointer([field], new Issue.MissingKey(undefined))), + onNone: () => Effect.fail(new SchemaIssue.Pointer([field], new SchemaIssue.MissingKey(undefined))), onSome: Effect.succeed }), encode: (value) => Effect.succeed(make([[field, value]])) @@ -546,8 +808,8 @@ export const schemaJsonField = (field: string): schemaJsonField => /** * Extract a record of key-value pairs from the `UrlParams`. * + * @category schemas * @since 4.0.0 - * @category Schemas */ export interface schemaRecord extends Schema.decodeTo< @@ -559,9 +821,14 @@ export interface schemaRecord extends {} /** - * Extract schema from all key-value pairs in the given `UrlParams`. + * Schema that decodes `UrlParams` into a record of key-value pairs. + * + * **Details** * - * **Example** + * Keys with one value decode to a string, and keys with multiple values decode to + * a non-empty readonly array of strings. + * + * **Example** (Decoding URL parameters to a record) * * ```ts * import { Schema } from "effect" @@ -582,8 +849,8 @@ export interface schemaRecord extends * ) * ``` * + * @category schemas * @since 4.0.0 - * @category schema */ export const schemaRecord: schemaRecord = UrlParamsSchema.pipe( Schema.decodeTo( @@ -591,7 +858,7 @@ export const schemaRecord: schemaRecord = UrlParamsSchema.pipe( Schema.String, Schema.Union([Schema.String, Schema.NonEmptyArray(Schema.String)]) ), - Transformation.transform({ + SchemaTransformation.transform({ decode: toReadonlyRecord, encode: fromInput }) diff --git a/.opencode/node_modules/effect/src/unstable/httpapi/HttpApi.ts b/.opencode/node_modules/effect/src/unstable/httpapi/HttpApi.ts index 944be89b81947d23f43867903741870c0b37b7c4..4ded3973d55b91a4fbb7ab3fb8a6667b350f6cc2 100644 --- a/.opencode/node_modules/effect/src/unstable/httpapi/HttpApi.ts +++ b/.opencode/node_modules/effect/src/unstable/httpapi/HttpApi.ts @@ -1,4 +1,11 @@ /** + * Describes an Effect HTTP API as groups of endpoints. + * + * An `HttpApi` value is data: it has an identifier, annotations, and groups of + * endpoints that describe request inputs, responses, middleware, and route + * metadata. The same description can be used by server builders, generated + * clients, URL builders, OpenAPI generation, and reflection tools. + * * @since 4.0.0 */ import type { NonEmptyReadonlyArray } from "../../Array.ts" @@ -7,7 +14,7 @@ import { type Pipeable, pipeArguments } from "../../Pipeable.ts" import * as Predicate from "../../Predicate.ts" import * as Record from "../../Record.ts" import type * as Schema from "../../Schema.ts" -import type * as AST from "../../SchemaAST.ts" +import type * as SchemaAST from "../../SchemaAST.ts" import type { Mutable } from "../../Types.ts" import type { PathInput } from "../http/HttpRouter.ts" import * as HttpApiEndpoint from "./HttpApiEndpoint.ts" @@ -18,19 +25,24 @@ import * as HttpApiSchema from "./HttpApiSchema.ts" const TypeId = "~effect/httpapi/HttpApi" /** - * @since 4.0.0 + * Returns `true` when a value is an `HttpApi`. + * * @category guards + * @since 4.0.0 */ export const isHttpApi = (u: unknown): u is Any => Predicate.hasProperty(u, TypeId) /** - * An `HttpApi` is a collection of `HttpApiEndpoint`s. You can use an `HttpApi` to - * represent a portion of your domain. + * An `HttpApi` is a collection of HTTP API groups and endpoints that represents a + * portion of your domain. * - * The endpoints can be implemented later using the `HttpApiBuilder.make` api. + * **When to use** + * + * Use when endpoint implementations can be provided with `HttpApiBuilder.group`, and the + * completed API can be registered with `HttpApiBuilder.layer`. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface HttpApi< out Id extends string, @@ -45,7 +57,7 @@ export interface HttpApi< /** * Add a `HttpApiGroup` to the `HttpApi`. */ - add>(...groups: A): HttpApi + add>(...groups: A): HttpApi /** * Add another `HttpApi` to the `HttpApi`. @@ -60,11 +72,11 @@ export interface HttpApi< prefix(prefix: Prefix): HttpApi> /** - * Add a middleware to a `HttpApi`. It will be applied to all endpoints in the - * `HttpApi`. + * Adds a middleware to every endpoint currently in the `HttpApi`. + * + * **Gotchas** * - * Note that this will only add the middleware to the endpoints **before** this - * api is called. + * Endpoints added after this method is called do not receive the middleware. */ middleware( middleware: Context.Key @@ -82,16 +94,21 @@ export interface HttpApi< } /** - * @since 4.0.0 + * An `HttpApi` value with its identifier and group types erased. + * * @category models + * @since 4.0.0 */ export interface Any { readonly [TypeId]: typeof TypeId } /** - * @since 4.0.0 + * An `HttpApi` with broad identifier and group types while retaining the concrete + * runtime properties used by implementation helpers. + * * @category models + * @since 4.0.0 */ export type AnyWithProps = HttpApi @@ -175,14 +192,16 @@ const makeProto = ( } /** - * An `HttpApi` is a collection of `HttpApiEndpoint`s. You can use an `HttpApi` to - * represent a portion of your domain. + * Creates an empty `HttpApi` with the supplied identifier. * - * You can then use `HttpApiBuilder.layer(api)` to implement the endpoints of the - * `HttpApi`. + * **When to use** + * + * Use when you need to start defining an HTTP API, add groups with `add` or + * `addHttpApi`, provide endpoint implementations with `HttpApiBuilder.group`, + * and register the API with `HttpApiBuilder.layer`. * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const make = (identifier: Id): HttpApi => makeProto({ @@ -192,8 +211,15 @@ export const make = (identifier: Id): HttpApi( self: HttpApi, @@ -256,7 +282,7 @@ export const reflect = ( const extractResponseContent = ( schemas: Array, - getStatus: (ast: AST.AST) => number + getStatus: (ast: SchemaAST.AST) => number ): ReadonlyMap]> => { const map = new Map]>() @@ -265,6 +291,7 @@ const extractResponseContent = ( return map function add(schema: Schema.Top) { + if (HttpApiSchema.isStreamSchema(schema)) return const ast = schema.ast const status = getStatus(ast) const schemas = map.get(status) @@ -280,8 +307,8 @@ const extractResponseContent = ( * Adds additional schemas to components/schemas. * The provided schemas must have a `identifier` annotation. * + * @category services * @since 4.0.0 - * @category tags */ export class AdditionalSchemas extends Context.Service< AdditionalSchemas, diff --git a/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiBuilder.ts b/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiBuilder.ts index 5fcc6fedf388b470cf9236a84c1dd28c0349ae01..b742a9eaef1d83e4c37816d4f3c41d8277e00874 100644 --- a/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiBuilder.ts +++ b/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiBuilder.ts @@ -1,6 +1,15 @@ /** + * Builds server routes from declarative `HttpApi` contracts. + * + * This module turns an `HttpApi` description plus group handlers into + * `HttpRouter` routes. At runtime it decodes request parts with schemas, runs + * middleware and security handlers, invokes the registered endpoint handler, and + * encodes successes or declared errors into `HttpServerResponse` values. + * * @since 4.0.0 */ +import type { NonEmptyReadonlyArray } from "../../Array.ts" +import type * as Cause from "../../Cause.ts" import * as Context from "../../Context.ts" import * as Effect from "../../Effect.ts" import * as Encoding from "../../Encoding.ts" @@ -15,13 +24,14 @@ import { type Pipeable, pipeArguments } from "../../Pipeable.ts" import * as Redacted from "../../Redacted.ts" import * as Result from "../../Result.ts" import * as Schema from "../../Schema.ts" -import * as AST from "../../SchemaAST.ts" -import * as Issue from "../../SchemaIssue.ts" -import * as Transformation from "../../SchemaTransformation.ts" +import * as SchemaAST from "../../SchemaAST.ts" +import * as SchemaIssue from "../../SchemaIssue.ts" +import * as SchemaTransformation from "../../SchemaTransformation.ts" import * as Scope from "../../Scope.ts" import * as Stream from "../../Stream.ts" import type { Covariant, NoInfer } from "../../Types.ts" import * as UndefinedOr from "../../UndefinedOr.ts" +import * as Sse from "../encoding/Sse.ts" import type { Cookie } from "../http/Cookies.ts" import type * as Etag from "../http/Etag.ts" import * as HttpEffect from "../http/HttpEffect.ts" @@ -44,10 +54,10 @@ import type * as HttpApiSecurity from "./HttpApiSecurity.ts" import * as OpenApi from "./OpenApi.ts" /** - * Register an `HttpApi` with a `HttpRouter`. + * Registers an `HttpApi` with a `HttpRouter`. * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const layer = ( api: HttpApi.HttpApi, @@ -94,15 +104,16 @@ export const layer = ( })) /** - * Create a `Layer` that will implement all the endpoints in an `HttpApi`. + * Create a `Layer` that implements all endpoints in an `HttpApi` group. * - * An unimplemented `Handlers` instance is passed to the `build` function, which - * you can use to add handlers to the group. + * **Details** * - * You can implement endpoints using the `handlers.handle` api. + * The `build` function receives an unimplemented `Handlers` instance that can + * be used to add handlers to the group. Implement endpoints with + * `handlers.handle`. * - * @since 4.0.0 * @category handlers + * @since 4.0.0 */ export const group = < ApiId extends string, @@ -142,22 +153,32 @@ export const group = < })) as any /** + * Type identifier symbol used to brand `Handlers` values. + * + * @category type IDs * @since 4.0.0 - * @category handlers */ export const HandlersTypeId: unique symbol = Symbol.for("@effect/platform/HttpApiBuilder/Handlers") /** + * Type of the `Handlers` type identifier symbol. + * + * @category type IDs * @since 4.0.0 - * @category handlers */ export type HandlersTypeId = typeof HandlersTypeId /** - * Represents a handled `HttpApi`. + * Mutable handler collection for one `HttpApi` group. + * + * **Details** + * + * Each call to `handle` or `handleRaw` registers an endpoint implementation and + * removes that endpoint from the type-level set of endpoints still requiring + * handlers. * - * @since 4.0.0 * @category handlers + * @since 4.0.0 */ export interface Handlers< R, @@ -210,21 +231,31 @@ export interface Handlers< } /** + * Namespace containing helper types for `HttpApiBuilder` handler collections. + * * @since 4.0.0 - * @category handlers */ export declare namespace Handlers { /** - * @since 4.0.0 + * A `Handlers` value with its context and endpoint types erased. + * * @category handlers + * @since 4.0.0 */ export interface Any { readonly [HandlersTypeId]: any } /** - * @since 4.0.0 + * Record stored for a registered endpoint handler. + * + * **Details** + * + * It keeps the endpoint metadata, handler function, whether raw request handling + * is used, and whether the handler should run uninterruptibly. + * * @category handlers + * @since 4.0.0 */ export type Item = { readonly endpoint: HttpApiEndpoint.AnyWithProps @@ -234,8 +265,11 @@ export declare namespace Handlers { } /** - * @since 4.0.0 + * Creates a handler collection for a group where every endpoint in the group is + * still awaiting an implementation. + * * @category handlers + * @since 4.0.0 */ export type FromGroup = Handlers< never, @@ -243,8 +277,12 @@ export declare namespace Handlers { > /** - * @since 4.0.0 + * Validates the return value of a group handler builder, preserving successful + * handler collections and producing a descriptive type error when endpoints remain + * unhandled. + * * @category handlers + * @since 4.0.0 */ export type ValidateReturn = A extends ( | Handlers< @@ -264,8 +302,11 @@ export declare namespace Handlers { `Must return the implemented handlers` /** - * @since 4.0.0 + * Extracts the error channel from an effect that produces a `Handlers` + * collection, returning `never` for non-effectful handler collections. + * * @category handlers + * @since 4.0.0 */ export type Error = A extends Effect.Effect< Handlers< @@ -278,8 +319,11 @@ export declare namespace Handlers { never /** - * @since 4.0.0 + * Extracts the services required by a handler collection, including both handler + * requirements and the environment required to construct the handlers. + * * @category handlers + * @since 4.0.0 */ export type Context = A extends Handlers< infer _R, @@ -297,8 +341,11 @@ export declare namespace Handlers { } /** - * @since 4.0.0 + * Builds the server-side HTTP effect for a single endpoint in an API group using + * the endpoint metadata, middleware, codecs, and supplied handler. + * * @category handlers + * @since 4.0.0 */ export const endpoint = < ApiId extends string, @@ -351,8 +398,11 @@ export const endpoint = < }) /** - * @since 4.0.0 + * Decodes credentials for an HTTP API security scheme from the current request, + * supporting bearer, API key, and basic authentication inputs. + * * @category security + * @since 4.0.0 */ export const securityDecode = ( self: Security @@ -362,10 +412,11 @@ export const securityDecode = HttpServerRequest | Request.ParsedSearchParams > => { switch (self._tag) { - case "Bearer": { + case "Http": { return Effect.map( - HttpServerRequest.asEffect(), - (request) => Redacted.make((request.headers.authorization ?? "").slice(bearerLen)) as any + HttpServerRequest, + // schemeLength + space + (request) => Redacted.make((request.headers.authorization ?? "").slice(self.schemeLength + 1)) as any ) } case "ApiKey": { @@ -392,9 +443,9 @@ export const securityDecode = username: "", password: Redacted.make("") } as any - return HttpServerRequest.asEffect().pipe( + return HttpServerRequest.pipe( Effect.flatMap((request) => - Encoding.decodeBase64String((request.headers.authorization ?? "").slice(basicLen)).asEffect() + Effect.fromResult(Encoding.decodeBase64String((request.headers.authorization ?? "").slice(basicLen))) ), Effect.match({ onFailure: () => empty, @@ -415,8 +466,11 @@ export const securityDecode = } /** - * @since 4.0.0 + * Registers a pre-response handler that sets an API-key cookie on the outgoing + * response, defaulting the cookie to `secure` and `httpOnly` unless overridden. + * * @category security + * @since 4.0.0 */ export const securitySetCookie = ( self: HttpApiSecurity.ApiKey, @@ -437,7 +491,6 @@ export const securitySetCookie = ( // Internal // ----------------------------------------------------------------------------- -const bearerLen = `Bearer `.length const basicLen = `Basic `.length const HandlersProto = { @@ -513,7 +566,7 @@ function buildPayloadDecoders( result.set(contentType, { _tag: encoding._tag, decode, - nullOnEmpty: schemas.some((s) => AST.isNull(AST.toEncoded(s.ast))) + nullOnEmpty: schemas.some((s) => SchemaAST.isNull(SchemaAST.toEncoded(s.ast))) }) } }) @@ -585,6 +638,7 @@ function handlerToHttpEffect( const decodeParams = UndefinedOr.map(endpoint.params, Schema.decodeUnknownEffect) const decodeHeaders = UndefinedOr.map(endpoint.headers, Schema.decodeUnknownEffect) const decodeQuery = UndefinedOr.map(endpoint.query, Schema.decodeUnknownEffect) + const encodeStream = makeStreamEncoder(endpoint) const shouldParsePayload = endpoint.payload.size > 0 && !isRaw const payloadBy = shouldParsePayload ? buildPayloadDecoders(endpoint.payload) : undefined @@ -623,9 +677,14 @@ function handlerToHttpEffect( } } const response = yield* handler(request) - return Response.isHttpServerResponse(response) - ? response - : yield* HttpApiSchemaError.wrap("Body", encodeSuccess(response)) + if (Response.isHttpServerResponse(response)) { + return response + } + const streamResponse = encodeStream?.(response, context) + if (streamResponse !== undefined) { + return yield* HttpApiSchemaError.wrap("Body", streamResponse) + } + return yield* HttpApiSchemaError.wrap("Body", encodeSuccess(response)) }) ).pipe( Effect.withErrorReporting, @@ -722,7 +781,7 @@ const makeSecurityMiddleware = ( } return result.success } - return yield* lastResult!.asEffect() + return yield* Effect.fromResult(lastResult!) }) securityMiddlewareCache.set(service, middleware) @@ -731,6 +790,142 @@ const makeSecurityMiddleware = ( const $HttpServerResponse = Schema.declare(Response.isHttpServerResponse) +type StreamEncoder = (response: unknown, context: Context.Context) => + | Effect.Effect + | undefined + +function makeStreamEncoder(endpoint: HttpApiEndpoint.AnyWithProps): StreamEncoder | undefined { + const streamSchema = getStreamSuccessSchema(endpoint) + if (streamSchema === undefined) { + return undefined + } + + const hasBuffered = hasBufferedSuccess(endpoint) + const status = HttpApiSchema.getStatusStream(streamSchema) + const contentType = streamSchema.contentType + + if (HttpApiSchema.isStreamUint8Array(streamSchema)) { + return (response, context) => { + if (!Stream.isStream(response)) { + return hasBuffered ? undefined : expectedStreamResponse(response) + } + + return Effect.succeed(Response.stream( + Stream.provideContext( + response as Stream.Stream, + context as Context.Context + ), + { status, contentType } + )) + } + } + + const sseEncoder = makeSseEncoder(streamSchema) + + return (response, context) => { + if (!Stream.isStream(response)) { + return hasBuffered ? undefined : expectedStreamResponse(response) + } + + return Effect.succeed(Response.stream( + Stream.provideContext( + encodeSseStream(response, sseEncoder), + context as Context.Context + ), + { status, contentType } + )) + } +} + +function getStreamSuccessSchema(endpoint: HttpApiEndpoint.AnyWithProps) { + for (const schema of endpoint.success) { + if (HttpApiSchema.isStreamSchema(schema)) { + return schema + } + } +} + +function hasBufferedSuccess(endpoint: HttpApiEndpoint.AnyWithProps): boolean { + for (const schema of endpoint.success) { + if (Schema.isSchema(schema) && !HttpApiSchema.isStreamSchema(schema)) return true + } + return endpoint.success.size === 0 +} + +function expectedStreamResponse(response: unknown) { + return Effect.fail( + makeSchemaError( + new SchemaIssue.InvalidValue(Option.some(response), { + message: "Expected a streaming response" + }) + ) + ) +} + +interface SseStreamEncoder { + readonly sseMode: HttpApiSchema.StreamSseMode + readonly encodeEvents: ( + input: NonEmptyReadonlyArray + ) => Effect.Effect, Schema.SchemaError, unknown> + readonly encodeCause: (input: unknown) => Effect.Effect +} + +function makeSseEncoder( + streamSchema: HttpApiSchema.StreamSse +): SseStreamEncoder { + const CauseSchema = Schema.toCodecJson(Schema.Cause(streamSchema.error, Schema.Defect())) + return { + sseMode: streamSchema.sseMode, + encodeEvents: Schema.encodeUnknownEffect(Schema.Array(streamSchema.events)) as any, + encodeCause: Schema.encodeUnknownEffect(Schema.fromJsonString(CauseSchema)) + } +} + +function encodeSseStream( + stream: Stream.Stream, + encoder: SseStreamEncoder +): Stream.Stream { + return stream.pipe( + encoder.sseMode === "data" ? + Stream.map((value) => ({ + id: undefined, + event: "message", + data: value + })) : + identity, + Stream.mapArrayEffect((chunk) => Effect.orDie(encoder.encodeEvents(chunk))), + Stream.catchCause((cause) => Stream.fromEffect(encodeFailureEvent(cause, encoder))), + Stream.map(renderSseEvent), + Stream.encodeText + ) +} + +function encodeFailureEvent(cause: Cause.Cause, encoder: SseStreamEncoder) { + return encoder.encodeCause(cause).pipe( + Effect.orDie, + Effect.map((encodedCause) => ({ + id: undefined, + event: reservedStreamFailureEvent, + data: encodedCause + })) + ) +} + +const reservedStreamFailureEvent = "effect/httpapi/stream/failure" + +function renderSseEvent(event: Sse.EventEncoded) { + return Sse.encoder.write({ + _tag: "Event", + event: event.event, + id: event.id, + data: event.data + }) +} + +function makeSchemaError(issue: SchemaIssue.Issue): Schema.SchemaError { + return new Schema.SchemaError(issue) +} + const toResponseSuccessSchema = toResponseSchema(HttpApiSchema.getStatusSuccess) const toResponseErrorSchema = toResponseSchema(HttpApiSchema.getStatusError) @@ -745,8 +940,8 @@ function makeErrorSchema(endpoint: HttpApiEndpoint.AnyWithProps): Schema.Encoder return schemas.length === 1 ? schemas[0] : Schema.Union(schemas) } -function toResponseSchema(getStatus: (ast: AST.AST) => number) { - const cache = new WeakMap() +function toResponseSchema(getStatus: (ast: SchemaAST.AST) => number) { + const cache = new WeakMap() return (schema: Schema.Top): Schema.Encoder => { const cached = cache.get(schema.ast) @@ -762,9 +957,9 @@ function toResponseSchema(getStatus: (ast: AST.AST) => number) { } function getResponseTransformation( - getStatus: (ast: AST.AST) => number, + getStatus: (ast: SchemaAST.AST) => number, schema: Schema.Top -): Transformation.Transformation { +): SchemaTransformation.Transformation { const ast = schema.ast const encode = getResponseEncode( getStatus(ast), @@ -772,8 +967,8 @@ function getResponseTransformation( HttpApiSchema.isNoContent(ast) ) - return Transformation.transformOrFail({ - decode: (res) => Effect.fail(new Issue.Forbidden(Option.some(res), { message: "Encode only schema" })), + return SchemaTransformation.transformOrFail({ + decode: (res) => Effect.fail(new SchemaIssue.Forbidden(Option.some(res), { message: "Encode only schema" })), encode }) } @@ -782,7 +977,7 @@ function getResponseEncode( status: number, encoding: HttpApiSchema.ResponseEncoding, isNoContent: boolean -): (e: E) => Effect.Effect { +): (e: E) => Effect.Effect { switch (encoding._tag) { case "Json": { return ((e) => { @@ -793,7 +988,7 @@ function getResponseEncode( const s = JSON.stringify(e) return Effect.succeed(Response.text(s, { status, contentType: encoding.contentType })) } catch (error) { - return Effect.fail(new Issue.InvalidValue(Option.some(e), { message: globalThis.String(error) })) + return Effect.fail(new SchemaIssue.InvalidValue(Option.some(e), { message: globalThis.String(error) })) } }) } diff --git a/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiClient.ts b/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiClient.ts index 1ff1e31d6d385dc608a6722ba893dc4eafb0b340..7e0fb9c73d1e8e4ecba20a0d5025f317877dd9a8 100644 --- a/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiClient.ts +++ b/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiClient.ts @@ -1,4 +1,13 @@ /** + * Builds HTTP clients from `HttpApi` declarations. + * + * The client methods are derived from the groups and endpoints in an `HttpApi` + * and run through an `HttpClient`. They use the same schema-driven contract as + * the server: request parts are encoded from endpoint schemas, client + * middleware is applied, the HTTP request is executed, and declared success or + * error responses are decoded. This module also includes helpers for building a + * client for only one group, one endpoint, or only the encoded URL. + * * @since 4.0.0 */ import * as Arr from "../../Array.ts" @@ -9,11 +18,13 @@ import { identity } from "../../Function.ts" import * as Option from "../../Option.ts" import * as Predicate from "../../Predicate.ts" import * as Schema from "../../Schema.ts" -import * as AST from "../../SchemaAST.ts" -import * as Issue from "../../SchemaIssue.ts" -import * as Transformation from "../../SchemaTransformation.ts" +import * as SchemaAST from "../../SchemaAST.ts" +import * as SchemaIssue from "../../SchemaIssue.ts" +import * as SchemaTransformation from "../../SchemaTransformation.ts" +import * as Stream from "../../Stream.ts" import type { Simplify } from "../../Types.ts" import * as UndefinedOr from "../../UndefinedOr.ts" +import * as Sse from "../encoding/Sse.ts" import * as HttpBody from "../http/HttpBody.ts" import * as HttpClient from "../http/HttpClient.ts" import * as HttpClientError from "../http/HttpClientError.ts" @@ -28,8 +39,11 @@ import type * as HttpApiMiddleware from "./HttpApiMiddleware.ts" import * as HttpApiSchema from "./HttpApiSchema.ts" /** - * @since 4.0.0 + * The type-safe client shape generated from HTTP API groups, with non-top-level + * groups exposed as nested objects and top-level endpoints exposed as methods. + * * @category models + * @since 4.0.0 */ export type Client = Simplify< & { @@ -46,27 +60,62 @@ export type Client = Simp > /** - * @since 4.0.0 + * Derives the typed client interface for an `HttpApi`, preserving any additional + * client error and service requirements supplied by the caller. + * * @category models + * @since 4.0.0 */ export type ForApi = Api extends HttpApi.HttpApi ? Client : never +type SuccessType = S extends HttpApiSchema.StreamSse< + infer _Events, + infer _Error, + infer _Value +> ? Stream.Stream< + _Value, + _Error["Type"] | HttpClientError.HttpClientError | Schema.SchemaError | Sse.Retry, + never + > + : S extends HttpApiSchema.StreamUint8Array ? Stream.Stream + : S extends Schema.Top ? S["Type"] + : never + +type SuccessDecodingServices = S extends HttpApiSchema.StreamSse< + infer _Events, + infer _Error, + infer _Value +> ? + | _Events["DecodingServices"] + | _Error["DecodingServices"] + : S extends HttpApiSchema.StreamUint8Array ? never + : S extends Schema.Top ? S["DecodingServices"] + : never + /** + * Helper types used to describe generated HTTP API clients, including endpoint + * methods, response modes, and grouped client shapes. + * * @since 4.0.0 - * @category models */ export declare namespace Client { /** - * @since 4.0.0 + * The response mode accepted by generated client methods, controlling whether a + * call returns the decoded success value, the raw response, or both. + * * @category models + * @since 4.0.0 */ export type ResponseMode = HttpApiEndpoint.ClientResponseMode /** - * @since 4.0.0 + * Computes the value returned by a client method for a success type and response + * mode. + * * @category models + * @since 4.0.0 */ export type Response = [Mode] extends ["decoded-and-response"] ? [Success, HttpClientResponse.HttpClientResponse] @@ -74,8 +123,11 @@ export declare namespace Client { : Success /** - * @since 4.0.0 + * The client object for one API group, mapping each endpoint name in that group to + * its typed client method. + * * @category models + * @since 4.0.0 */ export type Group = [HttpApiGroup.WithName] extends [HttpApiGroup.HttpApiGroup] ? @@ -85,8 +137,12 @@ export declare namespace Client { never /** - * @since 4.0.0 + * The typed function generated for an endpoint, accepting the endpoint request + * shape and returning an effect whose success, error, and service channels reflect + * the endpoint schemas, middleware, and selected response mode. + * * @category models + * @since 4.0.0 */ export type Method = [Endpoint] extends [ HttpApiEndpoint.HttpApiEndpoint< @@ -105,7 +161,7 @@ export declare namespace Client { ] ? ( request: Simplify> ) => Effect.Effect< - Response<_Success["Type"], Mode>, + Response, Mode>, | HttpApiMiddleware.Error<_Middleware> | HttpApiMiddleware.ClientError<_Middleware> | E @@ -116,13 +172,19 @@ export declare namespace Client { | _Query["EncodingServices"] | _Payload["EncodingServices"] | _Headers["EncodingServices"] - | ([Mode] extends ["response-only"] ? never : _Success["DecodingServices"] | _Error["DecodingServices"]) + | ([Mode] extends ["response-only"] ? never + : + | SuccessDecodingServices<_Success> + | _Error["DecodingServices"]) > : never /** - * @since 4.0.0 + * Extracts client methods for endpoints in top-level groups so they can be exposed + * directly on the generated client object. + * * @category models + * @since 4.0.0 */ export type TopLevelMethods = Extract extends @@ -145,8 +207,11 @@ type UrlBuilderArgs = [UrlBuilderRequest] /** - * @since 4.0.0 + * The type-safe URL builder shape for an HTTP API, mirroring the generated client + * layout while returning URL strings instead of executing requests. + * * @category models + * @since 4.0.0 */ export type UrlBuilder = Api extends HttpApi.HttpApi ? Simplify< & { @@ -276,9 +341,25 @@ export const makeClient = { - decodeMap[status] = schemasToResponse(schemas) - }) + + const successAlternatives = new Map>() + for (const [status, schemas] of successes.entries()) { + const grouped = groupSchemasByContentType(schemas) + for (const [contentType, schemas] of grouped.entries()) { + addResponseAlternative(successAlternatives, status, contentType, schemasToResponse(schemas)) + } + } + for (const streamSuccess of getStreamSuccessSchemas(endpoint)) { + addResponseAlternative( + successAlternatives, + HttpApiSchema.getStatusStream(streamSuccess), + streamSuccess.contentType, + streamToResponse(streamSuccess) + ) + } + for (const [status, alternatives] of successAlternatives.entries()) { + decodeMap[status] = makeResponseDecoder(alternatives) + } // encoders const encodeParams = UndefinedOr.map(endpoint.params, Schema.encodeUnknownEffect) @@ -369,8 +450,11 @@ export const makeClient = ( api: HttpApi.HttpApi, @@ -386,15 +470,19 @@ export const make = ( never, HttpClient.HttpClient | HttpApiGroup.MiddlewareClient > => - Effect.flatMap(HttpClient.HttpClient.asEffect(), (httpClient) => + Effect.flatMap(HttpClient.HttpClient, (httpClient) => makeWith(api, { ...options, httpClient: options?.transformClient ? options.transformClient(httpClient) : httpClient })) /** - * @since 4.0.0 + * Constructs a type-safe client for an HTTP API from the supplied `HttpClient`, + * using the API metadata to encode requests, execute middleware, and decode + * responses. + * * @category constructors + * @since 4.0.0 */ export const makeWith = ( api: HttpApi.HttpApi, @@ -420,8 +508,11 @@ export const makeWith = "https://api.example.com/users/123" * ``` - * @since 4.0.0 + * * @category constructors + * @since 4.0.0 */ export const urlBuilder = (api: Api, options?: { readonly baseUrl?: URL | string | undefined @@ -569,24 +665,25 @@ export const urlBuilder = (api: Api, options?: { // ---------------------------------------------------------------------------- -const paramsRegExp = /:(\w+)\??/g +const paramsRegExp = /(\/?):(\w+)(\?)?/g const compilePath = (path: string) => { - const segments = path.split(paramsRegExp) - const len = segments.length - if (len === 1) { + if (!paramsRegExp.test(path)) { return (_: any) => path } + paramsRegExp.lastIndex = 0 return (params: Record) => { - let url = segments[0] - for (let i = 1; i < len; i++) { - if (i % 2 === 0) { - url += segments[i] - } else { - url += params[segments[i]] + paramsRegExp.lastIndex = 0 + return path.replace(paramsRegExp, (_, slash: string, key: string, optional: string | undefined) => { + const value = params[key] + if (value === undefined) { + if (optional !== undefined) { + return "" + } + throw new Error(`Missing path parameter: ${key}`) } - } - return url + return `${slash}${encodeURIComponent(value)}` + }) } } @@ -596,6 +693,152 @@ function schemasToResponse(schemas: readonly [Schema.Top, ...Array]) return (response: HttpClientResponse.HttpClientResponse) => Effect.flatMap(response.arrayBuffer, decode) } +type ResponseDecoder = (response: HttpClientResponse.HttpClientResponse) => Effect.Effect + +interface ResponseAlternative { + readonly contentType: string + readonly decode: ResponseDecoder +} + +function addResponseAlternative( + map: Map>, + status: number, + contentType: string, + decode: ResponseDecoder +) { + const normalizedContentType = normalizeContentType(contentType) + const alternatives = map.get(status) + if (alternatives === undefined) { + map.set(status, [{ contentType: normalizedContentType, decode }]) + } else { + alternatives.push({ contentType: normalizedContentType, decode }) + } +} + +function makeResponseDecoder(alternatives: ReadonlyArray): ResponseDecoder { + const first = alternatives[0] + if (alternatives.length === 1 && first !== undefined) { + return first.decode + } + return (response) => { + const contentType = normalizeContentType(response.headers["content-type"] ?? "") + const alternative = alternatives.find((alternative) => alternative.contentType === contentType) + return alternative === undefined + ? failUnsupportedContentType(response, contentType, alternatives) + : alternative.decode(response) + } +} + +function groupSchemasByContentType( + schemas: Arr.NonEmptyReadonlyArray +): Map> { + const grouped = new Map]>() + for (const schema of schemas) { + const contentType = HttpApiSchema.getResponseEncoding(schema.ast).contentType + const existing = grouped.get(contentType) + if (existing === undefined) { + grouped.set(contentType, [schema]) + } else { + existing.push(schema) + } + } + return grouped +} + +function normalizeContentType(contentType: string): string { + const normalized = contentType.toLowerCase().trim() + const index = normalized.indexOf(";") + return index === -1 ? normalized : normalized.slice(0, index).trim() +} + +function failUnsupportedContentType( + response: HttpClientResponse.HttpClientResponse, + contentType: string, + alternatives: ReadonlyArray +) { + const expected = Array.from(new Set(alternatives.map((alternative) => alternative.contentType))).join(", ") + return Effect.fail( + new HttpClientError.HttpClientError({ + reason: new HttpClientError.DecodeError({ + request: response.request, + response, + description: `Unsupported response content-type for status ${response.status}: ${ + contentType || "" + }. Expected one of: ${expected}` + }) + }) + ) +} + +const reservedStreamFailureEvent = "effect/httpapi/stream/failure" + +function getStreamSuccessSchemas(endpoint: HttpApiEndpoint.AnyWithProps): Array { + const schemas: Array = [] + for (const schema of endpoint.success) { + if (HttpApiSchema.isStreamSchema(schema)) { + schemas.push(schema) + } + } + return schemas +} + +function streamToResponse(streamSchema: HttpApiSchema.StreamSchema) { + return (response: HttpClientResponse.HttpClientResponse) => + Effect.map(Effect.context(), (context) => + Stream.provideContext( + HttpApiSchema.isStreamUint8Array(streamSchema) ? + response.stream : + decodeSseStream(response.stream, streamSchema), + context as Context.Context + )) +} + +function decodeSseStream( + stream: Stream.Stream, + declaration: HttpApiSchema.StreamSse +): Stream.Stream { + const Event = Schema.Union([ + declaration.events, + Schema.Struct({ + event: Schema.Literal(reservedStreamFailureEvent), + data: Schema.fromJsonString(Schema.toCodecJson(Schema.Cause(declaration.error, Schema.Defect()))) + }) + ]) + const events = Stream.transformPull( + stream.pipe( + Stream.decodeText, + Stream.pipeThroughChannel(Sse.decodeSchema(Event)) + ), + (pull) => + Effect.sync(() => { + let failureCause: Cause.Cause | undefined = undefined + return Effect.suspend(() => { + if (failureCause) { + return Effect.failCause(failureCause) + } + return Effect.flatMap(pull, (events) => { + for (let i = 0; i < events.length; i++) { + const event = events[i] + if (event.event === reservedStreamFailureEvent) { + if (i === 0) { + return Effect.failCause(event.data) + } + failureCause = event.data + events = events.slice(0, i) as any + break + } + } + return Effect.succeed(events) + }) + }) + }) + ) + if (declaration.sseMode === "data") { + return Stream.map(events, (event) => event.data) + } + return events +} + const ArrayBuffer = Schema.instanceOf(globalThis.ArrayBuffer, { expected: "ArrayBuffer" }) @@ -604,7 +847,7 @@ const ArrayBuffer = Schema.instanceOf(globalThis.ArrayBuffer, { const Uint8ArrayFromArrayBuffer = ArrayBuffer.pipe( Schema.decodeTo( Schema.Uint8Array as Schema.instanceOf>, - Transformation.transform({ + SchemaTransformation.transform({ decode(fromA) { return new Uint8Array(fromA) }, @@ -621,7 +864,7 @@ const Uint8ArrayFromArrayBuffer = ArrayBuffer.pipe( const StringFromArrayBuffer = ArrayBuffer.pipe( Schema.decodeTo( Schema.String, - Transformation.transform({ + SchemaTransformation.transform({ decode(fromA) { return new TextDecoder().decode(fromA) }, @@ -641,7 +884,7 @@ const UnknownFromArrayBuffer = StringFromArrayBuffer.pipe(Schema.decodeTo( // Handle No Content Schema.Literal("").pipe(Schema.decodeTo( Schema.Undefined, - Transformation.transform({ + SchemaTransformation.transform({ decode: () => undefined, encode: () => "" }) @@ -658,11 +901,11 @@ function toCodecArrayBuffer(schemas: readonly [Schema.Top, ...Array] switch (encoding._tag) { case "Json": { // handle json codecs that transform void schemas to null - const encodedIsNull = AST.isNull(AST.toEncoded(schema.ast)) + const encodedIsNull = SchemaAST.isNull(SchemaAST.toEncoded(schema.ast)) return UnknownFromArrayBuffer.pipe(Schema.decodeTo( schema, encodedIsNull ? - Transformation.transform({ + SchemaTransformation.transform({ decode: (a) => a === undefined ? null : a, encode: (a) => a === null ? undefined : a }) as any : @@ -701,7 +944,7 @@ function getEncodePayloadSchema( return Schema.Union(schemas.map((s) => getEncodePayloadSchemaFromBody(s, method))) } -const bodyFromPayloadCache = new WeakMap() +const bodyFromPayloadCache = new WeakMap() function getEncodePayloadSchemaFromBody( schema: Schema.Top, @@ -715,40 +958,40 @@ function getEncodePayloadSchemaFromBody( const encoding = HttpApiSchema.getPayloadEncoding(ast, method) const out = $HttpBody.pipe(Schema.decodeTo( schema, - Transformation.transformOrFail({ + SchemaTransformation.transformOrFail({ decode(httpBody) { - return Effect.fail(new Issue.Forbidden(Option.some(httpBody), { message: "Encode only schema" })) + return Effect.fail(new SchemaIssue.Forbidden(Option.some(httpBody), { message: "Encode only schema" })) }, encode(t) { switch (encoding._tag) { case "Multipart": - return Effect.fail(new Issue.Forbidden(Option.some(t), { message: "Payload must be a FormData" })) + return Effect.fail(new SchemaIssue.Forbidden(Option.some(t), { message: "Payload must be a FormData" })) case "Json": { try { const body = JSON.stringify(t) return Effect.succeed(HttpBody.text(body, encoding.contentType)) } catch (error) { - return Effect.fail(new Issue.InvalidValue(Option.some(t), { message: globalThis.String(error) })) + return Effect.fail(new SchemaIssue.InvalidValue(Option.some(t), { message: globalThis.String(error) })) } } case "Text": { if (typeof t !== "string") { return Effect.fail( - new Issue.InvalidValue(Option.some(t), { message: "Expected a string" }) + new SchemaIssue.InvalidValue(Option.some(t), { message: "Expected a string" }) ) } return Effect.succeed(HttpBody.text(t, encoding.contentType)) } case "FormUrlEncoded": { if (!Predicate.isObject(t)) { - return Effect.fail(new Issue.InvalidValue(Option.some(t), { message: "Expected a record" })) + return Effect.fail(new SchemaIssue.InvalidValue(Option.some(t), { message: "Expected a record" })) } return Effect.succeed(HttpBody.urlParams(UrlParams.fromInput(t as any))) } case "Uint8Array": { if (!(t instanceof Uint8Array)) { return Effect.fail( - new Issue.InvalidValue(Option.some(t), { message: "Expected a Uint8Array" }) + new SchemaIssue.InvalidValue(Option.some(t), { message: "Expected a Uint8Array" }) ) } return Effect.succeed(HttpBody.uint8Array(t, encoding.contentType)) diff --git a/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiEndpoint.ts b/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiEndpoint.ts index aec699cc65820f9dc7b6727bdf8956c8314f5b88..b2efbb90d79174d20044371e6965148ca8850284 100644 --- a/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiEndpoint.ts +++ b/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiEndpoint.ts @@ -1,4 +1,14 @@ /** + * Defines endpoint declarations used inside an HTTP API group. + * + * An endpoint records a stable name, HTTP method, router path, request schemas, + * response schemas, declared errors, middleware, and annotations. Endpoint + * values are declarations, not handlers: builders use them to decode requests, + * type handler input, encode responses, generate OpenAPI metadata, and derive + * generated-client call signatures. This module also includes HTTP method + * constructors, payload and response schema helpers, and type utilities used by + * builders and generated clients. + * * @since 4.0.0 */ import * as Arr from "../../Array.ts" @@ -9,6 +19,7 @@ import { identity } from "../../Function.ts" import { type Pipeable, pipeArguments } from "../../Pipeable.ts" import * as Predicate from "../../Predicate.ts" import * as Schema from "../../Schema.ts" +import * as AST from "../../SchemaAST.ts" import type * as Stream from "../../Stream.ts" import type * as Types from "../../Types.ts" import type { HttpMethod } from "../http/HttpMethod.ts" @@ -23,26 +34,74 @@ import * as HttpApiSchema from "./HttpApiSchema.ts" const TypeId = "~effect/httpapi/HttpApiEndpoint" /** - * @since 4.0.0 + * Returns `true` when a value is an `HttpApiEndpoint`, narrowing the value to the + * endpoint interface. + * * @category guards + * @since 4.0.0 */ export const isHttpApiEndpoint = (u: unknown): u is HttpApiEndpoint => Predicate.hasProperty(u, TypeId) /** - * @since 4.0.0 + * Maps content types to the payload encoding strategy and one or more schemas that + * can decode or encode payloads for that content type. + * * @category models + * @since 4.0.0 */ export type PayloadMap = ReadonlyMap] }> +type SuccessType = S extends HttpApiSchema.StreamSse< + infer _Events, + infer _Error, + infer _Value +> ? Stream.Stream<_Value, _Error["Type"], never> + : S extends HttpApiSchema.StreamUint8Array ? Stream.Stream + : S extends Schema.Top ? S["Type"] + : never + +type SuccessEncodingServices = S extends HttpApiSchema.StreamSse< + infer _Events, + infer _Error, + infer _Value +> ? _Events["EncodingServices"] | _Error["EncodingServices"] + : S extends HttpApiSchema.StreamUint8Array ? never + : S extends Schema.Top ? S["EncodingServices"] + : never + +type SuccessDecodingServices = S extends HttpApiSchema.StreamSse< + infer _Events, + infer _Error, + infer _Value +> ? _Events["DecodingServices"] | _Error["DecodingServices"] + : S extends HttpApiSchema.StreamUint8Array ? never + : S extends Schema.Top ? S["DecodingServices"] + : never + +type ExtractSuccessOrArray = S extends ReadonlyArray ? S[number] : S + +type ExtractBufferedSuccess = Exclude< + Extract, Schema.Top>, + HttpApiSchema.StreamSchema +> + +type ExtractStreamSuccess = ExtractSuccessOrArray extends infer Success ? + Success extends HttpApiSchema.StreamSchema ? Success : never + : never + +type JsonSuccessOrArray = [ExtractBufferedSuccess] extends [never] ? + ExtractStreamSuccess + : Json> | ExtractStreamSuccess + /** * Represents an API endpoint. An API endpoint is mapped to a single route on * the underlying `HttpRouter`. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface HttpApiEndpoint< out Name extends string, @@ -183,8 +242,11 @@ export function getErrorSchemas(endpoint: AnyWithProps): Array { } /** - * @since 4.0.0 + * A widened `HttpApiEndpoint` type used when the concrete method, path, schemas, + * and middleware types are not needed. + * * @category models + * @since 4.0.0 */ export interface Any extends Pipeable { readonly [TypeId]: any @@ -194,16 +256,21 @@ export interface Any extends Pipeable { } /** - * @since 4.0.0 + * A widened endpoint type that preserves concrete runtime properties such as + * method, path, schemas, annotations, and middleware sets. + * * @category models + * @since 4.0.0 */ export interface AnyWithProps extends HttpApiEndpoint {} /** - * @since 4.0.0 + * Extracts the name literal from an `HttpApiEndpoint`. + * * @category models + * @since 4.0.0 */ export type Name = Endpoint extends HttpApiEndpoint< infer _Name, @@ -221,8 +288,10 @@ export type Name = Endpoint extends HttpApiEndpoint< : never /** - * @since 4.0.0 + * Extracts the success schema associated with an endpoint. + * * @category models + * @since 4.0.0 */ export type Success = Endpoint extends HttpApiEndpoint< infer _Name, @@ -240,8 +309,10 @@ export type Success = Endpoint extends HttpApiEndpoint< : never /** - * @since 4.0.0 + * Extracts the error schema associated with an endpoint. + * * @category models + * @since 4.0.0 */ export type Error = Endpoint extends HttpApiEndpoint< infer _Name, @@ -259,8 +330,10 @@ export type Error = Endpoint extends HttpApiEndpoint< : never /** - * @since 4.0.0 + * Extracts the schema used for an endpoint's path parameters. + * * @category models + * @since 4.0.0 */ export type Params = Endpoint extends HttpApiEndpoint< infer _Name, @@ -278,8 +351,10 @@ export type Params = Endpoint extends HttpApiEndpoint< : never /** - * @since 4.0.0 + * Extracts the schema used for an endpoint's query parameters. + * * @category models + * @since 4.0.0 */ export type Query = Endpoint extends HttpApiEndpoint< infer _Name, @@ -297,8 +372,10 @@ export type Query = Endpoint extends HttpApiEndpoint< : never /** - * @since 4.0.0 + * Extracts the schema used for an endpoint's request payload. + * * @category models + * @since 4.0.0 */ export type Payload = Endpoint extends HttpApiEndpoint< infer _Name, @@ -316,8 +393,10 @@ export type Payload = Endpoint extends HttpApiEndpoint< : never /** - * @since 4.0.0 + * Extracts the schema used for an endpoint's request headers. + * * @category models + * @since 4.0.0 */ export type Headers = Endpoint extends HttpApiEndpoint< infer _Name, @@ -335,8 +414,10 @@ export type Headers = Endpoint extends HttpApiEndpoint< : never /** - * @since 4.0.0 + * Extracts the middleware identifiers attached to an endpoint. + * * @category models + * @since 4.0.0 */ export type Middleware = Endpoint extends HttpApiEndpoint< infer _Name, @@ -354,26 +435,36 @@ export type Middleware = Endpoint extends HttpApiEndpoint< : never /** - * @since 4.0.0 + * Computes the services provided by the middleware attached to an endpoint. + * * @category models + * @since 4.0.0 */ export type MiddlewareProvides = HttpApiMiddleware.Provides> /** - * @since 4.0.0 + * Computes the client-side middleware services required by an endpoint. + * * @category models + * @since 4.0.0 */ export type MiddlewareClient = HttpApiMiddleware.MiddlewareClient> /** - * @since 4.0.0 + * Computes the error types that can be produced by the middleware attached to an + * endpoint. + * * @category models + * @since 4.0.0 */ export type MiddlewareError = HttpApiMiddleware.Error> /** - * @since 4.0.0 + * Computes the full error value union for an endpoint, including the endpoint + * error schema's type and errors introduced by middleware. + * * @category models + * @since 4.0.0 */ export type Errors = Endpoint extends HttpApiEndpoint< infer _Name, @@ -391,8 +482,11 @@ export type Errors = Endpoint extends HttpApiEndpoint< : never /** - * @since 4.0.0 + * Computes the services required to encode an endpoint's error responses, + * including services required by middleware error encoders. + * * @category models + * @since 4.0.0 */ export type ErrorServicesEncode = Endpoint extends HttpApiEndpoint< infer _Name, @@ -410,8 +504,12 @@ export type ErrorServicesEncode = Endpoint extends HttpApi : never /** - * @since 4.0.0 + * Builds the decoded request shape passed to a normal endpoint handler, including + * available params, query, payload, headers, the raw request, endpoint, and group. + * Multipart stream payloads are exposed as streams of parts. + * * @category models + * @since 4.0.0 */ export type Request = Endpoint extends HttpApiEndpoint< infer _Name, @@ -441,8 +539,12 @@ export type Request = Endpoint extends HttpApiEndpoint< : {} /** - * @since 4.0.0 + * Builds the request shape passed to a raw endpoint handler, including decoded + * params, query, and headers plus the raw request, endpoint, and group, while + * leaving payload handling to the raw request. + * * @category models + * @since 4.0.0 */ export type RequestRaw = Endpoint extends HttpApiEndpoint< infer _Name, @@ -468,8 +570,12 @@ export type RequestRaw = Endpoint extends HttpApiEndpoint< : {} /** - * @since 4.0.0 + * Builds the request object accepted by a generated client method, including only + * the params, query, headers, payload, and response mode fields required by the + * endpoint. Multipart payloads are supplied as `FormData`. + * * @category models + * @since 4.0.0 */ export type ClientRequest< Params extends Schema.Top, @@ -492,14 +598,20 @@ export type ClientRequest< void /** - * @since 4.0.0 + * Controls what a generated client method returns: the decoded success value, + * the decoded value paired with the raw response, or only the raw response. + * * @category models + * @since 4.0.0 */ export type ClientResponseMode = "decoded-only" | "decoded-and-response" | "response-only" /** - * @since 4.0.0 + * Computes the services required on the server to decode endpoint inputs and + * encode endpoint success, error, and middleware error responses. + * * @category models + * @since 4.0.0 */ export type ServerServices = Endpoint extends HttpApiEndpoint< infer _Name, @@ -518,14 +630,17 @@ export type ServerServices = Endpoint extends HttpApiEndpoint< | _Query["DecodingServices"] | _Payload["DecodingServices"] | _Headers["DecodingServices"] - | _Success["EncodingServices"] + | SuccessEncodingServices<_Success> | _Error["EncodingServices"] | HttpApiMiddleware.ErrorServicesEncode<_M> : never /** - * @since 4.0.0 + * Computes the services required on the client to encode endpoint requests and + * decode endpoint success or error responses. + * * @category models + * @since 4.0.0 */ export type ClientServices = Endpoint extends HttpApiEndpoint< infer _Name, @@ -544,13 +659,15 @@ export type ClientServices = Endpoint extends HttpApiEndpoint< | _Query["EncodingServices"] | _Payload["EncodingServices"] | _Headers["EncodingServices"] - | _Success["DecodingServices"] + | SuccessDecodingServices<_Success> | _Error["DecodingServices"] : never /** - * @since 4.0.0 + * Extracts the additional services required by middleware applied to an endpoint. + * * @category models + * @since 4.0.0 */ export type MiddlewareServices = Endpoint extends HttpApiEndpoint< infer _Name, @@ -568,8 +685,11 @@ export type MiddlewareServices = Endpoint extends HttpApiEndpoint< : never /** - * @since 4.0.0 + * Computes the services required to decode an endpoint's error responses, + * including services required by middleware error decoders. + * * @category models + * @since 4.0.0 */ export type ErrorServicesDecode = Endpoint extends HttpApiEndpoint< infer _Name, @@ -587,36 +707,49 @@ export type ErrorServicesDecode = Endpoint extends HttpApiEndpoint< : never /** - * @since 4.0.0 + * The normal server handler for an endpoint, accepting the decoded request shape + * and returning either the endpoint success value or a custom `HttpServerResponse`. + * * @category models + * @since 4.0.0 */ export type Handler = ( request: Types.Simplify> -) => Effect +) => Effect | HttpServerResponse, Endpoint["~Error"]["Type"] | E, R> /** - * @since 4.0.0 + * The raw server handler for an endpoint, receiving a request shape without a + * decoded payload so the handler can read the raw `HttpServerRequest` directly. + * * @category models + * @since 4.0.0 */ export type HandlerRaw = ( request: Types.Simplify> -) => Effect +) => Effect | HttpServerResponse, Endpoint["~Error"]["Type"] | E, R> /** - * @since 4.0.0 + * Selects the endpoint with the specified name from a union of endpoints. + * * @category models + * @since 4.0.0 */ export type WithName = Extract /** - * @since 4.0.0 + * Removes endpoints with the specified name from a union of endpoints. + * * @category models + * @since 4.0.0 */ export type ExcludeName = Exclude /** - * @since 4.0.0 + * Derives the normal handler type for the endpoint with the specified name in an + * endpoint union. + * * @category models + * @since 4.0.0 */ export type HandlerWithName = Handler< WithName, @@ -625,8 +758,11 @@ export type HandlerWithName = > /** - * @since 4.0.0 + * Derives the raw handler type for the endpoint with the specified name in an + * endpoint union. + * * @category models + * @since 4.0.0 */ export type HandlerRawWithName = HandlerRaw< WithName, @@ -635,44 +771,62 @@ export type HandlerRawWithName > /** - * @since 4.0.0 + * Extracts the decoded success value type for the endpoint with the specified name + * in an endpoint union. + * * @category models + * @since 4.0.0 */ export type SuccessWithName = Success< WithName ->["Type"] +> extends infer S ? SuccessType : never /** - * @since 4.0.0 + * Computes the full error value union for the endpoint with the specified name in + * an endpoint union. + * * @category models + * @since 4.0.0 */ export type ErrorsWithName = Errors> /** - * @since 4.0.0 + * Computes the server-side service requirements for the endpoint with the + * specified name in an endpoint union. + * * @category models + * @since 4.0.0 */ export type ServerServicesWithName = ServerServices< WithName > /** - * @since 4.0.0 + * Extracts the middleware identifiers for the endpoint with the specified name in + * an endpoint union. + * * @category models + * @since 4.0.0 */ export type MiddlewareWithName = Middleware> /** - * @since 4.0.0 + * Extracts the middleware service requirements for the endpoint with the specified + * name in an endpoint union. + * * @category models + * @since 4.0.0 */ export type MiddlewareServicesWithName = MiddlewareServices< WithName > /** - * @since 4.0.0 + * Removes services provided by the HTTP router and the named endpoint's middleware + * from a service requirement union. + * * @category models + * @since 4.0.0 */ export type ExcludeProvidedWithName = ExcludeProvided< WithName, @@ -680,8 +834,11 @@ export type ExcludeProvidedWithName /** - * @since 4.0.0 + * Removes services provided by the HTTP router and endpoint middleware from a + * service requirement union. + * * @category models + * @since 4.0.0 */ export type ExcludeProvided = Exclude< R, @@ -690,8 +847,11 @@ export type ExcludeProvided = Exclude< > /** - * @since 4.0.0 + * Returns an endpoint type with the supplied path prefix prepended while + * preserving the endpoint's schemas, method, errors, and middleware. + * * @category models + * @since 4.0.0 */ export type AddPrefix = Endpoint extends HttpApiEndpoint< infer _Name, @@ -721,8 +881,11 @@ export type AddPrefix never /** - * @since 4.0.0 + * Returns an endpoint type with an additional error schema added to the endpoint's + * existing error schema union. + * * @category models + * @since 4.0.0 */ export type AddError = Endpoint extends HttpApiEndpoint< infer _Name, @@ -752,8 +915,11 @@ export type AddError = Endpoint exte never /** - * @since 4.0.0 + * Returns an endpoint type with additional middleware applied and the endpoint's + * middleware service requirements updated accordingly. + * * @category models + * @since 4.0.0 */ export type AddMiddleware = Endpoint extends HttpApiEndpoint< infer _Name, @@ -854,24 +1020,33 @@ function makeProto< } /** - * @since 4.0.0 + * Constraint for path parameter schemas: each parameter must encode to + * `string | undefined`, or the schema must encode to a record of those values. + * * @category constraints + * @since 4.0.0 */ export type ParamsConstraint = | Record> | Schema.Encoder, unknown> /** - * @since 4.0.0 + * Constraint for header schemas: each header must encode to `string | undefined`, + * or the schema must encode to a record of those values. + * * @category constraints + * @since 4.0.0 */ export type HeadersConstraint = | Record> | Schema.Encoder, unknown> /** - * @since 4.0.0 + * Constraint for query schemas: each field must encode to `string`, an array of + * strings, or `undefined`, or the schema must encode to a record of those values. + * * @category constraints + * @since 4.0.0 */ export type QueryConstraint = | Record | undefined, unknown>> @@ -885,38 +1060,60 @@ export type QueryConstraint = * - for body methods, payload may be any `Schema.Top` (or content-type keyed * schemas) and OpenAPI uses `requestBody` instead of `parameters` * - * @since 4.0.0 * @category constraints + * @since 4.0.0 */ export type PayloadConstraint = Method extends HttpMethod.NoBody ? Record< string, Schema.Encoder | undefined, unknown> > : - SuccessConstraint + Schema.Top | ReadonlyArray /** - * @since 4.0.0 + * Payload constraint used when automatic codecs are enabled: no-body methods + * accept field records for query-style encoding, while body methods accept one or + * more schemas. + * * @category constraints + * @since 4.0.0 */ export type PayloadConstraintCodecs = Method extends HttpMethod.NoBody ? Record : Schema.Top | ReadonlyArray /** - * @since 4.0.0 + * Constraint for success response schemas, allowing either a single schema or a + * readonly array of schemas. + * * @category constraints + * @since 4.0.0 */ export type SuccessConstraint = Schema.Top | ReadonlyArray /** - * @since 4.0.0 + * Constraint for error response schemas, allowing either a single schema or a + * readonly array of schemas. + * * @category constraints + * @since 4.0.0 */ export type ErrorConstraint = Schema.Top | ReadonlyArray +type ErrorNoStream = [ + Extract< + S extends ReadonlyArray ? S[number] : S, + HttpApiSchema.StreamSchema + > +] extends [never] ? S : never + /** - * @since 4.0.0 + * Creates endpoint constructors for a specific HTTP method. The resulting + * constructor builds an `HttpApiEndpoint` from a name, path, and optional request + * and response schemas, applying automatic JSON or string-tree codecs unless + * `disableCodecs` is enabled. + * * @category constructors + * @since 4.0.0 */ export const make = (method: Method): { < @@ -926,7 +1123,7 @@ export const make = (method: Method): { Query extends Schema.Top | Schema.Struct.Fields = never, Payload extends PayloadConstraintCodecs = never, Headers extends Schema.Top | Schema.Struct.Fields = never, - const Success extends Schema.Top | ReadonlyArray = HttpApiSchema.NoContent, + const Success extends SuccessConstraint = HttpApiSchema.NoContent, const Error extends Schema.Top | ReadonlyArray = never >( name: Name, @@ -938,7 +1135,7 @@ export const make = (method: Method): { readonly headers?: Headers | undefined readonly payload?: Payload | undefined readonly success?: Success | undefined - readonly error?: Error | undefined + readonly error?: (Error & ErrorNoStream>) | undefined } ): HttpApiEndpoint< Name, @@ -949,7 +1146,7 @@ export const make = (method: Method): { Method extends HttpMethod.WithBody ? Json> : StringTree>, StringTree : Headers>, - Json ? Success[number] : Success>, + JsonSuccessOrArray, Json ? Error[number] : Error> > < @@ -971,7 +1168,7 @@ export const make = (method: Method): { readonly headers?: Headers | undefined readonly payload?: Payload | undefined readonly success?: Success | undefined - readonly error?: Error | undefined + readonly error?: (Error & ErrorNoStream>) | undefined } ): HttpApiEndpoint< Name, @@ -981,7 +1178,7 @@ export const make = (method: Method): { Query extends Schema.Struct.Fields ? Schema.Struct : Query, ExtractSchemaOrArray, ExtractSchemaOrArray, - Success extends ReadonlyArray ? Success[number] : Success, + ExtractSuccessOrArray, Error extends ReadonlyArray ? Error[number] : Error > } => @@ -1004,7 +1201,7 @@ export const make = (method: Method): { readonly headers?: Headers | undefined readonly payload?: Payload | undefined readonly success?: Success | undefined - readonly error?: Error | undefined + readonly error?: (Error & ErrorNoStream>) | undefined } ): HttpApiEndpoint< Name, @@ -1016,7 +1213,7 @@ export const make = (method: Method): { : Payload extends ReadonlyArray ? Payload[number] : Payload, Headers extends Schema.Struct.Fields ? Schema.Struct : Headers, - Success extends ReadonlyArray ? Success[number] : Success, + ExtractSuccessOrArray, Error extends ReadonlyArray ? Error[number] : Error > => { const disableCodecs = options?.disableCodecs ?? false @@ -1029,8 +1226,8 @@ export const make = (method: Method): { query: ensureStruct(options?.query, transformStringTree), headers: ensureStruct(options?.headers, transformStringTree), payload: getPayload(options?.payload, method, disableCodecs), - success: getResponse(options?.success, disableCodecs), - error: getResponse(options?.error, disableCodecs), + success: getSuccessResponse(options?.success, method, disableCodecs), + error: getErrorResponse(options?.error, disableCodecs), annotations: Context.empty(), middlewares: new Set() }) @@ -1042,16 +1239,22 @@ type ExtractSchemaOrArray extends Schema.Codec {} /** - * @since 4.0.0 + * A schema codec that decodes and encodes the schema's value type through + * `Schema.StringTree` transport values. + * * @category Codecs + * @since 4.0.0 */ export interface StringTree extends Schema.Codec< @@ -1104,13 +1307,154 @@ function getPayload( return result } -function getResponse( +const reservedStreamFailureEvent = "effect/httpapi/stream/failure" + +function getSuccessResponse( success: Schema.Top | ReadonlyArray | undefined, + method: HttpMethod, disableCodecs: boolean ): Set { if (success === undefined) return new Set() - const arr = Arr.ensure(success) - return new Set(disableCodecs ? arr : arr.map(transformResponse)) + const schemas = Arr.ensure(success) + validateSuccessResponse(schemas, method) + return new Set( + disableCodecs ? + schemas : + schemas.map((schema) => HttpApiSchema.isStreamSchema(schema) ? schema : transformResponse(schema)) + ) +} + +function getErrorResponse( + error: Schema.Top | ReadonlyArray | undefined, + disableCodecs: boolean +): Set { + if (error === undefined) return new Set() + const schemas = Arr.ensure(error) + for (const schema of schemas) { + if (HttpApiSchema.isStreamSchema(schema)) { + throw new Error("Streaming schemas are not supported in error responses") + } + } + return new Set(disableCodecs ? schemas : schemas.map(transformResponse)) +} + +function validateSuccessResponse(schemas: ReadonlyArray, method: HttpMethod) { + const statuses = new Map + noContent: boolean + }>() + + for (const schema of schemas) { + if (HttpApiSchema.isStreamSchema(schema)) { + validateStreamSuccess(schema, method) + const status = HttpApiSchema.getStatusStream(schema) + const entry = getStatusEntry(statuses, status) + if (entry.stream !== undefined) { + throw new Error(`Multiple streaming success responses for status: ${status}`) + } + if (entry.noContent) { + throw new Error(`Cannot combine no-content and streaming success responses for status: ${status}`) + } + if (entry.bufferedContentTypes.has(normalizeResponseContentType(schema.contentType))) { + throw new Error( + `Cannot combine buffered and streaming success responses for status ${status} and content-type: ${schema.contentType}` + ) + } + statuses.set(status, { ...entry, stream: schema }) + } else { + const status = HttpApiSchema.getStatusSuccess(schema.ast) + const entry = getStatusEntry(statuses, status) + const noContent = HttpApiSchema.isNoContent(schema.ast) + if (entry.stream !== undefined) { + if (noContent) { + throw new Error(`Cannot combine no-content and streaming success responses for status: ${status}`) + } + const encoding = HttpApiSchema.getResponseEncoding(schema.ast) + if ( + normalizeResponseContentType(encoding.contentType) === normalizeResponseContentType(entry.stream.contentType) + ) { + throw new Error( + `Cannot combine buffered and streaming success responses for status ${status} and content-type: ${encoding.contentType}` + ) + } + } + if (!noContent) { + entry.bufferedContentTypes.add( + normalizeResponseContentType(HttpApiSchema.getResponseEncoding(schema.ast).contentType) + ) + } + entry.noContent = entry.noContent || noContent + } + } +} + +function normalizeResponseContentType(contentType: string): string { + const normalized = contentType.toLowerCase().trim() + const index = normalized.indexOf(";") + return index === -1 ? normalized : normalized.slice(0, index).trim() +} + +function getStatusEntry( + statuses: Map + noContent: boolean + }>, + status: number +) { + let entry = statuses.get(status) + if (entry === undefined) { + entry = { bufferedContentTypes: new Set(), noContent: false } + statuses.set(status, entry) + } + return entry +} + +function validateStreamSuccess(schema: HttpApiSchema.StreamSchema, method: HttpMethod) { + if (method === "HEAD") { + throw new Error("HEAD endpoints cannot declare streaming success responses") + } + if (HttpApiSchema.isStreamSse(schema) && hasReservedSseEventName(schema.events.ast)) { + throw new Error(`SSE event name is reserved: ${reservedStreamFailureEvent}`) + } +} + +function hasReservedSseEventName(ast: AST.AST): boolean { + return hasReservedEventName(AST.toEncoded(ast), new Set()) +} + +function hasReservedEventName(ast: AST.AST, seen: Set): boolean { + if (seen.has(ast)) return false + seen.add(ast) + if (AST.isUnion(ast)) { + return ast.types.some((type) => hasReservedEventName(type, seen)) + } + if (AST.isSuspend(ast)) { + return hasReservedEventName(ast.thunk(), seen) + } + if (!AST.isObjects(ast)) return false + const event = ast.propertySignatures.find((ps) => ps.name === "event") + return event !== undefined && hasReservedEventLiteral(event.type, seen) +} + +function hasReservedEventLiteral(ast: AST.AST, seen: Set): boolean { + if (seen.has(ast)) return false + seen.add(ast) + const encoded = AST.toEncoded(ast) + if (encoded !== ast) { + return hasReservedEventLiteral(encoded, seen) + } + if (AST.isLiteral(ast)) { + return ast.literal === reservedStreamFailureEvent + } + if (AST.isUnion(ast)) { + return ast.types.some((type) => hasReservedEventLiteral(type, seen)) + } + if (AST.isSuspend(ast)) { + return hasReservedEventLiteral(ast.thunk(), seen) + } + return false } function transformResponse(schema: Schema.Top): Schema.Top { @@ -1141,26 +1485,34 @@ function transformPayload(schema: Schema.Top, method: HttpMethod): Schema.Top { } /** - * @since 4.0.0 + * Creates a `GET` endpoint declaration. + * * @category constructors + * @since 4.0.0 */ export const get = make("GET") /** - * @since 4.0.0 + * Creates a `POST` endpoint declaration. + * * @category constructors + * @since 4.0.0 */ export const post = make("POST") /** - * @since 4.0.0 + * Creates a `PUT` endpoint declaration. + * * @category constructors + * @since 4.0.0 */ export const put = make("PUT") /** - * @since 4.0.0 + * Creates a `PATCH` endpoint declaration. + * * @category constructors + * @since 4.0.0 */ export const patch = make("PATCH") @@ -1168,20 +1520,26 @@ const del = make("DELETE") export { /** - * @since 4.0.0 + * Creates a `DELETE` endpoint declaration. + * * @category constructors + * @since 4.0.0 */ del as delete } /** - * @since 4.0.0 + * Creates a `HEAD` endpoint declaration. + * * @category constructors + * @since 4.0.0 */ export const head = make("HEAD") /** - * @since 4.0.0 + * Creates an `OPTIONS` endpoint declaration. + * * @category constructors + * @since 4.0.0 */ export const options = make("OPTIONS") diff --git a/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiError.ts b/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiError.ts index 8ae7220b034a3a33575ae0f1e30474139fd34ed7..a1f7bc6eea147969d574e817ac563ac7d8fba182 100644 --- a/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiError.ts +++ b/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiError.ts @@ -1,4 +1,12 @@ /** + * Built-in error schemas for common HTTP API failure responses. + * + * This module provides reusable `Schema.ErrorClass` values for common HTTP + * status codes, plus `HttpApiSchemaError` for request decoding failures raised + * by the HTTP API runtime. The status errors can be used in endpoint or + * middleware error declarations and are understood by builders, generated + * clients, reflection, and OpenAPI generation. + * * @since 4.0.0 */ import * as Data from "../../Data.ts" @@ -24,7 +32,10 @@ const notImplementedResponse = HttpServerResponse.empty({ status: 501 }) const serviceUnavailableResponse = HttpServerResponse.empty({ status: 503 }) /** - * @category Built-in errors + * Built-in HTTP API error for a `400 Bad Request` response. When used directly as + * a server response, it renders as an empty response with status 400. + * + * @category errors * @since 4.0.0 */ export class BadRequest extends Schema.ErrorClass("effect/HttpApiError/BadRequest")({ @@ -41,6 +52,9 @@ export class BadRequest extends Schema.ErrorClass("effect/HttpApiErr } /** + * No-content schema variant for `BadRequest`, decoding an empty 400 response into + * a `BadRequest` error value. + * * @category NoContent errors * @since 4.0.0 */ @@ -49,7 +63,10 @@ export const BadRequestNoContent = BadRequest.pipe(HttpApiSchema.asNoContent({ })) /** - * @category Built-in errors + * Built-in HTTP API error for a `401 Unauthorized` response. When used directly as + * a server response, it renders as an empty response with status 401. + * + * @category errors * @since 4.0.0 */ export class Unauthorized extends Schema.ErrorClass("effect/HttpApiError/Unauthorized")({ @@ -65,6 +82,9 @@ export class Unauthorized extends Schema.ErrorClass("effect/HttpAp } /** + * No-content schema variant for `Unauthorized`, decoding an empty 401 response + * into an `Unauthorized` error value. + * * @category NoContent errors * @since 4.0.0 */ @@ -73,7 +93,10 @@ export const UnauthorizedNoContent = Unauthorized.pipe(HttpApiSchema.asNoContent })) /** - * @category Built-in errors + * Built-in HTTP API error for a `403 Forbidden` response. When used directly as a + * server response, it renders as an empty response with status 403. + * + * @category errors * @since 4.0.0 */ export class Forbidden extends Schema.ErrorClass("effect/HttpApiError/Forbidden")({ @@ -89,6 +112,9 @@ export class Forbidden extends Schema.ErrorClass("effect/HttpApiError } /** + * No-content schema variant for `Forbidden`, decoding an empty 403 response into a + * `Forbidden` error value. + * * @category NoContent errors * @since 4.0.0 */ @@ -97,7 +123,10 @@ export const ForbiddenNoContent = Forbidden.pipe(HttpApiSchema.asNoContent({ })) /** - * @category Built-in errors + * Built-in HTTP API error for a `404 Not Found` response. When used directly as a + * server response, it renders as an empty response with status 404. + * + * @category errors * @since 4.0.0 */ export class NotFound extends Schema.ErrorClass("effect/HttpApiError/NotFound")({ @@ -113,6 +142,9 @@ export class NotFound extends Schema.ErrorClass("effect/HttpApiError/N } /** + * No-content schema variant for `NotFound`, decoding an empty 404 response into a + * `NotFound` error value. + * * @category NoContent errors * @since 4.0.0 */ @@ -121,7 +153,10 @@ export const NotFoundNoContent = NotFound.pipe(HttpApiSchema.asNoContent({ })) /** - * @category Built-in errors + * Built-in HTTP API error for a `405 Method Not Allowed` response. When used + * directly as a server response, it renders as an empty response with status 405. + * + * @category errors * @since 4.0.0 */ export class MethodNotAllowed extends Schema.ErrorClass("effect/HttpApiError/MethodNotAllowed")({ @@ -137,6 +172,9 @@ export class MethodNotAllowed extends Schema.ErrorClass("effec } /** + * No-content schema variant for `MethodNotAllowed`, decoding an empty 405 response + * into a `MethodNotAllowed` error value. + * * @category NoContent errors * @since 4.0.0 */ @@ -145,7 +183,10 @@ export const MethodNotAllowedNoContent = MethodNotAllowed.pipe(HttpApiSchema.asN })) /** - * @category Built-in errors + * Built-in HTTP API error for a `406 Not Acceptable` response. When used directly + * as a server response, it renders as an empty response with status 406. + * + * @category errors * @since 4.0.0 */ export class NotAcceptable extends Schema.ErrorClass("effect/HttpApiError/NotAcceptable")({ @@ -161,6 +202,9 @@ export class NotAcceptable extends Schema.ErrorClass("effect/Http } /** + * No-content schema variant for `NotAcceptable`, decoding an empty 406 response + * into a `NotAcceptable` error value. + * * @category NoContent errors * @since 4.0.0 */ @@ -169,7 +213,10 @@ export const NotAcceptableNoContent = NotAcceptable.pipe(HttpApiSchema.asNoConte })) /** - * @category Built-in errors + * Built-in HTTP API error for a `408 Request Timeout` response. When used directly + * as a server response, it renders as an empty response with status 408. + * + * @category errors * @since 4.0.0 */ export class RequestTimeout extends Schema.ErrorClass("effect/HttpApiError/RequestTimeout")({ @@ -185,6 +232,9 @@ export class RequestTimeout extends Schema.ErrorClass("effect/Ht } /** + * No-content schema variant for `RequestTimeout`, decoding an empty 408 response + * into a `RequestTimeout` error value. + * * @category NoContent errors * @since 4.0.0 */ @@ -193,7 +243,10 @@ export const RequestTimeoutNoContent = RequestTimeout.pipe(HttpApiSchema.asNoCon })) /** - * @category Built-in errors + * Built-in HTTP API error for a `409 Conflict` response. When used directly as a + * server response, it renders as an empty response with status 409. + * + * @category errors * @since 4.0.0 */ export class Conflict extends Schema.ErrorClass("effect/HttpApiError/Conflict")({ @@ -209,15 +262,21 @@ export class Conflict extends Schema.ErrorClass("effect/HttpApiError/C } /** - * @since 4.0.0 + * No-content schema variant for `Conflict`, decoding an empty 409 response into a + * `Conflict` error value. + * * @category NoContent errors + * @since 4.0.0 */ export const ConflictNoContent = Conflict.pipe(HttpApiSchema.asNoContent({ decode: () => new Conflict({}) })) /** - * @category Built-in errors + * Built-in HTTP API error for a `410 Gone` response. When used directly as a + * server response, it renders as an empty response with status 410. + * + * @category errors * @since 4.0.0 */ export class Gone extends Schema.ErrorClass("effect/HttpApiError/Gone")({ @@ -233,6 +292,9 @@ export class Gone extends Schema.ErrorClass("effect/HttpApiError/Gone")({ } /** + * No-content schema variant for `Gone`, decoding an empty 410 response into a + * `Gone` error value. + * * @category NoContent errors * @since 4.0.0 */ @@ -241,7 +303,10 @@ export const GoneNoContent = Gone.pipe(HttpApiSchema.asNoContent({ })) /** - * @category Built-in errors + * Built-in HTTP API error for a `500 Internal Server Error` response. When used + * directly as a server response, it renders as an empty response with status 500. + * + * @category errors * @since 4.0.0 */ export class InternalServerError @@ -258,6 +323,9 @@ export class InternalServerError } /** + * No-content schema variant for `InternalServerError`, decoding an empty 500 + * response into an `InternalServerError` error value. + * * @category NoContent errors * @since 4.0.0 */ @@ -266,7 +334,10 @@ export const InternalServerErrorNoContent = InternalServerError.pipe(HttpApiSche })) /** - * @category Built-in errors + * Built-in HTTP API error for a `501 Not Implemented` response. When used directly + * as a server response, it renders as an empty response with status 501. + * + * @category errors * @since 4.0.0 */ export class NotImplemented extends Schema.ErrorClass("effect/HttpApiError/NotImplemented")({ @@ -281,6 +352,9 @@ export class NotImplemented extends Schema.ErrorClass("effect/Ht } /** + * No-content schema variant for `NotImplemented`, decoding an empty 501 response + * into a `NotImplemented` error value. + * * @category NoContent errors * @since 4.0.0 */ @@ -289,7 +363,10 @@ export const NotImplementedNoContent = NotImplemented.pipe(HttpApiSchema.asNoCon })) /** - * @category Built-in errors + * Built-in HTTP API error for a `503 Service Unavailable` response. When used + * directly as a server response, it renders as an empty response with status 503. + * + * @category errors * @since 4.0.0 */ export class ServiceUnavailable @@ -306,6 +383,9 @@ export class ServiceUnavailable } /** + * No-content schema variant for `ServiceUnavailable`, decoding an empty 503 + * response into a `ServiceUnavailable` error value. + * * @category NoContent errors * @since 4.0.0 */ @@ -314,19 +394,27 @@ export const ServiceUnavailableNoContent = ServiceUnavailable.pipe(HttpApiSchema })) /** - * @category Parsing errors + * Type-level identifier used to mark `HttpApiSchemaError` values. + * + * @category type IDs * @since 4.0.0 */ export type HttpApiSchemaErrorTypeId = "~effect/httpapi/HttpApiError/HttpApiSchemaError" /** - * @category Parsing errors + * Runtime identifier used to mark and detect `HttpApiSchemaError` values. + * + * @category type IDs * @since 4.0.0 */ export const HttpApiSchemaErrorTypeId: HttpApiSchemaErrorTypeId = "~effect/httpapi/HttpApiError/HttpApiSchemaError" /** - * @category Parsing errors + * Error raised when an HTTP API request component fails schema decoding. It records + * which component failed and responds as an empty `400 Bad Request` when rendered + * as a server response. + * + * @category errors * @since 4.0.0 */ export class HttpApiSchemaError extends Data.TaggedClass("HttpApiSchemaError")<{ diff --git a/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiGroup.ts b/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiGroup.ts index e2c2fd0b263266b463bd2a6ec6e7c5d3a6991eff..9634518342f8cd39608e62f3751e51f1b1d11059 100644 --- a/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiGroup.ts +++ b/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiGroup.ts @@ -1,4 +1,13 @@ /** + * Defines named groups of HTTP API endpoints. + * + * A group collects endpoints that belong to the same resource or feature area + * inside an `HttpApi`. Builders, generated clients, URL builders, and OpenAPI + * generation read the same group value, including its identifier, endpoints, + * annotations, and `topLevel` flag. This module includes helpers for creating + * groups, adding endpoints, prefixing paths, applying middleware, annotating + * groups or endpoints, and deriving builder or client types. + * * @since 4.0.0 */ import type { NonEmptyReadonlyArray } from "../../Array.ts" @@ -13,19 +22,24 @@ import type * as HttpApiMiddleware from "./HttpApiMiddleware.ts" const TypeId = "~effect/httpapi/HttpApiGroup" /** - * @since 4.0.0 + * Returns `true` when a value is an `HttpApiGroup`, narrowing the value to the + * group interface. + * * @category guards + * @since 4.0.0 */ export const isHttpApiGroup = (u: unknown): u is Any => Predicate.hasProperty(u, TypeId) /** - * An `HttpApiGroup` is a collection of `HttpApiEndpoint`s. You can use an `HttpApiGroup` to - * represent a portion of your domain. + * An `HttpApiGroup` is a named collection of `HttpApiEndpoint`s that represents + * a portion of your domain. * - * The endpoints can be implemented later using the `HttpApiBuilder.group` api. + * **Details** + * + * Endpoint implementations can be provided later with `HttpApiBuilder.group`. * - * @since 4.0.0 * @category models + * @since 4.0.0 */ export interface HttpApiGroup< out Id extends string, @@ -43,7 +57,7 @@ export interface HttpApiGroup< /** * Add an `HttpApiEndpoint` to an `HttpApiGroup`. */ - add>( + add>( ...endpoints: A ): HttpApiGroup @@ -56,9 +70,11 @@ export interface HttpApiGroup< ): HttpApiGroup, TopLevel> /** - * Add an `HttpApiMiddleware` to the `HttpApiGroup`. + * Adds an `HttpApiMiddleware` to every endpoint currently in the group. + * + * **Gotchas** * - * Endpoints added after this api is called **will not** have the middleware + * Endpoints added after this method is called do not have the middleware * applied. */ middleware(middleware: Context.Key): HttpApiGroup< @@ -78,25 +94,30 @@ export interface HttpApiGroup< annotate(key: Context.Key, value: S): HttpApiGroup /** - * For each endpoint in an `HttpApiGroup`, update the annotations with a new - * Context. + * Merges the provided context into every endpoint currently in the group. * - * Note that this will only update the annotations before this api is called. + * **Gotchas** + * + * Endpoints added after this method is called do not have these annotations. */ annotateEndpointsMerge(annotations: Context.Context): HttpApiGroup /** - * For each endpoint in an `HttpApiGroup`, add an annotation. + * Adds an annotation to every endpoint currently in the group. + * + * **Gotchas** * - * Note that this will only add the annotation to the endpoints before this api - * is called. + * Endpoints added after this method is called do not have this annotation. */ annotateEndpoints(key: Context.Key, value: S): HttpApiGroup } /** - * @since 4.0.0 + * Type-level identity for a group within an HTTP API, pairing the API id with the + * group name for service derivation. + * * @category models + * @since 4.0.0 */ export interface ApiGroup { readonly _: unique symbol @@ -105,8 +126,11 @@ export interface ApiGroup { } /** - * @since 4.0.0 + * A widened `HttpApiGroup` type used when the concrete group name, endpoints, and + * top-level flag are not needed. + * * @category models + * @since 4.0.0 */ export interface Any { readonly [TypeId]: typeof TypeId @@ -116,92 +140,124 @@ export interface Any { } /** - * @since 4.0.0 + * A widened group type that preserves concrete runtime properties such as + * identifier, key, top-level status, endpoints, and annotations. + * * @category models + * @since 4.0.0 */ export type AnyWithProps = HttpApiGroup /** - * @since 4.0.0 + * Derives the API-specific `ApiGroup` service identity for an HTTP API group. + * * @category models + * @since 4.0.0 */ export type ToService = A extends HttpApiGroup ? ApiGroup : never /** - * @since 4.0.0 + * Selects the group with the specified identifier from a union of groups. + * * @category models + * @since 4.0.0 */ export type WithName = Extract /** - * @since 4.0.0 + * Extracts the identifier literal from an `HttpApiGroup`. + * * @category models + * @since 4.0.0 */ export type Name = Group extends HttpApiGroup ? _Name : never /** - * @since 4.0.0 + * Extracts the endpoint union contained in an `HttpApiGroup`. + * * @category models + * @since 4.0.0 */ export type Endpoints = Group extends HttpApiGroup ? _Endpoints : never /** - * @since 4.0.0 + * Computes the services required to encode error responses for every endpoint in a + * group. + * * @category models + * @since 4.0.0 */ export type ErrorServicesEncode = HttpApiEndpoint.ErrorServicesEncode> /** - * @since 4.0.0 + * Computes the services required to decode error responses for every endpoint in a + * group. + * * @category models + * @since 4.0.0 */ export type ErrorServicesDecode = HttpApiEndpoint.ErrorServicesDecode> /** - * @since 4.0.0 + * Computes the middleware error union for every endpoint in a group. + * * @category models + * @since 4.0.0 */ export type MiddlewareError = HttpApiEndpoint.MiddlewareError> /** - * @since 4.0.0 + * Computes the services provided by middleware attached to any endpoint in a + * group. + * * @category models + * @since 4.0.0 */ export type MiddlewareProvides = HttpApiEndpoint.MiddlewareProvides> /** - * @since 4.0.0 + * Computes the client-side middleware services required by endpoints in a group. + * * @category models + * @since 4.0.0 */ export type MiddlewareClient = HttpApiEndpoint.MiddlewareClient> /** - * @since 4.0.0 + * Extracts the runtime services required by middleware attached to the endpoints in an `HttpApiGroup`. + * * @category models + * @since 4.0.0 */ export type MiddlewareServices = HttpApiEndpoint.MiddlewareServices> /** - * @since 4.0.0 + * Selects the endpoints in a group whose `name` matches the provided endpoint name. + * * @category models + * @since 4.0.0 */ export type EndpointsWithName = Endpoints> /** - * @since 4.0.0 + * Computes the schema encoding and decoding services required by clients for all endpoints in a group. + * * @category models + * @since 4.0.0 */ export type ClientServices = Group extends HttpApiGroup ? HttpApiEndpoint.ClientServices<_Endpoints> : never /** - * @since 4.0.0 + * Returns the type of a group after adding the supplied path prefix to each endpoint in the group. + * * @category models + * @since 4.0.0 */ export type AddPrefix = Group extends HttpApiGroup ? @@ -209,8 +265,10 @@ export type AddPrefix = Group extends : never /** - * @since 4.0.0 + * Returns the type of a group after applying a middleware identifier to every endpoint in the group. + * * @category models + * @since 4.0.0 */ export type AddMiddleware = Group extends HttpApiGroup ? @@ -301,13 +359,16 @@ const makeProto = < } /** - * An `HttpApiGroup` is a collection of `HttpApiEndpoint`s. You can use an `HttpApiGroup` to - * represent a portion of your domain. + * Creates an empty `HttpApiGroup` with the supplied identifier. * - * The endpoints can be implemented later using the `HttpApiBuilder.group` api. + * **Details** + * + * Add endpoints with `add`, provide implementations with `HttpApiBuilder.group`, + * and set `topLevel` when the generated client should expose endpoint methods + * directly instead of nesting them under the group name. * - * @since 4.0.0 * @category constructors + * @since 4.0.0 */ export const make = (identifier: Id, options?: { readonly topLevel?: TopLevel | undefined diff --git a/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiMiddleware.ts b/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiMiddleware.ts index 500cd7d76dacdf050eb101c698a7972097a960ee..2773142925e9a95676f6d3cfd4747b3e23f8c5b0 100644 --- a/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiMiddleware.ts +++ b/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiMiddleware.ts @@ -1,6 +1,18 @@ /** + * Declares middleware for schema-driven HTTP APIs. + * + * HTTP API middleware wraps endpoint execution on the server and, when the API + * requires it, can also wrap requests made by generated clients. It is used for + * cross-cutting behavior that belongs to the API contract, such as + * authentication, authorization, logging, tracing, rate limiting, + * request-scoped services, schema-error handling, and client request + * decoration. This module defines the middleware service keys and helpers used + * by `HttpApi` declarations. + * * @since 4.0.0 */ +/** @effect-diagnostics floatingEffect:skip-file */ +/** @effect-diagnostics classSelfMismatch:off */ import * as Context from "../../Context.ts" import * as Effect from "../../Effect.ts" import * as Layer from "../../Layer.ts" @@ -23,8 +35,10 @@ const TypeId = "~effect/httpapi/HttpApiMiddleware" const SecurityTypeId = "~effect/httpapi/HttpApiMiddleware/Security" /** - * @since 4.0.0 + * Returns `true` when an HTTP API middleware service is security middleware. + * * @category guards + * @since 4.0.0 */ export const isSecurity = (u: AnyService): u is AnyServiceSecurity => hasProperty(u, SecurityTypeId) @@ -35,8 +49,16 @@ type ErrorSchemaFromConstraint = E extends ReadonlyArray ? E[numb : never /** - * @since 4.0.0 + * Server-side middleware function for an HTTP API endpoint. + * + * **Details** + * + * It receives the endpoint response effect and endpoint/group metadata, and returns + * a new response effect that may require additional services and fail with the + * middleware's declared error schema. + * * @category models + * @since 4.0.0 */ export type HttpApiMiddleware = ( httpEffect: Effect.Effect, @@ -47,8 +69,15 @@ export type HttpApiMiddleware = ( ) => Effect.Effect["Type"], Requires | HttpRouter.Provided> /** - * @since 4.0.0 + * Server-side middleware implementations for one or more security schemes. + * + * **Details** + * + * Each property handles the credential decoded for that scheme and wraps the + * endpoint response effect with the middleware's declared requirements and errors. + * * @category models + * @since 4.0.0 */ export type HttpApiMiddlewareSecurity< Security extends Record, @@ -71,8 +100,15 @@ export type HttpApiMiddlewareSecurity< } /** - * @since 4.0.0 + * Client-side middleware function for generated HTTP API clients. + * + * **Details** + * + * It receives endpoint/group metadata, the outgoing request, and a `next` function + * for continuing the request pipeline. + * * @category models + * @since 4.0.0 */ export interface HttpApiMiddlewareClient<_E, CE, R> { (options: { @@ -86,8 +122,10 @@ export interface HttpApiMiddlewareClient<_E, CE, R> { } /** - * @since 4.0.0 + * Client-side service marker required when a middleware declares `requiredForClient`. + * * @category models + * @since 4.0.0 */ export interface ForClient { readonly _: unique symbol @@ -95,8 +133,10 @@ export interface ForClient { } /** - * @since 4.0.0 + * Base service key shape for HTTP API middleware services, including provided services, declared error schemas, and client requirements. + * * @category models + * @since 4.0.0 */ export interface AnyService extends Context.Key { readonly [TypeId]: typeof TypeId @@ -107,8 +147,10 @@ export interface AnyService extends Context.Key { } /** - * @since 4.0.0 + * Middleware service key shape for security middleware, including the security schemes handled by the service. + * * @category models + * @since 4.0.0 */ export interface AnyServiceSecurity extends AnyService { readonly [SecurityTypeId]: typeof SecurityTypeId @@ -116,8 +158,10 @@ export interface AnyServiceSecurity extends AnyService { } /** - * @since 4.0.0 + * Type-level identifier carried by middleware services to track provided services, required services, errors, client errors, and client requirements. + * * @category models + * @since 4.0.0 */ export interface AnyId { readonly [TypeId]: { @@ -130,39 +174,51 @@ export interface AnyId { } /** - * @since 4.0.0 + * Extracts the services provided by a middleware identifier. + * * @category models + * @since 4.0.0 */ export type Provides = A extends { readonly [TypeId]: { readonly provides: infer P } } ? P : never /** - * @since 4.0.0 + * Extracts the services required to run a middleware implementation. + * * @category models + * @since 4.0.0 */ export type Requires = A extends { readonly [TypeId]: { readonly requires: infer R } } ? R : never /** - * @since 4.0.0 + * Applies a middleware's service changes to an existing requirement type by removing services it provides and adding services it requires. + * * @category models + * @since 4.0.0 */ export type ApplyServices = Exclude> | Requires /** - * @since 4.0.0 + * Extracts the schema or schema union used for errors declared by a middleware identifier. + * * @category models + * @since 4.0.0 */ export type ErrorSchema = A extends { readonly [TypeId]: { readonly error: infer E } } ? ErrorSchemaFromConstraint : never /** - * @since 4.0.0 + * Extracts the decoded error type declared by a middleware identifier. + * * @category models + * @since 4.0.0 */ export type Error = ErrorSchema["Type"] /** - * @since 4.0.0 + * Extracts the client-side error type for middleware that is required on generated clients. + * * @category models + * @since 4.0.0 */ export type ClientError = A extends { readonly [TypeId]: { @@ -173,8 +229,10 @@ export type ClientError = A extends { : never /** - * @since 4.0.0 + * Computes the client-side service marker required for middleware that must also run in generated clients. + * * @category models + * @since 4.0.0 */ export type MiddlewareClient = A extends { readonly [TypeId]: { @@ -184,20 +242,31 @@ export type MiddlewareClient = A extends { : never /** - * @since 4.0.0 + * Extracts the schema services required to encode errors declared by a middleware identifier. + * * @category models + * @since 4.0.0 */ export type ErrorServicesEncode = ErrorSchema["EncodingServices"] /** - * @since 4.0.0 + * Extracts the schema services required to decode errors declared by a middleware identifier. + * * @category models + * @since 4.0.0 */ export type ErrorServicesDecode = ErrorSchema["DecodingServices"] /** + * Class type produced by `Service` for an HTTP API middleware service. + * + * **Details** + * + * It combines a `Context.Service` class with the middleware metadata used by + * endpoints, builders, and generated clients. + * + * @category schemas * @since 4.0.0 - * @category Schemas */ export type ServiceClass< Self, @@ -236,8 +305,16 @@ export type ServiceClass< }) /** + * Creates a `Context.Service` class for an HTTP API middleware implementation. + * + * **When to use** + * + * Use when you need an HTTP API middleware service whose configuration declares + * required services, provided services, typed error schemas, security schemes, + * client errors, or a matching client middleware requirement. + * + * @category schemas * @since 4.0.0 - * @category Schemas */ export const Service = < Self, @@ -280,7 +357,6 @@ export const Service = < const creationError = new Err() Err.stackTraceLimit = limit - /** @effect-diagnostics-next-line classSelfMismatch:off */ class Service extends Context.Service()(id) {} const self = Service as any Object.defineProperty(Service, "stack", { @@ -307,7 +383,15 @@ function getError(error: ErrorConstraint | undefined): ReadonlySet { } /** - * Implement a middleware Layer that transforms `SchemaError`'s. + * Creates a middleware layer that transforms `HttpApiSchemaError` failures. + * + * **Details** + * + * The middleware catches schema errors produced while running an endpoint and uses + * the supplied `transform` function to convert them into the middleware's declared + * error schema. + * + * **Example** (Mapping schema errors to custom errors) * * ```ts * import { Effect, Schema } from "effect" @@ -328,8 +412,8 @@ function getError(error: ErrorConstraint | undefined): ReadonlySet { * ) * ``` * - * @since 4.0.0 * @category SchemaError transform + * @since 4.0.0 */ export const layerSchemaErrorTransform = ( service: Context.Service>, @@ -356,8 +440,15 @@ export const layerSchemaErrorTransform = ( tag: Context.Key, diff --git a/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiScalar.ts b/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiScalar.ts index d0ca249930dae8f3488e6b92064a3d70b01957ce..b046175618c2d7cea3083d90ffb059522ecc0e81 100644 --- a/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiScalar.ts +++ b/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiScalar.ts @@ -1,4 +1,11 @@ /** + * Scalar documentation UI for declarative `HttpApi` contracts. + * + * Use this module to mount a browser-based API reference on an `HttpRouter` + * without writing or storing a separate OpenAPI file. The route renders an HTML + * page containing the OpenAPI document produced from the supplied `HttpApi` and + * boots Scalar in the browser. + * * @since 4.0.0 */ import * as Effect from "../../Effect.ts" @@ -12,8 +19,10 @@ import * as internal from "./internal/httpApiScalar.ts" import * as OpenApi from "./OpenApi.ts" /** + * Theme preset identifier accepted by the Scalar API reference UI. + * + * @category models * @since 4.0.0 - * @category model */ export type ScalarThemeId = | "alternate" @@ -30,10 +39,15 @@ export type ScalarThemeId = | "none" /** - * @see https://github.com/scalar/scalar/blob/main/documentation/configuration.md + * Configuration passed to the embedded Scalar API reference UI. + * + * **Details** * + * This configuration follows Scalar's API reference configuration: + * https://github.com/scalar/scalar/blob/main/documentation/configuration.md + * + * @category models * @since 4.0.0 - * @category model */ export type ScalarConfig = { /** A string to use one of the color presets */ @@ -42,24 +56,26 @@ export type ScalarConfig = { layout?: "modern" | "classic" /** URL to a request proxy for the API client */ proxyUrl?: string + /** Browser JavaScript function expression used by Scalar for documents and test requests */ + customFetch?: string /** Whether to show the sidebar */ showSidebar?: boolean /** * Whether to show models in the sidebar, search, and content. * - * Default: `false` + * @default false */ hideModels?: boolean /** * Whether to show the "Test Request" button. * - * Default: `false` + * @default false */ hideTestRequestButton?: boolean /** * Whether to show the sidebar search bar. * - * Default: `false` + * @default false */ hideSearch?: boolean /** Whether dark mode is on or off initially (light mode) */ @@ -71,37 +87,56 @@ export type ScalarConfig = { /** * Path to a favicon image. * - * Default: `undefined` - * Example: "/favicon.svg" + * **Example** (Relative favicon) + * + * ```ts + * const favicon = "/favicon.svg" + * ``` + * + * @default undefined */ favicon?: string /** Custom CSS to be added to the page */ customCss?: string /** - * The baseServerURL is used when the spec servers are relative paths and we are using SSR. - * On the client we can grab the window.location.origin but on the server we need - * to use this prop. + * Origin used when the OpenAPI document contains relative server URLs and is + * rendered during SSR. + * + * **Details** * - * Default: `undefined` - * Example: "http://localhost:3000" + * Browsers can derive the origin from `window.location.origin`; server + * rendering needs this value supplied explicitly. + * + * **Example** (Local server URL) + * + * ```ts + * const baseServerURL = "http://localhost:3000" + * ``` + * + * @default undefined */ baseServerURL?: string /** - * We use Inter and JetBrains Mono as the default fonts. If you want to use your own fonts, set this to false. + * Whether Scalar loads its default Inter and JetBrains Mono fonts. + * + * **Details** * - * Default: `true` + * Set this to `false` when supplying custom fonts. + * + * @default true */ withDefaultFonts?: boolean /** - * By default we only open the relevant tag based on the url, however if you want all the tags open by default then set this configuration option. + * Whether all tags are open by default instead of only the tag matching the + * current URL. * - * Default: `false` + * @default false */ defaultOpenAllTags?: boolean /** * Whether to display the operation ID in the operation reference. * - * Default: `false` + * @default false */ showOperationId?: boolean } @@ -122,9 +157,10 @@ const makeHandler = (options readonly scalar: ScalarConfig | undefined }) => { const spec = OpenApi.fromApi(options.api) + const { customFetch, ...scalar } = options.scalar ?? {} const scalarConfig = { _integration: "html", - ...options.scalar + ...scalar } const response = HttpServerResponse.html(` @@ -146,12 +182,7 @@ const makeHandler = (options content="width=device-width, initial-scale=1" /> - - +

${ options.source._tag === "Cdn" ? `` : `` } + `) return Effect.succeed(response) } /** - * @since 4.0.0 + * Mounts a Scalar API reference page for an `HttpApi` using the bundled Scalar script. + * + * **Details** + * + * The route serves the OpenAPI specification generated from the API at the + * configured path, defaulting to `/docs`. + * * @category layers + * @since 4.0.0 */ export const layer = ( api: HttpApi.HttpApi, @@ -188,8 +235,16 @@ export const layer = ( })) /** - * @since 4.0.0 + * Mounts a Scalar API reference page for an `HttpApi` that loads Scalar from jsDelivr. + * + * **Details** + * + * The route serves the OpenAPI specification generated from the API at the + * configured path, defaulting to `/docs`; `version` selects the Scalar package + * version loaded from the CDN. + * * @category layers + * @since 4.0.0 */ export const layerCdn = ( api: HttpApi.HttpApi, diff --git a/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiSchema.ts b/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiSchema.ts index 5f4222987d202de15f278ffb0afb9544b8dff77b..f2920365cf0328146523ce2e2dba04d6a8809a4a 100644 --- a/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiSchema.ts +++ b/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiSchema.ts @@ -1,36 +1,21 @@ /** - * HttpApiSchema provides helpers to annotate Effect Schema values with HTTP API metadata - * (status codes and payload/response encodings) used by the HttpApi builder, client, - * and OpenAPI generation. - * - * Mental model: - * - A "Schema" is the base validation/encoding description from `Schema`. - * - An "Encoding" tells HttpApi how to serialize/parse a payload or response body. - * - A "Status" is metadata that chooses the HTTP response status code. - * - "Empty" schemas represent responses with no body (204/201/202 or custom). - * - "NoContent" schemas can still decode into a value via {@link asNoContent}. - * - Multipart is a payload-only encoding for file-like form data. - * - * Common tasks: - * - Set a response status on a schema -> {@link status} - * - Declare an empty response -> {@link Empty}, {@link NoContent}, {@link Created}, {@link Accepted} - * - Decode an empty response into a value -> {@link asNoContent} - * - Force a specific encoding -> {@link asJson}, {@link asFormUrlEncoded}, {@link asText}, {@link asUint8Array} - * - Mark multipart payloads -> {@link asMultipart}, {@link asMultipartStream} - * - * Gotchas: - * - If you don't set an encoding, HttpApi assumes JSON by default. - * - {@link asFormUrlEncoded} expects the schema's encoded type to be a record of strings. - * - {@link asText} expects the encoded type to be `string`, and {@link asUint8Array} expects `Uint8Array`. - * - Multipart encodings are intended for request payloads; response multipart is not supported. - * - These helpers annotate schemas; they don't perform validation or IO by themselves. + * Attaches HTTP API metadata to Effect Schema values. + * + * This module is the schema-side bridge for HttpApi endpoint builders, + * generated clients, and OpenAPI support. It does not define routes or perform + * IO. Instead, the helpers annotate schemas so the surrounding HTTP API tooling + * can choose response status codes, content types, body codecs, multipart + * handling, and no-body response behavior. * * @since 4.0.0 */ import { constVoid, type LazyArg } from "../../Function.ts" +import * as Predicate from "../../Predicate.ts" import * as Schema from "../../Schema.ts" -import * as AST from "../../SchemaAST.ts" -import * as Transformation from "../../SchemaTransformation.ts" +import * as SchemaAST from "../../SchemaAST.ts" +import * as SchemaTransformation from "../../SchemaTransformation.ts" +import * as Stream from "../../Stream.ts" +import type * as Sse from "../encoding/Sse.ts" import { hasBody, type HttpMethod } from "../http/HttpMethod.ts" import type * as Multipart_ from "../http/Multipart.ts" @@ -49,13 +34,18 @@ declare module "../../Schema.ts" { } /** - * @internal + * HTTP API body encoding metadata used by payloads and responses. + * + * @category models + * @since 4.0.0 */ export type Encoding = PayloadEncoding | ResponseEncoding /** - * Encodings for payloads - * @internal + * HTTP API request payload encoding metadata. + * + * @category models + * @since 4.0.0 */ export type PayloadEncoding = | { @@ -70,8 +60,10 @@ export type PayloadEncoding = } /** - * Encodings for responses - * @internal + * HTTP API response body encoding metadata. + * + * @category models + * @since 4.0.0 */ export type ResponseEncoding = { readonly _tag: "Json" | "FormUrlEncoded" | "Uint8Array" | "Text" @@ -143,6 +135,8 @@ const statusCodeByLiteral = { NetworkAuthenticationRequired: 511 } as const +const StreamSchemaTypeId = "~effect/httpapi/HttpApiSchema/Stream" + /** * Common HTTP status code literals accepted by {@link status}. * @@ -152,30 +146,33 @@ const statusCodeByLiteral = { export type StatusLiteral = keyof typeof statusCodeByLiteral /** - * A convenience function to set the HTTP status code of a schema. + * Sets the HTTP status code of a schema. * - * This is equivalent to calling `.annotate({ httpApiStatus: code })` on the schema. + * **Details** * - * You can pass either a numeric status code (for example, `201`) or a common - * literal name (for example, `"Created"`). + * This is equivalent to calling `.annotate({ httpApiStatus: code })` on the + * schema. You can pass either a numeric status code (for example, `201`) or a + * common literal name (for example, `"Created"`). * * @category status * @since 4.0.0 */ -export function status(code: number): (self: S) => S["Rebuild"] -export function status(code: StatusLiteral): (self: S) => S["Rebuild"] +export function status(code: number): { + (self: S): S["Rebuild"] +} +export function status(code: StatusLiteral): { + (self: S): S["Rebuild"] +} export function status(code: number | StatusLiteral) { const statusCode = typeof code === "string" ? statusCodeByLiteral[code] : code - return (self: S): S["Rebuild"] => { - return self.annotate({ httpApiStatus: statusCode }) - } + return (self: S): S["Rebuild"] => self.annotate({ httpApiStatus: statusCode }) } /** * Creates a void schema with the given HTTP status code. * This is used to represent empty responses with a specific status code. * - * @see {@link asEmpty} for creating a no content response that can be decoded into a meaningful value on the client side. + * @see {@link NoContent} for the predefined 204 no content schema. * * @category Empty * @since 4.0.0 @@ -183,27 +180,31 @@ export function status(code: number | StatusLiteral) { export const Empty = (code: number): Schema.Void => Schema.Void.pipe(status(code)) /** + * Type of the `NoContent` schema, a void schema annotated with HTTP status code 204. + * + * @category models * @since 4.0.0 */ export interface NoContent extends Schema.Void {} /** - * A void schema with the HTTP status code 204. - * This is used to represent empty responses with the status code 204. + * Schema for empty HTTP responses with status code 204. * - * @since 4.0.0 * @category Empty + * @since 4.0.0 */ export const NoContent: NoContent = Empty(204) /** + * Type of the `Created` schema, a void schema annotated with HTTP status code 201. + * + * @category models * @since 4.0.0 */ export interface Created extends Schema.Void {} /** - * A void schema with the HTTP status code 201. - * This is used to represent empty responses with the status code 201. + * Schema for empty HTTP responses with status code 201. * * @category Empty * @since 4.0.0 @@ -211,13 +212,15 @@ export interface Created extends Schema.Void {} export const Created: Created = Empty(201) /** + * Type of the `Accepted` schema, a void schema annotated with HTTP status code 202. + * + * @category models * @since 4.0.0 */ export interface Accepted extends Schema.Void {} /** - * A void schema with the HTTP status code 202. - * This is used to represent empty responses with the status code 202. + * Schema for empty HTTP responses with status code 202. * * @category Empty * @since 4.0.0 @@ -225,19 +228,25 @@ export interface Accepted extends Schema.Void {} export const Accepted: Accepted = Empty(202) /** + * Schema type returned by `asNoContent`, encoding as `void` while decoding to the original schema type. + * + * @category schemas * @since 4.0.0 */ export interface asNoContent extends Schema.decodeTo, Schema.Void> {} /** - * Marks a schema as a no content response. + * Marks a schema as a no-content response while preserving a decoded client value. + * + * **Details** * - * The `decode` function is used to decode the response body on the client side into a meaningful value. + * The server encodes the response as `void`; generated clients call `decode` to + * produce the schema's decoded value when the response has no body. * * @see {@link NoContent} for a void schema with the status code 204. * @see {@link Empty} for creating a void schema with a specific status code. * - * @category Encoding + * @category encoding * @since 4.0.0 */ export function asNoContent(options: { @@ -247,7 +256,7 @@ export function asNoContent(options: { return Schema.Void.pipe( Schema.decodeTo( Schema.toType(self), - Transformation.transform({ + SchemaTransformation.transform({ decode: options.decode, encode: constVoid }) @@ -256,17 +265,263 @@ export function asNoContent(options: { } } +type StreamMode = "sse" | "uint8array" + +/** + * Mode describing whether an SSE stream emits full events or raw data values. + * + * @category models + * @since 4.0.0 + */ +export type StreamSseMode = "events" | "data" + +/** + * Schema for a Server-Sent Events success response. + * + * **Details** + * + * `events` describes successful application events emitted by the stream, and + * `error` describes typed stream failures that will be encoded by later + * endpoint/server/client integrations using the reserved failure event. If + * `error` is omitted, it defaults to `Schema.Never`. When `StreamSse` is + * constructed from `data`, handlers and clients expose raw data values while + * the server and client still use an SSE event schema internally. + * + * @category models + * @since 4.0.0 + */ +export interface StreamSse< + Events extends Sse.EventCodec, + Error extends Schema.Top, + Value = Events["Type"] +> extends + Schema.Bottom< + Stream.Stream, + Stream.Stream, + Events["DecodingServices"] | Error["DecodingServices"], + Events["EncodingServices"] | Error["EncodingServices"], + SchemaAST.Declaration, + StreamSse + > +{ + readonly "Rebuild": StreamSse + readonly [StreamSchemaTypeId]: typeof StreamSchemaTypeId + readonly _tag: "StreamSse" + readonly mode: "sse" + readonly sseMode: StreamSseMode + readonly contentType: string + readonly events: Events + readonly error: Error + readonly "~Value"?: Value | undefined +} + +/** + * Event schema produced when {@link StreamSse} is constructed from a JSON data schema. + * + * @category models + * @since 4.0.0 + */ +export interface SseEventFromData extends + Schema.Codec< + { + readonly id: string | undefined + readonly event: string + readonly data: Data["Type"] + }, + { + readonly id?: string | undefined + readonly event?: string | undefined + readonly data: string + }, + Data["DecodingServices"], + Data["EncodingServices"] + > +{} + +/** + * Schema for a streaming `Uint8Array` success response. + * + * **Details** + * + * This declaration stores the response content type for later endpoint, + * server, client, and OpenAPI integrations. It is intentionally separate from + * the buffered `asUint8Array` response encoding. + * + * @category models + * @since 4.0.0 + */ +export interface StreamUint8Array extends + Schema.Bottom< + Stream.Stream, + Stream.Stream, + never, + never, + SchemaAST.Declaration, + StreamUint8Array + > +{ + readonly "Rebuild": StreamUint8Array + readonly [StreamSchemaTypeId]: typeof StreamSchemaTypeId + readonly _tag: "StreamUint8Array" + readonly mode: "uint8array" + readonly contentType: string +} + +/** + * Schema for a streaming HTTP API success response. + * + * @category models + * @since 4.0.0 + */ +export type StreamSchema = StreamSse | StreamUint8Array + +/** @internal */ +export type StreamMetadata = + | { + readonly mode: "sse" + readonly sseMode: StreamSseMode + readonly contentType: string + readonly events: Sse.EventCodec + readonly error: Schema.Top + } + | { + readonly mode: "uint8array" + readonly contentType: string + } + +const streamSchema = Schema.declare(Stream.isStream) + +/** + * Creates a Server-Sent Events streaming success response schema. + * + * @category constructors + * @since 4.0.0 + */ +export const StreamSse: { + /** + * Creates a Server-Sent Events streaming success response schema. + * + * @category constructors + * @since 4.0.0 + */ + ( + options: { + readonly contentType?: string | undefined + readonly events: Events + readonly error?: Error | undefined + } + ): StreamSse + /** + * Creates a Server-Sent Events streaming success response schema. + * + * @category constructors + * @since 4.0.0 + */ + ( + options: { + readonly contentType?: string | undefined + readonly data: Data + readonly error?: Error | undefined + } + ): StreamSse, Error, Data["Type"]> +} = (options: { + readonly contentType?: string | undefined + readonly events?: Sse.EventCodec | undefined + readonly data?: Schema.Top | undefined + readonly error?: Schema.Top | undefined +}): StreamSse => { + const events = options.events ?? (options.data === undefined ? undefined : Schema.Struct({ + id: Schema.UndefinedOr(Schema.String), + event: Schema.String, + data: Schema.fromJsonString(options.data) + })) + if (events === undefined) { + throw new Error("StreamSse requires either an events schema or a data schema") + } + return Schema.make>(streamSchema.ast, { + [StreamSchemaTypeId]: StreamSchemaTypeId, + _tag: "StreamSse", + mode: "sse", + sseMode: options.events === undefined ? "data" : "events", + contentType: options.contentType ?? defaultStreamContentType("sse"), + events, + error: options.error ?? Schema.Never + }) +} + +/** + * Creates a streaming `Uint8Array` success response schema. + * + * @category constructors + * @since 4.0.0 + */ +export const StreamUint8Array = (options?: { + readonly contentType?: string | undefined +}): StreamUint8Array => + Schema.make(streamSchema.ast, { + [StreamSchemaTypeId]: StreamSchemaTypeId, + _tag: "StreamUint8Array", + mode: "uint8array", + contentType: options?.contentType ?? defaultStreamContentType("uint8array") + }) + +/** @internal */ +export const isStreamSchema = (u: unknown): u is StreamSchema => + Schema.isSchema(u) && Predicate.hasProperty(u, StreamSchemaTypeId) + +/** @internal */ +export const isStreamSse = (u: unknown): u is StreamSse => + isStreamSchema(u) && u._tag === "StreamSse" + +/** @internal */ +export const isStreamUint8Array = (u: unknown): u is StreamUint8Array => + isStreamSchema(u) && u._tag === "StreamUint8Array" + +/** @internal */ +export function getStreamMetadata(self: StreamSchema): StreamMetadata { + return self._tag === "StreamSse" ? + { + mode: self.mode, + sseMode: self.sseMode, + contentType: self.contentType, + events: self.events, + error: self.error + } : + { + mode: self.mode, + contentType: self.contentType + } +} + +function defaultStreamContentType(mode: StreamMode): string { + switch (mode) { + case "sse": + return "text/event-stream" + case "uint8array": + return "application/octet-stream" + } +} + /** + * Runtime brand key used to mark schemas as buffered multipart payloads. + * + * @category type IDs * @since 4.0.0 */ export const MultipartTypeId = "~effect/httpapi/HttpApiSchema/Multipart" /** + * Type-level brand identifier used by `asMultipart`. + * + * @category type IDs * @since 4.0.0 */ export type MultipartTypeId = typeof MultipartTypeId /** + * Schema type returned by `asMultipart` for buffered multipart payloads. + * + * @category schemas * @since 4.0.0 */ export interface asMultipart extends Schema.brand {} @@ -276,7 +531,7 @@ export interface asMultipart extends Schema.brand extends Schema.brand {} @@ -311,7 +575,7 @@ export interface asMultipartStream extends Schema.brand { - if (AST.isVoid(ast)) return true - const encoded = AST.toEncoded(ast) - if (AST.isVoid(encoded)) return true +export const isNoContent = (ast: SchemaAST.AST): boolean => { + if (SchemaAST.isVoid(ast)) return true + const encoded = SchemaAST.toEncoded(ast) + if (SchemaAST.isVoid(encoded)) return true const target = ast.encoding?.[0].to if (target === undefined) return false - return AST.isVoid(target) + return SchemaAST.isVoid(target) } -const resolveHttpApiEncoding = AST.resolveAt("~httpApiEncoding") +const resolveHttpApiEncoding = SchemaAST.resolveAt("~httpApiEncoding") -const resolveHttpApiStatus = AST.resolveAt("httpApiStatus") +const resolveHttpApiStatus = SchemaAST.resolveAt("httpApiStatus") const defaultJsonEncoding: Encoding = { _tag: "Json", @@ -435,19 +713,19 @@ const defaultUrlEncodedEncoding: Encoding = { contentType: "application/x-www-form-urlencoded" } -function getEncoding(ast: AST.AST): Encoding { +function getEncoding(ast: SchemaAST.AST): Encoding { return resolveHttpApiEncoding(ast) ?? defaultJsonEncoding } /** @internal */ -export function getPayloadEncoding(ast: AST.AST, method: HttpMethod): PayloadEncoding { +export function getPayloadEncoding(ast: SchemaAST.AST, method: HttpMethod): PayloadEncoding { const encoding = resolveHttpApiEncoding(ast) if (encoding) return encoding return hasBody(method) ? defaultJsonEncoding : defaultUrlEncodedEncoding } /** @internal */ -export function getResponseEncoding(ast: AST.AST): ResponseEncoding { +export function getResponseEncoding(ast: SchemaAST.AST): ResponseEncoding { const out = getEncoding(ast) if (out._tag === "Multipart") { throw new Error("Multipart is not supported in response") @@ -456,11 +734,16 @@ export function getResponseEncoding(ast: AST.AST): ResponseEncoding { } /** @internal */ -export function getStatusSuccess(self: AST.AST): number { +export function getStatusSuccess(self: SchemaAST.AST): number { return resolveHttpApiStatus(self) ?? 200 } /** @internal */ -export function getStatusError(self: AST.AST): number { +export function getStatusStream(self: StreamSchema): number { + return getStatusSuccess(self.ast) +} + +/** @internal */ +export function getStatusError(self: SchemaAST.AST): number { return resolveHttpApiStatus(self) ?? 500 } diff --git a/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiSecurity.ts b/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiSecurity.ts index 7c69f980ad749dd3c47f49543368a7fed5890a88..0514b7c29c0cdeb918dc1e17c825adba35da2b78 100644 --- a/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiSecurity.ts +++ b/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiSecurity.ts @@ -1,4 +1,11 @@ /** + * Defines security scheme declarations for declarative HTTP APIs. + * + * Security schemes describe where credentials are read from and which credential + * type is passed to security middleware. They are consumed by + * `HttpApiMiddleware.Service`, `HttpApiBuilder`, generated clients, and OpenAPI + * generation, but they do not authenticate requests by themselves. + * * @since 4.0.0 */ import * as Context from "../../Context.ts" @@ -10,19 +17,24 @@ import type { Covariant } from "../../Types.ts" const TypeId = "~effect/httpapi/HttpApiSecurity" /** - * @since 4.0.0 + * Union of security schemes supported by the HTTP API OpenAPI model. + * * @category models + * @since 4.0.0 */ -export type HttpApiSecurity = Bearer | ApiKey | Basic +export type HttpApiSecurity = Http | ApiKey | Basic /** + * Helper types for HTTP API security schemes. + * * @since 4.0.0 - * @category models */ export declare namespace HttpApiSecurity { /** - * @since 4.0.0 + * Common prototype for security schemes, carrying the credential type and OpenAPI annotations. + * * @category models + * @since 4.0.0 */ export interface Proto extends Pipeable { readonly [TypeId]: { @@ -32,23 +44,32 @@ export declare namespace HttpApiSecurity { } /** - * @since 4.0.0 + * Extracts the credential type produced by a security scheme. + * * @category models + * @since 4.0.0 */ export type Type = A extends Proto ? Out : never } /** - * @since 4.0.0 + * Http token security scheme whose decoded credential is a redacted token. + * * @category models + * @since 4.0.0 */ -export interface Bearer extends HttpApiSecurity.Proto { - readonly _tag: "Bearer" +export interface Http extends HttpApiSecurity.Proto { + readonly _tag: "Http" + readonly scheme: string + /** @internal */ + readonly schemeLength: number } /** - * @since 4.0.0 + * API key security scheme identifying the key name and whether it is read from a header, query parameter, or cookie. + * * @category models + * @since 4.0.0 */ export interface ApiKey extends HttpApiSecurity.Proto { readonly _tag: "ApiKey" @@ -57,16 +78,20 @@ export interface ApiKey extends HttpApiSecurity.Proto { } /** - * @since 4.0.0 + * HTTP Basic authentication security scheme whose decoded credential is `Credentials`. + * * @category models + * @since 4.0.0 */ export interface Basic extends HttpApiSecurity.Proto { readonly _tag: "Basic" } /** - * @since 4.0.0 + * Decoded credentials for HTTP Basic authentication. + * * @category models + * @since 4.0.0 */ export interface Credentials { readonly username: string @@ -81,32 +106,73 @@ const Proto = { } /** - * Create an Bearer token security scheme. + * Creates a Http token security scheme. * - * You can implement some api middleware for this security scheme using - * `HttpApiBuilder.middlewareSecurity`. + * **When to use** * - * @since 4.0.0 + * Use to require `Authorization: scheme ...` credentials for an HTTP API group + * or endpoint. + * + * **Details** + * + * Use `HttpApiBuilder.middlewareSecurity` to implement API middleware for this + * security scheme. + * + * @see {@link apiKey} for an API-key security scheme + * @see {@link basic} for an HTTP Basic security scheme * @category constructors + * @since 4.0.0 */ -export const bearer: Bearer = Object.assign(Object.create(Proto), { - _tag: "Bearer", - annotations: Context.empty() -}) +export const http = (options: { + readonly scheme: string +}): Http => + Object.assign(Object.create(Proto), { + _tag: "Http", + scheme: options.scheme, + schemeLength: options.scheme.length, + annotations: Context.empty() + }) /** - * Create an API key security scheme. + * Creates a Bearer token security scheme. * - * You can implement some api middleware for this security scheme using - * `HttpApiBuilder.middlewareSecurity`. + * **When to use** * - * To set the correct cookie in a handler, you can use - * `HttpApiBuilder.securitySetCookie`. + * Use to require `Authorization: Bearer ...` credentials for an HTTP API group + * or endpoint. * - * The default value for `in` is "header". + * **Details** * + * Use `HttpApiBuilder.middlewareSecurity` to implement API middleware for this + * security scheme. + * + * @see {@link apiKey} for an API-key security scheme + * @see {@link basic} for an HTTP Basic security scheme + * @category constructors * @since 4.0.0 + */ +export const bearer: Http = http({ scheme: "Bearer" }) + +/** + * Creates an API key security scheme. + * + * **When to use** + * + * Use to require API key credentials passed through a header, query parameter, + * or cookie. + * + * **Details** + * + * Use `HttpApiBuilder.middlewareSecurity` to implement API middleware for this + * security scheme. + * + * Use `HttpApiBuilder.securitySetCookie` to set the correct cookie in a + * handler. By default, `in` is `"header"`. + * + * @see {@link bearer} for a Bearer token security scheme + * @see {@link basic} for an HTTP Basic security scheme * @category constructors + * @since 4.0.0 */ export const apiKey = (options: { readonly key: string @@ -120,8 +186,21 @@ export const apiKey = (options: { }) /** - * @since 4.0.0 + * Creates an HTTP Basic authentication security scheme. + * + * **When to use** + * + * Use to require HTTP Basic username/password credentials. + * + * **Details** + * + * Use `HttpApiBuilder.middlewareSecurity` to implement API middleware for this + * security scheme. + * + * @see {@link bearer} for a Bearer token security scheme + * @see {@link apiKey} for an API-key security scheme * @category constructors + * @since 4.0.0 */ export const basic: Basic = Object.assign(Object.create(Proto), { _tag: "Basic", @@ -129,18 +208,24 @@ export const basic: Basic = Object.assign(Object.create(Proto), { }) /** - * @since 4.0.0 + * Merges OpenAPI annotations into a security scheme. + * * @category annotations + * @since 4.0.0 */ export const annotateMerge: { /** - * @since 4.0.0 + * Merges OpenAPI annotations into a security scheme. + * * @category annotations + * @since 4.0.0 */ (annotations: Context.Context): (self: A) => A /** - * @since 4.0.0 + * Merges OpenAPI annotations into a security scheme. + * * @category annotations + * @since 4.0.0 */ (self: A, annotations: Context.Context): A } = dual( @@ -153,18 +238,24 @@ export const annotateMerge: { ) /** - * @since 4.0.0 + * Adds an OpenAPI annotation value to a security scheme. + * * @category annotations + * @since 4.0.0 */ export const annotate: { /** - * @since 4.0.0 + * Adds an OpenAPI annotation value to a security scheme. + * * @category annotations + * @since 4.0.0 */ (service: Context.Key, value: S): (self: A) => A /** - * @since 4.0.0 + * Adds an OpenAPI annotation value to a security scheme. + * * @category annotations + * @since 4.0.0 */ (self: A, service: Context.Key, value: S): A } = dual( diff --git a/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiSwagger.ts b/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiSwagger.ts index e06ad02750a8ce63da34969add5da10475dc6695..6ee7728321af75e50e477b4949c6aefd6294e4b1 100644 --- a/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiSwagger.ts +++ b/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiSwagger.ts @@ -1,4 +1,11 @@ /** + * Swagger documentation UI for declarative `HttpApi` contracts. + * + * This module mounts a browser-based Swagger UI route on an `HttpRouter`. The + * page renders the OpenAPI document derived from the supplied `HttpApi`, so a + * running application can expose interactive API documentation without writing a + * separate OpenAPI file. + * * @since 4.0.0 */ import * as Effect from "../../Effect.ts" @@ -43,12 +50,11 @@ const makeHandler = (options } /** - * Exported layer mounting Swagger/OpenAPI documentation UI. - * - * @param options.path Optional mount path (default "/docs"). + * Mounts Swagger UI for an `HttpApi` at the configured path, defaulting to + * `/docs`, using the OpenAPI specification generated from the API. * - * @since 4.0.0 * @category layers + * @since 4.0.0 */ export const layer = ( api: HttpApi.HttpApi, diff --git a/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiTest.ts b/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiTest.ts index c192b6576ac34b3f6f9b9bd972f56c6b138f31e7..18b8bfcd36a711085a543c4c6b51f8f118e8661a 100644 --- a/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiTest.ts +++ b/.opencode/node_modules/effect/src/unstable/httpapi/HttpApiTest.ts @@ -1,4 +1,11 @@ /** + * Tests `HttpApi` implementations through an in-memory generated client. + * + * The helpers use the same request encoding, routing, response encoding, and + * client decoding as the normal `HttpApiBuilder` and `HttpApiClient` pipeline, + * but they do not start an HTTP server. This is useful for focused handler + * tests, schema round trips, middleware behavior, and typed client calls. + * * @since 4.0.0 */ import * as Context from "../../Context.ts" @@ -21,8 +28,15 @@ import type * as HttpApiEndpoint from "./HttpApiEndpoint.ts" import type * as HttpApiGroup from "./HttpApiGroup.ts" /** + * Creates an in-memory client for testing selected groups of an `HttpApi`. + * + * **Details** + * + * Handlers for the selected groups are taken from the environment; unselected + * groups are wired with placeholder handlers that fail if called. + * + * @category testing * @since 4.0.0 - * @category Testing */ export const groups = Effect.fnUntraced(function*< ApiId extends string, @@ -31,7 +45,10 @@ export const groups = Effect.fnUntraced(function*< SelectedGroups = HttpApiGroup.WithName >( api: HttpApi.HttpApi, - groupNames: Names + groupNames: Names, + options?: { + readonly baseUrl?: string | URL | undefined + } ): Effect.fn.Return< HttpApiClient.Client, never, @@ -90,6 +107,6 @@ export const groups = Effect.fnUntraced(function*< return yield* HttpApiClient.makeWith(api, { httpClient, - baseUrl: "http://localhost:3000" + baseUrl: options?.baseUrl ?? "http://localhost:3000" }) }) diff --git a/.opencode/node_modules/effect/src/unstable/httpapi/OpenApi.ts b/.opencode/node_modules/effect/src/unstable/httpapi/OpenApi.ts index 72ba4cee6edfc034600be31e9416d10a5442adde..7044943735684feae5e8b301a1d363f96543f700 100644 --- a/.opencode/node_modules/effect/src/unstable/httpapi/OpenApi.ts +++ b/.opencode/node_modules/effect/src/unstable/httpapi/OpenApi.ts @@ -1,4 +1,11 @@ /** + * Generates OpenAPI 3.1 documents from declarative `HttpApi` contracts. + * + * The generator reads API groups, endpoints, schemas, security definitions, and + * annotations, then produces an OpenAPI document. This module also provides the + * annotations used to shape that output and the TypeScript model for the + * OpenAPI objects it generates. + * * @since 4.0.0 */ import * as Arr from "../../Array.ts" @@ -10,7 +17,7 @@ import { escapeToken } from "../../JsonPointer.ts" import * as JsonSchema from "../../JsonSchema.ts" import * as Option from "../../Option.ts" import * as Schema from "../../Schema.ts" -import * as AST from "../../SchemaAST.ts" +import * as SchemaAST from "../../SchemaAST.ts" import * as SchemaRepresentation from "../../SchemaRepresentation.ts" import * as HttpMethod from "../http/HttpMethod.ts" import * as HttpApi from "./HttpApi.ts" @@ -21,88 +28,123 @@ import * as HttpApiSchema from "./HttpApiSchema.ts" import type { HttpApiSecurity } from "./HttpApiSecurity.ts" /** - * @since 4.0.0 + * OpenAPI annotation for overriding generated identifiers, including operation ids. + * * @category annotations + * @since 4.0.0 */ export class Identifier extends Context.Service()("effect/httpapi/OpenApi/Identifier") {} /** - * @since 4.0.0 + * OpenAPI annotation for setting the API title or group tag name. + * * @category annotations + * @since 4.0.0 */ export class Title extends Context.Service()("effect/httpapi/OpenApi/Title") {} /** - * @since 4.0.0 + * OpenAPI annotation for setting the generated API version. + * * @category annotations + * @since 4.0.0 */ export class Version extends Context.Service()("effect/httpapi/OpenApi/Version") {} /** - * @since 4.0.0 + * OpenAPI annotation for setting generated descriptions on APIs, groups, endpoints, or security schemes. + * * @category annotations + * @since 4.0.0 */ export class Description extends Context.Service()("effect/httpapi/OpenApi/Description") {} /** - * @since 4.0.0 + * OpenAPI annotation for setting the generated API license metadata. + * * @category annotations + * @since 4.0.0 */ export class License extends Context.Service()("effect/httpapi/OpenApi/License") {} /** - * @since 4.0.0 + * OpenAPI annotation for adding external documentation metadata to groups or endpoints. + * * @category annotations + * @since 4.0.0 */ export class ExternalDocs extends Context.Service()("effect/httpapi/OpenApi/ExternalDocs") {} /** - * @since 4.0.0 + * OpenAPI annotation for setting the generated API server list. + * * @category annotations + * @since 4.0.0 */ export class Servers extends Context.Service>()("effect/httpapi/OpenApi/Servers") {} /** - * @since 4.0.0 + * OpenAPI annotation for setting the format metadata, such as a bearer token format on security schemes. + * * @category annotations + * @since 4.0.0 */ export class Format extends Context.Service()("effect/httpapi/OpenApi/Format") {} /** - * @since 4.0.0 + * OpenAPI annotation for setting generated summary text. + * * @category annotations + * @since 4.0.0 */ export class Summary extends Context.Service()("effect/httpapi/OpenApi/Summary") {} /** - * @since 4.0.0 + * OpenAPI annotation for marking a generated endpoint operation as deprecated. + * * @category annotations + * @since 4.0.0 */ export class Deprecated extends Context.Service()("effect/httpapi/OpenApi/Deprecated") {} /** - * @since 4.0.0 + * OpenAPI annotation for shallowly merging additional fields into a generated OpenAPI object. + * * @category annotations + * @since 4.0.0 */ export class Override extends Context.Service>()("effect/httpapi/OpenApi/Override") {} /** - * @since 4.0.0 + * Annotation that excludes an annotated group or endpoint from the generated + * OpenAPI specification. + * + * **When to use** + * + * Use to hide internal, experimental, or otherwise undocumented HTTP API groups + * and endpoints from generated OpenAPI output. + * * @category annotations + * @since 4.0.0 */ export const Exclude = Context.Reference("effect/httpapi/OpenApi/Exclude", { defaultValue: constFalse }) /** - * Transforms the generated OpenAPI specification + * OpenAPI annotation for transforming a generated OpenAPI object. + * + * **Details** + * + * The function is applied during generation to the annotated API, group tag, or + * endpoint operation. * - * @since 4.0.0 * @category annotations + * @since 4.0.0 */ export class Transform extends Context.Service< Transform, @@ -129,8 +171,10 @@ const servicesPartial = | Con } /** - * @since 4.0.0 + * Builds a `Context` containing OpenAPI annotations from the supplied options. + * * @category annotations + * @since 4.0.0 */ export const annotations: ( options: { @@ -227,11 +271,11 @@ export function fromApi( const pathOps: Array< { readonly _tag: "schema" - readonly ast: AST.AST + readonly ast: SchemaAST.AST readonly path: ReadonlyArray } | { readonly _tag: "parameter" - readonly ast: AST.AST + readonly ast: SchemaAST.AST readonly path: ReadonlyArray } > = [] @@ -305,8 +349,8 @@ export function fromApi( const filtered = schemas.filter((s) => !HttpApiSchema.isNoContent(s.ast)) if (filtered.length === 0) return hasContent = true - const asts = filtered.map(AST.getAST) - const ast = asts.length === 1 ? asts[0] : new AST.Union(asts, "anyOf") + const asts = filtered.map(SchemaAST.getAST) + const ast = asts.length === 1 ? asts[0] : new SchemaAST.Union(asts, "anyOf") pathOps.push({ _tag: "schema", ast: toEncodingAST(ast, encoding._tag), @@ -323,7 +367,7 @@ export function fromApi( } function processResponseBodies(bodies: ResponseBodies, defaultDescription: () => string) { - for (const [status, { content, descriptions }] of bodies) { + for (const [status, { content, descriptions, streamContent }] of bodies) { const description = descriptions.size > 0 ? Array.from(descriptions).join(" | ") : defaultDescription() op.responses[status] = { description @@ -331,8 +375,8 @@ export function fromApi( if (content !== undefined) { content.forEach((map, encoding) => { map.forEach((schemas, contentType) => { - const asts = Array.from(schemas, AST.getAST) - const ast = asts.length === 1 ? asts[0] : new AST.Union(asts, "anyOf") + const asts = Array.from(schemas, SchemaAST.getAST) + const ast = asts.length === 1 ? asts[0] : new SchemaAST.Union(asts, "anyOf") pathOps.push({ _tag: "schema", @@ -346,19 +390,80 @@ export function fromApi( }) }) } + if (streamContent !== undefined) { + streamContent.forEach((stream, contentType) => { + op.responses[status].content ??= {} + if (HttpApiSchema.isStreamSse(stream)) { + pathOps.push({ + _tag: "schema", + ast: SchemaAST.getAST(stream.events), + path: ["paths", path, method, "responses", String(status), "content", contentType, "schema"] + }) + pathOps.push({ + _tag: "schema", + ast: SchemaAST.getAST(Schema.toCodecJson(Schema.Cause(stream.error, Schema.Defect()))), + path: [ + "paths", + path, + method, + "responses", + String(status), + "content", + contentType, + "x-effect-stream", + "causeSchema" + ] + }) + pathOps.push({ + _tag: "schema", + ast: SchemaAST.getAST(stream.error), + path: [ + "paths", + path, + method, + "responses", + String(status), + "content", + contentType, + "x-effect-stream", + "errorSchema" + ] + }) + op.responses[status].content[contentType] = { + schema: {}, + "x-effect-stream": { + encoding: "sse", + causeSchema: {}, + errorSchema: {}, + failureEvent: reservedStreamFailureEvent + } + } + } else { + op.responses[status].content[contentType] = { + schema: { + type: "string", + format: "binary" + }, + "x-effect-stream": { + encoding: "uint8array" + } + } + } + }) + } } } function processParameters(schema: Schema.Top | undefined, i: OpenAPISpecParameter["in"]) { if (schema) { - const ast = AST.getLastEncoding(schema.ast) - if (AST.isObjects(ast)) { + const ast = SchemaAST.getLastEncoding(schema.ast) + if (SchemaAST.isObjects(ast)) { for (const ps of ast.propertySignatures) { op.parameters.push({ name: String(ps.name), in: i, schema: {}, - required: i === "path" || !AST.isOptional(ps.type) + required: i === "path" || !SchemaAST.isOptional(ps.type) }) pathOps.push({ _tag: "parameter", @@ -417,11 +522,7 @@ export function fromApi( processParameters(endpoint.query, "query") processResponseBodies( - extractResponseBodies( - HttpApiEndpoint.getSuccessSchemas(endpoint), - HttpApiSchema.getStatusSuccess, - resolveDescriptionOrIdentifier - ), + extractSuccessResponseBodies(endpoint), () => "Success" ) processResponseBodies( @@ -450,7 +551,7 @@ export function fromApi( processAnnotation(api.annotations, HttpApi.AdditionalSchemas, (componentSchemas) => { componentSchemas.forEach((componentSchema) => { - const identifier = AST.resolveIdentifier(componentSchema.ast) + const identifier = SchemaAST.resolveIdentifier(componentSchema.ast) if (identifier !== undefined) { if (identifier in spec.components.schemas) { throw new globalThis.Error(`Duplicate component schema identifier: ${identifier}`) @@ -520,17 +621,29 @@ type ResponseBodies = Map< { descriptions: Set content: Content | undefined // undefined means no content + streamContent: StreamContent | undefined } > +const reservedStreamFailureEvent = "effect/httpapi/stream/failure" + +function extractSuccessResponseBodies(endpoint: HttpApiEndpoint.AnyWithProps): ResponseBodies { + return extractResponseBodies( + HttpApiEndpoint.getSuccessSchemas(endpoint), + HttpApiSchema.getStatusSuccess, + resolveDescriptionOrIdentifier + ) +} + function extractResponseBodies( schemas: Array, - getStatus: (ast: AST.AST) => number, - getDescription: (ast: AST.AST) => string | undefined + getStatus: (ast: SchemaAST.AST) => number, + getDescription: (ast: SchemaAST.AST) => string | undefined ): ResponseBodies { const map = new Map content: Content | undefined + streamContent: StreamContent | undefined }>() schemas.forEach(process) @@ -538,6 +651,10 @@ function extractResponseBodies( return map function process(schema: Schema.Top) { + if (HttpApiSchema.isStreamSchema(schema)) { + addStreamContent(schema) + return + } const ast = schema.ast const status = getStatus(ast) if (HttpApiSchema.isNoContent(ast)) { @@ -552,7 +669,8 @@ function extractResponseBodies( if (statusMap === undefined) { map.set(status, { descriptions: new Set([description]), - content: undefined + content: undefined, + streamContent: undefined }) } else { if (description !== undefined) { @@ -568,22 +686,25 @@ function extractResponseBodies( if (statusMap === undefined) { map.set(status, { descriptions: new Set(description !== undefined ? [description] : []), - content: new Map([[_tag, new Map([[contentType, new Set([schema])]])]]) + content: new Map([[_tag, new Map([[contentType, new Set([schema])]])]]), + streamContent: undefined }) } else { - if (statusMap.content !== undefined) { - // concat descriptions - if (description !== undefined) { - statusMap.descriptions.add(description) - } + // concat descriptions + if (description !== undefined) { + statusMap.descriptions.add(description) + } - const contentTypeMap = statusMap.content.get(_tag) - if (contentTypeMap === undefined) { + if (statusMap.content === undefined) { + statusMap.content = new Map([[_tag, new Map([[contentType, new Set([schema])]])]]) + } else { + const schemasByContentType = statusMap.content.get(_tag) + if (schemasByContentType === undefined) { statusMap.content.set(_tag, new Map([[contentType, new Set([schema])]])) } else { - const set = contentTypeMap.get(contentType) + const set = schemasByContentType.get(contentType) if (set === undefined) { - contentTypeMap.set(contentType, new Set([schema])) + schemasByContentType.set(contentType, new Set([schema])) } else { set.add(schema) } @@ -591,10 +712,26 @@ function extractResponseBodies( } } } + + function addStreamContent(stream: HttpApiSchema.StreamSchema) { + const status = HttpApiSchema.getStatusStream(stream) + const statusMap = map.get(status) + if (statusMap === undefined) { + map.set(status, { + descriptions: new Set(), + content: undefined, + streamContent: new Map([[stream.contentType, stream]]) + }) + } else if (statusMap.streamContent === undefined) { + statusMap.streamContent = new Map([[stream.contentType, stream]]) + } else { + statusMap.streamContent.set(stream.contentType, stream) + } + } } -function resolveDescriptionOrIdentifier(ast: AST.AST): string | undefined { - return AST.resolveDescription(ast) ?? AST.resolveIdentifier(ast) +function resolveDescriptionOrIdentifier(ast: SchemaAST.AST): string | undefined { + return SchemaAST.resolveDescription(ast) ?? SchemaAST.resolveIdentifier(ast) } type Content = Map< @@ -605,11 +742,13 @@ type Content = Map< > > +type StreamContent = Map + const Uint8ArrayEncoding = Schema.String.annotate({ format: "binary" }) -function toEncodingAST(ast: AST.AST, _tag: HttpApiSchema.Encoding["_tag"]): AST.AST { +function toEncodingAST(ast: SchemaAST.AST, _tag: HttpApiSchema.Encoding["_tag"]): SchemaAST.AST { switch (_tag) { case "Uint8Array": return Uint8ArrayEncoding.ast @@ -623,9 +762,9 @@ function toEncodingAST(ast: AST.AST, _tag: HttpApiSchema.Encoding["_tag"]): AST. } } -function persistedFileToBinaryEncoding(ast: AST.AST): AST.AST { +function persistedFileToBinaryEncoding(ast: SchemaAST.AST): SchemaAST.AST { if ( - AST.isDeclaration(ast) && + SchemaAST.isDeclaration(ast) && ((ast.annotations as (Schema.Annotations.Declaration | undefined))?.typeConstructor?._tag === "effect/http/PersistedFile") ) { @@ -652,7 +791,7 @@ const makeSecurityScheme = (security: HttpApiSecurity): OpenAPISecurityScheme => scheme: "basic" } } - case "Bearer": { + case "Http": { const format = Context.getOption(security.annotations, Format).pipe( Option.map((format) => ({ bearerFormat: format })), Option.getOrUndefined @@ -660,7 +799,7 @@ const makeSecurityScheme = (security: HttpApiSecurity): OpenAPISecurityScheme => return { ...meta, type: "http", - scheme: "bearer", + scheme: security.scheme, ...format } } @@ -694,6 +833,8 @@ export interface OpenAPISpec { } /** + * OpenAPI `info` object generated by `fromApi`. + * * @category models * @since 4.0.0 */ @@ -706,6 +847,8 @@ export interface OpenAPISpecInfo { } /** + * OpenAPI tag object generated for an HTTP API group. + * * @category models * @since 4.0.0 */ @@ -716,6 +859,8 @@ export interface OpenAPISpecTag { } /** + * OpenAPI external documentation metadata. + * * @category models * @since 4.0.0 */ @@ -725,6 +870,8 @@ export interface OpenAPISpecExternalDocs { } /** + * OpenAPI license metadata used in the generated `info` object. + * * @category models * @since 4.0.0 */ @@ -735,6 +882,8 @@ export interface OpenAPISpecLicense { } /** + * OpenAPI server object used in the generated `servers` array. + * * @category models * @since 4.0.0 */ @@ -745,6 +894,8 @@ export interface OpenAPISpecServer { } /** + * OpenAPI variable definition for templated server URLs. + * * @category models * @since 4.0.0 */ @@ -755,12 +906,16 @@ export interface OpenAPISpecServerVariable { } /** + * Generated OpenAPI `paths` object, keyed by route path. + * * @category models * @since 4.0.0 */ export type OpenAPISpecPaths = Record /** + * Lowercase HTTP method names used as keys in generated OpenAPI path items. + * * @category models * @since 4.0.0 */ @@ -775,6 +930,8 @@ export type OpenAPISpecMethodName = | "trace" /** + * Generated OpenAPI path item mapping HTTP methods to operations for a single route path. + * * @category models * @since 4.0.0 */ @@ -783,6 +940,8 @@ export type OpenAPISpecPathItem = { } /** + * Generated OpenAPI parameter object for path, query, header, or cookie parameters. + * * @category models * @since 4.0.0 */ @@ -795,12 +954,16 @@ export interface OpenAPISpecParameter { } /** + * Generated OpenAPI responses object, keyed by HTTP status code. + * * @category models * @since 4.0.0 */ export type OpenAPISpecResponses = Record /** + * Generated OpenAPI content object, keyed by media type. + * * @category models * @since 4.0.0 */ @@ -809,6 +972,8 @@ export type OpenApiSpecContent = { } /** + * Generated OpenAPI response object for an endpoint success or error schema. + * * @category models * @since 4.0.0 */ @@ -818,14 +983,36 @@ export interface OpenApiSpecResponse { } /** + * Generated OpenAPI media type object containing the JSON Schema for a request or response body. + * * @category models * @since 4.0.0 */ export interface OpenApiSpecMediaType { schema: JsonSchema.JsonSchema + "x-effect-stream"?: OpenApiSpecEffectStream } /** + * Effect-specific metadata for generated streaming response media types. + * + * @category models + * @since 4.0.0 + */ +export type OpenApiSpecEffectStream = + | { + encoding: "sse" + causeSchema: JsonSchema.JsonSchema + errorSchema: JsonSchema.JsonSchema + failureEvent: "effect/httpapi/stream/failure" + } + | { + encoding: "uint8array" + } + +/** + * Generated OpenAPI request body object for endpoint payloads. + * * @category models * @since 4.0.0 */ @@ -835,6 +1022,8 @@ export interface OpenAPISpecRequestBody { } /** + * Generated OpenAPI components containing shared schemas and security schemes. + * * @category models * @since 4.0.0 */ @@ -844,6 +1033,8 @@ export interface OpenAPIComponents { } /** + * Generated OpenAPI HTTP security scheme, such as bearer or basic authentication. + * * @category models * @since 4.0.0 */ @@ -856,6 +1047,8 @@ export interface OpenAPIHTTPSecurityScheme { } /** + * Generated OpenAPI API key security scheme. + * * @category models * @since 4.0.0 */ @@ -867,6 +1060,8 @@ export interface OpenAPIApiKeySecurityScheme { } /** + * Union of security scheme objects emitted in generated OpenAPI components. + * * @category models * @since 4.0.0 */ @@ -875,12 +1070,16 @@ export type OpenAPISecurityScheme = | OpenAPIApiKeySecurityScheme /** + * Generated OpenAPI security requirement, keyed by security scheme name. + * * @category models * @since 4.0.0 */ export type OpenAPISecurityRequirement = Record> /** + * Generated OpenAPI operation object for an HTTP API endpoint. + * * @category models * @since 4.0.0 */ diff --git a/.opencode/node_modules/effect/src/unstable/httpapi/index.ts b/.opencode/node_modules/effect/src/unstable/httpapi/index.ts index 8a92a73af182c8462875dd87e0cc669522742b0a..6d1f2288956a1691cb12e8c10c264b11273bca41 100644 --- a/.opencode/node_modules/effect/src/unstable/httpapi/index.ts +++ b/.opencode/node_modules/effect/src/unstable/httpapi/index.ts @@ -45,32 +45,6 @@ export * as HttpApiMiddleware from "./HttpApiMiddleware.ts" export * as HttpApiScalar from "./HttpApiScalar.ts" /** - * HttpApiSchema provides helpers to annotate Effect Schema values with HTTP API metadata - * (status codes and payload/response encodings) used by the HttpApi builder, client, - * and OpenAPI generation. - * - * Mental model: - * - A "Schema" is the base validation/encoding description from `Schema`. - * - An "Encoding" tells HttpApi how to serialize/parse a payload or response body. - * - A "Status" is metadata that chooses the HTTP response status code. - * - "Empty" schemas represent responses with no body (204/201/202 or custom). - * - "NoContent" schemas can still decode into a value via {@link asNoContent}. - * - Multipart is a payload-only encoding for file-like form data. - * - * Common tasks: - * - Set a response status on a schema -> {@link status} - * - Declare an empty response -> {@link Empty}, {@link NoContent}, {@link Created}, {@link Accepted} - * - Decode an empty response into a value -> {@link asNoContent} - * - Force a specific encoding -> {@link asJson}, {@link asFormUrlEncoded}, {@link asText}, {@link asUint8Array} - * - Mark multipart payloads -> {@link asMultipart}, {@link asMultipartStream} - * - * Gotchas: - * - If you don't set an encoding, HttpApi assumes JSON by default. - * - {@link asFormUrlEncoded} expects the schema's encoded type to be a record of strings. - * - {@link asText} expects the encoded type to be `string`, and {@link asUint8Array} expects `Uint8Array`. - * - Multipart encodings are intended for request payloads; response multipart is not supported. - * - These helpers annotate schemas; they don't perform validation or IO by themselves. - * * @since 4.0.0 */ export * as HttpApiSchema from "./HttpApiSchema.ts" diff --git a/.opencode/node_modules/effect/src/unstable/observability/Otlp.ts b/.opencode/node_modules/effect/src/unstable/observability/Otlp.ts index 77536404f52805f749d64f862e613cd7cf02e887..9f4e8175e48a8ac20c141b7d6c5d4f0081b7447e 100644 --- a/.opencode/node_modules/effect/src/unstable/observability/Otlp.ts +++ b/.opencode/node_modules/effect/src/unstable/observability/Otlp.ts @@ -1,4 +1,11 @@ /** + * Configures OpenTelemetry Protocol (OTLP) HTTP export for Effect telemetry. + * + * This module installs the OTLP logger, metrics exporter, and tracer exporter + * from one shared configuration. Use it when an application sends logs, metrics, + * and traces to the same OpenTelemetry Collector, vendor OTLP endpoint, or local + * development collector. + * * @since 4.0.0 */ import type * as Duration from "../../Duration.ts" @@ -15,8 +22,15 @@ import * as OtlpSerialization from "./OtlpSerialization.ts" import * as OtlpTracer from "./OtlpTracer.ts" /** + * Creates a combined OTLP layer for logs, metrics, and traces. + * + * **Details** + * + * The layer sends data to `/v1/logs`, `/v1/metrics`, and `/v1/traces` below + * `baseUrl` and requires an `OtlpSerialization` implementation. + * + * @category layers * @since 4.0.0 - * @category Layers */ export const layer = (options: { readonly baseUrl: string @@ -70,8 +84,47 @@ export const layer = (options: { } /** + * Creates a combined OTLP layer for logs, metrics, and traces from + * OpenTelemetry configuration. + * + * @category layers + * @since 4.0.0 + */ +export const layerFromConfig = (options?: { + readonly resource?: { + readonly serviceName?: string | undefined + readonly serviceVersion?: string | undefined + readonly attributes?: Record + } | undefined + readonly headers?: Headers.Input | undefined + readonly tracerContext?: ((primitive: Tracer.EffectPrimitive, span: Tracer.AnySpan) => X) | undefined + readonly loggerExcludeLogSpans?: boolean | undefined + readonly loggerMergeWithExisting?: boolean | undefined +}): Layer.Layer => + Layer.mergeAll( + OtlpLogger.layerFromConfig({ + resource: options?.resource, + headers: options?.headers, + excludeLogSpans: options?.loggerExcludeLogSpans, + mergeWithExisting: options?.loggerMergeWithExisting + }), + OtlpMetrics.layerFromConfig({ + resource: options?.resource, + headers: options?.headers + }), + OtlpTracer.layerFromConfig({ + resource: options?.resource, + headers: options?.headers, + context: options?.tracerContext + }) + ) + +/** + * Creates the combined OTLP logs, metrics, and traces layer using JSON + * serialization. + * + * @category layers * @since 4.0.0 - * @category Layers */ export const layerJson: (options: { readonly baseUrl: string @@ -93,8 +146,11 @@ export const layerJson: (options: { }) => Layer.Layer = flow(layer, Layer.provide(OtlpSerialization.layerJson)) /** + * Creates the combined OTLP logs, metrics, and traces layer using protobuf + * serialization. + * + * @category layers * @since 4.0.0 - * @category Layers */ export const layerProtobuf: (options: { readonly baseUrl: string diff --git a/.opencode/node_modules/effect/src/unstable/observability/OtlpExporter.ts b/.opencode/node_modules/effect/src/unstable/observability/OtlpExporter.ts index 7a61d926f0c5d3e58566457096e4081b44a35de5..dc1f90d69c769f5ce64a2b4f719abf4fca0f9ce9 100644 --- a/.opencode/node_modules/effect/src/unstable/observability/OtlpExporter.ts +++ b/.opencode/node_modules/effect/src/unstable/observability/OtlpExporter.ts @@ -1,4 +1,11 @@ /** + * Shared batch exporter for OTLP/HTTP observability modules. + * + * Signal modules use this exporter to buffer already-encoded telemetry and post + * it to a configured OTLP endpoint. It owns the scoped transport loop, batching, + * retry behavior, temporary disabling after repeated failures, and final flush + * during shutdown. + * * @since 4.0.0 */ import { Clock } from "../../Clock.ts" @@ -35,8 +42,17 @@ const policy = Schedule.forever.pipe( ) /** + * Creates a scoped OTLP batch exporter. + * + * **Details** + * + * The exporter buffers pushed data, periodically posts encoded batches to the + * configured URL, retries transient failures, temporarily disables exporting + * after unhandled failures, and flushes during scope finalization up to + * `shutdownTimeout`. + * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const make: ( options: { diff --git a/.opencode/node_modules/effect/src/unstable/observability/OtlpLogger.ts b/.opencode/node_modules/effect/src/unstable/observability/OtlpLogger.ts index a9ead3b5fa17d05ce82bdb98c551b427c9950aac..c80d5caef84d31b4f32f592c11bba8fef5e10098 100644 --- a/.opencode/node_modules/effect/src/unstable/observability/OtlpLogger.ts +++ b/.opencode/node_modules/effect/src/unstable/observability/OtlpLogger.ts @@ -1,26 +1,44 @@ /** + * Exports Effect log entries over OTLP/HTTP. + * + * The logger turns Effect log entries into OTLP log records and sends them to a + * logs endpoint, such as an OpenTelemetry Collector or vendor OTLP endpoint. It + * includes log levels, messages, annotations, causes, fiber ids, optional log + * spans, and current trace/span ids when they are present. + * * @since 4.0.0 */ import * as Arr from "../../Array.ts" import * as Cause from "../../Cause.ts" import { Clock } from "../../Clock.ts" +import * as Config from "../../Config.ts" import * as Duration from "../../Duration.ts" import * as Effect from "../../Effect.ts" -import type * as Layer from "../../Layer.ts" +import * as Layer from "../../Layer.ts" import * as Logger from "../../Logger.ts" import type * as LogLevel from "../../LogLevel.ts" +import * as Option from "../../Option.ts" import { CurrentLogAnnotations, CurrentLogSpans } from "../../References.ts" import type * as Scope from "../../Scope.ts" import type * as Headers from "../http/Headers.ts" import type * as HttpClient from "../http/HttpClient.ts" +import * as OtlpEnv from "./internal/otlpEnv.ts" import * as Exporter from "./OtlpExporter.ts" import type { AnyValue, Fixed64, KeyValue, Resource } from "./OtlpResource.ts" import * as OtlpResource from "./OtlpResource.ts" import { OtlpSerialization } from "./OtlpSerialization.ts" /** + * Creates an Effect `Logger` that exports log records through OTLP. + * + * **Details** + * + * The logger serializes records with the configured resource, sends them + * through the OTLP exporter, and requires `Scope` so pending records can be + * flushed on shutdown. + * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const make: ( options: { @@ -76,8 +94,14 @@ export const make: ( }) /** + * Layer that installs the OTLP logger created by `make`. + * + * **Details** + * + * By default the OTLP logger is merged with any existing loggers. + * + * @category layers * @since 4.0.0 - * @category Layers */ export const layer = (options: { readonly url: string @@ -98,6 +122,61 @@ export const layer = (options: { }) /** + * Creates an OTLP logs layer from OpenTelemetry configuration. + * + * @category layers + * @since 4.0.0 + */ +export const layerFromConfig = (options?: { + readonly resource?: { + readonly serviceName?: string | undefined + readonly serviceVersion?: string | undefined + readonly attributes?: Record + } | undefined + readonly headers?: Headers.Input | undefined + readonly excludeLogSpans?: boolean | undefined + readonly mergeWithExisting?: boolean | undefined +}): Layer.Layer => + Effect.gen(function*() { + const { disabled, endpoint, exporters } = yield* Config.all({ + disabled: Config.boolean("OTEL_SDK_DISABLED").pipe(Config.withDefault(false)), + endpoint: OtlpEnv.endpoint("LOGS"), + exporters: OtlpEnv.exporters("LOGS") + }) + + if (disabled || !endpoint || !exporters.includes("otlp")) { + return Layer.empty + } + + const { baseTimeout, logsTimeout, exportTimeout, scheduleDelay, maxBatchSize } = yield* Config.all({ + baseTimeout: Config.option(Config.int("OTEL_EXPORTER_OTLP_TIMEOUT")), + logsTimeout: Config.option(Config.int("OTEL_EXPORTER_OTLP_LOGS_TIMEOUT")), + exportTimeout: Config.option(Config.int("OTEL_BLRP_EXPORT_TIMEOUT")), + scheduleDelay: Config.option(Config.int("OTEL_BLRP_SCHEDULE_DELAY")), + maxBatchSize: Config.option(Config.int("OTEL_BLRP_MAX_EXPORT_BATCH_SIZE")) + }) + + const shutdownTimeout = Option.firstSomeOf([logsTimeout, baseTimeout, exportTimeout]).pipe( + Option.map((_) => Duration.millis(_)) + ) + const exportInterval = Option.map(scheduleDelay, (_) => Duration.millis(_)) + + return layer({ + url: endpoint.toString(), + resource: options?.resource, + headers: options?.headers ?? (yield* OtlpEnv.headers("LOGS")), + exportInterval: Option.getOrUndefined(exportInterval), + maxBatchSize: Option.getOrUndefined(maxBatchSize), + shutdownTimeout: Option.getOrUndefined(shutdownTimeout), + excludeLogSpans: options?.excludeLogSpans, + mergeWithExisting: options?.mergeWithExisting + }) + }).pipe(Effect.orDie, Layer.unwrap) + +/** + * OTLP logs payload serialized by `OtlpLogger`. + * + * @category models * @since 4.0.0 */ export interface LogsData { diff --git a/.opencode/node_modules/effect/src/unstable/observability/OtlpMetrics.ts b/.opencode/node_modules/effect/src/unstable/observability/OtlpMetrics.ts index e27604b01cccb127e0ff4ba59eab0386731d49c3..6ec1e9c6e67b4dc72e8d3373010f77d195b94e21 100644 --- a/.opencode/node_modules/effect/src/unstable/observability/OtlpMetrics.ts +++ b/.opencode/node_modules/effect/src/unstable/observability/OtlpMetrics.ts @@ -1,34 +1,47 @@ /** + * Exports Effect metrics over OTLP/HTTP. + * + * This module periodically snapshots metrics from the current Effect context, + * serializes them as OTLP resource metrics, and posts them to a metrics + * endpoint such as an OpenTelemetry Collector or vendor intake. It is meant for + * long-running services that already update `Metric` counters, gauges, + * histograms, frequencies, or summaries. The exporter supports cumulative + * reporting from a fixed start time and delta reporting from the previous + * export. + * * @since 4.0.0 */ import * as Arr from "../../Array.ts" import { Clock } from "../../Clock.ts" +import * as Config from "../../Config.ts" import * as Duration from "../../Duration.ts" import * as Effect from "../../Effect.ts" import * as Layer from "../../Layer.ts" import * as Metric from "../../Metric.ts" +import * as Option from "../../Option.ts" import type * as Scope from "../../Scope.ts" import type * as Headers from "../http/Headers.ts" import type { HttpBody } from "../http/HttpBody.ts" import type * as HttpClient from "../http/HttpClient.ts" +import * as OtlpEnv from "./internal/otlpEnv.ts" import * as Exporter from "./OtlpExporter.ts" import type { Fixed64, KeyValue } from "./OtlpResource.ts" import * as OtlpResource from "./OtlpResource.ts" import { OtlpSerialization } from "./OtlpSerialization.ts" /** - * Determines how metric values relate to the time interval over which they - * are aggregated. + * Determines how metric values relate to the time interval over which they are aggregated. + * + * **Details** + * + * `"cumulative"` reports total since a fixed start time. Each data point depends on all previous measurements. This is the default behavior. * - * - `"cumulative"`: Reports total since a fixed start time. Each data point - * depends on all previous measurements. This is the default behavior. + * `"delta"` reports changes since the last export. Each interval is independent with no dependency on previous measurements. * - * - `"delta"`: Reports changes since the last export. Each interval is - * independent with no dependency on previous measurements. + * **Example** (Configuring aggregation temporality) * - * @example * ```ts - * import * as OtlpMetrics from "effect/unstable/observability/OtlpMetrics" + * import { OtlpMetrics } from "effect/unstable/observability" * * // Use delta temporality for backends that prefer it (e.g., Datadog, Dynatrace) * const metricsLayer = OtlpMetrics.layer({ @@ -43,14 +56,20 @@ import { OtlpSerialization } from "./OtlpSerialization.ts" * }) * ``` * + * @category models * @since 4.0.0 - * @category Models */ export type AggregationTemporality = "cumulative" | "delta" /** + * Starts a scoped OTLP metrics exporter. + * + * **Details** + * + * The exporter snapshots registered Effect metrics on the configured interval, serializes them with the selected aggregation temporality, and flushes during scope finalization up to `shutdownTimeout`. + * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const make: (options: { readonly url: string @@ -429,8 +448,10 @@ export const make: (options: { }) /** + * Layer that starts the OTLP metrics exporter created by `make`. + * + * @category layers * @since 4.0.0 - * @category Layers */ export const layer = (options: { readonly url: string @@ -446,6 +467,61 @@ export const layer = (options: { }): Layer.Layer => Layer.effectDiscard(make(options)) /** + * Creates an OTLP metrics layer from OpenTelemetry configuration. + * + * @category layers + * @since 4.0.0 + */ +export const layerFromConfig = (options?: { + readonly resource?: { + readonly serviceName?: string | undefined + readonly serviceVersion?: string | undefined + readonly attributes?: Record + } | undefined + readonly headers?: Headers.Input | undefined +}): Layer.Layer => + Effect.gen(function*() { + const { disabled, endpoint, exporters } = yield* Config.all({ + disabled: Config.boolean("OTEL_SDK_DISABLED").pipe(Config.withDefault(false)), + endpoint: OtlpEnv.endpoint("METRICS"), + exporters: OtlpEnv.exporters("METRICS") + }) + if (disabled || !endpoint || !exporters.includes("otlp")) { + return Layer.empty + } + + const { baseTimeout, metricsTimeout, exportTimeout, exportInterval, temporalityPreference } = yield* Config.all({ + baseTimeout: Config.option(Config.int("OTEL_EXPORTER_OTLP_TIMEOUT")), + metricsTimeout: Config.option(Config.int("OTEL_EXPORTER_OTLP_METRICS_TIMEOUT")), + exportTimeout: Config.option(Config.int("OTEL_METRIC_EXPORT_TIMEOUT")), + exportInterval: Config.option( + Config.int("OTEL_METRIC_EXPORT_INTERVAL").pipe( + Config.map(Duration.millis) + ) + ), + temporalityPreference: Config.option( + Config.literals(["delta", "cumulative"], "OTEL_EXPORTER_OTLP_METRICS_TEMPORALITY_PREFERENCE") + ) + }) + + const shutdownTimeout = Option.firstSomeOf([metricsTimeout, baseTimeout, exportTimeout]).pipe( + Option.map((_) => Duration.millis(_)) + ) + + return layer({ + url: endpoint.toString(), + resource: options?.resource, + headers: options?.headers ?? (yield* OtlpEnv.headers("METRICS")), + exportInterval: Option.getOrUndefined(exportInterval), + shutdownTimeout: Option.getOrUndefined(shutdownTimeout), + temporality: Option.getOrUndefined(temporalityPreference) + }) + }).pipe(Effect.orDie, Layer.unwrap) + +/** + * OTLP metrics payload serialized by `OtlpMetrics`. + * + * @category models * @since 4.0.0 */ export interface MetricsData { diff --git a/.opencode/node_modules/effect/src/unstable/observability/OtlpResource.ts b/.opencode/node_modules/effect/src/unstable/observability/OtlpResource.ts index f686bd376d9a1ba9563f179fc496eda6ccc46b8a..8602e53ce9aa6f135a805f998973580ec64b6691 100644 --- a/.opencode/node_modules/effect/src/unstable/observability/OtlpResource.ts +++ b/.opencode/node_modules/effect/src/unstable/observability/OtlpResource.ts @@ -1,4 +1,11 @@ /** + * Builds OTLP resource metadata shared by exported telemetry. + * + * An OTLP resource describes the service and other attributes attached to every + * exported log, metric, or trace. This module builds resources from explicit + * options or OpenTelemetry environment variables and converts JavaScript values + * into OTLP attribute values. + * * @since 4.0.0 */ import * as Config from "../../Config.ts" @@ -7,8 +14,10 @@ import { format } from "../../Formatter.ts" import * as Schema from "../../Schema.ts" /** + * OTLP resource metadata attached to exported logs, metrics, and traces. + * + * @category models * @since 4.0.0 - * @category Models */ export interface Resource { /** Resource attributes */ @@ -18,8 +27,15 @@ export interface Resource { } /** + * Creates an OTLP resource from service metadata and additional attributes. + * + * **Details** + * + * The resource always includes `service.name`, includes `service.version` when + * provided, and converts custom attributes into OTLP attribute values. + * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const make = (options: { readonly serviceName: string @@ -51,8 +67,17 @@ export const make = (options: { } /** + * Creates an OTLP resource from explicit options and OpenTelemetry + * configuration. + * + * **Details** + * + * `OTEL_RESOURCE_ATTRIBUTES`, `OTEL_SERVICE_NAME`, and + * `OTEL_SERVICE_VERSION` override explicit options; missing required + * configuration is converted to a defect. + * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const fromConfig: ( options?: { @@ -65,19 +90,30 @@ export const fromConfig: ( readonly serviceVersion?: string | undefined readonly attributes?: Record | undefined }) { + const env = yield* Config.schema( + Schema.UndefinedOr(Config.Record(Schema.String, Schema.String)), + "OTEL_RESOURCE_ATTRIBUTES" + ) + + const serviceName = (yield* Config.schema(Schema.UndefinedOr(Schema.String), "OTEL_SERVICE_NAME")) + ?? env?.["service.name"] as string | undefined + ?? options?.attributes?.["service.name"] as string | undefined + ?? options?.serviceName + ?? (yield* Config.string("OTEL_SERVICE_NAME")) + + const serviceVersion = (yield* Config.schema(Schema.UndefinedOr(Schema.String), "OTEL_SERVICE_VERSION")) + ?? env?.["service.version"] as string | undefined + ?? options?.attributes?.["service.version"] as string | undefined + ?? options?.serviceVersion + const attributes = { - ...(yield* Config.schema( - Schema.UndefinedOr(Config.Record(Schema.String, Schema.String)), - "OTEL_RESOURCE_ATTRIBUTES" - )), - ...options?.attributes + ...options?.attributes, + ...env } - const serviceName = options?.serviceName ?? attributes["service.name"] as string ?? - (yield* Config.schema(Schema.String, "OTEL_SERVICE_NAME")) + delete attributes["service.name"] - const serviceVersion = options?.serviceVersion ?? attributes["service.version"] as string ?? - (yield* Config.schema(Schema.UndefinedOr(Schema.String), "OTEL_SERVICE_VERSION")) delete attributes["service.version"] + return make({ serviceName, serviceVersion, @@ -86,8 +122,19 @@ export const fromConfig: ( }, Effect.orDie) /** - * @since 4.0.0 + * Returns the `service.name` attribute from an OTLP resource. + * + * **When to use** + * + * Use when an OTLP resource is known to contain a string `service.name` and + * throwing is acceptable if that invariant is broken. + * + * **Gotchas** + * + * Throws if the resource does not contain a string `service.name` attribute. + * * @category Attributes + * @since 4.0.0 */ export const serviceNameUnsafe = (resource: Resource): string => { const serviceNameAttribute = resource.attributes.find( @@ -100,8 +147,10 @@ export const serviceNameUnsafe = (resource: Resource): string => { } /** - * @since 4.0.0 + * Converts key/value entries into OTLP `KeyValue` attributes. + * * @category Attributes + * @since 4.0.0 */ export const entriesToAttributes = (entries: Iterable<[string, unknown]>): Array => { const attributes: Array = [] @@ -115,8 +164,15 @@ export const entriesToAttributes = (entries: Iterable<[string, unknown]>): Array } /** - * @since 4.0.0 + * Converts an arbitrary JavaScript value into an OTLP `AnyValue`. + * + * **Details** + * + * Arrays are converted recursively, primitive values use their matching OTLP + * fields, and unsupported values are formatted as strings. + * * @category Attributes + * @since 4.0.0 */ export const unknownToAttributeValue = (value: unknown): AnyValue => { if (Array.isArray(value)) { @@ -155,8 +211,10 @@ export const unknownToAttributeValue = (value: unknown): AnyValue => { } /** + * An OTLP attribute represented as a string key and typed value. + * + * @category models * @since 4.0.0 - * @category Models */ export interface KeyValue { /** KeyValue key */ @@ -166,8 +224,10 @@ export interface KeyValue { } /** + * OTLP `AnyValue` payload for scalar, array, key/value-list, or byte values. + * + * @category models * @since 4.0.0 - * @category Models */ export interface AnyValue { /** AnyValue stringValue */ @@ -187,8 +247,10 @@ export interface AnyValue { } /** + * OTLP array value containing nested `AnyValue` entries. + * + * @category models * @since 4.0.0 - * @category Models */ export interface ArrayValue { /** ArrayValue values */ @@ -196,8 +258,10 @@ export interface ArrayValue { } /** + * OTLP key/value-list value containing nested attributes. + * + * @category models * @since 4.0.0 - * @category Models */ export interface KeyValueList { /** KeyValueList values */ @@ -205,8 +269,10 @@ export interface KeyValueList { } /** + * Low and high 32-bit parts of a 64-bit integer value. + * + * @category models * @since 4.0.0 - * @category Models */ export interface LongBits { low: number @@ -214,7 +280,9 @@ export interface LongBits { } /** + * Accepted runtime representations for an OTLP/protobuf fixed 64-bit value. + * + * @category models * @since 4.0.0 - * @category Models */ export type Fixed64 = LongBits | string | number diff --git a/.opencode/node_modules/effect/src/unstable/observability/OtlpSerialization.ts b/.opencode/node_modules/effect/src/unstable/observability/OtlpSerialization.ts index 5658f22fe04421393279b713172bb37b919c9b63..5bf7a75585e732edd594ec8dd10cc3f728445ff1 100644 --- a/.opencode/node_modules/effect/src/unstable/observability/OtlpSerialization.ts +++ b/.opencode/node_modules/effect/src/unstable/observability/OtlpSerialization.ts @@ -1,4 +1,10 @@ /** + * Serializes OTLP payloads into HTTP request bodies. + * + * Signal exporters build trace, metric, and log data structures in memory. This + * module provides the service that turns those structures into JSON or protobuf + * HTTP bodies before they are posted to an OTLP collector. + * * @since 4.0.0 */ import * as Context from "../../Context.ts" @@ -10,8 +16,11 @@ import type { MetricsData } from "./OtlpMetrics.ts" import type { TraceData } from "./OtlpTracer.ts" /** + * Service for serializing OTLP traces, metrics, and logs into HTTP request + * bodies. + * + * @category services * @since 4.0.0 - * @category Services */ export class OtlpSerialization extends Context.Service HttpBody.HttpBody @@ -20,8 +29,10 @@ export class OtlpSerialization extends Context.Service()("effect/observability/OtlpSerialization") {} /** + * Provides `OtlpSerialization` using OTLP/HTTP JSON bodies. + * + * @category layers * @since 4.0.0 - * @category Layers */ export const layerJson = Layer.succeed(OtlpSerialization, { traces: (spans) => HttpBody.jsonUnsafe(spans), @@ -30,8 +41,11 @@ export const layerJson = Layer.succeed(OtlpSerialization, { }) /** + * Provides `OtlpSerialization` using protobuf-encoded OTLP bodies with the + * `application/x-protobuf` content type. + * + * @category layers * @since 4.0.0 - * @category Layers */ export const layerProtobuf = Layer.succeed(OtlpSerialization, { traces: (spans) => diff --git a/.opencode/node_modules/effect/src/unstable/observability/OtlpTracer.ts b/.opencode/node_modules/effect/src/unstable/observability/OtlpTracer.ts index 09fc6c1cf9235a21a779c9296c51169e61f08924..8410fe9a9a657d5a15ccbcbc75f8d3e7f7478805 100644 --- a/.opencode/node_modules/effect/src/unstable/observability/OtlpTracer.ts +++ b/.opencode/node_modules/effect/src/unstable/observability/OtlpTracer.ts @@ -1,7 +1,17 @@ /** + * Exports Effect tracing spans over OTLP/HTTP. + * + * This module creates a `Tracer.Tracer` backed by the shared OTLP batch + * exporter, so spans created by Effect tracing APIs can be sent to an + * OpenTelemetry Collector, vendor endpoint, or local collector. Exported spans + * include identifiers, parent links, attributes, events, timing, kind, and + * status information. Use the constructor directly or install it through the + * provided layer. + * * @since 4.0.0 */ import * as Cause from "../../Cause.ts" +import * as Config from "../../Config.ts" import type * as Context from "../../Context.ts" import * as Duration from "../../Duration.ts" import * as Effect from "../../Effect.ts" @@ -14,6 +24,7 @@ import * as Tracer from "../../Tracer.ts" import type { ExtractTag, Mutable } from "../../Types.ts" import type * as Headers from "../http/Headers.ts" import type * as HttpClient from "../http/HttpClient.ts" +import * as OtlpEnv from "./internal/otlpEnv.ts" import * as Exporter from "./OtlpExporter.ts" import type { KeyValue, Resource } from "./OtlpResource.ts" import { entriesToAttributes } from "./OtlpResource.ts" @@ -21,8 +32,15 @@ import * as OtlpResource from "./OtlpResource.ts" import { OtlpSerialization } from "./OtlpSerialization.ts" /** + * Creates a `Tracer` that exports ended sampled spans to an OTLP traces endpoint. + * + * **Details** + * + * Spans are batched using the configured interval and batch size, serialized + * with `OtlpSerialization`, and flushed when the surrounding `Scope` closes. + * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const make: ( options: { @@ -99,8 +117,10 @@ export const make: ( }) /** + * Provides `Tracer.Tracer` using the OTLP tracer created by `make`. + * + * @category layers * @since 4.0.0 - * @category Layers */ export const layer: (options: { readonly url: string @@ -116,6 +136,59 @@ export const layer: (options: { readonly shutdownTimeout?: Duration.Input | undefined }) => Layer.Layer = flow(make, Layer.effect(Tracer.Tracer)) +/** + * Creates an OTLP traces layer from OpenTelemetry configuration. + * + * @category layers + * @since 4.0.0 + */ +export const layerFromConfig = (options?: { + readonly resource?: { + readonly serviceName?: string | undefined + readonly serviceVersion?: string | undefined + readonly attributes?: Record + } | undefined + readonly headers?: Headers.Input | undefined + readonly context?: ((primitive: Tracer.EffectPrimitive, span: Tracer.AnySpan) => X) | undefined +}): Layer.Layer => + Effect.gen(function*() { + const { disabled, endpoint, exporters } = yield* Config.all({ + disabled: Config.boolean("OTEL_SDK_DISABLED").pipe(Config.withDefault(false)), + endpoint: OtlpEnv.endpoint("TRACES"), + exporters: OtlpEnv.exporters("TRACES") + }) + + if (disabled || !endpoint || !exporters.includes("otlp")) { + return Layer.empty + } + + const { baseTimeout, tracesTimeout, exportTimeout, scheduleDelay, maxBatchSize } = yield* Config.all({ + baseTimeout: Config.option(Config.int("OTEL_EXPORTER_OTLP_TIMEOUT")), + tracesTimeout: Config.option(Config.int("OTEL_EXPORTER_OTLP_TRACES_TIMEOUT")), + exportTimeout: Config.option(Config.int("OTEL_BSP_EXPORT_TIMEOUT")), + scheduleDelay: Config.option( + Config.int("OTEL_BSP_SCHEDULE_DELAY").pipe( + Config.map(Duration.millis) + ) + ), + maxBatchSize: Config.option(Config.int("OTEL_BSP_MAX_EXPORT_BATCH_SIZE")) + }) + + const shutdownTimeout = Option.firstSomeOf([tracesTimeout, baseTimeout, exportTimeout]).pipe( + Option.map((_) => Duration.millis(_)) + ) + + return layer({ + url: endpoint.toString(), + resource: options?.resource, + headers: options?.headers ?? (yield* OtlpEnv.headers("TRACES")), + exportInterval: Option.getOrUndefined(scheduleDelay), + maxBatchSize: Option.getOrUndefined(maxBatchSize), + context: options?.context, + shutdownTimeout: Option.getOrUndefined(shutdownTimeout) + }) + }).pipe(Effect.orDie, Layer.unwrap) + // internal interface SpanImpl extends Tracer.Span { @@ -274,6 +347,9 @@ const makeOtlpSpan = (self: SpanImpl): OtlpSpan => { } /** + * Root OTLP traces payload containing spans grouped by resource. + * + * @category models * @since 4.0.0 */ export interface TraceData { @@ -281,6 +357,9 @@ export interface TraceData { } /** + * Group of OTLP scope spans associated with a single resource. + * + * @category models * @since 4.0.0 */ export interface ResourceSpan { @@ -290,6 +369,9 @@ export interface ResourceSpan { } /** + * Group of OTLP spans emitted by a single instrumentation scope. + * + * @category models * @since 4.0.0 */ export interface ScopeSpan { diff --git a/.opencode/node_modules/effect/src/unstable/observability/PrometheusMetrics.ts b/.opencode/node_modules/effect/src/unstable/observability/PrometheusMetrics.ts index 643123558d318223b7f4471672c408b0d24fb9b4..b2a48b74beace21ec52538af9bfcabb06abafad8 100644 --- a/.opencode/node_modules/effect/src/unstable/observability/PrometheusMetrics.ts +++ b/.opencode/node_modules/effect/src/unstable/observability/PrometheusMetrics.ts @@ -1,29 +1,9 @@ /** - * Prometheus metrics exporter for Effect's Metric system. + * Formats Effect metrics for Prometheus. * - * This module provides functionality to export Effect metrics in the Prometheus - * exposition format, making them scrapeable by Prometheus servers. - * - * @example - * ```ts - * import { Effect, Metric } from "effect" - * import * as PrometheusMetrics from "effect/unstable/observability/PrometheusMetrics" - * - * const program = Effect.gen(function*() { - * // Create and update metrics - * const counter = Metric.counter("http_requests_total", { - * description: "Total HTTP requests" - * }) - * yield* Metric.update(counter, 42) - * - * // Format metrics for Prometheus - * const output = yield* PrometheusMetrics.format() - * console.log(output) - * // # HELP http_requests_total Total HTTP requests - * // # TYPE http_requests_total counter - * // http_requests_total 42 - * }) - * ``` + * This module reads metrics from the current Effect context and renders them in + * the Prometheus text format. It can also register a pull-based HTTP endpoint, + * such as `/metrics`, for Prometheus to scrape. * * @since 4.0.0 */ @@ -37,25 +17,26 @@ import * as HttpServerResponse from "../http/HttpServerResponse.ts" /** * A function that transforms metric names before formatting. * - * @example + * **Example** (Mapping metric names) + * * ```ts - * import type * as PrometheusMetrics from "effect/unstable/observability/PrometheusMetrics" + * import type { PrometheusMetrics } from "effect/unstable/observability" * * // Convert camelCase to snake_case * const mapper: PrometheusMetrics.MetricNameMapper = (name) => * name.replace(/([a-z])([A-Z])/g, "$1_$2").toLowerCase() * ``` * + * @category models * @since 4.0.0 - * @category Models */ export type MetricNameMapper = (name: string) => string /** * Options for formatting metrics. * + * @category options * @since 4.0.0 - * @category Models */ export interface FormatOptions { /** @@ -72,8 +53,8 @@ export interface FormatOptions { /** * Options for exporting Prometheus metrics over HTTP. * + * @category options * @since 4.0.0 - * @category Models */ export interface HttpOptions extends FormatOptions { /** @@ -83,12 +64,13 @@ export interface HttpOptions extends FormatOptions { } /** - * Format all metrics in the registry to Prometheus exposition format. + * Formats all metrics in the registry to Prometheus exposition format. + * + * **Example** (Formatting metrics) * - * @example * ```ts * import { Effect, Metric } from "effect" - * import * as PrometheusMetrics from "effect/unstable/observability/PrometheusMetrics" + * import { PrometheusMetrics } from "effect/unstable/observability" * * const program = Effect.gen(function*() { * const counter = Metric.counter("api_requests_total", { @@ -109,8 +91,8 @@ export interface HttpOptions extends FormatOptions { * }) * ``` * + * @category formatting * @since 4.0.0 - * @category Formatting */ export const format: (options?: FormatOptions | undefined) => Effect.Effect = Effect.fnUntraced( function*(options) { @@ -120,13 +102,17 @@ export const format: (options?: FormatOptions | undefined) => Effect.Effect, @@ -162,13 +148,16 @@ export const formatUnsafe = ( * Creates a Layer that registers a `/metrics` HTTP endpoint for Prometheus * scraping. * + * **Details** + * * This layer automatically adds a GET route to your HTTP router that serves * metrics in Prometheus exposition format. By default, the endpoint is * registered at `/metrics`, but this can be customized via the `path` option. * - * @example + * **Example** (Serving metrics over HTTP) + * * ```ts - * import * as PrometheusMetrics from "effect/unstable/observability/PrometheusMetrics" + * import { PrometheusMetrics } from "effect/unstable/observability" * * // Create a layer that adds /metrics endpoint to the router * const PrometheusLayer = PrometheusMetrics.layerHttp() @@ -180,8 +169,8 @@ export const formatUnsafe = ( * }) * ``` * - * @since 4.0.0 * @category Http + * @since 4.0.0 */ export const layerHttp = ( options?: HttpOptions | undefined diff --git a/.opencode/node_modules/effect/src/unstable/observability/index.ts b/.opencode/node_modules/effect/src/unstable/observability/index.ts index e84562be970ced42728a02a0d8ef07de302ffd28..4b1c407c4aa1f70f89416341d5fcb5e949c3f5c0 100644 --- a/.opencode/node_modules/effect/src/unstable/observability/index.ts +++ b/.opencode/node_modules/effect/src/unstable/observability/index.ts @@ -40,32 +40,6 @@ export * as OtlpSerialization from "./OtlpSerialization.ts" export * as OtlpTracer from "./OtlpTracer.ts" /** - * Prometheus metrics exporter for Effect's Metric system. - * - * This module provides functionality to export Effect metrics in the Prometheus - * exposition format, making them scrapeable by Prometheus servers. - * - * @example - * ```ts - * import { Effect, Metric } from "effect" - * import * as PrometheusMetrics from "effect/unstable/observability/PrometheusMetrics" - * - * const program = Effect.gen(function*() { - * // Create and update metrics - * const counter = Metric.counter("http_requests_total", { - * description: "Total HTTP requests" - * }) - * yield* Metric.update(counter, 42) - * - * // Format metrics for Prometheus - * const output = yield* PrometheusMetrics.format() - * console.log(output) - * // # HELP http_requests_total Total HTTP requests - * // # TYPE http_requests_total counter - * // http_requests_total 42 - * }) - * ``` - * * @since 4.0.0 */ export * as PrometheusMetrics from "./PrometheusMetrics.ts" diff --git a/.opencode/node_modules/effect/src/unstable/observability/internal/otlpEnv.ts b/.opencode/node_modules/effect/src/unstable/observability/internal/otlpEnv.ts new file mode 100644 index 0000000000000000000000000000000000000000..1004a83e1f572af652034ce7f1e924b0025762dd --- /dev/null +++ b/.opencode/node_modules/effect/src/unstable/observability/internal/otlpEnv.ts @@ -0,0 +1,39 @@ +import * as Config from "../../../Config.ts" +import * as Schema from "../../../Schema.ts" +import * as SchemaGetter from "../../../SchemaGetter.ts" + +export type Signal = "LOGS" | "METRICS" | "TRACES" + +const ExporterList = Config.Array(Schema.String).pipe( + Schema.decode({ + decode: SchemaGetter.transform((_) => _.map((_) => _.toLowerCase().trim()).filter((_) => _ !== "")), + encode: SchemaGetter.passthrough() + }) +) + +const HeadersRecord = Config.Record(Schema.String, Schema.String) + +export const headers = (signal: Signal) => + Config.schema(HeadersRecord, `OTEL_EXPORTER_OTLP_${signal}_HEADERS`).pipe( + Config.orElse(() => Config.schema(HeadersRecord, "OTEL_EXPORTER_OTLP_HEADERS")), + Config.withDefault(undefined) + ) + +export const endpoint = (signal: Signal) => + Config.url(`OTEL_EXPORTER_OTLP_${signal}_ENDPOINT`).pipe( + Config.orElse(() => + Config.url("OTEL_EXPORTER_OTLP_ENDPOINT").pipe( + Config.map((url) => { + const slash = url.pathname.endsWith("/") ? "" : "/" + url.pathname += `${slash}v1/${signal.toLowerCase()}` + return url + }) + ) + ), + Config.withDefault(undefined) + ) + +export const exporters = (signal: Signal) => + Config.schema(ExporterList, `OTEL_${signal}_EXPORTER`).pipe( + Config.withDefault>([]) + ) diff --git a/.opencode/node_modules/effect/src/unstable/persistence/KeyValueStore.ts b/.opencode/node_modules/effect/src/unstable/persistence/KeyValueStore.ts index f18d6bbc6d6abbba74e9db8d876f810c931eebc6..834fc7849e3d584967aeabc8701e44a64e791e4e 100644 --- a/.opencode/node_modules/effect/src/unstable/persistence/KeyValueStore.ts +++ b/.opencode/node_modules/effect/src/unstable/persistence/KeyValueStore.ts @@ -1,4 +1,13 @@ /** + * Provides effectful key/value storage for persistence backends. + * + * `KeyValueStore` is a service for storing string or binary values by key. It + * is useful for lightweight durable state, browser storage, local files, SQL + * tables, tests, and as a storage building block for higher-level persistence + * APIs. This module includes store operations, prefixed views, schema-aware JSON + * storage, error values, and layers for memory, filesystem, Web Storage, and + * SQL-backed stores. + * * @since 4.0.0 */ import * as Context from "../../Context.ts" @@ -21,8 +30,10 @@ import type { SqlError } from "../sql/SqlError.ts" const TypeId = "~effect/persistence/KeyValueStore" as const /** + * Effectful key/value store service for string and binary values. + * + * @category models * @since 4.0.0 - * @category Models */ export interface KeyValueStore { readonly [TypeId]: typeof TypeId @@ -78,14 +89,21 @@ export interface KeyValueStore { readonly has: (key: string) => Effect.Effect /** - * Checks if the KeyValueStore contains any entries. + * Checks whether the KeyValueStore contains any entries. */ readonly isEmpty: Effect.Effect } /** + * Implementation callbacks used by `make` to construct a `KeyValueStore`. + * + * **Details** + * + * Primitive operations are required, while helpers such as `has`, `isEmpty`, + * and `modify` can be supplied to override the defaults. + * + * @category options * @since 4.0.0 - * @category Models */ export type MakeOptions = Partial & { /** @@ -120,8 +138,11 @@ export type MakeOptions = Partial & { } /** + * Implementation callbacks for adapting a string-only backing store into a + * `KeyValueStore`. + * + * @category options * @since 4.0.0 - * @category Models */ export type MakeStringOptions = Partial> & { /** @@ -153,8 +174,11 @@ export type MakeStringOptions = Partial> & { const ErrorTypeId = "~effect/persistence/KeyValueStore/KeyValueStoreError" as const /** + * Error raised by key/value store operations, including the failed method, + * optional key, message, and cause. + * + * @category errors * @since 4.0.0 - * @category Errors */ export class KeyValueStoreError extends Data.TaggedError("KeyValueStoreError")<{ message: string @@ -163,14 +187,23 @@ export class KeyValueStoreError extends Data.TaggedError("KeyValueStoreError")<{ cause?: unknown }> { /** + * Marks this value as a key-value store error for runtime guards. + * * @since 4.0.0 */ readonly [ErrorTypeId]: typeof ErrorTypeId = ErrorTypeId } /** + * Service tag for string and binary key/value storage. + * + * **When to use** + * + * Use to access or provide the persistence store used for lightweight durable + * state. + * + * @category services * @since 4.0.0 - * @category tags */ export const KeyValueStore: Context.Service< KeyValueStore, @@ -178,8 +211,15 @@ export const KeyValueStore: Context.Service< > = Context.Service("effect/persistence/KeyValueStore") /** - * @since 4.0.0 + * Constructs a `KeyValueStore` from primitive store operations. + * + * **Details** + * + * Default implementations are derived for `has`, `isEmpty`, `modify`, and + * `modifyUint8Array` unless they are provided in the options. + * * @category constructors + * @since 4.0.0 */ export const make = (options: MakeOptions): KeyValueStore => KeyValueStore.of({ @@ -215,8 +255,15 @@ export const make = (options: MakeOptions): KeyValueStore => }) /** - * @since 4.0.0 + * Adapts a string-only backing store into a `KeyValueStore`. + * + * **Details** + * + * `Uint8Array` values are stored as base64 strings. `getUint8Array` decodes + * base64 values and falls back to UTF-8 encoding for non-base64 strings. + * * @category constructors + * @since 4.0.0 */ export const makeStringOnly = ( options: MakeStringOptions @@ -241,18 +288,27 @@ export const makeStringOnly = ( } /** - * @since 4.0.0 + * Returns a view of a `KeyValueStore` that prepends the given prefix to every + * key. + * * @category combinators + * @since 4.0.0 */ export const prefix: { /** - * @since 4.0.0 + * Returns a view of a `KeyValueStore` that prepends the given prefix to every + * key. + * * @category combinators + * @since 4.0.0 */ (prefix: string): (self: KeyValueStore) => KeyValueStore /** - * @since 4.0.0 + * Returns a view of a `KeyValueStore` that prepends the given prefix to every + * key. + * * @category combinators + * @since 4.0.0 */ (self: KeyValueStore, prefix: string): KeyValueStore } = dual(2, (self: KeyValueStore, prefix: string): KeyValueStore => ({ @@ -267,8 +323,10 @@ export const prefix: { })) /** - * @since 4.0.0 + * Provides a process-local in-memory `KeyValueStore` backed by a `Map`. + * * @category layers + * @since 4.0.0 */ export const layerMemory: Layer.Layer = Layer.sync(KeyValueStore)(() => { const store = new Map() @@ -293,8 +351,14 @@ export const layerMemory: Layer.Layer = Layer.sync(KeyValueStore) }) /** - * @since 4.0.0 + * Provides a `KeyValueStore` backed by files in the specified directory. + * + * **Details** + * + * The directory is created if needed, and each key is encoded as a file name. + * * @category layers + * @since 4.0.0 */ export const layerFileSystem = ( directory: string @@ -394,8 +458,10 @@ export const layerFileSystem = ( })) /** - * @since 4.0.0 + * Options for configuring the SQL-backed `KeyValueStore` layer. + * * @category layers + * @since 4.0.0 */ export interface LayerSqlOptions { /** @@ -407,8 +473,15 @@ export interface LayerSqlOptions { } /** - * @since 4.0.0 + * Provides a SQL-backed `KeyValueStore`. + * + * **Details** + * + * The layer creates the configured table if it does not exist and stores both + * string and binary values through the current `SqlClient`. + * * @category layers + * @since 4.0.0 */ export const layerSql = ( options: LayerSqlOptions = {} @@ -617,8 +690,10 @@ export const layerSql = ( const SchemaStoreTypeId = "~effect/persistence/KeyValueStore/SchemaStore" as const /** - * @since 4.0.0 + * Schema-aware view of a `KeyValueStore` that stores values as encoded JSON. + * * @category SchemaStore + * @since 4.0.0 */ export interface SchemaStore { readonly [SchemaStoreTypeId]: typeof SchemaStoreTypeId @@ -670,14 +745,16 @@ export interface SchemaStore { readonly has: (key: string) => Effect.Effect /** - * Checks if the KeyValueStore contains any entries. + * Checks whether the KeyValueStore contains any entries. */ readonly isEmpty: Effect.Effect } /** - * @since 4.0.0 + * Adapts a `KeyValueStore` into a `SchemaStore` using the schema's JSON codec. + * * @category SchemaStore + * @since 4.0.0 */ export const toSchemaStore = (self: KeyValueStore, schema: S): SchemaStore => { const serializer = Schema.toCodecJson(schema) @@ -725,12 +802,16 @@ export const toSchemaStore = (self: KeyValueStore, schema: } /** - * Creates an KeyValueStorage from an instance of the `Storage` api. + * Provides a `KeyValueStore` backed by a Web `Storage` instance such as + * `localStorage` or `sessionStorage`. * - * @see https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API + * **Details** + * + * This layer uses the Web Storage API: + * https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API * - * @since 4.0.0 * @category layers + * @since 4.0.0 */ export const layerStorage = ( evaluate: LazyArg @@ -741,51 +822,56 @@ export const layerStorage = ( get: (key: string) => Effect.try({ try: () => storage.getItem(key) ?? undefined, - catch: () => + catch: (cause) => new KeyValueStoreError({ key, method: "get", - message: `Unable to get item with key ${key}` + message: `Unable to get item with key ${key}`, + cause }) }), set: (key: string, value: string) => Effect.try({ try: () => storage.setItem(key, value), - catch: () => + catch: (cause) => new KeyValueStoreError({ key, method: "set", - message: `Unable to set item with key ${key}` + message: `Unable to set item with key ${key}`, + cause }) }), remove: (key: string) => Effect.try({ try: () => storage.removeItem(key), - catch: () => + catch: (cause) => new KeyValueStoreError({ key, method: "remove", - message: `Unable to remove item with key ${key}` + message: `Unable to remove item with key ${key}`, + cause }) }), clear: Effect.try({ try: () => storage.clear(), - catch: () => + catch: (cause) => new KeyValueStoreError({ method: "clear", - message: `Unable to clear storage` + message: `Unable to clear storage`, + cause }) }), size: Effect.try({ try: () => storage.length, - catch: () => + catch: (cause) => new KeyValueStoreError({ method: "size", - message: `Unable to get size` + message: `Unable to get size`, + cause }) }) }) diff --git a/.opencode/node_modules/effect/src/unstable/persistence/Persistable.ts b/.opencode/node_modules/effect/src/unstable/persistence/Persistable.ts index bdadf8e1c4f0646bbe84cbbd219f973fdd2728cc..4470dc42979f0031dc85d1b0494d2519f92114fc 100644 --- a/.opencode/node_modules/effect/src/unstable/persistence/Persistable.ts +++ b/.opencode/node_modules/effect/src/unstable/persistence/Persistable.ts @@ -1,4 +1,10 @@ /** + * Describes request values whose results can be persisted. + * + * A `Persistable` request has a primary key and schemas for its success and + * error results. `Persistence` and `PersistedCache` use that information to + * store the request's `Exit` value and restore it later from a backing store. + * * @since 4.0.0 */ import type * as Duration from "../../Duration.ts" @@ -11,14 +17,25 @@ import type * as Types from "../../Types.ts" import type { PersistenceError } from "./Persistence.ts" /** + * Defines the property key used to attach success and error schemas to persistable + * requests. + * + * **When to use** + * + * Use to implement persistable request values by attaching success and error + * schemas at this property key. + * + * @category symbols * @since 4.0.0 - * @category Symbols */ export const symbol = "~effect/persistence/Persistable" as const /** + * A primary-keyed request value whose success and error results can be + * serialized for persistence. + * + * @category models * @since 4.0.0 - * @category Models */ export interface Persistable extends PrimaryKey.PrimaryKey { readonly [symbol]: { @@ -28,54 +45,72 @@ export interface Persistable extends } /** + * Any persistable request regardless of its success and error schemas. + * + * @category models * @since 4.0.0 - * @category Models */ export type Any = Persistable /** + * Extracts the success schema from a persistable request. + * + * @category models * @since 4.0.0 - * @category Models */ export type SuccessSchema = A["~effect/persistence/Persistable"]["success"] /** + * Extracts the success value type from a persistable request. + * + * @category models * @since 4.0.0 - * @category Models */ export type Success = A["~effect/persistence/Persistable"]["success"]["Type"] /** + * Extracts the error schema from a persistable request. + * + * @category models * @since 4.0.0 - * @category Models */ export type ErrorSchema = A["~effect/persistence/Persistable"]["error"] /** + * Extracts the error value type from a persistable request. + * + * @category models * @since 4.0.0 - * @category Models */ export type Error = A["~effect/persistence/Persistable"]["error"]["Type"] /** + * Services required to decode a persisted success or error value for the + * request. + * + * @category models * @since 4.0.0 - * @category Models */ export type DecodingServices = | A["~effect/persistence/Persistable"]["success"]["DecodingServices"] | A["~effect/persistence/Persistable"]["error"]["DecodingServices"] /** + * Services required to encode a success or error value for persistence. + * + * @category models * @since 4.0.0 - * @category Models */ export type EncodingServices = | A["~effect/persistence/Persistable"]["success"]["EncodingServices"] | A["~effect/persistence/Persistable"]["error"]["EncodingServices"] /** + * All schema services required to encode and decode a persistable request + * result. + * + * @category models * @since 4.0.0 - * @category Models */ export type Services = | A["~effect/persistence/Persistable"]["success"]["DecodingServices"] @@ -84,14 +119,24 @@ export type Services = | A["~effect/persistence/Persistable"]["error"]["EncodingServices"] /** + * Computes the time to live for a persisted result from the result `Exit` and + * request value. + * + * @category models * @since 4.0.0 - * @category Models */ export type TimeToLiveFn = (exit: Exit.Exit, Error>, request: K) => Duration.Input /** + * Creates request classes that implement `Persistable` and `Request.Request`. + * + * **Details** + * + * The generated class stores the supplied tag, derives its primary key from + * the payload, and carries schemas for persisted success and error exits. + * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const Class = < Config extends { @@ -154,15 +199,18 @@ export const Class = < } /** + * Returns the cached `Exit` schema for a persistable request's success and + * error schemas. + * + * @category accessors * @since 4.0.0 - * @category Accessors */ export const exitSchema = ( self: Persistable ): Schema.Exit => { let schema = exitSchemaCache.get(self) if (schema) return schema as Schema.Exit - schema = Schema.Exit(self[symbol].success, self[symbol].error, Schema.Defect) + schema = Schema.Exit(self[symbol].success, self[symbol].error, Schema.Defect()) exitSchemaCache.set(self, schema) return schema as Schema.Exit } @@ -170,8 +218,11 @@ export const exitSchema = ( const exitSchemaCache = new WeakMap, Schema.Exit>() /** + * Encodes an `Exit` for a persistable request using its success and error + * schemas. + * + * @category serialization * @since 4.0.0 - * @category Serialization */ export const serializeExit = ( self: Persistable, @@ -182,8 +233,11 @@ export const serializeExit = ( } /** + * Decodes a persisted value into an `Exit` for a persistable request using its + * success and error schemas. + * + * @category serialization * @since 4.0.0 - * @category Serialization */ export const deserializeExit = ( self: Persistable, diff --git a/.opencode/node_modules/effect/src/unstable/persistence/PersistedCache.ts b/.opencode/node_modules/effect/src/unstable/persistence/PersistedCache.ts index 6d9e7ad4eadba2300d119602908a02a516945ba4..b08cdc1ab77ebe81bc371213945b1ab125e51329 100644 --- a/.opencode/node_modules/effect/src/unstable/persistence/PersistedCache.ts +++ b/.opencode/node_modules/effect/src/unstable/persistence/PersistedCache.ts @@ -1,4 +1,11 @@ /** + * Combines in-memory caching with durable storage for `Persistable` requests. + * + * A `PersistedCache` checks a process-local `Cache`, then a named `Persistence` + * store, before running the supplied lookup. It stores the lookup `Exit`, so + * expensive or idempotent results can be reused across fibers, process restarts, + * or workers that share the same backing store. + * * @since 4.0.0 */ import * as Cache from "../../Cache.ts" @@ -14,8 +21,10 @@ import * as Persistence from "./Persistence.ts" const TypeId = "~effect/persistence/PersistedCache" as const /** + * Cache that combines an in-memory `Cache` with a persisted backing store. + * + * @category models * @since 4.0.0 - * @category Models */ export interface PersistedCache { readonly [TypeId]: typeof TypeId @@ -34,8 +43,16 @@ export interface PersistedCache { } /** + * Creates a persisted cache for `Persistable` request keys. + * + * **Details** + * + * The cache reads persisted exits before running the lookup, stores lookup + * exits with the configured persistent TTL, and also keeps a scoped in-memory + * cache with its own capacity and TTL. + * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const make: < K extends Persistable.Any, diff --git a/.opencode/node_modules/effect/src/unstable/persistence/PersistedQueue.ts b/.opencode/node_modules/effect/src/unstable/persistence/PersistedQueue.ts index e44fec1a07cce03f2fee4d376ba781cd5457318f..003ca315a101d398e5a013c173bbd8284c8ee03f 100644 --- a/.opencode/node_modules/effect/src/unstable/persistence/PersistedQueue.ts +++ b/.opencode/node_modules/effect/src/unstable/persistence/PersistedQueue.ts @@ -1,4 +1,13 @@ /** + * Stores schema-encoded queue work in persistent storage. + * + * A `PersistedQueue` keeps JSON-encoded values in a named queue and lets + * workers take one value at a time inside a scoped processing window. It is + * useful for durable handoffs, background jobs, outbox-style integrations, and + * work that should retry across fibers, process restarts, or multiple workers. + * This module includes a queue factory, store service, id-based de-duplication, + * retry handling, and in-memory, Redis, and SQL-backed store layers. + * * @since 4.0.0 */ import type * as Arr from "../../Array.ts" @@ -23,26 +32,40 @@ import type { SqlError } from "../sql/SqlError.ts" import * as Redis from "./Redis.ts" /** + * Runtime type identifier for `PersistedQueue` values. + * + * @category type IDs * @since 4.0.0 - * @category Type IDs */ export const TypeId: TypeId = "~effect/persistence/PersistedQueue" /** + * Type-level identifier used to brand `PersistedQueue` values. + * + * @category type IDs * @since 4.0.0 - * @category Type IDs */ export type TypeId = "~effect/persistence/PersistedQueue" /** + * Persistent queue of schema-encoded values. + * + * **Details** + * + * `offer` enqueues values by id, and `take` processes one value at a time, + * marking it complete on success or retrying it until the maximum attempts is + * reached. + * + * @category models * @since 4.0.0 - * @category Models */ export interface PersistedQueue { readonly [TypeId]: TypeId /** - * Adds an element to the queue. Returns the id of the enqueued element. + * Adds an element to the queue and returns the id of the enqueued element. + * + * **Details** * * If an element with the same id already exists in the queue, it will not be * added again. @@ -52,13 +75,14 @@ export interface PersistedQueue { }) => Effect.Effect /** - * Takes an element from the queue. - * If the queue is empty, it will wait until an element is available. + * Takes an element from the queue, waiting until one is available when the + * queue is empty. * - * If the returned effect succeeds, the element is marked as processed, - * otherwise it will be retried according to the provided options. + * **Details** * - * By default, max attempts is set to 10. + * If the returned effect succeeds, the element is marked as processed; + * otherwise it will be retried according to the provided options. By default, + * max attempts is set to 10. */ readonly take: ( f: (value: A, metadata: { @@ -72,8 +96,10 @@ export interface PersistedQueue { } /** + * Service for constructing named `PersistedQueue` instances from schemas. + * + * @category services * @since 4.0.0 - * @category Factory */ export class PersistedQueueFactory extends Context.Service< PersistedQueueFactory, @@ -86,8 +112,11 @@ export class PersistedQueueFactory extends Context.Service< >()("effect/persistence/PersistedQueue/PersistedQueueFactory") {} /** + * Accesses `PersistedQueueFactory` to create a named persisted queue for a + * schema. + * + * @category accessors * @since 4.0.0 - * @category Accessors */ export const make = (options: { readonly name: string @@ -99,8 +128,16 @@ export const make = (options: { > => PersistedQueueFactory.use((factory) => factory.make(options)) /** + * Creates a `PersistedQueueFactory` from the current `PersistedQueueStore`. + * + * **Details** + * + * Values are encoded and decoded with the supplied schema, automatically + * assigned an id when needed, and acknowledged or retried according to the + * `take` handler's exit. + * + * @category constructors * @since 4.0.0 - * @category Factory */ export const makeFactory = Effect.gen(function*() { const store = yield* PersistedQueueStore @@ -153,8 +190,10 @@ export const makeFactory = Effect.gen(function*() { }) /** + * Provides `PersistedQueueFactory` using the current `PersistedQueueStore`. + * + * @category layers * @since 4.0.0 - * @category Factory */ export const layer: Layer.Layer< PersistedQueueFactory, @@ -163,37 +202,57 @@ export const layer: Layer.Layer< > = Layer.effect(PersistedQueueFactory, makeFactory) /** + * Runtime type identifier for `PersistedQueueError`. + * + * @category type IDs * @since 4.0.0 - * @category Errors */ export const ErrorTypeId: ErrorTypeId = "~@effect/experimental/PersistedQueue/PersistedQueueError" /** + * Type-level identifier used to brand `PersistedQueueError` values. + * + * @category type IDs * @since 4.0.0 - * @category Errors */ export type ErrorTypeId = "~@effect/experimental/PersistedQueue/PersistedQueueError" /** + * Error raised by persisted queue store operations. + * + * @category errors * @since 4.0.0 - * @category Errors */ export class PersistedQueueError extends Schema.ErrorClass( "effect/persistence/PersistedQueue/PersistedQueueError" )({ _tag: Schema.tag("PersistedQueueError"), message: Schema.String, - cause: Schema.optional(Schema.Defect) + cause: Schema.optional(Schema.Defect()) }) { /** + * Marks this value as a persisted queue error for runtime guards. + * * @since 4.0.0 */ readonly [ErrorTypeId]: ErrorTypeId = ErrorTypeId } /** + * Defines the low-level backing store service used by `PersistedQueue`. + * + * **When to use** + * + * Use to provide the persistence backend that stores queued elements, scoped + * takes, retry attempts, and acknowledgements. + * + * **Details** + * + * The store persists offered elements and returns taken elements in a scope so + * the finalizer can complete or retry them based on the processing exit. + * + * @category store * @since 4.0.0 - * @category Store */ export class PersistedQueueStore extends Context.Service< PersistedQueueStore, @@ -223,8 +282,15 @@ export class PersistedQueueStore extends Context.Service< >()("effect/persistence/PersistedQueue/PersistedQueueStore") {} /** + * Provides an in-memory `PersistedQueueStore`. + * + * **Details** + * + * The store is process-local and volatile; failed takes are requeued until the + * configured maximum attempts is reached. + * + * @category store * @since 4.0.0 - * @category Store */ export const layerStoreMemory: Layer.Layer< PersistedQueueStore @@ -289,8 +355,16 @@ export const layerStoreMemory: Layer.Layer< }) /** + * Creates a Redis-backed `PersistedQueueStore`. + * + * **Details** + * + * The store uses Redis lists and hashes with worker locks, periodically + * refreshes locks while items are being processed, and moves exhausted items + * to a failed queue. + * + * @category store * @since 4.0.0 - * @category Store */ export const makeStoreRedis = Effect.fnUntraced(function*( options?: { @@ -648,8 +722,10 @@ end ) /** + * Provides a Redis-backed `PersistedQueueStore` using `makeStoreRedis`. + * + * @category store * @since 4.0.0 - * @category Store */ export const layerStoreRedis: ( options?: { @@ -665,8 +741,16 @@ export const layerStoreRedis: ( > = flow(makeStoreRedis, Layer.effect(PersistedQueueStore)) /** + * Creates a SQL-backed `PersistedQueueStore`. + * + * **Details** + * + * The store creates the queue table and indexes, acquires rows with + * per-worker locks, refreshes active locks while scoped takes are running, and + * retries or completes rows according to the processing exit. + * + * @category store * @since 4.0.0 - * @category Store */ export const makeStoreSql: ( options?: { @@ -1093,8 +1177,10 @@ class QueueKey extends Data.Class<{ }> {} /** + * Provides a SQL-backed `PersistedQueueStore` using `makeStoreSql`. + * + * @category store * @since 4.0.0 - * @category Store */ export const layerStoreSql: ( options?: { diff --git a/.opencode/node_modules/effect/src/unstable/persistence/Persistence.ts b/.opencode/node_modules/effect/src/unstable/persistence/Persistence.ts index af38488db11fcbf181dbf8c0812fb715ca82ec12..a374b100a9d73a70cd0043f6c705eae1fec1a748 100644 --- a/.opencode/node_modules/effect/src/unstable/persistence/Persistence.ts +++ b/.opencode/node_modules/effect/src/unstable/persistence/Persistence.ts @@ -1,4 +1,11 @@ /** + * Stores encoded results for `Persistable` requests. + * + * The `Persistence` service creates scoped stores keyed by each request's + * `PrimaryKey`. Stores read and write schema-encoded `Exit` values with + * optional TTLs, letting request workflows reuse expensive or idempotent results + * across fibers, process restarts, or workers that share a backing store. + * * @since 4.0.0 */ import * as Arr from "../../Array.ts" @@ -21,23 +28,30 @@ import * as Redis from "./Redis.ts" const ErrorTypeId = "~effect/persistence/Persistence/PersistenceError" as const /** - * @since 4.0.0 + * Error raised by persistence and backing-store operations. + * * @category errors + * @since 4.0.0 */ export class PersistenceError extends Schema.ErrorClass(ErrorTypeId)({ _tag: Schema.tag("PersistenceError"), message: Schema.String, - cause: Schema.optional(Schema.Defect) + cause: Schema.optional(Schema.Defect()) }) { /** + * Marks this value as a persistence error for runtime guards. + * * @since 4.0.0 */ readonly [ErrorTypeId]: typeof ErrorTypeId = ErrorTypeId } /** + * Service for creating scoped stores of persisted `Persistable` request + * results. + * + * @category models * @since 4.0.0 - * @category Models */ export class Persistence extends Context.Service()("effect/persistence/Persistence") {} /** - * @since 4.0.0 + * Typed store for persisted `Exit` values keyed by `Persistable` requests. + * * @category models + * @since 4.0.0 */ export interface PersistenceStore { readonly get: ( @@ -79,16 +95,21 @@ export interface PersistenceStore { } /** - * @since 4.0.0 + * Service for creating raw backing stores for persistence store ids. + * * @category BackingPersistence + * @since 4.0.0 */ export class BackingPersistence extends Context.Service Effect.Effect }>()("effect/persistence/BackingPersistence") {} /** - * @since 4.0.0 + * Raw persistence backing store for JSON-compatible objects with optional + * TTLs. + * * @category BackingPersistence + * @since 4.0.0 */ export interface BackingPersistenceStore { readonly get: (key: string) => Effect.Effect @@ -108,8 +129,15 @@ export interface BackingPersistenceStore { } /** - * @since 4.0.0 + * Provides `Persistence` from `BackingPersistence`. + * + * **Details** + * + * The layer serializes and deserializes `Persistable` exits, applies + * per-entry TTLs, and skips writes whose TTL is zero or negative. + * * @category layers + * @since 4.0.0 */ export const layer = Layer.effect(Persistence)(Effect.gen(function*() { const backing = yield* BackingPersistence @@ -202,8 +230,14 @@ export const layer = Layer.effect(Persistence)(Effect.gen(function*() { })) /** - * @since 4.0.0 + * Provides an in-memory `BackingPersistence` grouped by store id. + * + * **Details** + * + * Entries are process-local and expire according to their stored TTL. + * * @category layers + * @since 4.0.0 */ export const layerBackingMemory: Layer.Layer = Layer.sync(BackingPersistence)( () => { @@ -249,8 +283,15 @@ export const layerBackingMemory: Layer.Layer = Layer.sync(Ba ) /** - * @since 4.0.0 + * Provides SQL-backed persistence using one table per store id. + * + * **Details** + * + * Each table is created if needed and stores JSON-encoded values with optional + * expiration timestamps. + * * @category layers + * @since 4.0.0 */ export const layerBackingSqlMultiTable: Layer.Layer< BackingPersistence, @@ -457,8 +498,15 @@ export const layerBackingSqlMultiTable: Layer.Layer< })) /** - * @since 4.0.0 + * Provides SQL-backed persistence using a shared `effect_persistence` table. + * + * **Details** + * + * Rows are partitioned by `store_id` and store JSON-encoded values with + * optional expiration timestamps. + * * @category layers + * @since 4.0.0 */ export const layerBackingSql: Layer.Layer< BackingPersistence, @@ -695,8 +743,15 @@ export const layerBackingSql: Layer.Layer< })) /** - * @since 4.0.0 + * Provides Redis-backed persistence. + * + * **Details** + * + * Each store id is used as a key prefix, values are JSON-encoded, and finite + * TTLs are stored with Redis expiration. + * * @category layers + * @since 4.0.0 */ export const layerBackingRedis: Layer.Layer< BackingPersistence, @@ -849,8 +904,15 @@ end ) /** - * @since 4.0.0 + * Provides `BackingPersistence` using a `KeyValueStore`. + * + * **Details** + * + * Each store id becomes a key prefix, and values are stored as JSON with + * optional expiration timestamps. + * * @category layers + * @since 4.0.0 */ export const layerBackingKvs: Layer.Layer< BackingPersistence, @@ -945,46 +1007,64 @@ export const layerBackingKvs: Layer.Layer< })) /** - * @since 4.0.0 + * Provides `Persistence` backed by the current `KeyValueStore`. + * * @category layers + * @since 4.0.0 */ export const layerKvs: Layer.Layer = layer.pipe( Layer.provide(layerBackingKvs) ) /** - * @since 4.0.0 + * Provides `Persistence` backed by process-local in-memory storage. + * * @category layers + * @since 4.0.0 */ export const layerMemory: Layer.Layer = layer.pipe( Layer.provide(layerBackingMemory) ) /** - * @since 4.0.0 + * Provides `Persistence` backed by the current `Redis` service. + * * @category layers + * @since 4.0.0 */ export const layerRedis: Layer.Layer = layer.pipe( Layer.provide(layerBackingRedis) ) /** - * @since 4.0.0 + * Provides `Persistence` backed by SQL with one table per store id. + * * @category layers + * @since 4.0.0 */ export const layerSqlMultiTable: Layer.Layer = layer.pipe( Layer.provide(layerBackingSqlMultiTable) ) /** - * @since 4.0.0 + * Provides `Persistence` backed by SQL using a shared persistence table. + * * @category layers + * @since 4.0.0 */ export const layerSql: Layer.Layer = layer.pipe( Layer.provide(layerBackingSql) ) /** + * Converts a TTL to an absolute expiration timestamp in milliseconds. + * + * **Details** + * + * Returns `null` for no TTL and uses `clock.currentTimeMillisUnsafe`, so it is + * intended for backing-store internals. + * + * @category converting * @since 4.0.0 */ export const unsafeTtlToExpires = (clock: Clock.Clock, ttl: Duration.Duration | undefined): number | null => diff --git a/.opencode/node_modules/effect/src/unstable/persistence/RateLimiter.ts b/.opencode/node_modules/effect/src/unstable/persistence/RateLimiter.ts index ec974571aaf8ee6ca9c682cf631393fffad2e14c..575330fe1510ed5c618845a8dd3909279f525fe3 100644 --- a/.opencode/node_modules/effect/src/unstable/persistence/RateLimiter.ts +++ b/.opencode/node_modules/effect/src/unstable/persistence/RateLimiter.ts @@ -1,4 +1,13 @@ /** + * Coordinates rate limits through shared persistent storage. + * + * The `RateLimiter` service consumes tokens for string keys using fixed-window + * counters or token-bucket state. It can protect external APIs, enforce quotas, + * or throttle workers across fibers and processes that share the same store. + * This module includes helpers that fail when a limit is exceeded, return the + * delay needed before continuing, or wrap an effect so it waits automatically. + * It also defines the store service and in-memory or Redis-backed store layers. + * * @since 4.0.0 */ import * as Config from "../../Config.ts" @@ -11,20 +20,27 @@ import * as Schema from "../../Schema.ts" import * as Redis from "./Redis.ts" /** + * Runtime type identifier for `RateLimiter` values. + * + * @category type IDs * @since 4.0.0 - * @category Type IDs */ export const TypeId: TypeId = "~effect/persistence/RateLimiter" /** + * Type-level identifier used to brand `RateLimiter` values. + * + * @category type IDs * @since 4.0.0 - * @category Type IDs */ export type TypeId = "~effect/persistence/RateLimiter" /** + * Service for consuming rate-limit tokens for a key using fixed-window or + * token-bucket algorithms. + * + * @category models * @since 4.0.0 - * @category Models */ export interface RateLimiter { readonly [TypeId]: TypeId @@ -40,14 +56,28 @@ export interface RateLimiter { } /** + * Service tag for persistent token-consumption services. + * + * **When to use** + * + * Use to access or provide rate-limit checks backed by fixed-window counters or + * token-bucket state. + * + * @category services * @since 4.0.0 - * @category Tags */ export const RateLimiter: Context.Service = Context.Service(TypeId) /** + * Creates a `RateLimiter` from the current `RateLimiterStore`. + * + * **Details** + * + * The limiter supports fixed-window and token-bucket algorithms and either + * fails or returns a delay when a limit is exceeded. + * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const make: Effect.Effect< RateLimiter, @@ -182,8 +212,10 @@ export const make: Effect.Effect< }) /** + * Provides `RateLimiter` using the current `RateLimiterStore`. + * + * @category layers * @since 4.0.0 - * @category Layers */ export const layer: Layer.Layer< RateLimiter, @@ -192,7 +224,9 @@ export const layer: Layer.Layer< > = Layer.effect(RateLimiter, make) /** - * Access a function that applies rate limiting to an effect. + * Accesses a function that applies rate limiting to an effect. + * + * **Example** (Applying rate limits to effects) * * ```ts * import { Effect } from "effect" @@ -215,8 +249,8 @@ export const layer: Layer.Layer< * }) * ``` * + * @category accessors * @since 4.0.0 - * @category Accessors */ export const makeWithRateLimiter: Effect.Effect< ((options: { @@ -239,7 +273,9 @@ export const makeWithRateLimiter: Effect.Effect< ) /** - * Access a function that sleeps when the rate limit is exceeded. + * Accesses a function that sleeps when the rate limit is exceeded. + * + * **Example** (Sleeping until rate limit permits) * * ```ts * import { Effect } from "effect" @@ -260,8 +296,8 @@ export const makeWithRateLimiter: Effect.Effect< * }) * ``` * + * @category accessors * @since 4.0.0 - * @category Accessors */ export const makeSleep: Effect.Effect< ((options: { @@ -289,20 +325,30 @@ export const makeSleep: Effect.Effect< ) /** + * Runtime type identifier for `RateLimiterError`. + * + * @category type IDs * @since 4.0.0 - * @category Errors */ export const ErrorTypeId: ErrorTypeId = "~@effect/experimental/RateLimiter/RateLimiterError" /** + * Type-level identifier used to brand `RateLimiterError` values. + * + * @category type IDs * @since 4.0.0 - * @category Errors */ export type ErrorTypeId = "~@effect/experimental/RateLimiter/RateLimiterError" /** + * Error reason for a rate-limit check that exceeded the configured limit. + * + * **Details** + * + * Includes the affected key, limit, remaining token count, and retry delay. + * + * @category errors * @since 4.0.0 - * @category Errors */ export class RateLimitExceeded extends Schema.ErrorClass( "effect/persistence/RateLimiter/RateLimitExceeded" @@ -314,6 +360,8 @@ export class RateLimitExceeded extends Schema.ErrorClass( remaining: Schema.Number }) { /** + * Public message used when the rate limiter rejects a request. + * * @since 4.0.0 */ override get message(): string { @@ -322,26 +370,32 @@ export class RateLimitExceeded extends Schema.ErrorClass( } /** + * Error reason for failures in the backing `RateLimiterStore`. + * + * @category errors * @since 4.0.0 - * @category Errors */ export class RateLimitStoreError extends Schema.ErrorClass( "effect/persistence/RateLimiter/RateLimitStoreError" )({ _tag: Schema.tag("RateLimitStoreError"), message: Schema.String, - cause: Schema.optional(Schema.Defect) + cause: Schema.optional(Schema.Defect()) }) {} /** + * Union of reasons carried by `RateLimiterError`. + * + * @category errors * @since 4.0.0 - * @category Errors */ export type RateLimiterErrorReason = RateLimitExceeded | RateLimitStoreError /** + * Schema for all reasons that can be carried by `RateLimiterError`. + * + * @category errors * @since 4.0.0 - * @category Errors */ export const RateLimiterErrorReason: Schema.Union<[ typeof RateLimitExceeded, @@ -349,8 +403,11 @@ export const RateLimiterErrorReason: Schema.Union<[ ]> = Schema.Union([RateLimitExceeded, RateLimitStoreError]) /** + * Error raised by rate limiter operations, wrapping a concrete failure + * `reason`. + * + * @category errors * @since 4.0.0 - * @category Errors */ export class RateLimiterError extends Schema.ErrorClass(ErrorTypeId)({ _tag: Schema.tag("RateLimiterError"), @@ -371,6 +428,8 @@ export class RateLimiterError extends Schema.ErrorClass(ErrorT } /** + * Marks this value as a rate limiter error for runtime guards. + * * @since 4.0.0 */ readonly [ErrorTypeId]: ErrorTypeId = ErrorTypeId @@ -381,15 +440,16 @@ export class RateLimiterError extends Schema.ErrorClass(ErrorT } /** + * Metadata returned after consuming tokens from a rate limiter. + * + * @category models * @since 4.0.0 - * @category Models */ export interface ConsumeResult { /** * The amount of delay to wait before making the next request, when the rate - * limiter is using the "delay" `onExceeded` strategy. - * - * It will be Duration.zero if the request is allowed immediately. + * limiter is using the "delay" `onExceeded` strategy. It will be + * Duration.zero if the request is allowed immediately. */ readonly delay: Duration.Duration @@ -410,8 +470,15 @@ export interface ConsumeResult { } /** + * Defines the low-level backing store for fixed-window counters and token-bucket state. + * + * **When to use** + * + * Use to provide the shared counter storage used by persistent rate-limit + * checks. + * + * @category store * @since 4.0.0 - * @category RateLimiterStore */ export class RateLimiterStore extends Context.Service< RateLimiterStore, @@ -454,8 +521,10 @@ export class RateLimiterStore extends Context.Service< >()("effect/persistence/RateLimiter/RateLimiterStore") {} /** - * @since 4.0.0 + * Provides a process-local in-memory `RateLimiterStore`. + * * @category RateLimiterStore + * @since 4.0.0 */ export const layerStoreMemory: Layer.Layer< RateLimiterStore @@ -511,8 +580,11 @@ export const layerStoreMemory: Layer.Layer< }) /** - * @since 4.0.0 + * Creates a Redis-backed `RateLimiterStore` using Lua scripts and the + * configured key prefix. + * * @category RateLimiterStore + * @since 4.0.0 */ export const makeStoreRedis = Effect.fnUntraced(function*( options?: { @@ -542,11 +614,13 @@ export const makeStoreRedis = Effect.fnUntraced(function*( }, tokenBucket(options) { const key = `${prefix}${options.key}` + const lastRefillKey = `${key}:refill` const refillMillis = Duration.toMillis(options.refillRate) return Effect.clockWith((clock) => Effect.mapError( tokenBucket( key, + lastRefillKey, options.tokens, refillMillis, options.limit, @@ -599,17 +673,18 @@ return { next, nextpttl } const tokenBucketScript = Redis.script( ( key: string, + lastRefillKey: string, tokens: number, refillMillis: number, limit: number, now: number, overflow: 0 | 1 - ) => [key, tokens, refillMillis, limit, now, overflow], + ) => [key, lastRefillKey, tokens, refillMillis, limit, now, overflow], { - numberOfKeys: 1, + numberOfKeys: 2, lua: ` local key = KEYS[1] -local last_refill_key = key .. ":refill" +local last_refill_key = KEYS[2] local tokens = tonumber(ARGV[1]) local refill_ms = tonumber(ARGV[2]) local limit = tonumber(ARGV[3]) @@ -618,36 +693,36 @@ local overflow = ARGV[5] == "1" local current = tonumber(redis.call("GET", key)) local last_refill = tonumber(redis.call("GET", last_refill_key)) -if not current then - current = limit - last_refill = now - redis.call("SET", key, current) - redis.call("SET", last_refill_key, last_refill) -end +if not current then current = limit end +if not last_refill then last_refill = now end local elapsed = now - last_refill local refill_amount = math.floor(elapsed / refill_ms) if refill_amount > 0 then current = math.min(current + refill_amount, limit) last_refill = last_refill + (refill_amount * refill_ms) - redis.call("SET", last_refill_key, last_refill) end local next = current - tokens -if next < 0 and not overflow then - redis.call("SET", key, current) - return next +local stored = current +if next >= 0 or overflow then + stored = next end -redis.call("SET", key, next) +local ttl = math.floor((limit - stored) * refill_ms) +if ttl < 1 then ttl = 1 end +redis.call("SET", key, stored, "PX", ttl) +redis.call("SET", last_refill_key, last_refill, "PX", ttl) return next ` } ).withReturnType() /** + * Provides a Redis-backed `RateLimiterStore` using `makeStoreRedis`. + * + * @category layers * @since 4.0.0 - * @category Layers */ export const layerStoreRedis: ( options?: { readonly prefix?: string | undefined } @@ -658,13 +733,16 @@ export const layerStoreRedis: ( > = flow(makeStoreRedis, Layer.effect(RateLimiterStore)) /** + * Provides a Redis-backed `RateLimiterStore` from wrapped configuration + * options. + * + * @category layers * @since 4.0.0 - * @category Layers */ export const layerStoreRedisConfig = ( options: Config.Wrap<{ readonly prefix?: string | undefined }> ): Layer.Layer => Layer.effect( RateLimiterStore, - Effect.flatMap(Config.unwrap(options).asEffect(), makeStoreRedis) + Effect.flatMap(Config.unwrap(options), makeStoreRedis) ) diff --git a/.opencode/node_modules/effect/src/unstable/persistence/Redis.ts b/.opencode/node_modules/effect/src/unstable/persistence/Redis.ts index 4b1c2f99c33ec45b80e3ee0ff8f8babdde8e65d9..e932ac43f8da88cfd307ab2b9b037df593430957 100644 --- a/.opencode/node_modules/effect/src/unstable/persistence/Redis.ts +++ b/.opencode/node_modules/effect/src/unstable/persistence/Redis.ts @@ -1,4 +1,12 @@ /** + * Redis support shared by persistence modules. + * + * This module defines a `Redis` service that can send Redis commands and run + * Lua scripts. It does not create a Redis client itself; callers provide a + * `send` function from their client or connection pool. The module also + * provides helpers for describing Lua scripts, loading them once, and running + * them later by their cached Redis id. + * * @since 4.0.0 */ import * as Cache from "../../Cache.ts" @@ -10,8 +18,10 @@ import * as Hash from "../../Hash.ts" import * as Schema from "../../Schema.ts" /** + * Service for sending Redis commands and evaluating cached Lua scripts. + * + * @category services * @since 4.0.0 - * @category Service */ export class Redis extends Context.Service(command: string, ...args: ReadonlyArray) => Effect.Effect @@ -25,8 +35,15 @@ export class Redis extends Context.Service()("effect/persistence/Redis") {} /** + * Creates a `Redis` service from a raw command sender. + * + * **Details** + * + * Lua scripts are loaded through `SCRIPT LOAD`, cached, and then invoked with + * `EVALSHA`. + * + * @category constructors * @since 4.0.0 - * @category Constructors */ export const make = Effect.fnUntraced(function*( options: { @@ -46,14 +63,22 @@ export const make = Effect.fnUntraced(function*( >( script: Script ) => - (...params: Config["params"]): Effect.Effect => - Effect.flatMap(Cache.get(scriptCache, script), (sha) => + (...params: Config["params"]): Effect.Effect => { + const evalSha = (sha: string) => options.send( "EVALSHA", sha, script.numberOfKeys(...params).toString(), ...script.params(...params).map((param) => String(param)) - )) + ) + return Cache.get(scriptCache, script).pipe( + Effect.flatMap(evalSha), + Effect.catchIf( + (error) => String(error.cause).includes("NOSCRIPT"), + () => Cache.refresh(scriptCache, script).pipe(Effect.flatMap(evalSha)) + ) + ) + } return identity({ send: options.send, @@ -65,14 +90,18 @@ type ErrorTypeId = "~effect/persistence/Redis/RedisError" const ErrorTypeId: ErrorTypeId = "~effect/persistence/Redis/RedisError" /** + * Error raised by Redis command or script execution. + * + * @category errors * @since 4.0.0 - * @category Errors */ export class RedisError extends Schema.ErrorClass(ErrorTypeId)({ _tag: Schema.tag("RedisError"), - cause: Schema.Defect + cause: Schema.Defect() }) { /** + * Marks this value as a Redis persistence error for runtime guards. + * * @since 4.0.0 */ readonly [ErrorTypeId]: ErrorTypeId = ErrorTypeId @@ -82,8 +111,15 @@ type ScriptTypeId = "~effect/persistence/Redis/Script" const ScriptTypeId: ScriptTypeId = "~effect/persistence/Redis/Script" /** - * @since 4.0.0 + * Typed descriptor for a Redis Lua script. + * + * **Details** + * + * It defines the Lua source, parameter-to-argument mapping, Redis key count, + * and result type used by `Redis.eval`. + * * @category Scripting + * @since 4.0.0 */ export interface Script< Config extends { @@ -125,8 +161,15 @@ const ScriptProto = { } /** - * @since 4.0.0 + * Constructs a typed Redis Lua script descriptor. + * + * **Details** + * + * The result type defaults to `void` and can be refined with + * `withReturnType`. + * * @category Scripting + * @since 4.0.0 */ export const script = >( f: (...params: Params) => ReadonlyArray, diff --git a/.opencode/node_modules/effect/src/unstable/process/ChildProcess.ts b/.opencode/node_modules/effect/src/unstable/process/ChildProcess.ts index 25a932754746bf92b29d344b70dbfdd7a8bd860e..0d9a334563f6cabada0334c4548d7cbf39550f85 100644 --- a/.opencode/node_modules/effect/src/unstable/process/ChildProcess.ts +++ b/.opencode/node_modules/effect/src/unstable/process/ChildProcess.ts @@ -1,50 +1,19 @@ /** - * An Effect-native module for working with child processes. + * Describes child processes before they are started. * - * This module uses an AST-based approach where commands are built first - * using `make` and `pipeTo`, then executed using `spawn`. - * - * @example - * ```ts - * import { NodeServices } from "@effect/platform-node" - * import { Effect, Stream } from "effect" - * import { ChildProcess } from "effect/unstable/process" - * - * // Build a command - * const command = ChildProcess.make`echo "hello world"` - * - * // Spawn and collect output - * const program = Effect.gen(function*() { - * // You can `yield*` a command, which calls `ChildProcess.spawn` - * const handle = yield* command - * const chunks = yield* Stream.runCollect(handle.stdout) - * const exitCode = yield* handle.exitCode - * return { chunks, exitCode } - * }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)) - * - * // With options - * const withOptions = ChildProcess.make({ cwd: "/tmp" })`ls -la` - * - * // Piping commands - * const pipeline = ChildProcess.make`cat package.json`.pipe( - * ChildProcess.pipeTo(ChildProcess.make`grep name`) - * ) - * - * // Spawn the pipeline - * const pipelineProgram = Effect.gen(function*() { - * const handle = yield* pipeline - * const chunks = yield* Stream.runCollect(handle.stdout) - * return chunks - * }).pipe(Effect.scoped, Effect.provide(NodeServices.layer)) - * ``` + * A `Command` stores the executable, arguments, environment, standard streams, + * working directory, and other process options. Commands can also be piped + * together. A command is an `Effect`; running it asks the + * `ChildProcessSpawner` service to start the process and returns a + * `ChildProcessHandle`. * * @since 4.0.0 */ +import * as Context from "../../Context.ts" import type * as Duration from "../../Duration.ts" import type * as Effect from "../../Effect.ts" +import * as Effectable from "../../Effectable.ts" import { dual } from "../../Function.ts" -import { PipeInspectableProto, YieldableProto } from "../../internal/core.ts" -import type { Pipeable } from "../../Pipeable.ts" import type * as PlatformError from "../../PlatformError.ts" import * as Predicate from "../../Predicate.ts" import type * as Scope from "../../Scope.ts" @@ -55,13 +24,10 @@ import { type ChildProcessHandle, ChildProcessSpawner } from "./ChildProcessSpaw const TypeId = "~effect/unstable/process/ChildProcess" /** - * A command that can be executed as a child process. - * - * Commands are built using `make` and can be combined using `pipeTo`. - * They are executed using `exec` or `spawn`. + * A command that can be built using `make`, combined using `pipeTo`, and executed using `exec` or `spawn`. * + * @category models * @since 4.0.0 - * @category Models */ export type Command = | StandardCommand @@ -70,13 +36,11 @@ export type Command = /** * A standard command with pre-parsed command and arguments. * + * @category models * @since 4.0.0 - * @category Models */ export interface StandardCommand extends - Pipeable, - Effect.Yieldable< - StandardCommand, + Effect.Effect< ChildProcessHandle, PlatformError.PlatformError, ChildProcessSpawner | Scope.Scope @@ -92,13 +56,11 @@ export interface StandardCommand extends * A pipeline of commands where the output of one is piped to the input of the * next. * + * @category models * @since 4.0.0 - * @category Models */ export interface PipedCommand extends - Pipeable, - Effect.Yieldable< - PipedCommand, + Effect.Effect< ChildProcessHandle, PlatformError.PlatformError, ChildProcessSpawner | Scope.Scope @@ -113,31 +75,36 @@ export interface PipedCommand extends /** * Specifies which stream to pipe from the source subprocess. * + * **Details** + * * - `"stdout"`: Pipe stdout from the source (default) * - `"stderr"`: Pipe stderr from the source * - `"all"`: Pipe both stdout and stderr interleaved * - `` `fd${number}` ``: Pipe from a custom file descriptor (e.g., `"fd3"`) * + * @category models * @since 4.0.0 - * @category Models */ export type PipeFromOption = "stdout" | "stderr" | "all" | `fd${number}` /** * Specifies which input to pipe to on the destination subprocess. * + * **Details** + * * - `"stdin"`: Pipe to stdin of the destination (default) * - `` `fd${number}` ``: Pipe to a custom file descriptor (e.g., `"fd3"`) * + * @category models * @since 4.0.0 - * @category Models */ export type PipeToOption = "stdin" | `fd${number}` /** * Options for controlling how commands are piped together. * - * @example + * **Example** (Piping stderr between commands) + * * ```ts * import { ChildProcess } from "effect/unstable/process" * @@ -147,13 +114,15 @@ export type PipeToOption = "stdin" | `fd${number}` * ) * ``` * + * @category options * @since 4.0.0 - * @category Models */ export interface PipeOptions { /** * Which stream to pipe from the source subprocess. * + * **Details** + * * - `"stdout"` (default): Pipe stdout from the source * - `"stderr"`: Pipe stderr from the source * - `"all"`: Pipe both stdout and stderr interleaved @@ -164,6 +133,8 @@ export interface PipeOptions { /** * Which input to pipe to on the destination subprocess. * + * **Details** + * * - `"stdin"` (default): Pipe to stdin of the destination * - `"fd3"`, `"fd4"`, etc.: Pipe to a custom file descriptor */ @@ -173,8 +144,8 @@ export interface PipeOptions { /** * Input type for child process stdin. * + * @category models * @since 4.0.0 - * @category Models */ export type CommandInput = | "pipe" @@ -186,8 +157,8 @@ export type CommandInput = /** * Output type for child process stdout/stderr. * + * @category models * @since 4.0.0 - * @category Models */ export type CommandOutput = | "pipe" @@ -199,8 +170,8 @@ export type CommandOutput = /** * A signal that can be sent to a child process. * + * @category models * @since 4.0.0 - * @category Models */ export type Signal = | "SIGABRT" @@ -244,8 +215,8 @@ export type Signal = /** * The encoding format to use for binary data. * + * @category models * @since 4.0.0 - * @category Models */ export type Encoding = | "ascii" @@ -264,23 +235,19 @@ export type Encoding = /** * Options that can be used to control how a child process is terminated. * + * @category options * @since 4.0.0 - * @category Models */ export interface KillOptions { /** - * The default signal used to terminate the child process. - * - * Defaults to `"SIGTERM"`. + * The default signal used to terminate the child process. Defaults to `"SIGTERM"`. */ readonly killSignal?: Signal | undefined /** * The duration of time to wait after the child process has been terminated * before forcefully killing the child process by sending it the `"SIGKILL"` - * signal. - * - * Defaults to `undefined`, which means that no timeout will be enforced by - * default. + * signal. Defaults to `undefined`, which means that no timeout will be + * enforced by default. */ readonly forceKillAfter?: Duration.Input | undefined } @@ -288,13 +255,15 @@ export interface KillOptions { /** * Configuration for the child process standard input stream. * + * @category models * @since 4.0.0 - * @category Models */ export interface StdinConfig { /** * The configuration for the standard input stream of the child process. * + * **Details** + * * Can be a string indicating how the operating system should configure the * pipe established between the child process `stdin` and the parent process. * @@ -306,15 +275,11 @@ export interface StdinConfig { readonly stream: CommandInput /** * Whether or not the child process `stdin` should be closed after the input - * stream is finished. - * - * Defaults to `true`. + * stream is finished. Defaults to `true`. */ readonly endOnDone?: boolean | undefined /** - * The buffer encoding to use to decode string chunks. - * - * Defaults to `utf-8`. + * The buffer encoding to use to decode string chunks. Defaults to `utf-8`. */ readonly encoding?: Encoding | undefined } @@ -322,12 +287,14 @@ export interface StdinConfig { /** * Configuration for the child process standard output stream. * + * @category models * @since 4.0.0 - * @category Models */ export interface StdoutConfig { /** - * The configuration for the standard ouput stream of the child process. + * The configuration for the standard output stream of the child process. + * + * **Details** * * Can be a string indicating how the operating system should configure the * pipe established between the child process `stdout` and the parent process. @@ -343,12 +310,14 @@ export interface StdoutConfig { /** * Configuration for the child process standard error stream. * + * @category models * @since 4.0.0 - * @category Models */ export interface StderrConfig { /** - * The configuration for the standard ouput stream of the child process. + * The configuration for the standard error stream of the child process. + * + * **Details** * * Can be a string indicating how the operating system should configure the * pipe established between the child process `stderr` and the parent process. @@ -364,8 +333,8 @@ export interface StderrConfig { /** * Configuration for additional file descriptors to expose to the child process. * + * @category models * @since 4.0.0 - * @category Models */ export type AdditionalFdConfig = | { @@ -398,8 +367,8 @@ export type AdditionalFdConfig = /** * Options for command execution. * + * @category options * @since 4.0.0 - * @category Models */ export interface CommandOptions extends KillOptions { /** @@ -409,6 +378,8 @@ export interface CommandOptions extends KillOptions { /** * The environment of the child process. * + * **Details** + * * If `extendEnv` is set to `true`, the value of `env` will be merged with * the value of `globalThis.process.env`, prioritizing the values in `env` * when conflicts exist. @@ -419,6 +390,8 @@ export interface CommandOptions extends KillOptions { * as the values in `globalThis.process.env`, prioritizing the values in `env` * when conflicts exist. * + * **Details** + * * If set to `false`, only the value of `env` is used. */ readonly extendEnv?: boolean | undefined @@ -426,9 +399,13 @@ export interface CommandOptions extends KillOptions { * If set to `true`, runs the command inside of a shell, defaulting to `/bin/sh` * on UNIX systems and `cmd.exe` on Windows. * + * **Details** + * * Can also be set to a string representing the absolute path to a shell to * use on the system. * + * **Gotchas** + * * It is generally disadvised to use this option. */ readonly shell?: boolean | string | undefined @@ -436,6 +413,8 @@ export interface CommandOptions extends KillOptions { * If set to `true`, the child process will run independently of the parent * process. * + * **Details** + * * The specific behavior of this option depends upon the platform. For * example, the NodeJS documentation outlines the differences between Windows * and non-Windows platforms. @@ -461,13 +440,16 @@ export interface CommandOptions extends KillOptions { * Additional file descriptors to expose to the child process beyond `stdin` / * `stdout` / `stderr`. * + * **Details** + * * Keys must be in the format `"fd3"`, `"fd4"`, etc. with a file descriptor * index >= 3. * * The file descriptor index is determined by the numeric suffix (i.e. `fd3` * has a file descriptor index of 3). * - * @example + * **Example** (Configuring additional file descriptors) + * * ```ts * import { ChildProcess } from "effect/unstable/process" * @@ -492,16 +474,16 @@ export interface CommandOptions extends KillOptions { /** * Valid template expression item types. * + * @category models * @since 4.0.0 - * @category Models */ export type TemplateExpressionItem = string | number | boolean /** * Template expression type for interpolated values. * + * @category models * @since 4.0.0 - * @category Models */ export type TemplateExpression = TemplateExpressionItem | ReadonlyArray @@ -510,35 +492,36 @@ export type TemplateExpression = TemplateExpressionItem | ReadonlyArray