Socket
Socket
Sign inDemoInstall

@effect/schema

Package Overview
Dependencies
Maintainers
3
Versions
328
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@effect/schema - npm Package Compare versions

Comparing version 0.23.0 to 0.24.0

33

Arbitrary.js

@@ -54,3 +54,6 @@ "use strict";

case "Declaration":
return (0, _Function.pipe)(getHook(ast), O.match(() => go(ast.type), handler => handler(...ast.typeParameters.map(p => go(p)))));
return (0, _Function.pipe)(getHook(ast), O.match({
onNone: () => go(ast.type),
onSome: handler => handler(...ast.typeParameters.map(p => go(p)))
}));
case "Literal":

@@ -195,6 +198,9 @@ return fc => fc.constant(ast.literal);

case "Lazy":
return (0, _Function.pipe)(getHook(ast), O.match(() => {
const get = I.memoizeThunk(() => go(ast.f()));
return fc => fc.constant(null).chain(() => get()(fc));
}, handler => handler()));
return (0, _Function.pipe)(getHook(ast), O.match({
onNone: () => {
const get = I.memoizeThunk(() => go(ast.f()));
return fc => fc.constant(null).chain(() => get()(fc));
},
onSome: handler => handler()
}));
case "Enums":

@@ -210,9 +216,12 @@ {

const from = go(ast.from, combineConstraints(constraints, getConstraints(ast)));
return (0, _Function.pipe)(getHook(ast), O.match(() => fc => from(fc).filter(a => {
const eu = (0, _ParseResult.eitherOrUndefined)(ast.decode(a));
if (eu) {
return E.isRight(eu);
}
throw new Error("cannot build an Arbitrary for effectful refinements");
}), handler => handler(from)));
return (0, _Function.pipe)(getHook(ast), O.match({
onNone: () => fc => from(fc).filter(a => {
const eu = (0, _ParseResult.eitherOrUndefined)(ast.decode(a));
if (eu) {
return E.isRight(eu);
}
throw new Error("cannot build an Arbitrary for effectful refinements");
}),
onSome: handler => handler(from)
}));
}

@@ -219,0 +228,0 @@ case "Transform":

@@ -10,5 +10,5 @@ "use strict";

var O = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/data/Option"));
var Order = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/data/Order"));
var _Predicate = /*#__PURE__*/require("@effect/data/Predicate");
var RA = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/data/ReadonlyArray"));
var Order = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/data/typeclass/Order"));
var _common = /*#__PURE__*/require("@effect/schema/internal/common");

@@ -644,7 +644,10 @@ var PR = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/schema/ParseResult"));

}
return (0, _Function.pipe)(ast.rest, O.match(() => createTuple([...ast.elements, newElement], O.none(), ast.isReadonly), rest => {
if (newElement.isOptional) {
throw new Error("An optional element cannot follow a rest element. ts(1266)");
return (0, _Function.pipe)(ast.rest, O.match({
onNone: () => createTuple([...ast.elements, newElement], O.none(), ast.isReadonly),
onSome: rest => {
if (newElement.isOptional) {
throw new Error("An optional element cannot follow a rest element. ts(1266)");
}
return createTuple(ast.elements, O.some([...rest, newElement.type]), ast.isReadonly);
}
return createTuple(ast.elements, O.some([...rest, newElement.type]), ast.isReadonly);
}));

@@ -651,0 +654,0 @@ };

{
"name": "@effect/schema",
"version": "0.23.0",
"version": "0.24.0",
"license": "MIT",

@@ -10,5 +10,5 @@ "repository": {

"dependencies": {
"@effect/data": "^0.12.10",
"@effect/io": "^0.29.0",
"fast-check": "^3.10.0"
"@effect/data": "^0.13.2",
"@effect/io": "^0.31.1",
"fast-check": "^3.11.0"
},

@@ -15,0 +15,0 @@ "publishConfig": {

@@ -7,3 +7,2 @@ "use strict";

exports.validateResult = exports.validatePromise = exports.validateOption = exports.validateEither = exports.validateEffect = exports.validate = exports.reverse = exports.parseResult = exports.parsePromise = exports.parseOption = exports.parseEither = exports.parseEffect = exports.parse = exports.is = exports.encodeResult = exports.encodePromise = exports.encodeOption = exports.encodeEither = exports.encodeEffect = exports.encode = exports.decodeResult = exports.decodePromise = exports.decodeOption = exports.decodeEither = exports.decodeEffect = exports.decode = exports.asserts = exports._getSearchTree = exports._getLiterals = void 0;
var _Debug = /*#__PURE__*/require("@effect/data/Debug");
var E = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/data/Either"));

@@ -38,4 +37,4 @@ var _Function = /*#__PURE__*/require("@effect/data/Function");

const getOption = ast => {
const parser = go(ast);
return (input, options) => O.fromEither(parser(input, options));
const parser = getEither(ast);
return (input, options) => O.getRight(parser(input, options));
};

@@ -224,3 +223,3 @@ const getEither = ast => {

exports.encodeEffect = encodeEffect;
const go = /*#__PURE__*/(0, _Debug.untracedMethod)(() => (ast, isBoundary = true) => {
const go = (ast, isBoundary = true) => {
switch (ast._tag) {

@@ -361,3 +360,3 @@ case "Refinement":

}
queue.push((0, _Debug.untracedMethod)(() => ({
queue.push(({
es,

@@ -371,3 +370,3 @@ output

es.push([nk, e]);
return Effect.unit();
return Effect.unit;
} else {

@@ -378,4 +377,4 @@ return PR.failures(mutableAppend(sortByIndex(es), e));

output.push([nk, t.right]);
return Effect.unit();
})));
return Effect.unit;
}));
}

@@ -411,3 +410,3 @@ }

}
queue.push((0, _Debug.untracedMethod)(() => ({
queue.push(({
es,

@@ -420,3 +419,3 @@ output

es.push([nk, e]);
return Effect.unit();
return Effect.unit;
} else {

@@ -427,5 +426,5 @@ return PR.failures(mutableAppend(sortByIndex(es), e));

output.push([nk, t.right]);
return Effect.unit();
return Effect.unit;
}
})));
}));
}

@@ -461,3 +460,3 @@ }

}
queue.push((0, _Debug.untracedMethod)(() => ({
queue.push(({
es,

@@ -471,3 +470,3 @@ output

es.push([nk, e]);
return Effect.unit();
return Effect.unit;
} else {

@@ -478,4 +477,4 @@ return PR.failures(mutableAppend(sortByIndex(es), e));

output.push([nk, t.right]);
return Effect.unit();
})));
return Effect.unit;
}));
}

@@ -494,3 +493,3 @@ }

const cqueue = queue;
return (0, _Debug.untraced)(() => Effect.suspend(() => {
return Effect.suspend(() => {
const state = {

@@ -500,4 +499,7 @@ es: Array.from(es),

};
return Effect.flatMap(Effect.forEachParDiscard(cqueue, f => f(state)), () => computeResult(state));
}));
return Effect.flatMap(Effect.forEach(cqueue, f => f(state), {
concurrency: "unbounded",
discard: true
}), () => computeResult(state));
});
}

@@ -580,3 +582,3 @@ return computeResult({

}
queue.push((0, _Debug.untracedMethod)(() => ({
queue.push(({
es,

@@ -590,3 +592,3 @@ output

es.push([nk, e]);
return Effect.unit();
return Effect.unit;
} else {

@@ -597,4 +599,4 @@ return PR.failures(mutableAppend(sortByIndex(es), e));

output[index] = t.right;
return Effect.unit();
})));
return Effect.unit;
}));
}

@@ -666,3 +668,3 @@ } else {

}
queue.push((0, _Debug.untracedMethod)(() => ({
queue.push(({
es,

@@ -675,3 +677,3 @@ output

es.push([nk, e]);
return Effect.unit();
return Effect.unit;
} else {

@@ -682,5 +684,5 @@ return PR.failures(mutableAppend(sortByIndex(es), e));

output[key] = tv.right;
return Effect.unit();
return Effect.unit;
}
})));
}));
}

@@ -698,3 +700,3 @@ }

const cqueue = queue;
return (0, _Debug.untraced)(() => Effect.suspend(() => {
return Effect.suspend(() => {
const state = {

@@ -704,4 +706,7 @@ es: Array.from(es),

};
return Effect.flatMap(Effect.forEachParDiscard(cqueue, f => f(state)), () => computeResult(state));
}));
return Effect.flatMap(Effect.forEach(cqueue, f => f(state), {
concurrency: "unbounded",
discard: true
}), () => computeResult(state));
});
}

@@ -773,5 +778,5 @@ return computeResult({

}
queue.push((0, _Debug.untracedMethod)(() => state => Effect.suspend(() => {
queue.push(state => Effect.suspend(() => {
if ("finalResult" in state) {
return Effect.unit();
return Effect.unit;
} else {

@@ -784,6 +789,6 @@ return Effect.flatMap(Effect.either(pr), t => {

}
return Effect.unit();
return Effect.unit;
});
}
})));
}));
}

@@ -799,7 +804,10 @@ }

const cqueue = queue;
return (0, _Debug.untraced)(() => Effect.suspend(() => {
return Effect.suspend(() => {
const state = {
es: Array.from(es)
};
return Effect.flatMap(Effect.forEachDiscard(cqueue, f => f(state)), () => {
return Effect.flatMap(Effect.forEach(cqueue, f => f(state), {
concurrency: 1,
discard: true
}), () => {
if ("finalResult" in state) {

@@ -810,3 +818,3 @@ return state.finalResult;

});
}));
});
}

@@ -822,3 +830,3 @@ return computeResult(es);

}
});
};
const fromRefinement = (ast, refinement) => u => refinement(u) ? PR.success(u) : PR.failure(PR.type(ast, u));

@@ -825,0 +833,0 @@ /** @internal */

@@ -12,10 +12,6 @@ /**

*/
export type IO<E, A> = Effect.Effect<never, E, A> | E.Either<E, A>;
export type ParseResult<A> = Effect.Effect<never, ParseError, A>;
/**
* @since 1.0.0
*/
export type ParseResult<A> = IO<ParseError, A>;
/**
* @since 1.0.0
*/
export interface ParseError {

@@ -173,3 +169,3 @@ readonly _tag: "ParseError";

*/
export declare const eitherOrUndefined: <E, A>(self: IO<E, A>) => E.Either<E, A> | undefined;
export declare const eitherOrUndefined: <A>(self: ParseResult<A>) => E.Either<ParseError, A> | undefined;
/**

@@ -179,3 +175,3 @@ * @category optimisation

*/
export declare const flatMap: <E, E1, A, B>(self: IO<E, A>, f: (self: A) => IO<E1, B>) => IO<E | E1, B>;
export declare const flatMap: <A, B>(self: ParseResult<A>, f: (self: A) => ParseResult<B>) => ParseResult<B>;
/**

@@ -185,3 +181,3 @@ * @category optimisation

*/
export declare const map: <E, A, B>(self: IO<E, A>, f: (self: A) => B) => IO<E, B>;
export declare const map: <A, B>(self: ParseResult<A>, f: (self: A) => B) => ParseResult<B>;
//# sourceMappingURL=ParseResult.d.ts.map

@@ -7,3 +7,2 @@ "use strict";

exports.unionMember = exports.unexpected = exports.type = exports.success = exports.parseError = exports.missing = exports.map = exports.key = exports.index = exports.forbidden = exports.flatMap = exports.failures = exports.failure = exports.eitherOrUndefined = void 0;
var Debug = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/data/Debug"));
var E = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/data/Either"));

@@ -132,3 +131,3 @@ var O = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/data/Option"));

}
return Debug.bodyWithTrace((trace, restore) => Effect.flatMap(self, a => restore(f)(a)).traced(trace));
return Effect.flatMap(self, f);
};

@@ -148,5 +147,5 @@ /**

}
return Debug.bodyWithTrace((trace, restore) => Effect.map(self, restore(f)).traced(trace));
return Effect.map(self, f);
};
exports.map = map;
//# sourceMappingURL=ParseResult.js.map

@@ -47,3 +47,6 @@ "use strict";

const match = {
"Declaration": (ast, go) => (0, _Function.pipe)(getHook(ast), O.match(() => go(ast.type), handler => handler(...ast.typeParameters.map(go)))),
"Declaration": (ast, go) => (0, _Function.pipe)(getHook(ast), O.match({
onNone: () => go(ast.type),
onSome: handler => handler(...ast.typeParameters.map(go))
})),
"VoidKeyword": () => () => "void(0)",

@@ -50,0 +53,0 @@ "NeverKeyword": () => () => {

@@ -436,2 +436,3 @@ <h3 align="center">

S.UUID;
S.ULID;
```

@@ -438,0 +439,0 @@

@@ -1122,2 +1122,12 @@ /**

/**
* @category type id
* @since 1.0.0
*/
export declare const ULIDTypeId = "@effect/schema/ULIDTypeId";
/**
* @category constructors
* @since 1.0.0
*/
export declare const ULID: Schema<string>;
/**
* @category string

@@ -1124,0 +1134,0 @@ * @since 1.0.0

@@ -6,3 +6,3 @@ "use strict";

});
exports.array = exports.any = exports.annotations = exports.ValidDateTypeId = exports.ValidDateFromSelf = exports.UUIDTypeId = exports.UUID = exports.TrimmedTypeId = exports.Trim = exports.StartsWithTypeId = exports.PositiveTypeId = exports.PositiveBigintTypeId = exports.PatternTypeId = exports.NumberFromString = exports.NonPositiveTypeId = exports.NonPositiveBigintTypeId = exports.NonNegativeTypeId = exports.NonNegativeBigintTypeId = exports.NonNaNTypeId = exports.NegativeTypeId = exports.NegativeBigintTypeId = exports.MultipleOfTypeId = exports.MinLengthTypeId = exports.MinItemsTypeId = exports.MaxLengthTypeId = exports.MaxItemsTypeId = exports.LessThanTypeId = exports.LessThanOrEqualToTypeId = exports.LessThanOrEqualToBigintTypeId = exports.LessThanBigintTypeId = exports.JsonNumberTypeId = exports.JsonNumber = exports.ItemsCountTypeId = exports.IntTypeId = exports.InstanceOfTypeId = exports.IncludesTypeId = exports.GreaterThanTypeId = exports.GreaterThanOrEqualToTypeId = exports.GreaterThanOrEqualToBigintTypeId = exports.GreaterThanBigintTypeId = exports.FiniteTypeId = exports.EndsWithTypeId = exports.DateFromSelf = exports.Date = exports.BrandTypeId = exports.BetweenTypeId = exports.BetweenBigintTypeId = void 0;
exports.array = exports.any = exports.annotations = exports.ValidDateTypeId = exports.ValidDateFromSelf = exports.UUIDTypeId = exports.UUID = exports.ULIDTypeId = exports.ULID = exports.TrimmedTypeId = exports.Trim = exports.StartsWithTypeId = exports.PositiveTypeId = exports.PositiveBigintTypeId = exports.PatternTypeId = exports.NumberFromString = exports.NonPositiveTypeId = exports.NonPositiveBigintTypeId = exports.NonNegativeTypeId = exports.NonNegativeBigintTypeId = exports.NonNaNTypeId = exports.NegativeTypeId = exports.NegativeBigintTypeId = exports.MultipleOfTypeId = exports.MinLengthTypeId = exports.MinItemsTypeId = exports.MaxLengthTypeId = exports.MaxItemsTypeId = exports.LessThanTypeId = exports.LessThanOrEqualToTypeId = exports.LessThanOrEqualToBigintTypeId = exports.LessThanBigintTypeId = exports.JsonNumberTypeId = exports.JsonNumber = exports.ItemsCountTypeId = exports.IntTypeId = exports.InstanceOfTypeId = exports.IncludesTypeId = exports.GreaterThanTypeId = exports.GreaterThanOrEqualToTypeId = exports.GreaterThanOrEqualToBigintTypeId = exports.GreaterThanBigintTypeId = exports.FiniteTypeId = exports.EndsWithTypeId = exports.DateFromSelf = exports.Date = exports.BrandTypeId = exports.BetweenTypeId = exports.BetweenBigintTypeId = void 0;
Object.defineProperty(exports, "asserts", {

@@ -97,4 +97,4 @@ enumerable: true,

});
exports.lazy = exports.keyof = exports.json = exports.itemsCount = void 0;
exports.optionalElement = exports.optional = exports.optionFromSelf = exports.optionFromNullable = exports.option = exports.omit = exports.object = exports.numberFromString = exports.number = exports.nullable = exports.null = exports.not = exports.nonPositiveBigint = exports.nonPositive = exports.nonNegativeBigint = exports.nonNegative = exports.nonNaN = exports.nonEmptyArray = exports.nonEmpty = exports.never = exports.negativeBigint = exports.negative = exports.multipleOf = exports.minLength = exports.minItems = exports.message = exports.maxLength = exports.maxItems = exports.make = exports.literal = exports.lessThanOrEqualToBigint = exports.lessThanOrEqualTo = exports.lessThanBigint = exports.lessThan = exports.length = void 0;
exports.json = exports.itemsCount = void 0;
exports.optionalElement = exports.optional = exports.optionFromSelf = exports.optionFromNullable = exports.option = exports.omit = exports.object = exports.numberFromString = exports.number = exports.nullable = exports.null = exports.not = exports.nonPositiveBigint = exports.nonPositive = exports.nonNegativeBigint = exports.nonNegative = exports.nonNaN = exports.nonEmptyArray = exports.nonEmpty = exports.never = exports.negativeBigint = exports.negative = exports.multipleOf = exports.minLength = exports.minItems = exports.message = exports.maxLength = exports.maxItems = exports.make = exports.literal = exports.lessThanOrEqualToBigint = exports.lessThanOrEqualTo = exports.lessThanBigint = exports.lessThan = exports.length = exports.lazy = exports.keyof = void 0;
Object.defineProperty(exports, "parse", {

@@ -178,3 +178,2 @@ enumerable: true,

var D = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/data/Data"));
var _Debug = /*#__PURE__*/require("@effect/data/Debug");
var E = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/data/Either"));

@@ -996,3 +995,3 @@ var Equal = /*#__PURE__*/_interopRequireWildcard( /*#__PURE__*/require("@effect/data/Equal"));

const fromBrand = (constructor, options) => self => {
const decode = (0, _Debug.untracedMethod)(() => a => E.mapLeft(constructor.either(a), brandErrors => PR.parseError([PR.type(ast, a, brandErrors.map(v => v.message).join(", "))])));
const decode = a => E.mapLeft(constructor.either(a), brandErrors => PR.parseError([PR.type(ast, a, brandErrors.map(v => v.message).join(", "))]));
const ast = AST.createRefinement(self.ast, decode, false, toAnnotations({

@@ -1123,3 +1122,6 @@ typeId: BrandTypeId,

const eitherArbitrary = (left, right) => fc => fc.oneof(left(fc).map(E.left), right(fc).map(E.right));
const eitherPretty = (left, right) => E.match(e => `left(${left(e)})`, a => `right(${right(a)})`);
const eitherPretty = (left, right) => E.match({
onLeft: e => `left(${left(e)})`,
onRight: a => `right(${right(a)})`
});
const eitherInline = (left, right) => union(struct({

@@ -1153,9 +1155,12 @@ _tag: literal("Left"),

exports.eitherFromSelf = eitherFromSelf;
const either = (left, right) => transform(eitherInline(left, right), to(eitherFromSelf(left, right)), a => a._tag === "Left" ? E.left(a.left) : E.right(a.right), E.match(left => ({
_tag: "Left",
left
}), right => ({
_tag: "Right",
right
})));
const either = (left, right) => transform(eitherInline(left, right), to(eitherFromSelf(left, right)), a => a._tag === "Left" ? E.left(a.left) : E.right(a.right), E.match({
onLeft: left => ({
_tag: "Left",
left
}),
onRight: right => ({
_tag: "Right",
right
})
}));
exports.either = either;

@@ -1518,3 +1523,6 @@ const arbitraryJson = fc => fc.jsonValue().map(json => json);

const optionArbitrary = value => fc => fc.oneof(fc.constant(O.none()), value(fc).map(O.some));
const optionPretty = value => O.match(() => "none()", a => `some(${value(a)})`);
const optionPretty = value => O.match({
onNone: () => "none()",
onSome: a => `some(${value(a)})`
});
const optionInline = value => union(struct({

@@ -1546,8 +1554,11 @@ _tag: literal("None")

exports.optionFromSelf = optionFromSelf;
const option = value => transform(optionInline(value), to(optionFromSelf(value)), a => a._tag === "None" ? O.none() : O.some(a.value), O.match(() => ({
_tag: "None"
}), value => ({
_tag: "Some",
value
})));
const option = value => transform(optionInline(value), to(optionFromSelf(value)), a => a._tag === "None" ? O.none() : O.some(a.value), O.match({
onNone: () => ({
_tag: "None"
}),
onSome: value => ({
_tag: "Some",
value
})
}));
/**

@@ -1882,9 +1893,27 @@ * @category option

typeId: UUIDTypeId,
title: "UUID",
arbitrary: () => fc => fc.uuid()
}));
/**
* @category type id
* @since 1.0.0
*/
exports.UUID = UUID;
const ULIDTypeId = "@effect/schema/ULIDTypeId";
exports.ULIDTypeId = ULIDTypeId;
const ulidRegex = /^[0-7][0-9A-HJKMNP-TV-Z]{25}$/i;
/**
* @category constructors
* @since 1.0.0
*/
const ULID = /*#__PURE__*/(0, _Function.pipe)(string, /*#__PURE__*/pattern(ulidRegex, {
typeId: ULIDTypeId,
title: "ULID",
arbitrary: () => fc => fc.ulid()
}));
/**
* @category string
* @since 1.0.0
*/
exports.UUID = UUID;
exports.ULID = ULID;
const length = (length, options) => self => minLength(length, options)(maxLength(length)(self));

@@ -1891,0 +1920,0 @@ /**

@@ -69,6 +69,6 @@ /**

getHook(ast),
O.match(
() => go(ast.type),
(handler) => handler(...ast.typeParameters.map((p) => go(p)))
)
O.match({
onNone: () => go(ast.type),
onSome: (handler) => handler(...ast.typeParameters.map((p) => go(p)))
})
)

@@ -211,9 +211,9 @@ case "Literal":

getHook(ast),
O.match(
() => {
O.match({
onNone: () => {
const get = I.memoizeThunk(() => go(ast.f()))
return (fc) => fc.constant(null).chain(() => get()(fc))
},
(handler) => handler()
)
onSome: (handler) => handler()
})
)

@@ -230,4 +230,4 @@ case "Enums": {

getHook(ast),
O.match(
() =>
O.match({
onNone: () =>
(fc) =>

@@ -241,4 +241,4 @@ from(fc).filter((a) => {

}),
(handler) => handler(from)
)
onSome: (handler) => handler(from)
})
)

@@ -245,0 +245,0 @@ }

@@ -10,5 +10,5 @@ /**

import * as O from "@effect/data/Option"
import * as Order from "@effect/data/Order"
import { isString, isSymbol } from "@effect/data/Predicate"
import * as RA from "@effect/data/ReadonlyArray"
import * as Order from "@effect/data/typeclass/Order"
import { memoizeThunk } from "@effect/schema/internal/common"

@@ -1086,5 +1086,5 @@ import type { ParseResult } from "@effect/schema/ParseResult"

ast.rest,
O.match(
() => createTuple([...ast.elements, newElement], O.none(), ast.isReadonly),
(rest) => {
O.match({
onNone: () => createTuple([...ast.elements, newElement], O.none(), ast.isReadonly),
onSome: (rest) => {
if (newElement.isOptional) {

@@ -1095,3 +1095,3 @@ throw new Error("An optional element cannot follow a rest element. ts(1266)")

}
)
})
)

@@ -1098,0 +1098,0 @@ }

@@ -5,3 +5,2 @@ /**

import { untraced, untracedMethod } from "@effect/data/Debug"
import * as E from "@effect/data/Either"

@@ -37,5 +36,5 @@ import { pipe } from "@effect/data/Function"

const getOption = (ast: AST.AST) => {
const parser = go(ast)
return (input: unknown, options?: ParseOptions) =>
O.fromEither<any, any>(parser(input, options) as any)
const parser = getEither(ast)
return (input: unknown, options?: ParseOptions): O.Option<any> =>
O.getRight(parser(input, options))
}

@@ -289,89 +288,102 @@

const go = untracedMethod(() =>
(ast: AST.AST, isBoundary = true): Parser<any, any> => {
switch (ast._tag) {
case "Refinement": {
if (ast.isReversed) {
const from = go(AST.to(ast), isBoundary)
const to = go(reverse(dropRightRefinement(ast.from)), false)
return (i, options) =>
handleForbidden(PR.flatMap(from(i, options), (a) => to(a, options)), options)
} else {
const from = go(ast.from, isBoundary)
return (i, options) =>
handleForbidden(PR.flatMap(from(i, options), (a) => ast.decode(a, options)), options)
}
const go = (ast: AST.AST, isBoundary = true): Parser<any, any> => {
switch (ast._tag) {
case "Refinement": {
if (ast.isReversed) {
const from = go(AST.to(ast), isBoundary)
const to = go(reverse(dropRightRefinement(ast.from)), false)
return (i, options) =>
handleForbidden(PR.flatMap(from(i, options), (a) => to(a, options)), options)
} else {
const from = go(ast.from, isBoundary)
return (i, options) =>
handleForbidden(PR.flatMap(from(i, options), (a) => ast.decode(a, options)), options)
}
case "Transform": {
const to = go(ast.to, false)
if (isBoundary) {
const from = go(ast.from)
return (i1, options) =>
handleForbidden(
PR.flatMap(
from(i1, options),
(a) => PR.flatMap(ast.decode(a, options), (i2) => to(i2, options))
),
options
)
} else {
return (a, options) =>
handleForbidden(PR.flatMap(ast.decode(a, options), (i2) => to(i2, options)), options)
}
}
case "Transform": {
const to = go(ast.to, false)
if (isBoundary) {
const from = go(ast.from)
return (i1, options) =>
handleForbidden(
PR.flatMap(
from(i1, options),
(a) => PR.flatMap(ast.decode(a, options), (i2) => to(i2, options))
),
options
)
} else {
return (a, options) =>
handleForbidden(PR.flatMap(ast.decode(a, options), (i2) => to(i2, options)), options)
}
case "Declaration": {
const decode = ast.decode(...ast.typeParameters)
return (i, options) => handleForbidden(decode(i, options), options)
}
case "Declaration": {
const decode = ast.decode(...ast.typeParameters)
return (i, options) => handleForbidden(decode(i, options), options)
}
case "Literal":
return fromRefinement(ast, (u): u is typeof ast.literal => u === ast.literal)
case "UniqueSymbol":
return fromRefinement(ast, (u): u is typeof ast.symbol => u === ast.symbol)
case "UndefinedKeyword":
return fromRefinement(ast, P.isUndefined)
case "VoidKeyword":
return fromRefinement(ast, P.isUndefined)
case "NeverKeyword":
return fromRefinement(ast, P.isNever)
case "UnknownKeyword":
case "AnyKeyword":
return PR.success
case "StringKeyword":
return fromRefinement(ast, P.isString)
case "NumberKeyword":
return fromRefinement(ast, P.isNumber)
case "BooleanKeyword":
return fromRefinement(ast, P.isBoolean)
case "BigIntKeyword":
return fromRefinement(ast, P.isBigint)
case "SymbolKeyword":
return fromRefinement(ast, P.isSymbol)
case "ObjectKeyword":
return fromRefinement(ast, P.isObject)
case "Enums":
return fromRefinement(ast, (u): u is any => ast.enums.some(([_, value]) => value === u))
case "TemplateLiteral": {
const regex = getTemplateLiteralRegex(ast)
return fromRefinement(ast, (u): u is any => P.isString(u) && regex.test(u))
}
case "Tuple": {
const elements = ast.elements.map((e) => go(e.type, isBoundary))
const rest = pipe(ast.rest, O.map(RA.mapNonEmpty((ast) => go(ast))))
let requiredLen = ast.elements.filter((e) => !e.isOptional).length
if (O.isSome(ast.rest)) {
requiredLen += ast.rest.value.length - 1
}
case "Literal":
return fromRefinement(ast, (u): u is typeof ast.literal => u === ast.literal)
case "UniqueSymbol":
return fromRefinement(ast, (u): u is typeof ast.symbol => u === ast.symbol)
case "UndefinedKeyword":
return fromRefinement(ast, P.isUndefined)
case "VoidKeyword":
return fromRefinement(ast, P.isUndefined)
case "NeverKeyword":
return fromRefinement(ast, P.isNever)
case "UnknownKeyword":
case "AnyKeyword":
return PR.success
case "StringKeyword":
return fromRefinement(ast, P.isString)
case "NumberKeyword":
return fromRefinement(ast, P.isNumber)
case "BooleanKeyword":
return fromRefinement(ast, P.isBoolean)
case "BigIntKeyword":
return fromRefinement(ast, P.isBigint)
case "SymbolKeyword":
return fromRefinement(ast, P.isSymbol)
case "ObjectKeyword":
return fromRefinement(ast, P.isObject)
case "Enums":
return fromRefinement(ast, (u): u is any => ast.enums.some(([_, value]) => value === u))
case "TemplateLiteral": {
const regex = getTemplateLiteralRegex(ast)
return fromRefinement(ast, (u): u is any => P.isString(u) && regex.test(u))
}
case "Tuple": {
const elements = ast.elements.map((e) => go(e.type, isBoundary))
const rest = pipe(ast.rest, O.map(RA.mapNonEmpty((ast) => go(ast))))
let requiredLen = ast.elements.filter((e) => !e.isOptional).length
if (O.isSome(ast.rest)) {
requiredLen += ast.rest.value.length - 1
return (input: unknown, options) => {
if (!Array.isArray(input)) {
return PR.failure(PR.type(unknownArray, input))
}
return (input: unknown, options) => {
if (!Array.isArray(input)) {
return PR.failure(PR.type(unknownArray, input))
const allErrors = options?.errors === "all"
const es: Array<[number, PR.ParseErrors]> = []
let stepKey = 0
// ---------------------------------------------
// handle missing indexes
// ---------------------------------------------
const len = input.length
for (let i = len; i <= requiredLen - 1; i++) {
const e = PR.index(i, [PR.missing])
if (allErrors) {
es.push([stepKey++, e])
continue
} else {
return PR.failure(e)
}
const allErrors = options?.errors === "all"
const es: Array<[number, PR.ParseErrors]> = []
let stepKey = 0
// ---------------------------------------------
// handle missing indexes
// ---------------------------------------------
const len = input.length
for (let i = len; i <= requiredLen - 1; i++) {
const e = PR.index(i, [PR.missing])
}
// ---------------------------------------------
// handle excess indexes
// ---------------------------------------------
if (O.isNone(ast.rest)) {
for (let i = ast.elements.length; i <= len - 1; i++) {
const e = PR.index(i, [PR.unexpected(input[i])])
if (allErrors) {

@@ -381,42 +393,122 @@ es.push([stepKey++, e])

} else {
return PR.failure(e)
return PR.failures(mutableAppend(sortByIndex(es), e))
}
}
}
// ---------------------------------------------
// handle excess indexes
// ---------------------------------------------
if (O.isNone(ast.rest)) {
for (let i = ast.elements.length; i <= len - 1; i++) {
const e = PR.index(i, [PR.unexpected(input[i])])
if (allErrors) {
es.push([stepKey++, e])
continue
const output: Array<[number, any]> = []
let i = 0
type State = {
es: typeof es
output: typeof output
}
let queue: Array<(_: State) => Effect.Effect<never, PR.ParseError, void>> | undefined =
undefined
// ---------------------------------------------
// handle elements
// ---------------------------------------------
for (; i < elements.length; i++) {
if (len < i + 1) {
// the input element is missing...
if (ast.elements[i].isOptional) {
continue
}
} else {
const parser = elements[i]
const te = parser(input[i], options)
const eu = PR.eitherOrUndefined(te)
if (eu) {
if (E.isLeft(eu)) {
// the input element is present but is not valid
const e = PR.index(i, eu.left.errors)
if (allErrors) {
es.push([stepKey++, e])
continue
} else {
return PR.failures(mutableAppend(sortByIndex(es), e))
}
}
output.push([stepKey++, eu.right])
} else {
const nk = stepKey++
const index = i
if (!queue) {
queue = []
}
queue.push(
({ es, output }: State) =>
Effect.flatMap(Effect.either(te), (t) => {
if (E.isLeft(t)) {
// the input element is present but is not valid
const e = PR.index(index, t.left.errors)
if (allErrors) {
es.push([nk, e])
return Effect.unit
} else {
return PR.failures(mutableAppend(sortByIndex(es), e))
}
}
output.push([nk, t.right])
return Effect.unit
})
)
}
}
}
// ---------------------------------------------
// handle rest element
// ---------------------------------------------
if (O.isSome(rest)) {
const head = RA.headNonEmpty(rest.value)
const tail = RA.tailNonEmpty(rest.value)
for (; i < len - tail.length; i++) {
const te = head(input[i], options)
const eu = PR.eitherOrUndefined(te)
if (eu) {
if (E.isLeft(eu)) {
const e = PR.index(i, eu.left.errors)
if (allErrors) {
es.push([stepKey++, e])
continue
} else {
return PR.failures(mutableAppend(sortByIndex(es), e))
}
} else {
return PR.failures(mutableAppend(sortByIndex(es), e))
output.push([stepKey++, eu.right])
}
} else {
const nk = stepKey++
const index = i
if (!queue) {
queue = []
}
queue.push(
({ es, output }: State) =>
Effect.flatMap(Effect.either(te), (t) => {
if (E.isLeft(t)) {
const e = PR.index(index, t.left.errors)
if (allErrors) {
es.push([nk, e])
return Effect.unit
} else {
return PR.failures(mutableAppend(sortByIndex(es), e))
}
} else {
output.push([nk, t.right])
return Effect.unit
}
})
)
}
}
const output: Array<[number, any]> = []
let i = 0
type State = {
es: typeof es
output: typeof output
}
let queue: Array<(_: State) => Effect.Effect<never, PR.ParseError, void>> | undefined =
undefined
// ---------------------------------------------
// handle elements
// handle post rest elements
// ---------------------------------------------
for (; i < elements.length; i++) {
for (let j = 0; j < tail.length; j++) {
i += j
if (len < i + 1) {
// the input element is missing...
if (ast.elements[i].isOptional) {
continue
}
continue
} else {
const parser = elements[i]
const te = parser(input[i], options)
const te = tail[j](input[i], options)
const eu = PR.eitherOrUndefined(te)

@@ -442,188 +534,85 @@ if (eu) {

queue.push(
untracedMethod(() =>
({ es, output }: State) =>
Effect.flatMap(Effect.either(te), (t) => {
if (E.isLeft(t)) {
// the input element is present but is not valid
const e = PR.index(index, t.left.errors)
if (allErrors) {
es.push([nk, e])
return Effect.unit()
} else {
return PR.failures(mutableAppend(sortByIndex(es), e))
}
}
output.push([nk, t.right])
return Effect.unit()
})
)
)
}
}
}
// ---------------------------------------------
// handle rest element
// ---------------------------------------------
if (O.isSome(rest)) {
const head = RA.headNonEmpty(rest.value)
const tail = RA.tailNonEmpty(rest.value)
for (; i < len - tail.length; i++) {
const te = head(input[i], options)
const eu = PR.eitherOrUndefined(te)
if (eu) {
if (E.isLeft(eu)) {
const e = PR.index(i, eu.left.errors)
if (allErrors) {
es.push([stepKey++, e])
continue
} else {
return PR.failures(mutableAppend(sortByIndex(es), e))
}
} else {
output.push([stepKey++, eu.right])
}
} else {
const nk = stepKey++
const index = i
if (!queue) {
queue = []
}
queue.push(
untracedMethod(() =>
({ es, output }: State) =>
Effect.flatMap(Effect.either(te), (t) => {
if (E.isLeft(t)) {
const e = PR.index(index, t.left.errors)
if (allErrors) {
es.push([nk, e])
return Effect.unit()
} else {
return PR.failures(mutableAppend(sortByIndex(es), e))
}
({ es, output }: State) =>
Effect.flatMap(Effect.either(te), (t) => {
if (E.isLeft(t)) {
// the input element is present but is not valid
const e = PR.index(index, t.left.errors)
if (allErrors) {
es.push([nk, e])
return Effect.unit
} else {
output.push([nk, t.right])
return Effect.unit()
return PR.failures(mutableAppend(sortByIndex(es), e))
}
})
)
}
output.push([nk, t.right])
return Effect.unit
})
)
}
}
// ---------------------------------------------
// handle post rest elements
// ---------------------------------------------
for (let j = 0; j < tail.length; j++) {
i += j
if (len < i + 1) {
continue
} else {
const te = tail[j](input[i], options)
const eu = PR.eitherOrUndefined(te)
if (eu) {
if (E.isLeft(eu)) {
// the input element is present but is not valid
const e = PR.index(i, eu.left.errors)
if (allErrors) {
es.push([stepKey++, e])
continue
} else {
return PR.failures(mutableAppend(sortByIndex(es), e))
}
}
output.push([stepKey++, eu.right])
} else {
const nk = stepKey++
const index = i
if (!queue) {
queue = []
}
queue.push(
untracedMethod(() =>
({ es, output }: State) =>
Effect.flatMap(Effect.either(te), (t) => {
if (E.isLeft(t)) {
// the input element is present but is not valid
const e = PR.index(index, t.left.errors)
if (allErrors) {
es.push([nk, e])
return Effect.unit()
} else {
return PR.failures(mutableAppend(sortByIndex(es), e))
}
}
output.push([nk, t.right])
return Effect.unit()
})
)
)
}
}
}
}
}
// ---------------------------------------------
// compute output
// ---------------------------------------------
const computeResult = ({ es, output }: State) =>
RA.isNonEmptyArray(es) ?
PR.failures(sortByIndex(es)) :
PR.success(sortByIndex(output))
if (queue && queue.length > 0) {
const cqueue = queue
return untraced(() =>
Effect.suspend(() => {
const state: State = {
es: Array.from(es),
output: Array.from(output)
}
return Effect.flatMap(
Effect.forEachParDiscard(cqueue, (f) => f(state)),
() => computeResult(state)
)
})
// ---------------------------------------------
// compute output
// ---------------------------------------------
const computeResult = ({ es, output }: State) =>
RA.isNonEmptyArray(es) ?
PR.failures(sortByIndex(es)) :
PR.success(sortByIndex(output))
if (queue && queue.length > 0) {
const cqueue = queue
return Effect.suspend(() => {
const state: State = {
es: Array.from(es),
output: Array.from(output)
}
return Effect.flatMap(
Effect.forEach(cqueue, (f) => f(state), { concurrency: "unbounded", discard: true }),
() => computeResult(state)
)
}
return computeResult({ output, es })
})
}
return computeResult({ output, es })
}
case "TypeLiteral": {
if (ast.propertySignatures.length === 0 && ast.indexSignatures.length === 0) {
return fromRefinement(ast, P.isNotNullable)
}
case "TypeLiteral": {
if (ast.propertySignatures.length === 0 && ast.indexSignatures.length === 0) {
return fromRefinement(ast, P.isNotNullable)
}
const propertySignatures = ast.propertySignatures.map((ps) => go(ps.type, isBoundary))
const indexSignatures = ast.indexSignatures.map((is) =>
[go(is.parameter, isBoundary), go(is.type, isBoundary)] as const
)
const parameter = go(AST.createUnion(
ast.indexSignatures.map((is) => AST.getParameterBase(is.parameter))
))
const expectedKeys: any = {}
for (let i = 0; i < propertySignatures.length; i++) {
expectedKeys[ast.propertySignatures[i].name] = null
}
return (input: unknown, options) => {
if (!P.isRecord(input)) {
return PR.failure(PR.type(unknownRecord, input))
}
const propertySignatures = ast.propertySignatures.map((ps) => go(ps.type, isBoundary))
const indexSignatures = ast.indexSignatures.map((is) =>
[go(is.parameter, isBoundary), go(is.type, isBoundary)] as const
)
const parameter = go(AST.createUnion(
ast.indexSignatures.map((is) => AST.getParameterBase(is.parameter))
))
const expectedKeys: any = {}
for (let i = 0; i < propertySignatures.length; i++) {
expectedKeys[ast.propertySignatures[i].name] = null
}
return (input: unknown, options) => {
if (!P.isRecord(input)) {
return PR.failure(PR.type(unknownRecord, input))
}
const allErrors = options?.errors === "all"
const es: Array<[number, PR.ParseErrors]> = []
let stepKey = 0
const allErrors = options?.errors === "all"
const es: Array<[number, PR.ParseErrors]> = []
let stepKey = 0
// ---------------------------------------------
// handle excess properties
// ---------------------------------------------
const onExcessPropertyError = options?.onExcessProperty === "error"
if (onExcessPropertyError) {
for (const key of I.ownKeys(input)) {
if (!(Object.prototype.hasOwnProperty.call(expectedKeys, key))) {
const te = parameter(key)
const eu = PR.eitherOrUndefined(te)
if (eu && E.isLeft(eu)) {
const e = PR.key(key, [PR.unexpected(input[key])])
if (allErrors) {
es.push([stepKey++, e])
continue
} else {
return PR.failures(mutableAppend(sortByIndex(es), e))
}
// ---------------------------------------------
// handle excess properties
// ---------------------------------------------
const onExcessPropertyError = options?.onExcessProperty === "error"
if (onExcessPropertyError) {
for (const key of I.ownKeys(input)) {
if (!(Object.prototype.hasOwnProperty.call(expectedKeys, key))) {
const te = parameter(key)
const eu = PR.eitherOrUndefined(te)
if (eu && E.isLeft(eu)) {
const e = PR.key(key, [PR.unexpected(input[key])])
if (allErrors) {
es.push([stepKey++, e])
continue
} else {
return PR.failures(mutableAppend(sortByIndex(es), e))
}

@@ -633,66 +622,27 @@ }

}
}
// ---------------------------------------------
// handle property signatures
// ---------------------------------------------
const output: any = {}
type State = {
es: typeof es
output: typeof output
}
let queue:
| Array<(state: State) => Effect.Effect<never, PR.ParseError, void>>
| undefined = undefined
// ---------------------------------------------
// handle property signatures
// ---------------------------------------------
const output: any = {}
type State = {
es: typeof es
output: typeof output
}
let queue:
| Array<(state: State) => Effect.Effect<never, PR.ParseError, void>>
| undefined = undefined
for (let i = 0; i < propertySignatures.length; i++) {
const ps = ast.propertySignatures[i]
const parser = propertySignatures[i]
const name = ps.name
if (Object.prototype.hasOwnProperty.call(input, name)) {
const te = parser(input[name], options)
const eu = PR.eitherOrUndefined(te)
if (eu) {
if (E.isLeft(eu)) {
// the input key is present but is not valid
const e = PR.key(name, eu.left.errors)
if (allErrors) {
es.push([stepKey++, e])
continue
} else {
return PR.failures(mutableAppend(sortByIndex(es), e))
}
}
output[name] = eu.right
} else {
const nk = stepKey++
const index = name
if (!queue) {
queue = []
}
queue.push(
untracedMethod(() =>
({ es, output }: State) =>
Effect.flatMap(Effect.either(te), (t) => {
if (E.isLeft(t)) {
// the input key is present but is not valid
const e = PR.key(index, t.left.errors)
if (allErrors) {
es.push([nk, e])
return Effect.unit()
} else {
return PR.failures(mutableAppend(sortByIndex(es), e))
}
}
output[index] = t.right
return Effect.unit()
})
)
)
}
} else {
// ---------------------------------------------
// handle missing keys
// ---------------------------------------------
if (!ps.isOptional) {
const e = PR.key(name, [PR.missing])
for (let i = 0; i < propertySignatures.length; i++) {
const ps = ast.propertySignatures[i]
const parser = propertySignatures[i]
const name = ps.name
if (Object.prototype.hasOwnProperty.call(input, name)) {
const te = parser(input[name], options)
const eu = PR.eitherOrUndefined(te)
if (eu) {
if (E.isLeft(eu)) {
// the input key is present but is not valid
const e = PR.key(name, eu.left.errors)
if (allErrors) {

@@ -702,239 +652,274 @@ es.push([stepKey++, e])

} else {
return PR.failure(e)
return PR.failures(mutableAppend(sortByIndex(es), e))
}
}
output[name] = eu.right
} else {
const nk = stepKey++
const index = name
if (!queue) {
queue = []
}
queue.push(
({ es, output }: State) =>
Effect.flatMap(Effect.either(te), (t) => {
if (E.isLeft(t)) {
// the input key is present but is not valid
const e = PR.key(index, t.left.errors)
if (allErrors) {
es.push([nk, e])
return Effect.unit
} else {
return PR.failures(mutableAppend(sortByIndex(es), e))
}
}
output[index] = t.right
return Effect.unit
})
)
}
} else {
// ---------------------------------------------
// handle missing keys
// ---------------------------------------------
if (!ps.isOptional) {
const e = PR.key(name, [PR.missing])
if (allErrors) {
es.push([stepKey++, e])
continue
} else {
return PR.failure(e)
}
}
}
}
// ---------------------------------------------
// handle index signatures
// ---------------------------------------------
for (let i = 0; i < indexSignatures.length; i++) {
const parameter = indexSignatures[i][0]
const type = indexSignatures[i][1]
const keys = I.getKeysForIndexSignature(input, ast.indexSignatures[i].parameter)
for (const key of keys) {
if (Object.prototype.hasOwnProperty.call(expectedKeys, key)) {
continue
}
// ---------------------------------------------
// handle keys
// ---------------------------------------------
const keu = PR.eitherOrUndefined(parameter(key, options))
if (keu) {
if (E.isLeft(keu)) {
const e = PR.key(key, keu.left.errors)
if (allErrors) {
es.push([stepKey++, e])
continue
} else {
return PR.failures(mutableAppend(sortByIndex(es), e))
}
// ---------------------------------------------
// handle index signatures
// ---------------------------------------------
for (let i = 0; i < indexSignatures.length; i++) {
const parameter = indexSignatures[i][0]
const type = indexSignatures[i][1]
const keys = I.getKeysForIndexSignature(input, ast.indexSignatures[i].parameter)
for (const key of keys) {
if (Object.prototype.hasOwnProperty.call(expectedKeys, key)) {
continue
}
// ---------------------------------------------
// handle keys
// ---------------------------------------------
const keu = PR.eitherOrUndefined(parameter(key, options))
if (keu) {
if (E.isLeft(keu)) {
const e = PR.key(key, keu.left.errors)
if (allErrors) {
es.push([stepKey++, e])
continue
} else {
return PR.failures(mutableAppend(sortByIndex(es), e))
}
}
// there's no else here because index signature parameters are restricted to primitives
}
// there's no else here because index signature parameters are restricted to primitives
// ---------------------------------------------
// handle values
// ---------------------------------------------
const vpr = type(input[key], options)
const veu = PR.eitherOrUndefined(vpr)
if (veu) {
if (E.isLeft(veu)) {
const e = PR.key(key, veu.left.errors)
if (allErrors) {
es.push([stepKey++, e])
continue
} else {
return PR.failures(mutableAppend(sortByIndex(es), e))
}
// ---------------------------------------------
// handle values
// ---------------------------------------------
const vpr = type(input[key], options)
const veu = PR.eitherOrUndefined(vpr)
if (veu) {
if (E.isLeft(veu)) {
const e = PR.key(key, veu.left.errors)
if (allErrors) {
es.push([stepKey++, e])
continue
} else {
output[key] = veu.right
return PR.failures(mutableAppend(sortByIndex(es), e))
}
} else {
const nk = stepKey++
const index = key
if (!queue) {
queue = []
}
queue.push(
untracedMethod(() =>
({ es, output }: State) =>
Effect.flatMap(
Effect.either(vpr),
(tv) => {
if (E.isLeft(tv)) {
const e = PR.key(index, tv.left.errors)
if (allErrors) {
es.push([nk, e])
return Effect.unit()
} else {
return PR.failures(mutableAppend(sortByIndex(es), e))
}
} else {
output[key] = tv.right
return Effect.unit()
}
output[key] = veu.right
}
} else {
const nk = stepKey++
const index = key
if (!queue) {
queue = []
}
queue.push(
({ es, output }: State) =>
Effect.flatMap(
Effect.either(vpr),
(tv) => {
if (E.isLeft(tv)) {
const e = PR.key(index, tv.left.errors)
if (allErrors) {
es.push([nk, e])
return Effect.unit
} else {
return PR.failures(mutableAppend(sortByIndex(es), e))
}
)
} else {
output[key] = tv.right
return Effect.unit
}
}
)
)
}
)
}
}
// ---------------------------------------------
// compute output
// ---------------------------------------------
const computeResult = ({ es, output }: State) =>
RA.isNonEmptyArray(es) ?
PR.failures(sortByIndex(es)) :
PR.success(output)
if (queue && queue.length > 0) {
const cqueue = queue
return untraced(() =>
Effect.suspend(() => {
const state: State = {
es: Array.from(es),
output: Object.assign({}, output)
}
return Effect.flatMap(
Effect.forEachParDiscard(cqueue, (f) => f(state)),
() => computeResult(state)
)
})
}
// ---------------------------------------------
// compute output
// ---------------------------------------------
const computeResult = ({ es, output }: State) =>
RA.isNonEmptyArray(es) ?
PR.failures(sortByIndex(es)) :
PR.success(output)
if (queue && queue.length > 0) {
const cqueue = queue
return Effect.suspend(() => {
const state: State = {
es: Array.from(es),
output: Object.assign({}, output)
}
return Effect.flatMap(
Effect.forEach(cqueue, (f) => f(state), {
concurrency: "unbounded",
discard: true
}),
() => computeResult(state)
)
}
return computeResult({ es, output })
})
}
return computeResult({ es, output })
}
case "Union": {
const searchTree = _getSearchTree(ast.types)
const ownKeys = I.ownKeys(searchTree.keys)
const len = ownKeys.length
const map = new Map<any, Parser<any, any>>()
for (let i = 0; i < ast.types.length; i++) {
map.set(ast.types[i], go(ast.types[i], true)) // <= this must be true
}
return (input, options) => {
const es: Array<[number, PR.ParseErrors]> = []
let stepKey = 0
let candidates: Array<AST.AST> = []
if (len > 0) {
// if there is at least one key then input must be an object
if (P.isRecord(input)) {
for (let i = 0; i < len; i++) {
const name = ownKeys[i]
const buckets = searchTree.keys[name].buckets
// for each property that should contain a literal, check if the input contains that property
if (Object.prototype.hasOwnProperty.call(input, name)) {
const literal = String(input[name])
// check that the value obtained from the input for the property corresponds to an existing bucket
if (Object.prototype.hasOwnProperty.call(buckets, literal)) {
// retrive the minimal set of candidates for decoding
candidates = candidates.concat(buckets[literal])
} else {
es.push([
stepKey++,
PR.key(name, [PR.type(
searchTree.keys[name].ast,
input[name]
)])
])
}
}
case "Union": {
const searchTree = _getSearchTree(ast.types)
const ownKeys = I.ownKeys(searchTree.keys)
const len = ownKeys.length
const map = new Map<any, Parser<any, any>>()
for (let i = 0; i < ast.types.length; i++) {
map.set(ast.types[i], go(ast.types[i], true)) // <= this must be true
}
return (input, options) => {
const es: Array<[number, PR.ParseErrors]> = []
let stepKey = 0
let candidates: Array<AST.AST> = []
if (len > 0) {
// if there is at least one key then input must be an object
if (P.isRecord(input)) {
for (let i = 0; i < len; i++) {
const name = ownKeys[i]
const buckets = searchTree.keys[name].buckets
// for each property that should contain a literal, check if the input contains that property
if (Object.prototype.hasOwnProperty.call(input, name)) {
const literal = String(input[name])
// check that the value obtained from the input for the property corresponds to an existing bucket
if (Object.prototype.hasOwnProperty.call(buckets, literal)) {
// retrive the minimal set of candidates for decoding
candidates = candidates.concat(buckets[literal])
} else {
es.push([stepKey++, PR.key(name, [PR.missing])])
es.push([
stepKey++,
PR.key(name, [PR.type(
searchTree.keys[name].ast,
input[name]
)])
])
}
} else {
es.push([stepKey++, PR.key(name, [PR.missing])])
}
} else {
es.push([stepKey++, PR.type(unknownRecord, input)])
}
} else {
es.push([stepKey++, PR.type(unknownRecord, input)])
}
if (searchTree.otherwise.length > 0) {
candidates = candidates.concat(searchTree.otherwise)
}
}
if (searchTree.otherwise.length > 0) {
candidates = candidates.concat(searchTree.otherwise)
}
let queue:
| Array<(state: State) => Effect.Effect<never, PR.ParseError, unknown>>
| undefined = undefined
let queue:
| Array<(state: State) => Effect.Effect<never, PR.ParseError, unknown>>
| undefined = undefined
type State = {
finalResult?: any
es: typeof es
}
type State = {
finalResult?: any
es: typeof es
}
for (let i = 0; i < candidates.length; i++) {
const pr = map.get(candidates[i])!(input, options)
// the members of a union are ordered based on which one should be decoded first,
// therefore if one member has added a task, all subsequent members must
// also add a task to the queue even if they are synchronous
const eu = !queue || queue.length === 0 ? PR.eitherOrUndefined(pr) : undefined
if (eu) {
if (E.isRight(eu)) {
return PR.success(eu.right)
} else {
es.push([stepKey++, PR.unionMember(eu.left.errors)])
}
for (let i = 0; i < candidates.length; i++) {
const pr = map.get(candidates[i])!(input, options)
// the members of a union are ordered based on which one should be decoded first,
// therefore if one member has added a task, all subsequent members must
// also add a task to the queue even if they are synchronous
const eu = !queue || queue.length === 0 ? PR.eitherOrUndefined(pr) : undefined
if (eu) {
if (E.isRight(eu)) {
return PR.success(eu.right)
} else {
const nk = stepKey++
if (!queue) {
queue = []
}
queue.push(
untracedMethod(() =>
(state) =>
Effect.suspend(() => {
if ("finalResult" in state) {
return Effect.unit()
es.push([stepKey++, PR.unionMember(eu.left.errors)])
}
} else {
const nk = stepKey++
if (!queue) {
queue = []
}
queue.push(
(state) =>
Effect.suspend(() => {
if ("finalResult" in state) {
return Effect.unit
} else {
return Effect.flatMap(Effect.either(pr), (t) => {
if (E.isRight(t)) {
state.finalResult = PR.success(t.right)
} else {
return Effect.flatMap(Effect.either(pr), (t) => {
if (E.isRight(t)) {
state.finalResult = PR.success(t.right)
} else {
state.es.push([nk, PR.unionMember(t.left.errors)])
}
return Effect.unit()
})
state.es.push([nk, PR.unionMember(t.left.errors)])
}
return Effect.unit
})
)
)
}
}
})
)
}
}
// ---------------------------------------------
// compute output
// ---------------------------------------------
const computeResult = (es: State["es"]) =>
RA.isNonEmptyArray(es) ?
PR.failures(sortByIndex(es)) :
// this should never happen
PR.failure(PR.type(AST.neverKeyword, input))
// ---------------------------------------------
// compute output
// ---------------------------------------------
const computeResult = (es: State["es"]) =>
RA.isNonEmptyArray(es) ?
PR.failures(sortByIndex(es)) :
// this should never happen
PR.failure(PR.type(AST.neverKeyword, input))
if (queue && queue.length > 0) {
const cqueue = queue
return untraced(() =>
Effect.suspend(() => {
const state: State = { es: Array.from(es) }
return Effect.flatMap(
Effect.forEachDiscard(cqueue, (f) => f(state)),
() => {
if ("finalResult" in state) {
return state.finalResult
}
return computeResult(state.es)
}
)
})
if (queue && queue.length > 0) {
const cqueue = queue
return Effect.suspend(() => {
const state: State = { es: Array.from(es) }
return Effect.flatMap(
Effect.forEach(cqueue, (f) => f(state), {
concurrency: 1,
discard: true
}),
() => {
if ("finalResult" in state) {
return state.finalResult
}
return computeResult(state.es)
}
)
}
return computeResult(es)
})
}
return computeResult(es)
}
case "Lazy": {
const get = I.memoizeThunk(() => go(ast.f(), isBoundary))
return (a, options) => get()(a, options)
}
}
case "Lazy": {
const get = I.memoizeThunk(() => go(ast.f(), isBoundary))
return (a, options) => get()(a, options)
}
}
)
}

@@ -941,0 +926,0 @@ const fromRefinement = <A>(ast: AST.AST, refinement: (u: unknown) => u is A): Parser<unknown, A> =>

@@ -5,3 +5,2 @@ /**

import * as Debug from "@effect/data/Debug"
import * as E from "@effect/data/Either"

@@ -16,3 +15,3 @@ import * as O from "@effect/data/Option"

*/
export type IO<E, A> = Effect.Effect<never, E, A> | E.Either<E, A>
export type ParseResult<A> = Effect.Effect<never, ParseError, A>

@@ -22,7 +21,2 @@ /**

*/
export type ParseResult<A> = IO<ParseError, A>
/**
* @since 1.0.0
*/
export interface ParseError {

@@ -124,7 +118,3 @@ readonly _tag: "ParseError"

errors: NonEmptyReadonlyArray<ParseErrors>
): Index => ({
_tag: "Index",
index,
errors
})
): Index => ({ _tag: "Index", index, errors })

@@ -154,7 +144,3 @@ /**

errors: NonEmptyReadonlyArray<ParseErrors>
): Key => ({
_tag: "Key",
key,
errors
})
): Key => ({ _tag: "Key", key, errors })

@@ -192,5 +178,3 @@ /**

*/
export const unexpected = (
actual: unknown
): Unexpected => ({
export const unexpected = (actual: unknown): Unexpected => ({
_tag: "Unexpected",

@@ -215,5 +199,3 @@ actual

*/
export const unionMember = (
errors: NonEmptyReadonlyArray<ParseErrors>
): UnionMember => ({
export const unionMember = (errors: NonEmptyReadonlyArray<ParseErrors>): UnionMember => ({
_tag: "UnionMember",

@@ -239,5 +221,4 @@ errors

*/
export const failures = (
es: NonEmptyReadonlyArray<ParseErrors>
): ParseResult<never> => E.left(parseError(es))
export const failures = (es: NonEmptyReadonlyArray<ParseErrors>): ParseResult<never> =>
E.left(parseError(es))

@@ -248,3 +229,5 @@ /**

*/
export const eitherOrUndefined = <E, A>(self: IO<E, A>): E.Either<E, A> | undefined => {
export const eitherOrUndefined = <A>(
self: ParseResult<A>
): E.Either<ParseError, A> | undefined => {
const s: any = self

@@ -260,6 +243,6 @@ if (s["_tag"] === "Left" || s["_tag"] === "Right") {

*/
export const flatMap = <E, E1, A, B>(
self: IO<E, A>,
f: (self: A) => IO<E1, B>
): IO<E | E1, B> => {
export const flatMap = <A, B>(
self: ParseResult<A>,
f: (self: A) => ParseResult<B>
): ParseResult<B> => {
const s: any = self

@@ -272,5 +255,3 @@ if (s["_tag"] === "Left") {

}
return Debug.bodyWithTrace((trace, restore) =>
Effect.flatMap(self, (a) => restore(f)(a)).traced(trace)
)
return Effect.flatMap(self, f)
}

@@ -282,6 +263,3 @@

*/
export const map = <E, A, B>(
self: IO<E, A>,
f: (self: A) => B
): IO<E, B> => {
export const map = <A, B>(self: ParseResult<A>, f: (self: A) => B): ParseResult<B> => {
const s: any = self

@@ -294,3 +272,3 @@ if (s["_tag"] === "Left") {

}
return Debug.bodyWithTrace((trace, restore) => Effect.map(self, restore(f)).traced(trace))
return Effect.map(self, f)
}

@@ -57,6 +57,6 @@ /**

getHook(ast),
O.match(
() => go(ast.type),
(handler) => handler(...ast.typeParameters.map(go))
)
O.match({
onNone: () => go(ast.type),
onSome: (handler) => handler(...ast.typeParameters.map(go))
})
),

@@ -63,0 +63,0 @@ "VoidKeyword": () => () => "void(0)",

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is too big to display

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc