//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Pipeable.js
/**
* The `Pipeable` module defines the shared interface and implementation helpers
* for values that support Effect-style method chaining with `.pipe(...)`.
*
* A `Pipeable` value can pass itself through a sequence of unary functions from
* left to right, so code can be written as `value.pipe(f, g, h)` instead of
* deeply nesting calls. This is the method form used by many Effect data types
* to compose transformations, validations, and effectful operations while
* keeping the original value as the starting point of the pipeline.
*
* @stability stable
* @since 2.0.0
*/
/**
* Applies a `pipe` method's variadic arguments to an initial value from left
* to right.
*
* **When to use**
*
* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments`
* object.
*
* **Details**
*
* This helper is intended for implementing `Pipeable.pipe` methods that
* receive JavaScript's `arguments` object. With no functions it returns the
* original value; otherwise it feeds each result into the next function.
*
* **Example** (Implementing a pipe method)
*
* ```ts import.meta.vitest
* import { Pipeable } from "effect"
*
* class NumberBox {
* constructor(readonly value: number) {}
*
* pipe(..._fns: ReadonlyArray<(value: number) => number>): number {
* return Pipeable.pipeArguments(this.value, arguments) as number
* }
* }
*
* const result = new NumberBox(5).pipe(
* (n) => n + 2,
* (n) => n * 3
* )
* result // => 21
* ```
*
* @stability stable
* @category combinators
* @since 2.0.0
*/
const pipeArguments = (self, args) => {
switch (args.length) {
case 0:
return self;
case 1:
return args[0](self);
case 2:
return args[1](args[0](self));
case 3:
return args[2](
args[1](args[0](self)),
);
case 4:
return args[3](
args[2](args[1](args[0](self))),
);
case 5:
return args[4](
args[3](
args[2](
args[1](args[0](self)),
),
),
);
case 6:
return args[5](
args[4](
args[3](
args[2](
args[1](args[0](self)),
),
),
),
);
case 7:
return args[6](
args[5](
args[4](
args[3](
args[2](
args[1](args[0](self)),
),
),
),
),
);
case 8:
return args[7](
args[6](
args[5](
args[4](
args[3](
args[2](
args[1](
args[0](self),
),
),
),
),
),
),
);
case 9:
return args[8](
args[7](
args[6](
args[5](
args[4](
args[3](
args[2](
args[1](
args[0](self),
),
),
),
),
),
),
),
);
default: {
let ret = self;
for (
let i = 0, len = args.length;
i < len;
i++
)
ret = args[i](ret);
return ret;
}
}
};
/**
* Reusable prototype that implements `Pipeable.pipe`.
*
* **When to use**
*
* Use when classes or object prototypes can reuse this value when they need the
* standard pipe implementation backed by `pipeArguments`.
*
* @stability stable
* @category prototypes
* @since 3.15.0
*/
const Prototype$1 = {
pipe() {
return pipeArguments(
this,
arguments,
);
},
};
/**
* Provides a base constructor whose instances implement the standard `Pipeable.pipe`
* method.
*
* **When to use**
*
* Use when you need to define a class that supports Effect-style method
* chaining through `.pipe(...)`.
*
* @stability stable
* @category constructors
* @since 3.15.0
*/
const Class$1 =
/*#__PURE__*/ (function () {
function PipeableBase() {}
PipeableBase.prototype =
Prototype$1;
return PipeableBase;
})();
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Function.js
/**
* Creates a function that can be called in data-first style or data-last
* (`pipe`-friendly) style.
*
* **When to use**
*
* Use to expose one implementation through both direct and `pipe`-friendly
* call styles.
*
* **Details**
*
* Pass either the arity of the uncurried function or a predicate that decides
* whether the current call is data-first. Arity is the common case. Use a
* predicate when optional arguments make arity ambiguous.
*
* **Example** (Selecting data-first or data-last style by arity)
*
* ```ts import.meta.vitest
* import { Function, pipe } from "effect"
*
* const sum = Function.dual<
* (that: number) => (self: number) => number,
* (self: number, that: number) => number
* >(2, (self, that) => self + that)
*
* sum(2, 3) // => 5
* pipe(2, sum(3)) // => 5
* ```
*
* **Example** (Defining overloads with call signatures)
*
* ```ts import.meta.vitest
* import { Function, pipe } from "effect"
*
* const sum: {
* (that: number): (self: number) => number
* (self: number, that: number): number
* } = Function.dual(2, (self: number, that: number): number => self + that)
*
* sum(2, 3) // => 5
* pipe(2, sum(3)) // => 5
* ```
*
* **Example** (Selecting data-first or data-last style with a predicate)
*
* ```ts import.meta.vitest
* import { Function, pipe } from "effect"
*
* const sum = Function.dual<
* (that: number) => (self: number) => number,
* (self: number, that: number) => number
* >(
* (args) => args.length === 2,
* (self, that) => self + that
* )
*
* sum(2, 3) // => 5
* pipe(2, sum(3)) // => 5
* ```
*
* @stability stable
* @category combinators
* @since 2.0.0
*/
const dual = function (arity, body) {
if (typeof arity === "function")
return function () {
return arity(arguments)
? body.apply(this, arguments)
: (self) =>
body(self, ...arguments);
};
switch (arity) {
case 0:
case 1:
throw new RangeError(
`Invalid arity ${arity}`,
);
case 2:
return function (a, b) {
if (arguments.length >= 2)
return body(a, b);
return function (self) {
return body(self, a);
};
};
case 3:
return function (a, b, c) {
if (arguments.length >= 3)
return body(a, b, c);
return function (self) {
return body(self, a, b);
};
};
default:
return function () {
if (arguments.length >= arity)
return body.apply(
this,
arguments,
);
const args = arguments;
return function (self) {
return body(self, ...args);
};
};
}
};
/**
* Returns its input argument unchanged.
*
* **When to use**
*
* Use to return a value unchanged where a function is required.
*
* **Example** (Returning the same value)
*
* ```ts import.meta.vitest
* import { identity } from "effect"
*
* identity(5) // => 5
* ```
*
* @stability stable
* @category combinators
* @since 2.0.0
*/
const identity = (a) => a;
/**
* Creates a zero-argument function that always returns the provided value.
*
* **When to use**
*
* Use when you need a thunk or callback that returns the same value on every
* invocation.
*
* **Example** (Creating a constant thunk)
*
* ```ts import.meta.vitest
* import { Function } from "effect"
*
* const constNull = Function.constant(null)
*
* constNull() // => null
* constNull() // => null
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const constant = (value) => () => value;
/**
* Returns `true` when called.
*
* **When to use**
*
* Use when you need a thunk that returns `true` on every invocation.
*
* **Example** (Returning true from a thunk)
*
* ```ts import.meta.vitest
* import { Function } from "effect"
*
* Function.constTrue() // => true
* ```
*
* @stability stable
* @category constants
* @since 2.0.0
*/
const constTrue =
/*#__PURE__*/ constant(true);
/**
* Returns `undefined` when called.
*
* **When to use**
*
* Use when you need a thunk that returns `undefined` on every invocation.
*
* **Example** (Returning undefined from a thunk)
*
* ```ts import.meta.vitest
* import { Function } from "effect"
*
* Function.constUndefined() // => undefined
* ```
*
* @stability stable
* @category constants
* @since 2.0.0
*/
const constUndefined =
/*#__PURE__*/ constant(void 0);
/**
* Returns no meaningful value when called.
*
* **When to use**
*
* Use when you need a thunk that is called only for its effect and has no
* meaningful return value.
*
* **Example** (Returning void from a thunk)
*
* ```ts import.meta.vitest
* import { Function } from "effect"
*
* Function.constVoid() // => undefined
* ```
*
* @stability stable
* @category constants
* @since 2.0.0
*/
const constVoid = constUndefined;
/**
* Creates a memoized function whose input is an object, caching results by
* object identity.
*
* **When to use**
*
* Use to reuse the result of a synchronous computation whose output is stable
* for a given object reference.
*
* **Details**
*
* Each memoized wrapper owns a private `WeakMap` keyed by object identity.
*
* **Gotchas**
*
* `undefined` is reserved to represent a cache miss and is therefore not
* supported as a return value.
*
* Structurally equal objects do not share cache entries. If the same object is
* mutated after its first call, later calls still return the cached result for
* that reference.
*
* @stability stable
* @category caching
* @since 4.0.0
*/
function memoize(f) {
const cache =
/* @__PURE__ */ new WeakMap();
return (a) => {
const cached = cache.get(a);
if (cached !== void 0)
return cached;
const result = f(a);
cache.set(a, result);
return result;
};
}
/**
* Creates a memoized idempotent object transformation that caches both inputs
* and their outputs by object identity.
*
* **When to use**
*
* Use when an object transformation is idempotent and its output can be safely
* reused as a fixed point.
*
* **Details**
*
* After computing an input, the returned function caches both the input and
* the output. Calling it with either reference returns the output without
* invoking the supplied function again.
*
* **Gotchas**
*
* The returned function treats each computed output as a fixed point. If
* applying the supplied function to an output would produce an observably
* different value, this memoization changes that behavior.
*
* @see {@link memoize} for memoizing functions without an idempotence requirement
* @stability stable
* @category caching
* @since 4.0.0
*/
function memoizeIdempotent(f) {
const cache =
/* @__PURE__ */ new WeakMap();
return (a) => {
const cached = cache.get(a);
if (cached !== void 0)
return cached;
const result = f(a);
cache.set(a, result);
if (result !== a)
cache.set(result, result);
return result;
};
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/equal.js
/** @internal */
const getAllObjectKeys = (obj) => {
const keys = new Set(
Reflect.ownKeys(obj),
);
if (obj.constructor === Object)
return keys;
if (obj instanceof Error)
keys.delete("stack");
const proto =
Object.getPrototypeOf(obj);
let current = proto;
while (
current !== null &&
current !== Object.prototype
) {
const ownKeys =
Reflect.ownKeys(current);
for (
let i = 0;
i < ownKeys.length;
i++
)
keys.add(ownKeys[i]);
current =
Object.getPrototypeOf(current);
}
if (
keys.has("constructor") &&
typeof obj.constructor ===
"function" &&
proto === obj.constructor.prototype
)
keys.delete("constructor");
return keys;
};
/** @internal */
const byReferenceInstances =
/*#__PURE__*/ new WeakSet();
/** @internal */
const viewBytes = (view) =>
new Uint8Array(
view.buffer,
view.byteOffset,
view.byteLength,
);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/hash.js
/**
* Back-edge count used to avoid caching entry-point-dependent hashes.
*
* @internal
*/
let backEdges = 0;
/** @internal */
const addBackEdge = () => {
backEdges++;
};
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Predicate.js
/**
* Defines runtime checks for values.
*
* A `Predicate<A>` returns `true` or `false` for an `A`. A
* `Refinement<A, B>` is a predicate that also narrows the TypeScript type when
* it succeeds. This module includes guards for common JavaScript values,
* property and tag checks, tuple and struct checks, boolean combinators, and
* helpers for composing predicates and refinements.
*
* @stability stable
* @since 2.0.0
*/
/**
* Checks whether a value is a `string`.
*
* **When to use**
*
* Use when you need a `Predicate` guard to narrow an `unknown` value to a
* string.
*
* **Details**
*
* Uses `typeof input === "string"`.
*
* **Example** (Guarding strings)
*
* ```ts import.meta.vitest
* import { Predicate } from "effect"
*
* const data: unknown = "hi"
*
* if (Predicate.isString(data)) {
* data.toUpperCase() // => "HI"
* }
* ```
*
* @see {@link isNumber}
* @see {@link isBoolean}
* @see {@link Refinement}
* @stability stable
* @category guards
* @since 2.0.0
*/
function isString$1(input) {
return typeof input === "string";
}
/**
* Checks whether a value is a `number`.
*
* **When to use**
*
* Use when you need a `Predicate` guard to narrow an `unknown` value to a
* number.
*
* **Details**
*
* Uses `typeof input === "number"` and does not exclude `NaN` or `Infinity`.
*
* **Example** (Guarding numbers)
*
* ```ts import.meta.vitest
* import { Predicate } from "effect"
*
* const data: unknown = 42
*
* if (Predicate.isNumber(data)) {
* data + 1 // => 43
* }
* ```
*
* @see {@link isBigInt}
* @see {@link isString}
* @stability stable
* @category guards
* @since 2.0.0
*/
function isNumber(input) {
return typeof input === "number";
}
/**
* Checks whether a value is a `function`.
*
* **When to use**
*
* Use when you need a `Predicate` guard to narrow an `unknown` value to a
* callable function.
*
* **Details**
*
* Uses `typeof input === "function"`.
*
* **Example** (Guarding functions)
*
* ```ts import.meta.vitest
* import { Predicate } from "effect"
*
* const data: unknown = () => 1
*
* if (Predicate.isFunction(data)) {
* data() // => 1
* }
* ```
*
* @see {@link isObjectKeyword}
* @stability stable
* @category guards
* @since 2.0.0
*/
function isFunction(input) {
return typeof input === "function";
}
/**
* Checks whether a value is not `null` and not `undefined`.
*
* **When to use**
*
* Use when you need a `Predicate` refinement that filters out nullish values
* but keeps other falsy ones.
*
* **Details**
*
* Uses `input != null`.
*
* **Example** (Filtering non-nullish values)
*
* ```ts import.meta.vitest
* import { Predicate } from "effect"
*
* const values = [0, null, "", undefined]
* const present = values.filter(Predicate.isNotNullish) // => [0, ""]
* ```
*
* @see {@link isNullish}
* @see {@link isNotNull}
* @see {@link isNotUndefined}
* @stability stable
* @category guards
* @since 4.0.0
*/
function isNotNullish(input) {
return input != null;
}
/**
* Type guard that always returns `true`.
*
* **When to use**
*
* Use when you need a `Predicate` that always accepts, e.g. as a placeholder.
*
* **Example** (Matching every value)
*
* ```ts import.meta.vitest
* import { Predicate } from "effect"
*
* Predicate.isUnknown(123) // => true
* ```
*
* @see {@link isNever}
* @stability stable
* @category guards
* @since 2.0.0
*/
function isUnknown(_) {
return true;
}
/**
* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions).
*
* **When to use**
*
* Use when you need a `Predicate` guard that accepts arrays and functions as
* well as objects.
*
* **Details**
*
* Returns `true` for arrays and functions, and `false` for `null`.
*
* **Example** (Checking object keywords)
*
* ```ts import.meta.vitest
* import { Predicate } from "effect"
*
* Predicate.isObjectKeyword(() => 1) // => true
* Predicate.isObjectKeyword(null) // => false
* ```
*
* @see {@link isObject}
* @see {@link isObjectOrArray}
* @stability stable
* @category guards
* @since 4.0.0
*/
function isObjectKeyword(input) {
return (
(typeof input === "object" &&
input !== null) ||
isFunction(input)
);
}
/**
* Checks whether a value has a given property key.
*
* **When to use**
*
* Use when you need a `Predicate` guard for property access on `unknown`
* values with a simple structural object check.
*
* **Details**
*
* Uses the `in` operator and `isObjectKeyword`. This does not check property
* value types.
*
* **Example** (Guarding object properties)
*
* ```ts import.meta.vitest
* import { Predicate } from "effect"
*
* const hasName = Predicate.hasProperty("name")
* const data: unknown = { name: "Ada" }
*
* if (hasName(data)) {
* data.name // => "Ada"
* }
* ```
*
* @see {@link isTagged}
* @see {@link isObjectKeyword}
* @stability stable
* @category guards
* @since 2.0.0
*/
const hasProperty = /*#__PURE__*/ dual(
2,
(self, property) =>
isObjectKeyword(self) &&
property in self,
);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Hash.js
/**
* Computes Effect hash values and defines the interface for objects that want
* to provide their own hash implementation. Hashes are small numeric
* fingerprints used by Effect data structures to bucket values quickly; they
* are not cryptographic digests and they are not proof that two values are
* equal. The module also includes helpers for primitive, structure, array, and
* reference-based hashes, plus functions for combining and optimizing numeric
* hash values.
*
* @stability stable
* @since 2.0.0
*/
/**
* Defines the unique identifier used to identify objects that implement the Hash interface.
*
* **When to use**
*
* Use as the computed property key for the method that supplies a custom hash
* value on a `Hash` implementor.
*
* @see {@link Hash} for the interface implemented with this symbol
* @see {@link isHash} for checking whether a value implements `Hash`
* @see {@link hash} for computing hash values
*
* @stability stable
* @category symbols
* @since 2.0.0
*/
const symbol$1 = "~effect/Hash";
/**
* Computes a hash value for any given value.
*
* **When to use**
*
* Use to compute an Effect hash for primitives, collections, and hashable
* objects.
*
* **Details**
*
* This function can hash primitives (numbers, strings, booleans, etc.) as well as
* objects, arrays, and other complex data structures. It automatically handles
* different types and provides a consistent hash value for equivalent inputs.
*
* **Gotchas**
*
* Objects being hashed must be treated as immutable after their first hash
* computation. Hash results are cached, so mutating an object after hashing will
* lead to stale cached values and broken hash-based operations. For mutable
* objects, implement a custom `Hash` interface that hashes the object reference
* rather than its content.
*
* **Example** (Hashing different values)
*
* ```ts import.meta.vitest
* import { Hash } from "effect"
*
* Hash.hash(42) === Hash.hash(42) // => true
* Hash.hash("hello") === Hash.hash("hello") // => true
* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true
* ```
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const hash = (self) => {
switch (typeof self) {
case "number":
return number$1(self);
case "bigint":
return string$1(
self.toString(10),
);
case "string":
return string$1(self);
case "function":
case "object":
if (self === null) break;
else if (self instanceof Date) {
if (
Number.isNaN(self.getTime())
)
return string$1(
"Invalid Date",
);
return string$1(
self.toISOString(),
);
} else if (self instanceof RegExp)
return string$1(
self.toString(),
);
else {
if (
byReferenceInstances.has(self)
)
return random(self);
const cached =
hashCache.get(self);
if (cached !== void 0)
return cached;
if (visitedObjects.has(self)) {
addBackEdge();
return string$1("[Circular]");
}
visitedObjects.add(self);
const seen = backEdges;
let h;
try {
if ("~effect/Hash" in self)
h = self[symbol$1]();
else if (
typeof self === "function"
)
h = random(self);
else if (
self instanceof DataView
)
h = array(viewBytes(self));
else if (
Array.isArray(self) ||
ArrayBuffer.isView(self)
)
h = array(self);
else if (self instanceof Map)
h = hashMap(self);
else if (self instanceof Set)
h = hashSet(self);
else h = structure(self);
} finally {
visitedObjects.delete(self);
}
if (seen === backEdges)
hashCache.set(self, h);
return h;
}
}
return optimize(
mix(string$1(String(self))),
);
};
/**
* Generates a random hash value for an object and caches it.
*
* **When to use**
*
* Use to hash an object by reference identity instead of structural content.
*
* **Details**
*
* This function creates a random hash value for objects that don't have their own
* hash implementation. The hash value is cached using a WeakMap, so the same object
* will always return the same hash value during its lifetime.
*
* **Example** (Hashing objects by reference)
*
* ```ts import.meta.vitest
* import { Hash } from "effect"
*
* const obj1 = { a: 1 }
* const obj2 = { a: 1 }
*
* Hash.random(obj1) === Hash.random(obj1) // => true
*
* typeof Hash.random(obj2) // => "number"
* ```
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const random = (self) => {
if (!randomHashCache.has(self))
randomHashCache.set(
self,
optimize(
(Math.random() * 4294967296) |
0,
),
);
return randomHashCache.get(self);
};
const mix = (h) => {
h ^= h >>> 16;
h = Math.imul(h, 2246822507);
h ^= h >>> 13;
h = Math.imul(h, 3266489909);
return h ^ (h >>> 16);
};
/**
* Combines two hash values into a single hash value.
*
* **When to use**
*
* Use to build a hash for a composite value by folding together hash values for
* its parts.
*
* **Details**
*
* Supports direct and pipeable usage. Argument order affects the result.
*
* **Example** (Combining hash values)
*
* ```ts import.meta.vitest
* import { Hash, pipe } from "effect"
*
* const hash1 = Hash.hash("hello")
* const hash2 = Hash.hash("world")
*
* const combined = Hash.combine(hash2)(hash1)
* combined === pipe(hash1, Hash.combine(hash2)) // => true
* ```
*
* @see {@link hash} for computing hash values from arbitrary inputs
* @see {@link structureKeys} for hashing selected object fields without manual combination
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const combine = /*#__PURE__*/ dual(
2,
(self, b) =>
mix(
Math.imul(self, 2654435761) +
Math.imul(b, 2246822507),
),
);
/**
* Applies bit manipulation techniques to optimize a hash value.
*
* **When to use**
*
* Use to improve the bit distribution of a raw numeric hash value.
*
* **Details**
*
* This function takes a hash value and applies bitwise operations to improve
* the distribution of hash values, reducing the likelihood of collisions.
*
* **Example** (Optimizing a hash value)
*
* ```ts import.meta.vitest
* import { Hash } from "effect"
*
* Hash.optimize(1234567890) // => 160826066
* ```
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const optimize = (n) =>
(n & 3221225471) |
((n >>> 1) & 1073741824);
const float64 =
/*#__PURE__*/ new DataView(
/*#__PURE__*/ new ArrayBuffer(8),
);
/**
* Computes a hash value for a number.
*
* **When to use**
*
* Use to hash a JavaScript number with Effect's numeric hash semantics.
*
* **Details**
*
* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits,
* with a canonical representation for `NaN`.
*
* **Example** (Hashing numbers)
*
* ```ts import.meta.vitest
* import { Hash } from "effect"
*
* Number.isInteger(Hash.number(42)) // => true
* Number.isInteger(Hash.number(3.14)) // => true
* Hash.number(NaN) === Hash.number(NaN) // => true
* Hash.number(Infinity) === Hash.number(Infinity) // => true
* Hash.number(100) === Hash.number(100) // => true
* ```
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const number$1 = (n) => {
const h = n | 0;
if (h === n) return optimize(h);
float64.setFloat64(
0,
n !== n ? NaN : n,
);
return optimize(
combine(
float64.getInt32(0),
float64.getInt32(4),
),
);
};
/**
* Computes a hash value for a string using the djb2 algorithm.
*
* **When to use**
*
* Use when you need a string field to contribute to a custom structural hash
* implementation.
*
* **Details**
*
* This function implements a variation of the djb2 hash algorithm, which is
* known for its good distribution properties and speed. It processes each
* character of the string to produce a consistent hash value.
*
* **Example** (Hashing strings)
*
* ```ts import.meta.vitest
* import { Hash } from "effect"
*
* Hash.string("hello") // => 181380007
* Hash.string("world") // => 164394279
* Hash.string("") // => 5381
* Hash.string("test") === Hash.string("test") // => true
* ```
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const string$1 = (str) => {
let h = 5381,
i = str.length;
while (i)
h = (h * 33) ^ str.charCodeAt(--i);
return optimize(h);
};
/**
* Computes a hash value for an object using only the specified keys.
*
* **When to use**
*
* Use to hash an object by a selected set of property keys.
*
* **Details**
*
* This function allows you to hash an object by considering only specific keys,
* which is useful when you want to create a hash based on a subset of an object's
* properties.
*
* **Example** (Hashing selected object keys)
*
* ```ts import.meta.vitest
* import { Hash } from "effect"
*
* const person = { name: "John", age: 30, city: "New York" }
*
* const hash1 = Hash.structureKeys(person, ["name", "age"])
* const hash2 = Hash.structureKeys(person, ["name", "city"])
*
* hash1 // => -731887653
* hash2 // => 148523102
*
* const person2 = { name: "John", age: 30, city: "Boston" }
* const hash3 = Hash.structureKeys(person2, ["name", "age"])
* hash1 === hash3 // => true
* ```
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const structureKeys = (o, keys) => {
let h = 12289;
for (const key of keys)
h ^= combine(
hash(key),
hash(o[key]),
);
return optimize(h);
};
/**
* Computes a structural hash for an object using Effect's object key collection.
*
* **When to use**
*
* Use to hash an object from all structural keys collected by Effect.
*
* **Details**
*
* The hash is based on the object's structural keys and their values, including
* symbol keys and relevant prototype keys for non-plain objects.
*
* **Example** (Hashing object structures)
*
* ```ts import.meta.vitest
* import { Hash } from "effect"
*
* const obj1 = { name: "John", age: 30 }
* const obj2 = { name: "Jane", age: 25 }
* const obj3 = { name: "John", age: 30 }
*
* Hash.structure(obj1) // => -731887653
* Hash.structure(obj2) // => -222100417
* Hash.structure(obj3) // => -731887653
* Hash.structure(obj1) === Hash.structure(obj3) // => true
* ```
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const structure = (o) =>
structureKeys(o, getAllObjectKeys(o));
const unordered =
(seed, f) => (iter) => {
let h = seed;
for (const element of iter)
h ^= f(element);
return optimize(h);
};
/**
* Computes a hash value for an iterable by hashing all of its elements.
*
* **When to use**
*
* Use to hash the values yielded by an iterable with Effect hash semantics.
*
* **Details**
*
* Folds element hashes with {@link combine}, so order and length affect the
* result.
*
* **Gotchas**
*
* A hash is not an equality proof. Distinct inputs can still share a hash.
*
* **Example** (Hashing arrays)
*
* ```ts import.meta.vitest
* import { Hash } from "effect"
*
* const arr1 = [1, 2, 3]
* const arr2 = [1, 2, 3]
* const arr3 = [3, 2, 1]
*
* Hash.array(arr1) === Hash.array(arr2) // => true
* Hash.array(arr1) === Hash.array(arr3) // => false
* ```
*
* @see {@link hash} for the general-purpose hash dispatcher
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const array = (arr) => {
let h = 6151;
for (const element of arr)
h = combine(h, hash(element));
return optimize(h);
};
const hashMap = /*#__PURE__*/ unordered(
/*#__PURE__*/ string$1("Map"),
([k, v]) => combine(hash(k), hash(v)),
);
const setSeed =
/*#__PURE__*/ string$1("Set");
const hashSet = /*#__PURE__*/ unordered(
setSeed,
(element) =>
combine(setSeed, hash(element)),
);
const randomHashCache =
/*#__PURE__*/ new WeakMap();
const hashCache =
/*#__PURE__*/ new WeakMap();
const visitedObjects =
/*#__PURE__*/ new WeakSet();
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Equal.js
/**
* Defines the unique string identifier for the `Equal` interface.
*
* **When to use**
*
* Use when you implement custom equality and need the computed property key for
* the equality method.
*
* **Details**
*
* This is a pure constant with no allocation or side effects.
*
* **Example** (Implementing Equal on a class)
*
* ```ts import.meta.vitest
* import { Equal, Hash } from "effect"
*
* class UserId implements Equal.Equal {
* constructor(readonly id: string) {}
*
* [Equal.symbol](that: Equal.Equal): boolean {
* return that instanceof UserId && this.id === that.id
* }
*
* [Hash.symbol](): number {
* return Hash.string(this.id)
* }
* }
*
* Equal.equals(new UserId("1"), new UserId("1")) // => true
* Equal.equals(new UserId("1"), new UserId("2")) // => false
* ```
*
* @see {@link Equal} — the interface that uses this symbol
* @see {@link isEqual} — type guard for `Equal` implementors
* @stability stable
* @category symbols
* @since 2.0.0
*/
const symbol = "~effect/Equal";
function equals$1() {
if (arguments.length === 1)
return (self) =>
compareBoth(self, arguments[0]);
return compareBoth(
arguments[0],
arguments[1],
);
}
function compareBoth(self, that) {
if (self === that) return true;
if (self == null || that == null)
return false;
const selfType = typeof self;
if (selfType !== typeof that)
return false;
if (
selfType === "number" &&
self !== self &&
that !== that
)
return true;
if (
selfType !== "object" &&
selfType !== "function"
)
return false;
if (
byReferenceInstances.has(self) ||
byReferenceInstances.has(that)
)
return false;
return compareObjects(self, that);
}
function compareObjects(self, that) {
const depth = pathLeft.length;
for (let i = depth; i-- > 0;)
if (
pathLeft[i] === self &&
pathRight[i] === that
)
return true;
if (depth)
return compareOnPath(self, that);
let known = results.get(self);
if (!known)
results.set(
self,
(known =
/* @__PURE__ */ new WeakMap()),
);
let result = known.get(that);
if (result === void 0)
known.set(
that,
(result = compareOnPath(
self,
that,
)),
);
return result;
}
function compareOnPath(self, that) {
pathLeft.push(self);
pathRight.push(that);
try {
return compareStructure(self, that);
} finally {
pathLeft.pop();
pathRight.pop();
}
}
const pathLeft = [];
const pathRight = [];
const results =
/*#__PURE__*/ new WeakMap();
function compareStructure(self, that) {
if (hash(self) !== hash(that))
return false;
else if (self instanceof Date) {
if (!(that instanceof Date))
return false;
const selfTime = self.getTime();
const thatTime = that.getTime();
return (
selfTime === thatTime ||
(Number.isNaN(selfTime) &&
Number.isNaN(thatTime))
);
} else if (self instanceof RegExp)
return (
that instanceof RegExp &&
self.toString() ===
that.toString()
);
const bothEquals = isEqual(self);
if (
bothEquals !== isEqual(that) ||
(typeof self === "function" &&
!bothEquals)
)
return false;
else if (bothEquals)
return self[symbol](that);
else if (Array.isArray(self)) {
if (
!Array.isArray(that) ||
self.length !== that.length
)
return false;
return compareArrays(self, that);
} else if (ArrayBuffer.isView(self)) {
const selfIsDataView =
self instanceof DataView;
if (
!ArrayBuffer.isView(that) ||
self.byteLength !==
that.byteLength ||
selfIsDataView !==
that instanceof DataView
)
return false;
if (selfIsDataView)
return compareTypedArrays(
viewBytes(self),
viewBytes(that),
);
return compareTypedArrays(
self,
that,
);
} else if (self instanceof Map) {
if (
!(that instanceof Map) ||
self.size !== that.size
)
return false;
return compareHashed(
self,
that,
entryHash,
equalEntries,
);
} else if (self instanceof Set) {
if (
!(that instanceof Set) ||
self.size !== that.size
)
return false;
return compareHashed(
self,
that,
hash,
compareBoth,
);
}
return compareRecords(self, that);
}
function compareArrays(self, that) {
for (let i = 0; i < self.length; i++)
if (!compareBoth(self[i], that[i]))
return false;
return true;
}
function compareTypedArrays(
self,
that,
) {
if (self.length !== that.length)
return false;
for (let i = 0; i < self.length; i++)
if (self[i] !== that[i])
return false;
return true;
}
function compareRecords(self, that) {
const selfKeys =
getAllObjectKeys(self);
const thatKeys =
getAllObjectKeys(that);
if (selfKeys.size !== thatKeys.size)
return false;
for (const key of selfKeys)
if (
!thatKeys.has(key) ||
!compareBoth(self[key], that[key])
)
return false;
return true;
}
function compareHashed(
self,
that,
hashOf,
equivalent,
) {
const groups =
/* @__PURE__ */ new Map();
let remaining = 0;
for (const item of that) {
const h = hashOf(item);
const group = groups.get(h);
if (group) group.push(item);
else groups.set(h, [item]);
remaining++;
}
outer: for (const item of self) {
const group = groups.get(
hashOf(item),
);
if (group) {
for (
let i = 0;
i < group.length;
i++
)
if (
equivalent(item, group[i])
) {
group[i] =
group[group.length - 1];
group.pop();
remaining--;
continue outer;
}
}
return false;
}
return remaining === 0;
}
const entryHash = (entry) =>
hash(entry[0]);
const equalEntries = (self, that) =>
compareBoth(self[0], that[0]) &&
compareBoth(self[1], that[1]);
/**
* Checks whether a value implements the {@link Equal} interface.
*
* **When to use**
*
* Use when you need generic utility code to distinguish `Equal` implementors
* from plain values before calling `[Equal.symbol]` directly.
*
* **Details**
*
* - Pure function, no side effects.
* - Returns `true` if and only if `u` has a property keyed by
* {@link symbol}.
* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}.
*
* **Example** (Checking Equal values)
*
* ```ts import.meta.vitest
* import { Equal, Hash } from "effect"
*
* class Token implements Equal.Equal {
* constructor(readonly value: string) {}
* [Equal.symbol](that: Equal.Equal): boolean {
* return that instanceof Token && this.value === that.value
* }
* [Hash.symbol](): number {
* return Hash.string(this.value)
* }
* }
*
* Equal.isEqual(new Token("abc")) // => true
* Equal.isEqual({ x: 1 }) // => false
* Equal.isEqual(42) // => false
* ```
*
* @see {@link Equal} — the interface being checked
* @see {@link symbol} — the property key that signals `Equal` support
* @stability stable
* @category guards
* @since 2.0.0
*/
const isEqual = (u) =>
hasProperty(u, symbol);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/array.js
/**
* @since 2.0.0
*/
/** @internal */
const isArrayNonEmpty$1 = (self) =>
self.length > 0;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/record.js
/** @internal */
function assignProperty(
self,
key,
value,
) {
if (key === "__proto__")
Object.defineProperty(self, key, {
value,
writable: true,
enumerable: true,
configurable: true,
});
else self[key] = value;
}
/** @internal */
function assignProperties(
self,
source,
) {
for (const key of Reflect.ownKeys(
source,
))
if (
Object.prototype.propertyIsEnumerable.call(
source,
key,
)
)
assignProperty(
self,
key,
source[key],
);
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Redactable.js
/**
* Defines the symbol used to identify objects that implement the {@link Redactable}
* protocol.
*
* **When to use**
*
* Use as the property key when implementing the `Redactable` protocol.
*
* **Details**
*
* Add a method under this key to make an object redactable. The method receives
* the current `Context` and must return the replacement value. The symbol is
* registered globally via `Symbol.for("~effect/Redactable")`, so it is
* identical across multiple copies of the library at runtime.
*
* **Example** (Masking an API key)
*
* ```ts import.meta.vitest
* import { Context, Redactable } from "effect"
*
* class ApiKey {
* constructor(readonly raw: string) {}
*
* [Redactable.symbolRedactable](_ctx: Context.Context<never>) {
* return this.raw.slice(0, 4) + "..."
* }
* }
*
* Redactable.redact(new ApiKey("secret-key")) // => "secr..."
* ```
*
* @see {@link Redactable} for the interface this symbol belongs to
* @see {@link isRedactable} to check whether a value has this symbol
* @stability stable
* @category symbols
* @since 3.10.0
*/
const symbolRedactable =
/*#__PURE__*/ Symbol.for(
"~effect/Redactable",
);
/**
* Type guard that checks whether a value implements the {@link Redactable}
* interface.
*
* **When to use**
*
* Use to narrow an unknown value before calling redaction-specific helpers.
*
* @see {@link Redactable} for the interface being checked
* @see {@link redact} to apply redaction if the value is redactable
* @stability stable
* @category guards
* @since 3.10.0
*/
const isRedactable = (u) =>
hasProperty(u, symbolRedactable);
/**
* Returns a redacted value if it implements {@link Redactable}, otherwise returns it
* unchanged.
*
* **When to use**
*
* Use as the general-purpose entry point for redaction when the input may
* or may not implement the redaction protocol.
*
* **Details**
*
* This function calls {@link isRedactable} and, when it returns `true`,
* delegates to {@link getRedacted}.
*
* **Gotchas**
*
* Redaction is not recursive. Nested redactable values inside the returned
* object are not automatically redacted.
*
* @see {@link isRedactable} to check before redacting
* @see {@link getRedacted} for the lower-level variant for known redactables
* @stability stable
* @category destructors
* @since 3.10.0
*/
function redact$2(u) {
if (isRedactable(u))
return getRedacted(u);
return u;
}
/**
* Returns the result of calling `[symbolRedactable]` on a value that is
* already known to be {@link Redactable}.
*
* **When to use**
*
* Use when you need to read the redacted representation from a value already
* verified as `Redactable`.
*
* **Details**
*
* This function reads the current fiber's `Context` from the global fiber
* reference and passes it to the redaction method.
*
* **Gotchas**
*
* If no fiber is active, an empty `Context` is passed to the redaction method.
*
* @see {@link redact} for the higher-level variant that handles non-redactable values
* @see {@link isRedactable} for the type guard to verify before calling this
* @stability stable
* @category destructors
* @since 4.0.0
*/
function getRedacted(redactable) {
return redactable[symbolRedactable](
globalThis[
"~effect/Fiber/currentFiber"
]?.context ?? emptyContext$1,
);
}
/** @internal */
const currentFiberTypeId =
"~effect/Fiber/currentFiber";
const emptyMap =
/*#__PURE__*/ new Map();
const emptyContext$1 = {
"~effect/Context": {},
base: emptyMap,
depth: 0,
mapUnsafe: emptyMap,
pipe() {
return pipeArguments(
this,
arguments,
);
},
};
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Formatter.js
/**
* Formats JavaScript values into readable strings.
*
* `format` is intended for logs, diagnostics, and error messages. It handles
* primitives, objects, arrays, dates, regular expressions, maps, sets, class
* instances, errors, circular references, and redactable values. `formatJson`
* wraps JSON formatting with redaction and circular-reference handling, and the
* module also includes helpers for property keys, paths, and dates.
*
* @stability stable
* @since 4.0.0
*/
/**
* Converts any JavaScript value into a human-readable string.
*
* **When to use**
*
* Use when you need to format arbitrary JavaScript values for debugging,
* logging, or error messages.
*
* **Details**
*
* - Output is **not** valid JSON; use {@link formatJson} when you need
* parseable JSON.
* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class
* instances that `JSON.stringify` cannot represent.
* - Circular references are shown as `"[Circular]"` instead of throwing.
* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing.
* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`).
* Strings are JSON-quoted.
* - Objects with a custom `toString` (not `Object.prototype.toString`):
* `toString()` is called unless `ignoreToString` is `true`.
* - Errors with a `cause`: formatted as `"<message> (cause: <cause>)"`.
* - Iterables (`Set`, `Map`, etc.): formatted as
* `ClassName([...elements])`.
* - Class instances: wrapped as `ClassName({...})`.
* - `Redactable` values are automatically redacted.
* - Arrays/objects with 0–1 entries are inline; larger ones are
* pretty-printed when `space` is set.
* - `space` — indentation unit (number of spaces, or a string like
* `"\t"`). Defaults to `0` (compact).
* - `ignoreToString` — skip calling `toString()`. Defaults to `false`.
*
* **Example** (Formatting compact output)
*
* ```ts import.meta.vitest
* import { Formatter } from "effect"
*
* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}"
* ```
*
* **Example** (Pretty-printed output)
*
* ```ts import.meta.vitest
* import { Formatter } from "effect"
*
* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 })
* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}"
* ```
*
* **Example** (Handling circular references)
*
* ```ts import.meta.vitest
* import { Formatter } from "effect"
*
* const obj: any = { name: "loop" }
* obj.self = obj
* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}"
* ```
*
* @see {@link formatJson}
* @see {@link Formatter}
* @stability stable
* @category formatting
* @since 2.0.0
*/
function format$1(input, options) {
const space = options?.space ?? 0;
const ancestors =
/* @__PURE__ */ new WeakSet();
const gap = !space
? ""
: typeof space === "number"
? " ".repeat(space)
: space;
const ind = (d) => gap.repeat(d);
const wrap = (v, body) => {
const ctor = v?.constructor;
return ctor &&
ctor !==
Object.prototype.constructor &&
ctor.name
? `${ctor.name}(${body})`
: body;
};
const ownKeys = (o) => {
try {
return Reflect.ownKeys(o);
} catch {
return ["[ownKeys threw]"];
}
};
function recur(v, d = 0) {
try {
return recurUnsafe(v, d);
} catch {
if (
(typeof v === "object" &&
v !== null) ||
typeof v === "function"
)
ancestors.delete(v);
return "[inspection threw]";
}
}
function recurUnsafe(v, d = 0) {
if (typeof v === "string")
return JSON.stringify(v);
if (
typeof v === "number" ||
v == null ||
typeof v === "boolean" ||
typeof v === "symbol"
)
return String(v);
if (typeof v === "bigint")
return String(v) + "n";
if (
typeof v === "object" ||
typeof v === "function"
) {
if (ancestors.has(v))
return CIRCULAR;
ancestors.add(v);
let output;
if (symbolRedactable in v)
output = recur(
getRedacted(v),
d,
);
else if (Array.isArray(v))
output =
!gap || v.length <= 1
? `[${v.map((x) => recur(x, d)).join(",")}]`
: `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`;
else if (v instanceof Date)
output = formatDate(v);
else if (
!options?.ignoreToString &&
hasProperty(v, "toString") &&
typeof v["toString"] ===
"function" &&
v["toString"] !==
Object.prototype.toString &&
v["toString"] !==
Array.prototype.toString
) {
const s = safeToString(v);
output =
v instanceof Error &&
v.cause !== void 0
? `${s} (cause: ${recur(v.cause, d)})`
: s;
} else if (Symbol.iterator in v)
output = `${v.constructor.name}(${recur(Array.from(v), d)})`;
else {
const keys = ownKeys(v);
if (!gap || keys.length <= 1) {
const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`;
output = wrap(v, body);
} else {
const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`;
output = wrap(v, body);
}
}
ancestors.delete(v);
return output;
}
return String(v);
}
return recur(input, 0);
}
const CIRCULAR = "[Circular]";
/**
* @internal
*/
function formatPropertyKey(name) {
return typeof name === "string"
? JSON.stringify(name)
: String(name);
}
/**
* Formats an array of property keys as a bracket-notation path string.
*
* @internal
*/
function formatPath(path) {
return path
.map(
(key) =>
`[${formatPropertyKey(key)}]`,
)
.join("");
}
/**
* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for
* invalid dates instead of throwing.
*
* @internal
*/
function formatDate(date) {
try {
return date.toISOString();
} catch {
return "Invalid Date";
}
}
function safeToString(input) {
try {
const s = input.toString();
return typeof s === "string"
? s
: String(s);
} catch {
return "[toString threw]";
}
}
function safeGet(input, key) {
try {
return input[key];
} catch {
return "[property access threw]";
}
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Inspectable.js
/**
* Controls how values appear in logs and debugging output.
*
* Effect data types use `Inspectable` to provide stable string, JSON, and
* Node.js inspection output. This keeps custom values readable in logs, REPLs,
* test failures, and diagnostics. This module defines the Node inspect symbol,
* the `Inspectable` interface, safe conversion helpers, and shared prototype or
* class implementations for custom values.
*
* @stability stable
* @since 2.0.0
*/
/**
* Defines the symbol used by Node.js for custom object inspection.
*
* **When to use**
*
* Use to implement Node.js custom inspection for a value.
*
* **Details**
*
* This symbol is recognized by Node.js's `util.inspect()` function and the REPL
* for custom object representation. When an object has a method with this symbol,
* it will be called to determine how the object should be displayed.
*
* **Example** (Defining custom Node inspection)
*
* ```ts import.meta.vitest
* import { Inspectable } from "effect"
*
* class CustomObject {
* constructor(private value: string) {}
*
* [Inspectable.NodeInspectSymbol]() {
* return `CustomObject(${this.value})`
* }
* }
*
* const obj = new CustomObject("hello")
* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)"
* ```
*
* @stability stable
* @category symbols
* @since 2.0.0
*/
const NodeInspectSymbol =
/*#__PURE__*/ Symbol.for(
"nodejs.util.inspect.custom",
);
/**
* Converts a value to its structured inspection representation.
*
* **When to use**
*
* Use when you need the structured representation of an inspectable value
* without risking unhandled errors.
*
* **Details**
*
* This function applies redaction before extracting data from objects that
* implement `toJSON`, recursively processes arrays, and handles errors
* gracefully. Plain objects are returned unchanged, so the result is not
* guaranteed to be accepted by `JSON.stringify`; it may still contain values
* such as `BigInt`, functions, or circular references.
*
* @see {@link toStringUnknown} for converting unknown values to strings
*
* @stability stable
* @category converting
* @since 4.0.0
*/
const toJson = (input) => {
try {
input = redact$2(input);
if (
hasProperty(input, "toJSON") &&
isFunction(input["toJSON"]) &&
input["toJSON"].length === 0
)
return input.toJSON();
else if (Array.isArray(input))
return input.map(toJson);
return input;
} catch {
return "[toJSON threw]";
}
};
/**
* A base prototype object that implements the {@link Inspectable} interface.
*
* **When to use**
*
* Use as a prototype for plain objects that should share standard inspectable behavior.
*
* **Details**
*
* This object provides default implementations for the {@link Inspectable} methods.
* It can be used as a prototype for objects that want to be inspectable,
* or as a mixin to add inspection capabilities to existing objects.
*
* **Example** (Using the base inspectable prototype)
*
* ```ts import.meta.vitest
* import { Inspectable } from "effect"
*
* // Use as prototype
* const myObject = Object.create(Inspectable.BaseProto)
* myObject.name = "example"
* myObject.value = 42
*
* myObject.toString() // => "\"[toJSON threw]\""
*
* // Or extend in a constructor
* function MyClass(this: any, name: string) {
* this.name = name
* }
* MyClass.prototype = Object.create(Inspectable.BaseProto)
* MyClass.prototype.constructor = MyClass
* ```
*
* @stability stable
* @category prototypes
* @since 2.0.0
*/
const BaseProto = {
toJSON() {
return toJson(this);
},
[NodeInspectSymbol]() {
return this.toJSON();
},
toString() {
return format$1(this.toJSON());
},
};
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/stackTraceLimit.js
/**
* Check if `Error.stackTraceLimit` is writable.
* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible.
*
* @internal
*/
const isStackTraceLimitWritable =
() => {
const desc =
Object.getOwnPropertyDescriptor(
Error,
"stackTraceLimit",
);
if (desc === void 0)
return Object.isExtensible(Error);
return Object.hasOwn(
desc,
"writable",
)
? desc.writable === true
: desc.set !== void 0;
};
const canWriteStackTraceLimit =
/*#__PURE__*/ isStackTraceLimitWritable();
/**
* Get the current `Error.stackTraceLimit` value.
* Returns `undefined` if the property doesn't exist.
*
* @internal
*/
const getStackTraceLimit = () =>
Error.stackTraceLimit;
/**
* Safely set `Error.stackTraceLimit` if possible, otherwise no-op.
*
* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be
* restored faithfully.
*
* @internal
*/
const setStackTraceLimit = (value) => {
if (canWriteStackTraceLimit)
Error.stackTraceLimit = value;
};
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Utils.js
/**
* Yields its wrapped value exactly once, then completes with the value sent
* back in.
*
* **When to use**
*
* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be
* `yield*`-ed inside generator functions, such as `Effect.gen` and
* `Option.gen`.
*
* **Details**
*
* The first call to `next()` returns a fresh `{ value: self, done: false }`.
* Every subsequent call returns `{ value: a, done: true }` where `a` is the
* argument passed to `next()`. To keep `yield*` cheap, the completion result
* is the iterator itself rather than a new object, so only the iterator and
* the single yielded result are allocated per `yield*`.
*
* **Example** (Yielding a wrapped value in a generator)
*
* ```ts import.meta.vitest
* import { Utils } from "effect"
*
* const gen = new Utils.SingleShotGen<string, number>("hello")
*
* gen.next(0).value // => "hello"
*
* gen.next(42).value // => 42
* ```
*
* @see {@link Gen} for the type-level signature that relies on `SingleShotGen`
* @stability stable
* @category constructors
* @since 2.0.0
*/
var SingleShotGen = class {
constructor(self) {
this.value = self;
this.done = false;
}
/**
* Yields the stored value once, then completes with the value sent back in.
*
* **When to use**
*
* Use to advance a `SingleShotGen` through its single yield and completion
* step.
*
* @since 2.0.0
*/
next(a) {
if (this.done) {
this.value = a;
return this;
}
this.done = true;
return {
value: this.value,
done: false,
};
}
};
const pickInternalCall = () => {
const InternalTypeId =
"~effect/Utils/internal";
const standard = {
[InternalTypeId]: (body) => {
return body();
},
};
const forced = {
[InternalTypeId]: (body) => {
try {
return body();
} finally {
}
},
};
const limit = getStackTraceLimit();
if (limit === 0)
return forced[InternalTypeId];
setStackTraceLimit(2);
const error = standard[
InternalTypeId
](() => /* @__PURE__ */ new Error());
setStackTraceLimit(limit);
return error.stack?.includes(
InternalTypeId,
) === true
? standard[InternalTypeId]
: forced[InternalTypeId];
};
/** @internal */
const internalCall =
/*#__PURE__*/ pickInternalCall();
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/core.js
/** @internal */
const EffectTypeId = `~effect/Effect`;
/** @internal */
const ExitTypeId = `~effect/Exit`;
const effectVariance = {
_A: identity,
_E: identity,
_R: identity,
};
/** @internal */
const identifier = `${EffectTypeId}/identifier`;
/** @internal */
const args = `${EffectTypeId}/args`;
/** @internal */
const evaluate = `${EffectTypeId}/evaluate`;
/** @internal */
const contA = `${EffectTypeId}/successCont`;
/** @internal */
const contE = `${EffectTypeId}/failureCont`;
/** @internal */
const contAll = `${EffectTypeId}/ensureCont`;
/** @internal */
const Yield = /*#__PURE__*/ Symbol.for(
"effect/Effect/Yield",
);
/** @internal */
const PipeInspectableProto = {
pipe() {
return pipeArguments(
this,
arguments,
);
},
toJSON() {
return { ...this };
},
toString() {
return format$1(this.toJSON(), {
ignoreToString: true,
space: 2,
});
},
[NodeInspectSymbol]() {
return this.toJSON();
},
};
/** @internal */
const EffectProto = {
[EffectTypeId]: effectVariance,
...PipeInspectableProto,
[Symbol.iterator]() {
return new SingleShotGen(this);
},
toJSON() {
return {
_id: "Effect",
op: this[identifier],
...("~effect/Effect/args" in this
? { args: this[args] }
: void 0),
};
},
};
/** @internal */
const isExit = (u) =>
hasProperty(u, ExitTypeId);
/** @internal */
const CauseTypeId = "~effect/Cause";
/** @internal */
const CauseReasonTypeId =
"~effect/Cause/Reason";
/** @internal */
const isCause = (self) =>
hasProperty(self, CauseTypeId);
/** @internal */
var CauseImpl = class {
constructor(failures) {
this[CauseTypeId] = CauseTypeId;
this.reasons = failures;
}
pipe() {
return pipeArguments(
this,
arguments,
);
}
toJSON() {
return {
_id: "Cause",
failures: this.reasons.map((f) =>
f.toJSON(),
),
};
}
toString() {
return `Cause(${format$1(this.reasons)})`;
}
[NodeInspectSymbol]() {
return this.toJSON();
}
[symbol](that) {
return (
isCause(that) &&
this.reasons.length ===
that.reasons.length &&
this.reasons.every((e, i) =>
equals$1(e, that.reasons[i]),
)
);
}
[symbol$1]() {
return array(this.reasons);
}
};
const annotationsMap =
/*#__PURE__*/ new WeakMap();
/** @internal */
var ReasonBase = class {
[CauseReasonTypeId];
annotations;
_tag;
constructor(
_tag,
annotations,
originalError,
) {
this[CauseReasonTypeId] =
CauseReasonTypeId;
this._tag = _tag;
if (
annotations !==
constEmptyAnnotations &&
typeof originalError ===
"object" &&
originalError !== null &&
annotations.size > 0
) {
const prevAnnotations =
annotationsMap.get(
originalError,
);
if (prevAnnotations)
annotations = new Map([
...prevAnnotations,
...annotations,
]);
annotationsMap.set(
originalError,
annotations,
);
}
this.annotations = annotations;
}
annotate(annotations, options) {
if (
annotations.mapUnsafe.size === 0
)
return this;
const newAnnotations = new Map(
this.annotations,
);
annotations.mapUnsafe.forEach(
(value, key) => {
if (
options?.overwrite !== true &&
newAnnotations.has(key)
)
return;
newAnnotations.set(key, value);
},
);
const self = Object.assign(
Object.create(
Object.getPrototypeOf(this),
),
this,
);
self.annotations = newAnnotations;
return self;
}
pipe() {
return pipeArguments(
this,
arguments,
);
}
toString() {
return format$1(this);
}
[NodeInspectSymbol]() {
return this.toString();
}
};
/** @internal */
const constEmptyAnnotations =
/*#__PURE__*/ new Map();
/** @internal */
var Fail = class extends ReasonBase {
constructor(
error,
annotations = constEmptyAnnotations,
) {
super("Fail", annotations, error);
this.error = error;
}
toString() {
return `Fail(${format$1(this.error)})`;
}
toJSON() {
return {
_tag: "Fail",
error: this.error,
};
}
[symbol](that) {
return (
isFailReason$1(that) &&
equals$1(
this.error,
that.error,
) &&
equals$1(
this.annotations,
that.annotations,
)
);
}
[symbol$1]() {
return combine(string$1(this._tag))(
combine(hash(this.error))(
hash(this.annotations),
),
);
}
};
/** @internal */
const causeFromReasons = (reasons) =>
new CauseImpl(reasons);
const dedupeReasons = (self, that) => {
const buckets =
/* @__PURE__ */ new Map();
const out = [];
for (const reason of self.concat(
that,
)) {
const hash$2 = hash(reason);
const bucket = buckets.get(hash$2);
if (bucket === void 0)
buckets.set(hash$2, [reason]);
else if (
bucket.some((previous) =>
equals$1(previous, reason),
)
)
continue;
else bucket.push(reason);
out.push(reason);
}
return out;
};
/** @internal */
const causeCombine = /*#__PURE__*/ dual(
2,
(self, that) => {
if (self.reasons.length === 0)
return that;
else if (that.reasons.length === 0)
return self;
const newCause = new CauseImpl(
dedupeReasons(
self.reasons,
that.reasons,
),
);
return equals$1(self, newCause)
? self
: newCause;
},
);
/**
* Appends the interrupts from `interrupts` that `self` does not contain yet.
* Unlike `causeCombine`, it never calls hash or equality methods, which can be
* user-defined, random, or throwing.
*
* @internal
*/
const causeAddInterrupts = (
self,
interrupts,
) => {
const reasons = self.reasons.slice();
for (const reason of interrupts.reasons)
if (
isInterruptReason(reason) &&
!reasons.some(
(r) =>
isInterruptReason(r) &&
r.fiberId ===
reason.fiberId &&
r.annotations ===
reason.annotations,
)
)
reasons.push(reason);
return reasons.length ===
self.reasons.length
? self
: new CauseImpl(reasons);
};
/** @internal */
const causeFail = (error) =>
new CauseImpl([new Fail(error)]);
/** @internal */
var Die = class extends ReasonBase {
constructor(
defect,
annotations = constEmptyAnnotations,
) {
super("Die", annotations, defect);
this.defect = defect;
}
toString() {
return `Die(${format$1(this.defect)})`;
}
toJSON() {
return {
_tag: "Die",
defect: this.defect,
};
}
[symbol](that) {
return (
isDieReason(that) &&
equals$1(
this.defect,
that.defect,
) &&
equals$1(
this.annotations,
that.annotations,
)
);
}
[symbol$1]() {
return combine(string$1(this._tag))(
combine(hash(this.defect))(
hash(this.annotations),
),
);
}
};
/** @internal */
const causeDie = (defect) =>
new CauseImpl([new Die(defect)]);
/** @internal */
const causeAnnotate =
/*#__PURE__*/ dual(
(args) => isCause(args[0]),
(self, annotations, options) => {
if (
annotations.mapUnsafe.size === 0
)
return self;
return new CauseImpl(
self.reasons.map((f) =>
f.annotate(
annotations,
options,
),
),
);
},
);
/** @internal */
const isFailReason$1 = (self) =>
self._tag === "Fail";
/** @internal */
const isDieReason = (self) =>
self._tag === "Die";
/** @internal */
const isInterruptReason = (self) =>
self._tag === "Interrupt";
function defaultEvaluate(_fiber) {
return exitDie(
`Effect.evaluate: Not implemented`,
);
}
/** @internal */
const makePrimitiveProto = (
options,
) => ({
...EffectProto,
[identifier]: options.op,
[evaluate]:
options[
"~effect/Effect/evaluate"
] ?? defaultEvaluate,
[contA]: options[contA],
[contE]: options[contE],
[contAll]: options[contAll],
});
/** @internal */
const makePrimitive = (options) => {
const Proto =
makePrimitiveProto(options);
const PrimitiveImpl = function (
value,
) {
this[args] = value;
};
PrimitiveImpl.prototype = Proto;
return function (value) {
return new PrimitiveImpl(value);
};
};
/** @internal */
const makeExit = (options) => {
const Proto = {
[ExitTypeId]: ExitTypeId,
_tag: options.op,
get [options.prop]() {
return this[args];
},
...makePrimitiveProto(options),
toString() {
return `${options.op}(${format$1(this[args])})`;
},
toJSON() {
return {
_id: "Exit",
_tag: options.op,
[options.prop]: this[args],
};
},
[symbol](that) {
return (
isExit(that) &&
that._tag === this._tag &&
equals$1(
this["~effect/Effect/args"],
that["~effect/Effect/args"],
)
);
},
[symbol$1]() {
return combine(
string$1(options.op),
hash(this[args]),
);
},
};
const ExitPrimitive = function (
value,
) {
this[args] = value;
};
ExitPrimitive.prototype = Proto;
return function (value) {
return new ExitPrimitive(value);
};
};
/** @internal */
const exitSucceed =
/*#__PURE__*/ makeExit({
op: "Success",
prop: "value",
[evaluate](fiber) {
const cont = fiber.getCont(contA);
return cont
? cont[contA](
this[args],
fiber,
this,
)
: fiber.yieldWith(this);
},
});
/** @internal */
const StackTraceKey = {
key: "effect/Cause/StackTrace",
};
/** @internal */
const InterruptorStackTrace = {
key: "effect/Cause/InterruptorStackTrace",
};
/** @internal */
const exitFailCause =
/*#__PURE__*/ makeExit({
op: "Failure",
prop: "cause",
[evaluate](fiber) {
let cause = this[args];
let annotated = false;
if (fiber.cache.stackFrame) {
cause = causeAnnotate(cause, {
mapUnsafe:
/* @__PURE__ */ new Map([
[
StackTraceKey.key,
fiber.cache.stackFrame,
],
]),
});
annotated = true;
}
let cont = fiber.getCont(contE);
const interruptedCause =
fiber._interruptedCause;
if (
interruptedCause &&
fiber.interruptible
) {
let skippedHandler = false;
while (
cont &&
fiber.interruptible
) {
skippedHandler ||=
identifier in cont;
cont = fiber.getCont(contE);
}
if (skippedHandler)
cause = causeFromReasons(
cause.reasons.filter(
(reason) =>
reason._tag !== "Fail",
),
);
cause = causeAddInterrupts(
cause,
interruptedCause,
);
annotated = true;
}
return cont
? cont[contE](
cause,
fiber,
annotated ? void 0 : this,
)
: fiber.yieldWith(
annotated
? exitFailCause(cause)
: this,
);
},
});
/** @internal */
const exitFail = (e) =>
exitFailCause(causeFail(e));
/** @internal */
const exitDie = (defect) =>
exitFailCause(causeDie(defect));
/** @internal */
const withFiber =
/*#__PURE__*/ makePrimitive({
op: "WithFiber",
[evaluate](fiber) {
return this[args](fiber);
},
});
/** @internal */
const YieldableError =
/*#__PURE__*/ (function () {
class YieldableError
extends globalThis.Error {}
const proto =
/*#__PURE__*/ makePrimitiveProto({
op: "YieldableError",
[evaluate]() {
return exitFail(this);
},
});
delete proto.toString;
Object.assign(
YieldableError.prototype,
proto,
);
return YieldableError;
})();
/** @internal */
const Error$2 =
/*#__PURE__*/ (function () {
const plainArgsSymbol =
/*#__PURE__*/ Symbol.for(
"effect/Data/Error/plainArgs",
);
return class Base extends YieldableError {
constructor(args) {
super(
args?.message,
args?.cause
? { cause: args.cause }
: void 0,
);
if (args) {
assignProperties(this, args);
Object.defineProperty(
this,
plainArgsSymbol,
{
value: args,
enumerable: false,
},
);
}
}
toJSON() {
return {
...this[plainArgsSymbol],
...this,
};
}
};
})();
/** @internal */
const TaggedError$1 = (tag) => {
class Base extends Error$2 {
_tag = tag;
}
Base.prototype.name = tag;
return Base;
};
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/option.js
/**
* @since 2.0.0
*/
const TypeId$15 = "~effect/Option";
const CommonProto$1 = {
[TypeId$15]: { _A: (_) => _ },
...PipeInspectableProto,
[Symbol.iterator]() {
return new SingleShotGen(this);
},
};
const SomeProto =
/*#__PURE__*/ Object.defineProperty(
/*#__PURE__*/ Object.assign(
/*#__PURE__*/ Object.create(
CommonProto$1,
),
{
_tag: "Some",
_op: "Some",
[symbol](that) {
return (
isOption(that) &&
isSome$1(that) &&
equals$1(
this.value,
that.value,
)
);
},
[symbol$1]() {
return combine(
hash(this._tag),
)(hash(this.value));
},
toString() {
return `some(${format$1(this.value)})`;
},
toJSON() {
return {
_id: "Option",
_tag: this._tag,
value: toJson(this.value),
};
},
},
),
"valueOrUndefined",
{
get() {
return this.value;
},
},
);
const NoneHash =
/*#__PURE__*/ hash("None");
const NoneProto =
/*#__PURE__*/ Object.assign(
/*#__PURE__*/ Object.create(
CommonProto$1,
),
{
_tag: "None",
_op: "None",
valueOrUndefined: void 0,
[symbol](that) {
return (
isOption(that) &&
isNone$1(that)
);
},
[symbol$1]() {
return NoneHash;
},
toString() {
return `none()`;
},
toJSON() {
return {
_id: "Option",
_tag: this._tag,
};
},
},
);
/** @internal */
const isOption = (input) =>
hasProperty(input, TypeId$15);
/** @internal */
const isNone$1 = (fa) =>
fa._tag === "None";
/** @internal */
const isSome$1 = (fa) =>
fa._tag === "Some";
/** @internal */
const none$1 =
/*#__PURE__*/ Object.create(
NoneProto,
);
/** @internal */
const SomeImpl = function (value) {
this.value = value;
};
SomeImpl.prototype = SomeProto;
/** @internal */
const some$1 = (value) =>
new SomeImpl(value);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/result.js
const TypeId$14 = "~effect/Result";
const CommonProto = {
[TypeId$14]: {
/* v8 ignore next 2 */
_A: (_) => _,
_E: (_) => _,
},
...PipeInspectableProto,
[Symbol.iterator]() {
return new SingleShotGen(this);
},
};
const SuccessProto =
/*#__PURE__*/ Object.assign(
/*#__PURE__*/ Object.create(
CommonProto,
),
{
_tag: "Success",
_op: "Success",
[symbol](that) {
return (
isResult(that) &&
isSuccess$2(that) &&
equals$1(
this.success,
that.success,
)
);
},
[symbol$1]() {
return combine(hash(this._tag))(
hash(this.success),
);
},
toString() {
return `success(${format$1(this.success)})`;
},
toJSON() {
return {
_id: "Result",
_tag: this._tag,
value: toJson(this.success),
};
},
},
);
const FailureProto =
/*#__PURE__*/ Object.assign(
/*#__PURE__*/ Object.create(
CommonProto,
),
{
_tag: "Failure",
_op: "Failure",
[symbol](that) {
return (
isResult(that) &&
isFailure$1(that) &&
equals$1(
this.failure,
that.failure,
)
);
},
[symbol$1]() {
return combine(hash(this._tag))(
hash(this.failure),
);
},
toString() {
return `failure(${format$1(this.failure)})`;
},
toJSON() {
return {
_id: "Result",
_tag: this._tag,
failure: toJson(this.failure),
};
},
},
);
/** @internal */
const isResult = (input) =>
hasProperty(input, TypeId$14);
/** @internal */
const isFailure$1 = (result) =>
result._tag === "Failure";
/** @internal */
const isSuccess$2 = (result) =>
result._tag === "Success";
/** @internal */
const FailureImpl = function (failure) {
this.failure = failure;
};
FailureImpl.prototype = FailureProto;
/** @internal */
const SuccessImpl = function (success) {
this.success = success;
};
SuccessImpl.prototype = SuccessProto;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Order.js
/**
* Defines comparison functions for ordered values.
*
* An `Order<A>` compares two `A` values and returns whether the first is less
* than, equal to, or greater than the second. Orders are used for sorting,
* choosing minimum or maximum values, checking ranges, and building ordered data
* structures. This module includes built-in orders, constructors for custom
* orders, tools for reversing and combining comparisons, tuple and struct
* helpers, comparison predicates, clamping, and reducer support.
*
* @stability stable
* @since 2.0.0
*/
/**
* Creates a new `Order` instance from a comparison function.
*
* **When to use**
*
* Use when you need a sorting rule not covered by the built-in orders or input
* mapping helpers, and you can provide a total comparison.
*
* **Details**
*
* Uses reference equality (`===`) as a shortcut: if `self === that`, it returns
* `0` without calling the comparison function. The comparison function should
* return `-1`, `0`, or `1`, and the returned order satisfies total ordering
* laws when the comparison function does.
*
* **Example** (Creating an Order)
*
* ```ts import.meta.vitest
* import { Order } from "effect"
*
* const byAge = Order.make<{ name: string; age: number }>((self, that) => {
* if (self.age < that.age) return -1
* if (self.age > that.age) return 1
* return 0
* })
*
* byAge({ name: "Alice", age: 30 }, { name: "Bob", age: 25 }) // => 1
* byAge({ name: "Alice", age: 25 }, { name: "Bob", age: 30 }) // => -1
* ```
*
* @see {@link mapInput} to transform an order by mapping the input type
* @see {@link combine} to combine multiple orders
* @stability stable
* @category constructors
* @since 2.0.0
*/
function make$10(compare) {
return (self, that) =>
self === that
? 0
: compare(self, that);
}
/**
* Order instance for strings that compares them lexicographically using JavaScript's `<` operator.
*
* **When to use**
*
* Use when you need lexicographic string ordering.
*
* **Details**
*
* Uses lexicographic dictionary ordering. The empty string is less than any
* non-empty string, and comparisons are case-sensitive.
*
* **Example** (Ordering strings)
*
* ```ts import.meta.vitest
* import { Order } from "effect"
*
* Order.String("apple", "banana") // => -1
* Order.String("banana", "apple") // => 1
* Order.String("apple", "apple") // => 0
* ```
*
* @see {@link mapInput} to compare objects by a string property
* @see {@link Struct} to combine with other orders for struct comparison
* @stability stable
* @category instances
* @since 4.0.0
*/
const String$4 = /*#__PURE__*/ make$10(
(self, that) =>
self < that ? -1 : 1,
);
/**
* Order instance for numbers that compares them numerically.
*
* **When to use**
*
* Use when you need numeric ordering for numbers.
*
* **Details**
*
* `0` is considered equal to `-0`. All `NaN` values are considered equal to
* each other, and any `NaN` is considered less than any non-`NaN` number. All
* other values use standard numeric comparison.
*
* **Example** (Ordering numbers)
*
* ```ts import.meta.vitest
* import { Order } from "effect"
*
* Order.Number(1, 1) // => 0
* Order.Number(1, 2) // => -1
* Order.Number(2, 1) // => 1
*
* Order.Number(0, -0) // => 0
* Order.Number(NaN, 1) // => -1
* ```
*
* @see {@link mapInput} to compare objects by a number property
* @see {@link BigInt} for bigint comparisons
* @stability stable
* @category instances
* @since 4.0.0
*/
const Number$4 = /*#__PURE__*/ make$10(
(self, that) => {
if (
globalThis.Number.isNaN(self) &&
globalThis.Number.isNaN(that)
)
return 0;
if (globalThis.Number.isNaN(self))
return -1;
if (globalThis.Number.isNaN(that))
return 1;
return self < that ? -1 : 1;
},
);
/**
* Checks whether one value is less than or equal to another according to the given order.
*
* **When to use**
*
* Use when you need a boolean less-than-or-equal predicate using an `Order`.
*
* **Details**
*
* Returns `true` if the order returns `-1` or `0`, and returns `false` only if
* the order returns `1`.
*
* **Example** (Checking less-than-or-equal comparisons)
*
* ```ts import.meta.vitest
* import { Order } from "effect"
*
* const isLessThanOrEqualToNumber = Order.isLessThanOrEqualTo(Order.Number)
*
* isLessThanOrEqualToNumber(1, 2) // => true
* isLessThanOrEqualToNumber(1, 1) // => true
* isLessThanOrEqualToNumber(2, 1) // => false
* ```
*
* @see {@link isLessThan} for strict less than
* @see {@link isGreaterThan} for strict greater than
* @stability stable
* @category predicates
* @since 4.0.0
*/
const isLessThanOrEqualTo$1 = (O) =>
dual(
2,
(self, that) => O(self, that) !== 1,
);
/**
* Checks whether one value is greater than or equal to another according to the given order.
*
* **When to use**
*
* Use when you need a boolean greater-than-or-equal predicate using an
* `Order`.
*
* **Details**
*
* Returns `true` if the order returns `1` or `0`, and returns `false` only if
* the order returns `-1`.
*
* **Example** (Checking greater-than-or-equal comparisons)
*
* ```ts import.meta.vitest
* import { Order } from "effect"
*
* const isGreaterThanOrEqualToNumber = Order.isGreaterThanOrEqualTo(Order.Number)
*
* isGreaterThanOrEqualToNumber(2, 1) // => true
* isGreaterThanOrEqualToNumber(1, 1) // => true
* isGreaterThanOrEqualToNumber(1, 2) // => false
* ```
*
* @see {@link isGreaterThan} for strict greater than
* @see {@link isLessThanOrEqualTo} for less than or equal
* @stability stable
* @category predicates
* @since 4.0.0
*/
const isGreaterThanOrEqualTo$1 = (O) =>
dual(
2,
(self, that) =>
O(self, that) !== -1,
);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Option.js
/**
* Creates an `Option` representing the absence of a value.
*
* **When to use**
*
* Use to represent a missing or uninitialized value, such as returning "no
* result" from a function.
*
* **Details**
*
* - Returns `Option<never>`, which is a subtype of `Option<A>` for any `A`
* - Always returns the same singleton instance
*
* **Example** (Creating an empty Option)
*
* ```ts import.meta.vitest
* import { Option } from "effect"
*
* // ┌─── Option<never>
* // â–¼
* const noValue = Option.none() // => Option.none()
* ```
*
* @see {@link some} for the opposite operation.
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const none = () => none$1;
/**
* Wraps the given value into an `Option` to represent its presence.
*
* **When to use**
*
* Use to wrap a known present value as `Option`
* - Returning a successful result from a partial function
*
* **Details**
*
* - Always returns `Some<A>`
* - Does not filter `null` or `undefined`; use {@link fromNullishOr} for that
*
* **Example** (Wrapping a value)
*
* ```ts import.meta.vitest
* import { Option } from "effect"
*
* // ┌─── Option<number>
* // â–¼
* const value = Option.some(1) // => Option.some(1)
* ```
*
* @see {@link none} for the opposite operation.
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const some = some$1;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Array.js
/**
* Exposes the global array constructor.
*
* **When to use**
*
* Use to access native JavaScript array constructor methods such as `isArray`
* or `from` from the Effect module namespace.
*
* **Example** (Accessing the Array constructor)
*
* ```ts import.meta.vitest
* import { Array } from "effect"
*
* Array.Array === globalThis.Array // => true
* ```
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Array$1 = globalThis.Array;
/**
* Adds a single element to the end of an iterable, returning a `NonEmptyArray`.
*
* **When to use**
*
* Use when you need to guarantee a non-empty result after adding a required
* trailing value.
*
* **Example** (Appending an element)
*
* ```ts import.meta.vitest
* import { Array } from "effect"
*
* Array.append([1, 2, 3], 4) // => [1, 2, 3, 4]
* ```
*
* @see {@link prepend} — add to the front
* @see {@link appendAll} — append multiple elements
*
* @stability stable
* @category combining
* @since 2.0.0
*/
const append = /*#__PURE__*/ dual(
2,
(self, last) => [...self, last],
);
Array$1.isArray;
/**
* Checks whether a mutable `Array` is non-empty, narrowing the type to
* `NonEmptyArray`.
*
* **When to use**
*
* Use when you need the narrowed value to remain a mutable `Array` after proving
* it has at least one element.
*
* **Example** (Checking for a non-empty array)
*
* ```ts import.meta.vitest
* import { Array } from "effect"
*
* Array.isArrayNonEmpty([]) // => false
* Array.isArrayNonEmpty([1, 2, 3]) // => true
* ```
*
* @see {@link isReadonlyArrayNonEmpty} — readonly variant
* @see {@link isArrayEmpty} — opposite check
*
* @stability stable
* @category guards
* @since 4.0.0
*/
const isArrayNonEmpty =
isArrayNonEmpty$1;
/**
* Checks whether a `ReadonlyArray` is non-empty, narrowing the type to
* `NonEmptyReadonlyArray`.
*
* **When to use**
*
* Use when you need to prove a readonly array has at least one element without
* requiring mutable array methods afterward.
*
* **Example** (Checking for a non-empty readonly array)
*
* ```ts import.meta.vitest
* import { Array } from "effect"
*
* Array.isReadonlyArrayNonEmpty([]) // => false
* Array.isReadonlyArrayNonEmpty([1, 2, 3]) // => true
* ```
*
* @see {@link isArrayNonEmpty} — mutable variant
* @see {@link isReadonlyArrayEmpty} — opposite check
*
* @stability stable
* @category guards
* @since 4.0.0
*/
const isReadonlyArrayNonEmpty =
isArrayNonEmpty$1;
/**
* Creates an empty array.
*
* **When to use**
*
* Use to create a typed empty array without allocating placeholder elements.
*
* **Example** (Creating an empty array)
*
* ```ts import.meta.vitest
* import { Array } from "effect"
*
* Array.empty<number>() // => []
* ```
*
* @see {@link of} — create a single-element array
* @see {@link make} — create from multiple values
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const empty$1 = () => [];
/**
* Transforms each element using a function, returning a new array.
*
* **When to use**
*
* Use to transform each element independently while preserving the array shape.
*
* **Details**
*
* The function receives `(element, index)`. The return type preserves
* `NonEmptyArray`.
*
* **Example** (Doubling values)
*
* ```ts import.meta.vitest
* import { Array } from "effect"
*
* Array.map([1, 2, 3], (x) => x * 2) // => [2, 4, 6]
* ```
*
* @see {@link flatMap} — map and flatten
*
* @stability stable
* @category mapping
* @since 2.0.0
*/
const map$2 = /*#__PURE__*/ dual(
2,
(self, f) => self.map(f),
);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/BigDecimal.js
/**
* Decimal numbers and arithmetic for cases where JavaScript `number` rounding
* is not precise enough. A `BigDecimal` stores digits as a `bigint` plus a
* decimal scale, which lets the module parse, compare, add, subtract, multiply,
* divide, round, and format decimal values such as money, quantities, and
* measurements.
*
* @stability stable
* @since 2.0.0
*/
const TypeId$13 = "~effect/BigDecimal";
const BigDecimalProto = {
[TypeId$13]: TypeId$13,
[symbol$1]() {
const normalized = normalize(this);
return combine(
string$1(
String(normalized.value),
),
number$1(normalized.scale),
);
},
[symbol](that) {
return (
isBigDecimal(that) &&
compare(this, that) === 0
);
},
toString() {
return `BigDecimal(${format(this)})`;
},
toJSON() {
return {
_id: "BigDecimal",
value: String(this.value),
scale: this.scale,
};
},
[NodeInspectSymbol]() {
return this.toJSON();
},
pipe() {
return pipeArguments(
this,
arguments,
);
},
};
/**
* Checks whether a given value is a `BigDecimal`.
*
* **When to use**
*
* Use to validate unknown input and narrow it to `BigDecimal`.
*
* **Example** (Checking BigDecimal values)
*
* ```ts import.meta.vitest
* import { BigDecimal } from "effect"
*
* const decimal = BigDecimal.fromNumber(123.45)
* BigDecimal.isBigDecimal(decimal) // => false
* BigDecimal.isBigDecimal(BigDecimal.fromStringUnsafe("123.45")) // => true
* BigDecimal.isBigDecimal(123.45) // => false
* BigDecimal.isBigDecimal("123.45") // => false
* ```
*
* @stability stable
* @category guards
* @since 2.0.0
*/
const isBigDecimal = (u) =>
hasProperty(u, TypeId$13);
/**
* Creates a `BigDecimal` from a `bigint` value and a safe integer scale.
*
* **When to use**
*
* Use to construct a decimal directly from its unscaled integer value and
* decimal scale.
*
* **Gotchas**
*
* Throws a `RangeError` if `scale` is not a safe integer.
*
* **Example** (Creating decimals from bigint and scale)
*
* ```ts import.meta.vitest
* import { BigDecimal } from "effect"
*
* // Create 123.45 (12345 with scale 2)
* const decimal = BigDecimal.make(12345n, 2)
* decimal // => BigDecimal.fromStringUnsafe("123.45")
*
* // Create 42 (42 with scale 0)
* const integer = BigDecimal.make(42n, 0)
* integer // => BigDecimal.fromBigInt(42n)
* ```
*
* @see {@link fromBigInt} for constructing an integer decimal from a `bigint`
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const make$9 = (value, scale) => {
if (!Number.isSafeInteger(scale))
throw new RangeError(
`Scale must be a safe integer, got ${scale}`,
);
const o = Object.create(
BigDecimalProto,
);
o.value = value;
o.scale = scale;
return o;
};
const makeNormalized = (
value,
scale,
) => {
const o = make$9(value, scale);
o.normalized = o;
return o;
};
const bigint0$1 =
/*#__PURE__*/ BigInt(0);
const bigint1$1 =
/*#__PURE__*/ BigInt(1);
const bigint10$1 =
/*#__PURE__*/ BigInt(10);
const zero$1 =
/*#__PURE__*/ makeNormalized(
bigint0$1,
0,
);
/**
* Normalizes a given `BigDecimal` by removing trailing zeros.
*
* **When to use**
*
* Use to canonicalize decimals that have equivalent values but different
* internal scales.
*
* **Example** (Normalizing trailing zeros)
*
* ```ts import.meta.vitest
* import { BigDecimal } from "effect"
*
* const decimal = BigDecimal.normalize(BigDecimal.fromStringUnsafe("123.00000"))
* const decimalStorage = [decimal.value, decimal.scale] // => [123n, 0]
*
* const largeDecimal = BigDecimal.normalize(BigDecimal.fromStringUnsafe("12300000"))
* const largeDecimalStorage = [largeDecimal.value, largeDecimal.scale] // => [123n, -5]
* ```
*
* @see {@link format} for rendering normalized decimals as strings
*
* @stability stable
* @category scaling
* @since 2.0.0
*/
const normalize = (self) => {
if (self.normalized === void 0) {
if (self.value === bigint0$1)
self.normalized = zero$1;
else {
const digits = `${self.value}`;
let end = digits.length;
while (digits[end - 1] === "0")
end--;
self.normalized = makeNormalized(
BigInt(digits.slice(0, end)),
self.scale -
(digits.length - end),
);
}
}
return self.normalized;
};
const MAX_COMPARISON_SCALE_ALIGNMENT = 100;
const comparisonPowersOfTen = [
bigint1$1,
];
const compareBigInt = (self, that) =>
self === that
? 0
: self < that
? -1
: 1;
const compareMagnitude = (
self,
that,
) => {
const selfDigits = `${self.value < bigint0$1 ? -self.value : self.value}`;
const thatDigits = `${that.value < bigint0$1 ? -that.value : that.value}`;
const exponentDifference =
BigInt(
selfDigits.length -
thatDigits.length,
) -
BigInt(self.scale) +
BigInt(that.scale);
if (exponentDifference !== bigint0$1)
return exponentDifference <
bigint0$1
? -1
: 1;
const length = Math.max(
selfDigits.length,
thatDigits.length,
);
return String$4(
selfDigits.padEnd(length, "0"),
thatDigits.padEnd(length, "0"),
);
};
const compare = (self, that) => {
if (self.scale === that.scale)
return compareBigInt(
self.value,
that.value,
);
const selfSign = sign(self);
const thatSign = sign(that);
if (selfSign !== thatSign)
return selfSign < thatSign ? -1 : 1;
if (selfSign === 0) return 0;
const scaleDifference =
self.scale - that.scale;
const absoluteScaleDifference =
Math.abs(scaleDifference);
if (
absoluteScaleDifference >
MAX_COMPARISON_SCALE_ALIGNMENT
)
return selfSign === -1
? compareMagnitude(that, self)
: compareMagnitude(self, that);
const powerOfTen =
(comparisonPowersOfTen[
absoluteScaleDifference
] ??=
bigint10$1 **
BigInt(absoluteScaleDifference));
return scaleDifference > 0
? compareBigInt(
self.value,
that.value * powerOfTen,
)
: compareBigInt(
self.value * powerOfTen,
that.value,
);
};
/**
* Determines the sign of a given `BigDecimal`.
*
* **When to use**
*
* Use to classify a `BigDecimal` as negative, zero, or positive.
*
* **Example** (Reading decimal signs)
*
* ```ts import.meta.vitest
* import { BigDecimal } from "effect"
*
* BigDecimal.sign(BigDecimal.fromStringUnsafe("-5")) // => -1
* BigDecimal.sign(BigDecimal.fromStringUnsafe("0")) // => 0
* BigDecimal.sign(BigDecimal.fromStringUnsafe("5")) // => 1
* ```
*
* @stability stable
* @category math
* @since 2.0.0
*/
const sign = (n) =>
n.value === bigint0$1
? 0
: n.value < bigint0$1
? -1
: 1;
/**
* Formats a `BigDecimal` as a string.
*
* **When to use**
*
* Use to render a `BigDecimal` as plain decimal text when possible.
*
* **Details**
*
* The value is normalized before formatting. Scientific notation is used when
* the absolute value of the normalized scale is at least `16`; otherwise plain
* decimal notation is used.
*
* **Example** (Formatting decimals)
*
* ```ts import.meta.vitest
* import { BigDecimal } from "effect"
*
* BigDecimal.format(BigDecimal.fromStringUnsafe("-5")) // => "-5"
* BigDecimal.format(BigDecimal.fromStringUnsafe("123.456")) // => "123.456"
* BigDecimal.format(BigDecimal.fromStringUnsafe("-0.00000123")) // => "-0.00000123"
* ```
*
* @see {@link toExponential} for always rendering scientific notation
*
* @stability stable
* @category converting
* @since 2.0.0
*/
const format = (n) => {
const normalized = normalize(n);
if (Math.abs(normalized.scale) >= 16)
return toExponential(normalized);
const negative =
normalized.value < bigint0$1;
const absolute = `${negative ? -normalized.value : normalized.value}`;
const digits =
normalized.scale > 0
? absolute.padStart(
normalized.scale + 1,
"0",
)
: absolute.padEnd(
absolute.length -
normalized.scale,
"0",
);
const point =
digits.length - normalized.scale;
const complete =
normalized.scale > 0
? `${digits.slice(0, point)}.${digits.slice(point)}`
: digits;
return negative
? `-${complete}`
: complete;
};
/**
* Formats a given `BigDecimal` as a `string` in scientific notation.
*
* **When to use**
*
* Use to render a `BigDecimal` in scientific notation.
*
* **Example** (Formatting decimals exponentially)
*
* ```ts import.meta.vitest
* import { BigDecimal } from "effect"
*
* BigDecimal.toExponential(BigDecimal.make(123456n, -5)) // => "1.23456e+10"
* ```
*
* @see {@link format} for plain decimal formatting when possible
*
* @stability stable
* @category converting
* @since 3.11.0
*/
const toExponential = (n) => {
if (isZero(n)) return "0e+0";
const normalized = normalize(n);
const digits = `${normalized.value}`;
const point =
normalized.value < bigint0$1
? 2
: 1;
const head = digits.slice(0, point);
const tail = digits.slice(point);
const exp =
tail.length - normalized.scale;
return `${head}${tail === "" ? "" : `.${tail}`}e${exp >= 0 ? "+" : ""}${exp}`;
};
/**
* Checks whether a given `BigDecimal` is `0`.
*
* **When to use**
*
* Use to test whether a `BigDecimal` is exactly zero.
*
* **Example** (Checking zero decimals)
*
* ```ts import.meta.vitest
* import { BigDecimal } from "effect"
*
* BigDecimal.isZero(BigDecimal.fromStringUnsafe("0")) // => true
* BigDecimal.isZero(BigDecimal.fromStringUnsafe("1")) // => false
* ```
*
* @stability stable
* @category predicates
* @since 2.0.0
*/
const isZero = (n) =>
n.value === bigint0$1;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Effectable.js
/**
* Create a low-level `Effect` prototype.
*
* **When to use**
*
* Use when you need to create a custom Effect-like value without extending a
* class, by providing a label and an evaluate function that receives the
* current fiber.
*
* **Details**
*
* When the effect is evaluated, it calls `evaluate` with the current fiber.
*
* @see {@link Class} for a class-based approach to defining custom Effect values
* @see {@link Mixin} for wrapping an existing class constructor
*
* @stability stable
* @category prototypes
* @since 4.0.0
*/
const Prototype = (options) =>
makePrimitiveProto({
op: options.label,
[evaluate]: options.evaluate,
});
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Context.js
/**
* Runtime type identifier attached to `Context` service keys and used by
* `isKey` to recognize them.
*
* @stability stable
* @category type IDs
* @since 4.0.0
*/
const ServiceTypeId =
"~effect/Context/Service";
/**
* Creates a `Context` service key.
*
* **When to use**
*
* Use when you need to define a context service key for a dependency that must
* be provided by the surrounding context.
*
* **Details**
*
* Call `Context.Service("Key")` for a function-style key, or use the two-stage
* form `Context.Service<Self, Shape>()("Key")` for class-style service
* declarations. The returned key can be yielded as an Effect and passed to
* `Context.make`, `Context.add`, and the Context getter functions.
*
* **Gotchas**
*
* The string key is the runtime identity of the service. Reusing the same key
* string for unrelated services makes them occupy the same slot in a
* `Context`.
*
* **Example** (Creating service keys)
*
* ```ts import.meta.vitest
* import { Context } from "effect"
*
* // Create a simple service
* const Database = Context.Service<{
* query: (sql: string) => string
* }>("Database")
*
* // Create a service class
* class Config extends Context.Service<Config, {
* port: number
* }>()("Config") {}
*
* // Use the services to create contexts
* const db = Context.make(Database, {
* query: (sql) => `Result: ${sql}`
* })
* const config = Context.make(Config, { port: 8080 })
* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1"
* Context.get(config, Config).port // => 8080
* ```
*
* @see {@link Reference} for service keys with default values
*
* @stability stable
* @category services
* @since 4.0.0
*/
const Service = function () {
function KeyClass() {}
const self = KeyClass;
Object.setPrototypeOf(
self,
ServiceProto,
);
const init = (key, options) => {
self.key = key;
if (options?.defaultValue) {
self[ReferenceTypeId] =
ReferenceTypeId;
self.defaultValue =
options.defaultValue;
}
if (options?.make)
self.make = options.make;
if (options?.fiberCached)
cacheKeys.add(key);
return self;
};
return arguments.length > 0
? init(arguments[0], arguments[1])
: init;
};
const ServiceProto = {
[ServiceTypeId]: ServiceTypeId,
.../*#__PURE__*/ Prototype({
label: "Service",
evaluate(fiber) {
return exitSucceed(
get(fiber.context, this),
);
},
}),
toJSON() {
return {
_id: "Service",
key: this.key,
};
},
of(self) {
return self;
},
context(self) {
return make$8(this, self);
},
use(f) {
return withFiber((fiber) =>
f(get(fiber.context, this)),
);
},
useSync(f) {
return withFiber((fiber) =>
exitSucceed(
f(get(fiber.context, this)),
),
);
},
};
const cacheKeys =
/*#__PURE__*/ new Set();
const ReferenceTypeId =
"~effect/Context/Reference";
const TypeId$12 = "~effect/Context";
const MaxDepth = 8;
const FlattenAfterBaseHits = 8;
const makeImpl = (
cacheRoot,
base,
overlay,
depth,
) => {
const self = Object.create(Proto$5);
self.cacheRoot = cacheRoot ?? self;
self.base = base;
self.overlay = overlay;
self.depth = depth;
self._flat = void 0;
self.baseHits = 0;
return self;
};
const applyOverlays = (
map,
overlay,
) => {
if (!overlay) return;
applyOverlays(map, overlay.parent);
map.set(overlay.key, overlay.value);
};
const flatten = (self) => {
if (self._flat) return self._flat;
if (!self.overlay)
return (self._flat = self.base);
const map = new Map(self.base);
applyOverlays(map, self.overlay);
return (self._flat = map);
};
const notFound = /*#__PURE__*/ Symbol();
const lookup = (self, key) => {
const impl = self;
for (
let overlay = impl.overlay;
overlay;
overlay = overlay.parent
)
if (overlay.key === key)
return overlay.value;
const value = impl.base.get(key);
if (
value === void 0 &&
!impl.base.has(key)
)
return notFound;
if (
impl.overlay &&
++impl.baseHits >= impl.base.size &&
impl.baseHits >=
FlattenAfterBaseHits
) {
impl.base = flatten(impl);
impl.overlay = void 0;
impl.depth = 0;
}
return value;
};
/**
* Creates a `Context` from an existing service map.
*
* **When to use**
*
* Use when constructing a low-level `Context` from a trusted map whose lifecycle
* you control.
*
* **Gotchas**
*
* The provided map is retained without copying and must not be mutated after
* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context
* construction.
*
* **Example** (Creating a context from a map)
*
* ```ts import.meta.vitest
* import { Context } from "effect"
*
* // Create a context from a Map (unsafe)
* const map = new Map([
* ["Logger", { log: (_msg: string) => {} }]
* ])
*
* const context = Context.makeUnsafe(map)
* context.mapUnsafe.size // => 1
* ```
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const makeUnsafe$2 = (mapUnsafe) =>
makeImpl(
void 0,
mapUnsafe,
void 0,
0,
);
const Proto$5 = {
get mapUnsafe() {
return flatten(this);
},
...PipeInspectableProto,
[TypeId$12]: { _Services: (_) => _ },
toJSON() {
return {
_id: "Context",
services: Array.from(
this.mapUnsafe,
).map(([key, value]) => ({
key,
value,
})),
};
},
[symbol](that) {
if (!isContext(that)) return false;
const self = this.mapUnsafe;
const other = that.mapUnsafe;
if (self.size !== other.size)
return false;
for (const [key, value] of self)
if (
!other.has(key) ||
!equals$1(value, other.get(key))
)
return false;
return true;
},
[symbol$1]() {
return number$1(
this.mapUnsafe.size,
);
},
};
/** @internal */
const hasSameCache = (self, that) =>
self.cacheRoot === that.cacheRoot;
/**
* Checks whether the provided argument is a `Context`.
*
* **When to use**
*
* Use to narrow an unknown value before passing it to APIs that require a
* `Context`.
*
* **Details**
*
* This checks the runtime `Context` marker and does not inspect which services
* the context contains.
*
* **Gotchas**
*
* This guard only proves that the value is a `Context`; it does not prove that
* any specific service is present.
*
* **Example** (Checking for contexts)
*
* ```ts import.meta.vitest
* import { Context } from "effect"
* Context.isContext(Context.empty()) // => true
* ```
*
* @see {@link isKey} for checking service keys
* @see {@link isReference} for checking references with defaults
*
* @stability stable
* @category guards
* @since 2.0.0
*/
const isContext = (u) =>
hasProperty(u, TypeId$12);
/**
* Checks whether the provided argument is a `Reference`.
*
* **Example** (Checking for references)
*
* ```ts import.meta.vitest
* import { Context } from "effect"
*
* const LoggerRef = Context.Reference("Logger", {
* defaultValue: () => ({ log: (_msg: string) => {} })
* })
*
* Context.isReference(LoggerRef) // => true
* Context.isReference(Context.Service("Key")) // => false
* ```
*
* @stability stable
* @category guards
* @since 3.11.0
*/
const isReference = (u) =>
!!u[ReferenceTypeId];
/**
* Returns an empty `Context`.
*
* **Example** (Creating an empty context)
*
* ```ts import.meta.vitest
* import { Context } from "effect"
* Context.empty().mapUnsafe.size // => 0
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const empty = () => emptyContext;
const emptyContext =
/*#__PURE__*/ makeUnsafe$2(
/*#__PURE__*/ new Map(),
);
/**
* Creates a new `Context` with a single service associated to the key.
*
* **Example** (Creating a context with one service)
*
* ```ts import.meta.vitest
* import { Context } from "effect"
*
* const Port = Context.Service<{ PORT: number }>("Port")
*
* const context = Context.make(Port, { PORT: 8080 })
*
* Context.get(context, Port).PORT // => 8080
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const make$8 = (key, service) =>
makeUnsafe$2(
/* @__PURE__ */ new Map([
[key.key, service],
]),
);
/**
* Adds a service to a given `Context`.
*
* **When to use**
*
* Use when you need to store a known service value in a `Context`.
*
* **Details**
*
* If the context already contains the same service key, the new service
* replaces the previous one.
*
* **Example** (Adding a service to a context)
*
* ```ts import.meta.vitest
* import { Context, pipe } from "effect"
*
* const Port = Context.Service<{ PORT: number }>("Port")
* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout")
*
* const someContext = Context.make(Port, { PORT: 8080 })
*
* const context = pipe(
* someContext,
* Context.add(Timeout, { TIMEOUT: 5000 })
* )
*
* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT]
* values // => [8080, 5000]
* ```
*
* @see {@link addOrOmit} for adding or removing a service from an `Option`
*
* @stability stable
* @category combining
* @since 2.0.0
*/
const add = /*#__PURE__*/ dual(
3,
(self, key, service) =>
addUnsafe(self, key.key, service),
);
/**
* Adds a service by key to a given `Context` using a string key.
*
* @stability stable
* @category combining
* @since 4.0.0
*/
const addUnsafe = (
self,
key,
service,
) => {
const impl = self;
const cacheRoot = cacheKeys.has(key)
? void 0
: impl.cacheRoot;
if (impl.depth >= MaxDepth) {
const map = new Map(
impl._flat ?? impl.base,
);
if (!impl._flat)
applyOverlays(map, impl.overlay);
map.set(key, service);
return makeImpl(
cacheRoot,
map,
void 0,
0,
);
}
return makeImpl(
cacheRoot,
impl.base,
{
key,
value: service,
parent: impl.overlay,
},
impl.depth + 1,
);
};
/** @internal */
const getOrUndefinedUnsafe = (
self,
key,
) => {
const value = lookup(self, key);
return value === notFound
? void 0
: value;
};
/**
* Gets a service from the context that corresponds to the given key.
*
* **When to use**
*
* Use when you need type-checked access to a service already included in the
* context type.
*
* **Example** (Getting a service from a context)
*
* ```ts import.meta.vitest
* import { Context, pipe } from "effect"
*
* const Port = Context.Service<{ PORT: number }>("Port")
* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout")
*
* const context = pipe(
* Context.make(Port, { PORT: 8080 }),
* Context.add(Timeout, { TIMEOUT: 5000 })
* )
*
* Context.get(context, Timeout).TIMEOUT // => 5000
* ```
*
* @see {@link getOption} for optional service access
* @see {@link getOrElse} for fallback values
*
* @stability stable
* @category getters
* @since 2.0.0
*/
const get = /* @__PURE__ */ dual(
2,
(self, service) => {
const value = lookup(
self,
service.key,
);
if (value === notFound) {
if (isReference(service))
return getDefaultValue(service);
throw serviceNotFoundError(
service,
);
}
return value;
},
);
const defaultValueCacheKey =
"~effect/Context/defaultValue";
const getDefaultValue = (ref) => {
if (defaultValueCacheKey in ref)
return ref[defaultValueCacheKey];
return (ref[defaultValueCacheKey] =
ref.defaultValue());
};
const serviceNotFoundError = (
service,
) => {
const error =
/* @__PURE__ */ new Error(
`Service not found${service.key ? `: ${String(service.key)}` : ""}`,
);
if (error.stack) {
const lines =
error.stack.split("\n");
lines.splice(1, 3);
error.stack = lines.join("\n");
}
return error;
};
/**
* Creates a context key with a default value.
*
* **When to use**
*
* Use when you need to define a context key with a lazily computed default
* value.
*
* **Details**
*
* `Context.Reference` allows you to create a key that can hold a value. You
* can provide a default value for the service, which will automatically be used
* when the context is accessed, or override it with a custom implementation
* when needed. The default value is computed lazily and cached on the
* reference.
*
* **Example** (Creating references with default values)
*
* ```ts import.meta.vitest
* import { Context } from "effect"
*
* // Create a reference with a default value
* const messages: Array<string> = []
* const LoggerRef = Context.Reference("Logger", {
* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) })
* })
*
* // The reference provides the default value when accessed from an empty context
* const context = Context.empty()
* const logger = Context.get(context, LoggerRef)
*
* // You can also override the default value
* const customContext = Context.make(LoggerRef, {
* log: (msg: string) => messages.push(`Custom: ${msg}`)
* })
* const customLogger = Context.get(customContext, LoggerRef)
* logger.log("default")
* customLogger.log("message")
* messages // => ["Default: default", "Custom: message"]
* ```
*
* @see {@link Service} for required services without default values
*
* @stability stable
* @category services
* @since 3.11.0
*/
const Reference = Service;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Duration.js
const TypeId$11 = "~effect/Duration";
const bigint0 = /*#__PURE__*/ BigInt(0);
const bigint1 = /*#__PURE__*/ BigInt(1);
const bigint2 = /*#__PURE__*/ BigInt(2);
const bigint10 =
/*#__PURE__*/ BigInt(10);
const bigint1e3 =
/*#__PURE__*/ BigInt(1e3);
const bigint1e6 =
/*#__PURE__*/ BigInt(1e6);
const roundTiesAwayFromZero = (input) =>
BigInt(
Math.sign(input) *
Math.round(Math.abs(input)),
);
const roundMillisToNanos = (millis) =>
Number.isInteger(millis)
? BigInt(millis) * bigint1e6
: roundTiesAwayFromZero(
millis * 1e6,
);
const fromNanosNumber = (nanos) =>
make$7(
Number.isFinite(nanos)
? roundTiesAwayFromZero(nanos)
: nanos,
);
const parseNanos = (input, scale) => {
const decimalIndex =
input.indexOf(".");
if (decimalIndex === -1)
return BigInt(input) * scale;
const isNegative = input[0] === "-";
const fractional = input.slice(
decimalIndex + 1,
);
const fractionalScale =
bigint10 **
BigInt(fractional.length);
const scaled =
(BigInt(
input.slice(
isNegative ? 1 : 0,
decimalIndex,
),
) *
fractionalScale +
BigInt(fractional)) *
scale;
return divideTiesAwayFromZero(
isNegative ? -scaled : scaled,
fractionalScale,
);
};
const divideTiesAwayFromZero = (
numerator,
denominator,
) => {
const absolute =
numerator < bigint0
? -numerator
: numerator;
const rounded =
absolute / denominator +
((absolute % denominator) *
bigint2 >=
denominator
? bigint1
: bigint0);
return numerator < bigint0
? -rounded
: rounded;
};
const DURATION_REGEXP =
/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/;
/**
* Decodes a `Duration.Input` into a `Duration`.
*
* **When to use**
*
* Use when the input has already been validated or comes from a trusted source
* and throwing is acceptable for invalid duration syntax.
*
* **Gotchas**
*
* If the input is not a valid `Duration.Input`, it throws an error.
*
* **Example** (Decoding duration inputs)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.fromInputUnsafe(1000) // => Duration.millis(1000)
* Duration.fromInputUnsafe("5 seconds") // => Duration.seconds(5)
* Duration.fromInputUnsafe("Infinity") // => Duration.infinity
* Duration.fromInputUnsafe([2, 500_000_000]) // => Duration.nanos(2_500_000_000n)
* ```
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const fromInputUnsafe = (input) => {
switch (typeof input) {
case "number":
return millis(input);
case "bigint":
return nanos(input);
case "string": {
if (input === "Infinity")
return infinity;
if (input === "-Infinity")
return negativeInfinity;
const match =
DURATION_REGEXP.exec(input);
if (!match) break;
const [_, valueStr, unit] = match;
if (
unit === "nano" ||
unit === "nanos"
)
return nanos(
parseNanos(valueStr, bigint1),
);
if (
unit === "micro" ||
unit === "micros"
)
return nanos(
parseNanos(
valueStr,
bigint1e3,
),
);
const value = Number(valueStr);
switch (unit) {
case "milli":
case "millis":
return millis(value);
case "second":
case "seconds":
return seconds(value);
case "minute":
case "minutes":
return minutes(value);
case "hour":
case "hours":
return hours(value);
case "day":
case "days":
return days(value);
case "week":
case "weeks":
return weeks(value);
}
break;
}
case "object": {
if (input === null) break;
if (TypeId$11 in input)
return input;
if (Array.isArray(input)) {
if (
input.length !== 2 ||
!input.every(isNumber)
)
return invalid$1(input);
if (
Number.isNaN(input[0]) ||
Number.isNaN(input[1])
)
return zero;
if (
input[0] === -Infinity ||
input[1] === -Infinity
)
return negativeInfinity;
if (
input[0] === Infinity ||
input[1] === Infinity
)
return infinity;
return fromNanosNumber(
input[0] * 1e9 + input[1],
);
}
const obj = input;
let millis = 0;
if (obj.weeks)
millis += obj.weeks * 6048e5;
if (obj.days)
millis += obj.days * 864e5;
if (obj.hours)
millis += obj.hours * 36e5;
if (obj.minutes)
millis += obj.minutes * 6e4;
if (obj.seconds)
millis += obj.seconds * 1e3;
if (obj.milliseconds)
millis += obj.milliseconds;
if (
!obj.microseconds &&
!obj.nanoseconds
)
return make$7(millis);
return fromNanosNumber(
millis * 1e6 +
(obj.microseconds ?? 0) *
1e3 +
(obj.nanoseconds ?? 0),
);
}
}
return invalid$1(input);
};
const invalid$1 = (input) => {
throw new Error(
`Invalid Input: ${input}`,
);
};
const zeroDurationValue = {
_tag: "Millis",
millis: 0,
};
const infinityDurationValue = {
_tag: "Infinity",
};
const negativeInfinityDurationValue = {
_tag: "NegativeInfinity",
};
const DurationProto = {
[TypeId$11]: TypeId$11,
[symbol$1]() {
switch (this.value._tag) {
case "Millis":
return hash(
roundMillisToNanos(
this.value.millis,
),
);
case "Nanos":
return hash(this.value.nanos);
default:
return structure(this.value);
}
},
[symbol](that) {
return (
isDuration(that) &&
equals(this, that)
);
},
toString() {
switch (this.value._tag) {
case "Infinity":
return "Infinity";
case "NegativeInfinity":
return "-Infinity";
case "Nanos":
return `${this.value.nanos} nanos`;
case "Millis":
return `${this.value.millis} millis`;
}
},
toJSON() {
switch (this.value._tag) {
case "Millis":
return {
_id: "Duration",
_tag: "Millis",
millis: this.value.millis,
};
case "Nanos":
return {
_id: "Duration",
_tag: "Nanos",
nanos: String(
this.value.nanos,
),
};
case "Infinity":
return {
_id: "Duration",
_tag: "Infinity",
};
case "NegativeInfinity":
return {
_id: "Duration",
_tag: "NegativeInfinity",
};
}
},
[NodeInspectSymbol]() {
return this.toJSON();
},
pipe() {
return pipeArguments(
this,
arguments,
);
},
};
const make$7 = (input) => {
const duration = Object.create(
DurationProto,
);
if (typeof input === "number") {
if (
isNaN(input) ||
input === 0 ||
Object.is(input, -0)
)
duration.value =
zeroDurationValue;
else if (!Number.isFinite(input))
duration.value =
input > 0
? infinityDurationValue
: negativeInfinityDurationValue;
else if (!Number.isInteger(input))
duration.value = {
_tag: "Nanos",
nanos:
roundMillisToNanos(input),
};
else
duration.value = {
_tag: "Millis",
millis: input,
};
} else if (input === bigint0)
duration.value = zeroDurationValue;
else
duration.value = {
_tag: "Nanos",
nanos: input,
};
return duration;
};
/**
* Checks whether a value is a Duration.
*
* **Example** (Checking for durations)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.isDuration(Duration.seconds(1)) // => true
* Duration.isDuration(1000) // => false
* ```
*
* @stability stable
* @category guards
* @since 2.0.0
*/
const isDuration = (u) =>
hasProperty(u, TypeId$11);
/**
* A Duration representing zero time.
*
* **Example** (Referencing the zero duration)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.zero) // => 0
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const zero = /*#__PURE__*/ make$7(0);
/**
* A Duration representing infinite time.
*
* **Example** (Referencing infinite duration)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.infinity) // => Infinity
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const infinity =
/*#__PURE__*/ make$7(Infinity);
/**
* A Duration representing negative infinite time.
*
* **Example** (Referencing negative infinite duration)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.negativeInfinity) // => -Infinity
* ```
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const negativeInfinity =
/*#__PURE__*/ make$7(-Infinity);
/**
* Creates a Duration from nanoseconds.
*
* **Example** (Creating durations from nanoseconds)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.nanos(500_000_000n) // => Duration.nanos(500_000_000n)
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const nanos = (nanos) => make$7(nanos);
/**
* Creates a Duration from milliseconds.
*
* **Example** (Creating durations from milliseconds)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.millis(1000)) // => 1000
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const millis = (millis) =>
make$7(millis);
/**
* Creates a Duration from seconds.
*
* **Example** (Creating durations from seconds)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.seconds(30)) // => 30_000
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const seconds = (seconds) =>
make$7(seconds * 1e3);
/**
* Creates a Duration from minutes.
*
* **Example** (Creating durations from minutes)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.minutes(5)) // => 300_000
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const minutes = (minutes) =>
make$7(minutes * 6e4);
/**
* Creates a Duration from hours.
*
* **Example** (Creating durations from hours)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.hours(2)) // => 7_200_000
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const hours = (hours) =>
make$7(hours * 36e5);
/**
* Creates a Duration from days.
*
* **Example** (Creating durations from days)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.days(1)) // => 86_400_000
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const days = (days) =>
make$7(days * 864e5);
/**
* Creates a Duration from weeks.
*
* **Example** (Creating durations from weeks)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.weeks(1)) // => 604_800_000
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const weeks = (weeks) =>
make$7(weeks * 6048e5);
/**
* Gets the duration in nanoseconds as a bigint.
*
* **When to use**
*
* Use when the duration is known to be finite and you need the nanosecond value
* as a `bigint`.
*
* **Details**
*
* Millisecond-backed fractional durations are rounded to the nearest
* nanosecond, with ties away from zero.
*
* **Gotchas**
*
* If the duration is infinite, it throws an error.
*
* **Example** (Reading nanoseconds unsafely)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toNanosUnsafe(Duration.seconds(2)) // => 2_000_000_000n
*
* // Duration.toNanosUnsafe(Duration.infinity)
* // throws Error: "Cannot convert infinite duration to nanos"
* ```
*
* @stability stable
* @category getters
* @since 4.0.0
*/
const toNanosUnsafe = (input) => {
const self = fromInputUnsafe(input);
switch (self.value._tag) {
case "Infinity":
case "NegativeInfinity":
throw new Error(
"Cannot convert infinite duration to nanos",
);
case "Nanos":
return self.value.nanos;
case "Millis":
return roundMillisToNanos(
self.value.millis,
);
}
};
/**
* Pattern matches on two `Duration`s, providing handlers that receive both values.
*
* **Example** (Pattern matching on duration pairs)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.matchPair(Duration.seconds(3), Duration.seconds(2), {
* onMillis: (a, b) => a + b,
* onNanos: (a, b) => Number(a + b),
* onInfinity: () => Infinity
* }) // => 5000
* ```
*
* @stability stable
* @category pattern matching
* @since 4.0.0
*/
const matchPair = /*#__PURE__*/ dual(
3,
(self, that, options) => {
if (
self.value._tag === "Infinity" ||
self.value._tag ===
"NegativeInfinity" ||
that.value._tag === "Infinity" ||
that.value._tag ===
"NegativeInfinity"
)
return options.onInfinity(
self,
that,
);
if (self.value._tag === "Millis")
return that.value._tag ===
"Millis"
? options.onMillis(
self.value.millis,
that.value.millis,
)
: options.onNanos(
toNanosUnsafe(self),
that.value.nanos,
);
else
return options.onNanos(
self.value.nanos,
toNanosUnsafe(that),
);
},
);
/**
* Provides an `Equivalence` instance for comparing `Duration` values.
*
* **Example** (Comparing durations for equivalence)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.Equivalence(Duration.seconds(5), Duration.millis(5000)) // => true
* ```
*
* @stability stable
* @category instances
* @since 2.0.0
*/
const Equivalence$2 = (self, that) =>
matchPair(self, that, {
onMillis: (self, that) =>
self === that,
onNanos: (self, that) =>
self === that,
onInfinity: (self, that) =>
self.value._tag ===
that.value._tag,
});
/**
* Checks whether two Durations are equal.
*
* **Example** (Checking duration equality)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.equals(Duration.seconds(5), Duration.millis(5000)) // => true
* ```
*
* @stability stable
* @category predicates
* @since 2.0.0
*/
const equals = /*#__PURE__*/ dual(
2,
(self, that) =>
Equivalence$2(self, that),
);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Scheduler.js
/**
* Controls how runnable Effect fiber tasks are dispatched.
*
* A scheduler decides how tasks are queued, when queued tasks run, and when a
* fiber should pause so other work can continue. This module includes the
* scheduler service reference, the default `MixedScheduler`, dispatcher types
* for queued tasks, and references for tuning or disabling automatic scheduler
* yields.
*
* @stability stable
* @since 2.0.0
*/
/**
* Context reference for the scheduler used by the Effect runtime.
*
* **When to use**
*
* Use when you need to replace scheduling behavior globally in tests or runtime
* setup, such as forcing deterministic task dispatch.
*
* **Details**
*
* The default value creates a `MixedScheduler`. Provide this service to
* customize execution mode, task dispatching, or yield behavior.
*
* @stability stable
* @category services
* @since 2.0.0
*/
const Scheduler =
/*#__PURE__*/ Reference(
"effect/Scheduler",
{
fiberCached: true,
defaultValue: () =>
new MixedScheduler(),
},
);
const setMicrotask = (f) => {
let cancelled = false;
Promise.resolve().then(() => {
if (!cancelled) f();
});
return () => {
cancelled = true;
};
};
const setTimer =
"setImmediate" in globalThis
? (f) => {
const timer =
globalThis.setImmediate(f);
return () =>
globalThis.clearImmediate(
timer,
);
}
: (f) => {
const timer = setTimeout(f, 0);
return () =>
clearTimeout(timer);
};
const setImmediate = (f) => {
try {
return setTimer(f);
} catch {
return setMicrotask(f);
}
};
var PriorityBuckets = class {
buckets = [];
scheduleTask(task, priority) {
const buckets = this.buckets;
const len = buckets.length;
let bucket;
let index = 0;
for (; index < len; index++) {
if (buckets[index][0] > priority)
break;
bucket = buckets[index];
}
if (
bucket &&
bucket[0] === priority
)
bucket[1].push(task);
else if (index === len)
buckets.push([priority, [task]]);
else
buckets.splice(index, 0, [
priority,
[task],
]);
}
drain() {
const buckets = this.buckets;
this.buckets = [];
return buckets;
}
};
/**
* Provides a scheduler implementation that batches queued tasks and dispatches them by
* priority.
*
* **When to use**
*
* Use when you need the default runtime scheduler directly, including a
* scheduler that batches queued work by priority and preserves FIFO order within
* each priority.
*
* **Details**
*
* `MixedScheduler` supports synchronous and asynchronous execution modes, uses
* operation counts to decide when fibers should yield, and is the default
* scheduler implementation.
*
* **Gotchas**
*
* On Cloudflare Workers, request-owned scheduler timers can be discarded,
* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the
* whole application; see `HttpRouter.toWebHandler` for a recipe.
* Sync mode does not yield to the event loop: CPU-heavy work delays other
* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix
* request-owned timers (such as `Effect.sleep`) or request-bound async contexts.
*
* @stability stable
* @category models
* @since 2.0.0
*/
var MixedScheduler = class {
executionMode;
setImmediate;
constructor(
executionMode = "async",
setImmediateFn,
) {
this.executionMode = executionMode;
this.setImmediate =
setImmediateFn ??
(executionMode === "sync"
? setMicrotask
: setImmediate);
}
/**
* Returns whether the fiber has reached its operation budget and should yield.
*
* **When to use**
*
* Use to decide whether a fiber should yield after consuming its current
* operation budget.
*
* @since 2.0.0
*/
shouldYield(fiber) {
return (
fiber.currentOpCount >=
fiber.cache.maxOpsBeforeYield
);
}
/**
* Creates a dispatcher that schedules work through this scheduler.
*
* **When to use**
*
* Use when you need a standalone dispatcher from a scheduler instance, for
* example in tests that enqueue tasks and then flush them deterministically.
*
* @since 4.0.0
*/
makeDispatcher() {
return new MixedSchedulerDispatcher(
this.setImmediate,
);
}
};
var MixedSchedulerDispatcher = class {
tasks =
/*#__PURE__*/ new PriorityBuckets();
running = void 0;
setImmediate;
constructor(
setImmediateFn = setImmediate,
) {
this.setImmediate = setImmediateFn;
}
/**
* @since 2.0.0
*/
scheduleTask(task, priority) {
this.tasks.scheduleTask(
task,
priority,
);
if (this.running === void 0)
this.running = this.setImmediate(
this.afterScheduled,
);
}
/**
* @since 2.0.0
*/
afterScheduled = () => {
this.running = void 0;
this.runTasks();
};
/**
* @since 2.0.0
*/
runTasks() {
const buckets = this.tasks.drain();
for (
let i = 0;
i < buckets.length;
i++
) {
const toRun = buckets[i][1];
for (
let j = 0;
j < toRun.length;
j++
)
toRun[j]();
}
}
/**
* @since 2.0.0
*/
flush() {
while (
this.tasks.buckets.length > 0
) {
if (this.running !== void 0) {
this.running();
this.running = void 0;
}
this.runTasks();
}
}
};
/**
* Context reference that controls the maximum number of operations a fiber
* can perform before yielding control back to the scheduler.
*
* **When to use**
*
* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler
* operation budget that triggers a yield.
*
* **Details**
*
* The default value is `2048` operations, which balances performance and
* fairness by helping prevent long-running fibers from monopolizing the
* execution thread.
*
* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget
*
* @stability stable
* @category services
* @since 4.0.0
*/
const MaxOpsBeforeYield =
/*#__PURE__*/ Reference(
"effect/Scheduler/MaxOpsBeforeYield",
{
fiberCached: true,
defaultValue: () => 2048,
},
);
/**
* Context reference that controls whether the runtime should bypass scheduler
* yield checks. When set to `true`, the fiber run loop won't call
* `Scheduler.shouldYield`.
*
* **When to use**
*
* Use to bypass scheduler yield checks for controlled runtime workloads where
* cooperative yielding should be disabled.
*
* **Gotchas**
*
* Setting this reference to `true` can let long-running fibers monopolize the
* JavaScript thread.
*
* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks
* @see {@link Scheduler} for providing custom scheduler yield behavior
*
* @stability stable
* @category services
* @since 4.0.0
*/
const PreventSchedulerYield =
/*#__PURE__*/ Reference(
"effect/Scheduler/PreventSchedulerYield",
{
fiberCached: true,
defaultValue: () => false,
},
);
/**
* Creates a tagged error class with a `_tag` discriminator.
*
* **When to use**
*
* Use when you need domain errors with discriminated-union handling.
*
* **Details**
*
* Like {@link Error}, but instances also carry a `readonly _tag` property,
* enabling `Effect.catchTag` and `Effect.catchTags` for tag-based recovery.
* The `_tag` is excluded from the constructor argument. Yielding an instance
* inside `Effect.gen` fails the effect with this error.
*
* **Example** (Recovering by tag)
*
* ```ts import.meta.vitest
* import { Data, Effect } from "effect"
*
* class NotFound extends Data.TaggedError("NotFound")<{
* readonly resource: string
* }> {}
*
* class Forbidden extends Data.TaggedError("Forbidden")<{
* readonly reason: string
* }> {}
*
* const program = Effect.gen(function*() {
* return yield* new NotFound({ resource: "/users/42" })
* })
*
* const recovered = program.pipe(
* Effect.catchTag("NotFound", (e) =>
* Effect.succeed(`missing: ${e.resource}`))
* )
*
* await Effect.runPromise(recovered) // => "missing: /users/42"
* ```
*
* @see {@link Error} — without a `_tag`
* @see {@link TaggedClass} — tagged class that is not an error
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const TaggedError = TaggedError$1;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Tracer.js
/**
* Defines the string key for the parent-span context service.
*
* **When to use**
*
* Use when you need the raw context key for parent span lookup in lower-level
* tracing code.
*
* **Example** (Reading the parent span key)
*
* ```ts import.meta.vitest
* import { Tracer } from "effect"
*
* // The key used to identify parent spans in the context
* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan"
* ```
*
* @stability stable
* @category constants
* @since 4.0.0
*/
const ParentSpanKey =
"effect/Tracer/ParentSpan";
/**
* Defines the string key for the active tracer context reference.
*
* **When to use**
*
* Use when you need the raw context key for active tracer lookup in lower-level
* tracing code.
*
* @stability stable
* @category constants
* @since 4.0.0
*/
const TracerKey = "effect/Tracer";
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/metric.js
/** @internal */
const FiberRuntimeMetricsKey =
"effect/Metric/FiberRuntimeMetrics";
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/references.js
/** @internal */
const CurrentStackFrame =
/*#__PURE__*/ Reference(
"effect/References/CurrentStackFrame",
{
fiberCached: true,
defaultValue: constUndefined,
},
);
/** @internal */
const TracerEnabled =
/*#__PURE__*/ Reference(
"effect/References/TracerEnabled",
{
fiberCached: true,
defaultValue: constTrue,
},
);
/** @internal */
const CurrentLogLevel =
/*#__PURE__*/ Reference(
"effect/References/CurrentLogLevel",
{
fiberCached: true,
defaultValue: () => "Info",
},
);
/** @internal */
const MinimumLogLevel =
/*#__PURE__*/ Reference(
"effect/References/MinimumLogLevel",
{
fiberCached: true,
defaultValue: () => "Info",
},
);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/effect.js
/** @internal */
var Interrupt = class extends ReasonBase {
constructor(
fiberId,
annotations = constEmptyAnnotations,
) {
super(
"Interrupt",
annotations,
"Interrupted",
);
this.fiberId = fiberId;
}
toString() {
return `Interrupt(${this.fiberId})`;
}
toJSON() {
return {
_tag: "Interrupt",
fiberId: this.fiberId,
};
}
[symbol](that) {
return (
isInterruptReason(that) &&
this.fiberId === that.fiberId &&
this.annotations ===
that.annotations
);
}
[symbol$1]() {
return string$1(
`${this._tag}:${this.fiberId}`,
);
}
};
/** @internal */
const causeInterrupt = (fiberId) =>
new CauseImpl([
new Interrupt(fiberId),
]);
/** @internal */
const hasInterrupts = (self) =>
self.reasons.some(isInterruptReason);
/** @internal */
const causeMap = /*#__PURE__*/ dual(
2,
(self, f) => {
let hasFail = false;
const failures = self.reasons.map(
(failure) => {
if (isFailReason$1(failure)) {
hasFail = true;
return new Fail(
f(failure.error),
failure.annotations,
);
}
return failure;
},
);
return hasFail
? causeFromReasons(failures)
: self;
},
);
/** @internal */
const FiberTypeId = "~effect/Fiber";
const fiberVariance = {
_A: identity,
_E: identity,
};
const fiberIdStore = { id: 0 };
const AsyncResource =
/*#__PURE__*/ (() => {
try {
return globalThis.process?.getBuiltinModule?.(
"node:async_hooks",
)?.AsyncResource;
} catch {
return;
}
})();
const captureAsyncContext = () =>
AsyncResource === void 0
? void 0
: new AsyncResource("effect/Fiber");
/** @internal */
const getCurrentFiber = () =>
globalThis[currentFiberTypeId];
/** @internal */
var FiberImpl = class {
constructor(
context,
interruptible = true,
) {
this.setContext(context);
this.id = ++fiberIdStore.id;
this.currentOpCount = 0;
this.interruptible = interruptible;
this._stack = [];
this._observers = void 0;
this._exit = void 0;
this._children = void 0;
this._interruptedCause = void 0;
this._yielded = void 0;
this._running = false;
this._deferredInterrupt = false;
this._parent = void 0;
this._asyncContext = void 0;
this.cache.runtimeMetrics?.recordFiberStart(
this.context,
);
}
get [FiberTypeId]() {
return fiberVariance;
}
get currentDispatcher() {
return (this._dispatcher ??=
this.cache.scheduler.makeDispatcher());
}
getRef(ref) {
return get(this.context, ref);
}
addObserver(cb) {
if (this._exit) {
cb(this._exit);
return constVoid;
}
if (this._observers === void 0)
this._observers = [cb];
else this._observers.push(cb);
return () =>
this.removeObserver(cb);
}
removeObserver(cb) {
if (
this._exit ||
this._observers === void 0
)
return;
const index =
this._observers.indexOf(cb);
if (index >= 0)
this._observers.splice(index, 1);
}
interruptUnsafe(
fiberId,
annotations,
) {
if (this._exit) return;
let cause = causeInterrupt(fiberId);
if (this.cache.stackFrame)
cause = causeAnnotate(
cause,
make$8(
StackTraceKey,
this.cache.stackFrame,
),
);
if (annotations)
cause = causeAnnotate(
cause,
annotations,
);
this._interruptedCause = this
._interruptedCause
? causeAddInterrupts(
this._interruptedCause,
cause,
)
: cause;
if (this.interruptible) {
if (this._running)
this._deferredInterrupt = true;
else
this.evaluate(
failCause$1(
this._interruptedCause,
),
);
}
}
pollUnsafe() {
return this._exit;
}
evaluate(effect) {
if (this._exit) return;
else if (
this._asyncContext !== void 0
) {
const asyncContext =
this._asyncContext;
this._asyncContext = void 0;
return asyncContext.runInAsyncScope(
this.evaluate,
this,
effect,
);
} else if (
this._yielded !== void 0
) {
const yielded = this._yielded;
this._yielded = void 0;
yielded();
}
const exit = this.runLoop(effect);
if (exit === Yield) {
this._asyncContext =
captureAsyncContext();
return;
}
const interruptChildren =
fiberMiddleware.interruptChildren &&
fiberMiddleware.interruptChildren(
this,
);
if (interruptChildren !== void 0)
return this.evaluate(
flatMap$1(
interruptChildren,
() => exit,
),
);
this._exit = exit;
this.cache.runtimeMetrics?.recordFiberEnd(
this.context,
this._exit,
);
if (this._parent) {
this._parent._children?.delete(
this,
);
this._parent = void 0;
}
if (this._observers !== void 0) {
const observers = this._observers;
this._observers = void 0;
for (
let i = 0;
i < observers.length;
i++
)
observers[i](exit);
}
this._stack.length = 0;
this._children = void 0;
this.context = empty();
}
runLoop(effect) {
const prevFiber =
globalThis[currentFiberTypeId];
globalThis[currentFiberTypeId] =
this;
const prevRunning = this._running;
this._running = true;
let yielding = false;
let current = effect;
this.currentOpCount = 0;
try {
while (true)
try {
if (this._deferredInterrupt) {
this._deferredInterrupt = false;
current = failCause$1(
this._interruptedCause,
);
}
this.currentOpCount++;
const cache = this.cache;
if (
!yielding &&
!cache.preventYield &&
cache.scheduler.shouldYield(
this,
)
) {
yielding = true;
const prev = current;
current = flatMap$1(
yieldNow,
() => prev,
);
}
current = cache.tracerContext
? cache.tracerContext(
current,
this,
)
: current[evaluate](this);
if (current === Yield) {
const yielded =
this._yielded;
if (
"~effect/Exit" in yielded
) {
this._deferredInterrupt = false;
this._yielded = void 0;
return yielded;
} else if (
this._deferredInterrupt
) {
this._yielded = void 0;
yielded();
continue;
}
return Yield;
}
} catch (error) {
if (
!hasProperty(
current,
"~effect/Effect/evaluate",
)
)
return exitDie(
`Fiber.runLoop: Not a valid effect: ${String(current)}`,
);
current = exitDie(error);
}
} finally {
this._running = prevRunning;
globalThis[currentFiberTypeId] =
prevFiber;
}
}
getCont(symbol) {
if (this._deferredInterrupt) {
this._deferredInterrupt = false;
return deferredInterruptCont;
}
while (true) {
const op = this._stack.pop();
if (!op) return void 0;
const all = op[contAll];
if (all !== void 0) {
const cont = all.call(op, this);
if (cont) {
cont[symbol] = cont;
return cont;
}
}
if (op[symbol]) return op;
}
}
succeedWith(value) {
if (
(++this.currentOpCount &
(maxInlineSteps - 1)) ===
0
)
return exitSucceed(value);
const cont = this.getCont(contA);
return cont
? cont[contA](value, this)
: this.yieldWith(
exitSucceed(value),
);
}
yieldWith(value) {
this._yielded = value;
return Yield;
}
children() {
return (this._children ??=
/* @__PURE__ */ new Set());
}
pipe() {
return pipeArguments(
this,
arguments,
);
}
setContext(context) {
const previous = this.context;
this.context = context;
if (
previous !== void 0 &&
hasSameCache(previous, context)
)
return;
const root = context.cacheRoot;
const cache = (root._fiberCache ??=
makeFiberContextCache(context));
if (
this.cache?.scheduler !==
cache.scheduler
)
this._dispatcher = void 0;
this.cache = cache;
}
get currentSpanLocal() {
const span = this.cache.span;
return span?._tag === "Span"
? span
: void 0;
}
};
const makeFiberContextCache = (
context,
) => {
const currentTracer =
getOrUndefinedUnsafe(
context,
TracerKey,
);
return {
scheduler: get(context, Scheduler),
tracer: currentTracer,
tracerContext: currentTracer
? currentTracer["context"]
: void 0,
tracerEnabled: get(
context,
TracerEnabled,
),
span: getOrUndefinedUnsafe(
context,
ParentSpanKey,
),
logLevel: get(
context,
CurrentLogLevel,
),
minimumLogLevel: get(
context,
MinimumLogLevel,
),
stackFrame: get(
context,
CurrentStackFrame,
),
runtimeMetrics:
getOrUndefinedUnsafe(
context,
FiberRuntimeMetricsKey,
),
maxOpsBeforeYield: get(
context,
MaxOpsBeforeYield,
),
preventYield: get(
context,
PreventSchedulerYield,
),
};
};
const deferredInterruptCont = {
[contA](_value, fiber) {
return failCause$1(
fiber._interruptedCause,
);
},
[contE](_cause, fiber) {
return failCause$1(
fiber._interruptedCause,
);
},
};
const maxInlineSteps = 32;
const fiberMiddleware = {
interruptChildren: void 0,
};
const fiberStackAnnotations = (
fiber,
) => {
if (!fiber.cache.stackFrame)
return void 0;
const annotations =
/* @__PURE__ */ new Map();
annotations.set(
InterruptorStackTrace.key,
fiber.cache.stackFrame,
);
return makeUnsafe$2(annotations);
};
/** @internal */
const fiberAwaitAll = (self) =>
callback((resume) => {
const iter =
self[Symbol.iterator]();
const exits = [];
let cancel = void 0;
function loop() {
let result = iter.next();
while (!result.done) {
if (result.value._exit) {
exits.push(
result.value._exit,
);
result = iter.next();
continue;
}
cancel =
result.value.addObserver(
(exit) => {
exits.push(exit);
loop();
},
);
return;
}
resume(succeed$3(exits));
}
loop();
return sync(() => cancel?.());
});
/** @internal */
const fiberInterruptAll = (fibers) =>
withFiber((parent) => {
const annotations =
fiberStackAnnotations(parent);
let fiberArr = empty$1();
for (const fiber of fibers) {
fiber.interruptUnsafe(
parent.id,
annotations,
);
fiberArr.push(fiber);
}
return asVoid(
fiberAwaitAll(fiberArr),
);
});
/** @internal */
const succeed$3 = exitSucceed;
/** @internal */
const failCause$1 = exitFailCause;
/** @internal */
const fail$3 = exitFail;
/** @internal */
const sync =
/*#__PURE__*/ makePrimitive({
op: "Sync",
[evaluate](fiber) {
const value = this[args]();
const cont = fiber.getCont(contA);
return cont
? cont[contA](value, fiber)
: fiber.yieldWith(
exitSucceed(value),
);
},
});
/** @internal */
const suspend$1 =
/*#__PURE__*/ makePrimitive({
op: "Suspend",
[evaluate](_fiber) {
return this[args]();
},
});
/** @internal */
const yieldNow =
/*#__PURE__*/ /* @__PURE__ */ makePrimitive(
{
op: "Yield",
[evaluate](fiber) {
let resumed = false;
fiber.currentDispatcher.scheduleTask(
() => {
if (resumed) return;
fiber.evaluate(exitVoid);
},
this["~effect/Effect/args"] ??
0,
);
return fiber.yieldWith(() => {
resumed = true;
});
},
},
)(0);
/** @internal */
const failCauseSync$1 = (evaluate) =>
suspend$1(() =>
failCause$1(evaluate()),
);
/** @internal */
const die$2 = (defect) =>
exitDie(defect);
/** @internal */
const void_$1 =
/*#__PURE__*/ succeed$3(void 0);
const callbackOptions =
/*#__PURE__*/ (function () {
const Proto =
/*#__PURE__*/ makePrimitiveProto({
op: "Async",
[evaluate](fiber) {
let resumed = false;
let yielded = false;
const controller = this
.withSignal
? new AbortController()
: void 0;
const onCancel =
this.register.call(
fiber.cache.scheduler,
(effect) => {
if (resumed) return;
resumed = true;
if (yielded)
fiber.evaluate(
effect,
);
else yielded = effect;
},
controller?.signal,
);
if (yielded !== false)
return yielded;
yielded = true;
fiber._yielded = () => {
resumed = true;
};
if (
controller === void 0 &&
onCancel === void 0
)
return Yield;
fiber._stack.push(
asyncFinalizer(() => {
resumed = true;
controller?.abort();
return (
onCancel ?? exitVoid
);
}),
);
return Yield;
},
});
const AsyncImpl = function (
register,
withSignal,
) {
this.register = register;
this.withSignal = withSignal;
};
AsyncImpl.prototype = Proto;
return function (
register,
withSignal,
) {
return new AsyncImpl(
register,
withSignal,
);
};
})();
const asyncFinalizer =
/*#__PURE__*/ makePrimitive({
op: "AsyncFinalizer",
[contAll](fiber) {
if (fiber.interruptible) {
fiber.interruptible = false;
fiber._stack.push(
setInterruptibleTrue,
);
}
},
[contE](cause, _fiber) {
return hasInterrupts(cause)
? flatMap$1(
combineFinalizerCause(
exitFailCause(cause),
this[args](),
),
() => failCause$1(cause),
)
: failCause$1(cause);
},
});
/** @internal */
const callback = (register) =>
callbackOptions(
register,
register.length >= 2,
);
const defineFunctionLength = (
length,
fn,
) =>
Object.defineProperty(fn, "length", {
value: length,
configurable: true,
});
/** @internal */
const fnUntracedEager$1 = (
body,
...pipeables
) =>
defineFunctionLength(
body.length,
pipeables.length === 0
? function () {
return fromIteratorEagerUnsafe(
() =>
body.apply(
this,
arguments,
),
);
}
: function () {
let effect =
fromIteratorEagerUnsafe(
() =>
body.apply(
this,
arguments,
),
);
for (const pipeable of pipeables)
effect = pipeable(
effect,
...arguments,
);
return effect;
},
);
const fromIteratorEagerUnsafe = (
evaluate,
) => {
try {
const iterator = evaluate();
let value = void 0;
while (true) {
const state =
iterator.next(value);
if (state.done)
return succeed$3(state.value);
const primitive = state.value;
if (
primitive &&
primitive._tag === "Success"
) {
value = primitive.value;
continue;
} else if (
primitive &&
primitive._tag === "Failure"
)
return state.value;
else {
let isFirstExecution = true;
return suspend$1(() => {
if (isFirstExecution) {
isFirstExecution = false;
return flatMap$1(
state.value,
(value) =>
fromIteratorUnsafe(
iterator,
value,
),
);
} else
return suspend$1(() =>
fromIteratorUnsafe(
evaluate(),
),
);
});
}
}
} catch (error) {
return die$2(error);
}
};
const fromIteratorUnsafe =
/*#__PURE__*/ (function () {
const Proto =
/*#__PURE__*/ makePrimitiveProto({
op: "Iterator",
[contA](value, fiber) {
const iter = this.iterator;
while (true) {
const state =
iter.next(value);
if (state.done)
return succeed$3(
state.value,
);
if (
!effectIsExit(state.value)
) {
fiber._stack.push(this);
return state.value;
} else if (
state.value._tag ===
"Failure"
)
return state.value;
value = state.value.value;
}
},
[evaluate](fiber) {
return this[contA](
this.initial,
fiber,
);
},
});
const IteratorImpl = function (
iterator,
initial,
) {
this.iterator = iterator;
this.initial = initial;
};
IteratorImpl.prototype = Proto;
return function (
iterator,
initial,
) {
return new IteratorImpl(
iterator,
initial,
);
};
})();
const evaluateCont = function (fiber) {
fiber._stack.push(this);
return this[args];
};
const OnSuccessProto =
/*#__PURE__*/ makePrimitiveProto({
op: "OnSuccess",
[evaluate]: evaluateCont,
});
const ContImpl = function (
self,
cont,
payload,
) {
this[args] = self;
this[contA] = cont;
this.payload = payload;
};
ContImpl.prototype = OnSuccessProto;
const returnPayload = function () {
return this.payload;
};
const continuationMarksStack =
/*#__PURE__*/ (() => {
const limit =
/*#__PURE__*/ getStackTraceLimit();
if (limit === 0) return false;
const marker =
"~effect/Effect/stackProbe";
const probe = {
[marker]: function stackProbe() {
return /* @__PURE__ */ new Error();
},
};
setStackTraceLimit(1);
const error =
/*#__PURE__*/ probe[marker]();
setStackTraceLimit(limit);
return (
error.stack?.includes(
"[as " + marker + "]",
) === true
);
})();
const mapCont = function (
value,
fiber,
) {
const f = this.payload;
return fiber.succeedWith(
continuationMarksStack
? f(value)
: internalCall(() => f(value)),
);
};
const andThenCont = function (value) {
const f = this.payload;
return f(value);
};
/** @internal */
const asVoid = (self) =>
new ContImpl(
self,
returnPayload,
exitVoid,
);
/** @internal */
const flatMap$1 = /*#__PURE__*/ dual(
2,
(self, f) =>
new ContImpl(self, andThenCont, f),
);
/** @internal */
const effectIsExit = (effect) =>
effect[ExitTypeId] !== void 0;
/** @internal */
const flatMapEager$1 =
/*#__PURE__*/ dual(2, (self, f) => {
if (effectIsExit(self))
return self._tag === "Success"
? f(self.value)
: self;
return flatMap$1(self, f);
});
/** @internal */
const map$1 = /*#__PURE__*/ dual(
2,
(self, f) =>
new ContImpl(self, mapCont, f),
);
/** @internal */
const mapEager$1 = /*#__PURE__*/ dual(
2,
(self, f) =>
effectIsExit(self)
? exitMap(self, f)
: map$1(self, f),
);
/** @internal */
const exitIsSuccess = (self) =>
self._tag === "Success";
/** @internal */
const exitVoid =
/*#__PURE__*/ exitSucceed(void 0);
/** @internal */
const exitMap = /*#__PURE__*/ dual(
2,
(self, f) =>
self._tag === "Success"
? exitSucceed(f(self.value))
: self,
);
/** @internal */
const catchCause$1 = /*#__PURE__*/ dual(
2,
(self, f) =>
new OnFailureImpl(
self,
f.length !== 1
? (cause) => f(cause)
: f,
),
);
const OnFailureProto =
/*#__PURE__*/ makePrimitiveProto({
op: "OnFailure",
[evaluate]: evaluateCont,
});
const OnFailureImpl = function (
self,
f,
) {
this[args] = self;
this[contE] = f;
};
OnFailureImpl.prototype =
OnFailureProto;
const OnSuccessAndFailureProto =
/*#__PURE__*/ makePrimitiveProto({
op: "OnSuccessAndFailure",
[evaluate]: evaluateCont,
});
const OnSuccessAndFailureImpl =
function (
self,
onSuccess,
onFailure,
) {
this[args] = self;
this[contA] = onSuccess;
this[contE] = onFailure;
};
OnSuccessAndFailureImpl.prototype =
OnSuccessAndFailureProto;
/** @internal */
const exit$1 = (self) =>
effectIsExit(self)
? exitSucceed(self)
: exitPrimitive(self);
const exitPrimitive =
/*#__PURE__*/ makePrimitive({
op: "Exit",
[evaluate](fiber) {
fiber._stack.push(this);
return this[args];
},
[contA](value, fiber, exit) {
return fiber.succeedWith(
exit ?? exitSucceed(value),
);
},
[contE](cause, fiber, exit) {
return fiber.succeedWith(
exit ?? exitFailCause(cause),
);
},
});
const combineFinalizerCause = (
exit_,
finalizer,
) =>
exitIsSuccess(exit_)
? finalizer
: catchCause$1(finalizer, (cause) =>
failCause$1(
causeCombine(
exit_.cause,
cause,
),
),
);
/** @internal */
const uninterruptible = (self) =>
withFiber((fiber) => {
if (!fiber.interruptible)
return self;
fiber.interruptible = false;
fiber._stack.push(
setInterruptibleTrue,
);
return self;
});
const setInterruptibleTrue =
/*#__PURE__*/ /* @__PURE__ */ makePrimitive(
{
op: "SetInterruptible",
[contAll](fiber) {
fiber.interruptible =
this[args];
if (
fiber._interruptedCause &&
fiber.interruptible
)
return () =>
failCause$1(
fiber._interruptedCause,
);
},
},
)(true);
/** @internal */
const resolveConcurrency = (
concurrency,
) =>
concurrency === "unbounded"
? Number.POSITIVE_INFINITY
: Math.max(1, concurrency ?? 1);
/** @internal */
const iterateEager =
() => (options) => {
const onItem = options.onItem;
const step = options.step;
const resumeSequential = (
state,
items,
index,
end,
effect,
) =>
flatMap$1(
exit$1(effect),
(itemExit) =>
step(
state,
items[index],
itemExit,
index,
) ??
runSequential(
state,
items,
index + 1,
end,
) ??
void_$1,
);
const runSequential = (
state,
items,
index = 0,
end = items.length,
) => {
for (; index < end; index++) {
const item = items[index];
const effect = onItem(
state,
item,
index,
);
if (!effectIsExit(effect))
return resumeSequential(
state,
items,
index,
end,
effect,
);
const terminal = step(
state,
item,
effect,
index,
);
if (terminal)
return terminal._tag ===
"Failure"
? terminal
: void 0;
}
};
return runSequential;
};
const iterateConcurrentImpl = (
options,
) => {
const onItem = options.onItem;
const step = options.step;
return (state, items, opts) => {
let index = 0;
const end =
opts.end ?? items.length;
const concurrency =
opts.concurrency;
let done = false;
let parentFiber;
let fibers;
let resume;
let terminal;
let effect;
const failDefect = (error) => {
const defect = exitDie(error);
terminal = defect;
done = true;
return fibers && fibers.size > 0
? flatMap$1(
uninterruptible(
fiberInterruptAll(
Array.from(fibers),
),
),
() => terminal ?? defect,
)
: defect;
};
const go = () => {
let paused = false;
for (
;
!terminal && index < end;
index++
) {
const item = items[index];
const eff =
effect ??
onItem(state, item, index);
if (effectIsExit(eff)) {
terminal = step(
state,
item,
eff,
index,
);
if (terminal) break;
} else if (!parentFiber)
return callback((cb) => {
parentFiber =
getCurrentFiber();
fibers =
/* @__PURE__ */ new Set();
effect = eff;
resume = cb;
let result;
try {
result = go();
} catch (error) {
return cb(
failDefect(error),
);
}
if (result)
return cb(result);
return suspend$1(() => {
terminal ??= exitVoid;
return flatMap$1(
fibers
? fiberInterruptAll(
fibers,
)
: void_$1,
() =>
terminal?._tag ===
"Failure"
? terminal
: void_$1,
);
});
});
else {
effect = void 0;
const fiber = forkUnsafe(
parentFiber,
eff,
true,
true,
"inherit",
);
if (fiber._exit) {
terminal = step(
state,
item,
fiber._exit,
index,
);
if (terminal) break;
continue;
}
fibers.add(fiber);
const currentIndex = index;
fiber.addObserver((exit) => {
fibers.delete(fiber);
try {
if (terminal) {
if (
exit._tag ===
"Failure"
) {
const reasons =
exit.cause.reasons.filter(
(reason) =>
reason._tag !==
"Interrupt",
);
if (
reasons.length > 0
) {
const cause =
causeFromReasons(
reasons,
);
terminal =
exitFailCause(
terminal._tag ===
"Failure"
? causeCombine(
terminal.cause,
cause,
)
: cause,
);
}
}
} else {
const result = step(
state,
item,
exit,
currentIndex,
);
if (result) {
terminal = result;
go();
}
}
if (paused) {
const eff = go();
if (eff) resume(eff);
} else if (
done &&
fibers.size === 0
)
resume(
terminal ?? void_$1,
);
} catch (error) {
resume(failDefect(error));
}
});
if (fibers.size < concurrency)
continue;
paused = true;
index++;
return;
}
}
done = true;
if (terminal) {
if (fibers && fibers.size > 0) {
const annotations =
fiberStackAnnotations(
parentFiber,
);
fibers.forEach((f) =>
f.interruptUnsafe(
parentFiber.id,
annotations,
),
);
return;
}
if (
resume ||
terminal._tag === "Failure"
)
return terminal;
} else if (resume) {
if (!fibers) return exitVoid;
else if (fibers.size === 0)
resume(void_$1);
}
};
return go();
};
};
/** @internal */
const iterateConcurrent =
() => (options) =>
iterateConcurrentImpl(options);
/** @internal */
const forkUnsafe = (
parent,
effect,
immediate = false,
daemon = false,
uninterruptible = false,
) => {
const parentRuntime = parent;
const interruptible =
uninterruptible === "inherit"
? parentRuntime.interruptible
: !uninterruptible;
const child = new FiberImpl(
parentRuntime.context,
interruptible,
);
if (!daemon) {
parentRuntime.children().add(child);
child._parent = parentRuntime;
}
if (immediate) child.evaluate(effect);
else {
child._asyncContext =
captureAsyncContext();
parentRuntime.currentDispatcher.scheduleTask(
() => child.evaluate(effect),
0,
);
}
return child;
};
/** @internal */
const runForkWith =
(context) => (effect, options) => {
const fiber = new FiberImpl(
options?.scheduler
? add(
context,
Scheduler,
options.scheduler,
)
: context,
options?.uninterruptible !== true,
);
fiber.evaluate(effect);
if (fiber._exit) return fiber;
if (options?.signal) {
if (options.signal.aborted)
fiber.interruptUnsafe();
else {
const abort = () =>
fiber.interruptUnsafe();
options.signal.addEventListener(
"abort",
abort,
{ once: true },
);
fiber.addObserver(() =>
options.signal.removeEventListener(
"abort",
abort,
),
);
}
}
if (options?.onFiberStart)
options.onFiberStart(fiber);
return fiber;
};
/** @internal */
const runSyncExitWith = (context) => {
const runFork = runForkWith(context);
return (effect) => {
if (effectIsExit(effect))
return effect;
const scheduler =
new MixedScheduler("sync");
const fiber = runFork(effect, {
scheduler,
});
fiber._dispatcher?.flush();
return (
fiber._exit ??
exitDie(
new AsyncFiberError(fiber),
)
);
};
};
/** @internal */
const runSyncExit$1 =
/*#__PURE__*/ runSyncExitWith(
/*#__PURE__*/ empty(),
);
/** @internal */
const AsyncFiberErrorTypeId =
"~effect/Cause/AsyncFiberError";
/** @internal */
var AsyncFiberError = class extends /*#__PURE__*/ TaggedError$1(
"AsyncFiberError",
) {
[AsyncFiberErrorTypeId] =
AsyncFiberErrorTypeId;
constructor(fiber) {
super({
message:
"An asynchronous Effect was executed with Effect.runSync",
fiber,
});
}
};
const colors = {
bold: "1",
red: "31",
green: "32",
yellow: "33",
blue: "34",
cyan: "36",
white: "37",
gray: "90",
black: "30",
bgBrightRed: "101",
};
(colors.gray,
colors.blue,
colors.green,
colors.yellow,
colors.red,
colors.bgBrightRed,
colors.black);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Cause.js
/**
* Narrows a `Reason` to `Fail`.
*
* **When to use**
*
* Use as a predicate for `Array.filter` to pick out typed `Fail` reasons when
* iterating over `cause.reasons`.
*
* **Example** (Filtering fail reasons)
*
* ```ts import.meta.vitest
* import { Cause } from "effect"
*
* const cause = Cause.fail("error")
* const fails = cause.reasons.filter(Cause.isFailReason)
* fails[0].error // => "error"
* ```
*
* @see {@link isDieReason} — narrow to `Die`
* @see {@link isInterruptReason} — narrow to `Interrupt`
*
* @stability stable
* @category guards
* @since 4.0.0
*/
const isFailReason = isFailReason$1;
/**
* Creates a `Cause` containing a single `Die` reason with the
* given defect.
*
* **When to use**
*
* Use to construct a cause from an untyped defect or unexpected thrown value.
*
* **Example** (Creating a die cause)
*
* ```ts import.meta.vitest
* import { Cause } from "effect"
*
* Cause.die("Unexpected") // => Cause.fromReasons([Cause.makeDieReason("Unexpected")])
* ```
*
* @see {@link fail} — for typed errors
* @see {@link interrupt} — for fiber interruptions
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const die$1 = causeDie;
/**
* Transforms the typed error values inside a `Cause` using the
* provided function. Only `Fail` reasons are affected; `Die` and `Interrupt`
* reasons pass through unchanged.
*
* **When to use**
*
* Use to transform expected typed failures while preserving defects and
* interruptions unchanged.
*
* **Details**
*
* If at least one `Fail` reason exists, this returns a new `Cause`
* containing the mapped failures. If the cause has no `Fail` reasons, the
* original cause is returned unchanged.
*
* **Example** (Mapping errors to uppercase)
*
* ```ts import.meta.vitest
* import { Cause } from "effect"
*
* const cause = Cause.fail("error")
* const mapped = Cause.map(cause, (e) => e.toUpperCase())
* const reason = mapped.reasons[0]
* if (Cause.isFailReason(reason)) {
* reason.error // => "ERROR"
* }
* ```
*
* @stability stable
* @category mapping
* @since 2.0.0
*/
const map = causeMap;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Exit.js
/**
* Creates a successful Exit containing the given value.
*
* **When to use**
*
* Use when you need an Exit that contains a known success value.
*
* **Details**
*
* Returns a `Success<A>` with the provided value. Does not perform any
* computation.
*
* **Example** (Creating a successful Exit)
*
* ```ts import.meta.vitest
* import { Exit } from "effect"
*
* Exit.succeed(42) // => Exit.succeed(42)
* ```
*
* @see {@link fail} to create a failed Exit
* @see {@link void_ void} for a pre-allocated success with no value
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const succeed$2 = exitSucceed;
/**
* Creates a failed Exit from a Cause.
*
* **When to use**
*
* Use when you already have a `Cause<E>` and want to wrap it in an Exit
* for advanced error handling where you need full control over the Cause
* structure.
*
* **Details**
*
* Returns a `Failure<never, E>`. If you only have an error value, use
* {@link fail} instead.
*
* **Example** (Creating a failed Exit from a Cause)
*
* ```ts import.meta.vitest
* import { Cause, Exit } from "effect"
*
* Exit.failCause(Cause.fail("Something went wrong")) // => Exit.fail("Something went wrong")
* ```
*
* @see {@link fail} to create a Failure from a plain error value
* @see {@link die} to create a Failure from a defect
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const failCause = exitFailCause;
/**
* Creates a failed Exit from a typed error value.
*
* **When to use**
*
* Use when you need to represent an expected typed failure as an `Exit`.
*
* **Details**
*
* The error is wrapped in a `Cause.Fail` internally.
*
* Returns a `Failure<never, E>`.
*
* **Example** (Creating a failed Exit)
*
* ```ts import.meta.vitest
* import { Exit } from "effect"
*
* Exit.fail("Something went wrong") // => Exit.fail("Something went wrong")
* ```
*
* @see {@link succeed} to create a successful Exit
* @see {@link die} to create a Failure from an unexpected defect
* @see {@link failCause} to create a Failure from a full Cause
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const fail$2 = exitFail;
const void_ = exitVoid;
/**
* Checks whether an Exit is a Success.
*
* **When to use**
*
* Use as a type guard to narrow `Exit<A, E>` to `Success<A, E>` and access the
* `value` property.
*
* **Example** (Narrowing to success)
*
* ```ts import.meta.vitest
* import { Exit } from "effect"
*
* const exit = Exit.succeed(42)
*
* if (Exit.isSuccess(exit)) {
* exit.value // => 42
* }
* ```
*
* @see {@link isFailure} for the opposite check
* @see {@link match} for exhaustive pattern matching
*
* @stability stable
* @category guards
* @since 2.0.0
*/
const isSuccess = exitIsSuccess;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/dateTime.js
/** @internal */
const TypeId$10 = "~effect/DateTime";
/** @internal */
const TimeZoneTypeId =
"~effect/DateTime/TimeZone";
const Proto$4 = {
[TypeId$10]: TypeId$10,
pipe() {
return pipeArguments(
this,
arguments,
);
},
[NodeInspectSymbol]() {
return this.toString();
},
toJSON() {
return toDateUtc$1(this).toJSON();
},
};
({ ...Proto$4 });
({ ...Proto$4 });
const ProtoTimeZone = {
[TimeZoneTypeId]: TimeZoneTypeId,
[NodeInspectSymbol]() {
return this.toString();
},
};
({ ...ProtoTimeZone });
({ ...ProtoTimeZone });
/** @internal */
const toDateUtc$1 = (self) =>
new Date(self.epochMilliseconds);
/**
* Creates an `Effect` that always succeeds with a given value.
*
* **When to use**
*
* Use when an effect should complete successfully with a specific value without any errors
* or external dependencies.
*
* **Example** (Creating a successful effect)
*
* ```ts import.meta.vitest
* import { Effect } from "effect"
*
* // Creating an effect that represents a successful scenario
* //
* // ┌─── Effect<number, never, never>
* // â–¼
* const success = Effect.succeed(42)
* Effect.runSync(success) // => 42
* ```
*
* @see {@link fail} to create an effect that represents a failure.
* @stability stable
* @category constructors
* @since 2.0.0
*/
const succeed$1 = succeed$3;
/**
* Creates an `Effect` lazily, delaying construction until it is needed.
*
* **When to use**
*
* Use when you need to defer the evaluation of an effect until it is required.
*
* **Details**
*
* `suspend` takes a thunk that represents an effect and delays creating it
* until the suspended effect is evaluated. This is useful for optimizing
* expensive computations, managing circular dependencies such as recursive
* functions, and helping TypeScript unify return types when branches construct
* different effects. Any side effects or scoped captures inside the thunk are
* re-executed on each invocation.
*
* **Example** (Lazily evaluating side effects)
*
* ```ts import.meta.vitest
* import { Effect } from "effect"
*
* let i = 0
*
* const bad = Effect.succeed(i++)
*
* const good = Effect.suspend(() => Effect.succeed(i++))
*
* Effect.runSync(bad) // => 0
* Effect.runSync(bad) // => 0
*
* Effect.runSync(good) // => 1
* Effect.runSync(good) // => 2
* ```
*
* **Example** (Suspending recursive Fibonacci evaluation)
*
* ```ts import.meta.vitest
* import { Effect } from "effect"
*
* const blowsUp = (n: number): Effect.Effect<number> =>
* n < 2
* ? Effect.succeed(1)
* : Effect.zipWith(blowsUp(n - 1), blowsUp(n - 2), (a, b) => a + b)
*
* // console.log(Effect.runSync(blowsUp(32)))
* // crash: JavaScript heap out of memory
*
* const allGood = (n: number): Effect.Effect<number> =>
* n < 2
* ? Effect.succeed(1)
* : Effect.zipWith(
* Effect.suspend(() => allGood(n - 1)),
* Effect.suspend(() => allGood(n - 2)),
* (a, b) => a + b
* )
*
* Effect.runSync(allGood(16)) // => 1597
* ```
*
* **Example** (Helping TypeScript infer recursive effect types)
*
* ```ts import.meta.vitest
* import { Effect } from "effect"
*
* // Without suspend, TypeScript may struggle with type inference.
* // Inferred type:
* // (a: number, b: number) =>
* // Effect<never, Error, never> | Effect<number, never, never>
* const withoutSuspend = (a: number, b: number) =>
* b === 0
* ? Effect.fail(new Error("Cannot divide by zero"))
* : Effect.succeed(a / b)
*
* // Using suspend to unify return types.
* // Inferred type:
* // (a: number, b: number) => Effect<number, Error, never>
* const withSuspend = (a: number, b: number) =>
* Effect.suspend(() =>
* b === 0
* ? Effect.fail(new Error("Cannot divide by zero"))
* : Effect.succeed(a / b)
* )
*
* Effect.runSync(withSuspend(6, 2)) // => 3
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const suspend = suspend$1;
/**
* Creates an `Effect` that represents a recoverable error.
*
* **When to use**
*
* Use to explicitly signal a recoverable error in an `Effect`.
*
* **Details**
*
* The error keeps propagating unless it is handled. You can handle tagged
* errors with functions like {@link catchTag} or {@link catchTags}.
*
* **Example** (Creating a failed effect)
*
* ```ts import.meta.vitest
* import { Data, Effect } from "effect"
*
* class OperationFailedError extends Data.TaggedError("OperationFailedError")<{}> {}
*
* // ┌─── Effect<never, OperationFailedError, never>
* // â–¼
* const failure = Effect.fail(
* new OperationFailedError()
* )
* Effect.runSync(Effect.flip(failure))._tag // => "OperationFailedError"
* ```
*
* @see {@link succeed} to create an effect that represents a successful value.
* @stability stable
* @category constructors
* @since 2.0.0
*/
const fail$1 = fail$3;
/**
* Creates an `Effect` that represents a failure with a `Cause` computed lazily.
*
* **When to use**
*
* Use to defer computing a full `Cause` until the effect is run.
*
* **Details**
*
* The cause-producing function is evaluated each time the effect is executed.
*
* **Example** (Lazily creating a Cause)
*
* ```ts import.meta.vitest
* import { Cause, Effect } from "effect"
*
* const program = Effect.failCauseSync(() =>
* Cause.fail("Error computed at runtime")
* )
*
* Effect.runSync(Effect.flip(program)) // => "Error computed at runtime"
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const failCauseSync = failCauseSync$1;
/**
* Creates an effect that terminates a fiber with a specified error.
*
* **When to use**
*
* Use when you need an `Effect` to report an unrecoverable defect instead of a
* typed error.
*
* **Details**
*
* The `die` function is used to signal a defect, which represents a critical
* and unexpected error in the code. When invoked, it produces an effect that
* does not handle the error and instead terminates the fiber.
*
* The error channel of the resulting effect is of type `never`, indicating that
* it cannot recover from this failure.
*
* **Example** (Failing on division by zero)
*
* ```ts import.meta.vitest
* import { Effect, Exit } from "effect"
*
* const defect = new Error("Cannot divide by zero")
* const divide = (a: number, b: number) =>
* b === 0
* ? Effect.die(defect)
* : Effect.succeed(a / b)
*
* // ┌─── Effect<number, never, never>
* // â–¼
* const program = divide(1, 0)
*
* Effect.runSyncExit(program) // => Exit.die(defect)
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const die = die$2;
/**
* Chains effects to produce new `Effect` instances, useful for combining
* operations that depend on previous results.
*
* **When to use**
*
* Use when you need to chain multiple effects, ensuring that each
* step produces a new `Effect` while flattening any nested effects that may
* occur.
*
* **Details**
*
* `flatMap` lets you sequence effects so that the result of one effect can be
* used in the next step. It is similar to `flatMap` used with arrays but works
* specifically with `Effect` instances, allowing you to avoid deeply nested
* effect structures.
*
* Since effects are immutable, `flatMap` always returns a new effect instead of
* changing the original one.
*
* **Example** (Choosing flatMap syntax variants)
*
* ```ts import.meta.vitest
* import { Effect, pipe } from "effect"
* const output: Array<unknown> = []
*
* const myEffect = Effect.succeed(1)
* const transformation = (n: number) => Effect.succeed(n + 1)
*
* const flatMappedWithPipe = pipe(myEffect, Effect.flatMap(transformation))
* const flatMappedWithDataFirst = Effect.flatMap(myEffect, transformation)
* const flatMappedWithMethod = myEffect.pipe(Effect.flatMap(transformation))
*
* void output.push(Effect.runSync(Effect.all([
* flatMappedWithPipe,
* flatMappedWithDataFirst,
* flatMappedWithMethod
* ])))
* output // => [[2, 2, 2]]
* ```
*
* **Example** (Sequencing dependent effects)
*
* ```ts import.meta.vitest
* import { Data, Effect, pipe } from "effect"
*
* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {}
*
* // Function to apply a discount safely to a transaction amount
* const applyDiscount = (
* total: number,
* discountRate: number
* ): Effect.Effect<number, DiscountRateError> =>
* discountRate === 0
* ? Effect.fail(new DiscountRateError())
* : Effect.succeed(total - (total * discountRate) / 100)
*
* // Simulated asynchronous task to fetch a transaction amount from database
* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
*
* // Chaining the fetch and discount application using `flatMap`
* const finalAmount = pipe(
* fetchTransactionAmount,
* Effect.flatMap((amount) => applyDiscount(amount, 5))
* )
*
* await Effect.runPromise(finalAmount) // => 95
* ```
*
* @see {@link tap} for a version that ignores the result of the effect.
* @stability stable
* @category sequencing
* @since 2.0.0
*/
const flatMap = flatMap$1;
/**
* Transforms an effect to encapsulate both failure and success using the `Exit`
* data type.
*
* **When to use**
*
* Use when you need to inspect the full outcome, including typed failures, defects,
* and interruptions.
*
* **Details**
*
* `exit` wraps an effect's success or failure inside an `Exit` type, allowing
* you to handle both cases explicitly.
*
* The resulting effect cannot fail because the failure is encapsulated within
* the `Exit.Failure` type. The error type is set to `never`, indicating that
* the effect is structured to never fail directly.
*
* **Example** (Capturing completion as Exit)
*
* ```ts import.meta.vitest
* import { Effect, Exit } from "effect"
*
* const success = Effect.succeed(42)
* const failure = Effect.fail("Something went wrong")
*
* const program1 = Effect.exit(success)
* const program2 = Effect.exit(failure)
*
* Effect.runSync(program1) // => Exit.succeed(42)
*
* Effect.runSync(program2) // => Exit.fail("Something went wrong")
* ```
*
* @see {@link option} for a version that uses `Option` instead.
* @see {@link result} for a version that uses `Result` instead.
*
* @stability stable
* @category error handling
* @since 2.0.0
*/
const exit = exit$1;
/**
* Handles both recoverable and unrecoverable errors by providing a recovery
* effect.
*
* **When to use**
*
* Use when you need to recover from an `Effect` by inspecting the full `Cause`,
* including recoverable failures, defects, and interruptions, instead of only
* the typed error value.
*
* **Details**
*
* When to Recover from Defects:
*
* Defects are unexpected errors that typically shouldn't be recovered from, as
* they often indicate serious issues. However, in some cases, such as
* dynamically loaded plugins, controlled recovery might be needed.
*
* **Example** (Recovering from full failure causes)
*
* ```ts import.meta.vitest
* import { Cause, Effect } from "effect"
* const output: Array<unknown> = []
*
* // An effect that might fail in different ways
* const program = Effect.die("Something went wrong")
*
* // Recover from any cause (including defects)
* const recovered = Effect.catchCause(program, (cause) => {
* if (Cause.hasDies(cause)) {
* return Effect.sync(() => { output.push("Caught defect") }).pipe(
* Effect.as("Recovered from defect")
* )
* }
* return Effect.succeed("Unknown error")
* })
*
* void output.push(Effect.runSync(recovered))
* output // => ["Caught defect", "Recovered from defect"]
* ```
*
* @stability stable
* @category error handling
* @since 4.0.0
*/
const catchCause = catchCause$1;
/**
* Runs an effect synchronously and captures the outcome safely as an `Exit` type, which
* represents the outcome (success or failure) of the effect.
*
* **When to use**
*
* Use to find out whether an effect succeeded or failed,
* including any defects, without dealing with asynchronous operations.
*
* **Details**
*
* The `Exit` type represents the result of the effect. Successful effects are
* wrapped in `Success`, and failed effects are wrapped in `Failure` with a
* `Cause`.
*
* If the effect contains asynchronous operations, `runSyncExit` will
* return an `Failure` with a `Die` cause, indicating that the effect cannot be
* resolved synchronously.
*
* **Example** (Observing synchronous results as Exit)
*
* ```ts import.meta.vitest
* import { Effect, Exit } from "effect"
*
* Effect.runSyncExit(Effect.succeed(1)) // => Exit.succeed(1)
*
* Effect.runSyncExit(Effect.fail("my error")) // => Exit.fail("my error")
* ```
*
* **Example** (Capturing async work as a Die cause)
*
* ```ts import.meta.vitest
* import { Cause, Effect, Exit } from "effect"
*
* const exit = Effect.runSyncExit(Effect.promise(() => Promise.resolve(1)))
* const isAsyncDie = Exit.hasDies(exit) && exit.cause.reasons.some(
* (reason) => Cause.isDieReason(reason) && Cause.isAsyncFiberError(reason.defect)
* )
*
* isAsyncDie // => true
* ```
*
* @see {@link runSync} for a version that throws on failure.
*
* @stability stable
* @category running
* @since 2.0.0
*/
const runSyncExit = runSyncExit$1;
/**
* Applies `map` eagerly when an effect is already resolved.
*
* **When to use**
*
* Use when an already-resolved effect should apply a success transformation
* immediately while pending effects still use regular mapping.
*
* **Details**
*
* Success effects apply the mapping function immediately. Failure effects pass
* through unchanged, and pending effects fall back to regular `map` behavior.
*
* **Example** (Mapping already completed effects)
*
* ```ts import.meta.vitest
* import { Effect } from "effect"
*
* // For resolved effects, the mapping is applied immediately
* const resolved = Effect.succeed(5)
* const mapped = Effect.mapEager(resolved, (n) => n * 2) // Applied eagerly
*
* // For pending effects, behaves like regular map
* const pending = Effect.delay(Effect.succeed(5), 0)
* const mappedPending = Effect.mapEager(pending, (n) => n * 2) // Uses regular map
*
* await Effect.runPromise(Effect.all([mapped, mappedPending])) // => [10, 10]
* ```
*
* @stability stable
* @category mapping
* @since 4.0.0
*/
const mapEager = mapEager$1;
/**
* Applies `flatMap` eagerly when an effect is already resolved.
*
* **When to use**
*
* Use when an already-resolved successful effect should bind immediately to the
* next effect while pending effects still use regular flat mapping.
*
* **Details**
*
* Success effects apply the flatMap function immediately. Failure effects pass
* through unchanged, and pending effects fall back to regular `flatMap`
* behavior.
*
* **Example** (Flat mapping eagerly when possible)
*
* ```ts import.meta.vitest
* import { Effect } from "effect"
*
* // For resolved effects, the flatMap is applied immediately
* const resolved = Effect.succeed(5)
* const flatMapped = Effect.flatMapEager(resolved, (n) => Effect.succeed(n * 2)) // Applied eagerly
*
* // For pending effects, behaves like regular flatMap
* const pending = Effect.delay(Effect.succeed(5), 0)
* const flatMappedPending = Effect.flatMapEager(
* pending,
* (n) => Effect.succeed(n * 2)
* ) // Uses regular flatMap
*
* await Effect.runPromise(Effect.all([flatMapped, flatMappedPending])) // => [10, 10]
* ```
*
* @stability stable
* @category sequencing
* @since 4.0.0
*/
const flatMapEager = flatMapEager$1;
/**
* Creates untraced function effects with eager evaluation optimization.
*
* **Details**
*
* Executes generator functions eagerly when all yielded effects are synchronous,
* stopping at the first async effect and deferring to normal execution.
*
* **Example** (Defining eager untraced effect functions)
*
* ```ts import.meta.vitest
* import { Effect } from "effect"
*
* const computation = Effect.fnUntracedEager(function*() {
* yield* Effect.succeed(1)
* yield* Effect.succeed(2)
* return "computed eagerly"
* })
*
* const effect = computation() // Executed immediately if all effects are sync
* Effect.runSync(effect) // => "computed eagerly"
* ```
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const fnUntracedEager =
fnUntracedEager$1;
const alphabet =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const codes =
/*#__PURE__*/ /* @__PURE__ */ new Uint8Array(
123,
).fill(255);
for (let i = 0; i < 64; i++)
codes[
/*#__PURE__*/ alphabet.charCodeAt(i)
] = i;
codes[/*#__PURE__*/ "=".charCodeAt(0)] =
0;
({ ...BaseProto });
({ ...BaseProto });
({ ...PipeInspectableProto });
(BaseProto.toString,
BaseProto[NodeInspectSymbol]);
({ ...PipeInspectableProto });
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/schema/annotations.js
/** @internal */
function resolve$1(ast) {
return ast.checks
? ast.checks[ast.checks.length - 1]
.annotations
: ast.annotations;
}
/** @internal */
const STRUCTURAL_ANNOTATION_KEY =
"~structural";
/** @internal */
const SENTINELS_ANNOTATION_KEY =
"~sentinels";
/** @internal */
const CONSTRUCTOR_ANNOTATION_KEY =
"~constructor";
/** @internal */
const getExpected =
/*#__PURE__*/ memoize((ast) => {
const identifier =
resolve$1(ast)?.identifier;
if (typeof identifier === "string")
return identifier;
return ast.getExpected(getExpected);
});
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/schema/parser.js
/** @internal */
const missing = /*#__PURE__*/ Symbol();
/** @internal */
const succeed = succeed$2;
/** @internal */
const missingExit =
/*#__PURE__*/ succeed(missing);
/** @internal */
const sameExit =
/*#__PURE__*/ succeed(missing);
/** @internal */
const toOption = (value) =>
value === missing
? none()
: some(value);
/** @internal */
const fromOptionExit = (option) =>
option._tag === "None"
? missingExit
: succeed(option.value);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/SchemaIssue.js
/**
* Describes problems found while decoding, encoding, or checking data with
* schemas.
*
* An `Issue` records what failed and, for nested data, where the failure
* happened. The Schema system uses these values for missing keys, unexpected
* keys, invalid types, invalid values, failed filters, failed transformations,
* and alternatives that did not match. This module also formats issues.
*
* @stability stable
* @since 4.0.0
*/
const TypeId$5 =
"~effect/SchemaIssue/Issue";
/**
* Returns `true` if the given value is an {@link Issue}.
*
* **When to use**
*
* Use when you need to narrow an `unknown` value to `Issue` in error-handling
* code, such as distinguishing an `Issue` from other error types in a catch-all
* handler.
*
* **Details**
*
* - Checks for the internal `TypeId` brand on the value.
*
* **Example** (Type-guarding an unknown error)
*
* ```ts import.meta.vitest
* import { SchemaIssue } from "effect"
*
* const issue = new SchemaIssue.MissingKey(undefined)
* SchemaIssue.isIssue(issue) // => true
* SchemaIssue.isIssue("not an issue") // => false
* ```
*
* @see {@link Issue}
*
* @stability stable
* @category guards
* @since 4.0.0
*/
function isIssue(u) {
return (
hasProperty(u, TypeId$5) &&
u[TypeId$5] === TypeId$5
);
}
/**
* Returns `true` when an issue contains an input reported by the schema parser.
*
* **When to use**
*
* Use when reading `Issue.input`, especially when `undefined` is a valid input
* value.
*
* **Details**
*
* Reported input is stored as an own property. This guard checks for that
* property and narrows `input` from optional to required.
*
* **Example** (Reading a reported input)
*
* ```ts import.meta.vitest
* import { Result, Schema, SchemaIssue } from "effect"
*
* const result = Schema.decodeUnknownResult(Schema.String)(1, { reportInput: true })
* if (Result.isFailure(result) && SchemaIssue.hasInput(result.failure.issue)) {
* result.failure.issue.input // => 1
* }
* ```
*
* @see {@link Issue} for the complete issue model
*
* @stability stable
* @category guards
* @since 4.0.0
*/
function hasInput(issue) {
return Object.hasOwn(issue, "input");
}
var IssueNodeImpl = class {
[TypeId$5] = TypeId$5;
constructor(input, options) {
if (
options?.reportInput === true &&
input !== missing
)
this.input = input;
}
};
/**
* Constructs a schema issue for a failed refinement check.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Filter$1 = class extends IssueNodeImpl {
_tag = "Filter";
/**
* The filter that failed.
*/
filter;
/**
* The issue that occurred.
*/
issue;
constructor(
filter,
issue,
input,
options,
) {
super(input, options);
this.filter = filter;
this.issue = issue;
}
};
/**
* Constructs a schema issue for a failed transformation.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Encoding = class extends IssueNodeImpl {
_tag = "Encoding";
/**
* The schema that caused the issue.
*/
ast;
/**
* The issue that occurred.
*/
issue;
constructor(
ast,
issue,
input,
options,
) {
super(input, options);
this.ast = ast;
this.issue = issue;
}
};
/**
* Constructs a schema issue that points to a nested location.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Pointer = class extends IssueNodeImpl {
_tag = "Pointer";
/**
* The path to the location in the input that caused the issue.
*/
path;
/**
* The issue that occurred.
*/
issue;
constructor(path, issue) {
super();
this.path = path;
this.issue = issue;
}
};
/**
* Constructs a schema issue for a missing key or tuple index.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const MissingKey = class extends IssueNodeImpl {
_tag = "MissingKey";
/**
* The metadata for the issue.
*/
annotations;
constructor(annotations) {
super();
this.annotations = annotations;
}
};
/**
* Constructs a schema issue for an unexpected key or tuple index.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const UnexpectedKey = class extends IssueNodeImpl {
_tag = "UnexpectedKey";
/**
* The schema that caused the issue.
*/
ast;
constructor(ast, input, options) {
super(input, options);
this.ast = ast;
}
};
/**
* Constructs a schema issue that groups multiple child issues.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Composite = class extends IssueNodeImpl {
_tag = "Composite";
/**
* The schema that caused the issue.
*/
ast;
/**
* The issues that occurred.
*/
issues;
constructor(
ast,
issues,
input,
options,
) {
super(input, options);
this.ast = ast;
this.issues = issues;
}
};
/**
* Constructs a schema issue for an input with an invalid runtime type.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const InvalidType = class extends IssueNodeImpl {
_tag = "InvalidType";
/**
* The schema that caused the issue.
*/
ast;
constructor(ast, input, options) {
super(input, options);
this.ast = ast;
}
};
/**
* Constructs a schema issue for a value that violates a constraint.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const InvalidValue = class extends IssueNodeImpl {
_tag = "InvalidValue";
/**
* The metadata for the issue.
*/
annotations;
constructor(
annotations,
input,
options,
) {
super(input, options);
this.annotations = annotations;
}
};
/**
* Constructs a schema issue for a value that matches no union member.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const AnyOf = class extends IssueNodeImpl {
_tag = "AnyOf";
/**
* The schema that caused the issue.
*/
ast;
/**
* The issues that occurred.
*/
issues;
constructor(
ast,
issues,
input,
options,
) {
super(input, options);
this.ast = ast;
this.issues = issues;
}
};
/**
* Constructs a schema issue for a value that matches multiple union members.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const OneOf = class extends IssueNodeImpl {
_tag = "OneOf";
/**
* The schema that caused the issue.
*/
ast;
/**
* The schemas that were successful.
*/
successes;
constructor(
ast,
successes,
input,
options,
) {
super(input, options);
this.ast = ast;
this.successes = successes;
}
};
function makeFilterIssue(
entry,
input,
options,
) {
if (isIssue(entry)) return entry;
if (typeof entry === "string")
return new InvalidValue(
{ message: entry },
input,
options,
);
const inner =
typeof entry.issue === "string"
? new InvalidValue(
{ message: entry.issue },
input,
options,
)
: entry.issue;
return new Pointer(entry.path, inner);
}
/** @internal */
function makeSingle(
out,
input,
options,
) {
if (out === void 0) return;
if (typeof out === "boolean")
return out
? void 0
: new InvalidValue(
void 0,
input,
options,
);
return makeFilterIssue(
out,
input,
options,
);
}
/** @internal */
function normalizeFilterOutput(
ast,
out,
input,
options,
) {
if (Array.isArray(out)) {
if (!isReadonlyArrayNonEmpty(out))
return;
return out.length === 1
? makeFilterIssue(
out[0],
input,
options,
)
: new Composite(
ast,
map$2(out, (entry) =>
makeFilterIssue(
entry,
input,
options,
),
),
input,
options,
);
}
return makeSingle(
out,
input,
options,
);
}
/**
* Returns the built-in {@link LeafHook} used by default formatters.
*
* **When to use**
*
* Use as the default leaf renderer when customizing only the {@link CheckHook}.
*
* **Details**
*
* - Checks for a `message` annotation first; returns it if present.
* - For `InvalidValue`, an `expected` annotation uses the standard expected
* value message and includes reported input when available.
* - Otherwise generates a default message per `_tag`. When the issue reports
* input, the message includes its formatted value where applicable:
* - `InvalidType` → `"Expected <type>"` or `"Expected <type>, got <input>"`
* - `InvalidValue` → `"Expected a valid value"` or `"Invalid data <input>"`
* - `MissingKey` → `"Missing key"`
* - `UnexpectedKey` → `"Expected no excess property"` or
* `"Unexpected key with value <input>"`
* - `Forbidden` → `"Forbidden operation"`
* - `OneOf` → `"Expected exactly one member to match"` or
* `"Expected exactly one member to match the input <input>"`
*
* **Example** (Formatting Standard Schema issues with defaultLeafHook)
*
* ```ts import.meta.vitest
* import { SchemaIssue } from "effect"
*
* const formatter = SchemaIssue.makeFormatterStandardSchemaV1({
* leafHook: SchemaIssue.defaultLeafHook
* })
* formatter(new SchemaIssue.MissingKey(undefined)) // => { issues: [{ path: [], message: "Missing key" }] }
* ```
*
* @see {@link LeafHook}
* @see {@link makeFormatterStandardSchemaV1}
*
* @stability stable
* @category formatting
* @since 4.0.0
*/
const defaultLeafHook = (issue) => {
const message = findMessage(issue);
if (message !== void 0)
return message;
switch (issue._tag) {
case "InvalidType":
return getExpectedMessage(
getExpected(issue.ast),
issue,
);
case "InvalidValue": {
const expected =
findExpected(issue);
if (expected !== void 0)
return getExpectedMessage(
expected,
issue,
);
const input = formatInput(issue);
return input === void 0
? "Expected a valid value"
: `Invalid data ${input}`;
}
case "MissingKey":
return "Missing key";
case "UnexpectedKey": {
const input = formatInput(issue);
return input === void 0
? "Expected no excess property"
: `Unexpected key with value ${input}`;
}
case "Forbidden":
return "Forbidden operation";
case "OneOf": {
const input = formatInput(issue);
return input === void 0
? "Expected exactly one member to match"
: `Expected exactly one member to match the input ${input}`;
}
}
};
/**
* Returns the built-in {@link CheckHook} used by default formatters.
*
* **When to use**
*
* Use as the default filter renderer when customizing only the {@link LeafHook}.
*
* **Details**
*
* - Looks for a `message` annotation on the inner issue first, then on the
* filter itself.
* - Returns `undefined` when no annotation is found, causing the formatter to
* fall back to `"Expected <filter>"` or, when the filter reports input,
* `"Expected <filter>, got <input>"`.
*
* @see {@link CheckHook}
* @see {@link makeFormatterStandardSchemaV1}
*
* @stability stable
* @category formatting
* @since 4.0.0
*/
const defaultCheckHook = (issue) =>
findMessage(issue.issue) ??
findMessage(issue);
function formatInput(issue) {
return hasInput(issue)
? format$1(issue.input)
: void 0;
}
function findExpected(issue) {
const expected =
issue.annotations?.expected;
return typeof expected === "string"
? expected
: void 0;
}
function getExpectedMessage(
expected,
issue,
) {
const input = formatInput(issue);
return input === void 0
? `Expected ${expected}`
: `Expected ${expected}, got ${input}`;
}
function formatCheck(check) {
const expected =
check.annotations?.expected;
if (typeof expected === "string")
return expected;
switch (check._tag) {
case "Filter":
return "<filter>";
case "FilterGroup":
return check.checks
.map((check) =>
formatCheck(check),
)
.join(" & ");
}
}
/**
* Creates a {@link Formatter} that converts an {@link Issue} into a
* human-readable multi-line string.
*
* **When to use**
*
* Use when you need to format a `SchemaIssue.Issue` as error messages for
* logging, CLI output, or developer-facing diagnostics.
*
* **Details**
*
* - Flattens the issue tree into `{ message, path }` entries using
* {@link defaultLeafHook} and {@link defaultCheckHook}.
* - Includes reported input in default messages when the node producing the
* message has an `input` field.
* - Each entry is rendered as `"<message>"` or `"<message>\n at <path>"`.
* - Multiple entries are joined with newlines.
*
* **Gotchas**
*
* Formatting an issue can disclose input retained with `reportInput: true`.
* Wrapper inputs are not inherited by child messages, and custom messages are
* returned unchanged.
*
* **Example** (Formatting an issue as a string)
*
* ```ts import.meta.vitest
* import { SchemaIssue } from "effect"
*
* const formatter = SchemaIssue.makeFormatterDefault()
* formatter(new SchemaIssue.MissingKey(undefined)) // => "Missing key"
* ```
*
* @see {@link makeFormatterStandardSchemaV1} — produces Standard Schema V1 format instead
* @see {@link Formatter}
*
* @stability stable
* @category formatting
* @since 4.0.0
*/
function makeFormatterDefault() {
return (issue) =>
formatIssue(issue, "");
}
/** @internal */
const defaultFormatter =
/*#__PURE__*/ makeFormatterDefault();
function formatIssue(issue, path) {
let message;
switch (issue._tag) {
case "Filter": {
const annotated =
defaultCheckHook(issue);
if (annotated !== void 0)
message = annotated;
else {
if (
issue.issue._tag !==
"InvalidValue"
)
return formatIssue(
issue.issue,
path,
);
const expected = findExpected(
issue.issue,
);
message =
expected === void 0
? getExpectedMessage(
formatCheck(
issue.filter,
),
issue,
)
: getExpectedMessage(
expected,
issue.issue,
);
}
break;
}
case "Encoding":
return formatIssue(
issue.issue,
path,
);
case "Pointer":
return formatIssue(
issue.issue,
path + formatPath(issue.path),
);
case "Composite":
case "AnyOf":
if (
issue._tag === "Composite" ||
issue.issues.length > 0
)
return issue.issues
.map((issue) =>
formatIssue(issue, path),
)
.join("\n");
message =
findMessage(issue) ??
getExpectedMessage(
getExpected(issue.ast),
issue,
);
break;
default:
message = defaultLeafHook(issue);
}
return path
? `${message}\n at ${path}`
: message;
}
function findMessage(issue) {
if (issue._tag === "Pointer") return;
if (issue._tag === "Encoding")
return findMessage(issue.issue);
const message = (
issue._tag === "Filter"
? issue.filter.annotations
: "annotations" in issue
? issue.annotations
: issue.ast.annotations
)?.[
issue._tag === "MissingKey"
? "messageMissingKey"
: issue._tag === "UnexpectedKey"
? "messageUnexpectedKey"
: "message"
];
if (typeof message === "string")
return message;
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/schema/cause.js
/** @internal */
function getSchemaIssue(cause) {
let issue;
for (const reason of cause.reasons) {
if (
!isFailReason(reason) ||
!isIssue(reason.error)
)
return;
issue ??= reason.error;
}
return issue;
}
/** @internal */
function getSchemaIssueOrThrow(
cause,
message,
) {
const issue = getSchemaIssue(cause);
if (issue === void 0)
throw new Error(message, { cause });
return issue;
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/SchemaGetter.js
const makeGetter = (fields) =>
Object.assign(
Object.create(Prototype$1),
fields,
);
const passthrough_$1 =
/*#__PURE__*/ makeGetter({
_tag: "Passthrough",
});
function passthrough$1() {
return passthrough_$1;
}
/**
* Creates a getter that applies a pure function to present values.
*
* **When to use**
*
* Use when you need a schema getter for a pure, infallible transformation
* between types.
* - Building encode/decode pairs for `Schema.decodeTo`.
*
* **Details**
*
* - This is the most commonly used constructor.
* - Transforms `Some(e)` to `Some(f(e))` and leaves `None` unchanged.
* - Skips `None` inputs — only called when a value is present.
* - Never fails.
*
* **Example** (Transforming strings to numbers)
*
* ```ts import.meta.vitest
* import { Schema, SchemaGetter } from "effect"
*
* const NumberFromString = Schema.String.pipe(
* Schema.decodeTo(Schema.Number, {
* decode: SchemaGetter.transform((s) => Number(s)),
* encode: SchemaGetter.transform((n) => String(n))
* })
* )
* Schema.decodeSync(NumberFromString)("42") // => 42
* ```
*
* @see {@link transformEffect} when the transformation returns an `Effect`
* @see {@link transformOptional} when you need to handle `None` inputs
* @see {@link passthrough} when no transformation is needed
*
* @stability stable
* @category transforming
* @since 4.0.0
*/
function transform$1(f) {
return makeGetter({
_tag: "Transform",
transform: f,
});
}
/**
* Coerces any value to a `string` using the global `String()` constructor.
*
* **When to use**
*
* Use when you need a schema getter to coerce a present encoded value to a
* string with `String()`.
*
* **Details**
*
* The getter is pure, never fails, and delegates to `globalThis.String`.
*
* **Example** (Coercing to a string)
*
* ```ts import.meta.vitest
* import { Effect, Option, SchemaGetter } from "effect"
*
* const toString = SchemaGetter.String<number>()
* Effect.runSync(SchemaGetter.run(toString, Option.some(42), {})) // => Option.some("42")
* ```
*
* @see {@link transform} for custom string conversions
*
* @stability stable
* @category converting
* @since 4.0.0
*/
function String$3() {
return transform$1(globalThis.String);
}
/**
* Coerces any value to a `number` using the global `Number()` constructor.
*
* **When to use**
*
* Use when you need a schema getter to coerce a present encoded value to a
* number with `Number()`.
*
* **Details**
*
* The getter is pure, never fails, and delegates to `globalThis.Number`. It may
* produce `NaN` for non-numeric inputs.
*
* **Example** (Coercing to a number)
*
* ```ts import.meta.vitest
* import { Effect, Option, SchemaGetter } from "effect"
*
* const toNumber = SchemaGetter.Number<string>()
* Effect.runSync(SchemaGetter.run(toNumber, Option.some("42"), {})) // => Option.some(42)
* ```
*
* @see {@link transformEffect} for effectful or validated number parsing
*
* @stability stable
* @category converting
* @since 4.0.0
*/
function Number$3() {
return transform$1(globalThis.Number);
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/SchemaTransformation.js
/**
* Constructs schema middleware from its decode and encode functions.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Middleware = class extends Class$1 {
_tag = "Middleware";
decode;
encode;
constructor(decode, encode) {
super();
this.decode = decode;
this.encode = encode;
}
flip() {
return new Middleware(
this.encode,
this.decode,
);
}
};
const TypeId$4 =
"~effect/SchemaTransformation/Transformation";
/**
* Constructs a bidirectional schema transformation from its decode and encode getters.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Transformation = class extends Class$1 {
[TypeId$4] = TypeId$4;
_tag = "Transformation";
decode;
encode;
constructor(decode, encode) {
super();
this.decode = decode;
this.encode = encode;
}
flip() {
return new Transformation(
this.encode,
this.decode,
);
}
};
/**
* Returns `true` if `u` is a `Transformation` instance.
*
* **When to use**
*
* Use to check whether a value is already a schema transformation before
* wrapping it.
*
* **Details**
*
* - Pure predicate, no side effects.
* - Acts as a TypeScript type guard.
*
* **Example** (Checking a value)
*
* ```ts import.meta.vitest
* import { SchemaTransformation } from "effect"
*
* SchemaTransformation.isTransformation(SchemaTransformation.trim()) // => true
* SchemaTransformation.isTransformation({ decode: null, encode: null }) // => false
* ```
*
* @see {@link Transformation}
* @see {@link makeTransformation}
*
* @stability stable
* @category guards
* @since 4.0.0
*/
function isTransformation(u) {
return (
hasProperty(u, TypeId$4) &&
u[TypeId$4] === TypeId$4
);
}
/**
* Constructs a `Transformation` from an object with `decode` and `encode`
* `Getter`s. If the input is already a `Transformation`, returns it as-is.
*
* **When to use**
*
* Use when you already have schema getter instances and want to pair them into
* a schema transformation.
* - You want idempotent wrapping (won't double-wrap).
*
* **Details**
*
* - Returns the input unchanged if it is already a `Transformation`.
*
* **Example** (Wrapping existing getters)
*
* ```ts import.meta.vitest
* import { SchemaGetter, SchemaTransformation } from "effect"
*
* const t = SchemaTransformation.makeTransformation({
* decode: SchemaGetter.transform<number, string>((s) => Number(s)),
* encode: SchemaGetter.transform<string, number>((n) => String(n))
* })
* t._tag // => "Transformation"
* ```
*
* @see {@link transform} — simpler constructor from pure functions
* @see {@link transformEffect} — constructor from effectful functions
* @see {@link Transformation}
*
* @stability stable
* @category constructors
* @since 3.10.0
*/
const makeTransformation = (
options,
) => {
if (isTransformation(options))
return options;
return new Transformation(
options.decode,
options.encode,
);
};
const passthrough_ =
/*#__PURE__*/ new Transformation(
/*#__PURE__*/ passthrough$1(),
/*#__PURE__*/ passthrough$1(),
);
function passthrough() {
return passthrough_;
}
/**
* Decodes a `string` into a `number` and encodes a `number` back to a
* `string`.
*
* **When to use**
*
* Use when you need a schema transformation to parse numeric strings from APIs,
* form data, or URL parameters.
*
* **Details**
*
* Decoding coerces the string to a number like `Number(s)`. Encoding coerces
* the number to a string like `String(n)`. This does not validate that the
* result is finite; combine with `Schema.Finite` or `Schema.Int` for stricter
* checks.
*
* **Example** (Converting a string to a number)
*
* ```ts import.meta.vitest
* import { Schema, SchemaTransformation } from "effect"
*
* const schema = Schema.String.pipe(
* Schema.decodeTo(Schema.Number, SchemaTransformation.numberFromString)
* )
* Schema.decodeSync(schema)("42") // => 42
* ```
*
* @see {@link bigintFromString}
* @see {@link transform}
*
* @stability stable
* @category converting
* @since 4.0.0
*/
const numberFromString =
/*#__PURE__*/ new Transformation(
/*#__PURE__*/ Number$3(),
/*#__PURE__*/ String$3(),
);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/SchemaAST.js
/**
* Represents Effect schemas as runtime trees.
*
* Every `Schema` has an AST made from nodes for declarations, primitives,
* literals, arrays, objects, unions, suspended schemas, checks, annotations,
* encoding links, and parsing context. Most users work with the higher-level
* `Schema` module. Use `SchemaAST` when you need to inspect schema nodes, build
* ASTs programmatically, change encoded or decoded views, collect issues, or
* run low-level schema checks.
*
* @stability stable
* @since 4.0.0
*/
function makeGuard(tag) {
return (ast) => ast._tag === tag;
}
/**
* Narrows an {@link AST} to {@link Declaration}.
*
* **When to use**
*
* Use to recognize declaration AST nodes before running declaration-specific
* handling.
*
* @see {@link Declaration} for the AST node type narrowed by this guard
*
* @stability stable
* @category guards
* @since 3.10.0
*/
const isDeclaration =
/*#__PURE__*/ makeGuard(
"Declaration",
);
/**
* Narrows an {@link AST} to {@link Never}.
*
* **When to use**
*
* Use to detect the AST node for a schema that can never match before handling
* other schema variants.
*
* @see {@link Never} for the AST node type narrowed by this guard
* @see {@link never} for the singleton `Never` AST instance
*
* @stability stable
* @category guards
* @since 4.0.0
*/
const isNever =
/*#__PURE__*/ makeGuard("Never");
/**
* Narrows an {@link AST} to {@link Literal}.
*
* **When to use**
*
* Use to recognize exact string, number, boolean, or bigint literal AST nodes.
*
* @see {@link Literal} for the AST node type narrowed by this guard
* @see {@link LiteralValue} for the values stored by literal nodes
*
* @stability stable
* @category guards
* @since 3.10.0
*/
const isLiteral =
/*#__PURE__*/ makeGuard("Literal");
/**
* Narrows an {@link AST} to {@link UniqueSymbol}.
*
* @stability stable
* @category guards
* @since 3.10.0
*/
const isUniqueSymbol =
/*#__PURE__*/ makeGuard(
"UniqueSymbol",
);
/**
* Narrows an {@link AST} to {@link Arrays}.
*
* **When to use**
*
* Use to recognize array-like AST nodes before reading their element, rest, or
* mutability metadata.
*
* @see {@link Arrays} for the AST node type narrowed by this guard
*
* @stability stable
* @category guards
* @since 4.0.0
*/
const isArrays =
/*#__PURE__*/ makeGuard("Arrays");
/**
* Narrows an {@link AST} to {@link Objects}.
*
* @stability stable
* @category guards
* @since 4.0.0
*/
const isObjects =
/*#__PURE__*/ makeGuard("Objects");
/**
* Narrows an {@link AST} to {@link Suspend}.
*
* @stability stable
* @category guards
* @since 3.10.0
*/
const isSuspend =
/*#__PURE__*/ makeGuard("Suspend");
/**
* Constructs a {@link Link}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Link = class {
to;
transformation;
constructor(to, transformation) {
this.to = to;
this.transformation =
transformation;
}
};
/** @internal */
const defaultParseOptions = {};
/**
* Constructs a {@link Context}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Context = class {
isOptional;
isMutable;
/** Used for constructor default values (e.g. `withConstructorDefault` API) */
constructorDefault;
annotations;
constructor(
isOptional,
isMutable,
constructorDefault = void 0,
annotations = void 0,
) {
this.isOptional = isOptional;
this.isMutable = isMutable;
this.constructorDefault =
constructorDefault;
this.annotations = annotations;
}
};
const TypeId$3 = "~effect/Schema";
var ASTNodeImpl = class {
[TypeId$3] = TypeId$3;
annotations;
checks;
encoding;
context;
constructor(
annotations = void 0,
checks = void 0,
encoding = void 0,
context = void 0,
) {
this.annotations = annotations;
this.checks = checks;
this.encoding = encoding;
this.context = context;
}
toString() {
return `<${this._tag}>`;
}
};
/**
* Constructs a {@link Declaration}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Declaration = class extends ASTNodeImpl {
_tag = "Declaration";
typeParameters;
run;
encodingChecks;
/**
* Parser factory {@link flip} swaps in, so a declaration can behave
* differently when encoding. `undefined` reuses `run`.
*/
encodingRun;
constructor(
typeParameters,
run,
annotations,
checks,
encoding,
context,
encodingChecks,
encodingRun,
) {
super(
annotations,
checks,
encoding,
context,
);
this.typeParameters =
typeParameters;
this.run = run;
this.encodingChecks =
encodingChecks;
this.encodingRun = encodingRun;
}
/** @internal */
getParser() {
let run;
return (input, options) => {
if (input === missing)
return missingExit;
return (run ??= this.run(
this.typeParameters,
))(input, this, options);
};
}
_rebuild(
recur,
checks,
encodingChecks,
run,
encodingRun,
) {
const tps = mapOrSame(
this.typeParameters,
recur,
);
return tps ===
this.typeParameters &&
checks === this.checks &&
encodingChecks ===
this.encodingChecks &&
run === this.run &&
encodingRun === this.encodingRun
? this
: new Declaration(
tps,
run,
this.annotations,
checks,
void 0,
this.context,
encodingChecks,
encodingRun,
);
}
/** @internal */
recur(recur) {
return this._rebuild(
recur,
this.checks,
this.encodingChecks,
this.run,
this.encodingRun,
);
}
/** @internal */
flip(recur) {
return this._rebuild(
recur,
this.encodingChecks,
this.checks,
this.encodingRun ?? this.run,
this.run,
);
}
/** @internal */
getExpected() {
const expected =
this.annotations?.expected;
if (typeof expected === "string")
return expected;
return "<Declaration>";
}
};
/**
* Constructs a {@link Null}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Null$1 = class extends ASTNodeImpl {
_tag = "Null";
/** @internal */
getParser() {
return fromConst(this, null);
}
/** @internal */
getExpected() {
return "null";
}
};
const null_ =
/*#__PURE__*/ new Null$1();
/**
* Constructs a {@link Unknown}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Unknown = class extends ASTNodeImpl {
_tag = "Unknown";
/** @internal */
getParser() {
return fromRefinement(
this,
isUnknown,
);
}
/** @internal */
getExpected() {
return "unknown";
}
};
/**
* Provides the singleton {@link Unknown} AST instance.
*
* **When to use**
*
* Use when you need the reusable AST singleton for a schema node that accepts
* every value while keeping parsed values opaque.
*
* @see {@link any} for the singleton that accepts every value as `any`
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const unknown =
/*#__PURE__*/ new Unknown();
/**
* Constructs a {@link Literal}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Literal$1 = class extends ASTNodeImpl {
_tag = "Literal";
literal;
constructor(
literal,
annotations,
checks,
encoding,
context,
) {
super(
annotations,
checks,
encoding,
context,
);
if (
typeof literal === "number" &&
!globalThis.Number.isFinite(
literal,
)
)
throw new Error(
`A numeric literal must be finite, got ${format$1(literal)}`,
);
this.literal = literal;
}
/** @internal */
getParser() {
return fromConst(
this,
this.literal,
);
}
/** @internal */
matchPart(s, _options) {
return s ===
globalThis.String(this.literal)
? this.literal
: void 0;
}
/** @internal */
toCodecJson() {
return typeof this.literal ===
"bigint"
? literalToString(this)
: this;
}
/** @internal */
toCodecStringTree() {
return typeof this.literal ===
"string"
? this
: literalToString(this);
}
/** @internal */
getExpected() {
return typeof this.literal ===
"string"
? JSON.stringify(this.literal)
: globalThis.String(this.literal);
}
};
function literalToString(ast) {
const literalAsString =
globalThis.String(ast.literal);
return replaceEncoding(ast, [
new Link(
new Literal$1(literalAsString),
new Transformation(
transform$1(() => ast.literal),
transform$1(
() => literalAsString,
),
),
),
]);
}
/**
* Constructs a {@link String}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const String$2 = class extends ASTNodeImpl {
_tag = "String";
/** @internal */
getParser() {
return fromRefinement(
this,
isString$1,
);
}
/** @internal */
matchPart(s, options) {
const checks = this.checks;
return checks &&
!options.disableChecks &&
collectIssues(
checks,
s,
void 0,
this,
options,
)
? void 0
: s;
}
/** @internal */
getExpected() {
return "string";
}
};
/**
* Provides the singleton {@link String} AST instance.
*
* **When to use**
*
* Use as the shared `SchemaAST` node for unconstrained JavaScript strings.
*
* @see {@link String} for the AST node class
* @see {@link isString} for narrowing an AST to a string node
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const string =
/*#__PURE__*/ new String$2();
/**
* Constructs a {@link Number}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Number$2 = class extends ASTNodeImpl {
_tag = "Number";
/** @internal */
getParser() {
return fromRefinement(
this,
isNumber,
);
}
/** @internal */
matchKey(s, options) {
return this._match(
isStringNumberRegExp,
s,
options,
);
}
/** @internal */
matchPart(s, options) {
return this._match(
isStringFiniteRegExp,
s,
options,
);
}
_match(regexp, s, options) {
if (!regexp.test(s)) return void 0;
const value = globalThis.Number(s);
if (
options.disableChecks ||
!this.checks
)
return value;
return collectIssues(
this.checks,
value,
void 0,
this,
options,
)
? void 0
: value;
}
/** @internal */
toCodecJson() {
if (
this.checks &&
(hasCheck(
this.checks,
"effect/schema/isFinite",
) ||
hasCheck(
this.checks,
"effect/schema/isInt",
))
)
return this;
return replaceEncoding(this, [
numberToJson,
]);
}
/** @internal */
toCodecStringTree() {
if (this.toCodecJson() === this)
return replaceEncoding(this, [
finiteToString,
]);
return replaceEncoding(this, [
numberToString,
]);
}
/** @internal */
getExpected() {
return "number";
}
};
function hasCheck(checks, id) {
return checks.some(
(check) =>
check.annotations?.representation
?.id === id ||
(check._tag === "FilterGroup" &&
hasCheck(check.checks, id)),
);
}
/**
* Provides the singleton {@link Number} AST instance.
*
* **When to use**
*
* Use when you need the canonical `SchemaAST` node for schemas that accept any
* JavaScript number value.
*
* @see {@link Number} for the AST node class and serialization behavior
* @see {@link Literal} for exact finite numeric literal AST nodes
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const number =
/*#__PURE__*/ new Number$2();
/**
* Constructs a {@link Arrays}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Arrays = class extends ASTNodeImpl {
_tag = "Arrays";
isMutable;
elements;
rest;
encodingChecks;
constructor(
isMutable,
elements,
rest,
annotations,
checks,
encoding,
context,
encodingChecks,
) {
super(
annotations,
checks,
encoding,
context,
);
this.isMutable = isMutable;
this.elements = elements;
this.rest = rest;
this.encodingChecks =
encodingChecks;
let hasOptional = false;
for (
let i = 0;
i < elements.length;
i++
)
if (isOptional(elements[i]))
hasOptional = true;
else if (hasOptional)
throw new Error(
"A required element cannot follow an optional element. ts(1257)",
);
if (hasOptional && rest.length > 1)
throw new Error(
"A required element cannot follow an optional element. ts(1257)",
);
for (
let i = 1;
i < rest.length;
i++
)
if (isOptional(rest[i]))
throw new Error(
"An optional element cannot follow a rest element. ts(1266)",
);
}
/** @internal */
getParser(
compile,
compileField = compile,
) {
const ast = this;
let elements;
let rest;
const elementLen =
ast.elements.length;
const tailLen = Math.max(
0,
ast.rest.length - 1,
);
function getParser(
tailThreshold,
index,
) {
if (index < elementLen)
return elements[index];
else if (index >= tailThreshold)
return rest[
index - tailThreshold + 1
];
return rest[0];
}
const finish = (state) => {
const { input, len, options } =
state;
if (
ast.rest.length === 0 &&
len > elementLen
)
for (
let i = elementLen;
i < len;
i++
) {
const unexpected =
new UnexpectedKey(
ast,
input[i],
options,
);
const issue = new Pointer(
[i],
unexpected,
);
if (
options.errors === "all"
) {
if (state.issues)
state.issues.push(issue);
else state.issues = [issue];
} else
return fail$1(
new Composite(
ast,
[issue],
input,
options,
),
);
}
if (state.issues)
return fail$1(
new Composite(
ast,
state.issues,
input,
options,
),
);
return succeed(state.output);
};
const parse = (input, options) => {
const len = input.length;
const state = {
ast,
getParser,
input,
len,
tailThreshold: Math.max(
elementLen,
len - tailLen,
),
output: new globalThis.Array(
len,
),
issues: void 0,
options,
};
const end =
ast.rest.length === 0
? elementLen
: Math.max(
len,
elementLen + tailLen,
);
const concurrency =
options.concurrency === void 0
? 1
: resolveConcurrency(
options.concurrency,
);
const eff =
concurrency === 1
? parseArray(
state,
input,
0,
end,
)
: parseArrayConcurrent(
state,
input,
{
concurrency,
end,
},
);
if (!eff) return finish(state);
if (effectIsExit(eff))
return flatMapEager(eff, () =>
finish(state),
);
let first = true;
return suspend(() => {
if (!first)
return parse(input, options);
first = false;
return flatMap(eff, () =>
finish(state),
);
});
};
return (input, options) => {
if (input === missing)
return missingExit;
try {
if (!Array.isArray(input))
return fail$1(
new InvalidType(
ast,
input,
options,
),
);
if (!elements) {
elements = ast.elements.map(
(ast) => ({
ast,
parser: compileField(ast),
}),
);
rest = ast.rest.map(
(ast) => ({
ast,
parser: compileField(ast),
}),
);
}
return parse(input, options);
} catch (error) {
return die(error);
}
};
}
_rebuild(
recur,
checks,
encodingChecks,
) {
const elements = mapOrSame(
this.elements,
recur,
);
const rest = mapOrSame(
this.rest,
recur,
);
return elements === this.elements &&
rest === this.rest &&
checks === this.checks &&
encodingChecks ===
this.encodingChecks
? this
: new Arrays(
this.isMutable,
elements,
rest,
this.annotations,
checks,
void 0,
this.context,
encodingChecks,
);
}
/** @internal */
recur(recur) {
return this._rebuild(
recur,
this.checks,
this.encodingChecks,
);
}
/** @internal */
flip(recur) {
return this._rebuild(
recur,
this.encodingChecks,
this.checks,
);
}
/** @internal */
getExpected() {
return "array";
}
};
/** @internal */
function stepArray(s, item, exit, i) {
if (exit._tag === "Failure")
return wrapPropertyKeyIssue(
s,
s.ast,
i,
exit,
);
const value =
exit === sameExit
? item
: exit[args];
if (value !== missing)
s.output[i] = value;
else {
const p = s.getParser(
s.tailThreshold,
i,
);
if (isOptional(p.ast)) return;
const issue = new Pointer(
[i],
new MissingKey(
p.ast.context?.annotations,
),
);
if (s.options.errors === "all") {
if (s.issues)
s.issues.push(issue);
else s.issues = [issue];
} else
return fail$2(
new Composite(
s.ast,
[issue],
s.input,
s.options,
),
);
}
}
const parseArrayOptions = {
onItem(s, item, i) {
const value =
i < s.len ? item : missing;
return s
.getParser(s.tailThreshold, i)
.parser(value, s.options);
},
step: stepArray,
};
/** @internal */
const parseArray =
/*#__PURE__*/ iterateEager()(
parseArrayOptions,
);
const parseArrayConcurrent =
/*#__PURE__*/ iterateConcurrent()(
parseArrayOptions,
);
const wrapPropertyKeyIssue = (
s,
ast,
key,
exit,
) => {
if (exit.cause.reasons.length === 0)
return exit;
const issue = getSchemaIssue(
exit.cause,
);
if (issue === void 0)
return failCause(
map(
exit.cause,
(issue) =>
new Composite(
ast,
[new Pointer([key], issue)],
s.input,
s.options,
),
),
);
const pointer = new Pointer(
[key],
issue,
);
if (s.options.errors === "all") {
if (s.issues)
s.issues.push(pointer);
else s.issues = [pointer];
} else
return fail$2(
new Composite(
ast,
[pointer],
s.input,
s.options,
),
);
};
/**
* floating point or integer, with optional exponent
* @internal
*/
const FINITE_PATTERN =
"[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?";
/**
* Returns the object keys that match the index signature parameter schema.
* @internal
*/
function getIndexSignatureKeys(
input,
parameter,
options = defaultParseOptions,
) {
let stringKeys;
let symbolKeys;
function go(parameter) {
switch (parameter._tag) {
case "String":
case "TemplateLiteral":
return (stringKeys ??=
Object.keys(input)).filter(
(k) =>
parameter.matchPart(
k,
options,
) !== void 0,
);
case "Number":
return (stringKeys ??=
Object.keys(input)).filter(
(k) =>
parameter.matchKey(
k,
options,
) !== void 0,
);
case "Symbol":
return (symbolKeys ??=
Object.getOwnPropertySymbols(
input,
)).filter(
(k) =>
Object.prototype.propertyIsEnumerable.call(
input,
k,
) &&
parameter.matchKey(
k,
options,
) !== void 0,
);
case "Union":
return [
...new Set(
parameter.types.flatMap(go),
),
];
default:
return [];
}
}
return go(
parameterFromPropertyKey(
toEncoded(parameter),
),
);
}
/**
* Constructs a {@link PropertySignature}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const PropertySignature = class {
name;
type;
constructor(name, type) {
this.name = name;
this.type = type;
}
};
function isIndexSignatureParameterSide(
ast,
) {
switch (ast._tag) {
case "String":
case "Number":
case "Symbol":
case "TemplateLiteral":
return true;
case "Union":
return ast.types.every(
isIndexSignatureParameterSide,
);
default:
return false;
}
}
function isIndexSignatureParameterEncodedSide(
ast,
) {
const encoded = getLastEncoding(ast);
switch (encoded._tag) {
case "String":
case "Number":
case "Symbol":
case "TemplateLiteral":
return true;
case "Union":
return encoded.types.every(
isIndexSignatureParameterEncodedSide,
);
default:
return false;
}
}
function isIndexSignatureParameter(
ast,
) {
return (
isIndexSignatureParameterSide(
ast,
) &&
isIndexSignatureParameterEncodedSide(
ast,
)
);
}
/**
* Constructs a {@link IndexSignature}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const IndexSignature = class {
parameter;
type;
constructor(parameter, type) {
if (
!isIndexSignatureParameter(
parameter,
)
)
throw new Error(
`Invalid index signature parameter ${parameter._tag}`,
);
this.parameter = parameter;
this.type = type;
if (
isOptional(type) &&
!containsUndefined(type)
)
throw new Error(
"Cannot use `Schema.optionalKey` with index signatures, use `Schema.optional` instead.",
);
}
};
/**
* Constructs a {@link Objects}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Objects = class extends ASTNodeImpl {
_tag = "Objects";
propertySignatures;
indexSignatures;
encodingChecks;
constructor(
propertySignatures,
indexSignatures,
annotations,
checks,
encoding,
context,
encodingChecks,
) {
super(
annotations,
checks,
encoding,
context,
);
this.propertySignatures =
propertySignatures;
this.indexSignatures =
indexSignatures;
this.encodingChecks =
encodingChecks;
}
/** @internal */
getParser(
compile,
compileField = compile,
) {
const ast = this;
const hasProperties =
ast.propertySignatures.length;
const indexCount =
ast.indexSignatures.length;
if (!hasProperties && !indexCount)
return fromRefinement(
ast,
isNotNullish,
);
let properties;
let indexes;
const compileMembers = () => {
if (!properties) {
properties =
ast.propertySignatures.map(
(ps) => ({
parser: compileField(
ps.type,
),
name: ps.name,
type: ps.type,
}),
);
indexes = indexCount
? ast.indexSignatures.map(
(is) => ({
is,
parserKey: compile(
parameterFromPropertyKey(
is.parameter,
),
),
parserValue:
compileField(is.type),
}),
)
: void 0;
}
return properties;
};
const makeFallback = () => {
const expectedKeys = new Set(
ast.propertySignatures.map(
(ps) =>
typeof ps.name === "number"
? globalThis.String(
ps.name,
)
: ps.name,
),
);
const finishIndex = (
s,
key,
k2,
inputValue,
exitValue,
) => {
if (
exitValue._tag === "Failure"
)
return (
wrapPropertyKeyIssue(
s,
ast,
key,
exitValue,
) ?? void_
);
const value =
exitValue === sameExit
? inputValue
: exitValue[args];
if (
k2 !== missing &&
value !== missing
) {
if (
hasProperties &&
(expectedKeys.has(key) ||
expectedKeys.has(
typeof k2 === "number"
? globalThis.String(
k2,
)
: k2,
))
)
return void_;
assignProperty(
s.out,
k2,
value,
);
}
return void_;
};
const parseIndex = (
s,
key,
index,
exitKey,
) => {
if (!exitKey) {
const eff = index.parserKey(
key,
s.options,
);
if (!effectIsExit(eff))
return flatMap(
exit(eff),
(exit) =>
parseIndex(
s,
key,
index,
exit,
),
);
exitKey = eff;
}
if (exitKey._tag === "Failure")
return (
wrapPropertyKeyIssue(
s,
ast,
key,
exitKey,
) ?? void_
);
const k2 =
exitKey === sameExit
? key
: exitKey[args];
const inputValue = s.input[key];
const result =
index.parserValue(
inputValue,
s.options,
);
return effectIsExit(result)
? finishIndex(
s,
key,
k2,
inputValue,
result,
)
: flatMap(
exit(result),
(exit) =>
finishIndex(
s,
key,
k2,
inputValue,
exit,
),
);
};
const parseStringIndex = (
s,
key,
index,
) => {
const inputValue = s.input[key];
const result =
index.parserValue(
inputValue,
s.options,
);
return effectIsExit(result)
? finishIndex(
s,
key,
key,
inputValue,
result,
)
: flatMap(
exit(result),
(exit) =>
finishIndex(
s,
key,
key,
inputValue,
exit,
),
);
};
const parseIndexes = indexCount
? iterateConcurrent()({
onItem: (
s,
[key, index],
) =>
index.is.parameter ===
string
? parseStringIndex(
s,
key,
index,
)
: parseIndex(
s,
key,
index,
),
step: (_s, _item, exit) =>
exit._tag === "Failure"
? exit
: void 0,
})
: void 0;
return fnUntracedEager(
function* (input, options) {
if (input === missing)
return missing;
if (
!(
typeof input ===
"object" &&
input !== null &&
!Array.isArray(input)
)
)
return yield* fail$1(
new InvalidType(
ast,
input,
options,
),
);
compileMembers();
const record = input;
const out = {};
const state = {
ast,
input: record,
out,
issues: void 0,
options,
};
const errorsAllOption =
options.errors === "all";
const onExcessPropertyError =
options.onExcessProperty ===
"error";
const concurrency =
options.concurrency ===
void 0
? 1
: resolveConcurrency(
options.concurrency,
);
const indexKeys =
indexCount &&
onExcessPropertyError
? ast.indexSignatures.map(
(index) =>
getIndexSignatureKeys(
record,
index.parameter,
options,
),
)
: void 0;
if (onExcessPropertyError) {
const coveredKeys =
indexKeys
? new Set(expectedKeys)
: expectedKeys;
if (indexKeys)
for (const keys of indexKeys)
for (const key of keys)
coveredKeys.add(key);
const inputKeys =
Reflect.ownKeys(record);
for (
let i = 0;
i < inputKeys.length;
i++
) {
const key = inputKeys[i];
if (
!coveredKeys.has(key) &&
Object.prototype.propertyIsEnumerable.call(
record,
key,
)
) {
const unexpected =
new UnexpectedKey(
ast,
record[key],
options,
);
const issue =
new Pointer(
[key],
unexpected,
);
if (errorsAllOption) {
if (state.issues)
state.issues.push(
issue,
);
else
state.issues = [
issue,
];
continue;
} else
return yield* fail$1(
new Composite(
ast,
[issue],
input,
options,
),
);
}
}
}
if (hasProperties) {
const eff =
concurrency === 1
? parseProperties(
state,
properties,
)
: parsePropertiesConcurrent(
state,
properties,
{ concurrency },
);
if (eff) yield* eff;
}
if (
indexCount &&
concurrency === 1
)
for (
let i = 0;
i < indexCount;
i++
) {
const index = indexes[i];
const parse =
index.is.parameter ===
string
? parseStringIndex
: parseIndex;
const keys =
indexKeys?.[i] ??
(index.is.parameter ===
string
? Object.keys(record)
: getIndexSignatureKeys(
record,
index.is
.parameter,
options,
));
for (
let j = 0;
j < keys.length;
j++
) {
const eff = parse(
state,
keys[j],
index,
);
if (!effectIsExit(eff))
yield* eff;
else if (
eff._tag === "Failure"
)
return yield* eff;
}
}
else if (parseIndexes) {
const keyPairs = empty$1();
for (
let i = 0;
i < indexCount;
i++
) {
const index = indexes[i];
const keys =
indexKeys?.[i] ??
(index.is.parameter ===
string
? Object.keys(record)
: getIndexSignatureKeys(
record,
index.is
.parameter,
options,
));
for (
let j = 0;
j < keys.length;
j++
)
keyPairs.push([
keys[j],
index,
]);
}
const eff = parseIndexes(
state,
keyPairs,
{ concurrency },
);
if (eff) yield* eff;
}
if (state.issues)
return yield* fail$1(
new Composite(
ast,
state.issues,
input,
options,
),
);
return out;
},
);
};
if (indexCount)
return makeFallback();
let fallback;
const resume = (
state,
index,
pending,
) => {
const property =
properties[index];
return flatMap(
exit(pending),
(exit) => {
const terminal = stepProperty(
state,
property,
exit,
);
if (terminal) return terminal;
const done = () =>
succeed(state.out);
const eff = parseProperties(
state,
properties.slice(index + 1),
);
return eff
? flatMapEager(eff, done)
: done();
},
);
};
return (input, options) => {
if (input === missing)
return missingExit;
if (
options.errors === "all" ||
options.onExcessProperty !==
void 0 ||
(options.concurrency !==
void 0 &&
resolveConcurrency(
options.concurrency,
) !== 1)
)
return (fallback ??=
makeFallback())(
input,
options,
);
if (
!(
typeof input === "object" &&
input !== null &&
!Array.isArray(input)
)
)
return fail$1(
new InvalidType(
ast,
input,
options,
),
);
const props = compileMembers();
const record = input;
const out = {};
const state = {
ast,
input: record,
out,
issues: void 0,
options,
};
try {
for (
let index = 0;
index < props.length;
index++
) {
const property = props[index];
const name = property.name;
const hasKey =
hasPropertySignature(
record,
name,
);
const value = hasKey
? record[name]
: missing;
const exit = property.parser(
value,
options,
);
if (!effectIsExit(exit))
return resume(
state,
index,
exit,
);
if (exit === sameExit) {
if (hasKey)
assignProperty(
out,
name,
value,
);
continue;
}
const terminal = stepProperty(
state,
property,
exit,
);
if (terminal) return terminal;
}
} catch (error) {
return die(error);
}
return succeed(out);
};
}
_rebuild(
recur,
recurParameter,
checks,
encodingChecks,
) {
const props = mapOrSame(
this.propertySignatures,
(ps) => {
const t = recur(ps.type);
return t === ps.type
? ps
: new PropertySignature(
ps.name,
t,
);
},
);
const indexes = mapOrSame(
this.indexSignatures,
(is) => {
const p = recurParameter(
is.parameter,
);
const t = recur(is.type);
return p === is.parameter &&
t === is.type
? is
: new IndexSignature(p, t);
},
);
return props ===
this.propertySignatures &&
indexes ===
this.indexSignatures &&
checks === this.checks &&
encodingChecks ===
this.encodingChecks
? this
: new Objects(
props,
indexes,
this.annotations,
checks,
void 0,
this.context,
encodingChecks,
);
}
/** @internal */
flip(recur) {
return this._rebuild(
recur,
recur,
this.encodingChecks,
this.checks,
);
}
/** @internal */
recur(recur, recurParameter = recur) {
return this._rebuild(
recur,
recurParameter,
this.checks,
this.encodingChecks,
);
}
/** @internal */
getExpected() {
if (
this.propertySignatures.length ===
0 &&
this.indexSignatures.length === 0
)
return "object | array";
return "object";
}
};
/** @internal */
function stepProperty(s, p, exit) {
if (exit._tag === "Failure")
return wrapPropertyKeyIssue(
s,
s.ast,
p.name,
exit,
);
if (exit === sameExit) return;
const value = exit[args];
if (value !== missing) {
assignProperty(
s.out,
p.name,
value,
);
return;
}
delete s.out[p.name];
if (!isOptional(p.type)) {
const issue = new Pointer(
[p.name],
new MissingKey(
p.type.context?.annotations,
),
);
if (s.options.errors === "all") {
if (s.issues)
s.issues.push(issue);
else s.issues = [issue];
return;
} else
return fail$2(
new Composite(
s.ast,
[issue],
s.input,
s.options,
),
);
}
}
const parsePropertiesOptions = {
onItem(s, p) {
if (
!hasPropertySignature(
s.input,
p.name,
)
)
return p.parser(
missing,
s.options,
);
const value = s.input[p.name];
assignProperty(
s.out,
p.name,
value,
);
return p.parser(value, s.options);
},
step: stepProperty,
};
/** @internal */
const parseProperties =
/*#__PURE__*/ iterateEager()(
parsePropertiesOptions,
);
const parsePropertiesConcurrent =
/*#__PURE__*/ iterateConcurrent()(
parsePropertiesOptions,
);
function combineChecks(a, b) {
if (!a) return b;
if (!b) return a;
return [...a, ...b];
}
/** @internal */
function struct(
fields,
checks,
annotations,
) {
return new Objects(
Reflect.ownKeys(fields).map(
(key) => {
return new PropertySignature(
key,
fields[key].ast,
);
},
),
[],
annotations,
checks,
);
}
/** @internal */
function getAST(self) {
return self.ast;
}
/** @internal */
function union(
members,
options,
checks,
) {
return new Union$1(
members.map(getAST),
options,
void 0,
checks,
);
}
/** @internal */
function mutable$1(ast) {
if (ast.encoding)
throw new Error(
"mutable does not support encodings",
);
return new Arrays(
true,
ast.elements,
ast.rest,
ast.annotations,
ast.checks,
void 0,
ast.context,
ast.encodingChecks,
);
}
const toCandidate =
/*#__PURE__*/ memoizeIdempotent(
(ast) => {
while (true) {
if (isSuspend(ast))
return unknown;
const encoding = ast.encoding;
if (!encoding)
return (
ast.recur?.(
toCandidate,
identity,
) ?? ast
);
if (
encoding.some(
(link) =>
link.transformation
._tag ===
"Middleware" &&
link.transformation
.decode !== identity,
)
)
return unknown;
ast =
encoding[encoding.length - 1]
.to;
}
},
);
function getCandidateTypes(ast) {
switch (ast._tag) {
case "Null":
return ["null"];
case "Undefined":
return ["undefined"];
case "String":
case "TemplateLiteral":
return ["string"];
case "Number":
return ["number"];
case "Boolean":
return ["boolean"];
case "Symbol":
case "UniqueSymbol":
return ["symbol"];
case "BigInt":
return ["bigint"];
case "Arrays":
return ["array"];
case "ObjectKeyword":
return [
"object",
"array",
"function",
];
case "Objects":
return ast.propertySignatures
.length ||
ast.indexSignatures.length
? ["object"]
: [
"string",
"number",
"boolean",
"symbol",
"bigint",
"object",
"array",
"function",
];
case "Enum":
return Array.from(
new Set(
ast.enums.map(
([, v]) => typeof v,
),
),
);
case "Literal":
return [typeof ast.literal];
case "Union":
return Array.from(
new Set(
ast.types.flatMap(
getCandidateTypes,
),
),
);
default:
return [
"null",
"undefined",
"string",
"number",
"boolean",
"symbol",
"bigint",
"object",
"array",
"function",
];
}
}
/** @internal */
function collectSentinels(ast) {
switch (ast._tag) {
default:
return [];
case "Declaration": {
const s =
ast.annotations?.[
SENTINELS_ANNOTATION_KEY
];
return Array.isArray(s) ? s : [];
}
case "Objects":
return ast.propertySignatures.flatMap(
(ps) => {
const type = ps.type;
if (!isOptional(type)) {
if (isLiteral(type))
return [
{
key: ps.name,
literal: type.literal,
},
];
if (isUniqueSymbol(type))
return [
{
key: ps.name,
literal: type.symbol,
},
];
}
return [];
},
);
case "Arrays":
return ast.elements.flatMap(
(e, i) => {
if (!isOptional(e)) {
if (isLiteral(e))
return [
{
key: i,
literal: e.literal,
},
];
if (isUniqueSymbol(e))
return [
{
key: i,
literal: e.symbol,
},
];
}
return [];
},
);
case "Union": {
if (ast.types.length === 0)
return [];
const members = ast.types.map(
(type) =>
collectSentinels(
toCandidate(type),
),
);
return members[0].filter((s) =>
members.every((sentinels) =>
sentinels.some(
(o) =>
o.key === s.key &&
o.literal === s.literal,
),
),
);
}
case "Suspend":
return collectSentinels(
ast.thunk(),
);
}
}
const candidateIndexCache =
/*#__PURE__*/ new WeakMap();
const emptyCandidates =
/*#__PURE__*/ Object.freeze([]);
const getRuntimeType = (input) =>
input === null
? "null"
: Array.isArray(input)
? "array"
: typeof input;
const hasPropertySignature = (
input,
key,
) =>
key === "__proto__"
? Object.hasOwn(input, key)
: key in input;
/** @internal */
function getCandidateIndex(types) {
let index =
candidateIndexCache.get(types);
if (index) return index;
let bySentinel;
let sentinelCandidateCount = 0;
let otherwise;
let literalCandidates;
let onlyLiterals = true;
const literalOf = [];
for (
let i = 0;
i < types.length;
i++
) {
const a = types[i];
const encoded = toCandidate(a);
if (isNever(encoded)) continue;
if (
isLiteral(encoded) ||
isUniqueSymbol(encoded)
) {
literalCandidates ??=
/* @__PURE__ */ new Map();
const literal = isLiteral(encoded)
? encoded.literal
: encoded.symbol;
literalOf[i] = literal;
let arr =
literalCandidates.get(literal);
if (!arr)
literalCandidates.set(
literal,
(arr = []),
);
arr.push(i);
} else onlyLiterals = false;
const sentinels =
collectSentinels(encoded);
if (sentinels.length) {
bySentinel ??=
/* @__PURE__ */ new Map();
sentinelCandidateCount++;
for (const {
key,
literal,
} of sentinels) {
let entry = bySentinel.get(key);
if (!entry)
bySentinel.set(
key,
(entry = [
/* @__PURE__ */ new Map(),
/* @__PURE__ */ new Set(),
]),
);
entry[1].add(i);
let indexes =
entry[0].get(literal);
if (!indexes)
entry[0].set(
literal,
(indexes =
/* @__PURE__ */ new Set()),
);
indexes.add(i);
}
} else {
otherwise ??= {};
const candidateTypes =
getCandidateTypes(encoded);
for (const t of candidateTypes)
(otherwise[t] ??= []).push(i);
}
}
const fallbacks = {};
const getFallback = (type) =>
(fallbacks[type] ??= Object.freeze(
otherwise?.[type] ??
emptyCandidates,
));
if (
onlyLiterals &&
literalCandidates
) {
literalCandidates.forEach(
Object.freeze,
);
index = (input) =>
literalCandidates.get(input) ??
emptyCandidates;
} else if (
bySentinel?.size === 1 &&
!otherwise
) {
const [key, [byValue]] = bySentinel
.entries()
.next().value;
const candidates =
/* @__PURE__ */ new Map();
for (const [
literal,
indexes,
] of byValue)
candidates.set(
literal,
Object.freeze(
Array.from(indexes),
),
);
const all = Object.freeze(
types.map((_, i) => i),
);
index = (input, isConstructor) => {
if (isObjectKeyword(input)) {
const value =
hasPropertySignature(
input,
key,
)
? input[key]
: void 0;
if (value !== void 0)
return (
candidates.get(value) ??
emptyCandidates
);
if (isConstructor) return all;
}
return emptyCandidates;
};
} else if (bySentinel) {
let commonSentinel;
for (const entry of bySentinel)
if (
(!commonSentinel ||
entry[1][0].size >
commonSentinel[1][0]
.size) &&
entry[1][1].size ===
sentinelCandidateCount
)
commonSentinel = entry;
index = (input, isConstructor) => {
const runtimeType =
getRuntimeType(input);
if (!isObjectKeyword(input))
return getFallback(runtimeType);
const selected = new Set(
otherwise?.[runtimeType],
);
let directKey;
if (commonSentinel) {
const [key, [byValue]] =
commonSentinel;
const hasKey =
hasPropertySignature(
input,
key,
);
const value = hasKey
? input[key]
: void 0;
if (
hasKey &&
(!isConstructor ||
value !== void 0)
) {
const match =
byValue.get(value);
if (!match)
return getFallback(
runtimeType,
);
for (const i of match)
selected.add(i);
directKey = key;
}
}
if (directKey === void 0)
for (const [
key,
[byValue, all],
] of bySentinel) {
const hasKey =
hasPropertySignature(
input,
key,
);
const value = hasKey
? input[key]
: void 0;
if (
hasKey &&
(!isConstructor ||
value !== void 0)
) {
const match =
byValue.get(value);
if (match)
for (const i of match)
selected.add(i);
} else if (isConstructor)
for (const i of all)
selected.add(i);
}
for (const [
key,
[byValue, all],
] of bySentinel) {
if (key === directKey) continue;
const hasKey =
hasPropertySignature(
input,
key,
);
const value = hasKey
? input[key]
: void 0;
if (
hasKey &&
(!isConstructor ||
value !== void 0)
) {
const match =
byValue.get(value);
for (const i of selected)
if (
all.has(i) &&
!match?.has(i)
)
selected.delete(i);
}
}
return Array.from(selected).sort(
(a, b) => a - b,
);
};
} else
index = (input) => {
const fallback = getFallback(
getRuntimeType(input),
);
return literalCandidates
? fallback.filter(
(i) =>
literalOf[i] === void 0 ||
literalOf[i] === input,
)
: fallback;
};
candidateIndexCache.set(types, index);
return index;
}
/**
* Constructs a {@link Union}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Union$1 = class extends ASTNodeImpl {
_tag = "Union";
types;
options;
encodingChecks;
constructor(
types,
options,
annotations,
checks,
encoding,
context,
encodingChecks,
) {
super(
annotations,
checks,
encoding,
context,
);
this.types = types;
this.options = options;
this.encodingChecks =
encodingChecks;
}
/** @internal */
getParser(compile, compileField) {
const ast = this;
const isConstructor =
compileField !== void 0;
const parsers = [];
const parser = (i) =>
(parsers[i] ??= compile(
ast.types[i],
));
let index;
return (input, options) => {
if (input === missing)
return missingExit;
const candidates = (index ??=
getCandidateIndex(ast.types))(
input,
isConstructor,
);
if (candidates.length === 0)
return fail$1(
new AnyOf(
ast,
[],
input,
options,
),
);
if (candidates.length === 1) {
const result = parser(
candidates[0],
)(input, options);
if (result._tag === "Success")
return result;
return effectIsExit(result)
? failSingleUnionCandidate(
ast,
result.cause,
input,
options,
)
: catchSingleUnionCandidate(
ast,
result,
input,
options,
);
}
return parseUnionCandidates(
ast,
parser,
candidates,
input,
options,
);
};
}
_rebuild(
recur,
checks,
encodingChecks,
) {
const types = mapOrSame(
this.types,
recur,
);
return types === this.types &&
checks === this.checks &&
encodingChecks ===
this.encodingChecks
? this
: new Union$1(
types,
this.options,
this.annotations,
checks,
void 0,
this.context,
encodingChecks,
);
}
/** @internal */
recur(recur) {
return this._rebuild(
recur,
this.checks,
this.encodingChecks,
);
}
/** @internal */
flip(recur) {
return this._rebuild(
recur,
this.encodingChecks,
this.checks,
);
}
/** @internal */
matchPart(s, options) {
for (const type of this.types) {
const out = type.matchPart(
s,
options,
);
if (out !== void 0) return out;
}
}
/** @internal */
getExpected(getExpected) {
const expected =
this.annotations?.expected;
if (typeof expected === "string")
return expected;
if (this.types.length === 0)
return "never";
const types = this.types.map(
(type) => {
const encoded = toEncoded(type);
switch (encoded._tag) {
case "Arrays": {
const literals =
encoded.elements.filter(
isLiteral,
);
if (literals.length > 0)
return `${formatIsMutable(encoded.isMutable)}[ ${literals.map((e) => getExpected(e) + formatIsOptional(e.context?.isOptional)).join(", ")}, ... ]`;
break;
}
case "Objects": {
const literals =
encoded.propertySignatures.filter(
(ps) =>
isLiteral(ps.type),
);
if (literals.length > 0)
return `{ ${literals.map((ps) => `${formatIsMutable(ps.type.context?.isMutable)}${formatPropertyKey(ps.name)}${formatIsOptional(ps.type.context?.isOptional)}: ${getExpected(ps.type)}`).join(", ")}, ... }`;
break;
}
}
return getExpected(encoded);
},
);
return Array.from(
new Set(types),
).join(" | ");
}
};
function failSingleUnionCandidate(
ast,
cause,
input,
options,
) {
const issue = getSchemaIssue(cause);
if (!issue) return failCause(cause);
return fail$2(
new AnyOf(
ast,
[issue],
input,
options,
),
);
}
function catchSingleUnionCandidate(
ast,
result,
input,
options,
) {
return catchCause(result, (cause) =>
failSingleUnionCandidate(
ast,
cause,
input,
options,
),
);
}
function parseUnionCandidates(
ast,
parser,
candidates,
input,
options,
) {
const state = {
ast,
parser,
input,
out: void 0,
successes:
ast.options?.mode === "oneOf"
? []
: void 0,
issues: void 0,
options,
};
const eff = parseUnion(
state,
candidates,
);
if (!eff) {
if (state.out) return state.out;
return fail$1(
new AnyOf(
ast,
state.issues ?? [],
input,
options,
),
);
}
if (effectIsExit(eff))
return resumeUnion(eff, state);
let first = true;
return suspend(() => {
if (!first)
return parseUnionCandidates(
ast,
parser,
candidates,
input,
options,
);
first = false;
return resumeUnion(eff, state);
});
}
function resumeUnion(eff, state) {
return flatMapEager(eff, (_) => {
if (state.out === sameExit)
return succeed$1(state.input);
if (state.out) return state.out;
return fail$1(
new AnyOf(
state.ast,
state.issues ?? [],
state.input,
state.options,
),
);
});
}
const parseUnion =
/*#__PURE__*/ iterateEager()({
onItem(s, i) {
return s.parser(i)(
s.input,
s.options,
);
},
step(s, i, exit) {
if (exit._tag === "Failure") {
const issue = getSchemaIssue(
exit.cause,
);
if (issue === void 0)
return exit;
if (s.issues)
s.issues.push(issue);
else s.issues = [issue];
} else {
if (s.out && s.successes) {
s.successes.push(
s.ast.types[i],
);
return fail$2(
new OneOf(
s.ast,
s.successes,
s.input,
s.options,
),
);
}
s.out = exit;
if (s.successes)
s.successes.push(
s.ast.types[i],
);
else return void_;
}
},
});
const nonFiniteLiterals =
/*#__PURE__*/ new Union$1([
/*#__PURE__*/ new Literal$1(
"Infinity",
),
/*#__PURE__*/ new Literal$1(
"-Infinity",
),
/*#__PURE__*/ new Literal$1("NaN"),
]);
function formatIsMutable(isMutable) {
return isMutable ? "" : "readonly ";
}
function formatIsOptional(isOptional) {
return isOptional ? "?" : "";
}
/**
* Constructs a {@link Filter}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Filter = class extends Class$1 {
_tag = "Filter";
run;
annotations;
/**
* Whether the parsing process should be aborted after this check has failed.
*/
aborted;
constructor(
run,
annotations = void 0,
aborted = false,
) {
super();
this.run = run;
this.annotations = annotations;
this.aborted = aborted;
}
annotate(annotations) {
return new Filter(
this.run,
{
...this.annotations,
...annotations,
},
this.aborted,
);
}
abort() {
return new Filter(
this.run,
this.annotations,
true,
);
}
and(other, annotations) {
return new FilterGroup(
[this, other],
annotations,
);
}
};
/**
* Constructs a {@link FilterGroup}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const FilterGroup = class extends Class$1 {
_tag = "FilterGroup";
checks;
annotations;
constructor(
checks,
annotations = void 0,
) {
super();
this.checks = checks;
this.annotations = annotations;
}
annotate(annotations) {
return new FilterGroup(
this.checks,
{
...this.annotations,
...annotations,
},
);
}
and(other, annotations) {
return new FilterGroup(
[this, other],
annotations,
);
}
};
/** @internal */
function makeFilter$1(
filter,
annotations,
aborted = false,
) {
return new Filter(
(input, ast, options) =>
normalizeFilterOutput(
ast,
filter(input, ast, options),
input,
options,
),
annotations,
aborted,
);
}
/** @internal */
function isFinite(annotations) {
return makeFilter$1(
(n) =>
globalThis.Number.isFinite(n),
{
expected: "a finite number",
representation: {
id: "effect/schema/isFinite",
payload: null,
},
toJsonSchema: () => ({
type: "number",
}),
toCode: () => ({
runtime: "Schema.isFinite()",
}),
arbitraryConstraint: {
number: "finite",
},
...annotations,
},
);
}
const numberToJson =
/*#__PURE__*/ new Link(
/*#__PURE__*/ new Union$1([
/* @__PURE__ */ appendChecks(
number,
[/*#__PURE__*/ isFinite()],
),
nonFiniteLiterals,
]),
/*#__PURE__*/ new Transformation(
/*#__PURE__*/ Number$3(),
/*#__PURE__*/ transform$1((n) =>
globalThis.Number.isFinite(n)
? n
: globalThis.String(n),
),
),
);
/**
* Creates a {@link Filter} that validates strings by running `RegExp.test`.
*
* **When to use**
*
* Use when string validation should be represented as a schema `Filter` backed
* by a regular expression.
*
* **Details**
*
* The filter can be used with `Schema.filter` or attached directly to a
* `String` AST node through checks. The regular expression is cloned and its
* `lastIndex` is reset before each test, so global and sticky expressions are
* deterministic and the provided regular expression is not mutated. The
* regular expression source is stored in annotations for serialization and
* arbitrary generation.
*
* **Gotchas**
*
* Arbitrary metadata preserves both `regExp.source` and `regExp.flags`.
* Implementations that cannot consume all flags may still use the source as a
* generation hint because the Schema filter validates every generated value.
* JSON Schema has no way to carry JavaScript regular-expression flags. Unless
* annotations provide `toJsonSchema`, the RegExp constraint is omitted from
* JSON Schema export.
*
* **Example** (Validating an email pattern)
*
* ```ts import.meta.vitest
* import { SchemaAST } from "effect"
*
* const emailFilter = SchemaAST.isPattern(/^[^@]+@[^@]+$/)
* emailFilter.run("alice@example.com", SchemaAST.string, {}) // => undefined
* emailFilter.run("invalid", SchemaAST.string, {})?._tag // => "InvalidValue"
* ```
*
* @see {@link Filter}
* @stability stable
* @category constructors
* @since 4.0.0
*/
function isPattern$1(
regExp,
annotations,
) {
const copy = new globalThis.RegExp(
regExp,
);
const payload = {
source: copy.source,
flags: copy.flags,
};
return makeFilter$1(
(s) => {
copy.lastIndex = 0;
return copy.test(s);
},
{
expected: `a string matching the RegExp ${payload.source}`,
representation: {
id: "effect/schema/isPattern",
payload,
},
toJsonSchema: () => [{}, true],
arbitraryConstraint: {
patterns: [payload],
},
...annotations,
},
);
}
const bodyOwners =
/*#__PURE__*/ new WeakMap();
function copy(ast, changes) {
const out = Object.assign(
Object.create(
Object.getPrototypeOf(ast),
),
ast,
changes,
);
if (
Reflect.ownKeys(changes).every(
(key) =>
key === "context" ||
key === "encoding",
)
)
bodyOwners.set(
out,
getContextOwner(ast),
);
return out;
}
/** @internal */
function getContextOwner(ast) {
const existing = bodyOwners.get(ast);
if (existing !== void 0)
return existing;
if (ast.encoding === void 0)
return ast;
const owner = Object.assign(
Object.create(
Object.getPrototypeOf(ast),
),
ast,
{ encoding: void 0 },
);
bodyOwners.set(ast, owner);
return owner;
}
/** @internal */
function replaceEncoding(
ast,
encoding,
) {
return ast.encoding === encoding
? ast
: copy(ast, { encoding });
}
/** @internal */
function replaceContext(ast, context) {
if (ast.context === context)
return ast;
const owner = getContextOwner(ast);
if (
owner.context === context &&
owner.encoding === ast.encoding
)
return owner;
return copy(ast, { context });
}
/** @internal */
function getLastEncoding(ast) {
return ast.encoding
? getLastEncoding(
ast.encoding[
ast.encoding.length - 1
].to,
)
: ast;
}
/** @internal */
function annotate(ast, annotations) {
if (ast.checks) {
const last =
ast.checks[ast.checks.length - 1];
return replaceChecks(
ast,
append(
ast.checks.slice(0, -1),
last.annotate(annotations),
),
);
}
return copy(ast, {
annotations: {
...ast.annotations,
...annotations,
},
});
}
/** @internal */
function replaceChecks(ast, checks) {
if (ast._tag === "Suspend" && checks)
throw new Error(
"Cannot add checks to Suspend",
);
if (ast.checks === checks) return ast;
return copy(ast, { checks });
}
/** @internal */
function appendChecks(ast, checks) {
return replaceChecks(
ast,
combineChecks(ast.checks, checks),
);
}
/** @internal */
function mapLink(link, f) {
const to = f(link.to);
return to === link.to
? link
: new Link(to, link.transformation);
}
function updateLastLink(encoding, f) {
const links = encoding;
const last = links[links.length - 1];
const out = mapLink(last, f);
return out === last
? encoding
: append(
encoding.slice(
0,
encoding.length - 1,
),
out,
);
}
/** @internal */
function applyToSelfOrLastLinkEncodingIdempotent(
f,
options,
) {
function out(ast) {
if (ast.encoding) {
const last =
ast.encoding[
ast.encoding.length - 1
];
return options?.stopAt?.(last)
? ast
: replaceEncoding(
ast,
updateLastLink(
ast.encoding,
out,
),
);
}
return f(ast);
}
return memoizeIdempotent(out);
}
function appendTransformation(
from,
transformation,
to,
) {
const link = new Link(
from,
transformation,
);
return replaceEncoding(
to,
to.encoding
? [...to.encoding, link]
: [link],
);
}
function mapOrSame(as, f) {
let out;
for (let i = 0; i < as.length; i++) {
const a = as[i];
const fa = f(a);
if (out) out[i] = fa;
else if (fa !== a) {
out = new Array(as.length);
for (let j = 0; j < i; j++)
out[j] = as[j];
out[i] = fa;
}
}
return out ?? as;
}
/** @internal */
function annotateKey(ast, annotations) {
return replaceContext(
ast,
ast.context
? new Context(
ast.context.isOptional,
ast.context.isMutable,
ast.context
.constructorDefault,
{
...ast.context.annotations,
...annotations,
},
)
: new Context(
false,
false,
void 0,
annotations,
),
);
}
/**
* Attaches a `Transformation` to the `to` AST, making it decode from the
* `from` AST and encode back to it.
*
* **Details**
*
* This is the low-level primitive behind `Schema.decodeTo`. It appends a
* {@link Link} to the `to` node's encoding chain.
*
* - Returns a new AST with the same type as `to`.
*
* @see {@link Link}
* @see {@link Encoding}
* @see {@link flip}
* @stability stable
* @category transforming
* @since 4.0.0
*/
function decodeTo$1(
from,
to,
transformation,
) {
return appendTransformation(
from,
transformation,
to,
);
}
/**
* Returns `true` if the AST node represents an optional property.
*
* **Details**
*
* Checks `ast.context?.isOptional`. Defaults to `false` when no
* {@link Context} is set.
*
* @see `Schema.optionalKey`
* @see {@link Context}
* @stability stable
* @category predicates
* @since 4.0.0
*/
function isOptional(ast) {
return (
ast.context?.isOptional ?? false
);
}
function isStructuralCheck(check) {
return (
check.annotations?.[
"~structural"
] === true ||
(check._tag === "FilterGroup" &&
check.checks.every(
isStructuralCheck,
))
);
}
function extractStructuralChecks(
checks,
) {
function extract(check) {
if (isStructuralCheck(check))
return [check];
return check._tag === "FilterGroup"
? check.checks.flatMap(extract)
: [];
}
const out = checks.flatMap(extract);
return isArrayNonEmpty(out)
? out
: void 0;
}
function canPreserveEncodingChecks(
ast,
) {
let preserve = true;
function visit(child) {
preserve =
preserve &&
!child.encoding &&
!isSuspend(child);
if (preserve && "recur" in child)
child.recur(visit);
return child;
}
if ("recur" in ast) ast.recur(visit);
return preserve;
}
/**
* Strips all encoding transformations from an AST, returning the decoded
* (type-level) representation.
*
* **Details**
*
* - Memoized: same input reference → same output reference.
* - Recursively walks into composite nodes ({@link Arrays}, {@link Objects},
* {@link Union}, {@link Suspend}).
*
* **Example** (Getting the type AST)
*
* ```ts import.meta.vitest
* import { Schema, SchemaAST } from "effect"
*
* const schema = Schema.NumberFromString
* const typeAst = SchemaAST.toType(schema.ast)
* typeAst._tag // => "Number"
* ```
*
* @see {@link toEncoded}
* @see {@link flip}
* @stability stable
* @category transforming
* @since 4.0.0
*/
const toType =
/*#__PURE__*/ memoizeIdempotent(
(ast) => {
const owner =
getContextOwner(ast);
if (owner !== ast) {
const type = toType(owner);
return type === owner &&
ast.encoding === void 0
? ast
: replaceContext(
type,
ast.context,
);
}
const type =
"recur" in ast
? ast.recur(toType)
: ast;
if (
"encodingChecks" in type &&
type.encodingChecks
) {
const checks =
canPreserveEncodingChecks(ast)
? type.encodingChecks
: isArrays(type) ||
isObjects(type) ||
(isDeclaration(type) &&
type.typeParameters
.length > 0)
? extractStructuralChecks(
type.encodingChecks,
)
: void 0;
return copy(type, {
encodingChecks: void 0,
checks: combineChecks(
type.checks,
checks,
),
});
}
return type;
},
);
/**
* Returns the encoded (wire-format) AST by flipping and then stripping
* encodings.
*
* **Details**
*
* Equivalent to `toType(flip(ast))`. This gives you the AST that describes
* the shape of the serialized/encoded data.
*
* - Memoized: same input reference → same output reference.
*
* **Example** (Getting the encoded AST)
*
* ```ts import.meta.vitest
* import { Schema, SchemaAST } from "effect"
*
* const schema = Schema.NumberFromString
* const encodedAst = SchemaAST.toEncoded(schema.ast)
* encodedAst._tag // => "String"
* ```
*
* @see {@link toType}
* @see {@link flip}
* @stability stable
* @category transforming
* @since 4.0.0
*/
const toEncoded =
/*#__PURE__*/ memoizeIdempotent(
(ast) => {
return toType(flip(ast));
},
);
function flipEncoding(ast, encoding) {
const links = encoding;
const len = links.length;
const last = links[len - 1];
const ls = [
new Link(
flip(
replaceEncoding(ast, void 0),
),
links[0].transformation.flip(),
),
];
for (let i = 1; i < len; i++)
ls.unshift(
new Link(
flip(links[i - 1].to),
links[i].transformation.flip(),
),
);
const to = flip(last.to);
if (to.encoding)
return replaceEncoding(to, [
...to.encoding,
...ls,
]);
else return replaceEncoding(to, ls);
}
/**
* Swaps the decode and encode directions of an AST's {@link Encoding} chain.
*
* **Details**
*
* After flipping, what was decoding becomes encoding and vice versa. This is
* the core operation behind `Schema.encode` — encoding a value is decoding
* with a flipped SchemaAST.
*
* - Memoized: same input reference → same output reference.
* - Recursively walks composite nodes.
*
* @see {@link toType}
* @see {@link toEncoded}
* @stability stable
* @category transforming
* @since 4.0.0
*/
const flip = /*#__PURE__*/ memoize(
(ast) => {
if (ast.encoding)
return flipEncoding(
ast,
ast.encoding,
);
const owner = getContextOwner(ast);
if (owner !== ast) {
const flipped = flip(owner);
return flipped === owner
? ast
: replaceContext(
flipped,
ast.context,
);
}
return "flip" in ast
? ast.flip(flip)
: "recur" in ast
? ast.recur(flip)
: ast;
},
);
/** @internal */
function containsUndefined(ast) {
switch (ast._tag) {
case "Undefined":
return true;
case "Union":
return ast.types.some(
containsUndefined,
);
default:
return false;
}
}
function fromConst(ast, value) {
const succeed$6 =
value === 0
? sameExit
: succeed(value);
return (input, options) => {
if (input === missing)
return missingExit;
if (input === value)
return succeed$6;
return fail$1(
new InvalidType(
ast,
input,
options,
),
);
};
}
function fromRefinement(
ast,
refinement,
) {
return (input, options) => {
if (input === missing)
return missingExit;
if (refinement(input))
return sameExit;
return fail$1(
new InvalidType(
ast,
input,
options,
),
);
};
}
/** @internal */
const parameterFromPropertyKey =
/*#__PURE__*/ applyToSelfOrLastLinkEncodingIdempotent(
(ast) => {
switch (ast._tag) {
default:
return ast;
case "Number":
return ast.toCodecStringTree();
case "Union":
return ast.recur(
parameterFromPropertyKey,
);
}
},
);
const isStringFiniteRegExp =
/*#__PURE__*/ new globalThis.RegExp(
`^${FINITE_PATTERN}$`,
);
const isStringNumberRegExp =
/*#__PURE__*/ new globalThis.RegExp(
`^(?:${FINITE_PATTERN}|Infinity|-Infinity|NaN)$`,
);
/** @internal */
function isStringFinite(annotations) {
return isPattern$1(
isStringFiniteRegExp,
{
expected:
"a string representing a finite number",
representation: {
id: "effect/schema/isStringFinite",
payload: null,
},
toJsonSchema: () => ({
pattern:
isStringFiniteRegExp.source,
}),
...annotations,
},
);
}
const finiteString =
/*#__PURE__*/ appendChecks(string, [
/*#__PURE__*/ isStringFinite(),
]);
const finiteToString =
/*#__PURE__*/ new Link(
finiteString,
numberFromString,
);
const numberToString =
/*#__PURE__*/ new Link(
/*#__PURE__*/ new Union$1([
finiteString,
nonFiniteLiterals,
]),
numberFromString,
);
/** @internal */
function collectIssues(
checks,
value,
issues,
ast,
options,
) {
for (
let i = 0;
i < checks.length;
i++
) {
const check = checks[i];
if (check._tag === "FilterGroup") {
issues = collectIssues(
check.checks,
value,
issues,
ast,
options,
);
if (
issues &&
(options.errors !== "all" ||
issues[issues.length - 1]
.filter.aborted)
)
return issues;
} else {
const issue = check.run(
value,
ast,
options,
);
if (issue) {
const filter = new Filter$1(
check,
issue,
value,
options,
);
if (issues) issues.push(filter);
else issues = [filter];
if (
options.errors !== "all" ||
check.aborted
)
return issues;
}
}
}
return issues;
}
/** @internal */
function getConstructorDescriptor(ast) {
if (!isDeclaration(ast))
return void 0;
const getDescriptor =
ast.annotations?.[
CONSTRUCTOR_ANNOTATION_KEY
];
return isFunction(getDescriptor)
? getDescriptor(ast.typeParameters)
: void 0;
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/schema/interpreter.js
const flatMapTransformation = (
result,
current,
f,
) =>
result === sameExit
? f(current)
: flatMapEager(result, f);
function compileTransformation(
transformation,
) {
if (
transformation._tag === "Middleware"
)
return (
result,
current,
options,
) => {
const transformed =
result === sameExit
? transformation.decode(
succeed(
toOption(current),
),
options,
)
: transformation.decode(
mapEager(
result,
toOption,
),
options,
);
return fromOptionalEffect(
transformed,
);
};
const getter = transformation.decode;
switch (getter._tag) {
case "Passthrough":
return (result, current) =>
result === sameExit
? succeed(current)
: result;
case "Transform": {
const transform = (value) =>
value === missing
? missingExit
: succeed(
getter.transform(value),
);
return (result, current) =>
flatMapTransformation(
result,
current,
transform,
);
}
case "TransformOptional": {
const transform = (value) =>
fromOptionExit(
getter.transform(
toOption(value),
),
);
return (result, current) =>
flatMapTransformation(
result,
current,
transform,
);
}
case "TransformEffect":
return (
result,
current,
options,
) =>
flatMapTransformation(
result,
current,
(value) =>
value === missing
? missingExit
: getter.transform(
value,
options,
),
);
case "TransformOptionalEffect":
return (
result,
current,
options,
) =>
flatMapTransformation(
result,
current,
(value) =>
fromOptionalEffect(
getter.transform(
toOption(value),
options,
),
),
);
}
}
const fromOptionalEffect = (effect) =>
flatMapEager(effect, fromOptionExit);
/** @internal */
const wrapEncoding = (
ast,
input,
options,
effect,
) =>
catchCause(effect, (cause) =>
failCauseSync(() =>
map(
cause,
(issue) =>
new Encoding(
ast,
issue,
input,
options,
),
),
),
);
function makeConstructorParser(
descriptor,
compile,
) {
const transform =
compileTransformation(
descriptor.link.transformation,
);
let sourceParser;
return (input, options) => {
if (input === missing)
return missingExit;
if (descriptor.isConstructed(input))
return sameExit;
const result = (sourceParser ??=
compile(descriptor.link.to))(
input,
options,
);
return transform(
result,
input,
options,
);
};
}
function withDefault(ast, parser) {
const defaultValue =
ast.context.constructorDefault;
return (input, options) => {
if (
input !== missing &&
input !== void 0
)
return parser(input, options);
const result = defaultValue;
if (
effectIsExit(result) &&
result._tag === "Success"
) {
const local = parser(
result[args],
options,
);
return local === sameExit
? result
: local;
}
return flatMapEager(
wrapEncoding(
ast,
input,
options,
result,
),
(value) => {
const local = parser(
value,
options,
);
return local === sameExit
? succeed(value)
: local;
},
);
};
}
/** @internal */
function compileField(ast, compile) {
const parser = compile(ast);
return ast.context
?.constructorDefault === void 0
? parser
: withDefault(ast, parser);
}
/** @internal */
function compile(
ast,
compile,
compileField,
base,
specialize,
) {
if (ast._tag === "Declaration")
for (const parameter of ast.typeParameters)
compile(parameter);
const descriptor = compileField
? getConstructorDescriptor(ast)
: void 0;
const parser = descriptor
? makeConstructorParser(
descriptor,
compile,
)
: (base ??
ast.getParser(
compile,
compileField,
));
const checks = ast.checks;
const links = ast.encoding;
const transformations = links?.map(
(link) =>
compileTransformation(
link.transformation,
),
);
const encodingChecks =
ast.encodingChecks;
if (
!links &&
!checks &&
!encodingChecks
)
return parser;
let encodingParsers;
const parseChecks = (
input,
options,
) => {
let result = parser(input, options);
if (
encodingChecks &&
!options.disableChecks
) {
if (effectIsExit(result)) {
if (result._tag === "Success") {
const output =
result === sameExit
? input
: result[args];
if (
input !== missing &&
output !== missing
) {
const issues =
collectIssues(
encodingChecks,
input,
void 0,
ast,
options,
);
if (issues)
result = fail$1(
new Composite(
ast,
issues,
input,
options,
),
);
}
}
} else
result = flatMap(
result,
(value) => {
if (
input !== missing &&
value !== missing
) {
const issues =
collectIssues(
encodingChecks,
input,
void 0,
ast,
options,
);
if (issues)
return fail$1(
new Composite(
ast,
issues,
input,
options,
),
);
}
return succeed$1(value);
},
);
}
if (
checks &&
!options.disableChecks
) {
if (effectIsExit(result)) {
if (result._tag === "Success") {
const value =
result === sameExit
? input
: result[args];
if (value === missing)
return result;
const issues = collectIssues(
checks,
value,
void 0,
ast,
options,
);
if (issues)
result = fail$1(
new Composite(
ast,
issues,
value,
options,
),
);
}
} else
result = flatMap(
result,
(value) => {
if (value !== missing) {
const issues =
collectIssues(
checks,
value,
void 0,
ast,
options,
);
if (issues)
return fail$1(
new Composite(
ast,
issues,
value,
options,
),
);
}
return succeed$1(value);
},
);
}
return result;
};
const parseLocal =
specialize === void 0
? parseChecks
: specialize(parseChecks);
if (!links) return parseLocal;
return (input, options) => {
const parsers = (encodingParsers ??=
links.map((link) =>
compile(link.to),
));
let current = input;
let result = parsers[
parsers.length - 1
](input, options);
for (
let i = links.length - 1;
i >= 0;
i--
) {
result = transformations[i](
result,
current,
options,
);
if (i !== 0) {
const next = parsers[i - 1];
if (result._tag === "Success") {
current = result[args];
result = next(
current,
options,
);
} else
result = flatMapEager(
result,
(value) => {
const nextResult = next(
value,
options,
);
return nextResult ===
sameExit
? succeed(value)
: nextResult;
},
);
}
}
if (result._tag === "Success") {
const value = result[args];
const local = parseLocal(
value,
options,
);
return local === sameExit
? result
: local;
}
result = wrapEncoding(
ast,
input,
options,
result,
);
return flatMapEager(
result,
(value) => {
const local = parseLocal(
value,
options,
);
return local === sameExit
? succeed(value)
: local;
},
);
};
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/schema/compilerRegistry.js
/** @internal */
const invalid = /*#__PURE__*/ Symbol();
const cache =
/*#__PURE__*/ new WeakMap();
const decodeChild = (ast) =>
resolve(ast).parser;
const makeChild = (ast) =>
resolve(ast).makeEffect;
const makeField = (ast) =>
compileField(ast, makeChild);
var InterpretedEntry = class {
ast;
constructor(ast) {
this.ast = ast;
}
get decodeEffect() {
return (this.cachedDecodeEffect ??=
compile(this.ast, decodeChild));
}
get parser() {
return this.decodeEffect;
}
get makeEffect() {
return (this.cachedMakeEffect ??=
compile(
this.ast,
makeChild,
makeField,
));
}
};
/** @internal */
function resolve(ast) {
const cached = cache.get(ast);
if (cached !== void 0) return cached;
const entry = new InterpretedEntry(
ast,
);
cache.set(ast, entry);
return entry;
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/SchemaParser.js
/**
* Runs schemas against real values.
*
* Schema parsers construct values from schema input, check whether a value
* matches a schema, decode encoded input, and encode decoded values back to
* their external form. This module exposes those operations through several
* result styles, including `Effect`, `Promise`, `Exit`, `Option`, `Result`, and
* synchronous functions that throw. It also contains the lower-level runner that
* walks a schema AST and reports schema failures as `SchemaIssue.Issue` values.
*
* @stability stable
* @since 4.0.0
*/
/**
* Creates an effectful maker for the schema's decoded type side.
*
* **When to use**
*
* Use to construct decoded schema values in `Effect` while preserving
* construction failures as `SchemaIssue.Issue` values in the error channel.
*
* **Details**
*
* The returned function accepts constructor input, applies constructor defaults,
* runs type-side validation unless checks are disabled, and fails with a
* `SchemaIssue.Issue` when construction fails.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
function makeEffect(schema) {
const ast = schema.ast;
let parser;
return (input, options) => {
return (parser ??= runWithCompiler(
constructorCompiler,
toType(ast),
))(
input,
options?.disableChecks
? options?.parseOptions
? {
...options.parseOptions,
disableChecks: true,
}
: { disableChecks: true }
: options?.parseOptions,
);
};
}
/**
* Creates a synchronous maker that returns `Option.some` with the constructed
* value on success, or `Option.none` when construction fails with schema issues.
*
* **When to use**
*
* Use when you need to validate schema constructor input and only care whether
* construction succeeds, without exposing `SchemaIssue.Issue` details.
*
* **Gotchas**
*
* Only causes made entirely of schema issues are converted to `Option.none`.
* Causes that contain defects, interruptions, or asynchronous work at this
* synchronous boundary throw an `Error` whose cause is the underlying `Cause`.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
function makeOption(schema) {
const parser = makeEffect(schema);
return (input, options) => {
const exit = runSyncExit(
parser(input, options),
);
if (isSuccess(exit))
return some(exit.value);
getSchemaIssueOrThrow(
exit.cause,
"Option adapter can only return none for schema issues",
);
return none();
};
}
/**
* Creates a synchronous maker for the schema's decoded type side.
*
* **When to use**
*
* Use to construct decoded schema values synchronously when invalid input
* should throw an `Error` whose cause is `SchemaIssue.Issue`.
*
* **Details**
*
* The returned function constructs a value from constructor input and throws an
* `Error` with the `SchemaIssue.Issue` in its `cause` when construction fails.
* Schema validation failures use the generic message `"Schema validation failed"`.
* Format the `cause` explicitly with `SchemaIssue.makeFormatterDefault()` when
* human-readable details are needed.
*
* **Gotchas**
*
* Causes that contain defects, interruptions, or asynchronous work at this
* synchronous boundary throw an `Error` whose cause is the underlying `Cause`,
* instead of being converted to a schema validation error.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
function make$2(schema) {
return makeConstructorSync(
toType(schema.ast),
);
}
/**
* Creates an effectful decoder for `unknown` input.
*
* **When to use**
*
* Use when you need to decode untyped boundary input in an `Effect` whose
* failure channel is `SchemaIssue.Issue`, while preserving transformations
* and service requirements.
*
* **Details**
*
* The returned function succeeds with the schema's decoded `Type` or fails with a
* `SchemaIssue.Issue`. Decoding service requirements are preserved in the returned
* `Effect`. Parse options may be provided when creating the decoder and overridden
* when applying it.
*
* @see {@link decodeEffect} for input already typed as the schema's `Encoded` type
*
* @stability stable
* @category decoding
* @since 4.0.0
*/
function decodeUnknownEffect$1(
schema,
options,
) {
const parser = run(schema.ast);
return options === void 0
? parser
: (input, overrideOptions) =>
parser(
input,
mergeParseOptions(
options,
overrideOptions,
),
);
}
const mergeParseOptions = (
options,
overrideOptions,
) =>
overrideOptions
? {
...options,
...overrideOptions,
}
: options;
const getValue = (value) => {
if (value === missing)
return fail$1(new InvalidValue());
return succeed$1(value);
};
/** @internal */
function run(ast) {
return runWithCompiler(
normalCompiler,
ast,
);
}
function parserResult(result, input) {
if (result === sameExit)
return succeed$1(input);
if (!effectIsExit(result))
return flatMapEager(
result,
getValue,
);
return result[
"~effect/Effect/args"
] === missing
? getValue(missing)
: result;
}
function runWithCompiler(
compiler,
ast,
) {
let parser;
return (input, options) => {
const result = (parser ??=
compiler(ast))(
input,
options ?? defaultParseOptions,
);
if (result === sameExit)
return succeed$1(input);
if (!effectIsExit(result))
return flatMapEager(
result,
getValue,
);
return result[
"~effect/Effect/args"
] === missing
? getValue(missing)
: result;
};
}
function runSync(effect, message) {
const exit = runSyncExit(effect);
if (isSuccess(exit))
return exit.value;
const issue = getSchemaIssueOrThrow(
exit.cause,
message,
);
throw new Error(
"Schema validation failed",
{ cause: issue },
);
}
function makeConstructorSync(ast) {
let entry;
let parser;
return (input, options) => {
entry ??= resolve(ast);
const parseOptions =
options?.disableChecks
? options.parseOptions
? {
...options.parseOptions,
disableChecks: true,
}
: { disableChecks: true }
: (options?.parseOptions ??
defaultParseOptions);
const make = entry.make;
if (
make !== void 0 &&
input !== missing
) {
let output;
try {
output = make(
input,
parseOptions,
);
} catch (error) {
getSchemaIssueOrThrow(
die$1(error),
"Constructor adapter can only throw schema issues",
);
throw error;
}
if (
output !== invalid &&
output !== missing
)
return output;
}
return runSync(
parserResult(
(parser ??= entry.makeEffect)(
input,
parseOptions,
),
input,
),
"Constructor adapter can only throw schema issues",
);
};
}
const normalCompiler = (ast) =>
resolve(ast).parser;
const constructorCompiler = (ast) =>
resolve(ast).makeEffect;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/schema/make.js
/** @internal */
const TypeId$2 =
"~effect/Schema/Schema";
const RebuildOptions =
/*#__PURE__*/ Symbol();
const SchemaProto = {
[TypeId$2]: TypeId$2,
get make() {
const value = make$2(this);
Object.defineProperty(
this,
"make",
{
value,
enumerable: true,
},
);
return value;
},
get makeEffect() {
const value = makeEffect(this);
Object.defineProperty(
this,
"makeEffect",
{
value,
enumerable: true,
},
);
return value;
},
get makeOption() {
const value = makeOption(this);
Object.defineProperty(
this,
"makeOption",
{
value,
enumerable: true,
},
);
return value;
},
pipe() {
return pipeArguments(
this,
arguments,
);
},
annotate(annotations) {
return this.rebuild(
annotate(this.ast, annotations),
);
},
annotateKey(annotations) {
return this.rebuild(
annotateKey(
this.ast,
annotations,
),
);
},
check(...checks) {
return this.rebuild(
appendChecks(this.ast, checks),
);
},
rebuild(ast) {
return make$1(
ast,
this[RebuildOptions],
);
},
};
/** @internal */
function make$1(ast, options) {
function Schema() {}
const self = Object.setPrototypeOf(
Schema,
SchemaProto,
);
if (
options &&
(Object.hasOwn(options, "name") ||
Object.hasOwn(
options,
"length",
) ||
Object.hasOwn(
options,
"__proto__",
))
)
Object.defineProperties(
self,
Object.getOwnPropertyDescriptors({
...options,
}),
);
else Object.assign(self, options);
self[RebuildOptions] = options;
self.ast = ast;
return self;
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Struct.js
/**
* Wraps a plain function as a {@link Lambda} value so it can be used with
* {@link map}, {@link mapPick}, and {@link mapOmit}.
*
* **When to use**
*
* Use to create a typed lambda for struct mapping APIs that need type-level
* input and output tracking.
*
* **Details**
*
* The type parameter `L` encodes both the input and output types at the type
* level, allowing the compiler to track how struct value types change. At
* runtime, the returned value is the same function; `lambda` only adjusts the
* type.
*
* **Example** (Wrapping values in arrays)
*
* ```ts import.meta.vitest
* import { pipe, Struct } from "effect"
*
* interface AsArray extends Struct.Lambda {
* <A>(self: A): Array<A>
* readonly "~lambda.out": Array<this["~lambda.in"]>
* }
*
* const asArray = Struct.lambda<AsArray>((a) => [a])
* const result = pipe({ x: 1, y: "hello" }, Struct.map(asArray))
* result // => { x: [1], y: ["hello"] }
* ```
*
* @see {@link Lambda} – the type-level interface
* @see {@link map} – apply a lambda to all struct values
* @stability stable
* @category constructors
* @since 4.0.0
*/
const lambda = (f) => f;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/schemaError.js
const SchemaErrorTypeId =
"~effect/Schema/SchemaError";
function isSchemaError$1(u) {
return (
hasProperty(
u,
"~effect/Schema/SchemaError",
) &&
u["~effect/Schema/SchemaError"] ===
"~effect/Schema/SchemaError"
);
}
({ ...BaseProto });
({ ...BaseProto });
({ ...BaseProto });
({ ...BaseProto });
({ ...BaseProto });
({ ...BaseProto });
({ ...BaseProto });
({ ...BaseProto });
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Schema.js
/**
* Creates a schema for a **parametric** type (a generic container such as
* `Array<A>`, `Option<A>`, etc.) by accepting a list of type-parameter schemas
* and a decoder factory.
*
* **When to use**
*
* Use when you are defining a schema for a generic container whose validation
* depends on one or more type-parameter schemas.
*
* **Details**
*
* The outer call `declareConstructor<T, E, Iso>()` fixes the decoded type `T`,
* the encoded type `E`, and the optional iso type. The inner call receives:
* - `typeParameters` — the concrete schemas for each type variable
* - `run` — a factory that, given resolved codecs for each type parameter,
* returns a parsing function `(u, ast, options) => Effect<T, Issue>`
* - `annotations` — optional metadata
*
* @see {@link declare} for creating schemas for non-parametric types.
*
* **Example** (Schema for a parametric `Box<A>` type)
*
* ```ts import.meta.vitest
* import { Effect, Schema, SchemaIssue, SchemaParser } from "effect"
*
* interface Box<A> {
* readonly value: A
* }
*
* const isBox = (u: unknown): u is Box<unknown> =>
* typeof u === "object" && u !== null && "value" in u
*
* const Box = <A extends Schema.Constraint>(item: A) =>
* Schema.declareConstructor<Box<A["Type"]>, Box<A["Encoded"]>>()(
* [item],
* ([itemCodec]) =>
* (u, ast, options) => {
* if (!isBox(u)) {
* return Effect.fail(new SchemaIssue.InvalidType(ast, u, options))
* }
* return Effect.map(
* SchemaParser.decodeUnknownEffect(itemCodec)(u.value, options),
* (value) => ({ value })
* )
* }
* )
*
* const schema = Box(Schema.Number)
* Effect.runSync(Schema.decodeUnknownEffect(schema)({ value: 1 })) // => { value: 1 }
* ```
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
function declareConstructor() {
return (
typeParameters,
run,
annotations,
) => {
return make(
new Declaration(
typeParameters.map(getAST),
(typeParameters) =>
run(
typeParameters.map((ast) =>
make(ast),
),
),
annotations,
),
);
};
}
/**
* Creates a schema for a **non-parametric** opaque type using a type-guard
* function. The schema accepts any unknown value and succeeds when `is` returns
* `true`, failing with an `InvalidType` issue otherwise.
*
* **When to use**
*
* Use when you are defining a schema for an opaque type with no type parameters
* and validation can be expressed as a type guard.
*
* **Example** (Defining a schema for a custom `UserId` branded type)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* type UserId = string & { readonly _tag: "UserId" }
*
* const isUserId = (u: unknown): u is UserId =>
* typeof u === "string" && u.startsWith("user_")
*
* const UserId = Schema.declare<UserId>(isUserId, {
* title: "UserId",
* description: "A user identifier starting with 'user_'"
* })
* Schema.decodeUnknownSync(UserId)("user_123") // => "user_123"
* ```
*
* @see {@link declareConstructor} for creating schemas for parametric types.
*
* @stability stable
* @category constructors
* @since 3.10.0
*/
function declare(is, annotations) {
return declareConstructor()(
[],
() => (input, ast, options) =>
is(input)
? succeed$1(input)
: fail$1(
new InvalidType(
ast,
input,
options,
),
),
annotations,
);
}
/**
* Error thrown or returned when schema decoding or encoding fails.
*
* **Details**
*
* The `issue` field contains a structured {@link SchemaIssue.Issue} tree describing
* every validation failure, including the path to the problematic value and
* the expected type or constraint. The `message` field renders the issue tree
* with the default formatter.
*
* **Gotchas**
*
* Parsing with `reportInput: true` adds an enumerable `input` field to
* value-bearing issues. Built-in messages may include reported input, and
* custom annotations or messages are not sanitized.
*
* **Example** (Inspecting a SchemaError)
*
* ```ts import.meta.vitest
* import { Result, Schema } from "effect"
*
* const result = Schema.decodeUnknownResult(Schema.Number)("not a number")
* const message = Result.isFailure(result) ? result.failure.message : ""
* message // => "Expected number"
* ```
*
* @see {@link isSchemaError} for narrowing unknown values
* @stability stable
* @category errors
* @since 4.0.0
*/
var SchemaError = class extends /*#__PURE__*/ TaggedError(
"SchemaError",
) {
[SchemaErrorTypeId] =
SchemaErrorTypeId;
constructor(issue) {
const stackTraceLimit =
getStackTraceLimit();
setStackTraceLimit(0);
try {
super({ issue });
} finally {
setStackTraceLimit(
stackTraceLimit,
);
}
}
get message() {
return defaultFormatter(this.issue);
}
toJSON() {
return {
_tag: this._tag,
message: this.message,
};
}
[NodeInspectSymbol]() {
return this.toJSON();
}
toString() {
return `SchemaError(${this.message})`;
}
};
/**
* Returns `true` if `u` is a {@link SchemaError}.
*
* **When to use**
*
* Use when you need to narrow an unknown value to `SchemaError`.
*
* **Example** (Narrowing Schema errors)
*
* ```ts import.meta.vitest
* import { Result, Schema } from "effect"
*
* const result = Result.try(() => Schema.decodeUnknownSync(Schema.Number)("oops"))
* const error: unknown = Result.isFailure(result) ? result.failure : undefined
* Schema.isSchemaError(error) // => true
* ```
*
* @stability stable
* @category guards
* @since 4.0.0
*/
function isSchemaError(u) {
return isSchemaError$1(u);
}
function fromIssueEffect(self) {
if (effectIsExit(self))
return fromIssueExit(self);
return catchCause(self, (cause) =>
failCauseSync(() =>
map(
cause,
(issue) =>
new SchemaError(issue),
),
),
);
}
function fromIssueExit(exit) {
return isSuccess(exit)
? exit
: failCause(
map(
exit.cause,
(issue) =>
new SchemaError(issue),
),
);
}
function getSchemaErrorOrThrow(
cause,
message,
) {
let schemaError;
for (const reason of cause.reasons) {
if (
!isFailReason(reason) ||
!isSchemaError(reason.error)
)
throw new globalThis.Error(
message,
{ cause },
);
schemaError ??= reason.error;
}
if (schemaError === void 0)
throw new globalThis.Error(
message,
{ cause },
);
return schemaError;
}
function runSchemaErrorSync(self) {
const exit = runSyncExit(self);
if (isSuccess(exit))
return exit.value;
throw getSchemaErrorOrThrow(
exit.cause,
"Sync adapter can only throw schema errors",
);
}
/**
* Decodes an `unknown` input against a schema, returning an `Effect` that
* succeeds with the decoded value or fails with a {@link SchemaError}.
*
* **When to use**
*
* Use when you need to decode unknown input in an `Effect` whose failure
* channel is `SchemaError`.
*
* **Details**
*
* Prefer {@link decodeEffect} when the input is already typed as the schema's
* `Encoded` type.
* Options may be provided either when creating the decoder or when applying it;
* application options override creation options.
*
* @see {@link SchemaParser.decodeUnknownEffect} for the adapter that fails with `SchemaIssue.Issue` directly
*
* @stability stable
* @category decoding
* @since 4.0.0
*/
function decodeUnknownEffect(
schema,
options,
) {
const parser = decodeUnknownEffect$1(
schema,
options,
);
return (input, options) => {
return fromIssueEffect(
parser(input, options),
);
};
}
/**
* Decodes an `unknown` input against a schema synchronously, returning the
* decoded value or throwing a {@link SchemaError} for schema mismatches.
*
* **When to use**
*
* Use when you need to validate unknown data at a synchronous boundary and want
* schema mismatches to throw `SchemaError`.
*
* **Details**
*
* For input already typed as the schema's `Encoded` type use `decodeSync`.
* Only service-free schemas can be decoded synchronously. For alternatives that
* do not throw on schema mismatches, see `decodeUnknownOption`,
* `decodeUnknownExit`, or `decodeUnknownEffect`. Options may be provided either
* when creating the decoder or when applying it; application options override
* creation options.
*
* **Gotchas**
*
* Non-schema failures may throw a runtime failure instead of `SchemaError`.
*
* **Example** (Decoding with a transformation schema)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* const NumberFromString = Schema.NumberFromString
*
* Schema.decodeUnknownSync(NumberFromString)("42") // => 42
* ```
*
* @see {@link SchemaParser.decodeUnknownSync} for the adapter that throws an `Error` whose cause is `SchemaIssue.Issue`
*
* @stability stable
* @category decoding
* @since 4.0.0
*/
function decodeUnknownSync(
schema,
options,
) {
const parser = decodeUnknownEffect(
schema,
options,
);
return (input, options) => {
return runSchemaErrorSync(
parser(input, options),
);
};
}
/**
* Creates a schema from an AST (Abstract Syntax Tree) node.
*
* **Details**
*
* This is the fundamental constructor for all schemas in the Effect Schema
* library. It takes an AST node and wraps it in a fully-typed schema that
* preserves all type information and provides the complete schema API.
*
* The `make` function is used internally to create all primitive schemas like
* `String`, `Number`, `Boolean`, etc., as well as more complex schemas. It's
* the bridge between the untyped AST representation and the strongly-typed
* schema.
*
* @stability stable
* @category constructors
* @since 3.10.0
*/
const make = make$1;
/**
* Creates a schema for a single literal value (string, number, bigint, boolean, or null).
*
* **Example** (Defining a string literal)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* const schema = Schema.Literal("hello")
* // Type: Schema.Literal<"hello">
* Schema.decodeSync(schema)("hello") // => "hello"
* ```
*
* @see {@link Literals} for a schema that represents a union of literals.
* @see {@link tag} for a schema that represents a literal value that can be
* used as a discriminator field in tagged unions and has a constructor default.
* @stability stable
* @category constructors
* @since 3.10.0
*/
function Literal(literal) {
const out = make(
new Literal$1(literal),
{
literal,
transform(to) {
return out.pipe(
decodeTo(Literal(to), {
decode: transform$1(
() => to,
),
encode: transform$1(
() => literal,
),
}),
);
},
},
);
return out;
}
/**
* Schema for the `null` literal. Validates that the input is strictly `null`.
*
* @see {@link NullOr} for a union with another schema.
* @stability stable
* @category schemas
* @since 3.10.0
*/
const Null = /*#__PURE__*/ make(null_);
/**
* Schema for `string` values. Validates that the input is `typeof` `"string"`.
*
* @stability stable
* @category schemas
* @since 4.0.0
*/
const String$1 =
/*#__PURE__*/ make(string);
/**
* Schema for `number` values, including `NaN`, `Infinity`, and `-Infinity`.
*
* **Details**
*
* Default JSON serializer:
*
* - Finite numbers are serialized as numbers.
* - Non-finite values are serialized as strings (`"NaN"`, `"Infinity"`, `"-Infinity"`).
*
* @see {@link Finite} for a schema that excludes non-finite values.
* @stability stable
* @category schemas
* @since 4.0.0
*/
const Number$1 =
/*#__PURE__*/ make(number);
function makeStruct(ast, fields) {
return make(ast, {
fields,
mapFields(f, options) {
const fields = f(this.fields);
return makeStruct(
struct(
fields,
options?.unsafePreserveChecks
? this.ast.checks
: void 0,
),
fields,
);
},
});
}
/**
* Defines a struct schema from a map of field schemas.
*
* **Details**
*
* Each field value is a schema. Use {@link optionalKey} or {@link optional} to
* mark fields as optional, and {@link mutableKey} to mark them as mutable.
*
* The resulting schema's `Type` is a readonly object type with the fields'
* decoded types. The `Encoded` form mirrors the field schemas' encoded types.
* Declared fields may be inherited and are copied to own properties in the
* output. The `__proto__` field is accepted only when it is an own property.
* Parsing does not guarantee that output keys retain their input order.
*
* **Example** (Defining a basic struct)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* const Person = Schema.Struct({
* name: Schema.String,
* age: Schema.Number,
* email: Schema.optionalKey(Schema.String)
* })
*
* // { readonly name: string; readonly age: number; readonly email?: string }
* type Person = typeof Person.Type
*
* Schema.decodeUnknownSync(Person)({ name: "Alice", age: 30 }) // => { name: "Alice", age: 30 }
* ```
*
* @stability stable
* @category constructors
* @since 3.10.0
*/
function Struct(fields) {
return makeStruct(
struct(fields, void 0),
fields,
);
}
/**
* @category constructors
* @since 4.0.0
*/
const ArraySchema =
/*#__PURE__*/ lambda((schema) =>
make(
new Arrays(
false,
[],
[schema.ast],
),
{ value: schema },
),
);
/**
* Makes an array or tuple schema mutable, removing the `readonly` modifier.
*
* **Gotchas**
*
* This combinator does not support an encoding attached to the array or tuple
* node and throws if one is present. Encodings on element schemas are
* supported.
*
* **Example** (Defining mutable arrays)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* const schema = Schema.mutable(Schema.Array(Schema.Number))
*
* // number[] (mutable)
* type T = typeof schema.Type
* const value: T = [1, 2]
* value.push(3)
* value // => [1, 2, 3]
* ```
*
* @stability stable
* @category transforming
* @since 3.10.0
*/
const mutable = /*#__PURE__*/ lambda(
(schema) =>
make(mutable$1(schema.ast), {
schema,
}),
);
function makeUnion(ast, members) {
return make(ast, {
members,
mapMembers(f, options) {
const members = f(this.members);
return makeUnion(
union(
members,
this.ast.options,
options?.unsafePreserveChecks
? this.ast.checks
: void 0,
),
members,
);
},
});
}
/**
* Creates a union schema from an array of member schemas. Members are tested in
* order; the first match is returned.
*
* **Details**
*
* Optionally, specify `mode`:
* - `"anyOf"` (default) — matches if any member matches.
* - `"oneOf"` — matches if exactly one member matches.
*
* **Example** (Defining a string or number union)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* const schema = Schema.Union([Schema.String, Schema.Number])
*
* Schema.decodeUnknownSync(schema)("hello") // => "hello"
* Schema.decodeUnknownSync(schema)(42) // => 42
* ```
*
* @stability stable
* @category constructors
* @since 3.10.0
*/
function Union(members, options) {
return makeUnion(
union(members, options, void 0),
members,
);
}
/**
* Creates a union schema from an array of literal values.
*
* **Example** (Defining status codes)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* const schema = Schema.Literals(["active", "inactive", "pending"])
* Schema.decodeSync(schema)("active") // => "active"
* ```
*
* @see {@link Literal} for a schema that represents a single literal.
* @stability stable
* @category constructors
* @since 4.0.0
*/
function Literals(literals) {
const members = literals.map(Literal);
return make(
union(members, void 0, void 0),
{
literals,
members,
mapMembers(f) {
return Union(f(this.members));
},
pick(literals) {
return Literals(literals);
},
transform(to) {
return Union(
members.map((member, index) =>
member.transform(to[index]),
),
);
},
},
);
}
/**
* Creates a union schema of `S | null`.
*
* @stability stable
* @category constructors
* @since 3.10.0
*/
const NullOr = /*#__PURE__*/ lambda(
(self) => Union([self, Null]),
);
function decodeTo(to, transformation) {
return (from) => {
return make(
decodeTo$1(
from.ast,
to.ast,
transformation
? makeTransformation(
transformation,
)
: passthrough(),
),
{
from,
to,
},
);
};
}
/**
* Creates a schema that validates values using `instanceof`.
* Decoding and encoding pass the value through unchanged.
*
* **Example** (Defining a schema for a built-in class)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* const DateSchema = Schema.instanceOf(Date)
*
* const decoded = Schema.decodeUnknownSync(DateSchema)(new Date("2024-01-01"))
* decoded.toISOString() // => "2024-01-01T00:00:00.000Z"
* ```
*
* @stability stable
* @category constructors
* @since 3.10.0
*/
function instanceOf(
constructor,
annotations,
) {
return declare(
(u) => u instanceof constructor,
annotations,
);
}
/**
* Creates a custom validation filter from a predicate function.
*
* **Details**
*
* The predicate receives the decoded input value, the schema AST, and parse
* options, and returns a `FilterOutput`. Non-success outputs are normalized into
* schema issues. The `annotations` parameter annotates the filter itself; with
* the default formatter, failures use `message` first, `expected` second, and
* `<filter>` when neither is provided.
*
* When `abort` is `true`, parsing stops after this filter fails instead of
* collecting later check failures.
*
* **Example** (Reporting failure at a nested path)
*
* ```ts import.meta.vitest
* import { Result, Schema } from "effect"
*
* const schema = Schema.Struct({ password: Schema.String, confirmPassword: Schema.String }).check(
* Schema.makeFilter((o) =>
* o.password === o.confirmPassword
* ? undefined
* : { path: ["password"], issue: "password and confirmPassword must match" }
* )
* )
*
* const result = Schema.decodeUnknownResult(schema)({ password: "123456", confirmPassword: "1234567" })
* if (Result.isFailure(result) && result.failure.issue._tag === "Filter" && result.failure.issue.issue._tag === "Pointer") {
* result.failure.issue.issue.path // => ["password"]
* }
* ```
*
* **Example** (Reporting multiple failures at once)
*
* ```ts import.meta.vitest
* import { Result, Schema } from "effect"
*
* const schema = Schema.Struct({ a: Schema.Finite, b: Schema.Finite, c: Schema.Finite }).check(
* Schema.makeFilter((o) => {
* const issues: Array<Schema.FilterIssue> = []
* if (o.a > 0) {
* if (o.b <= 0) issues.push({ path: ["b"], issue: "b must be greater than 0" })
* if (o.c <= 0) issues.push({ path: ["c"], issue: "c must be greater than 0" })
* }
* return issues
* })
* )
*
* const result = Schema.decodeUnknownResult(schema)({ a: 1, b: 0, c: 0 })
* if (Result.isFailure(result) && result.failure.issue._tag === "Filter" && result.failure.issue.issue._tag === "Composite") {
* result.failure.issue.issue.issues.map((issue) => issue._tag === "Pointer" ? issue.path : []) // => [["b"], ["c"]]
* }
* ```
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const makeFilter = makeFilter$1;
/**
* Creates a greater-than-or-equal-to (`>=`) check for any ordered type from an
* `Order.Order` instance.
*
* @stability stable
* @category validation
* @since 4.0.0
*/
function makeIsGreaterThanOrEqualTo(
options,
) {
const gte = isGreaterThanOrEqualTo$1(
options.order,
);
const formatter =
options.formatter ?? format$1;
return (minimum, annotations) => {
return makeFilter(
(input) => gte(input, minimum),
{
expected: `a value greater than or equal to ${formatter(minimum)}`,
arbitraryConstraint: {
order: options.order,
minimum,
},
...options.annotate?.(minimum),
...annotations,
},
);
};
}
/**
* Creates a less-than-or-equal-to (`<=`) check for any ordered type from an
* `Order.Order` instance.
*
* @stability stable
* @category validation
* @since 4.0.0
*/
function makeIsLessThanOrEqualTo(
options,
) {
const lte = isLessThanOrEqualTo$1(
options.order,
);
const formatter =
options.formatter ?? format$1;
return (maximum, annotations) => {
return makeFilter(
(input) => lte(input, maximum),
{
expected: `a value less than or equal to ${formatter(maximum)}`,
arbitraryConstraint: {
order: options.order,
maximum,
},
...options.annotate?.(maximum),
...annotations,
},
);
};
}
function encodeNumberPayload(number) {
if (
!globalThis.Number.isFinite(number)
)
throw new globalThis.RangeError(
`Expected a finite number, got ${format$1(number)}`,
);
return number;
}
/**
* Validates that a number is greater than or equal to the specified value
* (inclusive).
*
* **Details**
*
* JSON Schema:
*
* This check corresponds to the `minimum` constraint in JSON Schema.
*
* Arbitrary:
*
* During arbitrary generation, this applies a `minimum` constraint
* to ensure generated numbers are greater than or equal to the specified value.
*
* @stability stable
* @category validation
* @since 4.0.0
*/
const isGreaterThanOrEqualTo =
/*#__PURE__*/ makeIsGreaterThanOrEqualTo(
{
order: Number$4,
annotate: (minimum) => ({
representation: {
id: "effect/schema/isGreaterThanOrEqualTo",
payload: {
minimum:
encodeNumberPayload(
minimum,
),
},
},
toJsonSchema: () => ({
minimum,
}),
toCode: () => ({
runtime: `Schema.isGreaterThanOrEqualTo(${format$1(minimum)})`,
}),
}),
},
);
/**
* Validates that a number is less than or equal to the specified value
* (inclusive).
*
* **Details**
*
* JSON Schema:
*
* This check corresponds to the `maximum` constraint in JSON Schema.
*
* Arbitrary:
*
* During arbitrary generation, this applies a `maximum` constraint
* to ensure generated numbers are less than or equal to the specified value.
*
* @stability stable
* @category validation
* @since 4.0.0
*/
const isLessThanOrEqualTo =
/*#__PURE__*/ makeIsLessThanOrEqualTo(
{
order: Number$4,
annotate: (maximum) => ({
representation: {
id: "effect/schema/isLessThanOrEqualTo",
payload: {
maximum:
encodeNumberPayload(
maximum,
),
},
},
toJsonSchema: () => ({
maximum,
}),
toCode: () => ({
runtime: `Schema.isLessThanOrEqualTo(${format$1(maximum)})`,
}),
}),
},
);
/**
* Validates that a value has at least the specified length. Works with strings
* and arrays.
*
* **Details**
*
* JSON Schema:
*
* The bound must be finite; it is rounded down and clamped to zero. For arrays,
* this check corresponds to `minItems`. JavaScript counts UTF-16 code units
* while JSON Schema counts Unicode code points, so strings use
* `minLength: Math.ceil(minLength / 2)`, the tightest lower bound that cannot
* reject a string accepted by this check.
*
* Arbitrary:
*
* During arbitrary generation, this applies a `minLength`
* constraint to ensure generated strings or arrays have at least the required
* length.
*
* **Example** (Checking minimum length)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* const NonEmptyStringSchema = Schema.String.check(Schema.isMinLength(1))
* const NonEmptyArraySchema = Schema.Array(Schema.Number).check(Schema.isMinLength(1))
* Schema.is(NonEmptyStringSchema)("a") // => true
* Schema.is(NonEmptyArraySchema)([1]) // => true
* ```
*
* @stability stable
* @category validation
* @since 4.0.0
*/
function isMinLength(
minLength,
annotations,
) {
minLength =
normalizeCardinality(minLength);
return makeIsMinLength(
minLength,
Math.ceil(minLength / 2),
annotations,
);
}
function makeIsMinLength(
minLength,
minCodePoints,
annotations,
) {
return makeFilter(
(input) =>
input.length >= minLength,
{
expected: `a value with a length of at least ${minLength}`,
representation: {
id: "effect/schema/isMinLength",
payload: { minLength },
},
toJsonSchema: ({ type }) =>
type === "string"
? minLength <= 1
? {
minLength:
minCodePoints,
}
: [
{
minLength:
minCodePoints,
},
true,
]
: type === "array"
? { minItems: minLength }
: type === void 0
? [
{
minLength:
minCodePoints,
minItems: minLength,
},
true,
]
: [{}, true],
toCode: () => ({
runtime: `Schema.isMinLength(${minLength})`,
}),
[STRUCTURAL_ANNOTATION_KEY]: true,
arbitraryConstraint: {
minLength,
},
...annotations,
},
);
}
/**
* Validates that a value has at most the specified length. Works with strings
* and arrays.
*
* **Details**
*
* JSON Schema:
*
* The bound must be finite; it is rounded down and clamped to zero. This check
* corresponds to `maxItems` for arrays. Strings use the same bound for
* `maxLength`, which cannot reject a string accepted by this check because a
* string has no more code points than UTF-16 code units.
*
* Arbitrary:
*
* During arbitrary generation, this applies a `maxLength`
* constraint to ensure generated strings or arrays have at most the required
* length.
*
* @stability stable
* @category validation
* @since 4.0.0
*/
function isMaxLength(
maxLength,
annotations,
) {
maxLength =
normalizeCardinality(maxLength);
return makeFilter(
(input) =>
input.length <= maxLength,
{
expected: `a value with a length of at most ${maxLength}`,
representation: {
id: "effect/schema/isMaxLength",
payload: { maxLength },
},
toJsonSchema: ({ type }) =>
type === "string"
? maxLength === 0
? { maxLength }
: [{ maxLength }, true]
: type === "array"
? { maxItems: maxLength }
: type === void 0
? [
{
maxLength,
maxItems: maxLength,
},
true,
]
: [{}, true],
toCode: () => ({
runtime: `Schema.isMaxLength(${maxLength})`,
}),
[STRUCTURAL_ANNOTATION_KEY]: true,
arbitraryConstraint: {
maxLength,
},
...annotations,
},
);
}
function normalizeCardinality(value) {
if (
!globalThis.Number.isFinite(value)
)
throw new globalThis.RangeError(
`Expected a finite number, got ${value}`,
);
return Math.max(0, Math.floor(value));
}
globalThis.RegExp;
globalThis.URL;
globalThis.File;
globalThis.FormData;
globalThis.URLSearchParams;
globalThis.Uint8Array;
//#endregion
//#region ../schemas/libraries/effect/download/index.ts
const Image = Struct({
id: Number$1,
created: instanceOf(Date),
title: String$1.check(
isMinLength(1),
isMaxLength(100),
),
type: Literals(["jpg", "png"]),
size: Number$1,
url: String$1.check(
makeFilter((value) =>
URL.canParse(value),
),
),
});
const Rating = Struct({
id: Number$1,
stars: Number$1.check(
isGreaterThanOrEqualTo(1),
isLessThanOrEqualTo(5),
),
title: String$1.check(
isMinLength(1),
isMaxLength(100),
),
text: String$1.check(
isMinLength(1),
isMaxLength(1e3),
),
images: mutable(ArraySchema(Image)),
});
decodeUnknownSync(
Struct({
id: Number$1,
created: instanceOf(Date),
title: String$1.check(
isMinLength(1),
isMaxLength(100),
),
brand: String$1.check(
isMinLength(1),
isMaxLength(30),
),
description: String$1.check(
isMinLength(1),
isMaxLength(500),
),
price: Number$1.check(
isGreaterThanOrEqualTo(1),
isLessThanOrEqualTo(1e4),
),
discount: NullOr(
Number$1.check(
isGreaterThanOrEqualTo(1),
isLessThanOrEqualTo(100),
),
),
quantity: Number$1.check(
isGreaterThanOrEqualTo(0),
isLessThanOrEqualTo(10),
),
tags: mutable(
ArraySchema(
String$1.check(
isMinLength(1),
isMaxLength(30),
),
),
),
images: mutable(ArraySchema(Image)),
ratings: mutable(
ArraySchema(Rating),
),
}),
)({});
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Pipeable.js
/**
* The `Pipeable` module defines the shared interface and implementation helpers
* for values that support Effect-style method chaining with `.pipe(...)`.
*
* A `Pipeable` value can pass itself through a sequence of unary functions from
* left to right, so code can be written as `value.pipe(f, g, h)` instead of
* deeply nesting calls. This is the method form used by many Effect data types
* to compose transformations, validations, and effectful operations while
* keeping the original value as the starting point of the pipeline.
*
* @stability stable
* @since 2.0.0
*/
/**
* Applies a `pipe` method's variadic arguments to an initial value from left
* to right.
*
* **When to use**
*
* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments`
* object.
*
* **Details**
*
* This helper is intended for implementing `Pipeable.pipe` methods that
* receive JavaScript's `arguments` object. With no functions it returns the
* original value; otherwise it feeds each result into the next function.
*
* **Example** (Implementing a pipe method)
*
* ```ts import.meta.vitest
* import { Pipeable } from "effect"
*
* class NumberBox {
* constructor(readonly value: number) {}
*
* pipe(..._fns: ReadonlyArray<(value: number) => number>): number {
* return Pipeable.pipeArguments(this.value, arguments) as number
* }
* }
*
* const result = new NumberBox(5).pipe(
* (n) => n + 2,
* (n) => n * 3
* )
* result // => 21
* ```
*
* @stability stable
* @category combinators
* @since 2.0.0
*/
const pipeArguments = (self, args) => {
switch (args.length) {
case 0:
return self;
case 1:
return args[0](self);
case 2:
return args[1](args[0](self));
case 3:
return args[2](args[1](args[0](self)));
case 4:
return args[3](args[2](args[1](args[0](self))));
case 5:
return args[4](
args[3](args[2](args[1](args[0](self)))),
);
case 6:
return args[5](
args[4](args[3](args[2](args[1](args[0](self))))),
);
case 7:
return args[6](
args[5](
args[4](args[3](args[2](args[1](args[0](self))))),
),
);
case 8:
return args[7](
args[6](
args[5](
args[4](
args[3](args[2](args[1](args[0](self)))),
),
),
),
);
case 9:
return args[8](
args[7](
args[6](
args[5](
args[4](
args[3](args[2](args[1](args[0](self)))),
),
),
),
),
);
default: {
let ret = self;
for (let i = 0, len = args.length; i < len; i++)
ret = args[i](ret);
return ret;
}
}
};
/**
* Reusable prototype that implements `Pipeable.pipe`.
*
* **When to use**
*
* Use when classes or object prototypes can reuse this value when they need the
* standard pipe implementation backed by `pipeArguments`.
*
* @stability stable
* @category prototypes
* @since 3.15.0
*/
const Prototype$1 = {
pipe() {
return pipeArguments(this, arguments);
},
};
/**
* Provides a base constructor whose instances implement the standard `Pipeable.pipe`
* method.
*
* **When to use**
*
* Use when you need to define a class that supports Effect-style method
* chaining through `.pipe(...)`.
*
* @stability stable
* @category constructors
* @since 3.15.0
*/
const Class$1 = /*#__PURE__*/ (function () {
function PipeableBase() {}
PipeableBase.prototype = Prototype$1;
return PipeableBase;
})();
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Function.js
/**
* Creates a function that can be called in data-first style or data-last
* (`pipe`-friendly) style.
*
* **When to use**
*
* Use to expose one implementation through both direct and `pipe`-friendly
* call styles.
*
* **Details**
*
* Pass either the arity of the uncurried function or a predicate that decides
* whether the current call is data-first. Arity is the common case. Use a
* predicate when optional arguments make arity ambiguous.
*
* **Example** (Selecting data-first or data-last style by arity)
*
* ```ts import.meta.vitest
* import { Function, pipe } from "effect"
*
* const sum = Function.dual<
* (that: number) => (self: number) => number,
* (self: number, that: number) => number
* >(2, (self, that) => self + that)
*
* sum(2, 3) // => 5
* pipe(2, sum(3)) // => 5
* ```
*
* **Example** (Defining overloads with call signatures)
*
* ```ts import.meta.vitest
* import { Function, pipe } from "effect"
*
* const sum: {
* (that: number): (self: number) => number
* (self: number, that: number): number
* } = Function.dual(2, (self: number, that: number): number => self + that)
*
* sum(2, 3) // => 5
* pipe(2, sum(3)) // => 5
* ```
*
* **Example** (Selecting data-first or data-last style with a predicate)
*
* ```ts import.meta.vitest
* import { Function, pipe } from "effect"
*
* const sum = Function.dual<
* (that: number) => (self: number) => number,
* (self: number, that: number) => number
* >(
* (args) => args.length === 2,
* (self, that) => self + that
* )
*
* sum(2, 3) // => 5
* pipe(2, sum(3)) // => 5
* ```
*
* @stability stable
* @category combinators
* @since 2.0.0
*/
const dual = function (arity, body) {
if (typeof arity === "function")
return function () {
return arity(arguments)
? body.apply(this, arguments)
: (self) => body(self, ...arguments);
};
switch (arity) {
case 0:
case 1:
throw new RangeError(`Invalid arity ${arity}`);
case 2:
return function (a, b) {
if (arguments.length >= 2) return body(a, b);
return function (self) {
return body(self, a);
};
};
case 3:
return function (a, b, c) {
if (arguments.length >= 3) return body(a, b, c);
return function (self) {
return body(self, a, b);
};
};
default:
return function () {
if (arguments.length >= arity)
return body.apply(this, arguments);
const args = arguments;
return function (self) {
return body(self, ...args);
};
};
}
};
/**
* Returns its input argument unchanged.
*
* **When to use**
*
* Use to return a value unchanged where a function is required.
*
* **Example** (Returning the same value)
*
* ```ts import.meta.vitest
* import { identity } from "effect"
*
* identity(5) // => 5
* ```
*
* @stability stable
* @category combinators
* @since 2.0.0
*/
const identity = (a) => a;
/**
* Creates a zero-argument function that always returns the provided value.
*
* **When to use**
*
* Use when you need a thunk or callback that returns the same value on every
* invocation.
*
* **Example** (Creating a constant thunk)
*
* ```ts import.meta.vitest
* import { Function } from "effect"
*
* const constNull = Function.constant(null)
*
* constNull() // => null
* constNull() // => null
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const constant = (value) => () => value;
/**
* Returns `true` when called.
*
* **When to use**
*
* Use when you need a thunk that returns `true` on every invocation.
*
* **Example** (Returning true from a thunk)
*
* ```ts import.meta.vitest
* import { Function } from "effect"
*
* Function.constTrue() // => true
* ```
*
* @stability stable
* @category constants
* @since 2.0.0
*/
const constTrue = /*#__PURE__*/ constant(true);
/**
* Returns `undefined` when called.
*
* **When to use**
*
* Use when you need a thunk that returns `undefined` on every invocation.
*
* **Example** (Returning undefined from a thunk)
*
* ```ts import.meta.vitest
* import { Function } from "effect"
*
* Function.constUndefined() // => undefined
* ```
*
* @stability stable
* @category constants
* @since 2.0.0
*/
const constUndefined = /*#__PURE__*/ constant(void 0);
/**
* Returns no meaningful value when called.
*
* **When to use**
*
* Use when you need a thunk that is called only for its effect and has no
* meaningful return value.
*
* **Example** (Returning void from a thunk)
*
* ```ts import.meta.vitest
* import { Function } from "effect"
*
* Function.constVoid() // => undefined
* ```
*
* @stability stable
* @category constants
* @since 2.0.0
*/
const constVoid = constUndefined;
/**
* Creates a memoized function whose input is an object, caching results by
* object identity.
*
* **When to use**
*
* Use to reuse the result of a synchronous computation whose output is stable
* for a given object reference.
*
* **Details**
*
* Each memoized wrapper owns a private `WeakMap` keyed by object identity.
*
* **Gotchas**
*
* `undefined` is reserved to represent a cache miss and is therefore not
* supported as a return value.
*
* Structurally equal objects do not share cache entries. If the same object is
* mutated after its first call, later calls still return the cached result for
* that reference.
*
* @stability stable
* @category caching
* @since 4.0.0
*/
function memoize(f) {
const cache = /* @__PURE__ */ new WeakMap();
return (a) => {
const cached = cache.get(a);
if (cached !== void 0) return cached;
const result = f(a);
cache.set(a, result);
return result;
};
}
/**
* Creates a memoized idempotent object transformation that caches both inputs
* and their outputs by object identity.
*
* **When to use**
*
* Use when an object transformation is idempotent and its output can be safely
* reused as a fixed point.
*
* **Details**
*
* After computing an input, the returned function caches both the input and
* the output. Calling it with either reference returns the output without
* invoking the supplied function again.
*
* **Gotchas**
*
* The returned function treats each computed output as a fixed point. If
* applying the supplied function to an output would produce an observably
* different value, this memoization changes that behavior.
*
* @see {@link memoize} for memoizing functions without an idempotence requirement
* @stability stable
* @category caching
* @since 4.0.0
*/
function memoizeIdempotent(f) {
const cache = /* @__PURE__ */ new WeakMap();
return (a) => {
const cached = cache.get(a);
if (cached !== void 0) return cached;
const result = f(a);
cache.set(a, result);
if (result !== a) cache.set(result, result);
return result;
};
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/equal.js
/** @internal */
const getAllObjectKeys = (obj) => {
const keys = new Set(Reflect.ownKeys(obj));
if (obj.constructor === Object) return keys;
if (obj instanceof Error) keys.delete("stack");
const proto = Object.getPrototypeOf(obj);
let current = proto;
while (current !== null && current !== Object.prototype) {
const ownKeys = Reflect.ownKeys(current);
for (let i = 0; i < ownKeys.length; i++)
keys.add(ownKeys[i]);
current = Object.getPrototypeOf(current);
}
if (
keys.has("constructor") &&
typeof obj.constructor === "function" &&
proto === obj.constructor.prototype
)
keys.delete("constructor");
return keys;
};
/** @internal */
const byReferenceInstances = /*#__PURE__*/ new WeakSet();
/** @internal */
const viewBytes = (view) =>
new Uint8Array(
view.buffer,
view.byteOffset,
view.byteLength,
);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/hash.js
/**
* Back-edge count used to avoid caching entry-point-dependent hashes.
*
* @internal
*/
let backEdges = 0;
/** @internal */
const addBackEdge = () => {
backEdges++;
};
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Predicate.js
/**
* Defines runtime checks for values.
*
* A `Predicate<A>` returns `true` or `false` for an `A`. A
* `Refinement<A, B>` is a predicate that also narrows the TypeScript type when
* it succeeds. This module includes guards for common JavaScript values,
* property and tag checks, tuple and struct checks, boolean combinators, and
* helpers for composing predicates and refinements.
*
* @stability stable
* @since 2.0.0
*/
/**
* Checks whether a value is a `string`.
*
* **When to use**
*
* Use when you need a `Predicate` guard to narrow an `unknown` value to a
* string.
*
* **Details**
*
* Uses `typeof input === "string"`.
*
* **Example** (Guarding strings)
*
* ```ts import.meta.vitest
* import { Predicate } from "effect"
*
* const data: unknown = "hi"
*
* if (Predicate.isString(data)) {
* data.toUpperCase() // => "HI"
* }
* ```
*
* @see {@link isNumber}
* @see {@link isBoolean}
* @see {@link Refinement}
* @stability stable
* @category guards
* @since 2.0.0
*/
function isString$1(input) {
return typeof input === "string";
}
/**
* Checks whether a value is a `number`.
*
* **When to use**
*
* Use when you need a `Predicate` guard to narrow an `unknown` value to a
* number.
*
* **Details**
*
* Uses `typeof input === "number"` and does not exclude `NaN` or `Infinity`.
*
* **Example** (Guarding numbers)
*
* ```ts import.meta.vitest
* import { Predicate } from "effect"
*
* const data: unknown = 42
*
* if (Predicate.isNumber(data)) {
* data + 1 // => 43
* }
* ```
*
* @see {@link isBigInt}
* @see {@link isString}
* @stability stable
* @category guards
* @since 2.0.0
*/
function isNumber(input) {
return typeof input === "number";
}
/**
* Checks whether a value is a `function`.
*
* **When to use**
*
* Use when you need a `Predicate` guard to narrow an `unknown` value to a
* callable function.
*
* **Details**
*
* Uses `typeof input === "function"`.
*
* **Example** (Guarding functions)
*
* ```ts import.meta.vitest
* import { Predicate } from "effect"
*
* const data: unknown = () => 1
*
* if (Predicate.isFunction(data)) {
* data() // => 1
* }
* ```
*
* @see {@link isObjectKeyword}
* @stability stable
* @category guards
* @since 2.0.0
*/
function isFunction(input) {
return typeof input === "function";
}
/**
* Checks whether a value is not `null` and not `undefined`.
*
* **When to use**
*
* Use when you need a `Predicate` refinement that filters out nullish values
* but keeps other falsy ones.
*
* **Details**
*
* Uses `input != null`.
*
* **Example** (Filtering non-nullish values)
*
* ```ts import.meta.vitest
* import { Predicate } from "effect"
*
* const values = [0, null, "", undefined]
* const present = values.filter(Predicate.isNotNullish) // => [0, ""]
* ```
*
* @see {@link isNullish}
* @see {@link isNotNull}
* @see {@link isNotUndefined}
* @stability stable
* @category guards
* @since 4.0.0
*/
function isNotNullish(input) {
return input != null;
}
/**
* Type guard that always returns `true`.
*
* **When to use**
*
* Use when you need a `Predicate` that always accepts, e.g. as a placeholder.
*
* **Example** (Matching every value)
*
* ```ts import.meta.vitest
* import { Predicate } from "effect"
*
* Predicate.isUnknown(123) // => true
* ```
*
* @see {@link isNever}
* @stability stable
* @category guards
* @since 2.0.0
*/
function isUnknown(_) {
return true;
}
/**
* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions).
*
* **When to use**
*
* Use when you need a `Predicate` guard that accepts arrays and functions as
* well as objects.
*
* **Details**
*
* Returns `true` for arrays and functions, and `false` for `null`.
*
* **Example** (Checking object keywords)
*
* ```ts import.meta.vitest
* import { Predicate } from "effect"
*
* Predicate.isObjectKeyword(() => 1) // => true
* Predicate.isObjectKeyword(null) // => false
* ```
*
* @see {@link isObject}
* @see {@link isObjectOrArray}
* @stability stable
* @category guards
* @since 4.0.0
*/
function isObjectKeyword(input) {
return (
(typeof input === "object" && input !== null) ||
isFunction(input)
);
}
/**
* Checks whether a value has a given property key.
*
* **When to use**
*
* Use when you need a `Predicate` guard for property access on `unknown`
* values with a simple structural object check.
*
* **Details**
*
* Uses the `in` operator and `isObjectKeyword`. This does not check property
* value types.
*
* **Example** (Guarding object properties)
*
* ```ts import.meta.vitest
* import { Predicate } from "effect"
*
* const hasName = Predicate.hasProperty("name")
* const data: unknown = { name: "Ada" }
*
* if (hasName(data)) {
* data.name // => "Ada"
* }
* ```
*
* @see {@link isTagged}
* @see {@link isObjectKeyword}
* @stability stable
* @category guards
* @since 2.0.0
*/
const hasProperty = /*#__PURE__*/ dual(
2,
(self, property) =>
isObjectKeyword(self) && property in self,
);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Hash.js
/**
* Computes Effect hash values and defines the interface for objects that want
* to provide their own hash implementation. Hashes are small numeric
* fingerprints used by Effect data structures to bucket values quickly; they
* are not cryptographic digests and they are not proof that two values are
* equal. The module also includes helpers for primitive, structure, array, and
* reference-based hashes, plus functions for combining and optimizing numeric
* hash values.
*
* @stability stable
* @since 2.0.0
*/
/**
* Defines the unique identifier used to identify objects that implement the Hash interface.
*
* **When to use**
*
* Use as the computed property key for the method that supplies a custom hash
* value on a `Hash` implementor.
*
* @see {@link Hash} for the interface implemented with this symbol
* @see {@link isHash} for checking whether a value implements `Hash`
* @see {@link hash} for computing hash values
*
* @stability stable
* @category symbols
* @since 2.0.0
*/
const symbol$1 = "~effect/Hash";
/**
* Computes a hash value for any given value.
*
* **When to use**
*
* Use to compute an Effect hash for primitives, collections, and hashable
* objects.
*
* **Details**
*
* This function can hash primitives (numbers, strings, booleans, etc.) as well as
* objects, arrays, and other complex data structures. It automatically handles
* different types and provides a consistent hash value for equivalent inputs.
*
* **Gotchas**
*
* Objects being hashed must be treated as immutable after their first hash
* computation. Hash results are cached, so mutating an object after hashing will
* lead to stale cached values and broken hash-based operations. For mutable
* objects, implement a custom `Hash` interface that hashes the object reference
* rather than its content.
*
* **Example** (Hashing different values)
*
* ```ts import.meta.vitest
* import { Hash } from "effect"
*
* Hash.hash(42) === Hash.hash(42) // => true
* Hash.hash("hello") === Hash.hash("hello") // => true
* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true
* ```
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const hash = (self) => {
switch (typeof self) {
case "number":
return number$1(self);
case "bigint":
return string$1(self.toString(10));
case "string":
return string$1(self);
case "function":
case "object":
if (self === null) break;
else if (self instanceof Date) {
if (Number.isNaN(self.getTime()))
return string$1("Invalid Date");
return string$1(self.toISOString());
} else if (self instanceof RegExp)
return string$1(self.toString());
else {
if (byReferenceInstances.has(self))
return random(self);
const cached = hashCache.get(self);
if (cached !== void 0) return cached;
if (visitedObjects.has(self)) {
addBackEdge();
return string$1("[Circular]");
}
visitedObjects.add(self);
const seen = backEdges;
let h;
try {
if ("~effect/Hash" in self) h = self[symbol$1]();
else if (typeof self === "function")
h = random(self);
else if (self instanceof DataView)
h = array(viewBytes(self));
else if (
Array.isArray(self) ||
ArrayBuffer.isView(self)
)
h = array(self);
else if (self instanceof Map) h = hashMap(self);
else if (self instanceof Set) h = hashSet(self);
else h = structure(self);
} finally {
visitedObjects.delete(self);
}
if (seen === backEdges) hashCache.set(self, h);
return h;
}
}
return optimize(mix(string$1(String(self))));
};
/**
* Generates a random hash value for an object and caches it.
*
* **When to use**
*
* Use to hash an object by reference identity instead of structural content.
*
* **Details**
*
* This function creates a random hash value for objects that don't have their own
* hash implementation. The hash value is cached using a WeakMap, so the same object
* will always return the same hash value during its lifetime.
*
* **Example** (Hashing objects by reference)
*
* ```ts import.meta.vitest
* import { Hash } from "effect"
*
* const obj1 = { a: 1 }
* const obj2 = { a: 1 }
*
* Hash.random(obj1) === Hash.random(obj1) // => true
*
* typeof Hash.random(obj2) // => "number"
* ```
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const random = (self) => {
if (!randomHashCache.has(self))
randomHashCache.set(
self,
optimize((Math.random() * 4294967296) | 0),
);
return randomHashCache.get(self);
};
const mix = (h) => {
h ^= h >>> 16;
h = Math.imul(h, 2246822507);
h ^= h >>> 13;
h = Math.imul(h, 3266489909);
return h ^ (h >>> 16);
};
/**
* Combines two hash values into a single hash value.
*
* **When to use**
*
* Use to build a hash for a composite value by folding together hash values for
* its parts.
*
* **Details**
*
* Supports direct and pipeable usage. Argument order affects the result.
*
* **Example** (Combining hash values)
*
* ```ts import.meta.vitest
* import { Hash, pipe } from "effect"
*
* const hash1 = Hash.hash("hello")
* const hash2 = Hash.hash("world")
*
* const combined = Hash.combine(hash2)(hash1)
* combined === pipe(hash1, Hash.combine(hash2)) // => true
* ```
*
* @see {@link hash} for computing hash values from arbitrary inputs
* @see {@link structureKeys} for hashing selected object fields without manual combination
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const combine = /*#__PURE__*/ dual(2, (self, b) =>
mix(
Math.imul(self, 2654435761) + Math.imul(b, 2246822507),
),
);
/**
* Applies bit manipulation techniques to optimize a hash value.
*
* **When to use**
*
* Use to improve the bit distribution of a raw numeric hash value.
*
* **Details**
*
* This function takes a hash value and applies bitwise operations to improve
* the distribution of hash values, reducing the likelihood of collisions.
*
* **Example** (Optimizing a hash value)
*
* ```ts import.meta.vitest
* import { Hash } from "effect"
*
* Hash.optimize(1234567890) // => 160826066
* ```
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const optimize = (n) =>
(n & 3221225471) | ((n >>> 1) & 1073741824);
const float64 = /*#__PURE__*/ new DataView(
/*#__PURE__*/ new ArrayBuffer(8),
);
/**
* Computes a hash value for a number.
*
* **When to use**
*
* Use to hash a JavaScript number with Effect's numeric hash semantics.
*
* **Details**
*
* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits,
* with a canonical representation for `NaN`.
*
* **Example** (Hashing numbers)
*
* ```ts import.meta.vitest
* import { Hash } from "effect"
*
* Number.isInteger(Hash.number(42)) // => true
* Number.isInteger(Hash.number(3.14)) // => true
* Hash.number(NaN) === Hash.number(NaN) // => true
* Hash.number(Infinity) === Hash.number(Infinity) // => true
* Hash.number(100) === Hash.number(100) // => true
* ```
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const number$1 = (n) => {
const h = n | 0;
if (h === n) return optimize(h);
float64.setFloat64(0, n !== n ? NaN : n);
return optimize(
combine(float64.getInt32(0), float64.getInt32(4)),
);
};
/**
* Computes a hash value for a string using the djb2 algorithm.
*
* **When to use**
*
* Use when you need a string field to contribute to a custom structural hash
* implementation.
*
* **Details**
*
* This function implements a variation of the djb2 hash algorithm, which is
* known for its good distribution properties and speed. It processes each
* character of the string to produce a consistent hash value.
*
* **Example** (Hashing strings)
*
* ```ts import.meta.vitest
* import { Hash } from "effect"
*
* Hash.string("hello") // => 181380007
* Hash.string("world") // => 164394279
* Hash.string("") // => 5381
* Hash.string("test") === Hash.string("test") // => true
* ```
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const string$1 = (str) => {
let h = 5381,
i = str.length;
while (i) h = (h * 33) ^ str.charCodeAt(--i);
return optimize(h);
};
/**
* Computes a hash value for an object using only the specified keys.
*
* **When to use**
*
* Use to hash an object by a selected set of property keys.
*
* **Details**
*
* This function allows you to hash an object by considering only specific keys,
* which is useful when you want to create a hash based on a subset of an object's
* properties.
*
* **Example** (Hashing selected object keys)
*
* ```ts import.meta.vitest
* import { Hash } from "effect"
*
* const person = { name: "John", age: 30, city: "New York" }
*
* const hash1 = Hash.structureKeys(person, ["name", "age"])
* const hash2 = Hash.structureKeys(person, ["name", "city"])
*
* hash1 // => -731887653
* hash2 // => 148523102
*
* const person2 = { name: "John", age: 30, city: "Boston" }
* const hash3 = Hash.structureKeys(person2, ["name", "age"])
* hash1 === hash3 // => true
* ```
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const structureKeys = (o, keys) => {
let h = 12289;
for (const key of keys)
h ^= combine(hash(key), hash(o[key]));
return optimize(h);
};
/**
* Computes a structural hash for an object using Effect's object key collection.
*
* **When to use**
*
* Use to hash an object from all structural keys collected by Effect.
*
* **Details**
*
* The hash is based on the object's structural keys and their values, including
* symbol keys and relevant prototype keys for non-plain objects.
*
* **Example** (Hashing object structures)
*
* ```ts import.meta.vitest
* import { Hash } from "effect"
*
* const obj1 = { name: "John", age: 30 }
* const obj2 = { name: "Jane", age: 25 }
* const obj3 = { name: "John", age: 30 }
*
* Hash.structure(obj1) // => -731887653
* Hash.structure(obj2) // => -222100417
* Hash.structure(obj3) // => -731887653
* Hash.structure(obj1) === Hash.structure(obj3) // => true
* ```
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const structure = (o) =>
structureKeys(o, getAllObjectKeys(o));
const unordered = (seed, f) => (iter) => {
let h = seed;
for (const element of iter) h ^= f(element);
return optimize(h);
};
/**
* Computes a hash value for an iterable by hashing all of its elements.
*
* **When to use**
*
* Use to hash the values yielded by an iterable with Effect hash semantics.
*
* **Details**
*
* Folds element hashes with {@link combine}, so order and length affect the
* result.
*
* **Gotchas**
*
* A hash is not an equality proof. Distinct inputs can still share a hash.
*
* **Example** (Hashing arrays)
*
* ```ts import.meta.vitest
* import { Hash } from "effect"
*
* const arr1 = [1, 2, 3]
* const arr2 = [1, 2, 3]
* const arr3 = [3, 2, 1]
*
* Hash.array(arr1) === Hash.array(arr2) // => true
* Hash.array(arr1) === Hash.array(arr3) // => false
* ```
*
* @see {@link hash} for the general-purpose hash dispatcher
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const array = (arr) => {
let h = 6151;
for (const element of arr) h = combine(h, hash(element));
return optimize(h);
};
const hashMap = /*#__PURE__*/ unordered(
/*#__PURE__*/ string$1("Map"),
([k, v]) => combine(hash(k), hash(v)),
);
const setSeed = /*#__PURE__*/ string$1("Set");
const hashSet = /*#__PURE__*/ unordered(
setSeed,
(element) => combine(setSeed, hash(element)),
);
const randomHashCache = /*#__PURE__*/ new WeakMap();
const hashCache = /*#__PURE__*/ new WeakMap();
const visitedObjects = /*#__PURE__*/ new WeakSet();
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Equal.js
/**
* Defines the unique string identifier for the `Equal` interface.
*
* **When to use**
*
* Use when you implement custom equality and need the computed property key for
* the equality method.
*
* **Details**
*
* This is a pure constant with no allocation or side effects.
*
* **Example** (Implementing Equal on a class)
*
* ```ts import.meta.vitest
* import { Equal, Hash } from "effect"
*
* class UserId implements Equal.Equal {
* constructor(readonly id: string) {}
*
* [Equal.symbol](that: Equal.Equal): boolean {
* return that instanceof UserId && this.id === that.id
* }
*
* [Hash.symbol](): number {
* return Hash.string(this.id)
* }
* }
*
* Equal.equals(new UserId("1"), new UserId("1")) // => true
* Equal.equals(new UserId("1"), new UserId("2")) // => false
* ```
*
* @see {@link Equal} — the interface that uses this symbol
* @see {@link isEqual} — type guard for `Equal` implementors
* @stability stable
* @category symbols
* @since 2.0.0
*/
const symbol = "~effect/Equal";
function equals$1() {
if (arguments.length === 1)
return (self) => compareBoth(self, arguments[0]);
return compareBoth(arguments[0], arguments[1]);
}
function compareBoth(self, that) {
if (self === that) return true;
if (self == null || that == null) return false;
const selfType = typeof self;
if (selfType !== typeof that) return false;
if (
selfType === "number" &&
self !== self &&
that !== that
)
return true;
if (selfType !== "object" && selfType !== "function")
return false;
if (
byReferenceInstances.has(self) ||
byReferenceInstances.has(that)
)
return false;
return compareObjects(self, that);
}
function compareObjects(self, that) {
const depth = pathLeft.length;
for (let i = depth; i-- > 0;)
if (pathLeft[i] === self && pathRight[i] === that)
return true;
if (depth) return compareOnPath(self, that);
let known = results.get(self);
if (!known)
results.set(
self,
(known = /* @__PURE__ */ new WeakMap()),
);
let result = known.get(that);
if (result === void 0)
known.set(that, (result = compareOnPath(self, that)));
return result;
}
function compareOnPath(self, that) {
pathLeft.push(self);
pathRight.push(that);
try {
return compareStructure(self, that);
} finally {
pathLeft.pop();
pathRight.pop();
}
}
const pathLeft = [];
const pathRight = [];
const results = /*#__PURE__*/ new WeakMap();
function compareStructure(self, that) {
if (hash(self) !== hash(that)) return false;
else if (self instanceof Date) {
if (!(that instanceof Date)) return false;
const selfTime = self.getTime();
const thatTime = that.getTime();
return (
selfTime === thatTime ||
(Number.isNaN(selfTime) && Number.isNaN(thatTime))
);
} else if (self instanceof RegExp)
return (
that instanceof RegExp &&
self.toString() === that.toString()
);
const bothEquals = isEqual(self);
if (
bothEquals !== isEqual(that) ||
(typeof self === "function" && !bothEquals)
)
return false;
else if (bothEquals) return self[symbol](that);
else if (Array.isArray(self)) {
if (!Array.isArray(that) || self.length !== that.length)
return false;
return compareArrays(self, that);
} else if (ArrayBuffer.isView(self)) {
const selfIsDataView = self instanceof DataView;
if (
!ArrayBuffer.isView(that) ||
self.byteLength !== that.byteLength ||
selfIsDataView !== that instanceof DataView
)
return false;
if (selfIsDataView)
return compareTypedArrays(
viewBytes(self),
viewBytes(that),
);
return compareTypedArrays(self, that);
} else if (self instanceof Map) {
if (!(that instanceof Map) || self.size !== that.size)
return false;
return compareHashed(
self,
that,
entryHash,
equalEntries,
);
} else if (self instanceof Set) {
if (!(that instanceof Set) || self.size !== that.size)
return false;
return compareHashed(self, that, hash, compareBoth);
}
return compareRecords(self, that);
}
function compareArrays(self, that) {
for (let i = 0; i < self.length; i++)
if (!compareBoth(self[i], that[i])) return false;
return true;
}
function compareTypedArrays(self, that) {
if (self.length !== that.length) return false;
for (let i = 0; i < self.length; i++)
if (self[i] !== that[i]) return false;
return true;
}
function compareRecords(self, that) {
const selfKeys = getAllObjectKeys(self);
const thatKeys = getAllObjectKeys(that);
if (selfKeys.size !== thatKeys.size) return false;
for (const key of selfKeys)
if (
!thatKeys.has(key) ||
!compareBoth(self[key], that[key])
)
return false;
return true;
}
function compareHashed(self, that, hashOf, equivalent) {
const groups = /* @__PURE__ */ new Map();
let remaining = 0;
for (const item of that) {
const h = hashOf(item);
const group = groups.get(h);
if (group) group.push(item);
else groups.set(h, [item]);
remaining++;
}
outer: for (const item of self) {
const group = groups.get(hashOf(item));
if (group) {
for (let i = 0; i < group.length; i++)
if (equivalent(item, group[i])) {
group[i] = group[group.length - 1];
group.pop();
remaining--;
continue outer;
}
}
return false;
}
return remaining === 0;
}
const entryHash = (entry) => hash(entry[0]);
const equalEntries = (self, that) =>
compareBoth(self[0], that[0]) &&
compareBoth(self[1], that[1]);
/**
* Checks whether a value implements the {@link Equal} interface.
*
* **When to use**
*
* Use when you need generic utility code to distinguish `Equal` implementors
* from plain values before calling `[Equal.symbol]` directly.
*
* **Details**
*
* - Pure function, no side effects.
* - Returns `true` if and only if `u` has a property keyed by
* {@link symbol}.
* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}.
*
* **Example** (Checking Equal values)
*
* ```ts import.meta.vitest
* import { Equal, Hash } from "effect"
*
* class Token implements Equal.Equal {
* constructor(readonly value: string) {}
* [Equal.symbol](that: Equal.Equal): boolean {
* return that instanceof Token && this.value === that.value
* }
* [Hash.symbol](): number {
* return Hash.string(this.value)
* }
* }
*
* Equal.isEqual(new Token("abc")) // => true
* Equal.isEqual({ x: 1 }) // => false
* Equal.isEqual(42) // => false
* ```
*
* @see {@link Equal} — the interface being checked
* @see {@link symbol} — the property key that signals `Equal` support
* @stability stable
* @category guards
* @since 2.0.0
*/
const isEqual = (u) => hasProperty(u, symbol);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/array.js
/**
* @since 2.0.0
*/
/** @internal */
const isArrayNonEmpty$1 = (self) => self.length > 0;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/record.js
/** @internal */
function assignProperty(self, key, value) {
if (key === "__proto__")
Object.defineProperty(self, key, {
value,
writable: true,
enumerable: true,
configurable: true,
});
else self[key] = value;
}
/** @internal */
function assignProperties(self, source) {
for (const key of Reflect.ownKeys(source))
if (
Object.prototype.propertyIsEnumerable.call(
source,
key,
)
)
assignProperty(self, key, source[key]);
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Redactable.js
/**
* Defines the symbol used to identify objects that implement the {@link Redactable}
* protocol.
*
* **When to use**
*
* Use as the property key when implementing the `Redactable` protocol.
*
* **Details**
*
* Add a method under this key to make an object redactable. The method receives
* the current `Context` and must return the replacement value. The symbol is
* registered globally via `Symbol.for("~effect/Redactable")`, so it is
* identical across multiple copies of the library at runtime.
*
* **Example** (Masking an API key)
*
* ```ts import.meta.vitest
* import { Context, Redactable } from "effect"
*
* class ApiKey {
* constructor(readonly raw: string) {}
*
* [Redactable.symbolRedactable](_ctx: Context.Context<never>) {
* return this.raw.slice(0, 4) + "..."
* }
* }
*
* Redactable.redact(new ApiKey("secret-key")) // => "secr..."
* ```
*
* @see {@link Redactable} for the interface this symbol belongs to
* @see {@link isRedactable} to check whether a value has this symbol
* @stability stable
* @category symbols
* @since 3.10.0
*/
const symbolRedactable = /*#__PURE__*/ Symbol.for(
"~effect/Redactable",
);
/**
* Type guard that checks whether a value implements the {@link Redactable}
* interface.
*
* **When to use**
*
* Use to narrow an unknown value before calling redaction-specific helpers.
*
* @see {@link Redactable} for the interface being checked
* @see {@link redact} to apply redaction if the value is redactable
* @stability stable
* @category guards
* @since 3.10.0
*/
const isRedactable = (u) =>
hasProperty(u, symbolRedactable);
/**
* Returns a redacted value if it implements {@link Redactable}, otherwise returns it
* unchanged.
*
* **When to use**
*
* Use as the general-purpose entry point for redaction when the input may
* or may not implement the redaction protocol.
*
* **Details**
*
* This function calls {@link isRedactable} and, when it returns `true`,
* delegates to {@link getRedacted}.
*
* **Gotchas**
*
* Redaction is not recursive. Nested redactable values inside the returned
* object are not automatically redacted.
*
* @see {@link isRedactable} to check before redacting
* @see {@link getRedacted} for the lower-level variant for known redactables
* @stability stable
* @category destructors
* @since 3.10.0
*/
function redact$2(u) {
if (isRedactable(u)) return getRedacted(u);
return u;
}
/**
* Returns the result of calling `[symbolRedactable]` on a value that is
* already known to be {@link Redactable}.
*
* **When to use**
*
* Use when you need to read the redacted representation from a value already
* verified as `Redactable`.
*
* **Details**
*
* This function reads the current fiber's `Context` from the global fiber
* reference and passes it to the redaction method.
*
* **Gotchas**
*
* If no fiber is active, an empty `Context` is passed to the redaction method.
*
* @see {@link redact} for the higher-level variant that handles non-redactable values
* @see {@link isRedactable} for the type guard to verify before calling this
* @stability stable
* @category destructors
* @since 4.0.0
*/
function getRedacted(redactable) {
return redactable[symbolRedactable](
globalThis["~effect/Fiber/currentFiber"]?.context ??
emptyContext$1,
);
}
/** @internal */
const currentFiberTypeId = "~effect/Fiber/currentFiber";
const emptyMap = /*#__PURE__*/ new Map();
const emptyContext$1 = {
"~effect/Context": {},
base: emptyMap,
depth: 0,
mapUnsafe: emptyMap,
pipe() {
return pipeArguments(this, arguments);
},
};
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Formatter.js
/**
* Formats JavaScript values into readable strings.
*
* `format` is intended for logs, diagnostics, and error messages. It handles
* primitives, objects, arrays, dates, regular expressions, maps, sets, class
* instances, errors, circular references, and redactable values. `formatJson`
* wraps JSON formatting with redaction and circular-reference handling, and the
* module also includes helpers for property keys, paths, and dates.
*
* @stability stable
* @since 4.0.0
*/
/**
* Converts any JavaScript value into a human-readable string.
*
* **When to use**
*
* Use when you need to format arbitrary JavaScript values for debugging,
* logging, or error messages.
*
* **Details**
*
* - Output is **not** valid JSON; use {@link formatJson} when you need
* parseable JSON.
* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class
* instances that `JSON.stringify` cannot represent.
* - Circular references are shown as `"[Circular]"` instead of throwing.
* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing.
* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`).
* Strings are JSON-quoted.
* - Objects with a custom `toString` (not `Object.prototype.toString`):
* `toString()` is called unless `ignoreToString` is `true`.
* - Errors with a `cause`: formatted as `"<message> (cause: <cause>)"`.
* - Iterables (`Set`, `Map`, etc.): formatted as
* `ClassName([...elements])`.
* - Class instances: wrapped as `ClassName({...})`.
* - `Redactable` values are automatically redacted.
* - Arrays/objects with 0–1 entries are inline; larger ones are
* pretty-printed when `space` is set.
* - `space` — indentation unit (number of spaces, or a string like
* `"\t"`). Defaults to `0` (compact).
* - `ignoreToString` — skip calling `toString()`. Defaults to `false`.
*
* **Example** (Formatting compact output)
*
* ```ts import.meta.vitest
* import { Formatter } from "effect"
*
* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}"
* ```
*
* **Example** (Pretty-printed output)
*
* ```ts import.meta.vitest
* import { Formatter } from "effect"
*
* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 })
* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}"
* ```
*
* **Example** (Handling circular references)
*
* ```ts import.meta.vitest
* import { Formatter } from "effect"
*
* const obj: any = { name: "loop" }
* obj.self = obj
* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}"
* ```
*
* @see {@link formatJson}
* @see {@link Formatter}
* @stability stable
* @category formatting
* @since 2.0.0
*/
function format$1(input, options) {
const space = options?.space ?? 0;
const ancestors = /* @__PURE__ */ new WeakSet();
const gap = !space
? ""
: typeof space === "number"
? " ".repeat(space)
: space;
const ind = (d) => gap.repeat(d);
const wrap = (v, body) => {
const ctor = v?.constructor;
return ctor &&
ctor !== Object.prototype.constructor &&
ctor.name
? `${ctor.name}(${body})`
: body;
};
const ownKeys = (o) => {
try {
return Reflect.ownKeys(o);
} catch {
return ["[ownKeys threw]"];
}
};
function recur(v, d = 0) {
try {
return recurUnsafe(v, d);
} catch {
if (
(typeof v === "object" && v !== null) ||
typeof v === "function"
)
ancestors.delete(v);
return "[inspection threw]";
}
}
function recurUnsafe(v, d = 0) {
if (typeof v === "string") return JSON.stringify(v);
if (
typeof v === "number" ||
v == null ||
typeof v === "boolean" ||
typeof v === "symbol"
)
return String(v);
if (typeof v === "bigint") return String(v) + "n";
if (typeof v === "object" || typeof v === "function") {
if (ancestors.has(v)) return CIRCULAR;
ancestors.add(v);
let output;
if (symbolRedactable in v)
output = recur(getRedacted(v), d);
else if (Array.isArray(v))
output =
!gap || v.length <= 1
? `[${v.map((x) => recur(x, d)).join(",")}]`
: `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`;
else if (v instanceof Date) output = formatDate(v);
else if (
!options?.ignoreToString &&
hasProperty(v, "toString") &&
typeof v["toString"] === "function" &&
v["toString"] !== Object.prototype.toString &&
v["toString"] !== Array.prototype.toString
) {
const s = safeToString(v);
output =
v instanceof Error && v.cause !== void 0
? `${s} (cause: ${recur(v.cause, d)})`
: s;
} else if (Symbol.iterator in v)
output = `${v.constructor.name}(${recur(Array.from(v), d)})`;
else {
const keys = ownKeys(v);
if (!gap || keys.length <= 1) {
const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`;
output = wrap(v, body);
} else {
const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`;
output = wrap(v, body);
}
}
ancestors.delete(v);
return output;
}
return String(v);
}
return recur(input, 0);
}
const CIRCULAR = "[Circular]";
/**
* @internal
*/
function formatPropertyKey(name) {
return typeof name === "string"
? JSON.stringify(name)
: String(name);
}
/**
* Formats an array of property keys as a bracket-notation path string.
*
* @internal
*/
function formatPath(path) {
return path
.map((key) => `[${formatPropertyKey(key)}]`)
.join("");
}
/**
* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for
* invalid dates instead of throwing.
*
* @internal
*/
function formatDate(date) {
try {
return date.toISOString();
} catch {
return "Invalid Date";
}
}
function safeToString(input) {
try {
const s = input.toString();
return typeof s === "string" ? s : String(s);
} catch {
return "[toString threw]";
}
}
function safeGet(input, key) {
try {
return input[key];
} catch {
return "[property access threw]";
}
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Inspectable.js
/**
* Controls how values appear in logs and debugging output.
*
* Effect data types use `Inspectable` to provide stable string, JSON, and
* Node.js inspection output. This keeps custom values readable in logs, REPLs,
* test failures, and diagnostics. This module defines the Node inspect symbol,
* the `Inspectable` interface, safe conversion helpers, and shared prototype or
* class implementations for custom values.
*
* @stability stable
* @since 2.0.0
*/
/**
* Defines the symbol used by Node.js for custom object inspection.
*
* **When to use**
*
* Use to implement Node.js custom inspection for a value.
*
* **Details**
*
* This symbol is recognized by Node.js's `util.inspect()` function and the REPL
* for custom object representation. When an object has a method with this symbol,
* it will be called to determine how the object should be displayed.
*
* **Example** (Defining custom Node inspection)
*
* ```ts import.meta.vitest
* import { Inspectable } from "effect"
*
* class CustomObject {
* constructor(private value: string) {}
*
* [Inspectable.NodeInspectSymbol]() {
* return `CustomObject(${this.value})`
* }
* }
*
* const obj = new CustomObject("hello")
* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)"
* ```
*
* @stability stable
* @category symbols
* @since 2.0.0
*/
const NodeInspectSymbol = /*#__PURE__*/ Symbol.for(
"nodejs.util.inspect.custom",
);
/**
* Converts a value to its structured inspection representation.
*
* **When to use**
*
* Use when you need the structured representation of an inspectable value
* without risking unhandled errors.
*
* **Details**
*
* This function applies redaction before extracting data from objects that
* implement `toJSON`, recursively processes arrays, and handles errors
* gracefully. Plain objects are returned unchanged, so the result is not
* guaranteed to be accepted by `JSON.stringify`; it may still contain values
* such as `BigInt`, functions, or circular references.
*
* @see {@link toStringUnknown} for converting unknown values to strings
*
* @stability stable
* @category converting
* @since 4.0.0
*/
const toJson = (input) => {
try {
input = redact$2(input);
if (
hasProperty(input, "toJSON") &&
isFunction(input["toJSON"]) &&
input["toJSON"].length === 0
)
return input.toJSON();
else if (Array.isArray(input)) return input.map(toJson);
return input;
} catch {
return "[toJSON threw]";
}
};
/**
* A base prototype object that implements the {@link Inspectable} interface.
*
* **When to use**
*
* Use as a prototype for plain objects that should share standard inspectable behavior.
*
* **Details**
*
* This object provides default implementations for the {@link Inspectable} methods.
* It can be used as a prototype for objects that want to be inspectable,
* or as a mixin to add inspection capabilities to existing objects.
*
* **Example** (Using the base inspectable prototype)
*
* ```ts import.meta.vitest
* import { Inspectable } from "effect"
*
* // Use as prototype
* const myObject = Object.create(Inspectable.BaseProto)
* myObject.name = "example"
* myObject.value = 42
*
* myObject.toString() // => "\"[toJSON threw]\""
*
* // Or extend in a constructor
* function MyClass(this: any, name: string) {
* this.name = name
* }
* MyClass.prototype = Object.create(Inspectable.BaseProto)
* MyClass.prototype.constructor = MyClass
* ```
*
* @stability stable
* @category prototypes
* @since 2.0.0
*/
const BaseProto = {
toJSON() {
return toJson(this);
},
[NodeInspectSymbol]() {
return this.toJSON();
},
toString() {
return format$1(this.toJSON());
},
};
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/stackTraceLimit.js
/**
* Check if `Error.stackTraceLimit` is writable.
* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible.
*
* @internal
*/
const isStackTraceLimitWritable = () => {
const desc = Object.getOwnPropertyDescriptor(
Error,
"stackTraceLimit",
);
if (desc === void 0) return Object.isExtensible(Error);
return Object.hasOwn(desc, "writable")
? desc.writable === true
: desc.set !== void 0;
};
const canWriteStackTraceLimit =
/*#__PURE__*/ isStackTraceLimitWritable();
/**
* Get the current `Error.stackTraceLimit` value.
* Returns `undefined` if the property doesn't exist.
*
* @internal
*/
const getStackTraceLimit = () => Error.stackTraceLimit;
/**
* Safely set `Error.stackTraceLimit` if possible, otherwise no-op.
*
* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be
* restored faithfully.
*
* @internal
*/
const setStackTraceLimit = (value) => {
if (canWriteStackTraceLimit)
Error.stackTraceLimit = value;
};
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Utils.js
/**
* Yields its wrapped value exactly once, then completes with the value sent
* back in.
*
* **When to use**
*
* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be
* `yield*`-ed inside generator functions, such as `Effect.gen` and
* `Option.gen`.
*
* **Details**
*
* The first call to `next()` returns a fresh `{ value: self, done: false }`.
* Every subsequent call returns `{ value: a, done: true }` where `a` is the
* argument passed to `next()`. To keep `yield*` cheap, the completion result
* is the iterator itself rather than a new object, so only the iterator and
* the single yielded result are allocated per `yield*`.
*
* **Example** (Yielding a wrapped value in a generator)
*
* ```ts import.meta.vitest
* import { Utils } from "effect"
*
* const gen = new Utils.SingleShotGen<string, number>("hello")
*
* gen.next(0).value // => "hello"
*
* gen.next(42).value // => 42
* ```
*
* @see {@link Gen} for the type-level signature that relies on `SingleShotGen`
* @stability stable
* @category constructors
* @since 2.0.0
*/
var SingleShotGen = class {
constructor(self) {
this.value = self;
this.done = false;
}
/**
* Yields the stored value once, then completes with the value sent back in.
*
* **When to use**
*
* Use to advance a `SingleShotGen` through its single yield and completion
* step.
*
* @since 2.0.0
*/
next(a) {
if (this.done) {
this.value = a;
return this;
}
this.done = true;
return {
value: this.value,
done: false,
};
}
};
const pickInternalCall = () => {
const InternalTypeId = "~effect/Utils/internal";
const standard = {
[InternalTypeId]: (body) => {
return body();
},
};
const forced = {
[InternalTypeId]: (body) => {
try {
return body();
} finally {
}
},
};
const limit = getStackTraceLimit();
if (limit === 0) return forced[InternalTypeId];
setStackTraceLimit(2);
const error = standard[InternalTypeId](
() => /* @__PURE__ */ new Error(),
);
setStackTraceLimit(limit);
return error.stack?.includes(InternalTypeId) === true
? standard[InternalTypeId]
: forced[InternalTypeId];
};
/** @internal */
const internalCall = /*#__PURE__*/ pickInternalCall();
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/core.js
/** @internal */
const EffectTypeId = `~effect/Effect`;
/** @internal */
const ExitTypeId = `~effect/Exit`;
const effectVariance = {
_A: identity,
_E: identity,
_R: identity,
};
/** @internal */
const identifier = `${EffectTypeId}/identifier`;
/** @internal */
const args = `${EffectTypeId}/args`;
/** @internal */
const evaluate = `${EffectTypeId}/evaluate`;
/** @internal */
const contA = `${EffectTypeId}/successCont`;
/** @internal */
const contE = `${EffectTypeId}/failureCont`;
/** @internal */
const contAll = `${EffectTypeId}/ensureCont`;
/** @internal */
const Yield = /*#__PURE__*/ Symbol.for(
"effect/Effect/Yield",
);
/** @internal */
const PipeInspectableProto = {
pipe() {
return pipeArguments(this, arguments);
},
toJSON() {
return { ...this };
},
toString() {
return format$1(this.toJSON(), {
ignoreToString: true,
space: 2,
});
},
[NodeInspectSymbol]() {
return this.toJSON();
},
};
/** @internal */
const EffectProto = {
[EffectTypeId]: effectVariance,
...PipeInspectableProto,
[Symbol.iterator]() {
return new SingleShotGen(this);
},
toJSON() {
return {
_id: "Effect",
op: this[identifier],
...("~effect/Effect/args" in this
? { args: this[args] }
: void 0),
};
},
};
/** @internal */
const isExit = (u) => hasProperty(u, ExitTypeId);
/** @internal */
const CauseTypeId = "~effect/Cause";
/** @internal */
const CauseReasonTypeId = "~effect/Cause/Reason";
/** @internal */
const isCause = (self) => hasProperty(self, CauseTypeId);
/** @internal */
var CauseImpl = class {
constructor(failures) {
this[CauseTypeId] = CauseTypeId;
this.reasons = failures;
}
pipe() {
return pipeArguments(this, arguments);
}
toJSON() {
return {
_id: "Cause",
failures: this.reasons.map((f) => f.toJSON()),
};
}
toString() {
return `Cause(${format$1(this.reasons)})`;
}
[NodeInspectSymbol]() {
return this.toJSON();
}
[symbol](that) {
return (
isCause(that) &&
this.reasons.length === that.reasons.length &&
this.reasons.every((e, i) =>
equals$1(e, that.reasons[i]),
)
);
}
[symbol$1]() {
return array(this.reasons);
}
};
const annotationsMap = /*#__PURE__*/ new WeakMap();
/** @internal */
var ReasonBase = class {
[CauseReasonTypeId];
annotations;
_tag;
constructor(_tag, annotations, originalError) {
this[CauseReasonTypeId] = CauseReasonTypeId;
this._tag = _tag;
if (
annotations !== constEmptyAnnotations &&
typeof originalError === "object" &&
originalError !== null &&
annotations.size > 0
) {
const prevAnnotations =
annotationsMap.get(originalError);
if (prevAnnotations)
annotations = new Map([
...prevAnnotations,
...annotations,
]);
annotationsMap.set(originalError, annotations);
}
this.annotations = annotations;
}
annotate(annotations, options) {
if (annotations.mapUnsafe.size === 0) return this;
const newAnnotations = new Map(this.annotations);
annotations.mapUnsafe.forEach((value, key) => {
if (
options?.overwrite !== true &&
newAnnotations.has(key)
)
return;
newAnnotations.set(key, value);
});
const self = Object.assign(
Object.create(Object.getPrototypeOf(this)),
this,
);
self.annotations = newAnnotations;
return self;
}
pipe() {
return pipeArguments(this, arguments);
}
toString() {
return format$1(this);
}
[NodeInspectSymbol]() {
return this.toString();
}
};
/** @internal */
const constEmptyAnnotations = /*#__PURE__*/ new Map();
/** @internal */
var Fail = class extends ReasonBase {
constructor(error, annotations = constEmptyAnnotations) {
super("Fail", annotations, error);
this.error = error;
}
toString() {
return `Fail(${format$1(this.error)})`;
}
toJSON() {
return {
_tag: "Fail",
error: this.error,
};
}
[symbol](that) {
return (
isFailReason$1(that) &&
equals$1(this.error, that.error) &&
equals$1(this.annotations, that.annotations)
);
}
[symbol$1]() {
return combine(string$1(this._tag))(
combine(hash(this.error))(hash(this.annotations)),
);
}
};
/** @internal */
const causeFromReasons = (reasons) =>
new CauseImpl(reasons);
const dedupeReasons = (self, that) => {
const buckets = /* @__PURE__ */ new Map();
const out = [];
for (const reason of self.concat(that)) {
const hash$2 = hash(reason);
const bucket = buckets.get(hash$2);
if (bucket === void 0) buckets.set(hash$2, [reason]);
else if (
bucket.some((previous) => equals$1(previous, reason))
)
continue;
else bucket.push(reason);
out.push(reason);
}
return out;
};
/** @internal */
const causeCombine = /*#__PURE__*/ dual(2, (self, that) => {
if (self.reasons.length === 0) return that;
else if (that.reasons.length === 0) return self;
const newCause = new CauseImpl(
dedupeReasons(self.reasons, that.reasons),
);
return equals$1(self, newCause) ? self : newCause;
});
/**
* Appends the interrupts from `interrupts` that `self` does not contain yet.
* Unlike `causeCombine`, it never calls hash or equality methods, which can be
* user-defined, random, or throwing.
*
* @internal
*/
const causeAddInterrupts = (self, interrupts) => {
const reasons = self.reasons.slice();
for (const reason of interrupts.reasons)
if (
isInterruptReason(reason) &&
!reasons.some(
(r) =>
isInterruptReason(r) &&
r.fiberId === reason.fiberId &&
r.annotations === reason.annotations,
)
)
reasons.push(reason);
return reasons.length === self.reasons.length
? self
: new CauseImpl(reasons);
};
/** @internal */
const causeFail = (error) =>
new CauseImpl([new Fail(error)]);
/** @internal */
var Die = class extends ReasonBase {
constructor(defect, annotations = constEmptyAnnotations) {
super("Die", annotations, defect);
this.defect = defect;
}
toString() {
return `Die(${format$1(this.defect)})`;
}
toJSON() {
return {
_tag: "Die",
defect: this.defect,
};
}
[symbol](that) {
return (
isDieReason(that) &&
equals$1(this.defect, that.defect) &&
equals$1(this.annotations, that.annotations)
);
}
[symbol$1]() {
return combine(string$1(this._tag))(
combine(hash(this.defect))(hash(this.annotations)),
);
}
};
/** @internal */
const causeDie = (defect) =>
new CauseImpl([new Die(defect)]);
/** @internal */
const causeAnnotate = /*#__PURE__*/ dual(
(args) => isCause(args[0]),
(self, annotations, options) => {
if (annotations.mapUnsafe.size === 0) return self;
return new CauseImpl(
self.reasons.map((f) =>
f.annotate(annotations, options),
),
);
},
);
/** @internal */
const isFailReason$1 = (self) => self._tag === "Fail";
/** @internal */
const isDieReason = (self) => self._tag === "Die";
/** @internal */
const isInterruptReason = (self) =>
self._tag === "Interrupt";
function defaultEvaluate(_fiber) {
return exitDie(`Effect.evaluate: Not implemented`);
}
/** @internal */
const makePrimitiveProto = (options) => ({
...EffectProto,
[identifier]: options.op,
[evaluate]:
options["~effect/Effect/evaluate"] ?? defaultEvaluate,
[contA]: options[contA],
[contE]: options[contE],
[contAll]: options[contAll],
});
/** @internal */
const makePrimitive = (options) => {
const Proto = makePrimitiveProto(options);
const PrimitiveImpl = function (value) {
this[args] = value;
};
PrimitiveImpl.prototype = Proto;
return function (value) {
return new PrimitiveImpl(value);
};
};
/** @internal */
const makeExit = (options) => {
const Proto = {
[ExitTypeId]: ExitTypeId,
_tag: options.op,
get [options.prop]() {
return this[args];
},
...makePrimitiveProto(options),
toString() {
return `${options.op}(${format$1(this[args])})`;
},
toJSON() {
return {
_id: "Exit",
_tag: options.op,
[options.prop]: this[args],
};
},
[symbol](that) {
return (
isExit(that) &&
that._tag === this._tag &&
equals$1(
this["~effect/Effect/args"],
that["~effect/Effect/args"],
)
);
},
[symbol$1]() {
return combine(
string$1(options.op),
hash(this[args]),
);
},
};
const ExitPrimitive = function (value) {
this[args] = value;
};
ExitPrimitive.prototype = Proto;
return function (value) {
return new ExitPrimitive(value);
};
};
/** @internal */
const exitSucceed = /*#__PURE__*/ makeExit({
op: "Success",
prop: "value",
[evaluate](fiber) {
const cont = fiber.getCont(contA);
return cont
? cont[contA](this[args], fiber, this)
: fiber.yieldWith(this);
},
});
/** @internal */
const StackTraceKey = { key: "effect/Cause/StackTrace" };
/** @internal */
const InterruptorStackTrace = {
key: "effect/Cause/InterruptorStackTrace",
};
/** @internal */
const exitFailCause = /*#__PURE__*/ makeExit({
op: "Failure",
prop: "cause",
[evaluate](fiber) {
let cause = this[args];
let annotated = false;
if (fiber.cache.stackFrame) {
cause = causeAnnotate(cause, {
mapUnsafe: /* @__PURE__ */ new Map([
[StackTraceKey.key, fiber.cache.stackFrame],
]),
});
annotated = true;
}
let cont = fiber.getCont(contE);
const interruptedCause = fiber._interruptedCause;
if (interruptedCause && fiber.interruptible) {
let skippedHandler = false;
while (cont && fiber.interruptible) {
skippedHandler ||= identifier in cont;
cont = fiber.getCont(contE);
}
if (skippedHandler)
cause = causeFromReasons(
cause.reasons.filter(
(reason) => reason._tag !== "Fail",
),
);
cause = causeAddInterrupts(cause, interruptedCause);
annotated = true;
}
return cont
? cont[contE](cause, fiber, annotated ? void 0 : this)
: fiber.yieldWith(
annotated ? exitFailCause(cause) : this,
);
},
});
/** @internal */
const exitFail = (e) => exitFailCause(causeFail(e));
/** @internal */
const exitDie = (defect) => exitFailCause(causeDie(defect));
/** @internal */
const withFiber = /*#__PURE__*/ makePrimitive({
op: "WithFiber",
[evaluate](fiber) {
return this[args](fiber);
},
});
/** @internal */
const YieldableError = /*#__PURE__*/ (function () {
class YieldableError extends globalThis.Error {}
const proto = /*#__PURE__*/ makePrimitiveProto({
op: "YieldableError",
[evaluate]() {
return exitFail(this);
},
});
delete proto.toString;
Object.assign(YieldableError.prototype, proto);
return YieldableError;
})();
/** @internal */
const Error$2 = /*#__PURE__*/ (function () {
const plainArgsSymbol = /*#__PURE__*/ Symbol.for(
"effect/Data/Error/plainArgs",
);
return class Base extends YieldableError {
constructor(args) {
super(
args?.message,
args?.cause ? { cause: args.cause } : void 0,
);
if (args) {
assignProperties(this, args);
Object.defineProperty(this, plainArgsSymbol, {
value: args,
enumerable: false,
});
}
}
toJSON() {
return {
...this[plainArgsSymbol],
...this,
};
}
};
})();
/** @internal */
const TaggedError$1 = (tag) => {
class Base extends Error$2 {
_tag = tag;
}
Base.prototype.name = tag;
return Base;
};
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/option.js
/**
* @since 2.0.0
*/
const TypeId$15 = "~effect/Option";
const CommonProto$1 = {
[TypeId$15]: { _A: (_) => _ },
...PipeInspectableProto,
[Symbol.iterator]() {
return new SingleShotGen(this);
},
};
const SomeProto = /*#__PURE__*/ Object.defineProperty(
/*#__PURE__*/ Object.assign(
/*#__PURE__*/ Object.create(CommonProto$1),
{
_tag: "Some",
_op: "Some",
[symbol](that) {
return (
isOption(that) &&
isSome$1(that) &&
equals$1(this.value, that.value)
);
},
[symbol$1]() {
return combine(hash(this._tag))(hash(this.value));
},
toString() {
return `some(${format$1(this.value)})`;
},
toJSON() {
return {
_id: "Option",
_tag: this._tag,
value: toJson(this.value),
};
},
},
),
"valueOrUndefined",
{
get() {
return this.value;
},
},
);
const NoneHash = /*#__PURE__*/ hash("None");
const NoneProto = /*#__PURE__*/ Object.assign(
/*#__PURE__*/ Object.create(CommonProto$1),
{
_tag: "None",
_op: "None",
valueOrUndefined: void 0,
[symbol](that) {
return isOption(that) && isNone$1(that);
},
[symbol$1]() {
return NoneHash;
},
toString() {
return `none()`;
},
toJSON() {
return {
_id: "Option",
_tag: this._tag,
};
},
},
);
/** @internal */
const isOption = (input) => hasProperty(input, TypeId$15);
/** @internal */
const isNone$1 = (fa) => fa._tag === "None";
/** @internal */
const isSome$1 = (fa) => fa._tag === "Some";
/** @internal */
const none$1 = /*#__PURE__*/ Object.create(NoneProto);
/** @internal */
const SomeImpl = function (value) {
this.value = value;
};
SomeImpl.prototype = SomeProto;
/** @internal */
const some$1 = (value) => new SomeImpl(value);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/result.js
const TypeId$14 = "~effect/Result";
const CommonProto = {
[TypeId$14]: {
/* v8 ignore next 2 */
_A: (_) => _,
_E: (_) => _,
},
...PipeInspectableProto,
[Symbol.iterator]() {
return new SingleShotGen(this);
},
};
const SuccessProto = /*#__PURE__*/ Object.assign(
/*#__PURE__*/ Object.create(CommonProto),
{
_tag: "Success",
_op: "Success",
[symbol](that) {
return (
isResult(that) &&
isSuccess$2(that) &&
equals$1(this.success, that.success)
);
},
[symbol$1]() {
return combine(hash(this._tag))(hash(this.success));
},
toString() {
return `success(${format$1(this.success)})`;
},
toJSON() {
return {
_id: "Result",
_tag: this._tag,
value: toJson(this.success),
};
},
},
);
const FailureProto = /*#__PURE__*/ Object.assign(
/*#__PURE__*/ Object.create(CommonProto),
{
_tag: "Failure",
_op: "Failure",
[symbol](that) {
return (
isResult(that) &&
isFailure$1(that) &&
equals$1(this.failure, that.failure)
);
},
[symbol$1]() {
return combine(hash(this._tag))(hash(this.failure));
},
toString() {
return `failure(${format$1(this.failure)})`;
},
toJSON() {
return {
_id: "Result",
_tag: this._tag,
failure: toJson(this.failure),
};
},
},
);
/** @internal */
const isResult = (input) => hasProperty(input, TypeId$14);
/** @internal */
const isFailure$1 = (result) => result._tag === "Failure";
/** @internal */
const isSuccess$2 = (result) => result._tag === "Success";
/** @internal */
const FailureImpl = function (failure) {
this.failure = failure;
};
FailureImpl.prototype = FailureProto;
/** @internal */
const SuccessImpl = function (success) {
this.success = success;
};
SuccessImpl.prototype = SuccessProto;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Order.js
/**
* Defines comparison functions for ordered values.
*
* An `Order<A>` compares two `A` values and returns whether the first is less
* than, equal to, or greater than the second. Orders are used for sorting,
* choosing minimum or maximum values, checking ranges, and building ordered data
* structures. This module includes built-in orders, constructors for custom
* orders, tools for reversing and combining comparisons, tuple and struct
* helpers, comparison predicates, clamping, and reducer support.
*
* @stability stable
* @since 2.0.0
*/
/**
* Creates a new `Order` instance from a comparison function.
*
* **When to use**
*
* Use when you need a sorting rule not covered by the built-in orders or input
* mapping helpers, and you can provide a total comparison.
*
* **Details**
*
* Uses reference equality (`===`) as a shortcut: if `self === that`, it returns
* `0` without calling the comparison function. The comparison function should
* return `-1`, `0`, or `1`, and the returned order satisfies total ordering
* laws when the comparison function does.
*
* **Example** (Creating an Order)
*
* ```ts import.meta.vitest
* import { Order } from "effect"
*
* const byAge = Order.make<{ name: string; age: number }>((self, that) => {
* if (self.age < that.age) return -1
* if (self.age > that.age) return 1
* return 0
* })
*
* byAge({ name: "Alice", age: 30 }, { name: "Bob", age: 25 }) // => 1
* byAge({ name: "Alice", age: 25 }, { name: "Bob", age: 30 }) // => -1
* ```
*
* @see {@link mapInput} to transform an order by mapping the input type
* @see {@link combine} to combine multiple orders
* @stability stable
* @category constructors
* @since 2.0.0
*/
function make$10(compare) {
return (self, that) =>
self === that ? 0 : compare(self, that);
}
/**
* Order instance for strings that compares them lexicographically using JavaScript's `<` operator.
*
* **When to use**
*
* Use when you need lexicographic string ordering.
*
* **Details**
*
* Uses lexicographic dictionary ordering. The empty string is less than any
* non-empty string, and comparisons are case-sensitive.
*
* **Example** (Ordering strings)
*
* ```ts import.meta.vitest
* import { Order } from "effect"
*
* Order.String("apple", "banana") // => -1
* Order.String("banana", "apple") // => 1
* Order.String("apple", "apple") // => 0
* ```
*
* @see {@link mapInput} to compare objects by a string property
* @see {@link Struct} to combine with other orders for struct comparison
* @stability stable
* @category instances
* @since 4.0.0
*/
const String$4 = /*#__PURE__*/ make$10((self, that) =>
self < that ? -1 : 1,
);
/**
* Order instance for numbers that compares them numerically.
*
* **When to use**
*
* Use when you need numeric ordering for numbers.
*
* **Details**
*
* `0` is considered equal to `-0`. All `NaN` values are considered equal to
* each other, and any `NaN` is considered less than any non-`NaN` number. All
* other values use standard numeric comparison.
*
* **Example** (Ordering numbers)
*
* ```ts import.meta.vitest
* import { Order } from "effect"
*
* Order.Number(1, 1) // => 0
* Order.Number(1, 2) // => -1
* Order.Number(2, 1) // => 1
*
* Order.Number(0, -0) // => 0
* Order.Number(NaN, 1) // => -1
* ```
*
* @see {@link mapInput} to compare objects by a number property
* @see {@link BigInt} for bigint comparisons
* @stability stable
* @category instances
* @since 4.0.0
*/
const Number$4 = /*#__PURE__*/ make$10((self, that) => {
if (
globalThis.Number.isNaN(self) &&
globalThis.Number.isNaN(that)
)
return 0;
if (globalThis.Number.isNaN(self)) return -1;
if (globalThis.Number.isNaN(that)) return 1;
return self < that ? -1 : 1;
});
/**
* Checks whether one value is less than or equal to another according to the given order.
*
* **When to use**
*
* Use when you need a boolean less-than-or-equal predicate using an `Order`.
*
* **Details**
*
* Returns `true` if the order returns `-1` or `0`, and returns `false` only if
* the order returns `1`.
*
* **Example** (Checking less-than-or-equal comparisons)
*
* ```ts import.meta.vitest
* import { Order } from "effect"
*
* const isLessThanOrEqualToNumber = Order.isLessThanOrEqualTo(Order.Number)
*
* isLessThanOrEqualToNumber(1, 2) // => true
* isLessThanOrEqualToNumber(1, 1) // => true
* isLessThanOrEqualToNumber(2, 1) // => false
* ```
*
* @see {@link isLessThan} for strict less than
* @see {@link isGreaterThan} for strict greater than
* @stability stable
* @category predicates
* @since 4.0.0
*/
const isLessThanOrEqualTo$1 = (O) =>
dual(2, (self, that) => O(self, that) !== 1);
/**
* Checks whether one value is greater than or equal to another according to the given order.
*
* **When to use**
*
* Use when you need a boolean greater-than-or-equal predicate using an
* `Order`.
*
* **Details**
*
* Returns `true` if the order returns `1` or `0`, and returns `false` only if
* the order returns `-1`.
*
* **Example** (Checking greater-than-or-equal comparisons)
*
* ```ts import.meta.vitest
* import { Order } from "effect"
*
* const isGreaterThanOrEqualToNumber = Order.isGreaterThanOrEqualTo(Order.Number)
*
* isGreaterThanOrEqualToNumber(2, 1) // => true
* isGreaterThanOrEqualToNumber(1, 1) // => true
* isGreaterThanOrEqualToNumber(1, 2) // => false
* ```
*
* @see {@link isGreaterThan} for strict greater than
* @see {@link isLessThanOrEqualTo} for less than or equal
* @stability stable
* @category predicates
* @since 4.0.0
*/
const isGreaterThanOrEqualTo$1 = (O) =>
dual(2, (self, that) => O(self, that) !== -1);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Option.js
/**
* Creates an `Option` representing the absence of a value.
*
* **When to use**
*
* Use to represent a missing or uninitialized value, such as returning "no
* result" from a function.
*
* **Details**
*
* - Returns `Option<never>`, which is a subtype of `Option<A>` for any `A`
* - Always returns the same singleton instance
*
* **Example** (Creating an empty Option)
*
* ```ts import.meta.vitest
* import { Option } from "effect"
*
* // ┌─── Option<never>
* // â–¼
* const noValue = Option.none() // => Option.none()
* ```
*
* @see {@link some} for the opposite operation.
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const none = () => none$1;
/**
* Wraps the given value into an `Option` to represent its presence.
*
* **When to use**
*
* Use to wrap a known present value as `Option`
* - Returning a successful result from a partial function
*
* **Details**
*
* - Always returns `Some<A>`
* - Does not filter `null` or `undefined`; use {@link fromNullishOr} for that
*
* **Example** (Wrapping a value)
*
* ```ts import.meta.vitest
* import { Option } from "effect"
*
* // ┌─── Option<number>
* // â–¼
* const value = Option.some(1) // => Option.some(1)
* ```
*
* @see {@link none} for the opposite operation.
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const some = some$1;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Array.js
/**
* Exposes the global array constructor.
*
* **When to use**
*
* Use to access native JavaScript array constructor methods such as `isArray`
* or `from` from the Effect module namespace.
*
* **Example** (Accessing the Array constructor)
*
* ```ts import.meta.vitest
* import { Array } from "effect"
*
* Array.Array === globalThis.Array // => true
* ```
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Array$1 = globalThis.Array;
/**
* Adds a single element to the end of an iterable, returning a `NonEmptyArray`.
*
* **When to use**
*
* Use when you need to guarantee a non-empty result after adding a required
* trailing value.
*
* **Example** (Appending an element)
*
* ```ts import.meta.vitest
* import { Array } from "effect"
*
* Array.append([1, 2, 3], 4) // => [1, 2, 3, 4]
* ```
*
* @see {@link prepend} — add to the front
* @see {@link appendAll} — append multiple elements
*
* @stability stable
* @category combining
* @since 2.0.0
*/
const append = /*#__PURE__*/ dual(2, (self, last) => [
...self,
last,
]);
Array$1.isArray;
/**
* Checks whether a mutable `Array` is non-empty, narrowing the type to
* `NonEmptyArray`.
*
* **When to use**
*
* Use when you need the narrowed value to remain a mutable `Array` after proving
* it has at least one element.
*
* **Example** (Checking for a non-empty array)
*
* ```ts import.meta.vitest
* import { Array } from "effect"
*
* Array.isArrayNonEmpty([]) // => false
* Array.isArrayNonEmpty([1, 2, 3]) // => true
* ```
*
* @see {@link isReadonlyArrayNonEmpty} — readonly variant
* @see {@link isArrayEmpty} — opposite check
*
* @stability stable
* @category guards
* @since 4.0.0
*/
const isArrayNonEmpty = isArrayNonEmpty$1;
/**
* Checks whether a `ReadonlyArray` is non-empty, narrowing the type to
* `NonEmptyReadonlyArray`.
*
* **When to use**
*
* Use when you need to prove a readonly array has at least one element without
* requiring mutable array methods afterward.
*
* **Example** (Checking for a non-empty readonly array)
*
* ```ts import.meta.vitest
* import { Array } from "effect"
*
* Array.isReadonlyArrayNonEmpty([]) // => false
* Array.isReadonlyArrayNonEmpty([1, 2, 3]) // => true
* ```
*
* @see {@link isArrayNonEmpty} — mutable variant
* @see {@link isReadonlyArrayEmpty} — opposite check
*
* @stability stable
* @category guards
* @since 4.0.0
*/
const isReadonlyArrayNonEmpty = isArrayNonEmpty$1;
/**
* Creates an empty array.
*
* **When to use**
*
* Use to create a typed empty array without allocating placeholder elements.
*
* **Example** (Creating an empty array)
*
* ```ts import.meta.vitest
* import { Array } from "effect"
*
* Array.empty<number>() // => []
* ```
*
* @see {@link of} — create a single-element array
* @see {@link make} — create from multiple values
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const empty$1 = () => [];
/**
* Transforms each element using a function, returning a new array.
*
* **When to use**
*
* Use to transform each element independently while preserving the array shape.
*
* **Details**
*
* The function receives `(element, index)`. The return type preserves
* `NonEmptyArray`.
*
* **Example** (Doubling values)
*
* ```ts import.meta.vitest
* import { Array } from "effect"
*
* Array.map([1, 2, 3], (x) => x * 2) // => [2, 4, 6]
* ```
*
* @see {@link flatMap} — map and flatten
*
* @stability stable
* @category mapping
* @since 2.0.0
*/
const map$2 = /*#__PURE__*/ dual(2, (self, f) =>
self.map(f),
);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/BigDecimal.js
/**
* Decimal numbers and arithmetic for cases where JavaScript `number` rounding
* is not precise enough. A `BigDecimal` stores digits as a `bigint` plus a
* decimal scale, which lets the module parse, compare, add, subtract, multiply,
* divide, round, and format decimal values such as money, quantities, and
* measurements.
*
* @stability stable
* @since 2.0.0
*/
const TypeId$13 = "~effect/BigDecimal";
const BigDecimalProto = {
[TypeId$13]: TypeId$13,
[symbol$1]() {
const normalized = normalize(this);
return combine(
string$1(String(normalized.value)),
number$1(normalized.scale),
);
},
[symbol](that) {
return isBigDecimal(that) && compare(this, that) === 0;
},
toString() {
return `BigDecimal(${format(this)})`;
},
toJSON() {
return {
_id: "BigDecimal",
value: String(this.value),
scale: this.scale,
};
},
[NodeInspectSymbol]() {
return this.toJSON();
},
pipe() {
return pipeArguments(this, arguments);
},
};
/**
* Checks whether a given value is a `BigDecimal`.
*
* **When to use**
*
* Use to validate unknown input and narrow it to `BigDecimal`.
*
* **Example** (Checking BigDecimal values)
*
* ```ts import.meta.vitest
* import { BigDecimal } from "effect"
*
* const decimal = BigDecimal.fromNumber(123.45)
* BigDecimal.isBigDecimal(decimal) // => false
* BigDecimal.isBigDecimal(BigDecimal.fromStringUnsafe("123.45")) // => true
* BigDecimal.isBigDecimal(123.45) // => false
* BigDecimal.isBigDecimal("123.45") // => false
* ```
*
* @stability stable
* @category guards
* @since 2.0.0
*/
const isBigDecimal = (u) => hasProperty(u, TypeId$13);
/**
* Creates a `BigDecimal` from a `bigint` value and a safe integer scale.
*
* **When to use**
*
* Use to construct a decimal directly from its unscaled integer value and
* decimal scale.
*
* **Gotchas**
*
* Throws a `RangeError` if `scale` is not a safe integer.
*
* **Example** (Creating decimals from bigint and scale)
*
* ```ts import.meta.vitest
* import { BigDecimal } from "effect"
*
* // Create 123.45 (12345 with scale 2)
* const decimal = BigDecimal.make(12345n, 2)
* decimal // => BigDecimal.fromStringUnsafe("123.45")
*
* // Create 42 (42 with scale 0)
* const integer = BigDecimal.make(42n, 0)
* integer // => BigDecimal.fromBigInt(42n)
* ```
*
* @see {@link fromBigInt} for constructing an integer decimal from a `bigint`
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const make$9 = (value, scale) => {
if (!Number.isSafeInteger(scale))
throw new RangeError(
`Scale must be a safe integer, got ${scale}`,
);
const o = Object.create(BigDecimalProto);
o.value = value;
o.scale = scale;
return o;
};
const makeNormalized = (value, scale) => {
const o = make$9(value, scale);
o.normalized = o;
return o;
};
const bigint0$1 = /*#__PURE__*/ BigInt(0);
const bigint1$1 = /*#__PURE__*/ BigInt(1);
const bigint10$1 = /*#__PURE__*/ BigInt(10);
const zero$1 = /*#__PURE__*/ makeNormalized(bigint0$1, 0);
/**
* Normalizes a given `BigDecimal` by removing trailing zeros.
*
* **When to use**
*
* Use to canonicalize decimals that have equivalent values but different
* internal scales.
*
* **Example** (Normalizing trailing zeros)
*
* ```ts import.meta.vitest
* import { BigDecimal } from "effect"
*
* const decimal = BigDecimal.normalize(BigDecimal.fromStringUnsafe("123.00000"))
* const decimalStorage = [decimal.value, decimal.scale] // => [123n, 0]
*
* const largeDecimal = BigDecimal.normalize(BigDecimal.fromStringUnsafe("12300000"))
* const largeDecimalStorage = [largeDecimal.value, largeDecimal.scale] // => [123n, -5]
* ```
*
* @see {@link format} for rendering normalized decimals as strings
*
* @stability stable
* @category scaling
* @since 2.0.0
*/
const normalize = (self) => {
if (self.normalized === void 0) {
if (self.value === bigint0$1) self.normalized = zero$1;
else {
const digits = `${self.value}`;
let end = digits.length;
while (digits[end - 1] === "0") end--;
self.normalized = makeNormalized(
BigInt(digits.slice(0, end)),
self.scale - (digits.length - end),
);
}
}
return self.normalized;
};
const MAX_COMPARISON_SCALE_ALIGNMENT = 100;
const comparisonPowersOfTen = [bigint1$1];
const compareBigInt = (self, that) =>
self === that ? 0 : self < that ? -1 : 1;
const compareMagnitude = (self, that) => {
const selfDigits = `${self.value < bigint0$1 ? -self.value : self.value}`;
const thatDigits = `${that.value < bigint0$1 ? -that.value : that.value}`;
const exponentDifference =
BigInt(selfDigits.length - thatDigits.length) -
BigInt(self.scale) +
BigInt(that.scale);
if (exponentDifference !== bigint0$1)
return exponentDifference < bigint0$1 ? -1 : 1;
const length = Math.max(
selfDigits.length,
thatDigits.length,
);
return String$4(
selfDigits.padEnd(length, "0"),
thatDigits.padEnd(length, "0"),
);
};
const compare = (self, that) => {
if (self.scale === that.scale)
return compareBigInt(self.value, that.value);
const selfSign = sign(self);
const thatSign = sign(that);
if (selfSign !== thatSign)
return selfSign < thatSign ? -1 : 1;
if (selfSign === 0) return 0;
const scaleDifference = self.scale - that.scale;
const absoluteScaleDifference = Math.abs(scaleDifference);
if (
absoluteScaleDifference > MAX_COMPARISON_SCALE_ALIGNMENT
)
return selfSign === -1
? compareMagnitude(that, self)
: compareMagnitude(self, that);
const powerOfTen = (comparisonPowersOfTen[
absoluteScaleDifference
] ??= bigint10$1 ** BigInt(absoluteScaleDifference));
return scaleDifference > 0
? compareBigInt(self.value, that.value * powerOfTen)
: compareBigInt(self.value * powerOfTen, that.value);
};
/**
* Determines the sign of a given `BigDecimal`.
*
* **When to use**
*
* Use to classify a `BigDecimal` as negative, zero, or positive.
*
* **Example** (Reading decimal signs)
*
* ```ts import.meta.vitest
* import { BigDecimal } from "effect"
*
* BigDecimal.sign(BigDecimal.fromStringUnsafe("-5")) // => -1
* BigDecimal.sign(BigDecimal.fromStringUnsafe("0")) // => 0
* BigDecimal.sign(BigDecimal.fromStringUnsafe("5")) // => 1
* ```
*
* @stability stable
* @category math
* @since 2.0.0
*/
const sign = (n) =>
n.value === bigint0$1 ? 0 : n.value < bigint0$1 ? -1 : 1;
/**
* Formats a `BigDecimal` as a string.
*
* **When to use**
*
* Use to render a `BigDecimal` as plain decimal text when possible.
*
* **Details**
*
* The value is normalized before formatting. Scientific notation is used when
* the absolute value of the normalized scale is at least `16`; otherwise plain
* decimal notation is used.
*
* **Example** (Formatting decimals)
*
* ```ts import.meta.vitest
* import { BigDecimal } from "effect"
*
* BigDecimal.format(BigDecimal.fromStringUnsafe("-5")) // => "-5"
* BigDecimal.format(BigDecimal.fromStringUnsafe("123.456")) // => "123.456"
* BigDecimal.format(BigDecimal.fromStringUnsafe("-0.00000123")) // => "-0.00000123"
* ```
*
* @see {@link toExponential} for always rendering scientific notation
*
* @stability stable
* @category converting
* @since 2.0.0
*/
const format = (n) => {
const normalized = normalize(n);
if (Math.abs(normalized.scale) >= 16)
return toExponential(normalized);
const negative = normalized.value < bigint0$1;
const absolute = `${negative ? -normalized.value : normalized.value}`;
const digits =
normalized.scale > 0
? absolute.padStart(normalized.scale + 1, "0")
: absolute.padEnd(
absolute.length - normalized.scale,
"0",
);
const point = digits.length - normalized.scale;
const complete =
normalized.scale > 0
? `${digits.slice(0, point)}.${digits.slice(point)}`
: digits;
return negative ? `-${complete}` : complete;
};
/**
* Formats a given `BigDecimal` as a `string` in scientific notation.
*
* **When to use**
*
* Use to render a `BigDecimal` in scientific notation.
*
* **Example** (Formatting decimals exponentially)
*
* ```ts import.meta.vitest
* import { BigDecimal } from "effect"
*
* BigDecimal.toExponential(BigDecimal.make(123456n, -5)) // => "1.23456e+10"
* ```
*
* @see {@link format} for plain decimal formatting when possible
*
* @stability stable
* @category converting
* @since 3.11.0
*/
const toExponential = (n) => {
if (isZero(n)) return "0e+0";
const normalized = normalize(n);
const digits = `${normalized.value}`;
const point = normalized.value < bigint0$1 ? 2 : 1;
const head = digits.slice(0, point);
const tail = digits.slice(point);
const exp = tail.length - normalized.scale;
return `${head}${tail === "" ? "" : `.${tail}`}e${exp >= 0 ? "+" : ""}${exp}`;
};
/**
* Checks whether a given `BigDecimal` is `0`.
*
* **When to use**
*
* Use to test whether a `BigDecimal` is exactly zero.
*
* **Example** (Checking zero decimals)
*
* ```ts import.meta.vitest
* import { BigDecimal } from "effect"
*
* BigDecimal.isZero(BigDecimal.fromStringUnsafe("0")) // => true
* BigDecimal.isZero(BigDecimal.fromStringUnsafe("1")) // => false
* ```
*
* @stability stable
* @category predicates
* @since 2.0.0
*/
const isZero = (n) => n.value === bigint0$1;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Effectable.js
/**
* Create a low-level `Effect` prototype.
*
* **When to use**
*
* Use when you need to create a custom Effect-like value without extending a
* class, by providing a label and an evaluate function that receives the
* current fiber.
*
* **Details**
*
* When the effect is evaluated, it calls `evaluate` with the current fiber.
*
* @see {@link Class} for a class-based approach to defining custom Effect values
* @see {@link Mixin} for wrapping an existing class constructor
*
* @stability stable
* @category prototypes
* @since 4.0.0
*/
const Prototype = (options) =>
makePrimitiveProto({
op: options.label,
[evaluate]: options.evaluate,
});
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Context.js
/**
* Runtime type identifier attached to `Context` service keys and used by
* `isKey` to recognize them.
*
* @stability stable
* @category type IDs
* @since 4.0.0
*/
const ServiceTypeId = "~effect/Context/Service";
/**
* Creates a `Context` service key.
*
* **When to use**
*
* Use when you need to define a context service key for a dependency that must
* be provided by the surrounding context.
*
* **Details**
*
* Call `Context.Service("Key")` for a function-style key, or use the two-stage
* form `Context.Service<Self, Shape>()("Key")` for class-style service
* declarations. The returned key can be yielded as an Effect and passed to
* `Context.make`, `Context.add`, and the Context getter functions.
*
* **Gotchas**
*
* The string key is the runtime identity of the service. Reusing the same key
* string for unrelated services makes them occupy the same slot in a
* `Context`.
*
* **Example** (Creating service keys)
*
* ```ts import.meta.vitest
* import { Context } from "effect"
*
* // Create a simple service
* const Database = Context.Service<{
* query: (sql: string) => string
* }>("Database")
*
* // Create a service class
* class Config extends Context.Service<Config, {
* port: number
* }>()("Config") {}
*
* // Use the services to create contexts
* const db = Context.make(Database, {
* query: (sql) => `Result: ${sql}`
* })
* const config = Context.make(Config, { port: 8080 })
* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1"
* Context.get(config, Config).port // => 8080
* ```
*
* @see {@link Reference} for service keys with default values
*
* @stability stable
* @category services
* @since 4.0.0
*/
const Service = function () {
function KeyClass() {}
const self = KeyClass;
Object.setPrototypeOf(self, ServiceProto);
const init = (key, options) => {
self.key = key;
if (options?.defaultValue) {
self[ReferenceTypeId] = ReferenceTypeId;
self.defaultValue = options.defaultValue;
}
if (options?.make) self.make = options.make;
if (options?.fiberCached) cacheKeys.add(key);
return self;
};
return arguments.length > 0
? init(arguments[0], arguments[1])
: init;
};
const ServiceProto = {
[ServiceTypeId]: ServiceTypeId,
.../*#__PURE__*/ Prototype({
label: "Service",
evaluate(fiber) {
return exitSucceed(get(fiber.context, this));
},
}),
toJSON() {
return {
_id: "Service",
key: this.key,
};
},
of(self) {
return self;
},
context(self) {
return make$8(this, self);
},
use(f) {
return withFiber((fiber) =>
f(get(fiber.context, this)),
);
},
useSync(f) {
return withFiber((fiber) =>
exitSucceed(f(get(fiber.context, this))),
);
},
};
const cacheKeys = /*#__PURE__*/ new Set();
const ReferenceTypeId = "~effect/Context/Reference";
const TypeId$12 = "~effect/Context";
const MaxDepth = 8;
const FlattenAfterBaseHits = 8;
const makeImpl = (cacheRoot, base, overlay, depth) => {
const self = Object.create(Proto$5);
self.cacheRoot = cacheRoot ?? self;
self.base = base;
self.overlay = overlay;
self.depth = depth;
self._flat = void 0;
self.baseHits = 0;
return self;
};
const applyOverlays = (map, overlay) => {
if (!overlay) return;
applyOverlays(map, overlay.parent);
map.set(overlay.key, overlay.value);
};
const flatten = (self) => {
if (self._flat) return self._flat;
if (!self.overlay) return (self._flat = self.base);
const map = new Map(self.base);
applyOverlays(map, self.overlay);
return (self._flat = map);
};
const notFound = /*#__PURE__*/ Symbol();
const lookup = (self, key) => {
const impl = self;
for (
let overlay = impl.overlay;
overlay;
overlay = overlay.parent
)
if (overlay.key === key) return overlay.value;
const value = impl.base.get(key);
if (value === void 0 && !impl.base.has(key))
return notFound;
if (
impl.overlay &&
++impl.baseHits >= impl.base.size &&
impl.baseHits >= FlattenAfterBaseHits
) {
impl.base = flatten(impl);
impl.overlay = void 0;
impl.depth = 0;
}
return value;
};
/**
* Creates a `Context` from an existing service map.
*
* **When to use**
*
* Use when constructing a low-level `Context` from a trusted map whose lifecycle
* you control.
*
* **Gotchas**
*
* The provided map is retained without copying and must not be mutated after
* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context
* construction.
*
* **Example** (Creating a context from a map)
*
* ```ts import.meta.vitest
* import { Context } from "effect"
*
* // Create a context from a Map (unsafe)
* const map = new Map([
* ["Logger", { log: (_msg: string) => {} }]
* ])
*
* const context = Context.makeUnsafe(map)
* context.mapUnsafe.size // => 1
* ```
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const makeUnsafe$2 = (mapUnsafe) =>
makeImpl(void 0, mapUnsafe, void 0, 0);
const Proto$5 = {
get mapUnsafe() {
return flatten(this);
},
...PipeInspectableProto,
[TypeId$12]: { _Services: (_) => _ },
toJSON() {
return {
_id: "Context",
services: Array.from(this.mapUnsafe).map(
([key, value]) => ({
key,
value,
}),
),
};
},
[symbol](that) {
if (!isContext(that)) return false;
const self = this.mapUnsafe;
const other = that.mapUnsafe;
if (self.size !== other.size) return false;
for (const [key, value] of self)
if (
!other.has(key) ||
!equals$1(value, other.get(key))
)
return false;
return true;
},
[symbol$1]() {
return number$1(this.mapUnsafe.size);
},
};
/** @internal */
const hasSameCache = (self, that) =>
self.cacheRoot === that.cacheRoot;
/**
* Checks whether the provided argument is a `Context`.
*
* **When to use**
*
* Use to narrow an unknown value before passing it to APIs that require a
* `Context`.
*
* **Details**
*
* This checks the runtime `Context` marker and does not inspect which services
* the context contains.
*
* **Gotchas**
*
* This guard only proves that the value is a `Context`; it does not prove that
* any specific service is present.
*
* **Example** (Checking for contexts)
*
* ```ts import.meta.vitest
* import { Context } from "effect"
* Context.isContext(Context.empty()) // => true
* ```
*
* @see {@link isKey} for checking service keys
* @see {@link isReference} for checking references with defaults
*
* @stability stable
* @category guards
* @since 2.0.0
*/
const isContext = (u) => hasProperty(u, TypeId$12);
/**
* Checks whether the provided argument is a `Reference`.
*
* **Example** (Checking for references)
*
* ```ts import.meta.vitest
* import { Context } from "effect"
*
* const LoggerRef = Context.Reference("Logger", {
* defaultValue: () => ({ log: (_msg: string) => {} })
* })
*
* Context.isReference(LoggerRef) // => true
* Context.isReference(Context.Service("Key")) // => false
* ```
*
* @stability stable
* @category guards
* @since 3.11.0
*/
const isReference = (u) => !!u[ReferenceTypeId];
/**
* Returns an empty `Context`.
*
* **Example** (Creating an empty context)
*
* ```ts import.meta.vitest
* import { Context } from "effect"
* Context.empty().mapUnsafe.size // => 0
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const empty = () => emptyContext;
const emptyContext = /*#__PURE__*/ makeUnsafe$2(
/*#__PURE__*/ new Map(),
);
/**
* Creates a new `Context` with a single service associated to the key.
*
* **Example** (Creating a context with one service)
*
* ```ts import.meta.vitest
* import { Context } from "effect"
*
* const Port = Context.Service<{ PORT: number }>("Port")
*
* const context = Context.make(Port, { PORT: 8080 })
*
* Context.get(context, Port).PORT // => 8080
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const make$8 = (key, service) =>
makeUnsafe$2(
/* @__PURE__ */ new Map([[key.key, service]]),
);
/**
* Adds a service to a given `Context`.
*
* **When to use**
*
* Use when you need to store a known service value in a `Context`.
*
* **Details**
*
* If the context already contains the same service key, the new service
* replaces the previous one.
*
* **Example** (Adding a service to a context)
*
* ```ts import.meta.vitest
* import { Context, pipe } from "effect"
*
* const Port = Context.Service<{ PORT: number }>("Port")
* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout")
*
* const someContext = Context.make(Port, { PORT: 8080 })
*
* const context = pipe(
* someContext,
* Context.add(Timeout, { TIMEOUT: 5000 })
* )
*
* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT]
* values // => [8080, 5000]
* ```
*
* @see {@link addOrOmit} for adding or removing a service from an `Option`
*
* @stability stable
* @category combining
* @since 2.0.0
*/
const add = /*#__PURE__*/ dual(3, (self, key, service) =>
addUnsafe(self, key.key, service),
);
/**
* Adds a service by key to a given `Context` using a string key.
*
* @stability stable
* @category combining
* @since 4.0.0
*/
const addUnsafe = (self, key, service) => {
const impl = self;
const cacheRoot = cacheKeys.has(key)
? void 0
: impl.cacheRoot;
if (impl.depth >= MaxDepth) {
const map = new Map(impl._flat ?? impl.base);
if (!impl._flat) applyOverlays(map, impl.overlay);
map.set(key, service);
return makeImpl(cacheRoot, map, void 0, 0);
}
return makeImpl(
cacheRoot,
impl.base,
{
key,
value: service,
parent: impl.overlay,
},
impl.depth + 1,
);
};
/** @internal */
const getOrUndefinedUnsafe = (self, key) => {
const value = lookup(self, key);
return value === notFound ? void 0 : value;
};
/**
* Gets a service from the context that corresponds to the given key.
*
* **When to use**
*
* Use when you need type-checked access to a service already included in the
* context type.
*
* **Example** (Getting a service from a context)
*
* ```ts import.meta.vitest
* import { Context, pipe } from "effect"
*
* const Port = Context.Service<{ PORT: number }>("Port")
* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout")
*
* const context = pipe(
* Context.make(Port, { PORT: 8080 }),
* Context.add(Timeout, { TIMEOUT: 5000 })
* )
*
* Context.get(context, Timeout).TIMEOUT // => 5000
* ```
*
* @see {@link getOption} for optional service access
* @see {@link getOrElse} for fallback values
*
* @stability stable
* @category getters
* @since 2.0.0
*/
const get = /* @__PURE__ */ dual(2, (self, service) => {
const value = lookup(self, service.key);
if (value === notFound) {
if (isReference(service))
return getDefaultValue(service);
throw serviceNotFoundError(service);
}
return value;
});
const defaultValueCacheKey = "~effect/Context/defaultValue";
const getDefaultValue = (ref) => {
if (defaultValueCacheKey in ref)
return ref[defaultValueCacheKey];
return (ref[defaultValueCacheKey] = ref.defaultValue());
};
const serviceNotFoundError = (service) => {
const error = /* @__PURE__ */ new Error(
`Service not found${service.key ? `: ${String(service.key)}` : ""}`,
);
if (error.stack) {
const lines = error.stack.split("\n");
lines.splice(1, 3);
error.stack = lines.join("\n");
}
return error;
};
/**
* Creates a context key with a default value.
*
* **When to use**
*
* Use when you need to define a context key with a lazily computed default
* value.
*
* **Details**
*
* `Context.Reference` allows you to create a key that can hold a value. You
* can provide a default value for the service, which will automatically be used
* when the context is accessed, or override it with a custom implementation
* when needed. The default value is computed lazily and cached on the
* reference.
*
* **Example** (Creating references with default values)
*
* ```ts import.meta.vitest
* import { Context } from "effect"
*
* // Create a reference with a default value
* const messages: Array<string> = []
* const LoggerRef = Context.Reference("Logger", {
* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) })
* })
*
* // The reference provides the default value when accessed from an empty context
* const context = Context.empty()
* const logger = Context.get(context, LoggerRef)
*
* // You can also override the default value
* const customContext = Context.make(LoggerRef, {
* log: (msg: string) => messages.push(`Custom: ${msg}`)
* })
* const customLogger = Context.get(customContext, LoggerRef)
* logger.log("default")
* customLogger.log("message")
* messages // => ["Default: default", "Custom: message"]
* ```
*
* @see {@link Service} for required services without default values
*
* @stability stable
* @category services
* @since 3.11.0
*/
const Reference = Service;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Duration.js
const TypeId$11 = "~effect/Duration";
const bigint0 = /*#__PURE__*/ BigInt(0);
const bigint1 = /*#__PURE__*/ BigInt(1);
const bigint2 = /*#__PURE__*/ BigInt(2);
const bigint10 = /*#__PURE__*/ BigInt(10);
const bigint1e3 = /*#__PURE__*/ BigInt(1e3);
const bigint1e6 = /*#__PURE__*/ BigInt(1e6);
const roundTiesAwayFromZero = (input) =>
BigInt(Math.sign(input) * Math.round(Math.abs(input)));
const roundMillisToNanos = (millis) =>
Number.isInteger(millis)
? BigInt(millis) * bigint1e6
: roundTiesAwayFromZero(millis * 1e6);
const fromNanosNumber = (nanos) =>
make$7(
Number.isFinite(nanos)
? roundTiesAwayFromZero(nanos)
: nanos,
);
const parseNanos = (input, scale) => {
const decimalIndex = input.indexOf(".");
if (decimalIndex === -1) return BigInt(input) * scale;
const isNegative = input[0] === "-";
const fractional = input.slice(decimalIndex + 1);
const fractionalScale =
bigint10 ** BigInt(fractional.length);
const scaled =
(BigInt(input.slice(isNegative ? 1 : 0, decimalIndex)) *
fractionalScale +
BigInt(fractional)) *
scale;
return divideTiesAwayFromZero(
isNegative ? -scaled : scaled,
fractionalScale,
);
};
const divideTiesAwayFromZero = (numerator, denominator) => {
const absolute =
numerator < bigint0 ? -numerator : numerator;
const rounded =
absolute / denominator +
((absolute % denominator) * bigint2 >= denominator
? bigint1
: bigint0);
return numerator < bigint0 ? -rounded : rounded;
};
const DURATION_REGEXP =
/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/;
/**
* Decodes a `Duration.Input` into a `Duration`.
*
* **When to use**
*
* Use when the input has already been validated or comes from a trusted source
* and throwing is acceptable for invalid duration syntax.
*
* **Gotchas**
*
* If the input is not a valid `Duration.Input`, it throws an error.
*
* **Example** (Decoding duration inputs)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.fromInputUnsafe(1000) // => Duration.millis(1000)
* Duration.fromInputUnsafe("5 seconds") // => Duration.seconds(5)
* Duration.fromInputUnsafe("Infinity") // => Duration.infinity
* Duration.fromInputUnsafe([2, 500_000_000]) // => Duration.nanos(2_500_000_000n)
* ```
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const fromInputUnsafe = (input) => {
switch (typeof input) {
case "number":
return millis(input);
case "bigint":
return nanos(input);
case "string": {
if (input === "Infinity") return infinity;
if (input === "-Infinity") return negativeInfinity;
const match = DURATION_REGEXP.exec(input);
if (!match) break;
const [_, valueStr, unit] = match;
if (unit === "nano" || unit === "nanos")
return nanos(parseNanos(valueStr, bigint1));
if (unit === "micro" || unit === "micros")
return nanos(parseNanos(valueStr, bigint1e3));
const value = Number(valueStr);
switch (unit) {
case "milli":
case "millis":
return millis(value);
case "second":
case "seconds":
return seconds(value);
case "minute":
case "minutes":
return minutes(value);
case "hour":
case "hours":
return hours(value);
case "day":
case "days":
return days(value);
case "week":
case "weeks":
return weeks(value);
}
break;
}
case "object": {
if (input === null) break;
if (TypeId$11 in input) return input;
if (Array.isArray(input)) {
if (input.length !== 2 || !input.every(isNumber))
return invalid$1(input);
if (
Number.isNaN(input[0]) ||
Number.isNaN(input[1])
)
return zero;
if (
input[0] === -Infinity ||
input[1] === -Infinity
)
return negativeInfinity;
if (input[0] === Infinity || input[1] === Infinity)
return infinity;
return fromNanosNumber(input[0] * 1e9 + input[1]);
}
const obj = input;
let millis = 0;
if (obj.weeks) millis += obj.weeks * 6048e5;
if (obj.days) millis += obj.days * 864e5;
if (obj.hours) millis += obj.hours * 36e5;
if (obj.minutes) millis += obj.minutes * 6e4;
if (obj.seconds) millis += obj.seconds * 1e3;
if (obj.milliseconds) millis += obj.milliseconds;
if (!obj.microseconds && !obj.nanoseconds)
return make$7(millis);
return fromNanosNumber(
millis * 1e6 +
(obj.microseconds ?? 0) * 1e3 +
(obj.nanoseconds ?? 0),
);
}
}
return invalid$1(input);
};
const invalid$1 = (input) => {
throw new Error(`Invalid Input: ${input}`);
};
const zeroDurationValue = {
_tag: "Millis",
millis: 0,
};
const infinityDurationValue = { _tag: "Infinity" };
const negativeInfinityDurationValue = {
_tag: "NegativeInfinity",
};
const DurationProto = {
[TypeId$11]: TypeId$11,
[symbol$1]() {
switch (this.value._tag) {
case "Millis":
return hash(roundMillisToNanos(this.value.millis));
case "Nanos":
return hash(this.value.nanos);
default:
return structure(this.value);
}
},
[symbol](that) {
return isDuration(that) && equals(this, that);
},
toString() {
switch (this.value._tag) {
case "Infinity":
return "Infinity";
case "NegativeInfinity":
return "-Infinity";
case "Nanos":
return `${this.value.nanos} nanos`;
case "Millis":
return `${this.value.millis} millis`;
}
},
toJSON() {
switch (this.value._tag) {
case "Millis":
return {
_id: "Duration",
_tag: "Millis",
millis: this.value.millis,
};
case "Nanos":
return {
_id: "Duration",
_tag: "Nanos",
nanos: String(this.value.nanos),
};
case "Infinity":
return {
_id: "Duration",
_tag: "Infinity",
};
case "NegativeInfinity":
return {
_id: "Duration",
_tag: "NegativeInfinity",
};
}
},
[NodeInspectSymbol]() {
return this.toJSON();
},
pipe() {
return pipeArguments(this, arguments);
},
};
const make$7 = (input) => {
const duration = Object.create(DurationProto);
if (typeof input === "number") {
if (isNaN(input) || input === 0 || Object.is(input, -0))
duration.value = zeroDurationValue;
else if (!Number.isFinite(input))
duration.value =
input > 0
? infinityDurationValue
: negativeInfinityDurationValue;
else if (!Number.isInteger(input))
duration.value = {
_tag: "Nanos",
nanos: roundMillisToNanos(input),
};
else
duration.value = {
_tag: "Millis",
millis: input,
};
} else if (input === bigint0)
duration.value = zeroDurationValue;
else
duration.value = {
_tag: "Nanos",
nanos: input,
};
return duration;
};
/**
* Checks whether a value is a Duration.
*
* **Example** (Checking for durations)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.isDuration(Duration.seconds(1)) // => true
* Duration.isDuration(1000) // => false
* ```
*
* @stability stable
* @category guards
* @since 2.0.0
*/
const isDuration = (u) => hasProperty(u, TypeId$11);
/**
* A Duration representing zero time.
*
* **Example** (Referencing the zero duration)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.zero) // => 0
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const zero = /*#__PURE__*/ make$7(0);
/**
* A Duration representing infinite time.
*
* **Example** (Referencing infinite duration)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.infinity) // => Infinity
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const infinity = /*#__PURE__*/ make$7(Infinity);
/**
* A Duration representing negative infinite time.
*
* **Example** (Referencing negative infinite duration)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.negativeInfinity) // => -Infinity
* ```
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const negativeInfinity = /*#__PURE__*/ make$7(-Infinity);
/**
* Creates a Duration from nanoseconds.
*
* **Example** (Creating durations from nanoseconds)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.nanos(500_000_000n) // => Duration.nanos(500_000_000n)
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const nanos = (nanos) => make$7(nanos);
/**
* Creates a Duration from milliseconds.
*
* **Example** (Creating durations from milliseconds)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.millis(1000)) // => 1000
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const millis = (millis) => make$7(millis);
/**
* Creates a Duration from seconds.
*
* **Example** (Creating durations from seconds)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.seconds(30)) // => 30_000
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const seconds = (seconds) => make$7(seconds * 1e3);
/**
* Creates a Duration from minutes.
*
* **Example** (Creating durations from minutes)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.minutes(5)) // => 300_000
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const minutes = (minutes) => make$7(minutes * 6e4);
/**
* Creates a Duration from hours.
*
* **Example** (Creating durations from hours)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.hours(2)) // => 7_200_000
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const hours = (hours) => make$7(hours * 36e5);
/**
* Creates a Duration from days.
*
* **Example** (Creating durations from days)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.days(1)) // => 86_400_000
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const days = (days) => make$7(days * 864e5);
/**
* Creates a Duration from weeks.
*
* **Example** (Creating durations from weeks)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.weeks(1)) // => 604_800_000
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const weeks = (weeks) => make$7(weeks * 6048e5);
/**
* Gets the duration in nanoseconds as a bigint.
*
* **When to use**
*
* Use when the duration is known to be finite and you need the nanosecond value
* as a `bigint`.
*
* **Details**
*
* Millisecond-backed fractional durations are rounded to the nearest
* nanosecond, with ties away from zero.
*
* **Gotchas**
*
* If the duration is infinite, it throws an error.
*
* **Example** (Reading nanoseconds unsafely)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toNanosUnsafe(Duration.seconds(2)) // => 2_000_000_000n
*
* // Duration.toNanosUnsafe(Duration.infinity)
* // throws Error: "Cannot convert infinite duration to nanos"
* ```
*
* @stability stable
* @category getters
* @since 4.0.0
*/
const toNanosUnsafe = (input) => {
const self = fromInputUnsafe(input);
switch (self.value._tag) {
case "Infinity":
case "NegativeInfinity":
throw new Error(
"Cannot convert infinite duration to nanos",
);
case "Nanos":
return self.value.nanos;
case "Millis":
return roundMillisToNanos(self.value.millis);
}
};
/**
* Pattern matches on two `Duration`s, providing handlers that receive both values.
*
* **Example** (Pattern matching on duration pairs)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.matchPair(Duration.seconds(3), Duration.seconds(2), {
* onMillis: (a, b) => a + b,
* onNanos: (a, b) => Number(a + b),
* onInfinity: () => Infinity
* }) // => 5000
* ```
*
* @stability stable
* @category pattern matching
* @since 4.0.0
*/
const matchPair = /*#__PURE__*/ dual(
3,
(self, that, options) => {
if (
self.value._tag === "Infinity" ||
self.value._tag === "NegativeInfinity" ||
that.value._tag === "Infinity" ||
that.value._tag === "NegativeInfinity"
)
return options.onInfinity(self, that);
if (self.value._tag === "Millis")
return that.value._tag === "Millis"
? options.onMillis(
self.value.millis,
that.value.millis,
)
: options.onNanos(
toNanosUnsafe(self),
that.value.nanos,
);
else
return options.onNanos(
self.value.nanos,
toNanosUnsafe(that),
);
},
);
/**
* Provides an `Equivalence` instance for comparing `Duration` values.
*
* **Example** (Comparing durations for equivalence)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.Equivalence(Duration.seconds(5), Duration.millis(5000)) // => true
* ```
*
* @stability stable
* @category instances
* @since 2.0.0
*/
const Equivalence$2 = (self, that) =>
matchPair(self, that, {
onMillis: (self, that) => self === that,
onNanos: (self, that) => self === that,
onInfinity: (self, that) =>
self.value._tag === that.value._tag,
});
/**
* Checks whether two Durations are equal.
*
* **Example** (Checking duration equality)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.equals(Duration.seconds(5), Duration.millis(5000)) // => true
* ```
*
* @stability stable
* @category predicates
* @since 2.0.0
*/
const equals = /*#__PURE__*/ dual(2, (self, that) =>
Equivalence$2(self, that),
);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Scheduler.js
/**
* Controls how runnable Effect fiber tasks are dispatched.
*
* A scheduler decides how tasks are queued, when queued tasks run, and when a
* fiber should pause so other work can continue. This module includes the
* scheduler service reference, the default `MixedScheduler`, dispatcher types
* for queued tasks, and references for tuning or disabling automatic scheduler
* yields.
*
* @stability stable
* @since 2.0.0
*/
/**
* Context reference for the scheduler used by the Effect runtime.
*
* **When to use**
*
* Use when you need to replace scheduling behavior globally in tests or runtime
* setup, such as forcing deterministic task dispatch.
*
* **Details**
*
* The default value creates a `MixedScheduler`. Provide this service to
* customize execution mode, task dispatching, or yield behavior.
*
* @stability stable
* @category services
* @since 2.0.0
*/
const Scheduler = /*#__PURE__*/ Reference(
"effect/Scheduler",
{
fiberCached: true,
defaultValue: () => new MixedScheduler(),
},
);
const setMicrotask = (f) => {
let cancelled = false;
Promise.resolve().then(() => {
if (!cancelled) f();
});
return () => {
cancelled = true;
};
};
const setTimer =
"setImmediate" in globalThis
? (f) => {
const timer = globalThis.setImmediate(f);
return () => globalThis.clearImmediate(timer);
}
: (f) => {
const timer = setTimeout(f, 0);
return () => clearTimeout(timer);
};
const setImmediate = (f) => {
try {
return setTimer(f);
} catch {
return setMicrotask(f);
}
};
var PriorityBuckets = class {
buckets = [];
scheduleTask(task, priority) {
const buckets = this.buckets;
const len = buckets.length;
let bucket;
let index = 0;
for (; index < len; index++) {
if (buckets[index][0] > priority) break;
bucket = buckets[index];
}
if (bucket && bucket[0] === priority)
bucket[1].push(task);
else if (index === len)
buckets.push([priority, [task]]);
else buckets.splice(index, 0, [priority, [task]]);
}
drain() {
const buckets = this.buckets;
this.buckets = [];
return buckets;
}
};
/**
* Provides a scheduler implementation that batches queued tasks and dispatches them by
* priority.
*
* **When to use**
*
* Use when you need the default runtime scheduler directly, including a
* scheduler that batches queued work by priority and preserves FIFO order within
* each priority.
*
* **Details**
*
* `MixedScheduler` supports synchronous and asynchronous execution modes, uses
* operation counts to decide when fibers should yield, and is the default
* scheduler implementation.
*
* **Gotchas**
*
* On Cloudflare Workers, request-owned scheduler timers can be discarded,
* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the
* whole application; see `HttpRouter.toWebHandler` for a recipe.
* Sync mode does not yield to the event loop: CPU-heavy work delays other
* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix
* request-owned timers (such as `Effect.sleep`) or request-bound async contexts.
*
* @stability stable
* @category models
* @since 2.0.0
*/
var MixedScheduler = class {
executionMode;
setImmediate;
constructor(executionMode = "async", setImmediateFn) {
this.executionMode = executionMode;
this.setImmediate =
setImmediateFn ??
(executionMode === "sync"
? setMicrotask
: setImmediate);
}
/**
* Returns whether the fiber has reached its operation budget and should yield.
*
* **When to use**
*
* Use to decide whether a fiber should yield after consuming its current
* operation budget.
*
* @since 2.0.0
*/
shouldYield(fiber) {
return (
fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield
);
}
/**
* Creates a dispatcher that schedules work through this scheduler.
*
* **When to use**
*
* Use when you need a standalone dispatcher from a scheduler instance, for
* example in tests that enqueue tasks and then flush them deterministically.
*
* @since 4.0.0
*/
makeDispatcher() {
return new MixedSchedulerDispatcher(this.setImmediate);
}
};
var MixedSchedulerDispatcher = class {
tasks = /*#__PURE__*/ new PriorityBuckets();
running = void 0;
setImmediate;
constructor(setImmediateFn = setImmediate) {
this.setImmediate = setImmediateFn;
}
/**
* @since 2.0.0
*/
scheduleTask(task, priority) {
this.tasks.scheduleTask(task, priority);
if (this.running === void 0)
this.running = this.setImmediate(this.afterScheduled);
}
/**
* @since 2.0.0
*/
afterScheduled = () => {
this.running = void 0;
this.runTasks();
};
/**
* @since 2.0.0
*/
runTasks() {
const buckets = this.tasks.drain();
for (let i = 0; i < buckets.length; i++) {
const toRun = buckets[i][1];
for (let j = 0; j < toRun.length; j++) toRun[j]();
}
}
/**
* @since 2.0.0
*/
flush() {
while (this.tasks.buckets.length > 0) {
if (this.running !== void 0) {
this.running();
this.running = void 0;
}
this.runTasks();
}
}
};
/**
* Context reference that controls the maximum number of operations a fiber
* can perform before yielding control back to the scheduler.
*
* **When to use**
*
* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler
* operation budget that triggers a yield.
*
* **Details**
*
* The default value is `2048` operations, which balances performance and
* fairness by helping prevent long-running fibers from monopolizing the
* execution thread.
*
* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget
*
* @stability stable
* @category services
* @since 4.0.0
*/
const MaxOpsBeforeYield = /*#__PURE__*/ Reference(
"effect/Scheduler/MaxOpsBeforeYield",
{
fiberCached: true,
defaultValue: () => 2048,
},
);
/**
* Context reference that controls whether the runtime should bypass scheduler
* yield checks. When set to `true`, the fiber run loop won't call
* `Scheduler.shouldYield`.
*
* **When to use**
*
* Use to bypass scheduler yield checks for controlled runtime workloads where
* cooperative yielding should be disabled.
*
* **Gotchas**
*
* Setting this reference to `true` can let long-running fibers monopolize the
* JavaScript thread.
*
* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks
* @see {@link Scheduler} for providing custom scheduler yield behavior
*
* @stability stable
* @category services
* @since 4.0.0
*/
const PreventSchedulerYield = /*#__PURE__*/ Reference(
"effect/Scheduler/PreventSchedulerYield",
{
fiberCached: true,
defaultValue: () => false,
},
);
/**
* Creates a tagged error class with a `_tag` discriminator.
*
* **When to use**
*
* Use when you need domain errors with discriminated-union handling.
*
* **Details**
*
* Like {@link Error}, but instances also carry a `readonly _tag` property,
* enabling `Effect.catchTag` and `Effect.catchTags` for tag-based recovery.
* The `_tag` is excluded from the constructor argument. Yielding an instance
* inside `Effect.gen` fails the effect with this error.
*
* **Example** (Recovering by tag)
*
* ```ts import.meta.vitest
* import { Data, Effect } from "effect"
*
* class NotFound extends Data.TaggedError("NotFound")<{
* readonly resource: string
* }> {}
*
* class Forbidden extends Data.TaggedError("Forbidden")<{
* readonly reason: string
* }> {}
*
* const program = Effect.gen(function*() {
* return yield* new NotFound({ resource: "/users/42" })
* })
*
* const recovered = program.pipe(
* Effect.catchTag("NotFound", (e) =>
* Effect.succeed(`missing: ${e.resource}`))
* )
*
* await Effect.runPromise(recovered) // => "missing: /users/42"
* ```
*
* @see {@link Error} — without a `_tag`
* @see {@link TaggedClass} — tagged class that is not an error
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const TaggedError = TaggedError$1;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Tracer.js
/**
* Defines the string key for the parent-span context service.
*
* **When to use**
*
* Use when you need the raw context key for parent span lookup in lower-level
* tracing code.
*
* **Example** (Reading the parent span key)
*
* ```ts import.meta.vitest
* import { Tracer } from "effect"
*
* // The key used to identify parent spans in the context
* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan"
* ```
*
* @stability stable
* @category constants
* @since 4.0.0
*/
const ParentSpanKey = "effect/Tracer/ParentSpan";
/**
* Defines the string key for the active tracer context reference.
*
* **When to use**
*
* Use when you need the raw context key for active tracer lookup in lower-level
* tracing code.
*
* @stability stable
* @category constants
* @since 4.0.0
*/
const TracerKey = "effect/Tracer";
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/metric.js
/** @internal */
const FiberRuntimeMetricsKey =
"effect/Metric/FiberRuntimeMetrics";
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/references.js
/** @internal */
const CurrentStackFrame = /*#__PURE__*/ Reference(
"effect/References/CurrentStackFrame",
{
fiberCached: true,
defaultValue: constUndefined,
},
);
/** @internal */
const TracerEnabled = /*#__PURE__*/ Reference(
"effect/References/TracerEnabled",
{
fiberCached: true,
defaultValue: constTrue,
},
);
/** @internal */
const CurrentLogLevel = /*#__PURE__*/ Reference(
"effect/References/CurrentLogLevel",
{
fiberCached: true,
defaultValue: () => "Info",
},
);
/** @internal */
const MinimumLogLevel = /*#__PURE__*/ Reference(
"effect/References/MinimumLogLevel",
{
fiberCached: true,
defaultValue: () => "Info",
},
);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/effect.js
/** @internal */
var Interrupt = class extends ReasonBase {
constructor(
fiberId,
annotations = constEmptyAnnotations,
) {
super("Interrupt", annotations, "Interrupted");
this.fiberId = fiberId;
}
toString() {
return `Interrupt(${this.fiberId})`;
}
toJSON() {
return {
_tag: "Interrupt",
fiberId: this.fiberId,
};
}
[symbol](that) {
return (
isInterruptReason(that) &&
this.fiberId === that.fiberId &&
this.annotations === that.annotations
);
}
[symbol$1]() {
return string$1(`${this._tag}:${this.fiberId}`);
}
};
/** @internal */
const causeInterrupt = (fiberId) =>
new CauseImpl([new Interrupt(fiberId)]);
/** @internal */
const hasInterrupts = (self) =>
self.reasons.some(isInterruptReason);
/** @internal */
const causeMap = /*#__PURE__*/ dual(2, (self, f) => {
let hasFail = false;
const failures = self.reasons.map((failure) => {
if (isFailReason$1(failure)) {
hasFail = true;
return new Fail(
f(failure.error),
failure.annotations,
);
}
return failure;
});
return hasFail ? causeFromReasons(failures) : self;
});
/** @internal */
const FiberTypeId = "~effect/Fiber";
const fiberVariance = {
_A: identity,
_E: identity,
};
const fiberIdStore = { id: 0 };
const AsyncResource = /*#__PURE__*/ (() => {
try {
return globalThis.process?.getBuiltinModule?.(
"node:async_hooks",
)?.AsyncResource;
} catch {
return;
}
})();
const captureAsyncContext = () =>
AsyncResource === void 0
? void 0
: new AsyncResource("effect/Fiber");
/** @internal */
const getCurrentFiber = () =>
globalThis[currentFiberTypeId];
/** @internal */
var FiberImpl = class {
constructor(context, interruptible = true) {
this.setContext(context);
this.id = ++fiberIdStore.id;
this.currentOpCount = 0;
this.interruptible = interruptible;
this._stack = [];
this._observers = void 0;
this._exit = void 0;
this._children = void 0;
this._interruptedCause = void 0;
this._yielded = void 0;
this._running = false;
this._deferredInterrupt = false;
this._parent = void 0;
this._asyncContext = void 0;
this.cache.runtimeMetrics?.recordFiberStart(
this.context,
);
}
get [FiberTypeId]() {
return fiberVariance;
}
get currentDispatcher() {
return (this._dispatcher ??=
this.cache.scheduler.makeDispatcher());
}
getRef(ref) {
return get(this.context, ref);
}
addObserver(cb) {
if (this._exit) {
cb(this._exit);
return constVoid;
}
if (this._observers === void 0) this._observers = [cb];
else this._observers.push(cb);
return () => this.removeObserver(cb);
}
removeObserver(cb) {
if (this._exit || this._observers === void 0) return;
const index = this._observers.indexOf(cb);
if (index >= 0) this._observers.splice(index, 1);
}
interruptUnsafe(fiberId, annotations) {
if (this._exit) return;
let cause = causeInterrupt(fiberId);
if (this.cache.stackFrame)
cause = causeAnnotate(
cause,
make$8(StackTraceKey, this.cache.stackFrame),
);
if (annotations)
cause = causeAnnotate(cause, annotations);
this._interruptedCause = this._interruptedCause
? causeAddInterrupts(this._interruptedCause, cause)
: cause;
if (this.interruptible) {
if (this._running) this._deferredInterrupt = true;
else
this.evaluate(failCause$1(this._interruptedCause));
}
}
pollUnsafe() {
return this._exit;
}
evaluate(effect) {
if (this._exit) return;
else if (this._asyncContext !== void 0) {
const asyncContext = this._asyncContext;
this._asyncContext = void 0;
return asyncContext.runInAsyncScope(
this.evaluate,
this,
effect,
);
} else if (this._yielded !== void 0) {
const yielded = this._yielded;
this._yielded = void 0;
yielded();
}
const exit = this.runLoop(effect);
if (exit === Yield) {
this._asyncContext = captureAsyncContext();
return;
}
const interruptChildren =
fiberMiddleware.interruptChildren &&
fiberMiddleware.interruptChildren(this);
if (interruptChildren !== void 0)
return this.evaluate(
flatMap$1(interruptChildren, () => exit),
);
this._exit = exit;
this.cache.runtimeMetrics?.recordFiberEnd(
this.context,
this._exit,
);
if (this._parent) {
this._parent._children?.delete(this);
this._parent = void 0;
}
if (this._observers !== void 0) {
const observers = this._observers;
this._observers = void 0;
for (let i = 0; i < observers.length; i++)
observers[i](exit);
}
this._stack.length = 0;
this._children = void 0;
this.context = empty();
}
runLoop(effect) {
const prevFiber = globalThis[currentFiberTypeId];
globalThis[currentFiberTypeId] = this;
const prevRunning = this._running;
this._running = true;
let yielding = false;
let current = effect;
this.currentOpCount = 0;
try {
while (true)
try {
if (this._deferredInterrupt) {
this._deferredInterrupt = false;
current = failCause$1(this._interruptedCause);
}
this.currentOpCount++;
const cache = this.cache;
if (
!yielding &&
!cache.preventYield &&
cache.scheduler.shouldYield(this)
) {
yielding = true;
const prev = current;
current = flatMap$1(yieldNow, () => prev);
}
current = cache.tracerContext
? cache.tracerContext(current, this)
: current[evaluate](this);
if (current === Yield) {
const yielded = this._yielded;
if ("~effect/Exit" in yielded) {
this._deferredInterrupt = false;
this._yielded = void 0;
return yielded;
} else if (this._deferredInterrupt) {
this._yielded = void 0;
yielded();
continue;
}
return Yield;
}
} catch (error) {
if (
!hasProperty(current, "~effect/Effect/evaluate")
)
return exitDie(
`Fiber.runLoop: Not a valid effect: ${String(current)}`,
);
current = exitDie(error);
}
} finally {
this._running = prevRunning;
globalThis[currentFiberTypeId] = prevFiber;
}
}
getCont(symbol) {
if (this._deferredInterrupt) {
this._deferredInterrupt = false;
return deferredInterruptCont;
}
while (true) {
const op = this._stack.pop();
if (!op) return void 0;
const all = op[contAll];
if (all !== void 0) {
const cont = all.call(op, this);
if (cont) {
cont[symbol] = cont;
return cont;
}
}
if (op[symbol]) return op;
}
}
succeedWith(value) {
if (
(++this.currentOpCount & (maxInlineSteps - 1)) ===
0
)
return exitSucceed(value);
const cont = this.getCont(contA);
return cont
? cont[contA](value, this)
: this.yieldWith(exitSucceed(value));
}
yieldWith(value) {
this._yielded = value;
return Yield;
}
children() {
return (this._children ??= /* @__PURE__ */ new Set());
}
pipe() {
return pipeArguments(this, arguments);
}
setContext(context) {
const previous = this.context;
this.context = context;
if (
previous !== void 0 &&
hasSameCache(previous, context)
)
return;
const root = context.cacheRoot;
const cache = (root._fiberCache ??=
makeFiberContextCache(context));
if (this.cache?.scheduler !== cache.scheduler)
this._dispatcher = void 0;
this.cache = cache;
}
get currentSpanLocal() {
const span = this.cache.span;
return span?._tag === "Span" ? span : void 0;
}
};
const makeFiberContextCache = (context) => {
const currentTracer = getOrUndefinedUnsafe(
context,
TracerKey,
);
return {
scheduler: get(context, Scheduler),
tracer: currentTracer,
tracerContext: currentTracer
? currentTracer["context"]
: void 0,
tracerEnabled: get(context, TracerEnabled),
span: getOrUndefinedUnsafe(context, ParentSpanKey),
logLevel: get(context, CurrentLogLevel),
minimumLogLevel: get(context, MinimumLogLevel),
stackFrame: get(context, CurrentStackFrame),
runtimeMetrics: getOrUndefinedUnsafe(
context,
FiberRuntimeMetricsKey,
),
maxOpsBeforeYield: get(context, MaxOpsBeforeYield),
preventYield: get(context, PreventSchedulerYield),
};
};
const deferredInterruptCont = {
[contA](_value, fiber) {
return failCause$1(fiber._interruptedCause);
},
[contE](_cause, fiber) {
return failCause$1(fiber._interruptedCause);
},
};
const maxInlineSteps = 32;
const fiberMiddleware = { interruptChildren: void 0 };
const fiberStackAnnotations = (fiber) => {
if (!fiber.cache.stackFrame) return void 0;
const annotations = /* @__PURE__ */ new Map();
annotations.set(
InterruptorStackTrace.key,
fiber.cache.stackFrame,
);
return makeUnsafe$2(annotations);
};
/** @internal */
const fiberAwaitAll = (self) =>
callback((resume) => {
const iter = self[Symbol.iterator]();
const exits = [];
let cancel = void 0;
function loop() {
let result = iter.next();
while (!result.done) {
if (result.value._exit) {
exits.push(result.value._exit);
result = iter.next();
continue;
}
cancel = result.value.addObserver((exit) => {
exits.push(exit);
loop();
});
return;
}
resume(succeed$3(exits));
}
loop();
return sync(() => cancel?.());
});
/** @internal */
const fiberInterruptAll = (fibers) =>
withFiber((parent) => {
const annotations = fiberStackAnnotations(parent);
let fiberArr = empty$1();
for (const fiber of fibers) {
fiber.interruptUnsafe(parent.id, annotations);
fiberArr.push(fiber);
}
return asVoid(fiberAwaitAll(fiberArr));
});
/** @internal */
const succeed$3 = exitSucceed;
/** @internal */
const failCause$1 = exitFailCause;
/** @internal */
const fail$3 = exitFail;
/** @internal */
const sync = /*#__PURE__*/ makePrimitive({
op: "Sync",
[evaluate](fiber) {
const value = this[args]();
const cont = fiber.getCont(contA);
return cont
? cont[contA](value, fiber)
: fiber.yieldWith(exitSucceed(value));
},
});
/** @internal */
const suspend$1 = /*#__PURE__*/ makePrimitive({
op: "Suspend",
[evaluate](_fiber) {
return this[args]();
},
});
/** @internal */
const yieldNow =
/*#__PURE__*/ /* @__PURE__ */ makePrimitive({
op: "Yield",
[evaluate](fiber) {
let resumed = false;
fiber.currentDispatcher.scheduleTask(() => {
if (resumed) return;
fiber.evaluate(exitVoid);
}, this["~effect/Effect/args"] ?? 0);
return fiber.yieldWith(() => {
resumed = true;
});
},
})(0);
/** @internal */
const failCauseSync$1 = (evaluate) =>
suspend$1(() => failCause$1(evaluate()));
/** @internal */
const die$2 = (defect) => exitDie(defect);
/** @internal */
const void_$1 = /*#__PURE__*/ succeed$3(void 0);
const callbackOptions = /*#__PURE__*/ (function () {
const Proto = /*#__PURE__*/ makePrimitiveProto({
op: "Async",
[evaluate](fiber) {
let resumed = false;
let yielded = false;
const controller = this.withSignal
? new AbortController()
: void 0;
const onCancel = this.register.call(
fiber.cache.scheduler,
(effect) => {
if (resumed) return;
resumed = true;
if (yielded) fiber.evaluate(effect);
else yielded = effect;
},
controller?.signal,
);
if (yielded !== false) return yielded;
yielded = true;
fiber._yielded = () => {
resumed = true;
};
if (controller === void 0 && onCancel === void 0)
return Yield;
fiber._stack.push(
asyncFinalizer(() => {
resumed = true;
controller?.abort();
return onCancel ?? exitVoid;
}),
);
return Yield;
},
});
const AsyncImpl = function (register, withSignal) {
this.register = register;
this.withSignal = withSignal;
};
AsyncImpl.prototype = Proto;
return function (register, withSignal) {
return new AsyncImpl(register, withSignal);
};
})();
const asyncFinalizer = /*#__PURE__*/ makePrimitive({
op: "AsyncFinalizer",
[contAll](fiber) {
if (fiber.interruptible) {
fiber.interruptible = false;
fiber._stack.push(setInterruptibleTrue);
}
},
[contE](cause, _fiber) {
return hasInterrupts(cause)
? flatMap$1(
combineFinalizerCause(
exitFailCause(cause),
this[args](),
),
() => failCause$1(cause),
)
: failCause$1(cause);
},
});
/** @internal */
const callback = (register) =>
callbackOptions(register, register.length >= 2);
const defineFunctionLength = (length, fn) =>
Object.defineProperty(fn, "length", {
value: length,
configurable: true,
});
/** @internal */
const fnUntracedEager$1 = (body, ...pipeables) =>
defineFunctionLength(
body.length,
pipeables.length === 0
? function () {
return fromIteratorEagerUnsafe(() =>
body.apply(this, arguments),
);
}
: function () {
let effect = fromIteratorEagerUnsafe(() =>
body.apply(this, arguments),
);
for (const pipeable of pipeables)
effect = pipeable(effect, ...arguments);
return effect;
},
);
const fromIteratorEagerUnsafe = (evaluate) => {
try {
const iterator = evaluate();
let value = void 0;
while (true) {
const state = iterator.next(value);
if (state.done) return succeed$3(state.value);
const primitive = state.value;
if (primitive && primitive._tag === "Success") {
value = primitive.value;
continue;
} else if (primitive && primitive._tag === "Failure")
return state.value;
else {
let isFirstExecution = true;
return suspend$1(() => {
if (isFirstExecution) {
isFirstExecution = false;
return flatMap$1(state.value, (value) =>
fromIteratorUnsafe(iterator, value),
);
} else
return suspend$1(() =>
fromIteratorUnsafe(evaluate()),
);
});
}
}
} catch (error) {
return die$2(error);
}
};
const fromIteratorUnsafe = /*#__PURE__*/ (function () {
const Proto = /*#__PURE__*/ makePrimitiveProto({
op: "Iterator",
[contA](value, fiber) {
const iter = this.iterator;
while (true) {
const state = iter.next(value);
if (state.done) return succeed$3(state.value);
if (!effectIsExit(state.value)) {
fiber._stack.push(this);
return state.value;
} else if (state.value._tag === "Failure")
return state.value;
value = state.value.value;
}
},
[evaluate](fiber) {
return this[contA](this.initial, fiber);
},
});
const IteratorImpl = function (iterator, initial) {
this.iterator = iterator;
this.initial = initial;
};
IteratorImpl.prototype = Proto;
return function (iterator, initial) {
return new IteratorImpl(iterator, initial);
};
})();
const evaluateCont = function (fiber) {
fiber._stack.push(this);
return this[args];
};
const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({
op: "OnSuccess",
[evaluate]: evaluateCont,
});
const ContImpl = function (self, cont, payload) {
this[args] = self;
this[contA] = cont;
this.payload = payload;
};
ContImpl.prototype = OnSuccessProto;
const returnPayload = function () {
return this.payload;
};
const continuationMarksStack = /*#__PURE__*/ (() => {
const limit = /*#__PURE__*/ getStackTraceLimit();
if (limit === 0) return false;
const marker = "~effect/Effect/stackProbe";
const probe = {
[marker]: function stackProbe() {
return /* @__PURE__ */ new Error();
},
};
setStackTraceLimit(1);
const error = /*#__PURE__*/ probe[marker]();
setStackTraceLimit(limit);
return (
error.stack?.includes("[as " + marker + "]") === true
);
})();
const mapCont = function (value, fiber) {
const f = this.payload;
return fiber.succeedWith(
continuationMarksStack
? f(value)
: internalCall(() => f(value)),
);
};
const andThenCont = function (value) {
const f = this.payload;
return f(value);
};
/** @internal */
const asVoid = (self) =>
new ContImpl(self, returnPayload, exitVoid);
/** @internal */
const flatMap$1 = /*#__PURE__*/ dual(
2,
(self, f) => new ContImpl(self, andThenCont, f),
);
/** @internal */
const effectIsExit = (effect) =>
effect[ExitTypeId] !== void 0;
/** @internal */
const flatMapEager$1 = /*#__PURE__*/ dual(2, (self, f) => {
if (effectIsExit(self))
return self._tag === "Success" ? f(self.value) : self;
return flatMap$1(self, f);
});
/** @internal */
const map$1 = /*#__PURE__*/ dual(
2,
(self, f) => new ContImpl(self, mapCont, f),
);
/** @internal */
const mapEager$1 = /*#__PURE__*/ dual(2, (self, f) =>
effectIsExit(self) ? exitMap(self, f) : map$1(self, f),
);
/** @internal */
const exitIsSuccess = (self) => self._tag === "Success";
/** @internal */
const exitVoid = /*#__PURE__*/ exitSucceed(void 0);
/** @internal */
const exitMap = /*#__PURE__*/ dual(2, (self, f) =>
self._tag === "Success"
? exitSucceed(f(self.value))
: self,
);
/** @internal */
const catchCause$1 = /*#__PURE__*/ dual(
2,
(self, f) =>
new OnFailureImpl(
self,
f.length !== 1 ? (cause) => f(cause) : f,
),
);
const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({
op: "OnFailure",
[evaluate]: evaluateCont,
});
const OnFailureImpl = function (self, f) {
this[args] = self;
this[contE] = f;
};
OnFailureImpl.prototype = OnFailureProto;
const OnSuccessAndFailureProto =
/*#__PURE__*/ makePrimitiveProto({
op: "OnSuccessAndFailure",
[evaluate]: evaluateCont,
});
const OnSuccessAndFailureImpl = function (
self,
onSuccess,
onFailure,
) {
this[args] = self;
this[contA] = onSuccess;
this[contE] = onFailure;
};
OnSuccessAndFailureImpl.prototype =
OnSuccessAndFailureProto;
/** @internal */
const exit$1 = (self) =>
effectIsExit(self)
? exitSucceed(self)
: exitPrimitive(self);
const exitPrimitive = /*#__PURE__*/ makePrimitive({
op: "Exit",
[evaluate](fiber) {
fiber._stack.push(this);
return this[args];
},
[contA](value, fiber, exit) {
return fiber.succeedWith(exit ?? exitSucceed(value));
},
[contE](cause, fiber, exit) {
return fiber.succeedWith(exit ?? exitFailCause(cause));
},
});
const combineFinalizerCause = (exit_, finalizer) =>
exitIsSuccess(exit_)
? finalizer
: catchCause$1(finalizer, (cause) =>
failCause$1(causeCombine(exit_.cause, cause)),
);
/** @internal */
const uninterruptible = (self) =>
withFiber((fiber) => {
if (!fiber.interruptible) return self;
fiber.interruptible = false;
fiber._stack.push(setInterruptibleTrue);
return self;
});
const setInterruptibleTrue =
/*#__PURE__*/ /* @__PURE__ */ makePrimitive({
op: "SetInterruptible",
[contAll](fiber) {
fiber.interruptible = this[args];
if (fiber._interruptedCause && fiber.interruptible)
return () => failCause$1(fiber._interruptedCause);
},
})(true);
/** @internal */
const resolveConcurrency = (concurrency) =>
concurrency === "unbounded"
? Number.POSITIVE_INFINITY
: Math.max(1, concurrency ?? 1);
/** @internal */
const iterateEager = () => (options) => {
const onItem = options.onItem;
const step = options.step;
const resumeSequential = (
state,
items,
index,
end,
effect,
) =>
flatMap$1(
exit$1(effect),
(itemExit) =>
step(state, items[index], itemExit, index) ??
runSequential(state, items, index + 1, end) ??
void_$1,
);
const runSequential = (
state,
items,
index = 0,
end = items.length,
) => {
for (; index < end; index++) {
const item = items[index];
const effect = onItem(state, item, index);
if (!effectIsExit(effect))
return resumeSequential(
state,
items,
index,
end,
effect,
);
const terminal = step(state, item, effect, index);
if (terminal)
return terminal._tag === "Failure"
? terminal
: void 0;
}
};
return runSequential;
};
const iterateConcurrentImpl = (options) => {
const onItem = options.onItem;
const step = options.step;
return (state, items, opts) => {
let index = 0;
const end = opts.end ?? items.length;
const concurrency = opts.concurrency;
let done = false;
let parentFiber;
let fibers;
let resume;
let terminal;
let effect;
const failDefect = (error) => {
const defect = exitDie(error);
terminal = defect;
done = true;
return fibers && fibers.size > 0
? flatMap$1(
uninterruptible(
fiberInterruptAll(Array.from(fibers)),
),
() => terminal ?? defect,
)
: defect;
};
const go = () => {
let paused = false;
for (; !terminal && index < end; index++) {
const item = items[index];
const eff = effect ?? onItem(state, item, index);
if (effectIsExit(eff)) {
terminal = step(state, item, eff, index);
if (terminal) break;
} else if (!parentFiber)
return callback((cb) => {
parentFiber = getCurrentFiber();
fibers = /* @__PURE__ */ new Set();
effect = eff;
resume = cb;
let result;
try {
result = go();
} catch (error) {
return cb(failDefect(error));
}
if (result) return cb(result);
return suspend$1(() => {
terminal ??= exitVoid;
return flatMap$1(
fibers
? fiberInterruptAll(fibers)
: void_$1,
() =>
terminal?._tag === "Failure"
? terminal
: void_$1,
);
});
});
else {
effect = void 0;
const fiber = forkUnsafe(
parentFiber,
eff,
true,
true,
"inherit",
);
if (fiber._exit) {
terminal = step(
state,
item,
fiber._exit,
index,
);
if (terminal) break;
continue;
}
fibers.add(fiber);
const currentIndex = index;
fiber.addObserver((exit) => {
fibers.delete(fiber);
try {
if (terminal) {
if (exit._tag === "Failure") {
const reasons = exit.cause.reasons.filter(
(reason) => reason._tag !== "Interrupt",
);
if (reasons.length > 0) {
const cause = causeFromReasons(reasons);
terminal = exitFailCause(
terminal._tag === "Failure"
? causeCombine(
terminal.cause,
cause,
)
: cause,
);
}
}
} else {
const result = step(
state,
item,
exit,
currentIndex,
);
if (result) {
terminal = result;
go();
}
}
if (paused) {
const eff = go();
if (eff) resume(eff);
} else if (done && fibers.size === 0)
resume(terminal ?? void_$1);
} catch (error) {
resume(failDefect(error));
}
});
if (fibers.size < concurrency) continue;
paused = true;
index++;
return;
}
}
done = true;
if (terminal) {
if (fibers && fibers.size > 0) {
const annotations =
fiberStackAnnotations(parentFiber);
fibers.forEach((f) =>
f.interruptUnsafe(parentFiber.id, annotations),
);
return;
}
if (resume || terminal._tag === "Failure")
return terminal;
} else if (resume) {
if (!fibers) return exitVoid;
else if (fibers.size === 0) resume(void_$1);
}
};
return go();
};
};
/** @internal */
const iterateConcurrent = () => (options) =>
iterateConcurrentImpl(options);
/** @internal */
const forkUnsafe = (
parent,
effect,
immediate = false,
daemon = false,
uninterruptible = false,
) => {
const parentRuntime = parent;
const interruptible =
uninterruptible === "inherit"
? parentRuntime.interruptible
: !uninterruptible;
const child = new FiberImpl(
parentRuntime.context,
interruptible,
);
if (!daemon) {
parentRuntime.children().add(child);
child._parent = parentRuntime;
}
if (immediate) child.evaluate(effect);
else {
child._asyncContext = captureAsyncContext();
parentRuntime.currentDispatcher.scheduleTask(
() => child.evaluate(effect),
0,
);
}
return child;
};
/** @internal */
const runForkWith = (context) => (effect, options) => {
const fiber = new FiberImpl(
options?.scheduler
? add(context, Scheduler, options.scheduler)
: context,
options?.uninterruptible !== true,
);
fiber.evaluate(effect);
if (fiber._exit) return fiber;
if (options?.signal) {
if (options.signal.aborted) fiber.interruptUnsafe();
else {
const abort = () => fiber.interruptUnsafe();
options.signal.addEventListener("abort", abort, {
once: true,
});
fiber.addObserver(() =>
options.signal.removeEventListener("abort", abort),
);
}
}
if (options?.onFiberStart) options.onFiberStart(fiber);
return fiber;
};
/** @internal */
const runSyncExitWith = (context) => {
const runFork = runForkWith(context);
return (effect) => {
if (effectIsExit(effect)) return effect;
const scheduler = new MixedScheduler("sync");
const fiber = runFork(effect, { scheduler });
fiber._dispatcher?.flush();
return (
fiber._exit ?? exitDie(new AsyncFiberError(fiber))
);
};
};
/** @internal */
const runSyncExit$1 = /*#__PURE__*/ runSyncExitWith(
/*#__PURE__*/ empty(),
);
/** @internal */
const AsyncFiberErrorTypeId =
"~effect/Cause/AsyncFiberError";
/** @internal */
var AsyncFiberError = class extends /*#__PURE__*/ TaggedError$1(
"AsyncFiberError",
) {
[AsyncFiberErrorTypeId] = AsyncFiberErrorTypeId;
constructor(fiber) {
super({
message:
"An asynchronous Effect was executed with Effect.runSync",
fiber,
});
}
};
const colors = {
bold: "1",
red: "31",
green: "32",
yellow: "33",
blue: "34",
cyan: "36",
white: "37",
gray: "90",
black: "30",
bgBrightRed: "101",
};
(colors.gray,
colors.blue,
colors.green,
colors.yellow,
colors.red,
colors.bgBrightRed,
colors.black);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Cause.js
/**
* Narrows a `Reason` to `Fail`.
*
* **When to use**
*
* Use as a predicate for `Array.filter` to pick out typed `Fail` reasons when
* iterating over `cause.reasons`.
*
* **Example** (Filtering fail reasons)
*
* ```ts import.meta.vitest
* import { Cause } from "effect"
*
* const cause = Cause.fail("error")
* const fails = cause.reasons.filter(Cause.isFailReason)
* fails[0].error // => "error"
* ```
*
* @see {@link isDieReason} — narrow to `Die`
* @see {@link isInterruptReason} — narrow to `Interrupt`
*
* @stability stable
* @category guards
* @since 4.0.0
*/
const isFailReason = isFailReason$1;
/**
* Creates a `Cause` containing a single `Die` reason with the
* given defect.
*
* **When to use**
*
* Use to construct a cause from an untyped defect or unexpected thrown value.
*
* **Example** (Creating a die cause)
*
* ```ts import.meta.vitest
* import { Cause } from "effect"
*
* Cause.die("Unexpected") // => Cause.fromReasons([Cause.makeDieReason("Unexpected")])
* ```
*
* @see {@link fail} — for typed errors
* @see {@link interrupt} — for fiber interruptions
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const die$1 = causeDie;
/**
* Transforms the typed error values inside a `Cause` using the
* provided function. Only `Fail` reasons are affected; `Die` and `Interrupt`
* reasons pass through unchanged.
*
* **When to use**
*
* Use to transform expected typed failures while preserving defects and
* interruptions unchanged.
*
* **Details**
*
* If at least one `Fail` reason exists, this returns a new `Cause`
* containing the mapped failures. If the cause has no `Fail` reasons, the
* original cause is returned unchanged.
*
* **Example** (Mapping errors to uppercase)
*
* ```ts import.meta.vitest
* import { Cause } from "effect"
*
* const cause = Cause.fail("error")
* const mapped = Cause.map(cause, (e) => e.toUpperCase())
* const reason = mapped.reasons[0]
* if (Cause.isFailReason(reason)) {
* reason.error // => "ERROR"
* }
* ```
*
* @stability stable
* @category mapping
* @since 2.0.0
*/
const map = causeMap;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Exit.js
/**
* Creates a successful Exit containing the given value.
*
* **When to use**
*
* Use when you need an Exit that contains a known success value.
*
* **Details**
*
* Returns a `Success<A>` with the provided value. Does not perform any
* computation.
*
* **Example** (Creating a successful Exit)
*
* ```ts import.meta.vitest
* import { Exit } from "effect"
*
* Exit.succeed(42) // => Exit.succeed(42)
* ```
*
* @see {@link fail} to create a failed Exit
* @see {@link void_ void} for a pre-allocated success with no value
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const succeed$2 = exitSucceed;
/**
* Creates a failed Exit from a Cause.
*
* **When to use**
*
* Use when you already have a `Cause<E>` and want to wrap it in an Exit
* for advanced error handling where you need full control over the Cause
* structure.
*
* **Details**
*
* Returns a `Failure<never, E>`. If you only have an error value, use
* {@link fail} instead.
*
* **Example** (Creating a failed Exit from a Cause)
*
* ```ts import.meta.vitest
* import { Cause, Exit } from "effect"
*
* Exit.failCause(Cause.fail("Something went wrong")) // => Exit.fail("Something went wrong")
* ```
*
* @see {@link fail} to create a Failure from a plain error value
* @see {@link die} to create a Failure from a defect
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const failCause = exitFailCause;
/**
* Creates a failed Exit from a typed error value.
*
* **When to use**
*
* Use when you need to represent an expected typed failure as an `Exit`.
*
* **Details**
*
* The error is wrapped in a `Cause.Fail` internally.
*
* Returns a `Failure<never, E>`.
*
* **Example** (Creating a failed Exit)
*
* ```ts import.meta.vitest
* import { Exit } from "effect"
*
* Exit.fail("Something went wrong") // => Exit.fail("Something went wrong")
* ```
*
* @see {@link succeed} to create a successful Exit
* @see {@link die} to create a Failure from an unexpected defect
* @see {@link failCause} to create a Failure from a full Cause
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const fail$2 = exitFail;
const void_ = exitVoid;
/**
* Checks whether an Exit is a Success.
*
* **When to use**
*
* Use as a type guard to narrow `Exit<A, E>` to `Success<A, E>` and access the
* `value` property.
*
* **Example** (Narrowing to success)
*
* ```ts import.meta.vitest
* import { Exit } from "effect"
*
* const exit = Exit.succeed(42)
*
* if (Exit.isSuccess(exit)) {
* exit.value // => 42
* }
* ```
*
* @see {@link isFailure} for the opposite check
* @see {@link match} for exhaustive pattern matching
*
* @stability stable
* @category guards
* @since 2.0.0
*/
const isSuccess = exitIsSuccess;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/dateTime.js
/** @internal */
const TypeId$10 = "~effect/DateTime";
/** @internal */
const TimeZoneTypeId = "~effect/DateTime/TimeZone";
const Proto$4 = {
[TypeId$10]: TypeId$10,
pipe() {
return pipeArguments(this, arguments);
},
[NodeInspectSymbol]() {
return this.toString();
},
toJSON() {
return toDateUtc$1(this).toJSON();
},
};
({ ...Proto$4 });
({ ...Proto$4 });
const ProtoTimeZone = {
[TimeZoneTypeId]: TimeZoneTypeId,
[NodeInspectSymbol]() {
return this.toString();
},
};
({ ...ProtoTimeZone });
({ ...ProtoTimeZone });
/** @internal */
const toDateUtc$1 = (self) =>
new Date(self.epochMilliseconds);
/**
* Creates an `Effect` that always succeeds with a given value.
*
* **When to use**
*
* Use when an effect should complete successfully with a specific value without any errors
* or external dependencies.
*
* **Example** (Creating a successful effect)
*
* ```ts import.meta.vitest
* import { Effect } from "effect"
*
* // Creating an effect that represents a successful scenario
* //
* // ┌─── Effect<number, never, never>
* // â–¼
* const success = Effect.succeed(42)
* Effect.runSync(success) // => 42
* ```
*
* @see {@link fail} to create an effect that represents a failure.
* @stability stable
* @category constructors
* @since 2.0.0
*/
const succeed$1 = succeed$3;
/**
* Creates an `Effect` lazily, delaying construction until it is needed.
*
* **When to use**
*
* Use when you need to defer the evaluation of an effect until it is required.
*
* **Details**
*
* `suspend` takes a thunk that represents an effect and delays creating it
* until the suspended effect is evaluated. This is useful for optimizing
* expensive computations, managing circular dependencies such as recursive
* functions, and helping TypeScript unify return types when branches construct
* different effects. Any side effects or scoped captures inside the thunk are
* re-executed on each invocation.
*
* **Example** (Lazily evaluating side effects)
*
* ```ts import.meta.vitest
* import { Effect } from "effect"
*
* let i = 0
*
* const bad = Effect.succeed(i++)
*
* const good = Effect.suspend(() => Effect.succeed(i++))
*
* Effect.runSync(bad) // => 0
* Effect.runSync(bad) // => 0
*
* Effect.runSync(good) // => 1
* Effect.runSync(good) // => 2
* ```
*
* **Example** (Suspending recursive Fibonacci evaluation)
*
* ```ts import.meta.vitest
* import { Effect } from "effect"
*
* const blowsUp = (n: number): Effect.Effect<number> =>
* n < 2
* ? Effect.succeed(1)
* : Effect.zipWith(blowsUp(n - 1), blowsUp(n - 2), (a, b) => a + b)
*
* // console.log(Effect.runSync(blowsUp(32)))
* // crash: JavaScript heap out of memory
*
* const allGood = (n: number): Effect.Effect<number> =>
* n < 2
* ? Effect.succeed(1)
* : Effect.zipWith(
* Effect.suspend(() => allGood(n - 1)),
* Effect.suspend(() => allGood(n - 2)),
* (a, b) => a + b
* )
*
* Effect.runSync(allGood(16)) // => 1597
* ```
*
* **Example** (Helping TypeScript infer recursive effect types)
*
* ```ts import.meta.vitest
* import { Effect } from "effect"
*
* // Without suspend, TypeScript may struggle with type inference.
* // Inferred type:
* // (a: number, b: number) =>
* // Effect<never, Error, never> | Effect<number, never, never>
* const withoutSuspend = (a: number, b: number) =>
* b === 0
* ? Effect.fail(new Error("Cannot divide by zero"))
* : Effect.succeed(a / b)
*
* // Using suspend to unify return types.
* // Inferred type:
* // (a: number, b: number) => Effect<number, Error, never>
* const withSuspend = (a: number, b: number) =>
* Effect.suspend(() =>
* b === 0
* ? Effect.fail(new Error("Cannot divide by zero"))
* : Effect.succeed(a / b)
* )
*
* Effect.runSync(withSuspend(6, 2)) // => 3
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const suspend = suspend$1;
/**
* Creates an `Effect` that represents a recoverable error.
*
* **When to use**
*
* Use to explicitly signal a recoverable error in an `Effect`.
*
* **Details**
*
* The error keeps propagating unless it is handled. You can handle tagged
* errors with functions like {@link catchTag} or {@link catchTags}.
*
* **Example** (Creating a failed effect)
*
* ```ts import.meta.vitest
* import { Data, Effect } from "effect"
*
* class OperationFailedError extends Data.TaggedError("OperationFailedError")<{}> {}
*
* // ┌─── Effect<never, OperationFailedError, never>
* // â–¼
* const failure = Effect.fail(
* new OperationFailedError()
* )
* Effect.runSync(Effect.flip(failure))._tag // => "OperationFailedError"
* ```
*
* @see {@link succeed} to create an effect that represents a successful value.
* @stability stable
* @category constructors
* @since 2.0.0
*/
const fail$1 = fail$3;
/**
* Creates an `Effect` that represents a failure with a `Cause` computed lazily.
*
* **When to use**
*
* Use to defer computing a full `Cause` until the effect is run.
*
* **Details**
*
* The cause-producing function is evaluated each time the effect is executed.
*
* **Example** (Lazily creating a Cause)
*
* ```ts import.meta.vitest
* import { Cause, Effect } from "effect"
*
* const program = Effect.failCauseSync(() =>
* Cause.fail("Error computed at runtime")
* )
*
* Effect.runSync(Effect.flip(program)) // => "Error computed at runtime"
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const failCauseSync = failCauseSync$1;
/**
* Creates an effect that terminates a fiber with a specified error.
*
* **When to use**
*
* Use when you need an `Effect` to report an unrecoverable defect instead of a
* typed error.
*
* **Details**
*
* The `die` function is used to signal a defect, which represents a critical
* and unexpected error in the code. When invoked, it produces an effect that
* does not handle the error and instead terminates the fiber.
*
* The error channel of the resulting effect is of type `never`, indicating that
* it cannot recover from this failure.
*
* **Example** (Failing on division by zero)
*
* ```ts import.meta.vitest
* import { Effect, Exit } from "effect"
*
* const defect = new Error("Cannot divide by zero")
* const divide = (a: number, b: number) =>
* b === 0
* ? Effect.die(defect)
* : Effect.succeed(a / b)
*
* // ┌─── Effect<number, never, never>
* // â–¼
* const program = divide(1, 0)
*
* Effect.runSyncExit(program) // => Exit.die(defect)
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const die = die$2;
/**
* Chains effects to produce new `Effect` instances, useful for combining
* operations that depend on previous results.
*
* **When to use**
*
* Use when you need to chain multiple effects, ensuring that each
* step produces a new `Effect` while flattening any nested effects that may
* occur.
*
* **Details**
*
* `flatMap` lets you sequence effects so that the result of one effect can be
* used in the next step. It is similar to `flatMap` used with arrays but works
* specifically with `Effect` instances, allowing you to avoid deeply nested
* effect structures.
*
* Since effects are immutable, `flatMap` always returns a new effect instead of
* changing the original one.
*
* **Example** (Choosing flatMap syntax variants)
*
* ```ts import.meta.vitest
* import { Effect, pipe } from "effect"
* const output: Array<unknown> = []
*
* const myEffect = Effect.succeed(1)
* const transformation = (n: number) => Effect.succeed(n + 1)
*
* const flatMappedWithPipe = pipe(myEffect, Effect.flatMap(transformation))
* const flatMappedWithDataFirst = Effect.flatMap(myEffect, transformation)
* const flatMappedWithMethod = myEffect.pipe(Effect.flatMap(transformation))
*
* void output.push(Effect.runSync(Effect.all([
* flatMappedWithPipe,
* flatMappedWithDataFirst,
* flatMappedWithMethod
* ])))
* output // => [[2, 2, 2]]
* ```
*
* **Example** (Sequencing dependent effects)
*
* ```ts import.meta.vitest
* import { Data, Effect, pipe } from "effect"
*
* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {}
*
* // Function to apply a discount safely to a transaction amount
* const applyDiscount = (
* total: number,
* discountRate: number
* ): Effect.Effect<number, DiscountRateError> =>
* discountRate === 0
* ? Effect.fail(new DiscountRateError())
* : Effect.succeed(total - (total * discountRate) / 100)
*
* // Simulated asynchronous task to fetch a transaction amount from database
* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
*
* // Chaining the fetch and discount application using `flatMap`
* const finalAmount = pipe(
* fetchTransactionAmount,
* Effect.flatMap((amount) => applyDiscount(amount, 5))
* )
*
* await Effect.runPromise(finalAmount) // => 95
* ```
*
* @see {@link tap} for a version that ignores the result of the effect.
* @stability stable
* @category sequencing
* @since 2.0.0
*/
const flatMap = flatMap$1;
/**
* Transforms an effect to encapsulate both failure and success using the `Exit`
* data type.
*
* **When to use**
*
* Use when you need to inspect the full outcome, including typed failures, defects,
* and interruptions.
*
* **Details**
*
* `exit` wraps an effect's success or failure inside an `Exit` type, allowing
* you to handle both cases explicitly.
*
* The resulting effect cannot fail because the failure is encapsulated within
* the `Exit.Failure` type. The error type is set to `never`, indicating that
* the effect is structured to never fail directly.
*
* **Example** (Capturing completion as Exit)
*
* ```ts import.meta.vitest
* import { Effect, Exit } from "effect"
*
* const success = Effect.succeed(42)
* const failure = Effect.fail("Something went wrong")
*
* const program1 = Effect.exit(success)
* const program2 = Effect.exit(failure)
*
* Effect.runSync(program1) // => Exit.succeed(42)
*
* Effect.runSync(program2) // => Exit.fail("Something went wrong")
* ```
*
* @see {@link option} for a version that uses `Option` instead.
* @see {@link result} for a version that uses `Result` instead.
*
* @stability stable
* @category error handling
* @since 2.0.0
*/
const exit = exit$1;
/**
* Handles both recoverable and unrecoverable errors by providing a recovery
* effect.
*
* **When to use**
*
* Use when you need to recover from an `Effect` by inspecting the full `Cause`,
* including recoverable failures, defects, and interruptions, instead of only
* the typed error value.
*
* **Details**
*
* When to Recover from Defects:
*
* Defects are unexpected errors that typically shouldn't be recovered from, as
* they often indicate serious issues. However, in some cases, such as
* dynamically loaded plugins, controlled recovery might be needed.
*
* **Example** (Recovering from full failure causes)
*
* ```ts import.meta.vitest
* import { Cause, Effect } from "effect"
* const output: Array<unknown> = []
*
* // An effect that might fail in different ways
* const program = Effect.die("Something went wrong")
*
* // Recover from any cause (including defects)
* const recovered = Effect.catchCause(program, (cause) => {
* if (Cause.hasDies(cause)) {
* return Effect.sync(() => { output.push("Caught defect") }).pipe(
* Effect.as("Recovered from defect")
* )
* }
* return Effect.succeed("Unknown error")
* })
*
* void output.push(Effect.runSync(recovered))
* output // => ["Caught defect", "Recovered from defect"]
* ```
*
* @stability stable
* @category error handling
* @since 4.0.0
*/
const catchCause = catchCause$1;
/**
* Runs an effect synchronously and captures the outcome safely as an `Exit` type, which
* represents the outcome (success or failure) of the effect.
*
* **When to use**
*
* Use to find out whether an effect succeeded or failed,
* including any defects, without dealing with asynchronous operations.
*
* **Details**
*
* The `Exit` type represents the result of the effect. Successful effects are
* wrapped in `Success`, and failed effects are wrapped in `Failure` with a
* `Cause`.
*
* If the effect contains asynchronous operations, `runSyncExit` will
* return an `Failure` with a `Die` cause, indicating that the effect cannot be
* resolved synchronously.
*
* **Example** (Observing synchronous results as Exit)
*
* ```ts import.meta.vitest
* import { Effect, Exit } from "effect"
*
* Effect.runSyncExit(Effect.succeed(1)) // => Exit.succeed(1)
*
* Effect.runSyncExit(Effect.fail("my error")) // => Exit.fail("my error")
* ```
*
* **Example** (Capturing async work as a Die cause)
*
* ```ts import.meta.vitest
* import { Cause, Effect, Exit } from "effect"
*
* const exit = Effect.runSyncExit(Effect.promise(() => Promise.resolve(1)))
* const isAsyncDie = Exit.hasDies(exit) && exit.cause.reasons.some(
* (reason) => Cause.isDieReason(reason) && Cause.isAsyncFiberError(reason.defect)
* )
*
* isAsyncDie // => true
* ```
*
* @see {@link runSync} for a version that throws on failure.
*
* @stability stable
* @category running
* @since 2.0.0
*/
const runSyncExit = runSyncExit$1;
/**
* Applies `map` eagerly when an effect is already resolved.
*
* **When to use**
*
* Use when an already-resolved effect should apply a success transformation
* immediately while pending effects still use regular mapping.
*
* **Details**
*
* Success effects apply the mapping function immediately. Failure effects pass
* through unchanged, and pending effects fall back to regular `map` behavior.
*
* **Example** (Mapping already completed effects)
*
* ```ts import.meta.vitest
* import { Effect } from "effect"
*
* // For resolved effects, the mapping is applied immediately
* const resolved = Effect.succeed(5)
* const mapped = Effect.mapEager(resolved, (n) => n * 2) // Applied eagerly
*
* // For pending effects, behaves like regular map
* const pending = Effect.delay(Effect.succeed(5), 0)
* const mappedPending = Effect.mapEager(pending, (n) => n * 2) // Uses regular map
*
* await Effect.runPromise(Effect.all([mapped, mappedPending])) // => [10, 10]
* ```
*
* @stability stable
* @category mapping
* @since 4.0.0
*/
const mapEager = mapEager$1;
/**
* Applies `flatMap` eagerly when an effect is already resolved.
*
* **When to use**
*
* Use when an already-resolved successful effect should bind immediately to the
* next effect while pending effects still use regular flat mapping.
*
* **Details**
*
* Success effects apply the flatMap function immediately. Failure effects pass
* through unchanged, and pending effects fall back to regular `flatMap`
* behavior.
*
* **Example** (Flat mapping eagerly when possible)
*
* ```ts import.meta.vitest
* import { Effect } from "effect"
*
* // For resolved effects, the flatMap is applied immediately
* const resolved = Effect.succeed(5)
* const flatMapped = Effect.flatMapEager(resolved, (n) => Effect.succeed(n * 2)) // Applied eagerly
*
* // For pending effects, behaves like regular flatMap
* const pending = Effect.delay(Effect.succeed(5), 0)
* const flatMappedPending = Effect.flatMapEager(
* pending,
* (n) => Effect.succeed(n * 2)
* ) // Uses regular flatMap
*
* await Effect.runPromise(Effect.all([flatMapped, flatMappedPending])) // => [10, 10]
* ```
*
* @stability stable
* @category sequencing
* @since 4.0.0
*/
const flatMapEager = flatMapEager$1;
/**
* Creates untraced function effects with eager evaluation optimization.
*
* **Details**
*
* Executes generator functions eagerly when all yielded effects are synchronous,
* stopping at the first async effect and deferring to normal execution.
*
* **Example** (Defining eager untraced effect functions)
*
* ```ts import.meta.vitest
* import { Effect } from "effect"
*
* const computation = Effect.fnUntracedEager(function*() {
* yield* Effect.succeed(1)
* yield* Effect.succeed(2)
* return "computed eagerly"
* })
*
* const effect = computation() // Executed immediately if all effects are sync
* Effect.runSync(effect) // => "computed eagerly"
* ```
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const fnUntracedEager = fnUntracedEager$1;
const alphabet =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const codes = /*#__PURE__*/ /* @__PURE__ */ new Uint8Array(
123,
).fill(255);
for (let i = 0; i < 64; i++)
codes[/*#__PURE__*/ alphabet.charCodeAt(i)] = i;
codes[/*#__PURE__*/ "=".charCodeAt(0)] = 0;
({ ...BaseProto });
({ ...BaseProto });
({ ...PipeInspectableProto });
(BaseProto.toString, BaseProto[NodeInspectSymbol]);
({ ...PipeInspectableProto });
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/schema/annotations.js
/** @internal */
function resolve$1(ast) {
return ast.checks
? ast.checks[ast.checks.length - 1].annotations
: ast.annotations;
}
/** @internal */
const STRUCTURAL_ANNOTATION_KEY = "~structural";
/** @internal */
const SENTINELS_ANNOTATION_KEY = "~sentinels";
/** @internal */
const CONSTRUCTOR_ANNOTATION_KEY = "~constructor";
/** @internal */
const getExpected = /*#__PURE__*/ memoize((ast) => {
const identifier = resolve$1(ast)?.identifier;
if (typeof identifier === "string") return identifier;
return ast.getExpected(getExpected);
});
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/schema/parser.js
/** @internal */
const missing = /*#__PURE__*/ Symbol();
/** @internal */
const succeed = succeed$2;
/** @internal */
const missingExit = /*#__PURE__*/ succeed(missing);
/** @internal */
const sameExit = /*#__PURE__*/ succeed(missing);
/** @internal */
const toOption = (value) =>
value === missing ? none() : some(value);
/** @internal */
const fromOptionExit = (option) =>
option._tag === "None"
? missingExit
: succeed(option.value);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/SchemaIssue.js
/**
* Describes problems found while decoding, encoding, or checking data with
* schemas.
*
* An `Issue` records what failed and, for nested data, where the failure
* happened. The Schema system uses these values for missing keys, unexpected
* keys, invalid types, invalid values, failed filters, failed transformations,
* and alternatives that did not match. This module also formats issues.
*
* @stability stable
* @since 4.0.0
*/
const TypeId$5 = "~effect/SchemaIssue/Issue";
/**
* Returns `true` if the given value is an {@link Issue}.
*
* **When to use**
*
* Use when you need to narrow an `unknown` value to `Issue` in error-handling
* code, such as distinguishing an `Issue` from other error types in a catch-all
* handler.
*
* **Details**
*
* - Checks for the internal `TypeId` brand on the value.
*
* **Example** (Type-guarding an unknown error)
*
* ```ts import.meta.vitest
* import { SchemaIssue } from "effect"
*
* const issue = new SchemaIssue.MissingKey(undefined)
* SchemaIssue.isIssue(issue) // => true
* SchemaIssue.isIssue("not an issue") // => false
* ```
*
* @see {@link Issue}
*
* @stability stable
* @category guards
* @since 4.0.0
*/
function isIssue(u) {
return (
hasProperty(u, TypeId$5) && u[TypeId$5] === TypeId$5
);
}
/**
* Returns `true` when an issue contains an input reported by the schema parser.
*
* **When to use**
*
* Use when reading `Issue.input`, especially when `undefined` is a valid input
* value.
*
* **Details**
*
* Reported input is stored as an own property. This guard checks for that
* property and narrows `input` from optional to required.
*
* **Example** (Reading a reported input)
*
* ```ts import.meta.vitest
* import { Result, Schema, SchemaIssue } from "effect"
*
* const result = Schema.decodeUnknownResult(Schema.String)(1, { reportInput: true })
* if (Result.isFailure(result) && SchemaIssue.hasInput(result.failure.issue)) {
* result.failure.issue.input // => 1
* }
* ```
*
* @see {@link Issue} for the complete issue model
*
* @stability stable
* @category guards
* @since 4.0.0
*/
function hasInput(issue) {
return Object.hasOwn(issue, "input");
}
var IssueNodeImpl = class {
[TypeId$5] = TypeId$5;
constructor(input, options) {
if (options?.reportInput === true && input !== missing)
this.input = input;
}
};
/**
* Constructs a schema issue for a failed refinement check.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Filter$1 = class extends IssueNodeImpl {
_tag = "Filter";
/**
* The filter that failed.
*/
filter;
/**
* The issue that occurred.
*/
issue;
constructor(filter, issue, input, options) {
super(input, options);
this.filter = filter;
this.issue = issue;
}
};
/**
* Constructs a schema issue for a failed transformation.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Encoding = class extends IssueNodeImpl {
_tag = "Encoding";
/**
* The schema that caused the issue.
*/
ast;
/**
* The issue that occurred.
*/
issue;
constructor(ast, issue, input, options) {
super(input, options);
this.ast = ast;
this.issue = issue;
}
};
/**
* Constructs a schema issue that points to a nested location.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Pointer = class extends IssueNodeImpl {
_tag = "Pointer";
/**
* The path to the location in the input that caused the issue.
*/
path;
/**
* The issue that occurred.
*/
issue;
constructor(path, issue) {
super();
this.path = path;
this.issue = issue;
}
};
/**
* Constructs a schema issue for a missing key or tuple index.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const MissingKey = class extends IssueNodeImpl {
_tag = "MissingKey";
/**
* The metadata for the issue.
*/
annotations;
constructor(annotations) {
super();
this.annotations = annotations;
}
};
/**
* Constructs a schema issue for an unexpected key or tuple index.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const UnexpectedKey = class extends IssueNodeImpl {
_tag = "UnexpectedKey";
/**
* The schema that caused the issue.
*/
ast;
constructor(ast, input, options) {
super(input, options);
this.ast = ast;
}
};
/**
* Constructs a schema issue that groups multiple child issues.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Composite = class extends IssueNodeImpl {
_tag = "Composite";
/**
* The schema that caused the issue.
*/
ast;
/**
* The issues that occurred.
*/
issues;
constructor(ast, issues, input, options) {
super(input, options);
this.ast = ast;
this.issues = issues;
}
};
/**
* Constructs a schema issue for an input with an invalid runtime type.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const InvalidType = class extends IssueNodeImpl {
_tag = "InvalidType";
/**
* The schema that caused the issue.
*/
ast;
constructor(ast, input, options) {
super(input, options);
this.ast = ast;
}
};
/**
* Constructs a schema issue for a value that violates a constraint.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const InvalidValue = class extends IssueNodeImpl {
_tag = "InvalidValue";
/**
* The metadata for the issue.
*/
annotations;
constructor(annotations, input, options) {
super(input, options);
this.annotations = annotations;
}
};
/**
* Constructs a schema issue for a value that matches no union member.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const AnyOf = class extends IssueNodeImpl {
_tag = "AnyOf";
/**
* The schema that caused the issue.
*/
ast;
/**
* The issues that occurred.
*/
issues;
constructor(ast, issues, input, options) {
super(input, options);
this.ast = ast;
this.issues = issues;
}
};
/**
* Constructs a schema issue for a value that matches multiple union members.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const OneOf = class extends IssueNodeImpl {
_tag = "OneOf";
/**
* The schema that caused the issue.
*/
ast;
/**
* The schemas that were successful.
*/
successes;
constructor(ast, successes, input, options) {
super(input, options);
this.ast = ast;
this.successes = successes;
}
};
function makeFilterIssue(entry, input, options) {
if (isIssue(entry)) return entry;
if (typeof entry === "string")
return new InvalidValue(
{ message: entry },
input,
options,
);
const inner =
typeof entry.issue === "string"
? new InvalidValue(
{ message: entry.issue },
input,
options,
)
: entry.issue;
return new Pointer(entry.path, inner);
}
/** @internal */
function makeSingle(out, input, options) {
if (out === void 0) return;
if (typeof out === "boolean")
return out
? void 0
: new InvalidValue(void 0, input, options);
return makeFilterIssue(out, input, options);
}
/** @internal */
function normalizeFilterOutput(ast, out, input, options) {
if (Array.isArray(out)) {
if (!isReadonlyArrayNonEmpty(out)) return;
return out.length === 1
? makeFilterIssue(out[0], input, options)
: new Composite(
ast,
map$2(out, (entry) =>
makeFilterIssue(entry, input, options),
),
input,
options,
);
}
return makeSingle(out, input, options);
}
/**
* Returns the built-in {@link LeafHook} used by default formatters.
*
* **When to use**
*
* Use as the default leaf renderer when customizing only the {@link CheckHook}.
*
* **Details**
*
* - Checks for a `message` annotation first; returns it if present.
* - For `InvalidValue`, an `expected` annotation uses the standard expected
* value message and includes reported input when available.
* - Otherwise generates a default message per `_tag`. When the issue reports
* input, the message includes its formatted value where applicable:
* - `InvalidType` → `"Expected <type>"` or `"Expected <type>, got <input>"`
* - `InvalidValue` → `"Expected a valid value"` or `"Invalid data <input>"`
* - `MissingKey` → `"Missing key"`
* - `UnexpectedKey` → `"Expected no excess property"` or
* `"Unexpected key with value <input>"`
* - `Forbidden` → `"Forbidden operation"`
* - `OneOf` → `"Expected exactly one member to match"` or
* `"Expected exactly one member to match the input <input>"`
*
* **Example** (Formatting Standard Schema issues with defaultLeafHook)
*
* ```ts import.meta.vitest
* import { SchemaIssue } from "effect"
*
* const formatter = SchemaIssue.makeFormatterStandardSchemaV1({
* leafHook: SchemaIssue.defaultLeafHook
* })
* formatter(new SchemaIssue.MissingKey(undefined)) // => { issues: [{ path: [], message: "Missing key" }] }
* ```
*
* @see {@link LeafHook}
* @see {@link makeFormatterStandardSchemaV1}
*
* @stability stable
* @category formatting
* @since 4.0.0
*/
const defaultLeafHook = (issue) => {
const message = findMessage(issue);
if (message !== void 0) return message;
switch (issue._tag) {
case "InvalidType":
return getExpectedMessage(
getExpected(issue.ast),
issue,
);
case "InvalidValue": {
const expected = findExpected(issue);
if (expected !== void 0)
return getExpectedMessage(expected, issue);
const input = formatInput(issue);
return input === void 0
? "Expected a valid value"
: `Invalid data ${input}`;
}
case "MissingKey":
return "Missing key";
case "UnexpectedKey": {
const input = formatInput(issue);
return input === void 0
? "Expected no excess property"
: `Unexpected key with value ${input}`;
}
case "Forbidden":
return "Forbidden operation";
case "OneOf": {
const input = formatInput(issue);
return input === void 0
? "Expected exactly one member to match"
: `Expected exactly one member to match the input ${input}`;
}
}
};
/**
* Returns the built-in {@link CheckHook} used by default formatters.
*
* **When to use**
*
* Use as the default filter renderer when customizing only the {@link LeafHook}.
*
* **Details**
*
* - Looks for a `message` annotation on the inner issue first, then on the
* filter itself.
* - Returns `undefined` when no annotation is found, causing the formatter to
* fall back to `"Expected <filter>"` or, when the filter reports input,
* `"Expected <filter>, got <input>"`.
*
* @see {@link CheckHook}
* @see {@link makeFormatterStandardSchemaV1}
*
* @stability stable
* @category formatting
* @since 4.0.0
*/
const defaultCheckHook = (issue) =>
findMessage(issue.issue) ?? findMessage(issue);
function formatInput(issue) {
return hasInput(issue) ? format$1(issue.input) : void 0;
}
function findExpected(issue) {
const expected = issue.annotations?.expected;
return typeof expected === "string" ? expected : void 0;
}
function getExpectedMessage(expected, issue) {
const input = formatInput(issue);
return input === void 0
? `Expected ${expected}`
: `Expected ${expected}, got ${input}`;
}
function formatCheck(check) {
const expected = check.annotations?.expected;
if (typeof expected === "string") return expected;
switch (check._tag) {
case "Filter":
return "<filter>";
case "FilterGroup":
return check.checks
.map((check) => formatCheck(check))
.join(" & ");
}
}
/**
* Creates a {@link Formatter} that converts an {@link Issue} into a
* human-readable multi-line string.
*
* **When to use**
*
* Use when you need to format a `SchemaIssue.Issue` as error messages for
* logging, CLI output, or developer-facing diagnostics.
*
* **Details**
*
* - Flattens the issue tree into `{ message, path }` entries using
* {@link defaultLeafHook} and {@link defaultCheckHook}.
* - Includes reported input in default messages when the node producing the
* message has an `input` field.
* - Each entry is rendered as `"<message>"` or `"<message>\n at <path>"`.
* - Multiple entries are joined with newlines.
*
* **Gotchas**
*
* Formatting an issue can disclose input retained with `reportInput: true`.
* Wrapper inputs are not inherited by child messages, and custom messages are
* returned unchanged.
*
* **Example** (Formatting an issue as a string)
*
* ```ts import.meta.vitest
* import { SchemaIssue } from "effect"
*
* const formatter = SchemaIssue.makeFormatterDefault()
* formatter(new SchemaIssue.MissingKey(undefined)) // => "Missing key"
* ```
*
* @see {@link makeFormatterStandardSchemaV1} — produces Standard Schema V1 format instead
* @see {@link Formatter}
*
* @stability stable
* @category formatting
* @since 4.0.0
*/
function makeFormatterDefault() {
return (issue) => formatIssue(issue, "");
}
/** @internal */
const defaultFormatter =
/*#__PURE__*/ makeFormatterDefault();
function formatIssue(issue, path) {
let message;
switch (issue._tag) {
case "Filter": {
const annotated = defaultCheckHook(issue);
if (annotated !== void 0) message = annotated;
else {
if (issue.issue._tag !== "InvalidValue")
return formatIssue(issue.issue, path);
const expected = findExpected(issue.issue);
message =
expected === void 0
? getExpectedMessage(
formatCheck(issue.filter),
issue,
)
: getExpectedMessage(expected, issue.issue);
}
break;
}
case "Encoding":
return formatIssue(issue.issue, path);
case "Pointer":
return formatIssue(
issue.issue,
path + formatPath(issue.path),
);
case "Composite":
case "AnyOf":
if (
issue._tag === "Composite" ||
issue.issues.length > 0
)
return issue.issues
.map((issue) => formatIssue(issue, path))
.join("\n");
message =
findMessage(issue) ??
getExpectedMessage(getExpected(issue.ast), issue);
break;
default:
message = defaultLeafHook(issue);
}
return path ? `${message}\n at ${path}` : message;
}
function findMessage(issue) {
if (issue._tag === "Pointer") return;
if (issue._tag === "Encoding")
return findMessage(issue.issue);
const message = (
issue._tag === "Filter"
? issue.filter.annotations
: "annotations" in issue
? issue.annotations
: issue.ast.annotations
)?.[
issue._tag === "MissingKey"
? "messageMissingKey"
: issue._tag === "UnexpectedKey"
? "messageUnexpectedKey"
: "message"
];
if (typeof message === "string") return message;
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/schema/cause.js
/** @internal */
function getSchemaIssue(cause) {
let issue;
for (const reason of cause.reasons) {
if (!isFailReason(reason) || !isIssue(reason.error))
return;
issue ??= reason.error;
}
return issue;
}
/** @internal */
function getSchemaIssueOrThrow(cause, message) {
const issue = getSchemaIssue(cause);
if (issue === void 0) throw new Error(message, { cause });
return issue;
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/SchemaGetter.js
const makeGetter = (fields) =>
Object.assign(Object.create(Prototype$1), fields);
const passthrough_$1 = /*#__PURE__*/ makeGetter({
_tag: "Passthrough",
});
function passthrough$1() {
return passthrough_$1;
}
/**
* Creates a getter that applies a pure function to present values.
*
* **When to use**
*
* Use when you need a schema getter for a pure, infallible transformation
* between types.
* - Building encode/decode pairs for `Schema.decodeTo`.
*
* **Details**
*
* - This is the most commonly used constructor.
* - Transforms `Some(e)` to `Some(f(e))` and leaves `None` unchanged.
* - Skips `None` inputs — only called when a value is present.
* - Never fails.
*
* **Example** (Transforming strings to numbers)
*
* ```ts import.meta.vitest
* import { Schema, SchemaGetter } from "effect"
*
* const NumberFromString = Schema.String.pipe(
* Schema.decodeTo(Schema.Number, {
* decode: SchemaGetter.transform((s) => Number(s)),
* encode: SchemaGetter.transform((n) => String(n))
* })
* )
* Schema.decodeSync(NumberFromString)("42") // => 42
* ```
*
* @see {@link transformEffect} when the transformation returns an `Effect`
* @see {@link transformOptional} when you need to handle `None` inputs
* @see {@link passthrough} when no transformation is needed
*
* @stability stable
* @category transforming
* @since 4.0.0
*/
function transform$1(f) {
return makeGetter({
_tag: "Transform",
transform: f,
});
}
/**
* Coerces any value to a `string` using the global `String()` constructor.
*
* **When to use**
*
* Use when you need a schema getter to coerce a present encoded value to a
* string with `String()`.
*
* **Details**
*
* The getter is pure, never fails, and delegates to `globalThis.String`.
*
* **Example** (Coercing to a string)
*
* ```ts import.meta.vitest
* import { Effect, Option, SchemaGetter } from "effect"
*
* const toString = SchemaGetter.String<number>()
* Effect.runSync(SchemaGetter.run(toString, Option.some(42), {})) // => Option.some("42")
* ```
*
* @see {@link transform} for custom string conversions
*
* @stability stable
* @category converting
* @since 4.0.0
*/
function String$3() {
return transform$1(globalThis.String);
}
/**
* Coerces any value to a `number` using the global `Number()` constructor.
*
* **When to use**
*
* Use when you need a schema getter to coerce a present encoded value to a
* number with `Number()`.
*
* **Details**
*
* The getter is pure, never fails, and delegates to `globalThis.Number`. It may
* produce `NaN` for non-numeric inputs.
*
* **Example** (Coercing to a number)
*
* ```ts import.meta.vitest
* import { Effect, Option, SchemaGetter } from "effect"
*
* const toNumber = SchemaGetter.Number<string>()
* Effect.runSync(SchemaGetter.run(toNumber, Option.some("42"), {})) // => Option.some(42)
* ```
*
* @see {@link transformEffect} for effectful or validated number parsing
*
* @stability stable
* @category converting
* @since 4.0.0
*/
function Number$3() {
return transform$1(globalThis.Number);
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/SchemaTransformation.js
/**
* Constructs schema middleware from its decode and encode functions.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Middleware = class extends Class$1 {
_tag = "Middleware";
decode;
encode;
constructor(decode, encode) {
super();
this.decode = decode;
this.encode = encode;
}
flip() {
return new Middleware(this.encode, this.decode);
}
};
const TypeId$4 =
"~effect/SchemaTransformation/Transformation";
/**
* Constructs a bidirectional schema transformation from its decode and encode getters.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Transformation = class extends Class$1 {
[TypeId$4] = TypeId$4;
_tag = "Transformation";
decode;
encode;
constructor(decode, encode) {
super();
this.decode = decode;
this.encode = encode;
}
flip() {
return new Transformation(this.encode, this.decode);
}
};
/**
* Returns `true` if `u` is a `Transformation` instance.
*
* **When to use**
*
* Use to check whether a value is already a schema transformation before
* wrapping it.
*
* **Details**
*
* - Pure predicate, no side effects.
* - Acts as a TypeScript type guard.
*
* **Example** (Checking a value)
*
* ```ts import.meta.vitest
* import { SchemaTransformation } from "effect"
*
* SchemaTransformation.isTransformation(SchemaTransformation.trim()) // => true
* SchemaTransformation.isTransformation({ decode: null, encode: null }) // => false
* ```
*
* @see {@link Transformation}
* @see {@link makeTransformation}
*
* @stability stable
* @category guards
* @since 4.0.0
*/
function isTransformation(u) {
return (
hasProperty(u, TypeId$4) && u[TypeId$4] === TypeId$4
);
}
/**
* Constructs a `Transformation` from an object with `decode` and `encode`
* `Getter`s. If the input is already a `Transformation`, returns it as-is.
*
* **When to use**
*
* Use when you already have schema getter instances and want to pair them into
* a schema transformation.
* - You want idempotent wrapping (won't double-wrap).
*
* **Details**
*
* - Returns the input unchanged if it is already a `Transformation`.
*
* **Example** (Wrapping existing getters)
*
* ```ts import.meta.vitest
* import { SchemaGetter, SchemaTransformation } from "effect"
*
* const t = SchemaTransformation.makeTransformation({
* decode: SchemaGetter.transform<number, string>((s) => Number(s)),
* encode: SchemaGetter.transform<string, number>((n) => String(n))
* })
* t._tag // => "Transformation"
* ```
*
* @see {@link transform} — simpler constructor from pure functions
* @see {@link transformEffect} — constructor from effectful functions
* @see {@link Transformation}
*
* @stability stable
* @category constructors
* @since 3.10.0
*/
const makeTransformation = (options) => {
if (isTransformation(options)) return options;
return new Transformation(options.decode, options.encode);
};
const passthrough_ = /*#__PURE__*/ new Transformation(
/*#__PURE__*/ passthrough$1(),
/*#__PURE__*/ passthrough$1(),
);
function passthrough() {
return passthrough_;
}
/**
* Decodes a `string` into a `number` and encodes a `number` back to a
* `string`.
*
* **When to use**
*
* Use when you need a schema transformation to parse numeric strings from APIs,
* form data, or URL parameters.
*
* **Details**
*
* Decoding coerces the string to a number like `Number(s)`. Encoding coerces
* the number to a string like `String(n)`. This does not validate that the
* result is finite; combine with `Schema.Finite` or `Schema.Int` for stricter
* checks.
*
* **Example** (Converting a string to a number)
*
* ```ts import.meta.vitest
* import { Schema, SchemaTransformation } from "effect"
*
* const schema = Schema.String.pipe(
* Schema.decodeTo(Schema.Number, SchemaTransformation.numberFromString)
* )
* Schema.decodeSync(schema)("42") // => 42
* ```
*
* @see {@link bigintFromString}
* @see {@link transform}
*
* @stability stable
* @category converting
* @since 4.0.0
*/
const numberFromString = /*#__PURE__*/ new Transformation(
/*#__PURE__*/ Number$3(),
/*#__PURE__*/ String$3(),
);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/SchemaAST.js
/**
* Represents Effect schemas as runtime trees.
*
* Every `Schema` has an AST made from nodes for declarations, primitives,
* literals, arrays, objects, unions, suspended schemas, checks, annotations,
* encoding links, and parsing context. Most users work with the higher-level
* `Schema` module. Use `SchemaAST` when you need to inspect schema nodes, build
* ASTs programmatically, change encoded or decoded views, collect issues, or
* run low-level schema checks.
*
* @stability stable
* @since 4.0.0
*/
function makeGuard(tag) {
return (ast) => ast._tag === tag;
}
/**
* Narrows an {@link AST} to {@link Declaration}.
*
* **When to use**
*
* Use to recognize declaration AST nodes before running declaration-specific
* handling.
*
* @see {@link Declaration} for the AST node type narrowed by this guard
*
* @stability stable
* @category guards
* @since 3.10.0
*/
const isDeclaration =
/*#__PURE__*/ makeGuard("Declaration");
/**
* Narrows an {@link AST} to {@link Never}.
*
* **When to use**
*
* Use to detect the AST node for a schema that can never match before handling
* other schema variants.
*
* @see {@link Never} for the AST node type narrowed by this guard
* @see {@link never} for the singleton `Never` AST instance
*
* @stability stable
* @category guards
* @since 4.0.0
*/
const isNever = /*#__PURE__*/ makeGuard("Never");
/**
* Narrows an {@link AST} to {@link Literal}.
*
* **When to use**
*
* Use to recognize exact string, number, boolean, or bigint literal AST nodes.
*
* @see {@link Literal} for the AST node type narrowed by this guard
* @see {@link LiteralValue} for the values stored by literal nodes
*
* @stability stable
* @category guards
* @since 3.10.0
*/
const isLiteral = /*#__PURE__*/ makeGuard("Literal");
/**
* Narrows an {@link AST} to {@link UniqueSymbol}.
*
* @stability stable
* @category guards
* @since 3.10.0
*/
const isUniqueSymbol =
/*#__PURE__*/ makeGuard("UniqueSymbol");
/**
* Narrows an {@link AST} to {@link Arrays}.
*
* **When to use**
*
* Use to recognize array-like AST nodes before reading their element, rest, or
* mutability metadata.
*
* @see {@link Arrays} for the AST node type narrowed by this guard
*
* @stability stable
* @category guards
* @since 4.0.0
*/
const isArrays = /*#__PURE__*/ makeGuard("Arrays");
/**
* Narrows an {@link AST} to {@link Objects}.
*
* @stability stable
* @category guards
* @since 4.0.0
*/
const isObjects = /*#__PURE__*/ makeGuard("Objects");
/**
* Narrows an {@link AST} to {@link Suspend}.
*
* @stability stable
* @category guards
* @since 3.10.0
*/
const isSuspend = /*#__PURE__*/ makeGuard("Suspend");
/**
* Constructs a {@link Link}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Link = class {
to;
transformation;
constructor(to, transformation) {
this.to = to;
this.transformation = transformation;
}
};
/** @internal */
const defaultParseOptions = {};
/**
* Constructs a {@link Context}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Context = class {
isOptional;
isMutable;
/** Used for constructor default values (e.g. `withConstructorDefault` API) */
constructorDefault;
annotations;
constructor(
isOptional,
isMutable,
constructorDefault = void 0,
annotations = void 0,
) {
this.isOptional = isOptional;
this.isMutable = isMutable;
this.constructorDefault = constructorDefault;
this.annotations = annotations;
}
};
const TypeId$3 = "~effect/Schema";
var ASTNodeImpl = class {
[TypeId$3] = TypeId$3;
annotations;
checks;
encoding;
context;
constructor(
annotations = void 0,
checks = void 0,
encoding = void 0,
context = void 0,
) {
this.annotations = annotations;
this.checks = checks;
this.encoding = encoding;
this.context = context;
}
toString() {
return `<${this._tag}>`;
}
};
/**
* Constructs a {@link Declaration}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Declaration = class extends ASTNodeImpl {
_tag = "Declaration";
typeParameters;
run;
encodingChecks;
/**
* Parser factory {@link flip} swaps in, so a declaration can behave
* differently when encoding. `undefined` reuses `run`.
*/
encodingRun;
constructor(
typeParameters,
run,
annotations,
checks,
encoding,
context,
encodingChecks,
encodingRun,
) {
super(annotations, checks, encoding, context);
this.typeParameters = typeParameters;
this.run = run;
this.encodingChecks = encodingChecks;
this.encodingRun = encodingRun;
}
/** @internal */
getParser() {
let run;
return (input, options) => {
if (input === missing) return missingExit;
return (run ??= this.run(this.typeParameters))(
input,
this,
options,
);
};
}
_rebuild(
recur,
checks,
encodingChecks,
run,
encodingRun,
) {
const tps = mapOrSame(this.typeParameters, recur);
return tps === this.typeParameters &&
checks === this.checks &&
encodingChecks === this.encodingChecks &&
run === this.run &&
encodingRun === this.encodingRun
? this
: new Declaration(
tps,
run,
this.annotations,
checks,
void 0,
this.context,
encodingChecks,
encodingRun,
);
}
/** @internal */
recur(recur) {
return this._rebuild(
recur,
this.checks,
this.encodingChecks,
this.run,
this.encodingRun,
);
}
/** @internal */
flip(recur) {
return this._rebuild(
recur,
this.encodingChecks,
this.checks,
this.encodingRun ?? this.run,
this.run,
);
}
/** @internal */
getExpected() {
const expected = this.annotations?.expected;
if (typeof expected === "string") return expected;
return "<Declaration>";
}
};
/**
* Constructs a {@link Null}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Null$1 = class extends ASTNodeImpl {
_tag = "Null";
/** @internal */
getParser() {
return fromConst(this, null);
}
/** @internal */
getExpected() {
return "null";
}
};
const null_ = /*#__PURE__*/ new Null$1();
/**
* Constructs a {@link Unknown}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Unknown = class extends ASTNodeImpl {
_tag = "Unknown";
/** @internal */
getParser() {
return fromRefinement(this, isUnknown);
}
/** @internal */
getExpected() {
return "unknown";
}
};
/**
* Provides the singleton {@link Unknown} AST instance.
*
* **When to use**
*
* Use when you need the reusable AST singleton for a schema node that accepts
* every value while keeping parsed values opaque.
*
* @see {@link any} for the singleton that accepts every value as `any`
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const unknown = /*#__PURE__*/ new Unknown();
/**
* Constructs a {@link Literal}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Literal$1 = class extends ASTNodeImpl {
_tag = "Literal";
literal;
constructor(
literal,
annotations,
checks,
encoding,
context,
) {
super(annotations, checks, encoding, context);
if (
typeof literal === "number" &&
!globalThis.Number.isFinite(literal)
)
throw new Error(
`A numeric literal must be finite, got ${format$1(literal)}`,
);
this.literal = literal;
}
/** @internal */
getParser() {
return fromConst(this, this.literal);
}
/** @internal */
matchPart(s, _options) {
return s === globalThis.String(this.literal)
? this.literal
: void 0;
}
/** @internal */
toCodecJson() {
return typeof this.literal === "bigint"
? literalToString(this)
: this;
}
/** @internal */
toCodecStringTree() {
return typeof this.literal === "string"
? this
: literalToString(this);
}
/** @internal */
getExpected() {
return typeof this.literal === "string"
? JSON.stringify(this.literal)
: globalThis.String(this.literal);
}
};
function literalToString(ast) {
const literalAsString = globalThis.String(ast.literal);
return replaceEncoding(ast, [
new Link(
new Literal$1(literalAsString),
new Transformation(
transform$1(() => ast.literal),
transform$1(() => literalAsString),
),
),
]);
}
/**
* Constructs a {@link String}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const String$2 = class extends ASTNodeImpl {
_tag = "String";
/** @internal */
getParser() {
return fromRefinement(this, isString$1);
}
/** @internal */
matchPart(s, options) {
const checks = this.checks;
return checks &&
!options.disableChecks &&
collectIssues(checks, s, void 0, this, options)
? void 0
: s;
}
/** @internal */
getExpected() {
return "string";
}
};
/**
* Provides the singleton {@link String} AST instance.
*
* **When to use**
*
* Use as the shared `SchemaAST` node for unconstrained JavaScript strings.
*
* @see {@link String} for the AST node class
* @see {@link isString} for narrowing an AST to a string node
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const string = /*#__PURE__*/ new String$2();
/**
* Constructs a {@link Number}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Number$2 = class extends ASTNodeImpl {
_tag = "Number";
/** @internal */
getParser() {
return fromRefinement(this, isNumber);
}
/** @internal */
matchKey(s, options) {
return this._match(isStringNumberRegExp, s, options);
}
/** @internal */
matchPart(s, options) {
return this._match(isStringFiniteRegExp, s, options);
}
_match(regexp, s, options) {
if (!regexp.test(s)) return void 0;
const value = globalThis.Number(s);
if (options.disableChecks || !this.checks) return value;
return collectIssues(
this.checks,
value,
void 0,
this,
options,
)
? void 0
: value;
}
/** @internal */
toCodecJson() {
if (
this.checks &&
(hasCheck(this.checks, "effect/schema/isFinite") ||
hasCheck(this.checks, "effect/schema/isInt"))
)
return this;
return replaceEncoding(this, [numberToJson]);
}
/** @internal */
toCodecStringTree() {
if (this.toCodecJson() === this)
return replaceEncoding(this, [finiteToString]);
return replaceEncoding(this, [numberToString]);
}
/** @internal */
getExpected() {
return "number";
}
};
function hasCheck(checks, id) {
return checks.some(
(check) =>
check.annotations?.representation?.id === id ||
(check._tag === "FilterGroup" &&
hasCheck(check.checks, id)),
);
}
/**
* Provides the singleton {@link Number} AST instance.
*
* **When to use**
*
* Use when you need the canonical `SchemaAST` node for schemas that accept any
* JavaScript number value.
*
* @see {@link Number} for the AST node class and serialization behavior
* @see {@link Literal} for exact finite numeric literal AST nodes
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const number = /*#__PURE__*/ new Number$2();
/**
* Constructs a {@link Arrays}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Arrays = class extends ASTNodeImpl {
_tag = "Arrays";
isMutable;
elements;
rest;
encodingChecks;
constructor(
isMutable,
elements,
rest,
annotations,
checks,
encoding,
context,
encodingChecks,
) {
super(annotations, checks, encoding, context);
this.isMutable = isMutable;
this.elements = elements;
this.rest = rest;
this.encodingChecks = encodingChecks;
let hasOptional = false;
for (let i = 0; i < elements.length; i++)
if (isOptional(elements[i])) hasOptional = true;
else if (hasOptional)
throw new Error(
"A required element cannot follow an optional element. ts(1257)",
);
if (hasOptional && rest.length > 1)
throw new Error(
"A required element cannot follow an optional element. ts(1257)",
);
for (let i = 1; i < rest.length; i++)
if (isOptional(rest[i]))
throw new Error(
"An optional element cannot follow a rest element. ts(1266)",
);
}
/** @internal */
getParser(compile, compileField = compile) {
const ast = this;
let elements;
let rest;
const elementLen = ast.elements.length;
const tailLen = Math.max(0, ast.rest.length - 1);
function getParser(tailThreshold, index) {
if (index < elementLen) return elements[index];
else if (index >= tailThreshold)
return rest[index - tailThreshold + 1];
return rest[0];
}
const finish = (state) => {
const { input, len, options } = state;
if (ast.rest.length === 0 && len > elementLen)
for (let i = elementLen; i < len; i++) {
const unexpected = new UnexpectedKey(
ast,
input[i],
options,
);
const issue = new Pointer([i], unexpected);
if (options.errors === "all") {
if (state.issues) state.issues.push(issue);
else state.issues = [issue];
} else
return fail$1(
new Composite(ast, [issue], input, options),
);
}
if (state.issues)
return fail$1(
new Composite(ast, state.issues, input, options),
);
return succeed(state.output);
};
const parse = (input, options) => {
const len = input.length;
const state = {
ast,
getParser,
input,
len,
tailThreshold: Math.max(elementLen, len - tailLen),
output: new globalThis.Array(len),
issues: void 0,
options,
};
const end =
ast.rest.length === 0
? elementLen
: Math.max(len, elementLen + tailLen);
const concurrency =
options.concurrency === void 0
? 1
: resolveConcurrency(options.concurrency);
const eff =
concurrency === 1
? parseArray(state, input, 0, end)
: parseArrayConcurrent(state, input, {
concurrency,
end,
});
if (!eff) return finish(state);
if (effectIsExit(eff))
return flatMapEager(eff, () => finish(state));
let first = true;
return suspend(() => {
if (!first) return parse(input, options);
first = false;
return flatMap(eff, () => finish(state));
});
};
return (input, options) => {
if (input === missing) return missingExit;
try {
if (!Array.isArray(input))
return fail$1(
new InvalidType(ast, input, options),
);
if (!elements) {
elements = ast.elements.map((ast) => ({
ast,
parser: compileField(ast),
}));
rest = ast.rest.map((ast) => ({
ast,
parser: compileField(ast),
}));
}
return parse(input, options);
} catch (error) {
return die(error);
}
};
}
_rebuild(recur, checks, encodingChecks) {
const elements = mapOrSame(this.elements, recur);
const rest = mapOrSame(this.rest, recur);
return elements === this.elements &&
rest === this.rest &&
checks === this.checks &&
encodingChecks === this.encodingChecks
? this
: new Arrays(
this.isMutable,
elements,
rest,
this.annotations,
checks,
void 0,
this.context,
encodingChecks,
);
}
/** @internal */
recur(recur) {
return this._rebuild(
recur,
this.checks,
this.encodingChecks,
);
}
/** @internal */
flip(recur) {
return this._rebuild(
recur,
this.encodingChecks,
this.checks,
);
}
/** @internal */
getExpected() {
return "array";
}
};
/** @internal */
function stepArray(s, item, exit, i) {
if (exit._tag === "Failure")
return wrapPropertyKeyIssue(s, s.ast, i, exit);
const value = exit === sameExit ? item : exit[args];
if (value !== missing) s.output[i] = value;
else {
const p = s.getParser(s.tailThreshold, i);
if (isOptional(p.ast)) return;
const issue = new Pointer(
[i],
new MissingKey(p.ast.context?.annotations),
);
if (s.options.errors === "all") {
if (s.issues) s.issues.push(issue);
else s.issues = [issue];
} else
return fail$2(
new Composite(s.ast, [issue], s.input, s.options),
);
}
}
const parseArrayOptions = {
onItem(s, item, i) {
const value = i < s.len ? item : missing;
return s
.getParser(s.tailThreshold, i)
.parser(value, s.options);
},
step: stepArray,
};
/** @internal */
const parseArray = /*#__PURE__*/ iterateEager()(
parseArrayOptions,
);
const parseArrayConcurrent =
/*#__PURE__*/ iterateConcurrent()(parseArrayOptions);
const wrapPropertyKeyIssue = (s, ast, key, exit) => {
if (exit.cause.reasons.length === 0) return exit;
const issue = getSchemaIssue(exit.cause);
if (issue === void 0)
return failCause(
map(
exit.cause,
(issue) =>
new Composite(
ast,
[new Pointer([key], issue)],
s.input,
s.options,
),
),
);
const pointer = new Pointer([key], issue);
if (s.options.errors === "all") {
if (s.issues) s.issues.push(pointer);
else s.issues = [pointer];
} else
return fail$2(
new Composite(ast, [pointer], s.input, s.options),
);
};
/**
* floating point or integer, with optional exponent
* @internal
*/
const FINITE_PATTERN =
"[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?";
/**
* Returns the object keys that match the index signature parameter schema.
* @internal
*/
function getIndexSignatureKeys(
input,
parameter,
options = defaultParseOptions,
) {
let stringKeys;
let symbolKeys;
function go(parameter) {
switch (parameter._tag) {
case "String":
case "TemplateLiteral":
return (stringKeys ??= Object.keys(input)).filter(
(k) => parameter.matchPart(k, options) !== void 0,
);
case "Number":
return (stringKeys ??= Object.keys(input)).filter(
(k) => parameter.matchKey(k, options) !== void 0,
);
case "Symbol":
return (symbolKeys ??=
Object.getOwnPropertySymbols(input)).filter(
(k) =>
Object.prototype.propertyIsEnumerable.call(
input,
k,
) && parameter.matchKey(k, options) !== void 0,
);
case "Union":
return [...new Set(parameter.types.flatMap(go))];
default:
return [];
}
}
return go(parameterFromPropertyKey(toEncoded(parameter)));
}
/**
* Constructs a {@link PropertySignature}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const PropertySignature = class {
name;
type;
constructor(name, type) {
this.name = name;
this.type = type;
}
};
function isIndexSignatureParameterSide(ast) {
switch (ast._tag) {
case "String":
case "Number":
case "Symbol":
case "TemplateLiteral":
return true;
case "Union":
return ast.types.every(isIndexSignatureParameterSide);
default:
return false;
}
}
function isIndexSignatureParameterEncodedSide(ast) {
const encoded = getLastEncoding(ast);
switch (encoded._tag) {
case "String":
case "Number":
case "Symbol":
case "TemplateLiteral":
return true;
case "Union":
return encoded.types.every(
isIndexSignatureParameterEncodedSide,
);
default:
return false;
}
}
function isIndexSignatureParameter(ast) {
return (
isIndexSignatureParameterSide(ast) &&
isIndexSignatureParameterEncodedSide(ast)
);
}
/**
* Constructs a {@link IndexSignature}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const IndexSignature = class {
parameter;
type;
constructor(parameter, type) {
if (!isIndexSignatureParameter(parameter))
throw new Error(
`Invalid index signature parameter ${parameter._tag}`,
);
this.parameter = parameter;
this.type = type;
if (isOptional(type) && !containsUndefined(type))
throw new Error(
"Cannot use `Schema.optionalKey` with index signatures, use `Schema.optional` instead.",
);
}
};
/**
* Constructs a {@link Objects}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Objects = class extends ASTNodeImpl {
_tag = "Objects";
propertySignatures;
indexSignatures;
encodingChecks;
constructor(
propertySignatures,
indexSignatures,
annotations,
checks,
encoding,
context,
encodingChecks,
) {
super(annotations, checks, encoding, context);
this.propertySignatures = propertySignatures;
this.indexSignatures = indexSignatures;
this.encodingChecks = encodingChecks;
}
/** @internal */
getParser(compile, compileField = compile) {
const ast = this;
const hasProperties = ast.propertySignatures.length;
const indexCount = ast.indexSignatures.length;
if (!hasProperties && !indexCount)
return fromRefinement(ast, isNotNullish);
let properties;
let indexes;
const compileMembers = () => {
if (!properties) {
properties = ast.propertySignatures.map((ps) => ({
parser: compileField(ps.type),
name: ps.name,
type: ps.type,
}));
indexes = indexCount
? ast.indexSignatures.map((is) => ({
is,
parserKey: compile(
parameterFromPropertyKey(is.parameter),
),
parserValue: compileField(is.type),
}))
: void 0;
}
return properties;
};
const makeFallback = () => {
const expectedKeys = new Set(
ast.propertySignatures.map((ps) =>
typeof ps.name === "number"
? globalThis.String(ps.name)
: ps.name,
),
);
const finishIndex = (
s,
key,
k2,
inputValue,
exitValue,
) => {
if (exitValue._tag === "Failure")
return (
wrapPropertyKeyIssue(s, ast, key, exitValue) ??
void_
);
const value =
exitValue === sameExit
? inputValue
: exitValue[args];
if (k2 !== missing && value !== missing) {
if (
hasProperties &&
(expectedKeys.has(key) ||
expectedKeys.has(
typeof k2 === "number"
? globalThis.String(k2)
: k2,
))
)
return void_;
assignProperty(s.out, k2, value);
}
return void_;
};
const parseIndex = (s, key, index, exitKey) => {
if (!exitKey) {
const eff = index.parserKey(key, s.options);
if (!effectIsExit(eff))
return flatMap(exit(eff), (exit) =>
parseIndex(s, key, index, exit),
);
exitKey = eff;
}
if (exitKey._tag === "Failure")
return (
wrapPropertyKeyIssue(s, ast, key, exitKey) ??
void_
);
const k2 =
exitKey === sameExit ? key : exitKey[args];
const inputValue = s.input[key];
const result = index.parserValue(
inputValue,
s.options,
);
return effectIsExit(result)
? finishIndex(s, key, k2, inputValue, result)
: flatMap(exit(result), (exit) =>
finishIndex(s, key, k2, inputValue, exit),
);
};
const parseStringIndex = (s, key, index) => {
const inputValue = s.input[key];
const result = index.parserValue(
inputValue,
s.options,
);
return effectIsExit(result)
? finishIndex(s, key, key, inputValue, result)
: flatMap(exit(result), (exit) =>
finishIndex(s, key, key, inputValue, exit),
);
};
const parseIndexes = indexCount
? iterateConcurrent()({
onItem: (s, [key, index]) =>
index.is.parameter === string
? parseStringIndex(s, key, index)
: parseIndex(s, key, index),
step: (_s, _item, exit) =>
exit._tag === "Failure" ? exit : void 0,
})
: void 0;
return fnUntracedEager(function* (input, options) {
if (input === missing) return missing;
if (
!(
typeof input === "object" &&
input !== null &&
!Array.isArray(input)
)
)
return yield* fail$1(
new InvalidType(ast, input, options),
);
compileMembers();
const record = input;
const out = {};
const state = {
ast,
input: record,
out,
issues: void 0,
options,
};
const errorsAllOption = options.errors === "all";
const onExcessPropertyError =
options.onExcessProperty === "error";
const concurrency =
options.concurrency === void 0
? 1
: resolveConcurrency(options.concurrency);
const indexKeys =
indexCount && onExcessPropertyError
? ast.indexSignatures.map((index) =>
getIndexSignatureKeys(
record,
index.parameter,
options,
),
)
: void 0;
if (onExcessPropertyError) {
const coveredKeys = indexKeys
? new Set(expectedKeys)
: expectedKeys;
if (indexKeys)
for (const keys of indexKeys)
for (const key of keys) coveredKeys.add(key);
const inputKeys = Reflect.ownKeys(record);
for (let i = 0; i < inputKeys.length; i++) {
const key = inputKeys[i];
if (
!coveredKeys.has(key) &&
Object.prototype.propertyIsEnumerable.call(
record,
key,
)
) {
const unexpected = new UnexpectedKey(
ast,
record[key],
options,
);
const issue = new Pointer([key], unexpected);
if (errorsAllOption) {
if (state.issues) state.issues.push(issue);
else state.issues = [issue];
continue;
} else
return yield* fail$1(
new Composite(
ast,
[issue],
input,
options,
),
);
}
}
}
if (hasProperties) {
const eff =
concurrency === 1
? parseProperties(state, properties)
: parsePropertiesConcurrent(
state,
properties,
{ concurrency },
);
if (eff) yield* eff;
}
if (indexCount && concurrency === 1)
for (let i = 0; i < indexCount; i++) {
const index = indexes[i];
const parse =
index.is.parameter === string
? parseStringIndex
: parseIndex;
const keys =
indexKeys?.[i] ??
(index.is.parameter === string
? Object.keys(record)
: getIndexSignatureKeys(
record,
index.is.parameter,
options,
));
for (let j = 0; j < keys.length; j++) {
const eff = parse(state, keys[j], index);
if (!effectIsExit(eff)) yield* eff;
else if (eff._tag === "Failure")
return yield* eff;
}
}
else if (parseIndexes) {
const keyPairs = empty$1();
for (let i = 0; i < indexCount; i++) {
const index = indexes[i];
const keys =
indexKeys?.[i] ??
(index.is.parameter === string
? Object.keys(record)
: getIndexSignatureKeys(
record,
index.is.parameter,
options,
));
for (let j = 0; j < keys.length; j++)
keyPairs.push([keys[j], index]);
}
const eff = parseIndexes(state, keyPairs, {
concurrency,
});
if (eff) yield* eff;
}
if (state.issues)
return yield* fail$1(
new Composite(
ast,
state.issues,
input,
options,
),
);
return out;
});
};
if (indexCount) return makeFallback();
let fallback;
const resume = (state, index, pending) => {
const property = properties[index];
return flatMap(exit(pending), (exit) => {
const terminal = stepProperty(
state,
property,
exit,
);
if (terminal) return terminal;
const done = () => succeed(state.out);
const eff = parseProperties(
state,
properties.slice(index + 1),
);
return eff ? flatMapEager(eff, done) : done();
});
};
return (input, options) => {
if (input === missing) return missingExit;
if (
options.errors === "all" ||
options.onExcessProperty !== void 0 ||
(options.concurrency !== void 0 &&
resolveConcurrency(options.concurrency) !== 1)
)
return (fallback ??= makeFallback())(
input,
options,
);
if (
!(
typeof input === "object" &&
input !== null &&
!Array.isArray(input)
)
)
return fail$1(new InvalidType(ast, input, options));
const props = compileMembers();
const record = input;
const out = {};
const state = {
ast,
input: record,
out,
issues: void 0,
options,
};
try {
for (let index = 0; index < props.length; index++) {
const property = props[index];
const name = property.name;
const hasKey = hasPropertySignature(record, name);
const value = hasKey ? record[name] : missing;
const exit = property.parser(value, options);
if (!effectIsExit(exit))
return resume(state, index, exit);
if (exit === sameExit) {
if (hasKey) assignProperty(out, name, value);
continue;
}
const terminal = stepProperty(
state,
property,
exit,
);
if (terminal) return terminal;
}
} catch (error) {
return die(error);
}
return succeed(out);
};
}
_rebuild(recur, recurParameter, checks, encodingChecks) {
const props = mapOrSame(
this.propertySignatures,
(ps) => {
const t = recur(ps.type);
return t === ps.type
? ps
: new PropertySignature(ps.name, t);
},
);
const indexes = mapOrSame(
this.indexSignatures,
(is) => {
const p = recurParameter(is.parameter);
const t = recur(is.type);
return p === is.parameter && t === is.type
? is
: new IndexSignature(p, t);
},
);
return props === this.propertySignatures &&
indexes === this.indexSignatures &&
checks === this.checks &&
encodingChecks === this.encodingChecks
? this
: new Objects(
props,
indexes,
this.annotations,
checks,
void 0,
this.context,
encodingChecks,
);
}
/** @internal */
flip(recur) {
return this._rebuild(
recur,
recur,
this.encodingChecks,
this.checks,
);
}
/** @internal */
recur(recur, recurParameter = recur) {
return this._rebuild(
recur,
recurParameter,
this.checks,
this.encodingChecks,
);
}
/** @internal */
getExpected() {
if (
this.propertySignatures.length === 0 &&
this.indexSignatures.length === 0
)
return "object | array";
return "object";
}
};
/** @internal */
function stepProperty(s, p, exit) {
if (exit._tag === "Failure")
return wrapPropertyKeyIssue(s, s.ast, p.name, exit);
if (exit === sameExit) return;
const value = exit[args];
if (value !== missing) {
assignProperty(s.out, p.name, value);
return;
}
delete s.out[p.name];
if (!isOptional(p.type)) {
const issue = new Pointer(
[p.name],
new MissingKey(p.type.context?.annotations),
);
if (s.options.errors === "all") {
if (s.issues) s.issues.push(issue);
else s.issues = [issue];
return;
} else
return fail$2(
new Composite(s.ast, [issue], s.input, s.options),
);
}
}
const parsePropertiesOptions = {
onItem(s, p) {
if (!hasPropertySignature(s.input, p.name))
return p.parser(missing, s.options);
const value = s.input[p.name];
assignProperty(s.out, p.name, value);
return p.parser(value, s.options);
},
step: stepProperty,
};
/** @internal */
const parseProperties = /*#__PURE__*/ iterateEager()(
parsePropertiesOptions,
);
const parsePropertiesConcurrent =
/*#__PURE__*/ iterateConcurrent()(parsePropertiesOptions);
function combineChecks(a, b) {
if (!a) return b;
if (!b) return a;
return [...a, ...b];
}
/** @internal */
function struct(fields, checks, annotations) {
return new Objects(
Reflect.ownKeys(fields).map((key) => {
return new PropertySignature(key, fields[key].ast);
}),
[],
annotations,
checks,
);
}
/** @internal */
function getAST(self) {
return self.ast;
}
/** @internal */
function union(members, options, checks) {
return new Union$1(
members.map(getAST),
options,
void 0,
checks,
);
}
/** @internal */
function mutable$1(ast) {
if (ast.encoding)
throw new Error("mutable does not support encodings");
return new Arrays(
true,
ast.elements,
ast.rest,
ast.annotations,
ast.checks,
void 0,
ast.context,
ast.encodingChecks,
);
}
const toCandidate = /*#__PURE__*/ memoizeIdempotent(
(ast) => {
while (true) {
if (isSuspend(ast)) return unknown;
const encoding = ast.encoding;
if (!encoding)
return ast.recur?.(toCandidate, identity) ?? ast;
if (
encoding.some(
(link) =>
link.transformation._tag === "Middleware" &&
link.transformation.decode !== identity,
)
)
return unknown;
ast = encoding[encoding.length - 1].to;
}
},
);
function getCandidateTypes(ast) {
switch (ast._tag) {
case "Null":
return ["null"];
case "Undefined":
return ["undefined"];
case "String":
case "TemplateLiteral":
return ["string"];
case "Number":
return ["number"];
case "Boolean":
return ["boolean"];
case "Symbol":
case "UniqueSymbol":
return ["symbol"];
case "BigInt":
return ["bigint"];
case "Arrays":
return ["array"];
case "ObjectKeyword":
return ["object", "array", "function"];
case "Objects":
return ast.propertySignatures.length ||
ast.indexSignatures.length
? ["object"]
: [
"string",
"number",
"boolean",
"symbol",
"bigint",
"object",
"array",
"function",
];
case "Enum":
return Array.from(
new Set(ast.enums.map(([, v]) => typeof v)),
);
case "Literal":
return [typeof ast.literal];
case "Union":
return Array.from(
new Set(ast.types.flatMap(getCandidateTypes)),
);
default:
return [
"null",
"undefined",
"string",
"number",
"boolean",
"symbol",
"bigint",
"object",
"array",
"function",
];
}
}
/** @internal */
function collectSentinels(ast) {
switch (ast._tag) {
default:
return [];
case "Declaration": {
const s = ast.annotations?.[SENTINELS_ANNOTATION_KEY];
return Array.isArray(s) ? s : [];
}
case "Objects":
return ast.propertySignatures.flatMap((ps) => {
const type = ps.type;
if (!isOptional(type)) {
if (isLiteral(type))
return [
{
key: ps.name,
literal: type.literal,
},
];
if (isUniqueSymbol(type))
return [
{
key: ps.name,
literal: type.symbol,
},
];
}
return [];
});
case "Arrays":
return ast.elements.flatMap((e, i) => {
if (!isOptional(e)) {
if (isLiteral(e))
return [
{
key: i,
literal: e.literal,
},
];
if (isUniqueSymbol(e))
return [
{
key: i,
literal: e.symbol,
},
];
}
return [];
});
case "Union": {
if (ast.types.length === 0) return [];
const members = ast.types.map((type) =>
collectSentinels(toCandidate(type)),
);
return members[0].filter((s) =>
members.every((sentinels) =>
sentinels.some(
(o) =>
o.key === s.key && o.literal === s.literal,
),
),
);
}
case "Suspend":
return collectSentinels(ast.thunk());
}
}
const candidateIndexCache = /*#__PURE__*/ new WeakMap();
const emptyCandidates = /*#__PURE__*/ Object.freeze([]);
const getRuntimeType = (input) =>
input === null
? "null"
: Array.isArray(input)
? "array"
: typeof input;
const hasPropertySignature = (input, key) =>
key === "__proto__"
? Object.hasOwn(input, key)
: key in input;
/** @internal */
function getCandidateIndex(types) {
let index = candidateIndexCache.get(types);
if (index) return index;
let bySentinel;
let sentinelCandidateCount = 0;
let otherwise;
let literalCandidates;
let onlyLiterals = true;
const literalOf = [];
for (let i = 0; i < types.length; i++) {
const a = types[i];
const encoded = toCandidate(a);
if (isNever(encoded)) continue;
if (isLiteral(encoded) || isUniqueSymbol(encoded)) {
literalCandidates ??= /* @__PURE__ */ new Map();
const literal = isLiteral(encoded)
? encoded.literal
: encoded.symbol;
literalOf[i] = literal;
let arr = literalCandidates.get(literal);
if (!arr) literalCandidates.set(literal, (arr = []));
arr.push(i);
} else onlyLiterals = false;
const sentinels = collectSentinels(encoded);
if (sentinels.length) {
bySentinel ??= /* @__PURE__ */ new Map();
sentinelCandidateCount++;
for (const { key, literal } of sentinels) {
let entry = bySentinel.get(key);
if (!entry)
bySentinel.set(
key,
(entry = [
/* @__PURE__ */ new Map(),
/* @__PURE__ */ new Set(),
]),
);
entry[1].add(i);
let indexes = entry[0].get(literal);
if (!indexes)
entry[0].set(
literal,
(indexes = /* @__PURE__ */ new Set()),
);
indexes.add(i);
}
} else {
otherwise ??= {};
const candidateTypes = getCandidateTypes(encoded);
for (const t of candidateTypes)
(otherwise[t] ??= []).push(i);
}
}
const fallbacks = {};
const getFallback = (type) =>
(fallbacks[type] ??= Object.freeze(
otherwise?.[type] ?? emptyCandidates,
));
if (onlyLiterals && literalCandidates) {
literalCandidates.forEach(Object.freeze);
index = (input) =>
literalCandidates.get(input) ?? emptyCandidates;
} else if (bySentinel?.size === 1 && !otherwise) {
const [key, [byValue]] = bySentinel
.entries()
.next().value;
const candidates = /* @__PURE__ */ new Map();
for (const [literal, indexes] of byValue)
candidates.set(
literal,
Object.freeze(Array.from(indexes)),
);
const all = Object.freeze(types.map((_, i) => i));
index = (input, isConstructor) => {
if (isObjectKeyword(input)) {
const value = hasPropertySignature(input, key)
? input[key]
: void 0;
if (value !== void 0)
return candidates.get(value) ?? emptyCandidates;
if (isConstructor) return all;
}
return emptyCandidates;
};
} else if (bySentinel) {
let commonSentinel;
for (const entry of bySentinel)
if (
(!commonSentinel ||
entry[1][0].size > commonSentinel[1][0].size) &&
entry[1][1].size === sentinelCandidateCount
)
commonSentinel = entry;
index = (input, isConstructor) => {
const runtimeType = getRuntimeType(input);
if (!isObjectKeyword(input))
return getFallback(runtimeType);
const selected = new Set(otherwise?.[runtimeType]);
let directKey;
if (commonSentinel) {
const [key, [byValue]] = commonSentinel;
const hasKey = hasPropertySignature(input, key);
const value = hasKey ? input[key] : void 0;
if (
hasKey &&
(!isConstructor || value !== void 0)
) {
const match = byValue.get(value);
if (!match) return getFallback(runtimeType);
for (const i of match) selected.add(i);
directKey = key;
}
}
if (directKey === void 0)
for (const [key, [byValue, all]] of bySentinel) {
const hasKey = hasPropertySignature(input, key);
const value = hasKey ? input[key] : void 0;
if (
hasKey &&
(!isConstructor || value !== void 0)
) {
const match = byValue.get(value);
if (match)
for (const i of match) selected.add(i);
} else if (isConstructor)
for (const i of all) selected.add(i);
}
for (const [key, [byValue, all]] of bySentinel) {
if (key === directKey) continue;
const hasKey = hasPropertySignature(input, key);
const value = hasKey ? input[key] : void 0;
if (
hasKey &&
(!isConstructor || value !== void 0)
) {
const match = byValue.get(value);
for (const i of selected)
if (all.has(i) && !match?.has(i))
selected.delete(i);
}
}
return Array.from(selected).sort((a, b) => a - b);
};
} else
index = (input) => {
const fallback = getFallback(getRuntimeType(input));
return literalCandidates
? fallback.filter(
(i) =>
literalOf[i] === void 0 ||
literalOf[i] === input,
)
: fallback;
};
candidateIndexCache.set(types, index);
return index;
}
/**
* Constructs a {@link Union}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Union$1 = class extends ASTNodeImpl {
_tag = "Union";
types;
options;
encodingChecks;
constructor(
types,
options,
annotations,
checks,
encoding,
context,
encodingChecks,
) {
super(annotations, checks, encoding, context);
this.types = types;
this.options = options;
this.encodingChecks = encodingChecks;
}
/** @internal */
getParser(compile, compileField) {
const ast = this;
const isConstructor = compileField !== void 0;
const parsers = [];
const parser = (i) =>
(parsers[i] ??= compile(ast.types[i]));
let index;
return (input, options) => {
if (input === missing) return missingExit;
const candidates = (index ??= getCandidateIndex(
ast.types,
))(input, isConstructor);
if (candidates.length === 0)
return fail$1(new AnyOf(ast, [], input, options));
if (candidates.length === 1) {
const result = parser(candidates[0])(
input,
options,
);
if (result._tag === "Success") return result;
return effectIsExit(result)
? failSingleUnionCandidate(
ast,
result.cause,
input,
options,
)
: catchSingleUnionCandidate(
ast,
result,
input,
options,
);
}
return parseUnionCandidates(
ast,
parser,
candidates,
input,
options,
);
};
}
_rebuild(recur, checks, encodingChecks) {
const types = mapOrSame(this.types, recur);
return types === this.types &&
checks === this.checks &&
encodingChecks === this.encodingChecks
? this
: new Union$1(
types,
this.options,
this.annotations,
checks,
void 0,
this.context,
encodingChecks,
);
}
/** @internal */
recur(recur) {
return this._rebuild(
recur,
this.checks,
this.encodingChecks,
);
}
/** @internal */
flip(recur) {
return this._rebuild(
recur,
this.encodingChecks,
this.checks,
);
}
/** @internal */
matchPart(s, options) {
for (const type of this.types) {
const out = type.matchPart(s, options);
if (out !== void 0) return out;
}
}
/** @internal */
getExpected(getExpected) {
const expected = this.annotations?.expected;
if (typeof expected === "string") return expected;
if (this.types.length === 0) return "never";
const types = this.types.map((type) => {
const encoded = toEncoded(type);
switch (encoded._tag) {
case "Arrays": {
const literals =
encoded.elements.filter(isLiteral);
if (literals.length > 0)
return `${formatIsMutable(encoded.isMutable)}[ ${literals.map((e) => getExpected(e) + formatIsOptional(e.context?.isOptional)).join(", ")}, ... ]`;
break;
}
case "Objects": {
const literals =
encoded.propertySignatures.filter((ps) =>
isLiteral(ps.type),
);
if (literals.length > 0)
return `{ ${literals.map((ps) => `${formatIsMutable(ps.type.context?.isMutable)}${formatPropertyKey(ps.name)}${formatIsOptional(ps.type.context?.isOptional)}: ${getExpected(ps.type)}`).join(", ")}, ... }`;
break;
}
}
return getExpected(encoded);
});
return Array.from(new Set(types)).join(" | ");
}
};
function failSingleUnionCandidate(
ast,
cause,
input,
options,
) {
const issue = getSchemaIssue(cause);
if (!issue) return failCause(cause);
return fail$2(new AnyOf(ast, [issue], input, options));
}
function catchSingleUnionCandidate(
ast,
result,
input,
options,
) {
return catchCause(result, (cause) =>
failSingleUnionCandidate(ast, cause, input, options),
);
}
function parseUnionCandidates(
ast,
parser,
candidates,
input,
options,
) {
const state = {
ast,
parser,
input,
out: void 0,
successes: ast.options?.mode === "oneOf" ? [] : void 0,
issues: void 0,
options,
};
const eff = parseUnion(state, candidates);
if (!eff) {
if (state.out) return state.out;
return fail$1(
new AnyOf(ast, state.issues ?? [], input, options),
);
}
if (effectIsExit(eff)) return resumeUnion(eff, state);
let first = true;
return suspend(() => {
if (!first)
return parseUnionCandidates(
ast,
parser,
candidates,
input,
options,
);
first = false;
return resumeUnion(eff, state);
});
}
function resumeUnion(eff, state) {
return flatMapEager(eff, (_) => {
if (state.out === sameExit)
return succeed$1(state.input);
if (state.out) return state.out;
return fail$1(
new AnyOf(
state.ast,
state.issues ?? [],
state.input,
state.options,
),
);
});
}
const parseUnion = /*#__PURE__*/ iterateEager()({
onItem(s, i) {
return s.parser(i)(s.input, s.options);
},
step(s, i, exit) {
if (exit._tag === "Failure") {
const issue = getSchemaIssue(exit.cause);
if (issue === void 0) return exit;
if (s.issues) s.issues.push(issue);
else s.issues = [issue];
} else {
if (s.out && s.successes) {
s.successes.push(s.ast.types[i]);
return fail$2(
new OneOf(s.ast, s.successes, s.input, s.options),
);
}
s.out = exit;
if (s.successes) s.successes.push(s.ast.types[i]);
else return void_;
}
},
});
const nonFiniteLiterals = /*#__PURE__*/ new Union$1([
/*#__PURE__*/ new Literal$1("Infinity"),
/*#__PURE__*/ new Literal$1("-Infinity"),
/*#__PURE__*/ new Literal$1("NaN"),
]);
function formatIsMutable(isMutable) {
return isMutable ? "" : "readonly ";
}
function formatIsOptional(isOptional) {
return isOptional ? "?" : "";
}
/**
* Constructs a {@link Filter}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Filter = class extends Class$1 {
_tag = "Filter";
run;
annotations;
/**
* Whether the parsing process should be aborted after this check has failed.
*/
aborted;
constructor(run, annotations = void 0, aborted = false) {
super();
this.run = run;
this.annotations = annotations;
this.aborted = aborted;
}
annotate(annotations) {
return new Filter(
this.run,
{
...this.annotations,
...annotations,
},
this.aborted,
);
}
abort() {
return new Filter(this.run, this.annotations, true);
}
and(other, annotations) {
return new FilterGroup([this, other], annotations);
}
};
/**
* Constructs a {@link FilterGroup}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const FilterGroup = class extends Class$1 {
_tag = "FilterGroup";
checks;
annotations;
constructor(checks, annotations = void 0) {
super();
this.checks = checks;
this.annotations = annotations;
}
annotate(annotations) {
return new FilterGroup(this.checks, {
...this.annotations,
...annotations,
});
}
and(other, annotations) {
return new FilterGroup([this, other], annotations);
}
};
/** @internal */
function makeFilter$1(
filter,
annotations,
aborted = false,
) {
return new Filter(
(input, ast, options) =>
normalizeFilterOutput(
ast,
filter(input, ast, options),
input,
options,
),
annotations,
aborted,
);
}
/** @internal */
function isFinite(annotations) {
return makeFilter$1(
(n) => globalThis.Number.isFinite(n),
{
expected: "a finite number",
representation: {
id: "effect/schema/isFinite",
payload: null,
},
toJsonSchema: () => ({ type: "number" }),
toCode: () => ({ runtime: "Schema.isFinite()" }),
arbitraryConstraint: { number: "finite" },
...annotations,
},
);
}
const numberToJson = /*#__PURE__*/ new Link(
/*#__PURE__*/ new Union$1([
/* @__PURE__ */ appendChecks(number, [
/*#__PURE__*/ isFinite(),
]),
nonFiniteLiterals,
]),
/*#__PURE__*/ new Transformation(
/*#__PURE__*/ Number$3(),
/*#__PURE__*/ transform$1((n) =>
globalThis.Number.isFinite(n)
? n
: globalThis.String(n),
),
),
);
/**
* Creates a {@link Filter} that validates strings by running `RegExp.test`.
*
* **When to use**
*
* Use when string validation should be represented as a schema `Filter` backed
* by a regular expression.
*
* **Details**
*
* The filter can be used with `Schema.filter` or attached directly to a
* `String` AST node through checks. The regular expression is cloned and its
* `lastIndex` is reset before each test, so global and sticky expressions are
* deterministic and the provided regular expression is not mutated. The
* regular expression source is stored in annotations for serialization and
* arbitrary generation.
*
* **Gotchas**
*
* Arbitrary metadata preserves both `regExp.source` and `regExp.flags`.
* Implementations that cannot consume all flags may still use the source as a
* generation hint because the Schema filter validates every generated value.
* JSON Schema has no way to carry JavaScript regular-expression flags. Unless
* annotations provide `toJsonSchema`, the RegExp constraint is omitted from
* JSON Schema export.
*
* **Example** (Validating an email pattern)
*
* ```ts import.meta.vitest
* import { SchemaAST } from "effect"
*
* const emailFilter = SchemaAST.isPattern(/^[^@]+@[^@]+$/)
* emailFilter.run("alice@example.com", SchemaAST.string, {}) // => undefined
* emailFilter.run("invalid", SchemaAST.string, {})?._tag // => "InvalidValue"
* ```
*
* @see {@link Filter}
* @stability stable
* @category constructors
* @since 4.0.0
*/
function isPattern$1(regExp, annotations) {
const copy = new globalThis.RegExp(regExp);
const payload = {
source: copy.source,
flags: copy.flags,
};
return makeFilter$1(
(s) => {
copy.lastIndex = 0;
return copy.test(s);
},
{
expected: `a string matching the RegExp ${payload.source}`,
representation: {
id: "effect/schema/isPattern",
payload,
},
toJsonSchema: () => [{}, true],
arbitraryConstraint: { patterns: [payload] },
...annotations,
},
);
}
const bodyOwners = /*#__PURE__*/ new WeakMap();
function copy(ast, changes) {
const out = Object.assign(
Object.create(Object.getPrototypeOf(ast)),
ast,
changes,
);
if (
Reflect.ownKeys(changes).every(
(key) => key === "context" || key === "encoding",
)
)
bodyOwners.set(out, getContextOwner(ast));
return out;
}
/** @internal */
function getContextOwner(ast) {
const existing = bodyOwners.get(ast);
if (existing !== void 0) return existing;
if (ast.encoding === void 0) return ast;
const owner = Object.assign(
Object.create(Object.getPrototypeOf(ast)),
ast,
{ encoding: void 0 },
);
bodyOwners.set(ast, owner);
return owner;
}
/** @internal */
function replaceEncoding(ast, encoding) {
return ast.encoding === encoding
? ast
: copy(ast, { encoding });
}
/** @internal */
function replaceContext(ast, context) {
if (ast.context === context) return ast;
const owner = getContextOwner(ast);
if (
owner.context === context &&
owner.encoding === ast.encoding
)
return owner;
return copy(ast, { context });
}
/** @internal */
function getLastEncoding(ast) {
return ast.encoding
? getLastEncoding(
ast.encoding[ast.encoding.length - 1].to,
)
: ast;
}
/** @internal */
function annotate(ast, annotations) {
if (ast.checks) {
const last = ast.checks[ast.checks.length - 1];
return replaceChecks(
ast,
append(
ast.checks.slice(0, -1),
last.annotate(annotations),
),
);
}
return copy(ast, {
annotations: {
...ast.annotations,
...annotations,
},
});
}
/** @internal */
function replaceChecks(ast, checks) {
if (ast._tag === "Suspend" && checks)
throw new Error("Cannot add checks to Suspend");
if (ast.checks === checks) return ast;
return copy(ast, { checks });
}
/** @internal */
function appendChecks(ast, checks) {
return replaceChecks(
ast,
combineChecks(ast.checks, checks),
);
}
/** @internal */
function mapLink(link, f) {
const to = f(link.to);
return to === link.to
? link
: new Link(to, link.transformation);
}
function updateLastLink(encoding, f) {
const links = encoding;
const last = links[links.length - 1];
const out = mapLink(last, f);
return out === last
? encoding
: append(encoding.slice(0, encoding.length - 1), out);
}
/** @internal */
function applyToSelfOrLastLinkEncodingIdempotent(
f,
options,
) {
function out(ast) {
if (ast.encoding) {
const last = ast.encoding[ast.encoding.length - 1];
return options?.stopAt?.(last)
? ast
: replaceEncoding(
ast,
updateLastLink(ast.encoding, out),
);
}
return f(ast);
}
return memoizeIdempotent(out);
}
function appendTransformation(from, transformation, to) {
const link = new Link(from, transformation);
return replaceEncoding(
to,
to.encoding ? [...to.encoding, link] : [link],
);
}
function mapOrSame(as, f) {
let out;
for (let i = 0; i < as.length; i++) {
const a = as[i];
const fa = f(a);
if (out) out[i] = fa;
else if (fa !== a) {
out = new Array(as.length);
for (let j = 0; j < i; j++) out[j] = as[j];
out[i] = fa;
}
}
return out ?? as;
}
/** @internal */
function annotateKey(ast, annotations) {
return replaceContext(
ast,
ast.context
? new Context(
ast.context.isOptional,
ast.context.isMutable,
ast.context.constructorDefault,
{
...ast.context.annotations,
...annotations,
},
)
: new Context(false, false, void 0, annotations),
);
}
/**
* Attaches a `Transformation` to the `to` AST, making it decode from the
* `from` AST and encode back to it.
*
* **Details**
*
* This is the low-level primitive behind `Schema.decodeTo`. It appends a
* {@link Link} to the `to` node's encoding chain.
*
* - Returns a new AST with the same type as `to`.
*
* @see {@link Link}
* @see {@link Encoding}
* @see {@link flip}
* @stability stable
* @category transforming
* @since 4.0.0
*/
function decodeTo$1(from, to, transformation) {
return appendTransformation(from, transformation, to);
}
/**
* Returns `true` if the AST node represents an optional property.
*
* **Details**
*
* Checks `ast.context?.isOptional`. Defaults to `false` when no
* {@link Context} is set.
*
* @see `Schema.optionalKey`
* @see {@link Context}
* @stability stable
* @category predicates
* @since 4.0.0
*/
function isOptional(ast) {
return ast.context?.isOptional ?? false;
}
function isStructuralCheck(check) {
return (
check.annotations?.["~structural"] === true ||
(check._tag === "FilterGroup" &&
check.checks.every(isStructuralCheck))
);
}
function extractStructuralChecks(checks) {
function extract(check) {
if (isStructuralCheck(check)) return [check];
return check._tag === "FilterGroup"
? check.checks.flatMap(extract)
: [];
}
const out = checks.flatMap(extract);
return isArrayNonEmpty(out) ? out : void 0;
}
function canPreserveEncodingChecks(ast) {
let preserve = true;
function visit(child) {
preserve =
preserve && !child.encoding && !isSuspend(child);
if (preserve && "recur" in child) child.recur(visit);
return child;
}
if ("recur" in ast) ast.recur(visit);
return preserve;
}
/**
* Strips all encoding transformations from an AST, returning the decoded
* (type-level) representation.
*
* **Details**
*
* - Memoized: same input reference → same output reference.
* - Recursively walks into composite nodes ({@link Arrays}, {@link Objects},
* {@link Union}, {@link Suspend}).
*
* **Example** (Getting the type AST)
*
* ```ts import.meta.vitest
* import { Schema, SchemaAST } from "effect"
*
* const schema = Schema.NumberFromString
* const typeAst = SchemaAST.toType(schema.ast)
* typeAst._tag // => "Number"
* ```
*
* @see {@link toEncoded}
* @see {@link flip}
* @stability stable
* @category transforming
* @since 4.0.0
*/
const toType = /*#__PURE__*/ memoizeIdempotent((ast) => {
const owner = getContextOwner(ast);
if (owner !== ast) {
const type = toType(owner);
return type === owner && ast.encoding === void 0
? ast
: replaceContext(type, ast.context);
}
const type = "recur" in ast ? ast.recur(toType) : ast;
if ("encodingChecks" in type && type.encodingChecks) {
const checks = canPreserveEncodingChecks(ast)
? type.encodingChecks
: isArrays(type) ||
isObjects(type) ||
(isDeclaration(type) &&
type.typeParameters.length > 0)
? extractStructuralChecks(type.encodingChecks)
: void 0;
return copy(type, {
encodingChecks: void 0,
checks: combineChecks(type.checks, checks),
});
}
return type;
});
/**
* Returns the encoded (wire-format) AST by flipping and then stripping
* encodings.
*
* **Details**
*
* Equivalent to `toType(flip(ast))`. This gives you the AST that describes
* the shape of the serialized/encoded data.
*
* - Memoized: same input reference → same output reference.
*
* **Example** (Getting the encoded AST)
*
* ```ts import.meta.vitest
* import { Schema, SchemaAST } from "effect"
*
* const schema = Schema.NumberFromString
* const encodedAst = SchemaAST.toEncoded(schema.ast)
* encodedAst._tag // => "String"
* ```
*
* @see {@link toType}
* @see {@link flip}
* @stability stable
* @category transforming
* @since 4.0.0
*/
const toEncoded = /*#__PURE__*/ memoizeIdempotent((ast) => {
return toType(flip(ast));
});
function flipEncoding(ast, encoding) {
const links = encoding;
const len = links.length;
const last = links[len - 1];
const ls = [
new Link(
flip(replaceEncoding(ast, void 0)),
links[0].transformation.flip(),
),
];
for (let i = 1; i < len; i++)
ls.unshift(
new Link(
flip(links[i - 1].to),
links[i].transformation.flip(),
),
);
const to = flip(last.to);
if (to.encoding)
return replaceEncoding(to, [...to.encoding, ...ls]);
else return replaceEncoding(to, ls);
}
/**
* Swaps the decode and encode directions of an AST's {@link Encoding} chain.
*
* **Details**
*
* After flipping, what was decoding becomes encoding and vice versa. This is
* the core operation behind `Schema.encode` — encoding a value is decoding
* with a flipped SchemaAST.
*
* - Memoized: same input reference → same output reference.
* - Recursively walks composite nodes.
*
* @see {@link toType}
* @see {@link toEncoded}
* @stability stable
* @category transforming
* @since 4.0.0
*/
const flip = /*#__PURE__*/ memoize((ast) => {
if (ast.encoding) return flipEncoding(ast, ast.encoding);
const owner = getContextOwner(ast);
if (owner !== ast) {
const flipped = flip(owner);
return flipped === owner
? ast
: replaceContext(flipped, ast.context);
}
return "flip" in ast
? ast.flip(flip)
: "recur" in ast
? ast.recur(flip)
: ast;
});
/** @internal */
function containsUndefined(ast) {
switch (ast._tag) {
case "Undefined":
return true;
case "Union":
return ast.types.some(containsUndefined);
default:
return false;
}
}
function fromConst(ast, value) {
const succeed$6 = value === 0 ? sameExit : succeed(value);
return (input, options) => {
if (input === missing) return missingExit;
if (input === value) return succeed$6;
return fail$1(new InvalidType(ast, input, options));
};
}
function fromRefinement(ast, refinement) {
return (input, options) => {
if (input === missing) return missingExit;
if (refinement(input)) return sameExit;
return fail$1(new InvalidType(ast, input, options));
};
}
/** @internal */
const parameterFromPropertyKey =
/*#__PURE__*/ applyToSelfOrLastLinkEncodingIdempotent(
(ast) => {
switch (ast._tag) {
default:
return ast;
case "Number":
return ast.toCodecStringTree();
case "Union":
return ast.recur(parameterFromPropertyKey);
}
},
);
const isStringFiniteRegExp =
/*#__PURE__*/ new globalThis.RegExp(
`^${FINITE_PATTERN}$`,
);
const isStringNumberRegExp =
/*#__PURE__*/ new globalThis.RegExp(
`^(?:${FINITE_PATTERN}|Infinity|-Infinity|NaN)$`,
);
/** @internal */
function isStringFinite(annotations) {
return isPattern$1(isStringFiniteRegExp, {
expected: "a string representing a finite number",
representation: {
id: "effect/schema/isStringFinite",
payload: null,
},
toJsonSchema: () => ({
pattern: isStringFiniteRegExp.source,
}),
...annotations,
});
}
const finiteString = /*#__PURE__*/ appendChecks(string, [
/*#__PURE__*/ isStringFinite(),
]);
const finiteToString = /*#__PURE__*/ new Link(
finiteString,
numberFromString,
);
const numberToString = /*#__PURE__*/ new Link(
/*#__PURE__*/ new Union$1([
finiteString,
nonFiniteLiterals,
]),
numberFromString,
);
/** @internal */
function collectIssues(
checks,
value,
issues,
ast,
options,
) {
for (let i = 0; i < checks.length; i++) {
const check = checks[i];
if (check._tag === "FilterGroup") {
issues = collectIssues(
check.checks,
value,
issues,
ast,
options,
);
if (
issues &&
(options.errors !== "all" ||
issues[issues.length - 1].filter.aborted)
)
return issues;
} else {
const issue = check.run(value, ast, options);
if (issue) {
const filter = new Filter$1(
check,
issue,
value,
options,
);
if (issues) issues.push(filter);
else issues = [filter];
if (options.errors !== "all" || check.aborted)
return issues;
}
}
}
return issues;
}
/** @internal */
function getConstructorDescriptor(ast) {
if (!isDeclaration(ast)) return void 0;
const getDescriptor =
ast.annotations?.[CONSTRUCTOR_ANNOTATION_KEY];
return isFunction(getDescriptor)
? getDescriptor(ast.typeParameters)
: void 0;
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/schema/interpreter.js
const flatMapTransformation = (result, current, f) =>
result === sameExit
? f(current)
: flatMapEager(result, f);
function compileTransformation(transformation) {
if (transformation._tag === "Middleware")
return (result, current, options) => {
const transformed =
result === sameExit
? transformation.decode(
succeed(toOption(current)),
options,
)
: transformation.decode(
mapEager(result, toOption),
options,
);
return fromOptionalEffect(transformed);
};
const getter = transformation.decode;
switch (getter._tag) {
case "Passthrough":
return (result, current) =>
result === sameExit ? succeed(current) : result;
case "Transform": {
const transform = (value) =>
value === missing
? missingExit
: succeed(getter.transform(value));
return (result, current) =>
flatMapTransformation(result, current, transform);
}
case "TransformOptional": {
const transform = (value) =>
fromOptionExit(getter.transform(toOption(value)));
return (result, current) =>
flatMapTransformation(result, current, transform);
}
case "TransformEffect":
return (result, current, options) =>
flatMapTransformation(result, current, (value) =>
value === missing
? missingExit
: getter.transform(value, options),
);
case "TransformOptionalEffect":
return (result, current, options) =>
flatMapTransformation(result, current, (value) =>
fromOptionalEffect(
getter.transform(toOption(value), options),
),
);
}
}
const fromOptionalEffect = (effect) =>
flatMapEager(effect, fromOptionExit);
/** @internal */
const wrapEncoding = (ast, input, options, effect) =>
catchCause(effect, (cause) =>
failCauseSync(() =>
map(
cause,
(issue) => new Encoding(ast, issue, input, options),
),
),
);
function makeConstructorParser(descriptor, compile) {
const transform = compileTransformation(
descriptor.link.transformation,
);
let sourceParser;
return (input, options) => {
if (input === missing) return missingExit;
if (descriptor.isConstructed(input)) return sameExit;
const result = (sourceParser ??= compile(
descriptor.link.to,
))(input, options);
return transform(result, input, options);
};
}
function withDefault(ast, parser) {
const defaultValue = ast.context.constructorDefault;
return (input, options) => {
if (input !== missing && input !== void 0)
return parser(input, options);
const result = defaultValue;
if (effectIsExit(result) && result._tag === "Success") {
const local = parser(result[args], options);
return local === sameExit ? result : local;
}
return flatMapEager(
wrapEncoding(ast, input, options, result),
(value) => {
const local = parser(value, options);
return local === sameExit ? succeed(value) : local;
},
);
};
}
/** @internal */
function compileField(ast, compile) {
const parser = compile(ast);
return ast.context?.constructorDefault === void 0
? parser
: withDefault(ast, parser);
}
/** @internal */
function compile(
ast,
compile,
compileField,
base,
specialize,
) {
if (ast._tag === "Declaration")
for (const parameter of ast.typeParameters)
compile(parameter);
const descriptor = compileField
? getConstructorDescriptor(ast)
: void 0;
const parser = descriptor
? makeConstructorParser(descriptor, compile)
: (base ?? ast.getParser(compile, compileField));
const checks = ast.checks;
const links = ast.encoding;
const transformations = links?.map((link) =>
compileTransformation(link.transformation),
);
const encodingChecks = ast.encodingChecks;
if (!links && !checks && !encodingChecks) return parser;
let encodingParsers;
const parseChecks = (input, options) => {
let result = parser(input, options);
if (encodingChecks && !options.disableChecks) {
if (effectIsExit(result)) {
if (result._tag === "Success") {
const output =
result === sameExit ? input : result[args];
if (input !== missing && output !== missing) {
const issues = collectIssues(
encodingChecks,
input,
void 0,
ast,
options,
);
if (issues)
result = fail$1(
new Composite(ast, issues, input, options),
);
}
}
} else
result = flatMap(result, (value) => {
if (input !== missing && value !== missing) {
const issues = collectIssues(
encodingChecks,
input,
void 0,
ast,
options,
);
if (issues)
return fail$1(
new Composite(ast, issues, input, options),
);
}
return succeed$1(value);
});
}
if (checks && !options.disableChecks) {
if (effectIsExit(result)) {
if (result._tag === "Success") {
const value =
result === sameExit ? input : result[args];
if (value === missing) return result;
const issues = collectIssues(
checks,
value,
void 0,
ast,
options,
);
if (issues)
result = fail$1(
new Composite(ast, issues, value, options),
);
}
} else
result = flatMap(result, (value) => {
if (value !== missing) {
const issues = collectIssues(
checks,
value,
void 0,
ast,
options,
);
if (issues)
return fail$1(
new Composite(ast, issues, value, options),
);
}
return succeed$1(value);
});
}
return result;
};
const parseLocal =
specialize === void 0
? parseChecks
: specialize(parseChecks);
if (!links) return parseLocal;
return (input, options) => {
const parsers = (encodingParsers ??= links.map((link) =>
compile(link.to),
));
let current = input;
let result = parsers[parsers.length - 1](
input,
options,
);
for (let i = links.length - 1; i >= 0; i--) {
result = transformations[i](result, current, options);
if (i !== 0) {
const next = parsers[i - 1];
if (result._tag === "Success") {
current = result[args];
result = next(current, options);
} else
result = flatMapEager(result, (value) => {
const nextResult = next(value, options);
return nextResult === sameExit
? succeed(value)
: nextResult;
});
}
}
if (result._tag === "Success") {
const value = result[args];
const local = parseLocal(value, options);
return local === sameExit ? result : local;
}
result = wrapEncoding(ast, input, options, result);
return flatMapEager(result, (value) => {
const local = parseLocal(value, options);
return local === sameExit ? succeed(value) : local;
});
};
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/schema/compilerRegistry.js
/** @internal */
const invalid = /*#__PURE__*/ Symbol();
const cache = /*#__PURE__*/ new WeakMap();
const decodeChild = (ast) => resolve(ast).parser;
const makeChild = (ast) => resolve(ast).makeEffect;
const makeField = (ast) => compileField(ast, makeChild);
var InterpretedEntry = class {
ast;
constructor(ast) {
this.ast = ast;
}
get decodeEffect() {
return (this.cachedDecodeEffect ??= compile(
this.ast,
decodeChild,
));
}
get parser() {
return this.decodeEffect;
}
get makeEffect() {
return (this.cachedMakeEffect ??= compile(
this.ast,
makeChild,
makeField,
));
}
};
/** @internal */
function resolve(ast) {
const cached = cache.get(ast);
if (cached !== void 0) return cached;
const entry = new InterpretedEntry(ast);
cache.set(ast, entry);
return entry;
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/SchemaParser.js
/**
* Runs schemas against real values.
*
* Schema parsers construct values from schema input, check whether a value
* matches a schema, decode encoded input, and encode decoded values back to
* their external form. This module exposes those operations through several
* result styles, including `Effect`, `Promise`, `Exit`, `Option`, `Result`, and
* synchronous functions that throw. It also contains the lower-level runner that
* walks a schema AST and reports schema failures as `SchemaIssue.Issue` values.
*
* @stability stable
* @since 4.0.0
*/
/**
* Creates an effectful maker for the schema's decoded type side.
*
* **When to use**
*
* Use to construct decoded schema values in `Effect` while preserving
* construction failures as `SchemaIssue.Issue` values in the error channel.
*
* **Details**
*
* The returned function accepts constructor input, applies constructor defaults,
* runs type-side validation unless checks are disabled, and fails with a
* `SchemaIssue.Issue` when construction fails.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
function makeEffect(schema) {
const ast = schema.ast;
let parser;
return (input, options) => {
return (parser ??= runWithCompiler(
constructorCompiler,
toType(ast),
))(
input,
options?.disableChecks
? options?.parseOptions
? {
...options.parseOptions,
disableChecks: true,
}
: { disableChecks: true }
: options?.parseOptions,
);
};
}
/**
* Creates a synchronous maker that returns `Option.some` with the constructed
* value on success, or `Option.none` when construction fails with schema issues.
*
* **When to use**
*
* Use when you need to validate schema constructor input and only care whether
* construction succeeds, without exposing `SchemaIssue.Issue` details.
*
* **Gotchas**
*
* Only causes made entirely of schema issues are converted to `Option.none`.
* Causes that contain defects, interruptions, or asynchronous work at this
* synchronous boundary throw an `Error` whose cause is the underlying `Cause`.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
function makeOption(schema) {
const parser = makeEffect(schema);
return (input, options) => {
const exit = runSyncExit(parser(input, options));
if (isSuccess(exit)) return some(exit.value);
getSchemaIssueOrThrow(
exit.cause,
"Option adapter can only return none for schema issues",
);
return none();
};
}
/**
* Creates a synchronous maker for the schema's decoded type side.
*
* **When to use**
*
* Use to construct decoded schema values synchronously when invalid input
* should throw an `Error` whose cause is `SchemaIssue.Issue`.
*
* **Details**
*
* The returned function constructs a value from constructor input and throws an
* `Error` with the `SchemaIssue.Issue` in its `cause` when construction fails.
* Schema validation failures use the generic message `"Schema validation failed"`.
* Format the `cause` explicitly with `SchemaIssue.makeFormatterDefault()` when
* human-readable details are needed.
*
* **Gotchas**
*
* Causes that contain defects, interruptions, or asynchronous work at this
* synchronous boundary throw an `Error` whose cause is the underlying `Cause`,
* instead of being converted to a schema validation error.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
function make$2(schema) {
return makeConstructorSync(toType(schema.ast));
}
/**
* Creates an effectful decoder for `unknown` input.
*
* **When to use**
*
* Use when you need to decode untyped boundary input in an `Effect` whose
* failure channel is `SchemaIssue.Issue`, while preserving transformations
* and service requirements.
*
* **Details**
*
* The returned function succeeds with the schema's decoded `Type` or fails with a
* `SchemaIssue.Issue`. Decoding service requirements are preserved in the returned
* `Effect`. Parse options may be provided when creating the decoder and overridden
* when applying it.
*
* @see {@link decodeEffect} for input already typed as the schema's `Encoded` type
*
* @stability stable
* @category decoding
* @since 4.0.0
*/
function decodeUnknownEffect$1(schema, options) {
const parser = run(schema.ast);
return options === void 0
? parser
: (input, overrideOptions) =>
parser(
input,
mergeParseOptions(options, overrideOptions),
);
}
const mergeParseOptions = (options, overrideOptions) =>
overrideOptions
? {
...options,
...overrideOptions,
}
: options;
const getValue = (value) => {
if (value === missing) return fail$1(new InvalidValue());
return succeed$1(value);
};
/** @internal */
function run(ast) {
return runWithCompiler(normalCompiler, ast);
}
function parserResult(result, input) {
if (result === sameExit) return succeed$1(input);
if (!effectIsExit(result))
return flatMapEager(result, getValue);
return result["~effect/Effect/args"] === missing
? getValue(missing)
: result;
}
function runWithCompiler(compiler, ast) {
let parser;
return (input, options) => {
const result = (parser ??= compiler(ast))(
input,
options ?? defaultParseOptions,
);
if (result === sameExit) return succeed$1(input);
if (!effectIsExit(result))
return flatMapEager(result, getValue);
return result["~effect/Effect/args"] === missing
? getValue(missing)
: result;
};
}
function runSync(effect, message) {
const exit = runSyncExit(effect);
if (isSuccess(exit)) return exit.value;
const issue = getSchemaIssueOrThrow(exit.cause, message);
throw new Error("Schema validation failed", {
cause: issue,
});
}
function makeConstructorSync(ast) {
let entry;
let parser;
return (input, options) => {
entry ??= resolve(ast);
const parseOptions = options?.disableChecks
? options.parseOptions
? {
...options.parseOptions,
disableChecks: true,
}
: { disableChecks: true }
: (options?.parseOptions ?? defaultParseOptions);
const make = entry.make;
if (make !== void 0 && input !== missing) {
let output;
try {
output = make(input, parseOptions);
} catch (error) {
getSchemaIssueOrThrow(
die$1(error),
"Constructor adapter can only throw schema issues",
);
throw error;
}
if (output !== invalid && output !== missing)
return output;
}
return runSync(
parserResult(
(parser ??= entry.makeEffect)(input, parseOptions),
input,
),
"Constructor adapter can only throw schema issues",
);
};
}
const normalCompiler = (ast) => resolve(ast).parser;
const constructorCompiler = (ast) =>
resolve(ast).makeEffect;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/schema/make.js
/** @internal */
const TypeId$2 = "~effect/Schema/Schema";
const RebuildOptions = /*#__PURE__*/ Symbol();
const SchemaProto = {
[TypeId$2]: TypeId$2,
get make() {
const value = make$2(this);
Object.defineProperty(this, "make", {
value,
enumerable: true,
});
return value;
},
get makeEffect() {
const value = makeEffect(this);
Object.defineProperty(this, "makeEffect", {
value,
enumerable: true,
});
return value;
},
get makeOption() {
const value = makeOption(this);
Object.defineProperty(this, "makeOption", {
value,
enumerable: true,
});
return value;
},
pipe() {
return pipeArguments(this, arguments);
},
annotate(annotations) {
return this.rebuild(annotate(this.ast, annotations));
},
annotateKey(annotations) {
return this.rebuild(annotateKey(this.ast, annotations));
},
check(...checks) {
return this.rebuild(appendChecks(this.ast, checks));
},
rebuild(ast) {
return make$1(ast, this[RebuildOptions]);
},
};
/** @internal */
function make$1(ast, options) {
function Schema() {}
const self = Object.setPrototypeOf(Schema, SchemaProto);
if (
options &&
(Object.hasOwn(options, "name") ||
Object.hasOwn(options, "length") ||
Object.hasOwn(options, "__proto__"))
)
Object.defineProperties(
self,
Object.getOwnPropertyDescriptors({ ...options }),
);
else Object.assign(self, options);
self[RebuildOptions] = options;
self.ast = ast;
return self;
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Struct.js
/**
* Wraps a plain function as a {@link Lambda} value so it can be used with
* {@link map}, {@link mapPick}, and {@link mapOmit}.
*
* **When to use**
*
* Use to create a typed lambda for struct mapping APIs that need type-level
* input and output tracking.
*
* **Details**
*
* The type parameter `L` encodes both the input and output types at the type
* level, allowing the compiler to track how struct value types change. At
* runtime, the returned value is the same function; `lambda` only adjusts the
* type.
*
* **Example** (Wrapping values in arrays)
*
* ```ts import.meta.vitest
* import { pipe, Struct } from "effect"
*
* interface AsArray extends Struct.Lambda {
* <A>(self: A): Array<A>
* readonly "~lambda.out": Array<this["~lambda.in"]>
* }
*
* const asArray = Struct.lambda<AsArray>((a) => [a])
* const result = pipe({ x: 1, y: "hello" }, Struct.map(asArray))
* result // => { x: [1], y: ["hello"] }
* ```
*
* @see {@link Lambda} – the type-level interface
* @see {@link map} – apply a lambda to all struct values
* @stability stable
* @category constructors
* @since 4.0.0
*/
const lambda = (f) => f;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/schemaError.js
const SchemaErrorTypeId = "~effect/Schema/SchemaError";
function isSchemaError$1(u) {
return (
hasProperty(u, "~effect/Schema/SchemaError") &&
u["~effect/Schema/SchemaError"] ===
"~effect/Schema/SchemaError"
);
}
({ ...BaseProto });
({ ...BaseProto });
({ ...BaseProto });
({ ...BaseProto });
({ ...BaseProto });
({ ...BaseProto });
({ ...BaseProto });
({ ...BaseProto });
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Schema.js
/**
* Creates a schema for a **parametric** type (a generic container such as
* `Array<A>`, `Option<A>`, etc.) by accepting a list of type-parameter schemas
* and a decoder factory.
*
* **When to use**
*
* Use when you are defining a schema for a generic container whose validation
* depends on one or more type-parameter schemas.
*
* **Details**
*
* The outer call `declareConstructor<T, E, Iso>()` fixes the decoded type `T`,
* the encoded type `E`, and the optional iso type. The inner call receives:
* - `typeParameters` — the concrete schemas for each type variable
* - `run` — a factory that, given resolved codecs for each type parameter,
* returns a parsing function `(u, ast, options) => Effect<T, Issue>`
* - `annotations` — optional metadata
*
* @see {@link declare} for creating schemas for non-parametric types.
*
* **Example** (Schema for a parametric `Box<A>` type)
*
* ```ts import.meta.vitest
* import { Effect, Schema, SchemaIssue, SchemaParser } from "effect"
*
* interface Box<A> {
* readonly value: A
* }
*
* const isBox = (u: unknown): u is Box<unknown> =>
* typeof u === "object" && u !== null && "value" in u
*
* const Box = <A extends Schema.Constraint>(item: A) =>
* Schema.declareConstructor<Box<A["Type"]>, Box<A["Encoded"]>>()(
* [item],
* ([itemCodec]) =>
* (u, ast, options) => {
* if (!isBox(u)) {
* return Effect.fail(new SchemaIssue.InvalidType(ast, u, options))
* }
* return Effect.map(
* SchemaParser.decodeUnknownEffect(itemCodec)(u.value, options),
* (value) => ({ value })
* )
* }
* )
*
* const schema = Box(Schema.Number)
* Effect.runSync(Schema.decodeUnknownEffect(schema)({ value: 1 })) // => { value: 1 }
* ```
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
function declareConstructor() {
return (typeParameters, run, annotations) => {
return make(
new Declaration(
typeParameters.map(getAST),
(typeParameters) =>
run(typeParameters.map((ast) => make(ast))),
annotations,
),
);
};
}
/**
* Creates a schema for a **non-parametric** opaque type using a type-guard
* function. The schema accepts any unknown value and succeeds when `is` returns
* `true`, failing with an `InvalidType` issue otherwise.
*
* **When to use**
*
* Use when you are defining a schema for an opaque type with no type parameters
* and validation can be expressed as a type guard.
*
* **Example** (Defining a schema for a custom `UserId` branded type)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* type UserId = string & { readonly _tag: "UserId" }
*
* const isUserId = (u: unknown): u is UserId =>
* typeof u === "string" && u.startsWith("user_")
*
* const UserId = Schema.declare<UserId>(isUserId, {
* title: "UserId",
* description: "A user identifier starting with 'user_'"
* })
* Schema.decodeUnknownSync(UserId)("user_123") // => "user_123"
* ```
*
* @see {@link declareConstructor} for creating schemas for parametric types.
*
* @stability stable
* @category constructors
* @since 3.10.0
*/
function declare(is, annotations) {
return declareConstructor()(
[],
() => (input, ast, options) =>
is(input)
? succeed$1(input)
: fail$1(new InvalidType(ast, input, options)),
annotations,
);
}
/**
* Error thrown or returned when schema decoding or encoding fails.
*
* **Details**
*
* The `issue` field contains a structured {@link SchemaIssue.Issue} tree describing
* every validation failure, including the path to the problematic value and
* the expected type or constraint. The `message` field renders the issue tree
* with the default formatter.
*
* **Gotchas**
*
* Parsing with `reportInput: true` adds an enumerable `input` field to
* value-bearing issues. Built-in messages may include reported input, and
* custom annotations or messages are not sanitized.
*
* **Example** (Inspecting a SchemaError)
*
* ```ts import.meta.vitest
* import { Result, Schema } from "effect"
*
* const result = Schema.decodeUnknownResult(Schema.Number)("not a number")
* const message = Result.isFailure(result) ? result.failure.message : ""
* message // => "Expected number"
* ```
*
* @see {@link isSchemaError} for narrowing unknown values
* @stability stable
* @category errors
* @since 4.0.0
*/
var SchemaError = class extends /*#__PURE__*/ TaggedError(
"SchemaError",
) {
[SchemaErrorTypeId] = SchemaErrorTypeId;
constructor(issue) {
const stackTraceLimit = getStackTraceLimit();
setStackTraceLimit(0);
try {
super({ issue });
} finally {
setStackTraceLimit(stackTraceLimit);
}
}
get message() {
return defaultFormatter(this.issue);
}
toJSON() {
return {
_tag: this._tag,
message: this.message,
};
}
[NodeInspectSymbol]() {
return this.toJSON();
}
toString() {
return `SchemaError(${this.message})`;
}
};
/**
* Returns `true` if `u` is a {@link SchemaError}.
*
* **When to use**
*
* Use when you need to narrow an unknown value to `SchemaError`.
*
* **Example** (Narrowing Schema errors)
*
* ```ts import.meta.vitest
* import { Result, Schema } from "effect"
*
* const result = Result.try(() => Schema.decodeUnknownSync(Schema.Number)("oops"))
* const error: unknown = Result.isFailure(result) ? result.failure : undefined
* Schema.isSchemaError(error) // => true
* ```
*
* @stability stable
* @category guards
* @since 4.0.0
*/
function isSchemaError(u) {
return isSchemaError$1(u);
}
function fromIssueEffect(self) {
if (effectIsExit(self)) return fromIssueExit(self);
return catchCause(self, (cause) =>
failCauseSync(() =>
map(cause, (issue) => new SchemaError(issue)),
),
);
}
function fromIssueExit(exit) {
return isSuccess(exit)
? exit
: failCause(
map(exit.cause, (issue) => new SchemaError(issue)),
);
}
function getSchemaErrorOrThrow(cause, message) {
let schemaError;
for (const reason of cause.reasons) {
if (
!isFailReason(reason) ||
!isSchemaError(reason.error)
)
throw new globalThis.Error(message, { cause });
schemaError ??= reason.error;
}
if (schemaError === void 0)
throw new globalThis.Error(message, { cause });
return schemaError;
}
function runSchemaErrorSync(self) {
const exit = runSyncExit(self);
if (isSuccess(exit)) return exit.value;
throw getSchemaErrorOrThrow(
exit.cause,
"Sync adapter can only throw schema errors",
);
}
/**
* Decodes an `unknown` input against a schema, returning an `Effect` that
* succeeds with the decoded value or fails with a {@link SchemaError}.
*
* **When to use**
*
* Use when you need to decode unknown input in an `Effect` whose failure
* channel is `SchemaError`.
*
* **Details**
*
* Prefer {@link decodeEffect} when the input is already typed as the schema's
* `Encoded` type.
* Options may be provided either when creating the decoder or when applying it;
* application options override creation options.
*
* @see {@link SchemaParser.decodeUnknownEffect} for the adapter that fails with `SchemaIssue.Issue` directly
*
* @stability stable
* @category decoding
* @since 4.0.0
*/
function decodeUnknownEffect(schema, options) {
const parser = decodeUnknownEffect$1(schema, options);
return (input, options) => {
return fromIssueEffect(parser(input, options));
};
}
/**
* Decodes an `unknown` input against a schema synchronously, returning the
* decoded value or throwing a {@link SchemaError} for schema mismatches.
*
* **When to use**
*
* Use when you need to validate unknown data at a synchronous boundary and want
* schema mismatches to throw `SchemaError`.
*
* **Details**
*
* For input already typed as the schema's `Encoded` type use `decodeSync`.
* Only service-free schemas can be decoded synchronously. For alternatives that
* do not throw on schema mismatches, see `decodeUnknownOption`,
* `decodeUnknownExit`, or `decodeUnknownEffect`. Options may be provided either
* when creating the decoder or when applying it; application options override
* creation options.
*
* **Gotchas**
*
* Non-schema failures may throw a runtime failure instead of `SchemaError`.
*
* **Example** (Decoding with a transformation schema)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* const NumberFromString = Schema.NumberFromString
*
* Schema.decodeUnknownSync(NumberFromString)("42") // => 42
* ```
*
* @see {@link SchemaParser.decodeUnknownSync} for the adapter that throws an `Error` whose cause is `SchemaIssue.Issue`
*
* @stability stable
* @category decoding
* @since 4.0.0
*/
function decodeUnknownSync(schema, options) {
const parser = decodeUnknownEffect(schema, options);
return (input, options) => {
return runSchemaErrorSync(parser(input, options));
};
}
/**
* Creates a schema from an AST (Abstract Syntax Tree) node.
*
* **Details**
*
* This is the fundamental constructor for all schemas in the Effect Schema
* library. It takes an AST node and wraps it in a fully-typed schema that
* preserves all type information and provides the complete schema API.
*
* The `make` function is used internally to create all primitive schemas like
* `String`, `Number`, `Boolean`, etc., as well as more complex schemas. It's
* the bridge between the untyped AST representation and the strongly-typed
* schema.
*
* @stability stable
* @category constructors
* @since 3.10.0
*/
const make = make$1;
/**
* Creates a schema for a single literal value (string, number, bigint, boolean, or null).
*
* **Example** (Defining a string literal)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* const schema = Schema.Literal("hello")
* // Type: Schema.Literal<"hello">
* Schema.decodeSync(schema)("hello") // => "hello"
* ```
*
* @see {@link Literals} for a schema that represents a union of literals.
* @see {@link tag} for a schema that represents a literal value that can be
* used as a discriminator field in tagged unions and has a constructor default.
* @stability stable
* @category constructors
* @since 3.10.0
*/
function Literal(literal) {
const out = make(new Literal$1(literal), {
literal,
transform(to) {
return out.pipe(
decodeTo(Literal(to), {
decode: transform$1(() => to),
encode: transform$1(() => literal),
}),
);
},
});
return out;
}
/**
* Schema for the `null` literal. Validates that the input is strictly `null`.
*
* @see {@link NullOr} for a union with another schema.
* @stability stable
* @category schemas
* @since 3.10.0
*/
const Null = /*#__PURE__*/ make(null_);
/**
* Schema for `string` values. Validates that the input is `typeof` `"string"`.
*
* @stability stable
* @category schemas
* @since 4.0.0
*/
const String$1 = /*#__PURE__*/ make(string);
/**
* Schema for `number` values, including `NaN`, `Infinity`, and `-Infinity`.
*
* **Details**
*
* Default JSON serializer:
*
* - Finite numbers are serialized as numbers.
* - Non-finite values are serialized as strings (`"NaN"`, `"Infinity"`, `"-Infinity"`).
*
* @see {@link Finite} for a schema that excludes non-finite values.
* @stability stable
* @category schemas
* @since 4.0.0
*/
const Number$1 = /*#__PURE__*/ make(number);
function makeStruct(ast, fields) {
return make(ast, {
fields,
mapFields(f, options) {
const fields = f(this.fields);
return makeStruct(
struct(
fields,
options?.unsafePreserveChecks
? this.ast.checks
: void 0,
),
fields,
);
},
});
}
/**
* Defines a struct schema from a map of field schemas.
*
* **Details**
*
* Each field value is a schema. Use {@link optionalKey} or {@link optional} to
* mark fields as optional, and {@link mutableKey} to mark them as mutable.
*
* The resulting schema's `Type` is a readonly object type with the fields'
* decoded types. The `Encoded` form mirrors the field schemas' encoded types.
* Declared fields may be inherited and are copied to own properties in the
* output. The `__proto__` field is accepted only when it is an own property.
* Parsing does not guarantee that output keys retain their input order.
*
* **Example** (Defining a basic struct)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* const Person = Schema.Struct({
* name: Schema.String,
* age: Schema.Number,
* email: Schema.optionalKey(Schema.String)
* })
*
* // { readonly name: string; readonly age: number; readonly email?: string }
* type Person = typeof Person.Type
*
* Schema.decodeUnknownSync(Person)({ name: "Alice", age: 30 }) // => { name: "Alice", age: 30 }
* ```
*
* @stability stable
* @category constructors
* @since 3.10.0
*/
function Struct(fields) {
return makeStruct(struct(fields, void 0), fields);
}
/**
* @category constructors
* @since 4.0.0
*/
const ArraySchema = /*#__PURE__*/ lambda((schema) =>
make(new Arrays(false, [], [schema.ast]), {
value: schema,
}),
);
/**
* Makes an array or tuple schema mutable, removing the `readonly` modifier.
*
* **Gotchas**
*
* This combinator does not support an encoding attached to the array or tuple
* node and throws if one is present. Encodings on element schemas are
* supported.
*
* **Example** (Defining mutable arrays)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* const schema = Schema.mutable(Schema.Array(Schema.Number))
*
* // number[] (mutable)
* type T = typeof schema.Type
* const value: T = [1, 2]
* value.push(3)
* value // => [1, 2, 3]
* ```
*
* @stability stable
* @category transforming
* @since 3.10.0
*/
const mutable = /*#__PURE__*/ lambda((schema) =>
make(mutable$1(schema.ast), { schema }),
);
function makeUnion(ast, members) {
return make(ast, {
members,
mapMembers(f, options) {
const members = f(this.members);
return makeUnion(
union(
members,
this.ast.options,
options?.unsafePreserveChecks
? this.ast.checks
: void 0,
),
members,
);
},
});
}
/**
* Creates a union schema from an array of member schemas. Members are tested in
* order; the first match is returned.
*
* **Details**
*
* Optionally, specify `mode`:
* - `"anyOf"` (default) — matches if any member matches.
* - `"oneOf"` — matches if exactly one member matches.
*
* **Example** (Defining a string or number union)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* const schema = Schema.Union([Schema.String, Schema.Number])
*
* Schema.decodeUnknownSync(schema)("hello") // => "hello"
* Schema.decodeUnknownSync(schema)(42) // => 42
* ```
*
* @stability stable
* @category constructors
* @since 3.10.0
*/
function Union(members, options) {
return makeUnion(
union(members, options, void 0),
members,
);
}
/**
* Creates a union schema from an array of literal values.
*
* **Example** (Defining status codes)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* const schema = Schema.Literals(["active", "inactive", "pending"])
* Schema.decodeSync(schema)("active") // => "active"
* ```
*
* @see {@link Literal} for a schema that represents a single literal.
* @stability stable
* @category constructors
* @since 4.0.0
*/
function Literals(literals) {
const members = literals.map(Literal);
return make(union(members, void 0, void 0), {
literals,
members,
mapMembers(f) {
return Union(f(this.members));
},
pick(literals) {
return Literals(literals);
},
transform(to) {
return Union(
members.map((member, index) =>
member.transform(to[index]),
),
);
},
});
}
/**
* Creates a union schema of `S | null`.
*
* @stability stable
* @category constructors
* @since 3.10.0
*/
const NullOr = /*#__PURE__*/ lambda((self) =>
Union([self, Null]),
);
function decodeTo(to, transformation) {
return (from) => {
return make(
decodeTo$1(
from.ast,
to.ast,
transformation
? makeTransformation(transformation)
: passthrough(),
),
{
from,
to,
},
);
};
}
/**
* Creates a schema that validates values using `instanceof`.
* Decoding and encoding pass the value through unchanged.
*
* **Example** (Defining a schema for a built-in class)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* const DateSchema = Schema.instanceOf(Date)
*
* const decoded = Schema.decodeUnknownSync(DateSchema)(new Date("2024-01-01"))
* decoded.toISOString() // => "2024-01-01T00:00:00.000Z"
* ```
*
* @stability stable
* @category constructors
* @since 3.10.0
*/
function instanceOf(constructor, annotations) {
return declare(
(u) => u instanceof constructor,
annotations,
);
}
/**
* Creates a custom validation filter from a predicate function.
*
* **Details**
*
* The predicate receives the decoded input value, the schema AST, and parse
* options, and returns a `FilterOutput`. Non-success outputs are normalized into
* schema issues. The `annotations` parameter annotates the filter itself; with
* the default formatter, failures use `message` first, `expected` second, and
* `<filter>` when neither is provided.
*
* When `abort` is `true`, parsing stops after this filter fails instead of
* collecting later check failures.
*
* **Example** (Reporting failure at a nested path)
*
* ```ts import.meta.vitest
* import { Result, Schema } from "effect"
*
* const schema = Schema.Struct({ password: Schema.String, confirmPassword: Schema.String }).check(
* Schema.makeFilter((o) =>
* o.password === o.confirmPassword
* ? undefined
* : { path: ["password"], issue: "password and confirmPassword must match" }
* )
* )
*
* const result = Schema.decodeUnknownResult(schema)({ password: "123456", confirmPassword: "1234567" })
* if (Result.isFailure(result) && result.failure.issue._tag === "Filter" && result.failure.issue.issue._tag === "Pointer") {
* result.failure.issue.issue.path // => ["password"]
* }
* ```
*
* **Example** (Reporting multiple failures at once)
*
* ```ts import.meta.vitest
* import { Result, Schema } from "effect"
*
* const schema = Schema.Struct({ a: Schema.Finite, b: Schema.Finite, c: Schema.Finite }).check(
* Schema.makeFilter((o) => {
* const issues: Array<Schema.FilterIssue> = []
* if (o.a > 0) {
* if (o.b <= 0) issues.push({ path: ["b"], issue: "b must be greater than 0" })
* if (o.c <= 0) issues.push({ path: ["c"], issue: "c must be greater than 0" })
* }
* return issues
* })
* )
*
* const result = Schema.decodeUnknownResult(schema)({ a: 1, b: 0, c: 0 })
* if (Result.isFailure(result) && result.failure.issue._tag === "Filter" && result.failure.issue.issue._tag === "Composite") {
* result.failure.issue.issue.issues.map((issue) => issue._tag === "Pointer" ? issue.path : []) // => [["b"], ["c"]]
* }
* ```
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const makeFilter = makeFilter$1;
/**
* Creates a greater-than-or-equal-to (`>=`) check for any ordered type from an
* `Order.Order` instance.
*
* @stability stable
* @category validation
* @since 4.0.0
*/
function makeIsGreaterThanOrEqualTo(options) {
const gte = isGreaterThanOrEqualTo$1(options.order);
const formatter = options.formatter ?? format$1;
return (minimum, annotations) => {
return makeFilter((input) => gte(input, minimum), {
expected: `a value greater than or equal to ${formatter(minimum)}`,
arbitraryConstraint: {
order: options.order,
minimum,
},
...options.annotate?.(minimum),
...annotations,
});
};
}
/**
* Creates a less-than-or-equal-to (`<=`) check for any ordered type from an
* `Order.Order` instance.
*
* @stability stable
* @category validation
* @since 4.0.0
*/
function makeIsLessThanOrEqualTo(options) {
const lte = isLessThanOrEqualTo$1(options.order);
const formatter = options.formatter ?? format$1;
return (maximum, annotations) => {
return makeFilter((input) => lte(input, maximum), {
expected: `a value less than or equal to ${formatter(maximum)}`,
arbitraryConstraint: {
order: options.order,
maximum,
},
...options.annotate?.(maximum),
...annotations,
});
};
}
function encodeNumberPayload(number) {
if (!globalThis.Number.isFinite(number))
throw new globalThis.RangeError(
`Expected a finite number, got ${format$1(number)}`,
);
return number;
}
/**
* Validates that a number is greater than or equal to the specified value
* (inclusive).
*
* **Details**
*
* JSON Schema:
*
* This check corresponds to the `minimum` constraint in JSON Schema.
*
* Arbitrary:
*
* During arbitrary generation, this applies a `minimum` constraint
* to ensure generated numbers are greater than or equal to the specified value.
*
* @stability stable
* @category validation
* @since 4.0.0
*/
const isGreaterThanOrEqualTo =
/*#__PURE__*/ makeIsGreaterThanOrEqualTo({
order: Number$4,
annotate: (minimum) => ({
representation: {
id: "effect/schema/isGreaterThanOrEqualTo",
payload: { minimum: encodeNumberPayload(minimum) },
},
toJsonSchema: () => ({ minimum }),
toCode: () => ({
runtime: `Schema.isGreaterThanOrEqualTo(${format$1(minimum)})`,
}),
}),
});
/**
* Validates that a number is less than or equal to the specified value
* (inclusive).
*
* **Details**
*
* JSON Schema:
*
* This check corresponds to the `maximum` constraint in JSON Schema.
*
* Arbitrary:
*
* During arbitrary generation, this applies a `maximum` constraint
* to ensure generated numbers are less than or equal to the specified value.
*
* @stability stable
* @category validation
* @since 4.0.0
*/
const isLessThanOrEqualTo =
/*#__PURE__*/ makeIsLessThanOrEqualTo({
order: Number$4,
annotate: (maximum) => ({
representation: {
id: "effect/schema/isLessThanOrEqualTo",
payload: { maximum: encodeNumberPayload(maximum) },
},
toJsonSchema: () => ({ maximum }),
toCode: () => ({
runtime: `Schema.isLessThanOrEqualTo(${format$1(maximum)})`,
}),
}),
});
/**
* Validates that a value has at least the specified length. Works with strings
* and arrays.
*
* **Details**
*
* JSON Schema:
*
* The bound must be finite; it is rounded down and clamped to zero. For arrays,
* this check corresponds to `minItems`. JavaScript counts UTF-16 code units
* while JSON Schema counts Unicode code points, so strings use
* `minLength: Math.ceil(minLength / 2)`, the tightest lower bound that cannot
* reject a string accepted by this check.
*
* Arbitrary:
*
* During arbitrary generation, this applies a `minLength`
* constraint to ensure generated strings or arrays have at least the required
* length.
*
* **Example** (Checking minimum length)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* const NonEmptyStringSchema = Schema.String.check(Schema.isMinLength(1))
* const NonEmptyArraySchema = Schema.Array(Schema.Number).check(Schema.isMinLength(1))
* Schema.is(NonEmptyStringSchema)("a") // => true
* Schema.is(NonEmptyArraySchema)([1]) // => true
* ```
*
* @stability stable
* @category validation
* @since 4.0.0
*/
function isMinLength(minLength, annotations) {
minLength = normalizeCardinality(minLength);
return makeIsMinLength(
minLength,
Math.ceil(minLength / 2),
annotations,
);
}
function makeIsMinLength(
minLength,
minCodePoints,
annotations,
) {
return makeFilter((input) => input.length >= minLength, {
expected: `a value with a length of at least ${minLength}`,
representation: {
id: "effect/schema/isMinLength",
payload: { minLength },
},
toJsonSchema: ({ type }) =>
type === "string"
? minLength <= 1
? { minLength: minCodePoints }
: [{ minLength: minCodePoints }, true]
: type === "array"
? { minItems: minLength }
: type === void 0
? [
{
minLength: minCodePoints,
minItems: minLength,
},
true,
]
: [{}, true],
toCode: () => ({
runtime: `Schema.isMinLength(${minLength})`,
}),
[STRUCTURAL_ANNOTATION_KEY]: true,
arbitraryConstraint: { minLength },
...annotations,
});
}
/**
* Validates that a value has at most the specified length. Works with strings
* and arrays.
*
* **Details**
*
* JSON Schema:
*
* The bound must be finite; it is rounded down and clamped to zero. This check
* corresponds to `maxItems` for arrays. Strings use the same bound for
* `maxLength`, which cannot reject a string accepted by this check because a
* string has no more code points than UTF-16 code units.
*
* Arbitrary:
*
* During arbitrary generation, this applies a `maxLength`
* constraint to ensure generated strings or arrays have at most the required
* length.
*
* @stability stable
* @category validation
* @since 4.0.0
*/
function isMaxLength(maxLength, annotations) {
maxLength = normalizeCardinality(maxLength);
return makeFilter((input) => input.length <= maxLength, {
expected: `a value with a length of at most ${maxLength}`,
representation: {
id: "effect/schema/isMaxLength",
payload: { maxLength },
},
toJsonSchema: ({ type }) =>
type === "string"
? maxLength === 0
? { maxLength }
: [{ maxLength }, true]
: type === "array"
? { maxItems: maxLength }
: type === void 0
? [
{
maxLength,
maxItems: maxLength,
},
true,
]
: [{}, true],
toCode: () => ({
runtime: `Schema.isMaxLength(${maxLength})`,
}),
[STRUCTURAL_ANNOTATION_KEY]: true,
arbitraryConstraint: { maxLength },
...annotations,
});
}
function normalizeCardinality(value) {
if (!globalThis.Number.isFinite(value))
throw new globalThis.RangeError(
`Expected a finite number, got ${value}`,
);
return Math.max(0, Math.floor(value));
}
globalThis.RegExp;
globalThis.URL;
globalThis.File;
globalThis.FormData;
globalThis.URLSearchParams;
globalThis.Uint8Array;
//#endregion
//#region ../schemas/libraries/effect/download/index.ts
const Image = Struct({
id: Number$1,
created: instanceOf(Date),
title: String$1.check(isMinLength(1), isMaxLength(100)),
type: Literals(["jpg", "png"]),
size: Number$1,
url: String$1.check(
makeFilter((value) => URL.canParse(value)),
),
});
const Rating = Struct({
id: Number$1,
stars: Number$1.check(
isGreaterThanOrEqualTo(1),
isLessThanOrEqualTo(5),
),
title: String$1.check(isMinLength(1), isMaxLength(100)),
text: String$1.check(isMinLength(1), isMaxLength(1e3)),
images: mutable(ArraySchema(Image)),
});
decodeUnknownSync(
Struct({
id: Number$1,
created: instanceOf(Date),
title: String$1.check(isMinLength(1), isMaxLength(100)),
brand: String$1.check(isMinLength(1), isMaxLength(30)),
description: String$1.check(
isMinLength(1),
isMaxLength(500),
),
price: Number$1.check(
isGreaterThanOrEqualTo(1),
isLessThanOrEqualTo(1e4),
),
discount: NullOr(
Number$1.check(
isGreaterThanOrEqualTo(1),
isLessThanOrEqualTo(100),
),
),
quantity: Number$1.check(
isGreaterThanOrEqualTo(0),
isLessThanOrEqualTo(10),
),
tags: mutable(
ArraySchema(
String$1.check(isMinLength(1), isMaxLength(30)),
),
),
images: mutable(ArraySchema(Image)),
ratings: mutable(ArraySchema(Rating)),
}),
)({});
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Pipeable.js
/**
* The `Pipeable` module defines the shared interface and implementation helpers
* for values that support Effect-style method chaining with `.pipe(...)`.
*
* A `Pipeable` value can pass itself through a sequence of unary functions from
* left to right, so code can be written as `value.pipe(f, g, h)` instead of
* deeply nesting calls. This is the method form used by many Effect data types
* to compose transformations, validations, and effectful operations while
* keeping the original value as the starting point of the pipeline.
*
* @stability stable
* @since 2.0.0
*/
/**
* Applies a `pipe` method's variadic arguments to an initial value from left
* to right.
*
* **When to use**
*
* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments`
* object.
*
* **Details**
*
* This helper is intended for implementing `Pipeable.pipe` methods that
* receive JavaScript's `arguments` object. With no functions it returns the
* original value; otherwise it feeds each result into the next function.
*
* **Example** (Implementing a pipe method)
*
* ```ts import.meta.vitest
* import { Pipeable } from "effect"
*
* class NumberBox {
* constructor(readonly value: number) {}
*
* pipe(..._fns: ReadonlyArray<(value: number) => number>): number {
* return Pipeable.pipeArguments(this.value, arguments) as number
* }
* }
*
* const result = new NumberBox(5).pipe(
* (n) => n + 2,
* (n) => n * 3
* )
* result // => 21
* ```
*
* @stability stable
* @category combinators
* @since 2.0.0
*/
const pipeArguments = (self, args) => {
switch (args.length) {
case 0:
return self;
case 1:
return args[0](self);
case 2:
return args[1](args[0](self));
case 3:
return args[2](args[1](args[0](self)));
case 4:
return args[3](args[2](args[1](args[0](self))));
case 5:
return args[4](args[3](args[2](args[1](args[0](self)))));
case 6:
return args[5](args[4](args[3](args[2](args[1](args[0](self))))));
case 7:
return args[6](
args[5](args[4](args[3](args[2](args[1](args[0](self)))))),
);
case 8:
return args[7](
args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))),
);
case 9:
return args[8](
args[7](
args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))),
),
);
default: {
let ret = self;
for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret);
return ret;
}
}
};
/**
* Reusable prototype that implements `Pipeable.pipe`.
*
* **When to use**
*
* Use when classes or object prototypes can reuse this value when they need the
* standard pipe implementation backed by `pipeArguments`.
*
* @stability stable
* @category prototypes
* @since 3.15.0
*/
const Prototype$1 = {
pipe() {
return pipeArguments(this, arguments);
},
};
/**
* Provides a base constructor whose instances implement the standard `Pipeable.pipe`
* method.
*
* **When to use**
*
* Use when you need to define a class that supports Effect-style method
* chaining through `.pipe(...)`.
*
* @stability stable
* @category constructors
* @since 3.15.0
*/
const Class$1 = /*#__PURE__*/ (function () {
function PipeableBase() {}
PipeableBase.prototype = Prototype$1;
return PipeableBase;
})();
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Function.js
/**
* Creates a function that can be called in data-first style or data-last
* (`pipe`-friendly) style.
*
* **When to use**
*
* Use to expose one implementation through both direct and `pipe`-friendly
* call styles.
*
* **Details**
*
* Pass either the arity of the uncurried function or a predicate that decides
* whether the current call is data-first. Arity is the common case. Use a
* predicate when optional arguments make arity ambiguous.
*
* **Example** (Selecting data-first or data-last style by arity)
*
* ```ts import.meta.vitest
* import { Function, pipe } from "effect"
*
* const sum = Function.dual<
* (that: number) => (self: number) => number,
* (self: number, that: number) => number
* >(2, (self, that) => self + that)
*
* sum(2, 3) // => 5
* pipe(2, sum(3)) // => 5
* ```
*
* **Example** (Defining overloads with call signatures)
*
* ```ts import.meta.vitest
* import { Function, pipe } from "effect"
*
* const sum: {
* (that: number): (self: number) => number
* (self: number, that: number): number
* } = Function.dual(2, (self: number, that: number): number => self + that)
*
* sum(2, 3) // => 5
* pipe(2, sum(3)) // => 5
* ```
*
* **Example** (Selecting data-first or data-last style with a predicate)
*
* ```ts import.meta.vitest
* import { Function, pipe } from "effect"
*
* const sum = Function.dual<
* (that: number) => (self: number) => number,
* (self: number, that: number) => number
* >(
* (args) => args.length === 2,
* (self, that) => self + that
* )
*
* sum(2, 3) // => 5
* pipe(2, sum(3)) // => 5
* ```
*
* @stability stable
* @category combinators
* @since 2.0.0
*/
const dual = function (arity, body) {
if (typeof arity === "function")
return function () {
return arity(arguments)
? body.apply(this, arguments)
: (self) => body(self, ...arguments);
};
switch (arity) {
case 0:
case 1:
throw new RangeError(`Invalid arity ${arity}`);
case 2:
return function (a, b) {
if (arguments.length >= 2) return body(a, b);
return function (self) {
return body(self, a);
};
};
case 3:
return function (a, b, c) {
if (arguments.length >= 3) return body(a, b, c);
return function (self) {
return body(self, a, b);
};
};
default:
return function () {
if (arguments.length >= arity) return body.apply(this, arguments);
const args = arguments;
return function (self) {
return body(self, ...args);
};
};
}
};
/**
* Returns its input argument unchanged.
*
* **When to use**
*
* Use to return a value unchanged where a function is required.
*
* **Example** (Returning the same value)
*
* ```ts import.meta.vitest
* import { identity } from "effect"
*
* identity(5) // => 5
* ```
*
* @stability stable
* @category combinators
* @since 2.0.0
*/
const identity = (a) => a;
/**
* Creates a zero-argument function that always returns the provided value.
*
* **When to use**
*
* Use when you need a thunk or callback that returns the same value on every
* invocation.
*
* **Example** (Creating a constant thunk)
*
* ```ts import.meta.vitest
* import { Function } from "effect"
*
* const constNull = Function.constant(null)
*
* constNull() // => null
* constNull() // => null
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const constant = (value) => () => value;
/**
* Returns `true` when called.
*
* **When to use**
*
* Use when you need a thunk that returns `true` on every invocation.
*
* **Example** (Returning true from a thunk)
*
* ```ts import.meta.vitest
* import { Function } from "effect"
*
* Function.constTrue() // => true
* ```
*
* @stability stable
* @category constants
* @since 2.0.0
*/
const constTrue = /*#__PURE__*/ constant(true);
/**
* Returns `undefined` when called.
*
* **When to use**
*
* Use when you need a thunk that returns `undefined` on every invocation.
*
* **Example** (Returning undefined from a thunk)
*
* ```ts import.meta.vitest
* import { Function } from "effect"
*
* Function.constUndefined() // => undefined
* ```
*
* @stability stable
* @category constants
* @since 2.0.0
*/
const constUndefined = /*#__PURE__*/ constant(void 0);
/**
* Returns no meaningful value when called.
*
* **When to use**
*
* Use when you need a thunk that is called only for its effect and has no
* meaningful return value.
*
* **Example** (Returning void from a thunk)
*
* ```ts import.meta.vitest
* import { Function } from "effect"
*
* Function.constVoid() // => undefined
* ```
*
* @stability stable
* @category constants
* @since 2.0.0
*/
const constVoid = constUndefined;
/**
* Creates a memoized function whose input is an object, caching results by
* object identity.
*
* **When to use**
*
* Use to reuse the result of a synchronous computation whose output is stable
* for a given object reference.
*
* **Details**
*
* Each memoized wrapper owns a private `WeakMap` keyed by object identity.
*
* **Gotchas**
*
* `undefined` is reserved to represent a cache miss and is therefore not
* supported as a return value.
*
* Structurally equal objects do not share cache entries. If the same object is
* mutated after its first call, later calls still return the cached result for
* that reference.
*
* @stability stable
* @category caching
* @since 4.0.0
*/
function memoize(f) {
const cache = /* @__PURE__ */ new WeakMap();
return (a) => {
const cached = cache.get(a);
if (cached !== void 0) return cached;
const result = f(a);
cache.set(a, result);
return result;
};
}
/**
* Creates a memoized idempotent object transformation that caches both inputs
* and their outputs by object identity.
*
* **When to use**
*
* Use when an object transformation is idempotent and its output can be safely
* reused as a fixed point.
*
* **Details**
*
* After computing an input, the returned function caches both the input and
* the output. Calling it with either reference returns the output without
* invoking the supplied function again.
*
* **Gotchas**
*
* The returned function treats each computed output as a fixed point. If
* applying the supplied function to an output would produce an observably
* different value, this memoization changes that behavior.
*
* @see {@link memoize} for memoizing functions without an idempotence requirement
* @stability stable
* @category caching
* @since 4.0.0
*/
function memoizeIdempotent(f) {
const cache = /* @__PURE__ */ new WeakMap();
return (a) => {
const cached = cache.get(a);
if (cached !== void 0) return cached;
const result = f(a);
cache.set(a, result);
if (result !== a) cache.set(result, result);
return result;
};
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/equal.js
/** @internal */
const getAllObjectKeys = (obj) => {
const keys = new Set(Reflect.ownKeys(obj));
if (obj.constructor === Object) return keys;
if (obj instanceof Error) keys.delete("stack");
const proto = Object.getPrototypeOf(obj);
let current = proto;
while (current !== null && current !== Object.prototype) {
const ownKeys = Reflect.ownKeys(current);
for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]);
current = Object.getPrototypeOf(current);
}
if (
keys.has("constructor") &&
typeof obj.constructor === "function" &&
proto === obj.constructor.prototype
)
keys.delete("constructor");
return keys;
};
/** @internal */
const byReferenceInstances = /*#__PURE__*/ new WeakSet();
/** @internal */
const viewBytes = (view) =>
new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/hash.js
/**
* Back-edge count used to avoid caching entry-point-dependent hashes.
*
* @internal
*/
let backEdges = 0;
/** @internal */
const addBackEdge = () => {
backEdges++;
};
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Predicate.js
/**
* Defines runtime checks for values.
*
* A `Predicate<A>` returns `true` or `false` for an `A`. A
* `Refinement<A, B>` is a predicate that also narrows the TypeScript type when
* it succeeds. This module includes guards for common JavaScript values,
* property and tag checks, tuple and struct checks, boolean combinators, and
* helpers for composing predicates and refinements.
*
* @stability stable
* @since 2.0.0
*/
/**
* Checks whether a value is a `string`.
*
* **When to use**
*
* Use when you need a `Predicate` guard to narrow an `unknown` value to a
* string.
*
* **Details**
*
* Uses `typeof input === "string"`.
*
* **Example** (Guarding strings)
*
* ```ts import.meta.vitest
* import { Predicate } from "effect"
*
* const data: unknown = "hi"
*
* if (Predicate.isString(data)) {
* data.toUpperCase() // => "HI"
* }
* ```
*
* @see {@link isNumber}
* @see {@link isBoolean}
* @see {@link Refinement}
* @stability stable
* @category guards
* @since 2.0.0
*/
function isString$1(input) {
return typeof input === "string";
}
/**
* Checks whether a value is a `number`.
*
* **When to use**
*
* Use when you need a `Predicate` guard to narrow an `unknown` value to a
* number.
*
* **Details**
*
* Uses `typeof input === "number"` and does not exclude `NaN` or `Infinity`.
*
* **Example** (Guarding numbers)
*
* ```ts import.meta.vitest
* import { Predicate } from "effect"
*
* const data: unknown = 42
*
* if (Predicate.isNumber(data)) {
* data + 1 // => 43
* }
* ```
*
* @see {@link isBigInt}
* @see {@link isString}
* @stability stable
* @category guards
* @since 2.0.0
*/
function isNumber(input) {
return typeof input === "number";
}
/**
* Checks whether a value is a `function`.
*
* **When to use**
*
* Use when you need a `Predicate` guard to narrow an `unknown` value to a
* callable function.
*
* **Details**
*
* Uses `typeof input === "function"`.
*
* **Example** (Guarding functions)
*
* ```ts import.meta.vitest
* import { Predicate } from "effect"
*
* const data: unknown = () => 1
*
* if (Predicate.isFunction(data)) {
* data() // => 1
* }
* ```
*
* @see {@link isObjectKeyword}
* @stability stable
* @category guards
* @since 2.0.0
*/
function isFunction(input) {
return typeof input === "function";
}
/**
* Checks whether a value is not `null` and not `undefined`.
*
* **When to use**
*
* Use when you need a `Predicate` refinement that filters out nullish values
* but keeps other falsy ones.
*
* **Details**
*
* Uses `input != null`.
*
* **Example** (Filtering non-nullish values)
*
* ```ts import.meta.vitest
* import { Predicate } from "effect"
*
* const values = [0, null, "", undefined]
* const present = values.filter(Predicate.isNotNullish) // => [0, ""]
* ```
*
* @see {@link isNullish}
* @see {@link isNotNull}
* @see {@link isNotUndefined}
* @stability stable
* @category guards
* @since 4.0.0
*/
function isNotNullish(input) {
return input != null;
}
/**
* Type guard that always returns `true`.
*
* **When to use**
*
* Use when you need a `Predicate` that always accepts, e.g. as a placeholder.
*
* **Example** (Matching every value)
*
* ```ts import.meta.vitest
* import { Predicate } from "effect"
*
* Predicate.isUnknown(123) // => true
* ```
*
* @see {@link isNever}
* @stability stable
* @category guards
* @since 2.0.0
*/
function isUnknown(_) {
return true;
}
/**
* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions).
*
* **When to use**
*
* Use when you need a `Predicate` guard that accepts arrays and functions as
* well as objects.
*
* **Details**
*
* Returns `true` for arrays and functions, and `false` for `null`.
*
* **Example** (Checking object keywords)
*
* ```ts import.meta.vitest
* import { Predicate } from "effect"
*
* Predicate.isObjectKeyword(() => 1) // => true
* Predicate.isObjectKeyword(null) // => false
* ```
*
* @see {@link isObject}
* @see {@link isObjectOrArray}
* @stability stable
* @category guards
* @since 4.0.0
*/
function isObjectKeyword(input) {
return (typeof input === "object" && input !== null) || isFunction(input);
}
/**
* Checks whether a value has a given property key.
*
* **When to use**
*
* Use when you need a `Predicate` guard for property access on `unknown`
* values with a simple structural object check.
*
* **Details**
*
* Uses the `in` operator and `isObjectKeyword`. This does not check property
* value types.
*
* **Example** (Guarding object properties)
*
* ```ts import.meta.vitest
* import { Predicate } from "effect"
*
* const hasName = Predicate.hasProperty("name")
* const data: unknown = { name: "Ada" }
*
* if (hasName(data)) {
* data.name // => "Ada"
* }
* ```
*
* @see {@link isTagged}
* @see {@link isObjectKeyword}
* @stability stable
* @category guards
* @since 2.0.0
*/
const hasProperty = /*#__PURE__*/ dual(
2,
(self, property) => isObjectKeyword(self) && property in self,
);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Hash.js
/**
* Computes Effect hash values and defines the interface for objects that want
* to provide their own hash implementation. Hashes are small numeric
* fingerprints used by Effect data structures to bucket values quickly; they
* are not cryptographic digests and they are not proof that two values are
* equal. The module also includes helpers for primitive, structure, array, and
* reference-based hashes, plus functions for combining and optimizing numeric
* hash values.
*
* @stability stable
* @since 2.0.0
*/
/**
* Defines the unique identifier used to identify objects that implement the Hash interface.
*
* **When to use**
*
* Use as the computed property key for the method that supplies a custom hash
* value on a `Hash` implementor.
*
* @see {@link Hash} for the interface implemented with this symbol
* @see {@link isHash} for checking whether a value implements `Hash`
* @see {@link hash} for computing hash values
*
* @stability stable
* @category symbols
* @since 2.0.0
*/
const symbol$1 = "~effect/Hash";
/**
* Computes a hash value for any given value.
*
* **When to use**
*
* Use to compute an Effect hash for primitives, collections, and hashable
* objects.
*
* **Details**
*
* This function can hash primitives (numbers, strings, booleans, etc.) as well as
* objects, arrays, and other complex data structures. It automatically handles
* different types and provides a consistent hash value for equivalent inputs.
*
* **Gotchas**
*
* Objects being hashed must be treated as immutable after their first hash
* computation. Hash results are cached, so mutating an object after hashing will
* lead to stale cached values and broken hash-based operations. For mutable
* objects, implement a custom `Hash` interface that hashes the object reference
* rather than its content.
*
* **Example** (Hashing different values)
*
* ```ts import.meta.vitest
* import { Hash } from "effect"
*
* Hash.hash(42) === Hash.hash(42) // => true
* Hash.hash("hello") === Hash.hash("hello") // => true
* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true
* ```
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const hash = (self) => {
switch (typeof self) {
case "number":
return number$1(self);
case "bigint":
return string$1(self.toString(10));
case "string":
return string$1(self);
case "function":
case "object":
if (self === null) break;
else if (self instanceof Date) {
if (Number.isNaN(self.getTime())) return string$1("Invalid Date");
return string$1(self.toISOString());
} else if (self instanceof RegExp) return string$1(self.toString());
else {
if (byReferenceInstances.has(self)) return random(self);
const cached = hashCache.get(self);
if (cached !== void 0) return cached;
if (visitedObjects.has(self)) {
addBackEdge();
return string$1("[Circular]");
}
visitedObjects.add(self);
const seen = backEdges;
let h;
try {
if ("~effect/Hash" in self) h = self[symbol$1]();
else if (typeof self === "function") h = random(self);
else if (self instanceof DataView) h = array(viewBytes(self));
else if (Array.isArray(self) || ArrayBuffer.isView(self))
h = array(self);
else if (self instanceof Map) h = hashMap(self);
else if (self instanceof Set) h = hashSet(self);
else h = structure(self);
} finally {
visitedObjects.delete(self);
}
if (seen === backEdges) hashCache.set(self, h);
return h;
}
}
return optimize(mix(string$1(String(self))));
};
/**
* Generates a random hash value for an object and caches it.
*
* **When to use**
*
* Use to hash an object by reference identity instead of structural content.
*
* **Details**
*
* This function creates a random hash value for objects that don't have their own
* hash implementation. The hash value is cached using a WeakMap, so the same object
* will always return the same hash value during its lifetime.
*
* **Example** (Hashing objects by reference)
*
* ```ts import.meta.vitest
* import { Hash } from "effect"
*
* const obj1 = { a: 1 }
* const obj2 = { a: 1 }
*
* Hash.random(obj1) === Hash.random(obj1) // => true
*
* typeof Hash.random(obj2) // => "number"
* ```
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const random = (self) => {
if (!randomHashCache.has(self))
randomHashCache.set(self, optimize((Math.random() * 4294967296) | 0));
return randomHashCache.get(self);
};
const mix = (h) => {
h ^= h >>> 16;
h = Math.imul(h, 2246822507);
h ^= h >>> 13;
h = Math.imul(h, 3266489909);
return h ^ (h >>> 16);
};
/**
* Combines two hash values into a single hash value.
*
* **When to use**
*
* Use to build a hash for a composite value by folding together hash values for
* its parts.
*
* **Details**
*
* Supports direct and pipeable usage. Argument order affects the result.
*
* **Example** (Combining hash values)
*
* ```ts import.meta.vitest
* import { Hash, pipe } from "effect"
*
* const hash1 = Hash.hash("hello")
* const hash2 = Hash.hash("world")
*
* const combined = Hash.combine(hash2)(hash1)
* combined === pipe(hash1, Hash.combine(hash2)) // => true
* ```
*
* @see {@link hash} for computing hash values from arbitrary inputs
* @see {@link structureKeys} for hashing selected object fields without manual combination
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const combine = /*#__PURE__*/ dual(2, (self, b) =>
mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507)),
);
/**
* Applies bit manipulation techniques to optimize a hash value.
*
* **When to use**
*
* Use to improve the bit distribution of a raw numeric hash value.
*
* **Details**
*
* This function takes a hash value and applies bitwise operations to improve
* the distribution of hash values, reducing the likelihood of collisions.
*
* **Example** (Optimizing a hash value)
*
* ```ts import.meta.vitest
* import { Hash } from "effect"
*
* Hash.optimize(1234567890) // => 160826066
* ```
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const optimize = (n) => (n & 3221225471) | ((n >>> 1) & 1073741824);
const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8));
/**
* Computes a hash value for a number.
*
* **When to use**
*
* Use to hash a JavaScript number with Effect's numeric hash semantics.
*
* **Details**
*
* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits,
* with a canonical representation for `NaN`.
*
* **Example** (Hashing numbers)
*
* ```ts import.meta.vitest
* import { Hash } from "effect"
*
* Number.isInteger(Hash.number(42)) // => true
* Number.isInteger(Hash.number(3.14)) // => true
* Hash.number(NaN) === Hash.number(NaN) // => true
* Hash.number(Infinity) === Hash.number(Infinity) // => true
* Hash.number(100) === Hash.number(100) // => true
* ```
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const number$1 = (n) => {
const h = n | 0;
if (h === n) return optimize(h);
float64.setFloat64(0, n !== n ? NaN : n);
return optimize(combine(float64.getInt32(0), float64.getInt32(4)));
};
/**
* Computes a hash value for a string using the djb2 algorithm.
*
* **When to use**
*
* Use when you need a string field to contribute to a custom structural hash
* implementation.
*
* **Details**
*
* This function implements a variation of the djb2 hash algorithm, which is
* known for its good distribution properties and speed. It processes each
* character of the string to produce a consistent hash value.
*
* **Example** (Hashing strings)
*
* ```ts import.meta.vitest
* import { Hash } from "effect"
*
* Hash.string("hello") // => 181380007
* Hash.string("world") // => 164394279
* Hash.string("") // => 5381
* Hash.string("test") === Hash.string("test") // => true
* ```
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const string$1 = (str) => {
let h = 5381,
i = str.length;
while (i) h = (h * 33) ^ str.charCodeAt(--i);
return optimize(h);
};
/**
* Computes a hash value for an object using only the specified keys.
*
* **When to use**
*
* Use to hash an object by a selected set of property keys.
*
* **Details**
*
* This function allows you to hash an object by considering only specific keys,
* which is useful when you want to create a hash based on a subset of an object's
* properties.
*
* **Example** (Hashing selected object keys)
*
* ```ts import.meta.vitest
* import { Hash } from "effect"
*
* const person = { name: "John", age: 30, city: "New York" }
*
* const hash1 = Hash.structureKeys(person, ["name", "age"])
* const hash2 = Hash.structureKeys(person, ["name", "city"])
*
* hash1 // => -731887653
* hash2 // => 148523102
*
* const person2 = { name: "John", age: 30, city: "Boston" }
* const hash3 = Hash.structureKeys(person2, ["name", "age"])
* hash1 === hash3 // => true
* ```
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const structureKeys = (o, keys) => {
let h = 12289;
for (const key of keys) h ^= combine(hash(key), hash(o[key]));
return optimize(h);
};
/**
* Computes a structural hash for an object using Effect's object key collection.
*
* **When to use**
*
* Use to hash an object from all structural keys collected by Effect.
*
* **Details**
*
* The hash is based on the object's structural keys and their values, including
* symbol keys and relevant prototype keys for non-plain objects.
*
* **Example** (Hashing object structures)
*
* ```ts import.meta.vitest
* import { Hash } from "effect"
*
* const obj1 = { name: "John", age: 30 }
* const obj2 = { name: "Jane", age: 25 }
* const obj3 = { name: "John", age: 30 }
*
* Hash.structure(obj1) // => -731887653
* Hash.structure(obj2) // => -222100417
* Hash.structure(obj3) // => -731887653
* Hash.structure(obj1) === Hash.structure(obj3) // => true
* ```
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const structure = (o) => structureKeys(o, getAllObjectKeys(o));
const unordered = (seed, f) => (iter) => {
let h = seed;
for (const element of iter) h ^= f(element);
return optimize(h);
};
/**
* Computes a hash value for an iterable by hashing all of its elements.
*
* **When to use**
*
* Use to hash the values yielded by an iterable with Effect hash semantics.
*
* **Details**
*
* Folds element hashes with {@link combine}, so order and length affect the
* result.
*
* **Gotchas**
*
* A hash is not an equality proof. Distinct inputs can still share a hash.
*
* **Example** (Hashing arrays)
*
* ```ts import.meta.vitest
* import { Hash } from "effect"
*
* const arr1 = [1, 2, 3]
* const arr2 = [1, 2, 3]
* const arr3 = [3, 2, 1]
*
* Hash.array(arr1) === Hash.array(arr2) // => true
* Hash.array(arr1) === Hash.array(arr3) // => false
* ```
*
* @see {@link hash} for the general-purpose hash dispatcher
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const array = (arr) => {
let h = 6151;
for (const element of arr) h = combine(h, hash(element));
return optimize(h);
};
const hashMap = /*#__PURE__*/ unordered(
/*#__PURE__*/ string$1("Map"),
([k, v]) => combine(hash(k), hash(v)),
);
const setSeed = /*#__PURE__*/ string$1("Set");
const hashSet = /*#__PURE__*/ unordered(setSeed, (element) =>
combine(setSeed, hash(element)),
);
const randomHashCache = /*#__PURE__*/ new WeakMap();
const hashCache = /*#__PURE__*/ new WeakMap();
const visitedObjects = /*#__PURE__*/ new WeakSet();
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Equal.js
/**
* Defines the unique string identifier for the `Equal` interface.
*
* **When to use**
*
* Use when you implement custom equality and need the computed property key for
* the equality method.
*
* **Details**
*
* This is a pure constant with no allocation or side effects.
*
* **Example** (Implementing Equal on a class)
*
* ```ts import.meta.vitest
* import { Equal, Hash } from "effect"
*
* class UserId implements Equal.Equal {
* constructor(readonly id: string) {}
*
* [Equal.symbol](that: Equal.Equal): boolean {
* return that instanceof UserId && this.id === that.id
* }
*
* [Hash.symbol](): number {
* return Hash.string(this.id)
* }
* }
*
* Equal.equals(new UserId("1"), new UserId("1")) // => true
* Equal.equals(new UserId("1"), new UserId("2")) // => false
* ```
*
* @see {@link Equal} — the interface that uses this symbol
* @see {@link isEqual} — type guard for `Equal` implementors
* @stability stable
* @category symbols
* @since 2.0.0
*/
const symbol = "~effect/Equal";
function equals$1() {
if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]);
return compareBoth(arguments[0], arguments[1]);
}
function compareBoth(self, that) {
if (self === that) return true;
if (self == null || that == null) return false;
const selfType = typeof self;
if (selfType !== typeof that) return false;
if (selfType === "number" && self !== self && that !== that) return true;
if (selfType !== "object" && selfType !== "function") return false;
if (byReferenceInstances.has(self) || byReferenceInstances.has(that))
return false;
return compareObjects(self, that);
}
function compareObjects(self, that) {
const depth = pathLeft.length;
for (let i = depth; i-- > 0;)
if (pathLeft[i] === self && pathRight[i] === that) return true;
if (depth) return compareOnPath(self, that);
let known = results.get(self);
if (!known) results.set(self, (known = /* @__PURE__ */ new WeakMap()));
let result = known.get(that);
if (result === void 0) known.set(that, (result = compareOnPath(self, that)));
return result;
}
function compareOnPath(self, that) {
pathLeft.push(self);
pathRight.push(that);
try {
return compareStructure(self, that);
} finally {
pathLeft.pop();
pathRight.pop();
}
}
const pathLeft = [];
const pathRight = [];
const results = /*#__PURE__*/ new WeakMap();
function compareStructure(self, that) {
if (hash(self) !== hash(that)) return false;
else if (self instanceof Date) {
if (!(that instanceof Date)) return false;
const selfTime = self.getTime();
const thatTime = that.getTime();
return (
selfTime === thatTime ||
(Number.isNaN(selfTime) && Number.isNaN(thatTime))
);
} else if (self instanceof RegExp)
return that instanceof RegExp && self.toString() === that.toString();
const bothEquals = isEqual(self);
if (
bothEquals !== isEqual(that) ||
(typeof self === "function" && !bothEquals)
)
return false;
else if (bothEquals) return self[symbol](that);
else if (Array.isArray(self)) {
if (!Array.isArray(that) || self.length !== that.length) return false;
return compareArrays(self, that);
} else if (ArrayBuffer.isView(self)) {
const selfIsDataView = self instanceof DataView;
if (
!ArrayBuffer.isView(that) ||
self.byteLength !== that.byteLength ||
selfIsDataView !== that instanceof DataView
)
return false;
if (selfIsDataView)
return compareTypedArrays(viewBytes(self), viewBytes(that));
return compareTypedArrays(self, that);
} else if (self instanceof Map) {
if (!(that instanceof Map) || self.size !== that.size) return false;
return compareHashed(self, that, entryHash, equalEntries);
} else if (self instanceof Set) {
if (!(that instanceof Set) || self.size !== that.size) return false;
return compareHashed(self, that, hash, compareBoth);
}
return compareRecords(self, that);
}
function compareArrays(self, that) {
for (let i = 0; i < self.length; i++)
if (!compareBoth(self[i], that[i])) return false;
return true;
}
function compareTypedArrays(self, that) {
if (self.length !== that.length) return false;
for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false;
return true;
}
function compareRecords(self, that) {
const selfKeys = getAllObjectKeys(self);
const thatKeys = getAllObjectKeys(that);
if (selfKeys.size !== thatKeys.size) return false;
for (const key of selfKeys)
if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false;
return true;
}
function compareHashed(self, that, hashOf, equivalent) {
const groups = /* @__PURE__ */ new Map();
let remaining = 0;
for (const item of that) {
const h = hashOf(item);
const group = groups.get(h);
if (group) group.push(item);
else groups.set(h, [item]);
remaining++;
}
outer: for (const item of self) {
const group = groups.get(hashOf(item));
if (group) {
for (let i = 0; i < group.length; i++)
if (equivalent(item, group[i])) {
group[i] = group[group.length - 1];
group.pop();
remaining--;
continue outer;
}
}
return false;
}
return remaining === 0;
}
const entryHash = (entry) => hash(entry[0]);
const equalEntries = (self, that) =>
compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]);
/**
* Checks whether a value implements the {@link Equal} interface.
*
* **When to use**
*
* Use when you need generic utility code to distinguish `Equal` implementors
* from plain values before calling `[Equal.symbol]` directly.
*
* **Details**
*
* - Pure function, no side effects.
* - Returns `true` if and only if `u` has a property keyed by
* {@link symbol}.
* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}.
*
* **Example** (Checking Equal values)
*
* ```ts import.meta.vitest
* import { Equal, Hash } from "effect"
*
* class Token implements Equal.Equal {
* constructor(readonly value: string) {}
* [Equal.symbol](that: Equal.Equal): boolean {
* return that instanceof Token && this.value === that.value
* }
* [Hash.symbol](): number {
* return Hash.string(this.value)
* }
* }
*
* Equal.isEqual(new Token("abc")) // => true
* Equal.isEqual({ x: 1 }) // => false
* Equal.isEqual(42) // => false
* ```
*
* @see {@link Equal} — the interface being checked
* @see {@link symbol} — the property key that signals `Equal` support
* @stability stable
* @category guards
* @since 2.0.0
*/
const isEqual = (u) => hasProperty(u, symbol);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/array.js
/**
* @since 2.0.0
*/
/** @internal */
const isArrayNonEmpty$1 = (self) => self.length > 0;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/record.js
/** @internal */
function assignProperty(self, key, value) {
if (key === "__proto__")
Object.defineProperty(self, key, {
value,
writable: true,
enumerable: true,
configurable: true,
});
else self[key] = value;
}
/** @internal */
function assignProperties(self, source) {
for (const key of Reflect.ownKeys(source))
if (Object.prototype.propertyIsEnumerable.call(source, key))
assignProperty(self, key, source[key]);
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Redactable.js
/**
* Defines the symbol used to identify objects that implement the {@link Redactable}
* protocol.
*
* **When to use**
*
* Use as the property key when implementing the `Redactable` protocol.
*
* **Details**
*
* Add a method under this key to make an object redactable. The method receives
* the current `Context` and must return the replacement value. The symbol is
* registered globally via `Symbol.for("~effect/Redactable")`, so it is
* identical across multiple copies of the library at runtime.
*
* **Example** (Masking an API key)
*
* ```ts import.meta.vitest
* import { Context, Redactable } from "effect"
*
* class ApiKey {
* constructor(readonly raw: string) {}
*
* [Redactable.symbolRedactable](_ctx: Context.Context<never>) {
* return this.raw.slice(0, 4) + "..."
* }
* }
*
* Redactable.redact(new ApiKey("secret-key")) // => "secr..."
* ```
*
* @see {@link Redactable} for the interface this symbol belongs to
* @see {@link isRedactable} to check whether a value has this symbol
* @stability stable
* @category symbols
* @since 3.10.0
*/
const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable");
/**
* Type guard that checks whether a value implements the {@link Redactable}
* interface.
*
* **When to use**
*
* Use to narrow an unknown value before calling redaction-specific helpers.
*
* @see {@link Redactable} for the interface being checked
* @see {@link redact} to apply redaction if the value is redactable
* @stability stable
* @category guards
* @since 3.10.0
*/
const isRedactable = (u) => hasProperty(u, symbolRedactable);
/**
* Returns a redacted value if it implements {@link Redactable}, otherwise returns it
* unchanged.
*
* **When to use**
*
* Use as the general-purpose entry point for redaction when the input may
* or may not implement the redaction protocol.
*
* **Details**
*
* This function calls {@link isRedactable} and, when it returns `true`,
* delegates to {@link getRedacted}.
*
* **Gotchas**
*
* Redaction is not recursive. Nested redactable values inside the returned
* object are not automatically redacted.
*
* @see {@link isRedactable} to check before redacting
* @see {@link getRedacted} for the lower-level variant for known redactables
* @stability stable
* @category destructors
* @since 3.10.0
*/
function redact$2(u) {
if (isRedactable(u)) return getRedacted(u);
return u;
}
/**
* Returns the result of calling `[symbolRedactable]` on a value that is
* already known to be {@link Redactable}.
*
* **When to use**
*
* Use when you need to read the redacted representation from a value already
* verified as `Redactable`.
*
* **Details**
*
* This function reads the current fiber's `Context` from the global fiber
* reference and passes it to the redaction method.
*
* **Gotchas**
*
* If no fiber is active, an empty `Context` is passed to the redaction method.
*
* @see {@link redact} for the higher-level variant that handles non-redactable values
* @see {@link isRedactable} for the type guard to verify before calling this
* @stability stable
* @category destructors
* @since 4.0.0
*/
function getRedacted(redactable) {
return redactable[symbolRedactable](
globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1,
);
}
/** @internal */
const currentFiberTypeId = "~effect/Fiber/currentFiber";
const emptyMap = /*#__PURE__*/ new Map();
const emptyContext$1 = {
"~effect/Context": {},
base: emptyMap,
depth: 0,
mapUnsafe: emptyMap,
pipe() {
return pipeArguments(this, arguments);
},
};
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Formatter.js
/**
* Formats JavaScript values into readable strings.
*
* `format` is intended for logs, diagnostics, and error messages. It handles
* primitives, objects, arrays, dates, regular expressions, maps, sets, class
* instances, errors, circular references, and redactable values. `formatJson`
* wraps JSON formatting with redaction and circular-reference handling, and the
* module also includes helpers for property keys, paths, and dates.
*
* @stability stable
* @since 4.0.0
*/
/**
* Converts any JavaScript value into a human-readable string.
*
* **When to use**
*
* Use when you need to format arbitrary JavaScript values for debugging,
* logging, or error messages.
*
* **Details**
*
* - Output is **not** valid JSON; use {@link formatJson} when you need
* parseable JSON.
* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class
* instances that `JSON.stringify` cannot represent.
* - Circular references are shown as `"[Circular]"` instead of throwing.
* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing.
* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`).
* Strings are JSON-quoted.
* - Objects with a custom `toString` (not `Object.prototype.toString`):
* `toString()` is called unless `ignoreToString` is `true`.
* - Errors with a `cause`: formatted as `"<message> (cause: <cause>)"`.
* - Iterables (`Set`, `Map`, etc.): formatted as
* `ClassName([...elements])`.
* - Class instances: wrapped as `ClassName({...})`.
* - `Redactable` values are automatically redacted.
* - Arrays/objects with 0–1 entries are inline; larger ones are
* pretty-printed when `space` is set.
* - `space` — indentation unit (number of spaces, or a string like
* `"\t"`). Defaults to `0` (compact).
* - `ignoreToString` — skip calling `toString()`. Defaults to `false`.
*
* **Example** (Formatting compact output)
*
* ```ts import.meta.vitest
* import { Formatter } from "effect"
*
* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}"
* ```
*
* **Example** (Pretty-printed output)
*
* ```ts import.meta.vitest
* import { Formatter } from "effect"
*
* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 })
* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}"
* ```
*
* **Example** (Handling circular references)
*
* ```ts import.meta.vitest
* import { Formatter } from "effect"
*
* const obj: any = { name: "loop" }
* obj.self = obj
* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}"
* ```
*
* @see {@link formatJson}
* @see {@link Formatter}
* @stability stable
* @category formatting
* @since 2.0.0
*/
function format$1(input, options) {
const space = options?.space ?? 0;
const ancestors = /* @__PURE__ */ new WeakSet();
const gap = !space
? ""
: typeof space === "number"
? " ".repeat(space)
: space;
const ind = (d) => gap.repeat(d);
const wrap = (v, body) => {
const ctor = v?.constructor;
return ctor && ctor !== Object.prototype.constructor && ctor.name
? `${ctor.name}(${body})`
: body;
};
const ownKeys = (o) => {
try {
return Reflect.ownKeys(o);
} catch {
return ["[ownKeys threw]"];
}
};
function recur(v, d = 0) {
try {
return recurUnsafe(v, d);
} catch {
if ((typeof v === "object" && v !== null) || typeof v === "function")
ancestors.delete(v);
return "[inspection threw]";
}
}
function recurUnsafe(v, d = 0) {
if (typeof v === "string") return JSON.stringify(v);
if (
typeof v === "number" ||
v == null ||
typeof v === "boolean" ||
typeof v === "symbol"
)
return String(v);
if (typeof v === "bigint") return String(v) + "n";
if (typeof v === "object" || typeof v === "function") {
if (ancestors.has(v)) return CIRCULAR;
ancestors.add(v);
let output;
if (symbolRedactable in v) output = recur(getRedacted(v), d);
else if (Array.isArray(v))
output =
!gap || v.length <= 1
? `[${v.map((x) => recur(x, d)).join(",")}]`
: `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`;
else if (v instanceof Date) output = formatDate(v);
else if (
!options?.ignoreToString &&
hasProperty(v, "toString") &&
typeof v["toString"] === "function" &&
v["toString"] !== Object.prototype.toString &&
v["toString"] !== Array.prototype.toString
) {
const s = safeToString(v);
output =
v instanceof Error && v.cause !== void 0
? `${s} (cause: ${recur(v.cause, d)})`
: s;
} else if (Symbol.iterator in v)
output = `${v.constructor.name}(${recur(Array.from(v), d)})`;
else {
const keys = ownKeys(v);
if (!gap || keys.length <= 1) {
const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`;
output = wrap(v, body);
} else {
const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`;
output = wrap(v, body);
}
}
ancestors.delete(v);
return output;
}
return String(v);
}
return recur(input, 0);
}
const CIRCULAR = "[Circular]";
/**
* @internal
*/
function formatPropertyKey(name) {
return typeof name === "string" ? JSON.stringify(name) : String(name);
}
/**
* Formats an array of property keys as a bracket-notation path string.
*
* @internal
*/
function formatPath(path) {
return path.map((key) => `[${formatPropertyKey(key)}]`).join("");
}
/**
* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for
* invalid dates instead of throwing.
*
* @internal
*/
function formatDate(date) {
try {
return date.toISOString();
} catch {
return "Invalid Date";
}
}
function safeToString(input) {
try {
const s = input.toString();
return typeof s === "string" ? s : String(s);
} catch {
return "[toString threw]";
}
}
function safeGet(input, key) {
try {
return input[key];
} catch {
return "[property access threw]";
}
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Inspectable.js
/**
* Controls how values appear in logs and debugging output.
*
* Effect data types use `Inspectable` to provide stable string, JSON, and
* Node.js inspection output. This keeps custom values readable in logs, REPLs,
* test failures, and diagnostics. This module defines the Node inspect symbol,
* the `Inspectable` interface, safe conversion helpers, and shared prototype or
* class implementations for custom values.
*
* @stability stable
* @since 2.0.0
*/
/**
* Defines the symbol used by Node.js for custom object inspection.
*
* **When to use**
*
* Use to implement Node.js custom inspection for a value.
*
* **Details**
*
* This symbol is recognized by Node.js's `util.inspect()` function and the REPL
* for custom object representation. When an object has a method with this symbol,
* it will be called to determine how the object should be displayed.
*
* **Example** (Defining custom Node inspection)
*
* ```ts import.meta.vitest
* import { Inspectable } from "effect"
*
* class CustomObject {
* constructor(private value: string) {}
*
* [Inspectable.NodeInspectSymbol]() {
* return `CustomObject(${this.value})`
* }
* }
*
* const obj = new CustomObject("hello")
* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)"
* ```
*
* @stability stable
* @category symbols
* @since 2.0.0
*/
const NodeInspectSymbol = /*#__PURE__*/ Symbol.for(
"nodejs.util.inspect.custom",
);
/**
* Converts a value to its structured inspection representation.
*
* **When to use**
*
* Use when you need the structured representation of an inspectable value
* without risking unhandled errors.
*
* **Details**
*
* This function applies redaction before extracting data from objects that
* implement `toJSON`, recursively processes arrays, and handles errors
* gracefully. Plain objects are returned unchanged, so the result is not
* guaranteed to be accepted by `JSON.stringify`; it may still contain values
* such as `BigInt`, functions, or circular references.
*
* @see {@link toStringUnknown} for converting unknown values to strings
*
* @stability stable
* @category converting
* @since 4.0.0
*/
const toJson = (input) => {
try {
input = redact$2(input);
if (
hasProperty(input, "toJSON") &&
isFunction(input["toJSON"]) &&
input["toJSON"].length === 0
)
return input.toJSON();
else if (Array.isArray(input)) return input.map(toJson);
return input;
} catch {
return "[toJSON threw]";
}
};
/**
* A base prototype object that implements the {@link Inspectable} interface.
*
* **When to use**
*
* Use as a prototype for plain objects that should share standard inspectable behavior.
*
* **Details**
*
* This object provides default implementations for the {@link Inspectable} methods.
* It can be used as a prototype for objects that want to be inspectable,
* or as a mixin to add inspection capabilities to existing objects.
*
* **Example** (Using the base inspectable prototype)
*
* ```ts import.meta.vitest
* import { Inspectable } from "effect"
*
* // Use as prototype
* const myObject = Object.create(Inspectable.BaseProto)
* myObject.name = "example"
* myObject.value = 42
*
* myObject.toString() // => "\"[toJSON threw]\""
*
* // Or extend in a constructor
* function MyClass(this: any, name: string) {
* this.name = name
* }
* MyClass.prototype = Object.create(Inspectable.BaseProto)
* MyClass.prototype.constructor = MyClass
* ```
*
* @stability stable
* @category prototypes
* @since 2.0.0
*/
const BaseProto = {
toJSON() {
return toJson(this);
},
[NodeInspectSymbol]() {
return this.toJSON();
},
toString() {
return format$1(this.toJSON());
},
};
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/stackTraceLimit.js
/**
* Check if `Error.stackTraceLimit` is writable.
* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible.
*
* @internal
*/
const isStackTraceLimitWritable = () => {
const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit");
if (desc === void 0) return Object.isExtensible(Error);
return Object.hasOwn(desc, "writable")
? desc.writable === true
: desc.set !== void 0;
};
const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable();
/**
* Get the current `Error.stackTraceLimit` value.
* Returns `undefined` if the property doesn't exist.
*
* @internal
*/
const getStackTraceLimit = () => Error.stackTraceLimit;
/**
* Safely set `Error.stackTraceLimit` if possible, otherwise no-op.
*
* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be
* restored faithfully.
*
* @internal
*/
const setStackTraceLimit = (value) => {
if (canWriteStackTraceLimit) Error.stackTraceLimit = value;
};
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Utils.js
/**
* Yields its wrapped value exactly once, then completes with the value sent
* back in.
*
* **When to use**
*
* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be
* `yield*`-ed inside generator functions, such as `Effect.gen` and
* `Option.gen`.
*
* **Details**
*
* The first call to `next()` returns a fresh `{ value: self, done: false }`.
* Every subsequent call returns `{ value: a, done: true }` where `a` is the
* argument passed to `next()`. To keep `yield*` cheap, the completion result
* is the iterator itself rather than a new object, so only the iterator and
* the single yielded result are allocated per `yield*`.
*
* **Example** (Yielding a wrapped value in a generator)
*
* ```ts import.meta.vitest
* import { Utils } from "effect"
*
* const gen = new Utils.SingleShotGen<string, number>("hello")
*
* gen.next(0).value // => "hello"
*
* gen.next(42).value // => 42
* ```
*
* @see {@link Gen} for the type-level signature that relies on `SingleShotGen`
* @stability stable
* @category constructors
* @since 2.0.0
*/
var SingleShotGen = class {
constructor(self) {
this.value = self;
this.done = false;
}
/**
* Yields the stored value once, then completes with the value sent back in.
*
* **When to use**
*
* Use to advance a `SingleShotGen` through its single yield and completion
* step.
*
* @since 2.0.0
*/
next(a) {
if (this.done) {
this.value = a;
return this;
}
this.done = true;
return {
value: this.value,
done: false,
};
}
};
const pickInternalCall = () => {
const InternalTypeId = "~effect/Utils/internal";
const standard = {
[InternalTypeId]: (body) => {
return body();
},
};
const forced = {
[InternalTypeId]: (body) => {
try {
return body();
} finally {
}
},
};
const limit = getStackTraceLimit();
if (limit === 0) return forced[InternalTypeId];
setStackTraceLimit(2);
const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error());
setStackTraceLimit(limit);
return error.stack?.includes(InternalTypeId) === true
? standard[InternalTypeId]
: forced[InternalTypeId];
};
/** @internal */
const internalCall = /*#__PURE__*/ pickInternalCall();
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/core.js
/** @internal */
const EffectTypeId = `~effect/Effect`;
/** @internal */
const ExitTypeId = `~effect/Exit`;
const effectVariance = {
_A: identity,
_E: identity,
_R: identity,
};
/** @internal */
const identifier = `${EffectTypeId}/identifier`;
/** @internal */
const args = `${EffectTypeId}/args`;
/** @internal */
const evaluate = `${EffectTypeId}/evaluate`;
/** @internal */
const contA = `${EffectTypeId}/successCont`;
/** @internal */
const contE = `${EffectTypeId}/failureCont`;
/** @internal */
const contAll = `${EffectTypeId}/ensureCont`;
/** @internal */
const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield");
/** @internal */
const PipeInspectableProto = {
pipe() {
return pipeArguments(this, arguments);
},
toJSON() {
return { ...this };
},
toString() {
return format$1(this.toJSON(), {
ignoreToString: true,
space: 2,
});
},
[NodeInspectSymbol]() {
return this.toJSON();
},
};
/** @internal */
const EffectProto = {
[EffectTypeId]: effectVariance,
...PipeInspectableProto,
[Symbol.iterator]() {
return new SingleShotGen(this);
},
toJSON() {
return {
_id: "Effect",
op: this[identifier],
...("~effect/Effect/args" in this ? { args: this[args] } : void 0),
};
},
};
/** @internal */
const isExit = (u) => hasProperty(u, ExitTypeId);
/** @internal */
const CauseTypeId = "~effect/Cause";
/** @internal */
const CauseReasonTypeId = "~effect/Cause/Reason";
/** @internal */
const isCause = (self) => hasProperty(self, CauseTypeId);
/** @internal */
var CauseImpl = class {
constructor(failures) {
this[CauseTypeId] = CauseTypeId;
this.reasons = failures;
}
pipe() {
return pipeArguments(this, arguments);
}
toJSON() {
return {
_id: "Cause",
failures: this.reasons.map((f) => f.toJSON()),
};
}
toString() {
return `Cause(${format$1(this.reasons)})`;
}
[NodeInspectSymbol]() {
return this.toJSON();
}
[symbol](that) {
return (
isCause(that) &&
this.reasons.length === that.reasons.length &&
this.reasons.every((e, i) => equals$1(e, that.reasons[i]))
);
}
[symbol$1]() {
return array(this.reasons);
}
};
const annotationsMap = /*#__PURE__*/ new WeakMap();
/** @internal */
var ReasonBase = class {
[CauseReasonTypeId];
annotations;
_tag;
constructor(_tag, annotations, originalError) {
this[CauseReasonTypeId] = CauseReasonTypeId;
this._tag = _tag;
if (
annotations !== constEmptyAnnotations &&
typeof originalError === "object" &&
originalError !== null &&
annotations.size > 0
) {
const prevAnnotations = annotationsMap.get(originalError);
if (prevAnnotations)
annotations = new Map([...prevAnnotations, ...annotations]);
annotationsMap.set(originalError, annotations);
}
this.annotations = annotations;
}
annotate(annotations, options) {
if (annotations.mapUnsafe.size === 0) return this;
const newAnnotations = new Map(this.annotations);
annotations.mapUnsafe.forEach((value, key) => {
if (options?.overwrite !== true && newAnnotations.has(key)) return;
newAnnotations.set(key, value);
});
const self = Object.assign(
Object.create(Object.getPrototypeOf(this)),
this,
);
self.annotations = newAnnotations;
return self;
}
pipe() {
return pipeArguments(this, arguments);
}
toString() {
return format$1(this);
}
[NodeInspectSymbol]() {
return this.toString();
}
};
/** @internal */
const constEmptyAnnotations = /*#__PURE__*/ new Map();
/** @internal */
var Fail = class extends ReasonBase {
constructor(error, annotations = constEmptyAnnotations) {
super("Fail", annotations, error);
this.error = error;
}
toString() {
return `Fail(${format$1(this.error)})`;
}
toJSON() {
return {
_tag: "Fail",
error: this.error,
};
}
[symbol](that) {
return (
isFailReason$1(that) &&
equals$1(this.error, that.error) &&
equals$1(this.annotations, that.annotations)
);
}
[symbol$1]() {
return combine(string$1(this._tag))(
combine(hash(this.error))(hash(this.annotations)),
);
}
};
/** @internal */
const causeFromReasons = (reasons) => new CauseImpl(reasons);
const dedupeReasons = (self, that) => {
const buckets = /* @__PURE__ */ new Map();
const out = [];
for (const reason of self.concat(that)) {
const hash$2 = hash(reason);
const bucket = buckets.get(hash$2);
if (bucket === void 0) buckets.set(hash$2, [reason]);
else if (bucket.some((previous) => equals$1(previous, reason))) continue;
else bucket.push(reason);
out.push(reason);
}
return out;
};
/** @internal */
const causeCombine = /*#__PURE__*/ dual(2, (self, that) => {
if (self.reasons.length === 0) return that;
else if (that.reasons.length === 0) return self;
const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons));
return equals$1(self, newCause) ? self : newCause;
});
/**
* Appends the interrupts from `interrupts` that `self` does not contain yet.
* Unlike `causeCombine`, it never calls hash or equality methods, which can be
* user-defined, random, or throwing.
*
* @internal
*/
const causeAddInterrupts = (self, interrupts) => {
const reasons = self.reasons.slice();
for (const reason of interrupts.reasons)
if (
isInterruptReason(reason) &&
!reasons.some(
(r) =>
isInterruptReason(r) &&
r.fiberId === reason.fiberId &&
r.annotations === reason.annotations,
)
)
reasons.push(reason);
return reasons.length === self.reasons.length ? self : new CauseImpl(reasons);
};
/** @internal */
const causeFail = (error) => new CauseImpl([new Fail(error)]);
/** @internal */
var Die = class extends ReasonBase {
constructor(defect, annotations = constEmptyAnnotations) {
super("Die", annotations, defect);
this.defect = defect;
}
toString() {
return `Die(${format$1(this.defect)})`;
}
toJSON() {
return {
_tag: "Die",
defect: this.defect,
};
}
[symbol](that) {
return (
isDieReason(that) &&
equals$1(this.defect, that.defect) &&
equals$1(this.annotations, that.annotations)
);
}
[symbol$1]() {
return combine(string$1(this._tag))(
combine(hash(this.defect))(hash(this.annotations)),
);
}
};
/** @internal */
const causeDie = (defect) => new CauseImpl([new Die(defect)]);
/** @internal */
const causeAnnotate = /*#__PURE__*/ dual(
(args) => isCause(args[0]),
(self, annotations, options) => {
if (annotations.mapUnsafe.size === 0) return self;
return new CauseImpl(
self.reasons.map((f) => f.annotate(annotations, options)),
);
},
);
/** @internal */
const isFailReason$1 = (self) => self._tag === "Fail";
/** @internal */
const isDieReason = (self) => self._tag === "Die";
/** @internal */
const isInterruptReason = (self) => self._tag === "Interrupt";
function defaultEvaluate(_fiber) {
return exitDie(`Effect.evaluate: Not implemented`);
}
/** @internal */
const makePrimitiveProto = (options) => ({
...EffectProto,
[identifier]: options.op,
[evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate,
[contA]: options[contA],
[contE]: options[contE],
[contAll]: options[contAll],
});
/** @internal */
const makePrimitive = (options) => {
const Proto = makePrimitiveProto(options);
const PrimitiveImpl = function (value) {
this[args] = value;
};
PrimitiveImpl.prototype = Proto;
return function (value) {
return new PrimitiveImpl(value);
};
};
/** @internal */
const makeExit = (options) => {
const Proto = {
[ExitTypeId]: ExitTypeId,
_tag: options.op,
get [options.prop]() {
return this[args];
},
...makePrimitiveProto(options),
toString() {
return `${options.op}(${format$1(this[args])})`;
},
toJSON() {
return {
_id: "Exit",
_tag: options.op,
[options.prop]: this[args],
};
},
[symbol](that) {
return (
isExit(that) &&
that._tag === this._tag &&
equals$1(this["~effect/Effect/args"], that["~effect/Effect/args"])
);
},
[symbol$1]() {
return combine(string$1(options.op), hash(this[args]));
},
};
const ExitPrimitive = function (value) {
this[args] = value;
};
ExitPrimitive.prototype = Proto;
return function (value) {
return new ExitPrimitive(value);
};
};
/** @internal */
const exitSucceed = /*#__PURE__*/ makeExit({
op: "Success",
prop: "value",
[evaluate](fiber) {
const cont = fiber.getCont(contA);
return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this);
},
});
/** @internal */
const StackTraceKey = { key: "effect/Cause/StackTrace" };
/** @internal */
const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" };
/** @internal */
const exitFailCause = /*#__PURE__*/ makeExit({
op: "Failure",
prop: "cause",
[evaluate](fiber) {
let cause = this[args];
let annotated = false;
if (fiber.cache.stackFrame) {
cause = causeAnnotate(cause, {
mapUnsafe: /* @__PURE__ */ new Map([
[StackTraceKey.key, fiber.cache.stackFrame],
]),
});
annotated = true;
}
let cont = fiber.getCont(contE);
const interruptedCause = fiber._interruptedCause;
if (interruptedCause && fiber.interruptible) {
let skippedHandler = false;
while (cont && fiber.interruptible) {
skippedHandler ||= identifier in cont;
cont = fiber.getCont(contE);
}
if (skippedHandler)
cause = causeFromReasons(
cause.reasons.filter((reason) => reason._tag !== "Fail"),
);
cause = causeAddInterrupts(cause, interruptedCause);
annotated = true;
}
return cont
? cont[contE](cause, fiber, annotated ? void 0 : this)
: fiber.yieldWith(annotated ? exitFailCause(cause) : this);
},
});
/** @internal */
const exitFail = (e) => exitFailCause(causeFail(e));
/** @internal */
const exitDie = (defect) => exitFailCause(causeDie(defect));
/** @internal */
const withFiber = /*#__PURE__*/ makePrimitive({
op: "WithFiber",
[evaluate](fiber) {
return this[args](fiber);
},
});
/** @internal */
const YieldableError = /*#__PURE__*/ (function () {
class YieldableError extends globalThis.Error {}
const proto = /*#__PURE__*/ makePrimitiveProto({
op: "YieldableError",
[evaluate]() {
return exitFail(this);
},
});
delete proto.toString;
Object.assign(YieldableError.prototype, proto);
return YieldableError;
})();
/** @internal */
const Error$2 = /*#__PURE__*/ (function () {
const plainArgsSymbol = /*#__PURE__*/ Symbol.for(
"effect/Data/Error/plainArgs",
);
return class Base extends YieldableError {
constructor(args) {
super(args?.message, args?.cause ? { cause: args.cause } : void 0);
if (args) {
assignProperties(this, args);
Object.defineProperty(this, plainArgsSymbol, {
value: args,
enumerable: false,
});
}
}
toJSON() {
return {
...this[plainArgsSymbol],
...this,
};
}
};
})();
/** @internal */
const TaggedError$1 = (tag) => {
class Base extends Error$2 {
_tag = tag;
}
Base.prototype.name = tag;
return Base;
};
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/option.js
/**
* @since 2.0.0
*/
const TypeId$15 = "~effect/Option";
const CommonProto$1 = {
[TypeId$15]: { _A: (_) => _ },
...PipeInspectableProto,
[Symbol.iterator]() {
return new SingleShotGen(this);
},
};
const SomeProto = /*#__PURE__*/ Object.defineProperty(
/*#__PURE__*/ Object.assign(/*#__PURE__*/ Object.create(CommonProto$1), {
_tag: "Some",
_op: "Some",
[symbol](that) {
return (
isOption(that) && isSome$1(that) && equals$1(this.value, that.value)
);
},
[symbol$1]() {
return combine(hash(this._tag))(hash(this.value));
},
toString() {
return `some(${format$1(this.value)})`;
},
toJSON() {
return {
_id: "Option",
_tag: this._tag,
value: toJson(this.value),
};
},
}),
"valueOrUndefined",
{
get() {
return this.value;
},
},
);
const NoneHash = /*#__PURE__*/ hash("None");
const NoneProto = /*#__PURE__*/ Object.assign(
/*#__PURE__*/ Object.create(CommonProto$1),
{
_tag: "None",
_op: "None",
valueOrUndefined: void 0,
[symbol](that) {
return isOption(that) && isNone$1(that);
},
[symbol$1]() {
return NoneHash;
},
toString() {
return `none()`;
},
toJSON() {
return {
_id: "Option",
_tag: this._tag,
};
},
},
);
/** @internal */
const isOption = (input) => hasProperty(input, TypeId$15);
/** @internal */
const isNone$1 = (fa) => fa._tag === "None";
/** @internal */
const isSome$1 = (fa) => fa._tag === "Some";
/** @internal */
const none$1 = /*#__PURE__*/ Object.create(NoneProto);
/** @internal */
const SomeImpl = function (value) {
this.value = value;
};
SomeImpl.prototype = SomeProto;
/** @internal */
const some$1 = (value) => new SomeImpl(value);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/result.js
const TypeId$14 = "~effect/Result";
const CommonProto = {
[TypeId$14]: {
/* v8 ignore next 2 */
_A: (_) => _,
_E: (_) => _,
},
...PipeInspectableProto,
[Symbol.iterator]() {
return new SingleShotGen(this);
},
};
const SuccessProto = /*#__PURE__*/ Object.assign(
/*#__PURE__*/ Object.create(CommonProto),
{
_tag: "Success",
_op: "Success",
[symbol](that) {
return (
isResult(that) &&
isSuccess$2(that) &&
equals$1(this.success, that.success)
);
},
[symbol$1]() {
return combine(hash(this._tag))(hash(this.success));
},
toString() {
return `success(${format$1(this.success)})`;
},
toJSON() {
return {
_id: "Result",
_tag: this._tag,
value: toJson(this.success),
};
},
},
);
const FailureProto = /*#__PURE__*/ Object.assign(
/*#__PURE__*/ Object.create(CommonProto),
{
_tag: "Failure",
_op: "Failure",
[symbol](that) {
return (
isResult(that) &&
isFailure$1(that) &&
equals$1(this.failure, that.failure)
);
},
[symbol$1]() {
return combine(hash(this._tag))(hash(this.failure));
},
toString() {
return `failure(${format$1(this.failure)})`;
},
toJSON() {
return {
_id: "Result",
_tag: this._tag,
failure: toJson(this.failure),
};
},
},
);
/** @internal */
const isResult = (input) => hasProperty(input, TypeId$14);
/** @internal */
const isFailure$1 = (result) => result._tag === "Failure";
/** @internal */
const isSuccess$2 = (result) => result._tag === "Success";
/** @internal */
const FailureImpl = function (failure) {
this.failure = failure;
};
FailureImpl.prototype = FailureProto;
/** @internal */
const SuccessImpl = function (success) {
this.success = success;
};
SuccessImpl.prototype = SuccessProto;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Order.js
/**
* Defines comparison functions for ordered values.
*
* An `Order<A>` compares two `A` values and returns whether the first is less
* than, equal to, or greater than the second. Orders are used for sorting,
* choosing minimum or maximum values, checking ranges, and building ordered data
* structures. This module includes built-in orders, constructors for custom
* orders, tools for reversing and combining comparisons, tuple and struct
* helpers, comparison predicates, clamping, and reducer support.
*
* @stability stable
* @since 2.0.0
*/
/**
* Creates a new `Order` instance from a comparison function.
*
* **When to use**
*
* Use when you need a sorting rule not covered by the built-in orders or input
* mapping helpers, and you can provide a total comparison.
*
* **Details**
*
* Uses reference equality (`===`) as a shortcut: if `self === that`, it returns
* `0` without calling the comparison function. The comparison function should
* return `-1`, `0`, or `1`, and the returned order satisfies total ordering
* laws when the comparison function does.
*
* **Example** (Creating an Order)
*
* ```ts import.meta.vitest
* import { Order } from "effect"
*
* const byAge = Order.make<{ name: string; age: number }>((self, that) => {
* if (self.age < that.age) return -1
* if (self.age > that.age) return 1
* return 0
* })
*
* byAge({ name: "Alice", age: 30 }, { name: "Bob", age: 25 }) // => 1
* byAge({ name: "Alice", age: 25 }, { name: "Bob", age: 30 }) // => -1
* ```
*
* @see {@link mapInput} to transform an order by mapping the input type
* @see {@link combine} to combine multiple orders
* @stability stable
* @category constructors
* @since 2.0.0
*/
function make$10(compare) {
return (self, that) => (self === that ? 0 : compare(self, that));
}
/**
* Order instance for strings that compares them lexicographically using JavaScript's `<` operator.
*
* **When to use**
*
* Use when you need lexicographic string ordering.
*
* **Details**
*
* Uses lexicographic dictionary ordering. The empty string is less than any
* non-empty string, and comparisons are case-sensitive.
*
* **Example** (Ordering strings)
*
* ```ts import.meta.vitest
* import { Order } from "effect"
*
* Order.String("apple", "banana") // => -1
* Order.String("banana", "apple") // => 1
* Order.String("apple", "apple") // => 0
* ```
*
* @see {@link mapInput} to compare objects by a string property
* @see {@link Struct} to combine with other orders for struct comparison
* @stability stable
* @category instances
* @since 4.0.0
*/
const String$4 = /*#__PURE__*/ make$10((self, that) => (self < that ? -1 : 1));
/**
* Order instance for numbers that compares them numerically.
*
* **When to use**
*
* Use when you need numeric ordering for numbers.
*
* **Details**
*
* `0` is considered equal to `-0`. All `NaN` values are considered equal to
* each other, and any `NaN` is considered less than any non-`NaN` number. All
* other values use standard numeric comparison.
*
* **Example** (Ordering numbers)
*
* ```ts import.meta.vitest
* import { Order } from "effect"
*
* Order.Number(1, 1) // => 0
* Order.Number(1, 2) // => -1
* Order.Number(2, 1) // => 1
*
* Order.Number(0, -0) // => 0
* Order.Number(NaN, 1) // => -1
* ```
*
* @see {@link mapInput} to compare objects by a number property
* @see {@link BigInt} for bigint comparisons
* @stability stable
* @category instances
* @since 4.0.0
*/
const Number$4 = /*#__PURE__*/ make$10((self, that) => {
if (globalThis.Number.isNaN(self) && globalThis.Number.isNaN(that)) return 0;
if (globalThis.Number.isNaN(self)) return -1;
if (globalThis.Number.isNaN(that)) return 1;
return self < that ? -1 : 1;
});
/**
* Checks whether one value is less than or equal to another according to the given order.
*
* **When to use**
*
* Use when you need a boolean less-than-or-equal predicate using an `Order`.
*
* **Details**
*
* Returns `true` if the order returns `-1` or `0`, and returns `false` only if
* the order returns `1`.
*
* **Example** (Checking less-than-or-equal comparisons)
*
* ```ts import.meta.vitest
* import { Order } from "effect"
*
* const isLessThanOrEqualToNumber = Order.isLessThanOrEqualTo(Order.Number)
*
* isLessThanOrEqualToNumber(1, 2) // => true
* isLessThanOrEqualToNumber(1, 1) // => true
* isLessThanOrEqualToNumber(2, 1) // => false
* ```
*
* @see {@link isLessThan} for strict less than
* @see {@link isGreaterThan} for strict greater than
* @stability stable
* @category predicates
* @since 4.0.0
*/
const isLessThanOrEqualTo$1 = (O) =>
dual(2, (self, that) => O(self, that) !== 1);
/**
* Checks whether one value is greater than or equal to another according to the given order.
*
* **When to use**
*
* Use when you need a boolean greater-than-or-equal predicate using an
* `Order`.
*
* **Details**
*
* Returns `true` if the order returns `1` or `0`, and returns `false` only if
* the order returns `-1`.
*
* **Example** (Checking greater-than-or-equal comparisons)
*
* ```ts import.meta.vitest
* import { Order } from "effect"
*
* const isGreaterThanOrEqualToNumber = Order.isGreaterThanOrEqualTo(Order.Number)
*
* isGreaterThanOrEqualToNumber(2, 1) // => true
* isGreaterThanOrEqualToNumber(1, 1) // => true
* isGreaterThanOrEqualToNumber(1, 2) // => false
* ```
*
* @see {@link isGreaterThan} for strict greater than
* @see {@link isLessThanOrEqualTo} for less than or equal
* @stability stable
* @category predicates
* @since 4.0.0
*/
const isGreaterThanOrEqualTo$1 = (O) =>
dual(2, (self, that) => O(self, that) !== -1);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Option.js
/**
* Creates an `Option` representing the absence of a value.
*
* **When to use**
*
* Use to represent a missing or uninitialized value, such as returning "no
* result" from a function.
*
* **Details**
*
* - Returns `Option<never>`, which is a subtype of `Option<A>` for any `A`
* - Always returns the same singleton instance
*
* **Example** (Creating an empty Option)
*
* ```ts import.meta.vitest
* import { Option } from "effect"
*
* // ┌─── Option<never>
* // â–¼
* const noValue = Option.none() // => Option.none()
* ```
*
* @see {@link some} for the opposite operation.
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const none = () => none$1;
/**
* Wraps the given value into an `Option` to represent its presence.
*
* **When to use**
*
* Use to wrap a known present value as `Option`
* - Returning a successful result from a partial function
*
* **Details**
*
* - Always returns `Some<A>`
* - Does not filter `null` or `undefined`; use {@link fromNullishOr} for that
*
* **Example** (Wrapping a value)
*
* ```ts import.meta.vitest
* import { Option } from "effect"
*
* // ┌─── Option<number>
* // â–¼
* const value = Option.some(1) // => Option.some(1)
* ```
*
* @see {@link none} for the opposite operation.
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const some = some$1;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Array.js
/**
* Exposes the global array constructor.
*
* **When to use**
*
* Use to access native JavaScript array constructor methods such as `isArray`
* or `from` from the Effect module namespace.
*
* **Example** (Accessing the Array constructor)
*
* ```ts import.meta.vitest
* import { Array } from "effect"
*
* Array.Array === globalThis.Array // => true
* ```
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Array$1 = globalThis.Array;
/**
* Adds a single element to the end of an iterable, returning a `NonEmptyArray`.
*
* **When to use**
*
* Use when you need to guarantee a non-empty result after adding a required
* trailing value.
*
* **Example** (Appending an element)
*
* ```ts import.meta.vitest
* import { Array } from "effect"
*
* Array.append([1, 2, 3], 4) // => [1, 2, 3, 4]
* ```
*
* @see {@link prepend} — add to the front
* @see {@link appendAll} — append multiple elements
*
* @stability stable
* @category combining
* @since 2.0.0
*/
const append = /*#__PURE__*/ dual(2, (self, last) => [...self, last]);
Array$1.isArray;
/**
* Checks whether a mutable `Array` is non-empty, narrowing the type to
* `NonEmptyArray`.
*
* **When to use**
*
* Use when you need the narrowed value to remain a mutable `Array` after proving
* it has at least one element.
*
* **Example** (Checking for a non-empty array)
*
* ```ts import.meta.vitest
* import { Array } from "effect"
*
* Array.isArrayNonEmpty([]) // => false
* Array.isArrayNonEmpty([1, 2, 3]) // => true
* ```
*
* @see {@link isReadonlyArrayNonEmpty} — readonly variant
* @see {@link isArrayEmpty} — opposite check
*
* @stability stable
* @category guards
* @since 4.0.0
*/
const isArrayNonEmpty = isArrayNonEmpty$1;
/**
* Checks whether a `ReadonlyArray` is non-empty, narrowing the type to
* `NonEmptyReadonlyArray`.
*
* **When to use**
*
* Use when you need to prove a readonly array has at least one element without
* requiring mutable array methods afterward.
*
* **Example** (Checking for a non-empty readonly array)
*
* ```ts import.meta.vitest
* import { Array } from "effect"
*
* Array.isReadonlyArrayNonEmpty([]) // => false
* Array.isReadonlyArrayNonEmpty([1, 2, 3]) // => true
* ```
*
* @see {@link isArrayNonEmpty} — mutable variant
* @see {@link isReadonlyArrayEmpty} — opposite check
*
* @stability stable
* @category guards
* @since 4.0.0
*/
const isReadonlyArrayNonEmpty = isArrayNonEmpty$1;
/**
* Creates an empty array.
*
* **When to use**
*
* Use to create a typed empty array without allocating placeholder elements.
*
* **Example** (Creating an empty array)
*
* ```ts import.meta.vitest
* import { Array } from "effect"
*
* Array.empty<number>() // => []
* ```
*
* @see {@link of} — create a single-element array
* @see {@link make} — create from multiple values
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const empty$1 = () => [];
/**
* Transforms each element using a function, returning a new array.
*
* **When to use**
*
* Use to transform each element independently while preserving the array shape.
*
* **Details**
*
* The function receives `(element, index)`. The return type preserves
* `NonEmptyArray`.
*
* **Example** (Doubling values)
*
* ```ts import.meta.vitest
* import { Array } from "effect"
*
* Array.map([1, 2, 3], (x) => x * 2) // => [2, 4, 6]
* ```
*
* @see {@link flatMap} — map and flatten
*
* @stability stable
* @category mapping
* @since 2.0.0
*/
const map$2 = /*#__PURE__*/ dual(2, (self, f) => self.map(f));
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/BigDecimal.js
/**
* Decimal numbers and arithmetic for cases where JavaScript `number` rounding
* is not precise enough. A `BigDecimal` stores digits as a `bigint` plus a
* decimal scale, which lets the module parse, compare, add, subtract, multiply,
* divide, round, and format decimal values such as money, quantities, and
* measurements.
*
* @stability stable
* @since 2.0.0
*/
const TypeId$13 = "~effect/BigDecimal";
const BigDecimalProto = {
[TypeId$13]: TypeId$13,
[symbol$1]() {
const normalized = normalize(this);
return combine(
string$1(String(normalized.value)),
number$1(normalized.scale),
);
},
[symbol](that) {
return isBigDecimal(that) && compare(this, that) === 0;
},
toString() {
return `BigDecimal(${format(this)})`;
},
toJSON() {
return {
_id: "BigDecimal",
value: String(this.value),
scale: this.scale,
};
},
[NodeInspectSymbol]() {
return this.toJSON();
},
pipe() {
return pipeArguments(this, arguments);
},
};
/**
* Checks whether a given value is a `BigDecimal`.
*
* **When to use**
*
* Use to validate unknown input and narrow it to `BigDecimal`.
*
* **Example** (Checking BigDecimal values)
*
* ```ts import.meta.vitest
* import { BigDecimal } from "effect"
*
* const decimal = BigDecimal.fromNumber(123.45)
* BigDecimal.isBigDecimal(decimal) // => false
* BigDecimal.isBigDecimal(BigDecimal.fromStringUnsafe("123.45")) // => true
* BigDecimal.isBigDecimal(123.45) // => false
* BigDecimal.isBigDecimal("123.45") // => false
* ```
*
* @stability stable
* @category guards
* @since 2.0.0
*/
const isBigDecimal = (u) => hasProperty(u, TypeId$13);
/**
* Creates a `BigDecimal` from a `bigint` value and a safe integer scale.
*
* **When to use**
*
* Use to construct a decimal directly from its unscaled integer value and
* decimal scale.
*
* **Gotchas**
*
* Throws a `RangeError` if `scale` is not a safe integer.
*
* **Example** (Creating decimals from bigint and scale)
*
* ```ts import.meta.vitest
* import { BigDecimal } from "effect"
*
* // Create 123.45 (12345 with scale 2)
* const decimal = BigDecimal.make(12345n, 2)
* decimal // => BigDecimal.fromStringUnsafe("123.45")
*
* // Create 42 (42 with scale 0)
* const integer = BigDecimal.make(42n, 0)
* integer // => BigDecimal.fromBigInt(42n)
* ```
*
* @see {@link fromBigInt} for constructing an integer decimal from a `bigint`
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const make$9 = (value, scale) => {
if (!Number.isSafeInteger(scale))
throw new RangeError(`Scale must be a safe integer, got ${scale}`);
const o = Object.create(BigDecimalProto);
o.value = value;
o.scale = scale;
return o;
};
const makeNormalized = (value, scale) => {
const o = make$9(value, scale);
o.normalized = o;
return o;
};
const bigint0$1 = /*#__PURE__*/ BigInt(0);
const bigint1$1 = /*#__PURE__*/ BigInt(1);
const bigint10$1 = /*#__PURE__*/ BigInt(10);
const zero$1 = /*#__PURE__*/ makeNormalized(bigint0$1, 0);
/**
* Normalizes a given `BigDecimal` by removing trailing zeros.
*
* **When to use**
*
* Use to canonicalize decimals that have equivalent values but different
* internal scales.
*
* **Example** (Normalizing trailing zeros)
*
* ```ts import.meta.vitest
* import { BigDecimal } from "effect"
*
* const decimal = BigDecimal.normalize(BigDecimal.fromStringUnsafe("123.00000"))
* const decimalStorage = [decimal.value, decimal.scale] // => [123n, 0]
*
* const largeDecimal = BigDecimal.normalize(BigDecimal.fromStringUnsafe("12300000"))
* const largeDecimalStorage = [largeDecimal.value, largeDecimal.scale] // => [123n, -5]
* ```
*
* @see {@link format} for rendering normalized decimals as strings
*
* @stability stable
* @category scaling
* @since 2.0.0
*/
const normalize = (self) => {
if (self.normalized === void 0) {
if (self.value === bigint0$1) self.normalized = zero$1;
else {
const digits = `${self.value}`;
let end = digits.length;
while (digits[end - 1] === "0") end--;
self.normalized = makeNormalized(
BigInt(digits.slice(0, end)),
self.scale - (digits.length - end),
);
}
}
return self.normalized;
};
const MAX_COMPARISON_SCALE_ALIGNMENT = 100;
const comparisonPowersOfTen = [bigint1$1];
const compareBigInt = (self, that) =>
self === that ? 0 : self < that ? -1 : 1;
const compareMagnitude = (self, that) => {
const selfDigits = `${self.value < bigint0$1 ? -self.value : self.value}`;
const thatDigits = `${that.value < bigint0$1 ? -that.value : that.value}`;
const exponentDifference =
BigInt(selfDigits.length - thatDigits.length) -
BigInt(self.scale) +
BigInt(that.scale);
if (exponentDifference !== bigint0$1)
return exponentDifference < bigint0$1 ? -1 : 1;
const length = Math.max(selfDigits.length, thatDigits.length);
return String$4(
selfDigits.padEnd(length, "0"),
thatDigits.padEnd(length, "0"),
);
};
const compare = (self, that) => {
if (self.scale === that.scale) return compareBigInt(self.value, that.value);
const selfSign = sign(self);
const thatSign = sign(that);
if (selfSign !== thatSign) return selfSign < thatSign ? -1 : 1;
if (selfSign === 0) return 0;
const scaleDifference = self.scale - that.scale;
const absoluteScaleDifference = Math.abs(scaleDifference);
if (absoluteScaleDifference > MAX_COMPARISON_SCALE_ALIGNMENT)
return selfSign === -1
? compareMagnitude(that, self)
: compareMagnitude(self, that);
const powerOfTen = (comparisonPowersOfTen[absoluteScaleDifference] ??=
bigint10$1 ** BigInt(absoluteScaleDifference));
return scaleDifference > 0
? compareBigInt(self.value, that.value * powerOfTen)
: compareBigInt(self.value * powerOfTen, that.value);
};
/**
* Determines the sign of a given `BigDecimal`.
*
* **When to use**
*
* Use to classify a `BigDecimal` as negative, zero, or positive.
*
* **Example** (Reading decimal signs)
*
* ```ts import.meta.vitest
* import { BigDecimal } from "effect"
*
* BigDecimal.sign(BigDecimal.fromStringUnsafe("-5")) // => -1
* BigDecimal.sign(BigDecimal.fromStringUnsafe("0")) // => 0
* BigDecimal.sign(BigDecimal.fromStringUnsafe("5")) // => 1
* ```
*
* @stability stable
* @category math
* @since 2.0.0
*/
const sign = (n) => (n.value === bigint0$1 ? 0 : n.value < bigint0$1 ? -1 : 1);
/**
* Formats a `BigDecimal` as a string.
*
* **When to use**
*
* Use to render a `BigDecimal` as plain decimal text when possible.
*
* **Details**
*
* The value is normalized before formatting. Scientific notation is used when
* the absolute value of the normalized scale is at least `16`; otherwise plain
* decimal notation is used.
*
* **Example** (Formatting decimals)
*
* ```ts import.meta.vitest
* import { BigDecimal } from "effect"
*
* BigDecimal.format(BigDecimal.fromStringUnsafe("-5")) // => "-5"
* BigDecimal.format(BigDecimal.fromStringUnsafe("123.456")) // => "123.456"
* BigDecimal.format(BigDecimal.fromStringUnsafe("-0.00000123")) // => "-0.00000123"
* ```
*
* @see {@link toExponential} for always rendering scientific notation
*
* @stability stable
* @category converting
* @since 2.0.0
*/
const format = (n) => {
const normalized = normalize(n);
if (Math.abs(normalized.scale) >= 16) return toExponential(normalized);
const negative = normalized.value < bigint0$1;
const absolute = `${negative ? -normalized.value : normalized.value}`;
const digits =
normalized.scale > 0
? absolute.padStart(normalized.scale + 1, "0")
: absolute.padEnd(absolute.length - normalized.scale, "0");
const point = digits.length - normalized.scale;
const complete =
normalized.scale > 0
? `${digits.slice(0, point)}.${digits.slice(point)}`
: digits;
return negative ? `-${complete}` : complete;
};
/**
* Formats a given `BigDecimal` as a `string` in scientific notation.
*
* **When to use**
*
* Use to render a `BigDecimal` in scientific notation.
*
* **Example** (Formatting decimals exponentially)
*
* ```ts import.meta.vitest
* import { BigDecimal } from "effect"
*
* BigDecimal.toExponential(BigDecimal.make(123456n, -5)) // => "1.23456e+10"
* ```
*
* @see {@link format} for plain decimal formatting when possible
*
* @stability stable
* @category converting
* @since 3.11.0
*/
const toExponential = (n) => {
if (isZero(n)) return "0e+0";
const normalized = normalize(n);
const digits = `${normalized.value}`;
const point = normalized.value < bigint0$1 ? 2 : 1;
const head = digits.slice(0, point);
const tail = digits.slice(point);
const exp = tail.length - normalized.scale;
return `${head}${tail === "" ? "" : `.${tail}`}e${exp >= 0 ? "+" : ""}${exp}`;
};
/**
* Checks whether a given `BigDecimal` is `0`.
*
* **When to use**
*
* Use to test whether a `BigDecimal` is exactly zero.
*
* **Example** (Checking zero decimals)
*
* ```ts import.meta.vitest
* import { BigDecimal } from "effect"
*
* BigDecimal.isZero(BigDecimal.fromStringUnsafe("0")) // => true
* BigDecimal.isZero(BigDecimal.fromStringUnsafe("1")) // => false
* ```
*
* @stability stable
* @category predicates
* @since 2.0.0
*/
const isZero = (n) => n.value === bigint0$1;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Effectable.js
/**
* Create a low-level `Effect` prototype.
*
* **When to use**
*
* Use when you need to create a custom Effect-like value without extending a
* class, by providing a label and an evaluate function that receives the
* current fiber.
*
* **Details**
*
* When the effect is evaluated, it calls `evaluate` with the current fiber.
*
* @see {@link Class} for a class-based approach to defining custom Effect values
* @see {@link Mixin} for wrapping an existing class constructor
*
* @stability stable
* @category prototypes
* @since 4.0.0
*/
const Prototype = (options) =>
makePrimitiveProto({
op: options.label,
[evaluate]: options.evaluate,
});
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Context.js
/**
* Runtime type identifier attached to `Context` service keys and used by
* `isKey` to recognize them.
*
* @stability stable
* @category type IDs
* @since 4.0.0
*/
const ServiceTypeId = "~effect/Context/Service";
/**
* Creates a `Context` service key.
*
* **When to use**
*
* Use when you need to define a context service key for a dependency that must
* be provided by the surrounding context.
*
* **Details**
*
* Call `Context.Service("Key")` for a function-style key, or use the two-stage
* form `Context.Service<Self, Shape>()("Key")` for class-style service
* declarations. The returned key can be yielded as an Effect and passed to
* `Context.make`, `Context.add`, and the Context getter functions.
*
* **Gotchas**
*
* The string key is the runtime identity of the service. Reusing the same key
* string for unrelated services makes them occupy the same slot in a
* `Context`.
*
* **Example** (Creating service keys)
*
* ```ts import.meta.vitest
* import { Context } from "effect"
*
* // Create a simple service
* const Database = Context.Service<{
* query: (sql: string) => string
* }>("Database")
*
* // Create a service class
* class Config extends Context.Service<Config, {
* port: number
* }>()("Config") {}
*
* // Use the services to create contexts
* const db = Context.make(Database, {
* query: (sql) => `Result: ${sql}`
* })
* const config = Context.make(Config, { port: 8080 })
* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1"
* Context.get(config, Config).port // => 8080
* ```
*
* @see {@link Reference} for service keys with default values
*
* @stability stable
* @category services
* @since 4.0.0
*/
const Service = function () {
function KeyClass() {}
const self = KeyClass;
Object.setPrototypeOf(self, ServiceProto);
const init = (key, options) => {
self.key = key;
if (options?.defaultValue) {
self[ReferenceTypeId] = ReferenceTypeId;
self.defaultValue = options.defaultValue;
}
if (options?.make) self.make = options.make;
if (options?.fiberCached) cacheKeys.add(key);
return self;
};
return arguments.length > 0 ? init(arguments[0], arguments[1]) : init;
};
const ServiceProto = {
[ServiceTypeId]: ServiceTypeId,
.../*#__PURE__*/ Prototype({
label: "Service",
evaluate(fiber) {
return exitSucceed(get(fiber.context, this));
},
}),
toJSON() {
return {
_id: "Service",
key: this.key,
};
},
of(self) {
return self;
},
context(self) {
return make$8(this, self);
},
use(f) {
return withFiber((fiber) => f(get(fiber.context, this)));
},
useSync(f) {
return withFiber((fiber) => exitSucceed(f(get(fiber.context, this))));
},
};
const cacheKeys = /*#__PURE__*/ new Set();
const ReferenceTypeId = "~effect/Context/Reference";
const TypeId$12 = "~effect/Context";
const MaxDepth = 8;
const FlattenAfterBaseHits = 8;
const makeImpl = (cacheRoot, base, overlay, depth) => {
const self = Object.create(Proto$5);
self.cacheRoot = cacheRoot ?? self;
self.base = base;
self.overlay = overlay;
self.depth = depth;
self._flat = void 0;
self.baseHits = 0;
return self;
};
const applyOverlays = (map, overlay) => {
if (!overlay) return;
applyOverlays(map, overlay.parent);
map.set(overlay.key, overlay.value);
};
const flatten = (self) => {
if (self._flat) return self._flat;
if (!self.overlay) return (self._flat = self.base);
const map = new Map(self.base);
applyOverlays(map, self.overlay);
return (self._flat = map);
};
const notFound = /*#__PURE__*/ Symbol();
const lookup = (self, key) => {
const impl = self;
for (let overlay = impl.overlay; overlay; overlay = overlay.parent)
if (overlay.key === key) return overlay.value;
const value = impl.base.get(key);
if (value === void 0 && !impl.base.has(key)) return notFound;
if (
impl.overlay &&
++impl.baseHits >= impl.base.size &&
impl.baseHits >= FlattenAfterBaseHits
) {
impl.base = flatten(impl);
impl.overlay = void 0;
impl.depth = 0;
}
return value;
};
/**
* Creates a `Context` from an existing service map.
*
* **When to use**
*
* Use when constructing a low-level `Context` from a trusted map whose lifecycle
* you control.
*
* **Gotchas**
*
* The provided map is retained without copying and must not be mutated after
* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context
* construction.
*
* **Example** (Creating a context from a map)
*
* ```ts import.meta.vitest
* import { Context } from "effect"
*
* // Create a context from a Map (unsafe)
* const map = new Map([
* ["Logger", { log: (_msg: string) => {} }]
* ])
*
* const context = Context.makeUnsafe(map)
* context.mapUnsafe.size // => 1
* ```
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const makeUnsafe$2 = (mapUnsafe) => makeImpl(void 0, mapUnsafe, void 0, 0);
const Proto$5 = {
get mapUnsafe() {
return flatten(this);
},
...PipeInspectableProto,
[TypeId$12]: { _Services: (_) => _ },
toJSON() {
return {
_id: "Context",
services: Array.from(this.mapUnsafe).map(([key, value]) => ({
key,
value,
})),
};
},
[symbol](that) {
if (!isContext(that)) return false;
const self = this.mapUnsafe;
const other = that.mapUnsafe;
if (self.size !== other.size) return false;
for (const [key, value] of self)
if (!other.has(key) || !equals$1(value, other.get(key))) return false;
return true;
},
[symbol$1]() {
return number$1(this.mapUnsafe.size);
},
};
/** @internal */
const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot;
/**
* Checks whether the provided argument is a `Context`.
*
* **When to use**
*
* Use to narrow an unknown value before passing it to APIs that require a
* `Context`.
*
* **Details**
*
* This checks the runtime `Context` marker and does not inspect which services
* the context contains.
*
* **Gotchas**
*
* This guard only proves that the value is a `Context`; it does not prove that
* any specific service is present.
*
* **Example** (Checking for contexts)
*
* ```ts import.meta.vitest
* import { Context } from "effect"
* Context.isContext(Context.empty()) // => true
* ```
*
* @see {@link isKey} for checking service keys
* @see {@link isReference} for checking references with defaults
*
* @stability stable
* @category guards
* @since 2.0.0
*/
const isContext = (u) => hasProperty(u, TypeId$12);
/**
* Checks whether the provided argument is a `Reference`.
*
* **Example** (Checking for references)
*
* ```ts import.meta.vitest
* import { Context } from "effect"
*
* const LoggerRef = Context.Reference("Logger", {
* defaultValue: () => ({ log: (_msg: string) => {} })
* })
*
* Context.isReference(LoggerRef) // => true
* Context.isReference(Context.Service("Key")) // => false
* ```
*
* @stability stable
* @category guards
* @since 3.11.0
*/
const isReference = (u) => !!u[ReferenceTypeId];
/**
* Returns an empty `Context`.
*
* **Example** (Creating an empty context)
*
* ```ts import.meta.vitest
* import { Context } from "effect"
* Context.empty().mapUnsafe.size // => 0
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const empty = () => emptyContext;
const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map());
/**
* Creates a new `Context` with a single service associated to the key.
*
* **Example** (Creating a context with one service)
*
* ```ts import.meta.vitest
* import { Context } from "effect"
*
* const Port = Context.Service<{ PORT: number }>("Port")
*
* const context = Context.make(Port, { PORT: 8080 })
*
* Context.get(context, Port).PORT // => 8080
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const make$8 = (key, service) =>
makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]]));
/**
* Adds a service to a given `Context`.
*
* **When to use**
*
* Use when you need to store a known service value in a `Context`.
*
* **Details**
*
* If the context already contains the same service key, the new service
* replaces the previous one.
*
* **Example** (Adding a service to a context)
*
* ```ts import.meta.vitest
* import { Context, pipe } from "effect"
*
* const Port = Context.Service<{ PORT: number }>("Port")
* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout")
*
* const someContext = Context.make(Port, { PORT: 8080 })
*
* const context = pipe(
* someContext,
* Context.add(Timeout, { TIMEOUT: 5000 })
* )
*
* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT]
* values // => [8080, 5000]
* ```
*
* @see {@link addOrOmit} for adding or removing a service from an `Option`
*
* @stability stable
* @category combining
* @since 2.0.0
*/
const add = /*#__PURE__*/ dual(3, (self, key, service) =>
addUnsafe(self, key.key, service),
);
/**
* Adds a service by key to a given `Context` using a string key.
*
* @stability stable
* @category combining
* @since 4.0.0
*/
const addUnsafe = (self, key, service) => {
const impl = self;
const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot;
if (impl.depth >= MaxDepth) {
const map = new Map(impl._flat ?? impl.base);
if (!impl._flat) applyOverlays(map, impl.overlay);
map.set(key, service);
return makeImpl(cacheRoot, map, void 0, 0);
}
return makeImpl(
cacheRoot,
impl.base,
{
key,
value: service,
parent: impl.overlay,
},
impl.depth + 1,
);
};
/** @internal */
const getOrUndefinedUnsafe = (self, key) => {
const value = lookup(self, key);
return value === notFound ? void 0 : value;
};
/**
* Gets a service from the context that corresponds to the given key.
*
* **When to use**
*
* Use when you need type-checked access to a service already included in the
* context type.
*
* **Example** (Getting a service from a context)
*
* ```ts import.meta.vitest
* import { Context, pipe } from "effect"
*
* const Port = Context.Service<{ PORT: number }>("Port")
* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout")
*
* const context = pipe(
* Context.make(Port, { PORT: 8080 }),
* Context.add(Timeout, { TIMEOUT: 5000 })
* )
*
* Context.get(context, Timeout).TIMEOUT // => 5000
* ```
*
* @see {@link getOption} for optional service access
* @see {@link getOrElse} for fallback values
*
* @stability stable
* @category getters
* @since 2.0.0
*/
const get = /* @__PURE__ */ dual(2, (self, service) => {
const value = lookup(self, service.key);
if (value === notFound) {
if (isReference(service)) return getDefaultValue(service);
throw serviceNotFoundError(service);
}
return value;
});
const defaultValueCacheKey = "~effect/Context/defaultValue";
const getDefaultValue = (ref) => {
if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey];
return (ref[defaultValueCacheKey] = ref.defaultValue());
};
const serviceNotFoundError = (service) => {
const error = /* @__PURE__ */ new Error(
`Service not found${service.key ? `: ${String(service.key)}` : ""}`,
);
if (error.stack) {
const lines = error.stack.split("\n");
lines.splice(1, 3);
error.stack = lines.join("\n");
}
return error;
};
/**
* Creates a context key with a default value.
*
* **When to use**
*
* Use when you need to define a context key with a lazily computed default
* value.
*
* **Details**
*
* `Context.Reference` allows you to create a key that can hold a value. You
* can provide a default value for the service, which will automatically be used
* when the context is accessed, or override it with a custom implementation
* when needed. The default value is computed lazily and cached on the
* reference.
*
* **Example** (Creating references with default values)
*
* ```ts import.meta.vitest
* import { Context } from "effect"
*
* // Create a reference with a default value
* const messages: Array<string> = []
* const LoggerRef = Context.Reference("Logger", {
* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) })
* })
*
* // The reference provides the default value when accessed from an empty context
* const context = Context.empty()
* const logger = Context.get(context, LoggerRef)
*
* // You can also override the default value
* const customContext = Context.make(LoggerRef, {
* log: (msg: string) => messages.push(`Custom: ${msg}`)
* })
* const customLogger = Context.get(customContext, LoggerRef)
* logger.log("default")
* customLogger.log("message")
* messages // => ["Default: default", "Custom: message"]
* ```
*
* @see {@link Service} for required services without default values
*
* @stability stable
* @category services
* @since 3.11.0
*/
const Reference = Service;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Duration.js
const TypeId$11 = "~effect/Duration";
const bigint0 = /*#__PURE__*/ BigInt(0);
const bigint1 = /*#__PURE__*/ BigInt(1);
const bigint2 = /*#__PURE__*/ BigInt(2);
const bigint10 = /*#__PURE__*/ BigInt(10);
const bigint1e3 = /*#__PURE__*/ BigInt(1e3);
const bigint1e6 = /*#__PURE__*/ BigInt(1e6);
const roundTiesAwayFromZero = (input) =>
BigInt(Math.sign(input) * Math.round(Math.abs(input)));
const roundMillisToNanos = (millis) =>
Number.isInteger(millis)
? BigInt(millis) * bigint1e6
: roundTiesAwayFromZero(millis * 1e6);
const fromNanosNumber = (nanos) =>
make$7(Number.isFinite(nanos) ? roundTiesAwayFromZero(nanos) : nanos);
const parseNanos = (input, scale) => {
const decimalIndex = input.indexOf(".");
if (decimalIndex === -1) return BigInt(input) * scale;
const isNegative = input[0] === "-";
const fractional = input.slice(decimalIndex + 1);
const fractionalScale = bigint10 ** BigInt(fractional.length);
const scaled =
(BigInt(input.slice(isNegative ? 1 : 0, decimalIndex)) * fractionalScale +
BigInt(fractional)) *
scale;
return divideTiesAwayFromZero(isNegative ? -scaled : scaled, fractionalScale);
};
const divideTiesAwayFromZero = (numerator, denominator) => {
const absolute = numerator < bigint0 ? -numerator : numerator;
const rounded =
absolute / denominator +
((absolute % denominator) * bigint2 >= denominator ? bigint1 : bigint0);
return numerator < bigint0 ? -rounded : rounded;
};
const DURATION_REGEXP =
/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/;
/**
* Decodes a `Duration.Input` into a `Duration`.
*
* **When to use**
*
* Use when the input has already been validated or comes from a trusted source
* and throwing is acceptable for invalid duration syntax.
*
* **Gotchas**
*
* If the input is not a valid `Duration.Input`, it throws an error.
*
* **Example** (Decoding duration inputs)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.fromInputUnsafe(1000) // => Duration.millis(1000)
* Duration.fromInputUnsafe("5 seconds") // => Duration.seconds(5)
* Duration.fromInputUnsafe("Infinity") // => Duration.infinity
* Duration.fromInputUnsafe([2, 500_000_000]) // => Duration.nanos(2_500_000_000n)
* ```
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const fromInputUnsafe = (input) => {
switch (typeof input) {
case "number":
return millis(input);
case "bigint":
return nanos(input);
case "string": {
if (input === "Infinity") return infinity;
if (input === "-Infinity") return negativeInfinity;
const match = DURATION_REGEXP.exec(input);
if (!match) break;
const [_, valueStr, unit] = match;
if (unit === "nano" || unit === "nanos")
return nanos(parseNanos(valueStr, bigint1));
if (unit === "micro" || unit === "micros")
return nanos(parseNanos(valueStr, bigint1e3));
const value = Number(valueStr);
switch (unit) {
case "milli":
case "millis":
return millis(value);
case "second":
case "seconds":
return seconds(value);
case "minute":
case "minutes":
return minutes(value);
case "hour":
case "hours":
return hours(value);
case "day":
case "days":
return days(value);
case "week":
case "weeks":
return weeks(value);
}
break;
}
case "object": {
if (input === null) break;
if (TypeId$11 in input) return input;
if (Array.isArray(input)) {
if (input.length !== 2 || !input.every(isNumber))
return invalid$1(input);
if (Number.isNaN(input[0]) || Number.isNaN(input[1])) return zero;
if (input[0] === -Infinity || input[1] === -Infinity)
return negativeInfinity;
if (input[0] === Infinity || input[1] === Infinity) return infinity;
return fromNanosNumber(input[0] * 1e9 + input[1]);
}
const obj = input;
let millis = 0;
if (obj.weeks) millis += obj.weeks * 6048e5;
if (obj.days) millis += obj.days * 864e5;
if (obj.hours) millis += obj.hours * 36e5;
if (obj.minutes) millis += obj.minutes * 6e4;
if (obj.seconds) millis += obj.seconds * 1e3;
if (obj.milliseconds) millis += obj.milliseconds;
if (!obj.microseconds && !obj.nanoseconds) return make$7(millis);
return fromNanosNumber(
millis * 1e6 + (obj.microseconds ?? 0) * 1e3 + (obj.nanoseconds ?? 0),
);
}
}
return invalid$1(input);
};
const invalid$1 = (input) => {
throw new Error(`Invalid Input: ${input}`);
};
const zeroDurationValue = {
_tag: "Millis",
millis: 0,
};
const infinityDurationValue = { _tag: "Infinity" };
const negativeInfinityDurationValue = { _tag: "NegativeInfinity" };
const DurationProto = {
[TypeId$11]: TypeId$11,
[symbol$1]() {
switch (this.value._tag) {
case "Millis":
return hash(roundMillisToNanos(this.value.millis));
case "Nanos":
return hash(this.value.nanos);
default:
return structure(this.value);
}
},
[symbol](that) {
return isDuration(that) && equals(this, that);
},
toString() {
switch (this.value._tag) {
case "Infinity":
return "Infinity";
case "NegativeInfinity":
return "-Infinity";
case "Nanos":
return `${this.value.nanos} nanos`;
case "Millis":
return `${this.value.millis} millis`;
}
},
toJSON() {
switch (this.value._tag) {
case "Millis":
return {
_id: "Duration",
_tag: "Millis",
millis: this.value.millis,
};
case "Nanos":
return {
_id: "Duration",
_tag: "Nanos",
nanos: String(this.value.nanos),
};
case "Infinity":
return {
_id: "Duration",
_tag: "Infinity",
};
case "NegativeInfinity":
return {
_id: "Duration",
_tag: "NegativeInfinity",
};
}
},
[NodeInspectSymbol]() {
return this.toJSON();
},
pipe() {
return pipeArguments(this, arguments);
},
};
const make$7 = (input) => {
const duration = Object.create(DurationProto);
if (typeof input === "number") {
if (isNaN(input) || input === 0 || Object.is(input, -0))
duration.value = zeroDurationValue;
else if (!Number.isFinite(input))
duration.value =
input > 0 ? infinityDurationValue : negativeInfinityDurationValue;
else if (!Number.isInteger(input))
duration.value = {
_tag: "Nanos",
nanos: roundMillisToNanos(input),
};
else
duration.value = {
_tag: "Millis",
millis: input,
};
} else if (input === bigint0) duration.value = zeroDurationValue;
else
duration.value = {
_tag: "Nanos",
nanos: input,
};
return duration;
};
/**
* Checks whether a value is a Duration.
*
* **Example** (Checking for durations)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.isDuration(Duration.seconds(1)) // => true
* Duration.isDuration(1000) // => false
* ```
*
* @stability stable
* @category guards
* @since 2.0.0
*/
const isDuration = (u) => hasProperty(u, TypeId$11);
/**
* A Duration representing zero time.
*
* **Example** (Referencing the zero duration)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.zero) // => 0
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const zero = /*#__PURE__*/ make$7(0);
/**
* A Duration representing infinite time.
*
* **Example** (Referencing infinite duration)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.infinity) // => Infinity
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const infinity = /*#__PURE__*/ make$7(Infinity);
/**
* A Duration representing negative infinite time.
*
* **Example** (Referencing negative infinite duration)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.negativeInfinity) // => -Infinity
* ```
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const negativeInfinity = /*#__PURE__*/ make$7(-Infinity);
/**
* Creates a Duration from nanoseconds.
*
* **Example** (Creating durations from nanoseconds)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.nanos(500_000_000n) // => Duration.nanos(500_000_000n)
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const nanos = (nanos) => make$7(nanos);
/**
* Creates a Duration from milliseconds.
*
* **Example** (Creating durations from milliseconds)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.millis(1000)) // => 1000
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const millis = (millis) => make$7(millis);
/**
* Creates a Duration from seconds.
*
* **Example** (Creating durations from seconds)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.seconds(30)) // => 30_000
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const seconds = (seconds) => make$7(seconds * 1e3);
/**
* Creates a Duration from minutes.
*
* **Example** (Creating durations from minutes)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.minutes(5)) // => 300_000
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const minutes = (minutes) => make$7(minutes * 6e4);
/**
* Creates a Duration from hours.
*
* **Example** (Creating durations from hours)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.hours(2)) // => 7_200_000
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const hours = (hours) => make$7(hours * 36e5);
/**
* Creates a Duration from days.
*
* **Example** (Creating durations from days)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.days(1)) // => 86_400_000
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const days = (days) => make$7(days * 864e5);
/**
* Creates a Duration from weeks.
*
* **Example** (Creating durations from weeks)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.weeks(1)) // => 604_800_000
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const weeks = (weeks) => make$7(weeks * 6048e5);
/**
* Gets the duration in nanoseconds as a bigint.
*
* **When to use**
*
* Use when the duration is known to be finite and you need the nanosecond value
* as a `bigint`.
*
* **Details**
*
* Millisecond-backed fractional durations are rounded to the nearest
* nanosecond, with ties away from zero.
*
* **Gotchas**
*
* If the duration is infinite, it throws an error.
*
* **Example** (Reading nanoseconds unsafely)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toNanosUnsafe(Duration.seconds(2)) // => 2_000_000_000n
*
* // Duration.toNanosUnsafe(Duration.infinity)
* // throws Error: "Cannot convert infinite duration to nanos"
* ```
*
* @stability stable
* @category getters
* @since 4.0.0
*/
const toNanosUnsafe = (input) => {
const self = fromInputUnsafe(input);
switch (self.value._tag) {
case "Infinity":
case "NegativeInfinity":
throw new Error("Cannot convert infinite duration to nanos");
case "Nanos":
return self.value.nanos;
case "Millis":
return roundMillisToNanos(self.value.millis);
}
};
/**
* Pattern matches on two `Duration`s, providing handlers that receive both values.
*
* **Example** (Pattern matching on duration pairs)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.matchPair(Duration.seconds(3), Duration.seconds(2), {
* onMillis: (a, b) => a + b,
* onNanos: (a, b) => Number(a + b),
* onInfinity: () => Infinity
* }) // => 5000
* ```
*
* @stability stable
* @category pattern matching
* @since 4.0.0
*/
const matchPair = /*#__PURE__*/ dual(3, (self, that, options) => {
if (
self.value._tag === "Infinity" ||
self.value._tag === "NegativeInfinity" ||
that.value._tag === "Infinity" ||
that.value._tag === "NegativeInfinity"
)
return options.onInfinity(self, that);
if (self.value._tag === "Millis")
return that.value._tag === "Millis"
? options.onMillis(self.value.millis, that.value.millis)
: options.onNanos(toNanosUnsafe(self), that.value.nanos);
else return options.onNanos(self.value.nanos, toNanosUnsafe(that));
});
/**
* Provides an `Equivalence` instance for comparing `Duration` values.
*
* **Example** (Comparing durations for equivalence)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.Equivalence(Duration.seconds(5), Duration.millis(5000)) // => true
* ```
*
* @stability stable
* @category instances
* @since 2.0.0
*/
const Equivalence$2 = (self, that) =>
matchPair(self, that, {
onMillis: (self, that) => self === that,
onNanos: (self, that) => self === that,
onInfinity: (self, that) => self.value._tag === that.value._tag,
});
/**
* Checks whether two Durations are equal.
*
* **Example** (Checking duration equality)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.equals(Duration.seconds(5), Duration.millis(5000)) // => true
* ```
*
* @stability stable
* @category predicates
* @since 2.0.0
*/
const equals = /*#__PURE__*/ dual(2, (self, that) => Equivalence$2(self, that));
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Scheduler.js
/**
* Controls how runnable Effect fiber tasks are dispatched.
*
* A scheduler decides how tasks are queued, when queued tasks run, and when a
* fiber should pause so other work can continue. This module includes the
* scheduler service reference, the default `MixedScheduler`, dispatcher types
* for queued tasks, and references for tuning or disabling automatic scheduler
* yields.
*
* @stability stable
* @since 2.0.0
*/
/**
* Context reference for the scheduler used by the Effect runtime.
*
* **When to use**
*
* Use when you need to replace scheduling behavior globally in tests or runtime
* setup, such as forcing deterministic task dispatch.
*
* **Details**
*
* The default value creates a `MixedScheduler`. Provide this service to
* customize execution mode, task dispatching, or yield behavior.
*
* @stability stable
* @category services
* @since 2.0.0
*/
const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", {
fiberCached: true,
defaultValue: () => new MixedScheduler(),
});
const setMicrotask = (f) => {
let cancelled = false;
Promise.resolve().then(() => {
if (!cancelled) f();
});
return () => {
cancelled = true;
};
};
const setTimer =
"setImmediate" in globalThis
? (f) => {
const timer = globalThis.setImmediate(f);
return () => globalThis.clearImmediate(timer);
}
: (f) => {
const timer = setTimeout(f, 0);
return () => clearTimeout(timer);
};
const setImmediate = (f) => {
try {
return setTimer(f);
} catch {
return setMicrotask(f);
}
};
var PriorityBuckets = class {
buckets = [];
scheduleTask(task, priority) {
const buckets = this.buckets;
const len = buckets.length;
let bucket;
let index = 0;
for (; index < len; index++) {
if (buckets[index][0] > priority) break;
bucket = buckets[index];
}
if (bucket && bucket[0] === priority) bucket[1].push(task);
else if (index === len) buckets.push([priority, [task]]);
else buckets.splice(index, 0, [priority, [task]]);
}
drain() {
const buckets = this.buckets;
this.buckets = [];
return buckets;
}
};
/**
* Provides a scheduler implementation that batches queued tasks and dispatches them by
* priority.
*
* **When to use**
*
* Use when you need the default runtime scheduler directly, including a
* scheduler that batches queued work by priority and preserves FIFO order within
* each priority.
*
* **Details**
*
* `MixedScheduler` supports synchronous and asynchronous execution modes, uses
* operation counts to decide when fibers should yield, and is the default
* scheduler implementation.
*
* **Gotchas**
*
* On Cloudflare Workers, request-owned scheduler timers can be discarded,
* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the
* whole application; see `HttpRouter.toWebHandler` for a recipe.
* Sync mode does not yield to the event loop: CPU-heavy work delays other
* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix
* request-owned timers (such as `Effect.sleep`) or request-bound async contexts.
*
* @stability stable
* @category models
* @since 2.0.0
*/
var MixedScheduler = class {
executionMode;
setImmediate;
constructor(executionMode = "async", setImmediateFn) {
this.executionMode = executionMode;
this.setImmediate =
setImmediateFn ??
(executionMode === "sync" ? setMicrotask : setImmediate);
}
/**
* Returns whether the fiber has reached its operation budget and should yield.
*
* **When to use**
*
* Use to decide whether a fiber should yield after consuming its current
* operation budget.
*
* @since 2.0.0
*/
shouldYield(fiber) {
return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield;
}
/**
* Creates a dispatcher that schedules work through this scheduler.
*
* **When to use**
*
* Use when you need a standalone dispatcher from a scheduler instance, for
* example in tests that enqueue tasks and then flush them deterministically.
*
* @since 4.0.0
*/
makeDispatcher() {
return new MixedSchedulerDispatcher(this.setImmediate);
}
};
var MixedSchedulerDispatcher = class {
tasks = /*#__PURE__*/ new PriorityBuckets();
running = void 0;
setImmediate;
constructor(setImmediateFn = setImmediate) {
this.setImmediate = setImmediateFn;
}
/**
* @since 2.0.0
*/
scheduleTask(task, priority) {
this.tasks.scheduleTask(task, priority);
if (this.running === void 0)
this.running = this.setImmediate(this.afterScheduled);
}
/**
* @since 2.0.0
*/
afterScheduled = () => {
this.running = void 0;
this.runTasks();
};
/**
* @since 2.0.0
*/
runTasks() {
const buckets = this.tasks.drain();
for (let i = 0; i < buckets.length; i++) {
const toRun = buckets[i][1];
for (let j = 0; j < toRun.length; j++) toRun[j]();
}
}
/**
* @since 2.0.0
*/
flush() {
while (this.tasks.buckets.length > 0) {
if (this.running !== void 0) {
this.running();
this.running = void 0;
}
this.runTasks();
}
}
};
/**
* Context reference that controls the maximum number of operations a fiber
* can perform before yielding control back to the scheduler.
*
* **When to use**
*
* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler
* operation budget that triggers a yield.
*
* **Details**
*
* The default value is `2048` operations, which balances performance and
* fairness by helping prevent long-running fibers from monopolizing the
* execution thread.
*
* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget
*
* @stability stable
* @category services
* @since 4.0.0
*/
const MaxOpsBeforeYield = /*#__PURE__*/ Reference(
"effect/Scheduler/MaxOpsBeforeYield",
{
fiberCached: true,
defaultValue: () => 2048,
},
);
/**
* Context reference that controls whether the runtime should bypass scheduler
* yield checks. When set to `true`, the fiber run loop won't call
* `Scheduler.shouldYield`.
*
* **When to use**
*
* Use to bypass scheduler yield checks for controlled runtime workloads where
* cooperative yielding should be disabled.
*
* **Gotchas**
*
* Setting this reference to `true` can let long-running fibers monopolize the
* JavaScript thread.
*
* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks
* @see {@link Scheduler} for providing custom scheduler yield behavior
*
* @stability stable
* @category services
* @since 4.0.0
*/
const PreventSchedulerYield = /*#__PURE__*/ Reference(
"effect/Scheduler/PreventSchedulerYield",
{
fiberCached: true,
defaultValue: () => false,
},
);
/**
* Creates a tagged error class with a `_tag` discriminator.
*
* **When to use**
*
* Use when you need domain errors with discriminated-union handling.
*
* **Details**
*
* Like {@link Error}, but instances also carry a `readonly _tag` property,
* enabling `Effect.catchTag` and `Effect.catchTags` for tag-based recovery.
* The `_tag` is excluded from the constructor argument. Yielding an instance
* inside `Effect.gen` fails the effect with this error.
*
* **Example** (Recovering by tag)
*
* ```ts import.meta.vitest
* import { Data, Effect } from "effect"
*
* class NotFound extends Data.TaggedError("NotFound")<{
* readonly resource: string
* }> {}
*
* class Forbidden extends Data.TaggedError("Forbidden")<{
* readonly reason: string
* }> {}
*
* const program = Effect.gen(function*() {
* return yield* new NotFound({ resource: "/users/42" })
* })
*
* const recovered = program.pipe(
* Effect.catchTag("NotFound", (e) =>
* Effect.succeed(`missing: ${e.resource}`))
* )
*
* await Effect.runPromise(recovered) // => "missing: /users/42"
* ```
*
* @see {@link Error} — without a `_tag`
* @see {@link TaggedClass} — tagged class that is not an error
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const TaggedError = TaggedError$1;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Tracer.js
/**
* Defines the string key for the parent-span context service.
*
* **When to use**
*
* Use when you need the raw context key for parent span lookup in lower-level
* tracing code.
*
* **Example** (Reading the parent span key)
*
* ```ts import.meta.vitest
* import { Tracer } from "effect"
*
* // The key used to identify parent spans in the context
* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan"
* ```
*
* @stability stable
* @category constants
* @since 4.0.0
*/
const ParentSpanKey = "effect/Tracer/ParentSpan";
/**
* Defines the string key for the active tracer context reference.
*
* **When to use**
*
* Use when you need the raw context key for active tracer lookup in lower-level
* tracing code.
*
* @stability stable
* @category constants
* @since 4.0.0
*/
const TracerKey = "effect/Tracer";
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/metric.js
/** @internal */
const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics";
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/references.js
/** @internal */
const CurrentStackFrame = /*#__PURE__*/ Reference(
"effect/References/CurrentStackFrame",
{
fiberCached: true,
defaultValue: constUndefined,
},
);
/** @internal */
const TracerEnabled = /*#__PURE__*/ Reference(
"effect/References/TracerEnabled",
{
fiberCached: true,
defaultValue: constTrue,
},
);
/** @internal */
const CurrentLogLevel = /*#__PURE__*/ Reference(
"effect/References/CurrentLogLevel",
{
fiberCached: true,
defaultValue: () => "Info",
},
);
/** @internal */
const MinimumLogLevel = /*#__PURE__*/ Reference(
"effect/References/MinimumLogLevel",
{
fiberCached: true,
defaultValue: () => "Info",
},
);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/effect.js
/** @internal */
var Interrupt = class extends ReasonBase {
constructor(fiberId, annotations = constEmptyAnnotations) {
super("Interrupt", annotations, "Interrupted");
this.fiberId = fiberId;
}
toString() {
return `Interrupt(${this.fiberId})`;
}
toJSON() {
return {
_tag: "Interrupt",
fiberId: this.fiberId,
};
}
[symbol](that) {
return (
isInterruptReason(that) &&
this.fiberId === that.fiberId &&
this.annotations === that.annotations
);
}
[symbol$1]() {
return string$1(`${this._tag}:${this.fiberId}`);
}
};
/** @internal */
const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]);
/** @internal */
const hasInterrupts = (self) => self.reasons.some(isInterruptReason);
/** @internal */
const causeMap = /*#__PURE__*/ dual(2, (self, f) => {
let hasFail = false;
const failures = self.reasons.map((failure) => {
if (isFailReason$1(failure)) {
hasFail = true;
return new Fail(f(failure.error), failure.annotations);
}
return failure;
});
return hasFail ? causeFromReasons(failures) : self;
});
/** @internal */
const FiberTypeId = "~effect/Fiber";
const fiberVariance = {
_A: identity,
_E: identity,
};
const fiberIdStore = { id: 0 };
const AsyncResource = /*#__PURE__*/ (() => {
try {
return globalThis.process?.getBuiltinModule?.("node:async_hooks")
?.AsyncResource;
} catch {
return;
}
})();
const captureAsyncContext = () =>
AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber");
/** @internal */
const getCurrentFiber = () => globalThis[currentFiberTypeId];
/** @internal */
var FiberImpl = class {
constructor(context, interruptible = true) {
this.setContext(context);
this.id = ++fiberIdStore.id;
this.currentOpCount = 0;
this.interruptible = interruptible;
this._stack = [];
this._observers = void 0;
this._exit = void 0;
this._children = void 0;
this._interruptedCause = void 0;
this._yielded = void 0;
this._running = false;
this._deferredInterrupt = false;
this._parent = void 0;
this._asyncContext = void 0;
this.cache.runtimeMetrics?.recordFiberStart(this.context);
}
get [FiberTypeId]() {
return fiberVariance;
}
get currentDispatcher() {
return (this._dispatcher ??= this.cache.scheduler.makeDispatcher());
}
getRef(ref) {
return get(this.context, ref);
}
addObserver(cb) {
if (this._exit) {
cb(this._exit);
return constVoid;
}
if (this._observers === void 0) this._observers = [cb];
else this._observers.push(cb);
return () => this.removeObserver(cb);
}
removeObserver(cb) {
if (this._exit || this._observers === void 0) return;
const index = this._observers.indexOf(cb);
if (index >= 0) this._observers.splice(index, 1);
}
interruptUnsafe(fiberId, annotations) {
if (this._exit) return;
let cause = causeInterrupt(fiberId);
if (this.cache.stackFrame)
cause = causeAnnotate(
cause,
make$8(StackTraceKey, this.cache.stackFrame),
);
if (annotations) cause = causeAnnotate(cause, annotations);
this._interruptedCause = this._interruptedCause
? causeAddInterrupts(this._interruptedCause, cause)
: cause;
if (this.interruptible) {
if (this._running) this._deferredInterrupt = true;
else this.evaluate(failCause$1(this._interruptedCause));
}
}
pollUnsafe() {
return this._exit;
}
evaluate(effect) {
if (this._exit) return;
else if (this._asyncContext !== void 0) {
const asyncContext = this._asyncContext;
this._asyncContext = void 0;
return asyncContext.runInAsyncScope(this.evaluate, this, effect);
} else if (this._yielded !== void 0) {
const yielded = this._yielded;
this._yielded = void 0;
yielded();
}
const exit = this.runLoop(effect);
if (exit === Yield) {
this._asyncContext = captureAsyncContext();
return;
}
const interruptChildren =
fiberMiddleware.interruptChildren &&
fiberMiddleware.interruptChildren(this);
if (interruptChildren !== void 0)
return this.evaluate(flatMap$1(interruptChildren, () => exit));
this._exit = exit;
this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit);
if (this._parent) {
this._parent._children?.delete(this);
this._parent = void 0;
}
if (this._observers !== void 0) {
const observers = this._observers;
this._observers = void 0;
for (let i = 0; i < observers.length; i++) observers[i](exit);
}
this._stack.length = 0;
this._children = void 0;
this.context = empty();
}
runLoop(effect) {
const prevFiber = globalThis[currentFiberTypeId];
globalThis[currentFiberTypeId] = this;
const prevRunning = this._running;
this._running = true;
let yielding = false;
let current = effect;
this.currentOpCount = 0;
try {
while (true)
try {
if (this._deferredInterrupt) {
this._deferredInterrupt = false;
current = failCause$1(this._interruptedCause);
}
this.currentOpCount++;
const cache = this.cache;
if (
!yielding &&
!cache.preventYield &&
cache.scheduler.shouldYield(this)
) {
yielding = true;
const prev = current;
current = flatMap$1(yieldNow, () => prev);
}
current = cache.tracerContext
? cache.tracerContext(current, this)
: current[evaluate](this);
if (current === Yield) {
const yielded = this._yielded;
if ("~effect/Exit" in yielded) {
this._deferredInterrupt = false;
this._yielded = void 0;
return yielded;
} else if (this._deferredInterrupt) {
this._yielded = void 0;
yielded();
continue;
}
return Yield;
}
} catch (error) {
if (!hasProperty(current, "~effect/Effect/evaluate"))
return exitDie(
`Fiber.runLoop: Not a valid effect: ${String(current)}`,
);
current = exitDie(error);
}
} finally {
this._running = prevRunning;
globalThis[currentFiberTypeId] = prevFiber;
}
}
getCont(symbol) {
if (this._deferredInterrupt) {
this._deferredInterrupt = false;
return deferredInterruptCont;
}
while (true) {
const op = this._stack.pop();
if (!op) return void 0;
const all = op[contAll];
if (all !== void 0) {
const cont = all.call(op, this);
if (cont) {
cont[symbol] = cont;
return cont;
}
}
if (op[symbol]) return op;
}
}
succeedWith(value) {
if ((++this.currentOpCount & (maxInlineSteps - 1)) === 0)
return exitSucceed(value);
const cont = this.getCont(contA);
return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value));
}
yieldWith(value) {
this._yielded = value;
return Yield;
}
children() {
return (this._children ??= /* @__PURE__ */ new Set());
}
pipe() {
return pipeArguments(this, arguments);
}
setContext(context) {
const previous = this.context;
this.context = context;
if (previous !== void 0 && hasSameCache(previous, context)) return;
const root = context.cacheRoot;
const cache = (root._fiberCache ??= makeFiberContextCache(context));
if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0;
this.cache = cache;
}
get currentSpanLocal() {
const span = this.cache.span;
return span?._tag === "Span" ? span : void 0;
}
};
const makeFiberContextCache = (context) => {
const currentTracer = getOrUndefinedUnsafe(context, TracerKey);
return {
scheduler: get(context, Scheduler),
tracer: currentTracer,
tracerContext: currentTracer ? currentTracer["context"] : void 0,
tracerEnabled: get(context, TracerEnabled),
span: getOrUndefinedUnsafe(context, ParentSpanKey),
logLevel: get(context, CurrentLogLevel),
minimumLogLevel: get(context, MinimumLogLevel),
stackFrame: get(context, CurrentStackFrame),
runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey),
maxOpsBeforeYield: get(context, MaxOpsBeforeYield),
preventYield: get(context, PreventSchedulerYield),
};
};
const deferredInterruptCont = {
[contA](_value, fiber) {
return failCause$1(fiber._interruptedCause);
},
[contE](_cause, fiber) {
return failCause$1(fiber._interruptedCause);
},
};
const maxInlineSteps = 32;
const fiberMiddleware = { interruptChildren: void 0 };
const fiberStackAnnotations = (fiber) => {
if (!fiber.cache.stackFrame) return void 0;
const annotations = /* @__PURE__ */ new Map();
annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame);
return makeUnsafe$2(annotations);
};
/** @internal */
const fiberAwaitAll = (self) =>
callback((resume) => {
const iter = self[Symbol.iterator]();
const exits = [];
let cancel = void 0;
function loop() {
let result = iter.next();
while (!result.done) {
if (result.value._exit) {
exits.push(result.value._exit);
result = iter.next();
continue;
}
cancel = result.value.addObserver((exit) => {
exits.push(exit);
loop();
});
return;
}
resume(succeed$3(exits));
}
loop();
return sync(() => cancel?.());
});
/** @internal */
const fiberInterruptAll = (fibers) =>
withFiber((parent) => {
const annotations = fiberStackAnnotations(parent);
let fiberArr = empty$1();
for (const fiber of fibers) {
fiber.interruptUnsafe(parent.id, annotations);
fiberArr.push(fiber);
}
return asVoid(fiberAwaitAll(fiberArr));
});
/** @internal */
const succeed$3 = exitSucceed;
/** @internal */
const failCause$1 = exitFailCause;
/** @internal */
const fail$3 = exitFail;
/** @internal */
const sync = /*#__PURE__*/ makePrimitive({
op: "Sync",
[evaluate](fiber) {
const value = this[args]();
const cont = fiber.getCont(contA);
return cont
? cont[contA](value, fiber)
: fiber.yieldWith(exitSucceed(value));
},
});
/** @internal */
const suspend$1 = /*#__PURE__*/ makePrimitive({
op: "Suspend",
[evaluate](_fiber) {
return this[args]();
},
});
/** @internal */
const yieldNow = /*#__PURE__*/ /* @__PURE__ */ makePrimitive({
op: "Yield",
[evaluate](fiber) {
let resumed = false;
fiber.currentDispatcher.scheduleTask(() => {
if (resumed) return;
fiber.evaluate(exitVoid);
}, this["~effect/Effect/args"] ?? 0);
return fiber.yieldWith(() => {
resumed = true;
});
},
})(0);
/** @internal */
const failCauseSync$1 = (evaluate) => suspend$1(() => failCause$1(evaluate()));
/** @internal */
const die$2 = (defect) => exitDie(defect);
/** @internal */
const void_$1 = /*#__PURE__*/ succeed$3(void 0);
const callbackOptions = /*#__PURE__*/ (function () {
const Proto = /*#__PURE__*/ makePrimitiveProto({
op: "Async",
[evaluate](fiber) {
let resumed = false;
let yielded = false;
const controller = this.withSignal ? new AbortController() : void 0;
const onCancel = this.register.call(
fiber.cache.scheduler,
(effect) => {
if (resumed) return;
resumed = true;
if (yielded) fiber.evaluate(effect);
else yielded = effect;
},
controller?.signal,
);
if (yielded !== false) return yielded;
yielded = true;
fiber._yielded = () => {
resumed = true;
};
if (controller === void 0 && onCancel === void 0) return Yield;
fiber._stack.push(
asyncFinalizer(() => {
resumed = true;
controller?.abort();
return onCancel ?? exitVoid;
}),
);
return Yield;
},
});
const AsyncImpl = function (register, withSignal) {
this.register = register;
this.withSignal = withSignal;
};
AsyncImpl.prototype = Proto;
return function (register, withSignal) {
return new AsyncImpl(register, withSignal);
};
})();
const asyncFinalizer = /*#__PURE__*/ makePrimitive({
op: "AsyncFinalizer",
[contAll](fiber) {
if (fiber.interruptible) {
fiber.interruptible = false;
fiber._stack.push(setInterruptibleTrue);
}
},
[contE](cause, _fiber) {
return hasInterrupts(cause)
? flatMap$1(
combineFinalizerCause(exitFailCause(cause), this[args]()),
() => failCause$1(cause),
)
: failCause$1(cause);
},
});
/** @internal */
const callback = (register) => callbackOptions(register, register.length >= 2);
const defineFunctionLength = (length, fn) =>
Object.defineProperty(fn, "length", {
value: length,
configurable: true,
});
/** @internal */
const fnUntracedEager$1 = (body, ...pipeables) =>
defineFunctionLength(
body.length,
pipeables.length === 0
? function () {
return fromIteratorEagerUnsafe(() => body.apply(this, arguments));
}
: function () {
let effect = fromIteratorEagerUnsafe(() =>
body.apply(this, arguments),
);
for (const pipeable of pipeables)
effect = pipeable(effect, ...arguments);
return effect;
},
);
const fromIteratorEagerUnsafe = (evaluate) => {
try {
const iterator = evaluate();
let value = void 0;
while (true) {
const state = iterator.next(value);
if (state.done) return succeed$3(state.value);
const primitive = state.value;
if (primitive && primitive._tag === "Success") {
value = primitive.value;
continue;
} else if (primitive && primitive._tag === "Failure") return state.value;
else {
let isFirstExecution = true;
return suspend$1(() => {
if (isFirstExecution) {
isFirstExecution = false;
return flatMap$1(state.value, (value) =>
fromIteratorUnsafe(iterator, value),
);
} else return suspend$1(() => fromIteratorUnsafe(evaluate()));
});
}
}
} catch (error) {
return die$2(error);
}
};
const fromIteratorUnsafe = /*#__PURE__*/ (function () {
const Proto = /*#__PURE__*/ makePrimitiveProto({
op: "Iterator",
[contA](value, fiber) {
const iter = this.iterator;
while (true) {
const state = iter.next(value);
if (state.done) return succeed$3(state.value);
if (!effectIsExit(state.value)) {
fiber._stack.push(this);
return state.value;
} else if (state.value._tag === "Failure") return state.value;
value = state.value.value;
}
},
[evaluate](fiber) {
return this[contA](this.initial, fiber);
},
});
const IteratorImpl = function (iterator, initial) {
this.iterator = iterator;
this.initial = initial;
};
IteratorImpl.prototype = Proto;
return function (iterator, initial) {
return new IteratorImpl(iterator, initial);
};
})();
const evaluateCont = function (fiber) {
fiber._stack.push(this);
return this[args];
};
const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({
op: "OnSuccess",
[evaluate]: evaluateCont,
});
const ContImpl = function (self, cont, payload) {
this[args] = self;
this[contA] = cont;
this.payload = payload;
};
ContImpl.prototype = OnSuccessProto;
const returnPayload = function () {
return this.payload;
};
const continuationMarksStack = /*#__PURE__*/ (() => {
const limit = /*#__PURE__*/ getStackTraceLimit();
if (limit === 0) return false;
const marker = "~effect/Effect/stackProbe";
const probe = {
[marker]: function stackProbe() {
return /* @__PURE__ */ new Error();
},
};
setStackTraceLimit(1);
const error = /*#__PURE__*/ probe[marker]();
setStackTraceLimit(limit);
return error.stack?.includes("[as " + marker + "]") === true;
})();
const mapCont = function (value, fiber) {
const f = this.payload;
return fiber.succeedWith(
continuationMarksStack ? f(value) : internalCall(() => f(value)),
);
};
const andThenCont = function (value) {
const f = this.payload;
return f(value);
};
/** @internal */
const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid);
/** @internal */
const flatMap$1 = /*#__PURE__*/ dual(
2,
(self, f) => new ContImpl(self, andThenCont, f),
);
/** @internal */
const effectIsExit = (effect) => effect[ExitTypeId] !== void 0;
/** @internal */
const flatMapEager$1 = /*#__PURE__*/ dual(2, (self, f) => {
if (effectIsExit(self)) return self._tag === "Success" ? f(self.value) : self;
return flatMap$1(self, f);
});
/** @internal */
const map$1 = /*#__PURE__*/ dual(
2,
(self, f) => new ContImpl(self, mapCont, f),
);
/** @internal */
const mapEager$1 = /*#__PURE__*/ dual(2, (self, f) =>
effectIsExit(self) ? exitMap(self, f) : map$1(self, f),
);
/** @internal */
const exitIsSuccess = (self) => self._tag === "Success";
/** @internal */
const exitVoid = /*#__PURE__*/ exitSucceed(void 0);
/** @internal */
const exitMap = /*#__PURE__*/ dual(2, (self, f) =>
self._tag === "Success" ? exitSucceed(f(self.value)) : self,
);
/** @internal */
const catchCause$1 = /*#__PURE__*/ dual(
2,
(self, f) =>
new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f),
);
const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({
op: "OnFailure",
[evaluate]: evaluateCont,
});
const OnFailureImpl = function (self, f) {
this[args] = self;
this[contE] = f;
};
OnFailureImpl.prototype = OnFailureProto;
const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({
op: "OnSuccessAndFailure",
[evaluate]: evaluateCont,
});
const OnSuccessAndFailureImpl = function (self, onSuccess, onFailure) {
this[args] = self;
this[contA] = onSuccess;
this[contE] = onFailure;
};
OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto;
/** @internal */
const exit$1 = (self) =>
effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self);
const exitPrimitive = /*#__PURE__*/ makePrimitive({
op: "Exit",
[evaluate](fiber) {
fiber._stack.push(this);
return this[args];
},
[contA](value, fiber, exit) {
return fiber.succeedWith(exit ?? exitSucceed(value));
},
[contE](cause, fiber, exit) {
return fiber.succeedWith(exit ?? exitFailCause(cause));
},
});
const combineFinalizerCause = (exit_, finalizer) =>
exitIsSuccess(exit_)
? finalizer
: catchCause$1(finalizer, (cause) =>
failCause$1(causeCombine(exit_.cause, cause)),
);
/** @internal */
const uninterruptible = (self) =>
withFiber((fiber) => {
if (!fiber.interruptible) return self;
fiber.interruptible = false;
fiber._stack.push(setInterruptibleTrue);
return self;
});
const setInterruptibleTrue = /*#__PURE__*/ /* @__PURE__ */ makePrimitive({
op: "SetInterruptible",
[contAll](fiber) {
fiber.interruptible = this[args];
if (fiber._interruptedCause && fiber.interruptible)
return () => failCause$1(fiber._interruptedCause);
},
})(true);
/** @internal */
const resolveConcurrency = (concurrency) =>
concurrency === "unbounded"
? Number.POSITIVE_INFINITY
: Math.max(1, concurrency ?? 1);
/** @internal */
const iterateEager = () => (options) => {
const onItem = options.onItem;
const step = options.step;
const resumeSequential = (state, items, index, end, effect) =>
flatMap$1(
exit$1(effect),
(itemExit) =>
step(state, items[index], itemExit, index) ??
runSequential(state, items, index + 1, end) ??
void_$1,
);
const runSequential = (state, items, index = 0, end = items.length) => {
for (; index < end; index++) {
const item = items[index];
const effect = onItem(state, item, index);
if (!effectIsExit(effect))
return resumeSequential(state, items, index, end, effect);
const terminal = step(state, item, effect, index);
if (terminal) return terminal._tag === "Failure" ? terminal : void 0;
}
};
return runSequential;
};
const iterateConcurrentImpl = (options) => {
const onItem = options.onItem;
const step = options.step;
return (state, items, opts) => {
let index = 0;
const end = opts.end ?? items.length;
const concurrency = opts.concurrency;
let done = false;
let parentFiber;
let fibers;
let resume;
let terminal;
let effect;
const failDefect = (error) => {
const defect = exitDie(error);
terminal = defect;
done = true;
return fibers && fibers.size > 0
? flatMap$1(
uninterruptible(fiberInterruptAll(Array.from(fibers))),
() => terminal ?? defect,
)
: defect;
};
const go = () => {
let paused = false;
for (; !terminal && index < end; index++) {
const item = items[index];
const eff = effect ?? onItem(state, item, index);
if (effectIsExit(eff)) {
terminal = step(state, item, eff, index);
if (terminal) break;
} else if (!parentFiber)
return callback((cb) => {
parentFiber = getCurrentFiber();
fibers = /* @__PURE__ */ new Set();
effect = eff;
resume = cb;
let result;
try {
result = go();
} catch (error) {
return cb(failDefect(error));
}
if (result) return cb(result);
return suspend$1(() => {
terminal ??= exitVoid;
return flatMap$1(
fibers ? fiberInterruptAll(fibers) : void_$1,
() => (terminal?._tag === "Failure" ? terminal : void_$1),
);
});
});
else {
effect = void 0;
const fiber = forkUnsafe(parentFiber, eff, true, true, "inherit");
if (fiber._exit) {
terminal = step(state, item, fiber._exit, index);
if (terminal) break;
continue;
}
fibers.add(fiber);
const currentIndex = index;
fiber.addObserver((exit) => {
fibers.delete(fiber);
try {
if (terminal) {
if (exit._tag === "Failure") {
const reasons = exit.cause.reasons.filter(
(reason) => reason._tag !== "Interrupt",
);
if (reasons.length > 0) {
const cause = causeFromReasons(reasons);
terminal = exitFailCause(
terminal._tag === "Failure"
? causeCombine(terminal.cause, cause)
: cause,
);
}
}
} else {
const result = step(state, item, exit, currentIndex);
if (result) {
terminal = result;
go();
}
}
if (paused) {
const eff = go();
if (eff) resume(eff);
} else if (done && fibers.size === 0) resume(terminal ?? void_$1);
} catch (error) {
resume(failDefect(error));
}
});
if (fibers.size < concurrency) continue;
paused = true;
index++;
return;
}
}
done = true;
if (terminal) {
if (fibers && fibers.size > 0) {
const annotations = fiberStackAnnotations(parentFiber);
fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations));
return;
}
if (resume || terminal._tag === "Failure") return terminal;
} else if (resume) {
if (!fibers) return exitVoid;
else if (fibers.size === 0) resume(void_$1);
}
};
return go();
};
};
/** @internal */
const iterateConcurrent = () => (options) => iterateConcurrentImpl(options);
/** @internal */
const forkUnsafe = (
parent,
effect,
immediate = false,
daemon = false,
uninterruptible = false,
) => {
const parentRuntime = parent;
const interruptible =
uninterruptible === "inherit"
? parentRuntime.interruptible
: !uninterruptible;
const child = new FiberImpl(parentRuntime.context, interruptible);
if (!daemon) {
parentRuntime.children().add(child);
child._parent = parentRuntime;
}
if (immediate) child.evaluate(effect);
else {
child._asyncContext = captureAsyncContext();
parentRuntime.currentDispatcher.scheduleTask(
() => child.evaluate(effect),
0,
);
}
return child;
};
/** @internal */
const runForkWith = (context) => (effect, options) => {
const fiber = new FiberImpl(
options?.scheduler ? add(context, Scheduler, options.scheduler) : context,
options?.uninterruptible !== true,
);
fiber.evaluate(effect);
if (fiber._exit) return fiber;
if (options?.signal) {
if (options.signal.aborted) fiber.interruptUnsafe();
else {
const abort = () => fiber.interruptUnsafe();
options.signal.addEventListener("abort", abort, { once: true });
fiber.addObserver(() =>
options.signal.removeEventListener("abort", abort),
);
}
}
if (options?.onFiberStart) options.onFiberStart(fiber);
return fiber;
};
/** @internal */
const runSyncExitWith = (context) => {
const runFork = runForkWith(context);
return (effect) => {
if (effectIsExit(effect)) return effect;
const scheduler = new MixedScheduler("sync");
const fiber = runFork(effect, { scheduler });
fiber._dispatcher?.flush();
return fiber._exit ?? exitDie(new AsyncFiberError(fiber));
};
};
/** @internal */
const runSyncExit$1 = /*#__PURE__*/ runSyncExitWith(/*#__PURE__*/ empty());
/** @internal */
const AsyncFiberErrorTypeId = "~effect/Cause/AsyncFiberError";
/** @internal */
var AsyncFiberError = class extends /*#__PURE__*/ TaggedError$1(
"AsyncFiberError",
) {
[AsyncFiberErrorTypeId] = AsyncFiberErrorTypeId;
constructor(fiber) {
super({
message: "An asynchronous Effect was executed with Effect.runSync",
fiber,
});
}
};
const colors = {
bold: "1",
red: "31",
green: "32",
yellow: "33",
blue: "34",
cyan: "36",
white: "37",
gray: "90",
black: "30",
bgBrightRed: "101",
};
(colors.gray,
colors.blue,
colors.green,
colors.yellow,
colors.red,
colors.bgBrightRed,
colors.black);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Cause.js
/**
* Narrows a `Reason` to `Fail`.
*
* **When to use**
*
* Use as a predicate for `Array.filter` to pick out typed `Fail` reasons when
* iterating over `cause.reasons`.
*
* **Example** (Filtering fail reasons)
*
* ```ts import.meta.vitest
* import { Cause } from "effect"
*
* const cause = Cause.fail("error")
* const fails = cause.reasons.filter(Cause.isFailReason)
* fails[0].error // => "error"
* ```
*
* @see {@link isDieReason} — narrow to `Die`
* @see {@link isInterruptReason} — narrow to `Interrupt`
*
* @stability stable
* @category guards
* @since 4.0.0
*/
const isFailReason = isFailReason$1;
/**
* Creates a `Cause` containing a single `Die` reason with the
* given defect.
*
* **When to use**
*
* Use to construct a cause from an untyped defect or unexpected thrown value.
*
* **Example** (Creating a die cause)
*
* ```ts import.meta.vitest
* import { Cause } from "effect"
*
* Cause.die("Unexpected") // => Cause.fromReasons([Cause.makeDieReason("Unexpected")])
* ```
*
* @see {@link fail} — for typed errors
* @see {@link interrupt} — for fiber interruptions
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const die$1 = causeDie;
/**
* Transforms the typed error values inside a `Cause` using the
* provided function. Only `Fail` reasons are affected; `Die` and `Interrupt`
* reasons pass through unchanged.
*
* **When to use**
*
* Use to transform expected typed failures while preserving defects and
* interruptions unchanged.
*
* **Details**
*
* If at least one `Fail` reason exists, this returns a new `Cause`
* containing the mapped failures. If the cause has no `Fail` reasons, the
* original cause is returned unchanged.
*
* **Example** (Mapping errors to uppercase)
*
* ```ts import.meta.vitest
* import { Cause } from "effect"
*
* const cause = Cause.fail("error")
* const mapped = Cause.map(cause, (e) => e.toUpperCase())
* const reason = mapped.reasons[0]
* if (Cause.isFailReason(reason)) {
* reason.error // => "ERROR"
* }
* ```
*
* @stability stable
* @category mapping
* @since 2.0.0
*/
const map = causeMap;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Exit.js
/**
* Creates a successful Exit containing the given value.
*
* **When to use**
*
* Use when you need an Exit that contains a known success value.
*
* **Details**
*
* Returns a `Success<A>` with the provided value. Does not perform any
* computation.
*
* **Example** (Creating a successful Exit)
*
* ```ts import.meta.vitest
* import { Exit } from "effect"
*
* Exit.succeed(42) // => Exit.succeed(42)
* ```
*
* @see {@link fail} to create a failed Exit
* @see {@link void_ void} for a pre-allocated success with no value
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const succeed$2 = exitSucceed;
/**
* Creates a failed Exit from a Cause.
*
* **When to use**
*
* Use when you already have a `Cause<E>` and want to wrap it in an Exit
* for advanced error handling where you need full control over the Cause
* structure.
*
* **Details**
*
* Returns a `Failure<never, E>`. If you only have an error value, use
* {@link fail} instead.
*
* **Example** (Creating a failed Exit from a Cause)
*
* ```ts import.meta.vitest
* import { Cause, Exit } from "effect"
*
* Exit.failCause(Cause.fail("Something went wrong")) // => Exit.fail("Something went wrong")
* ```
*
* @see {@link fail} to create a Failure from a plain error value
* @see {@link die} to create a Failure from a defect
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const failCause = exitFailCause;
/**
* Creates a failed Exit from a typed error value.
*
* **When to use**
*
* Use when you need to represent an expected typed failure as an `Exit`.
*
* **Details**
*
* The error is wrapped in a `Cause.Fail` internally.
*
* Returns a `Failure<never, E>`.
*
* **Example** (Creating a failed Exit)
*
* ```ts import.meta.vitest
* import { Exit } from "effect"
*
* Exit.fail("Something went wrong") // => Exit.fail("Something went wrong")
* ```
*
* @see {@link succeed} to create a successful Exit
* @see {@link die} to create a Failure from an unexpected defect
* @see {@link failCause} to create a Failure from a full Cause
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const fail$2 = exitFail;
const void_ = exitVoid;
/**
* Checks whether an Exit is a Success.
*
* **When to use**
*
* Use as a type guard to narrow `Exit<A, E>` to `Success<A, E>` and access the
* `value` property.
*
* **Example** (Narrowing to success)
*
* ```ts import.meta.vitest
* import { Exit } from "effect"
*
* const exit = Exit.succeed(42)
*
* if (Exit.isSuccess(exit)) {
* exit.value // => 42
* }
* ```
*
* @see {@link isFailure} for the opposite check
* @see {@link match} for exhaustive pattern matching
*
* @stability stable
* @category guards
* @since 2.0.0
*/
const isSuccess = exitIsSuccess;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/dateTime.js
/** @internal */
const TypeId$10 = "~effect/DateTime";
/** @internal */
const TimeZoneTypeId = "~effect/DateTime/TimeZone";
const Proto$4 = {
[TypeId$10]: TypeId$10,
pipe() {
return pipeArguments(this, arguments);
},
[NodeInspectSymbol]() {
return this.toString();
},
toJSON() {
return toDateUtc$1(this).toJSON();
},
};
({ ...Proto$4 });
({ ...Proto$4 });
const ProtoTimeZone = {
[TimeZoneTypeId]: TimeZoneTypeId,
[NodeInspectSymbol]() {
return this.toString();
},
};
({ ...ProtoTimeZone });
({ ...ProtoTimeZone });
/** @internal */
const toDateUtc$1 = (self) => new Date(self.epochMilliseconds);
/**
* Creates an `Effect` that always succeeds with a given value.
*
* **When to use**
*
* Use when an effect should complete successfully with a specific value without any errors
* or external dependencies.
*
* **Example** (Creating a successful effect)
*
* ```ts import.meta.vitest
* import { Effect } from "effect"
*
* // Creating an effect that represents a successful scenario
* //
* // ┌─── Effect<number, never, never>
* // â–¼
* const success = Effect.succeed(42)
* Effect.runSync(success) // => 42
* ```
*
* @see {@link fail} to create an effect that represents a failure.
* @stability stable
* @category constructors
* @since 2.0.0
*/
const succeed$1 = succeed$3;
/**
* Creates an `Effect` lazily, delaying construction until it is needed.
*
* **When to use**
*
* Use when you need to defer the evaluation of an effect until it is required.
*
* **Details**
*
* `suspend` takes a thunk that represents an effect and delays creating it
* until the suspended effect is evaluated. This is useful for optimizing
* expensive computations, managing circular dependencies such as recursive
* functions, and helping TypeScript unify return types when branches construct
* different effects. Any side effects or scoped captures inside the thunk are
* re-executed on each invocation.
*
* **Example** (Lazily evaluating side effects)
*
* ```ts import.meta.vitest
* import { Effect } from "effect"
*
* let i = 0
*
* const bad = Effect.succeed(i++)
*
* const good = Effect.suspend(() => Effect.succeed(i++))
*
* Effect.runSync(bad) // => 0
* Effect.runSync(bad) // => 0
*
* Effect.runSync(good) // => 1
* Effect.runSync(good) // => 2
* ```
*
* **Example** (Suspending recursive Fibonacci evaluation)
*
* ```ts import.meta.vitest
* import { Effect } from "effect"
*
* const blowsUp = (n: number): Effect.Effect<number> =>
* n < 2
* ? Effect.succeed(1)
* : Effect.zipWith(blowsUp(n - 1), blowsUp(n - 2), (a, b) => a + b)
*
* // console.log(Effect.runSync(blowsUp(32)))
* // crash: JavaScript heap out of memory
*
* const allGood = (n: number): Effect.Effect<number> =>
* n < 2
* ? Effect.succeed(1)
* : Effect.zipWith(
* Effect.suspend(() => allGood(n - 1)),
* Effect.suspend(() => allGood(n - 2)),
* (a, b) => a + b
* )
*
* Effect.runSync(allGood(16)) // => 1597
* ```
*
* **Example** (Helping TypeScript infer recursive effect types)
*
* ```ts import.meta.vitest
* import { Effect } from "effect"
*
* // Without suspend, TypeScript may struggle with type inference.
* // Inferred type:
* // (a: number, b: number) =>
* // Effect<never, Error, never> | Effect<number, never, never>
* const withoutSuspend = (a: number, b: number) =>
* b === 0
* ? Effect.fail(new Error("Cannot divide by zero"))
* : Effect.succeed(a / b)
*
* // Using suspend to unify return types.
* // Inferred type:
* // (a: number, b: number) => Effect<number, Error, never>
* const withSuspend = (a: number, b: number) =>
* Effect.suspend(() =>
* b === 0
* ? Effect.fail(new Error("Cannot divide by zero"))
* : Effect.succeed(a / b)
* )
*
* Effect.runSync(withSuspend(6, 2)) // => 3
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const suspend = suspend$1;
/**
* Creates an `Effect` that represents a recoverable error.
*
* **When to use**
*
* Use to explicitly signal a recoverable error in an `Effect`.
*
* **Details**
*
* The error keeps propagating unless it is handled. You can handle tagged
* errors with functions like {@link catchTag} or {@link catchTags}.
*
* **Example** (Creating a failed effect)
*
* ```ts import.meta.vitest
* import { Data, Effect } from "effect"
*
* class OperationFailedError extends Data.TaggedError("OperationFailedError")<{}> {}
*
* // ┌─── Effect<never, OperationFailedError, never>
* // â–¼
* const failure = Effect.fail(
* new OperationFailedError()
* )
* Effect.runSync(Effect.flip(failure))._tag // => "OperationFailedError"
* ```
*
* @see {@link succeed} to create an effect that represents a successful value.
* @stability stable
* @category constructors
* @since 2.0.0
*/
const fail$1 = fail$3;
/**
* Creates an `Effect` that represents a failure with a `Cause` computed lazily.
*
* **When to use**
*
* Use to defer computing a full `Cause` until the effect is run.
*
* **Details**
*
* The cause-producing function is evaluated each time the effect is executed.
*
* **Example** (Lazily creating a Cause)
*
* ```ts import.meta.vitest
* import { Cause, Effect } from "effect"
*
* const program = Effect.failCauseSync(() =>
* Cause.fail("Error computed at runtime")
* )
*
* Effect.runSync(Effect.flip(program)) // => "Error computed at runtime"
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const failCauseSync = failCauseSync$1;
/**
* Creates an effect that terminates a fiber with a specified error.
*
* **When to use**
*
* Use when you need an `Effect` to report an unrecoverable defect instead of a
* typed error.
*
* **Details**
*
* The `die` function is used to signal a defect, which represents a critical
* and unexpected error in the code. When invoked, it produces an effect that
* does not handle the error and instead terminates the fiber.
*
* The error channel of the resulting effect is of type `never`, indicating that
* it cannot recover from this failure.
*
* **Example** (Failing on division by zero)
*
* ```ts import.meta.vitest
* import { Effect, Exit } from "effect"
*
* const defect = new Error("Cannot divide by zero")
* const divide = (a: number, b: number) =>
* b === 0
* ? Effect.die(defect)
* : Effect.succeed(a / b)
*
* // ┌─── Effect<number, never, never>
* // â–¼
* const program = divide(1, 0)
*
* Effect.runSyncExit(program) // => Exit.die(defect)
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const die = die$2;
/**
* Chains effects to produce new `Effect` instances, useful for combining
* operations that depend on previous results.
*
* **When to use**
*
* Use when you need to chain multiple effects, ensuring that each
* step produces a new `Effect` while flattening any nested effects that may
* occur.
*
* **Details**
*
* `flatMap` lets you sequence effects so that the result of one effect can be
* used in the next step. It is similar to `flatMap` used with arrays but works
* specifically with `Effect` instances, allowing you to avoid deeply nested
* effect structures.
*
* Since effects are immutable, `flatMap` always returns a new effect instead of
* changing the original one.
*
* **Example** (Choosing flatMap syntax variants)
*
* ```ts import.meta.vitest
* import { Effect, pipe } from "effect"
* const output: Array<unknown> = []
*
* const myEffect = Effect.succeed(1)
* const transformation = (n: number) => Effect.succeed(n + 1)
*
* const flatMappedWithPipe = pipe(myEffect, Effect.flatMap(transformation))
* const flatMappedWithDataFirst = Effect.flatMap(myEffect, transformation)
* const flatMappedWithMethod = myEffect.pipe(Effect.flatMap(transformation))
*
* void output.push(Effect.runSync(Effect.all([
* flatMappedWithPipe,
* flatMappedWithDataFirst,
* flatMappedWithMethod
* ])))
* output // => [[2, 2, 2]]
* ```
*
* **Example** (Sequencing dependent effects)
*
* ```ts import.meta.vitest
* import { Data, Effect, pipe } from "effect"
*
* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {}
*
* // Function to apply a discount safely to a transaction amount
* const applyDiscount = (
* total: number,
* discountRate: number
* ): Effect.Effect<number, DiscountRateError> =>
* discountRate === 0
* ? Effect.fail(new DiscountRateError())
* : Effect.succeed(total - (total * discountRate) / 100)
*
* // Simulated asynchronous task to fetch a transaction amount from database
* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
*
* // Chaining the fetch and discount application using `flatMap`
* const finalAmount = pipe(
* fetchTransactionAmount,
* Effect.flatMap((amount) => applyDiscount(amount, 5))
* )
*
* await Effect.runPromise(finalAmount) // => 95
* ```
*
* @see {@link tap} for a version that ignores the result of the effect.
* @stability stable
* @category sequencing
* @since 2.0.0
*/
const flatMap = flatMap$1;
/**
* Transforms an effect to encapsulate both failure and success using the `Exit`
* data type.
*
* **When to use**
*
* Use when you need to inspect the full outcome, including typed failures, defects,
* and interruptions.
*
* **Details**
*
* `exit` wraps an effect's success or failure inside an `Exit` type, allowing
* you to handle both cases explicitly.
*
* The resulting effect cannot fail because the failure is encapsulated within
* the `Exit.Failure` type. The error type is set to `never`, indicating that
* the effect is structured to never fail directly.
*
* **Example** (Capturing completion as Exit)
*
* ```ts import.meta.vitest
* import { Effect, Exit } from "effect"
*
* const success = Effect.succeed(42)
* const failure = Effect.fail("Something went wrong")
*
* const program1 = Effect.exit(success)
* const program2 = Effect.exit(failure)
*
* Effect.runSync(program1) // => Exit.succeed(42)
*
* Effect.runSync(program2) // => Exit.fail("Something went wrong")
* ```
*
* @see {@link option} for a version that uses `Option` instead.
* @see {@link result} for a version that uses `Result` instead.
*
* @stability stable
* @category error handling
* @since 2.0.0
*/
const exit = exit$1;
/**
* Handles both recoverable and unrecoverable errors by providing a recovery
* effect.
*
* **When to use**
*
* Use when you need to recover from an `Effect` by inspecting the full `Cause`,
* including recoverable failures, defects, and interruptions, instead of only
* the typed error value.
*
* **Details**
*
* When to Recover from Defects:
*
* Defects are unexpected errors that typically shouldn't be recovered from, as
* they often indicate serious issues. However, in some cases, such as
* dynamically loaded plugins, controlled recovery might be needed.
*
* **Example** (Recovering from full failure causes)
*
* ```ts import.meta.vitest
* import { Cause, Effect } from "effect"
* const output: Array<unknown> = []
*
* // An effect that might fail in different ways
* const program = Effect.die("Something went wrong")
*
* // Recover from any cause (including defects)
* const recovered = Effect.catchCause(program, (cause) => {
* if (Cause.hasDies(cause)) {
* return Effect.sync(() => { output.push("Caught defect") }).pipe(
* Effect.as("Recovered from defect")
* )
* }
* return Effect.succeed("Unknown error")
* })
*
* void output.push(Effect.runSync(recovered))
* output // => ["Caught defect", "Recovered from defect"]
* ```
*
* @stability stable
* @category error handling
* @since 4.0.0
*/
const catchCause = catchCause$1;
/**
* Runs an effect synchronously and captures the outcome safely as an `Exit` type, which
* represents the outcome (success or failure) of the effect.
*
* **When to use**
*
* Use to find out whether an effect succeeded or failed,
* including any defects, without dealing with asynchronous operations.
*
* **Details**
*
* The `Exit` type represents the result of the effect. Successful effects are
* wrapped in `Success`, and failed effects are wrapped in `Failure` with a
* `Cause`.
*
* If the effect contains asynchronous operations, `runSyncExit` will
* return an `Failure` with a `Die` cause, indicating that the effect cannot be
* resolved synchronously.
*
* **Example** (Observing synchronous results as Exit)
*
* ```ts import.meta.vitest
* import { Effect, Exit } from "effect"
*
* Effect.runSyncExit(Effect.succeed(1)) // => Exit.succeed(1)
*
* Effect.runSyncExit(Effect.fail("my error")) // => Exit.fail("my error")
* ```
*
* **Example** (Capturing async work as a Die cause)
*
* ```ts import.meta.vitest
* import { Cause, Effect, Exit } from "effect"
*
* const exit = Effect.runSyncExit(Effect.promise(() => Promise.resolve(1)))
* const isAsyncDie = Exit.hasDies(exit) && exit.cause.reasons.some(
* (reason) => Cause.isDieReason(reason) && Cause.isAsyncFiberError(reason.defect)
* )
*
* isAsyncDie // => true
* ```
*
* @see {@link runSync} for a version that throws on failure.
*
* @stability stable
* @category running
* @since 2.0.0
*/
const runSyncExit = runSyncExit$1;
/**
* Applies `map` eagerly when an effect is already resolved.
*
* **When to use**
*
* Use when an already-resolved effect should apply a success transformation
* immediately while pending effects still use regular mapping.
*
* **Details**
*
* Success effects apply the mapping function immediately. Failure effects pass
* through unchanged, and pending effects fall back to regular `map` behavior.
*
* **Example** (Mapping already completed effects)
*
* ```ts import.meta.vitest
* import { Effect } from "effect"
*
* // For resolved effects, the mapping is applied immediately
* const resolved = Effect.succeed(5)
* const mapped = Effect.mapEager(resolved, (n) => n * 2) // Applied eagerly
*
* // For pending effects, behaves like regular map
* const pending = Effect.delay(Effect.succeed(5), 0)
* const mappedPending = Effect.mapEager(pending, (n) => n * 2) // Uses regular map
*
* await Effect.runPromise(Effect.all([mapped, mappedPending])) // => [10, 10]
* ```
*
* @stability stable
* @category mapping
* @since 4.0.0
*/
const mapEager = mapEager$1;
/**
* Applies `flatMap` eagerly when an effect is already resolved.
*
* **When to use**
*
* Use when an already-resolved successful effect should bind immediately to the
* next effect while pending effects still use regular flat mapping.
*
* **Details**
*
* Success effects apply the flatMap function immediately. Failure effects pass
* through unchanged, and pending effects fall back to regular `flatMap`
* behavior.
*
* **Example** (Flat mapping eagerly when possible)
*
* ```ts import.meta.vitest
* import { Effect } from "effect"
*
* // For resolved effects, the flatMap is applied immediately
* const resolved = Effect.succeed(5)
* const flatMapped = Effect.flatMapEager(resolved, (n) => Effect.succeed(n * 2)) // Applied eagerly
*
* // For pending effects, behaves like regular flatMap
* const pending = Effect.delay(Effect.succeed(5), 0)
* const flatMappedPending = Effect.flatMapEager(
* pending,
* (n) => Effect.succeed(n * 2)
* ) // Uses regular flatMap
*
* await Effect.runPromise(Effect.all([flatMapped, flatMappedPending])) // => [10, 10]
* ```
*
* @stability stable
* @category sequencing
* @since 4.0.0
*/
const flatMapEager = flatMapEager$1;
/**
* Creates untraced function effects with eager evaluation optimization.
*
* **Details**
*
* Executes generator functions eagerly when all yielded effects are synchronous,
* stopping at the first async effect and deferring to normal execution.
*
* **Example** (Defining eager untraced effect functions)
*
* ```ts import.meta.vitest
* import { Effect } from "effect"
*
* const computation = Effect.fnUntracedEager(function*() {
* yield* Effect.succeed(1)
* yield* Effect.succeed(2)
* return "computed eagerly"
* })
*
* const effect = computation() // Executed immediately if all effects are sync
* Effect.runSync(effect) // => "computed eagerly"
* ```
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const fnUntracedEager = fnUntracedEager$1;
const alphabet =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const codes = /*#__PURE__*/ /* @__PURE__ */ new Uint8Array(123).fill(255);
for (let i = 0; i < 64; i++) codes[/*#__PURE__*/ alphabet.charCodeAt(i)] = i;
codes[/*#__PURE__*/ "=".charCodeAt(0)] = 0;
({ ...BaseProto });
({ ...BaseProto });
({ ...PipeInspectableProto });
(BaseProto.toString, BaseProto[NodeInspectSymbol]);
({ ...PipeInspectableProto });
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/schema/annotations.js
/** @internal */
function resolve$1(ast) {
return ast.checks
? ast.checks[ast.checks.length - 1].annotations
: ast.annotations;
}
/** @internal */
const STRUCTURAL_ANNOTATION_KEY = "~structural";
/** @internal */
const SENTINELS_ANNOTATION_KEY = "~sentinels";
/** @internal */
const CONSTRUCTOR_ANNOTATION_KEY = "~constructor";
/** @internal */
const getExpected = /*#__PURE__*/ memoize((ast) => {
const identifier = resolve$1(ast)?.identifier;
if (typeof identifier === "string") return identifier;
return ast.getExpected(getExpected);
});
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/schema/parser.js
/** @internal */
const missing = /*#__PURE__*/ Symbol();
/** @internal */
const succeed = succeed$2;
/** @internal */
const missingExit = /*#__PURE__*/ succeed(missing);
/** @internal */
const sameExit = /*#__PURE__*/ succeed(missing);
/** @internal */
const toOption = (value) => (value === missing ? none() : some(value));
/** @internal */
const fromOptionExit = (option) =>
option._tag === "None" ? missingExit : succeed(option.value);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/SchemaIssue.js
/**
* Describes problems found while decoding, encoding, or checking data with
* schemas.
*
* An `Issue` records what failed and, for nested data, where the failure
* happened. The Schema system uses these values for missing keys, unexpected
* keys, invalid types, invalid values, failed filters, failed transformations,
* and alternatives that did not match. This module also formats issues.
*
* @stability stable
* @since 4.0.0
*/
const TypeId$5 = "~effect/SchemaIssue/Issue";
/**
* Returns `true` if the given value is an {@link Issue}.
*
* **When to use**
*
* Use when you need to narrow an `unknown` value to `Issue` in error-handling
* code, such as distinguishing an `Issue` from other error types in a catch-all
* handler.
*
* **Details**
*
* - Checks for the internal `TypeId` brand on the value.
*
* **Example** (Type-guarding an unknown error)
*
* ```ts import.meta.vitest
* import { SchemaIssue } from "effect"
*
* const issue = new SchemaIssue.MissingKey(undefined)
* SchemaIssue.isIssue(issue) // => true
* SchemaIssue.isIssue("not an issue") // => false
* ```
*
* @see {@link Issue}
*
* @stability stable
* @category guards
* @since 4.0.0
*/
function isIssue(u) {
return hasProperty(u, TypeId$5) && u[TypeId$5] === TypeId$5;
}
/**
* Returns `true` when an issue contains an input reported by the schema parser.
*
* **When to use**
*
* Use when reading `Issue.input`, especially when `undefined` is a valid input
* value.
*
* **Details**
*
* Reported input is stored as an own property. This guard checks for that
* property and narrows `input` from optional to required.
*
* **Example** (Reading a reported input)
*
* ```ts import.meta.vitest
* import { Result, Schema, SchemaIssue } from "effect"
*
* const result = Schema.decodeUnknownResult(Schema.String)(1, { reportInput: true })
* if (Result.isFailure(result) && SchemaIssue.hasInput(result.failure.issue)) {
* result.failure.issue.input // => 1
* }
* ```
*
* @see {@link Issue} for the complete issue model
*
* @stability stable
* @category guards
* @since 4.0.0
*/
function hasInput(issue) {
return Object.hasOwn(issue, "input");
}
var IssueNodeImpl = class {
[TypeId$5] = TypeId$5;
constructor(input, options) {
if (options?.reportInput === true && input !== missing) this.input = input;
}
};
/**
* Constructs a schema issue for a failed refinement check.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Filter$1 = class extends IssueNodeImpl {
_tag = "Filter";
/**
* The filter that failed.
*/
filter;
/**
* The issue that occurred.
*/
issue;
constructor(filter, issue, input, options) {
super(input, options);
this.filter = filter;
this.issue = issue;
}
};
/**
* Constructs a schema issue for a failed transformation.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Encoding = class extends IssueNodeImpl {
_tag = "Encoding";
/**
* The schema that caused the issue.
*/
ast;
/**
* The issue that occurred.
*/
issue;
constructor(ast, issue, input, options) {
super(input, options);
this.ast = ast;
this.issue = issue;
}
};
/**
* Constructs a schema issue that points to a nested location.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Pointer = class extends IssueNodeImpl {
_tag = "Pointer";
/**
* The path to the location in the input that caused the issue.
*/
path;
/**
* The issue that occurred.
*/
issue;
constructor(path, issue) {
super();
this.path = path;
this.issue = issue;
}
};
/**
* Constructs a schema issue for a missing key or tuple index.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const MissingKey = class extends IssueNodeImpl {
_tag = "MissingKey";
/**
* The metadata for the issue.
*/
annotations;
constructor(annotations) {
super();
this.annotations = annotations;
}
};
/**
* Constructs a schema issue for an unexpected key or tuple index.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const UnexpectedKey = class extends IssueNodeImpl {
_tag = "UnexpectedKey";
/**
* The schema that caused the issue.
*/
ast;
constructor(ast, input, options) {
super(input, options);
this.ast = ast;
}
};
/**
* Constructs a schema issue that groups multiple child issues.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Composite = class extends IssueNodeImpl {
_tag = "Composite";
/**
* The schema that caused the issue.
*/
ast;
/**
* The issues that occurred.
*/
issues;
constructor(ast, issues, input, options) {
super(input, options);
this.ast = ast;
this.issues = issues;
}
};
/**
* Constructs a schema issue for an input with an invalid runtime type.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const InvalidType = class extends IssueNodeImpl {
_tag = "InvalidType";
/**
* The schema that caused the issue.
*/
ast;
constructor(ast, input, options) {
super(input, options);
this.ast = ast;
}
};
/**
* Constructs a schema issue for a value that violates a constraint.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const InvalidValue = class extends IssueNodeImpl {
_tag = "InvalidValue";
/**
* The metadata for the issue.
*/
annotations;
constructor(annotations, input, options) {
super(input, options);
this.annotations = annotations;
}
};
/**
* Constructs a schema issue for a value that matches no union member.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const AnyOf = class extends IssueNodeImpl {
_tag = "AnyOf";
/**
* The schema that caused the issue.
*/
ast;
/**
* The issues that occurred.
*/
issues;
constructor(ast, issues, input, options) {
super(input, options);
this.ast = ast;
this.issues = issues;
}
};
/**
* Constructs a schema issue for a value that matches multiple union members.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const OneOf = class extends IssueNodeImpl {
_tag = "OneOf";
/**
* The schema that caused the issue.
*/
ast;
/**
* The schemas that were successful.
*/
successes;
constructor(ast, successes, input, options) {
super(input, options);
this.ast = ast;
this.successes = successes;
}
};
function makeFilterIssue(entry, input, options) {
if (isIssue(entry)) return entry;
if (typeof entry === "string")
return new InvalidValue({ message: entry }, input, options);
const inner =
typeof entry.issue === "string"
? new InvalidValue({ message: entry.issue }, input, options)
: entry.issue;
return new Pointer(entry.path, inner);
}
/** @internal */
function makeSingle(out, input, options) {
if (out === void 0) return;
if (typeof out === "boolean")
return out ? void 0 : new InvalidValue(void 0, input, options);
return makeFilterIssue(out, input, options);
}
/** @internal */
function normalizeFilterOutput(ast, out, input, options) {
if (Array.isArray(out)) {
if (!isReadonlyArrayNonEmpty(out)) return;
return out.length === 1
? makeFilterIssue(out[0], input, options)
: new Composite(
ast,
map$2(out, (entry) => makeFilterIssue(entry, input, options)),
input,
options,
);
}
return makeSingle(out, input, options);
}
/**
* Returns the built-in {@link LeafHook} used by default formatters.
*
* **When to use**
*
* Use as the default leaf renderer when customizing only the {@link CheckHook}.
*
* **Details**
*
* - Checks for a `message` annotation first; returns it if present.
* - For `InvalidValue`, an `expected` annotation uses the standard expected
* value message and includes reported input when available.
* - Otherwise generates a default message per `_tag`. When the issue reports
* input, the message includes its formatted value where applicable:
* - `InvalidType` → `"Expected <type>"` or `"Expected <type>, got <input>"`
* - `InvalidValue` → `"Expected a valid value"` or `"Invalid data <input>"`
* - `MissingKey` → `"Missing key"`
* - `UnexpectedKey` → `"Expected no excess property"` or
* `"Unexpected key with value <input>"`
* - `Forbidden` → `"Forbidden operation"`
* - `OneOf` → `"Expected exactly one member to match"` or
* `"Expected exactly one member to match the input <input>"`
*
* **Example** (Formatting Standard Schema issues with defaultLeafHook)
*
* ```ts import.meta.vitest
* import { SchemaIssue } from "effect"
*
* const formatter = SchemaIssue.makeFormatterStandardSchemaV1({
* leafHook: SchemaIssue.defaultLeafHook
* })
* formatter(new SchemaIssue.MissingKey(undefined)) // => { issues: [{ path: [], message: "Missing key" }] }
* ```
*
* @see {@link LeafHook}
* @see {@link makeFormatterStandardSchemaV1}
*
* @stability stable
* @category formatting
* @since 4.0.0
*/
const defaultLeafHook = (issue) => {
const message = findMessage(issue);
if (message !== void 0) return message;
switch (issue._tag) {
case "InvalidType":
return getExpectedMessage(getExpected(issue.ast), issue);
case "InvalidValue": {
const expected = findExpected(issue);
if (expected !== void 0) return getExpectedMessage(expected, issue);
const input = formatInput(issue);
return input === void 0
? "Expected a valid value"
: `Invalid data ${input}`;
}
case "MissingKey":
return "Missing key";
case "UnexpectedKey": {
const input = formatInput(issue);
return input === void 0
? "Expected no excess property"
: `Unexpected key with value ${input}`;
}
case "Forbidden":
return "Forbidden operation";
case "OneOf": {
const input = formatInput(issue);
return input === void 0
? "Expected exactly one member to match"
: `Expected exactly one member to match the input ${input}`;
}
}
};
/**
* Returns the built-in {@link CheckHook} used by default formatters.
*
* **When to use**
*
* Use as the default filter renderer when customizing only the {@link LeafHook}.
*
* **Details**
*
* - Looks for a `message` annotation on the inner issue first, then on the
* filter itself.
* - Returns `undefined` when no annotation is found, causing the formatter to
* fall back to `"Expected <filter>"` or, when the filter reports input,
* `"Expected <filter>, got <input>"`.
*
* @see {@link CheckHook}
* @see {@link makeFormatterStandardSchemaV1}
*
* @stability stable
* @category formatting
* @since 4.0.0
*/
const defaultCheckHook = (issue) =>
findMessage(issue.issue) ?? findMessage(issue);
function formatInput(issue) {
return hasInput(issue) ? format$1(issue.input) : void 0;
}
function findExpected(issue) {
const expected = issue.annotations?.expected;
return typeof expected === "string" ? expected : void 0;
}
function getExpectedMessage(expected, issue) {
const input = formatInput(issue);
return input === void 0
? `Expected ${expected}`
: `Expected ${expected}, got ${input}`;
}
function formatCheck(check) {
const expected = check.annotations?.expected;
if (typeof expected === "string") return expected;
switch (check._tag) {
case "Filter":
return "<filter>";
case "FilterGroup":
return check.checks.map((check) => formatCheck(check)).join(" & ");
}
}
/**
* Creates a {@link Formatter} that converts an {@link Issue} into a
* human-readable multi-line string.
*
* **When to use**
*
* Use when you need to format a `SchemaIssue.Issue` as error messages for
* logging, CLI output, or developer-facing diagnostics.
*
* **Details**
*
* - Flattens the issue tree into `{ message, path }` entries using
* {@link defaultLeafHook} and {@link defaultCheckHook}.
* - Includes reported input in default messages when the node producing the
* message has an `input` field.
* - Each entry is rendered as `"<message>"` or `"<message>\n at <path>"`.
* - Multiple entries are joined with newlines.
*
* **Gotchas**
*
* Formatting an issue can disclose input retained with `reportInput: true`.
* Wrapper inputs are not inherited by child messages, and custom messages are
* returned unchanged.
*
* **Example** (Formatting an issue as a string)
*
* ```ts import.meta.vitest
* import { SchemaIssue } from "effect"
*
* const formatter = SchemaIssue.makeFormatterDefault()
* formatter(new SchemaIssue.MissingKey(undefined)) // => "Missing key"
* ```
*
* @see {@link makeFormatterStandardSchemaV1} — produces Standard Schema V1 format instead
* @see {@link Formatter}
*
* @stability stable
* @category formatting
* @since 4.0.0
*/
function makeFormatterDefault() {
return (issue) => formatIssue(issue, "");
}
/** @internal */
const defaultFormatter = /*#__PURE__*/ makeFormatterDefault();
function formatIssue(issue, path) {
let message;
switch (issue._tag) {
case "Filter": {
const annotated = defaultCheckHook(issue);
if (annotated !== void 0) message = annotated;
else {
if (issue.issue._tag !== "InvalidValue")
return formatIssue(issue.issue, path);
const expected = findExpected(issue.issue);
message =
expected === void 0
? getExpectedMessage(formatCheck(issue.filter), issue)
: getExpectedMessage(expected, issue.issue);
}
break;
}
case "Encoding":
return formatIssue(issue.issue, path);
case "Pointer":
return formatIssue(issue.issue, path + formatPath(issue.path));
case "Composite":
case "AnyOf":
if (issue._tag === "Composite" || issue.issues.length > 0)
return issue.issues.map((issue) => formatIssue(issue, path)).join("\n");
message =
findMessage(issue) ?? getExpectedMessage(getExpected(issue.ast), issue);
break;
default:
message = defaultLeafHook(issue);
}
return path ? `${message}\n at ${path}` : message;
}
function findMessage(issue) {
if (issue._tag === "Pointer") return;
if (issue._tag === "Encoding") return findMessage(issue.issue);
const message = (
issue._tag === "Filter"
? issue.filter.annotations
: "annotations" in issue
? issue.annotations
: issue.ast.annotations
)?.[
issue._tag === "MissingKey"
? "messageMissingKey"
: issue._tag === "UnexpectedKey"
? "messageUnexpectedKey"
: "message"
];
if (typeof message === "string") return message;
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/schema/cause.js
/** @internal */
function getSchemaIssue(cause) {
let issue;
for (const reason of cause.reasons) {
if (!isFailReason(reason) || !isIssue(reason.error)) return;
issue ??= reason.error;
}
return issue;
}
/** @internal */
function getSchemaIssueOrThrow(cause, message) {
const issue = getSchemaIssue(cause);
if (issue === void 0) throw new Error(message, { cause });
return issue;
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/SchemaGetter.js
const makeGetter = (fields) =>
Object.assign(Object.create(Prototype$1), fields);
const passthrough_$1 = /*#__PURE__*/ makeGetter({ _tag: "Passthrough" });
function passthrough$1() {
return passthrough_$1;
}
/**
* Creates a getter that applies a pure function to present values.
*
* **When to use**
*
* Use when you need a schema getter for a pure, infallible transformation
* between types.
* - Building encode/decode pairs for `Schema.decodeTo`.
*
* **Details**
*
* - This is the most commonly used constructor.
* - Transforms `Some(e)` to `Some(f(e))` and leaves `None` unchanged.
* - Skips `None` inputs — only called when a value is present.
* - Never fails.
*
* **Example** (Transforming strings to numbers)
*
* ```ts import.meta.vitest
* import { Schema, SchemaGetter } from "effect"
*
* const NumberFromString = Schema.String.pipe(
* Schema.decodeTo(Schema.Number, {
* decode: SchemaGetter.transform((s) => Number(s)),
* encode: SchemaGetter.transform((n) => String(n))
* })
* )
* Schema.decodeSync(NumberFromString)("42") // => 42
* ```
*
* @see {@link transformEffect} when the transformation returns an `Effect`
* @see {@link transformOptional} when you need to handle `None` inputs
* @see {@link passthrough} when no transformation is needed
*
* @stability stable
* @category transforming
* @since 4.0.0
*/
function transform$1(f) {
return makeGetter({
_tag: "Transform",
transform: f,
});
}
/**
* Coerces any value to a `string` using the global `String()` constructor.
*
* **When to use**
*
* Use when you need a schema getter to coerce a present encoded value to a
* string with `String()`.
*
* **Details**
*
* The getter is pure, never fails, and delegates to `globalThis.String`.
*
* **Example** (Coercing to a string)
*
* ```ts import.meta.vitest
* import { Effect, Option, SchemaGetter } from "effect"
*
* const toString = SchemaGetter.String<number>()
* Effect.runSync(SchemaGetter.run(toString, Option.some(42), {})) // => Option.some("42")
* ```
*
* @see {@link transform} for custom string conversions
*
* @stability stable
* @category converting
* @since 4.0.0
*/
function String$3() {
return transform$1(globalThis.String);
}
/**
* Coerces any value to a `number` using the global `Number()` constructor.
*
* **When to use**
*
* Use when you need a schema getter to coerce a present encoded value to a
* number with `Number()`.
*
* **Details**
*
* The getter is pure, never fails, and delegates to `globalThis.Number`. It may
* produce `NaN` for non-numeric inputs.
*
* **Example** (Coercing to a number)
*
* ```ts import.meta.vitest
* import { Effect, Option, SchemaGetter } from "effect"
*
* const toNumber = SchemaGetter.Number<string>()
* Effect.runSync(SchemaGetter.run(toNumber, Option.some("42"), {})) // => Option.some(42)
* ```
*
* @see {@link transformEffect} for effectful or validated number parsing
*
* @stability stable
* @category converting
* @since 4.0.0
*/
function Number$3() {
return transform$1(globalThis.Number);
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/SchemaTransformation.js
/**
* Constructs schema middleware from its decode and encode functions.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Middleware = class extends Class$1 {
_tag = "Middleware";
decode;
encode;
constructor(decode, encode) {
super();
this.decode = decode;
this.encode = encode;
}
flip() {
return new Middleware(this.encode, this.decode);
}
};
const TypeId$4 = "~effect/SchemaTransformation/Transformation";
/**
* Constructs a bidirectional schema transformation from its decode and encode getters.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Transformation = class extends Class$1 {
[TypeId$4] = TypeId$4;
_tag = "Transformation";
decode;
encode;
constructor(decode, encode) {
super();
this.decode = decode;
this.encode = encode;
}
flip() {
return new Transformation(this.encode, this.decode);
}
};
/**
* Returns `true` if `u` is a `Transformation` instance.
*
* **When to use**
*
* Use to check whether a value is already a schema transformation before
* wrapping it.
*
* **Details**
*
* - Pure predicate, no side effects.
* - Acts as a TypeScript type guard.
*
* **Example** (Checking a value)
*
* ```ts import.meta.vitest
* import { SchemaTransformation } from "effect"
*
* SchemaTransformation.isTransformation(SchemaTransformation.trim()) // => true
* SchemaTransformation.isTransformation({ decode: null, encode: null }) // => false
* ```
*
* @see {@link Transformation}
* @see {@link makeTransformation}
*
* @stability stable
* @category guards
* @since 4.0.0
*/
function isTransformation(u) {
return hasProperty(u, TypeId$4) && u[TypeId$4] === TypeId$4;
}
/**
* Constructs a `Transformation` from an object with `decode` and `encode`
* `Getter`s. If the input is already a `Transformation`, returns it as-is.
*
* **When to use**
*
* Use when you already have schema getter instances and want to pair them into
* a schema transformation.
* - You want idempotent wrapping (won't double-wrap).
*
* **Details**
*
* - Returns the input unchanged if it is already a `Transformation`.
*
* **Example** (Wrapping existing getters)
*
* ```ts import.meta.vitest
* import { SchemaGetter, SchemaTransformation } from "effect"
*
* const t = SchemaTransformation.makeTransformation({
* decode: SchemaGetter.transform<number, string>((s) => Number(s)),
* encode: SchemaGetter.transform<string, number>((n) => String(n))
* })
* t._tag // => "Transformation"
* ```
*
* @see {@link transform} — simpler constructor from pure functions
* @see {@link transformEffect} — constructor from effectful functions
* @see {@link Transformation}
*
* @stability stable
* @category constructors
* @since 3.10.0
*/
const makeTransformation = (options) => {
if (isTransformation(options)) return options;
return new Transformation(options.decode, options.encode);
};
const passthrough_ = /*#__PURE__*/ new Transformation(
/*#__PURE__*/ passthrough$1(),
/*#__PURE__*/ passthrough$1(),
);
function passthrough() {
return passthrough_;
}
/**
* Decodes a `string` into a `number` and encodes a `number` back to a
* `string`.
*
* **When to use**
*
* Use when you need a schema transformation to parse numeric strings from APIs,
* form data, or URL parameters.
*
* **Details**
*
* Decoding coerces the string to a number like `Number(s)`. Encoding coerces
* the number to a string like `String(n)`. This does not validate that the
* result is finite; combine with `Schema.Finite` or `Schema.Int` for stricter
* checks.
*
* **Example** (Converting a string to a number)
*
* ```ts import.meta.vitest
* import { Schema, SchemaTransformation } from "effect"
*
* const schema = Schema.String.pipe(
* Schema.decodeTo(Schema.Number, SchemaTransformation.numberFromString)
* )
* Schema.decodeSync(schema)("42") // => 42
* ```
*
* @see {@link bigintFromString}
* @see {@link transform}
*
* @stability stable
* @category converting
* @since 4.0.0
*/
const numberFromString = /*#__PURE__*/ new Transformation(
/*#__PURE__*/ Number$3(),
/*#__PURE__*/ String$3(),
);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/SchemaAST.js
/**
* Represents Effect schemas as runtime trees.
*
* Every `Schema` has an AST made from nodes for declarations, primitives,
* literals, arrays, objects, unions, suspended schemas, checks, annotations,
* encoding links, and parsing context. Most users work with the higher-level
* `Schema` module. Use `SchemaAST` when you need to inspect schema nodes, build
* ASTs programmatically, change encoded or decoded views, collect issues, or
* run low-level schema checks.
*
* @stability stable
* @since 4.0.0
*/
function makeGuard(tag) {
return (ast) => ast._tag === tag;
}
/**
* Narrows an {@link AST} to {@link Declaration}.
*
* **When to use**
*
* Use to recognize declaration AST nodes before running declaration-specific
* handling.
*
* @see {@link Declaration} for the AST node type narrowed by this guard
*
* @stability stable
* @category guards
* @since 3.10.0
*/
const isDeclaration = /*#__PURE__*/ makeGuard("Declaration");
/**
* Narrows an {@link AST} to {@link Never}.
*
* **When to use**
*
* Use to detect the AST node for a schema that can never match before handling
* other schema variants.
*
* @see {@link Never} for the AST node type narrowed by this guard
* @see {@link never} for the singleton `Never` AST instance
*
* @stability stable
* @category guards
* @since 4.0.0
*/
const isNever = /*#__PURE__*/ makeGuard("Never");
/**
* Narrows an {@link AST} to {@link Literal}.
*
* **When to use**
*
* Use to recognize exact string, number, boolean, or bigint literal AST nodes.
*
* @see {@link Literal} for the AST node type narrowed by this guard
* @see {@link LiteralValue} for the values stored by literal nodes
*
* @stability stable
* @category guards
* @since 3.10.0
*/
const isLiteral = /*#__PURE__*/ makeGuard("Literal");
/**
* Narrows an {@link AST} to {@link UniqueSymbol}.
*
* @stability stable
* @category guards
* @since 3.10.0
*/
const isUniqueSymbol = /*#__PURE__*/ makeGuard("UniqueSymbol");
/**
* Narrows an {@link AST} to {@link Arrays}.
*
* **When to use**
*
* Use to recognize array-like AST nodes before reading their element, rest, or
* mutability metadata.
*
* @see {@link Arrays} for the AST node type narrowed by this guard
*
* @stability stable
* @category guards
* @since 4.0.0
*/
const isArrays = /*#__PURE__*/ makeGuard("Arrays");
/**
* Narrows an {@link AST} to {@link Objects}.
*
* @stability stable
* @category guards
* @since 4.0.0
*/
const isObjects = /*#__PURE__*/ makeGuard("Objects");
/**
* Narrows an {@link AST} to {@link Suspend}.
*
* @stability stable
* @category guards
* @since 3.10.0
*/
const isSuspend = /*#__PURE__*/ makeGuard("Suspend");
/**
* Constructs a {@link Link}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Link = class {
to;
transformation;
constructor(to, transformation) {
this.to = to;
this.transformation = transformation;
}
};
/** @internal */
const defaultParseOptions = {};
/**
* Constructs a {@link Context}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Context = class {
isOptional;
isMutable;
/** Used for constructor default values (e.g. `withConstructorDefault` API) */
constructorDefault;
annotations;
constructor(
isOptional,
isMutable,
constructorDefault = void 0,
annotations = void 0,
) {
this.isOptional = isOptional;
this.isMutable = isMutable;
this.constructorDefault = constructorDefault;
this.annotations = annotations;
}
};
const TypeId$3 = "~effect/Schema";
var ASTNodeImpl = class {
[TypeId$3] = TypeId$3;
annotations;
checks;
encoding;
context;
constructor(
annotations = void 0,
checks = void 0,
encoding = void 0,
context = void 0,
) {
this.annotations = annotations;
this.checks = checks;
this.encoding = encoding;
this.context = context;
}
toString() {
return `<${this._tag}>`;
}
};
/**
* Constructs a {@link Declaration}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Declaration = class extends ASTNodeImpl {
_tag = "Declaration";
typeParameters;
run;
encodingChecks;
/**
* Parser factory {@link flip} swaps in, so a declaration can behave
* differently when encoding. `undefined` reuses `run`.
*/
encodingRun;
constructor(
typeParameters,
run,
annotations,
checks,
encoding,
context,
encodingChecks,
encodingRun,
) {
super(annotations, checks, encoding, context);
this.typeParameters = typeParameters;
this.run = run;
this.encodingChecks = encodingChecks;
this.encodingRun = encodingRun;
}
/** @internal */
getParser() {
let run;
return (input, options) => {
if (input === missing) return missingExit;
return (run ??= this.run(this.typeParameters))(input, this, options);
};
}
_rebuild(recur, checks, encodingChecks, run, encodingRun) {
const tps = mapOrSame(this.typeParameters, recur);
return tps === this.typeParameters &&
checks === this.checks &&
encodingChecks === this.encodingChecks &&
run === this.run &&
encodingRun === this.encodingRun
? this
: new Declaration(
tps,
run,
this.annotations,
checks,
void 0,
this.context,
encodingChecks,
encodingRun,
);
}
/** @internal */
recur(recur) {
return this._rebuild(
recur,
this.checks,
this.encodingChecks,
this.run,
this.encodingRun,
);
}
/** @internal */
flip(recur) {
return this._rebuild(
recur,
this.encodingChecks,
this.checks,
this.encodingRun ?? this.run,
this.run,
);
}
/** @internal */
getExpected() {
const expected = this.annotations?.expected;
if (typeof expected === "string") return expected;
return "<Declaration>";
}
};
/**
* Constructs a {@link Null}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Null$1 = class extends ASTNodeImpl {
_tag = "Null";
/** @internal */
getParser() {
return fromConst(this, null);
}
/** @internal */
getExpected() {
return "null";
}
};
const null_ = /*#__PURE__*/ new Null$1();
/**
* Constructs a {@link Unknown}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Unknown = class extends ASTNodeImpl {
_tag = "Unknown";
/** @internal */
getParser() {
return fromRefinement(this, isUnknown);
}
/** @internal */
getExpected() {
return "unknown";
}
};
/**
* Provides the singleton {@link Unknown} AST instance.
*
* **When to use**
*
* Use when you need the reusable AST singleton for a schema node that accepts
* every value while keeping parsed values opaque.
*
* @see {@link any} for the singleton that accepts every value as `any`
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const unknown = /*#__PURE__*/ new Unknown();
/**
* Constructs a {@link Literal}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Literal$1 = class extends ASTNodeImpl {
_tag = "Literal";
literal;
constructor(literal, annotations, checks, encoding, context) {
super(annotations, checks, encoding, context);
if (typeof literal === "number" && !globalThis.Number.isFinite(literal))
throw new Error(
`A numeric literal must be finite, got ${format$1(literal)}`,
);
this.literal = literal;
}
/** @internal */
getParser() {
return fromConst(this, this.literal);
}
/** @internal */
matchPart(s, _options) {
return s === globalThis.String(this.literal) ? this.literal : void 0;
}
/** @internal */
toCodecJson() {
return typeof this.literal === "bigint" ? literalToString(this) : this;
}
/** @internal */
toCodecStringTree() {
return typeof this.literal === "string" ? this : literalToString(this);
}
/** @internal */
getExpected() {
return typeof this.literal === "string"
? JSON.stringify(this.literal)
: globalThis.String(this.literal);
}
};
function literalToString(ast) {
const literalAsString = globalThis.String(ast.literal);
return replaceEncoding(ast, [
new Link(
new Literal$1(literalAsString),
new Transformation(
transform$1(() => ast.literal),
transform$1(() => literalAsString),
),
),
]);
}
/**
* Constructs a {@link String}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const String$2 = class extends ASTNodeImpl {
_tag = "String";
/** @internal */
getParser() {
return fromRefinement(this, isString$1);
}
/** @internal */
matchPart(s, options) {
const checks = this.checks;
return checks &&
!options.disableChecks &&
collectIssues(checks, s, void 0, this, options)
? void 0
: s;
}
/** @internal */
getExpected() {
return "string";
}
};
/**
* Provides the singleton {@link String} AST instance.
*
* **When to use**
*
* Use as the shared `SchemaAST` node for unconstrained JavaScript strings.
*
* @see {@link String} for the AST node class
* @see {@link isString} for narrowing an AST to a string node
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const string = /*#__PURE__*/ new String$2();
/**
* Constructs a {@link Number}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Number$2 = class extends ASTNodeImpl {
_tag = "Number";
/** @internal */
getParser() {
return fromRefinement(this, isNumber);
}
/** @internal */
matchKey(s, options) {
return this._match(isStringNumberRegExp, s, options);
}
/** @internal */
matchPart(s, options) {
return this._match(isStringFiniteRegExp, s, options);
}
_match(regexp, s, options) {
if (!regexp.test(s)) return void 0;
const value = globalThis.Number(s);
if (options.disableChecks || !this.checks) return value;
return collectIssues(this.checks, value, void 0, this, options)
? void 0
: value;
}
/** @internal */
toCodecJson() {
if (
this.checks &&
(hasCheck(this.checks, "effect/schema/isFinite") ||
hasCheck(this.checks, "effect/schema/isInt"))
)
return this;
return replaceEncoding(this, [numberToJson]);
}
/** @internal */
toCodecStringTree() {
if (this.toCodecJson() === this)
return replaceEncoding(this, [finiteToString]);
return replaceEncoding(this, [numberToString]);
}
/** @internal */
getExpected() {
return "number";
}
};
function hasCheck(checks, id) {
return checks.some(
(check) =>
check.annotations?.representation?.id === id ||
(check._tag === "FilterGroup" && hasCheck(check.checks, id)),
);
}
/**
* Provides the singleton {@link Number} AST instance.
*
* **When to use**
*
* Use when you need the canonical `SchemaAST` node for schemas that accept any
* JavaScript number value.
*
* @see {@link Number} for the AST node class and serialization behavior
* @see {@link Literal} for exact finite numeric literal AST nodes
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const number = /*#__PURE__*/ new Number$2();
/**
* Constructs a {@link Arrays}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Arrays = class extends ASTNodeImpl {
_tag = "Arrays";
isMutable;
elements;
rest;
encodingChecks;
constructor(
isMutable,
elements,
rest,
annotations,
checks,
encoding,
context,
encodingChecks,
) {
super(annotations, checks, encoding, context);
this.isMutable = isMutable;
this.elements = elements;
this.rest = rest;
this.encodingChecks = encodingChecks;
let hasOptional = false;
for (let i = 0; i < elements.length; i++)
if (isOptional(elements[i])) hasOptional = true;
else if (hasOptional)
throw new Error(
"A required element cannot follow an optional element. ts(1257)",
);
if (hasOptional && rest.length > 1)
throw new Error(
"A required element cannot follow an optional element. ts(1257)",
);
for (let i = 1; i < rest.length; i++)
if (isOptional(rest[i]))
throw new Error(
"An optional element cannot follow a rest element. ts(1266)",
);
}
/** @internal */
getParser(compile, compileField = compile) {
const ast = this;
let elements;
let rest;
const elementLen = ast.elements.length;
const tailLen = Math.max(0, ast.rest.length - 1);
function getParser(tailThreshold, index) {
if (index < elementLen) return elements[index];
else if (index >= tailThreshold) return rest[index - tailThreshold + 1];
return rest[0];
}
const finish = (state) => {
const { input, len, options } = state;
if (ast.rest.length === 0 && len > elementLen)
for (let i = elementLen; i < len; i++) {
const unexpected = new UnexpectedKey(ast, input[i], options);
const issue = new Pointer([i], unexpected);
if (options.errors === "all") {
if (state.issues) state.issues.push(issue);
else state.issues = [issue];
} else return fail$1(new Composite(ast, [issue], input, options));
}
if (state.issues)
return fail$1(new Composite(ast, state.issues, input, options));
return succeed(state.output);
};
const parse = (input, options) => {
const len = input.length;
const state = {
ast,
getParser,
input,
len,
tailThreshold: Math.max(elementLen, len - tailLen),
output: new globalThis.Array(len),
issues: void 0,
options,
};
const end =
ast.rest.length === 0
? elementLen
: Math.max(len, elementLen + tailLen);
const concurrency =
options.concurrency === void 0
? 1
: resolveConcurrency(options.concurrency);
const eff =
concurrency === 1
? parseArray(state, input, 0, end)
: parseArrayConcurrent(state, input, {
concurrency,
end,
});
if (!eff) return finish(state);
if (effectIsExit(eff)) return flatMapEager(eff, () => finish(state));
let first = true;
return suspend(() => {
if (!first) return parse(input, options);
first = false;
return flatMap(eff, () => finish(state));
});
};
return (input, options) => {
if (input === missing) return missingExit;
try {
if (!Array.isArray(input))
return fail$1(new InvalidType(ast, input, options));
if (!elements) {
elements = ast.elements.map((ast) => ({
ast,
parser: compileField(ast),
}));
rest = ast.rest.map((ast) => ({
ast,
parser: compileField(ast),
}));
}
return parse(input, options);
} catch (error) {
return die(error);
}
};
}
_rebuild(recur, checks, encodingChecks) {
const elements = mapOrSame(this.elements, recur);
const rest = mapOrSame(this.rest, recur);
return elements === this.elements &&
rest === this.rest &&
checks === this.checks &&
encodingChecks === this.encodingChecks
? this
: new Arrays(
this.isMutable,
elements,
rest,
this.annotations,
checks,
void 0,
this.context,
encodingChecks,
);
}
/** @internal */
recur(recur) {
return this._rebuild(recur, this.checks, this.encodingChecks);
}
/** @internal */
flip(recur) {
return this._rebuild(recur, this.encodingChecks, this.checks);
}
/** @internal */
getExpected() {
return "array";
}
};
/** @internal */
function stepArray(s, item, exit, i) {
if (exit._tag === "Failure") return wrapPropertyKeyIssue(s, s.ast, i, exit);
const value = exit === sameExit ? item : exit[args];
if (value !== missing) s.output[i] = value;
else {
const p = s.getParser(s.tailThreshold, i);
if (isOptional(p.ast)) return;
const issue = new Pointer([i], new MissingKey(p.ast.context?.annotations));
if (s.options.errors === "all") {
if (s.issues) s.issues.push(issue);
else s.issues = [issue];
} else return fail$2(new Composite(s.ast, [issue], s.input, s.options));
}
}
const parseArrayOptions = {
onItem(s, item, i) {
const value = i < s.len ? item : missing;
return s.getParser(s.tailThreshold, i).parser(value, s.options);
},
step: stepArray,
};
/** @internal */
const parseArray = /*#__PURE__*/ iterateEager()(parseArrayOptions);
const parseArrayConcurrent =
/*#__PURE__*/ iterateConcurrent()(parseArrayOptions);
const wrapPropertyKeyIssue = (s, ast, key, exit) => {
if (exit.cause.reasons.length === 0) return exit;
const issue = getSchemaIssue(exit.cause);
if (issue === void 0)
return failCause(
map(
exit.cause,
(issue) =>
new Composite(ast, [new Pointer([key], issue)], s.input, s.options),
),
);
const pointer = new Pointer([key], issue);
if (s.options.errors === "all") {
if (s.issues) s.issues.push(pointer);
else s.issues = [pointer];
} else return fail$2(new Composite(ast, [pointer], s.input, s.options));
};
/**
* floating point or integer, with optional exponent
* @internal
*/
const FINITE_PATTERN = "[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?";
/**
* Returns the object keys that match the index signature parameter schema.
* @internal
*/
function getIndexSignatureKeys(
input,
parameter,
options = defaultParseOptions,
) {
let stringKeys;
let symbolKeys;
function go(parameter) {
switch (parameter._tag) {
case "String":
case "TemplateLiteral":
return (stringKeys ??= Object.keys(input)).filter(
(k) => parameter.matchPart(k, options) !== void 0,
);
case "Number":
return (stringKeys ??= Object.keys(input)).filter(
(k) => parameter.matchKey(k, options) !== void 0,
);
case "Symbol":
return (symbolKeys ??= Object.getOwnPropertySymbols(input)).filter(
(k) =>
Object.prototype.propertyIsEnumerable.call(input, k) &&
parameter.matchKey(k, options) !== void 0,
);
case "Union":
return [...new Set(parameter.types.flatMap(go))];
default:
return [];
}
}
return go(parameterFromPropertyKey(toEncoded(parameter)));
}
/**
* Constructs a {@link PropertySignature}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const PropertySignature = class {
name;
type;
constructor(name, type) {
this.name = name;
this.type = type;
}
};
function isIndexSignatureParameterSide(ast) {
switch (ast._tag) {
case "String":
case "Number":
case "Symbol":
case "TemplateLiteral":
return true;
case "Union":
return ast.types.every(isIndexSignatureParameterSide);
default:
return false;
}
}
function isIndexSignatureParameterEncodedSide(ast) {
const encoded = getLastEncoding(ast);
switch (encoded._tag) {
case "String":
case "Number":
case "Symbol":
case "TemplateLiteral":
return true;
case "Union":
return encoded.types.every(isIndexSignatureParameterEncodedSide);
default:
return false;
}
}
function isIndexSignatureParameter(ast) {
return (
isIndexSignatureParameterSide(ast) &&
isIndexSignatureParameterEncodedSide(ast)
);
}
/**
* Constructs a {@link IndexSignature}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const IndexSignature = class {
parameter;
type;
constructor(parameter, type) {
if (!isIndexSignatureParameter(parameter))
throw new Error(`Invalid index signature parameter ${parameter._tag}`);
this.parameter = parameter;
this.type = type;
if (isOptional(type) && !containsUndefined(type))
throw new Error(
"Cannot use `Schema.optionalKey` with index signatures, use `Schema.optional` instead.",
);
}
};
/**
* Constructs a {@link Objects}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Objects = class extends ASTNodeImpl {
_tag = "Objects";
propertySignatures;
indexSignatures;
encodingChecks;
constructor(
propertySignatures,
indexSignatures,
annotations,
checks,
encoding,
context,
encodingChecks,
) {
super(annotations, checks, encoding, context);
this.propertySignatures = propertySignatures;
this.indexSignatures = indexSignatures;
this.encodingChecks = encodingChecks;
}
/** @internal */
getParser(compile, compileField = compile) {
const ast = this;
const hasProperties = ast.propertySignatures.length;
const indexCount = ast.indexSignatures.length;
if (!hasProperties && !indexCount) return fromRefinement(ast, isNotNullish);
let properties;
let indexes;
const compileMembers = () => {
if (!properties) {
properties = ast.propertySignatures.map((ps) => ({
parser: compileField(ps.type),
name: ps.name,
type: ps.type,
}));
indexes = indexCount
? ast.indexSignatures.map((is) => ({
is,
parserKey: compile(parameterFromPropertyKey(is.parameter)),
parserValue: compileField(is.type),
}))
: void 0;
}
return properties;
};
const makeFallback = () => {
const expectedKeys = new Set(
ast.propertySignatures.map((ps) =>
typeof ps.name === "number" ? globalThis.String(ps.name) : ps.name,
),
);
const finishIndex = (s, key, k2, inputValue, exitValue) => {
if (exitValue._tag === "Failure")
return wrapPropertyKeyIssue(s, ast, key, exitValue) ?? void_;
const value = exitValue === sameExit ? inputValue : exitValue[args];
if (k2 !== missing && value !== missing) {
if (
hasProperties &&
(expectedKeys.has(key) ||
expectedKeys.has(
typeof k2 === "number" ? globalThis.String(k2) : k2,
))
)
return void_;
assignProperty(s.out, k2, value);
}
return void_;
};
const parseIndex = (s, key, index, exitKey) => {
if (!exitKey) {
const eff = index.parserKey(key, s.options);
if (!effectIsExit(eff))
return flatMap(exit(eff), (exit) =>
parseIndex(s, key, index, exit),
);
exitKey = eff;
}
if (exitKey._tag === "Failure")
return wrapPropertyKeyIssue(s, ast, key, exitKey) ?? void_;
const k2 = exitKey === sameExit ? key : exitKey[args];
const inputValue = s.input[key];
const result = index.parserValue(inputValue, s.options);
return effectIsExit(result)
? finishIndex(s, key, k2, inputValue, result)
: flatMap(exit(result), (exit) =>
finishIndex(s, key, k2, inputValue, exit),
);
};
const parseStringIndex = (s, key, index) => {
const inputValue = s.input[key];
const result = index.parserValue(inputValue, s.options);
return effectIsExit(result)
? finishIndex(s, key, key, inputValue, result)
: flatMap(exit(result), (exit) =>
finishIndex(s, key, key, inputValue, exit),
);
};
const parseIndexes = indexCount
? iterateConcurrent()({
onItem: (s, [key, index]) =>
index.is.parameter === string
? parseStringIndex(s, key, index)
: parseIndex(s, key, index),
step: (_s, _item, exit) =>
exit._tag === "Failure" ? exit : void 0,
})
: void 0;
return fnUntracedEager(function* (input, options) {
if (input === missing) return missing;
if (
!(
typeof input === "object" &&
input !== null &&
!Array.isArray(input)
)
)
return yield* fail$1(new InvalidType(ast, input, options));
compileMembers();
const record = input;
const out = {};
const state = {
ast,
input: record,
out,
issues: void 0,
options,
};
const errorsAllOption = options.errors === "all";
const onExcessPropertyError = options.onExcessProperty === "error";
const concurrency =
options.concurrency === void 0
? 1
: resolveConcurrency(options.concurrency);
const indexKeys =
indexCount && onExcessPropertyError
? ast.indexSignatures.map((index) =>
getIndexSignatureKeys(record, index.parameter, options),
)
: void 0;
if (onExcessPropertyError) {
const coveredKeys = indexKeys ? new Set(expectedKeys) : expectedKeys;
if (indexKeys)
for (const keys of indexKeys)
for (const key of keys) coveredKeys.add(key);
const inputKeys = Reflect.ownKeys(record);
for (let i = 0; i < inputKeys.length; i++) {
const key = inputKeys[i];
if (
!coveredKeys.has(key) &&
Object.prototype.propertyIsEnumerable.call(record, key)
) {
const unexpected = new UnexpectedKey(ast, record[key], options);
const issue = new Pointer([key], unexpected);
if (errorsAllOption) {
if (state.issues) state.issues.push(issue);
else state.issues = [issue];
continue;
} else
return yield* fail$1(
new Composite(ast, [issue], input, options),
);
}
}
}
if (hasProperties) {
const eff =
concurrency === 1
? parseProperties(state, properties)
: parsePropertiesConcurrent(state, properties, { concurrency });
if (eff) yield* eff;
}
if (indexCount && concurrency === 1)
for (let i = 0; i < indexCount; i++) {
const index = indexes[i];
const parse =
index.is.parameter === string ? parseStringIndex : parseIndex;
const keys =
indexKeys?.[i] ??
(index.is.parameter === string
? Object.keys(record)
: getIndexSignatureKeys(record, index.is.parameter, options));
for (let j = 0; j < keys.length; j++) {
const eff = parse(state, keys[j], index);
if (!effectIsExit(eff)) yield* eff;
else if (eff._tag === "Failure") return yield* eff;
}
}
else if (parseIndexes) {
const keyPairs = empty$1();
for (let i = 0; i < indexCount; i++) {
const index = indexes[i];
const keys =
indexKeys?.[i] ??
(index.is.parameter === string
? Object.keys(record)
: getIndexSignatureKeys(record, index.is.parameter, options));
for (let j = 0; j < keys.length; j++)
keyPairs.push([keys[j], index]);
}
const eff = parseIndexes(state, keyPairs, { concurrency });
if (eff) yield* eff;
}
if (state.issues)
return yield* fail$1(
new Composite(ast, state.issues, input, options),
);
return out;
});
};
if (indexCount) return makeFallback();
let fallback;
const resume = (state, index, pending) => {
const property = properties[index];
return flatMap(exit(pending), (exit) => {
const terminal = stepProperty(state, property, exit);
if (terminal) return terminal;
const done = () => succeed(state.out);
const eff = parseProperties(state, properties.slice(index + 1));
return eff ? flatMapEager(eff, done) : done();
});
};
return (input, options) => {
if (input === missing) return missingExit;
if (
options.errors === "all" ||
options.onExcessProperty !== void 0 ||
(options.concurrency !== void 0 &&
resolveConcurrency(options.concurrency) !== 1)
)
return (fallback ??= makeFallback())(input, options);
if (
!(typeof input === "object" && input !== null && !Array.isArray(input))
)
return fail$1(new InvalidType(ast, input, options));
const props = compileMembers();
const record = input;
const out = {};
const state = {
ast,
input: record,
out,
issues: void 0,
options,
};
try {
for (let index = 0; index < props.length; index++) {
const property = props[index];
const name = property.name;
const hasKey = hasPropertySignature(record, name);
const value = hasKey ? record[name] : missing;
const exit = property.parser(value, options);
if (!effectIsExit(exit)) return resume(state, index, exit);
if (exit === sameExit) {
if (hasKey) assignProperty(out, name, value);
continue;
}
const terminal = stepProperty(state, property, exit);
if (terminal) return terminal;
}
} catch (error) {
return die(error);
}
return succeed(out);
};
}
_rebuild(recur, recurParameter, checks, encodingChecks) {
const props = mapOrSame(this.propertySignatures, (ps) => {
const t = recur(ps.type);
return t === ps.type ? ps : new PropertySignature(ps.name, t);
});
const indexes = mapOrSame(this.indexSignatures, (is) => {
const p = recurParameter(is.parameter);
const t = recur(is.type);
return p === is.parameter && t === is.type
? is
: new IndexSignature(p, t);
});
return props === this.propertySignatures &&
indexes === this.indexSignatures &&
checks === this.checks &&
encodingChecks === this.encodingChecks
? this
: new Objects(
props,
indexes,
this.annotations,
checks,
void 0,
this.context,
encodingChecks,
);
}
/** @internal */
flip(recur) {
return this._rebuild(recur, recur, this.encodingChecks, this.checks);
}
/** @internal */
recur(recur, recurParameter = recur) {
return this._rebuild(
recur,
recurParameter,
this.checks,
this.encodingChecks,
);
}
/** @internal */
getExpected() {
if (
this.propertySignatures.length === 0 &&
this.indexSignatures.length === 0
)
return "object | array";
return "object";
}
};
/** @internal */
function stepProperty(s, p, exit) {
if (exit._tag === "Failure")
return wrapPropertyKeyIssue(s, s.ast, p.name, exit);
if (exit === sameExit) return;
const value = exit[args];
if (value !== missing) {
assignProperty(s.out, p.name, value);
return;
}
delete s.out[p.name];
if (!isOptional(p.type)) {
const issue = new Pointer(
[p.name],
new MissingKey(p.type.context?.annotations),
);
if (s.options.errors === "all") {
if (s.issues) s.issues.push(issue);
else s.issues = [issue];
return;
} else return fail$2(new Composite(s.ast, [issue], s.input, s.options));
}
}
const parsePropertiesOptions = {
onItem(s, p) {
if (!hasPropertySignature(s.input, p.name))
return p.parser(missing, s.options);
const value = s.input[p.name];
assignProperty(s.out, p.name, value);
return p.parser(value, s.options);
},
step: stepProperty,
};
/** @internal */
const parseProperties = /*#__PURE__*/ iterateEager()(parsePropertiesOptions);
const parsePropertiesConcurrent = /*#__PURE__*/ iterateConcurrent()(
parsePropertiesOptions,
);
function combineChecks(a, b) {
if (!a) return b;
if (!b) return a;
return [...a, ...b];
}
/** @internal */
function struct(fields, checks, annotations) {
return new Objects(
Reflect.ownKeys(fields).map((key) => {
return new PropertySignature(key, fields[key].ast);
}),
[],
annotations,
checks,
);
}
/** @internal */
function getAST(self) {
return self.ast;
}
/** @internal */
function union(members, options, checks) {
return new Union$1(members.map(getAST), options, void 0, checks);
}
/** @internal */
function mutable$1(ast) {
if (ast.encoding) throw new Error("mutable does not support encodings");
return new Arrays(
true,
ast.elements,
ast.rest,
ast.annotations,
ast.checks,
void 0,
ast.context,
ast.encodingChecks,
);
}
const toCandidate = /*#__PURE__*/ memoizeIdempotent((ast) => {
while (true) {
if (isSuspend(ast)) return unknown;
const encoding = ast.encoding;
if (!encoding) return ast.recur?.(toCandidate, identity) ?? ast;
if (
encoding.some(
(link) =>
link.transformation._tag === "Middleware" &&
link.transformation.decode !== identity,
)
)
return unknown;
ast = encoding[encoding.length - 1].to;
}
});
function getCandidateTypes(ast) {
switch (ast._tag) {
case "Null":
return ["null"];
case "Undefined":
return ["undefined"];
case "String":
case "TemplateLiteral":
return ["string"];
case "Number":
return ["number"];
case "Boolean":
return ["boolean"];
case "Symbol":
case "UniqueSymbol":
return ["symbol"];
case "BigInt":
return ["bigint"];
case "Arrays":
return ["array"];
case "ObjectKeyword":
return ["object", "array", "function"];
case "Objects":
return ast.propertySignatures.length || ast.indexSignatures.length
? ["object"]
: [
"string",
"number",
"boolean",
"symbol",
"bigint",
"object",
"array",
"function",
];
case "Enum":
return Array.from(new Set(ast.enums.map(([, v]) => typeof v)));
case "Literal":
return [typeof ast.literal];
case "Union":
return Array.from(new Set(ast.types.flatMap(getCandidateTypes)));
default:
return [
"null",
"undefined",
"string",
"number",
"boolean",
"symbol",
"bigint",
"object",
"array",
"function",
];
}
}
/** @internal */
function collectSentinels(ast) {
switch (ast._tag) {
default:
return [];
case "Declaration": {
const s = ast.annotations?.[SENTINELS_ANNOTATION_KEY];
return Array.isArray(s) ? s : [];
}
case "Objects":
return ast.propertySignatures.flatMap((ps) => {
const type = ps.type;
if (!isOptional(type)) {
if (isLiteral(type))
return [
{
key: ps.name,
literal: type.literal,
},
];
if (isUniqueSymbol(type))
return [
{
key: ps.name,
literal: type.symbol,
},
];
}
return [];
});
case "Arrays":
return ast.elements.flatMap((e, i) => {
if (!isOptional(e)) {
if (isLiteral(e))
return [
{
key: i,
literal: e.literal,
},
];
if (isUniqueSymbol(e))
return [
{
key: i,
literal: e.symbol,
},
];
}
return [];
});
case "Union": {
if (ast.types.length === 0) return [];
const members = ast.types.map((type) =>
collectSentinels(toCandidate(type)),
);
return members[0].filter((s) =>
members.every((sentinels) =>
sentinels.some((o) => o.key === s.key && o.literal === s.literal),
),
);
}
case "Suspend":
return collectSentinels(ast.thunk());
}
}
const candidateIndexCache = /*#__PURE__*/ new WeakMap();
const emptyCandidates = /*#__PURE__*/ Object.freeze([]);
const getRuntimeType = (input) =>
input === null ? "null" : Array.isArray(input) ? "array" : typeof input;
const hasPropertySignature = (input, key) =>
key === "__proto__" ? Object.hasOwn(input, key) : key in input;
/** @internal */
function getCandidateIndex(types) {
let index = candidateIndexCache.get(types);
if (index) return index;
let bySentinel;
let sentinelCandidateCount = 0;
let otherwise;
let literalCandidates;
let onlyLiterals = true;
const literalOf = [];
for (let i = 0; i < types.length; i++) {
const a = types[i];
const encoded = toCandidate(a);
if (isNever(encoded)) continue;
if (isLiteral(encoded) || isUniqueSymbol(encoded)) {
literalCandidates ??= /* @__PURE__ */ new Map();
const literal = isLiteral(encoded) ? encoded.literal : encoded.symbol;
literalOf[i] = literal;
let arr = literalCandidates.get(literal);
if (!arr) literalCandidates.set(literal, (arr = []));
arr.push(i);
} else onlyLiterals = false;
const sentinels = collectSentinels(encoded);
if (sentinels.length) {
bySentinel ??= /* @__PURE__ */ new Map();
sentinelCandidateCount++;
for (const { key, literal } of sentinels) {
let entry = bySentinel.get(key);
if (!entry)
bySentinel.set(
key,
(entry = [/* @__PURE__ */ new Map(), /* @__PURE__ */ new Set()]),
);
entry[1].add(i);
let indexes = entry[0].get(literal);
if (!indexes)
entry[0].set(literal, (indexes = /* @__PURE__ */ new Set()));
indexes.add(i);
}
} else {
otherwise ??= {};
const candidateTypes = getCandidateTypes(encoded);
for (const t of candidateTypes) (otherwise[t] ??= []).push(i);
}
}
const fallbacks = {};
const getFallback = (type) =>
(fallbacks[type] ??= Object.freeze(otherwise?.[type] ?? emptyCandidates));
if (onlyLiterals && literalCandidates) {
literalCandidates.forEach(Object.freeze);
index = (input) => literalCandidates.get(input) ?? emptyCandidates;
} else if (bySentinel?.size === 1 && !otherwise) {
const [key, [byValue]] = bySentinel.entries().next().value;
const candidates = /* @__PURE__ */ new Map();
for (const [literal, indexes] of byValue)
candidates.set(literal, Object.freeze(Array.from(indexes)));
const all = Object.freeze(types.map((_, i) => i));
index = (input, isConstructor) => {
if (isObjectKeyword(input)) {
const value = hasPropertySignature(input, key) ? input[key] : void 0;
if (value !== void 0) return candidates.get(value) ?? emptyCandidates;
if (isConstructor) return all;
}
return emptyCandidates;
};
} else if (bySentinel) {
let commonSentinel;
for (const entry of bySentinel)
if (
(!commonSentinel || entry[1][0].size > commonSentinel[1][0].size) &&
entry[1][1].size === sentinelCandidateCount
)
commonSentinel = entry;
index = (input, isConstructor) => {
const runtimeType = getRuntimeType(input);
if (!isObjectKeyword(input)) return getFallback(runtimeType);
const selected = new Set(otherwise?.[runtimeType]);
let directKey;
if (commonSentinel) {
const [key, [byValue]] = commonSentinel;
const hasKey = hasPropertySignature(input, key);
const value = hasKey ? input[key] : void 0;
if (hasKey && (!isConstructor || value !== void 0)) {
const match = byValue.get(value);
if (!match) return getFallback(runtimeType);
for (const i of match) selected.add(i);
directKey = key;
}
}
if (directKey === void 0)
for (const [key, [byValue, all]] of bySentinel) {
const hasKey = hasPropertySignature(input, key);
const value = hasKey ? input[key] : void 0;
if (hasKey && (!isConstructor || value !== void 0)) {
const match = byValue.get(value);
if (match) for (const i of match) selected.add(i);
} else if (isConstructor) for (const i of all) selected.add(i);
}
for (const [key, [byValue, all]] of bySentinel) {
if (key === directKey) continue;
const hasKey = hasPropertySignature(input, key);
const value = hasKey ? input[key] : void 0;
if (hasKey && (!isConstructor || value !== void 0)) {
const match = byValue.get(value);
for (const i of selected)
if (all.has(i) && !match?.has(i)) selected.delete(i);
}
}
return Array.from(selected).sort((a, b) => a - b);
};
} else
index = (input) => {
const fallback = getFallback(getRuntimeType(input));
return literalCandidates
? fallback.filter(
(i) => literalOf[i] === void 0 || literalOf[i] === input,
)
: fallback;
};
candidateIndexCache.set(types, index);
return index;
}
/**
* Constructs a {@link Union}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Union$1 = class extends ASTNodeImpl {
_tag = "Union";
types;
options;
encodingChecks;
constructor(
types,
options,
annotations,
checks,
encoding,
context,
encodingChecks,
) {
super(annotations, checks, encoding, context);
this.types = types;
this.options = options;
this.encodingChecks = encodingChecks;
}
/** @internal */
getParser(compile, compileField) {
const ast = this;
const isConstructor = compileField !== void 0;
const parsers = [];
const parser = (i) => (parsers[i] ??= compile(ast.types[i]));
let index;
return (input, options) => {
if (input === missing) return missingExit;
const candidates = (index ??= getCandidateIndex(ast.types))(
input,
isConstructor,
);
if (candidates.length === 0)
return fail$1(new AnyOf(ast, [], input, options));
if (candidates.length === 1) {
const result = parser(candidates[0])(input, options);
if (result._tag === "Success") return result;
return effectIsExit(result)
? failSingleUnionCandidate(ast, result.cause, input, options)
: catchSingleUnionCandidate(ast, result, input, options);
}
return parseUnionCandidates(ast, parser, candidates, input, options);
};
}
_rebuild(recur, checks, encodingChecks) {
const types = mapOrSame(this.types, recur);
return types === this.types &&
checks === this.checks &&
encodingChecks === this.encodingChecks
? this
: new Union$1(
types,
this.options,
this.annotations,
checks,
void 0,
this.context,
encodingChecks,
);
}
/** @internal */
recur(recur) {
return this._rebuild(recur, this.checks, this.encodingChecks);
}
/** @internal */
flip(recur) {
return this._rebuild(recur, this.encodingChecks, this.checks);
}
/** @internal */
matchPart(s, options) {
for (const type of this.types) {
const out = type.matchPart(s, options);
if (out !== void 0) return out;
}
}
/** @internal */
getExpected(getExpected) {
const expected = this.annotations?.expected;
if (typeof expected === "string") return expected;
if (this.types.length === 0) return "never";
const types = this.types.map((type) => {
const encoded = toEncoded(type);
switch (encoded._tag) {
case "Arrays": {
const literals = encoded.elements.filter(isLiteral);
if (literals.length > 0)
return `${formatIsMutable(encoded.isMutable)}[ ${literals.map((e) => getExpected(e) + formatIsOptional(e.context?.isOptional)).join(", ")}, ... ]`;
break;
}
case "Objects": {
const literals = encoded.propertySignatures.filter((ps) =>
isLiteral(ps.type),
);
if (literals.length > 0)
return `{ ${literals.map((ps) => `${formatIsMutable(ps.type.context?.isMutable)}${formatPropertyKey(ps.name)}${formatIsOptional(ps.type.context?.isOptional)}: ${getExpected(ps.type)}`).join(", ")}, ... }`;
break;
}
}
return getExpected(encoded);
});
return Array.from(new Set(types)).join(" | ");
}
};
function failSingleUnionCandidate(ast, cause, input, options) {
const issue = getSchemaIssue(cause);
if (!issue) return failCause(cause);
return fail$2(new AnyOf(ast, [issue], input, options));
}
function catchSingleUnionCandidate(ast, result, input, options) {
return catchCause(result, (cause) =>
failSingleUnionCandidate(ast, cause, input, options),
);
}
function parseUnionCandidates(ast, parser, candidates, input, options) {
const state = {
ast,
parser,
input,
out: void 0,
successes: ast.options?.mode === "oneOf" ? [] : void 0,
issues: void 0,
options,
};
const eff = parseUnion(state, candidates);
if (!eff) {
if (state.out) return state.out;
return fail$1(new AnyOf(ast, state.issues ?? [], input, options));
}
if (effectIsExit(eff)) return resumeUnion(eff, state);
let first = true;
return suspend(() => {
if (!first)
return parseUnionCandidates(ast, parser, candidates, input, options);
first = false;
return resumeUnion(eff, state);
});
}
function resumeUnion(eff, state) {
return flatMapEager(eff, (_) => {
if (state.out === sameExit) return succeed$1(state.input);
if (state.out) return state.out;
return fail$1(
new AnyOf(state.ast, state.issues ?? [], state.input, state.options),
);
});
}
const parseUnion = /*#__PURE__*/ iterateEager()({
onItem(s, i) {
return s.parser(i)(s.input, s.options);
},
step(s, i, exit) {
if (exit._tag === "Failure") {
const issue = getSchemaIssue(exit.cause);
if (issue === void 0) return exit;
if (s.issues) s.issues.push(issue);
else s.issues = [issue];
} else {
if (s.out && s.successes) {
s.successes.push(s.ast.types[i]);
return fail$2(new OneOf(s.ast, s.successes, s.input, s.options));
}
s.out = exit;
if (s.successes) s.successes.push(s.ast.types[i]);
else return void_;
}
},
});
const nonFiniteLiterals = /*#__PURE__*/ new Union$1([
/*#__PURE__*/ new Literal$1("Infinity"),
/*#__PURE__*/ new Literal$1("-Infinity"),
/*#__PURE__*/ new Literal$1("NaN"),
]);
function formatIsMutable(isMutable) {
return isMutable ? "" : "readonly ";
}
function formatIsOptional(isOptional) {
return isOptional ? "?" : "";
}
/**
* Constructs a {@link Filter}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Filter = class extends Class$1 {
_tag = "Filter";
run;
annotations;
/**
* Whether the parsing process should be aborted after this check has failed.
*/
aborted;
constructor(run, annotations = void 0, aborted = false) {
super();
this.run = run;
this.annotations = annotations;
this.aborted = aborted;
}
annotate(annotations) {
return new Filter(
this.run,
{
...this.annotations,
...annotations,
},
this.aborted,
);
}
abort() {
return new Filter(this.run, this.annotations, true);
}
and(other, annotations) {
return new FilterGroup([this, other], annotations);
}
};
/**
* Constructs a {@link FilterGroup}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const FilterGroup = class extends Class$1 {
_tag = "FilterGroup";
checks;
annotations;
constructor(checks, annotations = void 0) {
super();
this.checks = checks;
this.annotations = annotations;
}
annotate(annotations) {
return new FilterGroup(this.checks, {
...this.annotations,
...annotations,
});
}
and(other, annotations) {
return new FilterGroup([this, other], annotations);
}
};
/** @internal */
function makeFilter$1(filter, annotations, aborted = false) {
return new Filter(
(input, ast, options) =>
normalizeFilterOutput(ast, filter(input, ast, options), input, options),
annotations,
aborted,
);
}
/** @internal */
function isFinite(annotations) {
return makeFilter$1((n) => globalThis.Number.isFinite(n), {
expected: "a finite number",
representation: {
id: "effect/schema/isFinite",
payload: null,
},
toJsonSchema: () => ({ type: "number" }),
toCode: () => ({ runtime: "Schema.isFinite()" }),
arbitraryConstraint: { number: "finite" },
...annotations,
});
}
const numberToJson = /*#__PURE__*/ new Link(
/*#__PURE__*/ new Union$1([
/* @__PURE__ */ appendChecks(number, [/*#__PURE__*/ isFinite()]),
nonFiniteLiterals,
]),
/*#__PURE__*/ new Transformation(
/*#__PURE__*/ Number$3(),
/*#__PURE__*/ transform$1((n) =>
globalThis.Number.isFinite(n) ? n : globalThis.String(n),
),
),
);
/**
* Creates a {@link Filter} that validates strings by running `RegExp.test`.
*
* **When to use**
*
* Use when string validation should be represented as a schema `Filter` backed
* by a regular expression.
*
* **Details**
*
* The filter can be used with `Schema.filter` or attached directly to a
* `String` AST node through checks. The regular expression is cloned and its
* `lastIndex` is reset before each test, so global and sticky expressions are
* deterministic and the provided regular expression is not mutated. The
* regular expression source is stored in annotations for serialization and
* arbitrary generation.
*
* **Gotchas**
*
* Arbitrary metadata preserves both `regExp.source` and `regExp.flags`.
* Implementations that cannot consume all flags may still use the source as a
* generation hint because the Schema filter validates every generated value.
* JSON Schema has no way to carry JavaScript regular-expression flags. Unless
* annotations provide `toJsonSchema`, the RegExp constraint is omitted from
* JSON Schema export.
*
* **Example** (Validating an email pattern)
*
* ```ts import.meta.vitest
* import { SchemaAST } from "effect"
*
* const emailFilter = SchemaAST.isPattern(/^[^@]+@[^@]+$/)
* emailFilter.run("alice@example.com", SchemaAST.string, {}) // => undefined
* emailFilter.run("invalid", SchemaAST.string, {})?._tag // => "InvalidValue"
* ```
*
* @see {@link Filter}
* @stability stable
* @category constructors
* @since 4.0.0
*/
function isPattern$1(regExp, annotations) {
const copy = new globalThis.RegExp(regExp);
const payload = {
source: copy.source,
flags: copy.flags,
};
return makeFilter$1(
(s) => {
copy.lastIndex = 0;
return copy.test(s);
},
{
expected: `a string matching the RegExp ${payload.source}`,
representation: {
id: "effect/schema/isPattern",
payload,
},
toJsonSchema: () => [{}, true],
arbitraryConstraint: { patterns: [payload] },
...annotations,
},
);
}
const bodyOwners = /*#__PURE__*/ new WeakMap();
function copy(ast, changes) {
const out = Object.assign(
Object.create(Object.getPrototypeOf(ast)),
ast,
changes,
);
if (
Reflect.ownKeys(changes).every(
(key) => key === "context" || key === "encoding",
)
)
bodyOwners.set(out, getContextOwner(ast));
return out;
}
/** @internal */
function getContextOwner(ast) {
const existing = bodyOwners.get(ast);
if (existing !== void 0) return existing;
if (ast.encoding === void 0) return ast;
const owner = Object.assign(Object.create(Object.getPrototypeOf(ast)), ast, {
encoding: void 0,
});
bodyOwners.set(ast, owner);
return owner;
}
/** @internal */
function replaceEncoding(ast, encoding) {
return ast.encoding === encoding ? ast : copy(ast, { encoding });
}
/** @internal */
function replaceContext(ast, context) {
if (ast.context === context) return ast;
const owner = getContextOwner(ast);
if (owner.context === context && owner.encoding === ast.encoding)
return owner;
return copy(ast, { context });
}
/** @internal */
function getLastEncoding(ast) {
return ast.encoding
? getLastEncoding(ast.encoding[ast.encoding.length - 1].to)
: ast;
}
/** @internal */
function annotate(ast, annotations) {
if (ast.checks) {
const last = ast.checks[ast.checks.length - 1];
return replaceChecks(
ast,
append(ast.checks.slice(0, -1), last.annotate(annotations)),
);
}
return copy(ast, {
annotations: {
...ast.annotations,
...annotations,
},
});
}
/** @internal */
function replaceChecks(ast, checks) {
if (ast._tag === "Suspend" && checks)
throw new Error("Cannot add checks to Suspend");
if (ast.checks === checks) return ast;
return copy(ast, { checks });
}
/** @internal */
function appendChecks(ast, checks) {
return replaceChecks(ast, combineChecks(ast.checks, checks));
}
/** @internal */
function mapLink(link, f) {
const to = f(link.to);
return to === link.to ? link : new Link(to, link.transformation);
}
function updateLastLink(encoding, f) {
const links = encoding;
const last = links[links.length - 1];
const out = mapLink(last, f);
return out === last
? encoding
: append(encoding.slice(0, encoding.length - 1), out);
}
/** @internal */
function applyToSelfOrLastLinkEncodingIdempotent(f, options) {
function out(ast) {
if (ast.encoding) {
const last = ast.encoding[ast.encoding.length - 1];
return options?.stopAt?.(last)
? ast
: replaceEncoding(ast, updateLastLink(ast.encoding, out));
}
return f(ast);
}
return memoizeIdempotent(out);
}
function appendTransformation(from, transformation, to) {
const link = new Link(from, transformation);
return replaceEncoding(to, to.encoding ? [...to.encoding, link] : [link]);
}
function mapOrSame(as, f) {
let out;
for (let i = 0; i < as.length; i++) {
const a = as[i];
const fa = f(a);
if (out) out[i] = fa;
else if (fa !== a) {
out = new Array(as.length);
for (let j = 0; j < i; j++) out[j] = as[j];
out[i] = fa;
}
}
return out ?? as;
}
/** @internal */
function annotateKey(ast, annotations) {
return replaceContext(
ast,
ast.context
? new Context(
ast.context.isOptional,
ast.context.isMutable,
ast.context.constructorDefault,
{
...ast.context.annotations,
...annotations,
},
)
: new Context(false, false, void 0, annotations),
);
}
/**
* Attaches a `Transformation` to the `to` AST, making it decode from the
* `from` AST and encode back to it.
*
* **Details**
*
* This is the low-level primitive behind `Schema.decodeTo`. It appends a
* {@link Link} to the `to` node's encoding chain.
*
* - Returns a new AST with the same type as `to`.
*
* @see {@link Link}
* @see {@link Encoding}
* @see {@link flip}
* @stability stable
* @category transforming
* @since 4.0.0
*/
function decodeTo$1(from, to, transformation) {
return appendTransformation(from, transformation, to);
}
/**
* Returns `true` if the AST node represents an optional property.
*
* **Details**
*
* Checks `ast.context?.isOptional`. Defaults to `false` when no
* {@link Context} is set.
*
* @see `Schema.optionalKey`
* @see {@link Context}
* @stability stable
* @category predicates
* @since 4.0.0
*/
function isOptional(ast) {
return ast.context?.isOptional ?? false;
}
function isStructuralCheck(check) {
return (
check.annotations?.["~structural"] === true ||
(check._tag === "FilterGroup" && check.checks.every(isStructuralCheck))
);
}
function extractStructuralChecks(checks) {
function extract(check) {
if (isStructuralCheck(check)) return [check];
return check._tag === "FilterGroup" ? check.checks.flatMap(extract) : [];
}
const out = checks.flatMap(extract);
return isArrayNonEmpty(out) ? out : void 0;
}
function canPreserveEncodingChecks(ast) {
let preserve = true;
function visit(child) {
preserve = preserve && !child.encoding && !isSuspend(child);
if (preserve && "recur" in child) child.recur(visit);
return child;
}
if ("recur" in ast) ast.recur(visit);
return preserve;
}
/**
* Strips all encoding transformations from an AST, returning the decoded
* (type-level) representation.
*
* **Details**
*
* - Memoized: same input reference → same output reference.
* - Recursively walks into composite nodes ({@link Arrays}, {@link Objects},
* {@link Union}, {@link Suspend}).
*
* **Example** (Getting the type AST)
*
* ```ts import.meta.vitest
* import { Schema, SchemaAST } from "effect"
*
* const schema = Schema.NumberFromString
* const typeAst = SchemaAST.toType(schema.ast)
* typeAst._tag // => "Number"
* ```
*
* @see {@link toEncoded}
* @see {@link flip}
* @stability stable
* @category transforming
* @since 4.0.0
*/
const toType = /*#__PURE__*/ memoizeIdempotent((ast) => {
const owner = getContextOwner(ast);
if (owner !== ast) {
const type = toType(owner);
return type === owner && ast.encoding === void 0
? ast
: replaceContext(type, ast.context);
}
const type = "recur" in ast ? ast.recur(toType) : ast;
if ("encodingChecks" in type && type.encodingChecks) {
const checks = canPreserveEncodingChecks(ast)
? type.encodingChecks
: isArrays(type) ||
isObjects(type) ||
(isDeclaration(type) && type.typeParameters.length > 0)
? extractStructuralChecks(type.encodingChecks)
: void 0;
return copy(type, {
encodingChecks: void 0,
checks: combineChecks(type.checks, checks),
});
}
return type;
});
/**
* Returns the encoded (wire-format) AST by flipping and then stripping
* encodings.
*
* **Details**
*
* Equivalent to `toType(flip(ast))`. This gives you the AST that describes
* the shape of the serialized/encoded data.
*
* - Memoized: same input reference → same output reference.
*
* **Example** (Getting the encoded AST)
*
* ```ts import.meta.vitest
* import { Schema, SchemaAST } from "effect"
*
* const schema = Schema.NumberFromString
* const encodedAst = SchemaAST.toEncoded(schema.ast)
* encodedAst._tag // => "String"
* ```
*
* @see {@link toType}
* @see {@link flip}
* @stability stable
* @category transforming
* @since 4.0.0
*/
const toEncoded = /*#__PURE__*/ memoizeIdempotent((ast) => {
return toType(flip(ast));
});
function flipEncoding(ast, encoding) {
const links = encoding;
const len = links.length;
const last = links[len - 1];
const ls = [
new Link(
flip(replaceEncoding(ast, void 0)),
links[0].transformation.flip(),
),
];
for (let i = 1; i < len; i++)
ls.unshift(new Link(flip(links[i - 1].to), links[i].transformation.flip()));
const to = flip(last.to);
if (to.encoding) return replaceEncoding(to, [...to.encoding, ...ls]);
else return replaceEncoding(to, ls);
}
/**
* Swaps the decode and encode directions of an AST's {@link Encoding} chain.
*
* **Details**
*
* After flipping, what was decoding becomes encoding and vice versa. This is
* the core operation behind `Schema.encode` — encoding a value is decoding
* with a flipped SchemaAST.
*
* - Memoized: same input reference → same output reference.
* - Recursively walks composite nodes.
*
* @see {@link toType}
* @see {@link toEncoded}
* @stability stable
* @category transforming
* @since 4.0.0
*/
const flip = /*#__PURE__*/ memoize((ast) => {
if (ast.encoding) return flipEncoding(ast, ast.encoding);
const owner = getContextOwner(ast);
if (owner !== ast) {
const flipped = flip(owner);
return flipped === owner ? ast : replaceContext(flipped, ast.context);
}
return "flip" in ast
? ast.flip(flip)
: "recur" in ast
? ast.recur(flip)
: ast;
});
/** @internal */
function containsUndefined(ast) {
switch (ast._tag) {
case "Undefined":
return true;
case "Union":
return ast.types.some(containsUndefined);
default:
return false;
}
}
function fromConst(ast, value) {
const succeed$6 = value === 0 ? sameExit : succeed(value);
return (input, options) => {
if (input === missing) return missingExit;
if (input === value) return succeed$6;
return fail$1(new InvalidType(ast, input, options));
};
}
function fromRefinement(ast, refinement) {
return (input, options) => {
if (input === missing) return missingExit;
if (refinement(input)) return sameExit;
return fail$1(new InvalidType(ast, input, options));
};
}
/** @internal */
const parameterFromPropertyKey =
/*#__PURE__*/ applyToSelfOrLastLinkEncodingIdempotent((ast) => {
switch (ast._tag) {
default:
return ast;
case "Number":
return ast.toCodecStringTree();
case "Union":
return ast.recur(parameterFromPropertyKey);
}
});
const isStringFiniteRegExp = /*#__PURE__*/ new globalThis.RegExp(
`^${FINITE_PATTERN}$`,
);
const isStringNumberRegExp = /*#__PURE__*/ new globalThis.RegExp(
`^(?:${FINITE_PATTERN}|Infinity|-Infinity|NaN)$`,
);
/** @internal */
function isStringFinite(annotations) {
return isPattern$1(isStringFiniteRegExp, {
expected: "a string representing a finite number",
representation: {
id: "effect/schema/isStringFinite",
payload: null,
},
toJsonSchema: () => ({ pattern: isStringFiniteRegExp.source }),
...annotations,
});
}
const finiteString = /*#__PURE__*/ appendChecks(string, [
/*#__PURE__*/ isStringFinite(),
]);
const finiteToString = /*#__PURE__*/ new Link(finiteString, numberFromString);
const numberToString = /*#__PURE__*/ new Link(
/*#__PURE__*/ new Union$1([finiteString, nonFiniteLiterals]),
numberFromString,
);
/** @internal */
function collectIssues(checks, value, issues, ast, options) {
for (let i = 0; i < checks.length; i++) {
const check = checks[i];
if (check._tag === "FilterGroup") {
issues = collectIssues(check.checks, value, issues, ast, options);
if (
issues &&
(options.errors !== "all" || issues[issues.length - 1].filter.aborted)
)
return issues;
} else {
const issue = check.run(value, ast, options);
if (issue) {
const filter = new Filter$1(check, issue, value, options);
if (issues) issues.push(filter);
else issues = [filter];
if (options.errors !== "all" || check.aborted) return issues;
}
}
}
return issues;
}
/** @internal */
function getConstructorDescriptor(ast) {
if (!isDeclaration(ast)) return void 0;
const getDescriptor = ast.annotations?.[CONSTRUCTOR_ANNOTATION_KEY];
return isFunction(getDescriptor) ? getDescriptor(ast.typeParameters) : void 0;
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/schema/interpreter.js
const flatMapTransformation = (result, current, f) =>
result === sameExit ? f(current) : flatMapEager(result, f);
function compileTransformation(transformation) {
if (transformation._tag === "Middleware")
return (result, current, options) => {
const transformed =
result === sameExit
? transformation.decode(succeed(toOption(current)), options)
: transformation.decode(mapEager(result, toOption), options);
return fromOptionalEffect(transformed);
};
const getter = transformation.decode;
switch (getter._tag) {
case "Passthrough":
return (result, current) =>
result === sameExit ? succeed(current) : result;
case "Transform": {
const transform = (value) =>
value === missing ? missingExit : succeed(getter.transform(value));
return (result, current) =>
flatMapTransformation(result, current, transform);
}
case "TransformOptional": {
const transform = (value) =>
fromOptionExit(getter.transform(toOption(value)));
return (result, current) =>
flatMapTransformation(result, current, transform);
}
case "TransformEffect":
return (result, current, options) =>
flatMapTransformation(result, current, (value) =>
value === missing ? missingExit : getter.transform(value, options),
);
case "TransformOptionalEffect":
return (result, current, options) =>
flatMapTransformation(result, current, (value) =>
fromOptionalEffect(getter.transform(toOption(value), options)),
);
}
}
const fromOptionalEffect = (effect) => flatMapEager(effect, fromOptionExit);
/** @internal */
const wrapEncoding = (ast, input, options, effect) =>
catchCause(effect, (cause) =>
failCauseSync(() =>
map(cause, (issue) => new Encoding(ast, issue, input, options)),
),
);
function makeConstructorParser(descriptor, compile) {
const transform = compileTransformation(descriptor.link.transformation);
let sourceParser;
return (input, options) => {
if (input === missing) return missingExit;
if (descriptor.isConstructed(input)) return sameExit;
const result = (sourceParser ??= compile(descriptor.link.to))(
input,
options,
);
return transform(result, input, options);
};
}
function withDefault(ast, parser) {
const defaultValue = ast.context.constructorDefault;
return (input, options) => {
if (input !== missing && input !== void 0) return parser(input, options);
const result = defaultValue;
if (effectIsExit(result) && result._tag === "Success") {
const local = parser(result[args], options);
return local === sameExit ? result : local;
}
return flatMapEager(wrapEncoding(ast, input, options, result), (value) => {
const local = parser(value, options);
return local === sameExit ? succeed(value) : local;
});
};
}
/** @internal */
function compileField(ast, compile) {
const parser = compile(ast);
return ast.context?.constructorDefault === void 0
? parser
: withDefault(ast, parser);
}
/** @internal */
function compile(ast, compile, compileField, base, specialize) {
if (ast._tag === "Declaration")
for (const parameter of ast.typeParameters) compile(parameter);
const descriptor = compileField ? getConstructorDescriptor(ast) : void 0;
const parser = descriptor
? makeConstructorParser(descriptor, compile)
: (base ?? ast.getParser(compile, compileField));
const checks = ast.checks;
const links = ast.encoding;
const transformations = links?.map((link) =>
compileTransformation(link.transformation),
);
const encodingChecks = ast.encodingChecks;
if (!links && !checks && !encodingChecks) return parser;
let encodingParsers;
const parseChecks = (input, options) => {
let result = parser(input, options);
if (encodingChecks && !options.disableChecks) {
if (effectIsExit(result)) {
if (result._tag === "Success") {
const output = result === sameExit ? input : result[args];
if (input !== missing && output !== missing) {
const issues = collectIssues(
encodingChecks,
input,
void 0,
ast,
options,
);
if (issues)
result = fail$1(new Composite(ast, issues, input, options));
}
}
} else
result = flatMap(result, (value) => {
if (input !== missing && value !== missing) {
const issues = collectIssues(
encodingChecks,
input,
void 0,
ast,
options,
);
if (issues)
return fail$1(new Composite(ast, issues, input, options));
}
return succeed$1(value);
});
}
if (checks && !options.disableChecks) {
if (effectIsExit(result)) {
if (result._tag === "Success") {
const value = result === sameExit ? input : result[args];
if (value === missing) return result;
const issues = collectIssues(checks, value, void 0, ast, options);
if (issues)
result = fail$1(new Composite(ast, issues, value, options));
}
} else
result = flatMap(result, (value) => {
if (value !== missing) {
const issues = collectIssues(checks, value, void 0, ast, options);
if (issues)
return fail$1(new Composite(ast, issues, value, options));
}
return succeed$1(value);
});
}
return result;
};
const parseLocal =
specialize === void 0 ? parseChecks : specialize(parseChecks);
if (!links) return parseLocal;
return (input, options) => {
const parsers = (encodingParsers ??= links.map((link) => compile(link.to)));
let current = input;
let result = parsers[parsers.length - 1](input, options);
for (let i = links.length - 1; i >= 0; i--) {
result = transformations[i](result, current, options);
if (i !== 0) {
const next = parsers[i - 1];
if (result._tag === "Success") {
current = result[args];
result = next(current, options);
} else
result = flatMapEager(result, (value) => {
const nextResult = next(value, options);
return nextResult === sameExit ? succeed(value) : nextResult;
});
}
}
if (result._tag === "Success") {
const value = result[args];
const local = parseLocal(value, options);
return local === sameExit ? result : local;
}
result = wrapEncoding(ast, input, options, result);
return flatMapEager(result, (value) => {
const local = parseLocal(value, options);
return local === sameExit ? succeed(value) : local;
});
};
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/schema/compilerRegistry.js
/** @internal */
const invalid = /*#__PURE__*/ Symbol();
const cache = /*#__PURE__*/ new WeakMap();
const decodeChild = (ast) => resolve(ast).parser;
const makeChild = (ast) => resolve(ast).makeEffect;
const makeField = (ast) => compileField(ast, makeChild);
var InterpretedEntry = class {
ast;
constructor(ast) {
this.ast = ast;
}
get decodeEffect() {
return (this.cachedDecodeEffect ??= compile(this.ast, decodeChild));
}
get parser() {
return this.decodeEffect;
}
get makeEffect() {
return (this.cachedMakeEffect ??= compile(this.ast, makeChild, makeField));
}
};
/** @internal */
function resolve(ast) {
const cached = cache.get(ast);
if (cached !== void 0) return cached;
const entry = new InterpretedEntry(ast);
cache.set(ast, entry);
return entry;
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/SchemaParser.js
/**
* Runs schemas against real values.
*
* Schema parsers construct values from schema input, check whether a value
* matches a schema, decode encoded input, and encode decoded values back to
* their external form. This module exposes those operations through several
* result styles, including `Effect`, `Promise`, `Exit`, `Option`, `Result`, and
* synchronous functions that throw. It also contains the lower-level runner that
* walks a schema AST and reports schema failures as `SchemaIssue.Issue` values.
*
* @stability stable
* @since 4.0.0
*/
/**
* Creates an effectful maker for the schema's decoded type side.
*
* **When to use**
*
* Use to construct decoded schema values in `Effect` while preserving
* construction failures as `SchemaIssue.Issue` values in the error channel.
*
* **Details**
*
* The returned function accepts constructor input, applies constructor defaults,
* runs type-side validation unless checks are disabled, and fails with a
* `SchemaIssue.Issue` when construction fails.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
function makeEffect(schema) {
const ast = schema.ast;
let parser;
return (input, options) => {
return (parser ??= runWithCompiler(constructorCompiler, toType(ast)))(
input,
options?.disableChecks
? options?.parseOptions
? {
...options.parseOptions,
disableChecks: true,
}
: { disableChecks: true }
: options?.parseOptions,
);
};
}
/**
* Creates a synchronous maker that returns `Option.some` with the constructed
* value on success, or `Option.none` when construction fails with schema issues.
*
* **When to use**
*
* Use when you need to validate schema constructor input and only care whether
* construction succeeds, without exposing `SchemaIssue.Issue` details.
*
* **Gotchas**
*
* Only causes made entirely of schema issues are converted to `Option.none`.
* Causes that contain defects, interruptions, or asynchronous work at this
* synchronous boundary throw an `Error` whose cause is the underlying `Cause`.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
function makeOption(schema) {
const parser = makeEffect(schema);
return (input, options) => {
const exit = runSyncExit(parser(input, options));
if (isSuccess(exit)) return some(exit.value);
getSchemaIssueOrThrow(
exit.cause,
"Option adapter can only return none for schema issues",
);
return none();
};
}
/**
* Creates a synchronous maker for the schema's decoded type side.
*
* **When to use**
*
* Use to construct decoded schema values synchronously when invalid input
* should throw an `Error` whose cause is `SchemaIssue.Issue`.
*
* **Details**
*
* The returned function constructs a value from constructor input and throws an
* `Error` with the `SchemaIssue.Issue` in its `cause` when construction fails.
* Schema validation failures use the generic message `"Schema validation failed"`.
* Format the `cause` explicitly with `SchemaIssue.makeFormatterDefault()` when
* human-readable details are needed.
*
* **Gotchas**
*
* Causes that contain defects, interruptions, or asynchronous work at this
* synchronous boundary throw an `Error` whose cause is the underlying `Cause`,
* instead of being converted to a schema validation error.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
function make$2(schema) {
return makeConstructorSync(toType(schema.ast));
}
/**
* Creates an effectful decoder for `unknown` input.
*
* **When to use**
*
* Use when you need to decode untyped boundary input in an `Effect` whose
* failure channel is `SchemaIssue.Issue`, while preserving transformations
* and service requirements.
*
* **Details**
*
* The returned function succeeds with the schema's decoded `Type` or fails with a
* `SchemaIssue.Issue`. Decoding service requirements are preserved in the returned
* `Effect`. Parse options may be provided when creating the decoder and overridden
* when applying it.
*
* @see {@link decodeEffect} for input already typed as the schema's `Encoded` type
*
* @stability stable
* @category decoding
* @since 4.0.0
*/
function decodeUnknownEffect$1(schema, options) {
const parser = run(schema.ast);
return options === void 0
? parser
: (input, overrideOptions) =>
parser(input, mergeParseOptions(options, overrideOptions));
}
const mergeParseOptions = (options, overrideOptions) =>
overrideOptions
? {
...options,
...overrideOptions,
}
: options;
const getValue = (value) => {
if (value === missing) return fail$1(new InvalidValue());
return succeed$1(value);
};
/** @internal */
function run(ast) {
return runWithCompiler(normalCompiler, ast);
}
function parserResult(result, input) {
if (result === sameExit) return succeed$1(input);
if (!effectIsExit(result)) return flatMapEager(result, getValue);
return result["~effect/Effect/args"] === missing ? getValue(missing) : result;
}
function runWithCompiler(compiler, ast) {
let parser;
return (input, options) => {
const result = (parser ??= compiler(ast))(
input,
options ?? defaultParseOptions,
);
if (result === sameExit) return succeed$1(input);
if (!effectIsExit(result)) return flatMapEager(result, getValue);
return result["~effect/Effect/args"] === missing
? getValue(missing)
: result;
};
}
function runSync(effect, message) {
const exit = runSyncExit(effect);
if (isSuccess(exit)) return exit.value;
const issue = getSchemaIssueOrThrow(exit.cause, message);
throw new Error("Schema validation failed", { cause: issue });
}
function makeConstructorSync(ast) {
let entry;
let parser;
return (input, options) => {
entry ??= resolve(ast);
const parseOptions = options?.disableChecks
? options.parseOptions
? {
...options.parseOptions,
disableChecks: true,
}
: { disableChecks: true }
: (options?.parseOptions ?? defaultParseOptions);
const make = entry.make;
if (make !== void 0 && input !== missing) {
let output;
try {
output = make(input, parseOptions);
} catch (error) {
getSchemaIssueOrThrow(
die$1(error),
"Constructor adapter can only throw schema issues",
);
throw error;
}
if (output !== invalid && output !== missing) return output;
}
return runSync(
parserResult((parser ??= entry.makeEffect)(input, parseOptions), input),
"Constructor adapter can only throw schema issues",
);
};
}
const normalCompiler = (ast) => resolve(ast).parser;
const constructorCompiler = (ast) => resolve(ast).makeEffect;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/schema/make.js
/** @internal */
const TypeId$2 = "~effect/Schema/Schema";
const RebuildOptions = /*#__PURE__*/ Symbol();
const SchemaProto = {
[TypeId$2]: TypeId$2,
get make() {
const value = make$2(this);
Object.defineProperty(this, "make", {
value,
enumerable: true,
});
return value;
},
get makeEffect() {
const value = makeEffect(this);
Object.defineProperty(this, "makeEffect", {
value,
enumerable: true,
});
return value;
},
get makeOption() {
const value = makeOption(this);
Object.defineProperty(this, "makeOption", {
value,
enumerable: true,
});
return value;
},
pipe() {
return pipeArguments(this, arguments);
},
annotate(annotations) {
return this.rebuild(annotate(this.ast, annotations));
},
annotateKey(annotations) {
return this.rebuild(annotateKey(this.ast, annotations));
},
check(...checks) {
return this.rebuild(appendChecks(this.ast, checks));
},
rebuild(ast) {
return make$1(ast, this[RebuildOptions]);
},
};
/** @internal */
function make$1(ast, options) {
function Schema() {}
const self = Object.setPrototypeOf(Schema, SchemaProto);
if (
options &&
(Object.hasOwn(options, "name") ||
Object.hasOwn(options, "length") ||
Object.hasOwn(options, "__proto__"))
)
Object.defineProperties(
self,
Object.getOwnPropertyDescriptors({ ...options }),
);
else Object.assign(self, options);
self[RebuildOptions] = options;
self.ast = ast;
return self;
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Struct.js
/**
* Wraps a plain function as a {@link Lambda} value so it can be used with
* {@link map}, {@link mapPick}, and {@link mapOmit}.
*
* **When to use**
*
* Use to create a typed lambda for struct mapping APIs that need type-level
* input and output tracking.
*
* **Details**
*
* The type parameter `L` encodes both the input and output types at the type
* level, allowing the compiler to track how struct value types change. At
* runtime, the returned value is the same function; `lambda` only adjusts the
* type.
*
* **Example** (Wrapping values in arrays)
*
* ```ts import.meta.vitest
* import { pipe, Struct } from "effect"
*
* interface AsArray extends Struct.Lambda {
* <A>(self: A): Array<A>
* readonly "~lambda.out": Array<this["~lambda.in"]>
* }
*
* const asArray = Struct.lambda<AsArray>((a) => [a])
* const result = pipe({ x: 1, y: "hello" }, Struct.map(asArray))
* result // => { x: [1], y: ["hello"] }
* ```
*
* @see {@link Lambda} – the type-level interface
* @see {@link map} – apply a lambda to all struct values
* @stability stable
* @category constructors
* @since 4.0.0
*/
const lambda = (f) => f;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/schemaError.js
const SchemaErrorTypeId = "~effect/Schema/SchemaError";
function isSchemaError$1(u) {
return (
hasProperty(u, "~effect/Schema/SchemaError") &&
u["~effect/Schema/SchemaError"] === "~effect/Schema/SchemaError"
);
}
({ ...BaseProto });
({ ...BaseProto });
({ ...BaseProto });
({ ...BaseProto });
({ ...BaseProto });
({ ...BaseProto });
({ ...BaseProto });
({ ...BaseProto });
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Schema.js
/**
* Creates a schema for a **parametric** type (a generic container such as
* `Array<A>`, `Option<A>`, etc.) by accepting a list of type-parameter schemas
* and a decoder factory.
*
* **When to use**
*
* Use when you are defining a schema for a generic container whose validation
* depends on one or more type-parameter schemas.
*
* **Details**
*
* The outer call `declareConstructor<T, E, Iso>()` fixes the decoded type `T`,
* the encoded type `E`, and the optional iso type. The inner call receives:
* - `typeParameters` — the concrete schemas for each type variable
* - `run` — a factory that, given resolved codecs for each type parameter,
* returns a parsing function `(u, ast, options) => Effect<T, Issue>`
* - `annotations` — optional metadata
*
* @see {@link declare} for creating schemas for non-parametric types.
*
* **Example** (Schema for a parametric `Box<A>` type)
*
* ```ts import.meta.vitest
* import { Effect, Schema, SchemaIssue, SchemaParser } from "effect"
*
* interface Box<A> {
* readonly value: A
* }
*
* const isBox = (u: unknown): u is Box<unknown> =>
* typeof u === "object" && u !== null && "value" in u
*
* const Box = <A extends Schema.Constraint>(item: A) =>
* Schema.declareConstructor<Box<A["Type"]>, Box<A["Encoded"]>>()(
* [item],
* ([itemCodec]) =>
* (u, ast, options) => {
* if (!isBox(u)) {
* return Effect.fail(new SchemaIssue.InvalidType(ast, u, options))
* }
* return Effect.map(
* SchemaParser.decodeUnknownEffect(itemCodec)(u.value, options),
* (value) => ({ value })
* )
* }
* )
*
* const schema = Box(Schema.Number)
* Effect.runSync(Schema.decodeUnknownEffect(schema)({ value: 1 })) // => { value: 1 }
* ```
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
function declareConstructor() {
return (typeParameters, run, annotations) => {
return make(
new Declaration(
typeParameters.map(getAST),
(typeParameters) => run(typeParameters.map((ast) => make(ast))),
annotations,
),
);
};
}
/**
* Creates a schema for a **non-parametric** opaque type using a type-guard
* function. The schema accepts any unknown value and succeeds when `is` returns
* `true`, failing with an `InvalidType` issue otherwise.
*
* **When to use**
*
* Use when you are defining a schema for an opaque type with no type parameters
* and validation can be expressed as a type guard.
*
* **Example** (Defining a schema for a custom `UserId` branded type)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* type UserId = string & { readonly _tag: "UserId" }
*
* const isUserId = (u: unknown): u is UserId =>
* typeof u === "string" && u.startsWith("user_")
*
* const UserId = Schema.declare<UserId>(isUserId, {
* title: "UserId",
* description: "A user identifier starting with 'user_'"
* })
* Schema.decodeUnknownSync(UserId)("user_123") // => "user_123"
* ```
*
* @see {@link declareConstructor} for creating schemas for parametric types.
*
* @stability stable
* @category constructors
* @since 3.10.0
*/
function declare(is, annotations) {
return declareConstructor()(
[],
() => (input, ast, options) =>
is(input)
? succeed$1(input)
: fail$1(new InvalidType(ast, input, options)),
annotations,
);
}
/**
* Error thrown or returned when schema decoding or encoding fails.
*
* **Details**
*
* The `issue` field contains a structured {@link SchemaIssue.Issue} tree describing
* every validation failure, including the path to the problematic value and
* the expected type or constraint. The `message` field renders the issue tree
* with the default formatter.
*
* **Gotchas**
*
* Parsing with `reportInput: true` adds an enumerable `input` field to
* value-bearing issues. Built-in messages may include reported input, and
* custom annotations or messages are not sanitized.
*
* **Example** (Inspecting a SchemaError)
*
* ```ts import.meta.vitest
* import { Result, Schema } from "effect"
*
* const result = Schema.decodeUnknownResult(Schema.Number)("not a number")
* const message = Result.isFailure(result) ? result.failure.message : ""
* message // => "Expected number"
* ```
*
* @see {@link isSchemaError} for narrowing unknown values
* @stability stable
* @category errors
* @since 4.0.0
*/
var SchemaError = class extends /*#__PURE__*/ TaggedError("SchemaError") {
[SchemaErrorTypeId] = SchemaErrorTypeId;
constructor(issue) {
const stackTraceLimit = getStackTraceLimit();
setStackTraceLimit(0);
try {
super({ issue });
} finally {
setStackTraceLimit(stackTraceLimit);
}
}
get message() {
return defaultFormatter(this.issue);
}
toJSON() {
return {
_tag: this._tag,
message: this.message,
};
}
[NodeInspectSymbol]() {
return this.toJSON();
}
toString() {
return `SchemaError(${this.message})`;
}
};
/**
* Returns `true` if `u` is a {@link SchemaError}.
*
* **When to use**
*
* Use when you need to narrow an unknown value to `SchemaError`.
*
* **Example** (Narrowing Schema errors)
*
* ```ts import.meta.vitest
* import { Result, Schema } from "effect"
*
* const result = Result.try(() => Schema.decodeUnknownSync(Schema.Number)("oops"))
* const error: unknown = Result.isFailure(result) ? result.failure : undefined
* Schema.isSchemaError(error) // => true
* ```
*
* @stability stable
* @category guards
* @since 4.0.0
*/
function isSchemaError(u) {
return isSchemaError$1(u);
}
function fromIssueEffect(self) {
if (effectIsExit(self)) return fromIssueExit(self);
return catchCause(self, (cause) =>
failCauseSync(() => map(cause, (issue) => new SchemaError(issue))),
);
}
function fromIssueExit(exit) {
return isSuccess(exit)
? exit
: failCause(map(exit.cause, (issue) => new SchemaError(issue)));
}
function getSchemaErrorOrThrow(cause, message) {
let schemaError;
for (const reason of cause.reasons) {
if (!isFailReason(reason) || !isSchemaError(reason.error))
throw new globalThis.Error(message, { cause });
schemaError ??= reason.error;
}
if (schemaError === void 0) throw new globalThis.Error(message, { cause });
return schemaError;
}
function runSchemaErrorSync(self) {
const exit = runSyncExit(self);
if (isSuccess(exit)) return exit.value;
throw getSchemaErrorOrThrow(
exit.cause,
"Sync adapter can only throw schema errors",
);
}
/**
* Decodes an `unknown` input against a schema, returning an `Effect` that
* succeeds with the decoded value or fails with a {@link SchemaError}.
*
* **When to use**
*
* Use when you need to decode unknown input in an `Effect` whose failure
* channel is `SchemaError`.
*
* **Details**
*
* Prefer {@link decodeEffect} when the input is already typed as the schema's
* `Encoded` type.
* Options may be provided either when creating the decoder or when applying it;
* application options override creation options.
*
* @see {@link SchemaParser.decodeUnknownEffect} for the adapter that fails with `SchemaIssue.Issue` directly
*
* @stability stable
* @category decoding
* @since 4.0.0
*/
function decodeUnknownEffect(schema, options) {
const parser = decodeUnknownEffect$1(schema, options);
return (input, options) => {
return fromIssueEffect(parser(input, options));
};
}
/**
* Decodes an `unknown` input against a schema synchronously, returning the
* decoded value or throwing a {@link SchemaError} for schema mismatches.
*
* **When to use**
*
* Use when you need to validate unknown data at a synchronous boundary and want
* schema mismatches to throw `SchemaError`.
*
* **Details**
*
* For input already typed as the schema's `Encoded` type use `decodeSync`.
* Only service-free schemas can be decoded synchronously. For alternatives that
* do not throw on schema mismatches, see `decodeUnknownOption`,
* `decodeUnknownExit`, or `decodeUnknownEffect`. Options may be provided either
* when creating the decoder or when applying it; application options override
* creation options.
*
* **Gotchas**
*
* Non-schema failures may throw a runtime failure instead of `SchemaError`.
*
* **Example** (Decoding with a transformation schema)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* const NumberFromString = Schema.NumberFromString
*
* Schema.decodeUnknownSync(NumberFromString)("42") // => 42
* ```
*
* @see {@link SchemaParser.decodeUnknownSync} for the adapter that throws an `Error` whose cause is `SchemaIssue.Issue`
*
* @stability stable
* @category decoding
* @since 4.0.0
*/
function decodeUnknownSync(schema, options) {
const parser = decodeUnknownEffect(schema, options);
return (input, options) => {
return runSchemaErrorSync(parser(input, options));
};
}
/**
* Creates a schema from an AST (Abstract Syntax Tree) node.
*
* **Details**
*
* This is the fundamental constructor for all schemas in the Effect Schema
* library. It takes an AST node and wraps it in a fully-typed schema that
* preserves all type information and provides the complete schema API.
*
* The `make` function is used internally to create all primitive schemas like
* `String`, `Number`, `Boolean`, etc., as well as more complex schemas. It's
* the bridge between the untyped AST representation and the strongly-typed
* schema.
*
* @stability stable
* @category constructors
* @since 3.10.0
*/
const make = make$1;
/**
* Creates a schema for a single literal value (string, number, bigint, boolean, or null).
*
* **Example** (Defining a string literal)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* const schema = Schema.Literal("hello")
* // Type: Schema.Literal<"hello">
* Schema.decodeSync(schema)("hello") // => "hello"
* ```
*
* @see {@link Literals} for a schema that represents a union of literals.
* @see {@link tag} for a schema that represents a literal value that can be
* used as a discriminator field in tagged unions and has a constructor default.
* @stability stable
* @category constructors
* @since 3.10.0
*/
function Literal(literal) {
const out = make(new Literal$1(literal), {
literal,
transform(to) {
return out.pipe(
decodeTo(Literal(to), {
decode: transform$1(() => to),
encode: transform$1(() => literal),
}),
);
},
});
return out;
}
/**
* Schema for the `null` literal. Validates that the input is strictly `null`.
*
* @see {@link NullOr} for a union with another schema.
* @stability stable
* @category schemas
* @since 3.10.0
*/
const Null = /*#__PURE__*/ make(null_);
/**
* Schema for `string` values. Validates that the input is `typeof` `"string"`.
*
* @stability stable
* @category schemas
* @since 4.0.0
*/
const String$1 = /*#__PURE__*/ make(string);
/**
* Schema for `number` values, including `NaN`, `Infinity`, and `-Infinity`.
*
* **Details**
*
* Default JSON serializer:
*
* - Finite numbers are serialized as numbers.
* - Non-finite values are serialized as strings (`"NaN"`, `"Infinity"`, `"-Infinity"`).
*
* @see {@link Finite} for a schema that excludes non-finite values.
* @stability stable
* @category schemas
* @since 4.0.0
*/
const Number$1 = /*#__PURE__*/ make(number);
function makeStruct(ast, fields) {
return make(ast, {
fields,
mapFields(f, options) {
const fields = f(this.fields);
return makeStruct(
struct(
fields,
options?.unsafePreserveChecks ? this.ast.checks : void 0,
),
fields,
);
},
});
}
/**
* Defines a struct schema from a map of field schemas.
*
* **Details**
*
* Each field value is a schema. Use {@link optionalKey} or {@link optional} to
* mark fields as optional, and {@link mutableKey} to mark them as mutable.
*
* The resulting schema's `Type` is a readonly object type with the fields'
* decoded types. The `Encoded` form mirrors the field schemas' encoded types.
* Declared fields may be inherited and are copied to own properties in the
* output. The `__proto__` field is accepted only when it is an own property.
* Parsing does not guarantee that output keys retain their input order.
*
* **Example** (Defining a basic struct)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* const Person = Schema.Struct({
* name: Schema.String,
* age: Schema.Number,
* email: Schema.optionalKey(Schema.String)
* })
*
* // { readonly name: string; readonly age: number; readonly email?: string }
* type Person = typeof Person.Type
*
* Schema.decodeUnknownSync(Person)({ name: "Alice", age: 30 }) // => { name: "Alice", age: 30 }
* ```
*
* @stability stable
* @category constructors
* @since 3.10.0
*/
function Struct(fields) {
return makeStruct(struct(fields, void 0), fields);
}
/**
* @category constructors
* @since 4.0.0
*/
const ArraySchema = /*#__PURE__*/ lambda((schema) =>
make(new Arrays(false, [], [schema.ast]), { value: schema }),
);
/**
* Makes an array or tuple schema mutable, removing the `readonly` modifier.
*
* **Gotchas**
*
* This combinator does not support an encoding attached to the array or tuple
* node and throws if one is present. Encodings on element schemas are
* supported.
*
* **Example** (Defining mutable arrays)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* const schema = Schema.mutable(Schema.Array(Schema.Number))
*
* // number[] (mutable)
* type T = typeof schema.Type
* const value: T = [1, 2]
* value.push(3)
* value // => [1, 2, 3]
* ```
*
* @stability stable
* @category transforming
* @since 3.10.0
*/
const mutable = /*#__PURE__*/ lambda((schema) =>
make(mutable$1(schema.ast), { schema }),
);
function makeUnion(ast, members) {
return make(ast, {
members,
mapMembers(f, options) {
const members = f(this.members);
return makeUnion(
union(
members,
this.ast.options,
options?.unsafePreserveChecks ? this.ast.checks : void 0,
),
members,
);
},
});
}
/**
* Creates a union schema from an array of member schemas. Members are tested in
* order; the first match is returned.
*
* **Details**
*
* Optionally, specify `mode`:
* - `"anyOf"` (default) — matches if any member matches.
* - `"oneOf"` — matches if exactly one member matches.
*
* **Example** (Defining a string or number union)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* const schema = Schema.Union([Schema.String, Schema.Number])
*
* Schema.decodeUnknownSync(schema)("hello") // => "hello"
* Schema.decodeUnknownSync(schema)(42) // => 42
* ```
*
* @stability stable
* @category constructors
* @since 3.10.0
*/
function Union(members, options) {
return makeUnion(union(members, options, void 0), members);
}
/**
* Creates a union schema from an array of literal values.
*
* **Example** (Defining status codes)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* const schema = Schema.Literals(["active", "inactive", "pending"])
* Schema.decodeSync(schema)("active") // => "active"
* ```
*
* @see {@link Literal} for a schema that represents a single literal.
* @stability stable
* @category constructors
* @since 4.0.0
*/
function Literals(literals) {
const members = literals.map(Literal);
return make(union(members, void 0, void 0), {
literals,
members,
mapMembers(f) {
return Union(f(this.members));
},
pick(literals) {
return Literals(literals);
},
transform(to) {
return Union(members.map((member, index) => member.transform(to[index])));
},
});
}
/**
* Creates a union schema of `S | null`.
*
* @stability stable
* @category constructors
* @since 3.10.0
*/
const NullOr = /*#__PURE__*/ lambda((self) => Union([self, Null]));
function decodeTo(to, transformation) {
return (from) => {
return make(
decodeTo$1(
from.ast,
to.ast,
transformation ? makeTransformation(transformation) : passthrough(),
),
{
from,
to,
},
);
};
}
/**
* Creates a schema that validates values using `instanceof`.
* Decoding and encoding pass the value through unchanged.
*
* **Example** (Defining a schema for a built-in class)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* const DateSchema = Schema.instanceOf(Date)
*
* const decoded = Schema.decodeUnknownSync(DateSchema)(new Date("2024-01-01"))
* decoded.toISOString() // => "2024-01-01T00:00:00.000Z"
* ```
*
* @stability stable
* @category constructors
* @since 3.10.0
*/
function instanceOf(constructor, annotations) {
return declare((u) => u instanceof constructor, annotations);
}
/**
* Creates a custom validation filter from a predicate function.
*
* **Details**
*
* The predicate receives the decoded input value, the schema AST, and parse
* options, and returns a `FilterOutput`. Non-success outputs are normalized into
* schema issues. The `annotations` parameter annotates the filter itself; with
* the default formatter, failures use `message` first, `expected` second, and
* `<filter>` when neither is provided.
*
* When `abort` is `true`, parsing stops after this filter fails instead of
* collecting later check failures.
*
* **Example** (Reporting failure at a nested path)
*
* ```ts import.meta.vitest
* import { Result, Schema } from "effect"
*
* const schema = Schema.Struct({ password: Schema.String, confirmPassword: Schema.String }).check(
* Schema.makeFilter((o) =>
* o.password === o.confirmPassword
* ? undefined
* : { path: ["password"], issue: "password and confirmPassword must match" }
* )
* )
*
* const result = Schema.decodeUnknownResult(schema)({ password: "123456", confirmPassword: "1234567" })
* if (Result.isFailure(result) && result.failure.issue._tag === "Filter" && result.failure.issue.issue._tag === "Pointer") {
* result.failure.issue.issue.path // => ["password"]
* }
* ```
*
* **Example** (Reporting multiple failures at once)
*
* ```ts import.meta.vitest
* import { Result, Schema } from "effect"
*
* const schema = Schema.Struct({ a: Schema.Finite, b: Schema.Finite, c: Schema.Finite }).check(
* Schema.makeFilter((o) => {
* const issues: Array<Schema.FilterIssue> = []
* if (o.a > 0) {
* if (o.b <= 0) issues.push({ path: ["b"], issue: "b must be greater than 0" })
* if (o.c <= 0) issues.push({ path: ["c"], issue: "c must be greater than 0" })
* }
* return issues
* })
* )
*
* const result = Schema.decodeUnknownResult(schema)({ a: 1, b: 0, c: 0 })
* if (Result.isFailure(result) && result.failure.issue._tag === "Filter" && result.failure.issue.issue._tag === "Composite") {
* result.failure.issue.issue.issues.map((issue) => issue._tag === "Pointer" ? issue.path : []) // => [["b"], ["c"]]
* }
* ```
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const makeFilter = makeFilter$1;
/**
* Creates a greater-than-or-equal-to (`>=`) check for any ordered type from an
* `Order.Order` instance.
*
* @stability stable
* @category validation
* @since 4.0.0
*/
function makeIsGreaterThanOrEqualTo(options) {
const gte = isGreaterThanOrEqualTo$1(options.order);
const formatter = options.formatter ?? format$1;
return (minimum, annotations) => {
return makeFilter((input) => gte(input, minimum), {
expected: `a value greater than or equal to ${formatter(minimum)}`,
arbitraryConstraint: {
order: options.order,
minimum,
},
...options.annotate?.(minimum),
...annotations,
});
};
}
/**
* Creates a less-than-or-equal-to (`<=`) check for any ordered type from an
* `Order.Order` instance.
*
* @stability stable
* @category validation
* @since 4.0.0
*/
function makeIsLessThanOrEqualTo(options) {
const lte = isLessThanOrEqualTo$1(options.order);
const formatter = options.formatter ?? format$1;
return (maximum, annotations) => {
return makeFilter((input) => lte(input, maximum), {
expected: `a value less than or equal to ${formatter(maximum)}`,
arbitraryConstraint: {
order: options.order,
maximum,
},
...options.annotate?.(maximum),
...annotations,
});
};
}
function encodeNumberPayload(number) {
if (!globalThis.Number.isFinite(number))
throw new globalThis.RangeError(
`Expected a finite number, got ${format$1(number)}`,
);
return number;
}
/**
* Validates that a number is greater than or equal to the specified value
* (inclusive).
*
* **Details**
*
* JSON Schema:
*
* This check corresponds to the `minimum` constraint in JSON Schema.
*
* Arbitrary:
*
* During arbitrary generation, this applies a `minimum` constraint
* to ensure generated numbers are greater than or equal to the specified value.
*
* @stability stable
* @category validation
* @since 4.0.0
*/
const isGreaterThanOrEqualTo = /*#__PURE__*/ makeIsGreaterThanOrEqualTo({
order: Number$4,
annotate: (minimum) => ({
representation: {
id: "effect/schema/isGreaterThanOrEqualTo",
payload: { minimum: encodeNumberPayload(minimum) },
},
toJsonSchema: () => ({ minimum }),
toCode: () => ({
runtime: `Schema.isGreaterThanOrEqualTo(${format$1(minimum)})`,
}),
}),
});
/**
* Validates that a number is less than or equal to the specified value
* (inclusive).
*
* **Details**
*
* JSON Schema:
*
* This check corresponds to the `maximum` constraint in JSON Schema.
*
* Arbitrary:
*
* During arbitrary generation, this applies a `maximum` constraint
* to ensure generated numbers are less than or equal to the specified value.
*
* @stability stable
* @category validation
* @since 4.0.0
*/
const isLessThanOrEqualTo = /*#__PURE__*/ makeIsLessThanOrEqualTo({
order: Number$4,
annotate: (maximum) => ({
representation: {
id: "effect/schema/isLessThanOrEqualTo",
payload: { maximum: encodeNumberPayload(maximum) },
},
toJsonSchema: () => ({ maximum }),
toCode: () => ({
runtime: `Schema.isLessThanOrEqualTo(${format$1(maximum)})`,
}),
}),
});
/**
* Validates that a value has at least the specified length. Works with strings
* and arrays.
*
* **Details**
*
* JSON Schema:
*
* The bound must be finite; it is rounded down and clamped to zero. For arrays,
* this check corresponds to `minItems`. JavaScript counts UTF-16 code units
* while JSON Schema counts Unicode code points, so strings use
* `minLength: Math.ceil(minLength / 2)`, the tightest lower bound that cannot
* reject a string accepted by this check.
*
* Arbitrary:
*
* During arbitrary generation, this applies a `minLength`
* constraint to ensure generated strings or arrays have at least the required
* length.
*
* **Example** (Checking minimum length)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* const NonEmptyStringSchema = Schema.String.check(Schema.isMinLength(1))
* const NonEmptyArraySchema = Schema.Array(Schema.Number).check(Schema.isMinLength(1))
* Schema.is(NonEmptyStringSchema)("a") // => true
* Schema.is(NonEmptyArraySchema)([1]) // => true
* ```
*
* @stability stable
* @category validation
* @since 4.0.0
*/
function isMinLength(minLength, annotations) {
minLength = normalizeCardinality(minLength);
return makeIsMinLength(minLength, Math.ceil(minLength / 2), annotations);
}
function makeIsMinLength(minLength, minCodePoints, annotations) {
return makeFilter((input) => input.length >= minLength, {
expected: `a value with a length of at least ${minLength}`,
representation: {
id: "effect/schema/isMinLength",
payload: { minLength },
},
toJsonSchema: ({ type }) =>
type === "string"
? minLength <= 1
? { minLength: minCodePoints }
: [{ minLength: minCodePoints }, true]
: type === "array"
? { minItems: minLength }
: type === void 0
? [
{
minLength: minCodePoints,
minItems: minLength,
},
true,
]
: [{}, true],
toCode: () => ({ runtime: `Schema.isMinLength(${minLength})` }),
[STRUCTURAL_ANNOTATION_KEY]: true,
arbitraryConstraint: { minLength },
...annotations,
});
}
/**
* Validates that a value has at most the specified length. Works with strings
* and arrays.
*
* **Details**
*
* JSON Schema:
*
* The bound must be finite; it is rounded down and clamped to zero. This check
* corresponds to `maxItems` for arrays. Strings use the same bound for
* `maxLength`, which cannot reject a string accepted by this check because a
* string has no more code points than UTF-16 code units.
*
* Arbitrary:
*
* During arbitrary generation, this applies a `maxLength`
* constraint to ensure generated strings or arrays have at most the required
* length.
*
* @stability stable
* @category validation
* @since 4.0.0
*/
function isMaxLength(maxLength, annotations) {
maxLength = normalizeCardinality(maxLength);
return makeFilter((input) => input.length <= maxLength, {
expected: `a value with a length of at most ${maxLength}`,
representation: {
id: "effect/schema/isMaxLength",
payload: { maxLength },
},
toJsonSchema: ({ type }) =>
type === "string"
? maxLength === 0
? { maxLength }
: [{ maxLength }, true]
: type === "array"
? { maxItems: maxLength }
: type === void 0
? [
{
maxLength,
maxItems: maxLength,
},
true,
]
: [{}, true],
toCode: () => ({ runtime: `Schema.isMaxLength(${maxLength})` }),
[STRUCTURAL_ANNOTATION_KEY]: true,
arbitraryConstraint: { maxLength },
...annotations,
});
}
function normalizeCardinality(value) {
if (!globalThis.Number.isFinite(value))
throw new globalThis.RangeError(`Expected a finite number, got ${value}`);
return Math.max(0, Math.floor(value));
}
globalThis.RegExp;
globalThis.URL;
globalThis.File;
globalThis.FormData;
globalThis.URLSearchParams;
globalThis.Uint8Array;
//#endregion
//#region ../schemas/libraries/effect/download/index.ts
const Image = Struct({
id: Number$1,
created: instanceOf(Date),
title: String$1.check(isMinLength(1), isMaxLength(100)),
type: Literals(["jpg", "png"]),
size: Number$1,
url: String$1.check(makeFilter((value) => URL.canParse(value))),
});
const Rating = Struct({
id: Number$1,
stars: Number$1.check(isGreaterThanOrEqualTo(1), isLessThanOrEqualTo(5)),
title: String$1.check(isMinLength(1), isMaxLength(100)),
text: String$1.check(isMinLength(1), isMaxLength(1e3)),
images: mutable(ArraySchema(Image)),
});
decodeUnknownSync(
Struct({
id: Number$1,
created: instanceOf(Date),
title: String$1.check(isMinLength(1), isMaxLength(100)),
brand: String$1.check(isMinLength(1), isMaxLength(30)),
description: String$1.check(isMinLength(1), isMaxLength(500)),
price: Number$1.check(isGreaterThanOrEqualTo(1), isLessThanOrEqualTo(1e4)),
discount: NullOr(
Number$1.check(isGreaterThanOrEqualTo(1), isLessThanOrEqualTo(100)),
),
quantity: Number$1.check(
isGreaterThanOrEqualTo(0),
isLessThanOrEqualTo(10),
),
tags: mutable(ArraySchema(String$1.check(isMinLength(1), isMaxLength(30)))),
images: mutable(ArraySchema(Image)),
ratings: mutable(ArraySchema(Rating)),
}),
)({});
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Pipeable.js
/**
* The `Pipeable` module defines the shared interface and implementation helpers
* for values that support Effect-style method chaining with `.pipe(...)`.
*
* A `Pipeable` value can pass itself through a sequence of unary functions from
* left to right, so code can be written as `value.pipe(f, g, h)` instead of
* deeply nesting calls. This is the method form used by many Effect data types
* to compose transformations, validations, and effectful operations while
* keeping the original value as the starting point of the pipeline.
*
* @stability stable
* @since 2.0.0
*/
/**
* Applies a `pipe` method's variadic arguments to an initial value from left
* to right.
*
* **When to use**
*
* Use to implement a custom `.pipe(...)` method from JavaScript's `arguments`
* object.
*
* **Details**
*
* This helper is intended for implementing `Pipeable.pipe` methods that
* receive JavaScript's `arguments` object. With no functions it returns the
* original value; otherwise it feeds each result into the next function.
*
* **Example** (Implementing a pipe method)
*
* ```ts import.meta.vitest
* import { Pipeable } from "effect"
*
* class NumberBox {
* constructor(readonly value: number) {}
*
* pipe(..._fns: ReadonlyArray<(value: number) => number>): number {
* return Pipeable.pipeArguments(this.value, arguments) as number
* }
* }
*
* const result = new NumberBox(5).pipe(
* (n) => n + 2,
* (n) => n * 3
* )
* result // => 21
* ```
*
* @stability stable
* @category combinators
* @since 2.0.0
*/
const pipeArguments = (self, args) => {
switch (args.length) {
case 0:
return self;
case 1:
return args[0](self);
case 2:
return args[1](args[0](self));
case 3:
return args[2](args[1](args[0](self)));
case 4:
return args[3](args[2](args[1](args[0](self))));
case 5:
return args[4](args[3](args[2](args[1](args[0](self)))));
case 6:
return args[5](args[4](args[3](args[2](args[1](args[0](self))))));
case 7:
return args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))));
case 8:
return args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self))))))));
case 9:
return args[8](args[7](args[6](args[5](args[4](args[3](args[2](args[1](args[0](self)))))))));
default: {
let ret = self;
for (let i = 0, len = args.length; i < len; i++) ret = args[i](ret);
return ret;
}
}
};
/**
* Reusable prototype that implements `Pipeable.pipe`.
*
* **When to use**
*
* Use when classes or object prototypes can reuse this value when they need the
* standard pipe implementation backed by `pipeArguments`.
*
* @stability stable
* @category prototypes
* @since 3.15.0
*/
const Prototype$1 = {
pipe() {
return pipeArguments(this, arguments);
},
};
/**
* Provides a base constructor whose instances implement the standard `Pipeable.pipe`
* method.
*
* **When to use**
*
* Use when you need to define a class that supports Effect-style method
* chaining through `.pipe(...)`.
*
* @stability stable
* @category constructors
* @since 3.15.0
*/
const Class$1 = /*#__PURE__*/ (function () {
function PipeableBase() {}
PipeableBase.prototype = Prototype$1;
return PipeableBase;
})();
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Function.js
/**
* Creates a function that can be called in data-first style or data-last
* (`pipe`-friendly) style.
*
* **When to use**
*
* Use to expose one implementation through both direct and `pipe`-friendly
* call styles.
*
* **Details**
*
* Pass either the arity of the uncurried function or a predicate that decides
* whether the current call is data-first. Arity is the common case. Use a
* predicate when optional arguments make arity ambiguous.
*
* **Example** (Selecting data-first or data-last style by arity)
*
* ```ts import.meta.vitest
* import { Function, pipe } from "effect"
*
* const sum = Function.dual<
* (that: number) => (self: number) => number,
* (self: number, that: number) => number
* >(2, (self, that) => self + that)
*
* sum(2, 3) // => 5
* pipe(2, sum(3)) // => 5
* ```
*
* **Example** (Defining overloads with call signatures)
*
* ```ts import.meta.vitest
* import { Function, pipe } from "effect"
*
* const sum: {
* (that: number): (self: number) => number
* (self: number, that: number): number
* } = Function.dual(2, (self: number, that: number): number => self + that)
*
* sum(2, 3) // => 5
* pipe(2, sum(3)) // => 5
* ```
*
* **Example** (Selecting data-first or data-last style with a predicate)
*
* ```ts import.meta.vitest
* import { Function, pipe } from "effect"
*
* const sum = Function.dual<
* (that: number) => (self: number) => number,
* (self: number, that: number) => number
* >(
* (args) => args.length === 2,
* (self, that) => self + that
* )
*
* sum(2, 3) // => 5
* pipe(2, sum(3)) // => 5
* ```
*
* @stability stable
* @category combinators
* @since 2.0.0
*/
const dual = function (arity, body) {
if (typeof arity === "function")
return function () {
return arity(arguments) ? body.apply(this, arguments) : (self) => body(self, ...arguments);
};
switch (arity) {
case 0:
case 1:
throw new RangeError(`Invalid arity ${arity}`);
case 2:
return function (a, b) {
if (arguments.length >= 2) return body(a, b);
return function (self) {
return body(self, a);
};
};
case 3:
return function (a, b, c) {
if (arguments.length >= 3) return body(a, b, c);
return function (self) {
return body(self, a, b);
};
};
default:
return function () {
if (arguments.length >= arity) return body.apply(this, arguments);
const args = arguments;
return function (self) {
return body(self, ...args);
};
};
}
};
/**
* Returns its input argument unchanged.
*
* **When to use**
*
* Use to return a value unchanged where a function is required.
*
* **Example** (Returning the same value)
*
* ```ts import.meta.vitest
* import { identity } from "effect"
*
* identity(5) // => 5
* ```
*
* @stability stable
* @category combinators
* @since 2.0.0
*/
const identity = (a) => a;
/**
* Creates a zero-argument function that always returns the provided value.
*
* **When to use**
*
* Use when you need a thunk or callback that returns the same value on every
* invocation.
*
* **Example** (Creating a constant thunk)
*
* ```ts import.meta.vitest
* import { Function } from "effect"
*
* const constNull = Function.constant(null)
*
* constNull() // => null
* constNull() // => null
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const constant = (value) => () => value;
/**
* Returns `true` when called.
*
* **When to use**
*
* Use when you need a thunk that returns `true` on every invocation.
*
* **Example** (Returning true from a thunk)
*
* ```ts import.meta.vitest
* import { Function } from "effect"
*
* Function.constTrue() // => true
* ```
*
* @stability stable
* @category constants
* @since 2.0.0
*/
const constTrue = /*#__PURE__*/ constant(true);
/**
* Returns `undefined` when called.
*
* **When to use**
*
* Use when you need a thunk that returns `undefined` on every invocation.
*
* **Example** (Returning undefined from a thunk)
*
* ```ts import.meta.vitest
* import { Function } from "effect"
*
* Function.constUndefined() // => undefined
* ```
*
* @stability stable
* @category constants
* @since 2.0.0
*/
const constUndefined = /*#__PURE__*/ constant(void 0);
/**
* Returns no meaningful value when called.
*
* **When to use**
*
* Use when you need a thunk that is called only for its effect and has no
* meaningful return value.
*
* **Example** (Returning void from a thunk)
*
* ```ts import.meta.vitest
* import { Function } from "effect"
*
* Function.constVoid() // => undefined
* ```
*
* @stability stable
* @category constants
* @since 2.0.0
*/
const constVoid = constUndefined;
/**
* Creates a memoized function whose input is an object, caching results by
* object identity.
*
* **When to use**
*
* Use to reuse the result of a synchronous computation whose output is stable
* for a given object reference.
*
* **Details**
*
* Each memoized wrapper owns a private `WeakMap` keyed by object identity.
*
* **Gotchas**
*
* `undefined` is reserved to represent a cache miss and is therefore not
* supported as a return value.
*
* Structurally equal objects do not share cache entries. If the same object is
* mutated after its first call, later calls still return the cached result for
* that reference.
*
* @stability stable
* @category caching
* @since 4.0.0
*/
function memoize(f) {
const cache = /* @__PURE__ */ new WeakMap();
return (a) => {
const cached = cache.get(a);
if (cached !== void 0) return cached;
const result = f(a);
cache.set(a, result);
return result;
};
}
/**
* Creates a memoized idempotent object transformation that caches both inputs
* and their outputs by object identity.
*
* **When to use**
*
* Use when an object transformation is idempotent and its output can be safely
* reused as a fixed point.
*
* **Details**
*
* After computing an input, the returned function caches both the input and
* the output. Calling it with either reference returns the output without
* invoking the supplied function again.
*
* **Gotchas**
*
* The returned function treats each computed output as a fixed point. If
* applying the supplied function to an output would produce an observably
* different value, this memoization changes that behavior.
*
* @see {@link memoize} for memoizing functions without an idempotence requirement
* @stability stable
* @category caching
* @since 4.0.0
*/
function memoizeIdempotent(f) {
const cache = /* @__PURE__ */ new WeakMap();
return (a) => {
const cached = cache.get(a);
if (cached !== void 0) return cached;
const result = f(a);
cache.set(a, result);
if (result !== a) cache.set(result, result);
return result;
};
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/equal.js
/** @internal */
const getAllObjectKeys = (obj) => {
const keys = new Set(Reflect.ownKeys(obj));
if (obj.constructor === Object) return keys;
if (obj instanceof Error) keys.delete("stack");
const proto = Object.getPrototypeOf(obj);
let current = proto;
while (current !== null && current !== Object.prototype) {
const ownKeys = Reflect.ownKeys(current);
for (let i = 0; i < ownKeys.length; i++) keys.add(ownKeys[i]);
current = Object.getPrototypeOf(current);
}
if (
keys.has("constructor") &&
typeof obj.constructor === "function" &&
proto === obj.constructor.prototype
)
keys.delete("constructor");
return keys;
};
/** @internal */
const byReferenceInstances = /*#__PURE__*/ new WeakSet();
/** @internal */
const viewBytes = (view) => new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/hash.js
/**
* Back-edge count used to avoid caching entry-point-dependent hashes.
*
* @internal
*/
let backEdges = 0;
/** @internal */
const addBackEdge = () => {
backEdges++;
};
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Predicate.js
/**
* Defines runtime checks for values.
*
* A `Predicate<A>` returns `true` or `false` for an `A`. A
* `Refinement<A, B>` is a predicate that also narrows the TypeScript type when
* it succeeds. This module includes guards for common JavaScript values,
* property and tag checks, tuple and struct checks, boolean combinators, and
* helpers for composing predicates and refinements.
*
* @stability stable
* @since 2.0.0
*/
/**
* Checks whether a value is a `string`.
*
* **When to use**
*
* Use when you need a `Predicate` guard to narrow an `unknown` value to a
* string.
*
* **Details**
*
* Uses `typeof input === "string"`.
*
* **Example** (Guarding strings)
*
* ```ts import.meta.vitest
* import { Predicate } from "effect"
*
* const data: unknown = "hi"
*
* if (Predicate.isString(data)) {
* data.toUpperCase() // => "HI"
* }
* ```
*
* @see {@link isNumber}
* @see {@link isBoolean}
* @see {@link Refinement}
* @stability stable
* @category guards
* @since 2.0.0
*/
function isString$1(input) {
return typeof input === "string";
}
/**
* Checks whether a value is a `number`.
*
* **When to use**
*
* Use when you need a `Predicate` guard to narrow an `unknown` value to a
* number.
*
* **Details**
*
* Uses `typeof input === "number"` and does not exclude `NaN` or `Infinity`.
*
* **Example** (Guarding numbers)
*
* ```ts import.meta.vitest
* import { Predicate } from "effect"
*
* const data: unknown = 42
*
* if (Predicate.isNumber(data)) {
* data + 1 // => 43
* }
* ```
*
* @see {@link isBigInt}
* @see {@link isString}
* @stability stable
* @category guards
* @since 2.0.0
*/
function isNumber(input) {
return typeof input === "number";
}
/**
* Checks whether a value is a `function`.
*
* **When to use**
*
* Use when you need a `Predicate` guard to narrow an `unknown` value to a
* callable function.
*
* **Details**
*
* Uses `typeof input === "function"`.
*
* **Example** (Guarding functions)
*
* ```ts import.meta.vitest
* import { Predicate } from "effect"
*
* const data: unknown = () => 1
*
* if (Predicate.isFunction(data)) {
* data() // => 1
* }
* ```
*
* @see {@link isObjectKeyword}
* @stability stable
* @category guards
* @since 2.0.0
*/
function isFunction(input) {
return typeof input === "function";
}
/**
* Checks whether a value is not `null` and not `undefined`.
*
* **When to use**
*
* Use when you need a `Predicate` refinement that filters out nullish values
* but keeps other falsy ones.
*
* **Details**
*
* Uses `input != null`.
*
* **Example** (Filtering non-nullish values)
*
* ```ts import.meta.vitest
* import { Predicate } from "effect"
*
* const values = [0, null, "", undefined]
* const present = values.filter(Predicate.isNotNullish) // => [0, ""]
* ```
*
* @see {@link isNullish}
* @see {@link isNotNull}
* @see {@link isNotUndefined}
* @stability stable
* @category guards
* @since 4.0.0
*/
function isNotNullish(input) {
return input != null;
}
/**
* Type guard that always returns `true`.
*
* **When to use**
*
* Use when you need a `Predicate` that always accepts, e.g. as a placeholder.
*
* **Example** (Matching every value)
*
* ```ts import.meta.vitest
* import { Predicate } from "effect"
*
* Predicate.isUnknown(123) // => true
* ```
*
* @see {@link isNever}
* @stability stable
* @category guards
* @since 2.0.0
*/
function isUnknown(_) {
return true;
}
/**
* Checks whether a value is an `object` in the JavaScript sense (objects, arrays, functions).
*
* **When to use**
*
* Use when you need a `Predicate` guard that accepts arrays and functions as
* well as objects.
*
* **Details**
*
* Returns `true` for arrays and functions, and `false` for `null`.
*
* **Example** (Checking object keywords)
*
* ```ts import.meta.vitest
* import { Predicate } from "effect"
*
* Predicate.isObjectKeyword(() => 1) // => true
* Predicate.isObjectKeyword(null) // => false
* ```
*
* @see {@link isObject}
* @see {@link isObjectOrArray}
* @stability stable
* @category guards
* @since 4.0.0
*/
function isObjectKeyword(input) {
return (typeof input === "object" && input !== null) || isFunction(input);
}
/**
* Checks whether a value has a given property key.
*
* **When to use**
*
* Use when you need a `Predicate` guard for property access on `unknown`
* values with a simple structural object check.
*
* **Details**
*
* Uses the `in` operator and `isObjectKeyword`. This does not check property
* value types.
*
* **Example** (Guarding object properties)
*
* ```ts import.meta.vitest
* import { Predicate } from "effect"
*
* const hasName = Predicate.hasProperty("name")
* const data: unknown = { name: "Ada" }
*
* if (hasName(data)) {
* data.name // => "Ada"
* }
* ```
*
* @see {@link isTagged}
* @see {@link isObjectKeyword}
* @stability stable
* @category guards
* @since 2.0.0
*/
const hasProperty = /*#__PURE__*/ dual(
2,
(self, property) => isObjectKeyword(self) && property in self,
);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Hash.js
/**
* Computes Effect hash values and defines the interface for objects that want
* to provide their own hash implementation. Hashes are small numeric
* fingerprints used by Effect data structures to bucket values quickly; they
* are not cryptographic digests and they are not proof that two values are
* equal. The module also includes helpers for primitive, structure, array, and
* reference-based hashes, plus functions for combining and optimizing numeric
* hash values.
*
* @stability stable
* @since 2.0.0
*/
/**
* Defines the unique identifier used to identify objects that implement the Hash interface.
*
* **When to use**
*
* Use as the computed property key for the method that supplies a custom hash
* value on a `Hash` implementor.
*
* @see {@link Hash} for the interface implemented with this symbol
* @see {@link isHash} for checking whether a value implements `Hash`
* @see {@link hash} for computing hash values
*
* @stability stable
* @category symbols
* @since 2.0.0
*/
const symbol$1 = "~effect/Hash";
/**
* Computes a hash value for any given value.
*
* **When to use**
*
* Use to compute an Effect hash for primitives, collections, and hashable
* objects.
*
* **Details**
*
* This function can hash primitives (numbers, strings, booleans, etc.) as well as
* objects, arrays, and other complex data structures. It automatically handles
* different types and provides a consistent hash value for equivalent inputs.
*
* **Gotchas**
*
* Objects being hashed must be treated as immutable after their first hash
* computation. Hash results are cached, so mutating an object after hashing will
* lead to stale cached values and broken hash-based operations. For mutable
* objects, implement a custom `Hash` interface that hashes the object reference
* rather than its content.
*
* **Example** (Hashing different values)
*
* ```ts import.meta.vitest
* import { Hash } from "effect"
*
* Hash.hash(42) === Hash.hash(42) // => true
* Hash.hash("hello") === Hash.hash("hello") // => true
* Hash.hash([1, 2, 3]) === Hash.hash([1, 2, 3]) // => true
* ```
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const hash = (self) => {
switch (typeof self) {
case "number":
return number$1(self);
case "bigint":
return string$1(self.toString(10));
case "string":
return string$1(self);
case "function":
case "object":
if (self === null) break;
else if (self instanceof Date) {
if (Number.isNaN(self.getTime())) return string$1("Invalid Date");
return string$1(self.toISOString());
} else if (self instanceof RegExp) return string$1(self.toString());
else {
if (byReferenceInstances.has(self)) return random(self);
const cached = hashCache.get(self);
if (cached !== void 0) return cached;
if (visitedObjects.has(self)) {
addBackEdge();
return string$1("[Circular]");
}
visitedObjects.add(self);
const seen = backEdges;
let h;
try {
if ("~effect/Hash" in self) h = self[symbol$1]();
else if (typeof self === "function") h = random(self);
else if (self instanceof DataView) h = array(viewBytes(self));
else if (Array.isArray(self) || ArrayBuffer.isView(self)) h = array(self);
else if (self instanceof Map) h = hashMap(self);
else if (self instanceof Set) h = hashSet(self);
else h = structure(self);
} finally {
visitedObjects.delete(self);
}
if (seen === backEdges) hashCache.set(self, h);
return h;
}
}
return optimize(mix(string$1(String(self))));
};
/**
* Generates a random hash value for an object and caches it.
*
* **When to use**
*
* Use to hash an object by reference identity instead of structural content.
*
* **Details**
*
* This function creates a random hash value for objects that don't have their own
* hash implementation. The hash value is cached using a WeakMap, so the same object
* will always return the same hash value during its lifetime.
*
* **Example** (Hashing objects by reference)
*
* ```ts import.meta.vitest
* import { Hash } from "effect"
*
* const obj1 = { a: 1 }
* const obj2 = { a: 1 }
*
* Hash.random(obj1) === Hash.random(obj1) // => true
*
* typeof Hash.random(obj2) // => "number"
* ```
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const random = (self) => {
if (!randomHashCache.has(self))
randomHashCache.set(self, optimize((Math.random() * 4294967296) | 0));
return randomHashCache.get(self);
};
const mix = (h) => {
h ^= h >>> 16;
h = Math.imul(h, 2246822507);
h ^= h >>> 13;
h = Math.imul(h, 3266489909);
return h ^ (h >>> 16);
};
/**
* Combines two hash values into a single hash value.
*
* **When to use**
*
* Use to build a hash for a composite value by folding together hash values for
* its parts.
*
* **Details**
*
* Supports direct and pipeable usage. Argument order affects the result.
*
* **Example** (Combining hash values)
*
* ```ts import.meta.vitest
* import { Hash, pipe } from "effect"
*
* const hash1 = Hash.hash("hello")
* const hash2 = Hash.hash("world")
*
* const combined = Hash.combine(hash2)(hash1)
* combined === pipe(hash1, Hash.combine(hash2)) // => true
* ```
*
* @see {@link hash} for computing hash values from arbitrary inputs
* @see {@link structureKeys} for hashing selected object fields without manual combination
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const combine = /*#__PURE__*/ dual(2, (self, b) =>
mix(Math.imul(self, 2654435761) + Math.imul(b, 2246822507)),
);
/**
* Applies bit manipulation techniques to optimize a hash value.
*
* **When to use**
*
* Use to improve the bit distribution of a raw numeric hash value.
*
* **Details**
*
* This function takes a hash value and applies bitwise operations to improve
* the distribution of hash values, reducing the likelihood of collisions.
*
* **Example** (Optimizing a hash value)
*
* ```ts import.meta.vitest
* import { Hash } from "effect"
*
* Hash.optimize(1234567890) // => 160826066
* ```
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const optimize = (n) => (n & 3221225471) | ((n >>> 1) & 1073741824);
const float64 = /*#__PURE__*/ new DataView(/*#__PURE__*/ new ArrayBuffer(8));
/**
* Computes a hash value for a number.
*
* **When to use**
*
* Use to hash a JavaScript number with Effect's numeric hash semantics.
*
* **Details**
*
* Int32 values hash to themselves. Other numbers hash from their IEEE-754 bits,
* with a canonical representation for `NaN`.
*
* **Example** (Hashing numbers)
*
* ```ts import.meta.vitest
* import { Hash } from "effect"
*
* Number.isInteger(Hash.number(42)) // => true
* Number.isInteger(Hash.number(3.14)) // => true
* Hash.number(NaN) === Hash.number(NaN) // => true
* Hash.number(Infinity) === Hash.number(Infinity) // => true
* Hash.number(100) === Hash.number(100) // => true
* ```
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const number$1 = (n) => {
const h = n | 0;
if (h === n) return optimize(h);
float64.setFloat64(0, n !== n ? NaN : n);
return optimize(combine(float64.getInt32(0), float64.getInt32(4)));
};
/**
* Computes a hash value for a string using the djb2 algorithm.
*
* **When to use**
*
* Use when you need a string field to contribute to a custom structural hash
* implementation.
*
* **Details**
*
* This function implements a variation of the djb2 hash algorithm, which is
* known for its good distribution properties and speed. It processes each
* character of the string to produce a consistent hash value.
*
* **Example** (Hashing strings)
*
* ```ts import.meta.vitest
* import { Hash } from "effect"
*
* Hash.string("hello") // => 181380007
* Hash.string("world") // => 164394279
* Hash.string("") // => 5381
* Hash.string("test") === Hash.string("test") // => true
* ```
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const string$1 = (str) => {
let h = 5381,
i = str.length;
while (i) h = (h * 33) ^ str.charCodeAt(--i);
return optimize(h);
};
/**
* Computes a hash value for an object using only the specified keys.
*
* **When to use**
*
* Use to hash an object by a selected set of property keys.
*
* **Details**
*
* This function allows you to hash an object by considering only specific keys,
* which is useful when you want to create a hash based on a subset of an object's
* properties.
*
* **Example** (Hashing selected object keys)
*
* ```ts import.meta.vitest
* import { Hash } from "effect"
*
* const person = { name: "John", age: 30, city: "New York" }
*
* const hash1 = Hash.structureKeys(person, ["name", "age"])
* const hash2 = Hash.structureKeys(person, ["name", "city"])
*
* hash1 // => -731887653
* hash2 // => 148523102
*
* const person2 = { name: "John", age: 30, city: "Boston" }
* const hash3 = Hash.structureKeys(person2, ["name", "age"])
* hash1 === hash3 // => true
* ```
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const structureKeys = (o, keys) => {
let h = 12289;
for (const key of keys) h ^= combine(hash(key), hash(o[key]));
return optimize(h);
};
/**
* Computes a structural hash for an object using Effect's object key collection.
*
* **When to use**
*
* Use to hash an object from all structural keys collected by Effect.
*
* **Details**
*
* The hash is based on the object's structural keys and their values, including
* symbol keys and relevant prototype keys for non-plain objects.
*
* **Example** (Hashing object structures)
*
* ```ts import.meta.vitest
* import { Hash } from "effect"
*
* const obj1 = { name: "John", age: 30 }
* const obj2 = { name: "Jane", age: 25 }
* const obj3 = { name: "John", age: 30 }
*
* Hash.structure(obj1) // => -731887653
* Hash.structure(obj2) // => -222100417
* Hash.structure(obj3) // => -731887653
* Hash.structure(obj1) === Hash.structure(obj3) // => true
* ```
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const structure = (o) => structureKeys(o, getAllObjectKeys(o));
const unordered = (seed, f) => (iter) => {
let h = seed;
for (const element of iter) h ^= f(element);
return optimize(h);
};
/**
* Computes a hash value for an iterable by hashing all of its elements.
*
* **When to use**
*
* Use to hash the values yielded by an iterable with Effect hash semantics.
*
* **Details**
*
* Folds element hashes with {@link combine}, so order and length affect the
* result.
*
* **Gotchas**
*
* A hash is not an equality proof. Distinct inputs can still share a hash.
*
* **Example** (Hashing arrays)
*
* ```ts import.meta.vitest
* import { Hash } from "effect"
*
* const arr1 = [1, 2, 3]
* const arr2 = [1, 2, 3]
* const arr3 = [3, 2, 1]
*
* Hash.array(arr1) === Hash.array(arr2) // => true
* Hash.array(arr1) === Hash.array(arr3) // => false
* ```
*
* @see {@link hash} for the general-purpose hash dispatcher
*
* @stability stable
* @category hashing
* @since 2.0.0
*/
const array = (arr) => {
let h = 6151;
for (const element of arr) h = combine(h, hash(element));
return optimize(h);
};
const hashMap = /*#__PURE__*/ unordered(/*#__PURE__*/ string$1("Map"), ([k, v]) =>
combine(hash(k), hash(v)),
);
const setSeed = /*#__PURE__*/ string$1("Set");
const hashSet = /*#__PURE__*/ unordered(setSeed, (element) => combine(setSeed, hash(element)));
const randomHashCache = /*#__PURE__*/ new WeakMap();
const hashCache = /*#__PURE__*/ new WeakMap();
const visitedObjects = /*#__PURE__*/ new WeakSet();
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Equal.js
/**
* Defines the unique string identifier for the `Equal` interface.
*
* **When to use**
*
* Use when you implement custom equality and need the computed property key for
* the equality method.
*
* **Details**
*
* This is a pure constant with no allocation or side effects.
*
* **Example** (Implementing Equal on a class)
*
* ```ts import.meta.vitest
* import { Equal, Hash } from "effect"
*
* class UserId implements Equal.Equal {
* constructor(readonly id: string) {}
*
* [Equal.symbol](that: Equal.Equal): boolean {
* return that instanceof UserId && this.id === that.id
* }
*
* [Hash.symbol](): number {
* return Hash.string(this.id)
* }
* }
*
* Equal.equals(new UserId("1"), new UserId("1")) // => true
* Equal.equals(new UserId("1"), new UserId("2")) // => false
* ```
*
* @see {@link Equal} — the interface that uses this symbol
* @see {@link isEqual} — type guard for `Equal` implementors
* @stability stable
* @category symbols
* @since 2.0.0
*/
const symbol = "~effect/Equal";
function equals$1() {
if (arguments.length === 1) return (self) => compareBoth(self, arguments[0]);
return compareBoth(arguments[0], arguments[1]);
}
function compareBoth(self, that) {
if (self === that) return true;
if (self == null || that == null) return false;
const selfType = typeof self;
if (selfType !== typeof that) return false;
if (selfType === "number" && self !== self && that !== that) return true;
if (selfType !== "object" && selfType !== "function") return false;
if (byReferenceInstances.has(self) || byReferenceInstances.has(that)) return false;
return compareObjects(self, that);
}
function compareObjects(self, that) {
const depth = pathLeft.length;
for (let i = depth; i-- > 0;) if (pathLeft[i] === self && pathRight[i] === that) return true;
if (depth) return compareOnPath(self, that);
let known = results.get(self);
if (!known) results.set(self, (known = /* @__PURE__ */ new WeakMap()));
let result = known.get(that);
if (result === void 0) known.set(that, (result = compareOnPath(self, that)));
return result;
}
function compareOnPath(self, that) {
pathLeft.push(self);
pathRight.push(that);
try {
return compareStructure(self, that);
} finally {
pathLeft.pop();
pathRight.pop();
}
}
const pathLeft = [];
const pathRight = [];
const results = /*#__PURE__*/ new WeakMap();
function compareStructure(self, that) {
if (hash(self) !== hash(that)) return false;
else if (self instanceof Date) {
if (!(that instanceof Date)) return false;
const selfTime = self.getTime();
const thatTime = that.getTime();
return selfTime === thatTime || (Number.isNaN(selfTime) && Number.isNaN(thatTime));
} else if (self instanceof RegExp)
return that instanceof RegExp && self.toString() === that.toString();
const bothEquals = isEqual(self);
if (bothEquals !== isEqual(that) || (typeof self === "function" && !bothEquals)) return false;
else if (bothEquals) return self[symbol](that);
else if (Array.isArray(self)) {
if (!Array.isArray(that) || self.length !== that.length) return false;
return compareArrays(self, that);
} else if (ArrayBuffer.isView(self)) {
const selfIsDataView = self instanceof DataView;
if (
!ArrayBuffer.isView(that) ||
self.byteLength !== that.byteLength ||
selfIsDataView !== that instanceof DataView
)
return false;
if (selfIsDataView) return compareTypedArrays(viewBytes(self), viewBytes(that));
return compareTypedArrays(self, that);
} else if (self instanceof Map) {
if (!(that instanceof Map) || self.size !== that.size) return false;
return compareHashed(self, that, entryHash, equalEntries);
} else if (self instanceof Set) {
if (!(that instanceof Set) || self.size !== that.size) return false;
return compareHashed(self, that, hash, compareBoth);
}
return compareRecords(self, that);
}
function compareArrays(self, that) {
for (let i = 0; i < self.length; i++) if (!compareBoth(self[i], that[i])) return false;
return true;
}
function compareTypedArrays(self, that) {
if (self.length !== that.length) return false;
for (let i = 0; i < self.length; i++) if (self[i] !== that[i]) return false;
return true;
}
function compareRecords(self, that) {
const selfKeys = getAllObjectKeys(self);
const thatKeys = getAllObjectKeys(that);
if (selfKeys.size !== thatKeys.size) return false;
for (const key of selfKeys)
if (!thatKeys.has(key) || !compareBoth(self[key], that[key])) return false;
return true;
}
function compareHashed(self, that, hashOf, equivalent) {
const groups = /* @__PURE__ */ new Map();
let remaining = 0;
for (const item of that) {
const h = hashOf(item);
const group = groups.get(h);
if (group) group.push(item);
else groups.set(h, [item]);
remaining++;
}
outer: for (const item of self) {
const group = groups.get(hashOf(item));
if (group) {
for (let i = 0; i < group.length; i++)
if (equivalent(item, group[i])) {
group[i] = group[group.length - 1];
group.pop();
remaining--;
continue outer;
}
}
return false;
}
return remaining === 0;
}
const entryHash = (entry) => hash(entry[0]);
const equalEntries = (self, that) => compareBoth(self[0], that[0]) && compareBoth(self[1], that[1]);
/**
* Checks whether a value implements the {@link Equal} interface.
*
* **When to use**
*
* Use when you need generic utility code to distinguish `Equal` implementors
* from plain values before calling `[Equal.symbol]` directly.
*
* **Details**
*
* - Pure function, no side effects.
* - Returns `true` if and only if `u` has a property keyed by
* {@link symbol}.
* - Acts as a TypeScript type guard, narrowing the input to {@link Equal}.
*
* **Example** (Checking Equal values)
*
* ```ts import.meta.vitest
* import { Equal, Hash } from "effect"
*
* class Token implements Equal.Equal {
* constructor(readonly value: string) {}
* [Equal.symbol](that: Equal.Equal): boolean {
* return that instanceof Token && this.value === that.value
* }
* [Hash.symbol](): number {
* return Hash.string(this.value)
* }
* }
*
* Equal.isEqual(new Token("abc")) // => true
* Equal.isEqual({ x: 1 }) // => false
* Equal.isEqual(42) // => false
* ```
*
* @see {@link Equal} — the interface being checked
* @see {@link symbol} — the property key that signals `Equal` support
* @stability stable
* @category guards
* @since 2.0.0
*/
const isEqual = (u) => hasProperty(u, symbol);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/array.js
/**
* @since 2.0.0
*/
/** @internal */
const isArrayNonEmpty$1 = (self) => self.length > 0;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/record.js
/** @internal */
function assignProperty(self, key, value) {
if (key === "__proto__")
Object.defineProperty(self, key, {
value,
writable: true,
enumerable: true,
configurable: true,
});
else self[key] = value;
}
/** @internal */
function assignProperties(self, source) {
for (const key of Reflect.ownKeys(source))
if (Object.prototype.propertyIsEnumerable.call(source, key))
assignProperty(self, key, source[key]);
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Redactable.js
/**
* Defines the symbol used to identify objects that implement the {@link Redactable}
* protocol.
*
* **When to use**
*
* Use as the property key when implementing the `Redactable` protocol.
*
* **Details**
*
* Add a method under this key to make an object redactable. The method receives
* the current `Context` and must return the replacement value. The symbol is
* registered globally via `Symbol.for("~effect/Redactable")`, so it is
* identical across multiple copies of the library at runtime.
*
* **Example** (Masking an API key)
*
* ```ts import.meta.vitest
* import { Context, Redactable } from "effect"
*
* class ApiKey {
* constructor(readonly raw: string) {}
*
* [Redactable.symbolRedactable](_ctx: Context.Context<never>) {
* return this.raw.slice(0, 4) + "..."
* }
* }
*
* Redactable.redact(new ApiKey("secret-key")) // => "secr..."
* ```
*
* @see {@link Redactable} for the interface this symbol belongs to
* @see {@link isRedactable} to check whether a value has this symbol
* @stability stable
* @category symbols
* @since 3.10.0
*/
const symbolRedactable = /*#__PURE__*/ Symbol.for("~effect/Redactable");
/**
* Type guard that checks whether a value implements the {@link Redactable}
* interface.
*
* **When to use**
*
* Use to narrow an unknown value before calling redaction-specific helpers.
*
* @see {@link Redactable} for the interface being checked
* @see {@link redact} to apply redaction if the value is redactable
* @stability stable
* @category guards
* @since 3.10.0
*/
const isRedactable = (u) => hasProperty(u, symbolRedactable);
/**
* Returns a redacted value if it implements {@link Redactable}, otherwise returns it
* unchanged.
*
* **When to use**
*
* Use as the general-purpose entry point for redaction when the input may
* or may not implement the redaction protocol.
*
* **Details**
*
* This function calls {@link isRedactable} and, when it returns `true`,
* delegates to {@link getRedacted}.
*
* **Gotchas**
*
* Redaction is not recursive. Nested redactable values inside the returned
* object are not automatically redacted.
*
* @see {@link isRedactable} to check before redacting
* @see {@link getRedacted} for the lower-level variant for known redactables
* @stability stable
* @category destructors
* @since 3.10.0
*/
function redact$2(u) {
if (isRedactable(u)) return getRedacted(u);
return u;
}
/**
* Returns the result of calling `[symbolRedactable]` on a value that is
* already known to be {@link Redactable}.
*
* **When to use**
*
* Use when you need to read the redacted representation from a value already
* verified as `Redactable`.
*
* **Details**
*
* This function reads the current fiber's `Context` from the global fiber
* reference and passes it to the redaction method.
*
* **Gotchas**
*
* If no fiber is active, an empty `Context` is passed to the redaction method.
*
* @see {@link redact} for the higher-level variant that handles non-redactable values
* @see {@link isRedactable} for the type guard to verify before calling this
* @stability stable
* @category destructors
* @since 4.0.0
*/
function getRedacted(redactable) {
return redactable[symbolRedactable](
globalThis["~effect/Fiber/currentFiber"]?.context ?? emptyContext$1,
);
}
/** @internal */
const currentFiberTypeId = "~effect/Fiber/currentFiber";
const emptyMap = /*#__PURE__*/ new Map();
const emptyContext$1 = {
"~effect/Context": {},
base: emptyMap,
depth: 0,
mapUnsafe: emptyMap,
pipe() {
return pipeArguments(this, arguments);
},
};
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Formatter.js
/**
* Formats JavaScript values into readable strings.
*
* `format` is intended for logs, diagnostics, and error messages. It handles
* primitives, objects, arrays, dates, regular expressions, maps, sets, class
* instances, errors, circular references, and redactable values. `formatJson`
* wraps JSON formatting with redaction and circular-reference handling, and the
* module also includes helpers for property keys, paths, and dates.
*
* @stability stable
* @since 4.0.0
*/
/**
* Converts any JavaScript value into a human-readable string.
*
* **When to use**
*
* Use when you need to format arbitrary JavaScript values for debugging,
* logging, or error messages.
*
* **Details**
*
* - Output is **not** valid JSON; use {@link formatJson} when you need
* parseable JSON.
* - Handles `BigInt`, `Symbol`, `Set`, `Map`, `Date`, `RegExp`, and class
* instances that `JSON.stringify` cannot represent.
* - Circular references are shown as `"[Circular]"` instead of throwing.
* - Failures while inspecting a value are rendered as diagnostic placeholders instead of throwing.
* - Primitives: stringified naturally (`null`, `undefined`, `123`, `true`).
* Strings are JSON-quoted.
* - Objects with a custom `toString` (not `Object.prototype.toString`):
* `toString()` is called unless `ignoreToString` is `true`.
* - Errors with a `cause`: formatted as `"<message> (cause: <cause>)"`.
* - Iterables (`Set`, `Map`, etc.): formatted as
* `ClassName([...elements])`.
* - Class instances: wrapped as `ClassName({...})`.
* - `Redactable` values are automatically redacted.
* - Arrays/objects with 0–1 entries are inline; larger ones are
* pretty-printed when `space` is set.
* - `space` — indentation unit (number of spaces, or a string like
* `"\t"`). Defaults to `0` (compact).
* - `ignoreToString` — skip calling `toString()`. Defaults to `false`.
*
* **Example** (Formatting compact output)
*
* ```ts import.meta.vitest
* import { Formatter } from "effect"
*
* Formatter.format({ a: 1, b: [2, 3] }) // => "{\"a\":1,\"b\":[2,3]}"
* ```
*
* **Example** (Pretty-printed output)
*
* ```ts import.meta.vitest
* import { Formatter } from "effect"
*
* const output = Formatter.format({ a: 1, b: [2, 3] }, { space: 2 })
* output // => "{\n \"a\": 1,\n \"b\": [\n 2,\n 3\n ]\n}"
* ```
*
* **Example** (Handling circular references)
*
* ```ts import.meta.vitest
* import { Formatter } from "effect"
*
* const obj: any = { name: "loop" }
* obj.self = obj
* Formatter.format(obj) // => "{\"name\":\"loop\",\"self\":[Circular]}"
* ```
*
* @see {@link formatJson}
* @see {@link Formatter}
* @stability stable
* @category formatting
* @since 2.0.0
*/
function format$1(input, options) {
const space = options?.space ?? 0;
const ancestors = /* @__PURE__ */ new WeakSet();
const gap = !space ? "" : typeof space === "number" ? " ".repeat(space) : space;
const ind = (d) => gap.repeat(d);
const wrap = (v, body) => {
const ctor = v?.constructor;
return ctor && ctor !== Object.prototype.constructor && ctor.name
? `${ctor.name}(${body})`
: body;
};
const ownKeys = (o) => {
try {
return Reflect.ownKeys(o);
} catch {
return ["[ownKeys threw]"];
}
};
function recur(v, d = 0) {
try {
return recurUnsafe(v, d);
} catch {
if ((typeof v === "object" && v !== null) || typeof v === "function") ancestors.delete(v);
return "[inspection threw]";
}
}
function recurUnsafe(v, d = 0) {
if (typeof v === "string") return JSON.stringify(v);
if (typeof v === "number" || v == null || typeof v === "boolean" || typeof v === "symbol")
return String(v);
if (typeof v === "bigint") return String(v) + "n";
if (typeof v === "object" || typeof v === "function") {
if (ancestors.has(v)) return CIRCULAR;
ancestors.add(v);
let output;
if (symbolRedactable in v) output = recur(getRedacted(v), d);
else if (Array.isArray(v))
output =
!gap || v.length <= 1
? `[${v.map((x) => recur(x, d)).join(",")}]`
: `[\n${ind(d + 1)}${v.map((x) => recur(x, d + 1)).join(",\n" + ind(d + 1))}\n${ind(d)}]`;
else if (v instanceof Date) output = formatDate(v);
else if (
!options?.ignoreToString &&
hasProperty(v, "toString") &&
typeof v["toString"] === "function" &&
v["toString"] !== Object.prototype.toString &&
v["toString"] !== Array.prototype.toString
) {
const s = safeToString(v);
output =
v instanceof Error && v.cause !== void 0 ? `${s} (cause: ${recur(v.cause, d)})` : s;
} else if (Symbol.iterator in v) output = `${v.constructor.name}(${recur(Array.from(v), d)})`;
else {
const keys = ownKeys(v);
if (!gap || keys.length <= 1) {
const body = `{${keys.map((k) => `${formatPropertyKey(k)}:${recur(safeGet(v, k), d)}`).join(",")}}`;
output = wrap(v, body);
} else {
const body = `{\n${keys.map((k) => `${ind(d + 1)}${formatPropertyKey(k)}: ${recur(safeGet(v, k), d + 1)}`).join(",\n")}\n${ind(d)}}`;
output = wrap(v, body);
}
}
ancestors.delete(v);
return output;
}
return String(v);
}
return recur(input, 0);
}
const CIRCULAR = "[Circular]";
/**
* @internal
*/
function formatPropertyKey(name) {
return typeof name === "string" ? JSON.stringify(name) : String(name);
}
/**
* Formats an array of property keys as a bracket-notation path string.
*
* @internal
*/
function formatPath(path) {
return path.map((key) => `[${formatPropertyKey(key)}]`).join("");
}
/**
* Formats a `Date` as an ISO 8601 string, returning `"Invalid Date"` for
* invalid dates instead of throwing.
*
* @internal
*/
function formatDate(date) {
try {
return date.toISOString();
} catch {
return "Invalid Date";
}
}
function safeToString(input) {
try {
const s = input.toString();
return typeof s === "string" ? s : String(s);
} catch {
return "[toString threw]";
}
}
function safeGet(input, key) {
try {
return input[key];
} catch {
return "[property access threw]";
}
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Inspectable.js
/**
* Controls how values appear in logs and debugging output.
*
* Effect data types use `Inspectable` to provide stable string, JSON, and
* Node.js inspection output. This keeps custom values readable in logs, REPLs,
* test failures, and diagnostics. This module defines the Node inspect symbol,
* the `Inspectable` interface, safe conversion helpers, and shared prototype or
* class implementations for custom values.
*
* @stability stable
* @since 2.0.0
*/
/**
* Defines the symbol used by Node.js for custom object inspection.
*
* **When to use**
*
* Use to implement Node.js custom inspection for a value.
*
* **Details**
*
* This symbol is recognized by Node.js's `util.inspect()` function and the REPL
* for custom object representation. When an object has a method with this symbol,
* it will be called to determine how the object should be displayed.
*
* **Example** (Defining custom Node inspection)
*
* ```ts import.meta.vitest
* import { Inspectable } from "effect"
*
* class CustomObject {
* constructor(private value: string) {}
*
* [Inspectable.NodeInspectSymbol]() {
* return `CustomObject(${this.value})`
* }
* }
*
* const obj = new CustomObject("hello")
* obj[Inspectable.NodeInspectSymbol]() // => "CustomObject(hello)"
* ```
*
* @stability stable
* @category symbols
* @since 2.0.0
*/
const NodeInspectSymbol = /*#__PURE__*/ Symbol.for("nodejs.util.inspect.custom");
/**
* Converts a value to its structured inspection representation.
*
* **When to use**
*
* Use when you need the structured representation of an inspectable value
* without risking unhandled errors.
*
* **Details**
*
* This function applies redaction before extracting data from objects that
* implement `toJSON`, recursively processes arrays, and handles errors
* gracefully. Plain objects are returned unchanged, so the result is not
* guaranteed to be accepted by `JSON.stringify`; it may still contain values
* such as `BigInt`, functions, or circular references.
*
* @see {@link toStringUnknown} for converting unknown values to strings
*
* @stability stable
* @category converting
* @since 4.0.0
*/
const toJson = (input) => {
try {
input = redact$2(input);
if (hasProperty(input, "toJSON") && isFunction(input["toJSON"]) && input["toJSON"].length === 0)
return input.toJSON();
else if (Array.isArray(input)) return input.map(toJson);
return input;
} catch {
return "[toJSON threw]";
}
};
/**
* A base prototype object that implements the {@link Inspectable} interface.
*
* **When to use**
*
* Use as a prototype for plain objects that should share standard inspectable behavior.
*
* **Details**
*
* This object provides default implementations for the {@link Inspectable} methods.
* It can be used as a prototype for objects that want to be inspectable,
* or as a mixin to add inspection capabilities to existing objects.
*
* **Example** (Using the base inspectable prototype)
*
* ```ts import.meta.vitest
* import { Inspectable } from "effect"
*
* // Use as prototype
* const myObject = Object.create(Inspectable.BaseProto)
* myObject.name = "example"
* myObject.value = 42
*
* myObject.toString() // => "\"[toJSON threw]\""
*
* // Or extend in a constructor
* function MyClass(this: any, name: string) {
* this.name = name
* }
* MyClass.prototype = Object.create(Inspectable.BaseProto)
* MyClass.prototype.constructor = MyClass
* ```
*
* @stability stable
* @category prototypes
* @since 2.0.0
*/
const BaseProto = {
toJSON() {
return toJson(this);
},
[NodeInspectSymbol]() {
return this.toJSON();
},
toString() {
return format$1(this.toJSON());
},
};
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/stackTraceLimit.js
/**
* Check if `Error.stackTraceLimit` is writable.
* Returns `false` if the property is frozen, non-writable, or `Error` is non-extensible.
*
* @internal
*/
const isStackTraceLimitWritable = () => {
const desc = Object.getOwnPropertyDescriptor(Error, "stackTraceLimit");
if (desc === void 0) return Object.isExtensible(Error);
return Object.hasOwn(desc, "writable") ? desc.writable === true : desc.set !== void 0;
};
const canWriteStackTraceLimit = /*#__PURE__*/ isStackTraceLimitWritable();
/**
* Get the current `Error.stackTraceLimit` value.
* Returns `undefined` if the property doesn't exist.
*
* @internal
*/
const getStackTraceLimit = () => Error.stackTraceLimit;
/**
* Safely set `Error.stackTraceLimit` if possible, otherwise no-op.
*
* Accepts `undefined` so a value read via {@link getStackTraceLimit} can be
* restored faithfully.
*
* @internal
*/
const setStackTraceLimit = (value) => {
if (canWriteStackTraceLimit) Error.stackTraceLimit = value;
};
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Utils.js
/**
* Yields its wrapped value exactly once, then completes with the value sent
* back in.
*
* **When to use**
*
* Use to implement `[Symbol.iterator]()` on Effect-like types so they can be
* `yield*`-ed inside generator functions, such as `Effect.gen` and
* `Option.gen`.
*
* **Details**
*
* The first call to `next()` returns a fresh `{ value: self, done: false }`.
* Every subsequent call returns `{ value: a, done: true }` where `a` is the
* argument passed to `next()`. To keep `yield*` cheap, the completion result
* is the iterator itself rather than a new object, so only the iterator and
* the single yielded result are allocated per `yield*`.
*
* **Example** (Yielding a wrapped value in a generator)
*
* ```ts import.meta.vitest
* import { Utils } from "effect"
*
* const gen = new Utils.SingleShotGen<string, number>("hello")
*
* gen.next(0).value // => "hello"
*
* gen.next(42).value // => 42
* ```
*
* @see {@link Gen} for the type-level signature that relies on `SingleShotGen`
* @stability stable
* @category constructors
* @since 2.0.0
*/
var SingleShotGen = class {
constructor(self) {
this.value = self;
this.done = false;
}
/**
* Yields the stored value once, then completes with the value sent back in.
*
* **When to use**
*
* Use to advance a `SingleShotGen` through its single yield and completion
* step.
*
* @since 2.0.0
*/
next(a) {
if (this.done) {
this.value = a;
return this;
}
this.done = true;
return {
value: this.value,
done: false,
};
}
};
const pickInternalCall = () => {
const InternalTypeId = "~effect/Utils/internal";
const standard = {
[InternalTypeId]: (body) => {
return body();
},
};
const forced = {
[InternalTypeId]: (body) => {
try {
return body();
} finally {
}
},
};
const limit = getStackTraceLimit();
if (limit === 0) return forced[InternalTypeId];
setStackTraceLimit(2);
const error = standard[InternalTypeId](() => /* @__PURE__ */ new Error());
setStackTraceLimit(limit);
return error.stack?.includes(InternalTypeId) === true
? standard[InternalTypeId]
: forced[InternalTypeId];
};
/** @internal */
const internalCall = /*#__PURE__*/ pickInternalCall();
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/core.js
/** @internal */
const EffectTypeId = `~effect/Effect`;
/** @internal */
const ExitTypeId = `~effect/Exit`;
const effectVariance = {
_A: identity,
_E: identity,
_R: identity,
};
/** @internal */
const identifier = `${EffectTypeId}/identifier`;
/** @internal */
const args = `${EffectTypeId}/args`;
/** @internal */
const evaluate = `${EffectTypeId}/evaluate`;
/** @internal */
const contA = `${EffectTypeId}/successCont`;
/** @internal */
const contE = `${EffectTypeId}/failureCont`;
/** @internal */
const contAll = `${EffectTypeId}/ensureCont`;
/** @internal */
const Yield = /*#__PURE__*/ Symbol.for("effect/Effect/Yield");
/** @internal */
const PipeInspectableProto = {
pipe() {
return pipeArguments(this, arguments);
},
toJSON() {
return { ...this };
},
toString() {
return format$1(this.toJSON(), {
ignoreToString: true,
space: 2,
});
},
[NodeInspectSymbol]() {
return this.toJSON();
},
};
/** @internal */
const EffectProto = {
[EffectTypeId]: effectVariance,
...PipeInspectableProto,
[Symbol.iterator]() {
return new SingleShotGen(this);
},
toJSON() {
return {
_id: "Effect",
op: this[identifier],
...("~effect/Effect/args" in this ? { args: this[args] } : void 0),
};
},
};
/** @internal */
const isExit = (u) => hasProperty(u, ExitTypeId);
/** @internal */
const CauseTypeId = "~effect/Cause";
/** @internal */
const CauseReasonTypeId = "~effect/Cause/Reason";
/** @internal */
const isCause = (self) => hasProperty(self, CauseTypeId);
/** @internal */
var CauseImpl = class {
constructor(failures) {
this[CauseTypeId] = CauseTypeId;
this.reasons = failures;
}
pipe() {
return pipeArguments(this, arguments);
}
toJSON() {
return {
_id: "Cause",
failures: this.reasons.map((f) => f.toJSON()),
};
}
toString() {
return `Cause(${format$1(this.reasons)})`;
}
[NodeInspectSymbol]() {
return this.toJSON();
}
[symbol](that) {
return (
isCause(that) &&
this.reasons.length === that.reasons.length &&
this.reasons.every((e, i) => equals$1(e, that.reasons[i]))
);
}
[symbol$1]() {
return array(this.reasons);
}
};
const annotationsMap = /*#__PURE__*/ new WeakMap();
/** @internal */
var ReasonBase = class {
[CauseReasonTypeId];
annotations;
_tag;
constructor(_tag, annotations, originalError) {
this[CauseReasonTypeId] = CauseReasonTypeId;
this._tag = _tag;
if (
annotations !== constEmptyAnnotations &&
typeof originalError === "object" &&
originalError !== null &&
annotations.size > 0
) {
const prevAnnotations = annotationsMap.get(originalError);
if (prevAnnotations) annotations = new Map([...prevAnnotations, ...annotations]);
annotationsMap.set(originalError, annotations);
}
this.annotations = annotations;
}
annotate(annotations, options) {
if (annotations.mapUnsafe.size === 0) return this;
const newAnnotations = new Map(this.annotations);
annotations.mapUnsafe.forEach((value, key) => {
if (options?.overwrite !== true && newAnnotations.has(key)) return;
newAnnotations.set(key, value);
});
const self = Object.assign(Object.create(Object.getPrototypeOf(this)), this);
self.annotations = newAnnotations;
return self;
}
pipe() {
return pipeArguments(this, arguments);
}
toString() {
return format$1(this);
}
[NodeInspectSymbol]() {
return this.toString();
}
};
/** @internal */
const constEmptyAnnotations = /*#__PURE__*/ new Map();
/** @internal */
var Fail = class extends ReasonBase {
constructor(error, annotations = constEmptyAnnotations) {
super("Fail", annotations, error);
this.error = error;
}
toString() {
return `Fail(${format$1(this.error)})`;
}
toJSON() {
return {
_tag: "Fail",
error: this.error,
};
}
[symbol](that) {
return (
isFailReason$1(that) &&
equals$1(this.error, that.error) &&
equals$1(this.annotations, that.annotations)
);
}
[symbol$1]() {
return combine(string$1(this._tag))(combine(hash(this.error))(hash(this.annotations)));
}
};
/** @internal */
const causeFromReasons = (reasons) => new CauseImpl(reasons);
const dedupeReasons = (self, that) => {
const buckets = /* @__PURE__ */ new Map();
const out = [];
for (const reason of self.concat(that)) {
const hash$2 = hash(reason);
const bucket = buckets.get(hash$2);
if (bucket === void 0) buckets.set(hash$2, [reason]);
else if (bucket.some((previous) => equals$1(previous, reason))) continue;
else bucket.push(reason);
out.push(reason);
}
return out;
};
/** @internal */
const causeCombine = /*#__PURE__*/ dual(2, (self, that) => {
if (self.reasons.length === 0) return that;
else if (that.reasons.length === 0) return self;
const newCause = new CauseImpl(dedupeReasons(self.reasons, that.reasons));
return equals$1(self, newCause) ? self : newCause;
});
/**
* Appends the interrupts from `interrupts` that `self` does not contain yet.
* Unlike `causeCombine`, it never calls hash or equality methods, which can be
* user-defined, random, or throwing.
*
* @internal
*/
const causeAddInterrupts = (self, interrupts) => {
const reasons = self.reasons.slice();
for (const reason of interrupts.reasons)
if (
isInterruptReason(reason) &&
!reasons.some(
(r) =>
isInterruptReason(r) &&
r.fiberId === reason.fiberId &&
r.annotations === reason.annotations,
)
)
reasons.push(reason);
return reasons.length === self.reasons.length ? self : new CauseImpl(reasons);
};
/** @internal */
const causeFail = (error) => new CauseImpl([new Fail(error)]);
/** @internal */
var Die = class extends ReasonBase {
constructor(defect, annotations = constEmptyAnnotations) {
super("Die", annotations, defect);
this.defect = defect;
}
toString() {
return `Die(${format$1(this.defect)})`;
}
toJSON() {
return {
_tag: "Die",
defect: this.defect,
};
}
[symbol](that) {
return (
isDieReason(that) &&
equals$1(this.defect, that.defect) &&
equals$1(this.annotations, that.annotations)
);
}
[symbol$1]() {
return combine(string$1(this._tag))(combine(hash(this.defect))(hash(this.annotations)));
}
};
/** @internal */
const causeDie = (defect) => new CauseImpl([new Die(defect)]);
/** @internal */
const causeAnnotate = /*#__PURE__*/ dual(
(args) => isCause(args[0]),
(self, annotations, options) => {
if (annotations.mapUnsafe.size === 0) return self;
return new CauseImpl(self.reasons.map((f) => f.annotate(annotations, options)));
},
);
/** @internal */
const isFailReason$1 = (self) => self._tag === "Fail";
/** @internal */
const isDieReason = (self) => self._tag === "Die";
/** @internal */
const isInterruptReason = (self) => self._tag === "Interrupt";
function defaultEvaluate(_fiber) {
return exitDie(`Effect.evaluate: Not implemented`);
}
/** @internal */
const makePrimitiveProto = (options) => ({
...EffectProto,
[identifier]: options.op,
[evaluate]: options["~effect/Effect/evaluate"] ?? defaultEvaluate,
[contA]: options[contA],
[contE]: options[contE],
[contAll]: options[contAll],
});
/** @internal */
const makePrimitive = (options) => {
const Proto = makePrimitiveProto(options);
const PrimitiveImpl = function (value) {
this[args] = value;
};
PrimitiveImpl.prototype = Proto;
return function (value) {
return new PrimitiveImpl(value);
};
};
/** @internal */
const makeExit = (options) => {
const Proto = {
[ExitTypeId]: ExitTypeId,
_tag: options.op,
get [options.prop]() {
return this[args];
},
...makePrimitiveProto(options),
toString() {
return `${options.op}(${format$1(this[args])})`;
},
toJSON() {
return {
_id: "Exit",
_tag: options.op,
[options.prop]: this[args],
};
},
[symbol](that) {
return (
isExit(that) &&
that._tag === this._tag &&
equals$1(this["~effect/Effect/args"], that["~effect/Effect/args"])
);
},
[symbol$1]() {
return combine(string$1(options.op), hash(this[args]));
},
};
const ExitPrimitive = function (value) {
this[args] = value;
};
ExitPrimitive.prototype = Proto;
return function (value) {
return new ExitPrimitive(value);
};
};
/** @internal */
const exitSucceed = /*#__PURE__*/ makeExit({
op: "Success",
prop: "value",
[evaluate](fiber) {
const cont = fiber.getCont(contA);
return cont ? cont[contA](this[args], fiber, this) : fiber.yieldWith(this);
},
});
/** @internal */
const StackTraceKey = { key: "effect/Cause/StackTrace" };
/** @internal */
const InterruptorStackTrace = { key: "effect/Cause/InterruptorStackTrace" };
/** @internal */
const exitFailCause = /*#__PURE__*/ makeExit({
op: "Failure",
prop: "cause",
[evaluate](fiber) {
let cause = this[args];
let annotated = false;
if (fiber.cache.stackFrame) {
cause = causeAnnotate(cause, {
mapUnsafe: /* @__PURE__ */ new Map([[StackTraceKey.key, fiber.cache.stackFrame]]),
});
annotated = true;
}
let cont = fiber.getCont(contE);
const interruptedCause = fiber._interruptedCause;
if (interruptedCause && fiber.interruptible) {
let skippedHandler = false;
while (cont && fiber.interruptible) {
skippedHandler ||= identifier in cont;
cont = fiber.getCont(contE);
}
if (skippedHandler)
cause = causeFromReasons(cause.reasons.filter((reason) => reason._tag !== "Fail"));
cause = causeAddInterrupts(cause, interruptedCause);
annotated = true;
}
return cont
? cont[contE](cause, fiber, annotated ? void 0 : this)
: fiber.yieldWith(annotated ? exitFailCause(cause) : this);
},
});
/** @internal */
const exitFail = (e) => exitFailCause(causeFail(e));
/** @internal */
const exitDie = (defect) => exitFailCause(causeDie(defect));
/** @internal */
const withFiber = /*#__PURE__*/ makePrimitive({
op: "WithFiber",
[evaluate](fiber) {
return this[args](fiber);
},
});
/** @internal */
const YieldableError = /*#__PURE__*/ (function () {
class YieldableError extends globalThis.Error {}
const proto = /*#__PURE__*/ makePrimitiveProto({
op: "YieldableError",
[evaluate]() {
return exitFail(this);
},
});
delete proto.toString;
Object.assign(YieldableError.prototype, proto);
return YieldableError;
})();
/** @internal */
const Error$2 = /*#__PURE__*/ (function () {
const plainArgsSymbol = /*#__PURE__*/ Symbol.for("effect/Data/Error/plainArgs");
return class Base extends YieldableError {
constructor(args) {
super(args?.message, args?.cause ? { cause: args.cause } : void 0);
if (args) {
assignProperties(this, args);
Object.defineProperty(this, plainArgsSymbol, {
value: args,
enumerable: false,
});
}
}
toJSON() {
return {
...this[plainArgsSymbol],
...this,
};
}
};
})();
/** @internal */
const TaggedError$1 = (tag) => {
class Base extends Error$2 {
_tag = tag;
}
Base.prototype.name = tag;
return Base;
};
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/option.js
/**
* @since 2.0.0
*/
const TypeId$15 = "~effect/Option";
const CommonProto$1 = {
[TypeId$15]: { _A: (_) => _ },
...PipeInspectableProto,
[Symbol.iterator]() {
return new SingleShotGen(this);
},
};
const SomeProto = /*#__PURE__*/ Object.defineProperty(
/*#__PURE__*/ Object.assign(/*#__PURE__*/ Object.create(CommonProto$1), {
_tag: "Some",
_op: "Some",
[symbol](that) {
return isOption(that) && isSome$1(that) && equals$1(this.value, that.value);
},
[symbol$1]() {
return combine(hash(this._tag))(hash(this.value));
},
toString() {
return `some(${format$1(this.value)})`;
},
toJSON() {
return {
_id: "Option",
_tag: this._tag,
value: toJson(this.value),
};
},
}),
"valueOrUndefined",
{
get() {
return this.value;
},
},
);
const NoneHash = /*#__PURE__*/ hash("None");
const NoneProto = /*#__PURE__*/ Object.assign(/*#__PURE__*/ Object.create(CommonProto$1), {
_tag: "None",
_op: "None",
valueOrUndefined: void 0,
[symbol](that) {
return isOption(that) && isNone$1(that);
},
[symbol$1]() {
return NoneHash;
},
toString() {
return `none()`;
},
toJSON() {
return {
_id: "Option",
_tag: this._tag,
};
},
});
/** @internal */
const isOption = (input) => hasProperty(input, TypeId$15);
/** @internal */
const isNone$1 = (fa) => fa._tag === "None";
/** @internal */
const isSome$1 = (fa) => fa._tag === "Some";
/** @internal */
const none$1 = /*#__PURE__*/ Object.create(NoneProto);
/** @internal */
const SomeImpl = function (value) {
this.value = value;
};
SomeImpl.prototype = SomeProto;
/** @internal */
const some$1 = (value) => new SomeImpl(value);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/result.js
const TypeId$14 = "~effect/Result";
const CommonProto = {
[TypeId$14]: {
/* v8 ignore next 2 */
_A: (_) => _,
_E: (_) => _,
},
...PipeInspectableProto,
[Symbol.iterator]() {
return new SingleShotGen(this);
},
};
const SuccessProto = /*#__PURE__*/ Object.assign(/*#__PURE__*/ Object.create(CommonProto), {
_tag: "Success",
_op: "Success",
[symbol](that) {
return isResult(that) && isSuccess$2(that) && equals$1(this.success, that.success);
},
[symbol$1]() {
return combine(hash(this._tag))(hash(this.success));
},
toString() {
return `success(${format$1(this.success)})`;
},
toJSON() {
return {
_id: "Result",
_tag: this._tag,
value: toJson(this.success),
};
},
});
const FailureProto = /*#__PURE__*/ Object.assign(/*#__PURE__*/ Object.create(CommonProto), {
_tag: "Failure",
_op: "Failure",
[symbol](that) {
return isResult(that) && isFailure$1(that) && equals$1(this.failure, that.failure);
},
[symbol$1]() {
return combine(hash(this._tag))(hash(this.failure));
},
toString() {
return `failure(${format$1(this.failure)})`;
},
toJSON() {
return {
_id: "Result",
_tag: this._tag,
failure: toJson(this.failure),
};
},
});
/** @internal */
const isResult = (input) => hasProperty(input, TypeId$14);
/** @internal */
const isFailure$1 = (result) => result._tag === "Failure";
/** @internal */
const isSuccess$2 = (result) => result._tag === "Success";
/** @internal */
const FailureImpl = function (failure) {
this.failure = failure;
};
FailureImpl.prototype = FailureProto;
/** @internal */
const SuccessImpl = function (success) {
this.success = success;
};
SuccessImpl.prototype = SuccessProto;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Order.js
/**
* Defines comparison functions for ordered values.
*
* An `Order<A>` compares two `A` values and returns whether the first is less
* than, equal to, or greater than the second. Orders are used for sorting,
* choosing minimum or maximum values, checking ranges, and building ordered data
* structures. This module includes built-in orders, constructors for custom
* orders, tools for reversing and combining comparisons, tuple and struct
* helpers, comparison predicates, clamping, and reducer support.
*
* @stability stable
* @since 2.0.0
*/
/**
* Creates a new `Order` instance from a comparison function.
*
* **When to use**
*
* Use when you need a sorting rule not covered by the built-in orders or input
* mapping helpers, and you can provide a total comparison.
*
* **Details**
*
* Uses reference equality (`===`) as a shortcut: if `self === that`, it returns
* `0` without calling the comparison function. The comparison function should
* return `-1`, `0`, or `1`, and the returned order satisfies total ordering
* laws when the comparison function does.
*
* **Example** (Creating an Order)
*
* ```ts import.meta.vitest
* import { Order } from "effect"
*
* const byAge = Order.make<{ name: string; age: number }>((self, that) => {
* if (self.age < that.age) return -1
* if (self.age > that.age) return 1
* return 0
* })
*
* byAge({ name: "Alice", age: 30 }, { name: "Bob", age: 25 }) // => 1
* byAge({ name: "Alice", age: 25 }, { name: "Bob", age: 30 }) // => -1
* ```
*
* @see {@link mapInput} to transform an order by mapping the input type
* @see {@link combine} to combine multiple orders
* @stability stable
* @category constructors
* @since 2.0.0
*/
function make$10(compare) {
return (self, that) => (self === that ? 0 : compare(self, that));
}
/**
* Order instance for strings that compares them lexicographically using JavaScript's `<` operator.
*
* **When to use**
*
* Use when you need lexicographic string ordering.
*
* **Details**
*
* Uses lexicographic dictionary ordering. The empty string is less than any
* non-empty string, and comparisons are case-sensitive.
*
* **Example** (Ordering strings)
*
* ```ts import.meta.vitest
* import { Order } from "effect"
*
* Order.String("apple", "banana") // => -1
* Order.String("banana", "apple") // => 1
* Order.String("apple", "apple") // => 0
* ```
*
* @see {@link mapInput} to compare objects by a string property
* @see {@link Struct} to combine with other orders for struct comparison
* @stability stable
* @category instances
* @since 4.0.0
*/
const String$4 = /*#__PURE__*/ make$10((self, that) => (self < that ? -1 : 1));
/**
* Order instance for numbers that compares them numerically.
*
* **When to use**
*
* Use when you need numeric ordering for numbers.
*
* **Details**
*
* `0` is considered equal to `-0`. All `NaN` values are considered equal to
* each other, and any `NaN` is considered less than any non-`NaN` number. All
* other values use standard numeric comparison.
*
* **Example** (Ordering numbers)
*
* ```ts import.meta.vitest
* import { Order } from "effect"
*
* Order.Number(1, 1) // => 0
* Order.Number(1, 2) // => -1
* Order.Number(2, 1) // => 1
*
* Order.Number(0, -0) // => 0
* Order.Number(NaN, 1) // => -1
* ```
*
* @see {@link mapInput} to compare objects by a number property
* @see {@link BigInt} for bigint comparisons
* @stability stable
* @category instances
* @since 4.0.0
*/
const Number$4 = /*#__PURE__*/ make$10((self, that) => {
if (globalThis.Number.isNaN(self) && globalThis.Number.isNaN(that)) return 0;
if (globalThis.Number.isNaN(self)) return -1;
if (globalThis.Number.isNaN(that)) return 1;
return self < that ? -1 : 1;
});
/**
* Checks whether one value is less than or equal to another according to the given order.
*
* **When to use**
*
* Use when you need a boolean less-than-or-equal predicate using an `Order`.
*
* **Details**
*
* Returns `true` if the order returns `-1` or `0`, and returns `false` only if
* the order returns `1`.
*
* **Example** (Checking less-than-or-equal comparisons)
*
* ```ts import.meta.vitest
* import { Order } from "effect"
*
* const isLessThanOrEqualToNumber = Order.isLessThanOrEqualTo(Order.Number)
*
* isLessThanOrEqualToNumber(1, 2) // => true
* isLessThanOrEqualToNumber(1, 1) // => true
* isLessThanOrEqualToNumber(2, 1) // => false
* ```
*
* @see {@link isLessThan} for strict less than
* @see {@link isGreaterThan} for strict greater than
* @stability stable
* @category predicates
* @since 4.0.0
*/
const isLessThanOrEqualTo$1 = (O) => dual(2, (self, that) => O(self, that) !== 1);
/**
* Checks whether one value is greater than or equal to another according to the given order.
*
* **When to use**
*
* Use when you need a boolean greater-than-or-equal predicate using an
* `Order`.
*
* **Details**
*
* Returns `true` if the order returns `1` or `0`, and returns `false` only if
* the order returns `-1`.
*
* **Example** (Checking greater-than-or-equal comparisons)
*
* ```ts import.meta.vitest
* import { Order } from "effect"
*
* const isGreaterThanOrEqualToNumber = Order.isGreaterThanOrEqualTo(Order.Number)
*
* isGreaterThanOrEqualToNumber(2, 1) // => true
* isGreaterThanOrEqualToNumber(1, 1) // => true
* isGreaterThanOrEqualToNumber(1, 2) // => false
* ```
*
* @see {@link isGreaterThan} for strict greater than
* @see {@link isLessThanOrEqualTo} for less than or equal
* @stability stable
* @category predicates
* @since 4.0.0
*/
const isGreaterThanOrEqualTo$1 = (O) => dual(2, (self, that) => O(self, that) !== -1);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Option.js
/**
* Creates an `Option` representing the absence of a value.
*
* **When to use**
*
* Use to represent a missing or uninitialized value, such as returning "no
* result" from a function.
*
* **Details**
*
* - Returns `Option<never>`, which is a subtype of `Option<A>` for any `A`
* - Always returns the same singleton instance
*
* **Example** (Creating an empty Option)
*
* ```ts import.meta.vitest
* import { Option } from "effect"
*
* // ┌─── Option<never>
* // â–¼
* const noValue = Option.none() // => Option.none()
* ```
*
* @see {@link some} for the opposite operation.
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const none = () => none$1;
/**
* Wraps the given value into an `Option` to represent its presence.
*
* **When to use**
*
* Use to wrap a known present value as `Option`
* - Returning a successful result from a partial function
*
* **Details**
*
* - Always returns `Some<A>`
* - Does not filter `null` or `undefined`; use {@link fromNullishOr} for that
*
* **Example** (Wrapping a value)
*
* ```ts import.meta.vitest
* import { Option } from "effect"
*
* // ┌─── Option<number>
* // â–¼
* const value = Option.some(1) // => Option.some(1)
* ```
*
* @see {@link none} for the opposite operation.
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const some = some$1;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Array.js
/**
* Exposes the global array constructor.
*
* **When to use**
*
* Use to access native JavaScript array constructor methods such as `isArray`
* or `from` from the Effect module namespace.
*
* **Example** (Accessing the Array constructor)
*
* ```ts import.meta.vitest
* import { Array } from "effect"
*
* Array.Array === globalThis.Array // => true
* ```
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Array$1 = globalThis.Array;
/**
* Adds a single element to the end of an iterable, returning a `NonEmptyArray`.
*
* **When to use**
*
* Use when you need to guarantee a non-empty result after adding a required
* trailing value.
*
* **Example** (Appending an element)
*
* ```ts import.meta.vitest
* import { Array } from "effect"
*
* Array.append([1, 2, 3], 4) // => [1, 2, 3, 4]
* ```
*
* @see {@link prepend} — add to the front
* @see {@link appendAll} — append multiple elements
*
* @stability stable
* @category combining
* @since 2.0.0
*/
const append = /*#__PURE__*/ dual(2, (self, last) => [...self, last]);
Array$1.isArray;
/**
* Checks whether a mutable `Array` is non-empty, narrowing the type to
* `NonEmptyArray`.
*
* **When to use**
*
* Use when you need the narrowed value to remain a mutable `Array` after proving
* it has at least one element.
*
* **Example** (Checking for a non-empty array)
*
* ```ts import.meta.vitest
* import { Array } from "effect"
*
* Array.isArrayNonEmpty([]) // => false
* Array.isArrayNonEmpty([1, 2, 3]) // => true
* ```
*
* @see {@link isReadonlyArrayNonEmpty} — readonly variant
* @see {@link isArrayEmpty} — opposite check
*
* @stability stable
* @category guards
* @since 4.0.0
*/
const isArrayNonEmpty = isArrayNonEmpty$1;
/**
* Checks whether a `ReadonlyArray` is non-empty, narrowing the type to
* `NonEmptyReadonlyArray`.
*
* **When to use**
*
* Use when you need to prove a readonly array has at least one element without
* requiring mutable array methods afterward.
*
* **Example** (Checking for a non-empty readonly array)
*
* ```ts import.meta.vitest
* import { Array } from "effect"
*
* Array.isReadonlyArrayNonEmpty([]) // => false
* Array.isReadonlyArrayNonEmpty([1, 2, 3]) // => true
* ```
*
* @see {@link isArrayNonEmpty} — mutable variant
* @see {@link isReadonlyArrayEmpty} — opposite check
*
* @stability stable
* @category guards
* @since 4.0.0
*/
const isReadonlyArrayNonEmpty = isArrayNonEmpty$1;
/**
* Creates an empty array.
*
* **When to use**
*
* Use to create a typed empty array without allocating placeholder elements.
*
* **Example** (Creating an empty array)
*
* ```ts import.meta.vitest
* import { Array } from "effect"
*
* Array.empty<number>() // => []
* ```
*
* @see {@link of} — create a single-element array
* @see {@link make} — create from multiple values
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const empty$1 = () => [];
/**
* Transforms each element using a function, returning a new array.
*
* **When to use**
*
* Use to transform each element independently while preserving the array shape.
*
* **Details**
*
* The function receives `(element, index)`. The return type preserves
* `NonEmptyArray`.
*
* **Example** (Doubling values)
*
* ```ts import.meta.vitest
* import { Array } from "effect"
*
* Array.map([1, 2, 3], (x) => x * 2) // => [2, 4, 6]
* ```
*
* @see {@link flatMap} — map and flatten
*
* @stability stable
* @category mapping
* @since 2.0.0
*/
const map$2 = /*#__PURE__*/ dual(2, (self, f) => self.map(f));
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/BigDecimal.js
/**
* Decimal numbers and arithmetic for cases where JavaScript `number` rounding
* is not precise enough. A `BigDecimal` stores digits as a `bigint` plus a
* decimal scale, which lets the module parse, compare, add, subtract, multiply,
* divide, round, and format decimal values such as money, quantities, and
* measurements.
*
* @stability stable
* @since 2.0.0
*/
const TypeId$13 = "~effect/BigDecimal";
const BigDecimalProto = {
[TypeId$13]: TypeId$13,
[symbol$1]() {
const normalized = normalize(this);
return combine(string$1(String(normalized.value)), number$1(normalized.scale));
},
[symbol](that) {
return isBigDecimal(that) && compare(this, that) === 0;
},
toString() {
return `BigDecimal(${format(this)})`;
},
toJSON() {
return {
_id: "BigDecimal",
value: String(this.value),
scale: this.scale,
};
},
[NodeInspectSymbol]() {
return this.toJSON();
},
pipe() {
return pipeArguments(this, arguments);
},
};
/**
* Checks whether a given value is a `BigDecimal`.
*
* **When to use**
*
* Use to validate unknown input and narrow it to `BigDecimal`.
*
* **Example** (Checking BigDecimal values)
*
* ```ts import.meta.vitest
* import { BigDecimal } from "effect"
*
* const decimal = BigDecimal.fromNumber(123.45)
* BigDecimal.isBigDecimal(decimal) // => false
* BigDecimal.isBigDecimal(BigDecimal.fromStringUnsafe("123.45")) // => true
* BigDecimal.isBigDecimal(123.45) // => false
* BigDecimal.isBigDecimal("123.45") // => false
* ```
*
* @stability stable
* @category guards
* @since 2.0.0
*/
const isBigDecimal = (u) => hasProperty(u, TypeId$13);
/**
* Creates a `BigDecimal` from a `bigint` value and a safe integer scale.
*
* **When to use**
*
* Use to construct a decimal directly from its unscaled integer value and
* decimal scale.
*
* **Gotchas**
*
* Throws a `RangeError` if `scale` is not a safe integer.
*
* **Example** (Creating decimals from bigint and scale)
*
* ```ts import.meta.vitest
* import { BigDecimal } from "effect"
*
* // Create 123.45 (12345 with scale 2)
* const decimal = BigDecimal.make(12345n, 2)
* decimal // => BigDecimal.fromStringUnsafe("123.45")
*
* // Create 42 (42 with scale 0)
* const integer = BigDecimal.make(42n, 0)
* integer // => BigDecimal.fromBigInt(42n)
* ```
*
* @see {@link fromBigInt} for constructing an integer decimal from a `bigint`
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const make$9 = (value, scale) => {
if (!Number.isSafeInteger(scale))
throw new RangeError(`Scale must be a safe integer, got ${scale}`);
const o = Object.create(BigDecimalProto);
o.value = value;
o.scale = scale;
return o;
};
const makeNormalized = (value, scale) => {
const o = make$9(value, scale);
o.normalized = o;
return o;
};
const bigint0$1 = /*#__PURE__*/ BigInt(0);
const bigint1$1 = /*#__PURE__*/ BigInt(1);
const bigint10$1 = /*#__PURE__*/ BigInt(10);
const zero$1 = /*#__PURE__*/ makeNormalized(bigint0$1, 0);
/**
* Normalizes a given `BigDecimal` by removing trailing zeros.
*
* **When to use**
*
* Use to canonicalize decimals that have equivalent values but different
* internal scales.
*
* **Example** (Normalizing trailing zeros)
*
* ```ts import.meta.vitest
* import { BigDecimal } from "effect"
*
* const decimal = BigDecimal.normalize(BigDecimal.fromStringUnsafe("123.00000"))
* const decimalStorage = [decimal.value, decimal.scale] // => [123n, 0]
*
* const largeDecimal = BigDecimal.normalize(BigDecimal.fromStringUnsafe("12300000"))
* const largeDecimalStorage = [largeDecimal.value, largeDecimal.scale] // => [123n, -5]
* ```
*
* @see {@link format} for rendering normalized decimals as strings
*
* @stability stable
* @category scaling
* @since 2.0.0
*/
const normalize = (self) => {
if (self.normalized === void 0) {
if (self.value === bigint0$1) self.normalized = zero$1;
else {
const digits = `${self.value}`;
let end = digits.length;
while (digits[end - 1] === "0") end--;
self.normalized = makeNormalized(
BigInt(digits.slice(0, end)),
self.scale - (digits.length - end),
);
}
}
return self.normalized;
};
const MAX_COMPARISON_SCALE_ALIGNMENT = 100;
const comparisonPowersOfTen = [bigint1$1];
const compareBigInt = (self, that) => (self === that ? 0 : self < that ? -1 : 1);
const compareMagnitude = (self, that) => {
const selfDigits = `${self.value < bigint0$1 ? -self.value : self.value}`;
const thatDigits = `${that.value < bigint0$1 ? -that.value : that.value}`;
const exponentDifference =
BigInt(selfDigits.length - thatDigits.length) - BigInt(self.scale) + BigInt(that.scale);
if (exponentDifference !== bigint0$1) return exponentDifference < bigint0$1 ? -1 : 1;
const length = Math.max(selfDigits.length, thatDigits.length);
return String$4(selfDigits.padEnd(length, "0"), thatDigits.padEnd(length, "0"));
};
const compare = (self, that) => {
if (self.scale === that.scale) return compareBigInt(self.value, that.value);
const selfSign = sign(self);
const thatSign = sign(that);
if (selfSign !== thatSign) return selfSign < thatSign ? -1 : 1;
if (selfSign === 0) return 0;
const scaleDifference = self.scale - that.scale;
const absoluteScaleDifference = Math.abs(scaleDifference);
if (absoluteScaleDifference > MAX_COMPARISON_SCALE_ALIGNMENT)
return selfSign === -1 ? compareMagnitude(that, self) : compareMagnitude(self, that);
const powerOfTen = (comparisonPowersOfTen[absoluteScaleDifference] ??=
bigint10$1 ** BigInt(absoluteScaleDifference));
return scaleDifference > 0
? compareBigInt(self.value, that.value * powerOfTen)
: compareBigInt(self.value * powerOfTen, that.value);
};
/**
* Determines the sign of a given `BigDecimal`.
*
* **When to use**
*
* Use to classify a `BigDecimal` as negative, zero, or positive.
*
* **Example** (Reading decimal signs)
*
* ```ts import.meta.vitest
* import { BigDecimal } from "effect"
*
* BigDecimal.sign(BigDecimal.fromStringUnsafe("-5")) // => -1
* BigDecimal.sign(BigDecimal.fromStringUnsafe("0")) // => 0
* BigDecimal.sign(BigDecimal.fromStringUnsafe("5")) // => 1
* ```
*
* @stability stable
* @category math
* @since 2.0.0
*/
const sign = (n) => (n.value === bigint0$1 ? 0 : n.value < bigint0$1 ? -1 : 1);
/**
* Formats a `BigDecimal` as a string.
*
* **When to use**
*
* Use to render a `BigDecimal` as plain decimal text when possible.
*
* **Details**
*
* The value is normalized before formatting. Scientific notation is used when
* the absolute value of the normalized scale is at least `16`; otherwise plain
* decimal notation is used.
*
* **Example** (Formatting decimals)
*
* ```ts import.meta.vitest
* import { BigDecimal } from "effect"
*
* BigDecimal.format(BigDecimal.fromStringUnsafe("-5")) // => "-5"
* BigDecimal.format(BigDecimal.fromStringUnsafe("123.456")) // => "123.456"
* BigDecimal.format(BigDecimal.fromStringUnsafe("-0.00000123")) // => "-0.00000123"
* ```
*
* @see {@link toExponential} for always rendering scientific notation
*
* @stability stable
* @category converting
* @since 2.0.0
*/
const format = (n) => {
const normalized = normalize(n);
if (Math.abs(normalized.scale) >= 16) return toExponential(normalized);
const negative = normalized.value < bigint0$1;
const absolute = `${negative ? -normalized.value : normalized.value}`;
const digits =
normalized.scale > 0
? absolute.padStart(normalized.scale + 1, "0")
: absolute.padEnd(absolute.length - normalized.scale, "0");
const point = digits.length - normalized.scale;
const complete =
normalized.scale > 0 ? `${digits.slice(0, point)}.${digits.slice(point)}` : digits;
return negative ? `-${complete}` : complete;
};
/**
* Formats a given `BigDecimal` as a `string` in scientific notation.
*
* **When to use**
*
* Use to render a `BigDecimal` in scientific notation.
*
* **Example** (Formatting decimals exponentially)
*
* ```ts import.meta.vitest
* import { BigDecimal } from "effect"
*
* BigDecimal.toExponential(BigDecimal.make(123456n, -5)) // => "1.23456e+10"
* ```
*
* @see {@link format} for plain decimal formatting when possible
*
* @stability stable
* @category converting
* @since 3.11.0
*/
const toExponential = (n) => {
if (isZero(n)) return "0e+0";
const normalized = normalize(n);
const digits = `${normalized.value}`;
const point = normalized.value < bigint0$1 ? 2 : 1;
const head = digits.slice(0, point);
const tail = digits.slice(point);
const exp = tail.length - normalized.scale;
return `${head}${tail === "" ? "" : `.${tail}`}e${exp >= 0 ? "+" : ""}${exp}`;
};
/**
* Checks whether a given `BigDecimal` is `0`.
*
* **When to use**
*
* Use to test whether a `BigDecimal` is exactly zero.
*
* **Example** (Checking zero decimals)
*
* ```ts import.meta.vitest
* import { BigDecimal } from "effect"
*
* BigDecimal.isZero(BigDecimal.fromStringUnsafe("0")) // => true
* BigDecimal.isZero(BigDecimal.fromStringUnsafe("1")) // => false
* ```
*
* @stability stable
* @category predicates
* @since 2.0.0
*/
const isZero = (n) => n.value === bigint0$1;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Effectable.js
/**
* Create a low-level `Effect` prototype.
*
* **When to use**
*
* Use when you need to create a custom Effect-like value without extending a
* class, by providing a label and an evaluate function that receives the
* current fiber.
*
* **Details**
*
* When the effect is evaluated, it calls `evaluate` with the current fiber.
*
* @see {@link Class} for a class-based approach to defining custom Effect values
* @see {@link Mixin} for wrapping an existing class constructor
*
* @stability stable
* @category prototypes
* @since 4.0.0
*/
const Prototype = (options) =>
makePrimitiveProto({
op: options.label,
[evaluate]: options.evaluate,
});
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Context.js
/**
* Runtime type identifier attached to `Context` service keys and used by
* `isKey` to recognize them.
*
* @stability stable
* @category type IDs
* @since 4.0.0
*/
const ServiceTypeId = "~effect/Context/Service";
/**
* Creates a `Context` service key.
*
* **When to use**
*
* Use when you need to define a context service key for a dependency that must
* be provided by the surrounding context.
*
* **Details**
*
* Call `Context.Service("Key")` for a function-style key, or use the two-stage
* form `Context.Service<Self, Shape>()("Key")` for class-style service
* declarations. The returned key can be yielded as an Effect and passed to
* `Context.make`, `Context.add`, and the Context getter functions.
*
* **Gotchas**
*
* The string key is the runtime identity of the service. Reusing the same key
* string for unrelated services makes them occupy the same slot in a
* `Context`.
*
* **Example** (Creating service keys)
*
* ```ts import.meta.vitest
* import { Context } from "effect"
*
* // Create a simple service
* const Database = Context.Service<{
* query: (sql: string) => string
* }>("Database")
*
* // Create a service class
* class Config extends Context.Service<Config, {
* port: number
* }>()("Config") {}
*
* // Use the services to create contexts
* const db = Context.make(Database, {
* query: (sql) => `Result: ${sql}`
* })
* const config = Context.make(Config, { port: 8080 })
* Context.get(db, Database).query("SELECT 1") // => "Result: SELECT 1"
* Context.get(config, Config).port // => 8080
* ```
*
* @see {@link Reference} for service keys with default values
*
* @stability stable
* @category services
* @since 4.0.0
*/
const Service = function () {
function KeyClass() {}
const self = KeyClass;
Object.setPrototypeOf(self, ServiceProto);
const init = (key, options) => {
self.key = key;
if (options?.defaultValue) {
self[ReferenceTypeId] = ReferenceTypeId;
self.defaultValue = options.defaultValue;
}
if (options?.make) self.make = options.make;
if (options?.fiberCached) cacheKeys.add(key);
return self;
};
return arguments.length > 0 ? init(arguments[0], arguments[1]) : init;
};
const ServiceProto = {
[ServiceTypeId]: ServiceTypeId,
.../*#__PURE__*/ Prototype({
label: "Service",
evaluate(fiber) {
return exitSucceed(get(fiber.context, this));
},
}),
toJSON() {
return {
_id: "Service",
key: this.key,
};
},
of(self) {
return self;
},
context(self) {
return make$8(this, self);
},
use(f) {
return withFiber((fiber) => f(get(fiber.context, this)));
},
useSync(f) {
return withFiber((fiber) => exitSucceed(f(get(fiber.context, this))));
},
};
const cacheKeys = /*#__PURE__*/ new Set();
const ReferenceTypeId = "~effect/Context/Reference";
const TypeId$12 = "~effect/Context";
const MaxDepth = 8;
const FlattenAfterBaseHits = 8;
const makeImpl = (cacheRoot, base, overlay, depth) => {
const self = Object.create(Proto$5);
self.cacheRoot = cacheRoot ?? self;
self.base = base;
self.overlay = overlay;
self.depth = depth;
self._flat = void 0;
self.baseHits = 0;
return self;
};
const applyOverlays = (map, overlay) => {
if (!overlay) return;
applyOverlays(map, overlay.parent);
map.set(overlay.key, overlay.value);
};
const flatten = (self) => {
if (self._flat) return self._flat;
if (!self.overlay) return (self._flat = self.base);
const map = new Map(self.base);
applyOverlays(map, self.overlay);
return (self._flat = map);
};
const notFound = /*#__PURE__*/ Symbol();
const lookup = (self, key) => {
const impl = self;
for (let overlay = impl.overlay; overlay; overlay = overlay.parent)
if (overlay.key === key) return overlay.value;
const value = impl.base.get(key);
if (value === void 0 && !impl.base.has(key)) return notFound;
if (impl.overlay && ++impl.baseHits >= impl.base.size && impl.baseHits >= FlattenAfterBaseHits) {
impl.base = flatten(impl);
impl.overlay = void 0;
impl.depth = 0;
}
return value;
};
/**
* Creates a `Context` from an existing service map.
*
* **When to use**
*
* Use when constructing a low-level `Context` from a trusted map whose lifecycle
* you control.
*
* **Gotchas**
*
* The provided map is retained without copying and must not be mutated after
* construction. Prefer `empty`, `make`, `add`, or `merge` for normal Context
* construction.
*
* **Example** (Creating a context from a map)
*
* ```ts import.meta.vitest
* import { Context } from "effect"
*
* // Create a context from a Map (unsafe)
* const map = new Map([
* ["Logger", { log: (_msg: string) => {} }]
* ])
*
* const context = Context.makeUnsafe(map)
* context.mapUnsafe.size // => 1
* ```
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const makeUnsafe$2 = (mapUnsafe) => makeImpl(void 0, mapUnsafe, void 0, 0);
const Proto$5 = {
get mapUnsafe() {
return flatten(this);
},
...PipeInspectableProto,
[TypeId$12]: { _Services: (_) => _ },
toJSON() {
return {
_id: "Context",
services: Array.from(this.mapUnsafe).map(([key, value]) => ({
key,
value,
})),
};
},
[symbol](that) {
if (!isContext(that)) return false;
const self = this.mapUnsafe;
const other = that.mapUnsafe;
if (self.size !== other.size) return false;
for (const [key, value] of self)
if (!other.has(key) || !equals$1(value, other.get(key))) return false;
return true;
},
[symbol$1]() {
return number$1(this.mapUnsafe.size);
},
};
/** @internal */
const hasSameCache = (self, that) => self.cacheRoot === that.cacheRoot;
/**
* Checks whether the provided argument is a `Context`.
*
* **When to use**
*
* Use to narrow an unknown value before passing it to APIs that require a
* `Context`.
*
* **Details**
*
* This checks the runtime `Context` marker and does not inspect which services
* the context contains.
*
* **Gotchas**
*
* This guard only proves that the value is a `Context`; it does not prove that
* any specific service is present.
*
* **Example** (Checking for contexts)
*
* ```ts import.meta.vitest
* import { Context } from "effect"
* Context.isContext(Context.empty()) // => true
* ```
*
* @see {@link isKey} for checking service keys
* @see {@link isReference} for checking references with defaults
*
* @stability stable
* @category guards
* @since 2.0.0
*/
const isContext = (u) => hasProperty(u, TypeId$12);
/**
* Checks whether the provided argument is a `Reference`.
*
* **Example** (Checking for references)
*
* ```ts import.meta.vitest
* import { Context } from "effect"
*
* const LoggerRef = Context.Reference("Logger", {
* defaultValue: () => ({ log: (_msg: string) => {} })
* })
*
* Context.isReference(LoggerRef) // => true
* Context.isReference(Context.Service("Key")) // => false
* ```
*
* @stability stable
* @category guards
* @since 3.11.0
*/
const isReference = (u) => !!u[ReferenceTypeId];
/**
* Returns an empty `Context`.
*
* **Example** (Creating an empty context)
*
* ```ts import.meta.vitest
* import { Context } from "effect"
* Context.empty().mapUnsafe.size // => 0
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const empty = () => emptyContext;
const emptyContext = /*#__PURE__*/ makeUnsafe$2(/*#__PURE__*/ new Map());
/**
* Creates a new `Context` with a single service associated to the key.
*
* **Example** (Creating a context with one service)
*
* ```ts import.meta.vitest
* import { Context } from "effect"
*
* const Port = Context.Service<{ PORT: number }>("Port")
*
* const context = Context.make(Port, { PORT: 8080 })
*
* Context.get(context, Port).PORT // => 8080
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const make$8 = (key, service) => makeUnsafe$2(/* @__PURE__ */ new Map([[key.key, service]]));
/**
* Adds a service to a given `Context`.
*
* **When to use**
*
* Use when you need to store a known service value in a `Context`.
*
* **Details**
*
* If the context already contains the same service key, the new service
* replaces the previous one.
*
* **Example** (Adding a service to a context)
*
* ```ts import.meta.vitest
* import { Context, pipe } from "effect"
*
* const Port = Context.Service<{ PORT: number }>("Port")
* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout")
*
* const someContext = Context.make(Port, { PORT: 8080 })
*
* const context = pipe(
* someContext,
* Context.add(Timeout, { TIMEOUT: 5000 })
* )
*
* const values = [Context.get(context, Port).PORT, Context.get(context, Timeout).TIMEOUT]
* values // => [8080, 5000]
* ```
*
* @see {@link addOrOmit} for adding or removing a service from an `Option`
*
* @stability stable
* @category combining
* @since 2.0.0
*/
const add = /*#__PURE__*/ dual(3, (self, key, service) => addUnsafe(self, key.key, service));
/**
* Adds a service by key to a given `Context` using a string key.
*
* @stability stable
* @category combining
* @since 4.0.0
*/
const addUnsafe = (self, key, service) => {
const impl = self;
const cacheRoot = cacheKeys.has(key) ? void 0 : impl.cacheRoot;
if (impl.depth >= MaxDepth) {
const map = new Map(impl._flat ?? impl.base);
if (!impl._flat) applyOverlays(map, impl.overlay);
map.set(key, service);
return makeImpl(cacheRoot, map, void 0, 0);
}
return makeImpl(
cacheRoot,
impl.base,
{
key,
value: service,
parent: impl.overlay,
},
impl.depth + 1,
);
};
/** @internal */
const getOrUndefinedUnsafe = (self, key) => {
const value = lookup(self, key);
return value === notFound ? void 0 : value;
};
/**
* Gets a service from the context that corresponds to the given key.
*
* **When to use**
*
* Use when you need type-checked access to a service already included in the
* context type.
*
* **Example** (Getting a service from a context)
*
* ```ts import.meta.vitest
* import { Context, pipe } from "effect"
*
* const Port = Context.Service<{ PORT: number }>("Port")
* const Timeout = Context.Service<{ TIMEOUT: number }>("Timeout")
*
* const context = pipe(
* Context.make(Port, { PORT: 8080 }),
* Context.add(Timeout, { TIMEOUT: 5000 })
* )
*
* Context.get(context, Timeout).TIMEOUT // => 5000
* ```
*
* @see {@link getOption} for optional service access
* @see {@link getOrElse} for fallback values
*
* @stability stable
* @category getters
* @since 2.0.0
*/
const get = /* @__PURE__ */ dual(2, (self, service) => {
const value = lookup(self, service.key);
if (value === notFound) {
if (isReference(service)) return getDefaultValue(service);
throw serviceNotFoundError(service);
}
return value;
});
const defaultValueCacheKey = "~effect/Context/defaultValue";
const getDefaultValue = (ref) => {
if (defaultValueCacheKey in ref) return ref[defaultValueCacheKey];
return (ref[defaultValueCacheKey] = ref.defaultValue());
};
const serviceNotFoundError = (service) => {
const error = /* @__PURE__ */ new Error(
`Service not found${service.key ? `: ${String(service.key)}` : ""}`,
);
if (error.stack) {
const lines = error.stack.split("\n");
lines.splice(1, 3);
error.stack = lines.join("\n");
}
return error;
};
/**
* Creates a context key with a default value.
*
* **When to use**
*
* Use when you need to define a context key with a lazily computed default
* value.
*
* **Details**
*
* `Context.Reference` allows you to create a key that can hold a value. You
* can provide a default value for the service, which will automatically be used
* when the context is accessed, or override it with a custom implementation
* when needed. The default value is computed lazily and cached on the
* reference.
*
* **Example** (Creating references with default values)
*
* ```ts import.meta.vitest
* import { Context } from "effect"
*
* // Create a reference with a default value
* const messages: Array<string> = []
* const LoggerRef = Context.Reference("Logger", {
* defaultValue: () => ({ log: (msg: string) => messages.push(`Default: ${msg}`) })
* })
*
* // The reference provides the default value when accessed from an empty context
* const context = Context.empty()
* const logger = Context.get(context, LoggerRef)
*
* // You can also override the default value
* const customContext = Context.make(LoggerRef, {
* log: (msg: string) => messages.push(`Custom: ${msg}`)
* })
* const customLogger = Context.get(customContext, LoggerRef)
* logger.log("default")
* customLogger.log("message")
* messages // => ["Default: default", "Custom: message"]
* ```
*
* @see {@link Service} for required services without default values
*
* @stability stable
* @category services
* @since 3.11.0
*/
const Reference = Service;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Duration.js
const TypeId$11 = "~effect/Duration";
const bigint0 = /*#__PURE__*/ BigInt(0);
const bigint1 = /*#__PURE__*/ BigInt(1);
const bigint2 = /*#__PURE__*/ BigInt(2);
const bigint10 = /*#__PURE__*/ BigInt(10);
const bigint1e3 = /*#__PURE__*/ BigInt(1e3);
const bigint1e6 = /*#__PURE__*/ BigInt(1e6);
const roundTiesAwayFromZero = (input) => BigInt(Math.sign(input) * Math.round(Math.abs(input)));
const roundMillisToNanos = (millis) =>
Number.isInteger(millis) ? BigInt(millis) * bigint1e6 : roundTiesAwayFromZero(millis * 1e6);
const fromNanosNumber = (nanos) =>
make$7(Number.isFinite(nanos) ? roundTiesAwayFromZero(nanos) : nanos);
const parseNanos = (input, scale) => {
const decimalIndex = input.indexOf(".");
if (decimalIndex === -1) return BigInt(input) * scale;
const isNegative = input[0] === "-";
const fractional = input.slice(decimalIndex + 1);
const fractionalScale = bigint10 ** BigInt(fractional.length);
const scaled =
(BigInt(input.slice(isNegative ? 1 : 0, decimalIndex)) * fractionalScale + BigInt(fractional)) *
scale;
return divideTiesAwayFromZero(isNegative ? -scaled : scaled, fractionalScale);
};
const divideTiesAwayFromZero = (numerator, denominator) => {
const absolute = numerator < bigint0 ? -numerator : numerator;
const rounded =
absolute / denominator +
((absolute % denominator) * bigint2 >= denominator ? bigint1 : bigint0);
return numerator < bigint0 ? -rounded : rounded;
};
const DURATION_REGEXP =
/^(-?\d+(?:\.\d+)?)\s+(nanos?|micros?|millis?|seconds?|minutes?|hours?|days?|weeks?)$/;
/**
* Decodes a `Duration.Input` into a `Duration`.
*
* **When to use**
*
* Use when the input has already been validated or comes from a trusted source
* and throwing is acceptable for invalid duration syntax.
*
* **Gotchas**
*
* If the input is not a valid `Duration.Input`, it throws an error.
*
* **Example** (Decoding duration inputs)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.fromInputUnsafe(1000) // => Duration.millis(1000)
* Duration.fromInputUnsafe("5 seconds") // => Duration.seconds(5)
* Duration.fromInputUnsafe("Infinity") // => Duration.infinity
* Duration.fromInputUnsafe([2, 500_000_000]) // => Duration.nanos(2_500_000_000n)
* ```
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const fromInputUnsafe = (input) => {
switch (typeof input) {
case "number":
return millis(input);
case "bigint":
return nanos(input);
case "string": {
if (input === "Infinity") return infinity;
if (input === "-Infinity") return negativeInfinity;
const match = DURATION_REGEXP.exec(input);
if (!match) break;
const [_, valueStr, unit] = match;
if (unit === "nano" || unit === "nanos") return nanos(parseNanos(valueStr, bigint1));
if (unit === "micro" || unit === "micros") return nanos(parseNanos(valueStr, bigint1e3));
const value = Number(valueStr);
switch (unit) {
case "milli":
case "millis":
return millis(value);
case "second":
case "seconds":
return seconds(value);
case "minute":
case "minutes":
return minutes(value);
case "hour":
case "hours":
return hours(value);
case "day":
case "days":
return days(value);
case "week":
case "weeks":
return weeks(value);
}
break;
}
case "object": {
if (input === null) break;
if (TypeId$11 in input) return input;
if (Array.isArray(input)) {
if (input.length !== 2 || !input.every(isNumber)) return invalid$1(input);
if (Number.isNaN(input[0]) || Number.isNaN(input[1])) return zero;
if (input[0] === -Infinity || input[1] === -Infinity) return negativeInfinity;
if (input[0] === Infinity || input[1] === Infinity) return infinity;
return fromNanosNumber(input[0] * 1e9 + input[1]);
}
const obj = input;
let millis = 0;
if (obj.weeks) millis += obj.weeks * 6048e5;
if (obj.days) millis += obj.days * 864e5;
if (obj.hours) millis += obj.hours * 36e5;
if (obj.minutes) millis += obj.minutes * 6e4;
if (obj.seconds) millis += obj.seconds * 1e3;
if (obj.milliseconds) millis += obj.milliseconds;
if (!obj.microseconds && !obj.nanoseconds) return make$7(millis);
return fromNanosNumber(millis * 1e6 + (obj.microseconds ?? 0) * 1e3 + (obj.nanoseconds ?? 0));
}
}
return invalid$1(input);
};
const invalid$1 = (input) => {
throw new Error(`Invalid Input: ${input}`);
};
const zeroDurationValue = {
_tag: "Millis",
millis: 0,
};
const infinityDurationValue = { _tag: "Infinity" };
const negativeInfinityDurationValue = { _tag: "NegativeInfinity" };
const DurationProto = {
[TypeId$11]: TypeId$11,
[symbol$1]() {
switch (this.value._tag) {
case "Millis":
return hash(roundMillisToNanos(this.value.millis));
case "Nanos":
return hash(this.value.nanos);
default:
return structure(this.value);
}
},
[symbol](that) {
return isDuration(that) && equals(this, that);
},
toString() {
switch (this.value._tag) {
case "Infinity":
return "Infinity";
case "NegativeInfinity":
return "-Infinity";
case "Nanos":
return `${this.value.nanos} nanos`;
case "Millis":
return `${this.value.millis} millis`;
}
},
toJSON() {
switch (this.value._tag) {
case "Millis":
return {
_id: "Duration",
_tag: "Millis",
millis: this.value.millis,
};
case "Nanos":
return {
_id: "Duration",
_tag: "Nanos",
nanos: String(this.value.nanos),
};
case "Infinity":
return {
_id: "Duration",
_tag: "Infinity",
};
case "NegativeInfinity":
return {
_id: "Duration",
_tag: "NegativeInfinity",
};
}
},
[NodeInspectSymbol]() {
return this.toJSON();
},
pipe() {
return pipeArguments(this, arguments);
},
};
const make$7 = (input) => {
const duration = Object.create(DurationProto);
if (typeof input === "number") {
if (isNaN(input) || input === 0 || Object.is(input, -0)) duration.value = zeroDurationValue;
else if (!Number.isFinite(input))
duration.value = input > 0 ? infinityDurationValue : negativeInfinityDurationValue;
else if (!Number.isInteger(input))
duration.value = {
_tag: "Nanos",
nanos: roundMillisToNanos(input),
};
else
duration.value = {
_tag: "Millis",
millis: input,
};
} else if (input === bigint0) duration.value = zeroDurationValue;
else
duration.value = {
_tag: "Nanos",
nanos: input,
};
return duration;
};
/**
* Checks whether a value is a Duration.
*
* **Example** (Checking for durations)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.isDuration(Duration.seconds(1)) // => true
* Duration.isDuration(1000) // => false
* ```
*
* @stability stable
* @category guards
* @since 2.0.0
*/
const isDuration = (u) => hasProperty(u, TypeId$11);
/**
* A Duration representing zero time.
*
* **Example** (Referencing the zero duration)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.zero) // => 0
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const zero = /*#__PURE__*/ make$7(0);
/**
* A Duration representing infinite time.
*
* **Example** (Referencing infinite duration)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.infinity) // => Infinity
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const infinity = /*#__PURE__*/ make$7(Infinity);
/**
* A Duration representing negative infinite time.
*
* **Example** (Referencing negative infinite duration)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.negativeInfinity) // => -Infinity
* ```
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const negativeInfinity = /*#__PURE__*/ make$7(-Infinity);
/**
* Creates a Duration from nanoseconds.
*
* **Example** (Creating durations from nanoseconds)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.nanos(500_000_000n) // => Duration.nanos(500_000_000n)
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const nanos = (nanos) => make$7(nanos);
/**
* Creates a Duration from milliseconds.
*
* **Example** (Creating durations from milliseconds)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.millis(1000)) // => 1000
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const millis = (millis) => make$7(millis);
/**
* Creates a Duration from seconds.
*
* **Example** (Creating durations from seconds)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.seconds(30)) // => 30_000
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const seconds = (seconds) => make$7(seconds * 1e3);
/**
* Creates a Duration from minutes.
*
* **Example** (Creating durations from minutes)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.minutes(5)) // => 300_000
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const minutes = (minutes) => make$7(minutes * 6e4);
/**
* Creates a Duration from hours.
*
* **Example** (Creating durations from hours)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.hours(2)) // => 7_200_000
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const hours = (hours) => make$7(hours * 36e5);
/**
* Creates a Duration from days.
*
* **Example** (Creating durations from days)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.days(1)) // => 86_400_000
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const days = (days) => make$7(days * 864e5);
/**
* Creates a Duration from weeks.
*
* **Example** (Creating durations from weeks)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toMillis(Duration.weeks(1)) // => 604_800_000
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const weeks = (weeks) => make$7(weeks * 6048e5);
/**
* Gets the duration in nanoseconds as a bigint.
*
* **When to use**
*
* Use when the duration is known to be finite and you need the nanosecond value
* as a `bigint`.
*
* **Details**
*
* Millisecond-backed fractional durations are rounded to the nearest
* nanosecond, with ties away from zero.
*
* **Gotchas**
*
* If the duration is infinite, it throws an error.
*
* **Example** (Reading nanoseconds unsafely)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.toNanosUnsafe(Duration.seconds(2)) // => 2_000_000_000n
*
* // Duration.toNanosUnsafe(Duration.infinity)
* // throws Error: "Cannot convert infinite duration to nanos"
* ```
*
* @stability stable
* @category getters
* @since 4.0.0
*/
const toNanosUnsafe = (input) => {
const self = fromInputUnsafe(input);
switch (self.value._tag) {
case "Infinity":
case "NegativeInfinity":
throw new Error("Cannot convert infinite duration to nanos");
case "Nanos":
return self.value.nanos;
case "Millis":
return roundMillisToNanos(self.value.millis);
}
};
/**
* Pattern matches on two `Duration`s, providing handlers that receive both values.
*
* **Example** (Pattern matching on duration pairs)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.matchPair(Duration.seconds(3), Duration.seconds(2), {
* onMillis: (a, b) => a + b,
* onNanos: (a, b) => Number(a + b),
* onInfinity: () => Infinity
* }) // => 5000
* ```
*
* @stability stable
* @category pattern matching
* @since 4.0.0
*/
const matchPair = /*#__PURE__*/ dual(3, (self, that, options) => {
if (
self.value._tag === "Infinity" ||
self.value._tag === "NegativeInfinity" ||
that.value._tag === "Infinity" ||
that.value._tag === "NegativeInfinity"
)
return options.onInfinity(self, that);
if (self.value._tag === "Millis")
return that.value._tag === "Millis"
? options.onMillis(self.value.millis, that.value.millis)
: options.onNanos(toNanosUnsafe(self), that.value.nanos);
else return options.onNanos(self.value.nanos, toNanosUnsafe(that));
});
/**
* Provides an `Equivalence` instance for comparing `Duration` values.
*
* **Example** (Comparing durations for equivalence)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.Equivalence(Duration.seconds(5), Duration.millis(5000)) // => true
* ```
*
* @stability stable
* @category instances
* @since 2.0.0
*/
const Equivalence$2 = (self, that) =>
matchPair(self, that, {
onMillis: (self, that) => self === that,
onNanos: (self, that) => self === that,
onInfinity: (self, that) => self.value._tag === that.value._tag,
});
/**
* Checks whether two Durations are equal.
*
* **Example** (Checking duration equality)
*
* ```ts import.meta.vitest
* import { Duration } from "effect"
*
* Duration.equals(Duration.seconds(5), Duration.millis(5000)) // => true
* ```
*
* @stability stable
* @category predicates
* @since 2.0.0
*/
const equals = /*#__PURE__*/ dual(2, (self, that) => Equivalence$2(self, that));
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Scheduler.js
/**
* Controls how runnable Effect fiber tasks are dispatched.
*
* A scheduler decides how tasks are queued, when queued tasks run, and when a
* fiber should pause so other work can continue. This module includes the
* scheduler service reference, the default `MixedScheduler`, dispatcher types
* for queued tasks, and references for tuning or disabling automatic scheduler
* yields.
*
* @stability stable
* @since 2.0.0
*/
/**
* Context reference for the scheduler used by the Effect runtime.
*
* **When to use**
*
* Use when you need to replace scheduling behavior globally in tests or runtime
* setup, such as forcing deterministic task dispatch.
*
* **Details**
*
* The default value creates a `MixedScheduler`. Provide this service to
* customize execution mode, task dispatching, or yield behavior.
*
* @stability stable
* @category services
* @since 2.0.0
*/
const Scheduler = /*#__PURE__*/ Reference("effect/Scheduler", {
fiberCached: true,
defaultValue: () => new MixedScheduler(),
});
const setMicrotask = (f) => {
let cancelled = false;
Promise.resolve().then(() => {
if (!cancelled) f();
});
return () => {
cancelled = true;
};
};
const setTimer =
"setImmediate" in globalThis
? (f) => {
const timer = globalThis.setImmediate(f);
return () => globalThis.clearImmediate(timer);
}
: (f) => {
const timer = setTimeout(f, 0);
return () => clearTimeout(timer);
};
const setImmediate = (f) => {
try {
return setTimer(f);
} catch {
return setMicrotask(f);
}
};
var PriorityBuckets = class {
buckets = [];
scheduleTask(task, priority) {
const buckets = this.buckets;
const len = buckets.length;
let bucket;
let index = 0;
for (; index < len; index++) {
if (buckets[index][0] > priority) break;
bucket = buckets[index];
}
if (bucket && bucket[0] === priority) bucket[1].push(task);
else if (index === len) buckets.push([priority, [task]]);
else buckets.splice(index, 0, [priority, [task]]);
}
drain() {
const buckets = this.buckets;
this.buckets = [];
return buckets;
}
};
/**
* Provides a scheduler implementation that batches queued tasks and dispatches them by
* priority.
*
* **When to use**
*
* Use when you need the default runtime scheduler directly, including a
* scheduler that batches queued work by priority and preserves FIFO order within
* each priority.
*
* **Details**
*
* `MixedScheduler` supports synchronous and asynchronous execution modes, uses
* operation counts to decide when fibers should yield, and is the default
* scheduler implementation.
*
* **Gotchas**
*
* On Cloudflare Workers, request-owned scheduler timers can be discarded,
* leaving shared fibers suspended. Use `new MixedScheduler("sync")` for the
* whole application; see `HttpRouter.toWebHandler` for a recipe.
* Sync mode does not yield to the event loop: CPU-heavy work delays other
* requests, and I/O-polling loops can exhaust the CPU limit. It does not fix
* request-owned timers (such as `Effect.sleep`) or request-bound async contexts.
*
* @stability stable
* @category models
* @since 2.0.0
*/
var MixedScheduler = class {
executionMode;
setImmediate;
constructor(executionMode = "async", setImmediateFn) {
this.executionMode = executionMode;
this.setImmediate = setImmediateFn ?? (executionMode === "sync" ? setMicrotask : setImmediate);
}
/**
* Returns whether the fiber has reached its operation budget and should yield.
*
* **When to use**
*
* Use to decide whether a fiber should yield after consuming its current
* operation budget.
*
* @since 2.0.0
*/
shouldYield(fiber) {
return fiber.currentOpCount >= fiber.cache.maxOpsBeforeYield;
}
/**
* Creates a dispatcher that schedules work through this scheduler.
*
* **When to use**
*
* Use when you need a standalone dispatcher from a scheduler instance, for
* example in tests that enqueue tasks and then flush them deterministically.
*
* @since 4.0.0
*/
makeDispatcher() {
return new MixedSchedulerDispatcher(this.setImmediate);
}
};
var MixedSchedulerDispatcher = class {
tasks = /*#__PURE__*/ new PriorityBuckets();
running = void 0;
setImmediate;
constructor(setImmediateFn = setImmediate) {
this.setImmediate = setImmediateFn;
}
/**
* @since 2.0.0
*/
scheduleTask(task, priority) {
this.tasks.scheduleTask(task, priority);
if (this.running === void 0) this.running = this.setImmediate(this.afterScheduled);
}
/**
* @since 2.0.0
*/
afterScheduled = () => {
this.running = void 0;
this.runTasks();
};
/**
* @since 2.0.0
*/
runTasks() {
const buckets = this.tasks.drain();
for (let i = 0; i < buckets.length; i++) {
const toRun = buckets[i][1];
for (let j = 0; j < toRun.length; j++) toRun[j]();
}
}
/**
* @since 2.0.0
*/
flush() {
while (this.tasks.buckets.length > 0) {
if (this.running !== void 0) {
this.running();
this.running = void 0;
}
this.runTasks();
}
}
};
/**
* Context reference that controls the maximum number of operations a fiber
* can perform before yielding control back to the scheduler.
*
* **When to use**
*
* Use to tune scheduler fairness for CPU-bound fibers by changing the scheduler
* operation budget that triggers a yield.
*
* **Details**
*
* The default value is `2048` operations, which balances performance and
* fairness by helping prevent long-running fibers from monopolizing the
* execution thread.
*
* @see {@link PreventSchedulerYield} for bypassing scheduler yield checks entirely rather than tuning the operation budget
*
* @stability stable
* @category services
* @since 4.0.0
*/
const MaxOpsBeforeYield = /*#__PURE__*/ Reference("effect/Scheduler/MaxOpsBeforeYield", {
fiberCached: true,
defaultValue: () => 2048,
});
/**
* Context reference that controls whether the runtime should bypass scheduler
* yield checks. When set to `true`, the fiber run loop won't call
* `Scheduler.shouldYield`.
*
* **When to use**
*
* Use to bypass scheduler yield checks for controlled runtime workloads where
* cooperative yielding should be disabled.
*
* **Gotchas**
*
* Setting this reference to `true` can let long-running fibers monopolize the
* JavaScript thread.
*
* @see {@link MaxOpsBeforeYield} for tuning yield frequency without disabling yield checks
* @see {@link Scheduler} for providing custom scheduler yield behavior
*
* @stability stable
* @category services
* @since 4.0.0
*/
const PreventSchedulerYield = /*#__PURE__*/ Reference("effect/Scheduler/PreventSchedulerYield", {
fiberCached: true,
defaultValue: () => false,
});
/**
* Creates a tagged error class with a `_tag` discriminator.
*
* **When to use**
*
* Use when you need domain errors with discriminated-union handling.
*
* **Details**
*
* Like {@link Error}, but instances also carry a `readonly _tag` property,
* enabling `Effect.catchTag` and `Effect.catchTags` for tag-based recovery.
* The `_tag` is excluded from the constructor argument. Yielding an instance
* inside `Effect.gen` fails the effect with this error.
*
* **Example** (Recovering by tag)
*
* ```ts import.meta.vitest
* import { Data, Effect } from "effect"
*
* class NotFound extends Data.TaggedError("NotFound")<{
* readonly resource: string
* }> {}
*
* class Forbidden extends Data.TaggedError("Forbidden")<{
* readonly reason: string
* }> {}
*
* const program = Effect.gen(function*() {
* return yield* new NotFound({ resource: "/users/42" })
* })
*
* const recovered = program.pipe(
* Effect.catchTag("NotFound", (e) =>
* Effect.succeed(`missing: ${e.resource}`))
* )
*
* await Effect.runPromise(recovered) // => "missing: /users/42"
* ```
*
* @see {@link Error} — without a `_tag`
* @see {@link TaggedClass} — tagged class that is not an error
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const TaggedError = TaggedError$1;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Tracer.js
/**
* Defines the string key for the parent-span context service.
*
* **When to use**
*
* Use when you need the raw context key for parent span lookup in lower-level
* tracing code.
*
* **Example** (Reading the parent span key)
*
* ```ts import.meta.vitest
* import { Tracer } from "effect"
*
* // The key used to identify parent spans in the context
* Tracer.ParentSpanKey // => "effect/Tracer/ParentSpan"
* ```
*
* @stability stable
* @category constants
* @since 4.0.0
*/
const ParentSpanKey = "effect/Tracer/ParentSpan";
/**
* Defines the string key for the active tracer context reference.
*
* **When to use**
*
* Use when you need the raw context key for active tracer lookup in lower-level
* tracing code.
*
* @stability stable
* @category constants
* @since 4.0.0
*/
const TracerKey = "effect/Tracer";
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/metric.js
/** @internal */
const FiberRuntimeMetricsKey = "effect/Metric/FiberRuntimeMetrics";
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/references.js
/** @internal */
const CurrentStackFrame = /*#__PURE__*/ Reference("effect/References/CurrentStackFrame", {
fiberCached: true,
defaultValue: constUndefined,
});
/** @internal */
const TracerEnabled = /*#__PURE__*/ Reference("effect/References/TracerEnabled", {
fiberCached: true,
defaultValue: constTrue,
});
/** @internal */
const CurrentLogLevel = /*#__PURE__*/ Reference("effect/References/CurrentLogLevel", {
fiberCached: true,
defaultValue: () => "Info",
});
/** @internal */
const MinimumLogLevel = /*#__PURE__*/ Reference("effect/References/MinimumLogLevel", {
fiberCached: true,
defaultValue: () => "Info",
});
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/effect.js
/** @internal */
var Interrupt = class extends ReasonBase {
constructor(fiberId, annotations = constEmptyAnnotations) {
super("Interrupt", annotations, "Interrupted");
this.fiberId = fiberId;
}
toString() {
return `Interrupt(${this.fiberId})`;
}
toJSON() {
return {
_tag: "Interrupt",
fiberId: this.fiberId,
};
}
[symbol](that) {
return (
isInterruptReason(that) &&
this.fiberId === that.fiberId &&
this.annotations === that.annotations
);
}
[symbol$1]() {
return string$1(`${this._tag}:${this.fiberId}`);
}
};
/** @internal */
const causeInterrupt = (fiberId) => new CauseImpl([new Interrupt(fiberId)]);
/** @internal */
const hasInterrupts = (self) => self.reasons.some(isInterruptReason);
/** @internal */
const causeMap = /*#__PURE__*/ dual(2, (self, f) => {
let hasFail = false;
const failures = self.reasons.map((failure) => {
if (isFailReason$1(failure)) {
hasFail = true;
return new Fail(f(failure.error), failure.annotations);
}
return failure;
});
return hasFail ? causeFromReasons(failures) : self;
});
/** @internal */
const FiberTypeId = "~effect/Fiber";
const fiberVariance = {
_A: identity,
_E: identity,
};
const fiberIdStore = { id: 0 };
const AsyncResource = /*#__PURE__*/ (() => {
try {
return globalThis.process?.getBuiltinModule?.("node:async_hooks")?.AsyncResource;
} catch {
return;
}
})();
const captureAsyncContext = () =>
AsyncResource === void 0 ? void 0 : new AsyncResource("effect/Fiber");
/** @internal */
const getCurrentFiber = () => globalThis[currentFiberTypeId];
/** @internal */
var FiberImpl = class {
constructor(context, interruptible = true) {
this.setContext(context);
this.id = ++fiberIdStore.id;
this.currentOpCount = 0;
this.interruptible = interruptible;
this._stack = [];
this._observers = void 0;
this._exit = void 0;
this._children = void 0;
this._interruptedCause = void 0;
this._yielded = void 0;
this._running = false;
this._deferredInterrupt = false;
this._parent = void 0;
this._asyncContext = void 0;
this.cache.runtimeMetrics?.recordFiberStart(this.context);
}
get [FiberTypeId]() {
return fiberVariance;
}
get currentDispatcher() {
return (this._dispatcher ??= this.cache.scheduler.makeDispatcher());
}
getRef(ref) {
return get(this.context, ref);
}
addObserver(cb) {
if (this._exit) {
cb(this._exit);
return constVoid;
}
if (this._observers === void 0) this._observers = [cb];
else this._observers.push(cb);
return () => this.removeObserver(cb);
}
removeObserver(cb) {
if (this._exit || this._observers === void 0) return;
const index = this._observers.indexOf(cb);
if (index >= 0) this._observers.splice(index, 1);
}
interruptUnsafe(fiberId, annotations) {
if (this._exit) return;
let cause = causeInterrupt(fiberId);
if (this.cache.stackFrame)
cause = causeAnnotate(cause, make$8(StackTraceKey, this.cache.stackFrame));
if (annotations) cause = causeAnnotate(cause, annotations);
this._interruptedCause = this._interruptedCause
? causeAddInterrupts(this._interruptedCause, cause)
: cause;
if (this.interruptible) {
if (this._running) this._deferredInterrupt = true;
else this.evaluate(failCause$1(this._interruptedCause));
}
}
pollUnsafe() {
return this._exit;
}
evaluate(effect) {
if (this._exit) return;
else if (this._asyncContext !== void 0) {
const asyncContext = this._asyncContext;
this._asyncContext = void 0;
return asyncContext.runInAsyncScope(this.evaluate, this, effect);
} else if (this._yielded !== void 0) {
const yielded = this._yielded;
this._yielded = void 0;
yielded();
}
const exit = this.runLoop(effect);
if (exit === Yield) {
this._asyncContext = captureAsyncContext();
return;
}
const interruptChildren =
fiberMiddleware.interruptChildren && fiberMiddleware.interruptChildren(this);
if (interruptChildren !== void 0)
return this.evaluate(flatMap$1(interruptChildren, () => exit));
this._exit = exit;
this.cache.runtimeMetrics?.recordFiberEnd(this.context, this._exit);
if (this._parent) {
this._parent._children?.delete(this);
this._parent = void 0;
}
if (this._observers !== void 0) {
const observers = this._observers;
this._observers = void 0;
for (let i = 0; i < observers.length; i++) observers[i](exit);
}
this._stack.length = 0;
this._children = void 0;
this.context = empty();
}
runLoop(effect) {
const prevFiber = globalThis[currentFiberTypeId];
globalThis[currentFiberTypeId] = this;
const prevRunning = this._running;
this._running = true;
let yielding = false;
let current = effect;
this.currentOpCount = 0;
try {
while (true)
try {
if (this._deferredInterrupt) {
this._deferredInterrupt = false;
current = failCause$1(this._interruptedCause);
}
this.currentOpCount++;
const cache = this.cache;
if (!yielding && !cache.preventYield && cache.scheduler.shouldYield(this)) {
yielding = true;
const prev = current;
current = flatMap$1(yieldNow, () => prev);
}
current = cache.tracerContext
? cache.tracerContext(current, this)
: current[evaluate](this);
if (current === Yield) {
const yielded = this._yielded;
if ("~effect/Exit" in yielded) {
this._deferredInterrupt = false;
this._yielded = void 0;
return yielded;
} else if (this._deferredInterrupt) {
this._yielded = void 0;
yielded();
continue;
}
return Yield;
}
} catch (error) {
if (!hasProperty(current, "~effect/Effect/evaluate"))
return exitDie(`Fiber.runLoop: Not a valid effect: ${String(current)}`);
current = exitDie(error);
}
} finally {
this._running = prevRunning;
globalThis[currentFiberTypeId] = prevFiber;
}
}
getCont(symbol) {
if (this._deferredInterrupt) {
this._deferredInterrupt = false;
return deferredInterruptCont;
}
while (true) {
const op = this._stack.pop();
if (!op) return void 0;
const all = op[contAll];
if (all !== void 0) {
const cont = all.call(op, this);
if (cont) {
cont[symbol] = cont;
return cont;
}
}
if (op[symbol]) return op;
}
}
succeedWith(value) {
if ((++this.currentOpCount & (maxInlineSteps - 1)) === 0) return exitSucceed(value);
const cont = this.getCont(contA);
return cont ? cont[contA](value, this) : this.yieldWith(exitSucceed(value));
}
yieldWith(value) {
this._yielded = value;
return Yield;
}
children() {
return (this._children ??= /* @__PURE__ */ new Set());
}
pipe() {
return pipeArguments(this, arguments);
}
setContext(context) {
const previous = this.context;
this.context = context;
if (previous !== void 0 && hasSameCache(previous, context)) return;
const root = context.cacheRoot;
const cache = (root._fiberCache ??= makeFiberContextCache(context));
if (this.cache?.scheduler !== cache.scheduler) this._dispatcher = void 0;
this.cache = cache;
}
get currentSpanLocal() {
const span = this.cache.span;
return span?._tag === "Span" ? span : void 0;
}
};
const makeFiberContextCache = (context) => {
const currentTracer = getOrUndefinedUnsafe(context, TracerKey);
return {
scheduler: get(context, Scheduler),
tracer: currentTracer,
tracerContext: currentTracer ? currentTracer["context"] : void 0,
tracerEnabled: get(context, TracerEnabled),
span: getOrUndefinedUnsafe(context, ParentSpanKey),
logLevel: get(context, CurrentLogLevel),
minimumLogLevel: get(context, MinimumLogLevel),
stackFrame: get(context, CurrentStackFrame),
runtimeMetrics: getOrUndefinedUnsafe(context, FiberRuntimeMetricsKey),
maxOpsBeforeYield: get(context, MaxOpsBeforeYield),
preventYield: get(context, PreventSchedulerYield),
};
};
const deferredInterruptCont = {
[contA](_value, fiber) {
return failCause$1(fiber._interruptedCause);
},
[contE](_cause, fiber) {
return failCause$1(fiber._interruptedCause);
},
};
const maxInlineSteps = 32;
const fiberMiddleware = { interruptChildren: void 0 };
const fiberStackAnnotations = (fiber) => {
if (!fiber.cache.stackFrame) return void 0;
const annotations = /* @__PURE__ */ new Map();
annotations.set(InterruptorStackTrace.key, fiber.cache.stackFrame);
return makeUnsafe$2(annotations);
};
/** @internal */
const fiberAwaitAll = (self) =>
callback((resume) => {
const iter = self[Symbol.iterator]();
const exits = [];
let cancel = void 0;
function loop() {
let result = iter.next();
while (!result.done) {
if (result.value._exit) {
exits.push(result.value._exit);
result = iter.next();
continue;
}
cancel = result.value.addObserver((exit) => {
exits.push(exit);
loop();
});
return;
}
resume(succeed$3(exits));
}
loop();
return sync(() => cancel?.());
});
/** @internal */
const fiberInterruptAll = (fibers) =>
withFiber((parent) => {
const annotations = fiberStackAnnotations(parent);
let fiberArr = empty$1();
for (const fiber of fibers) {
fiber.interruptUnsafe(parent.id, annotations);
fiberArr.push(fiber);
}
return asVoid(fiberAwaitAll(fiberArr));
});
/** @internal */
const succeed$3 = exitSucceed;
/** @internal */
const failCause$1 = exitFailCause;
/** @internal */
const fail$3 = exitFail;
/** @internal */
const sync = /*#__PURE__*/ makePrimitive({
op: "Sync",
[evaluate](fiber) {
const value = this[args]();
const cont = fiber.getCont(contA);
return cont ? cont[contA](value, fiber) : fiber.yieldWith(exitSucceed(value));
},
});
/** @internal */
const suspend$1 = /*#__PURE__*/ makePrimitive({
op: "Suspend",
[evaluate](_fiber) {
return this[args]();
},
});
/** @internal */
const yieldNow = /*#__PURE__*/ /* @__PURE__ */ makePrimitive({
op: "Yield",
[evaluate](fiber) {
let resumed = false;
fiber.currentDispatcher.scheduleTask(() => {
if (resumed) return;
fiber.evaluate(exitVoid);
}, this["~effect/Effect/args"] ?? 0);
return fiber.yieldWith(() => {
resumed = true;
});
},
})(0);
/** @internal */
const failCauseSync$1 = (evaluate) => suspend$1(() => failCause$1(evaluate()));
/** @internal */
const die$2 = (defect) => exitDie(defect);
/** @internal */
const void_$1 = /*#__PURE__*/ succeed$3(void 0);
const callbackOptions = /*#__PURE__*/ (function () {
const Proto = /*#__PURE__*/ makePrimitiveProto({
op: "Async",
[evaluate](fiber) {
let resumed = false;
let yielded = false;
const controller = this.withSignal ? new AbortController() : void 0;
const onCancel = this.register.call(
fiber.cache.scheduler,
(effect) => {
if (resumed) return;
resumed = true;
if (yielded) fiber.evaluate(effect);
else yielded = effect;
},
controller?.signal,
);
if (yielded !== false) return yielded;
yielded = true;
fiber._yielded = () => {
resumed = true;
};
if (controller === void 0 && onCancel === void 0) return Yield;
fiber._stack.push(
asyncFinalizer(() => {
resumed = true;
controller?.abort();
return onCancel ?? exitVoid;
}),
);
return Yield;
},
});
const AsyncImpl = function (register, withSignal) {
this.register = register;
this.withSignal = withSignal;
};
AsyncImpl.prototype = Proto;
return function (register, withSignal) {
return new AsyncImpl(register, withSignal);
};
})();
const asyncFinalizer = /*#__PURE__*/ makePrimitive({
op: "AsyncFinalizer",
[contAll](fiber) {
if (fiber.interruptible) {
fiber.interruptible = false;
fiber._stack.push(setInterruptibleTrue);
}
},
[contE](cause, _fiber) {
return hasInterrupts(cause)
? flatMap$1(combineFinalizerCause(exitFailCause(cause), this[args]()), () =>
failCause$1(cause),
)
: failCause$1(cause);
},
});
/** @internal */
const callback = (register) => callbackOptions(register, register.length >= 2);
const defineFunctionLength = (length, fn) =>
Object.defineProperty(fn, "length", {
value: length,
configurable: true,
});
/** @internal */
const fnUntracedEager$1 = (body, ...pipeables) =>
defineFunctionLength(
body.length,
pipeables.length === 0
? function () {
return fromIteratorEagerUnsafe(() => body.apply(this, arguments));
}
: function () {
let effect = fromIteratorEagerUnsafe(() => body.apply(this, arguments));
for (const pipeable of pipeables) effect = pipeable(effect, ...arguments);
return effect;
},
);
const fromIteratorEagerUnsafe = (evaluate) => {
try {
const iterator = evaluate();
let value = void 0;
while (true) {
const state = iterator.next(value);
if (state.done) return succeed$3(state.value);
const primitive = state.value;
if (primitive && primitive._tag === "Success") {
value = primitive.value;
continue;
} else if (primitive && primitive._tag === "Failure") return state.value;
else {
let isFirstExecution = true;
return suspend$1(() => {
if (isFirstExecution) {
isFirstExecution = false;
return flatMap$1(state.value, (value) => fromIteratorUnsafe(iterator, value));
} else return suspend$1(() => fromIteratorUnsafe(evaluate()));
});
}
}
} catch (error) {
return die$2(error);
}
};
const fromIteratorUnsafe = /*#__PURE__*/ (function () {
const Proto = /*#__PURE__*/ makePrimitiveProto({
op: "Iterator",
[contA](value, fiber) {
const iter = this.iterator;
while (true) {
const state = iter.next(value);
if (state.done) return succeed$3(state.value);
if (!effectIsExit(state.value)) {
fiber._stack.push(this);
return state.value;
} else if (state.value._tag === "Failure") return state.value;
value = state.value.value;
}
},
[evaluate](fiber) {
return this[contA](this.initial, fiber);
},
});
const IteratorImpl = function (iterator, initial) {
this.iterator = iterator;
this.initial = initial;
};
IteratorImpl.prototype = Proto;
return function (iterator, initial) {
return new IteratorImpl(iterator, initial);
};
})();
const evaluateCont = function (fiber) {
fiber._stack.push(this);
return this[args];
};
const OnSuccessProto = /*#__PURE__*/ makePrimitiveProto({
op: "OnSuccess",
[evaluate]: evaluateCont,
});
const ContImpl = function (self, cont, payload) {
this[args] = self;
this[contA] = cont;
this.payload = payload;
};
ContImpl.prototype = OnSuccessProto;
const returnPayload = function () {
return this.payload;
};
const continuationMarksStack = /*#__PURE__*/ (() => {
const limit = /*#__PURE__*/ getStackTraceLimit();
if (limit === 0) return false;
const marker = "~effect/Effect/stackProbe";
const probe = {
[marker]: function stackProbe() {
return /* @__PURE__ */ new Error();
},
};
setStackTraceLimit(1);
const error = /*#__PURE__*/ probe[marker]();
setStackTraceLimit(limit);
return error.stack?.includes("[as " + marker + "]") === true;
})();
const mapCont = function (value, fiber) {
const f = this.payload;
return fiber.succeedWith(continuationMarksStack ? f(value) : internalCall(() => f(value)));
};
const andThenCont = function (value) {
const f = this.payload;
return f(value);
};
/** @internal */
const asVoid = (self) => new ContImpl(self, returnPayload, exitVoid);
/** @internal */
const flatMap$1 = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, andThenCont, f));
/** @internal */
const effectIsExit = (effect) => effect[ExitTypeId] !== void 0;
/** @internal */
const flatMapEager$1 = /*#__PURE__*/ dual(2, (self, f) => {
if (effectIsExit(self)) return self._tag === "Success" ? f(self.value) : self;
return flatMap$1(self, f);
});
/** @internal */
const map$1 = /*#__PURE__*/ dual(2, (self, f) => new ContImpl(self, mapCont, f));
/** @internal */
const mapEager$1 = /*#__PURE__*/ dual(2, (self, f) =>
effectIsExit(self) ? exitMap(self, f) : map$1(self, f),
);
/** @internal */
const exitIsSuccess = (self) => self._tag === "Success";
/** @internal */
const exitVoid = /*#__PURE__*/ exitSucceed(void 0);
/** @internal */
const exitMap = /*#__PURE__*/ dual(2, (self, f) =>
self._tag === "Success" ? exitSucceed(f(self.value)) : self,
);
/** @internal */
const catchCause$1 = /*#__PURE__*/ dual(
2,
(self, f) => new OnFailureImpl(self, f.length !== 1 ? (cause) => f(cause) : f),
);
const OnFailureProto = /*#__PURE__*/ makePrimitiveProto({
op: "OnFailure",
[evaluate]: evaluateCont,
});
const OnFailureImpl = function (self, f) {
this[args] = self;
this[contE] = f;
};
OnFailureImpl.prototype = OnFailureProto;
const OnSuccessAndFailureProto = /*#__PURE__*/ makePrimitiveProto({
op: "OnSuccessAndFailure",
[evaluate]: evaluateCont,
});
const OnSuccessAndFailureImpl = function (self, onSuccess, onFailure) {
this[args] = self;
this[contA] = onSuccess;
this[contE] = onFailure;
};
OnSuccessAndFailureImpl.prototype = OnSuccessAndFailureProto;
/** @internal */
const exit$1 = (self) => (effectIsExit(self) ? exitSucceed(self) : exitPrimitive(self));
const exitPrimitive = /*#__PURE__*/ makePrimitive({
op: "Exit",
[evaluate](fiber) {
fiber._stack.push(this);
return this[args];
},
[contA](value, fiber, exit) {
return fiber.succeedWith(exit ?? exitSucceed(value));
},
[contE](cause, fiber, exit) {
return fiber.succeedWith(exit ?? exitFailCause(cause));
},
});
const combineFinalizerCause = (exit_, finalizer) =>
exitIsSuccess(exit_)
? finalizer
: catchCause$1(finalizer, (cause) => failCause$1(causeCombine(exit_.cause, cause)));
/** @internal */
const uninterruptible = (self) =>
withFiber((fiber) => {
if (!fiber.interruptible) return self;
fiber.interruptible = false;
fiber._stack.push(setInterruptibleTrue);
return self;
});
const setInterruptibleTrue = /*#__PURE__*/ /* @__PURE__ */ makePrimitive({
op: "SetInterruptible",
[contAll](fiber) {
fiber.interruptible = this[args];
if (fiber._interruptedCause && fiber.interruptible)
return () => failCause$1(fiber._interruptedCause);
},
})(true);
/** @internal */
const resolveConcurrency = (concurrency) =>
concurrency === "unbounded" ? Number.POSITIVE_INFINITY : Math.max(1, concurrency ?? 1);
/** @internal */
const iterateEager = () => (options) => {
const onItem = options.onItem;
const step = options.step;
const resumeSequential = (state, items, index, end, effect) =>
flatMap$1(
exit$1(effect),
(itemExit) =>
step(state, items[index], itemExit, index) ??
runSequential(state, items, index + 1, end) ??
void_$1,
);
const runSequential = (state, items, index = 0, end = items.length) => {
for (; index < end; index++) {
const item = items[index];
const effect = onItem(state, item, index);
if (!effectIsExit(effect)) return resumeSequential(state, items, index, end, effect);
const terminal = step(state, item, effect, index);
if (terminal) return terminal._tag === "Failure" ? terminal : void 0;
}
};
return runSequential;
};
const iterateConcurrentImpl = (options) => {
const onItem = options.onItem;
const step = options.step;
return (state, items, opts) => {
let index = 0;
const end = opts.end ?? items.length;
const concurrency = opts.concurrency;
let done = false;
let parentFiber;
let fibers;
let resume;
let terminal;
let effect;
const failDefect = (error) => {
const defect = exitDie(error);
terminal = defect;
done = true;
return fibers && fibers.size > 0
? flatMap$1(
uninterruptible(fiberInterruptAll(Array.from(fibers))),
() => terminal ?? defect,
)
: defect;
};
const go = () => {
let paused = false;
for (; !terminal && index < end; index++) {
const item = items[index];
const eff = effect ?? onItem(state, item, index);
if (effectIsExit(eff)) {
terminal = step(state, item, eff, index);
if (terminal) break;
} else if (!parentFiber)
return callback((cb) => {
parentFiber = getCurrentFiber();
fibers = /* @__PURE__ */ new Set();
effect = eff;
resume = cb;
let result;
try {
result = go();
} catch (error) {
return cb(failDefect(error));
}
if (result) return cb(result);
return suspend$1(() => {
terminal ??= exitVoid;
return flatMap$1(fibers ? fiberInterruptAll(fibers) : void_$1, () =>
terminal?._tag === "Failure" ? terminal : void_$1,
);
});
});
else {
effect = void 0;
const fiber = forkUnsafe(parentFiber, eff, true, true, "inherit");
if (fiber._exit) {
terminal = step(state, item, fiber._exit, index);
if (terminal) break;
continue;
}
fibers.add(fiber);
const currentIndex = index;
fiber.addObserver((exit) => {
fibers.delete(fiber);
try {
if (terminal) {
if (exit._tag === "Failure") {
const reasons = exit.cause.reasons.filter(
(reason) => reason._tag !== "Interrupt",
);
if (reasons.length > 0) {
const cause = causeFromReasons(reasons);
terminal = exitFailCause(
terminal._tag === "Failure" ? causeCombine(terminal.cause, cause) : cause,
);
}
}
} else {
const result = step(state, item, exit, currentIndex);
if (result) {
terminal = result;
go();
}
}
if (paused) {
const eff = go();
if (eff) resume(eff);
} else if (done && fibers.size === 0) resume(terminal ?? void_$1);
} catch (error) {
resume(failDefect(error));
}
});
if (fibers.size < concurrency) continue;
paused = true;
index++;
return;
}
}
done = true;
if (terminal) {
if (fibers && fibers.size > 0) {
const annotations = fiberStackAnnotations(parentFiber);
fibers.forEach((f) => f.interruptUnsafe(parentFiber.id, annotations));
return;
}
if (resume || terminal._tag === "Failure") return terminal;
} else if (resume) {
if (!fibers) return exitVoid;
else if (fibers.size === 0) resume(void_$1);
}
};
return go();
};
};
/** @internal */
const iterateConcurrent = () => (options) => iterateConcurrentImpl(options);
/** @internal */
const forkUnsafe = (parent, effect, immediate = false, daemon = false, uninterruptible = false) => {
const parentRuntime = parent;
const interruptible =
uninterruptible === "inherit" ? parentRuntime.interruptible : !uninterruptible;
const child = new FiberImpl(parentRuntime.context, interruptible);
if (!daemon) {
parentRuntime.children().add(child);
child._parent = parentRuntime;
}
if (immediate) child.evaluate(effect);
else {
child._asyncContext = captureAsyncContext();
parentRuntime.currentDispatcher.scheduleTask(() => child.evaluate(effect), 0);
}
return child;
};
/** @internal */
const runForkWith = (context) => (effect, options) => {
const fiber = new FiberImpl(
options?.scheduler ? add(context, Scheduler, options.scheduler) : context,
options?.uninterruptible !== true,
);
fiber.evaluate(effect);
if (fiber._exit) return fiber;
if (options?.signal) {
if (options.signal.aborted) fiber.interruptUnsafe();
else {
const abort = () => fiber.interruptUnsafe();
options.signal.addEventListener("abort", abort, { once: true });
fiber.addObserver(() => options.signal.removeEventListener("abort", abort));
}
}
if (options?.onFiberStart) options.onFiberStart(fiber);
return fiber;
};
/** @internal */
const runSyncExitWith = (context) => {
const runFork = runForkWith(context);
return (effect) => {
if (effectIsExit(effect)) return effect;
const scheduler = new MixedScheduler("sync");
const fiber = runFork(effect, { scheduler });
fiber._dispatcher?.flush();
return fiber._exit ?? exitDie(new AsyncFiberError(fiber));
};
};
/** @internal */
const runSyncExit$1 = /*#__PURE__*/ runSyncExitWith(/*#__PURE__*/ empty());
/** @internal */
const AsyncFiberErrorTypeId = "~effect/Cause/AsyncFiberError";
/** @internal */
var AsyncFiberError = class extends /*#__PURE__*/ TaggedError$1("AsyncFiberError") {
[AsyncFiberErrorTypeId] = AsyncFiberErrorTypeId;
constructor(fiber) {
super({
message: "An asynchronous Effect was executed with Effect.runSync",
fiber,
});
}
};
const colors = {
bold: "1",
red: "31",
green: "32",
yellow: "33",
blue: "34",
cyan: "36",
white: "37",
gray: "90",
black: "30",
bgBrightRed: "101",
};
(colors.gray,
colors.blue,
colors.green,
colors.yellow,
colors.red,
colors.bgBrightRed,
colors.black);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Cause.js
/**
* Narrows a `Reason` to `Fail`.
*
* **When to use**
*
* Use as a predicate for `Array.filter` to pick out typed `Fail` reasons when
* iterating over `cause.reasons`.
*
* **Example** (Filtering fail reasons)
*
* ```ts import.meta.vitest
* import { Cause } from "effect"
*
* const cause = Cause.fail("error")
* const fails = cause.reasons.filter(Cause.isFailReason)
* fails[0].error // => "error"
* ```
*
* @see {@link isDieReason} — narrow to `Die`
* @see {@link isInterruptReason} — narrow to `Interrupt`
*
* @stability stable
* @category guards
* @since 4.0.0
*/
const isFailReason = isFailReason$1;
/**
* Creates a `Cause` containing a single `Die` reason with the
* given defect.
*
* **When to use**
*
* Use to construct a cause from an untyped defect or unexpected thrown value.
*
* **Example** (Creating a die cause)
*
* ```ts import.meta.vitest
* import { Cause } from "effect"
*
* Cause.die("Unexpected") // => Cause.fromReasons([Cause.makeDieReason("Unexpected")])
* ```
*
* @see {@link fail} — for typed errors
* @see {@link interrupt} — for fiber interruptions
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const die$1 = causeDie;
/**
* Transforms the typed error values inside a `Cause` using the
* provided function. Only `Fail` reasons are affected; `Die` and `Interrupt`
* reasons pass through unchanged.
*
* **When to use**
*
* Use to transform expected typed failures while preserving defects and
* interruptions unchanged.
*
* **Details**
*
* If at least one `Fail` reason exists, this returns a new `Cause`
* containing the mapped failures. If the cause has no `Fail` reasons, the
* original cause is returned unchanged.
*
* **Example** (Mapping errors to uppercase)
*
* ```ts import.meta.vitest
* import { Cause } from "effect"
*
* const cause = Cause.fail("error")
* const mapped = Cause.map(cause, (e) => e.toUpperCase())
* const reason = mapped.reasons[0]
* if (Cause.isFailReason(reason)) {
* reason.error // => "ERROR"
* }
* ```
*
* @stability stable
* @category mapping
* @since 2.0.0
*/
const map = causeMap;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Exit.js
/**
* Creates a successful Exit containing the given value.
*
* **When to use**
*
* Use when you need an Exit that contains a known success value.
*
* **Details**
*
* Returns a `Success<A>` with the provided value. Does not perform any
* computation.
*
* **Example** (Creating a successful Exit)
*
* ```ts import.meta.vitest
* import { Exit } from "effect"
*
* Exit.succeed(42) // => Exit.succeed(42)
* ```
*
* @see {@link fail} to create a failed Exit
* @see {@link void_ void} for a pre-allocated success with no value
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const succeed$2 = exitSucceed;
/**
* Creates a failed Exit from a Cause.
*
* **When to use**
*
* Use when you already have a `Cause<E>` and want to wrap it in an Exit
* for advanced error handling where you need full control over the Cause
* structure.
*
* **Details**
*
* Returns a `Failure<never, E>`. If you only have an error value, use
* {@link fail} instead.
*
* **Example** (Creating a failed Exit from a Cause)
*
* ```ts import.meta.vitest
* import { Cause, Exit } from "effect"
*
* Exit.failCause(Cause.fail("Something went wrong")) // => Exit.fail("Something went wrong")
* ```
*
* @see {@link fail} to create a Failure from a plain error value
* @see {@link die} to create a Failure from a defect
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const failCause = exitFailCause;
/**
* Creates a failed Exit from a typed error value.
*
* **When to use**
*
* Use when you need to represent an expected typed failure as an `Exit`.
*
* **Details**
*
* The error is wrapped in a `Cause.Fail` internally.
*
* Returns a `Failure<never, E>`.
*
* **Example** (Creating a failed Exit)
*
* ```ts import.meta.vitest
* import { Exit } from "effect"
*
* Exit.fail("Something went wrong") // => Exit.fail("Something went wrong")
* ```
*
* @see {@link succeed} to create a successful Exit
* @see {@link die} to create a Failure from an unexpected defect
* @see {@link failCause} to create a Failure from a full Cause
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const fail$2 = exitFail;
const void_ = exitVoid;
/**
* Checks whether an Exit is a Success.
*
* **When to use**
*
* Use as a type guard to narrow `Exit<A, E>` to `Success<A, E>` and access the
* `value` property.
*
* **Example** (Narrowing to success)
*
* ```ts import.meta.vitest
* import { Exit } from "effect"
*
* const exit = Exit.succeed(42)
*
* if (Exit.isSuccess(exit)) {
* exit.value // => 42
* }
* ```
*
* @see {@link isFailure} for the opposite check
* @see {@link match} for exhaustive pattern matching
*
* @stability stable
* @category guards
* @since 2.0.0
*/
const isSuccess = exitIsSuccess;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/dateTime.js
/** @internal */
const TypeId$10 = "~effect/DateTime";
/** @internal */
const TimeZoneTypeId = "~effect/DateTime/TimeZone";
const Proto$4 = {
[TypeId$10]: TypeId$10,
pipe() {
return pipeArguments(this, arguments);
},
[NodeInspectSymbol]() {
return this.toString();
},
toJSON() {
return toDateUtc$1(this).toJSON();
},
};
({ ...Proto$4 });
({ ...Proto$4 });
const ProtoTimeZone = {
[TimeZoneTypeId]: TimeZoneTypeId,
[NodeInspectSymbol]() {
return this.toString();
},
};
({ ...ProtoTimeZone });
({ ...ProtoTimeZone });
/** @internal */
const toDateUtc$1 = (self) => new Date(self.epochMilliseconds);
/**
* Creates an `Effect` that always succeeds with a given value.
*
* **When to use**
*
* Use when an effect should complete successfully with a specific value without any errors
* or external dependencies.
*
* **Example** (Creating a successful effect)
*
* ```ts import.meta.vitest
* import { Effect } from "effect"
*
* // Creating an effect that represents a successful scenario
* //
* // ┌─── Effect<number, never, never>
* // â–¼
* const success = Effect.succeed(42)
* Effect.runSync(success) // => 42
* ```
*
* @see {@link fail} to create an effect that represents a failure.
* @stability stable
* @category constructors
* @since 2.0.0
*/
const succeed$1 = succeed$3;
/**
* Creates an `Effect` lazily, delaying construction until it is needed.
*
* **When to use**
*
* Use when you need to defer the evaluation of an effect until it is required.
*
* **Details**
*
* `suspend` takes a thunk that represents an effect and delays creating it
* until the suspended effect is evaluated. This is useful for optimizing
* expensive computations, managing circular dependencies such as recursive
* functions, and helping TypeScript unify return types when branches construct
* different effects. Any side effects or scoped captures inside the thunk are
* re-executed on each invocation.
*
* **Example** (Lazily evaluating side effects)
*
* ```ts import.meta.vitest
* import { Effect } from "effect"
*
* let i = 0
*
* const bad = Effect.succeed(i++)
*
* const good = Effect.suspend(() => Effect.succeed(i++))
*
* Effect.runSync(bad) // => 0
* Effect.runSync(bad) // => 0
*
* Effect.runSync(good) // => 1
* Effect.runSync(good) // => 2
* ```
*
* **Example** (Suspending recursive Fibonacci evaluation)
*
* ```ts import.meta.vitest
* import { Effect } from "effect"
*
* const blowsUp = (n: number): Effect.Effect<number> =>
* n < 2
* ? Effect.succeed(1)
* : Effect.zipWith(blowsUp(n - 1), blowsUp(n - 2), (a, b) => a + b)
*
* // console.log(Effect.runSync(blowsUp(32)))
* // crash: JavaScript heap out of memory
*
* const allGood = (n: number): Effect.Effect<number> =>
* n < 2
* ? Effect.succeed(1)
* : Effect.zipWith(
* Effect.suspend(() => allGood(n - 1)),
* Effect.suspend(() => allGood(n - 2)),
* (a, b) => a + b
* )
*
* Effect.runSync(allGood(16)) // => 1597
* ```
*
* **Example** (Helping TypeScript infer recursive effect types)
*
* ```ts import.meta.vitest
* import { Effect } from "effect"
*
* // Without suspend, TypeScript may struggle with type inference.
* // Inferred type:
* // (a: number, b: number) =>
* // Effect<never, Error, never> | Effect<number, never, never>
* const withoutSuspend = (a: number, b: number) =>
* b === 0
* ? Effect.fail(new Error("Cannot divide by zero"))
* : Effect.succeed(a / b)
*
* // Using suspend to unify return types.
* // Inferred type:
* // (a: number, b: number) => Effect<number, Error, never>
* const withSuspend = (a: number, b: number) =>
* Effect.suspend(() =>
* b === 0
* ? Effect.fail(new Error("Cannot divide by zero"))
* : Effect.succeed(a / b)
* )
*
* Effect.runSync(withSuspend(6, 2)) // => 3
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const suspend = suspend$1;
/**
* Creates an `Effect` that represents a recoverable error.
*
* **When to use**
*
* Use to explicitly signal a recoverable error in an `Effect`.
*
* **Details**
*
* The error keeps propagating unless it is handled. You can handle tagged
* errors with functions like {@link catchTag} or {@link catchTags}.
*
* **Example** (Creating a failed effect)
*
* ```ts import.meta.vitest
* import { Data, Effect } from "effect"
*
* class OperationFailedError extends Data.TaggedError("OperationFailedError")<{}> {}
*
* // ┌─── Effect<never, OperationFailedError, never>
* // â–¼
* const failure = Effect.fail(
* new OperationFailedError()
* )
* Effect.runSync(Effect.flip(failure))._tag // => "OperationFailedError"
* ```
*
* @see {@link succeed} to create an effect that represents a successful value.
* @stability stable
* @category constructors
* @since 2.0.0
*/
const fail$1 = fail$3;
/**
* Creates an `Effect` that represents a failure with a `Cause` computed lazily.
*
* **When to use**
*
* Use to defer computing a full `Cause` until the effect is run.
*
* **Details**
*
* The cause-producing function is evaluated each time the effect is executed.
*
* **Example** (Lazily creating a Cause)
*
* ```ts import.meta.vitest
* import { Cause, Effect } from "effect"
*
* const program = Effect.failCauseSync(() =>
* Cause.fail("Error computed at runtime")
* )
*
* Effect.runSync(Effect.flip(program)) // => "Error computed at runtime"
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const failCauseSync = failCauseSync$1;
/**
* Creates an effect that terminates a fiber with a specified error.
*
* **When to use**
*
* Use when you need an `Effect` to report an unrecoverable defect instead of a
* typed error.
*
* **Details**
*
* The `die` function is used to signal a defect, which represents a critical
* and unexpected error in the code. When invoked, it produces an effect that
* does not handle the error and instead terminates the fiber.
*
* The error channel of the resulting effect is of type `never`, indicating that
* it cannot recover from this failure.
*
* **Example** (Failing on division by zero)
*
* ```ts import.meta.vitest
* import { Effect, Exit } from "effect"
*
* const defect = new Error("Cannot divide by zero")
* const divide = (a: number, b: number) =>
* b === 0
* ? Effect.die(defect)
* : Effect.succeed(a / b)
*
* // ┌─── Effect<number, never, never>
* // â–¼
* const program = divide(1, 0)
*
* Effect.runSyncExit(program) // => Exit.die(defect)
* ```
*
* @stability stable
* @category constructors
* @since 2.0.0
*/
const die = die$2;
/**
* Chains effects to produce new `Effect` instances, useful for combining
* operations that depend on previous results.
*
* **When to use**
*
* Use when you need to chain multiple effects, ensuring that each
* step produces a new `Effect` while flattening any nested effects that may
* occur.
*
* **Details**
*
* `flatMap` lets you sequence effects so that the result of one effect can be
* used in the next step. It is similar to `flatMap` used with arrays but works
* specifically with `Effect` instances, allowing you to avoid deeply nested
* effect structures.
*
* Since effects are immutable, `flatMap` always returns a new effect instead of
* changing the original one.
*
* **Example** (Choosing flatMap syntax variants)
*
* ```ts import.meta.vitest
* import { Effect, pipe } from "effect"
* const output: Array<unknown> = []
*
* const myEffect = Effect.succeed(1)
* const transformation = (n: number) => Effect.succeed(n + 1)
*
* const flatMappedWithPipe = pipe(myEffect, Effect.flatMap(transformation))
* const flatMappedWithDataFirst = Effect.flatMap(myEffect, transformation)
* const flatMappedWithMethod = myEffect.pipe(Effect.flatMap(transformation))
*
* void output.push(Effect.runSync(Effect.all([
* flatMappedWithPipe,
* flatMappedWithDataFirst,
* flatMappedWithMethod
* ])))
* output // => [[2, 2, 2]]
* ```
*
* **Example** (Sequencing dependent effects)
*
* ```ts import.meta.vitest
* import { Data, Effect, pipe } from "effect"
*
* class DiscountRateError extends Data.TaggedError("DiscountRateError")<{}> {}
*
* // Function to apply a discount safely to a transaction amount
* const applyDiscount = (
* total: number,
* discountRate: number
* ): Effect.Effect<number, DiscountRateError> =>
* discountRate === 0
* ? Effect.fail(new DiscountRateError())
* : Effect.succeed(total - (total * discountRate) / 100)
*
* // Simulated asynchronous task to fetch a transaction amount from database
* const fetchTransactionAmount = Effect.promise(() => Promise.resolve(100))
*
* // Chaining the fetch and discount application using `flatMap`
* const finalAmount = pipe(
* fetchTransactionAmount,
* Effect.flatMap((amount) => applyDiscount(amount, 5))
* )
*
* await Effect.runPromise(finalAmount) // => 95
* ```
*
* @see {@link tap} for a version that ignores the result of the effect.
* @stability stable
* @category sequencing
* @since 2.0.0
*/
const flatMap = flatMap$1;
/**
* Transforms an effect to encapsulate both failure and success using the `Exit`
* data type.
*
* **When to use**
*
* Use when you need to inspect the full outcome, including typed failures, defects,
* and interruptions.
*
* **Details**
*
* `exit` wraps an effect's success or failure inside an `Exit` type, allowing
* you to handle both cases explicitly.
*
* The resulting effect cannot fail because the failure is encapsulated within
* the `Exit.Failure` type. The error type is set to `never`, indicating that
* the effect is structured to never fail directly.
*
* **Example** (Capturing completion as Exit)
*
* ```ts import.meta.vitest
* import { Effect, Exit } from "effect"
*
* const success = Effect.succeed(42)
* const failure = Effect.fail("Something went wrong")
*
* const program1 = Effect.exit(success)
* const program2 = Effect.exit(failure)
*
* Effect.runSync(program1) // => Exit.succeed(42)
*
* Effect.runSync(program2) // => Exit.fail("Something went wrong")
* ```
*
* @see {@link option} for a version that uses `Option` instead.
* @see {@link result} for a version that uses `Result` instead.
*
* @stability stable
* @category error handling
* @since 2.0.0
*/
const exit = exit$1;
/**
* Handles both recoverable and unrecoverable errors by providing a recovery
* effect.
*
* **When to use**
*
* Use when you need to recover from an `Effect` by inspecting the full `Cause`,
* including recoverable failures, defects, and interruptions, instead of only
* the typed error value.
*
* **Details**
*
* When to Recover from Defects:
*
* Defects are unexpected errors that typically shouldn't be recovered from, as
* they often indicate serious issues. However, in some cases, such as
* dynamically loaded plugins, controlled recovery might be needed.
*
* **Example** (Recovering from full failure causes)
*
* ```ts import.meta.vitest
* import { Cause, Effect } from "effect"
* const output: Array<unknown> = []
*
* // An effect that might fail in different ways
* const program = Effect.die("Something went wrong")
*
* // Recover from any cause (including defects)
* const recovered = Effect.catchCause(program, (cause) => {
* if (Cause.hasDies(cause)) {
* return Effect.sync(() => { output.push("Caught defect") }).pipe(
* Effect.as("Recovered from defect")
* )
* }
* return Effect.succeed("Unknown error")
* })
*
* void output.push(Effect.runSync(recovered))
* output // => ["Caught defect", "Recovered from defect"]
* ```
*
* @stability stable
* @category error handling
* @since 4.0.0
*/
const catchCause = catchCause$1;
/**
* Runs an effect synchronously and captures the outcome safely as an `Exit` type, which
* represents the outcome (success or failure) of the effect.
*
* **When to use**
*
* Use to find out whether an effect succeeded or failed,
* including any defects, without dealing with asynchronous operations.
*
* **Details**
*
* The `Exit` type represents the result of the effect. Successful effects are
* wrapped in `Success`, and failed effects are wrapped in `Failure` with a
* `Cause`.
*
* If the effect contains asynchronous operations, `runSyncExit` will
* return an `Failure` with a `Die` cause, indicating that the effect cannot be
* resolved synchronously.
*
* **Example** (Observing synchronous results as Exit)
*
* ```ts import.meta.vitest
* import { Effect, Exit } from "effect"
*
* Effect.runSyncExit(Effect.succeed(1)) // => Exit.succeed(1)
*
* Effect.runSyncExit(Effect.fail("my error")) // => Exit.fail("my error")
* ```
*
* **Example** (Capturing async work as a Die cause)
*
* ```ts import.meta.vitest
* import { Cause, Effect, Exit } from "effect"
*
* const exit = Effect.runSyncExit(Effect.promise(() => Promise.resolve(1)))
* const isAsyncDie = Exit.hasDies(exit) && exit.cause.reasons.some(
* (reason) => Cause.isDieReason(reason) && Cause.isAsyncFiberError(reason.defect)
* )
*
* isAsyncDie // => true
* ```
*
* @see {@link runSync} for a version that throws on failure.
*
* @stability stable
* @category running
* @since 2.0.0
*/
const runSyncExit = runSyncExit$1;
/**
* Applies `map` eagerly when an effect is already resolved.
*
* **When to use**
*
* Use when an already-resolved effect should apply a success transformation
* immediately while pending effects still use regular mapping.
*
* **Details**
*
* Success effects apply the mapping function immediately. Failure effects pass
* through unchanged, and pending effects fall back to regular `map` behavior.
*
* **Example** (Mapping already completed effects)
*
* ```ts import.meta.vitest
* import { Effect } from "effect"
*
* // For resolved effects, the mapping is applied immediately
* const resolved = Effect.succeed(5)
* const mapped = Effect.mapEager(resolved, (n) => n * 2) // Applied eagerly
*
* // For pending effects, behaves like regular map
* const pending = Effect.delay(Effect.succeed(5), 0)
* const mappedPending = Effect.mapEager(pending, (n) => n * 2) // Uses regular map
*
* await Effect.runPromise(Effect.all([mapped, mappedPending])) // => [10, 10]
* ```
*
* @stability stable
* @category mapping
* @since 4.0.0
*/
const mapEager = mapEager$1;
/**
* Applies `flatMap` eagerly when an effect is already resolved.
*
* **When to use**
*
* Use when an already-resolved successful effect should bind immediately to the
* next effect while pending effects still use regular flat mapping.
*
* **Details**
*
* Success effects apply the flatMap function immediately. Failure effects pass
* through unchanged, and pending effects fall back to regular `flatMap`
* behavior.
*
* **Example** (Flat mapping eagerly when possible)
*
* ```ts import.meta.vitest
* import { Effect } from "effect"
*
* // For resolved effects, the flatMap is applied immediately
* const resolved = Effect.succeed(5)
* const flatMapped = Effect.flatMapEager(resolved, (n) => Effect.succeed(n * 2)) // Applied eagerly
*
* // For pending effects, behaves like regular flatMap
* const pending = Effect.delay(Effect.succeed(5), 0)
* const flatMappedPending = Effect.flatMapEager(
* pending,
* (n) => Effect.succeed(n * 2)
* ) // Uses regular flatMap
*
* await Effect.runPromise(Effect.all([flatMapped, flatMappedPending])) // => [10, 10]
* ```
*
* @stability stable
* @category sequencing
* @since 4.0.0
*/
const flatMapEager = flatMapEager$1;
/**
* Creates untraced function effects with eager evaluation optimization.
*
* **Details**
*
* Executes generator functions eagerly when all yielded effects are synchronous,
* stopping at the first async effect and deferring to normal execution.
*
* **Example** (Defining eager untraced effect functions)
*
* ```ts import.meta.vitest
* import { Effect } from "effect"
*
* const computation = Effect.fnUntracedEager(function*() {
* yield* Effect.succeed(1)
* yield* Effect.succeed(2)
* return "computed eagerly"
* })
*
* const effect = computation() // Executed immediately if all effects are sync
* Effect.runSync(effect) // => "computed eagerly"
* ```
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const fnUntracedEager = fnUntracedEager$1;
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
const codes = /*#__PURE__*/ /* @__PURE__ */ new Uint8Array(123).fill(255);
for (let i = 0; i < 64; i++) codes[/*#__PURE__*/ alphabet.charCodeAt(i)] = i;
codes[/*#__PURE__*/ "=".charCodeAt(0)] = 0;
({ ...BaseProto });
({ ...BaseProto });
({ ...PipeInspectableProto });
(BaseProto.toString, BaseProto[NodeInspectSymbol]);
({ ...PipeInspectableProto });
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/schema/annotations.js
/** @internal */
function resolve$1(ast) {
return ast.checks ? ast.checks[ast.checks.length - 1].annotations : ast.annotations;
}
/** @internal */
const STRUCTURAL_ANNOTATION_KEY = "~structural";
/** @internal */
const SENTINELS_ANNOTATION_KEY = "~sentinels";
/** @internal */
const CONSTRUCTOR_ANNOTATION_KEY = "~constructor";
/** @internal */
const getExpected = /*#__PURE__*/ memoize((ast) => {
const identifier = resolve$1(ast)?.identifier;
if (typeof identifier === "string") return identifier;
return ast.getExpected(getExpected);
});
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/schema/parser.js
/** @internal */
const missing = /*#__PURE__*/ Symbol();
/** @internal */
const succeed = succeed$2;
/** @internal */
const missingExit = /*#__PURE__*/ succeed(missing);
/** @internal */
const sameExit = /*#__PURE__*/ succeed(missing);
/** @internal */
const toOption = (value) => (value === missing ? none() : some(value));
/** @internal */
const fromOptionExit = (option) => (option._tag === "None" ? missingExit : succeed(option.value));
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/SchemaIssue.js
/**
* Describes problems found while decoding, encoding, or checking data with
* schemas.
*
* An `Issue` records what failed and, for nested data, where the failure
* happened. The Schema system uses these values for missing keys, unexpected
* keys, invalid types, invalid values, failed filters, failed transformations,
* and alternatives that did not match. This module also formats issues.
*
* @stability stable
* @since 4.0.0
*/
const TypeId$5 = "~effect/SchemaIssue/Issue";
/**
* Returns `true` if the given value is an {@link Issue}.
*
* **When to use**
*
* Use when you need to narrow an `unknown` value to `Issue` in error-handling
* code, such as distinguishing an `Issue` from other error types in a catch-all
* handler.
*
* **Details**
*
* - Checks for the internal `TypeId` brand on the value.
*
* **Example** (Type-guarding an unknown error)
*
* ```ts import.meta.vitest
* import { SchemaIssue } from "effect"
*
* const issue = new SchemaIssue.MissingKey(undefined)
* SchemaIssue.isIssue(issue) // => true
* SchemaIssue.isIssue("not an issue") // => false
* ```
*
* @see {@link Issue}
*
* @stability stable
* @category guards
* @since 4.0.0
*/
function isIssue(u) {
return hasProperty(u, TypeId$5) && u[TypeId$5] === TypeId$5;
}
/**
* Returns `true` when an issue contains an input reported by the schema parser.
*
* **When to use**
*
* Use when reading `Issue.input`, especially when `undefined` is a valid input
* value.
*
* **Details**
*
* Reported input is stored as an own property. This guard checks for that
* property and narrows `input` from optional to required.
*
* **Example** (Reading a reported input)
*
* ```ts import.meta.vitest
* import { Result, Schema, SchemaIssue } from "effect"
*
* const result = Schema.decodeUnknownResult(Schema.String)(1, { reportInput: true })
* if (Result.isFailure(result) && SchemaIssue.hasInput(result.failure.issue)) {
* result.failure.issue.input // => 1
* }
* ```
*
* @see {@link Issue} for the complete issue model
*
* @stability stable
* @category guards
* @since 4.0.0
*/
function hasInput(issue) {
return Object.hasOwn(issue, "input");
}
var IssueNodeImpl = class {
[TypeId$5] = TypeId$5;
constructor(input, options) {
if (options?.reportInput === true && input !== missing) this.input = input;
}
};
/**
* Constructs a schema issue for a failed refinement check.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Filter$1 = class extends IssueNodeImpl {
_tag = "Filter";
/**
* The filter that failed.
*/
filter;
/**
* The issue that occurred.
*/
issue;
constructor(filter, issue, input, options) {
super(input, options);
this.filter = filter;
this.issue = issue;
}
};
/**
* Constructs a schema issue for a failed transformation.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Encoding = class extends IssueNodeImpl {
_tag = "Encoding";
/**
* The schema that caused the issue.
*/
ast;
/**
* The issue that occurred.
*/
issue;
constructor(ast, issue, input, options) {
super(input, options);
this.ast = ast;
this.issue = issue;
}
};
/**
* Constructs a schema issue that points to a nested location.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Pointer = class extends IssueNodeImpl {
_tag = "Pointer";
/**
* The path to the location in the input that caused the issue.
*/
path;
/**
* The issue that occurred.
*/
issue;
constructor(path, issue) {
super();
this.path = path;
this.issue = issue;
}
};
/**
* Constructs a schema issue for a missing key or tuple index.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const MissingKey = class extends IssueNodeImpl {
_tag = "MissingKey";
/**
* The metadata for the issue.
*/
annotations;
constructor(annotations) {
super();
this.annotations = annotations;
}
};
/**
* Constructs a schema issue for an unexpected key or tuple index.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const UnexpectedKey = class extends IssueNodeImpl {
_tag = "UnexpectedKey";
/**
* The schema that caused the issue.
*/
ast;
constructor(ast, input, options) {
super(input, options);
this.ast = ast;
}
};
/**
* Constructs a schema issue that groups multiple child issues.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Composite = class extends IssueNodeImpl {
_tag = "Composite";
/**
* The schema that caused the issue.
*/
ast;
/**
* The issues that occurred.
*/
issues;
constructor(ast, issues, input, options) {
super(input, options);
this.ast = ast;
this.issues = issues;
}
};
/**
* Constructs a schema issue for an input with an invalid runtime type.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const InvalidType = class extends IssueNodeImpl {
_tag = "InvalidType";
/**
* The schema that caused the issue.
*/
ast;
constructor(ast, input, options) {
super(input, options);
this.ast = ast;
}
};
/**
* Constructs a schema issue for a value that violates a constraint.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const InvalidValue = class extends IssueNodeImpl {
_tag = "InvalidValue";
/**
* The metadata for the issue.
*/
annotations;
constructor(annotations, input, options) {
super(input, options);
this.annotations = annotations;
}
};
/**
* Constructs a schema issue for a value that matches no union member.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const AnyOf = class extends IssueNodeImpl {
_tag = "AnyOf";
/**
* The schema that caused the issue.
*/
ast;
/**
* The issues that occurred.
*/
issues;
constructor(ast, issues, input, options) {
super(input, options);
this.ast = ast;
this.issues = issues;
}
};
/**
* Constructs a schema issue for a value that matches multiple union members.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const OneOf = class extends IssueNodeImpl {
_tag = "OneOf";
/**
* The schema that caused the issue.
*/
ast;
/**
* The schemas that were successful.
*/
successes;
constructor(ast, successes, input, options) {
super(input, options);
this.ast = ast;
this.successes = successes;
}
};
function makeFilterIssue(entry, input, options) {
if (isIssue(entry)) return entry;
if (typeof entry === "string") return new InvalidValue({ message: entry }, input, options);
const inner =
typeof entry.issue === "string"
? new InvalidValue({ message: entry.issue }, input, options)
: entry.issue;
return new Pointer(entry.path, inner);
}
/** @internal */
function makeSingle(out, input, options) {
if (out === void 0) return;
if (typeof out === "boolean") return out ? void 0 : new InvalidValue(void 0, input, options);
return makeFilterIssue(out, input, options);
}
/** @internal */
function normalizeFilterOutput(ast, out, input, options) {
if (Array.isArray(out)) {
if (!isReadonlyArrayNonEmpty(out)) return;
return out.length === 1
? makeFilterIssue(out[0], input, options)
: new Composite(
ast,
map$2(out, (entry) => makeFilterIssue(entry, input, options)),
input,
options,
);
}
return makeSingle(out, input, options);
}
/**
* Returns the built-in {@link LeafHook} used by default formatters.
*
* **When to use**
*
* Use as the default leaf renderer when customizing only the {@link CheckHook}.
*
* **Details**
*
* - Checks for a `message` annotation first; returns it if present.
* - For `InvalidValue`, an `expected` annotation uses the standard expected
* value message and includes reported input when available.
* - Otherwise generates a default message per `_tag`. When the issue reports
* input, the message includes its formatted value where applicable:
* - `InvalidType` → `"Expected <type>"` or `"Expected <type>, got <input>"`
* - `InvalidValue` → `"Expected a valid value"` or `"Invalid data <input>"`
* - `MissingKey` → `"Missing key"`
* - `UnexpectedKey` → `"Expected no excess property"` or
* `"Unexpected key with value <input>"`
* - `Forbidden` → `"Forbidden operation"`
* - `OneOf` → `"Expected exactly one member to match"` or
* `"Expected exactly one member to match the input <input>"`
*
* **Example** (Formatting Standard Schema issues with defaultLeafHook)
*
* ```ts import.meta.vitest
* import { SchemaIssue } from "effect"
*
* const formatter = SchemaIssue.makeFormatterStandardSchemaV1({
* leafHook: SchemaIssue.defaultLeafHook
* })
* formatter(new SchemaIssue.MissingKey(undefined)) // => { issues: [{ path: [], message: "Missing key" }] }
* ```
*
* @see {@link LeafHook}
* @see {@link makeFormatterStandardSchemaV1}
*
* @stability stable
* @category formatting
* @since 4.0.0
*/
const defaultLeafHook = (issue) => {
const message = findMessage(issue);
if (message !== void 0) return message;
switch (issue._tag) {
case "InvalidType":
return getExpectedMessage(getExpected(issue.ast), issue);
case "InvalidValue": {
const expected = findExpected(issue);
if (expected !== void 0) return getExpectedMessage(expected, issue);
const input = formatInput(issue);
return input === void 0 ? "Expected a valid value" : `Invalid data ${input}`;
}
case "MissingKey":
return "Missing key";
case "UnexpectedKey": {
const input = formatInput(issue);
return input === void 0
? "Expected no excess property"
: `Unexpected key with value ${input}`;
}
case "Forbidden":
return "Forbidden operation";
case "OneOf": {
const input = formatInput(issue);
return input === void 0
? "Expected exactly one member to match"
: `Expected exactly one member to match the input ${input}`;
}
}
};
/**
* Returns the built-in {@link CheckHook} used by default formatters.
*
* **When to use**
*
* Use as the default filter renderer when customizing only the {@link LeafHook}.
*
* **Details**
*
* - Looks for a `message` annotation on the inner issue first, then on the
* filter itself.
* - Returns `undefined` when no annotation is found, causing the formatter to
* fall back to `"Expected <filter>"` or, when the filter reports input,
* `"Expected <filter>, got <input>"`.
*
* @see {@link CheckHook}
* @see {@link makeFormatterStandardSchemaV1}
*
* @stability stable
* @category formatting
* @since 4.0.0
*/
const defaultCheckHook = (issue) => findMessage(issue.issue) ?? findMessage(issue);
function formatInput(issue) {
return hasInput(issue) ? format$1(issue.input) : void 0;
}
function findExpected(issue) {
const expected = issue.annotations?.expected;
return typeof expected === "string" ? expected : void 0;
}
function getExpectedMessage(expected, issue) {
const input = formatInput(issue);
return input === void 0 ? `Expected ${expected}` : `Expected ${expected}, got ${input}`;
}
function formatCheck(check) {
const expected = check.annotations?.expected;
if (typeof expected === "string") return expected;
switch (check._tag) {
case "Filter":
return "<filter>";
case "FilterGroup":
return check.checks.map((check) => formatCheck(check)).join(" & ");
}
}
/**
* Creates a {@link Formatter} that converts an {@link Issue} into a
* human-readable multi-line string.
*
* **When to use**
*
* Use when you need to format a `SchemaIssue.Issue` as error messages for
* logging, CLI output, or developer-facing diagnostics.
*
* **Details**
*
* - Flattens the issue tree into `{ message, path }` entries using
* {@link defaultLeafHook} and {@link defaultCheckHook}.
* - Includes reported input in default messages when the node producing the
* message has an `input` field.
* - Each entry is rendered as `"<message>"` or `"<message>\n at <path>"`.
* - Multiple entries are joined with newlines.
*
* **Gotchas**
*
* Formatting an issue can disclose input retained with `reportInput: true`.
* Wrapper inputs are not inherited by child messages, and custom messages are
* returned unchanged.
*
* **Example** (Formatting an issue as a string)
*
* ```ts import.meta.vitest
* import { SchemaIssue } from "effect"
*
* const formatter = SchemaIssue.makeFormatterDefault()
* formatter(new SchemaIssue.MissingKey(undefined)) // => "Missing key"
* ```
*
* @see {@link makeFormatterStandardSchemaV1} — produces Standard Schema V1 format instead
* @see {@link Formatter}
*
* @stability stable
* @category formatting
* @since 4.0.0
*/
function makeFormatterDefault() {
return (issue) => formatIssue(issue, "");
}
/** @internal */
const defaultFormatter = /*#__PURE__*/ makeFormatterDefault();
function formatIssue(issue, path) {
let message;
switch (issue._tag) {
case "Filter": {
const annotated = defaultCheckHook(issue);
if (annotated !== void 0) message = annotated;
else {
if (issue.issue._tag !== "InvalidValue") return formatIssue(issue.issue, path);
const expected = findExpected(issue.issue);
message =
expected === void 0
? getExpectedMessage(formatCheck(issue.filter), issue)
: getExpectedMessage(expected, issue.issue);
}
break;
}
case "Encoding":
return formatIssue(issue.issue, path);
case "Pointer":
return formatIssue(issue.issue, path + formatPath(issue.path));
case "Composite":
case "AnyOf":
if (issue._tag === "Composite" || issue.issues.length > 0)
return issue.issues.map((issue) => formatIssue(issue, path)).join("\n");
message = findMessage(issue) ?? getExpectedMessage(getExpected(issue.ast), issue);
break;
default:
message = defaultLeafHook(issue);
}
return path ? `${message}\n at ${path}` : message;
}
function findMessage(issue) {
if (issue._tag === "Pointer") return;
if (issue._tag === "Encoding") return findMessage(issue.issue);
const message = (
issue._tag === "Filter"
? issue.filter.annotations
: "annotations" in issue
? issue.annotations
: issue.ast.annotations
)?.[
issue._tag === "MissingKey"
? "messageMissingKey"
: issue._tag === "UnexpectedKey"
? "messageUnexpectedKey"
: "message"
];
if (typeof message === "string") return message;
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/schema/cause.js
/** @internal */
function getSchemaIssue(cause) {
let issue;
for (const reason of cause.reasons) {
if (!isFailReason(reason) || !isIssue(reason.error)) return;
issue ??= reason.error;
}
return issue;
}
/** @internal */
function getSchemaIssueOrThrow(cause, message) {
const issue = getSchemaIssue(cause);
if (issue === void 0) throw new Error(message, { cause });
return issue;
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/SchemaGetter.js
const makeGetter = (fields) => Object.assign(Object.create(Prototype$1), fields);
const passthrough_$1 = /*#__PURE__*/ makeGetter({ _tag: "Passthrough" });
function passthrough$1() {
return passthrough_$1;
}
/**
* Creates a getter that applies a pure function to present values.
*
* **When to use**
*
* Use when you need a schema getter for a pure, infallible transformation
* between types.
* - Building encode/decode pairs for `Schema.decodeTo`.
*
* **Details**
*
* - This is the most commonly used constructor.
* - Transforms `Some(e)` to `Some(f(e))` and leaves `None` unchanged.
* - Skips `None` inputs — only called when a value is present.
* - Never fails.
*
* **Example** (Transforming strings to numbers)
*
* ```ts import.meta.vitest
* import { Schema, SchemaGetter } from "effect"
*
* const NumberFromString = Schema.String.pipe(
* Schema.decodeTo(Schema.Number, {
* decode: SchemaGetter.transform((s) => Number(s)),
* encode: SchemaGetter.transform((n) => String(n))
* })
* )
* Schema.decodeSync(NumberFromString)("42") // => 42
* ```
*
* @see {@link transformEffect} when the transformation returns an `Effect`
* @see {@link transformOptional} when you need to handle `None` inputs
* @see {@link passthrough} when no transformation is needed
*
* @stability stable
* @category transforming
* @since 4.0.0
*/
function transform$1(f) {
return makeGetter({
_tag: "Transform",
transform: f,
});
}
/**
* Coerces any value to a `string` using the global `String()` constructor.
*
* **When to use**
*
* Use when you need a schema getter to coerce a present encoded value to a
* string with `String()`.
*
* **Details**
*
* The getter is pure, never fails, and delegates to `globalThis.String`.
*
* **Example** (Coercing to a string)
*
* ```ts import.meta.vitest
* import { Effect, Option, SchemaGetter } from "effect"
*
* const toString = SchemaGetter.String<number>()
* Effect.runSync(SchemaGetter.run(toString, Option.some(42), {})) // => Option.some("42")
* ```
*
* @see {@link transform} for custom string conversions
*
* @stability stable
* @category converting
* @since 4.0.0
*/
function String$3() {
return transform$1(globalThis.String);
}
/**
* Coerces any value to a `number` using the global `Number()` constructor.
*
* **When to use**
*
* Use when you need a schema getter to coerce a present encoded value to a
* number with `Number()`.
*
* **Details**
*
* The getter is pure, never fails, and delegates to `globalThis.Number`. It may
* produce `NaN` for non-numeric inputs.
*
* **Example** (Coercing to a number)
*
* ```ts import.meta.vitest
* import { Effect, Option, SchemaGetter } from "effect"
*
* const toNumber = SchemaGetter.Number<string>()
* Effect.runSync(SchemaGetter.run(toNumber, Option.some("42"), {})) // => Option.some(42)
* ```
*
* @see {@link transformEffect} for effectful or validated number parsing
*
* @stability stable
* @category converting
* @since 4.0.0
*/
function Number$3() {
return transform$1(globalThis.Number);
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/SchemaTransformation.js
/**
* Constructs schema middleware from its decode and encode functions.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Middleware = class extends Class$1 {
_tag = "Middleware";
decode;
encode;
constructor(decode, encode) {
super();
this.decode = decode;
this.encode = encode;
}
flip() {
return new Middleware(this.encode, this.decode);
}
};
const TypeId$4 = "~effect/SchemaTransformation/Transformation";
/**
* Constructs a bidirectional schema transformation from its decode and encode getters.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Transformation = class extends Class$1 {
[TypeId$4] = TypeId$4;
_tag = "Transformation";
decode;
encode;
constructor(decode, encode) {
super();
this.decode = decode;
this.encode = encode;
}
flip() {
return new Transformation(this.encode, this.decode);
}
};
/**
* Returns `true` if `u` is a `Transformation` instance.
*
* **When to use**
*
* Use to check whether a value is already a schema transformation before
* wrapping it.
*
* **Details**
*
* - Pure predicate, no side effects.
* - Acts as a TypeScript type guard.
*
* **Example** (Checking a value)
*
* ```ts import.meta.vitest
* import { SchemaTransformation } from "effect"
*
* SchemaTransformation.isTransformation(SchemaTransformation.trim()) // => true
* SchemaTransformation.isTransformation({ decode: null, encode: null }) // => false
* ```
*
* @see {@link Transformation}
* @see {@link makeTransformation}
*
* @stability stable
* @category guards
* @since 4.0.0
*/
function isTransformation(u) {
return hasProperty(u, TypeId$4) && u[TypeId$4] === TypeId$4;
}
/**
* Constructs a `Transformation` from an object with `decode` and `encode`
* `Getter`s. If the input is already a `Transformation`, returns it as-is.
*
* **When to use**
*
* Use when you already have schema getter instances and want to pair them into
* a schema transformation.
* - You want idempotent wrapping (won't double-wrap).
*
* **Details**
*
* - Returns the input unchanged if it is already a `Transformation`.
*
* **Example** (Wrapping existing getters)
*
* ```ts import.meta.vitest
* import { SchemaGetter, SchemaTransformation } from "effect"
*
* const t = SchemaTransformation.makeTransformation({
* decode: SchemaGetter.transform<number, string>((s) => Number(s)),
* encode: SchemaGetter.transform<string, number>((n) => String(n))
* })
* t._tag // => "Transformation"
* ```
*
* @see {@link transform} — simpler constructor from pure functions
* @see {@link transformEffect} — constructor from effectful functions
* @see {@link Transformation}
*
* @stability stable
* @category constructors
* @since 3.10.0
*/
const makeTransformation = (options) => {
if (isTransformation(options)) return options;
return new Transformation(options.decode, options.encode);
};
const passthrough_ = /*#__PURE__*/ new Transformation(
/*#__PURE__*/ passthrough$1(),
/*#__PURE__*/ passthrough$1(),
);
function passthrough() {
return passthrough_;
}
/**
* Decodes a `string` into a `number` and encodes a `number` back to a
* `string`.
*
* **When to use**
*
* Use when you need a schema transformation to parse numeric strings from APIs,
* form data, or URL parameters.
*
* **Details**
*
* Decoding coerces the string to a number like `Number(s)`. Encoding coerces
* the number to a string like `String(n)`. This does not validate that the
* result is finite; combine with `Schema.Finite` or `Schema.Int` for stricter
* checks.
*
* **Example** (Converting a string to a number)
*
* ```ts import.meta.vitest
* import { Schema, SchemaTransformation } from "effect"
*
* const schema = Schema.String.pipe(
* Schema.decodeTo(Schema.Number, SchemaTransformation.numberFromString)
* )
* Schema.decodeSync(schema)("42") // => 42
* ```
*
* @see {@link bigintFromString}
* @see {@link transform}
*
* @stability stable
* @category converting
* @since 4.0.0
*/
const numberFromString = /*#__PURE__*/ new Transformation(
/*#__PURE__*/ Number$3(),
/*#__PURE__*/ String$3(),
);
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/SchemaAST.js
/**
* Represents Effect schemas as runtime trees.
*
* Every `Schema` has an AST made from nodes for declarations, primitives,
* literals, arrays, objects, unions, suspended schemas, checks, annotations,
* encoding links, and parsing context. Most users work with the higher-level
* `Schema` module. Use `SchemaAST` when you need to inspect schema nodes, build
* ASTs programmatically, change encoded or decoded views, collect issues, or
* run low-level schema checks.
*
* @stability stable
* @since 4.0.0
*/
function makeGuard(tag) {
return (ast) => ast._tag === tag;
}
/**
* Narrows an {@link AST} to {@link Declaration}.
*
* **When to use**
*
* Use to recognize declaration AST nodes before running declaration-specific
* handling.
*
* @see {@link Declaration} for the AST node type narrowed by this guard
*
* @stability stable
* @category guards
* @since 3.10.0
*/
const isDeclaration = /*#__PURE__*/ makeGuard("Declaration");
/**
* Narrows an {@link AST} to {@link Never}.
*
* **When to use**
*
* Use to detect the AST node for a schema that can never match before handling
* other schema variants.
*
* @see {@link Never} for the AST node type narrowed by this guard
* @see {@link never} for the singleton `Never` AST instance
*
* @stability stable
* @category guards
* @since 4.0.0
*/
const isNever = /*#__PURE__*/ makeGuard("Never");
/**
* Narrows an {@link AST} to {@link Literal}.
*
* **When to use**
*
* Use to recognize exact string, number, boolean, or bigint literal AST nodes.
*
* @see {@link Literal} for the AST node type narrowed by this guard
* @see {@link LiteralValue} for the values stored by literal nodes
*
* @stability stable
* @category guards
* @since 3.10.0
*/
const isLiteral = /*#__PURE__*/ makeGuard("Literal");
/**
* Narrows an {@link AST} to {@link UniqueSymbol}.
*
* @stability stable
* @category guards
* @since 3.10.0
*/
const isUniqueSymbol = /*#__PURE__*/ makeGuard("UniqueSymbol");
/**
* Narrows an {@link AST} to {@link Arrays}.
*
* **When to use**
*
* Use to recognize array-like AST nodes before reading their element, rest, or
* mutability metadata.
*
* @see {@link Arrays} for the AST node type narrowed by this guard
*
* @stability stable
* @category guards
* @since 4.0.0
*/
const isArrays = /*#__PURE__*/ makeGuard("Arrays");
/**
* Narrows an {@link AST} to {@link Objects}.
*
* @stability stable
* @category guards
* @since 4.0.0
*/
const isObjects = /*#__PURE__*/ makeGuard("Objects");
/**
* Narrows an {@link AST} to {@link Suspend}.
*
* @stability stable
* @category guards
* @since 3.10.0
*/
const isSuspend = /*#__PURE__*/ makeGuard("Suspend");
/**
* Constructs a {@link Link}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Link = class {
to;
transformation;
constructor(to, transformation) {
this.to = to;
this.transformation = transformation;
}
};
/** @internal */
const defaultParseOptions = {};
/**
* Constructs a {@link Context}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Context = class {
isOptional;
isMutable;
/** Used for constructor default values (e.g. `withConstructorDefault` API) */
constructorDefault;
annotations;
constructor(isOptional, isMutable, constructorDefault = void 0, annotations = void 0) {
this.isOptional = isOptional;
this.isMutable = isMutable;
this.constructorDefault = constructorDefault;
this.annotations = annotations;
}
};
const TypeId$3 = "~effect/Schema";
var ASTNodeImpl = class {
[TypeId$3] = TypeId$3;
annotations;
checks;
encoding;
context;
constructor(annotations = void 0, checks = void 0, encoding = void 0, context = void 0) {
this.annotations = annotations;
this.checks = checks;
this.encoding = encoding;
this.context = context;
}
toString() {
return `<${this._tag}>`;
}
};
/**
* Constructs a {@link Declaration}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Declaration = class extends ASTNodeImpl {
_tag = "Declaration";
typeParameters;
run;
encodingChecks;
/**
* Parser factory {@link flip} swaps in, so a declaration can behave
* differently when encoding. `undefined` reuses `run`.
*/
encodingRun;
constructor(
typeParameters,
run,
annotations,
checks,
encoding,
context,
encodingChecks,
encodingRun,
) {
super(annotations, checks, encoding, context);
this.typeParameters = typeParameters;
this.run = run;
this.encodingChecks = encodingChecks;
this.encodingRun = encodingRun;
}
/** @internal */
getParser() {
let run;
return (input, options) => {
if (input === missing) return missingExit;
return (run ??= this.run(this.typeParameters))(input, this, options);
};
}
_rebuild(recur, checks, encodingChecks, run, encodingRun) {
const tps = mapOrSame(this.typeParameters, recur);
return tps === this.typeParameters &&
checks === this.checks &&
encodingChecks === this.encodingChecks &&
run === this.run &&
encodingRun === this.encodingRun
? this
: new Declaration(
tps,
run,
this.annotations,
checks,
void 0,
this.context,
encodingChecks,
encodingRun,
);
}
/** @internal */
recur(recur) {
return this._rebuild(recur, this.checks, this.encodingChecks, this.run, this.encodingRun);
}
/** @internal */
flip(recur) {
return this._rebuild(
recur,
this.encodingChecks,
this.checks,
this.encodingRun ?? this.run,
this.run,
);
}
/** @internal */
getExpected() {
const expected = this.annotations?.expected;
if (typeof expected === "string") return expected;
return "<Declaration>";
}
};
/**
* Constructs a {@link Null}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Null$1 = class extends ASTNodeImpl {
_tag = "Null";
/** @internal */
getParser() {
return fromConst(this, null);
}
/** @internal */
getExpected() {
return "null";
}
};
const null_ = /*#__PURE__*/ new Null$1();
/**
* Constructs a {@link Unknown}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Unknown = class extends ASTNodeImpl {
_tag = "Unknown";
/** @internal */
getParser() {
return fromRefinement(this, isUnknown);
}
/** @internal */
getExpected() {
return "unknown";
}
};
/**
* Provides the singleton {@link Unknown} AST instance.
*
* **When to use**
*
* Use when you need the reusable AST singleton for a schema node that accepts
* every value while keeping parsed values opaque.
*
* @see {@link any} for the singleton that accepts every value as `any`
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const unknown = /*#__PURE__*/ new Unknown();
/**
* Constructs a {@link Literal}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Literal$1 = class extends ASTNodeImpl {
_tag = "Literal";
literal;
constructor(literal, annotations, checks, encoding, context) {
super(annotations, checks, encoding, context);
if (typeof literal === "number" && !globalThis.Number.isFinite(literal))
throw new Error(`A numeric literal must be finite, got ${format$1(literal)}`);
this.literal = literal;
}
/** @internal */
getParser() {
return fromConst(this, this.literal);
}
/** @internal */
matchPart(s, _options) {
return s === globalThis.String(this.literal) ? this.literal : void 0;
}
/** @internal */
toCodecJson() {
return typeof this.literal === "bigint" ? literalToString(this) : this;
}
/** @internal */
toCodecStringTree() {
return typeof this.literal === "string" ? this : literalToString(this);
}
/** @internal */
getExpected() {
return typeof this.literal === "string"
? JSON.stringify(this.literal)
: globalThis.String(this.literal);
}
};
function literalToString(ast) {
const literalAsString = globalThis.String(ast.literal);
return replaceEncoding(ast, [
new Link(
new Literal$1(literalAsString),
new Transformation(
transform$1(() => ast.literal),
transform$1(() => literalAsString),
),
),
]);
}
/**
* Constructs a {@link String}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const String$2 = class extends ASTNodeImpl {
_tag = "String";
/** @internal */
getParser() {
return fromRefinement(this, isString$1);
}
/** @internal */
matchPart(s, options) {
const checks = this.checks;
return checks && !options.disableChecks && collectIssues(checks, s, void 0, this, options)
? void 0
: s;
}
/** @internal */
getExpected() {
return "string";
}
};
/**
* Provides the singleton {@link String} AST instance.
*
* **When to use**
*
* Use as the shared `SchemaAST` node for unconstrained JavaScript strings.
*
* @see {@link String} for the AST node class
* @see {@link isString} for narrowing an AST to a string node
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const string = /*#__PURE__*/ new String$2();
/**
* Constructs a {@link Number}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Number$2 = class extends ASTNodeImpl {
_tag = "Number";
/** @internal */
getParser() {
return fromRefinement(this, isNumber);
}
/** @internal */
matchKey(s, options) {
return this._match(isStringNumberRegExp, s, options);
}
/** @internal */
matchPart(s, options) {
return this._match(isStringFiniteRegExp, s, options);
}
_match(regexp, s, options) {
if (!regexp.test(s)) return void 0;
const value = globalThis.Number(s);
if (options.disableChecks || !this.checks) return value;
return collectIssues(this.checks, value, void 0, this, options) ? void 0 : value;
}
/** @internal */
toCodecJson() {
if (
this.checks &&
(hasCheck(this.checks, "effect/schema/isFinite") ||
hasCheck(this.checks, "effect/schema/isInt"))
)
return this;
return replaceEncoding(this, [numberToJson]);
}
/** @internal */
toCodecStringTree() {
if (this.toCodecJson() === this) return replaceEncoding(this, [finiteToString]);
return replaceEncoding(this, [numberToString]);
}
/** @internal */
getExpected() {
return "number";
}
};
function hasCheck(checks, id) {
return checks.some(
(check) =>
check.annotations?.representation?.id === id ||
(check._tag === "FilterGroup" && hasCheck(check.checks, id)),
);
}
/**
* Provides the singleton {@link Number} AST instance.
*
* **When to use**
*
* Use when you need the canonical `SchemaAST` node for schemas that accept any
* JavaScript number value.
*
* @see {@link Number} for the AST node class and serialization behavior
* @see {@link Literal} for exact finite numeric literal AST nodes
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const number = /*#__PURE__*/ new Number$2();
/**
* Constructs a {@link Arrays}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Arrays = class extends ASTNodeImpl {
_tag = "Arrays";
isMutable;
elements;
rest;
encodingChecks;
constructor(isMutable, elements, rest, annotations, checks, encoding, context, encodingChecks) {
super(annotations, checks, encoding, context);
this.isMutable = isMutable;
this.elements = elements;
this.rest = rest;
this.encodingChecks = encodingChecks;
let hasOptional = false;
for (let i = 0; i < elements.length; i++)
if (isOptional(elements[i])) hasOptional = true;
else if (hasOptional)
throw new Error("A required element cannot follow an optional element. ts(1257)");
if (hasOptional && rest.length > 1)
throw new Error("A required element cannot follow an optional element. ts(1257)");
for (let i = 1; i < rest.length; i++)
if (isOptional(rest[i]))
throw new Error("An optional element cannot follow a rest element. ts(1266)");
}
/** @internal */
getParser(compile, compileField = compile) {
const ast = this;
let elements;
let rest;
const elementLen = ast.elements.length;
const tailLen = Math.max(0, ast.rest.length - 1);
function getParser(tailThreshold, index) {
if (index < elementLen) return elements[index];
else if (index >= tailThreshold) return rest[index - tailThreshold + 1];
return rest[0];
}
const finish = (state) => {
const { input, len, options } = state;
if (ast.rest.length === 0 && len > elementLen)
for (let i = elementLen; i < len; i++) {
const unexpected = new UnexpectedKey(ast, input[i], options);
const issue = new Pointer([i], unexpected);
if (options.errors === "all") {
if (state.issues) state.issues.push(issue);
else state.issues = [issue];
} else return fail$1(new Composite(ast, [issue], input, options));
}
if (state.issues) return fail$1(new Composite(ast, state.issues, input, options));
return succeed(state.output);
};
const parse = (input, options) => {
const len = input.length;
const state = {
ast,
getParser,
input,
len,
tailThreshold: Math.max(elementLen, len - tailLen),
output: new globalThis.Array(len),
issues: void 0,
options,
};
const end = ast.rest.length === 0 ? elementLen : Math.max(len, elementLen + tailLen);
const concurrency =
options.concurrency === void 0 ? 1 : resolveConcurrency(options.concurrency);
const eff =
concurrency === 1
? parseArray(state, input, 0, end)
: parseArrayConcurrent(state, input, {
concurrency,
end,
});
if (!eff) return finish(state);
if (effectIsExit(eff)) return flatMapEager(eff, () => finish(state));
let first = true;
return suspend(() => {
if (!first) return parse(input, options);
first = false;
return flatMap(eff, () => finish(state));
});
};
return (input, options) => {
if (input === missing) return missingExit;
try {
if (!Array.isArray(input)) return fail$1(new InvalidType(ast, input, options));
if (!elements) {
elements = ast.elements.map((ast) => ({
ast,
parser: compileField(ast),
}));
rest = ast.rest.map((ast) => ({
ast,
parser: compileField(ast),
}));
}
return parse(input, options);
} catch (error) {
return die(error);
}
};
}
_rebuild(recur, checks, encodingChecks) {
const elements = mapOrSame(this.elements, recur);
const rest = mapOrSame(this.rest, recur);
return elements === this.elements &&
rest === this.rest &&
checks === this.checks &&
encodingChecks === this.encodingChecks
? this
: new Arrays(
this.isMutable,
elements,
rest,
this.annotations,
checks,
void 0,
this.context,
encodingChecks,
);
}
/** @internal */
recur(recur) {
return this._rebuild(recur, this.checks, this.encodingChecks);
}
/** @internal */
flip(recur) {
return this._rebuild(recur, this.encodingChecks, this.checks);
}
/** @internal */
getExpected() {
return "array";
}
};
/** @internal */
function stepArray(s, item, exit, i) {
if (exit._tag === "Failure") return wrapPropertyKeyIssue(s, s.ast, i, exit);
const value = exit === sameExit ? item : exit[args];
if (value !== missing) s.output[i] = value;
else {
const p = s.getParser(s.tailThreshold, i);
if (isOptional(p.ast)) return;
const issue = new Pointer([i], new MissingKey(p.ast.context?.annotations));
if (s.options.errors === "all") {
if (s.issues) s.issues.push(issue);
else s.issues = [issue];
} else return fail$2(new Composite(s.ast, [issue], s.input, s.options));
}
}
const parseArrayOptions = {
onItem(s, item, i) {
const value = i < s.len ? item : missing;
return s.getParser(s.tailThreshold, i).parser(value, s.options);
},
step: stepArray,
};
/** @internal */
const parseArray = /*#__PURE__*/ iterateEager()(parseArrayOptions);
const parseArrayConcurrent = /*#__PURE__*/ iterateConcurrent()(parseArrayOptions);
const wrapPropertyKeyIssue = (s, ast, key, exit) => {
if (exit.cause.reasons.length === 0) return exit;
const issue = getSchemaIssue(exit.cause);
if (issue === void 0)
return failCause(
map(
exit.cause,
(issue) => new Composite(ast, [new Pointer([key], issue)], s.input, s.options),
),
);
const pointer = new Pointer([key], issue);
if (s.options.errors === "all") {
if (s.issues) s.issues.push(pointer);
else s.issues = [pointer];
} else return fail$2(new Composite(ast, [pointer], s.input, s.options));
};
/**
* floating point or integer, with optional exponent
* @internal
*/
const FINITE_PATTERN = "[+-]?\\d*\\.?\\d+(?:[Ee][+-]?\\d+)?";
/**
* Returns the object keys that match the index signature parameter schema.
* @internal
*/
function getIndexSignatureKeys(input, parameter, options = defaultParseOptions) {
let stringKeys;
let symbolKeys;
function go(parameter) {
switch (parameter._tag) {
case "String":
case "TemplateLiteral":
return (stringKeys ??= Object.keys(input)).filter(
(k) => parameter.matchPart(k, options) !== void 0,
);
case "Number":
return (stringKeys ??= Object.keys(input)).filter(
(k) => parameter.matchKey(k, options) !== void 0,
);
case "Symbol":
return (symbolKeys ??= Object.getOwnPropertySymbols(input)).filter(
(k) =>
Object.prototype.propertyIsEnumerable.call(input, k) &&
parameter.matchKey(k, options) !== void 0,
);
case "Union":
return [...new Set(parameter.types.flatMap(go))];
default:
return [];
}
}
return go(parameterFromPropertyKey(toEncoded(parameter)));
}
/**
* Constructs a {@link PropertySignature}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const PropertySignature = class {
name;
type;
constructor(name, type) {
this.name = name;
this.type = type;
}
};
function isIndexSignatureParameterSide(ast) {
switch (ast._tag) {
case "String":
case "Number":
case "Symbol":
case "TemplateLiteral":
return true;
case "Union":
return ast.types.every(isIndexSignatureParameterSide);
default:
return false;
}
}
function isIndexSignatureParameterEncodedSide(ast) {
const encoded = getLastEncoding(ast);
switch (encoded._tag) {
case "String":
case "Number":
case "Symbol":
case "TemplateLiteral":
return true;
case "Union":
return encoded.types.every(isIndexSignatureParameterEncodedSide);
default:
return false;
}
}
function isIndexSignatureParameter(ast) {
return isIndexSignatureParameterSide(ast) && isIndexSignatureParameterEncodedSide(ast);
}
/**
* Constructs a {@link IndexSignature}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const IndexSignature = class {
parameter;
type;
constructor(parameter, type) {
if (!isIndexSignatureParameter(parameter))
throw new Error(`Invalid index signature parameter ${parameter._tag}`);
this.parameter = parameter;
this.type = type;
if (isOptional(type) && !containsUndefined(type))
throw new Error(
"Cannot use `Schema.optionalKey` with index signatures, use `Schema.optional` instead.",
);
}
};
/**
* Constructs a {@link Objects}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Objects = class extends ASTNodeImpl {
_tag = "Objects";
propertySignatures;
indexSignatures;
encodingChecks;
constructor(
propertySignatures,
indexSignatures,
annotations,
checks,
encoding,
context,
encodingChecks,
) {
super(annotations, checks, encoding, context);
this.propertySignatures = propertySignatures;
this.indexSignatures = indexSignatures;
this.encodingChecks = encodingChecks;
}
/** @internal */
getParser(compile, compileField = compile) {
const ast = this;
const hasProperties = ast.propertySignatures.length;
const indexCount = ast.indexSignatures.length;
if (!hasProperties && !indexCount) return fromRefinement(ast, isNotNullish);
let properties;
let indexes;
const compileMembers = () => {
if (!properties) {
properties = ast.propertySignatures.map((ps) => ({
parser: compileField(ps.type),
name: ps.name,
type: ps.type,
}));
indexes = indexCount
? ast.indexSignatures.map((is) => ({
is,
parserKey: compile(parameterFromPropertyKey(is.parameter)),
parserValue: compileField(is.type),
}))
: void 0;
}
return properties;
};
const makeFallback = () => {
const expectedKeys = new Set(
ast.propertySignatures.map((ps) =>
typeof ps.name === "number" ? globalThis.String(ps.name) : ps.name,
),
);
const finishIndex = (s, key, k2, inputValue, exitValue) => {
if (exitValue._tag === "Failure")
return wrapPropertyKeyIssue(s, ast, key, exitValue) ?? void_;
const value = exitValue === sameExit ? inputValue : exitValue[args];
if (k2 !== missing && value !== missing) {
if (
hasProperties &&
(expectedKeys.has(key) ||
expectedKeys.has(typeof k2 === "number" ? globalThis.String(k2) : k2))
)
return void_;
assignProperty(s.out, k2, value);
}
return void_;
};
const parseIndex = (s, key, index, exitKey) => {
if (!exitKey) {
const eff = index.parserKey(key, s.options);
if (!effectIsExit(eff))
return flatMap(exit(eff), (exit) => parseIndex(s, key, index, exit));
exitKey = eff;
}
if (exitKey._tag === "Failure") return wrapPropertyKeyIssue(s, ast, key, exitKey) ?? void_;
const k2 = exitKey === sameExit ? key : exitKey[args];
const inputValue = s.input[key];
const result = index.parserValue(inputValue, s.options);
return effectIsExit(result)
? finishIndex(s, key, k2, inputValue, result)
: flatMap(exit(result), (exit) => finishIndex(s, key, k2, inputValue, exit));
};
const parseStringIndex = (s, key, index) => {
const inputValue = s.input[key];
const result = index.parserValue(inputValue, s.options);
return effectIsExit(result)
? finishIndex(s, key, key, inputValue, result)
: flatMap(exit(result), (exit) => finishIndex(s, key, key, inputValue, exit));
};
const parseIndexes = indexCount
? iterateConcurrent()({
onItem: (s, [key, index]) =>
index.is.parameter === string
? parseStringIndex(s, key, index)
: parseIndex(s, key, index),
step: (_s, _item, exit) => (exit._tag === "Failure" ? exit : void 0),
})
: void 0;
return fnUntracedEager(function* (input, options) {
if (input === missing) return missing;
if (!(typeof input === "object" && input !== null && !Array.isArray(input)))
return yield* fail$1(new InvalidType(ast, input, options));
compileMembers();
const record = input;
const out = {};
const state = {
ast,
input: record,
out,
issues: void 0,
options,
};
const errorsAllOption = options.errors === "all";
const onExcessPropertyError = options.onExcessProperty === "error";
const concurrency =
options.concurrency === void 0 ? 1 : resolveConcurrency(options.concurrency);
const indexKeys =
indexCount && onExcessPropertyError
? ast.indexSignatures.map((index) =>
getIndexSignatureKeys(record, index.parameter, options),
)
: void 0;
if (onExcessPropertyError) {
const coveredKeys = indexKeys ? new Set(expectedKeys) : expectedKeys;
if (indexKeys) for (const keys of indexKeys) for (const key of keys) coveredKeys.add(key);
const inputKeys = Reflect.ownKeys(record);
for (let i = 0; i < inputKeys.length; i++) {
const key = inputKeys[i];
if (!coveredKeys.has(key) && Object.prototype.propertyIsEnumerable.call(record, key)) {
const unexpected = new UnexpectedKey(ast, record[key], options);
const issue = new Pointer([key], unexpected);
if (errorsAllOption) {
if (state.issues) state.issues.push(issue);
else state.issues = [issue];
continue;
} else return yield* fail$1(new Composite(ast, [issue], input, options));
}
}
}
if (hasProperties) {
const eff =
concurrency === 1
? parseProperties(state, properties)
: parsePropertiesConcurrent(state, properties, { concurrency });
if (eff) yield* eff;
}
if (indexCount && concurrency === 1)
for (let i = 0; i < indexCount; i++) {
const index = indexes[i];
const parse = index.is.parameter === string ? parseStringIndex : parseIndex;
const keys =
indexKeys?.[i] ??
(index.is.parameter === string
? Object.keys(record)
: getIndexSignatureKeys(record, index.is.parameter, options));
for (let j = 0; j < keys.length; j++) {
const eff = parse(state, keys[j], index);
if (!effectIsExit(eff)) yield* eff;
else if (eff._tag === "Failure") return yield* eff;
}
}
else if (parseIndexes) {
const keyPairs = empty$1();
for (let i = 0; i < indexCount; i++) {
const index = indexes[i];
const keys =
indexKeys?.[i] ??
(index.is.parameter === string
? Object.keys(record)
: getIndexSignatureKeys(record, index.is.parameter, options));
for (let j = 0; j < keys.length; j++) keyPairs.push([keys[j], index]);
}
const eff = parseIndexes(state, keyPairs, { concurrency });
if (eff) yield* eff;
}
if (state.issues) return yield* fail$1(new Composite(ast, state.issues, input, options));
return out;
});
};
if (indexCount) return makeFallback();
let fallback;
const resume = (state, index, pending) => {
const property = properties[index];
return flatMap(exit(pending), (exit) => {
const terminal = stepProperty(state, property, exit);
if (terminal) return terminal;
const done = () => succeed(state.out);
const eff = parseProperties(state, properties.slice(index + 1));
return eff ? flatMapEager(eff, done) : done();
});
};
return (input, options) => {
if (input === missing) return missingExit;
if (
options.errors === "all" ||
options.onExcessProperty !== void 0 ||
(options.concurrency !== void 0 && resolveConcurrency(options.concurrency) !== 1)
)
return (fallback ??= makeFallback())(input, options);
if (!(typeof input === "object" && input !== null && !Array.isArray(input)))
return fail$1(new InvalidType(ast, input, options));
const props = compileMembers();
const record = input;
const out = {};
const state = {
ast,
input: record,
out,
issues: void 0,
options,
};
try {
for (let index = 0; index < props.length; index++) {
const property = props[index];
const name = property.name;
const hasKey = hasPropertySignature(record, name);
const value = hasKey ? record[name] : missing;
const exit = property.parser(value, options);
if (!effectIsExit(exit)) return resume(state, index, exit);
if (exit === sameExit) {
if (hasKey) assignProperty(out, name, value);
continue;
}
const terminal = stepProperty(state, property, exit);
if (terminal) return terminal;
}
} catch (error) {
return die(error);
}
return succeed(out);
};
}
_rebuild(recur, recurParameter, checks, encodingChecks) {
const props = mapOrSame(this.propertySignatures, (ps) => {
const t = recur(ps.type);
return t === ps.type ? ps : new PropertySignature(ps.name, t);
});
const indexes = mapOrSame(this.indexSignatures, (is) => {
const p = recurParameter(is.parameter);
const t = recur(is.type);
return p === is.parameter && t === is.type ? is : new IndexSignature(p, t);
});
return props === this.propertySignatures &&
indexes === this.indexSignatures &&
checks === this.checks &&
encodingChecks === this.encodingChecks
? this
: new Objects(props, indexes, this.annotations, checks, void 0, this.context, encodingChecks);
}
/** @internal */
flip(recur) {
return this._rebuild(recur, recur, this.encodingChecks, this.checks);
}
/** @internal */
recur(recur, recurParameter = recur) {
return this._rebuild(recur, recurParameter, this.checks, this.encodingChecks);
}
/** @internal */
getExpected() {
if (this.propertySignatures.length === 0 && this.indexSignatures.length === 0)
return "object | array";
return "object";
}
};
/** @internal */
function stepProperty(s, p, exit) {
if (exit._tag === "Failure") return wrapPropertyKeyIssue(s, s.ast, p.name, exit);
if (exit === sameExit) return;
const value = exit[args];
if (value !== missing) {
assignProperty(s.out, p.name, value);
return;
}
delete s.out[p.name];
if (!isOptional(p.type)) {
const issue = new Pointer([p.name], new MissingKey(p.type.context?.annotations));
if (s.options.errors === "all") {
if (s.issues) s.issues.push(issue);
else s.issues = [issue];
return;
} else return fail$2(new Composite(s.ast, [issue], s.input, s.options));
}
}
const parsePropertiesOptions = {
onItem(s, p) {
if (!hasPropertySignature(s.input, p.name)) return p.parser(missing, s.options);
const value = s.input[p.name];
assignProperty(s.out, p.name, value);
return p.parser(value, s.options);
},
step: stepProperty,
};
/** @internal */
const parseProperties = /*#__PURE__*/ iterateEager()(parsePropertiesOptions);
const parsePropertiesConcurrent = /*#__PURE__*/ iterateConcurrent()(parsePropertiesOptions);
function combineChecks(a, b) {
if (!a) return b;
if (!b) return a;
return [...a, ...b];
}
/** @internal */
function struct(fields, checks, annotations) {
return new Objects(
Reflect.ownKeys(fields).map((key) => {
return new PropertySignature(key, fields[key].ast);
}),
[],
annotations,
checks,
);
}
/** @internal */
function getAST(self) {
return self.ast;
}
/** @internal */
function union(members, options, checks) {
return new Union$1(members.map(getAST), options, void 0, checks);
}
/** @internal */
function mutable$1(ast) {
if (ast.encoding) throw new Error("mutable does not support encodings");
return new Arrays(
true,
ast.elements,
ast.rest,
ast.annotations,
ast.checks,
void 0,
ast.context,
ast.encodingChecks,
);
}
const toCandidate = /*#__PURE__*/ memoizeIdempotent((ast) => {
while (true) {
if (isSuspend(ast)) return unknown;
const encoding = ast.encoding;
if (!encoding) return ast.recur?.(toCandidate, identity) ?? ast;
if (
encoding.some(
(link) =>
link.transformation._tag === "Middleware" && link.transformation.decode !== identity,
)
)
return unknown;
ast = encoding[encoding.length - 1].to;
}
});
function getCandidateTypes(ast) {
switch (ast._tag) {
case "Null":
return ["null"];
case "Undefined":
return ["undefined"];
case "String":
case "TemplateLiteral":
return ["string"];
case "Number":
return ["number"];
case "Boolean":
return ["boolean"];
case "Symbol":
case "UniqueSymbol":
return ["symbol"];
case "BigInt":
return ["bigint"];
case "Arrays":
return ["array"];
case "ObjectKeyword":
return ["object", "array", "function"];
case "Objects":
return ast.propertySignatures.length || ast.indexSignatures.length
? ["object"]
: ["string", "number", "boolean", "symbol", "bigint", "object", "array", "function"];
case "Enum":
return Array.from(new Set(ast.enums.map(([, v]) => typeof v)));
case "Literal":
return [typeof ast.literal];
case "Union":
return Array.from(new Set(ast.types.flatMap(getCandidateTypes)));
default:
return [
"null",
"undefined",
"string",
"number",
"boolean",
"symbol",
"bigint",
"object",
"array",
"function",
];
}
}
/** @internal */
function collectSentinels(ast) {
switch (ast._tag) {
default:
return [];
case "Declaration": {
const s = ast.annotations?.[SENTINELS_ANNOTATION_KEY];
return Array.isArray(s) ? s : [];
}
case "Objects":
return ast.propertySignatures.flatMap((ps) => {
const type = ps.type;
if (!isOptional(type)) {
if (isLiteral(type))
return [
{
key: ps.name,
literal: type.literal,
},
];
if (isUniqueSymbol(type))
return [
{
key: ps.name,
literal: type.symbol,
},
];
}
return [];
});
case "Arrays":
return ast.elements.flatMap((e, i) => {
if (!isOptional(e)) {
if (isLiteral(e))
return [
{
key: i,
literal: e.literal,
},
];
if (isUniqueSymbol(e))
return [
{
key: i,
literal: e.symbol,
},
];
}
return [];
});
case "Union": {
if (ast.types.length === 0) return [];
const members = ast.types.map((type) => collectSentinels(toCandidate(type)));
return members[0].filter((s) =>
members.every((sentinels) =>
sentinels.some((o) => o.key === s.key && o.literal === s.literal),
),
);
}
case "Suspend":
return collectSentinels(ast.thunk());
}
}
const candidateIndexCache = /*#__PURE__*/ new WeakMap();
const emptyCandidates = /*#__PURE__*/ Object.freeze([]);
const getRuntimeType = (input) =>
input === null ? "null" : Array.isArray(input) ? "array" : typeof input;
const hasPropertySignature = (input, key) =>
key === "__proto__" ? Object.hasOwn(input, key) : key in input;
/** @internal */
function getCandidateIndex(types) {
let index = candidateIndexCache.get(types);
if (index) return index;
let bySentinel;
let sentinelCandidateCount = 0;
let otherwise;
let literalCandidates;
let onlyLiterals = true;
const literalOf = [];
for (let i = 0; i < types.length; i++) {
const a = types[i];
const encoded = toCandidate(a);
if (isNever(encoded)) continue;
if (isLiteral(encoded) || isUniqueSymbol(encoded)) {
literalCandidates ??= /* @__PURE__ */ new Map();
const literal = isLiteral(encoded) ? encoded.literal : encoded.symbol;
literalOf[i] = literal;
let arr = literalCandidates.get(literal);
if (!arr) literalCandidates.set(literal, (arr = []));
arr.push(i);
} else onlyLiterals = false;
const sentinels = collectSentinels(encoded);
if (sentinels.length) {
bySentinel ??= /* @__PURE__ */ new Map();
sentinelCandidateCount++;
for (const { key, literal } of sentinels) {
let entry = bySentinel.get(key);
if (!entry)
bySentinel.set(key, (entry = [/* @__PURE__ */ new Map(), /* @__PURE__ */ new Set()]));
entry[1].add(i);
let indexes = entry[0].get(literal);
if (!indexes) entry[0].set(literal, (indexes = /* @__PURE__ */ new Set()));
indexes.add(i);
}
} else {
otherwise ??= {};
const candidateTypes = getCandidateTypes(encoded);
for (const t of candidateTypes) (otherwise[t] ??= []).push(i);
}
}
const fallbacks = {};
const getFallback = (type) =>
(fallbacks[type] ??= Object.freeze(otherwise?.[type] ?? emptyCandidates));
if (onlyLiterals && literalCandidates) {
literalCandidates.forEach(Object.freeze);
index = (input) => literalCandidates.get(input) ?? emptyCandidates;
} else if (bySentinel?.size === 1 && !otherwise) {
const [key, [byValue]] = bySentinel.entries().next().value;
const candidates = /* @__PURE__ */ new Map();
for (const [literal, indexes] of byValue)
candidates.set(literal, Object.freeze(Array.from(indexes)));
const all = Object.freeze(types.map((_, i) => i));
index = (input, isConstructor) => {
if (isObjectKeyword(input)) {
const value = hasPropertySignature(input, key) ? input[key] : void 0;
if (value !== void 0) return candidates.get(value) ?? emptyCandidates;
if (isConstructor) return all;
}
return emptyCandidates;
};
} else if (bySentinel) {
let commonSentinel;
for (const entry of bySentinel)
if (
(!commonSentinel || entry[1][0].size > commonSentinel[1][0].size) &&
entry[1][1].size === sentinelCandidateCount
)
commonSentinel = entry;
index = (input, isConstructor) => {
const runtimeType = getRuntimeType(input);
if (!isObjectKeyword(input)) return getFallback(runtimeType);
const selected = new Set(otherwise?.[runtimeType]);
let directKey;
if (commonSentinel) {
const [key, [byValue]] = commonSentinel;
const hasKey = hasPropertySignature(input, key);
const value = hasKey ? input[key] : void 0;
if (hasKey && (!isConstructor || value !== void 0)) {
const match = byValue.get(value);
if (!match) return getFallback(runtimeType);
for (const i of match) selected.add(i);
directKey = key;
}
}
if (directKey === void 0)
for (const [key, [byValue, all]] of bySentinel) {
const hasKey = hasPropertySignature(input, key);
const value = hasKey ? input[key] : void 0;
if (hasKey && (!isConstructor || value !== void 0)) {
const match = byValue.get(value);
if (match) for (const i of match) selected.add(i);
} else if (isConstructor) for (const i of all) selected.add(i);
}
for (const [key, [byValue, all]] of bySentinel) {
if (key === directKey) continue;
const hasKey = hasPropertySignature(input, key);
const value = hasKey ? input[key] : void 0;
if (hasKey && (!isConstructor || value !== void 0)) {
const match = byValue.get(value);
for (const i of selected) if (all.has(i) && !match?.has(i)) selected.delete(i);
}
}
return Array.from(selected).sort((a, b) => a - b);
};
} else
index = (input) => {
const fallback = getFallback(getRuntimeType(input));
return literalCandidates
? fallback.filter((i) => literalOf[i] === void 0 || literalOf[i] === input)
: fallback;
};
candidateIndexCache.set(types, index);
return index;
}
/**
* Constructs a {@link Union}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Union$1 = class extends ASTNodeImpl {
_tag = "Union";
types;
options;
encodingChecks;
constructor(types, options, annotations, checks, encoding, context, encodingChecks) {
super(annotations, checks, encoding, context);
this.types = types;
this.options = options;
this.encodingChecks = encodingChecks;
}
/** @internal */
getParser(compile, compileField) {
const ast = this;
const isConstructor = compileField !== void 0;
const parsers = [];
const parser = (i) => (parsers[i] ??= compile(ast.types[i]));
let index;
return (input, options) => {
if (input === missing) return missingExit;
const candidates = (index ??= getCandidateIndex(ast.types))(input, isConstructor);
if (candidates.length === 0) return fail$1(new AnyOf(ast, [], input, options));
if (candidates.length === 1) {
const result = parser(candidates[0])(input, options);
if (result._tag === "Success") return result;
return effectIsExit(result)
? failSingleUnionCandidate(ast, result.cause, input, options)
: catchSingleUnionCandidate(ast, result, input, options);
}
return parseUnionCandidates(ast, parser, candidates, input, options);
};
}
_rebuild(recur, checks, encodingChecks) {
const types = mapOrSame(this.types, recur);
return types === this.types && checks === this.checks && encodingChecks === this.encodingChecks
? this
: new Union$1(
types,
this.options,
this.annotations,
checks,
void 0,
this.context,
encodingChecks,
);
}
/** @internal */
recur(recur) {
return this._rebuild(recur, this.checks, this.encodingChecks);
}
/** @internal */
flip(recur) {
return this._rebuild(recur, this.encodingChecks, this.checks);
}
/** @internal */
matchPart(s, options) {
for (const type of this.types) {
const out = type.matchPart(s, options);
if (out !== void 0) return out;
}
}
/** @internal */
getExpected(getExpected) {
const expected = this.annotations?.expected;
if (typeof expected === "string") return expected;
if (this.types.length === 0) return "never";
const types = this.types.map((type) => {
const encoded = toEncoded(type);
switch (encoded._tag) {
case "Arrays": {
const literals = encoded.elements.filter(isLiteral);
if (literals.length > 0)
return `${formatIsMutable(encoded.isMutable)}[ ${literals.map((e) => getExpected(e) + formatIsOptional(e.context?.isOptional)).join(", ")}, ... ]`;
break;
}
case "Objects": {
const literals = encoded.propertySignatures.filter((ps) => isLiteral(ps.type));
if (literals.length > 0)
return `{ ${literals.map((ps) => `${formatIsMutable(ps.type.context?.isMutable)}${formatPropertyKey(ps.name)}${formatIsOptional(ps.type.context?.isOptional)}: ${getExpected(ps.type)}`).join(", ")}, ... }`;
break;
}
}
return getExpected(encoded);
});
return Array.from(new Set(types)).join(" | ");
}
};
function failSingleUnionCandidate(ast, cause, input, options) {
const issue = getSchemaIssue(cause);
if (!issue) return failCause(cause);
return fail$2(new AnyOf(ast, [issue], input, options));
}
function catchSingleUnionCandidate(ast, result, input, options) {
return catchCause(result, (cause) => failSingleUnionCandidate(ast, cause, input, options));
}
function parseUnionCandidates(ast, parser, candidates, input, options) {
const state = {
ast,
parser,
input,
out: void 0,
successes: ast.options?.mode === "oneOf" ? [] : void 0,
issues: void 0,
options,
};
const eff = parseUnion(state, candidates);
if (!eff) {
if (state.out) return state.out;
return fail$1(new AnyOf(ast, state.issues ?? [], input, options));
}
if (effectIsExit(eff)) return resumeUnion(eff, state);
let first = true;
return suspend(() => {
if (!first) return parseUnionCandidates(ast, parser, candidates, input, options);
first = false;
return resumeUnion(eff, state);
});
}
function resumeUnion(eff, state) {
return flatMapEager(eff, (_) => {
if (state.out === sameExit) return succeed$1(state.input);
if (state.out) return state.out;
return fail$1(new AnyOf(state.ast, state.issues ?? [], state.input, state.options));
});
}
const parseUnion = /*#__PURE__*/ iterateEager()({
onItem(s, i) {
return s.parser(i)(s.input, s.options);
},
step(s, i, exit) {
if (exit._tag === "Failure") {
const issue = getSchemaIssue(exit.cause);
if (issue === void 0) return exit;
if (s.issues) s.issues.push(issue);
else s.issues = [issue];
} else {
if (s.out && s.successes) {
s.successes.push(s.ast.types[i]);
return fail$2(new OneOf(s.ast, s.successes, s.input, s.options));
}
s.out = exit;
if (s.successes) s.successes.push(s.ast.types[i]);
else return void_;
}
},
});
const nonFiniteLiterals = /*#__PURE__*/ new Union$1([
/*#__PURE__*/ new Literal$1("Infinity"),
/*#__PURE__*/ new Literal$1("-Infinity"),
/*#__PURE__*/ new Literal$1("NaN"),
]);
function formatIsMutable(isMutable) {
return isMutable ? "" : "readonly ";
}
function formatIsOptional(isOptional) {
return isOptional ? "?" : "";
}
/**
* Constructs a {@link Filter}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const Filter = class extends Class$1 {
_tag = "Filter";
run;
annotations;
/**
* Whether the parsing process should be aborted after this check has failed.
*/
aborted;
constructor(run, annotations = void 0, aborted = false) {
super();
this.run = run;
this.annotations = annotations;
this.aborted = aborted;
}
annotate(annotations) {
return new Filter(
this.run,
{
...this.annotations,
...annotations,
},
this.aborted,
);
}
abort() {
return new Filter(this.run, this.annotations, true);
}
and(other, annotations) {
return new FilterGroup([this, other], annotations);
}
};
/**
* Constructs a {@link FilterGroup}.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const FilterGroup = class extends Class$1 {
_tag = "FilterGroup";
checks;
annotations;
constructor(checks, annotations = void 0) {
super();
this.checks = checks;
this.annotations = annotations;
}
annotate(annotations) {
return new FilterGroup(this.checks, {
...this.annotations,
...annotations,
});
}
and(other, annotations) {
return new FilterGroup([this, other], annotations);
}
};
/** @internal */
function makeFilter$1(filter, annotations, aborted = false) {
return new Filter(
(input, ast, options) =>
normalizeFilterOutput(ast, filter(input, ast, options), input, options),
annotations,
aborted,
);
}
/** @internal */
function isFinite(annotations) {
return makeFilter$1((n) => globalThis.Number.isFinite(n), {
expected: "a finite number",
representation: {
id: "effect/schema/isFinite",
payload: null,
},
toJsonSchema: () => ({ type: "number" }),
toCode: () => ({ runtime: "Schema.isFinite()" }),
arbitraryConstraint: { number: "finite" },
...annotations,
});
}
const numberToJson = /*#__PURE__*/ new Link(
/*#__PURE__*/ new Union$1([
/* @__PURE__ */ appendChecks(number, [/*#__PURE__*/ isFinite()]),
nonFiniteLiterals,
]),
/*#__PURE__*/ new Transformation(
/*#__PURE__*/ Number$3(),
/*#__PURE__*/ transform$1((n) => (globalThis.Number.isFinite(n) ? n : globalThis.String(n))),
),
);
/**
* Creates a {@link Filter} that validates strings by running `RegExp.test`.
*
* **When to use**
*
* Use when string validation should be represented as a schema `Filter` backed
* by a regular expression.
*
* **Details**
*
* The filter can be used with `Schema.filter` or attached directly to a
* `String` AST node through checks. The regular expression is cloned and its
* `lastIndex` is reset before each test, so global and sticky expressions are
* deterministic and the provided regular expression is not mutated. The
* regular expression source is stored in annotations for serialization and
* arbitrary generation.
*
* **Gotchas**
*
* Arbitrary metadata preserves both `regExp.source` and `regExp.flags`.
* Implementations that cannot consume all flags may still use the source as a
* generation hint because the Schema filter validates every generated value.
* JSON Schema has no way to carry JavaScript regular-expression flags. Unless
* annotations provide `toJsonSchema`, the RegExp constraint is omitted from
* JSON Schema export.
*
* **Example** (Validating an email pattern)
*
* ```ts import.meta.vitest
* import { SchemaAST } from "effect"
*
* const emailFilter = SchemaAST.isPattern(/^[^@]+@[^@]+$/)
* emailFilter.run("alice@example.com", SchemaAST.string, {}) // => undefined
* emailFilter.run("invalid", SchemaAST.string, {})?._tag // => "InvalidValue"
* ```
*
* @see {@link Filter}
* @stability stable
* @category constructors
* @since 4.0.0
*/
function isPattern$1(regExp, annotations) {
const copy = new globalThis.RegExp(regExp);
const payload = {
source: copy.source,
flags: copy.flags,
};
return makeFilter$1(
(s) => {
copy.lastIndex = 0;
return copy.test(s);
},
{
expected: `a string matching the RegExp ${payload.source}`,
representation: {
id: "effect/schema/isPattern",
payload,
},
toJsonSchema: () => [{}, true],
arbitraryConstraint: { patterns: [payload] },
...annotations,
},
);
}
const bodyOwners = /*#__PURE__*/ new WeakMap();
function copy(ast, changes) {
const out = Object.assign(Object.create(Object.getPrototypeOf(ast)), ast, changes);
if (Reflect.ownKeys(changes).every((key) => key === "context" || key === "encoding"))
bodyOwners.set(out, getContextOwner(ast));
return out;
}
/** @internal */
function getContextOwner(ast) {
const existing = bodyOwners.get(ast);
if (existing !== void 0) return existing;
if (ast.encoding === void 0) return ast;
const owner = Object.assign(Object.create(Object.getPrototypeOf(ast)), ast, { encoding: void 0 });
bodyOwners.set(ast, owner);
return owner;
}
/** @internal */
function replaceEncoding(ast, encoding) {
return ast.encoding === encoding ? ast : copy(ast, { encoding });
}
/** @internal */
function replaceContext(ast, context) {
if (ast.context === context) return ast;
const owner = getContextOwner(ast);
if (owner.context === context && owner.encoding === ast.encoding) return owner;
return copy(ast, { context });
}
/** @internal */
function getLastEncoding(ast) {
return ast.encoding ? getLastEncoding(ast.encoding[ast.encoding.length - 1].to) : ast;
}
/** @internal */
function annotate(ast, annotations) {
if (ast.checks) {
const last = ast.checks[ast.checks.length - 1];
return replaceChecks(ast, append(ast.checks.slice(0, -1), last.annotate(annotations)));
}
return copy(ast, {
annotations: {
...ast.annotations,
...annotations,
},
});
}
/** @internal */
function replaceChecks(ast, checks) {
if (ast._tag === "Suspend" && checks) throw new Error("Cannot add checks to Suspend");
if (ast.checks === checks) return ast;
return copy(ast, { checks });
}
/** @internal */
function appendChecks(ast, checks) {
return replaceChecks(ast, combineChecks(ast.checks, checks));
}
/** @internal */
function mapLink(link, f) {
const to = f(link.to);
return to === link.to ? link : new Link(to, link.transformation);
}
function updateLastLink(encoding, f) {
const links = encoding;
const last = links[links.length - 1];
const out = mapLink(last, f);
return out === last ? encoding : append(encoding.slice(0, encoding.length - 1), out);
}
/** @internal */
function applyToSelfOrLastLinkEncodingIdempotent(f, options) {
function out(ast) {
if (ast.encoding) {
const last = ast.encoding[ast.encoding.length - 1];
return options?.stopAt?.(last)
? ast
: replaceEncoding(ast, updateLastLink(ast.encoding, out));
}
return f(ast);
}
return memoizeIdempotent(out);
}
function appendTransformation(from, transformation, to) {
const link = new Link(from, transformation);
return replaceEncoding(to, to.encoding ? [...to.encoding, link] : [link]);
}
function mapOrSame(as, f) {
let out;
for (let i = 0; i < as.length; i++) {
const a = as[i];
const fa = f(a);
if (out) out[i] = fa;
else if (fa !== a) {
out = new Array(as.length);
for (let j = 0; j < i; j++) out[j] = as[j];
out[i] = fa;
}
}
return out ?? as;
}
/** @internal */
function annotateKey(ast, annotations) {
return replaceContext(
ast,
ast.context
? new Context(ast.context.isOptional, ast.context.isMutable, ast.context.constructorDefault, {
...ast.context.annotations,
...annotations,
})
: new Context(false, false, void 0, annotations),
);
}
/**
* Attaches a `Transformation` to the `to` AST, making it decode from the
* `from` AST and encode back to it.
*
* **Details**
*
* This is the low-level primitive behind `Schema.decodeTo`. It appends a
* {@link Link} to the `to` node's encoding chain.
*
* - Returns a new AST with the same type as `to`.
*
* @see {@link Link}
* @see {@link Encoding}
* @see {@link flip}
* @stability stable
* @category transforming
* @since 4.0.0
*/
function decodeTo$1(from, to, transformation) {
return appendTransformation(from, transformation, to);
}
/**
* Returns `true` if the AST node represents an optional property.
*
* **Details**
*
* Checks `ast.context?.isOptional`. Defaults to `false` when no
* {@link Context} is set.
*
* @see `Schema.optionalKey`
* @see {@link Context}
* @stability stable
* @category predicates
* @since 4.0.0
*/
function isOptional(ast) {
return ast.context?.isOptional ?? false;
}
function isStructuralCheck(check) {
return (
check.annotations?.["~structural"] === true ||
(check._tag === "FilterGroup" && check.checks.every(isStructuralCheck))
);
}
function extractStructuralChecks(checks) {
function extract(check) {
if (isStructuralCheck(check)) return [check];
return check._tag === "FilterGroup" ? check.checks.flatMap(extract) : [];
}
const out = checks.flatMap(extract);
return isArrayNonEmpty(out) ? out : void 0;
}
function canPreserveEncodingChecks(ast) {
let preserve = true;
function visit(child) {
preserve = preserve && !child.encoding && !isSuspend(child);
if (preserve && "recur" in child) child.recur(visit);
return child;
}
if ("recur" in ast) ast.recur(visit);
return preserve;
}
/**
* Strips all encoding transformations from an AST, returning the decoded
* (type-level) representation.
*
* **Details**
*
* - Memoized: same input reference → same output reference.
* - Recursively walks into composite nodes ({@link Arrays}, {@link Objects},
* {@link Union}, {@link Suspend}).
*
* **Example** (Getting the type AST)
*
* ```ts import.meta.vitest
* import { Schema, SchemaAST } from "effect"
*
* const schema = Schema.NumberFromString
* const typeAst = SchemaAST.toType(schema.ast)
* typeAst._tag // => "Number"
* ```
*
* @see {@link toEncoded}
* @see {@link flip}
* @stability stable
* @category transforming
* @since 4.0.0
*/
const toType = /*#__PURE__*/ memoizeIdempotent((ast) => {
const owner = getContextOwner(ast);
if (owner !== ast) {
const type = toType(owner);
return type === owner && ast.encoding === void 0 ? ast : replaceContext(type, ast.context);
}
const type = "recur" in ast ? ast.recur(toType) : ast;
if ("encodingChecks" in type && type.encodingChecks) {
const checks = canPreserveEncodingChecks(ast)
? type.encodingChecks
: isArrays(type) || isObjects(type) || (isDeclaration(type) && type.typeParameters.length > 0)
? extractStructuralChecks(type.encodingChecks)
: void 0;
return copy(type, {
encodingChecks: void 0,
checks: combineChecks(type.checks, checks),
});
}
return type;
});
/**
* Returns the encoded (wire-format) AST by flipping and then stripping
* encodings.
*
* **Details**
*
* Equivalent to `toType(flip(ast))`. This gives you the AST that describes
* the shape of the serialized/encoded data.
*
* - Memoized: same input reference → same output reference.
*
* **Example** (Getting the encoded AST)
*
* ```ts import.meta.vitest
* import { Schema, SchemaAST } from "effect"
*
* const schema = Schema.NumberFromString
* const encodedAst = SchemaAST.toEncoded(schema.ast)
* encodedAst._tag // => "String"
* ```
*
* @see {@link toType}
* @see {@link flip}
* @stability stable
* @category transforming
* @since 4.0.0
*/
const toEncoded = /*#__PURE__*/ memoizeIdempotent((ast) => {
return toType(flip(ast));
});
function flipEncoding(ast, encoding) {
const links = encoding;
const len = links.length;
const last = links[len - 1];
const ls = [new Link(flip(replaceEncoding(ast, void 0)), links[0].transformation.flip())];
for (let i = 1; i < len; i++)
ls.unshift(new Link(flip(links[i - 1].to), links[i].transformation.flip()));
const to = flip(last.to);
if (to.encoding) return replaceEncoding(to, [...to.encoding, ...ls]);
else return replaceEncoding(to, ls);
}
/**
* Swaps the decode and encode directions of an AST's {@link Encoding} chain.
*
* **Details**
*
* After flipping, what was decoding becomes encoding and vice versa. This is
* the core operation behind `Schema.encode` — encoding a value is decoding
* with a flipped SchemaAST.
*
* - Memoized: same input reference → same output reference.
* - Recursively walks composite nodes.
*
* @see {@link toType}
* @see {@link toEncoded}
* @stability stable
* @category transforming
* @since 4.0.0
*/
const flip = /*#__PURE__*/ memoize((ast) => {
if (ast.encoding) return flipEncoding(ast, ast.encoding);
const owner = getContextOwner(ast);
if (owner !== ast) {
const flipped = flip(owner);
return flipped === owner ? ast : replaceContext(flipped, ast.context);
}
return "flip" in ast ? ast.flip(flip) : "recur" in ast ? ast.recur(flip) : ast;
});
/** @internal */
function containsUndefined(ast) {
switch (ast._tag) {
case "Undefined":
return true;
case "Union":
return ast.types.some(containsUndefined);
default:
return false;
}
}
function fromConst(ast, value) {
const succeed$6 = value === 0 ? sameExit : succeed(value);
return (input, options) => {
if (input === missing) return missingExit;
if (input === value) return succeed$6;
return fail$1(new InvalidType(ast, input, options));
};
}
function fromRefinement(ast, refinement) {
return (input, options) => {
if (input === missing) return missingExit;
if (refinement(input)) return sameExit;
return fail$1(new InvalidType(ast, input, options));
};
}
/** @internal */
const parameterFromPropertyKey = /*#__PURE__*/ applyToSelfOrLastLinkEncodingIdempotent((ast) => {
switch (ast._tag) {
default:
return ast;
case "Number":
return ast.toCodecStringTree();
case "Union":
return ast.recur(parameterFromPropertyKey);
}
});
const isStringFiniteRegExp = /*#__PURE__*/ new globalThis.RegExp(`^${FINITE_PATTERN}$`);
const isStringNumberRegExp = /*#__PURE__*/ new globalThis.RegExp(
`^(?:${FINITE_PATTERN}|Infinity|-Infinity|NaN)$`,
);
/** @internal */
function isStringFinite(annotations) {
return isPattern$1(isStringFiniteRegExp, {
expected: "a string representing a finite number",
representation: {
id: "effect/schema/isStringFinite",
payload: null,
},
toJsonSchema: () => ({ pattern: isStringFiniteRegExp.source }),
...annotations,
});
}
const finiteString = /*#__PURE__*/ appendChecks(string, [/*#__PURE__*/ isStringFinite()]);
const finiteToString = /*#__PURE__*/ new Link(finiteString, numberFromString);
const numberToString = /*#__PURE__*/ new Link(
/*#__PURE__*/ new Union$1([finiteString, nonFiniteLiterals]),
numberFromString,
);
/** @internal */
function collectIssues(checks, value, issues, ast, options) {
for (let i = 0; i < checks.length; i++) {
const check = checks[i];
if (check._tag === "FilterGroup") {
issues = collectIssues(check.checks, value, issues, ast, options);
if (issues && (options.errors !== "all" || issues[issues.length - 1].filter.aborted))
return issues;
} else {
const issue = check.run(value, ast, options);
if (issue) {
const filter = new Filter$1(check, issue, value, options);
if (issues) issues.push(filter);
else issues = [filter];
if (options.errors !== "all" || check.aborted) return issues;
}
}
}
return issues;
}
/** @internal */
function getConstructorDescriptor(ast) {
if (!isDeclaration(ast)) return void 0;
const getDescriptor = ast.annotations?.[CONSTRUCTOR_ANNOTATION_KEY];
return isFunction(getDescriptor) ? getDescriptor(ast.typeParameters) : void 0;
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/schema/interpreter.js
const flatMapTransformation = (result, current, f) =>
result === sameExit ? f(current) : flatMapEager(result, f);
function compileTransformation(transformation) {
if (transformation._tag === "Middleware")
return (result, current, options) => {
const transformed =
result === sameExit
? transformation.decode(succeed(toOption(current)), options)
: transformation.decode(mapEager(result, toOption), options);
return fromOptionalEffect(transformed);
};
const getter = transformation.decode;
switch (getter._tag) {
case "Passthrough":
return (result, current) => (result === sameExit ? succeed(current) : result);
case "Transform": {
const transform = (value) =>
value === missing ? missingExit : succeed(getter.transform(value));
return (result, current) => flatMapTransformation(result, current, transform);
}
case "TransformOptional": {
const transform = (value) => fromOptionExit(getter.transform(toOption(value)));
return (result, current) => flatMapTransformation(result, current, transform);
}
case "TransformEffect":
return (result, current, options) =>
flatMapTransformation(result, current, (value) =>
value === missing ? missingExit : getter.transform(value, options),
);
case "TransformOptionalEffect":
return (result, current, options) =>
flatMapTransformation(result, current, (value) =>
fromOptionalEffect(getter.transform(toOption(value), options)),
);
}
}
const fromOptionalEffect = (effect) => flatMapEager(effect, fromOptionExit);
/** @internal */
const wrapEncoding = (ast, input, options, effect) =>
catchCause(effect, (cause) =>
failCauseSync(() => map(cause, (issue) => new Encoding(ast, issue, input, options))),
);
function makeConstructorParser(descriptor, compile) {
const transform = compileTransformation(descriptor.link.transformation);
let sourceParser;
return (input, options) => {
if (input === missing) return missingExit;
if (descriptor.isConstructed(input)) return sameExit;
const result = (sourceParser ??= compile(descriptor.link.to))(input, options);
return transform(result, input, options);
};
}
function withDefault(ast, parser) {
const defaultValue = ast.context.constructorDefault;
return (input, options) => {
if (input !== missing && input !== void 0) return parser(input, options);
const result = defaultValue;
if (effectIsExit(result) && result._tag === "Success") {
const local = parser(result[args], options);
return local === sameExit ? result : local;
}
return flatMapEager(wrapEncoding(ast, input, options, result), (value) => {
const local = parser(value, options);
return local === sameExit ? succeed(value) : local;
});
};
}
/** @internal */
function compileField(ast, compile) {
const parser = compile(ast);
return ast.context?.constructorDefault === void 0 ? parser : withDefault(ast, parser);
}
/** @internal */
function compile(ast, compile, compileField, base, specialize) {
if (ast._tag === "Declaration") for (const parameter of ast.typeParameters) compile(parameter);
const descriptor = compileField ? getConstructorDescriptor(ast) : void 0;
const parser = descriptor
? makeConstructorParser(descriptor, compile)
: (base ?? ast.getParser(compile, compileField));
const checks = ast.checks;
const links = ast.encoding;
const transformations = links?.map((link) => compileTransformation(link.transformation));
const encodingChecks = ast.encodingChecks;
if (!links && !checks && !encodingChecks) return parser;
let encodingParsers;
const parseChecks = (input, options) => {
let result = parser(input, options);
if (encodingChecks && !options.disableChecks) {
if (effectIsExit(result)) {
if (result._tag === "Success") {
const output = result === sameExit ? input : result[args];
if (input !== missing && output !== missing) {
const issues = collectIssues(encodingChecks, input, void 0, ast, options);
if (issues) result = fail$1(new Composite(ast, issues, input, options));
}
}
} else
result = flatMap(result, (value) => {
if (input !== missing && value !== missing) {
const issues = collectIssues(encodingChecks, input, void 0, ast, options);
if (issues) return fail$1(new Composite(ast, issues, input, options));
}
return succeed$1(value);
});
}
if (checks && !options.disableChecks) {
if (effectIsExit(result)) {
if (result._tag === "Success") {
const value = result === sameExit ? input : result[args];
if (value === missing) return result;
const issues = collectIssues(checks, value, void 0, ast, options);
if (issues) result = fail$1(new Composite(ast, issues, value, options));
}
} else
result = flatMap(result, (value) => {
if (value !== missing) {
const issues = collectIssues(checks, value, void 0, ast, options);
if (issues) return fail$1(new Composite(ast, issues, value, options));
}
return succeed$1(value);
});
}
return result;
};
const parseLocal = specialize === void 0 ? parseChecks : specialize(parseChecks);
if (!links) return parseLocal;
return (input, options) => {
const parsers = (encodingParsers ??= links.map((link) => compile(link.to)));
let current = input;
let result = parsers[parsers.length - 1](input, options);
for (let i = links.length - 1; i >= 0; i--) {
result = transformations[i](result, current, options);
if (i !== 0) {
const next = parsers[i - 1];
if (result._tag === "Success") {
current = result[args];
result = next(current, options);
} else
result = flatMapEager(result, (value) => {
const nextResult = next(value, options);
return nextResult === sameExit ? succeed(value) : nextResult;
});
}
}
if (result._tag === "Success") {
const value = result[args];
const local = parseLocal(value, options);
return local === sameExit ? result : local;
}
result = wrapEncoding(ast, input, options, result);
return flatMapEager(result, (value) => {
const local = parseLocal(value, options);
return local === sameExit ? succeed(value) : local;
});
};
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/schema/compilerRegistry.js
/** @internal */
const invalid = /*#__PURE__*/ Symbol();
const cache = /*#__PURE__*/ new WeakMap();
const decodeChild = (ast) => resolve(ast).parser;
const makeChild = (ast) => resolve(ast).makeEffect;
const makeField = (ast) => compileField(ast, makeChild);
var InterpretedEntry = class {
ast;
constructor(ast) {
this.ast = ast;
}
get decodeEffect() {
return (this.cachedDecodeEffect ??= compile(this.ast, decodeChild));
}
get parser() {
return this.decodeEffect;
}
get makeEffect() {
return (this.cachedMakeEffect ??= compile(this.ast, makeChild, makeField));
}
};
/** @internal */
function resolve(ast) {
const cached = cache.get(ast);
if (cached !== void 0) return cached;
const entry = new InterpretedEntry(ast);
cache.set(ast, entry);
return entry;
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/SchemaParser.js
/**
* Runs schemas against real values.
*
* Schema parsers construct values from schema input, check whether a value
* matches a schema, decode encoded input, and encode decoded values back to
* their external form. This module exposes those operations through several
* result styles, including `Effect`, `Promise`, `Exit`, `Option`, `Result`, and
* synchronous functions that throw. It also contains the lower-level runner that
* walks a schema AST and reports schema failures as `SchemaIssue.Issue` values.
*
* @stability stable
* @since 4.0.0
*/
/**
* Creates an effectful maker for the schema's decoded type side.
*
* **When to use**
*
* Use to construct decoded schema values in `Effect` while preserving
* construction failures as `SchemaIssue.Issue` values in the error channel.
*
* **Details**
*
* The returned function accepts constructor input, applies constructor defaults,
* runs type-side validation unless checks are disabled, and fails with a
* `SchemaIssue.Issue` when construction fails.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
function makeEffect(schema) {
const ast = schema.ast;
let parser;
return (input, options) => {
return (parser ??= runWithCompiler(constructorCompiler, toType(ast)))(
input,
options?.disableChecks
? options?.parseOptions
? {
...options.parseOptions,
disableChecks: true,
}
: { disableChecks: true }
: options?.parseOptions,
);
};
}
/**
* Creates a synchronous maker that returns `Option.some` with the constructed
* value on success, or `Option.none` when construction fails with schema issues.
*
* **When to use**
*
* Use when you need to validate schema constructor input and only care whether
* construction succeeds, without exposing `SchemaIssue.Issue` details.
*
* **Gotchas**
*
* Only causes made entirely of schema issues are converted to `Option.none`.
* Causes that contain defects, interruptions, or asynchronous work at this
* synchronous boundary throw an `Error` whose cause is the underlying `Cause`.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
function makeOption(schema) {
const parser = makeEffect(schema);
return (input, options) => {
const exit = runSyncExit(parser(input, options));
if (isSuccess(exit)) return some(exit.value);
getSchemaIssueOrThrow(exit.cause, "Option adapter can only return none for schema issues");
return none();
};
}
/**
* Creates a synchronous maker for the schema's decoded type side.
*
* **When to use**
*
* Use to construct decoded schema values synchronously when invalid input
* should throw an `Error` whose cause is `SchemaIssue.Issue`.
*
* **Details**
*
* The returned function constructs a value from constructor input and throws an
* `Error` with the `SchemaIssue.Issue` in its `cause` when construction fails.
* Schema validation failures use the generic message `"Schema validation failed"`.
* Format the `cause` explicitly with `SchemaIssue.makeFormatterDefault()` when
* human-readable details are needed.
*
* **Gotchas**
*
* Causes that contain defects, interruptions, or asynchronous work at this
* synchronous boundary throw an `Error` whose cause is the underlying `Cause`,
* instead of being converted to a schema validation error.
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
function make$2(schema) {
return makeConstructorSync(toType(schema.ast));
}
/**
* Creates an effectful decoder for `unknown` input.
*
* **When to use**
*
* Use when you need to decode untyped boundary input in an `Effect` whose
* failure channel is `SchemaIssue.Issue`, while preserving transformations
* and service requirements.
*
* **Details**
*
* The returned function succeeds with the schema's decoded `Type` or fails with a
* `SchemaIssue.Issue`. Decoding service requirements are preserved in the returned
* `Effect`. Parse options may be provided when creating the decoder and overridden
* when applying it.
*
* @see {@link decodeEffect} for input already typed as the schema's `Encoded` type
*
* @stability stable
* @category decoding
* @since 4.0.0
*/
function decodeUnknownEffect$1(schema, options) {
const parser = run(schema.ast);
return options === void 0
? parser
: (input, overrideOptions) => parser(input, mergeParseOptions(options, overrideOptions));
}
const mergeParseOptions = (options, overrideOptions) =>
overrideOptions
? {
...options,
...overrideOptions,
}
: options;
const getValue = (value) => {
if (value === missing) return fail$1(new InvalidValue());
return succeed$1(value);
};
/** @internal */
function run(ast) {
return runWithCompiler(normalCompiler, ast);
}
function parserResult(result, input) {
if (result === sameExit) return succeed$1(input);
if (!effectIsExit(result)) return flatMapEager(result, getValue);
return result["~effect/Effect/args"] === missing ? getValue(missing) : result;
}
function runWithCompiler(compiler, ast) {
let parser;
return (input, options) => {
const result = (parser ??= compiler(ast))(input, options ?? defaultParseOptions);
if (result === sameExit) return succeed$1(input);
if (!effectIsExit(result)) return flatMapEager(result, getValue);
return result["~effect/Effect/args"] === missing ? getValue(missing) : result;
};
}
function runSync(effect, message) {
const exit = runSyncExit(effect);
if (isSuccess(exit)) return exit.value;
const issue = getSchemaIssueOrThrow(exit.cause, message);
throw new Error("Schema validation failed", { cause: issue });
}
function makeConstructorSync(ast) {
let entry;
let parser;
return (input, options) => {
entry ??= resolve(ast);
const parseOptions = options?.disableChecks
? options.parseOptions
? {
...options.parseOptions,
disableChecks: true,
}
: { disableChecks: true }
: (options?.parseOptions ?? defaultParseOptions);
const make = entry.make;
if (make !== void 0 && input !== missing) {
let output;
try {
output = make(input, parseOptions);
} catch (error) {
getSchemaIssueOrThrow(die$1(error), "Constructor adapter can only throw schema issues");
throw error;
}
if (output !== invalid && output !== missing) return output;
}
return runSync(
parserResult((parser ??= entry.makeEffect)(input, parseOptions), input),
"Constructor adapter can only throw schema issues",
);
};
}
const normalCompiler = (ast) => resolve(ast).parser;
const constructorCompiler = (ast) => resolve(ast).makeEffect;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/schema/make.js
/** @internal */
const TypeId$2 = "~effect/Schema/Schema";
const RebuildOptions = /*#__PURE__*/ Symbol();
const SchemaProto = {
[TypeId$2]: TypeId$2,
get make() {
const value = make$2(this);
Object.defineProperty(this, "make", {
value,
enumerable: true,
});
return value;
},
get makeEffect() {
const value = makeEffect(this);
Object.defineProperty(this, "makeEffect", {
value,
enumerable: true,
});
return value;
},
get makeOption() {
const value = makeOption(this);
Object.defineProperty(this, "makeOption", {
value,
enumerable: true,
});
return value;
},
pipe() {
return pipeArguments(this, arguments);
},
annotate(annotations) {
return this.rebuild(annotate(this.ast, annotations));
},
annotateKey(annotations) {
return this.rebuild(annotateKey(this.ast, annotations));
},
check(...checks) {
return this.rebuild(appendChecks(this.ast, checks));
},
rebuild(ast) {
return make$1(ast, this[RebuildOptions]);
},
};
/** @internal */
function make$1(ast, options) {
function Schema() {}
const self = Object.setPrototypeOf(Schema, SchemaProto);
if (
options &&
(Object.hasOwn(options, "name") ||
Object.hasOwn(options, "length") ||
Object.hasOwn(options, "__proto__"))
)
Object.defineProperties(self, Object.getOwnPropertyDescriptors({ ...options }));
else Object.assign(self, options);
self[RebuildOptions] = options;
self.ast = ast;
return self;
}
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Struct.js
/**
* Wraps a plain function as a {@link Lambda} value so it can be used with
* {@link map}, {@link mapPick}, and {@link mapOmit}.
*
* **When to use**
*
* Use to create a typed lambda for struct mapping APIs that need type-level
* input and output tracking.
*
* **Details**
*
* The type parameter `L` encodes both the input and output types at the type
* level, allowing the compiler to track how struct value types change. At
* runtime, the returned value is the same function; `lambda` only adjusts the
* type.
*
* **Example** (Wrapping values in arrays)
*
* ```ts import.meta.vitest
* import { pipe, Struct } from "effect"
*
* interface AsArray extends Struct.Lambda {
* <A>(self: A): Array<A>
* readonly "~lambda.out": Array<this["~lambda.in"]>
* }
*
* const asArray = Struct.lambda<AsArray>((a) => [a])
* const result = pipe({ x: 1, y: "hello" }, Struct.map(asArray))
* result // => { x: [1], y: ["hello"] }
* ```
*
* @see {@link Lambda} – the type-level interface
* @see {@link map} – apply a lambda to all struct values
* @stability stable
* @category constructors
* @since 4.0.0
*/
const lambda = (f) => f;
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/internal/schemaError.js
const SchemaErrorTypeId = "~effect/Schema/SchemaError";
function isSchemaError$1(u) {
return (
hasProperty(u, "~effect/Schema/SchemaError") &&
u["~effect/Schema/SchemaError"] === "~effect/Schema/SchemaError"
);
}
({ ...BaseProto });
({ ...BaseProto });
({ ...BaseProto });
({ ...BaseProto });
({ ...BaseProto });
({ ...BaseProto });
({ ...BaseProto });
({ ...BaseProto });
//#endregion
//#region ../node_modules/.pnpm/effect@4.0.5/node_modules/effect/dist/Schema.js
/**
* Creates a schema for a **parametric** type (a generic container such as
* `Array<A>`, `Option<A>`, etc.) by accepting a list of type-parameter schemas
* and a decoder factory.
*
* **When to use**
*
* Use when you are defining a schema for a generic container whose validation
* depends on one or more type-parameter schemas.
*
* **Details**
*
* The outer call `declareConstructor<T, E, Iso>()` fixes the decoded type `T`,
* the encoded type `E`, and the optional iso type. The inner call receives:
* - `typeParameters` — the concrete schemas for each type variable
* - `run` — a factory that, given resolved codecs for each type parameter,
* returns a parsing function `(u, ast, options) => Effect<T, Issue>`
* - `annotations` — optional metadata
*
* @see {@link declare} for creating schemas for non-parametric types.
*
* **Example** (Schema for a parametric `Box<A>` type)
*
* ```ts import.meta.vitest
* import { Effect, Schema, SchemaIssue, SchemaParser } from "effect"
*
* interface Box<A> {
* readonly value: A
* }
*
* const isBox = (u: unknown): u is Box<unknown> =>
* typeof u === "object" && u !== null && "value" in u
*
* const Box = <A extends Schema.Constraint>(item: A) =>
* Schema.declareConstructor<Box<A["Type"]>, Box<A["Encoded"]>>()(
* [item],
* ([itemCodec]) =>
* (u, ast, options) => {
* if (!isBox(u)) {
* return Effect.fail(new SchemaIssue.InvalidType(ast, u, options))
* }
* return Effect.map(
* SchemaParser.decodeUnknownEffect(itemCodec)(u.value, options),
* (value) => ({ value })
* )
* }
* )
*
* const schema = Box(Schema.Number)
* Effect.runSync(Schema.decodeUnknownEffect(schema)({ value: 1 })) // => { value: 1 }
* ```
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
function declareConstructor() {
return (typeParameters, run, annotations) => {
return make(
new Declaration(
typeParameters.map(getAST),
(typeParameters) => run(typeParameters.map((ast) => make(ast))),
annotations,
),
);
};
}
/**
* Creates a schema for a **non-parametric** opaque type using a type-guard
* function. The schema accepts any unknown value and succeeds when `is` returns
* `true`, failing with an `InvalidType` issue otherwise.
*
* **When to use**
*
* Use when you are defining a schema for an opaque type with no type parameters
* and validation can be expressed as a type guard.
*
* **Example** (Defining a schema for a custom `UserId` branded type)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* type UserId = string & { readonly _tag: "UserId" }
*
* const isUserId = (u: unknown): u is UserId =>
* typeof u === "string" && u.startsWith("user_")
*
* const UserId = Schema.declare<UserId>(isUserId, {
* title: "UserId",
* description: "A user identifier starting with 'user_'"
* })
* Schema.decodeUnknownSync(UserId)("user_123") // => "user_123"
* ```
*
* @see {@link declareConstructor} for creating schemas for parametric types.
*
* @stability stable
* @category constructors
* @since 3.10.0
*/
function declare(is, annotations) {
return declareConstructor()(
[],
() => (input, ast, options) =>
is(input) ? succeed$1(input) : fail$1(new InvalidType(ast, input, options)),
annotations,
);
}
/**
* Error thrown or returned when schema decoding or encoding fails.
*
* **Details**
*
* The `issue` field contains a structured {@link SchemaIssue.Issue} tree describing
* every validation failure, including the path to the problematic value and
* the expected type or constraint. The `message` field renders the issue tree
* with the default formatter.
*
* **Gotchas**
*
* Parsing with `reportInput: true` adds an enumerable `input` field to
* value-bearing issues. Built-in messages may include reported input, and
* custom annotations or messages are not sanitized.
*
* **Example** (Inspecting a SchemaError)
*
* ```ts import.meta.vitest
* import { Result, Schema } from "effect"
*
* const result = Schema.decodeUnknownResult(Schema.Number)("not a number")
* const message = Result.isFailure(result) ? result.failure.message : ""
* message // => "Expected number"
* ```
*
* @see {@link isSchemaError} for narrowing unknown values
* @stability stable
* @category errors
* @since 4.0.0
*/
var SchemaError = class extends /*#__PURE__*/ TaggedError("SchemaError") {
[SchemaErrorTypeId] = SchemaErrorTypeId;
constructor(issue) {
const stackTraceLimit = getStackTraceLimit();
setStackTraceLimit(0);
try {
super({ issue });
} finally {
setStackTraceLimit(stackTraceLimit);
}
}
get message() {
return defaultFormatter(this.issue);
}
toJSON() {
return {
_tag: this._tag,
message: this.message,
};
}
[NodeInspectSymbol]() {
return this.toJSON();
}
toString() {
return `SchemaError(${this.message})`;
}
};
/**
* Returns `true` if `u` is a {@link SchemaError}.
*
* **When to use**
*
* Use when you need to narrow an unknown value to `SchemaError`.
*
* **Example** (Narrowing Schema errors)
*
* ```ts import.meta.vitest
* import { Result, Schema } from "effect"
*
* const result = Result.try(() => Schema.decodeUnknownSync(Schema.Number)("oops"))
* const error: unknown = Result.isFailure(result) ? result.failure : undefined
* Schema.isSchemaError(error) // => true
* ```
*
* @stability stable
* @category guards
* @since 4.0.0
*/
function isSchemaError(u) {
return isSchemaError$1(u);
}
function fromIssueEffect(self) {
if (effectIsExit(self)) return fromIssueExit(self);
return catchCause(self, (cause) =>
failCauseSync(() => map(cause, (issue) => new SchemaError(issue))),
);
}
function fromIssueExit(exit) {
return isSuccess(exit) ? exit : failCause(map(exit.cause, (issue) => new SchemaError(issue)));
}
function getSchemaErrorOrThrow(cause, message) {
let schemaError;
for (const reason of cause.reasons) {
if (!isFailReason(reason) || !isSchemaError(reason.error))
throw new globalThis.Error(message, { cause });
schemaError ??= reason.error;
}
if (schemaError === void 0) throw new globalThis.Error(message, { cause });
return schemaError;
}
function runSchemaErrorSync(self) {
const exit = runSyncExit(self);
if (isSuccess(exit)) return exit.value;
throw getSchemaErrorOrThrow(exit.cause, "Sync adapter can only throw schema errors");
}
/**
* Decodes an `unknown` input against a schema, returning an `Effect` that
* succeeds with the decoded value or fails with a {@link SchemaError}.
*
* **When to use**
*
* Use when you need to decode unknown input in an `Effect` whose failure
* channel is `SchemaError`.
*
* **Details**
*
* Prefer {@link decodeEffect} when the input is already typed as the schema's
* `Encoded` type.
* Options may be provided either when creating the decoder or when applying it;
* application options override creation options.
*
* @see {@link SchemaParser.decodeUnknownEffect} for the adapter that fails with `SchemaIssue.Issue` directly
*
* @stability stable
* @category decoding
* @since 4.0.0
*/
function decodeUnknownEffect(schema, options) {
const parser = decodeUnknownEffect$1(schema, options);
return (input, options) => {
return fromIssueEffect(parser(input, options));
};
}
/**
* Decodes an `unknown` input against a schema synchronously, returning the
* decoded value or throwing a {@link SchemaError} for schema mismatches.
*
* **When to use**
*
* Use when you need to validate unknown data at a synchronous boundary and want
* schema mismatches to throw `SchemaError`.
*
* **Details**
*
* For input already typed as the schema's `Encoded` type use `decodeSync`.
* Only service-free schemas can be decoded synchronously. For alternatives that
* do not throw on schema mismatches, see `decodeUnknownOption`,
* `decodeUnknownExit`, or `decodeUnknownEffect`. Options may be provided either
* when creating the decoder or when applying it; application options override
* creation options.
*
* **Gotchas**
*
* Non-schema failures may throw a runtime failure instead of `SchemaError`.
*
* **Example** (Decoding with a transformation schema)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* const NumberFromString = Schema.NumberFromString
*
* Schema.decodeUnknownSync(NumberFromString)("42") // => 42
* ```
*
* @see {@link SchemaParser.decodeUnknownSync} for the adapter that throws an `Error` whose cause is `SchemaIssue.Issue`
*
* @stability stable
* @category decoding
* @since 4.0.0
*/
function decodeUnknownSync(schema, options) {
const parser = decodeUnknownEffect(schema, options);
return (input, options) => {
return runSchemaErrorSync(parser(input, options));
};
}
/**
* Creates a schema from an AST (Abstract Syntax Tree) node.
*
* **Details**
*
* This is the fundamental constructor for all schemas in the Effect Schema
* library. It takes an AST node and wraps it in a fully-typed schema that
* preserves all type information and provides the complete schema API.
*
* The `make` function is used internally to create all primitive schemas like
* `String`, `Number`, `Boolean`, etc., as well as more complex schemas. It's
* the bridge between the untyped AST representation and the strongly-typed
* schema.
*
* @stability stable
* @category constructors
* @since 3.10.0
*/
const make = make$1;
/**
* Creates a schema for a single literal value (string, number, bigint, boolean, or null).
*
* **Example** (Defining a string literal)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* const schema = Schema.Literal("hello")
* // Type: Schema.Literal<"hello">
* Schema.decodeSync(schema)("hello") // => "hello"
* ```
*
* @see {@link Literals} for a schema that represents a union of literals.
* @see {@link tag} for a schema that represents a literal value that can be
* used as a discriminator field in tagged unions and has a constructor default.
* @stability stable
* @category constructors
* @since 3.10.0
*/
function Literal(literal) {
const out = make(new Literal$1(literal), {
literal,
transform(to) {
return out.pipe(
decodeTo(Literal(to), {
decode: transform$1(() => to),
encode: transform$1(() => literal),
}),
);
},
});
return out;
}
/**
* Schema for the `null` literal. Validates that the input is strictly `null`.
*
* @see {@link NullOr} for a union with another schema.
* @stability stable
* @category schemas
* @since 3.10.0
*/
const Null = /*#__PURE__*/ make(null_);
/**
* Schema for `string` values. Validates that the input is `typeof` `"string"`.
*
* @stability stable
* @category schemas
* @since 4.0.0
*/
const String$1 = /*#__PURE__*/ make(string);
/**
* Schema for `number` values, including `NaN`, `Infinity`, and `-Infinity`.
*
* **Details**
*
* Default JSON serializer:
*
* - Finite numbers are serialized as numbers.
* - Non-finite values are serialized as strings (`"NaN"`, `"Infinity"`, `"-Infinity"`).
*
* @see {@link Finite} for a schema that excludes non-finite values.
* @stability stable
* @category schemas
* @since 4.0.0
*/
const Number$1 = /*#__PURE__*/ make(number);
function makeStruct(ast, fields) {
return make(ast, {
fields,
mapFields(f, options) {
const fields = f(this.fields);
return makeStruct(
struct(fields, options?.unsafePreserveChecks ? this.ast.checks : void 0),
fields,
);
},
});
}
/**
* Defines a struct schema from a map of field schemas.
*
* **Details**
*
* Each field value is a schema. Use {@link optionalKey} or {@link optional} to
* mark fields as optional, and {@link mutableKey} to mark them as mutable.
*
* The resulting schema's `Type` is a readonly object type with the fields'
* decoded types. The `Encoded` form mirrors the field schemas' encoded types.
* Declared fields may be inherited and are copied to own properties in the
* output. The `__proto__` field is accepted only when it is an own property.
* Parsing does not guarantee that output keys retain their input order.
*
* **Example** (Defining a basic struct)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* const Person = Schema.Struct({
* name: Schema.String,
* age: Schema.Number,
* email: Schema.optionalKey(Schema.String)
* })
*
* // { readonly name: string; readonly age: number; readonly email?: string }
* type Person = typeof Person.Type
*
* Schema.decodeUnknownSync(Person)({ name: "Alice", age: 30 }) // => { name: "Alice", age: 30 }
* ```
*
* @stability stable
* @category constructors
* @since 3.10.0
*/
function Struct(fields) {
return makeStruct(struct(fields, void 0), fields);
}
/**
* @category constructors
* @since 4.0.0
*/
const ArraySchema = /*#__PURE__*/ lambda((schema) =>
make(new Arrays(false, [], [schema.ast]), { value: schema }),
);
/**
* Makes an array or tuple schema mutable, removing the `readonly` modifier.
*
* **Gotchas**
*
* This combinator does not support an encoding attached to the array or tuple
* node and throws if one is present. Encodings on element schemas are
* supported.
*
* **Example** (Defining mutable arrays)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* const schema = Schema.mutable(Schema.Array(Schema.Number))
*
* // number[] (mutable)
* type T = typeof schema.Type
* const value: T = [1, 2]
* value.push(3)
* value // => [1, 2, 3]
* ```
*
* @stability stable
* @category transforming
* @since 3.10.0
*/
const mutable = /*#__PURE__*/ lambda((schema) => make(mutable$1(schema.ast), { schema }));
function makeUnion(ast, members) {
return make(ast, {
members,
mapMembers(f, options) {
const members = f(this.members);
return makeUnion(
union(members, this.ast.options, options?.unsafePreserveChecks ? this.ast.checks : void 0),
members,
);
},
});
}
/**
* Creates a union schema from an array of member schemas. Members are tested in
* order; the first match is returned.
*
* **Details**
*
* Optionally, specify `mode`:
* - `"anyOf"` (default) — matches if any member matches.
* - `"oneOf"` — matches if exactly one member matches.
*
* **Example** (Defining a string or number union)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* const schema = Schema.Union([Schema.String, Schema.Number])
*
* Schema.decodeUnknownSync(schema)("hello") // => "hello"
* Schema.decodeUnknownSync(schema)(42) // => 42
* ```
*
* @stability stable
* @category constructors
* @since 3.10.0
*/
function Union(members, options) {
return makeUnion(union(members, options, void 0), members);
}
/**
* Creates a union schema from an array of literal values.
*
* **Example** (Defining status codes)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* const schema = Schema.Literals(["active", "inactive", "pending"])
* Schema.decodeSync(schema)("active") // => "active"
* ```
*
* @see {@link Literal} for a schema that represents a single literal.
* @stability stable
* @category constructors
* @since 4.0.0
*/
function Literals(literals) {
const members = literals.map(Literal);
return make(union(members, void 0, void 0), {
literals,
members,
mapMembers(f) {
return Union(f(this.members));
},
pick(literals) {
return Literals(literals);
},
transform(to) {
return Union(members.map((member, index) => member.transform(to[index])));
},
});
}
/**
* Creates a union schema of `S | null`.
*
* @stability stable
* @category constructors
* @since 3.10.0
*/
const NullOr = /*#__PURE__*/ lambda((self) => Union([self, Null]));
function decodeTo(to, transformation) {
return (from) => {
return make(
decodeTo$1(
from.ast,
to.ast,
transformation ? makeTransformation(transformation) : passthrough(),
),
{
from,
to,
},
);
};
}
/**
* Creates a schema that validates values using `instanceof`.
* Decoding and encoding pass the value through unchanged.
*
* **Example** (Defining a schema for a built-in class)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* const DateSchema = Schema.instanceOf(Date)
*
* const decoded = Schema.decodeUnknownSync(DateSchema)(new Date("2024-01-01"))
* decoded.toISOString() // => "2024-01-01T00:00:00.000Z"
* ```
*
* @stability stable
* @category constructors
* @since 3.10.0
*/
function instanceOf(constructor, annotations) {
return declare((u) => u instanceof constructor, annotations);
}
/**
* Creates a custom validation filter from a predicate function.
*
* **Details**
*
* The predicate receives the decoded input value, the schema AST, and parse
* options, and returns a `FilterOutput`. Non-success outputs are normalized into
* schema issues. The `annotations` parameter annotates the filter itself; with
* the default formatter, failures use `message` first, `expected` second, and
* `<filter>` when neither is provided.
*
* When `abort` is `true`, parsing stops after this filter fails instead of
* collecting later check failures.
*
* **Example** (Reporting failure at a nested path)
*
* ```ts import.meta.vitest
* import { Result, Schema } from "effect"
*
* const schema = Schema.Struct({ password: Schema.String, confirmPassword: Schema.String }).check(
* Schema.makeFilter((o) =>
* o.password === o.confirmPassword
* ? undefined
* : { path: ["password"], issue: "password and confirmPassword must match" }
* )
* )
*
* const result = Schema.decodeUnknownResult(schema)({ password: "123456", confirmPassword: "1234567" })
* if (Result.isFailure(result) && result.failure.issue._tag === "Filter" && result.failure.issue.issue._tag === "Pointer") {
* result.failure.issue.issue.path // => ["password"]
* }
* ```
*
* **Example** (Reporting multiple failures at once)
*
* ```ts import.meta.vitest
* import { Result, Schema } from "effect"
*
* const schema = Schema.Struct({ a: Schema.Finite, b: Schema.Finite, c: Schema.Finite }).check(
* Schema.makeFilter((o) => {
* const issues: Array<Schema.FilterIssue> = []
* if (o.a > 0) {
* if (o.b <= 0) issues.push({ path: ["b"], issue: "b must be greater than 0" })
* if (o.c <= 0) issues.push({ path: ["c"], issue: "c must be greater than 0" })
* }
* return issues
* })
* )
*
* const result = Schema.decodeUnknownResult(schema)({ a: 1, b: 0, c: 0 })
* if (Result.isFailure(result) && result.failure.issue._tag === "Filter" && result.failure.issue.issue._tag === "Composite") {
* result.failure.issue.issue.issues.map((issue) => issue._tag === "Pointer" ? issue.path : []) // => [["b"], ["c"]]
* }
* ```
*
* @stability stable
* @category constructors
* @since 4.0.0
*/
const makeFilter = makeFilter$1;
/**
* Creates a greater-than-or-equal-to (`>=`) check for any ordered type from an
* `Order.Order` instance.
*
* @stability stable
* @category validation
* @since 4.0.0
*/
function makeIsGreaterThanOrEqualTo(options) {
const gte = isGreaterThanOrEqualTo$1(options.order);
const formatter = options.formatter ?? format$1;
return (minimum, annotations) => {
return makeFilter((input) => gte(input, minimum), {
expected: `a value greater than or equal to ${formatter(minimum)}`,
arbitraryConstraint: {
order: options.order,
minimum,
},
...options.annotate?.(minimum),
...annotations,
});
};
}
/**
* Creates a less-than-or-equal-to (`<=`) check for any ordered type from an
* `Order.Order` instance.
*
* @stability stable
* @category validation
* @since 4.0.0
*/
function makeIsLessThanOrEqualTo(options) {
const lte = isLessThanOrEqualTo$1(options.order);
const formatter = options.formatter ?? format$1;
return (maximum, annotations) => {
return makeFilter((input) => lte(input, maximum), {
expected: `a value less than or equal to ${formatter(maximum)}`,
arbitraryConstraint: {
order: options.order,
maximum,
},
...options.annotate?.(maximum),
...annotations,
});
};
}
function encodeNumberPayload(number) {
if (!globalThis.Number.isFinite(number))
throw new globalThis.RangeError(`Expected a finite number, got ${format$1(number)}`);
return number;
}
/**
* Validates that a number is greater than or equal to the specified value
* (inclusive).
*
* **Details**
*
* JSON Schema:
*
* This check corresponds to the `minimum` constraint in JSON Schema.
*
* Arbitrary:
*
* During arbitrary generation, this applies a `minimum` constraint
* to ensure generated numbers are greater than or equal to the specified value.
*
* @stability stable
* @category validation
* @since 4.0.0
*/
const isGreaterThanOrEqualTo = /*#__PURE__*/ makeIsGreaterThanOrEqualTo({
order: Number$4,
annotate: (minimum) => ({
representation: {
id: "effect/schema/isGreaterThanOrEqualTo",
payload: { minimum: encodeNumberPayload(minimum) },
},
toJsonSchema: () => ({ minimum }),
toCode: () => ({ runtime: `Schema.isGreaterThanOrEqualTo(${format$1(minimum)})` }),
}),
});
/**
* Validates that a number is less than or equal to the specified value
* (inclusive).
*
* **Details**
*
* JSON Schema:
*
* This check corresponds to the `maximum` constraint in JSON Schema.
*
* Arbitrary:
*
* During arbitrary generation, this applies a `maximum` constraint
* to ensure generated numbers are less than or equal to the specified value.
*
* @stability stable
* @category validation
* @since 4.0.0
*/
const isLessThanOrEqualTo = /*#__PURE__*/ makeIsLessThanOrEqualTo({
order: Number$4,
annotate: (maximum) => ({
representation: {
id: "effect/schema/isLessThanOrEqualTo",
payload: { maximum: encodeNumberPayload(maximum) },
},
toJsonSchema: () => ({ maximum }),
toCode: () => ({ runtime: `Schema.isLessThanOrEqualTo(${format$1(maximum)})` }),
}),
});
/**
* Validates that a value has at least the specified length. Works with strings
* and arrays.
*
* **Details**
*
* JSON Schema:
*
* The bound must be finite; it is rounded down and clamped to zero. For arrays,
* this check corresponds to `minItems`. JavaScript counts UTF-16 code units
* while JSON Schema counts Unicode code points, so strings use
* `minLength: Math.ceil(minLength / 2)`, the tightest lower bound that cannot
* reject a string accepted by this check.
*
* Arbitrary:
*
* During arbitrary generation, this applies a `minLength`
* constraint to ensure generated strings or arrays have at least the required
* length.
*
* **Example** (Checking minimum length)
*
* ```ts import.meta.vitest
* import { Schema } from "effect"
*
* const NonEmptyStringSchema = Schema.String.check(Schema.isMinLength(1))
* const NonEmptyArraySchema = Schema.Array(Schema.Number).check(Schema.isMinLength(1))
* Schema.is(NonEmptyStringSchema)("a") // => true
* Schema.is(NonEmptyArraySchema)([1]) // => true
* ```
*
* @stability stable
* @category validation
* @since 4.0.0
*/
function isMinLength(minLength, annotations) {
minLength = normalizeCardinality(minLength);
return makeIsMinLength(minLength, Math.ceil(minLength / 2), annotations);
}
function makeIsMinLength(minLength, minCodePoints, annotations) {
return makeFilter((input) => input.length >= minLength, {
expected: `a value with a length of at least ${minLength}`,
representation: {
id: "effect/schema/isMinLength",
payload: { minLength },
},
toJsonSchema: ({ type }) =>
type === "string"
? minLength <= 1
? { minLength: minCodePoints }
: [{ minLength: minCodePoints }, true]
: type === "array"
? { minItems: minLength }
: type === void 0
? [
{
minLength: minCodePoints,
minItems: minLength,
},
true,
]
: [{}, true],
toCode: () => ({ runtime: `Schema.isMinLength(${minLength})` }),
[STRUCTURAL_ANNOTATION_KEY]: true,
arbitraryConstraint: { minLength },
...annotations,
});
}
/**
* Validates that a value has at most the specified length. Works with strings
* and arrays.
*
* **Details**
*
* JSON Schema:
*
* The bound must be finite; it is rounded down and clamped to zero. This check
* corresponds to `maxItems` for arrays. Strings use the same bound for
* `maxLength`, which cannot reject a string accepted by this check because a
* string has no more code points than UTF-16 code units.
*
* Arbitrary:
*
* During arbitrary generation, this applies a `maxLength`
* constraint to ensure generated strings or arrays have at most the required
* length.
*
* @stability stable
* @category validation
* @since 4.0.0
*/
function isMaxLength(maxLength, annotations) {
maxLength = normalizeCardinality(maxLength);
return makeFilter((input) => input.length <= maxLength, {
expected: `a value with a length of at most ${maxLength}`,
representation: {
id: "effect/schema/isMaxLength",
payload: { maxLength },
},
toJsonSchema: ({ type }) =>
type === "string"
? maxLength === 0
? { maxLength }
: [{ maxLength }, true]
: type === "array"
? { maxItems: maxLength }
: type === void 0
? [
{
maxLength,
maxItems: maxLength,
},
true,
]
: [{}, true],
toCode: () => ({ runtime: `Schema.isMaxLength(${maxLength})` }),
[STRUCTURAL_ANNOTATION_KEY]: true,
arbitraryConstraint: { maxLength },
...annotations,
});
}
function normalizeCardinality(value) {
if (!globalThis.Number.isFinite(value))
throw new globalThis.RangeError(`Expected a finite number, got ${value}`);
return Math.max(0, Math.floor(value));
}
globalThis.RegExp;
globalThis.URL;
globalThis.File;
globalThis.FormData;
globalThis.URLSearchParams;
globalThis.Uint8Array;
//#endregion
//#region ../schemas/libraries/effect/download/index.ts
const Image = Struct({
id: Number$1,
created: instanceOf(Date),
title: String$1.check(isMinLength(1), isMaxLength(100)),
type: Literals(["jpg", "png"]),
size: Number$1,
url: String$1.check(makeFilter((value) => URL.canParse(value))),
});
const Rating = Struct({
id: Number$1,
stars: Number$1.check(isGreaterThanOrEqualTo(1), isLessThanOrEqualTo(5)),
title: String$1.check(isMinLength(1), isMaxLength(100)),
text: String$1.check(isMinLength(1), isMaxLength(1e3)),
images: mutable(ArraySchema(Image)),
});
decodeUnknownSync(
Struct({
id: Number$1,
created: instanceOf(Date),
title: String$1.check(isMinLength(1), isMaxLength(100)),
brand: String$1.check(isMinLength(1), isMaxLength(30)),
description: String$1.check(isMinLength(1), isMaxLength(500)),
price: Number$1.check(isGreaterThanOrEqualTo(1), isLessThanOrEqualTo(1e4)),
discount: NullOr(Number$1.check(isGreaterThanOrEqualTo(1), isLessThanOrEqualTo(100))),
quantity: Number$1.check(isGreaterThanOrEqualTo(0), isLessThanOrEqualTo(10)),
tags: mutable(ArraySchema(String$1.check(isMinLength(1), isMaxLength(30)))),
images: mutable(ArraySchema(Image)),
ratings: mutable(ArraySchema(Rating)),
}),
)({});
//#endregion