All files / lib/schemas constraints.js

17.18% Statements 11/64
0% Branches 0/42
12.5% Functions 1/8
19.29% Lines 11/57

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186          21x   21x   1x 1x   1x                                   21x           21x           21x                                                                     21x                                                                             21x           21x                                                                                                                              
import { type } from 'arktype';
import NaturalRegex from 'natural-regex';
 
import { describeNaturalRegex } from '../natural-regex-tokens.js';
 
export const RegexExpression = type('string').pipe.try((source) => new RegExp(source));
 
export const NaturalRegexExpression = type('string')
	.pipe.try((source) => {
		try {
			const regex = NaturalRegex.from(`start, ${source}, end`);
 
			return {
				source,
				regex,
				display: describeNaturalRegex(source)
			};
		} catch (e) {
			if (e instanceof Function) {
				// Trust
				throw new Error(e.message, { cause: e });
			}
 
			throw e;
		}
	})
	.describe(
		"Une description d'un motif avec la syntaxe de natural-regex, cf https://github.com/mbasso/natural-regex/wiki/Operators,-operands-and-expressions. Par exemple, 'group uppercase letter, word, space end group minimum 2 times then <, email, >' correspond à un motif pour Prénom Nom <email>. Voir https://github.com/mbasso/natural-regex/wiki/Examples pour plus d'exemples."
	);
 
const comparatorsMore = /** @type {const} */ ({
	'>': 'gt',
	'>=': 'gte',
	'≥': 'gte'
});
 
const comparatorsLess = /** @type {const} */ ({
	'<': 'lt',
	'<=': 'lte',
	'≤': 'lte'
});
 
const comparators = /** @type {const} */ ({
	...comparatorsLess,
	...comparatorsMore
});
 
/**
 * @overload
 * @param {"gt" | "gte"} op
 * @returns {"lt" | "lte"}
 */
 
/**
 * @overload
 * @param {"lt" | "lte"} op
 * @returns {"gt" | "gte"}
 */
 
/**
 *
 * @param {typeof comparators[keyof typeof comparators]} op
 * @returns {typeof comparators[keyof typeof comparators]}
 */
function flipComparator(op) {
	switch (op) {
		case 'gt':
			return 'lt';
		case 'gte':
			return 'lte';
		case 'lt':
			return 'gt';
		case 'lte':
			return 'gte';
	}
}
 
const reg = /** @type {const} */ ({
	float: '(-?\\d+(?:[.,]\\d+)?(?:[eE][+-]?\\d+)?)',
	comp: '(' + Object.keys(comparators).join('|') + ')',
	compLess: '(' + Object.keys(comparatorsLess).join('|') + ')'
});
 
/**
 * @param {string} s
 * @returns {typeof comparators[keyof typeof comparators] | undefined}
 */
function findComparator(s) {
	// @ts-expect-error
	return comparators[s.match(reg.comp)?.[1]];
}
 
/**
 * @param {string} s
 * @returns {typeof comparatorsLess[keyof typeof comparatorsLess] | undefined}
 */
function findLessComparator(s) {
	// @ts-expect-error
	return comparatorsLess[s.match(reg.compLess)?.[1]];
}
 
/**
 * @param {string} s
 * @returns {number | undefined}
 */
function findFloat(s) {
	const parsed = Number.parseFloat(s.match(reg.float)?.[1]?.replace(',', '.') ?? '');
	if (Number.isNaN(parsed)) return undefined;
	if (!Number.isFinite(parsed)) return undefined;
	return parsed;
}
 
/**
 * @typedef {({ gt?: number } | { gte?: number }) & ({ lt?: number } | { lte?: number })} NumberRange
 */
 
const numberRangePatterns = {
	open: `((?:x\\s*)?${reg.comp}\\s*${reg.float})`,
	closed: `(${reg.float}\\s*${reg.compLess}\\s*x\\s*${reg.compLess}\\s*${reg.float})`,
	interval: `(${reg.float}\\s*[.][.]\\s*${reg.float})`
};
 
export const NumberRangeLiteral = type(
	new RegExp('^' + Object.values(numberRangePatterns).join('|') + '$')
)
	.pipe.try(
		/** @returns {NumberRange} */
		(s) => {
			if (new RegExp(numberRangePatterns.open).test(s)) {
				const op = findComparator(s);
				const num = findFloat(s);
				if (!op) throw new Error(`Invalid comparator in range literal: ${s}`);
				if (num === undefined) throw new Error(`Invalid number in range literal: ${s}`);
 
				return { [op]: num };
			}
 
			if (new RegExp(numberRangePatterns.closed).test(s)) {
				const [lhs, rhs] = s.split(/\\s*x\\s*/);
				const lhsOp = findLessComparator(lhs);
				const rhsOp = findLessComparator(rhs);
				const lhsNum = findFloat(lhs);
				const rhsNum = findFloat(rhs);
 
				if (!lhsOp) throw new Error(`Invalid left comparator in range literal: ${s}`);
				if (!rhsOp) throw new Error(`Invalid right comparator in range literal: ${s}`);
				if (lhsNum === undefined)
					throw new Error(`Invalid left number in range literal: ${s}`);
				if (rhsNum === undefined)
					throw new Error(`Invalid right number in range literal: ${s}`);
 
				return {
					[lhsOp]: lhsNum,
					[flipComparator(rhsOp)]: rhsNum
				};
			}
 
			if (new RegExp(numberRangePatterns.interval).test(s)) {
				const [min, max] = s.split(/\s*[.][.]\s*/);
				const minNum = findFloat(min);
				const maxNum = findFloat(max);
 
				if (minNum === undefined)
					throw new Error(`Invalid minimum number in range literal: ${s}`);
				if (maxNum === undefined)
					throw new Error(`Invalid maximum number in range literal: ${s}`);
 
				return {
					gte: minNum,
					lte: maxNum
				};
			}
 
			throw new Error(`Invalid number range literal: ${s}`);
		}
	)
	.pipe((range) => {
		const max = 'lt' in range ? range.lt : 'lte' in range ? range.lte : undefined;
		const min = 'gt' in range ? range.gt : 'gte' in range ? range.gte : undefined;
 
		return { ...range, min, max };
	})
	.describe(
		"Un intervalle de nombres, sous les formes suivantes: '> 5', '<= 5', '5 < x ≤ 10', '5..10'. Précisément, il y a quatres formes possibles:\n- Op n (avec Op un des opérateurs >, >=, <, <=, ≥, ≤),\n- x Op n (qui est équivalent à Op n, mais permet de ne pas commencer l'expression avec un caractère '>', utile en YAML),\n- m Op x Op M (avec m et M des nombres, et Op un des opérateurs <, <=, ≤),\n- m..M (avec m et n des nombres), qui est un équivalent de m ≤ x ≤ M."
	);