UNPKG

2.01 kBJavaScriptView Raw
1import callsites from 'callsites';
2import { inferLabel } from './utils/infer-label.js';
3import { isPredicate } from './predicates/base-predicate.js';
4import modifiers from './modifiers.js';
5import predicates from './predicates.js';
6import test from './test.js';
7const ow = (value, labelOrPredicate, predicate) => {
8 if (!isPredicate(labelOrPredicate) && typeof labelOrPredicate !== 'string') {
9 throw new TypeError(`Expected second argument to be a predicate or a string, got \`${typeof labelOrPredicate}\``);
10 }
11 if (isPredicate(labelOrPredicate)) {
12 // If the second argument is a predicate, infer the label
13 const stackFrames = callsites();
14 test(value, () => inferLabel(stackFrames), labelOrPredicate);
15 return;
16 }
17 test(value, labelOrPredicate, predicate);
18};
19Object.defineProperties(ow, {
20 isValid: {
21 value(value, predicate) {
22 try {
23 test(value, '', predicate);
24 return true;
25 }
26 catch {
27 return false;
28 }
29 },
30 },
31 create: {
32 value: (labelOrPredicate, predicate) => (value, label) => {
33 if (isPredicate(labelOrPredicate)) {
34 const stackFrames = callsites();
35 test(value, label ?? (() => inferLabel(stackFrames)), labelOrPredicate);
36 return;
37 }
38 test(value, label ?? (labelOrPredicate), predicate);
39 },
40 },
41});
42// Can't use `export default predicates(modifiers(ow)) as Ow` because the variable needs a type annotation to avoid a compiler error when used:
43// Assertions require every name in the call target to be declared with an explicit type annotation.ts(2775)
44// See https://github.com/microsoft/TypeScript/issues/36931 for more details.
45const _ow = predicates(modifiers(ow));
46export default _ow;
47export * from './predicates.js';
48export { ArgumentError } from './argument-error.js';
49export { Predicate } from './predicates/predicate.js';