Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

@6river/reason-guard

Package Overview
Dependencies
Maintainers
5
Versions
52
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@6river/reason-guard - npm Package Compare versions

Comparing version 3.7.2 to 3.7.3

2

dist/src/arrayHasType.js

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

if (!itemGuard(input[i], innerErrors, innerConfs, innerContext)) {
throw new ContextError_1.CompositeError(innerErrors.map((err) => new ContextError_1.ContextError(`element ${i}: ${err.message}`, err instanceof ContextError_1.ContextError ? err.context : innerContext)));
throw new ContextError_1.CompositeError(innerErrors.map(err => new ContextError_1.ContextError(`element ${i}: ${err.message}`, err instanceof ContextError_1.ContextError ? err.context : innerContext)));
}

@@ -16,0 +16,0 @@ }

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

const ContextError_1 = require("./ContextError");
exports.checkerToGuard = (checker) => NegatableGuard_1.buildNegatable(() => getRawGuard(checker), () => getRawNegation(checker));
exports.checkerToGuard = checker => NegatableGuard_1.buildNegatable(() => getRawGuard(checker), () => getRawNegation(checker));
function getRawGuard(checker) {

@@ -8,0 +8,0 @@ return (input, e = [], c = [], context = []) => {

@@ -9,4 +9,4 @@ "use strict";

exports.altGuard = (left) => NegatableGuard_1.buildNegatable(() => getRawAlt(left), () => getRawNegatedAlt(left));
const getRawAlt = ((left) => left);
const getRawNegatedAlt = ((left) => notGuard_1.notGuard(left));
const getRawAlt = (left => left);
const getRawNegatedAlt = (left => notGuard_1.notGuard(left));
//# sourceMappingURL=altGuard.js.map

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

return (input, output, confirmations, context) => {
return left(input, output, confirmations, context) && right(input, output, confirmations, context);
return (left(input, output, confirmations, context) && right(input, output, confirmations, context));
};

@@ -12,0 +12,0 @@ }

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

});
exports.constantGuards = (result) => result ? trueGuard : falseGuard;
exports.constantGuards = (result) => (result ? trueGuard : falseGuard);
const unnegatableTrueGuard =

@@ -20,3 +20,3 @@ // eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars

};
exports.unnegatableConstantGuards = (result) => result ? unnegatableTrueGuard : unnegatableFalseGuard;
exports.unnegatableConstantGuards = result => result ? unnegatableTrueGuard : unnegatableFalseGuard;
//# sourceMappingURL=constantGuards.js.map

@@ -41,4 +41,4 @@ "use strict";

// type PropertyGuardBuilder<FROM, TO extends FROM> = (definition: PropertyGuards<FROM, TO>) => ReasonGuard<FROM, TO>;
exports.objectHasDefinition = ((definition) => (input, output = [], confirmations = [], context = []) => checkDefinition(definition, input, output, confirmations, context));
exports.objectHasDefinition = (definition => (input, output = [], confirmations = [], context = []) => checkDefinition(definition, input, output, confirmations, context));
exports.isObjectWithDefinition = (definition) => Combinators_1.thenGuard(primitiveGuards_1.isObject, exports.objectHasDefinition(definition));
//# sourceMappingURL=objectGuards.js.map

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

*/
exports.isNumberString = Checker_1.checkerToGuard((input) => {
exports.isNumberString = Checker_1.checkerToGuard(input => {
if (!isNaN(Number.parseFloat(input))) {

@@ -19,3 +19,3 @@ return 'is Number-string';

*/
exports.isDateString = Checker_1.checkerToGuard((input) => {
exports.isDateString = Checker_1.checkerToGuard(input => {
if (!isNaN(Date.parse(input))) {

@@ -31,3 +31,3 @@ return 'is Date-string';

*/
exports.isBigIntString = Checker_1.checkerToGuard((input) => {
exports.isBigIntString = Checker_1.checkerToGuard(input => {
try {

@@ -34,0 +34,0 @@ // eslint-disable-next-line 6river/new-cap

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

}
exports.isUndefined = Checker_1.checkerToGuard((input) => {
exports.isUndefined = Checker_1.checkerToGuard(input => {
if (input === undefined) {

@@ -21,3 +21,3 @@ return `undefined`;

});
exports.isNull = Checker_1.checkerToGuard((input) => {
exports.isNull = Checker_1.checkerToGuard(input => {
if (input === null) {

@@ -24,0 +24,0 @@ return `null`;

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

if (!itemGuard(input[p], innerErrors, innerConfs, innerContext)) {
throw new ContextError_1.CompositeError(innerErrors.map((err) => new ContextError_1.ContextError(`property ${p}: ${err.message}`, err instanceof ContextError_1.ContextError ? err.context : innerContext)));
throw new ContextError_1.CompositeError(innerErrors.map(err => new ContextError_1.ContextError(`property ${p}: ${err.message}`, err instanceof ContextError_1.ContextError ? err.context : innerContext)));
}

@@ -24,0 +24,0 @@ return `property ${p}: ${innerConfs[0]}`;

@@ -16,23 +16,23 @@ import { ReasonGuard } from './ReasonGuard';

'>': symbol;
'open': symbol;
open: symbol;
'(': symbol;
'gt': symbol;
'GT': symbol;
gt: symbol;
GT: symbol;
'>=': symbol;
'closed': symbol;
closed: symbol;
'[': symbol;
'gte': symbol;
'GTE': symbol;
gte: symbol;
GTE: symbol;
};
declare const topSymbols: {
'<': symbol;
'open': symbol;
open: symbol;
')': symbol;
'lt': symbol;
'LT': symbol;
lt: symbol;
LT: symbol;
'<=': symbol;
'closed': symbol;
closed: symbol;
']': symbol;
'lte': symbol;
'LTE': symbol;
lte: symbol;
LTE: symbol;
};

@@ -48,3 +48,3 @@ export declare type Bottom = keyof typeof bottomSymbols;

declare type BoolMap<T extends Literable> = Record<T, boolean>;
declare type LiteralCheck<T1 extends Literable, T2 extends Literable, BAD = unknown> = BoolMap<T1> extends BoolMap<T2> ? (BoolMap<T2> extends BoolMap<T1> ? T2 : BAD) : BAD;
declare type LiteralCheck<T1 extends Literable, T2 extends Literable, BAD = unknown> = BoolMap<T1> extends BoolMap<T2> ? BoolMap<T2> extends BoolMap<T1> ? T2 : BAD : BAD;
export declare type ArrayLiteralCheck<T extends Literable, TT extends ReadonlyArray<Literable>> = LiteralCheck<T, ArrayToLiteral<TT>>;

@@ -51,0 +51,0 @@ export declare const isLiterable: import("./NegatableGuard").NegatableGuard<unknown, string | number | symbol, unknown>;

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

const UUIDRegex = /^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/;
exports.isUUIDString = Checker_1.checkerToGuard((input) => {
exports.isUUIDString = Checker_1.checkerToGuard(input => {
if (UUIDRegex.test(input)) {

@@ -66,28 +66,30 @@ return 'Valid UUID';

'>': OPEN,
'open': OPEN,
open: OPEN,
'(': OPEN,
'gt': OPEN,
'GT': OPEN,
gt: OPEN,
GT: OPEN,
'>=': CLOSED,
'closed': CLOSED,
closed: CLOSED,
'[': CLOSED,
'gte': CLOSED,
'GTE': CLOSED,
gte: CLOSED,
GTE: CLOSED,
};
const topSymbols = {
'<': OPEN,
'open': OPEN,
open: OPEN,
')': OPEN,
'lt': OPEN,
'LT': OPEN,
lt: OPEN,
LT: OPEN,
'<=': CLOSED,
'closed': CLOSED,
closed: CLOSED,
']': CLOSED,
'lte': CLOSED,
'LTE': CLOSED,
lte: CLOSED,
LTE: CLOSED,
};
exports.interval = (bottomType, bottomValue) => (topValue, topType) => Combinators_1.thenGuard(primitiveGuards_1.isNumber, Combinators_1.andGuard(bottomSymbols[bottomType] === OPEN ? exports.numberIsGreaterThan(bottomValue) : exports.numberIsAtLeast(bottomValue), topSymbols[topType] === OPEN ? exports.numberIsLessThan(topValue) : exports.numberIsAtMost(topValue)));
exports.interval = (bottomType, bottomValue) => (topValue, topType) => Combinators_1.thenGuard(primitiveGuards_1.isNumber, Combinators_1.andGuard(bottomSymbols[bottomType] === OPEN
? exports.numberIsGreaterThan(bottomValue)
: exports.numberIsAtLeast(bottomValue), topSymbols[topType] === OPEN ? exports.numberIsLessThan(topValue) : exports.numberIsAtMost(topValue)));
exports.integralInterval = (bottomType, bottomValue) => (topValue, topType) => Combinators_1.thenGuard(exports.interval(bottomType, bottomValue)(topValue, topType), exports.numberIsInteger);
exports.numberIsSafeInteger = Combinators_1.andGuard(exports.numberIsInteger, exports.interval('>=', Number.MIN_SAFE_INTEGER)(Number.MAX_SAFE_INTEGER, '<='));
exports.isStrictEqual = (value) => Checker_1.checkerToGuard((input) => {
exports.isStrictEqual = (value) => Checker_1.checkerToGuard(input => {
// have to use String() because of Symbols

@@ -130,3 +132,2 @@ if (value === input) {

exports.isLiteral = isLiteral;
;
//# sourceMappingURL=restrictingGuards.js.map

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

exports.isTuple = isTuple;
;
//# sourceMappingURL=tupleGuards.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const chai_1 = require("chai");
const src_1 = require("../src");
const chai_1 = require("chai");
describe('arrayFilterGuard', function () {

@@ -6,0 +6,0 @@ const guard = src_1.arrayFilterGuard(src_1.isString);

@@ -7,4 +7,4 @@ "use strict";

testCombinator_1.testOneArgCombinator('~', [false, true, false, true], src_1.altGuard);
testCombinator_1.testOneArgCombinator('!~', [true, false, false, true], (g) => src_1.notGuard(src_1.altGuard(g)));
testCombinator_1.testOneArgCombinator('!~', [true, false, false, true], g => src_1.notGuard(src_1.altGuard(g)));
});
//# sourceMappingURL=altGuard.spec.js.map
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const chai_1 = require("chai");
const testCombinator_1 = require("./testCombinator");
const src_1 = require("../../src");
const chai_1 = require("chai");
describe('and', function () {

@@ -7,0 +7,0 @@ it('behaves as && at runtime', function () {

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

context('nots', function () {
testCombinator_1.testOneArgCombinator('!', [true, false, false, true], (left) => new src_1.FluentGuardBuilder(left).not().guard);
testCombinator_1.testOneArgCombinator('!', [true, false, false, true], left => new src_1.FluentGuardBuilder(left).not().guard);
});
});
//# sourceMappingURL=FluentGuardBuilder.spec.js.map

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

const assertGuards_1 = require("../assertGuards");
exports.abbrev = (b) => b ? 'T' : 'F';
exports.abbrev = (b) => (b ? 'T' : 'F');
function testOneArgCombinator(char, result, combinator) {

@@ -8,0 +8,0 @@ for (const guardSource of [src_1.constantGuards, src_1.unnegatableConstantGuards]) {

@@ -28,7 +28,9 @@ "use strict";

bounds: { x1: 0, y1: 0, x2: 100, y2: 100 },
aisles: [{
aisles: [
{
name: 'S2-A1',
type: 'aisle',
bounds: { x1: 0, y1: 0, x2: 100, y2: 100 },
}],
},
],
};

@@ -40,3 +42,3 @@ it('resolves path for errors', function () {

test.aisles[0].bounds.x1 = 'BAADF00D';
(test.aisles[0].type) = 'BAADF00D';
test.aisles[0].type = 'BAADF00D';
delete test.aisles[0].name;

@@ -43,0 +45,0 @@ assertGuards_1.assertGuards(false)(mapGuard, test);

"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const chai_1 = require("chai");
const src_1 = require("../src");
const assertGuards_1 = require("./assertGuards");
const chai_1 = require("chai");
describe('NegatableGuard', function () {

@@ -7,0 +7,0 @@ context(src_1.buildNegatable.name, function () {

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

// bad values for nested property
testPropertyBadValues(guard, { a: 'foo', b: { c: 'foo' }, e: 'foo' }, 'b', 1, commonValues.map((v) => ({ c: 'foo', d: v })));
testPropertyBadValues(guard, { a: 'foo', b: { c: 'foo' }, e: 'foo' }, 'b', 1, commonValues.map(v => ({ c: 'foo', d: v })));
it('accepts good values', function () {

@@ -133,0 +133,0 @@ assertGuards_1.assertGuards(true)(guard, { a: 'foo', b: { c: 'foo', d: 'foo' }, e: 'foo' });

@@ -69,4 +69,5 @@ "use strict";

context('array property', function () {
testGuardMaker(
// eslint-disable-next-line no-unused-vars, @typescript-eslint/no-unused-vars
testGuardMaker(property.hasArrayProperty((x) => true), 7);
property.hasArrayProperty((x) => true), 7);
});

@@ -73,0 +74,0 @@ context('has property', function () {

@@ -9,9 +9,9 @@ "use strict";

const badValues = [false, true, { datum: 1 }, undefined, 6, 'string', testSymbol, null, [1, 2]];
const values = [new Date(), (new Date()).toISOString()];
const values = [new Date(), new Date().toISOString()];
const guard = restricting.isDateOrDateString;
it('should guard for a date or date strings', function () {
values.forEach((value) => assertGuards_1.assertGuards(true)(guard, value));
values.forEach(value => assertGuards_1.assertGuards(true)(guard, value));
});
it('should guard against non-dates or none-date-strings', function () {
badValues.forEach((badValue) => assertGuards_1.assertGuards(false)(guard, badValue));
badValues.forEach(badValue => assertGuards_1.assertGuards(false)(guard, badValue));
});

@@ -49,4 +49,10 @@ });

const valueList = ['a', 5, true, false, testSymbol];
const badValuesLists = [[1, 'b'], [4, 'a'], [false], [true], [Symbol('test'), Symbol('bad')]];
const guards = valueList.map((v) => restricting.isStrictEqual(v));
const badValuesLists = [
[1, 'b'],
[4, 'a'],
[false],
[true],
[Symbol('test'), Symbol('bad')],
];
const guards = valueList.map(v => restricting.isStrictEqual(v));
it('guards for the exact value', function () {

@@ -61,3 +67,3 @@ guards.forEach((guard, i) => assertGuards_1.assertGuards(true)(guard, valueList[i]));

}));
guards.forEach((guard, i) => badValuesLists[i].forEach((badValue) => assertGuards_1.assertGuards(false)(guard, badValue)));
guards.forEach((guard, i) => badValuesLists[i].forEach(badValue => assertGuards_1.assertGuards(false)(guard, badValue)));
});

@@ -64,0 +70,0 @@ });

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

it('guards for valid tuples with extra items', function () {
testValues.forEach((v) => {
testValues.forEach(v => {
assertGuards_1.assertGuards(true)(guard2, [...guard2Good, v]);

@@ -35,3 +35,6 @@ assertGuards_1.assertGuards(true)(guard3, [...guard3Good, v]);

it('guards against too short tuples', function () {
[{ guard: guard2, good: guard2Good }, { guard: guard3, good: guard3Good }].forEach(({ guard, good }) => {
[
{ guard: guard2, good: guard2Good },
{ guard: guard3, good: guard3Good },
].forEach(({ guard, good }) => {
for (let i = 0; i < good.length; ++i) {

@@ -44,3 +47,6 @@ const bad = [...good].splice(i, 1);

it('guards against tuples with proper length but wrong element types', function () {
[{ guard: guard2, good: guard2Good }, { guard: guard3, good: guard3Good }].forEach(({ guard, good }) => {
[
{ guard: guard2, good: guard2Good },
{ guard: guard3, good: guard3Good },
].forEach(({ guard, good }) => {
for (let i = 0; i < good.length; ++i) {

@@ -76,7 +82,10 @@ for (let j = 0; j < testValues.length; ++j) {

assertGuards_1.assertGuards(false)(guard3Strict, guard2Good);
testValues.forEach((v) => {
testValues.forEach(v => {
assertGuards_1.assertGuards(false)(guard2Strict, [...guard2Good, v]);
assertGuards_1.assertGuards(false)(guard3Strict, [...guard3Good, v]);
});
[{ guard: guard2Strict, good: guard2Good }, { guard: guard3Strict, good: guard3Good }].forEach(({ guard, good }) => {
[
{ guard: guard2Strict, good: guard2Good },
{ guard: guard3Strict, good: guard3Good },
].forEach(({ guard, good }) => {
for (let i = 0; i < good.length; ++i) {

@@ -83,0 +92,0 @@ const bad = [...good].splice(i, 1);

@@ -11,2 +11,3 @@ {

"@6river/commitlint-config-6river": "2.1.7",
"@6river/prettier-config": "1.0.0",
"@commitlint/cli": "8.1.0",

@@ -16,8 +17,11 @@ "@types/chai": "4.1.7",

"@types/node": "10.14.15",
"@typescript-eslint/eslint-plugin": "1.13.0",
"@typescript-eslint/parser": "1.13.0",
"@typescript-eslint/eslint-plugin": "2.19.0",
"@typescript-eslint/parser": "2.19.0",
"chai": "4.2.0",
"codecov": "3.6.5",
"eslint": "6.1.0",
"eslint-config-6river": "2.1.0",
"eslint-config-6river": "3.0.0",
"eslint-config-prettier": "6.10.0",
"eslint-plugin-6river": "1.0.6",
"eslint-plugin-import": "2.20.1",
"husky": "3.0.2",

@@ -28,2 +32,3 @@ "mocha": "6.2.0",

"opener": "1.5.1",
"prettier": "1.19.1",
"source-map-support": "0.5.13",

@@ -40,2 +45,3 @@ "typescript": "3.5.3"

"name": "@6river/reason-guard",
"prettier": "@6river/prettier-config",
"repository": {

@@ -46,3 +52,8 @@ "type": "git",

"scripts": {
"lint": "eslint --ext .ts .",
"lint": "npm run eslint:check \u0026\u0026 npm run format:check",
"lint:fix": "npm run eslint:fix \u0026\u0026 npm run format:fix",
"eslint:check": "eslint --ext .ts .",
"format:check": "prettier --check '{src,test}/**/*.ts'",
"eslint:fix": "eslint --ext .ts,.js --fix ${ESLINT_OPTS} .",
"format:fix": "prettier --write '{src,test}/**/*.ts'",
"only:build": "tsc",

@@ -60,3 +71,3 @@ "only:test": "NODE_ENV=test nyc mocha ${MOCHA_OPTS}",

},
"version": "3.7.2"
"version": "3.7.3"
}

@@ -1,2 +0,2 @@

import {ReasonGuard} from './ReasonGuard';
import { ReasonGuard } from './ReasonGuard';

@@ -8,3 +8,4 @@ export type ArrayFilterGuard<FROM, TO extends FROM> = (input: FROM) => input is TO;

*/
export const arrayFilterGuard = <FROM, TO extends FROM>(guard: ReasonGuard<FROM, TO>): ArrayFilterGuard<FROM, TO> =>
(input): input is TO => guard(input, [], []);
export const arrayFilterGuard = <FROM, TO extends FROM>(
guard: ReasonGuard<FROM, TO>,
): ArrayFilterGuard<FROM, TO> => (input): input is TO => guard(input, [], []);

@@ -1,30 +0,31 @@

import {ReasonGuard} from './ReasonGuard';
import {checkerToGuard, pushContext} from './Checker';
import {thenGuard} from './Combinators';
import {isArray} from './instanceGuards';
import {NegatableGuard} from './NegatableGuard';
import {ContextError, CompositeError} from './ContextError';
import { ReasonGuard } from './ReasonGuard';
import { checkerToGuard, pushContext } from './Checker';
import { thenGuard } from './Combinators';
import { isArray } from './instanceGuards';
import { NegatableGuard } from './NegatableGuard';
import { ContextError, CompositeError } from './ContextError';
export const arrayHasType =
<TO>(itemGuard: ReasonGuard<unknown, TO>) =>
checkerToGuard<unknown[], TO[]>((input: unknown[], context?: PropertyKey[]) => {
for (let i = 0; i < input.length; i++) {
const innerErrors: Error[] = [];
const innerConfs: string[] = [];
const innerContext = pushContext(i, context);
if (!itemGuard(input[i], innerErrors, innerConfs, innerContext)) {
throw new CompositeError(innerErrors.map((err) =>
new ContextError(`element ${i}: ${err.message}`,
err instanceof ContextError ? err.context : innerContext))
);
}
export const arrayHasType = <TO>(itemGuard: ReasonGuard<unknown, TO>) =>
checkerToGuard<unknown[], TO[]>((input: unknown[], context?: PropertyKey[]) => {
for (let i = 0; i < input.length; i++) {
const innerErrors: Error[] = [];
const innerConfs: string[] = [];
const innerContext = pushContext(i, context);
if (!itemGuard(input[i], innerErrors, innerConfs, innerContext)) {
throw new CompositeError(
innerErrors.map(
err =>
new ContextError(
`element ${i}: ${err.message}`,
err instanceof ContextError ? err.context : innerContext,
),
),
);
}
return `is array of expected type`;
});
}
return `is array of expected type`;
});
export const isArrayOfType =
<TO>(itemGuard: ReasonGuard<unknown, TO>): NegatableGuard<unknown, TO[], unknown> =>
thenGuard(
isArray,
arrayHasType(itemGuard)
);
export const isArrayOfType = <TO>(
itemGuard: ReasonGuard<unknown, TO>,
): NegatableGuard<unknown, TO[], unknown> => thenGuard(isArray, arrayHasType(itemGuard));

@@ -1,4 +0,4 @@

import {ReasonGuard} from './ReasonGuard';
import {NegatableGuard, buildNegatable} from './NegatableGuard';
import {CompositeError} from './ContextError';
import { ReasonGuard } from './ReasonGuard';
import { NegatableGuard, buildNegatable } from './NegatableGuard';
import { CompositeError } from './ContextError';

@@ -8,7 +8,8 @@ export type Checker<FROM> = (input: FROM, context?: PropertyKey[]) => string;

export const checkerToGuard: <FROM, TO extends FROM, N extends FROM = FROM>(
checker: Checker<FROM>
) => NegatableGuard<FROM, TO, N> = (checker) => buildNegatable(
() => getRawGuard(checker),
() => getRawNegation(checker)
);
checker: Checker<FROM>,
) => NegatableGuard<FROM, TO, N> = checker =>
buildNegatable(
() => getRawGuard(checker),
() => getRawNegation(checker),
);

@@ -15,0 +16,0 @@ function getRawGuard<FROM, TO extends FROM>(checker: Checker<FROM>): ReasonGuard<FROM, TO> {

@@ -1,4 +0,4 @@

import {ReasonGuard} from '../ReasonGuard';
import {notGuard} from './notGuard';
import {buildNegatable} from '../NegatableGuard';
import { ReasonGuard } from '../ReasonGuard';
import { notGuard } from './notGuard';
import { buildNegatable } from '../NegatableGuard';

@@ -8,13 +8,14 @@ /**

*/
export const altGuard = <LEFT, RIGHT>(left: ReasonGuard<LEFT|RIGHT, LEFT>) => buildNegatable(
() => getRawAlt(left),
() => getRawNegatedAlt<LEFT, RIGHT>(left)
);
export const altGuard = <LEFT, RIGHT>(left: ReasonGuard<LEFT | RIGHT, LEFT>) =>
buildNegatable(
() => getRawAlt(left),
() => getRawNegatedAlt<LEFT, RIGHT>(left),
);
const getRawAlt =
<(<LEFT, RIGHT>(left: ReasonGuard<LEFT|RIGHT, LEFT>) =>
ReasonGuard<LEFT|RIGHT, LEFT>)>((left) => left);
const getRawAlt = <
<LEFT, RIGHT>(left: ReasonGuard<LEFT | RIGHT, LEFT>) => ReasonGuard<LEFT | RIGHT, LEFT>
>(left => left);
const getRawNegatedAlt =
<(<LEFT, RIGHT>(left: ReasonGuard<LEFT|RIGHT, LEFT>) =>
ReasonGuard<LEFT|RIGHT, RIGHT>)>((left) => notGuard(left));
const getRawNegatedAlt = <
<LEFT, RIGHT>(left: ReasonGuard<LEFT | RIGHT, LEFT>) => ReasonGuard<LEFT | RIGHT, RIGHT>
>(left => notGuard(left));

@@ -1,12 +0,13 @@

import {ReasonGuard} from '../ReasonGuard';
import {orGuard} from './orGuard';
import {notGuard} from './notGuard';
import {buildNegatable} from '../NegatableGuard';
import { ReasonGuard } from '../ReasonGuard';
import { orGuard } from './orGuard';
import { notGuard } from './notGuard';
import { buildNegatable } from '../NegatableGuard';
export const andGuard = <FROM, LEFT extends FROM, RIGHT extends FROM>(
left: ReasonGuard<FROM, LEFT>,
right: ReasonGuard<FROM, RIGHT>
) => buildNegatable(
right: ReasonGuard<FROM, RIGHT>,
) =>
buildNegatable(
() => getRawAnd(left, right),
() => getRawNegatedAnd(left, right)
() => getRawNegatedAnd(left, right),
);

@@ -16,5 +17,5 @@

left: ReasonGuard<FROM, LEFT>,
right: ReasonGuard<FROM, RIGHT>
): ReasonGuard<FROM, LEFT&RIGHT> {
return (input, output, confirmations): input is LEFT&RIGHT => {
right: ReasonGuard<FROM, RIGHT>,
): ReasonGuard<FROM, LEFT & RIGHT> {
return (input, output, confirmations): input is LEFT & RIGHT => {
return left(input, output, confirmations) && right(input, output, confirmations);

@@ -26,9 +27,5 @@ };

left: ReasonGuard<FROM, LEFT>,
right: ReasonGuard<FROM, RIGHT>
right: ReasonGuard<FROM, RIGHT>,
): ReasonGuard<FROM, FROM> {
return orGuard(
notGuard(right),
notGuard(left)
);
return orGuard(notGuard(right), notGuard(left));
}

@@ -1,10 +0,9 @@

import {orGuard} from './orGuard';
import {andGuard} from './andGuard';
import {thenGuard} from './thenGuard';
import {notGuard} from './notGuard';
import {ReasonGuard} from '../ReasonGuard';
import { orGuard } from './orGuard';
import { andGuard } from './andGuard';
import { thenGuard } from './thenGuard';
import { notGuard } from './notGuard';
import { ReasonGuard } from '../ReasonGuard';
export class FluentGuardBuilder<FROM, TO extends FROM> {
constructor(private readonly _guard: ReasonGuard<FROM, TO>) {
}
constructor(private readonly _guard: ReasonGuard<FROM, TO>) {}
public get guard() {

@@ -11,0 +10,0 @@ return this._guard;

@@ -1,16 +0,16 @@

import {ReasonGuard} from '../ReasonGuard';
import {isNegatableGuard, NegatableGuard, buildNegatable} from '../NegatableGuard';
import { ReasonGuard } from '../ReasonGuard';
import { isNegatableGuard, NegatableGuard, buildNegatable } from '../NegatableGuard';
export const notGuard =
<FROM, TO extends FROM, N extends FROM = FROM>
(inner: ReasonGuard<FROM, TO>|NegatableGuard<FROM, TO, N>) =>
isNegatableGuard(inner)
? inner.negate()
: buildNegatable<FROM, N, TO>(
export const notGuard = <FROM, TO extends FROM, N extends FROM = FROM>(
inner: ReasonGuard<FROM, TO> | NegatableGuard<FROM, TO, N>,
) =>
isNegatableGuard(inner)
? inner.negate()
: buildNegatable<FROM, N, TO>(
() => getRawNot(inner),
() => inner
);
() => inner,
);
function getRawNot<FROM, TO extends FROM, N extends FROM>(
inner: ReasonGuard<FROM, TO>
inner: ReasonGuard<FROM, TO>,
): ReasonGuard<FROM, N> {

@@ -22,3 +22,3 @@ return (input: FROM, errors: Error[] = [], confirmations: string[] = []): input is N => {

if (inner(input, innerErrors, innerConfs)) {
throw new Error(innerConfs[innerConfs.length-1]);
throw new Error(innerConfs[innerConfs.length - 1]);
} else {

@@ -25,0 +25,0 @@ confirmations.push(innerErrors[0].message);

@@ -1,12 +0,13 @@

import {ReasonGuard} from '../ReasonGuard';
import {notGuard} from './notGuard';
import {buildNegatable} from '../NegatableGuard';
import {andGuard} from './andGuard';
import { ReasonGuard } from '../ReasonGuard';
import { notGuard } from './notGuard';
import { buildNegatable } from '../NegatableGuard';
import { andGuard } from './andGuard';
export const orGuard = <FROM, LEFT extends FROM, RIGHT extends FROM>(
left: ReasonGuard<FROM, LEFT>,
right: ReasonGuard<FROM, RIGHT>
) => buildNegatable(
right: ReasonGuard<FROM, RIGHT>,
) =>
buildNegatable(
() => getRawOr(left, right),
() => getRawNegatedOr(left, right)
() => getRawNegatedOr(left, right),
);

@@ -16,5 +17,5 @@

left: ReasonGuard<FROM, LEFT>,
right: ReasonGuard<FROM, RIGHT>
): ReasonGuard<FROM, LEFT|RIGHT> {
return (input, output = [], confirmations = []): input is LEFT|RIGHT => {
right: ReasonGuard<FROM, RIGHT>,
): ReasonGuard<FROM, LEFT | RIGHT> {
return (input, output = [], confirmations = []): input is LEFT | RIGHT => {
try {

@@ -43,5 +44,5 @@ const innerErrors: Error[] = [];

left: ReasonGuard<FROM, LEFT>,
right: ReasonGuard<FROM, RIGHT>
right: ReasonGuard<FROM, RIGHT>,
): ReasonGuard<FROM, FROM> {
return andGuard(notGuard(left), notGuard(right));
}

@@ -1,12 +0,13 @@

import {ReasonGuard} from '../ReasonGuard';
import {orGuard} from './orGuard';
import {notGuard} from './notGuard';
import {buildNegatable} from '../NegatableGuard';
import { ReasonGuard } from '../ReasonGuard';
import { orGuard } from './orGuard';
import { notGuard } from './notGuard';
import { buildNegatable } from '../NegatableGuard';
export const thenGuard = <FROM, MID extends FROM, TO extends MID>(
left: ReasonGuard<FROM, MID>,
right: ReasonGuard<MID, TO>
) => buildNegatable(
right: ReasonGuard<MID, TO>,
) =>
buildNegatable(
() => getRawThen(left, right),
() => getRawNegatedThen(left, right)
() => getRawNegatedThen(left, right),
);

@@ -16,6 +17,8 @@

left: ReasonGuard<FROM, MID>,
right: ReasonGuard<MID, TO>
right: ReasonGuard<MID, TO>,
): ReasonGuard<FROM, TO> {
return (input, output, confirmations, context): input is TO => {
return left(input, output, confirmations, context) && right(input, output, confirmations, context);
return (
left(input, output, confirmations, context) && right(input, output, confirmations, context)
);
};

@@ -26,8 +29,5 @@ }

left: ReasonGuard<FROM, MID>,
right: ReasonGuard<MID, TO>
right: ReasonGuard<MID, TO>,
): ReasonGuard<FROM, FROM> {
return orGuard(
getRawThen(left, notGuard<MID, MID>(right)),
notGuard(left)
);
return orGuard(getRawThen(left, notGuard<MID, MID>(right)), notGuard(left));
}

@@ -1,15 +0,14 @@

import {ReasonGuard} from './ReasonGuard';
import {checkerToGuard} from './Checker';
import {NegatableGuard} from './NegatableGuard';
import { ReasonGuard } from './ReasonGuard';
import { checkerToGuard } from './Checker';
import { NegatableGuard } from './NegatableGuard';
const trueGuard: NegatableGuard<unknown, unknown, never> =
checkerToGuard(() => 'true');
const trueGuard: NegatableGuard<unknown, unknown, never> = checkerToGuard(() => 'true');
const falseGuard: NegatableGuard<unknown, never, unknown> =
checkerToGuard(() => {
throw new Error('false');
});
const falseGuard: NegatableGuard<unknown, never, unknown> = checkerToGuard(() => {
throw new Error('false');
});
export const constantGuards: (result: boolean) => NegatableGuard<unknown, unknown, unknown> =
(result: boolean) => result ? trueGuard : falseGuard;
export const constantGuards: (result: boolean) => NegatableGuard<unknown, unknown, unknown> = (
result: boolean,
) => (result ? trueGuard : falseGuard);

@@ -23,9 +22,10 @@ const unnegatableTrueGuard: ReasonGuard<unknown, unknown> =

const unnegatableFalseGuard: ReasonGuard<unknown, never> =
(input, es = []): input is never => {
es.push(new Error('false'));
return false;
};
const unnegatableFalseGuard: ReasonGuard<unknown, never> = (input, es = []): input is never => {
es.push(new Error('false'));
return false;
};
export const unnegatableConstantGuards: (result: boolean) => ReasonGuard<unknown, unknown> =
(result) => result ? unnegatableTrueGuard : unnegatableFalseGuard;
export const unnegatableConstantGuards: (
result: boolean,
) => ReasonGuard<unknown, unknown> = result =>
result ? unnegatableTrueGuard : unnegatableFalseGuard;

@@ -1,12 +0,10 @@

import {checkerToGuard} from './Checker';
import { checkerToGuard } from './Checker';
export const getInstanceTypeCheck =
<INST>(ctor: new(...args: any[]) => INST) =>
checkerToGuard<unknown, INST>((input: unknown) => {
if (!(input instanceof ctor)) throw new Error(`not a ${ctor.name}`);
return `a ${ctor.name}`;
});
export const getInstanceTypeCheck = <INST>(ctor: new (...args: any[]) => INST) =>
checkerToGuard<unknown, INST>((input: unknown) => {
if (!(input instanceof ctor)) throw new Error(`not a ${ctor.name}`);
return `a ${ctor.name}`;
});
export const isDate = getInstanceTypeCheck(Date);
export const isArray = getInstanceTypeCheck(Array);

@@ -1,29 +0,25 @@

import {ReasonGuard, cloneGuard} from './ReasonGuard';
import { ReasonGuard, cloneGuard } from './ReasonGuard';
export type NegatableGuard<FROM, TO extends FROM, N extends FROM = FROM> = ReasonGuard<FROM, TO> & {
negate: () => NegatableGuard<FROM, N, TO>
}
negate: () => NegatableGuard<FROM, N, TO>;
};
export type AlternativeGuard<LEFT, RIGHT> = NegatableGuard<LEFT|RIGHT, LEFT, RIGHT>;
export type AlternativeGuard<LEFT, RIGHT> = NegatableGuard<LEFT | RIGHT, LEFT, RIGHT>;
export const isNegatableGuard =
<FROM, TO extends FROM, N extends FROM = FROM>
(input: ReasonGuard<FROM, TO>): input is NegatableGuard<FROM, TO, N> =>
typeof input === 'function' && typeof (input as any).negate === 'function';
export const isNegatableGuard = <FROM, TO extends FROM, N extends FROM = FROM>(
input: ReasonGuard<FROM, TO>,
): input is NegatableGuard<FROM, TO, N> =>
typeof input === 'function' && typeof (input as any).negate === 'function';
export const buildNegatable =
<FROM, TO extends FROM, N extends FROM = FROM>
(input: () => ReasonGuard<FROM, TO>, negated: () => ReasonGuard<FROM, N>) => {
const negatableGuard: NegatableGuard<FROM, TO, N> = Object.assign(
cloneGuard(input()),
{
negate: () => Object.assign(
cloneGuard(negated()),
{
negate: () => negatableGuard,
}
),
}
);
return negatableGuard;
};
export const buildNegatable = <FROM, TO extends FROM, N extends FROM = FROM>(
input: () => ReasonGuard<FROM, TO>,
negated: () => ReasonGuard<FROM, N>,
) => {
const negatableGuard: NegatableGuard<FROM, TO, N> = Object.assign(cloneGuard(input()), {
negate: () =>
Object.assign(cloneGuard(negated()), {
negate: () => negatableGuard,
}),
});
return negatableGuard;
};

@@ -1,4 +0,4 @@

import {ReasonGuard} from './ReasonGuard';
import {thenGuard} from './Combinators';
import {isObject} from './primitiveGuards';
import { ReasonGuard } from './ReasonGuard';
import { thenGuard } from './Combinators';
import { isObject } from './primitiveGuards';

@@ -21,3 +21,5 @@ // NOTE: for this one you HAVE to have K as a parameter

*/
export type ChangedFields<FROM extends object, TO extends FROM> = NarrowedFields<FROM, TO> | ExtendedFields<FROM, TO>;
export type ChangedFields<FROM extends object, TO extends FROM> =
| NarrowedFields<FROM, TO>
| ExtendedFields<FROM, TO>;

@@ -27,10 +29,17 @@ /**

*/
type PropertyGuardFactory<FROM extends object, TO extends FROM, P extends keyof TO> =
(p: P) => ReasonGuard<Pick<FROM, P & keyof FROM>, Pick<TO, P>>;
type PropertyGuardFactory<FROM extends object, TO extends FROM, P extends keyof TO> = (
p: P,
) => ReasonGuard<Pick<FROM, P & keyof FROM>, Pick<TO, P>>;
export type RequiredGuards<FROM extends object, TO extends FROM, K extends keyof TO = ChangedFields<FROM, TO>> = {
[P in K]-?: PropertyGuardFactory<FROM, TO, P>
}
export type RequiredGuards<
FROM extends object,
TO extends FROM,
K extends keyof TO = ChangedFields<FROM, TO>
> = {
[P in K]-?: PropertyGuardFactory<FROM, TO, P>;
};
export type OptionalGuards<FROM extends object, TO extends FROM> = Partial<RequiredGuards<FROM, TO, keyof TO>>;
export type OptionalGuards<FROM extends object, TO extends FROM> = Partial<
RequiredGuards<FROM, TO, keyof TO>
>;

@@ -40,6 +49,11 @@ /**

*/
export type PropertyGuards<FROM extends object, TO extends FROM> = RequiredGuards<FROM, TO> & OptionalGuards<FROM, TO>;
export type PropertyGuards<FROM extends object, TO extends FROM> = RequiredGuards<FROM, TO> &
OptionalGuards<FROM, TO>;
function checkDefinition<FROM extends object, TO extends FROM>(
definition: PropertyGuards<FROM, TO>, input: FROM, output: Error[], confirmations: string[], context?: PropertyKey[]
definition: PropertyGuards<FROM, TO>,
input: FROM,
output: Error[],
confirmations: string[],
context?: PropertyKey[],
): input is TO {

@@ -85,13 +99,10 @@ let anyPassed = false;

export const objectHasDefinition =
<(<FROM extends object, TO extends FROM>(definition: PropertyGuards<FROM, TO>) => ReasonGuard<FROM, TO>)>(
(definition) =>
(input, output = [], confirmations = [], context = []) =>
checkDefinition(definition, input, output, confirmations, context)
);
export const objectHasDefinition = <
<FROM extends object, TO extends FROM>(
definition: PropertyGuards<FROM, TO>,
) => ReasonGuard<FROM, TO>
>(definition => (input, output = [], confirmations = [], context = []) =>
checkDefinition(definition, input, output, confirmations, context));
export const isObjectWithDefinition =
<TO extends object>(definition: PropertyGuards<object, TO>) => thenGuard<unknown, object, TO>(
isObject,
objectHasDefinition(definition)
);
export const isObjectWithDefinition = <TO extends object>(definition: PropertyGuards<object, TO>) =>
thenGuard<unknown, object, TO>(isObject, objectHasDefinition(definition));

@@ -1,2 +0,2 @@

import {checkerToGuard} from './Checker';
import { checkerToGuard } from './Checker';

@@ -6,3 +6,3 @@ /**

*/
export const isNumberString = checkerToGuard<string, string>((input) => {
export const isNumberString = checkerToGuard<string, string>(input => {
if (!isNaN(Number.parseFloat(input))) {

@@ -18,3 +18,3 @@ return 'is Number-string';

*/
export const isDateString = checkerToGuard<string, string>((input) => {
export const isDateString = checkerToGuard<string, string>(input => {
if (!isNaN(Date.parse(input))) {

@@ -30,3 +30,3 @@ return 'is Date-string';

*/
export const isBigIntString = checkerToGuard<string, string>((input) => {
export const isBigIntString = checkerToGuard<string, string>(input => {
try {

@@ -33,0 +33,0 @@ // eslint-disable-next-line 6river/new-cap

@@ -1,5 +0,13 @@

import {checkerToGuard} from './Checker';
import {andGuard, notGuard} from './Combinators';
import { checkerToGuard } from './Checker';
import { andGuard, notGuard } from './Combinators';
type Primitive = 'string'|'number'|'bigint'|'boolean'|'symbol'|'undefined'|'object'|'function';
type Primitive =
| 'string'
| 'number'
| 'bigint'
| 'boolean'
| 'symbol'
| 'undefined'
| 'object'
| 'function';
// Dangerous -- do not export!

@@ -14,3 +22,3 @@ // We cannot guarantee that "x: PRIM" -> "typeof x === 'prim'"!

export const isUndefined = checkerToGuard<unknown, undefined>((input) => {
export const isUndefined = checkerToGuard<unknown, undefined>(input => {
if (input === undefined) {

@@ -21,3 +29,3 @@ return `undefined`;

});
export const isNull = checkerToGuard<unknown, null>((input) => {
export const isNull = checkerToGuard<unknown, null>(input => {
if (input === null) {

@@ -35,5 +43,2 @@ return `null`;

export const isBigInt = getPrimitiveTypeCheck<BigInt>('bigint');
export const isObject = andGuard(
getPrimitiveTypeCheck<object>('object'),
notGuard(isNull)
);
export const isObject = andGuard(getPrimitiveTypeCheck<object>('object'), notGuard(isNull));

@@ -1,21 +0,23 @@

import {ReasonGuard} from './ReasonGuard';
import {checkerToGuard, pushContext} from './Checker';
import {thenGuard, orGuard, notGuard} from './Combinators';
import {isUndefined} from './primitiveGuards';
import {isArrayOfType} from './arrayHasType';
import {NegatableGuard} from './NegatableGuard';
import {ContextError, CompositeError} from './ContextError';
import { ReasonGuard } from './ReasonGuard';
import { checkerToGuard, pushContext } from './Checker';
import { thenGuard, orGuard, notGuard } from './Combinators';
import { isUndefined } from './primitiveGuards';
import { isArrayOfType } from './arrayHasType';
import { NegatableGuard } from './NegatableGuard';
import { ContextError, CompositeError } from './ContextError';
// TODO: we may have this type defined elsewhere already
export type PropertyKey = string|number|symbol;
export type PropertyKey = string | number | symbol;
export type PropertyGuard<DEST_PROP_TYPE> =
<T extends PropertyKey>(p: T) =>
NegatableGuard<unknown, Record<T, DEST_PROP_TYPE>>;
export type PropertyGuard<DEST_PROP_TYPE> = <T extends PropertyKey>(
p: T,
) => NegatableGuard<unknown, Record<T, DEST_PROP_TYPE>>;
export type StrictOptionalPropertyGuard<DEST_PROP_TYPE> =
<T extends PropertyKey>(p: T) =>
NegatableGuard<unknown, Partial<Record<T, DEST_PROP_TYPE>>>;
export type StrictOptionalPropertyGuard<DEST_PROP_TYPE> = <T extends PropertyKey>(
p: T,
) => NegatableGuard<unknown, Partial<Record<T, DEST_PROP_TYPE>>>;
export type OptionalPropertyGuard<DEST_PROP_TYPE> = StrictOptionalPropertyGuard<DEST_PROP_TYPE|undefined>;
export type OptionalPropertyGuard<DEST_PROP_TYPE> = StrictOptionalPropertyGuard<
DEST_PROP_TYPE | undefined
>;

@@ -25,71 +27,78 @@ export type NarrowPropertyGuard<

DEST_PROP_TYPE extends FROM_PROP_TYPE = FROM_PROP_TYPE
> = <T extends PropertyKey>(p: T) =>
NegatableGuard<Record<T, FROM_PROP_TYPE>, Record<T, DEST_PROP_TYPE>>;
> = <T extends PropertyKey>(
p: T,
) => NegatableGuard<Record<T, FROM_PROP_TYPE>, Record<T, DEST_PROP_TYPE>>;
export const hasProperty = <T extends PropertyKey>(p: T) =>
checkerToGuard<unknown, Record<T, unknown>, Partial<Record<T, never>>>(
(input: unknown, context?: PropertyKey[]) => {
const x: any = input;
// if (x[p] === undefined) throw new Error(`property ${p} is undefined`);
// if (x[p] === null) throw new Error(`property ${p} is null`); // is this right?
if (!(p in x))
throw new ContextError(`property ${p} is not present`, pushContext(p, context));
return `property ${p} is present`;
},
);
export const hasProperty =
<T extends PropertyKey>
(p: T) =>
checkerToGuard<unknown, Record<T, unknown>, Partial<Record<T, never>> >(
(input: unknown, context?: PropertyKey[]) => {
const x: any = input;
// if (x[p] === undefined) throw new Error(`property ${p} is undefined`);
// if (x[p] === null) throw new Error(`property ${p} is null`); // is this right?
if (!(p in x)) throw new ContextError(`property ${p} is not present`, pushContext(p, context));
return `property ${p} is present`;
});
export const propertyHasType = <
FROMT,
T extends string | number | symbol,
TOT extends FROMT,
TO extends Record<T, TOT>
>(
itemGuard: ReasonGuard<FROMT, TOT>,
p: T,
) =>
checkerToGuard<Record<T, FROMT>, Pick<TO, T>>((input, context) => {
const innerErrors: Error[] = [];
const innerConfs: string[] = [];
const innerContext = pushContext(p, context);
if (!itemGuard(input[p], innerErrors, innerConfs, innerContext)) {
throw new CompositeError(
innerErrors.map(
err =>
new ContextError(
`property ${p}: ${err.message}`,
err instanceof ContextError ? err.context : innerContext,
),
),
);
}
return `property ${p}: ${innerConfs[0]}`;
});
export const propertyHasType =
<FROMT, T extends string|number|symbol, TOT extends FROMT, TO extends Record<T, TOT>>
(itemGuard: ReasonGuard<FROMT, TOT>, p: T) =>
checkerToGuard<Record<T, FROMT>, Pick<TO, T>>((input, context) => {
const innerErrors: Error[] = [];
const innerConfs: string[] = [];
const innerContext = pushContext(p, context);
if (!itemGuard(input[p], innerErrors, innerConfs, innerContext)) {
throw new CompositeError(innerErrors.map((err) =>
new ContextError(`property ${p}: ${err.message}`,
err instanceof ContextError ? err.context : innerContext)));
}
return `property ${p}: ${innerConfs[0]}`;
});
export const narrowedProperty = <FROM_PROP_TYPE, TO_PROP_TYPE extends FROM_PROP_TYPE>(
g: ReasonGuard<FROM_PROP_TYPE, TO_PROP_TYPE>,
): NarrowPropertyGuard<FROM_PROP_TYPE, TO_PROP_TYPE> => <T extends PropertyKey>(
p: T,
): NegatableGuard<Record<T, FROM_PROP_TYPE>, Record<T, TO_PROP_TYPE>> => propertyHasType(g, p);
export const narrowedProperty =
<FROM_PROP_TYPE, TO_PROP_TYPE extends FROM_PROP_TYPE>
(g: ReasonGuard<FROM_PROP_TYPE, TO_PROP_TYPE>): NarrowPropertyGuard<FROM_PROP_TYPE, TO_PROP_TYPE> =>
<T extends PropertyKey>(p: T):
NegatableGuard<Record<T, FROM_PROP_TYPE>, Record<T, TO_PROP_TYPE>> =>
propertyHasType(g, p);
export const requiredProperty = <TO_PROP_TYPE>(
g: ReasonGuard<unknown, TO_PROP_TYPE>,
): PropertyGuard<TO_PROP_TYPE> => <T extends PropertyKey>(
p: T,
): NegatableGuard<unknown, Record<T, TO_PROP_TYPE>> =>
thenGuard(hasProperty(p), propertyHasType(g, p));
export const requiredProperty =
<TO_PROP_TYPE>(g: ReasonGuard<unknown, TO_PROP_TYPE>): PropertyGuard<TO_PROP_TYPE> =>
<T extends PropertyKey>(p: T):
NegatableGuard<unknown, Record<T, TO_PROP_TYPE>> =>
thenGuard(hasProperty(p), propertyHasType(g, p));
export const optionalProperty = <PTYPE>(
g: ReasonGuard<unknown, PTYPE>,
): OptionalPropertyGuard<PTYPE> => <T extends PropertyKey>(
p: T,
): NegatableGuard<unknown, Partial<Record<T, PTYPE | undefined>>> =>
orGuard(
notGuard(hasProperty(p)),
orGuard(requiredProperty(isUndefined)(p), requiredProperty(g)(p)),
);
export const optionalProperty =
<PTYPE>(g: ReasonGuard<unknown, PTYPE>): OptionalPropertyGuard<PTYPE> =>
<T extends PropertyKey>(p: T):
NegatableGuard<unknown, Partial<Record<T, PTYPE|undefined>>> =>
orGuard(
notGuard(hasProperty(p)),
orGuard(
requiredProperty(isUndefined)(p),
requiredProperty(g)(p)
)
);
export const strictOptionalProperty = <PTYPE>(
g: ReasonGuard<unknown, PTYPE>,
): StrictOptionalPropertyGuard<PTYPE> => <T extends PropertyKey>(
p: T,
): NegatableGuard<unknown, Partial<Record<T, PTYPE>>> =>
orGuard(notGuard(hasProperty(p)), requiredProperty(g)(p));
export const strictOptionalProperty =
<PTYPE>(g: ReasonGuard<unknown, PTYPE>): StrictOptionalPropertyGuard<PTYPE> =>
<T extends PropertyKey>(p: T):
NegatableGuard<unknown, Partial<Record<T, PTYPE>>> =>
orGuard(
notGuard(hasProperty(p)),
requiredProperty(g)(p)
);
export const hasArrayProperty =
<T extends PropertyKey, TO>
(itemGuard: ReasonGuard<unknown, TO>) =>
(p: T): NegatableGuard<unknown, Record<T, TO[]>> =>
thenGuard(hasProperty(p), propertyHasType(isArrayOfType(itemGuard), p));
export const hasArrayProperty = <T extends PropertyKey, TO>(
itemGuard: ReasonGuard<unknown, TO>,
) => (p: T): NegatableGuard<unknown, Record<T, TO[]>> =>
thenGuard(hasProperty(p), propertyHasType(isArrayOfType(itemGuard), p));

@@ -8,6 +8,4 @@ export type ReasonGuard<FROM, TO extends FROM> = (

export const cloneGuard =
<FROM, TO extends FROM>
(g: ReasonGuard<FROM, TO>): ReasonGuard<FROM, TO> =>
(input, es, cs, context): input is TO =>
g(input, es, cs, context);
export const cloneGuard = <FROM, TO extends FROM>(
g: ReasonGuard<FROM, TO>,
): ReasonGuard<FROM, TO> => (input, es, cs, context): input is TO => g(input, es, cs, context);

@@ -1,15 +0,9 @@

import {checkerToGuard} from './Checker';
import {andGuard, orGuard, thenGuard} from './Combinators';
import {ReasonGuard} from './ReasonGuard';
import {isNumber, isSymbol, isString} from './primitiveGuards';
import {isDate} from './instanceGuards';
import {isDateString} from './parseGuards';
import { checkerToGuard } from './Checker';
import { andGuard, orGuard, thenGuard } from './Combinators';
import { ReasonGuard } from './ReasonGuard';
import { isNumber, isSymbol, isString } from './primitiveGuards';
import { isDate } from './instanceGuards';
import { isDateString } from './parseGuards';
export const isDateOrDateString = orGuard(
thenGuard(
isString,
isDateString
),
isDate
);
export const isDateOrDateString = orGuard(thenGuard(isString, isDateString), isDate);

@@ -19,3 +13,3 @@ // TODO investigate non-regex pattern checks

export const isUUIDString = checkerToGuard<string, string>((input) => {
export const isUUIDString = checkerToGuard<string, string>(input => {
if (UUIDRegex.test(input)) {

@@ -63,24 +57,18 @@ return 'Valid UUID';

? checkerToGuard<number, number>((input: number) => {
if (Number.isNaN(input)) {
return `${input} = ${value}`;
}
throw new Error(`${input} != ${value}`);
})
if (Number.isNaN(input)) {
return `${input} = ${value}`;
}
throw new Error(`${input} != ${value}`);
})
: checkerToGuard<number, number>((input: number) => {
if (input === value) {
return `${input} = ${value}`;
}
throw new Error(`${input} != ${value}`);
});
if (input === value) {
return `${input} = ${value}`;
}
throw new Error(`${input} != ${value}`);
});
export const numberIsAtMost = (maximum: number) =>
orGuard(
numberIsLessThan(maximum),
numberIs(maximum)
);
orGuard(numberIsLessThan(maximum), numberIs(maximum));
export const numberIsAtLeast = (minimum: number) =>
orGuard(
numberIsGreaterThan(minimum),
numberIs(minimum)
);
orGuard(numberIsGreaterThan(minimum), numberIs(minimum));

@@ -95,11 +83,11 @@ export const numberIsLessThanOrEqual = numberIsAtMost;

'>': OPEN,
'open': OPEN,
open: OPEN,
'(': OPEN,
'gt': OPEN,
'GT': OPEN,
gt: OPEN,
GT: OPEN,
'>=': CLOSED,
'closed': CLOSED,
closed: CLOSED,
'[': CLOSED,
'gte': CLOSED,
'GTE': CLOSED,
gte: CLOSED,
GTE: CLOSED,
};

@@ -109,11 +97,11 @@

'<': OPEN,
'open': OPEN,
open: OPEN,
')': OPEN,
'lt': OPEN,
'LT': OPEN,
lt: OPEN,
LT: OPEN,
'<=': CLOSED,
'closed': CLOSED,
closed: CLOSED,
']': CLOSED,
'lte': CLOSED,
'LTE': CLOSED,
lte: CLOSED,
LTE: CLOSED,
};

@@ -124,34 +112,35 @@

export const interval =
(bottomType: Bottom, bottomValue: number) =>
(topValue: number, topType: Top) =>
thenGuard(
isNumber,
andGuard(
bottomSymbols[bottomType] === OPEN ? numberIsGreaterThan(bottomValue) : numberIsAtLeast(bottomValue),
topSymbols[topType] === OPEN ? numberIsLessThan(topValue) : numberIsAtMost(topValue)
)
);
export const interval = (bottomType: Bottom, bottomValue: number) => (
topValue: number,
topType: Top,
) =>
thenGuard(
isNumber,
andGuard(
bottomSymbols[bottomType] === OPEN
? numberIsGreaterThan(bottomValue)
: numberIsAtLeast(bottomValue),
topSymbols[topType] === OPEN ? numberIsLessThan(topValue) : numberIsAtMost(topValue),
),
);
export const integralInterval =
(bottomType: Bottom, bottomValue: number) =>
(topValue: number, topType: Top) =>
thenGuard(
interval(bottomType, bottomValue)(topValue, topType),
numberIsInteger
);
export const integralInterval = (bottomType: Bottom, bottomValue: number) => (
topValue: number,
topType: Top,
) => thenGuard(interval(bottomType, bottomValue)(topValue, topType), numberIsInteger);
export const numberIsSafeInteger = andGuard(
numberIsInteger,
interval('>=', Number.MIN_SAFE_INTEGER)(Number.MAX_SAFE_INTEGER, '<=')
interval('>=', Number.MIN_SAFE_INTEGER)(Number.MAX_SAFE_INTEGER, '<='),
);
export const isStrictEqual = <T>(value: T) => checkerToGuard<unknown, T>((input) => {
// have to use String() because of Symbols
if (value === input) {
return `is exactly ${String(value)}`;
} else {
throw new Error(`is not exactly ${String(input)}`);
}
});
export const isStrictEqual = <T>(value: T) =>
checkerToGuard<unknown, T>(input => {
// have to use String() because of Symbols
if (value === input) {
return `is exactly ${String(value)}`;
} else {
throw new Error(`is not exactly ${String(input)}`);
}
});

@@ -164,14 +153,15 @@ // You can have boolean literal types, but they don't work with Record<>,

type BoolMap<T extends Literable> = Record<T, boolean>;
type LiteralCheck<T1 extends Literable, T2 extends Literable, BAD = unknown> =
BoolMap<T1> extends BoolMap<T2> ? (BoolMap<T2> extends BoolMap<T1> ? T2 : BAD) : BAD;
export type ArrayLiteralCheck<T extends Literable, TT extends ReadonlyArray<Literable>> =
LiteralCheck<T, ArrayToLiteral<TT>>;
type LiteralCheck<T1 extends Literable, T2 extends Literable, BAD = unknown> = BoolMap<
T1
> extends BoolMap<T2>
? BoolMap<T2> extends BoolMap<T1>
? T2
: BAD
: BAD;
export type ArrayLiteralCheck<
T extends Literable,
TT extends ReadonlyArray<Literable>
> = LiteralCheck<T, ArrayToLiteral<TT>>;
export const isLiterable = orGuard(
orGuard(
isString,
isSymbol
),
isNumber
);
export const isLiterable = orGuard(orGuard(isString, isSymbol), isNumber);

@@ -185,3 +175,3 @@ /**

keys: ReadonlyArray<U>,
literableGuard: ReasonGuard<unknown, Literable> = isLiterable
literableGuard: ReasonGuard<unknown, Literable> = isLiterable,
): ReasonGuard<unknown, ArrayLiteralCheck<T, typeof keys>> {

@@ -207,2 +197,2 @@ // want this to be computed once when building the guard

};
};
}

@@ -1,9 +0,9 @@

import {ReasonGuard} from './ReasonGuard';
import {isNumber} from './primitiveGuards';
import {numberIs, numberIsAtLeast} from './restrictingGuards';
import {thenGuard, andGuard} from './Combinators';
import {isArray} from './instanceGuards';
import {requiredProperty} from './propertyGuards';
import {NegatableGuard} from './NegatableGuard';
import {constantGuards} from './constantGuards';
import { ReasonGuard } from './ReasonGuard';
import { isNumber } from './primitiveGuards';
import { numberIs, numberIsAtLeast } from './restrictingGuards';
import { thenGuard, andGuard } from './Combinators';
import { isArray } from './instanceGuards';
import { requiredProperty } from './propertyGuards';
import { NegatableGuard } from './NegatableGuard';
import { constantGuards } from './constantGuards';

@@ -20,3 +20,3 @@ // we can't do variadic types, but we can do some useful pieces, by virtue of homomorphic mapped array types

[P in keyof TTuple]: unknown;
}
};
type TupleGuards<TTuple extends unknown[]> = {

@@ -26,8 +26,10 @@ readonly [P in keyof TTuple]: ReasonGuard<unknown, TTuple[P]>;

const isArrayOfLength = <TTuple extends unknown[]>(
lengthGuard: ReasonGuard<number, number>
) => thenGuard<unknown, unknown[], TupleIntermediate<TTuple>>(
isArray,
requiredProperty(thenGuard(isNumber, lengthGuard))('length') as NegatableGuard<unknown[], TTuple>,
);
const isArrayOfLength = <TTuple extends unknown[]>(lengthGuard: ReasonGuard<number, number>) =>
thenGuard<unknown, unknown[], TupleIntermediate<TTuple>>(
isArray,
requiredProperty(thenGuard(isNumber, lengthGuard))('length') as NegatableGuard<
unknown[],
TTuple
>,
);

@@ -41,9 +43,9 @@ export type TupleGuard<TTuple extends unknown[]> = NegatableGuard<unknown, TTuple> & {

toLoose(): LooseTupleGuard<TTuple>;
}
};
export type StrictTupleGuard<TTuple extends unknown[]> = TupleGuard<TTuple> & {
isStrict: true;
}
};
export type LooseTupleGuard<TTuple extends unknown[]> = TupleGuard<TTuple> & {
isStrict: false;
}
};

@@ -57,7 +59,8 @@ export function isTuple<TTuple extends unknown[]>(

itemGuards
.map((guard, idx) => requiredProperty(guard)(idx))
.reduce(
(aggGuard, itemGuard) => aggGuard === constantGuards(true) ? itemGuard : andGuard(aggGuard, itemGuard),
constantGuards(true),
) as NegatableGuard<TupleIntermediate<TTuple>, TTuple>,
.map((guard, idx) => requiredProperty(guard)(idx))
.reduce(
(aggGuard, itemGuard) =>
aggGuard === constantGuards(true) ? itemGuard : andGuard(aggGuard, itemGuard),
constantGuards(true),
) as NegatableGuard<TupleIntermediate<TTuple>, TTuple>,
// ^^^ Typescript needs help because no varaidic types

@@ -70,6 +73,3 @@ ),

const strictGuard: StrictTupleGuard<TTuple> = Object.assign(
andGuard(
looseGuard,
isArrayOfLength(numberIs(looseGuard.tupleLength)),
),
andGuard(looseGuard, isArrayOfLength(numberIs(looseGuard.tupleLength))),
{

@@ -89,2 +89,2 @@ tupleLength: looseGuard.tupleLength,

return looseGuard;
};
}

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 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

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